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