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