1 from __future__
import unicode_literals
12 from .common
import AudioConversionError
, PostProcessor
14 from ..compat
import compat_str
21 _get_exe_version_output
,
37 EXT_TO_OUT_FORMATS
= {
56 'vorbis': 'libvorbis',
62 class FFmpegPostProcessorError(PostProcessingError
):
66 class FFmpegPostProcessor(PostProcessor
):
67 def __init__(self
, downloader
=None):
68 PostProcessor
.__init
__(self
, downloader
)
69 self
._determine
_executables
()
71 def check_version(self
):
72 if not self
.available
:
73 raise FFmpegPostProcessorError('ffmpeg not found. Please install or provide the path using --ffmpeg-location')
75 required_version
= '10-0' if self
.basename
== 'avconv' else '1.0'
76 if is_outdated_version(
77 self
._versions
[self
.basename
], required_version
):
78 warning
= 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
79 self
.basename
, self
.basename
, required_version
)
80 self
.report_warning(warning
)
83 def get_versions_and_features(downloader
=None):
84 pp
= FFmpegPostProcessor(downloader
)
85 return pp
._versions
, pp
._features
88 def get_versions(downloader
=None):
89 return FFmpegPostProcessor
.get_versions_and_features(downloader
)[0]
91 _version_cache
, _features_cache
= {}, {}
93 def _determine_executables(self
):
94 programs
= ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
96 def get_ffmpeg_version(path
, prog
):
97 if path
in self
._version
_cache
:
98 self
._versions
[prog
], self
._features
= self
._version
_cache
[path
], self
._features
_cache
.get(path
, {})
100 out
= _get_exe_version_output(path
, ['-bsfs'], to_screen
=self
.write_debug
)
101 ver
= detect_exe_version(out
) if out
else False
104 r
'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1]
105 r
'n([0-9.]+)$', # Arch Linux
106 # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/
109 mobj
= re
.match(regex
, ver
)
112 self
._versions
[prog
] = self
._version
_cache
[path
] = ver
113 if prog
!= 'ffmpeg' or not out
:
116 mobj
= re
.search(r
'(?m)^\s+libavformat\s+(?:[0-9. ]+)\s+/\s+(?P<runtime>[0-9. ]+)', out
)
117 lavf_runtime_version
= mobj
.group('runtime').replace(' ', '') if mobj
else None
118 self
._features
= self
._features
_cache
[path
] = {
119 'fdk': '--enable-libfdk-aac' in out
,
120 'setts': 'setts' in out
.splitlines(),
121 'needs_adtstoasc': is_outdated_version(lavf_runtime_version
, '57.56.100', False),
125 self
.probe_basename
= None
127 self
._versions
= None
130 prefer_ffmpeg
= self
.get_param('prefer_ffmpeg', True)
131 location
= self
.get_param('ffmpeg_location')
133 self
._paths
= {p: p for p in programs}
135 if not os
.path
.exists(location
):
137 'ffmpeg-location %s does not exist! '
138 'Continuing without ffmpeg.' % (location
))
141 elif os
.path
.isdir(location
):
142 dirname
, basename
= location
, None
144 basename
= os
.path
.splitext(os
.path
.basename(location
))[0]
145 basename
= next((p
for p
in programs
if basename
.startswith(p
)), 'ffmpeg')
146 dirname
= os
.path
.dirname(os
.path
.abspath(location
))
147 if basename
in ('ffmpeg', 'ffprobe'):
151 (p
, os
.path
.join(dirname
, p
)) for p
in programs
)
153 self
._paths
[basename
] = location
156 executables
= {'basename': ('ffmpeg', 'avconv'), 'probe_basename': ('ffprobe', 'avprobe')}
157 if prefer_ffmpeg
is False:
158 executables
= {k: v[::-1] for k, v in executables.items()}
159 for var
, prefs
in executables
.items():
161 get_ffmpeg_version(self
._paths
[p
], p
)
162 if self
._versions
[p
]:
163 setattr(self
, var
, p
)
166 if self
.basename
== 'avconv':
167 self
.deprecation_warning(
168 'Support for avconv is deprecated and may be removed in a future version. Use ffmpeg instead')
169 if self
.probe_basename
== 'avprobe':
170 self
.deprecation_warning(
171 'Support for avprobe is deprecated and may be removed in a future version. Use ffprobe instead')
175 return self
.basename
is not None
178 def executable(self
):
179 return self
._paths
[self
.basename
]
182 def probe_available(self
):
183 return self
.probe_basename
is not None
186 def probe_executable(self
):
187 return self
._paths
[self
.probe_basename
]
190 def stream_copy_opts(copy
=True, *, ext
=None):
191 yield from ('-map', '0')
192 # Don't copy Apple TV chapters track, bin_data
193 # See https://github.com/yt-dlp/yt-dlp/issues/2, #19042, #19024, https://trac.ffmpeg.org/ticket/6016
194 yield from ('-dn', '-ignore_unknown')
196 yield from ('-c', 'copy')
197 # For some reason, '-c copy -map 0' is not enough to copy subtitles
198 if ext
in ('mp4', 'mov'):
199 yield from ('-c:s', 'mov_text')
201 def get_audio_codec(self
, path
):
202 if not self
.probe_available
and not self
.available
:
203 raise PostProcessingError('ffprobe and ffmpeg not found. Please install or provide the path using --ffmpeg-location')
205 if self
.probe_available
:
207 encodeFilename(self
.probe_executable
, True),
208 encodeArgument('-show_streams')]
211 encodeFilename(self
.executable
, True),
212 encodeArgument('-i')]
213 cmd
.append(encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True))
214 self
.write_debug('%s command line: %s' % (self
.basename
, shell_quote(cmd
)))
215 handle
= Popen(cmd
, stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
216 stdout_data
, stderr_data
= handle
.communicate_or_kill()
217 expected_ret
= 0 if self
.probe_available
else 1
218 if handle
.wait() != expected_ret
:
220 except (IOError, OSError):
222 output
= (stdout_data
if self
.probe_available
else stderr_data
).decode('ascii', 'ignore')
223 if self
.probe_available
:
225 for line
in output
.split('\n'):
226 if line
.startswith('codec_name='):
227 audio_codec
= line
.split('=')[1].strip()
228 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
231 # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME
233 r
'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)',
239 def get_metadata_object(self
, path
, opts
=[]):
240 if self
.probe_basename
!= 'ffprobe':
241 if self
.probe_available
:
242 self
.report_warning('Only ffprobe is supported for metadata extraction')
243 raise PostProcessingError('ffprobe not found. Please install or provide the path using --ffmpeg-location')
247 encodeFilename(self
.probe_executable
, True),
248 encodeArgument('-hide_banner'),
249 encodeArgument('-show_format'),
250 encodeArgument('-show_streams'),
251 encodeArgument('-print_format'),
252 encodeArgument('json'),
256 cmd
.append(encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True))
257 self
.write_debug('ffprobe command line: %s' % shell_quote(cmd
))
258 p
= Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
259 stdout
, stderr
= p
.communicate()
260 return json
.loads(stdout
.decode('utf-8', 'replace'))
262 def get_stream_number(self
, path
, keys
, value
):
263 streams
= self
.get_metadata_object(path
)['streams']
265 (i
for i
, stream
in enumerate(streams
) if traverse_obj(stream
, keys
, casesense
=False) == value
),
267 return num
, len(streams
)
269 def _get_real_video_duration(self
, filepath
, fatal
=True):
271 duration
= float_or_none(
272 traverse_obj(self
.get_metadata_object(filepath
), ('format', 'duration')))
274 raise PostProcessingError('ffprobe returned empty duration')
276 except PostProcessingError
as e
:
278 raise PostProcessingError(f
'Unable to determine video duration: {e.msg}')
280 def _duration_mismatch(self
, d1
, d2
):
283 # The duration is often only known to nearest second. So there can be <1sec disparity natually.
284 # Further excuse an additional <1sec difference.
285 return abs(d1
- d2
) > 2
287 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
, **kwargs
):
288 return self
.real_run_ffmpeg(
289 [(path
, []) for path
in input_paths
],
290 [(out_path
, opts
)], **kwargs
)
292 def real_run_ffmpeg(self
, input_path_opts
, output_path_opts
, *, expected_retcodes
=(0,)):
296 os
.stat(encodeFilename(path
)).st_mtime
for path
, _
in input_path_opts
if path
)
298 cmd
= [encodeFilename(self
.executable
, True), encodeArgument('-y')]
299 # avconv does not have repeat option
300 if self
.basename
== 'ffmpeg':
301 cmd
+= [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
303 def make_args(file, args
, name
, number
):
304 keys
= ['_%s%d' % (name
, number
), '_%s' % name
]
306 args
+= ['-movflags', '+faststart']
309 args
+= self
._configuration
_args
(self
.basename
, keys
)
313 [encodeArgument(arg
) for arg
in args
]
314 + [encodeFilename(self
._ffmpeg
_filename
_argument
(file), True)])
316 for arg_type
, path_opts
in (('i', input_path_opts
), ('o', output_path_opts
)):
317 cmd
+= itertools
.chain
.from_iterable(
318 make_args(path
, list(opts
), arg_type
, i
+ 1)
319 for i
, (path
, opts
) in enumerate(path_opts
) if path
)
321 self
.write_debug('ffmpeg command line: %s' % shell_quote(cmd
))
322 p
= Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
323 stdout
, stderr
= p
.communicate_or_kill()
324 if p
.returncode
not in variadic(expected_retcodes
):
325 stderr
= stderr
.decode('utf-8', 'replace').strip()
326 self
.write_debug(stderr
)
327 raise FFmpegPostProcessorError(stderr
.split('\n')[-1])
328 for out_path
, _
in output_path_opts
:
330 self
.try_utime(out_path
, oldest_mtime
, oldest_mtime
)
331 return stderr
.decode('utf-8', 'replace')
333 def run_ffmpeg(self
, path
, out_path
, opts
, **kwargs
):
334 return self
.run_ffmpeg_multiple_files([path
], out_path
, opts
, **kwargs
)
337 def _ffmpeg_filename_argument(fn
):
338 # Always use 'file:' because the filename may contain ':' (ffmpeg
339 # interprets that as a protocol) or can start with '-' (-- is broken in
340 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
341 # Also leave '-' intact in order not to break streaming to stdout.
342 if fn
.startswith(('http://', 'https://')):
344 return 'file:' + fn
if fn
!= '-' else fn
347 def _quote_for_ffmpeg(string
):
348 # See https://ffmpeg.org/ffmpeg-utils.html#toc-Quoting-and-escaping
349 # A sequence of '' produces '\'''\'';
350 # final replace removes the empty '' between \' \'.
351 string
= string
.replace("'", r
"'\''").replace("'''", "'")
352 # Handle potential ' at string boundaries.
353 string
= string
[1:] if string
[0] == "'" else "'" + string
354 return string
[:-1] if string
[-1] == "'" else string
+ "'"
356 def force_keyframes(self
, filename
, timestamps
):
357 timestamps
= orderedSet(timestamps
)
358 if timestamps
[0] == 0:
359 timestamps
= timestamps
[1:]
360 keyframe_file
= prepend_extension(filename
, 'keyframes.temp')
361 self
.to_screen(f
'Re-encoding "{filename}" with appropriate keyframes')
362 self
.run_ffmpeg(filename
, keyframe_file
, [
363 *self
.stream_copy_opts(False, ext
=determine_ext(filename
)),
364 '-force_key_frames', ','.join(f
'{t:.6f}' for t
in timestamps
)])
367 def concat_files(self
, in_files
, out_file
, concat_opts
=None):
369 Use concat demuxer to concatenate multiple files having identical streams.
371 Only inpoint, outpoint, and duration concat options are supported.
372 See https://ffmpeg.org/ffmpeg-formats.html#concat-1 for details
374 concat_file
= f
'{out_file}.concat'
375 self
.write_debug(f
'Writing concat spec to {concat_file}')
376 with open(concat_file
, 'wt', encoding
='utf-8') as f
:
377 f
.writelines(self
._concat
_spec
(in_files
, concat_opts
))
379 out_flags
= list(self
.stream_copy_opts(ext
=determine_ext(out_file
)))
381 self
.real_run_ffmpeg(
382 [(concat_file
, ['-hide_banner', '-nostdin', '-f', 'concat', '-safe', '0'])],
383 [(out_file
, out_flags
)])
384 os
.remove(concat_file
)
387 def _concat_spec(cls
, in_files
, concat_opts
=None):
388 if concat_opts
is None:
389 concat_opts
= [{}] * len(in_files
)
390 yield 'ffconcat version 1.0\n'
391 for file, opts
in zip(in_files
, concat_opts
):
392 yield f
'file {cls._quote_for_ffmpeg(cls._ffmpeg_filename_argument(file))}\n'
393 # Iterate explicitly to yield the following directives in order, ignoring the rest.
394 for directive
in 'inpoint', 'outpoint', 'duration':
395 if directive
in opts
:
396 yield f
'{directive} {opts[directive]}\n'
399 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
400 COMMON_AUDIO_EXTS
= ('wav', 'flac', 'm4a', 'aiff', 'mp3', 'ogg', 'mka', 'opus', 'wma')
401 SUPPORTED_EXTS
= ('aac', 'flac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav', 'alac')
403 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
404 FFmpegPostProcessor
.__init
__(self
, downloader
)
405 self
._preferredcodec
= preferredcodec
or 'best'
406 self
._preferredquality
= float_or_none(preferredquality
)
407 self
._nopostoverwrites
= nopostoverwrites
409 def _quality_args(self
, codec
):
410 if self
._preferredquality
is None:
412 elif self
._preferredquality
> 10:
413 return ['-b:a', f
'{self._preferredquality}k']
416 'libmp3lame': (10, 0),
417 'libvorbis': (0, 10),
418 # FFmpeg's AAC encoder does not have an upper limit for the value of -q:a.
419 # Experimentally, with values over 4, bitrate changes were minimal or non-existent
421 'libfdk_aac': (1, 5),
426 q
= limits
[1] + (limits
[0] - limits
[1]) * (self
._preferredquality
/ 10)
427 if codec
== 'libfdk_aac':
428 return ['-vbr', f
'{int(q)}']
429 return ['-q:a', f
'{q}']
431 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
435 acodec_opts
= ['-acodec', codec
]
436 opts
= ['-vn'] + acodec_opts
+ more_opts
438 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
439 except FFmpegPostProcessorError
as err
:
440 raise AudioConversionError(err
.msg
)
442 @PostProcessor._restrict_to(images
=False)
443 def run(self
, information
):
444 orig_path
= path
= information
['filepath']
445 orig_ext
= information
['ext']
447 if self
._preferredcodec
== 'best' and orig_ext
in self
.COMMON_AUDIO_EXTS
:
448 self
.to_screen('Skipping audio extraction since the file is already in a common audio format')
449 return [], information
451 filecodec
= self
.get_audio_codec(path
)
452 if filecodec
is None:
453 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
456 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
457 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
458 # Lossless, but in another container
461 more_opts
= ['-bsf:a', 'aac_adtstoasc']
462 elif filecodec
in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
463 # Lossless if possible
465 extension
= filecodec
466 if filecodec
== 'aac':
467 more_opts
= ['-f', 'adts']
468 if filecodec
== 'vorbis':
470 elif filecodec
== 'alac':
473 more_opts
+= ['-acodec', 'alac']
476 acodec
= 'libmp3lame'
478 more_opts
= self
._quality
_args
(acodec
)
480 # We convert the audio (lossy if codec is lossy)
481 acodec
= ACODECS
[self
._preferredcodec
]
482 if acodec
== 'aac' and self
._features
.get('fdk'):
483 acodec
= 'libfdk_aac'
484 extension
= self
._preferredcodec
485 more_opts
= self
._quality
_args
(acodec
)
486 if self
._preferredcodec
== 'aac':
487 more_opts
+= ['-f', 'adts']
488 elif self
._preferredcodec
== 'm4a':
489 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
490 elif self
._preferredcodec
== 'vorbis':
492 elif self
._preferredcodec
== 'wav':
494 more_opts
+= ['-f', 'wav']
495 elif self
._preferredcodec
== 'alac':
497 more_opts
+= ['-acodec', 'alac']
499 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
500 temp_path
= new_path
= prefix
+ sep
+ extension
503 orig_path
= prepend_extension(path
, 'orig')
504 temp_path
= prepend_extension(path
, 'temp')
505 if (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
))
506 and os
.path
.exists(encodeFilename(orig_path
))):
507 self
.to_screen('Post-process file %s exists, skipping' % new_path
)
508 return [], information
511 self
.to_screen(f
'Destination: {new_path}')
512 self
.run_ffmpeg(path
, temp_path
, acodec
, more_opts
)
513 except AudioConversionError
as e
:
514 raise PostProcessingError(
515 'audio conversion failed: ' + e
.msg
)
517 raise PostProcessingError('error running ' + self
.basename
)
519 os
.replace(path
, orig_path
)
520 os
.replace(temp_path
, new_path
)
521 information
['filepath'] = new_path
522 information
['ext'] = extension
524 # Try to update the date time for extracted audio file.
525 if information
.get('filetime') is not None:
527 new_path
, time
.time(), information
['filetime'],
528 errnote
='Cannot update utime of audio file')
530 return [orig_path
], information
533 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
534 SUPPORTED_EXTS
= ('mp4', 'mkv', 'flv', 'webm', 'mov', 'avi', 'mka', 'ogg', *FFmpegExtractAudioPP
.SUPPORTED_EXTS
)
535 FORMAT_RE
= re
.compile(r
'{0}(?:/{0})*$'.format(r
'(?:\w+>)?(?:%s)' % '|'.join(SUPPORTED_EXTS
)))
536 _ACTION
= 'converting'
538 def __init__(self
, downloader
=None, preferedformat
=None):
539 super(FFmpegVideoConvertorPP
, self
).__init
__(downloader
)
540 self
._preferedformats
= preferedformat
.lower().split('/')
542 def _target_ext(self
, source_ext
):
543 for pair
in self
._preferedformats
:
545 if len(kv
) == 1 or kv
[0].strip() == source_ext
:
546 return kv
[-1].strip()
549 def _options(target_ext
):
550 yield from FFmpegPostProcessor
.stream_copy_opts(False)
551 if target_ext
== 'avi':
552 yield from ('-c:v', 'libxvid', '-vtag', 'XVID')
554 @PostProcessor._restrict_to(images
=False)
556 filename
, source_ext
= info
['filepath'], info
['ext'].lower()
557 target_ext
= self
._target
_ext
(source_ext
)
559 f
'could not find a mapping for {source_ext}' if not target_ext
560 else f
'already is in target format {source_ext}' if source_ext
== target_ext
563 self
.to_screen(f
'Not {self._ACTION} media file "{filename}"; {_skip_msg}')
566 outpath
= replace_extension(filename
, target_ext
, source_ext
)
567 self
.to_screen(f
'{self._ACTION.title()} video from {source_ext} to {target_ext}; Destination: {outpath}')
568 self
.run_ffmpeg(filename
, outpath
, self
._options
(target_ext
))
570 info
['filepath'] = outpath
571 info
['format'] = info
['ext'] = target_ext
572 return [filename
], info
575 class FFmpegVideoRemuxerPP(FFmpegVideoConvertorPP
):
579 def _options(target_ext
):
580 return FFmpegPostProcessor
.stream_copy_opts()
583 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
584 def __init__(self
, downloader
=None, already_have_subtitle
=False):
585 super(FFmpegEmbedSubtitlePP
, self
).__init
__(downloader
)
586 self
._already
_have
_subtitle
= already_have_subtitle
588 @PostProcessor._restrict_to(images
=False)
590 if info
['ext'] not in ('mp4', 'webm', 'mkv'):
591 self
.to_screen('Subtitles can only be embedded in mp4, webm or mkv files')
593 subtitles
= info
.get('requested_subtitles')
595 self
.to_screen('There aren\'t any subtitles to embed')
598 filename
= info
['filepath']
600 # Disabled temporarily. There needs to be a way to overide this
601 # in case of duration actually mismatching in extractor
602 # See: https://github.com/yt-dlp/yt-dlp/issues/1870, https://github.com/yt-dlp/yt-dlp/issues/1385
604 if info.get('duration') and not info.get('__real_download') and self._duration_mismatch(
605 self._get_real_video_duration(filename, False), info['duration']):
606 self.to_screen(f'Skipping {self.pp_key()} since the real and expected durations mismatch')
611 sub_langs
, sub_names
, sub_filenames
= [], [], []
612 webm_vtt_warn
= False
615 for lang
, sub_info
in subtitles
.items():
616 if not os
.path
.exists(sub_info
.get('filepath', '')):
617 self
.report_warning(f
'Skipping embedding {lang} subtitle because the file is missing')
619 sub_ext
= sub_info
['ext']
620 if sub_ext
== 'json':
621 self
.report_warning('JSON subtitles cannot be embedded')
622 elif ext
!= 'webm' or ext
== 'webm' and sub_ext
== 'vtt':
623 sub_langs
.append(lang
)
624 sub_names
.append(sub_info
.get('name'))
625 sub_filenames
.append(sub_info
['filepath'])
627 if not webm_vtt_warn
and ext
== 'webm' and sub_ext
!= 'vtt':
629 self
.report_warning('Only WebVTT subtitles can be embedded in webm files')
630 if not mp4_ass_warn
and ext
== 'mp4' and sub_ext
== 'ass':
632 self
.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues')
637 input_files
= [filename
] + sub_filenames
640 *self
.stream_copy_opts(ext
=info
['ext']),
641 # Don't copy the existing subtitles, we may be running the
642 # postprocessor a second time
645 for i
, (lang
, name
) in enumerate(zip(sub_langs
, sub_names
)):
646 opts
.extend(['-map', '%d:0' % (i
+ 1)])
647 lang_code
= ISO639Utils
.short2long(lang
) or lang
648 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
650 opts
.extend(['-metadata:s:s:%d' % i
, 'handler_name=%s' % name
,
651 '-metadata:s:s:%d' % i
, 'title=%s' % name
])
653 temp_filename
= prepend_extension(filename
, 'temp')
654 self
.to_screen('Embedding subtitles in "%s"' % filename
)
655 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
656 os
.replace(temp_filename
, filename
)
658 files_to_delete
= [] if self
._already
_have
_subtitle
else sub_filenames
659 return files_to_delete
, info
662 class FFmpegMetadataPP(FFmpegPostProcessor
):
664 def __init__(self
, downloader
, add_metadata
=True, add_chapters
=True, add_infojson
='if_exists'):
665 FFmpegPostProcessor
.__init
__(self
, downloader
)
666 self
._add
_metadata
= add_metadata
667 self
._add
_chapters
= add_chapters
668 self
._add
_infojson
= add_infojson
671 def _options(target_ext
):
672 audio_only
= target_ext
== 'm4a'
673 yield from FFmpegPostProcessor
.stream_copy_opts(not audio_only
)
675 yield from ('-vn', '-acodec', 'copy')
677 @PostProcessor._restrict_to(images
=False)
679 filename
, metadata_filename
= info
['filepath'], None
680 files_to_delete
, options
= [], []
681 if self
._add
_chapters
and info
.get('chapters'):
682 metadata_filename
= replace_extension(filename
, 'meta')
683 options
.extend(self
._get
_chapter
_opts
(info
['chapters'], metadata_filename
))
684 files_to_delete
.append(metadata_filename
)
685 if self
._add
_metadata
:
686 options
.extend(self
._get
_metadata
_opts
(info
))
688 if self
._add
_infojson
:
689 if info
['ext'] in ('mkv', 'mka'):
690 infojson_filename
= info
.get('infojson_filename')
691 options
.extend(self
._get
_infojson
_opts
(info
, infojson_filename
))
692 if not infojson_filename
:
693 files_to_delete
.append(info
.get('infojson_filename'))
694 elif self
._add
_infojson
is True:
695 self
.to_screen('The info-json can only be attached to mkv/mka files')
698 self
.to_screen('There isn\'t any metadata to add')
701 temp_filename
= prepend_extension(filename
, 'temp')
702 self
.to_screen('Adding metadata to "%s"' % filename
)
703 self
.run_ffmpeg_multiple_files(
704 (filename
, metadata_filename
), temp_filename
,
705 itertools
.chain(self
._options
(info
['ext']), *options
))
706 for file in filter(None, files_to_delete
):
707 os
.remove(file) # Don't obey --keep-files
708 os
.replace(temp_filename
, filename
)
712 def _get_chapter_opts(chapters
, metadata_filename
):
713 with io
.open(metadata_filename
, 'wt', encoding
='utf-8') as f
:
714 def ffmpeg_escape(text
):
715 return re
.sub(r
'([\\=;#\n])', r
'\\\1', text
)
717 metadata_file_content
= ';FFMETADATA1\n'
718 for chapter
in chapters
:
719 metadata_file_content
+= '[CHAPTER]\nTIMEBASE=1/1000\n'
720 metadata_file_content
+= 'START=%d\n' % (chapter
['start_time'] * 1000)
721 metadata_file_content
+= 'END=%d\n' % (chapter
['end_time'] * 1000)
722 chapter_title
= chapter
.get('title')
724 metadata_file_content
+= 'title=%s\n' % ffmpeg_escape(chapter_title
)
725 f
.write(metadata_file_content
)
726 yield ('-map_metadata', '1')
728 def _get_metadata_opts(self
, info
):
730 metadata
= collections
.defaultdict(dict)
732 def add(meta_list
, info_list
=None):
734 str(info
[key
]) for key
in [f
'{meta_prefix}_'] + list(variadic(info_list
or meta_list
))
735 if info
.get(key
) is not None), None)
736 if value
not in ('', None):
737 metadata
['common'].update({meta_f: value for meta_f in variadic(meta_list)}
)
739 # See [1-4] for some info on media metadata/metadata supported
741 # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
742 # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
743 # 3. https://kodi.wiki/view/Video_file_tagging
745 add('title', ('track', 'title'))
746 add('date', 'upload_date')
747 add(('description', 'synopsis'), 'description')
748 add(('purl', 'comment'), 'webpage_url')
749 add('track', 'track_number')
750 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
754 add('disc', 'disc_number')
755 add('show', 'series')
757 add('episode_id', ('episode', 'episode_id'))
758 add('episode_sort', 'episode_number')
759 if 'embed-metadata' in self
.get_param('compat_opts', []):
760 add('comment', 'description')
761 metadata
['common'].pop('synopsis', None)
763 meta_regex
= rf
'{re.escape(meta_prefix)}(?P<i>\d+)?_(?P<key>.+)'
764 for key
, value
in info
.items():
765 mobj
= re
.fullmatch(meta_regex
, key
)
766 if value
is not None and mobj
:
767 metadata
[mobj
.group('i') or 'common'][mobj
.group('key')] = value
769 for name
, value
in metadata
['common'].items():
770 yield ('-metadata', f
'{name}={value}')
773 for fmt
in info
.get('requested_formats') or []:
774 stream_count
= 2 if 'none' not in (fmt
.get('vcodec'), fmt
.get('acodec')) else 1
775 lang
= ISO639Utils
.short2long(fmt
.get('language') or '') or fmt
.get('language')
776 for i
in range(stream_idx
, stream_idx
+ stream_count
):
778 metadata
[str(i
)].setdefault('language', lang
)
779 for name
, value
in metadata
[str(i
)].items():
780 yield (f
'-metadata:s:{i}', f
'{name}={value}')
781 stream_idx
+= stream_count
783 def _get_infojson_opts(self
, info
, infofn
):
784 if not infofn
or not os
.path
.exists(infofn
):
785 if self
._add
_infojson
is not True:
787 infofn
= infofn
or '%s.temp' % (
788 self
._downloader
.prepare_filename(info
, 'infojson')
789 or replace_extension(self
._downloader
.prepare_filename(info
), 'info.json', info
['ext']))
790 if not self
._downloader
._ensure
_dir
_exists
(infofn
):
792 self
.write_debug(f
'Writing info-json to: {infofn}')
793 write_json_file(self
._downloader
.sanitize_info(info
, self
.get_param('clean_infojson', True)), infofn
)
794 info
['infojson_filename'] = infofn
796 old_stream
, new_stream
= self
.get_stream_number(info
['filepath'], ('tags', 'mimetype'), 'application/json')
797 if old_stream
is not None:
798 yield ('-map', '-0:%d' % old_stream
)
801 yield ('-attach', infofn
,
802 '-metadata:s:%d' % new_stream
, 'mimetype=application/json')
805 class FFmpegMergerPP(FFmpegPostProcessor
):
806 @PostProcessor._restrict_to(images
=False)
808 filename
= info
['filepath']
809 temp_filename
= prepend_extension(filename
, 'temp')
810 args
= ['-c', 'copy']
812 for (i
, fmt
) in enumerate(info
['requested_formats']):
813 if fmt
.get('acodec') != 'none':
814 args
.extend(['-map', f
'{i}:a:0'])
815 aac_fixup
= fmt
['protocol'].startswith('m3u8') and self
.get_audio_codec(fmt
['filepath']) == 'aac'
817 args
.extend([f
'-bsf:a:{audio_streams}', 'aac_adtstoasc'])
819 if fmt
.get('vcodec') != 'none':
820 args
.extend(['-map', '%u:v:0' % (i
)])
821 self
.to_screen('Merging formats into "%s"' % filename
)
822 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
823 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
824 return info
['__files_to_merge'], info
827 # TODO: figure out merge-capable ffmpeg version
828 if self
.basename
!= 'avconv':
831 required_version
= '10-0'
832 if is_outdated_version(
833 self
._versions
[self
.basename
], required_version
):
834 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
835 'yt-dlp will download single file media. '
836 'Update %s to version %s or newer to fix this.') % (
837 self
.basename
, self
.basename
, required_version
)
838 self
.report_warning(warning
)
843 class FFmpegFixupPostProcessor(FFmpegPostProcessor
):
844 def _fixup(self
, msg
, filename
, options
):
845 temp_filename
= prepend_extension(filename
, 'temp')
847 self
.to_screen(f
'{msg} of "{filename}"')
848 self
.run_ffmpeg(filename
, temp_filename
, options
)
850 os
.replace(temp_filename
, filename
)
853 class FFmpegFixupStretchedPP(FFmpegFixupPostProcessor
):
854 @PostProcessor._restrict_to(images
=False, audio
=False)
856 stretched_ratio
= info
.get('stretched_ratio')
857 if stretched_ratio
not in (None, 1):
858 self
._fixup
('Fixing aspect ratio', info
['filepath'], [
859 *self
.stream_copy_opts(), '-aspect', '%f' % stretched_ratio
])
863 class FFmpegFixupM4aPP(FFmpegFixupPostProcessor
):
864 @PostProcessor._restrict_to(images
=False, video
=False)
866 if info
.get('container') == 'm4a_dash':
867 self
._fixup
('Correcting container', info
['filepath'], [*self
.stream_copy_opts(), '-f', 'mp4'])
871 class FFmpegFixupM3u8PP(FFmpegFixupPostProcessor
):
872 def _needs_fixup(self
, info
):
873 yield info
['ext'] in ('mp4', 'm4a')
874 yield info
['protocol'].startswith('m3u8')
876 metadata
= self
.get_metadata_object(info
['filepath'])
877 except PostProcessingError
as e
:
878 self
.report_warning(f
'Unable to extract metadata: {e.msg}')
881 yield traverse_obj(metadata
, ('format', 'format_name'), casesense
=False) == 'mpegts'
883 @PostProcessor._restrict_to(images
=False)
885 if all(self
._needs
_fixup
(info
)):
886 self
._fixup
('Fixing MPEG-TS in MP4 container', info
['filepath'], [
887 *self
.stream_copy_opts(), '-f', 'mp4', '-bsf:a', 'aac_adtstoasc'])
891 class FFmpegFixupTimestampPP(FFmpegFixupPostProcessor
):
893 def __init__(self
, downloader
=None, trim
=0.001):
894 # "trim" should be used when the video contains unintended packets
895 super(FFmpegFixupTimestampPP
, self
).__init
__(downloader
)
896 assert isinstance(trim
, (int, float))
897 self
.trim
= str(trim
)
899 @PostProcessor._restrict_to(images
=False)
901 if not self
._features
.get('setts'):
903 'A re-encode is needed to fix timestamps in older versions of ffmpeg. '
904 'Please install ffmpeg 4.4 or later to fixup without re-encoding')
905 opts
= ['-vf', 'setpts=PTS-STARTPTS']
907 opts
= ['-c', 'copy', '-bsf', 'setts=ts=TS-STARTPTS']
908 self
._fixup
('Fixing frame timestamp', info
['filepath'], opts
+ [*self
.stream_copy_opts(False), '-ss', self
.trim
])
912 class FFmpegCopyStreamPP(FFmpegFixupPostProcessor
):
913 MESSAGE
= 'Copying stream'
915 @PostProcessor._restrict_to(images
=False)
917 self
._fixup
(self
.MESSAGE
, info
['filepath'], self
.stream_copy_opts())
921 class FFmpegFixupDurationPP(FFmpegCopyStreamPP
):
922 MESSAGE
= 'Fixing video duration'
925 class FFmpegFixupDuplicateMoovPP(FFmpegCopyStreamPP
):
926 MESSAGE
= 'Fixing duplicate MOOV atoms'
929 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
930 SUPPORTED_EXTS
= ('srt', 'vtt', 'ass', 'lrc')
932 def __init__(self
, downloader
=None, format
=None):
933 super(FFmpegSubtitlesConvertorPP
, self
).__init
__(downloader
)
937 subs
= info
.get('requested_subtitles')
938 new_ext
= self
.format
940 if new_format
== 'vtt':
941 new_format
= 'webvtt'
943 self
.to_screen('There aren\'t any subtitles to convert')
945 self
.to_screen('Converting subtitles')
947 for lang
, sub
in subs
.items():
948 if not os
.path
.exists(sub
.get('filepath', '')):
949 self
.report_warning(f
'Skipping embedding {lang} subtitle because the file is missing')
953 self
.to_screen('Subtitle file for %s is already in the requested format' % new_ext
)
957 'You have requested to convert json subtitles into another format, '
958 'which is currently not possible')
960 old_file
= sub
['filepath']
961 sub_filenames
.append(old_file
)
962 new_file
= replace_extension(old_file
, new_ext
)
964 if ext
in ('dfxp', 'ttml', 'tt'):
966 'You have requested to convert dfxp (TTML) subtitles into another format, '
967 'which results in style information loss')
970 srt_file
= replace_extension(old_file
, 'srt')
972 with open(dfxp_file
, 'rb') as f
:
973 srt_data
= dfxp2srt(f
.read())
975 with io
.open(srt_file
, 'wt', encoding
='utf-8') as f
:
982 'filepath': srt_file
,
988 sub_filenames
.append(srt_file
)
990 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
992 with io
.open(new_file
, 'rt', encoding
='utf-8') as f
:
996 'filepath': new_file
,
999 info
['__files_to_move'][new_file
] = replace_extension(
1000 info
['__files_to_move'][sub
['filepath']], new_ext
)
1002 return sub_filenames
, info
1005 class FFmpegSplitChaptersPP(FFmpegPostProcessor
):
1006 def __init__(self
, downloader
, force_keyframes
=False):
1007 FFmpegPostProcessor
.__init
__(self
, downloader
)
1008 self
._force
_keyframes
= force_keyframes
1010 def _prepare_filename(self
, number
, chapter
, info
):
1013 'section_number': number
,
1014 'section_title': chapter
.get('title'),
1015 'section_start': chapter
.get('start_time'),
1016 'section_end': chapter
.get('end_time'),
1018 return self
._downloader
.prepare_filename(info
, 'chapter')
1020 def _ffmpeg_args_for_chapter(self
, number
, chapter
, info
):
1021 destination
= self
._prepare
_filename
(number
, chapter
, info
)
1022 if not self
._downloader
._ensure
_dir
_exists
(encodeFilename(destination
)):
1025 chapter
['filepath'] = destination
1026 self
.to_screen('Chapter %03d; Destination: %s' % (number
, destination
))
1029 ['-ss', compat_str(chapter
['start_time']),
1030 '-t', compat_str(chapter
['end_time'] - chapter
['start_time'])])
1032 @PostProcessor._restrict_to(images
=False)
1033 def run(self
, info
):
1034 chapters
= info
.get('chapters') or []
1036 self
.to_screen('Chapter information is unavailable')
1039 in_file
= info
['filepath']
1040 if self
._force
_keyframes
and len(chapters
) > 1:
1041 in_file
= self
.force_keyframes(in_file
, (c
['start_time'] for c
in chapters
))
1042 self
.to_screen('Splitting video by chapters; %d chapters found' % len(chapters
))
1043 for idx
, chapter
in enumerate(chapters
):
1044 destination
, opts
= self
._ffmpeg
_args
_for
_chapter
(idx
+ 1, chapter
, info
)
1045 self
.real_run_ffmpeg([(in_file
, opts
)], [(destination
, self
.stream_copy_opts())])
1046 if in_file
!= info
['filepath']:
1051 class FFmpegThumbnailsConvertorPP(FFmpegPostProcessor
):
1052 SUPPORTED_EXTS
= ('jpg', 'png', 'webp')
1054 def __init__(self
, downloader
=None, format
=None):
1055 super(FFmpegThumbnailsConvertorPP
, self
).__init
__(downloader
)
1056 self
.format
= format
1060 with open(encodeFilename(path
), 'rb') as f
:
1062 return b
[0:4] == b
'RIFF' and b
[8:] == b
'WEBP'
1064 def fixup_webp(self
, info
, idx
=-1):
1065 thumbnail_filename
= info
['thumbnails'][idx
]['filepath']
1066 _
, thumbnail_ext
= os
.path
.splitext(thumbnail_filename
)
1068 thumbnail_ext
= thumbnail_ext
[1:].lower()
1069 if thumbnail_ext
!= 'webp' and self
.is_webp(thumbnail_filename
):
1070 self
.to_screen('Correcting thumbnail "%s" extension to webp' % thumbnail_filename
)
1071 webp_filename
= replace_extension(thumbnail_filename
, 'webp')
1072 os
.replace(thumbnail_filename
, webp_filename
)
1073 info
['thumbnails'][idx
]['filepath'] = webp_filename
1074 info
['__files_to_move'][webp_filename
] = replace_extension(
1075 info
['__files_to_move'].pop(thumbnail_filename
), 'webp')
1078 def _options(target_ext
):
1079 if target_ext
== 'jpg':
1080 return ['-bsf:v', 'mjpeg2jpeg']
1083 def convert_thumbnail(self
, thumbnail_filename
, target_ext
):
1084 thumbnail_conv_filename
= replace_extension(thumbnail_filename
, target_ext
)
1086 self
.to_screen('Converting thumbnail "%s" to %s' % (thumbnail_filename
, target_ext
))
1087 self
.real_run_ffmpeg(
1088 [(thumbnail_filename
, ['-f', 'image2', '-pattern_type', 'none'])],
1089 [(thumbnail_conv_filename
.replace('%', '%%'), self
._options
(target_ext
))])
1090 return thumbnail_conv_filename
1092 def run(self
, info
):
1093 files_to_delete
= []
1094 has_thumbnail
= False
1096 for idx
, thumbnail_dict
in enumerate(info
.get('thumbnails') or []):
1097 original_thumbnail
= thumbnail_dict
.get('filepath')
1098 if not original_thumbnail
:
1100 has_thumbnail
= True
1101 self
.fixup_webp(info
, idx
)
1102 _
, thumbnail_ext
= os
.path
.splitext(original_thumbnail
)
1104 thumbnail_ext
= thumbnail_ext
[1:].lower()
1105 if thumbnail_ext
== 'jpeg':
1106 thumbnail_ext
= 'jpg'
1107 if thumbnail_ext
== self
.format
:
1108 self
.to_screen('Thumbnail "%s" is already in the requested format' % original_thumbnail
)
1110 thumbnail_dict
['filepath'] = self
.convert_thumbnail(original_thumbnail
, self
.format
)
1111 files_to_delete
.append(original_thumbnail
)
1112 info
['__files_to_move'][thumbnail_dict
['filepath']] = replace_extension(
1113 info
['__files_to_move'][original_thumbnail
], self
.format
)
1115 if not has_thumbnail
:
1116 self
.to_screen('There aren\'t any thumbnails to convert')
1117 return files_to_delete
, info
1120 class FFmpegConcatPP(FFmpegPostProcessor
):
1121 def __init__(self
, downloader
, only_multi_video
=False):
1122 self
._only
_multi
_video
= only_multi_video
1123 super().__init
__(downloader
)
1125 def concat_files(self
, in_files
, out_file
):
1126 if not self
._downloader
._ensure
_dir
_exists
(out_file
):
1128 if len(in_files
) == 1:
1129 if os
.path
.realpath(in_files
[0]) != os
.path
.realpath(out_file
):
1130 self
.to_screen(f
'Moving "{in_files[0]}" to "{out_file}"')
1131 os
.replace(in_files
[0], out_file
)
1134 codecs
= [traverse_obj(self
.get_metadata_object(file), ('streams', ..., 'codec_name')) for file in in_files
]
1135 if len(set(map(tuple, codecs
))) > 1:
1136 raise PostProcessingError(
1137 'The files have different streams/codecs and cannot be concatenated. '
1138 'Either select different formats or --recode-video them to a common format')
1140 self
.to_screen(f
'Concatenating {len(in_files)} files; Destination: {out_file}')
1141 super().concat_files(in_files
, out_file
)
1144 @PostProcessor._restrict_to(images
=False, simulated
=False)
1145 def run(self
, info
):
1146 entries
= info
.get('entries') or []
1147 if not any(entries
) or (self
._only
_multi
_video
and info
['_type'] != 'multi_video'):
1149 elif any(len(entry
) > 1 for entry
in traverse_obj(entries
, (..., 'requested_downloads')) or []):
1150 raise PostProcessingError('Concatenation is not supported when downloading multiple separate formats')
1152 in_files
= traverse_obj(entries
, (..., 'requested_downloads', 0, 'filepath')) or []
1153 if len(in_files
) < len(entries
):
1154 raise PostProcessingError('Aborting concatenation because some downloads failed')
1156 ie_copy
= self
._downloader
._playlist
_infodict
(info
)
1157 exts
= traverse_obj(entries
, (..., 'requested_downloads', 0, 'ext'), (..., 'ext'))
1158 ie_copy
['ext'] = exts
[0] if len(set(exts
)) == 1 else 'mkv'
1159 out_file
= self
._downloader
.prepare_filename(ie_copy
, 'pl_video')
1161 files_to_delete
= self
.concat_files(in_files
, out_file
)
1163 info
['requested_downloads'] = [{
1164 'filepath': out_file
,
1165 'ext': ie_copy
['ext'],
1167 return files_to_delete
, info