[ie/twitter:spaces] Support video spaces (#10789)
[yt-dlp3.git] / yt_dlp / postprocessor / ffmpeg.py
blob164c46d143b69c16c6c3ac3b632510a07d56ce25
1 import collections
2 import contextvars
3 import functools
4 import itertools
5 import json
6 import os
7 import re
8 import subprocess
9 import time
11 from .common import PostProcessor
12 from ..compat import imghdr
13 from ..utils import (
14 MEDIA_EXTENSIONS,
15 ISO639Utils,
16 Popen,
17 PostProcessingError,
18 _get_exe_version_output,
19 deprecation_warning,
20 detect_exe_version,
21 determine_ext,
22 dfxp2srt,
23 encodeArgument,
24 encodeFilename,
25 filter_dict,
26 float_or_none,
27 is_outdated_version,
28 orderedSet,
29 prepend_extension,
30 replace_extension,
31 shell_quote,
32 traverse_obj,
33 variadic,
34 write_json_file,
37 EXT_TO_OUT_FORMATS = {
38 'aac': 'adts',
39 'flac': 'flac',
40 'm4a': 'ipod',
41 'mka': 'matroska',
42 'mkv': 'matroska',
43 'mpg': 'mpeg',
44 'ogv': 'ogg',
45 'ts': 'mpegts',
46 'wma': 'asf',
47 'wmv': 'asf',
48 'weba': 'webm',
49 'vtt': 'webvtt',
51 ACODECS = {
52 # name: (ext, encoder, opts)
53 'mp3': ('mp3', 'libmp3lame', ()),
54 'aac': ('m4a', 'aac', ('-f', 'adts')),
55 'm4a': ('m4a', 'aac', ('-bsf:a', 'aac_adtstoasc')),
56 'opus': ('opus', 'libopus', ()),
57 'vorbis': ('ogg', 'libvorbis', ()),
58 'flac': ('flac', 'flac', ()),
59 'alac': ('m4a', None, ('-acodec', 'alac')),
60 'wav': ('wav', None, ('-f', 'wav')),
64 def create_mapping_re(supported):
65 return re.compile(r'{0}(?:/{0})*$'.format(r'(?:\s*\w+\s*>)?\s*(?:{})\s*'.format('|'.join(supported))))
68 def resolve_mapping(source, mapping):
69 """
70 Get corresponding item from a mapping string like 'A>B/C>D/E'
71 @returns (target, error_message)
72 """
73 for pair in mapping.lower().split('/'):
74 kv = pair.split('>', 1)
75 if len(kv) == 1 or kv[0].strip() == source:
76 target = kv[-1].strip()
77 if target == source:
78 return target, f'already is in target format {source}'
79 return target, None
80 return None, f'could not find a mapping for {source}'
83 class FFmpegPostProcessorError(PostProcessingError):
84 pass
87 class FFmpegPostProcessor(PostProcessor):
88 _ffmpeg_location = contextvars.ContextVar('ffmpeg_location', default=None)
90 def __init__(self, downloader=None):
91 PostProcessor.__init__(self, downloader)
92 self._prefer_ffmpeg = self.get_param('prefer_ffmpeg', True)
93 self._paths = self._determine_executables()
95 @staticmethod
96 def get_versions_and_features(downloader=None):
97 pp = FFmpegPostProcessor(downloader)
98 return pp._versions, pp._features
100 @staticmethod
101 def get_versions(downloader=None):
102 return FFmpegPostProcessor.get_versions_and_features(downloader)[0]
104 _ffmpeg_to_avconv = {'ffmpeg': 'avconv', 'ffprobe': 'avprobe'}
106 def _determine_executables(self):
107 programs = [*self._ffmpeg_to_avconv.keys(), *self._ffmpeg_to_avconv.values()]
109 location = self.get_param('ffmpeg_location', self._ffmpeg_location.get())
110 if location is None:
111 return {p: p for p in programs}
113 if not os.path.exists(location):
114 self.report_warning(
115 f'ffmpeg-location {location} does not exist! Continuing without ffmpeg', only_once=True)
116 return {}
117 elif os.path.isdir(location):
118 dirname, basename, filename = location, None, None
119 else:
120 filename = os.path.basename(location)
121 basename = next((p for p in programs if p in filename), 'ffmpeg')
122 dirname = os.path.dirname(os.path.abspath(location))
123 if basename in self._ffmpeg_to_avconv:
124 self._prefer_ffmpeg = True
126 paths = {p: os.path.join(dirname, p) for p in programs}
127 if basename and basename in filename:
128 for p in programs:
129 path = os.path.join(dirname, filename.replace(basename, p))
130 if os.path.exists(path):
131 paths[p] = path
132 if basename:
133 paths[basename] = location
134 return paths
136 _version_cache, _features_cache = {None: None}, {}
138 def _get_ffmpeg_version(self, prog):
139 path = self._paths.get(prog)
140 if path in self._version_cache:
141 return self._version_cache[path], self._features_cache.get(path, {})
142 out = _get_exe_version_output(path, ['-bsfs'])
143 ver = detect_exe_version(out) if out else False
144 if ver:
145 regexs = [
146 r'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1]
147 r'n([0-9.]+)$', # Arch Linux
148 # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/
150 for regex in regexs:
151 mobj = re.match(regex, ver)
152 if mobj:
153 ver = mobj.group(1)
154 self._version_cache[path] = ver
155 if prog != 'ffmpeg' or not out:
156 return ver, {}
158 mobj = re.search(r'(?m)^\s+libavformat\s+(?:[0-9. ]+)\s+/\s+(?P<runtime>[0-9. ]+)', out)
159 lavf_runtime_version = mobj.group('runtime').replace(' ', '') if mobj else None
160 self._features_cache[path] = features = {
161 'fdk': '--enable-libfdk-aac' in out,
162 'setts': 'setts' in out.splitlines(),
163 'needs_adtstoasc': is_outdated_version(lavf_runtime_version, '57.56.100', False),
165 return ver, features
167 @property
168 def _versions(self):
169 return filter_dict({self.basename: self._version, self.probe_basename: self._probe_version})
171 @functools.cached_property
172 def basename(self):
173 _ = self._version # run property
174 return self.basename
176 @functools.cached_property
177 def probe_basename(self):
178 _ = self._probe_version # run property
179 return self.probe_basename
181 def _get_version(self, kind):
182 executables = (kind, )
183 if not self._prefer_ffmpeg:
184 executables = (kind, self._ffmpeg_to_avconv[kind])
185 basename, version, features = next(filter(
186 lambda x: x[1], ((p, *self._get_ffmpeg_version(p)) for p in executables)), (None, None, {}))
187 if kind == 'ffmpeg':
188 self.basename, self._features = basename, features
189 else:
190 self.probe_basename = basename
191 if basename == self._ffmpeg_to_avconv[kind]:
192 self.deprecated_feature(f'Support for {self._ffmpeg_to_avconv[kind]} is deprecated and '
193 f'may be removed in a future version. Use {kind} instead')
194 return version
196 @functools.cached_property
197 def _version(self):
198 return self._get_version('ffmpeg')
200 @functools.cached_property
201 def _probe_version(self):
202 return self._get_version('ffprobe')
204 @property
205 def available(self):
206 return self.basename is not None
208 @property
209 def executable(self):
210 return self._paths.get(self.basename)
212 @property
213 def probe_available(self):
214 return self.probe_basename is not None
216 @property
217 def probe_executable(self):
218 return self._paths.get(self.probe_basename)
220 @staticmethod
221 def stream_copy_opts(copy=True, *, ext=None):
222 yield from ('-map', '0')
223 # Don't copy Apple TV chapters track, bin_data
224 # See https://github.com/yt-dlp/yt-dlp/issues/2, #19042, #19024, https://trac.ffmpeg.org/ticket/6016
225 yield from ('-dn', '-ignore_unknown')
226 if copy:
227 yield from ('-c', 'copy')
228 if ext in ('mp4', 'mov', 'm4a'):
229 yield from ('-c:s', 'mov_text')
231 def check_version(self):
232 if not self.available:
233 raise FFmpegPostProcessorError('ffmpeg not found. Please install or provide the path using --ffmpeg-location')
235 required_version = '10-0' if self.basename == 'avconv' else '1.0'
236 if is_outdated_version(self._version, required_version):
237 self.report_warning(f'Your copy of {self.basename} is outdated, update {self.basename} '
238 f'to version {required_version} or newer if you encounter any errors')
240 def get_audio_codec(self, path):
241 if not self.probe_available and not self.available:
242 raise PostProcessingError('ffprobe and ffmpeg not found. Please install or provide the path using --ffmpeg-location')
243 try:
244 if self.probe_available:
245 cmd = [
246 encodeFilename(self.probe_executable, True),
247 encodeArgument('-show_streams')]
248 else:
249 cmd = [
250 encodeFilename(self.executable, True),
251 encodeArgument('-i')]
252 cmd.append(encodeFilename(self._ffmpeg_filename_argument(path), True))
253 self.write_debug(f'{self.basename} command line: {shell_quote(cmd)}')
254 stdout, stderr, returncode = Popen.run(
255 cmd, text=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
256 if returncode != (0 if self.probe_available else 1):
257 return None
258 except OSError:
259 return None
260 output = stdout if self.probe_available else stderr
261 if self.probe_available:
262 audio_codec = None
263 for line in output.split('\n'):
264 if line.startswith('codec_name='):
265 audio_codec = line.split('=')[1].strip()
266 elif line.strip() == 'codec_type=audio' and audio_codec is not None:
267 return audio_codec
268 else:
269 # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME
270 mobj = re.search(
271 r'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)',
272 output)
273 if mobj:
274 return mobj.group(1)
275 return None
277 def get_metadata_object(self, path, opts=[]):
278 if self.probe_basename != 'ffprobe':
279 if self.probe_available:
280 self.report_warning('Only ffprobe is supported for metadata extraction')
281 raise PostProcessingError('ffprobe not found. Please install or provide the path using --ffmpeg-location')
282 self.check_version()
284 cmd = [
285 encodeFilename(self.probe_executable, True),
286 encodeArgument('-hide_banner'),
287 encodeArgument('-show_format'),
288 encodeArgument('-show_streams'),
289 encodeArgument('-print_format'),
290 encodeArgument('json'),
293 cmd += opts
294 cmd.append(self._ffmpeg_filename_argument(path))
295 self.write_debug(f'ffprobe command line: {shell_quote(cmd)}')
296 stdout, _, _ = Popen.run(cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
297 return json.loads(stdout)
299 def get_stream_number(self, path, keys, value):
300 streams = self.get_metadata_object(path)['streams']
301 num = next(
302 (i for i, stream in enumerate(streams) if traverse_obj(stream, keys, casesense=False) == value),
303 None)
304 return num, len(streams)
306 def _fixup_chapters(self, info):
307 last_chapter = traverse_obj(info, ('chapters', -1))
308 if last_chapter and not last_chapter.get('end_time'):
309 last_chapter['end_time'] = self._get_real_video_duration(info['filepath'])
311 def _get_real_video_duration(self, filepath, fatal=True):
312 try:
313 duration = float_or_none(
314 traverse_obj(self.get_metadata_object(filepath), ('format', 'duration')))
315 if not duration:
316 raise PostProcessingError('ffprobe returned empty duration')
317 return duration
318 except PostProcessingError as e:
319 if fatal:
320 raise PostProcessingError(f'Unable to determine video duration: {e.msg}')
322 def _duration_mismatch(self, d1, d2, tolerance=2):
323 if not d1 or not d2:
324 return None
325 # The duration is often only known to nearest second. So there can be <1sec disparity natually.
326 # Further excuse an additional <1sec difference.
327 return abs(d1 - d2) > tolerance
329 def run_ffmpeg_multiple_files(self, input_paths, out_path, opts, **kwargs):
330 return self.real_run_ffmpeg(
331 [(path, []) for path in input_paths],
332 [(out_path, opts)], **kwargs)
334 def real_run_ffmpeg(self, input_path_opts, output_path_opts, *, expected_retcodes=(0,)):
335 self.check_version()
337 oldest_mtime = min(
338 os.stat(encodeFilename(path)).st_mtime for path, _ in input_path_opts if path)
340 cmd = [encodeFilename(self.executable, True), encodeArgument('-y')]
341 # avconv does not have repeat option
342 if self.basename == 'ffmpeg':
343 cmd += [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
345 def make_args(file, args, name, number):
346 keys = [f'_{name}{number}', f'_{name}']
347 if name == 'o':
348 args += ['-movflags', '+faststart']
349 if number == 1:
350 keys.append('')
351 args += self._configuration_args(self.basename, keys)
352 if name == 'i':
353 args.append('-i')
354 return (
355 [encodeArgument(arg) for arg in args]
356 + [encodeFilename(self._ffmpeg_filename_argument(file), True)])
358 for arg_type, path_opts in (('i', input_path_opts), ('o', output_path_opts)):
359 cmd += itertools.chain.from_iterable(
360 make_args(path, list(opts), arg_type, i + 1)
361 for i, (path, opts) in enumerate(path_opts) if path)
363 self.write_debug(f'ffmpeg command line: {shell_quote(cmd)}')
364 _, stderr, returncode = Popen.run(
365 cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
366 if returncode not in variadic(expected_retcodes):
367 self.write_debug(stderr)
368 raise FFmpegPostProcessorError(stderr.strip().splitlines()[-1])
369 for out_path, _ in output_path_opts:
370 if out_path:
371 self.try_utime(out_path, oldest_mtime, oldest_mtime)
372 return stderr
374 def run_ffmpeg(self, path, out_path, opts, **kwargs):
375 return self.run_ffmpeg_multiple_files([path], out_path, opts, **kwargs)
377 @staticmethod
378 def _ffmpeg_filename_argument(fn):
379 # Always use 'file:' because the filename may contain ':' (ffmpeg
380 # interprets that as a protocol) or can start with '-' (-- is broken in
381 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
382 # Also leave '-' intact in order not to break streaming to stdout.
383 if fn.startswith(('http://', 'https://')):
384 return fn
385 return 'file:' + fn if fn != '-' else fn
387 @staticmethod
388 def _quote_for_ffmpeg(string):
389 # See https://ffmpeg.org/ffmpeg-utils.html#toc-Quoting-and-escaping
390 # A sequence of '' produces '\'''\'';
391 # final replace removes the empty '' between \' \'.
392 string = string.replace("'", r"'\''").replace("'''", "'")
393 # Handle potential ' at string boundaries.
394 string = string[1:] if string[0] == "'" else "'" + string
395 return string[:-1] if string[-1] == "'" else string + "'"
397 def force_keyframes(self, filename, timestamps):
398 timestamps = orderedSet(timestamps)
399 if timestamps[0] == 0:
400 timestamps = timestamps[1:]
401 keyframe_file = prepend_extension(filename, 'keyframes.temp')
402 self.to_screen(f'Re-encoding "{filename}" with appropriate keyframes')
403 self.run_ffmpeg(filename, keyframe_file, [
404 *self.stream_copy_opts(False, ext=determine_ext(filename)),
405 '-force_key_frames', ','.join(f'{t:.6f}' for t in timestamps)])
406 return keyframe_file
408 def concat_files(self, in_files, out_file, concat_opts=None):
410 Use concat demuxer to concatenate multiple files having identical streams.
412 Only inpoint, outpoint, and duration concat options are supported.
413 See https://ffmpeg.org/ffmpeg-formats.html#concat-1 for details
415 concat_file = f'{out_file}.concat'
416 self.write_debug(f'Writing concat spec to {concat_file}')
417 with open(concat_file, 'w', encoding='utf-8') as f:
418 f.writelines(self._concat_spec(in_files, concat_opts))
420 out_flags = list(self.stream_copy_opts(ext=determine_ext(out_file)))
422 self.real_run_ffmpeg(
423 [(concat_file, ['-hide_banner', '-nostdin', '-f', 'concat', '-safe', '0'])],
424 [(out_file, out_flags)])
425 self._delete_downloaded_files(concat_file)
427 @classmethod
428 def _concat_spec(cls, in_files, concat_opts=None):
429 if concat_opts is None:
430 concat_opts = [{}] * len(in_files)
431 yield 'ffconcat version 1.0\n'
432 for file, opts in zip(in_files, concat_opts):
433 yield f'file {cls._quote_for_ffmpeg(cls._ffmpeg_filename_argument(file))}\n'
434 # Iterate explicitly to yield the following directives in order, ignoring the rest.
435 for directive in 'inpoint', 'outpoint', 'duration':
436 if directive in opts:
437 yield f'{directive} {opts[directive]}\n'
440 class FFmpegExtractAudioPP(FFmpegPostProcessor):
441 COMMON_AUDIO_EXTS = (*MEDIA_EXTENSIONS.common_audio, 'wma')
442 SUPPORTED_EXTS = tuple(ACODECS.keys())
443 FORMAT_RE = create_mapping_re(('best', *SUPPORTED_EXTS))
445 def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
446 FFmpegPostProcessor.__init__(self, downloader)
447 self.mapping = preferredcodec or 'best'
448 self._preferredquality = float_or_none(preferredquality)
449 self._nopostoverwrites = nopostoverwrites
451 def _quality_args(self, codec):
452 if self._preferredquality is None:
453 return []
454 elif self._preferredquality > 10:
455 return ['-b:a', f'{self._preferredquality}k']
457 limits = {
458 'libmp3lame': (10, 0),
459 'libvorbis': (0, 10),
460 # FFmpeg's AAC encoder does not have an upper limit for the value of -q:a.
461 # Experimentally, with values over 4, bitrate changes were minimal or non-existent
462 'aac': (0.1, 4),
463 'libfdk_aac': (1, 5),
464 }.get(codec)
465 if not limits:
466 return []
468 q = limits[1] + (limits[0] - limits[1]) * (self._preferredquality / 10)
469 if codec == 'libfdk_aac':
470 return ['-vbr', f'{int(q)}']
471 return ['-q:a', f'{q}']
473 def run_ffmpeg(self, path, out_path, codec, more_opts):
474 if codec is None:
475 acodec_opts = []
476 else:
477 acodec_opts = ['-acodec', codec]
478 opts = ['-vn', *acodec_opts, *more_opts]
479 try:
480 FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
481 except FFmpegPostProcessorError as err:
482 raise PostProcessingError(f'audio conversion failed: {err.msg}')
484 @PostProcessor._restrict_to(images=False)
485 def run(self, information):
486 orig_path = path = information['filepath']
487 target_format, _skip_msg = resolve_mapping(information['ext'], self.mapping)
488 if target_format == 'best' and information['ext'] in self.COMMON_AUDIO_EXTS:
489 target_format, _skip_msg = None, 'the file is already in a common audio format'
490 if not target_format:
491 self.to_screen(f'Not converting audio {orig_path}; {_skip_msg}')
492 return [], information
494 filecodec = self.get_audio_codec(path)
495 if filecodec is None:
496 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
498 if filecodec == 'aac' and target_format in ('m4a', 'best'):
499 # Lossless, but in another container
500 extension, _, more_opts, acodec = *ACODECS['m4a'], 'copy'
501 elif target_format == 'best' or target_format == filecodec:
502 # Lossless if possible
503 try:
504 extension, _, more_opts, acodec = *ACODECS[filecodec], 'copy'
505 except KeyError:
506 extension, acodec, more_opts = ACODECS['mp3']
507 else:
508 # We convert the audio (lossy if codec is lossy)
509 extension, acodec, more_opts = ACODECS[target_format]
510 if acodec == 'aac' and self._features.get('fdk'):
511 acodec, more_opts = 'libfdk_aac', []
513 more_opts = list(more_opts)
514 if acodec != 'copy':
515 more_opts = self._quality_args(acodec)
517 temp_path = new_path = replace_extension(path, extension, information['ext'])
519 if new_path == path:
520 if acodec == 'copy':
521 self.to_screen(f'Not converting audio {orig_path}; file is already in target format {target_format}')
522 return [], information
523 orig_path = prepend_extension(path, 'orig')
524 temp_path = prepend_extension(path, 'temp')
525 if (self._nopostoverwrites and os.path.exists(encodeFilename(new_path))
526 and os.path.exists(encodeFilename(orig_path))):
527 self.to_screen(f'Post-process file {new_path} exists, skipping')
528 return [], information
530 self.to_screen(f'Destination: {new_path}')
531 self.run_ffmpeg(path, temp_path, acodec, more_opts)
533 os.replace(path, orig_path)
534 os.replace(temp_path, new_path)
535 information['filepath'] = new_path
536 information['ext'] = extension
538 # Try to update the date time for extracted audio file.
539 if information.get('filetime') is not None:
540 self.try_utime(
541 new_path, time.time(), information['filetime'], errnote='Cannot update utime of audio file')
543 return [orig_path], information
546 class FFmpegVideoConvertorPP(FFmpegPostProcessor):
547 SUPPORTED_EXTS = (
548 *sorted((*MEDIA_EXTENSIONS.common_video, 'gif')),
549 *sorted((*MEDIA_EXTENSIONS.common_audio, 'aac', 'vorbis')),
551 FORMAT_RE = create_mapping_re(SUPPORTED_EXTS)
552 _ACTION = 'converting'
554 def __init__(self, downloader=None, preferedformat=None):
555 super().__init__(downloader)
556 self.mapping = preferedformat
558 @staticmethod
559 def _options(target_ext):
560 yield from FFmpegPostProcessor.stream_copy_opts(False)
561 if target_ext == 'avi':
562 yield from ('-c:v', 'libxvid', '-vtag', 'XVID')
564 @PostProcessor._restrict_to(images=False)
565 def run(self, info):
566 filename, source_ext = info['filepath'], info['ext'].lower()
567 target_ext, _skip_msg = resolve_mapping(source_ext, self.mapping)
568 if _skip_msg:
569 self.to_screen(f'Not {self._ACTION} media file "{filename}"; {_skip_msg}')
570 return [], info
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):
582 _ACTION = 'remuxing'
584 @staticmethod
585 def _options(target_ext):
586 return FFmpegPostProcessor.stream_copy_opts()
589 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
590 SUPPORTED_EXTS = ('mp4', 'mov', 'm4a', 'webm', 'mkv', 'mka')
592 def __init__(self, downloader=None, already_have_subtitle=False):
593 super().__init__(downloader)
594 self._already_have_subtitle = already_have_subtitle
596 @PostProcessor._restrict_to(images=False)
597 def run(self, info):
598 if info['ext'] not in self.SUPPORTED_EXTS:
599 self.to_screen(f'Subtitles can only be embedded in {", ".join(self.SUPPORTED_EXTS)} files')
600 return [], info
601 subtitles = info.get('requested_subtitles')
602 if not subtitles:
603 self.to_screen('There aren\'t any subtitles to embed')
604 return [], info
606 filename = info['filepath']
608 # Disabled temporarily. There needs to be a way to override this
609 # in case of duration actually mismatching in extractor
610 # See: https://github.com/yt-dlp/yt-dlp/issues/1870, https://github.com/yt-dlp/yt-dlp/issues/1385
612 if info.get('duration') and not info.get('__real_download') and self._duration_mismatch(
613 self._get_real_video_duration(filename, False), info['duration']):
614 self.to_screen(f'Skipping {self.pp_key()} since the real and expected durations mismatch')
615 return [], info
618 ext = info['ext']
619 sub_langs, sub_names, sub_filenames = [], [], []
620 webm_vtt_warn = False
621 mp4_ass_warn = False
623 for lang, sub_info in subtitles.items():
624 if not os.path.exists(sub_info.get('filepath', '')):
625 self.report_warning(f'Skipping embedding {lang} subtitle because the file is missing')
626 continue
627 sub_ext = sub_info['ext']
628 if sub_ext == 'json':
629 self.report_warning('JSON subtitles cannot be embedded')
630 elif ext != 'webm' or ext == 'webm' and sub_ext == 'vtt':
631 sub_langs.append(lang)
632 sub_names.append(sub_info.get('name'))
633 sub_filenames.append(sub_info['filepath'])
634 else:
635 if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt':
636 webm_vtt_warn = True
637 self.report_warning('Only WebVTT subtitles can be embedded in webm files')
638 if not mp4_ass_warn and ext == 'mp4' and sub_ext == 'ass':
639 mp4_ass_warn = True
640 self.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues')
642 if not sub_langs:
643 return [], info
645 input_files = [filename, *sub_filenames]
647 opts = [
648 *self.stream_copy_opts(ext=info['ext']),
649 # Don't copy the existing subtitles, we may be running the
650 # postprocessor a second time
651 '-map', '-0:s',
653 for i, (lang, name) in enumerate(zip(sub_langs, sub_names)):
654 opts.extend(['-map', f'{i + 1}:0'])
655 lang_code = ISO639Utils.short2long(lang) or lang
656 opts.extend([f'-metadata:s:s:{i}', f'language={lang_code}'])
657 if name:
658 opts.extend([f'-metadata:s:s:{i}', f'handler_name={name}',
659 f'-metadata:s:s:{i}', f'title={name}'])
661 temp_filename = prepend_extension(filename, 'temp')
662 self.to_screen(f'Embedding subtitles in "{filename}"')
663 self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
664 os.replace(temp_filename, filename)
666 files_to_delete = [] if self._already_have_subtitle else sub_filenames
667 return files_to_delete, info
670 class FFmpegMetadataPP(FFmpegPostProcessor):
672 def __init__(self, downloader, add_metadata=True, add_chapters=True, add_infojson='if_exists'):
673 FFmpegPostProcessor.__init__(self, downloader)
674 self._add_metadata = add_metadata
675 self._add_chapters = add_chapters
676 self._add_infojson = add_infojson
678 @staticmethod
679 def _options(target_ext):
680 audio_only = target_ext == 'm4a'
681 yield from FFmpegPostProcessor.stream_copy_opts(not audio_only)
682 if audio_only:
683 yield from ('-vn', '-acodec', 'copy')
685 @PostProcessor._restrict_to(images=False)
686 def run(self, info):
687 self._fixup_chapters(info)
688 filename, metadata_filename = info['filepath'], None
689 files_to_delete, options = [], []
690 if self._add_chapters and info.get('chapters'):
691 metadata_filename = replace_extension(filename, 'meta')
692 options.extend(self._get_chapter_opts(info['chapters'], metadata_filename))
693 files_to_delete.append(metadata_filename)
694 if self._add_metadata:
695 options.extend(self._get_metadata_opts(info))
697 if self._add_infojson:
698 if info['ext'] in ('mkv', 'mka'):
699 infojson_filename = info.get('infojson_filename')
700 options.extend(self._get_infojson_opts(info, infojson_filename))
701 if not infojson_filename:
702 files_to_delete.append(info.get('infojson_filename'))
703 elif self._add_infojson is True:
704 self.to_screen('The info-json can only be attached to mkv/mka files')
706 if not options:
707 self.to_screen('There isn\'t any metadata to add')
708 return [], info
710 temp_filename = prepend_extension(filename, 'temp')
711 self.to_screen(f'Adding metadata to "{filename}"')
712 self.run_ffmpeg_multiple_files(
713 (filename, metadata_filename), temp_filename,
714 itertools.chain(self._options(info['ext']), *options))
715 self._delete_downloaded_files(*files_to_delete)
716 os.replace(temp_filename, filename)
717 return [], info
719 @staticmethod
720 def _get_chapter_opts(chapters, metadata_filename):
721 with open(metadata_filename, 'w', encoding='utf-8') as f:
722 def ffmpeg_escape(text):
723 return re.sub(r'([\\=;#\n])', r'\\\1', text)
725 metadata_file_content = ';FFMETADATA1\n'
726 for chapter in chapters:
727 metadata_file_content += '[CHAPTER]\nTIMEBASE=1/1000\n'
728 metadata_file_content += 'START=%d\n' % (chapter['start_time'] * 1000)
729 metadata_file_content += 'END=%d\n' % (chapter['end_time'] * 1000)
730 chapter_title = chapter.get('title')
731 if chapter_title:
732 metadata_file_content += f'title={ffmpeg_escape(chapter_title)}\n'
733 f.write(metadata_file_content)
734 yield ('-map_metadata', '1')
736 def _get_metadata_opts(self, info):
737 meta_prefix = 'meta'
738 metadata = collections.defaultdict(dict)
740 def add(meta_list, info_list=None):
741 value = next((
742 info[key] for key in [f'{meta_prefix}_', *variadic(info_list or meta_list)]
743 if info.get(key) is not None), None)
744 if value not in ('', None):
745 value = ', '.join(map(str, variadic(value)))
746 value = value.replace('\0', '') # nul character cannot be passed in command line
747 metadata['common'].update({meta_f: value for meta_f in variadic(meta_list)})
749 # Info on media metadata/metadata supported by ffmpeg:
750 # https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
751 # https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
752 # https://kodi.wiki/view/Video_file_tagging
754 add('title', ('track', 'title'))
755 add('date', 'upload_date')
756 add(('description', 'synopsis'), 'description')
757 add(('purl', 'comment'), 'webpage_url')
758 add('track', 'track_number')
759 add('artist', ('artist', 'artists', 'creator', 'creators', 'uploader', 'uploader_id'))
760 add('composer', ('composer', 'composers'))
761 add('genre', ('genre', 'genres'))
762 add('album')
763 add('album_artist', ('album_artist', 'album_artists'))
764 add('disc', 'disc_number')
765 add('show', 'series')
766 add('season_number')
767 add('episode_id', ('episode', 'episode_id'))
768 add('episode_sort', 'episode_number')
769 if 'embed-metadata' in self.get_param('compat_opts', []):
770 add('comment', 'description')
771 metadata['common'].pop('synopsis', None)
773 meta_regex = rf'{re.escape(meta_prefix)}(?P<i>\d+)?_(?P<key>.+)'
774 for key, value in info.items():
775 mobj = re.fullmatch(meta_regex, key)
776 if value is not None and mobj:
777 metadata[mobj.group('i') or 'common'][mobj.group('key')] = value.replace('\0', '')
779 # Write id3v1 metadata also since Windows Explorer can't handle id3v2 tags
780 yield ('-write_id3v1', '1')
782 for name, value in metadata['common'].items():
783 yield ('-metadata', f'{name}={value}')
785 stream_idx = 0
786 for fmt in info.get('requested_formats') or [info]:
787 stream_count = 2 if 'none' not in (fmt.get('vcodec'), fmt.get('acodec')) else 1
788 lang = ISO639Utils.short2long(fmt.get('language') or '') or fmt.get('language')
789 for i in range(stream_idx, stream_idx + stream_count):
790 if lang:
791 metadata[str(i)].setdefault('language', lang)
792 for name, value in metadata[str(i)].items():
793 yield (f'-metadata:s:{i}', f'{name}={value}')
794 stream_idx += stream_count
796 def _get_infojson_opts(self, info, infofn):
797 if not infofn or not os.path.exists(infofn):
798 if self._add_infojson is not True:
799 return
800 infofn = infofn or '%s.temp' % (
801 self._downloader.prepare_filename(info, 'infojson')
802 or replace_extension(self._downloader.prepare_filename(info), 'info.json', info['ext']))
803 if not self._downloader._ensure_dir_exists(infofn):
804 return
805 self.write_debug(f'Writing info-json to: {infofn}')
806 write_json_file(self._downloader.sanitize_info(info, self.get_param('clean_infojson', True)), infofn)
807 info['infojson_filename'] = infofn
809 old_stream, new_stream = self.get_stream_number(info['filepath'], ('tags', 'mimetype'), 'application/json')
810 if old_stream is not None:
811 yield ('-map', f'-0:{old_stream}')
812 new_stream -= 1
814 yield (
815 '-attach', self._ffmpeg_filename_argument(infofn),
816 f'-metadata:s:{new_stream}', 'mimetype=application/json',
817 f'-metadata:s:{new_stream}', 'filename=info.json',
821 class FFmpegMergerPP(FFmpegPostProcessor):
822 SUPPORTED_EXTS = MEDIA_EXTENSIONS.common_video
824 @PostProcessor._restrict_to(images=False)
825 def run(self, info):
826 filename = info['filepath']
827 temp_filename = prepend_extension(filename, 'temp')
828 args = ['-c', 'copy']
829 audio_streams = 0
830 for (i, fmt) in enumerate(info['requested_formats']):
831 if fmt.get('acodec') != 'none':
832 args.extend(['-map', f'{i}:a:0'])
833 aac_fixup = fmt['protocol'].startswith('m3u8') and self.get_audio_codec(fmt['filepath']) == 'aac'
834 if aac_fixup:
835 args.extend([f'-bsf:a:{audio_streams}', 'aac_adtstoasc'])
836 audio_streams += 1
837 if fmt.get('vcodec') != 'none':
838 args.extend(['-map', f'{i}:v:0'])
839 self.to_screen(f'Merging formats into "{filename}"')
840 self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
841 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
842 return info['__files_to_merge'], info
844 def can_merge(self):
845 # TODO: figure out merge-capable ffmpeg version
846 if self.basename != 'avconv':
847 return True
849 required_version = '10-0'
850 if is_outdated_version(
851 self._versions[self.basename], required_version):
852 warning = (f'Your copy of {self.basename} is outdated and unable to properly mux separate video and audio files, '
853 'yt-dlp will download single file media. '
854 f'Update {self.basename} to version {required_version} or newer to fix this.')
855 self.report_warning(warning)
856 return False
857 return True
860 class FFmpegFixupPostProcessor(FFmpegPostProcessor):
861 def _fixup(self, msg, filename, options):
862 temp_filename = prepend_extension(filename, 'temp')
864 self.to_screen(f'{msg} of "{filename}"')
865 self.run_ffmpeg(filename, temp_filename, options)
867 os.replace(temp_filename, filename)
870 class FFmpegFixupStretchedPP(FFmpegFixupPostProcessor):
871 @PostProcessor._restrict_to(images=False, audio=False)
872 def run(self, info):
873 stretched_ratio = info.get('stretched_ratio')
874 if stretched_ratio not in (None, 1):
875 self._fixup('Fixing aspect ratio', info['filepath'], [
876 *self.stream_copy_opts(), '-aspect', f'{stretched_ratio:f}'])
877 return [], info
880 class FFmpegFixupM4aPP(FFmpegFixupPostProcessor):
881 @PostProcessor._restrict_to(images=False, video=False)
882 def run(self, info):
883 if info.get('container') == 'm4a_dash':
884 self._fixup('Correcting container', info['filepath'], [*self.stream_copy_opts(), '-f', 'mp4'])
885 return [], info
888 class FFmpegFixupM3u8PP(FFmpegFixupPostProcessor):
889 def _needs_fixup(self, info):
890 yield info['ext'] in ('mp4', 'm4a')
891 yield info['protocol'].startswith('m3u8')
892 try:
893 metadata = self.get_metadata_object(info['filepath'])
894 except PostProcessingError as e:
895 self.report_warning(f'Unable to extract metadata: {e.msg}')
896 yield True
897 else:
898 yield traverse_obj(metadata, ('format', 'format_name'), casesense=False) == 'mpegts'
900 @PostProcessor._restrict_to(images=False)
901 def run(self, info):
902 if all(self._needs_fixup(info)):
903 args = ['-f', 'mp4']
904 if self.get_audio_codec(info['filepath']) == 'aac':
905 args.extend(['-bsf:a', 'aac_adtstoasc'])
906 self._fixup('Fixing MPEG-TS in MP4 container', info['filepath'], [
907 *self.stream_copy_opts(), *args])
908 return [], info
911 class FFmpegFixupTimestampPP(FFmpegFixupPostProcessor):
913 def __init__(self, downloader=None, trim=0.001):
914 # "trim" should be used when the video contains unintended packets
915 super().__init__(downloader)
916 assert isinstance(trim, (int, float))
917 self.trim = str(trim)
919 @PostProcessor._restrict_to(images=False)
920 def run(self, info):
921 if not self._features.get('setts'):
922 self.report_warning(
923 'A re-encode is needed to fix timestamps in older versions of ffmpeg. '
924 'Please install ffmpeg 4.4 or later to fixup without re-encoding')
925 opts = ['-vf', 'setpts=PTS-STARTPTS']
926 else:
927 opts = ['-c', 'copy', '-bsf', 'setts=ts=TS-STARTPTS']
928 self._fixup('Fixing frame timestamp', info['filepath'], [*opts, *self.stream_copy_opts(False), '-ss', self.trim])
929 return [], info
932 class FFmpegCopyStreamPP(FFmpegFixupPostProcessor):
933 MESSAGE = 'Copying stream'
935 @PostProcessor._restrict_to(images=False)
936 def run(self, info):
937 self._fixup(self.MESSAGE, info['filepath'], self.stream_copy_opts())
938 return [], info
941 class FFmpegFixupDurationPP(FFmpegCopyStreamPP):
942 MESSAGE = 'Fixing video duration'
945 class FFmpegFixupDuplicateMoovPP(FFmpegCopyStreamPP):
946 MESSAGE = 'Fixing duplicate MOOV atoms'
949 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
950 SUPPORTED_EXTS = MEDIA_EXTENSIONS.subtitles
952 def __init__(self, downloader=None, format=None):
953 super().__init__(downloader)
954 self.format = format
956 def run(self, info):
957 subs = info.get('requested_subtitles')
958 new_ext = self.format
959 new_format = new_ext
960 if new_format == 'vtt':
961 new_format = 'webvtt'
962 if subs is None:
963 self.to_screen('There aren\'t any subtitles to convert')
964 return [], info
965 self.to_screen('Converting subtitles')
966 sub_filenames = []
967 for lang, sub in subs.items():
968 if not os.path.exists(sub.get('filepath', '')):
969 self.report_warning(f'Skipping embedding {lang} subtitle because the file is missing')
970 continue
971 ext = sub['ext']
972 if ext == new_ext:
973 self.to_screen(f'Subtitle file for {new_ext} is already in the requested format')
974 continue
975 elif ext == 'json':
976 self.to_screen(
977 'You have requested to convert json subtitles into another format, '
978 'which is currently not possible')
979 continue
980 old_file = sub['filepath']
981 sub_filenames.append(old_file)
982 new_file = replace_extension(old_file, new_ext)
984 if ext in ('dfxp', 'ttml', 'tt'):
985 self.report_warning(
986 'You have requested to convert dfxp (TTML) subtitles into another format, '
987 'which results in style information loss')
989 dfxp_file = old_file
990 srt_file = replace_extension(old_file, 'srt')
992 with open(dfxp_file, 'rb') as f:
993 srt_data = dfxp2srt(f.read())
995 with open(srt_file, 'w', encoding='utf-8') as f:
996 f.write(srt_data)
997 old_file = srt_file
999 subs[lang] = {
1000 'ext': 'srt',
1001 'data': srt_data,
1002 'filepath': srt_file,
1005 if new_ext == 'srt':
1006 continue
1007 else:
1008 sub_filenames.append(srt_file)
1010 self.run_ffmpeg(old_file, new_file, ['-f', new_format])
1012 with open(new_file, encoding='utf-8') as f:
1013 subs[lang] = {
1014 'ext': new_ext,
1015 'data': f.read(),
1016 'filepath': new_file,
1019 info['__files_to_move'][new_file] = replace_extension(
1020 info['__files_to_move'][sub['filepath']], new_ext)
1022 return sub_filenames, info
1025 class FFmpegSplitChaptersPP(FFmpegPostProcessor):
1026 def __init__(self, downloader, force_keyframes=False):
1027 FFmpegPostProcessor.__init__(self, downloader)
1028 self._force_keyframes = force_keyframes
1030 def _prepare_filename(self, number, chapter, info):
1031 info = info.copy()
1032 info.update({
1033 'section_number': number,
1034 'section_title': chapter.get('title'),
1035 'section_start': chapter.get('start_time'),
1036 'section_end': chapter.get('end_time'),
1038 return self._downloader.prepare_filename(info, 'chapter')
1040 def _ffmpeg_args_for_chapter(self, number, chapter, info):
1041 destination = self._prepare_filename(number, chapter, info)
1042 if not self._downloader._ensure_dir_exists(encodeFilename(destination)):
1043 return
1045 chapter['filepath'] = destination
1046 self.to_screen('Chapter %03d; Destination: %s' % (number, destination))
1047 return (
1048 destination,
1049 ['-ss', str(chapter['start_time']),
1050 '-t', str(chapter['end_time'] - chapter['start_time'])])
1052 @PostProcessor._restrict_to(images=False)
1053 def run(self, info):
1054 self._fixup_chapters(info)
1055 chapters = info.get('chapters') or []
1056 if not chapters:
1057 self.to_screen('Chapter information is unavailable')
1058 return [], info
1060 in_file = info['filepath']
1061 if self._force_keyframes and len(chapters) > 1:
1062 in_file = self.force_keyframes(in_file, (c['start_time'] for c in chapters))
1063 self.to_screen(f'Splitting video by chapters; {len(chapters)} chapters found')
1064 for idx, chapter in enumerate(chapters):
1065 destination, opts = self._ffmpeg_args_for_chapter(idx + 1, chapter, info)
1066 self.real_run_ffmpeg([(in_file, opts)], [(destination, self.stream_copy_opts())])
1067 if in_file != info['filepath']:
1068 self._delete_downloaded_files(in_file, msg=None)
1069 return [], info
1072 class FFmpegThumbnailsConvertorPP(FFmpegPostProcessor):
1073 SUPPORTED_EXTS = MEDIA_EXTENSIONS.thumbnails
1074 FORMAT_RE = create_mapping_re(SUPPORTED_EXTS)
1076 def __init__(self, downloader=None, format=None):
1077 super().__init__(downloader)
1078 self.mapping = format
1080 @classmethod
1081 def is_webp(cls, path):
1082 deprecation_warning(f'{cls.__module__}.{cls.__name__}.is_webp is deprecated')
1083 return imghdr.what(path) == 'webp'
1085 def fixup_webp(self, info, idx=-1):
1086 thumbnail_filename = info['thumbnails'][idx]['filepath']
1087 _, thumbnail_ext = os.path.splitext(thumbnail_filename)
1088 if thumbnail_ext:
1089 if thumbnail_ext.lower() != '.webp' and imghdr.what(thumbnail_filename) == 'webp':
1090 self.to_screen(f'Correcting thumbnail "{thumbnail_filename}" extension to webp')
1091 webp_filename = replace_extension(thumbnail_filename, 'webp')
1092 os.replace(thumbnail_filename, webp_filename)
1093 info['thumbnails'][idx]['filepath'] = webp_filename
1094 info['__files_to_move'][webp_filename] = replace_extension(
1095 info['__files_to_move'].pop(thumbnail_filename), 'webp')
1097 @staticmethod
1098 def _options(target_ext):
1099 yield from ('-update', '1')
1100 if target_ext == 'jpg':
1101 yield from ('-bsf:v', 'mjpeg2jpeg')
1103 def convert_thumbnail(self, thumbnail_filename, target_ext):
1104 thumbnail_conv_filename = replace_extension(thumbnail_filename, target_ext)
1106 self.to_screen(f'Converting thumbnail "{thumbnail_filename}" to {target_ext}')
1107 _, source_ext = os.path.splitext(thumbnail_filename)
1108 self.real_run_ffmpeg(
1109 [(thumbnail_filename, [] if source_ext == '.gif' else ['-f', 'image2', '-pattern_type', 'none'])],
1110 [(thumbnail_conv_filename, self._options(target_ext))])
1111 return thumbnail_conv_filename
1113 def run(self, info):
1114 files_to_delete = []
1115 has_thumbnail = False
1117 for idx, thumbnail_dict in enumerate(info.get('thumbnails') or []):
1118 original_thumbnail = thumbnail_dict.get('filepath')
1119 if not original_thumbnail:
1120 continue
1121 has_thumbnail = True
1122 self.fixup_webp(info, idx)
1123 original_thumbnail = thumbnail_dict['filepath'] # Path can change during fixup
1124 thumbnail_ext = os.path.splitext(original_thumbnail)[1][1:].lower()
1125 if thumbnail_ext == 'jpeg':
1126 thumbnail_ext = 'jpg'
1127 target_ext, _skip_msg = resolve_mapping(thumbnail_ext, self.mapping)
1128 if _skip_msg:
1129 self.to_screen(f'Not converting thumbnail "{original_thumbnail}"; {_skip_msg}')
1130 continue
1131 thumbnail_dict['filepath'] = self.convert_thumbnail(original_thumbnail, target_ext)
1132 files_to_delete.append(original_thumbnail)
1133 info['__files_to_move'][thumbnail_dict['filepath']] = replace_extension(
1134 info['__files_to_move'][original_thumbnail], target_ext)
1136 if not has_thumbnail:
1137 self.to_screen('There aren\'t any thumbnails to convert')
1138 return files_to_delete, info
1141 class FFmpegConcatPP(FFmpegPostProcessor):
1142 def __init__(self, downloader, only_multi_video=False):
1143 self._only_multi_video = only_multi_video
1144 super().__init__(downloader)
1146 def _get_codecs(self, file):
1147 codecs = traverse_obj(self.get_metadata_object(file), ('streams', ..., 'codec_name'))
1148 self.write_debug(f'Codecs = {", ".join(codecs)}')
1149 return tuple(codecs)
1151 def concat_files(self, in_files, out_file):
1152 if not self._downloader._ensure_dir_exists(out_file):
1153 return
1154 if len(in_files) == 1:
1155 if os.path.realpath(in_files[0]) != os.path.realpath(out_file):
1156 self.to_screen(f'Moving "{in_files[0]}" to "{out_file}"')
1157 os.replace(in_files[0], out_file)
1158 return []
1160 if len(set(map(self._get_codecs, in_files))) > 1:
1161 raise PostProcessingError(
1162 'The files have different streams/codecs and cannot be concatenated. '
1163 'Either select different formats or --recode-video them to a common format')
1165 self.to_screen(f'Concatenating {len(in_files)} files; Destination: {out_file}')
1166 super().concat_files(in_files, out_file)
1167 return in_files
1169 @PostProcessor._restrict_to(images=False, simulated=False)
1170 def run(self, info):
1171 entries = info.get('entries') or []
1172 if not any(entries) or (self._only_multi_video and info['_type'] != 'multi_video'):
1173 return [], info
1174 elif traverse_obj(entries, (..., lambda k, v: k == 'requested_downloads' and len(v) > 1)):
1175 raise PostProcessingError('Concatenation is not supported when downloading multiple separate formats')
1177 in_files = traverse_obj(entries, (..., 'requested_downloads', 0, 'filepath')) or []
1178 if len(in_files) < len(entries):
1179 raise PostProcessingError('Aborting concatenation because some downloads failed')
1181 exts = traverse_obj(entries, (..., 'requested_downloads', 0, 'ext'), (..., 'ext'))
1182 ie_copy = collections.ChainMap({'ext': exts[0] if len(set(exts)) == 1 else 'mkv'},
1183 info, self._downloader._playlist_infodict(info))
1184 out_file = self._downloader.prepare_filename(ie_copy, 'pl_video')
1186 files_to_delete = self.concat_files(in_files, out_file)
1188 info['requested_downloads'] = [{
1189 'filepath': out_file,
1190 'ext': ie_copy['ext'],
1192 return files_to_delete, info