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