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