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