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