9 from .common
import AudioConversionError
, PostProcessor
10 from ..compat
import compat_str
15 _get_exe_version_output
,
32 EXT_TO_OUT_FORMATS
= {
51 'vorbis': 'libvorbis',
57 class FFmpegPostProcessorError(PostProcessingError
):
61 class FFmpegPostProcessor(PostProcessor
):
62 def __init__(self
, downloader
=None):
63 PostProcessor
.__init
__(self
, downloader
)
64 self
._determine
_executables
()
66 def check_version(self
):
67 if not self
.available
:
68 raise FFmpegPostProcessorError('ffmpeg not found. Please install or provide the path using --ffmpeg-location')
70 required_version
= '10-0' if self
.basename
== 'avconv' else '1.0'
71 if is_outdated_version(self
._versions
[self
.basename
], required_version
):
72 self
.report_warning(f
'Your copy of {self.basename} is outdated, update {self.basename} '
73 f
'to version {required_version} or newer if you encounter any errors')
76 def get_versions_and_features(downloader
=None):
77 pp
= FFmpegPostProcessor(downloader
)
78 return pp
._versions
, pp
._features
81 def get_versions(downloader
=None):
82 return FFmpegPostProcessor
.get_versions_and_features(downloader
)[0]
84 _version_cache
, _features_cache
= {}, {}
86 def _determine_executables(self
):
87 programs
= ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
89 def get_ffmpeg_version(path
, prog
):
90 if path
in self
._version
_cache
:
91 self
._versions
[prog
], self
._features
= self
._version
_cache
[path
], self
._features
_cache
.get(path
, {})
93 out
= _get_exe_version_output(path
, ['-bsfs'], to_screen
=self
.write_debug
)
94 ver
= detect_exe_version(out
) if out
else False
97 r
'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1]
98 r
'n([0-9.]+)$', # Arch Linux
99 # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/
102 mobj
= re
.match(regex
, ver
)
105 self
._versions
[prog
] = self
._version
_cache
[path
] = ver
106 if prog
!= 'ffmpeg' or not out
:
109 mobj
= re
.search(r
'(?m)^\s+libavformat\s+(?:[0-9. ]+)\s+/\s+(?P<runtime>[0-9. ]+)', out
)
110 lavf_runtime_version
= mobj
.group('runtime').replace(' ', '') if mobj
else None
111 self
._features
= self
._features
_cache
[path
] = {
112 'fdk': '--enable-libfdk-aac' in out
,
113 'setts': 'setts' in out
.splitlines(),
114 'needs_adtstoasc': is_outdated_version(lavf_runtime_version
, '57.56.100', False),
118 self
.probe_basename
= None
120 self
._versions
= None
123 prefer_ffmpeg
= self
.get_param('prefer_ffmpeg', True)
124 location
= self
.get_param('ffmpeg_location')
126 self
._paths
= {p: p for p in programs}
128 if not os
.path
.exists(location
):
130 'ffmpeg-location %s does not exist! '
131 'Continuing without ffmpeg.' % (location
))
134 elif os
.path
.isdir(location
):
135 dirname
, basename
= location
, None
137 basename
= os
.path
.splitext(os
.path
.basename(location
))[0]
138 basename
= next((p
for p
in programs
if basename
.startswith(p
)), 'ffmpeg')
139 dirname
= os
.path
.dirname(os
.path
.abspath(location
))
140 if basename
in ('ffmpeg', 'ffprobe'):
144 p
: os
.path
.join(dirname
, p
) for p
in programs
}
146 self
._paths
[basename
] = location
149 # NB: probe must be first for _features to be poulated correctly
150 executables
= {'probe_basename': ('ffprobe', 'avprobe'), 'basename': ('ffmpeg', 'avconv')}
151 if prefer_ffmpeg
is False:
152 executables
= {k: v[::-1] for k, v in executables.items()}
153 for var
, prefs
in executables
.items():
155 get_ffmpeg_version(self
._paths
[p
], p
)
156 if self
._versions
[p
]:
157 setattr(self
, var
, p
)
160 if self
.basename
== 'avconv':
161 self
.deprecation_warning(
162 'Support for avconv is deprecated and may be removed in a future version. Use ffmpeg instead')
163 if self
.probe_basename
== 'avprobe':
164 self
.deprecation_warning(
165 'Support for avprobe is deprecated and may be removed in a future version. Use ffprobe instead')
169 return self
.basename
is not None
172 def executable(self
):
173 return self
._paths
[self
.basename
]
176 def probe_available(self
):
177 return self
.probe_basename
is not None
180 def probe_executable(self
):
181 return self
._paths
[self
.probe_basename
]
184 def stream_copy_opts(copy
=True, *, ext
=None):
185 yield from ('-map', '0')
186 # Don't copy Apple TV chapters track, bin_data
187 # See https://github.com/yt-dlp/yt-dlp/issues/2, #19042, #19024, https://trac.ffmpeg.org/ticket/6016
188 yield from ('-dn', '-ignore_unknown')
190 yield from ('-c', 'copy')
191 if ext
in ('mp4', 'mov', 'm4a'):
192 yield from ('-c:s', 'mov_text')
194 def get_audio_codec(self
, path
):
195 if not self
.probe_available
and not self
.available
:
196 raise PostProcessingError('ffprobe and ffmpeg not found. Please install or provide the path using --ffmpeg-location')
198 if self
.probe_available
:
200 encodeFilename(self
.probe_executable
, True),
201 encodeArgument('-show_streams')]
204 encodeFilename(self
.executable
, True),
205 encodeArgument('-i')]
206 cmd
.append(encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True))
207 self
.write_debug(f
'{self.basename} command line: {shell_quote(cmd)}')
208 handle
= Popen(cmd
, stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
209 stdout_data
, stderr_data
= handle
.communicate_or_kill()
210 expected_ret
= 0 if self
.probe_available
else 1
211 if handle
.wait() != expected_ret
:
215 output
= (stdout_data
if self
.probe_available
else stderr_data
).decode('ascii', 'ignore')
216 if self
.probe_available
:
218 for line
in output
.split('\n'):
219 if line
.startswith('codec_name='):
220 audio_codec
= line
.split('=')[1].strip()
221 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
224 # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME
226 r
'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)',
232 def get_metadata_object(self
, path
, opts
=[]):
233 if self
.probe_basename
!= 'ffprobe':
234 if self
.probe_available
:
235 self
.report_warning('Only ffprobe is supported for metadata extraction')
236 raise PostProcessingError('ffprobe not found. Please install or provide the path using --ffmpeg-location')
240 encodeFilename(self
.probe_executable
, True),
241 encodeArgument('-hide_banner'),
242 encodeArgument('-show_format'),
243 encodeArgument('-show_streams'),
244 encodeArgument('-print_format'),
245 encodeArgument('json'),
249 cmd
.append(encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True))
250 self
.write_debug('ffprobe command line: %s' % shell_quote(cmd
))
251 p
= Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
252 stdout
, stderr
= p
.communicate()
253 return json
.loads(stdout
.decode('utf-8', 'replace'))
255 def get_stream_number(self
, path
, keys
, value
):
256 streams
= self
.get_metadata_object(path
)['streams']
258 (i
for i
, stream
in enumerate(streams
) if traverse_obj(stream
, keys
, casesense
=False) == value
),
260 return num
, len(streams
)
262 def _get_real_video_duration(self
, filepath
, fatal
=True):
264 duration
= float_or_none(
265 traverse_obj(self
.get_metadata_object(filepath
), ('format', 'duration')))
267 raise PostProcessingError('ffprobe returned empty duration')
269 except PostProcessingError
as e
:
271 raise PostProcessingError(f
'Unable to determine video duration: {e.msg}')
273 def _duration_mismatch(self
, d1
, d2
):
276 # The duration is often only known to nearest second. So there can be <1sec disparity natually.
277 # Further excuse an additional <1sec difference.
278 return abs(d1
- d2
) > 2
280 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
, **kwargs
):
281 return self
.real_run_ffmpeg(
282 [(path
, []) for path
in input_paths
],
283 [(out_path
, opts
)], **kwargs
)
285 def real_run_ffmpeg(self
, input_path_opts
, output_path_opts
, *, expected_retcodes
=(0,)):
289 os
.stat(encodeFilename(path
)).st_mtime
for path
, _
in input_path_opts
if path
)
291 cmd
= [encodeFilename(self
.executable
, True), encodeArgument('-y')]
292 # avconv does not have repeat option
293 if self
.basename
== 'ffmpeg':
294 cmd
+= [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
296 def make_args(file, args
, name
, number
):
297 keys
= ['_%s%d' % (name
, number
), '_%s' % name
]
299 args
+= ['-movflags', '+faststart']
302 args
+= self
._configuration
_args
(self
.basename
, keys
)
306 [encodeArgument(arg
) for arg
in args
]
307 + [encodeFilename(self
._ffmpeg
_filename
_argument
(file), True)])
309 for arg_type
, path_opts
in (('i', input_path_opts
), ('o', output_path_opts
)):
310 cmd
+= itertools
.chain
.from_iterable(
311 make_args(path
, list(opts
), arg_type
, i
+ 1)
312 for i
, (path
, opts
) in enumerate(path_opts
) if path
)
314 self
.write_debug('ffmpeg command line: %s' % shell_quote(cmd
))
315 p
= Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
316 stdout
, stderr
= p
.communicate_or_kill()
317 if p
.returncode
not in variadic(expected_retcodes
):
318 stderr
= stderr
.decode('utf-8', 'replace').strip()
319 self
.write_debug(stderr
)
320 raise FFmpegPostProcessorError(stderr
.split('\n')[-1])
321 for out_path
, _
in output_path_opts
:
323 self
.try_utime(out_path
, oldest_mtime
, oldest_mtime
)
324 return stderr
.decode('utf-8', 'replace')
326 def run_ffmpeg(self
, path
, out_path
, opts
, **kwargs
):
327 return self
.run_ffmpeg_multiple_files([path
], out_path
, opts
, **kwargs
)
330 def _ffmpeg_filename_argument(fn
):
331 # Always use 'file:' because the filename may contain ':' (ffmpeg
332 # interprets that as a protocol) or can start with '-' (-- is broken in
333 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
334 # Also leave '-' intact in order not to break streaming to stdout.
335 if fn
.startswith(('http://', 'https://')):
337 return 'file:' + fn
if fn
!= '-' else fn
340 def _quote_for_ffmpeg(string
):
341 # See https://ffmpeg.org/ffmpeg-utils.html#toc-Quoting-and-escaping
342 # A sequence of '' produces '\'''\'';
343 # final replace removes the empty '' between \' \'.
344 string
= string
.replace("'", r
"'\''").replace("'''", "'")
345 # Handle potential ' at string boundaries.
346 string
= string
[1:] if string
[0] == "'" else "'" + string
347 return string
[:-1] if string
[-1] == "'" else string
+ "'"
349 def force_keyframes(self
, filename
, timestamps
):
350 timestamps
= orderedSet(timestamps
)
351 if timestamps
[0] == 0:
352 timestamps
= timestamps
[1:]
353 keyframe_file
= prepend_extension(filename
, 'keyframes.temp')
354 self
.to_screen(f
'Re-encoding "{filename}" with appropriate keyframes')
355 self
.run_ffmpeg(filename
, keyframe_file
, [
356 *self
.stream_copy_opts(False, ext
=determine_ext(filename
)),
357 '-force_key_frames', ','.join(f
'{t:.6f}' for t
in timestamps
)])
360 def concat_files(self
, in_files
, out_file
, concat_opts
=None):
362 Use concat demuxer to concatenate multiple files having identical streams.
364 Only inpoint, outpoint, and duration concat options are supported.
365 See https://ffmpeg.org/ffmpeg-formats.html#concat-1 for details
367 concat_file
= f
'{out_file}.concat'
368 self
.write_debug(f
'Writing concat spec to {concat_file}')
369 with open(concat_file
, 'wt', encoding
='utf-8') as f
:
370 f
.writelines(self
._concat
_spec
(in_files
, concat_opts
))
372 out_flags
= list(self
.stream_copy_opts(ext
=determine_ext(out_file
)))
374 self
.real_run_ffmpeg(
375 [(concat_file
, ['-hide_banner', '-nostdin', '-f', 'concat', '-safe', '0'])],
376 [(out_file
, out_flags
)])
377 self
._delete
_downloaded
_files
(concat_file
)
380 def _concat_spec(cls
, in_files
, concat_opts
=None):
381 if concat_opts
is None:
382 concat_opts
= [{}] * len(in_files
)
383 yield 'ffconcat version 1.0\n'
384 for file, opts
in zip(in_files
, concat_opts
):
385 yield f
'file {cls._quote_for_ffmpeg(cls._ffmpeg_filename_argument(file))}\n'
386 # Iterate explicitly to yield the following directives in order, ignoring the rest.
387 for directive
in 'inpoint', 'outpoint', 'duration':
388 if directive
in opts
:
389 yield f
'{directive} {opts[directive]}\n'
392 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
393 COMMON_AUDIO_EXTS
= ('wav', 'flac', 'm4a', 'aiff', 'mp3', 'ogg', 'mka', 'opus', 'wma')
394 SUPPORTED_EXTS
= ('aac', 'flac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav', 'alac')
396 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
397 FFmpegPostProcessor
.__init
__(self
, downloader
)
398 self
._preferredcodec
= preferredcodec
or 'best'
399 self
._preferredquality
= float_or_none(preferredquality
)
400 self
._nopostoverwrites
= nopostoverwrites
402 def _quality_args(self
, codec
):
403 if self
._preferredquality
is None:
405 elif self
._preferredquality
> 10:
406 return ['-b:a', f
'{self._preferredquality}k']
409 'libmp3lame': (10, 0),
410 'libvorbis': (0, 10),
411 # FFmpeg's AAC encoder does not have an upper limit for the value of -q:a.
412 # Experimentally, with values over 4, bitrate changes were minimal or non-existent
414 'libfdk_aac': (1, 5),
419 q
= limits
[1] + (limits
[0] - limits
[1]) * (self
._preferredquality
/ 10)
420 if codec
== 'libfdk_aac':
421 return ['-vbr', f
'{int(q)}']
422 return ['-q:a', f
'{q}']
424 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
428 acodec_opts
= ['-acodec', codec
]
429 opts
= ['-vn'] + acodec_opts
+ more_opts
431 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
432 except FFmpegPostProcessorError
as err
:
433 raise AudioConversionError(err
.msg
)
435 @PostProcessor._restrict_to(images
=False)
436 def run(self
, information
):
437 orig_path
= path
= information
['filepath']
438 orig_ext
= information
['ext']
440 if self
._preferredcodec
== 'best' and orig_ext
in self
.COMMON_AUDIO_EXTS
:
441 self
.to_screen('Skipping audio extraction since the file is already in a common audio format')
442 return [], information
444 filecodec
= self
.get_audio_codec(path
)
445 if filecodec
is None:
446 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
449 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
450 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
451 # Lossless, but in another container
454 more_opts
= ['-bsf:a', 'aac_adtstoasc']
455 elif filecodec
in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
456 # Lossless if possible
458 extension
= filecodec
459 if filecodec
== 'aac':
460 more_opts
= ['-f', 'adts']
461 if filecodec
== 'vorbis':
463 elif filecodec
== 'alac':
466 more_opts
+= ['-acodec', 'alac']
469 acodec
= 'libmp3lame'
471 more_opts
= self
._quality
_args
(acodec
)
473 # We convert the audio (lossy if codec is lossy)
474 acodec
= ACODECS
[self
._preferredcodec
]
475 if acodec
== 'aac' and self
._features
.get('fdk'):
476 acodec
= 'libfdk_aac'
477 extension
= self
._preferredcodec
478 more_opts
= self
._quality
_args
(acodec
)
479 if self
._preferredcodec
== 'aac':
480 more_opts
+= ['-f', 'adts']
481 elif self
._preferredcodec
== 'm4a':
482 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
483 elif self
._preferredcodec
== 'vorbis':
485 elif self
._preferredcodec
== 'wav':
487 more_opts
+= ['-f', 'wav']
488 elif self
._preferredcodec
== 'alac':
490 more_opts
+= ['-acodec', 'alac']
492 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
493 temp_path
= new_path
= prefix
+ sep
+ extension
497 self
.to_screen(f
'File is already in target format {self._preferredcodec}, skipping')
498 return [], information
499 orig_path
= prepend_extension(path
, 'orig')
500 temp_path
= prepend_extension(path
, 'temp')
501 if (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
))
502 and os
.path
.exists(encodeFilename(orig_path
))):
503 self
.to_screen('Post-process file %s exists, skipping' % new_path
)
504 return [], information
507 self
.to_screen(f
'Destination: {new_path}')
508 self
.run_ffmpeg(path
, temp_path
, acodec
, more_opts
)
509 except AudioConversionError
as e
:
510 raise PostProcessingError(
511 'audio conversion failed: ' + e
.msg
)
513 raise PostProcessingError('error running ' + self
.basename
)
515 os
.replace(path
, orig_path
)
516 os
.replace(temp_path
, new_path
)
517 information
['filepath'] = new_path
518 information
['ext'] = extension
520 # Try to update the date time for extracted audio file.
521 if information
.get('filetime') is not None:
523 new_path
, time
.time(), information
['filetime'],
524 errnote
='Cannot update utime of audio file')
526 return [orig_path
], information
529 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
530 SUPPORTED_EXTS
= ('mp4', 'mkv', 'flv', 'webm', 'mov', 'avi', 'mka', 'ogg', *FFmpegExtractAudioPP
.SUPPORTED_EXTS
)
531 FORMAT_RE
= re
.compile(r
'{0}(?:/{0})*$'.format(r
'(?:\w+>)?(?:%s)' % '|'.join(SUPPORTED_EXTS
)))
532 _ACTION
= 'converting'
534 def __init__(self
, downloader
=None, preferedformat
=None):
535 super().__init
__(downloader
)
536 self
._preferedformats
= preferedformat
.lower().split('/')
538 def _target_ext(self
, source_ext
):
539 for pair
in self
._preferedformats
:
541 if len(kv
) == 1 or kv
[0].strip() == source_ext
:
542 return kv
[-1].strip()
545 def _options(target_ext
):
546 yield from FFmpegPostProcessor
.stream_copy_opts(False)
547 if target_ext
== 'avi':
548 yield from ('-c:v', 'libxvid', '-vtag', 'XVID')
550 @PostProcessor._restrict_to(images
=False)
552 filename
, source_ext
= info
['filepath'], info
['ext'].lower()
553 target_ext
= self
._target
_ext
(source_ext
)
555 f
'could not find a mapping for {source_ext}' if not target_ext
556 else f
'already is in target format {source_ext}' if source_ext
== target_ext
559 self
.to_screen(f
'Not {self._ACTION} media file "{filename}"; {_skip_msg}')
562 outpath
= replace_extension(filename
, target_ext
, source_ext
)
563 self
.to_screen(f
'{self._ACTION.title()} video from {source_ext} to {target_ext}; Destination: {outpath}')
564 self
.run_ffmpeg(filename
, outpath
, self
._options
(target_ext
))
566 info
['filepath'] = outpath
567 info
['format'] = info
['ext'] = target_ext
568 return [filename
], info
571 class FFmpegVideoRemuxerPP(FFmpegVideoConvertorPP
):
575 def _options(target_ext
):
576 return FFmpegPostProcessor
.stream_copy_opts()
579 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
580 SUPPORTED_EXTS
= ('mp4', 'mov', 'm4a', 'webm', 'mkv', 'mka')
582 def __init__(self
, downloader
=None, already_have_subtitle
=False):
583 super().__init
__(downloader
)
584 self
._already
_have
_subtitle
= already_have_subtitle
586 @PostProcessor._restrict_to(images
=False)
588 if info
['ext'] not in self
.SUPPORTED_EXTS
:
589 self
.to_screen(f
'Subtitles can only be embedded in {", ".join(self.SUPPORTED_EXTS)} files')
591 subtitles
= info
.get('requested_subtitles')
593 self
.to_screen('There aren\'t any subtitles to embed')
596 filename
= info
['filepath']
598 # Disabled temporarily. There needs to be a way to overide this
599 # in case of duration actually mismatching in extractor
600 # See: https://github.com/yt-dlp/yt-dlp/issues/1870, https://github.com/yt-dlp/yt-dlp/issues/1385
602 if info.get('duration') and not info.get('__real_download') and self._duration_mismatch(
603 self._get_real_video_duration(filename, False), info['duration']):
604 self.to_screen(f'Skipping {self.pp_key()} since the real and expected durations mismatch')
609 sub_langs
, sub_names
, sub_filenames
= [], [], []
610 webm_vtt_warn
= False
613 for lang
, sub_info
in subtitles
.items():
614 if not os
.path
.exists(sub_info
.get('filepath', '')):
615 self
.report_warning(f
'Skipping embedding {lang} subtitle because the file is missing')
617 sub_ext
= sub_info
['ext']
618 if sub_ext
== 'json':
619 self
.report_warning('JSON subtitles cannot be embedded')
620 elif ext
!= 'webm' or ext
== 'webm' and sub_ext
== 'vtt':
621 sub_langs
.append(lang
)
622 sub_names
.append(sub_info
.get('name'))
623 sub_filenames
.append(sub_info
['filepath'])
625 if not webm_vtt_warn
and ext
== 'webm' and sub_ext
!= 'vtt':
627 self
.report_warning('Only WebVTT subtitles can be embedded in webm files')
628 if not mp4_ass_warn
and ext
== 'mp4' and sub_ext
== 'ass':
630 self
.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues')
635 input_files
= [filename
] + sub_filenames
638 *self
.stream_copy_opts(ext
=info
['ext']),
639 # Don't copy the existing subtitles, we may be running the
640 # postprocessor a second time
643 for i
, (lang
, name
) in enumerate(zip(sub_langs
, sub_names
)):
644 opts
.extend(['-map', '%d:0' % (i
+ 1)])
645 lang_code
= ISO639Utils
.short2long(lang
) or lang
646 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
648 opts
.extend(['-metadata:s:s:%d' % i
, 'handler_name=%s' % name
,
649 '-metadata:s:s:%d' % i
, 'title=%s' % name
])
651 temp_filename
= prepend_extension(filename
, 'temp')
652 self
.to_screen('Embedding subtitles in "%s"' % filename
)
653 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
654 os
.replace(temp_filename
, filename
)
656 files_to_delete
= [] if self
._already
_have
_subtitle
else sub_filenames
657 return files_to_delete
, info
660 class FFmpegMetadataPP(FFmpegPostProcessor
):
662 def __init__(self
, downloader
, add_metadata
=True, add_chapters
=True, add_infojson
='if_exists'):
663 FFmpegPostProcessor
.__init
__(self
, downloader
)
664 self
._add
_metadata
= add_metadata
665 self
._add
_chapters
= add_chapters
666 self
._add
_infojson
= add_infojson
669 def _options(target_ext
):
670 audio_only
= target_ext
== 'm4a'
671 yield from FFmpegPostProcessor
.stream_copy_opts(not audio_only
)
673 yield from ('-vn', '-acodec', 'copy')
675 @PostProcessor._restrict_to(images
=False)
677 filename
, metadata_filename
= info
['filepath'], None
678 files_to_delete
, options
= [], []
679 if self
._add
_chapters
and info
.get('chapters'):
680 metadata_filename
= replace_extension(filename
, 'meta')
681 options
.extend(self
._get
_chapter
_opts
(info
['chapters'], metadata_filename
))
682 files_to_delete
.append(metadata_filename
)
683 if self
._add
_metadata
:
684 options
.extend(self
._get
_metadata
_opts
(info
))
686 if self
._add
_infojson
:
687 if info
['ext'] in ('mkv', 'mka'):
688 infojson_filename
= info
.get('infojson_filename')
689 options
.extend(self
._get
_infojson
_opts
(info
, infojson_filename
))
690 if not infojson_filename
:
691 files_to_delete
.append(info
.get('infojson_filename'))
692 elif self
._add
_infojson
is True:
693 self
.to_screen('The info-json can only be attached to mkv/mka files')
696 self
.to_screen('There isn\'t any metadata to add')
699 temp_filename
= prepend_extension(filename
, 'temp')
700 self
.to_screen('Adding metadata to "%s"' % filename
)
701 self
.run_ffmpeg_multiple_files(
702 (filename
, metadata_filename
), temp_filename
,
703 itertools
.chain(self
._options
(info
['ext']), *options
))
704 self
._delete
_downloaded
_files
(*files_to_delete
)
705 os
.replace(temp_filename
, filename
)
709 def _get_chapter_opts(chapters
, metadata_filename
):
710 with open(metadata_filename
, 'wt', encoding
='utf-8') as f
:
711 def ffmpeg_escape(text
):
712 return re
.sub(r
'([\\=;#\n])', r
'\\\1', text
)
714 metadata_file_content
= ';FFMETADATA1\n'
715 for chapter
in chapters
:
716 metadata_file_content
+= '[CHAPTER]\nTIMEBASE=1/1000\n'
717 metadata_file_content
+= 'START=%d\n' % (chapter
['start_time'] * 1000)
718 metadata_file_content
+= 'END=%d\n' % (chapter
['end_time'] * 1000)
719 chapter_title
= chapter
.get('title')
721 metadata_file_content
+= 'title=%s\n' % ffmpeg_escape(chapter_title
)
722 f
.write(metadata_file_content
)
723 yield ('-map_metadata', '1')
725 def _get_metadata_opts(self
, info
):
727 metadata
= collections
.defaultdict(dict)
729 def add(meta_list
, info_list
=None):
731 str(info
[key
]) for key
in [f
'{meta_prefix}_'] + list(variadic(info_list
or meta_list
))
732 if info
.get(key
) is not None), None)
733 if value
not in ('', None):
734 value
= value
.replace('\0', '') # nul character cannot be passed in command line
735 metadata
['common'].update({meta_f: value for meta_f in variadic(meta_list)}
)
737 # See [1-4] for some info on media metadata/metadata supported
739 # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
740 # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
741 # 3. https://kodi.wiki/view/Video_file_tagging
743 add('title', ('track', 'title'))
744 add('date', 'upload_date')
745 add(('description', 'synopsis'), 'description')
746 add(('purl', 'comment'), 'webpage_url')
747 add('track', 'track_number')
748 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
752 add('disc', 'disc_number')
753 add('show', 'series')
755 add('episode_id', ('episode', 'episode_id'))
756 add('episode_sort', 'episode_number')
757 if 'embed-metadata' in self
.get_param('compat_opts', []):
758 add('comment', 'description')
759 metadata
['common'].pop('synopsis', None)
761 meta_regex
= rf
'{re.escape(meta_prefix)}(?P<i>\d+)?_(?P<key>.+)'
762 for key
, value
in info
.items():
763 mobj
= re
.fullmatch(meta_regex
, key
)
764 if value
is not None and mobj
:
765 metadata
[mobj
.group('i') or 'common'][mobj
.group('key')] = value
767 # Write id3v1 metadata also since Windows Explorer can't handle id3v2 tags
768 yield ('-write_id3v1', '1')
770 for name
, value
in metadata
['common'].items():
771 yield ('-metadata', f
'{name}={value}')
774 for fmt
in info
.get('requested_formats') or []:
775 stream_count
= 2 if 'none' not in (fmt
.get('vcodec'), fmt
.get('acodec')) else 1
776 lang
= ISO639Utils
.short2long(fmt
.get('language') or '') or fmt
.get('language')
777 for i
in range(stream_idx
, stream_idx
+ stream_count
):
779 metadata
[str(i
)].setdefault('language', lang
)
780 for name
, value
in metadata
[str(i
)].items():
781 yield (f
'-metadata:s:{i}', f
'{name}={value}')
782 stream_idx
+= stream_count
784 def _get_infojson_opts(self
, info
, infofn
):
785 if not infofn
or not os
.path
.exists(infofn
):
786 if self
._add
_infojson
is not True:
788 infofn
= infofn
or '%s.temp' % (
789 self
._downloader
.prepare_filename(info
, 'infojson')
790 or replace_extension(self
._downloader
.prepare_filename(info
), 'info.json', info
['ext']))
791 if not self
._downloader
._ensure
_dir
_exists
(infofn
):
793 self
.write_debug(f
'Writing info-json to: {infofn}')
794 write_json_file(self
._downloader
.sanitize_info(info
, self
.get_param('clean_infojson', True)), infofn
)
795 info
['infojson_filename'] = infofn
797 old_stream
, new_stream
= self
.get_stream_number(info
['filepath'], ('tags', 'mimetype'), 'application/json')
798 if old_stream
is not None:
799 yield ('-map', '-0:%d' % old_stream
)
804 f
'-metadata:s:{new_stream}', 'mimetype=application/json',
805 f
'-metadata:s:{new_stream}', 'filename=info.json',
809 class FFmpegMergerPP(FFmpegPostProcessor
):
810 @PostProcessor._restrict_to(images
=False)
812 filename
= info
['filepath']
813 temp_filename
= prepend_extension(filename
, 'temp')
814 args
= ['-c', 'copy']
816 for (i
, fmt
) in enumerate(info
['requested_formats']):
817 if fmt
.get('acodec') != 'none':
818 args
.extend(['-map', f
'{i}:a:0'])
819 aac_fixup
= fmt
['protocol'].startswith('m3u8') and self
.get_audio_codec(fmt
['filepath']) == 'aac'
821 args
.extend([f
'-bsf:a:{audio_streams}', 'aac_adtstoasc'])
823 if fmt
.get('vcodec') != 'none':
824 args
.extend(['-map', '%u:v:0' % (i
)])
825 self
.to_screen('Merging formats into "%s"' % filename
)
826 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
827 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
828 return info
['__files_to_merge'], info
831 # TODO: figure out merge-capable ffmpeg version
832 if self
.basename
!= 'avconv':
835 required_version
= '10-0'
836 if is_outdated_version(
837 self
._versions
[self
.basename
], required_version
):
838 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
839 'yt-dlp will download single file media. '
840 'Update %s to version %s or newer to fix this.') % (
841 self
.basename
, self
.basename
, required_version
)
842 self
.report_warning(warning
)
847 class FFmpegFixupPostProcessor(FFmpegPostProcessor
):
848 def _fixup(self
, msg
, filename
, options
):
849 temp_filename
= prepend_extension(filename
, 'temp')
851 self
.to_screen(f
'{msg} of "{filename}"')
852 self
.run_ffmpeg(filename
, temp_filename
, options
)
854 os
.replace(temp_filename
, filename
)
857 class FFmpegFixupStretchedPP(FFmpegFixupPostProcessor
):
858 @PostProcessor._restrict_to(images
=False, audio
=False)
860 stretched_ratio
= info
.get('stretched_ratio')
861 if stretched_ratio
not in (None, 1):
862 self
._fixup
('Fixing aspect ratio', info
['filepath'], [
863 *self
.stream_copy_opts(), '-aspect', '%f' % stretched_ratio
])
867 class FFmpegFixupM4aPP(FFmpegFixupPostProcessor
):
868 @PostProcessor._restrict_to(images
=False, video
=False)
870 if info
.get('container') == 'm4a_dash':
871 self
._fixup
('Correcting container', info
['filepath'], [*self
.stream_copy_opts(), '-f', 'mp4'])
875 class FFmpegFixupM3u8PP(FFmpegFixupPostProcessor
):
876 def _needs_fixup(self
, info
):
877 yield info
['ext'] in ('mp4', 'm4a')
878 yield info
['protocol'].startswith('m3u8')
880 metadata
= self
.get_metadata_object(info
['filepath'])
881 except PostProcessingError
as e
:
882 self
.report_warning(f
'Unable to extract metadata: {e.msg}')
885 yield traverse_obj(metadata
, ('format', 'format_name'), casesense
=False) == 'mpegts'
887 @PostProcessor._restrict_to(images
=False)
889 if all(self
._needs
_fixup
(info
)):
890 self
._fixup
('Fixing MPEG-TS in MP4 container', info
['filepath'], [
891 *self
.stream_copy_opts(), '-f', 'mp4', '-bsf:a', 'aac_adtstoasc'])
895 class FFmpegFixupTimestampPP(FFmpegFixupPostProcessor
):
897 def __init__(self
, downloader
=None, trim
=0.001):
898 # "trim" should be used when the video contains unintended packets
899 super().__init
__(downloader
)
900 assert isinstance(trim
, (int, float))
901 self
.trim
= str(trim
)
903 @PostProcessor._restrict_to(images
=False)
905 if not self
._features
.get('setts'):
907 'A re-encode is needed to fix timestamps in older versions of ffmpeg. '
908 'Please install ffmpeg 4.4 or later to fixup without re-encoding')
909 opts
= ['-vf', 'setpts=PTS-STARTPTS']
911 opts
= ['-c', 'copy', '-bsf', 'setts=ts=TS-STARTPTS']
912 self
._fixup
('Fixing frame timestamp', info
['filepath'], opts
+ [*self
.stream_copy_opts(False), '-ss', self
.trim
])
916 class FFmpegCopyStreamPP(FFmpegFixupPostProcessor
):
917 MESSAGE
= 'Copying stream'
919 @PostProcessor._restrict_to(images
=False)
921 self
._fixup
(self
.MESSAGE
, info
['filepath'], self
.stream_copy_opts())
925 class FFmpegFixupDurationPP(FFmpegCopyStreamPP
):
926 MESSAGE
= 'Fixing video duration'
929 class FFmpegFixupDuplicateMoovPP(FFmpegCopyStreamPP
):
930 MESSAGE
= 'Fixing duplicate MOOV atoms'
933 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
934 SUPPORTED_EXTS
= ('srt', 'vtt', 'ass', 'lrc')
936 def __init__(self
, downloader
=None, format
=None):
937 super().__init
__(downloader
)
941 subs
= info
.get('requested_subtitles')
942 new_ext
= self
.format
944 if new_format
== 'vtt':
945 new_format
= 'webvtt'
947 self
.to_screen('There aren\'t any subtitles to convert')
949 self
.to_screen('Converting subtitles')
951 for lang
, sub
in subs
.items():
952 if not os
.path
.exists(sub
.get('filepath', '')):
953 self
.report_warning(f
'Skipping embedding {lang} subtitle because the file is missing')
957 self
.to_screen('Subtitle file for %s is already in the requested format' % new_ext
)
961 'You have requested to convert json subtitles into another format, '
962 'which is currently not possible')
964 old_file
= sub
['filepath']
965 sub_filenames
.append(old_file
)
966 new_file
= replace_extension(old_file
, new_ext
)
968 if ext
in ('dfxp', 'ttml', 'tt'):
970 'You have requested to convert dfxp (TTML) subtitles into another format, '
971 'which results in style information loss')
974 srt_file
= replace_extension(old_file
, 'srt')
976 with open(dfxp_file
, 'rb') as f
:
977 srt_data
= dfxp2srt(f
.read())
979 with open(srt_file
, 'wt', encoding
='utf-8') as f
:
986 'filepath': srt_file
,
992 sub_filenames
.append(srt_file
)
994 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
996 with open(new_file
, encoding
='utf-8') as f
:
1000 'filepath': new_file
,
1003 info
['__files_to_move'][new_file
] = replace_extension(
1004 info
['__files_to_move'][sub
['filepath']], new_ext
)
1006 return sub_filenames
, info
1009 class FFmpegSplitChaptersPP(FFmpegPostProcessor
):
1010 def __init__(self
, downloader
, force_keyframes
=False):
1011 FFmpegPostProcessor
.__init
__(self
, downloader
)
1012 self
._force
_keyframes
= force_keyframes
1014 def _prepare_filename(self
, number
, chapter
, info
):
1017 'section_number': number
,
1018 'section_title': chapter
.get('title'),
1019 'section_start': chapter
.get('start_time'),
1020 'section_end': chapter
.get('end_time'),
1022 return self
._downloader
.prepare_filename(info
, 'chapter')
1024 def _ffmpeg_args_for_chapter(self
, number
, chapter
, info
):
1025 destination
= self
._prepare
_filename
(number
, chapter
, info
)
1026 if not self
._downloader
._ensure
_dir
_exists
(encodeFilename(destination
)):
1029 chapter
['filepath'] = destination
1030 self
.to_screen('Chapter %03d; Destination: %s' % (number
, destination
))
1033 ['-ss', compat_str(chapter
['start_time']),
1034 '-t', compat_str(chapter
['end_time'] - chapter
['start_time'])])
1036 @PostProcessor._restrict_to(images
=False)
1037 def run(self
, info
):
1038 chapters
= info
.get('chapters') or []
1040 self
.to_screen('Chapter information is unavailable')
1043 in_file
= info
['filepath']
1044 if self
._force
_keyframes
and len(chapters
) > 1:
1045 in_file
= self
.force_keyframes(in_file
, (c
['start_time'] for c
in chapters
))
1046 self
.to_screen('Splitting video by chapters; %d chapters found' % len(chapters
))
1047 for idx
, chapter
in enumerate(chapters
):
1048 destination
, opts
= self
._ffmpeg
_args
_for
_chapter
(idx
+ 1, chapter
, info
)
1049 self
.real_run_ffmpeg([(in_file
, opts
)], [(destination
, self
.stream_copy_opts())])
1050 if in_file
!= info
['filepath']:
1051 self
._delete
_downloaded
_files
(in_file
, msg
=None)
1055 class FFmpegThumbnailsConvertorPP(FFmpegPostProcessor
):
1056 SUPPORTED_EXTS
= ('jpg', 'png', 'webp')
1058 def __init__(self
, downloader
=None, format
=None):
1059 super().__init
__(downloader
)
1060 self
.format
= format
1064 with open(encodeFilename(path
), 'rb') as f
:
1066 return b
[0:4] == b
'RIFF' and b
[8:] == b
'WEBP'
1068 def fixup_webp(self
, info
, idx
=-1):
1069 thumbnail_filename
= info
['thumbnails'][idx
]['filepath']
1070 _
, thumbnail_ext
= os
.path
.splitext(thumbnail_filename
)
1072 thumbnail_ext
= thumbnail_ext
[1:].lower()
1073 if thumbnail_ext
!= 'webp' and self
.is_webp(thumbnail_filename
):
1074 self
.to_screen('Correcting thumbnail "%s" extension to webp' % thumbnail_filename
)
1075 webp_filename
= replace_extension(thumbnail_filename
, 'webp')
1076 os
.replace(thumbnail_filename
, webp_filename
)
1077 info
['thumbnails'][idx
]['filepath'] = webp_filename
1078 info
['__files_to_move'][webp_filename
] = replace_extension(
1079 info
['__files_to_move'].pop(thumbnail_filename
), 'webp')
1082 def _options(target_ext
):
1083 if target_ext
== 'jpg':
1084 return ['-bsf:v', 'mjpeg2jpeg']
1087 def convert_thumbnail(self
, thumbnail_filename
, target_ext
):
1088 thumbnail_conv_filename
= replace_extension(thumbnail_filename
, target_ext
)
1090 self
.to_screen(f
'Converting thumbnail "{thumbnail_filename}" to {target_ext}')
1091 self
.real_run_ffmpeg(
1092 [(thumbnail_filename
, ['-f', 'image2', '-pattern_type', 'none'])],
1093 [(thumbnail_conv_filename
.replace('%', '%%'), self
._options
(target_ext
))])
1094 return thumbnail_conv_filename
1096 def run(self
, info
):
1097 files_to_delete
= []
1098 has_thumbnail
= False
1100 for idx
, thumbnail_dict
in enumerate(info
.get('thumbnails') or []):
1101 original_thumbnail
= thumbnail_dict
.get('filepath')
1102 if not original_thumbnail
:
1104 has_thumbnail
= True
1105 self
.fixup_webp(info
, idx
)
1106 _
, thumbnail_ext
= os
.path
.splitext(original_thumbnail
)
1108 thumbnail_ext
= thumbnail_ext
[1:].lower()
1109 if thumbnail_ext
== 'jpeg':
1110 thumbnail_ext
= 'jpg'
1111 if thumbnail_ext
== self
.format
:
1112 self
.to_screen('Thumbnail "%s" is already in the requested format' % original_thumbnail
)
1114 thumbnail_dict
['filepath'] = self
.convert_thumbnail(original_thumbnail
, self
.format
)
1115 files_to_delete
.append(original_thumbnail
)
1116 info
['__files_to_move'][thumbnail_dict
['filepath']] = replace_extension(
1117 info
['__files_to_move'][original_thumbnail
], self
.format
)
1119 if not has_thumbnail
:
1120 self
.to_screen('There aren\'t any thumbnails to convert')
1121 return files_to_delete
, info
1124 class FFmpegConcatPP(FFmpegPostProcessor
):
1125 def __init__(self
, downloader
, only_multi_video
=False):
1126 self
._only
_multi
_video
= only_multi_video
1127 super().__init
__(downloader
)
1129 def _get_codecs(self
, file):
1130 codecs
= traverse_obj(self
.get_metadata_object(file), ('streams', ..., 'codec_name'))
1131 self
.write_debug(f
'Codecs = {", ".join(codecs)}')
1132 return tuple(codecs
)
1134 def concat_files(self
, in_files
, out_file
):
1135 if not self
._downloader
._ensure
_dir
_exists
(out_file
):
1137 if len(in_files
) == 1:
1138 if os
.path
.realpath(in_files
[0]) != os
.path
.realpath(out_file
):
1139 self
.to_screen(f
'Moving "{in_files[0]}" to "{out_file}"')
1140 os
.replace(in_files
[0], out_file
)
1143 if len(set(map(self
._get
_codecs
, in_files
))) > 1:
1144 raise PostProcessingError(
1145 'The files have different streams/codecs and cannot be concatenated. '
1146 'Either select different formats or --recode-video them to a common format')
1148 self
.to_screen(f
'Concatenating {len(in_files)} files; Destination: {out_file}')
1149 super().concat_files(in_files
, out_file
)
1152 @PostProcessor._restrict_to(images
=False, simulated
=False)
1153 def run(self
, info
):
1154 entries
= info
.get('entries') or []
1155 if not any(entries
) or (self
._only
_multi
_video
and info
['_type'] != 'multi_video'):
1157 elif traverse_obj(entries
, (..., lambda k
, v
: k
== 'requested_downloads' and len(v
) > 1)):
1158 raise PostProcessingError('Concatenation is not supported when downloading multiple separate formats')
1160 in_files
= traverse_obj(entries
, (..., 'requested_downloads', 0, 'filepath')) or []
1161 if len(in_files
) < len(entries
):
1162 raise PostProcessingError('Aborting concatenation because some downloads failed')
1164 ie_copy
= self
._downloader
._playlist
_infodict
(info
)
1165 exts
= traverse_obj(entries
, (..., 'requested_downloads', 0, 'ext'), (..., 'ext'))
1166 ie_copy
['ext'] = exts
[0] if len(set(exts
)) == 1 else 'mkv'
1167 out_file
= self
._downloader
.prepare_filename(ie_copy
, 'pl_video')
1169 files_to_delete
= self
.concat_files(in_files
, out_file
)
1171 info
['requested_downloads'] = [{
1172 'filepath': out_file
,
1173 'ext': ie_copy
['ext'],
1175 return files_to_delete
, info