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_version_and_features(downloader
)[0]
91 def _determine_executables(self
):
92 programs
= ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
94 def get_ffmpeg_version(path
, prog
):
95 out
= _get_exe_version_output(path
, ['-bsfs'])
96 ver
= detect_exe_version(out
) if out
else False
99 r
'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1]
100 r
'n([0-9.]+)$', # Arch Linux
101 # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/
104 mobj
= re
.match(regex
, ver
)
107 self
._versions
[prog
] = ver
108 if prog
!= 'ffmpeg' or not out
:
111 mobj
= re
.search(r
'(?m)^\s+libavformat\s+(?:[0-9. ]+)\s+/\s+(?P<runtime>[0-9. ]+)', out
)
112 lavf_runtime_version
= mobj
.group('runtime').replace(' ', '') if mobj
else None
114 'fdk': '--enable-libfdk-aac' in out
,
115 'setts': 'setts' in out
.splitlines(),
116 'needs_adtstoasc': is_outdated_version(lavf_runtime_version
, '57.56.100', False),
120 self
.probe_basename
= None
122 self
._versions
= None
125 prefer_ffmpeg
= self
.get_param('prefer_ffmpeg', True)
126 location
= self
.get_param('ffmpeg_location')
128 self
._paths
= {p: p for p in programs}
130 if not os
.path
.exists(location
):
132 'ffmpeg-location %s does not exist! '
133 'Continuing without ffmpeg.' % (location
))
136 elif os
.path
.isdir(location
):
137 dirname
, basename
= location
, None
139 basename
= os
.path
.splitext(os
.path
.basename(location
))[0]
140 basename
= next((p
for p
in programs
if basename
.startswith(p
)), 'ffmpeg')
141 dirname
= os
.path
.dirname(os
.path
.abspath(location
))
142 if basename
in ('ffmpeg', 'ffprobe'):
146 (p
, os
.path
.join(dirname
, p
)) for p
in programs
)
148 self
._paths
[basename
] = location
152 get_ffmpeg_version(self
._paths
[p
], p
)
154 if prefer_ffmpeg
is False:
155 prefs
= ('avconv', 'ffmpeg')
157 prefs
= ('ffmpeg', 'avconv')
159 if self
._versions
[p
]:
163 if prefer_ffmpeg
is False:
164 prefs
= ('avprobe', 'ffprobe')
166 prefs
= ('ffprobe', 'avprobe')
168 if self
._versions
[p
]:
169 self
.probe_basename
= p
172 if self
.basename
== 'avconv':
173 self
.deprecation_warning(
174 'Support for avconv is deprecated and may be removed in a future version. Use ffmpeg instead')
175 if self
.probe_basename
== 'avprobe':
176 self
.deprecation_warning(
177 'Support for avprobe is deprecated and may be removed in a future version. Use ffprobe instead')
181 return self
.basename
is not None
184 def executable(self
):
185 return self
._paths
[self
.basename
]
188 def probe_available(self
):
189 return self
.probe_basename
is not None
192 def probe_executable(self
):
193 return self
._paths
[self
.probe_basename
]
196 def stream_copy_opts(copy
=True, *, ext
=None):
197 yield from ('-map', '0')
198 # Don't copy Apple TV chapters track, bin_data
199 # See https://github.com/yt-dlp/yt-dlp/issues/2, #19042, #19024, https://trac.ffmpeg.org/ticket/6016
200 yield from ('-dn', '-ignore_unknown')
202 yield from ('-c', 'copy')
203 # For some reason, '-c copy -map 0' is not enough to copy subtitles
204 if ext
in ('mp4', 'mov'):
205 yield from ('-c:s', 'mov_text')
207 def get_audio_codec(self
, path
):
208 if not self
.probe_available
and not self
.available
:
209 raise PostProcessingError('ffprobe and ffmpeg not found. Please install or provide the path using --ffmpeg-location')
211 if self
.probe_available
:
213 encodeFilename(self
.probe_executable
, True),
214 encodeArgument('-show_streams')]
217 encodeFilename(self
.executable
, True),
218 encodeArgument('-i')]
219 cmd
.append(encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True))
220 self
.write_debug('%s command line: %s' % (self
.basename
, shell_quote(cmd
)))
221 handle
= Popen(cmd
, stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
222 stdout_data
, stderr_data
= handle
.communicate_or_kill()
223 expected_ret
= 0 if self
.probe_available
else 1
224 if handle
.wait() != expected_ret
:
226 except (IOError, OSError):
228 output
= (stdout_data
if self
.probe_available
else stderr_data
).decode('ascii', 'ignore')
229 if self
.probe_available
:
231 for line
in output
.split('\n'):
232 if line
.startswith('codec_name='):
233 audio_codec
= line
.split('=')[1].strip()
234 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
237 # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME
239 r
'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)',
245 def get_metadata_object(self
, path
, opts
=[]):
246 if self
.probe_basename
!= 'ffprobe':
247 if self
.probe_available
:
248 self
.report_warning('Only ffprobe is supported for metadata extraction')
249 raise PostProcessingError('ffprobe not found. Please install or provide the path using --ffmpeg-location')
253 encodeFilename(self
.probe_executable
, True),
254 encodeArgument('-hide_banner'),
255 encodeArgument('-show_format'),
256 encodeArgument('-show_streams'),
257 encodeArgument('-print_format'),
258 encodeArgument('json'),
262 cmd
.append(encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True))
263 self
.write_debug('ffprobe command line: %s' % shell_quote(cmd
))
264 p
= Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
265 stdout
, stderr
= p
.communicate()
266 return json
.loads(stdout
.decode('utf-8', 'replace'))
268 def get_stream_number(self
, path
, keys
, value
):
269 streams
= self
.get_metadata_object(path
)['streams']
271 (i
for i
, stream
in enumerate(streams
) if traverse_obj(stream
, keys
, casesense
=False) == value
),
273 return num
, len(streams
)
275 def _get_real_video_duration(self
, filepath
, fatal
=True):
277 duration
= float_or_none(
278 traverse_obj(self
.get_metadata_object(filepath
), ('format', 'duration')))
280 raise PostProcessingError('ffprobe returned empty duration')
282 except PostProcessingError
as e
:
284 raise PostProcessingError(f
'Unable to determine video duration: {e.msg}')
286 def _duration_mismatch(self
, d1
, d2
):
289 # The duration is often only known to nearest second. So there can be <1sec disparity natually.
290 # Further excuse an additional <1sec difference.
291 return abs(d1
- d2
) > 2
293 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
, **kwargs
):
294 return self
.real_run_ffmpeg(
295 [(path
, []) for path
in input_paths
],
296 [(out_path
, opts
)], **kwargs
)
298 def real_run_ffmpeg(self
, input_path_opts
, output_path_opts
, *, expected_retcodes
=(0,)):
302 os
.stat(encodeFilename(path
)).st_mtime
for path
, _
in input_path_opts
if path
)
304 cmd
= [encodeFilename(self
.executable
, True), encodeArgument('-y')]
305 # avconv does not have repeat option
306 if self
.basename
== 'ffmpeg':
307 cmd
+= [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
309 def make_args(file, args
, name
, number
):
310 keys
= ['_%s%d' % (name
, number
), '_%s' % name
]
312 args
+= ['-movflags', '+faststart']
315 args
+= self
._configuration
_args
(self
.basename
, keys
)
319 [encodeArgument(arg
) for arg
in args
]
320 + [encodeFilename(self
._ffmpeg
_filename
_argument
(file), True)])
322 for arg_type
, path_opts
in (('i', input_path_opts
), ('o', output_path_opts
)):
323 cmd
+= itertools
.chain
.from_iterable(
324 make_args(path
, list(opts
), arg_type
, i
+ 1)
325 for i
, (path
, opts
) in enumerate(path_opts
) if path
)
327 self
.write_debug('ffmpeg command line: %s' % shell_quote(cmd
))
328 p
= Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
329 stdout
, stderr
= p
.communicate_or_kill()
330 if p
.returncode
not in variadic(expected_retcodes
):
331 stderr
= stderr
.decode('utf-8', 'replace').strip()
332 self
.write_debug(stderr
)
333 raise FFmpegPostProcessorError(stderr
.split('\n')[-1])
334 for out_path
, _
in output_path_opts
:
336 self
.try_utime(out_path
, oldest_mtime
, oldest_mtime
)
337 return stderr
.decode('utf-8', 'replace')
339 def run_ffmpeg(self
, path
, out_path
, opts
, **kwargs
):
340 return self
.run_ffmpeg_multiple_files([path
], out_path
, opts
, **kwargs
)
343 def _ffmpeg_filename_argument(fn
):
344 # Always use 'file:' because the filename may contain ':' (ffmpeg
345 # interprets that as a protocol) or can start with '-' (-- is broken in
346 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
347 # Also leave '-' intact in order not to break streaming to stdout.
348 if fn
.startswith(('http://', 'https://')):
350 return 'file:' + fn
if fn
!= '-' else fn
353 def _quote_for_ffmpeg(string
):
354 # See https://ffmpeg.org/ffmpeg-utils.html#toc-Quoting-and-escaping
355 # A sequence of '' produces '\'''\'';
356 # final replace removes the empty '' between \' \'.
357 string
= string
.replace("'", r
"'\''").replace("'''", "'")
358 # Handle potential ' at string boundaries.
359 string
= string
[1:] if string
[0] == "'" else "'" + string
360 return string
[:-1] if string
[-1] == "'" else string
+ "'"
362 def force_keyframes(self
, filename
, timestamps
):
363 timestamps
= orderedSet(timestamps
)
364 if timestamps
[0] == 0:
365 timestamps
= timestamps
[1:]
366 keyframe_file
= prepend_extension(filename
, 'keyframes.temp')
367 self
.to_screen(f
'Re-encoding "{filename}" with appropriate keyframes')
368 self
.run_ffmpeg(filename
, keyframe_file
, [
369 *self
.stream_copy_opts(False, ext
=determine_ext(filename
)),
370 '-force_key_frames', ','.join(f
'{t:.6f}' for t
in timestamps
)])
373 def concat_files(self
, in_files
, out_file
, concat_opts
=None):
375 Use concat demuxer to concatenate multiple files having identical streams.
377 Only inpoint, outpoint, and duration concat options are supported.
378 See https://ffmpeg.org/ffmpeg-formats.html#concat-1 for details
380 concat_file
= f
'{out_file}.concat'
381 self
.write_debug(f
'Writing concat spec to {concat_file}')
382 with open(concat_file
, 'wt', encoding
='utf-8') as f
:
383 f
.writelines(self
._concat
_spec
(in_files
, concat_opts
))
385 out_flags
= list(self
.stream_copy_opts(ext
=determine_ext(out_file
)))
387 self
.real_run_ffmpeg(
388 [(concat_file
, ['-hide_banner', '-nostdin', '-f', 'concat', '-safe', '0'])],
389 [(out_file
, out_flags
)])
390 os
.remove(concat_file
)
393 def _concat_spec(cls
, in_files
, concat_opts
=None):
394 if concat_opts
is None:
395 concat_opts
= [{}] * len(in_files
)
396 yield 'ffconcat version 1.0\n'
397 for file, opts
in zip(in_files
, concat_opts
):
398 yield f
'file {cls._quote_for_ffmpeg(cls._ffmpeg_filename_argument(file))}\n'
399 # Iterate explicitly to yield the following directives in order, ignoring the rest.
400 for directive
in 'inpoint', 'outpoint', 'duration':
401 if directive
in opts
:
402 yield f
'{directive} {opts[directive]}\n'
405 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
406 COMMON_AUDIO_EXTS
= ('wav', 'flac', 'm4a', 'aiff', 'mp3', 'ogg', 'mka', 'opus', 'wma')
407 SUPPORTED_EXTS
= ('aac', 'flac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav', 'alac')
409 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
410 FFmpegPostProcessor
.__init
__(self
, downloader
)
411 self
._preferredcodec
= preferredcodec
or 'best'
412 self
._preferredquality
= float_or_none(preferredquality
)
413 self
._nopostoverwrites
= nopostoverwrites
415 def _quality_args(self
, codec
):
416 if self
._preferredquality
is None:
418 elif self
._preferredquality
> 10:
419 return ['-b:a', f
'{self._preferredquality}k']
422 'libmp3lame': (10, 0),
423 'libvorbis': (0, 10),
424 # FFmpeg's AAC encoder does not have an upper limit for the value of -q:a.
425 # Experimentally, with values over 4, bitrate changes were minimal or non-existent
427 'libfdk_aac': (1, 5),
432 q
= limits
[1] + (limits
[0] - limits
[1]) * (self
._preferredquality
/ 10)
433 if codec
== 'libfdk_aac':
434 return ['-vbr', f
'{int(q)}']
435 return ['-q:a', f
'{q}']
437 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
441 acodec_opts
= ['-acodec', codec
]
442 opts
= ['-vn'] + acodec_opts
+ more_opts
444 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
445 except FFmpegPostProcessorError
as err
:
446 raise AudioConversionError(err
.msg
)
448 @PostProcessor._restrict_to(images
=False)
449 def run(self
, information
):
450 orig_path
= path
= information
['filepath']
451 orig_ext
= information
['ext']
453 if self
._preferredcodec
== 'best' and orig_ext
in self
.COMMON_AUDIO_EXTS
:
454 self
.to_screen('Skipping audio extraction since the file is already in a common audio format')
455 return [], information
457 filecodec
= self
.get_audio_codec(path
)
458 if filecodec
is None:
459 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
462 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
463 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
464 # Lossless, but in another container
467 more_opts
= ['-bsf:a', 'aac_adtstoasc']
468 elif filecodec
in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
469 # Lossless if possible
471 extension
= filecodec
472 if filecodec
== 'aac':
473 more_opts
= ['-f', 'adts']
474 if filecodec
== 'vorbis':
476 elif filecodec
== 'alac':
479 more_opts
+= ['-acodec', 'alac']
482 acodec
= 'libmp3lame'
484 more_opts
= self
._quality
_args
(acodec
)
486 # We convert the audio (lossy if codec is lossy)
487 acodec
= ACODECS
[self
._preferredcodec
]
488 if acodec
== 'aac' and self
._features
.get('fdk'):
489 acodec
= 'libfdk_aac'
490 extension
= self
._preferredcodec
491 more_opts
= self
._quality
_args
(acodec
)
492 if self
._preferredcodec
== 'aac':
493 more_opts
+= ['-f', 'adts']
494 elif self
._preferredcodec
== 'm4a':
495 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
496 elif self
._preferredcodec
== 'vorbis':
498 elif self
._preferredcodec
== 'wav':
500 more_opts
+= ['-f', 'wav']
501 elif self
._preferredcodec
== 'alac':
503 more_opts
+= ['-acodec', 'alac']
505 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
506 temp_path
= new_path
= prefix
+ sep
+ extension
509 orig_path
= prepend_extension(path
, 'orig')
510 temp_path
= prepend_extension(path
, 'temp')
511 if (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
))
512 and os
.path
.exists(encodeFilename(orig_path
))):
513 self
.to_screen('Post-process file %s exists, skipping' % new_path
)
514 return [], information
517 self
.to_screen(f
'Destination: {new_path}')
518 self
.run_ffmpeg(path
, temp_path
, acodec
, more_opts
)
519 except AudioConversionError
as e
:
520 raise PostProcessingError(
521 'audio conversion failed: ' + e
.msg
)
523 raise PostProcessingError('error running ' + self
.basename
)
525 os
.replace(path
, orig_path
)
526 os
.replace(temp_path
, new_path
)
527 information
['filepath'] = new_path
528 information
['ext'] = extension
530 # Try to update the date time for extracted audio file.
531 if information
.get('filetime') is not None:
533 new_path
, time
.time(), information
['filetime'],
534 errnote
='Cannot update utime of audio file')
536 return [orig_path
], information
539 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
540 SUPPORTED_EXTS
= ('mp4', 'mkv', 'flv', 'webm', 'mov', 'avi', 'mka', 'ogg', *FFmpegExtractAudioPP
.SUPPORTED_EXTS
)
541 FORMAT_RE
= re
.compile(r
'{0}(?:/{0})*$'.format(r
'(?:\w+>)?(?:%s)' % '|'.join(SUPPORTED_EXTS
)))
542 _ACTION
= 'converting'
544 def __init__(self
, downloader
=None, preferedformat
=None):
545 super(FFmpegVideoConvertorPP
, self
).__init
__(downloader
)
546 self
._preferedformats
= preferedformat
.lower().split('/')
548 def _target_ext(self
, source_ext
):
549 for pair
in self
._preferedformats
:
551 if len(kv
) == 1 or kv
[0].strip() == source_ext
:
552 return kv
[-1].strip()
555 def _options(target_ext
):
556 if target_ext
== 'avi':
557 return ['-c:v', 'libxvid', '-vtag', 'XVID']
560 @PostProcessor._restrict_to(images
=False)
562 filename
, source_ext
= info
['filepath'], info
['ext'].lower()
563 target_ext
= self
._target
_ext
(source_ext
)
565 f
'could not find a mapping for {source_ext}' if not target_ext
566 else f
'already is in target format {source_ext}' if source_ext
== target_ext
569 self
.to_screen(f
'Not {self._ACTION} media file "{filename}"; {_skip_msg}')
572 outpath
= replace_extension(filename
, target_ext
, source_ext
)
573 self
.to_screen(f
'{self._ACTION.title()} video from {source_ext} to {target_ext}; Destination: {outpath}')
574 self
.run_ffmpeg(filename
, outpath
, self
._options
(target_ext
))
576 info
['filepath'] = outpath
577 info
['format'] = info
['ext'] = target_ext
578 return [filename
], info
581 class FFmpegVideoRemuxerPP(FFmpegVideoConvertorPP
):
585 def _options(target_ext
):
586 return FFmpegPostProcessor
.stream_copy_opts()
589 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
590 def __init__(self
, downloader
=None, already_have_subtitle
=False):
591 super(FFmpegEmbedSubtitlePP
, self
).__init
__(downloader
)
592 self
._already
_have
_subtitle
= already_have_subtitle
594 @PostProcessor._restrict_to(images
=False)
596 if info
['ext'] not in ('mp4', 'webm', 'mkv'):
597 self
.to_screen('Subtitles can only be embedded in mp4, webm or mkv files')
599 subtitles
= info
.get('requested_subtitles')
601 self
.to_screen('There aren\'t any subtitles to embed')
604 filename
= info
['filepath']
606 # Disabled temporarily. There needs to be a way to overide this
607 # in case of duration actually mismatching in extractor
608 # See: https://github.com/yt-dlp/yt-dlp/issues/1870, https://github.com/yt-dlp/yt-dlp/issues/1385
610 if info.get('duration') and not info.get('__real_download') and self._duration_mismatch(
611 self._get_real_video_duration(filename, False), info['duration']):
612 self.to_screen(f'Skipping {self.pp_key()} since the real and expected durations mismatch')
617 sub_langs
, sub_names
, sub_filenames
= [], [], []
618 webm_vtt_warn
= False
621 for lang
, sub_info
in subtitles
.items():
622 if not os
.path
.exists(sub_info
.get('filepath', '')):
623 self
.report_warning(f
'Skipping embedding {lang} subtitle because the file is missing')
625 sub_ext
= sub_info
['ext']
626 if sub_ext
== 'json':
627 self
.report_warning('JSON subtitles cannot be embedded')
628 elif ext
!= 'webm' or ext
== 'webm' and sub_ext
== 'vtt':
629 sub_langs
.append(lang
)
630 sub_names
.append(sub_info
.get('name'))
631 sub_filenames
.append(sub_info
['filepath'])
633 if not webm_vtt_warn
and ext
== 'webm' and sub_ext
!= 'vtt':
635 self
.report_warning('Only WebVTT subtitles can be embedded in webm files')
636 if not mp4_ass_warn
and ext
== 'mp4' and sub_ext
== 'ass':
638 self
.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues')
643 input_files
= [filename
] + sub_filenames
646 *self
.stream_copy_opts(ext
=info
['ext']),
647 # Don't copy the existing subtitles, we may be running the
648 # postprocessor a second time
651 for i
, (lang
, name
) in enumerate(zip(sub_langs
, sub_names
)):
652 opts
.extend(['-map', '%d:0' % (i
+ 1)])
653 lang_code
= ISO639Utils
.short2long(lang
) or lang
654 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
656 opts
.extend(['-metadata:s:s:%d' % i
, 'handler_name=%s' % name
,
657 '-metadata:s:s:%d' % i
, 'title=%s' % name
])
659 temp_filename
= prepend_extension(filename
, 'temp')
660 self
.to_screen('Embedding subtitles in "%s"' % filename
)
661 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
662 os
.replace(temp_filename
, filename
)
664 files_to_delete
= [] if self
._already
_have
_subtitle
else sub_filenames
665 return files_to_delete
, info
668 class FFmpegMetadataPP(FFmpegPostProcessor
):
670 def __init__(self
, downloader
, add_metadata
=True, add_chapters
=True, add_infojson
='if_exists'):
671 FFmpegPostProcessor
.__init
__(self
, downloader
)
672 self
._add
_metadata
= add_metadata
673 self
._add
_chapters
= add_chapters
674 self
._add
_infojson
= add_infojson
677 def _options(target_ext
):
678 audio_only
= target_ext
== 'm4a'
679 yield from FFmpegPostProcessor
.stream_copy_opts(not audio_only
)
681 yield from ('-vn', '-acodec', 'copy')
683 @PostProcessor._restrict_to(images
=False)
685 filename
, metadata_filename
= info
['filepath'], None
686 files_to_delete
, options
= [], []
687 if self
._add
_chapters
and info
.get('chapters'):
688 metadata_filename
= replace_extension(filename
, 'meta')
689 options
.extend(self
._get
_chapter
_opts
(info
['chapters'], metadata_filename
))
690 files_to_delete
.append(metadata_filename
)
691 if self
._add
_metadata
:
692 options
.extend(self
._get
_metadata
_opts
(info
))
694 if self
._add
_infojson
:
695 if info
['ext'] in ('mkv', 'mka'):
696 infojson_filename
= info
.get('infojson_filename')
697 options
.extend(self
._get
_infojson
_opts
(info
, infojson_filename
))
698 if not infojson_filename
:
699 files_to_delete
.append(info
.get('infojson_filename'))
700 elif self
._add
_infojson
is True:
701 self
.to_screen('The info-json can only be attached to mkv/mka files')
704 self
.to_screen('There isn\'t any metadata to add')
707 temp_filename
= prepend_extension(filename
, 'temp')
708 self
.to_screen('Adding metadata to "%s"' % filename
)
709 self
.run_ffmpeg_multiple_files(
710 (filename
, metadata_filename
), temp_filename
,
711 itertools
.chain(self
._options
(info
['ext']), *options
))
712 for file in filter(None, files_to_delete
):
713 os
.remove(file) # Don't obey --keep-files
714 os
.replace(temp_filename
, filename
)
718 def _get_chapter_opts(chapters
, metadata_filename
):
719 with io
.open(metadata_filename
, 'wt', encoding
='utf-8') as f
:
720 def ffmpeg_escape(text
):
721 return re
.sub(r
'([\\=;#\n])', r
'\\\1', text
)
723 metadata_file_content
= ';FFMETADATA1\n'
724 for chapter
in chapters
:
725 metadata_file_content
+= '[CHAPTER]\nTIMEBASE=1/1000\n'
726 metadata_file_content
+= 'START=%d\n' % (chapter
['start_time'] * 1000)
727 metadata_file_content
+= 'END=%d\n' % (chapter
['end_time'] * 1000)
728 chapter_title
= chapter
.get('title')
730 metadata_file_content
+= 'title=%s\n' % ffmpeg_escape(chapter_title
)
731 f
.write(metadata_file_content
)
732 yield ('-map_metadata', '1')
734 def _get_metadata_opts(self
, info
):
736 metadata
= collections
.defaultdict(dict)
738 def add(meta_list
, info_list
=None):
740 str(info
[key
]) for key
in [f
'{meta_prefix}_'] + list(variadic(info_list
or meta_list
))
741 if info
.get(key
) is not None), None)
742 if value
not in ('', None):
743 metadata
['common'].update({meta_f: value for meta_f in variadic(meta_list)}
)
745 # See [1-4] for some info on media metadata/metadata supported
747 # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
748 # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
749 # 3. https://kodi.wiki/view/Video_file_tagging
751 add('title', ('track', 'title'))
752 add('date', 'upload_date')
753 add(('description', 'synopsis'), 'description')
754 add(('purl', 'comment'), 'webpage_url')
755 add('track', 'track_number')
756 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
760 add('disc', 'disc_number')
761 add('show', 'series')
763 add('episode_id', ('episode', 'episode_id'))
764 add('episode_sort', 'episode_number')
765 if 'embed-metadata' in self
.get_param('compat_opts', []):
766 add('comment', 'description')
767 metadata
['common'].pop('synopsis', None)
769 meta_regex
= rf
'{re.escape(meta_prefix)}(?P<i>\d+)?_(?P<key>.+)'
770 for key
, value
in info
.items():
771 mobj
= re
.fullmatch(meta_regex
, key
)
772 if value
is not None and mobj
:
773 metadata
[mobj
.group('i') or 'common'][mobj
.group('key')] = value
775 for name
, value
in metadata
['common'].items():
776 yield ('-metadata', f
'{name}={value}')
779 for fmt
in info
.get('requested_formats') or []:
780 stream_count
= 2 if 'none' not in (fmt
.get('vcodec'), fmt
.get('acodec')) else 1
781 lang
= ISO639Utils
.short2long(fmt
.get('language') or '') or fmt
.get('language')
782 for i
in range(stream_idx
, stream_idx
+ stream_count
):
784 metadata
[str(i
)].setdefault('language', lang
)
785 for name
, value
in metadata
[str(i
)].items():
786 yield (f
'-metadata:s:{i}', f
'{name}={value}')
787 stream_idx
+= stream_count
789 def _get_infojson_opts(self
, info
, infofn
):
790 if not infofn
or not os
.path
.exists(infofn
):
791 if self
._add
_infojson
is not True:
793 infofn
= infofn
or '%s.temp' % (
794 self
._downloader
.prepare_filename(info
, 'infojson')
795 or replace_extension(self
._downloader
.prepare_filename(info
), 'info.json', info
['ext']))
796 if not self
._downloader
._ensure
_dir
_exists
(infofn
):
798 self
.write_debug(f
'Writing info-json to: {infofn}')
799 write_json_file(self
._downloader
.sanitize_info(info
, self
.get_param('clean_infojson', True)), infofn
)
800 info
['infojson_filename'] = infofn
802 old_stream
, new_stream
= self
.get_stream_number(info
['filepath'], ('tags', 'mimetype'), 'application/json')
803 if old_stream
is not None:
804 yield ('-map', '-0:%d' % old_stream
)
807 yield ('-attach', infofn
,
808 '-metadata:s:%d' % new_stream
, 'mimetype=application/json')
811 class FFmpegMergerPP(FFmpegPostProcessor
):
812 @PostProcessor._restrict_to(images
=False)
814 filename
= info
['filepath']
815 temp_filename
= prepend_extension(filename
, 'temp')
816 args
= ['-c', 'copy']
818 for (i
, fmt
) in enumerate(info
['requested_formats']):
819 if fmt
.get('acodec') != 'none':
820 args
.extend(['-map', f
'{i}:a:0'])
821 aac_fixup
= fmt
['protocol'].startswith('m3u8') and self
.get_audio_codec(fmt
['filepath']) == 'aac'
823 args
.extend([f
'-bsf:a:{audio_streams}', 'aac_adtstoasc'])
825 if fmt
.get('vcodec') != 'none':
826 args
.extend(['-map', '%u:v:0' % (i
)])
827 self
.to_screen('Merging formats into "%s"' % filename
)
828 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
829 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
830 return info
['__files_to_merge'], info
833 # TODO: figure out merge-capable ffmpeg version
834 if self
.basename
!= 'avconv':
837 required_version
= '10-0'
838 if is_outdated_version(
839 self
._versions
[self
.basename
], required_version
):
840 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
841 'yt-dlp will download single file media. '
842 'Update %s to version %s or newer to fix this.') % (
843 self
.basename
, self
.basename
, required_version
)
844 self
.report_warning(warning
)
849 class FFmpegFixupPostProcessor(FFmpegPostProcessor
):
850 def _fixup(self
, msg
, filename
, options
):
851 temp_filename
= prepend_extension(filename
, 'temp')
853 self
.to_screen(f
'{msg} of "{filename}"')
854 self
.run_ffmpeg(filename
, temp_filename
, options
)
856 os
.replace(temp_filename
, filename
)
859 class FFmpegFixupStretchedPP(FFmpegFixupPostProcessor
):
860 @PostProcessor._restrict_to(images
=False, audio
=False)
862 stretched_ratio
= info
.get('stretched_ratio')
863 if stretched_ratio
not in (None, 1):
864 self
._fixup
('Fixing aspect ratio', info
['filepath'], [
865 *self
.stream_copy_opts(), '-aspect', '%f' % stretched_ratio
])
869 class FFmpegFixupM4aPP(FFmpegFixupPostProcessor
):
870 @PostProcessor._restrict_to(images
=False, video
=False)
872 if info
.get('container') == 'm4a_dash':
873 self
._fixup
('Correcting container', info
['filepath'], [*self
.stream_copy_opts(), '-f', 'mp4'])
877 class FFmpegFixupM3u8PP(FFmpegFixupPostProcessor
):
878 def _needs_fixup(self
, info
):
879 yield info
['ext'] in ('mp4', 'm4a')
880 yield info
['protocol'].startswith('m3u8')
882 metadata
= self
.get_metadata_object(info
['filepath'])
883 except PostProcessingError
as e
:
884 self
.report_warning(f
'Unable to extract metadata: {e.msg}')
887 yield traverse_obj(metadata
, ('format', 'format_name'), casesense
=False) == 'mpegts'
889 @PostProcessor._restrict_to(images
=False)
891 if all(self
._needs
_fixup
(info
)):
892 self
._fixup
('Fixing MPEG-TS in MP4 container', info
['filepath'], [
893 *self
.stream_copy_opts(), '-f', 'mp4', '-bsf:a', 'aac_adtstoasc'])
897 class FFmpegFixupTimestampPP(FFmpegFixupPostProcessor
):
899 def __init__(self
, downloader
=None, trim
=0.001):
900 # "trim" should be used when the video contains unintended packets
901 super(FFmpegFixupTimestampPP
, self
).__init
__(downloader
)
902 assert isinstance(trim
, (int, float))
903 self
.trim
= str(trim
)
905 @PostProcessor._restrict_to(images
=False)
907 if not self
._features
.get('setts'):
909 'A re-encode is needed to fix timestamps in older versions of ffmpeg. '
910 'Please install ffmpeg 4.4 or later to fixup without re-encoding')
911 opts
= ['-vf', 'setpts=PTS-STARTPTS']
913 opts
= ['-c', 'copy', '-bsf', 'setts=ts=TS-STARTPTS']
914 self
._fixup
('Fixing frame timestamp', info
['filepath'], opts
+ [*self
.stream_copy_opts(False), '-ss', self
.trim
])
918 class FFmpegCopyStreamPP(FFmpegFixupPostProcessor
):
919 MESSAGE
= 'Copying stream'
921 @PostProcessor._restrict_to(images
=False)
923 self
._fixup
(self
.MESSAGE
, info
['filepath'], self
.stream_copy_opts())
927 class FFmpegFixupDurationPP(FFmpegCopyStreamPP
):
928 MESSAGE
= 'Fixing video duration'
931 class FFmpegFixupDuplicateMoovPP(FFmpegCopyStreamPP
):
932 MESSAGE
= 'Fixing duplicate MOOV atoms'
935 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
936 SUPPORTED_EXTS
= ('srt', 'vtt', 'ass', 'lrc')
938 def __init__(self
, downloader
=None, format
=None):
939 super(FFmpegSubtitlesConvertorPP
, self
).__init
__(downloader
)
943 subs
= info
.get('requested_subtitles')
944 new_ext
= self
.format
946 if new_format
== 'vtt':
947 new_format
= 'webvtt'
949 self
.to_screen('There aren\'t any subtitles to convert')
951 self
.to_screen('Converting subtitles')
953 for lang
, sub
in subs
.items():
954 if not os
.path
.exists(sub
.get('filepath', '')):
955 self
.report_warning(f
'Skipping embedding {lang} subtitle because the file is missing')
959 self
.to_screen('Subtitle file for %s is already in the requested format' % new_ext
)
963 'You have requested to convert json subtitles into another format, '
964 'which is currently not possible')
966 old_file
= sub
['filepath']
967 sub_filenames
.append(old_file
)
968 new_file
= replace_extension(old_file
, new_ext
)
970 if ext
in ('dfxp', 'ttml', 'tt'):
972 'You have requested to convert dfxp (TTML) subtitles into another format, '
973 'which results in style information loss')
976 srt_file
= replace_extension(old_file
, 'srt')
978 with open(dfxp_file
, 'rb') as f
:
979 srt_data
= dfxp2srt(f
.read())
981 with io
.open(srt_file
, 'wt', encoding
='utf-8') as f
:
988 'filepath': srt_file
,
994 sub_filenames
.append(srt_file
)
996 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
998 with io
.open(new_file
, 'rt', encoding
='utf-8') as f
:
1002 'filepath': new_file
,
1005 info
['__files_to_move'][new_file
] = replace_extension(
1006 info
['__files_to_move'][sub
['filepath']], new_ext
)
1008 return sub_filenames
, info
1011 class FFmpegSplitChaptersPP(FFmpegPostProcessor
):
1012 def __init__(self
, downloader
, force_keyframes
=False):
1013 FFmpegPostProcessor
.__init
__(self
, downloader
)
1014 self
._force
_keyframes
= force_keyframes
1016 def _prepare_filename(self
, number
, chapter
, info
):
1019 'section_number': number
,
1020 'section_title': chapter
.get('title'),
1021 'section_start': chapter
.get('start_time'),
1022 'section_end': chapter
.get('end_time'),
1024 return self
._downloader
.prepare_filename(info
, 'chapter')
1026 def _ffmpeg_args_for_chapter(self
, number
, chapter
, info
):
1027 destination
= self
._prepare
_filename
(number
, chapter
, info
)
1028 if not self
._downloader
._ensure
_dir
_exists
(encodeFilename(destination
)):
1031 chapter
['filepath'] = destination
1032 self
.to_screen('Chapter %03d; Destination: %s' % (number
, destination
))
1035 ['-ss', compat_str(chapter
['start_time']),
1036 '-t', compat_str(chapter
['end_time'] - chapter
['start_time'])])
1038 @PostProcessor._restrict_to(images
=False)
1039 def run(self
, info
):
1040 chapters
= info
.get('chapters') or []
1042 self
.to_screen('Chapter information is unavailable')
1045 in_file
= info
['filepath']
1046 if self
._force
_keyframes
and len(chapters
) > 1:
1047 in_file
= self
.force_keyframes(in_file
, (c
['start_time'] for c
in chapters
))
1048 self
.to_screen('Splitting video by chapters; %d chapters found' % len(chapters
))
1049 for idx
, chapter
in enumerate(chapters
):
1050 destination
, opts
= self
._ffmpeg
_args
_for
_chapter
(idx
+ 1, chapter
, info
)
1051 self
.real_run_ffmpeg([(in_file
, opts
)], [(destination
, self
.stream_copy_opts())])
1052 if in_file
!= info
['filepath']:
1057 class FFmpegThumbnailsConvertorPP(FFmpegPostProcessor
):
1058 SUPPORTED_EXTS
= ('jpg', 'png', 'webp')
1060 def __init__(self
, downloader
=None, format
=None):
1061 super(FFmpegThumbnailsConvertorPP
, self
).__init
__(downloader
)
1062 self
.format
= format
1066 with open(encodeFilename(path
), 'rb') as f
:
1068 return b
[0:4] == b
'RIFF' and b
[8:] == b
'WEBP'
1070 def fixup_webp(self
, info
, idx
=-1):
1071 thumbnail_filename
= info
['thumbnails'][idx
]['filepath']
1072 _
, thumbnail_ext
= os
.path
.splitext(thumbnail_filename
)
1074 thumbnail_ext
= thumbnail_ext
[1:].lower()
1075 if thumbnail_ext
!= 'webp' and self
.is_webp(thumbnail_filename
):
1076 self
.to_screen('Correcting thumbnail "%s" extension to webp' % thumbnail_filename
)
1077 webp_filename
= replace_extension(thumbnail_filename
, 'webp')
1078 os
.replace(thumbnail_filename
, webp_filename
)
1079 info
['thumbnails'][idx
]['filepath'] = webp_filename
1080 info
['__files_to_move'][webp_filename
] = replace_extension(
1081 info
['__files_to_move'].pop(thumbnail_filename
), 'webp')
1084 def _options(target_ext
):
1085 if target_ext
== 'jpg':
1086 return ['-bsf:v', 'mjpeg2jpeg']
1089 def convert_thumbnail(self
, thumbnail_filename
, target_ext
):
1090 thumbnail_conv_filename
= replace_extension(thumbnail_filename
, target_ext
)
1092 self
.to_screen('Converting thumbnail "%s" to %s' % (thumbnail_filename
, target_ext
))
1093 self
.real_run_ffmpeg(
1094 [(thumbnail_filename
, ['-f', 'image2', '-pattern_type', 'none'])],
1095 [(thumbnail_conv_filename
.replace('%', '%%'), self
._options
(target_ext
))])
1096 return thumbnail_conv_filename
1098 def run(self
, info
):
1099 files_to_delete
= []
1100 has_thumbnail
= False
1102 for idx
, thumbnail_dict
in enumerate(info
.get('thumbnails') or []):
1103 original_thumbnail
= thumbnail_dict
.get('filepath')
1104 if not original_thumbnail
:
1106 has_thumbnail
= True
1107 self
.fixup_webp(info
, idx
)
1108 _
, thumbnail_ext
= os
.path
.splitext(original_thumbnail
)
1110 thumbnail_ext
= thumbnail_ext
[1:].lower()
1111 if thumbnail_ext
== 'jpeg':
1112 thumbnail_ext
= 'jpg'
1113 if thumbnail_ext
== self
.format
:
1114 self
.to_screen('Thumbnail "%s" is already in the requested format' % original_thumbnail
)
1116 thumbnail_dict
['filepath'] = self
.convert_thumbnail(original_thumbnail
, self
.format
)
1117 files_to_delete
.append(original_thumbnail
)
1118 info
['__files_to_move'][thumbnail_dict
['filepath']] = replace_extension(
1119 info
['__files_to_move'][original_thumbnail
], self
.format
)
1121 if not has_thumbnail
:
1122 self
.to_screen('There aren\'t any thumbnails to convert')
1123 return files_to_delete
, info
1126 class FFmpegConcatPP(FFmpegPostProcessor
):
1127 def __init__(self
, downloader
, only_multi_video
=False):
1128 self
._only
_multi
_video
= only_multi_video
1129 super().__init
__(downloader
)
1131 def concat_files(self
, in_files
, out_file
):
1132 if len(in_files
) == 1:
1133 if os
.path
.realpath(in_files
[0]) != os
.path
.realpath(out_file
):
1134 self
.to_screen(f
'Moving "{in_files[0]}" to "{out_file}"')
1135 os
.replace(in_files
[0], out_file
)
1138 codecs
= [traverse_obj(self
.get_metadata_object(file), ('streams', ..., 'codec_name')) for file in in_files
]
1139 if len(set(map(tuple, codecs
))) > 1:
1140 raise PostProcessingError(
1141 'The files have different streams/codecs and cannot be concatenated. '
1142 'Either select different formats or --recode-video them to a common format')
1144 self
.to_screen(f
'Concatenating {len(in_files)} files; Destination: {out_file}')
1145 super().concat_files(in_files
, out_file
)
1148 @PostProcessor._restrict_to(images
=False, simulated
=False)
1149 def run(self
, info
):
1150 entries
= info
.get('entries') or []
1151 if not any(entries
) or (self
._only
_multi
_video
and info
['_type'] != 'multi_video'):
1153 elif any(len(entry
) > 1 for entry
in traverse_obj(entries
, (..., 'requested_downloads')) or []):
1154 raise PostProcessingError('Concatenation is not supported when downloading multiple separate formats')
1156 in_files
= traverse_obj(entries
, (..., 'requested_downloads', 0, 'filepath')) or []
1157 if len(in_files
) < len(entries
):
1158 raise PostProcessingError('Aborting concatenation because some downloads failed')
1160 ie_copy
= self
._downloader
._playlist
_infodict
(info
)
1161 exts
= traverse_obj(entries
, (..., 'requested_downloads', 0, 'ext'), (..., 'ext'))
1162 ie_copy
['ext'] = exts
[0] if len(set(exts
)) == 1 else 'mkv'
1163 out_file
= self
._downloader
.prepare_filename(ie_copy
, 'pl_video')
1165 files_to_delete
= self
.concat_files(in_files
, out_file
)
1167 info
['requested_downloads'] = [{
1168 'filepath': out_file
,
1169 'ext': ie_copy
['ext'],
1171 return files_to_delete
, info