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