]>
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, |
26 | traverse_dict, | |
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( | |
232 | (i for i, stream in enumerate(streams) if traverse_dict(stream, keys, casesense=False) == value), | |
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 | ||
313 | def run(self, information): | |
314 | path = information['filepath'] | |
1de75fa1 | 315 | orig_ext = information['ext'] |
316 | ||
81a23040 | 317 | if self._preferredcodec == 'best' and orig_ext in self.COMMON_AUDIO_EXTS: |
1de75fa1 | 318 | self.to_screen('Skipping audio extraction since the file is already in a common audio format') |
55b53b33 | 319 | return [], information |
496c1923 PH |
320 | |
321 | filecodec = self.get_audio_codec(path) | |
322 | if filecodec is None: | |
3aa578ca | 323 | raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe') |
496c1923 PH |
324 | |
325 | more_opts = [] | |
326 | if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'): | |
327 | if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']: | |
328 | # Lossless, but in another container | |
329 | acodec = 'copy' | |
330 | extension = 'm4a' | |
467d3c9a | 331 | more_opts = ['-bsf:a', 'aac_adtstoasc'] |
21bfcd3d | 332 | elif filecodec in ['aac', 'flac', 'mp3', 'vorbis', 'opus']: |
496c1923 PH |
333 | # Lossless if possible |
334 | acodec = 'copy' | |
335 | extension = filecodec | |
336 | if filecodec == 'aac': | |
337 | more_opts = ['-f', 'adts'] | |
338 | if filecodec == 'vorbis': | |
339 | extension = 'ogg' | |
340 | else: | |
341 | # MP3 otherwise. | |
342 | acodec = 'libmp3lame' | |
343 | extension = 'mp3' | |
344 | more_opts = [] | |
345 | if self._preferredquality is not None: | |
346 | if int(self._preferredquality) < 10: | |
467d3c9a | 347 | more_opts += ['-q:a', self._preferredquality] |
496c1923 | 348 | else: |
467d3c9a | 349 | more_opts += ['-b:a', self._preferredquality + 'k'] |
496c1923 | 350 | else: |
21bfcd3d PH |
351 | # We convert the audio (lossy if codec is lossy) |
352 | acodec = ACODECS[self._preferredcodec] | |
496c1923 PH |
353 | extension = self._preferredcodec |
354 | more_opts = [] | |
355 | if self._preferredquality is not None: | |
356 | # The opus codec doesn't support the -aq option | |
357 | if int(self._preferredquality) < 10 and extension != 'opus': | |
467d3c9a | 358 | more_opts += ['-q:a', self._preferredquality] |
496c1923 | 359 | else: |
467d3c9a | 360 | more_opts += ['-b:a', self._preferredquality + 'k'] |
496c1923 PH |
361 | if self._preferredcodec == 'aac': |
362 | more_opts += ['-f', 'adts'] | |
363 | if self._preferredcodec == 'm4a': | |
467d3c9a | 364 | more_opts += ['-bsf:a', 'aac_adtstoasc'] |
496c1923 PH |
365 | if self._preferredcodec == 'vorbis': |
366 | extension = 'ogg' | |
367 | if self._preferredcodec == 'wav': | |
368 | extension = 'wav' | |
369 | more_opts += ['-f', 'wav'] | |
370 | ||
3aa578ca | 371 | prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups |
496c1923 | 372 | new_path = prefix + sep + extension |
0b94dbb1 | 373 | |
2273e2c5 PM |
374 | information['filepath'] = new_path |
375 | information['ext'] = extension | |
496c1923 PH |
376 | |
377 | # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly. | |
3089bc74 S |
378 | if (new_path == path |
379 | or (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))): | |
1b77b347 | 380 | self.to_screen('Post-process file %s exists, skipping' % new_path) |
592e97e8 | 381 | return [], information |
496c1923 PH |
382 | |
383 | try: | |
1b77b347 | 384 | self.to_screen('Destination: ' + new_path) |
ce81b141 | 385 | self.run_ffmpeg(path, new_path, acodec, more_opts) |
70a1165b JMF |
386 | except AudioConversionError as e: |
387 | raise PostProcessingError( | |
388 | 'audio conversion failed: ' + e.msg) | |
389 | except Exception: | |
390 | raise PostProcessingError('error running ' + self.basename) | |
496c1923 PH |
391 | |
392 | # Try to update the date time for extracted audio file. | |
393 | if information.get('filetime') is not None: | |
dd29eb7f S |
394 | self.try_utime( |
395 | new_path, time.time(), information['filetime'], | |
396 | errnote='Cannot update utime of audio file') | |
496c1923 | 397 | |
592e97e8 | 398 | return [path], information |
496c1923 PH |
399 | |
400 | ||
857f6313 | 401 | class FFmpegVideoConvertorPP(FFmpegPostProcessor): |
81a23040 | 402 | SUPPORTED_EXTS = ('mp4', 'mkv', 'flv', 'webm', 'mov', 'avi', 'mp3', 'mka', 'm4a', 'ogg', 'opus') |
403 | FORMAT_RE = re.compile(r'{0}(?:/{0})*$'.format(r'(?:\w+>)?(?:%s)' % '|'.join(SUPPORTED_EXTS))) | |
857f6313 | 404 | _action = 'converting' |
405 | ||
efe87a10 | 406 | def __init__(self, downloader=None, preferedformat=None): |
857f6313 | 407 | super(FFmpegVideoConvertorPP, self).__init__(downloader) |
06167fbb | 408 | self._preferedformats = preferedformat.lower().split('/') |
efe87a10 | 409 | |
857f6313 | 410 | def _target_ext(self, source_ext): |
06167fbb | 411 | for pair in self._preferedformats: |
412 | kv = pair.split('>') | |
857f6313 | 413 | if len(kv) == 1 or kv[0].strip() == source_ext: |
414 | return kv[-1].strip() | |
06167fbb | 415 | |
857f6313 | 416 | @staticmethod |
417 | def _options(target_ext): | |
418 | if target_ext == 'avi': | |
419 | return ['-c:v', 'libxvid', '-vtag', 'XVID'] | |
420 | return [] | |
421 | ||
422 | def run(self, information): | |
81a23040 | 423 | path, source_ext = information['filepath'], information['ext'].lower() |
424 | target_ext = self._target_ext(source_ext) | |
06167fbb | 425 | _skip_msg = ( |
857f6313 | 426 | 'could not find a mapping for %s' if not target_ext |
427 | else 'already is in target format %s' if source_ext == target_ext | |
06167fbb | 428 | else None) |
429 | if _skip_msg: | |
81a23040 | 430 | self.to_screen('Not %s media file "%s"; %s' % (self._action, path, _skip_msg % source_ext)) |
efe87a10 | 431 | return [], information |
06167fbb | 432 | |
06167fbb | 433 | prefix, sep, oldext = path.rpartition('.') |
857f6313 | 434 | outpath = prefix + sep + target_ext |
435 | self.to_screen('%s video from %s to %s; Destination: %s' % (self._action.title(), source_ext, target_ext, outpath)) | |
436 | self.run_ffmpeg(path, outpath, self._options(target_ext)) | |
437 | ||
efe87a10 | 438 | information['filepath'] = outpath |
857f6313 | 439 | information['format'] = information['ext'] = target_ext |
efe87a10 FS |
440 | return [path], information |
441 | ||
442 | ||
857f6313 | 443 | class FFmpegVideoRemuxerPP(FFmpegVideoConvertorPP): |
444 | _action = 'remuxing' | |
496c1923 | 445 | |
857f6313 | 446 | @staticmethod |
447 | def _options(target_ext): | |
448 | options = ['-c', 'copy', '-map', '0', '-dn'] | |
449 | if target_ext in ['mp4', 'm4a', 'mov']: | |
450 | options.extend(['-movflags', '+faststart']) | |
451 | return options | |
496c1923 PH |
452 | |
453 | ||
454 | class FFmpegEmbedSubtitlePP(FFmpegPostProcessor): | |
cffab0ee | 455 | def __init__(self, downloader=None, already_have_subtitle=False): |
456 | super(FFmpegEmbedSubtitlePP, self).__init__(downloader) | |
457 | self._already_have_subtitle = already_have_subtitle | |
458 | ||
496c1923 | 459 | def run(self, information): |
40025ee2 | 460 | if information['ext'] not in ('mp4', 'webm', 'mkv'): |
1b77b347 | 461 | self.to_screen('Subtitles can only be embedded in mp4, webm or mkv files') |
592e97e8 | 462 | return [], information |
c84dd8a9 JMF |
463 | subtitles = information.get('requested_subtitles') |
464 | if not subtitles: | |
1b77b347 | 465 | self.to_screen('There aren\'t any subtitles to embed') |
592e97e8 | 466 | return [], information |
496c1923 | 467 | |
496c1923 | 468 | filename = information['filepath'] |
40025ee2 S |
469 | |
470 | ext = information['ext'] | |
2412044c | 471 | sub_langs, sub_names, sub_filenames = [], [], [] |
40025ee2 | 472 | webm_vtt_warn = False |
06167fbb | 473 | mp4_ass_warn = False |
40025ee2 S |
474 | |
475 | for lang, sub_info in subtitles.items(): | |
476 | sub_ext = sub_info['ext'] | |
503d4a44 | 477 | if sub_ext == 'json': |
06167fbb | 478 | self.report_warning('JSON subtitles cannot be embedded') |
503d4a44 | 479 | elif ext != 'webm' or ext == 'webm' and sub_ext == 'vtt': |
40025ee2 | 480 | sub_langs.append(lang) |
2412044c | 481 | sub_names.append(sub_info.get('name')) |
dcf64d43 | 482 | sub_filenames.append(sub_info['filepath']) |
40025ee2 S |
483 | else: |
484 | if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt': | |
485 | webm_vtt_warn = True | |
06167fbb | 486 | self.report_warning('Only WebVTT subtitles can be embedded in webm files') |
487 | if not mp4_ass_warn and ext == 'mp4' and sub_ext == 'ass': | |
488 | mp4_ass_warn = True | |
489 | self.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues') | |
40025ee2 S |
490 | |
491 | if not sub_langs: | |
492 | return [], information | |
493 | ||
14523ed9 | 494 | input_files = [filename] + sub_filenames |
496c1923 | 495 | |
e205db3b | 496 | opts = [ |
e0da59fe | 497 | '-c', 'copy', '-map', '0', '-dn', |
e205db3b JMF |
498 | # Don't copy the existing subtitles, we may be running the |
499 | # postprocessor a second time | |
500 | '-map', '-0:s', | |
7f903dd8 T |
501 | # Don't copy Apple TV chapters track, bin_data (see #19042, #19024, |
502 | # https://trac.ffmpeg.org/ticket/6016) | |
503 | '-map', '-0:d', | |
e205db3b | 504 | ] |
083c1bb9 N |
505 | if information['ext'] == 'mp4': |
506 | opts += ['-c:s', 'mov_text'] | |
2412044c | 507 | for i, (lang, name) in enumerate(zip(sub_langs, sub_names)): |
2875cf01 | 508 | opts.extend(['-map', '%d:0' % (i + 1)]) |
04fb6928 S |
509 | lang_code = ISO639Utils.short2long(lang) or lang |
510 | opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code]) | |
2412044c | 511 | if name: |
512 | opts.extend(['-metadata:s:s:%d' % i, 'handler_name=%s' % name, | |
513 | '-metadata:s:s:%d' % i, 'title=%s' % name]) | |
496c1923 | 514 | |
2875cf01 | 515 | temp_filename = prepend_extension(filename, 'temp') |
06167fbb | 516 | self.to_screen('Embedding subtitles in "%s"' % filename) |
496c1923 PH |
517 | self.run_ffmpeg_multiple_files(input_files, temp_filename, opts) |
518 | os.remove(encodeFilename(filename)) | |
519 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
520 | ||
cffab0ee | 521 | files_to_delete = [] if self._already_have_subtitle else sub_filenames |
522 | return files_to_delete, information | |
496c1923 PH |
523 | |
524 | ||
525 | class FFmpegMetadataPP(FFmpegPostProcessor): | |
526 | def run(self, info): | |
527 | metadata = {} | |
4bd143a3 S |
528 | |
529 | def add(meta_list, info_list=None): | |
84601bb7 | 530 | if not meta_list: |
531 | return | |
4bd143a3 S |
532 | if not info_list: |
533 | info_list = meta_list | |
534 | if not isinstance(meta_list, (list, tuple)): | |
535 | meta_list = (meta_list,) | |
536 | if not isinstance(info_list, (list, tuple)): | |
537 | info_list = (info_list,) | |
538 | for info_f in info_list: | |
84601bb7 | 539 | if isinstance(info.get(info_f), (compat_str, compat_numeric_types)): |
4bd143a3 S |
540 | for meta_f in meta_list: |
541 | metadata[meta_f] = info[info_f] | |
542 | break | |
543 | ||
2791e80b S |
544 | # See [1-4] for some info on media metadata/metadata supported |
545 | # by ffmpeg. | |
546 | # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/ | |
547 | # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata | |
548 | # 3. https://kodi.wiki/view/Video_file_tagging | |
2791e80b | 549 | |
4bd143a3 S |
550 | add('title', ('track', 'title')) |
551 | add('date', 'upload_date') | |
cd9b384c | 552 | add(('description', 'synopsis'), 'description') |
553 | add(('purl', 'comment'), 'webpage_url') | |
4bd143a3 S |
554 | add('track', 'track_number') |
555 | add('artist', ('artist', 'creator', 'uploader', 'uploader_id')) | |
556 | add('genre') | |
557 | add('album') | |
558 | add('album_artist') | |
559 | add('disc', 'disc_number') | |
2791e80b S |
560 | add('show', 'series') |
561 | add('season_number') | |
562 | add('episode_id', ('episode', 'episode_id')) | |
563 | add('episode_sort', 'episode_number') | |
496c1923 | 564 | |
84601bb7 | 565 | prefix = 'meta_' |
566 | for key in filter(lambda k: k.startswith(prefix), info.keys()): | |
567 | add(key[len(prefix):], key) | |
568 | ||
496c1923 | 569 | if not metadata: |
1b77b347 | 570 | self.to_screen('There isn\'t any metadata to add') |
592e97e8 | 571 | return [], info |
496c1923 PH |
572 | |
573 | filename = info['filepath'] | |
574 | temp_filename = prepend_extension(filename, 'temp') | |
fa2a36d9 | 575 | in_filenames = [filename] |
e0da59fe | 576 | options = ['-map', '0', '-dn'] |
496c1923 | 577 | |
3aa578ca | 578 | if info['ext'] == 'm4a': |
fa2a36d9 | 579 | options.extend(['-vn', '-acodec', 'copy']) |
39c68260 | 580 | else: |
fa2a36d9 | 581 | options.extend(['-c', 'copy']) |
39c68260 | 582 | |
84601bb7 | 583 | for name, value in metadata.items(): |
496c1923 PH |
584 | options.extend(['-metadata', '%s=%s' % (name, value)]) |
585 | ||
fa2a36d9 | 586 | chapters = info.get('chapters', []) |
587 | if chapters: | |
5192ee17 | 588 | metadata_filename = replace_extension(filename, 'meta') |
fa2a36d9 | 589 | with io.open(metadata_filename, 'wt', encoding='utf-8') as f: |
590 | def ffmpeg_escape(text): | |
591 | return re.sub(r'(=|;|#|\\|\n)', r'\\\1', text) | |
592 | ||
593 | metadata_file_content = ';FFMETADATA1\n' | |
594 | for chapter in chapters: | |
595 | metadata_file_content += '[CHAPTER]\nTIMEBASE=1/1000\n' | |
596 | metadata_file_content += 'START=%d\n' % (chapter['start_time'] * 1000) | |
597 | metadata_file_content += 'END=%d\n' % (chapter['end_time'] * 1000) | |
598 | chapter_title = chapter.get('title') | |
599 | if chapter_title: | |
600 | metadata_file_content += 'title=%s\n' % ffmpeg_escape(chapter_title) | |
601 | f.write(metadata_file_content) | |
602 | in_filenames.append(metadata_filename) | |
603 | options.extend(['-map_metadata', '1']) | |
604 | ||
41712218 | 605 | if ('no-attach-info-json' not in self.get_param('compat_opts', []) |
606 | and '__infojson_filename' in info and info['ext'] in ('mkv', 'mka')): | |
06167fbb | 607 | old_stream, new_stream = self.get_stream_number( |
608 | filename, ('tags', 'mimetype'), 'application/json') | |
609 | if old_stream is not None: | |
610 | options.extend(['-map', '-0:%d' % old_stream]) | |
611 | new_stream -= 1 | |
612 | ||
613 | options.extend([ | |
de6000d9 | 614 | '-attach', info['__infojson_filename'], |
06167fbb | 615 | '-metadata:s:%d' % new_stream, 'mimetype=application/json' |
616 | ]) | |
617 | ||
1b77b347 | 618 | self.to_screen('Adding metadata to \'%s\'' % filename) |
fa2a36d9 | 619 | self.run_ffmpeg_multiple_files(in_filenames, temp_filename, options) |
620 | if chapters: | |
621 | os.remove(metadata_filename) | |
496c1923 PH |
622 | os.remove(encodeFilename(filename)) |
623 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
592e97e8 | 624 | return [], info |
496c1923 PH |
625 | |
626 | ||
627 | class FFmpegMergerPP(FFmpegPostProcessor): | |
628 | def run(self, info): | |
629 | filename = info['filepath'] | |
5b5fbc08 | 630 | temp_filename = prepend_extension(filename, 'temp') |
d03cfdce | 631 | args = ['-c', 'copy'] |
632 | for (i, fmt) in enumerate(info['requested_formats']): | |
633 | if fmt.get('acodec') != 'none': | |
634 | args.extend(['-map', '%u:a:0' % (i)]) | |
635 | if fmt.get('vcodec') != 'none': | |
636 | args.extend(['-map', '%u:v:0' % (i)]) | |
1b77b347 | 637 | self.to_screen('Merging formats into "%s"' % filename) |
5b5fbc08 JMF |
638 | self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args) |
639 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
d47aeb22 | 640 | return info['__files_to_merge'], info |
496c1923 | 641 | |
13763ce5 S |
642 | def can_merge(self): |
643 | # TODO: figure out merge-capable ffmpeg version | |
644 | if self.basename != 'avconv': | |
645 | return True | |
646 | ||
647 | required_version = '10-0' | |
648 | if is_outdated_version( | |
649 | self._versions[self.basename], required_version): | |
650 | warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, ' | |
7a5c1cfe | 651 | 'yt-dlp will download single file media. ' |
13763ce5 S |
652 | 'Update %s to version %s or newer to fix this.') % ( |
653 | self.basename, self.basename, required_version) | |
f446cc66 | 654 | self.report_warning(warning) |
13763ce5 S |
655 | return False |
656 | return True | |
657 | ||
0c14e2fb | 658 | |
6271f1ca PH |
659 | class FFmpegFixupStretchedPP(FFmpegPostProcessor): |
660 | def run(self, info): | |
661 | stretched_ratio = info.get('stretched_ratio') | |
662 | if stretched_ratio is None or stretched_ratio == 1: | |
592e97e8 | 663 | return [], info |
6271f1ca PH |
664 | |
665 | filename = info['filepath'] | |
666 | temp_filename = prepend_extension(filename, 'temp') | |
667 | ||
e0da59fe | 668 | options = ['-c', 'copy', '-map', '0', '-dn', '-aspect', '%f' % stretched_ratio] |
1b77b347 | 669 | self.to_screen('Fixing aspect ratio in "%s"' % filename) |
6271f1ca PH |
670 | self.run_ffmpeg(filename, temp_filename, options) |
671 | ||
672 | os.remove(encodeFilename(filename)) | |
673 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
674 | ||
592e97e8 | 675 | return [], info |
62cd676c PH |
676 | |
677 | ||
678 | class FFmpegFixupM4aPP(FFmpegPostProcessor): | |
679 | def run(self, info): | |
680 | if info.get('container') != 'm4a_dash': | |
592e97e8 | 681 | return [], info |
62cd676c PH |
682 | |
683 | filename = info['filepath'] | |
684 | temp_filename = prepend_extension(filename, 'temp') | |
685 | ||
e0da59fe | 686 | options = ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4'] |
1b77b347 | 687 | self.to_screen('Correcting container in "%s"' % filename) |
62cd676c PH |
688 | self.run_ffmpeg(filename, temp_filename, options) |
689 | ||
690 | os.remove(encodeFilename(filename)) | |
691 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
692 | ||
592e97e8 | 693 | return [], info |
e9fade72 JMF |
694 | |
695 | ||
f17f8651 | 696 | class FFmpegFixupM3u8PP(FFmpegPostProcessor): |
697 | def run(self, info): | |
698 | filename = info['filepath'] | |
30d9e209 RA |
699 | if self.get_audio_codec(filename) == 'aac': |
700 | temp_filename = prepend_extension(filename, 'temp') | |
f17f8651 | 701 | |
e0da59fe | 702 | options = ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc'] |
1b77b347 | 703 | self.to_screen('Fixing malformed AAC bitstream in "%s"' % filename) |
30d9e209 | 704 | self.run_ffmpeg(filename, temp_filename, options) |
f17f8651 | 705 | |
30d9e209 RA |
706 | os.remove(encodeFilename(filename)) |
707 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
f17f8651 | 708 | return [], info |
709 | ||
710 | ||
e9fade72 | 711 | class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor): |
81a23040 | 712 | SUPPORTED_EXTS = ('srt', 'vtt', 'ass', 'lrc') |
713 | ||
e9fade72 JMF |
714 | def __init__(self, downloader=None, format=None): |
715 | super(FFmpegSubtitlesConvertorPP, self).__init__(downloader) | |
716 | self.format = format | |
717 | ||
718 | def run(self, info): | |
719 | subs = info.get('requested_subtitles') | |
e9fade72 JMF |
720 | new_ext = self.format |
721 | new_format = new_ext | |
722 | if new_format == 'vtt': | |
723 | new_format = 'webvtt' | |
724 | if subs is None: | |
1b77b347 | 725 | self.to_screen('There aren\'t any subtitles to convert') |
592e97e8 | 726 | return [], info |
1b77b347 | 727 | self.to_screen('Converting subtitles') |
e04398e3 | 728 | sub_filenames = [] |
e9fade72 JMF |
729 | for lang, sub in subs.items(): |
730 | ext = sub['ext'] | |
731 | if ext == new_ext: | |
1b77b347 | 732 | self.to_screen('Subtitle file for %s is already in the requested format' % new_ext) |
e9fade72 | 733 | continue |
503d4a44 | 734 | elif ext == 'json': |
1b77b347 | 735 | self.to_screen( |
736 | 'You have requested to convert json subtitles into another format, ' | |
503d4a44 | 737 | 'which is currently not possible') |
738 | continue | |
dcf64d43 | 739 | old_file = sub['filepath'] |
e04398e3 | 740 | sub_filenames.append(old_file) |
dcf64d43 | 741 | new_file = replace_extension(old_file, new_ext) |
bf6427d2 | 742 | |
40fcba5e | 743 | if ext in ('dfxp', 'ttml', 'tt'): |
f446cc66 | 744 | self.report_warning( |
1b77b347 | 745 | 'You have requested to convert dfxp (TTML) subtitles into another format, ' |
bf6427d2 YCH |
746 | 'which results in style information loss') |
747 | ||
e04398e3 | 748 | dfxp_file = old_file |
dcf64d43 | 749 | srt_file = replace_extension(old_file, 'srt') |
bf6427d2 | 750 | |
3869028f | 751 | with open(dfxp_file, 'rb') as f: |
bf6427d2 YCH |
752 | srt_data = dfxp2srt(f.read()) |
753 | ||
754 | with io.open(srt_file, 'wt', encoding='utf-8') as f: | |
755 | f.write(srt_data) | |
7e62c2eb | 756 | old_file = srt_file |
bf6427d2 | 757 | |
bf6427d2 YCH |
758 | subs[lang] = { |
759 | 'ext': 'srt', | |
dcf64d43 | 760 | 'data': srt_data, |
761 | 'filepath': srt_file, | |
bf6427d2 YCH |
762 | } |
763 | ||
764 | if new_ext == 'srt': | |
765 | continue | |
7b8b007c JMF |
766 | else: |
767 | sub_filenames.append(srt_file) | |
bf6427d2 | 768 | |
e04398e3 | 769 | self.run_ffmpeg(old_file, new_file, ['-f', new_format]) |
e9fade72 JMF |
770 | |
771 | with io.open(new_file, 'rt', encoding='utf-8') as f: | |
772 | subs[lang] = { | |
3547d265 | 773 | 'ext': new_ext, |
e9fade72 | 774 | 'data': f.read(), |
dcf64d43 | 775 | 'filepath': new_file, |
e9fade72 JMF |
776 | } |
777 | ||
dcf64d43 | 778 | info['__files_to_move'][new_file] = replace_extension( |
779 | info['__files_to_move'][old_file], new_ext) | |
780 | ||
e04398e3 | 781 | return sub_filenames, info |
72755351 | 782 | |
783 | ||
784 | class FFmpegSplitChaptersPP(FFmpegPostProcessor): | |
785 | ||
786 | def _prepare_filename(self, number, chapter, info): | |
787 | info = info.copy() | |
788 | info.update({ | |
789 | 'section_number': number, | |
790 | 'section_title': chapter.get('title'), | |
791 | 'section_start': chapter.get('start_time'), | |
792 | 'section_end': chapter.get('end_time'), | |
793 | }) | |
794 | return self._downloader.prepare_filename(info, 'chapter') | |
795 | ||
796 | def _ffmpeg_args_for_chapter(self, number, chapter, info): | |
797 | destination = self._prepare_filename(number, chapter, info) | |
798 | if not self._downloader._ensure_dir_exists(encodeFilename(destination)): | |
799 | return | |
800 | ||
dcf64d43 | 801 | chapter['filepath'] = destination |
72755351 | 802 | self.to_screen('Chapter %03d; Destination: %s' % (number, destination)) |
803 | return ( | |
804 | destination, | |
805 | ['-ss', compat_str(chapter['start_time']), | |
a94bfd6c | 806 | '-t', compat_str(chapter['end_time'] - chapter['start_time'])]) |
72755351 | 807 | |
808 | def run(self, info): | |
809 | chapters = info.get('chapters') or [] | |
810 | if not chapters: | |
beb4b92a | 811 | self.report_warning('Chapter information is unavailable') |
72755351 | 812 | return [], info |
813 | ||
814 | self.to_screen('Splitting video by chapters; %d chapters found' % len(chapters)) | |
815 | for idx, chapter in enumerate(chapters): | |
816 | destination, opts = self._ffmpeg_args_for_chapter(idx + 1, chapter, info) | |
817 | self.real_run_ffmpeg([(info['filepath'], opts)], [(destination, ['-c', 'copy'])]) | |
818 | return [], info | |
8fa43c73 | 819 | |
820 | ||
821 | class FFmpegThumbnailsConvertorPP(FFmpegPostProcessor): | |
81a23040 | 822 | SUPPORTED_EXTS = ('jpg', 'png') |
823 | ||
8fa43c73 | 824 | def __init__(self, downloader=None, format=None): |
825 | super(FFmpegThumbnailsConvertorPP, self).__init__(downloader) | |
826 | self.format = format | |
827 | ||
828 | @staticmethod | |
829 | def is_webp(path): | |
830 | with open(encodeFilename(path), 'rb') as f: | |
831 | b = f.read(12) | |
832 | return b[0:4] == b'RIFF' and b[8:] == b'WEBP' | |
833 | ||
834 | def fixup_webp(self, info, idx=-1): | |
835 | thumbnail_filename = info['thumbnails'][idx]['filepath'] | |
836 | _, thumbnail_ext = os.path.splitext(thumbnail_filename) | |
837 | if thumbnail_ext: | |
838 | thumbnail_ext = thumbnail_ext[1:].lower() | |
839 | if thumbnail_ext != 'webp' and self.is_webp(thumbnail_filename): | |
840 | self.to_screen('Correcting thumbnail "%s" extension to webp' % thumbnail_filename) | |
841 | webp_filename = replace_extension(thumbnail_filename, 'webp') | |
842 | if os.path.exists(webp_filename): | |
843 | os.remove(webp_filename) | |
844 | os.rename(encodeFilename(thumbnail_filename), encodeFilename(webp_filename)) | |
845 | info['thumbnails'][idx]['filepath'] = webp_filename | |
846 | info['__files_to_move'][webp_filename] = replace_extension( | |
847 | info['__files_to_move'].pop(thumbnail_filename), 'webp') | |
848 | ||
81a23040 | 849 | @staticmethod |
850 | def _options(target_ext): | |
851 | if target_ext == 'jpg': | |
852 | return ['-bsf:v', 'mjpeg2jpeg'] | |
853 | return [] | |
854 | ||
855 | def convert_thumbnail(self, thumbnail_filename, target_ext): | |
81a23040 | 856 | thumbnail_conv_filename = replace_extension(thumbnail_filename, target_ext) |
337e0c62 | 857 | |
858 | self.to_screen('Converting thumbnail "%s" to %s' % (thumbnail_filename, target_ext)) | |
859 | self.real_run_ffmpeg( | |
860 | [(thumbnail_filename, ['-f', 'image2', '-pattern_type', 'none'])], | |
861 | [(thumbnail_conv_filename.replace('%', '%%'), self._options(target_ext))]) | |
a927acb1 | 862 | return thumbnail_conv_filename |
8fa43c73 | 863 | |
864 | def run(self, info): | |
8fa43c73 | 865 | files_to_delete = [] |
866 | has_thumbnail = False | |
867 | ||
868 | for idx, thumbnail_dict in enumerate(info['thumbnails']): | |
869 | if 'filepath' not in thumbnail_dict: | |
870 | continue | |
871 | has_thumbnail = True | |
872 | self.fixup_webp(info, idx) | |
873 | original_thumbnail = thumbnail_dict['filepath'] | |
874 | _, thumbnail_ext = os.path.splitext(original_thumbnail) | |
875 | if thumbnail_ext: | |
876 | thumbnail_ext = thumbnail_ext[1:].lower() | |
877 | if thumbnail_ext == self.format: | |
878 | self.to_screen('Thumbnail "%s" is already in the requested format' % original_thumbnail) | |
879 | continue | |
880 | thumbnail_dict['filepath'] = self.convert_thumbnail(original_thumbnail, self.format) | |
881 | files_to_delete.append(original_thumbnail) | |
882 | info['__files_to_move'][thumbnail_dict['filepath']] = replace_extension( | |
883 | info['__files_to_move'][original_thumbnail], self.format) | |
884 | ||
885 | if not has_thumbnail: | |
886 | self.to_screen('There aren\'t any thumbnails to convert') | |
887 | return files_to_delete, info |