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