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