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