]>
Commit | Line | Data |
---|---|---|
3aa578ca PH |
1 | from __future__ import unicode_literals |
2 | ||
e9fade72 | 3 | import io |
496c1923 PH |
4 | import os |
5 | import subprocess | |
496c1923 | 6 | import time |
fa2a36d9 | 7 | import re |
06167fbb | 8 | import json |
496c1923 PH |
9 | |
10 | ||
11 | from .common import AudioConversionError, PostProcessor | |
12 | ||
84601bb7 | 13 | from ..compat import compat_str, compat_numeric_types |
8c25f81b | 14 | from ..utils import ( |
f07b74fc | 15 | encodeArgument, |
496c1923 | 16 | encodeFilename, |
95807118 | 17 | get_exe_version, |
48844745 | 18 | is_outdated_version, |
496c1923 PH |
19 | PostProcessingError, |
20 | prepend_extension, | |
21 | shell_quote, | |
bf6427d2 | 22 | dfxp2srt, |
39672624 | 23 | ISO639Utils, |
f5b1bca9 | 24 | process_communicate_or_kill, |
06167fbb | 25 | replace_extension, |
324ad820 | 26 | traverse_obj, |
496c1923 PH |
27 | ) |
28 | ||
29 | ||
a755f825 | 30 | EXT_TO_OUT_FORMATS = { |
21bfcd3d PH |
31 | 'aac': 'adts', |
32 | 'flac': 'flac', | |
33 | 'm4a': 'ipod', | |
34 | 'mka': 'matroska', | |
35 | 'mkv': 'matroska', | |
36 | 'mpg': 'mpeg', | |
37 | 'ogv': 'ogg', | |
38 | 'ts': 'mpegts', | |
39 | 'wma': 'asf', | |
40 | 'wmv': 'asf', | |
41 | } | |
42 | ACODECS = { | |
43 | 'mp3': 'libmp3lame', | |
44 | 'aac': 'aac', | |
45 | 'flac': 'flac', | |
46 | 'm4a': 'aac', | |
d2ae7e24 | 47 | 'opus': 'libopus', |
21bfcd3d PH |
48 | 'vorbis': 'libvorbis', |
49 | 'wav': None, | |
a755f825 | 50 | } |
51 | ||
52 | ||
496c1923 PH |
53 | class FFmpegPostProcessorError(PostProcessingError): |
54 | pass | |
55 | ||
d799b47b | 56 | |
496c1923 | 57 | class FFmpegPostProcessor(PostProcessor): |
d47aeb22 | 58 | def __init__(self, downloader=None): |
496c1923 | 59 | PostProcessor.__init__(self, downloader) |
73fac4e9 | 60 | self._determine_executables() |
496c1923 | 61 | |
48844745 | 62 | def check_version(self): |
f740fae2 | 63 | if not self.available: |
beb4b92a | 64 | raise FFmpegPostProcessorError('ffmpeg not found. Please install or provide the path using --ffmpeg-location') |
48844745 | 65 | |
65bf37ef | 66 | required_version = '10-0' if self.basename == 'avconv' else '1.0' |
48844745 | 67 | if is_outdated_version( |
73fac4e9 | 68 | self._versions[self.basename], required_version): |
3aa578ca | 69 | warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % ( |
73fac4e9 | 70 | self.basename, self.basename, required_version) |
f446cc66 | 71 | self.report_warning(warning) |
48844745 | 72 | |
496c1923 | 73 | @staticmethod |
73fac4e9 PH |
74 | def get_versions(downloader=None): |
75 | return FFmpegPostProcessor(downloader)._versions | |
6271f1ca | 76 | |
73fac4e9 PH |
77 | def _determine_executables(self): |
78 | programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe'] | |
d4a24f40 | 79 | prefer_ffmpeg = True |
73fac4e9 | 80 | |
a64646e4 RA |
81 | def get_ffmpeg_version(path): |
82 | ver = get_exe_version(path, args=['-version']) | |
83 | if ver: | |
84 | regexs = [ | |
cbdc688c | 85 | r'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1] |
5caa531a | 86 | r'n([0-9.]+)$', # Arch Linux |
cbdc688c | 87 | # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/ |
a64646e4 RA |
88 | ] |
89 | for regex in regexs: | |
90 | mobj = re.match(regex, ver) | |
91 | if mobj: | |
92 | ver = mobj.group(1) | |
93 | return ver | |
94 | ||
73fac4e9 PH |
95 | self.basename = None |
96 | self.probe_basename = None | |
97 | ||
98 | self._paths = None | |
99 | self._versions = None | |
100 | if self._downloader: | |
f446cc66 | 101 | prefer_ffmpeg = self.get_param('prefer_ffmpeg', True) |
102 | location = self.get_param('ffmpeg_location') | |
73fac4e9 PH |
103 | if location is not None: |
104 | if not os.path.exists(location): | |
f446cc66 | 105 | self.report_warning( |
73fac4e9 | 106 | 'ffmpeg-location %s does not exist! ' |
e4172ac9 | 107 | 'Continuing without ffmpeg.' % (location)) |
73fac4e9 PH |
108 | self._versions = {} |
109 | return | |
110 | elif not os.path.isdir(location): | |
111 | basename = os.path.splitext(os.path.basename(location))[0] | |
112 | if basename not in programs: | |
f446cc66 | 113 | self.report_warning( |
73fac4e9 | 114 | 'Cannot identify executable %s, its basename should be one of %s. ' |
e4172ac9 | 115 | 'Continuing without ffmpeg.' % |
73fac4e9 PH |
116 | (location, ', '.join(programs))) |
117 | self._versions = {} | |
118 | return None | |
119 | location = os.path.dirname(os.path.abspath(location)) | |
120 | if basename in ('ffmpeg', 'ffprobe'): | |
121 | prefer_ffmpeg = True | |
122 | ||
123 | self._paths = dict( | |
124 | (p, os.path.join(location, p)) for p in programs) | |
125 | self._versions = dict( | |
a64646e4 | 126 | (p, get_ffmpeg_version(self._paths[p])) for p in programs) |
73fac4e9 PH |
127 | if self._versions is None: |
128 | self._versions = dict( | |
a64646e4 | 129 | (p, get_ffmpeg_version(p)) for p in programs) |
73fac4e9 PH |
130 | self._paths = dict((p, p) for p in programs) |
131 | ||
d4a24f40 | 132 | if prefer_ffmpeg is False: |
d28b5171 | 133 | prefs = ('avconv', 'ffmpeg') |
d4a24f40 S |
134 | else: |
135 | prefs = ('ffmpeg', 'avconv') | |
d28b5171 PH |
136 | for p in prefs: |
137 | if self._versions[p]: | |
73fac4e9 PH |
138 | self.basename = p |
139 | break | |
76b1bd67 | 140 | |
d4a24f40 | 141 | if prefer_ffmpeg is False: |
1a253e13 | 142 | prefs = ('avprobe', 'ffprobe') |
d4a24f40 S |
143 | else: |
144 | prefs = ('ffprobe', 'avprobe') | |
1a253e13 PH |
145 | for p in prefs: |
146 | if self._versions[p]: | |
73fac4e9 PH |
147 | self.probe_basename = p |
148 | break | |
149 | ||
f740fae2 | 150 | @property |
73fac4e9 PH |
151 | def available(self): |
152 | return self.basename is not None | |
1a253e13 | 153 | |
73fac4e9 PH |
154 | @property |
155 | def executable(self): | |
156 | return self._paths[self.basename] | |
157 | ||
3da4b313 JMF |
158 | @property |
159 | def probe_available(self): | |
160 | return self.probe_basename is not None | |
161 | ||
73fac4e9 PH |
162 | @property |
163 | def probe_executable(self): | |
164 | return self._paths[self.probe_basename] | |
76b1bd67 | 165 | |
30d9e209 | 166 | def get_audio_codec(self, path): |
eb35b163 | 167 | if not self.probe_available and not self.available: |
beb4b92a | 168 | raise PostProcessingError('ffprobe and ffmpeg not found. Please install or provide the path using --ffmpeg-location') |
30d9e209 | 169 | try: |
eb35b163 RA |
170 | if self.probe_available: |
171 | cmd = [ | |
172 | encodeFilename(self.probe_executable, True), | |
173 | encodeArgument('-show_streams')] | |
174 | else: | |
175 | cmd = [ | |
176 | encodeFilename(self.executable, True), | |
177 | encodeArgument('-i')] | |
178 | cmd.append(encodeFilename(self._ffmpeg_filename_argument(path), True)) | |
f446cc66 | 179 | self.write_debug('%s command line: %s' % (self.basename, shell_quote(cmd))) |
eb35b163 RA |
180 | handle = subprocess.Popen( |
181 | cmd, stderr=subprocess.PIPE, | |
182 | stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
f5b1bca9 | 183 | stdout_data, stderr_data = process_communicate_or_kill(handle) |
eb35b163 RA |
184 | expected_ret = 0 if self.probe_available else 1 |
185 | if handle.wait() != expected_ret: | |
30d9e209 RA |
186 | return None |
187 | except (IOError, OSError): | |
188 | return None | |
eb35b163 RA |
189 | output = (stdout_data if self.probe_available else stderr_data).decode('ascii', 'ignore') |
190 | if self.probe_available: | |
191 | audio_codec = None | |
192 | for line in output.split('\n'): | |
193 | if line.startswith('codec_name='): | |
194 | audio_codec = line.split('=')[1].strip() | |
195 | elif line.strip() == 'codec_type=audio' and audio_codec is not None: | |
196 | return audio_codec | |
197 | else: | |
198 | # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME | |
199 | mobj = re.search( | |
200 | r'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)', | |
201 | output) | |
202 | if mobj: | |
203 | return mobj.group(1) | |
30d9e209 RA |
204 | return None |
205 | ||
06167fbb | 206 | def get_metadata_object(self, path, opts=[]): |
207 | if self.probe_basename != 'ffprobe': | |
208 | if self.probe_available: | |
209 | self.report_warning('Only ffprobe is supported for metadata extraction') | |
beb4b92a | 210 | raise PostProcessingError('ffprobe not found. Please install or provide the path using --ffmpeg-location') |
06167fbb | 211 | self.check_version() |
212 | ||
213 | cmd = [ | |
214 | encodeFilename(self.probe_executable, True), | |
215 | encodeArgument('-hide_banner'), | |
216 | encodeArgument('-show_format'), | |
217 | encodeArgument('-show_streams'), | |
218 | encodeArgument('-print_format'), | |
219 | encodeArgument('json'), | |
220 | ] | |
221 | ||
222 | cmd += opts | |
223 | cmd.append(encodeFilename(self._ffmpeg_filename_argument(path), True)) | |
06869367 | 224 | self.write_debug('ffprobe command line: %s' % shell_quote(cmd)) |
06167fbb | 225 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) |
226 | stdout, stderr = p.communicate() | |
227 | return json.loads(stdout.decode('utf-8', 'replace')) | |
228 | ||
229 | def get_stream_number(self, path, keys, value): | |
230 | streams = self.get_metadata_object(path)['streams'] | |
231 | num = next( | |
324ad820 | 232 | (i for i, stream in enumerate(streams) if traverse_obj(stream, keys, casesense=False) == value), |
06167fbb | 233 | None) |
234 | return num, len(streams) | |
235 | ||
496c1923 | 236 | def run_ffmpeg_multiple_files(self, input_paths, out_path, opts): |
e92caff5 | 237 | return self.real_run_ffmpeg( |
238 | [(path, []) for path in input_paths], | |
239 | [(out_path, opts)]) | |
240 | ||
241 | def real_run_ffmpeg(self, input_path_opts, output_path_opts): | |
48844745 | 242 | self.check_version() |
496c1923 | 243 | |
52afb2ac | 244 | oldest_mtime = min( |
e92caff5 | 245 | os.stat(encodeFilename(path)).st_mtime for path, _ in input_path_opts) |
43bc8890 | 246 | |
ce52c7c1 S |
247 | cmd = [encodeFilename(self.executable, True), encodeArgument('-y')] |
248 | # avconv does not have repeat option | |
249 | if self.basename == 'ffmpeg': | |
250 | cmd += [encodeArgument('-loglevel'), encodeArgument('repeat+info')] | |
5b1ecbb3 | 251 | |
e92caff5 | 252 | def make_args(file, args, name, number): |
253 | keys = ['_%s%d' % (name, number), '_%s' % name] | |
254 | if name == 'o' and number == 1: | |
255 | keys.append('') | |
256 | args += self._configuration_args(self.basename, keys) | |
257 | if name == 'i': | |
258 | args.append('-i') | |
5b1ecbb3 | 259 | return ( |
e92caff5 | 260 | [encodeArgument(arg) for arg in args] |
5b1ecbb3 | 261 | + [encodeFilename(self._ffmpeg_filename_argument(file), True)]) |
262 | ||
e92caff5 | 263 | for arg_type, path_opts in (('i', input_path_opts), ('o', output_path_opts)): |
264 | cmd += [arg for i, o in enumerate(path_opts) | |
265 | for arg in make_args(o[0], o[1], arg_type, i + 1)] | |
496c1923 | 266 | |
f446cc66 | 267 | self.write_debug('ffmpeg command line: %s' % shell_quote(cmd)) |
cffcbc02 | 268 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) |
f5b1bca9 | 269 | stdout, stderr = process_communicate_or_kill(p) |
496c1923 | 270 | if p.returncode != 0: |
06167fbb | 271 | stderr = stderr.decode('utf-8', 'replace').strip() |
06869367 | 272 | if self.get_param('verbose', False): |
06167fbb | 273 | self.report_error(stderr) |
274 | raise FFmpegPostProcessorError(stderr.split('\n')[-1]) | |
e92caff5 | 275 | for out_path, _ in output_path_opts: |
276 | self.try_utime(out_path, oldest_mtime, oldest_mtime) | |
06167fbb | 277 | return stderr.decode('utf-8', 'replace') |
cc55d088 | 278 | |
496c1923 | 279 | def run_ffmpeg(self, path, out_path, opts): |
ece8a2a1 | 280 | return self.run_ffmpeg_multiple_files([path], out_path, opts) |
496c1923 PH |
281 | |
282 | def _ffmpeg_filename_argument(self, fn): | |
8a7bbd16 JMF |
283 | # Always use 'file:' because the filename may contain ':' (ffmpeg |
284 | # interprets that as a protocol) or can start with '-' (-- is broken in | |
285 | # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details) | |
b9f2fdd3 | 286 | # Also leave '-' intact in order not to break streaming to stdout. |
06167fbb | 287 | if fn.startswith(('http://', 'https://')): |
288 | return fn | |
d868f43c | 289 | return 'file:' + fn if fn != '-' else fn |
496c1923 PH |
290 | |
291 | ||
292 | class FFmpegExtractAudioPP(FFmpegPostProcessor): | |
81a23040 | 293 | COMMON_AUDIO_EXTS = ('wav', 'flac', 'm4a', 'aiff', 'mp3', 'ogg', 'mka', 'opus', 'wma') |
294 | SUPPORTED_EXTS = ('best', 'aac', 'flac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav') | |
1de75fa1 | 295 | |
496c1923 PH |
296 | def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False): |
297 | FFmpegPostProcessor.__init__(self, downloader) | |
81a23040 | 298 | self._preferredcodec = preferredcodec or 'best' |
496c1923 PH |
299 | self._preferredquality = preferredquality |
300 | self._nopostoverwrites = nopostoverwrites | |
301 | ||
496c1923 | 302 | def run_ffmpeg(self, path, out_path, codec, more_opts): |
496c1923 PH |
303 | if codec is None: |
304 | acodec_opts = [] | |
305 | else: | |
306 | acodec_opts = ['-acodec', codec] | |
307 | opts = ['-vn'] + acodec_opts + more_opts | |
308 | try: | |
309 | FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts) | |
310 | except FFmpegPostProcessorError as err: | |
311 | raise AudioConversionError(err.msg) | |
312 | ||
8326b00a | 313 | @PostProcessor._restrict_to(images=False) |
496c1923 PH |
314 | def run(self, information): |
315 | path = information['filepath'] | |
1de75fa1 | 316 | orig_ext = information['ext'] |
317 | ||
81a23040 | 318 | if self._preferredcodec == 'best' and orig_ext in self.COMMON_AUDIO_EXTS: |
1de75fa1 | 319 | self.to_screen('Skipping audio extraction since the file is already in a common audio format') |
55b53b33 | 320 | return [], information |
496c1923 PH |
321 | |
322 | filecodec = self.get_audio_codec(path) | |
323 | if filecodec is None: | |
3aa578ca | 324 | raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe') |
496c1923 PH |
325 | |
326 | more_opts = [] | |
327 | if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'): | |
328 | if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']: | |
329 | # Lossless, but in another container | |
330 | acodec = 'copy' | |
331 | extension = 'm4a' | |
467d3c9a | 332 | more_opts = ['-bsf:a', 'aac_adtstoasc'] |
21bfcd3d | 333 | elif filecodec in ['aac', 'flac', 'mp3', 'vorbis', 'opus']: |
496c1923 PH |
334 | # Lossless if possible |
335 | acodec = 'copy' | |
336 | extension = filecodec | |
337 | if filecodec == 'aac': | |
338 | more_opts = ['-f', 'adts'] | |
339 | if filecodec == 'vorbis': | |
340 | extension = 'ogg' | |
341 | else: | |
342 | # MP3 otherwise. | |
343 | acodec = 'libmp3lame' | |
344 | extension = 'mp3' | |
345 | more_opts = [] | |
346 | if self._preferredquality is not None: | |
347 | if int(self._preferredquality) < 10: | |
467d3c9a | 348 | more_opts += ['-q:a', self._preferredquality] |
496c1923 | 349 | else: |
467d3c9a | 350 | more_opts += ['-b:a', self._preferredquality + 'k'] |
496c1923 | 351 | else: |
21bfcd3d PH |
352 | # We convert the audio (lossy if codec is lossy) |
353 | acodec = ACODECS[self._preferredcodec] | |
496c1923 PH |
354 | extension = self._preferredcodec |
355 | more_opts = [] | |
356 | if self._preferredquality is not None: | |
357 | # The opus codec doesn't support the -aq option | |
358 | if int(self._preferredquality) < 10 and extension != 'opus': | |
467d3c9a | 359 | more_opts += ['-q:a', self._preferredquality] |
496c1923 | 360 | else: |
467d3c9a | 361 | more_opts += ['-b:a', self._preferredquality + 'k'] |
496c1923 PH |
362 | if self._preferredcodec == 'aac': |
363 | more_opts += ['-f', 'adts'] | |
364 | if self._preferredcodec == 'm4a': | |
467d3c9a | 365 | more_opts += ['-bsf:a', 'aac_adtstoasc'] |
496c1923 PH |
366 | if self._preferredcodec == 'vorbis': |
367 | extension = 'ogg' | |
368 | if self._preferredcodec == 'wav': | |
369 | extension = 'wav' | |
370 | more_opts += ['-f', 'wav'] | |
371 | ||
3aa578ca | 372 | prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups |
496c1923 | 373 | new_path = prefix + sep + extension |
0b94dbb1 | 374 | |
2273e2c5 PM |
375 | information['filepath'] = new_path |
376 | information['ext'] = extension | |
496c1923 PH |
377 | |
378 | # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly. | |
3089bc74 S |
379 | if (new_path == path |
380 | or (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))): | |
1b77b347 | 381 | self.to_screen('Post-process file %s exists, skipping' % new_path) |
592e97e8 | 382 | return [], information |
496c1923 PH |
383 | |
384 | try: | |
1b77b347 | 385 | self.to_screen('Destination: ' + new_path) |
ce81b141 | 386 | self.run_ffmpeg(path, new_path, acodec, more_opts) |
70a1165b JMF |
387 | except AudioConversionError as e: |
388 | raise PostProcessingError( | |
389 | 'audio conversion failed: ' + e.msg) | |
390 | except Exception: | |
391 | raise PostProcessingError('error running ' + self.basename) | |
496c1923 PH |
392 | |
393 | # Try to update the date time for extracted audio file. | |
394 | if information.get('filetime') is not None: | |
dd29eb7f S |
395 | self.try_utime( |
396 | new_path, time.time(), information['filetime'], | |
397 | errnote='Cannot update utime of audio file') | |
496c1923 | 398 | |
592e97e8 | 399 | return [path], information |
496c1923 PH |
400 | |
401 | ||
857f6313 | 402 | class FFmpegVideoConvertorPP(FFmpegPostProcessor): |
81a23040 | 403 | SUPPORTED_EXTS = ('mp4', 'mkv', 'flv', 'webm', 'mov', 'avi', 'mp3', 'mka', 'm4a', 'ogg', 'opus') |
404 | FORMAT_RE = re.compile(r'{0}(?:/{0})*$'.format(r'(?:\w+>)?(?:%s)' % '|'.join(SUPPORTED_EXTS))) | |
857f6313 | 405 | _action = 'converting' |
406 | ||
efe87a10 | 407 | def __init__(self, downloader=None, preferedformat=None): |
857f6313 | 408 | super(FFmpegVideoConvertorPP, self).__init__(downloader) |
06167fbb | 409 | self._preferedformats = preferedformat.lower().split('/') |
efe87a10 | 410 | |
857f6313 | 411 | def _target_ext(self, source_ext): |
06167fbb | 412 | for pair in self._preferedformats: |
413 | kv = pair.split('>') | |
857f6313 | 414 | if len(kv) == 1 or kv[0].strip() == source_ext: |
415 | return kv[-1].strip() | |
06167fbb | 416 | |
857f6313 | 417 | @staticmethod |
418 | def _options(target_ext): | |
419 | if target_ext == 'avi': | |
420 | return ['-c:v', 'libxvid', '-vtag', 'XVID'] | |
421 | return [] | |
422 | ||
8326b00a | 423 | @PostProcessor._restrict_to(images=False) |
857f6313 | 424 | def run(self, information): |
81a23040 | 425 | path, source_ext = information['filepath'], information['ext'].lower() |
426 | target_ext = self._target_ext(source_ext) | |
06167fbb | 427 | _skip_msg = ( |
857f6313 | 428 | 'could not find a mapping for %s' if not target_ext |
429 | else 'already is in target format %s' if source_ext == target_ext | |
06167fbb | 430 | else None) |
431 | if _skip_msg: | |
81a23040 | 432 | self.to_screen('Not %s media file "%s"; %s' % (self._action, path, _skip_msg % source_ext)) |
efe87a10 | 433 | return [], information |
06167fbb | 434 | |
06167fbb | 435 | prefix, sep, oldext = path.rpartition('.') |
857f6313 | 436 | outpath = prefix + sep + target_ext |
437 | self.to_screen('%s video from %s to %s; Destination: %s' % (self._action.title(), source_ext, target_ext, outpath)) | |
438 | self.run_ffmpeg(path, outpath, self._options(target_ext)) | |
439 | ||
efe87a10 | 440 | information['filepath'] = outpath |
857f6313 | 441 | information['format'] = information['ext'] = target_ext |
efe87a10 FS |
442 | return [path], information |
443 | ||
444 | ||
857f6313 | 445 | class FFmpegVideoRemuxerPP(FFmpegVideoConvertorPP): |
446 | _action = 'remuxing' | |
496c1923 | 447 | |
857f6313 | 448 | @staticmethod |
449 | def _options(target_ext): | |
450 | options = ['-c', 'copy', '-map', '0', '-dn'] | |
451 | if target_ext in ['mp4', 'm4a', 'mov']: | |
452 | options.extend(['-movflags', '+faststart']) | |
453 | return options | |
496c1923 PH |
454 | |
455 | ||
456 | class FFmpegEmbedSubtitlePP(FFmpegPostProcessor): | |
cffab0ee | 457 | def __init__(self, downloader=None, already_have_subtitle=False): |
458 | super(FFmpegEmbedSubtitlePP, self).__init__(downloader) | |
459 | self._already_have_subtitle = already_have_subtitle | |
460 | ||
8326b00a | 461 | @PostProcessor._restrict_to(images=False) |
496c1923 | 462 | def run(self, information): |
40025ee2 | 463 | if information['ext'] not in ('mp4', 'webm', 'mkv'): |
1b77b347 | 464 | self.to_screen('Subtitles can only be embedded in mp4, webm or mkv files') |
592e97e8 | 465 | return [], information |
c84dd8a9 JMF |
466 | subtitles = information.get('requested_subtitles') |
467 | if not subtitles: | |
1b77b347 | 468 | self.to_screen('There aren\'t any subtitles to embed') |
592e97e8 | 469 | return [], information |
496c1923 | 470 | |
496c1923 | 471 | filename = information['filepath'] |
40025ee2 S |
472 | |
473 | ext = information['ext'] | |
2412044c | 474 | sub_langs, sub_names, sub_filenames = [], [], [] |
40025ee2 | 475 | webm_vtt_warn = False |
06167fbb | 476 | mp4_ass_warn = False |
40025ee2 S |
477 | |
478 | for lang, sub_info in subtitles.items(): | |
479 | sub_ext = sub_info['ext'] | |
503d4a44 | 480 | if sub_ext == 'json': |
06167fbb | 481 | self.report_warning('JSON subtitles cannot be embedded') |
503d4a44 | 482 | elif ext != 'webm' or ext == 'webm' and sub_ext == 'vtt': |
40025ee2 | 483 | sub_langs.append(lang) |
2412044c | 484 | sub_names.append(sub_info.get('name')) |
dcf64d43 | 485 | sub_filenames.append(sub_info['filepath']) |
40025ee2 S |
486 | else: |
487 | if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt': | |
488 | webm_vtt_warn = True | |
06167fbb | 489 | self.report_warning('Only WebVTT subtitles can be embedded in webm files') |
490 | if not mp4_ass_warn and ext == 'mp4' and sub_ext == 'ass': | |
491 | mp4_ass_warn = True | |
492 | self.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues') | |
40025ee2 S |
493 | |
494 | if not sub_langs: | |
495 | return [], information | |
496 | ||
14523ed9 | 497 | input_files = [filename] + sub_filenames |
496c1923 | 498 | |
e205db3b | 499 | opts = [ |
e0da59fe | 500 | '-c', 'copy', '-map', '0', '-dn', |
e205db3b JMF |
501 | # Don't copy the existing subtitles, we may be running the |
502 | # postprocessor a second time | |
503 | '-map', '-0:s', | |
7f903dd8 T |
504 | # Don't copy Apple TV chapters track, bin_data (see #19042, #19024, |
505 | # https://trac.ffmpeg.org/ticket/6016) | |
506 | '-map', '-0:d', | |
e205db3b | 507 | ] |
083c1bb9 N |
508 | if information['ext'] == 'mp4': |
509 | opts += ['-c:s', 'mov_text'] | |
2412044c | 510 | for i, (lang, name) in enumerate(zip(sub_langs, sub_names)): |
2875cf01 | 511 | opts.extend(['-map', '%d:0' % (i + 1)]) |
04fb6928 S |
512 | lang_code = ISO639Utils.short2long(lang) or lang |
513 | opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code]) | |
2412044c | 514 | if name: |
515 | opts.extend(['-metadata:s:s:%d' % i, 'handler_name=%s' % name, | |
516 | '-metadata:s:s:%d' % i, 'title=%s' % name]) | |
496c1923 | 517 | |
2875cf01 | 518 | temp_filename = prepend_extension(filename, 'temp') |
06167fbb | 519 | self.to_screen('Embedding subtitles in "%s"' % filename) |
496c1923 PH |
520 | self.run_ffmpeg_multiple_files(input_files, temp_filename, opts) |
521 | os.remove(encodeFilename(filename)) | |
522 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
523 | ||
cffab0ee | 524 | files_to_delete = [] if self._already_have_subtitle else sub_filenames |
525 | return files_to_delete, information | |
496c1923 PH |
526 | |
527 | ||
528 | class FFmpegMetadataPP(FFmpegPostProcessor): | |
8326b00a | 529 | @PostProcessor._restrict_to(images=False) |
496c1923 PH |
530 | def run(self, info): |
531 | metadata = {} | |
4bd143a3 S |
532 | |
533 | def add(meta_list, info_list=None): | |
84601bb7 | 534 | if not meta_list: |
535 | return | |
4bd143a3 S |
536 | if not info_list: |
537 | info_list = meta_list | |
538 | if not isinstance(meta_list, (list, tuple)): | |
539 | meta_list = (meta_list,) | |
540 | if not isinstance(info_list, (list, tuple)): | |
541 | info_list = (info_list,) | |
542 | for info_f in info_list: | |
84601bb7 | 543 | if isinstance(info.get(info_f), (compat_str, compat_numeric_types)): |
4bd143a3 S |
544 | for meta_f in meta_list: |
545 | metadata[meta_f] = info[info_f] | |
546 | break | |
547 | ||
2791e80b S |
548 | # See [1-4] for some info on media metadata/metadata supported |
549 | # by ffmpeg. | |
550 | # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/ | |
551 | # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata | |
552 | # 3. https://kodi.wiki/view/Video_file_tagging | |
2791e80b | 553 | |
4bd143a3 S |
554 | add('title', ('track', 'title')) |
555 | add('date', 'upload_date') | |
cd9b384c | 556 | add(('description', 'synopsis'), 'description') |
557 | add(('purl', 'comment'), 'webpage_url') | |
4bd143a3 S |
558 | add('track', 'track_number') |
559 | add('artist', ('artist', 'creator', 'uploader', 'uploader_id')) | |
560 | add('genre') | |
561 | add('album') | |
562 | add('album_artist') | |
563 | add('disc', 'disc_number') | |
2791e80b S |
564 | add('show', 'series') |
565 | add('season_number') | |
566 | add('episode_id', ('episode', 'episode_id')) | |
567 | add('episode_sort', 'episode_number') | |
496c1923 | 568 | |
84601bb7 | 569 | prefix = 'meta_' |
570 | for key in filter(lambda k: k.startswith(prefix), info.keys()): | |
571 | add(key[len(prefix):], key) | |
572 | ||
496c1923 | 573 | if not metadata: |
1b77b347 | 574 | self.to_screen('There isn\'t any metadata to add') |
592e97e8 | 575 | return [], info |
496c1923 PH |
576 | |
577 | filename = info['filepath'] | |
578 | temp_filename = prepend_extension(filename, 'temp') | |
fa2a36d9 | 579 | in_filenames = [filename] |
e0da59fe | 580 | options = ['-map', '0', '-dn'] |
496c1923 | 581 | |
3aa578ca | 582 | if info['ext'] == 'm4a': |
fa2a36d9 | 583 | options.extend(['-vn', '-acodec', 'copy']) |
39c68260 | 584 | else: |
fa2a36d9 | 585 | options.extend(['-c', 'copy']) |
39c68260 | 586 | |
84601bb7 | 587 | for name, value in metadata.items(): |
496c1923 PH |
588 | options.extend(['-metadata', '%s=%s' % (name, value)]) |
589 | ||
fa2a36d9 | 590 | chapters = info.get('chapters', []) |
591 | if chapters: | |
5192ee17 | 592 | metadata_filename = replace_extension(filename, 'meta') |
fa2a36d9 | 593 | with io.open(metadata_filename, 'wt', encoding='utf-8') as f: |
594 | def ffmpeg_escape(text): | |
595 | return re.sub(r'(=|;|#|\\|\n)', r'\\\1', text) | |
596 | ||
597 | metadata_file_content = ';FFMETADATA1\n' | |
598 | for chapter in chapters: | |
599 | metadata_file_content += '[CHAPTER]\nTIMEBASE=1/1000\n' | |
600 | metadata_file_content += 'START=%d\n' % (chapter['start_time'] * 1000) | |
601 | metadata_file_content += 'END=%d\n' % (chapter['end_time'] * 1000) | |
602 | chapter_title = chapter.get('title') | |
603 | if chapter_title: | |
604 | metadata_file_content += 'title=%s\n' % ffmpeg_escape(chapter_title) | |
605 | f.write(metadata_file_content) | |
606 | in_filenames.append(metadata_filename) | |
607 | options.extend(['-map_metadata', '1']) | |
608 | ||
41712218 | 609 | if ('no-attach-info-json' not in self.get_param('compat_opts', []) |
610 | and '__infojson_filename' in info and info['ext'] in ('mkv', 'mka')): | |
06167fbb | 611 | old_stream, new_stream = self.get_stream_number( |
612 | filename, ('tags', 'mimetype'), 'application/json') | |
613 | if old_stream is not None: | |
614 | options.extend(['-map', '-0:%d' % old_stream]) | |
615 | new_stream -= 1 | |
616 | ||
617 | options.extend([ | |
de6000d9 | 618 | '-attach', info['__infojson_filename'], |
06167fbb | 619 | '-metadata:s:%d' % new_stream, 'mimetype=application/json' |
620 | ]) | |
621 | ||
1b77b347 | 622 | self.to_screen('Adding metadata to \'%s\'' % filename) |
fa2a36d9 | 623 | self.run_ffmpeg_multiple_files(in_filenames, temp_filename, options) |
624 | if chapters: | |
625 | os.remove(metadata_filename) | |
496c1923 PH |
626 | os.remove(encodeFilename(filename)) |
627 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
592e97e8 | 628 | return [], info |
496c1923 PH |
629 | |
630 | ||
631 | class FFmpegMergerPP(FFmpegPostProcessor): | |
8326b00a | 632 | @PostProcessor._restrict_to(images=False) |
496c1923 PH |
633 | def run(self, info): |
634 | filename = info['filepath'] | |
5b5fbc08 | 635 | temp_filename = prepend_extension(filename, 'temp') |
d03cfdce | 636 | args = ['-c', 'copy'] |
637 | for (i, fmt) in enumerate(info['requested_formats']): | |
638 | if fmt.get('acodec') != 'none': | |
639 | args.extend(['-map', '%u:a:0' % (i)]) | |
640 | if fmt.get('vcodec') != 'none': | |
641 | args.extend(['-map', '%u:v:0' % (i)]) | |
1b77b347 | 642 | self.to_screen('Merging formats into "%s"' % filename) |
5b5fbc08 JMF |
643 | self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args) |
644 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
d47aeb22 | 645 | return info['__files_to_merge'], info |
496c1923 | 646 | |
13763ce5 S |
647 | def can_merge(self): |
648 | # TODO: figure out merge-capable ffmpeg version | |
649 | if self.basename != 'avconv': | |
650 | return True | |
651 | ||
652 | required_version = '10-0' | |
653 | if is_outdated_version( | |
654 | self._versions[self.basename], required_version): | |
655 | warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, ' | |
7a5c1cfe | 656 | 'yt-dlp will download single file media. ' |
13763ce5 S |
657 | 'Update %s to version %s or newer to fix this.') % ( |
658 | self.basename, self.basename, required_version) | |
f446cc66 | 659 | self.report_warning(warning) |
13763ce5 S |
660 | return False |
661 | return True | |
662 | ||
0c14e2fb | 663 | |
fd7cfb64 | 664 | class FFmpegFixupPostProcessor(FFmpegPostProcessor): |
665 | def _fixup(self, msg, filename, options): | |
6271f1ca PH |
666 | temp_filename = prepend_extension(filename, 'temp') |
667 | ||
f89b3e2d | 668 | self.to_screen(f'{msg} of "{filename}"') |
6271f1ca PH |
669 | self.run_ffmpeg(filename, temp_filename, options) |
670 | ||
671 | os.remove(encodeFilename(filename)) | |
672 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
673 | ||
fd7cfb64 | 674 | |
675 | class FFmpegFixupStretchedPP(FFmpegFixupPostProcessor): | |
676 | @PostProcessor._restrict_to(images=False, audio=False) | |
677 | def run(self, info): | |
678 | stretched_ratio = info.get('stretched_ratio') | |
679 | if stretched_ratio not in (None, 1): | |
680 | self._fixup('Fixing aspect ratio', info['filepath'], [ | |
681 | '-c', 'copy', '-map', '0', '-dn', '-aspect', '%f' % stretched_ratio]) | |
592e97e8 | 682 | return [], info |
62cd676c PH |
683 | |
684 | ||
fd7cfb64 | 685 | class FFmpegFixupM4aPP(FFmpegFixupPostProcessor): |
8326b00a | 686 | @PostProcessor._restrict_to(images=False, video=False) |
62cd676c | 687 | def run(self, info): |
fd7cfb64 | 688 | if info.get('container') == 'm4a_dash': |
689 | self._fixup('Correcting container', info['filepath'], [ | |
690 | '-c', 'copy', '-map', '0', '-dn', '-f', 'mp4']) | |
592e97e8 | 691 | return [], info |
e9fade72 JMF |
692 | |
693 | ||
fd7cfb64 | 694 | class FFmpegFixupM3u8PP(FFmpegFixupPostProcessor): |
8326b00a | 695 | @PostProcessor._restrict_to(images=False) |
f17f8651 | 696 | def run(self, info): |
fd7cfb64 | 697 | if self.get_audio_codec(info['filepath']) == 'aac': |
698 | self._fixup('Fixing malformed AAC bitstream', info['filepath'], [ | |
699 | '-c', 'copy', '-map', '0', '-dn', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']) | |
f17f8651 | 700 | return [], info |
701 | ||
702 | ||
e9fade72 | 703 | class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor): |
81a23040 | 704 | SUPPORTED_EXTS = ('srt', 'vtt', 'ass', 'lrc') |
705 | ||
e9fade72 JMF |
706 | def __init__(self, downloader=None, format=None): |
707 | super(FFmpegSubtitlesConvertorPP, self).__init__(downloader) | |
708 | self.format = format | |
709 | ||
710 | def run(self, info): | |
711 | subs = info.get('requested_subtitles') | |
e9fade72 JMF |
712 | new_ext = self.format |
713 | new_format = new_ext | |
714 | if new_format == 'vtt': | |
715 | new_format = 'webvtt' | |
716 | if subs is None: | |
1b77b347 | 717 | self.to_screen('There aren\'t any subtitles to convert') |
592e97e8 | 718 | return [], info |
1b77b347 | 719 | self.to_screen('Converting subtitles') |
e04398e3 | 720 | sub_filenames = [] |
e9fade72 JMF |
721 | for lang, sub in subs.items(): |
722 | ext = sub['ext'] | |
723 | if ext == new_ext: | |
1b77b347 | 724 | self.to_screen('Subtitle file for %s is already in the requested format' % new_ext) |
e9fade72 | 725 | continue |
503d4a44 | 726 | elif ext == 'json': |
1b77b347 | 727 | self.to_screen( |
728 | 'You have requested to convert json subtitles into another format, ' | |
503d4a44 | 729 | 'which is currently not possible') |
730 | continue | |
dcf64d43 | 731 | old_file = sub['filepath'] |
e04398e3 | 732 | sub_filenames.append(old_file) |
dcf64d43 | 733 | new_file = replace_extension(old_file, new_ext) |
bf6427d2 | 734 | |
40fcba5e | 735 | if ext in ('dfxp', 'ttml', 'tt'): |
f446cc66 | 736 | self.report_warning( |
1b77b347 | 737 | 'You have requested to convert dfxp (TTML) subtitles into another format, ' |
bf6427d2 YCH |
738 | 'which results in style information loss') |
739 | ||
e04398e3 | 740 | dfxp_file = old_file |
dcf64d43 | 741 | srt_file = replace_extension(old_file, 'srt') |
bf6427d2 | 742 | |
3869028f | 743 | with open(dfxp_file, 'rb') as f: |
bf6427d2 YCH |
744 | srt_data = dfxp2srt(f.read()) |
745 | ||
746 | with io.open(srt_file, 'wt', encoding='utf-8') as f: | |
747 | f.write(srt_data) | |
7e62c2eb | 748 | old_file = srt_file |
bf6427d2 | 749 | |
bf6427d2 YCH |
750 | subs[lang] = { |
751 | 'ext': 'srt', | |
dcf64d43 | 752 | 'data': srt_data, |
753 | 'filepath': srt_file, | |
bf6427d2 YCH |
754 | } |
755 | ||
756 | if new_ext == 'srt': | |
757 | continue | |
7b8b007c JMF |
758 | else: |
759 | sub_filenames.append(srt_file) | |
bf6427d2 | 760 | |
e04398e3 | 761 | self.run_ffmpeg(old_file, new_file, ['-f', new_format]) |
e9fade72 JMF |
762 | |
763 | with io.open(new_file, 'rt', encoding='utf-8') as f: | |
764 | subs[lang] = { | |
3547d265 | 765 | 'ext': new_ext, |
e9fade72 | 766 | 'data': f.read(), |
dcf64d43 | 767 | 'filepath': new_file, |
e9fade72 JMF |
768 | } |
769 | ||
dcf64d43 | 770 | info['__files_to_move'][new_file] = replace_extension( |
771 | info['__files_to_move'][old_file], new_ext) | |
772 | ||
e04398e3 | 773 | return sub_filenames, info |
72755351 | 774 | |
775 | ||
776 | class FFmpegSplitChaptersPP(FFmpegPostProcessor): | |
777 | ||
778 | def _prepare_filename(self, number, chapter, info): | |
779 | info = info.copy() | |
780 | info.update({ | |
781 | 'section_number': number, | |
782 | 'section_title': chapter.get('title'), | |
783 | 'section_start': chapter.get('start_time'), | |
784 | 'section_end': chapter.get('end_time'), | |
785 | }) | |
786 | return self._downloader.prepare_filename(info, 'chapter') | |
787 | ||
788 | def _ffmpeg_args_for_chapter(self, number, chapter, info): | |
789 | destination = self._prepare_filename(number, chapter, info) | |
790 | if not self._downloader._ensure_dir_exists(encodeFilename(destination)): | |
791 | return | |
792 | ||
dcf64d43 | 793 | chapter['filepath'] = destination |
72755351 | 794 | self.to_screen('Chapter %03d; Destination: %s' % (number, destination)) |
795 | return ( | |
796 | destination, | |
797 | ['-ss', compat_str(chapter['start_time']), | |
a94bfd6c | 798 | '-t', compat_str(chapter['end_time'] - chapter['start_time'])]) |
72755351 | 799 | |
8326b00a | 800 | @PostProcessor._restrict_to(images=False) |
72755351 | 801 | def run(self, info): |
802 | chapters = info.get('chapters') or [] | |
803 | if not chapters: | |
beb4b92a | 804 | self.report_warning('Chapter information is unavailable') |
72755351 | 805 | return [], info |
806 | ||
807 | self.to_screen('Splitting video by chapters; %d chapters found' % len(chapters)) | |
808 | for idx, chapter in enumerate(chapters): | |
809 | destination, opts = self._ffmpeg_args_for_chapter(idx + 1, chapter, info) | |
810 | self.real_run_ffmpeg([(info['filepath'], opts)], [(destination, ['-c', 'copy'])]) | |
811 | return [], info | |
8fa43c73 | 812 | |
813 | ||
814 | class FFmpegThumbnailsConvertorPP(FFmpegPostProcessor): | |
81a23040 | 815 | SUPPORTED_EXTS = ('jpg', 'png') |
816 | ||
8fa43c73 | 817 | def __init__(self, downloader=None, format=None): |
818 | super(FFmpegThumbnailsConvertorPP, self).__init__(downloader) | |
819 | self.format = format | |
820 | ||
821 | @staticmethod | |
822 | def is_webp(path): | |
823 | with open(encodeFilename(path), 'rb') as f: | |
824 | b = f.read(12) | |
825 | return b[0:4] == b'RIFF' and b[8:] == b'WEBP' | |
826 | ||
827 | def fixup_webp(self, info, idx=-1): | |
828 | thumbnail_filename = info['thumbnails'][idx]['filepath'] | |
829 | _, thumbnail_ext = os.path.splitext(thumbnail_filename) | |
830 | if thumbnail_ext: | |
831 | thumbnail_ext = thumbnail_ext[1:].lower() | |
832 | if thumbnail_ext != 'webp' and self.is_webp(thumbnail_filename): | |
833 | self.to_screen('Correcting thumbnail "%s" extension to webp' % thumbnail_filename) | |
834 | webp_filename = replace_extension(thumbnail_filename, 'webp') | |
835 | if os.path.exists(webp_filename): | |
836 | os.remove(webp_filename) | |
837 | os.rename(encodeFilename(thumbnail_filename), encodeFilename(webp_filename)) | |
838 | info['thumbnails'][idx]['filepath'] = webp_filename | |
839 | info['__files_to_move'][webp_filename] = replace_extension( | |
840 | info['__files_to_move'].pop(thumbnail_filename), 'webp') | |
841 | ||
81a23040 | 842 | @staticmethod |
843 | def _options(target_ext): | |
844 | if target_ext == 'jpg': | |
845 | return ['-bsf:v', 'mjpeg2jpeg'] | |
846 | return [] | |
847 | ||
848 | def convert_thumbnail(self, thumbnail_filename, target_ext): | |
81a23040 | 849 | thumbnail_conv_filename = replace_extension(thumbnail_filename, target_ext) |
337e0c62 | 850 | |
851 | self.to_screen('Converting thumbnail "%s" to %s' % (thumbnail_filename, target_ext)) | |
852 | self.real_run_ffmpeg( | |
853 | [(thumbnail_filename, ['-f', 'image2', '-pattern_type', 'none'])], | |
854 | [(thumbnail_conv_filename.replace('%', '%%'), self._options(target_ext))]) | |
a927acb1 | 855 | return thumbnail_conv_filename |
8fa43c73 | 856 | |
857 | def run(self, info): | |
8fa43c73 | 858 | files_to_delete = [] |
859 | has_thumbnail = False | |
860 | ||
861 | for idx, thumbnail_dict in enumerate(info['thumbnails']): | |
862 | if 'filepath' not in thumbnail_dict: | |
863 | continue | |
864 | has_thumbnail = True | |
865 | self.fixup_webp(info, idx) | |
866 | original_thumbnail = thumbnail_dict['filepath'] | |
867 | _, thumbnail_ext = os.path.splitext(original_thumbnail) | |
868 | if thumbnail_ext: | |
869 | thumbnail_ext = thumbnail_ext[1:].lower() | |
870 | if thumbnail_ext == self.format: | |
871 | self.to_screen('Thumbnail "%s" is already in the requested format' % original_thumbnail) | |
872 | continue | |
873 | thumbnail_dict['filepath'] = self.convert_thumbnail(original_thumbnail, self.format) | |
874 | files_to_delete.append(original_thumbnail) | |
875 | info['__files_to_move'][thumbnail_dict['filepath']] = replace_extension( | |
876 | info['__files_to_move'][original_thumbnail], self.format) | |
877 | ||
878 | if not has_thumbnail: | |
879 | self.to_screen('There aren\'t any thumbnails to convert') | |
880 | return files_to_delete, info |