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