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