]>
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, | |
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: |
e3b771a8 | 64 | raise FFmpegPostProcessorError('ffmpeg not found. Please install') |
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: |
e3b771a8 | 168 | raise PostProcessingError('ffprobe and ffmpeg not found. Please install') |
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') | |
210 | raise PostProcessingError('ffprobe not found. Please install.') | |
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): | |
1de75fa1 | 293 | COMMON_AUDIO_EXTENSIONS = ('wav', 'flac', 'm4a', 'aiff', 'mp3', 'ogg', 'mka', 'opus', 'wma') |
294 | ||
496c1923 PH |
295 | def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False): |
296 | FFmpegPostProcessor.__init__(self, downloader) | |
297 | if preferredcodec is None: | |
298 | preferredcodec = 'best' | |
299 | self._preferredcodec = preferredcodec | |
300 | self._preferredquality = preferredquality | |
301 | self._nopostoverwrites = nopostoverwrites | |
302 | ||
496c1923 | 303 | def run_ffmpeg(self, path, out_path, codec, more_opts): |
496c1923 PH |
304 | if codec is None: |
305 | acodec_opts = [] | |
306 | else: | |
307 | acodec_opts = ['-acodec', codec] | |
308 | opts = ['-vn'] + acodec_opts + more_opts | |
309 | try: | |
310 | FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts) | |
311 | except FFmpegPostProcessorError as err: | |
312 | raise AudioConversionError(err.msg) | |
313 | ||
314 | def run(self, information): | |
315 | path = information['filepath'] | |
1de75fa1 | 316 | orig_ext = information['ext'] |
317 | ||
318 | if self._preferredcodec == 'best' and orig_ext in self.COMMON_AUDIO_EXTENSIONS: | |
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 | ||
efe87a10 FS |
402 | class FFmpegVideoRemuxerPP(FFmpegPostProcessor): |
403 | def __init__(self, downloader=None, preferedformat=None): | |
404 | super(FFmpegVideoRemuxerPP, self).__init__(downloader) | |
06167fbb | 405 | self._preferedformats = preferedformat.lower().split('/') |
efe87a10 FS |
406 | |
407 | def run(self, information): | |
408 | path = information['filepath'] | |
06167fbb | 409 | sourceext, targetext = information['ext'].lower(), None |
410 | for pair in self._preferedformats: | |
411 | kv = pair.split('>') | |
412 | if len(kv) == 1 or kv[0].strip() == sourceext: | |
413 | targetext = kv[-1].strip() | |
414 | break | |
415 | ||
416 | _skip_msg = ( | |
417 | 'could not find a mapping for %s' if not targetext | |
418 | else 'already is in target format %s' if sourceext == targetext | |
419 | else None) | |
420 | if _skip_msg: | |
17912249 | 421 | self.to_screen('Not remuxing media file %s; %s' % (path, _skip_msg % sourceext)) |
efe87a10 | 422 | return [], information |
06167fbb | 423 | |
e0da59fe | 424 | options = ['-c', 'copy', '-map', '0', '-dn'] |
06167fbb | 425 | if targetext in ['mp4', 'm4a', 'mov']: |
426 | options.extend(['-movflags', '+faststart']) | |
427 | prefix, sep, oldext = path.rpartition('.') | |
428 | outpath = prefix + sep + targetext | |
429 | self.to_screen('Remuxing video from %s to %s; Destination: %s' % (sourceext, targetext, outpath)) | |
efe87a10 FS |
430 | self.run_ffmpeg(path, outpath, options) |
431 | information['filepath'] = outpath | |
06167fbb | 432 | information['format'] = targetext |
433 | information['ext'] = targetext | |
efe87a10 FS |
434 | return [path], information |
435 | ||
436 | ||
4f026faf | 437 | class FFmpegVideoConvertorPP(FFmpegPostProcessor): |
5f6a1245 | 438 | def __init__(self, downloader=None, preferedformat=None): |
4f026faf | 439 | super(FFmpegVideoConvertorPP, self).__init__(downloader) |
5f6a1245 | 440 | self._preferedformat = preferedformat |
496c1923 PH |
441 | |
442 | def run(self, information): | |
443 | path = information['filepath'] | |
496c1923 | 444 | if information['ext'] == self._preferedformat: |
1b77b347 | 445 | self.to_screen('Not converting video file %s - already is in target format %s' % (path, self._preferedformat)) |
592e97e8 | 446 | return [], information |
15006fed S |
447 | options = [] |
448 | if self._preferedformat == 'avi': | |
449 | options.extend(['-c:v', 'libxvid', '-vtag', 'XVID']) | |
450 | prefix, sep, ext = path.rpartition('.') | |
451 | outpath = prefix + sep + self._preferedformat | |
1b77b347 | 452 | self.to_screen('Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath) |
d84f1d14 | 453 | self.run_ffmpeg(path, outpath, options) |
496c1923 PH |
454 | information['filepath'] = outpath |
455 | information['format'] = self._preferedformat | |
f72b0a60 | 456 | information['ext'] = self._preferedformat |
592e97e8 | 457 | return [path], information |
496c1923 PH |
458 | |
459 | ||
460 | class FFmpegEmbedSubtitlePP(FFmpegPostProcessor): | |
cffab0ee | 461 | def __init__(self, downloader=None, already_have_subtitle=False): |
462 | super(FFmpegEmbedSubtitlePP, self).__init__(downloader) | |
463 | self._already_have_subtitle = already_have_subtitle | |
464 | ||
496c1923 | 465 | def run(self, information): |
40025ee2 | 466 | if information['ext'] not in ('mp4', 'webm', 'mkv'): |
1b77b347 | 467 | self.to_screen('Subtitles can only be embedded in mp4, webm or mkv files') |
592e97e8 | 468 | return [], information |
c84dd8a9 JMF |
469 | subtitles = information.get('requested_subtitles') |
470 | if not subtitles: | |
1b77b347 | 471 | self.to_screen('There aren\'t any subtitles to embed') |
592e97e8 | 472 | return [], information |
496c1923 | 473 | |
496c1923 | 474 | filename = information['filepath'] |
40025ee2 S |
475 | |
476 | ext = information['ext'] | |
477 | sub_langs = [] | |
478 | sub_filenames = [] | |
479 | webm_vtt_warn = False | |
06167fbb | 480 | mp4_ass_warn = False |
40025ee2 S |
481 | |
482 | for lang, sub_info in subtitles.items(): | |
483 | sub_ext = sub_info['ext'] | |
503d4a44 | 484 | if sub_ext == 'json': |
06167fbb | 485 | self.report_warning('JSON subtitles cannot be embedded') |
503d4a44 | 486 | elif ext != 'webm' or ext == 'webm' and sub_ext == 'vtt': |
40025ee2 | 487 | sub_langs.append(lang) |
dcf64d43 | 488 | sub_filenames.append(sub_info['filepath']) |
40025ee2 S |
489 | else: |
490 | if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt': | |
491 | webm_vtt_warn = True | |
06167fbb | 492 | self.report_warning('Only WebVTT subtitles can be embedded in webm files') |
493 | if not mp4_ass_warn and ext == 'mp4' and sub_ext == 'ass': | |
494 | mp4_ass_warn = True | |
495 | self.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues') | |
40025ee2 S |
496 | |
497 | if not sub_langs: | |
498 | return [], information | |
499 | ||
14523ed9 | 500 | input_files = [filename] + sub_filenames |
496c1923 | 501 | |
e205db3b | 502 | opts = [ |
e0da59fe | 503 | '-c', 'copy', '-map', '0', '-dn', |
e205db3b JMF |
504 | # Don't copy the existing subtitles, we may be running the |
505 | # postprocessor a second time | |
506 | '-map', '-0:s', | |
7f903dd8 T |
507 | # Don't copy Apple TV chapters track, bin_data (see #19042, #19024, |
508 | # https://trac.ffmpeg.org/ticket/6016) | |
509 | '-map', '-0:d', | |
e205db3b | 510 | ] |
083c1bb9 N |
511 | if information['ext'] == 'mp4': |
512 | opts += ['-c:s', 'mov_text'] | |
496c1923 | 513 | for (i, lang) in enumerate(sub_langs): |
2875cf01 | 514 | opts.extend(['-map', '%d:0' % (i + 1)]) |
04fb6928 S |
515 | lang_code = ISO639Utils.short2long(lang) or lang |
516 | opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code]) | |
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): | |
529 | def run(self, info): | |
530 | metadata = {} | |
4bd143a3 S |
531 | |
532 | def add(meta_list, info_list=None): | |
533 | if not info_list: | |
534 | info_list = meta_list | |
535 | if not isinstance(meta_list, (list, tuple)): | |
536 | meta_list = (meta_list,) | |
537 | if not isinstance(info_list, (list, tuple)): | |
538 | info_list = (info_list,) | |
539 | for info_f in info_list: | |
540 | if info.get(info_f) is not None: | |
541 | for meta_f in meta_list: | |
542 | metadata[meta_f] = info[info_f] | |
543 | break | |
544 | ||
2791e80b S |
545 | # See [1-4] for some info on media metadata/metadata supported |
546 | # by ffmpeg. | |
547 | # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/ | |
548 | # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata | |
549 | # 3. https://kodi.wiki/view/Video_file_tagging | |
2791e80b | 550 | |
4bd143a3 S |
551 | add('title', ('track', 'title')) |
552 | add('date', 'upload_date') | |
cd9b384c | 553 | add(('description', 'synopsis'), 'description') |
554 | add(('purl', 'comment'), 'webpage_url') | |
4bd143a3 S |
555 | add('track', 'track_number') |
556 | add('artist', ('artist', 'creator', 'uploader', 'uploader_id')) | |
557 | add('genre') | |
558 | add('album') | |
559 | add('album_artist') | |
560 | add('disc', 'disc_number') | |
2791e80b S |
561 | add('show', 'series') |
562 | add('season_number') | |
563 | add('episode_id', ('episode', 'episode_id')) | |
564 | add('episode_sort', 'episode_number') | |
496c1923 PH |
565 | |
566 | if not metadata: | |
1b77b347 | 567 | self.to_screen('There isn\'t any metadata to add') |
592e97e8 | 568 | return [], info |
496c1923 PH |
569 | |
570 | filename = info['filepath'] | |
571 | temp_filename = prepend_extension(filename, 'temp') | |
fa2a36d9 | 572 | in_filenames = [filename] |
e0da59fe | 573 | options = ['-map', '0', '-dn'] |
496c1923 | 574 | |
3aa578ca | 575 | if info['ext'] == 'm4a': |
fa2a36d9 | 576 | options.extend(['-vn', '-acodec', 'copy']) |
39c68260 | 577 | else: |
fa2a36d9 | 578 | options.extend(['-c', 'copy']) |
39c68260 | 579 | |
496c1923 PH |
580 | for (name, value) in metadata.items(): |
581 | options.extend(['-metadata', '%s=%s' % (name, value)]) | |
582 | ||
fa2a36d9 | 583 | chapters = info.get('chapters', []) |
584 | if chapters: | |
5192ee17 | 585 | metadata_filename = replace_extension(filename, 'meta') |
fa2a36d9 | 586 | with io.open(metadata_filename, 'wt', encoding='utf-8') as f: |
587 | def ffmpeg_escape(text): | |
588 | return re.sub(r'(=|;|#|\\|\n)', r'\\\1', text) | |
589 | ||
590 | metadata_file_content = ';FFMETADATA1\n' | |
591 | for chapter in chapters: | |
592 | metadata_file_content += '[CHAPTER]\nTIMEBASE=1/1000\n' | |
593 | metadata_file_content += 'START=%d\n' % (chapter['start_time'] * 1000) | |
594 | metadata_file_content += 'END=%d\n' % (chapter['end_time'] * 1000) | |
595 | chapter_title = chapter.get('title') | |
596 | if chapter_title: | |
597 | metadata_file_content += 'title=%s\n' % ffmpeg_escape(chapter_title) | |
598 | f.write(metadata_file_content) | |
599 | in_filenames.append(metadata_filename) | |
600 | options.extend(['-map_metadata', '1']) | |
601 | ||
de6000d9 | 602 | if '__infojson_filename' in info and info['ext'] in ('mkv', 'mka'): |
06167fbb | 603 | old_stream, new_stream = self.get_stream_number( |
604 | filename, ('tags', 'mimetype'), 'application/json') | |
605 | if old_stream is not None: | |
606 | options.extend(['-map', '-0:%d' % old_stream]) | |
607 | new_stream -= 1 | |
608 | ||
609 | options.extend([ | |
de6000d9 | 610 | '-attach', info['__infojson_filename'], |
06167fbb | 611 | '-metadata:s:%d' % new_stream, 'mimetype=application/json' |
612 | ]) | |
613 | ||
1b77b347 | 614 | self.to_screen('Adding metadata to \'%s\'' % filename) |
fa2a36d9 | 615 | self.run_ffmpeg_multiple_files(in_filenames, temp_filename, options) |
616 | if chapters: | |
617 | os.remove(metadata_filename) | |
496c1923 PH |
618 | os.remove(encodeFilename(filename)) |
619 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
592e97e8 | 620 | return [], info |
496c1923 PH |
621 | |
622 | ||
623 | class FFmpegMergerPP(FFmpegPostProcessor): | |
624 | def run(self, info): | |
625 | filename = info['filepath'] | |
5b5fbc08 | 626 | temp_filename = prepend_extension(filename, 'temp') |
d03cfdce | 627 | args = ['-c', 'copy'] |
628 | for (i, fmt) in enumerate(info['requested_formats']): | |
629 | if fmt.get('acodec') != 'none': | |
630 | args.extend(['-map', '%u:a:0' % (i)]) | |
631 | if fmt.get('vcodec') != 'none': | |
632 | args.extend(['-map', '%u:v:0' % (i)]) | |
1b77b347 | 633 | self.to_screen('Merging formats into "%s"' % filename) |
5b5fbc08 JMF |
634 | self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args) |
635 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
d47aeb22 | 636 | return info['__files_to_merge'], info |
496c1923 | 637 | |
13763ce5 S |
638 | def can_merge(self): |
639 | # TODO: figure out merge-capable ffmpeg version | |
640 | if self.basename != 'avconv': | |
641 | return True | |
642 | ||
643 | required_version = '10-0' | |
644 | if is_outdated_version( | |
645 | self._versions[self.basename], required_version): | |
646 | warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, ' | |
7a5c1cfe | 647 | 'yt-dlp will download single file media. ' |
13763ce5 S |
648 | 'Update %s to version %s or newer to fix this.') % ( |
649 | self.basename, self.basename, required_version) | |
f446cc66 | 650 | self.report_warning(warning) |
13763ce5 S |
651 | return False |
652 | return True | |
653 | ||
0c14e2fb | 654 | |
6271f1ca PH |
655 | class FFmpegFixupStretchedPP(FFmpegPostProcessor): |
656 | def run(self, info): | |
657 | stretched_ratio = info.get('stretched_ratio') | |
658 | if stretched_ratio is None or stretched_ratio == 1: | |
592e97e8 | 659 | return [], info |
6271f1ca PH |
660 | |
661 | filename = info['filepath'] | |
662 | temp_filename = prepend_extension(filename, 'temp') | |
663 | ||
e0da59fe | 664 | options = ['-c', 'copy', '-map', '0', '-dn', '-aspect', '%f' % stretched_ratio] |
1b77b347 | 665 | self.to_screen('Fixing aspect ratio in "%s"' % filename) |
6271f1ca PH |
666 | self.run_ffmpeg(filename, temp_filename, options) |
667 | ||
668 | os.remove(encodeFilename(filename)) | |
669 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
670 | ||
592e97e8 | 671 | return [], info |
62cd676c PH |
672 | |
673 | ||
674 | class FFmpegFixupM4aPP(FFmpegPostProcessor): | |
675 | def run(self, info): | |
676 | if info.get('container') != 'm4a_dash': | |
592e97e8 | 677 | return [], info |
62cd676c PH |
678 | |
679 | filename = info['filepath'] | |
680 | temp_filename = prepend_extension(filename, 'temp') | |
681 | ||
e0da59fe | 682 | options = ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4'] |
1b77b347 | 683 | self.to_screen('Correcting container in "%s"' % filename) |
62cd676c PH |
684 | self.run_ffmpeg(filename, temp_filename, options) |
685 | ||
686 | os.remove(encodeFilename(filename)) | |
687 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
688 | ||
592e97e8 | 689 | return [], info |
e9fade72 JMF |
690 | |
691 | ||
f17f8651 | 692 | class FFmpegFixupM3u8PP(FFmpegPostProcessor): |
693 | def run(self, info): | |
694 | filename = info['filepath'] | |
30d9e209 RA |
695 | if self.get_audio_codec(filename) == 'aac': |
696 | temp_filename = prepend_extension(filename, 'temp') | |
f17f8651 | 697 | |
e0da59fe | 698 | options = ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc'] |
1b77b347 | 699 | self.to_screen('Fixing malformed AAC bitstream in "%s"' % filename) |
30d9e209 | 700 | self.run_ffmpeg(filename, temp_filename, options) |
f17f8651 | 701 | |
30d9e209 RA |
702 | os.remove(encodeFilename(filename)) |
703 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
f17f8651 | 704 | return [], info |
705 | ||
706 | ||
e9fade72 JMF |
707 | class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor): |
708 | def __init__(self, downloader=None, format=None): | |
709 | super(FFmpegSubtitlesConvertorPP, self).__init__(downloader) | |
710 | self.format = format | |
711 | ||
712 | def run(self, info): | |
713 | subs = info.get('requested_subtitles') | |
e9fade72 JMF |
714 | new_ext = self.format |
715 | new_format = new_ext | |
716 | if new_format == 'vtt': | |
717 | new_format = 'webvtt' | |
718 | if subs is None: | |
1b77b347 | 719 | self.to_screen('There aren\'t any subtitles to convert') |
592e97e8 | 720 | return [], info |
1b77b347 | 721 | self.to_screen('Converting subtitles') |
e04398e3 | 722 | sub_filenames = [] |
e9fade72 JMF |
723 | for lang, sub in subs.items(): |
724 | ext = sub['ext'] | |
725 | if ext == new_ext: | |
1b77b347 | 726 | self.to_screen('Subtitle file for %s is already in the requested format' % new_ext) |
e9fade72 | 727 | continue |
503d4a44 | 728 | elif ext == 'json': |
1b77b347 | 729 | self.to_screen( |
730 | 'You have requested to convert json subtitles into another format, ' | |
503d4a44 | 731 | 'which is currently not possible') |
732 | continue | |
dcf64d43 | 733 | old_file = sub['filepath'] |
e04398e3 | 734 | sub_filenames.append(old_file) |
dcf64d43 | 735 | new_file = replace_extension(old_file, new_ext) |
bf6427d2 | 736 | |
40fcba5e | 737 | if ext in ('dfxp', 'ttml', 'tt'): |
f446cc66 | 738 | self.report_warning( |
1b77b347 | 739 | 'You have requested to convert dfxp (TTML) subtitles into another format, ' |
bf6427d2 YCH |
740 | 'which results in style information loss') |
741 | ||
e04398e3 | 742 | dfxp_file = old_file |
dcf64d43 | 743 | srt_file = replace_extension(old_file, 'srt') |
bf6427d2 | 744 | |
3869028f | 745 | with open(dfxp_file, 'rb') as f: |
bf6427d2 YCH |
746 | srt_data = dfxp2srt(f.read()) |
747 | ||
748 | with io.open(srt_file, 'wt', encoding='utf-8') as f: | |
749 | f.write(srt_data) | |
7e62c2eb | 750 | old_file = srt_file |
bf6427d2 | 751 | |
bf6427d2 YCH |
752 | subs[lang] = { |
753 | 'ext': 'srt', | |
dcf64d43 | 754 | 'data': srt_data, |
755 | 'filepath': srt_file, | |
bf6427d2 YCH |
756 | } |
757 | ||
758 | if new_ext == 'srt': | |
759 | continue | |
7b8b007c JMF |
760 | else: |
761 | sub_filenames.append(srt_file) | |
bf6427d2 | 762 | |
e04398e3 | 763 | self.run_ffmpeg(old_file, new_file, ['-f', new_format]) |
e9fade72 JMF |
764 | |
765 | with io.open(new_file, 'rt', encoding='utf-8') as f: | |
766 | subs[lang] = { | |
3547d265 | 767 | 'ext': new_ext, |
e9fade72 | 768 | 'data': f.read(), |
dcf64d43 | 769 | 'filepath': new_file, |
e9fade72 JMF |
770 | } |
771 | ||
dcf64d43 | 772 | info['__files_to_move'][new_file] = replace_extension( |
773 | info['__files_to_move'][old_file], new_ext) | |
774 | ||
e04398e3 | 775 | return sub_filenames, info |
72755351 | 776 | |
777 | ||
778 | class FFmpegSplitChaptersPP(FFmpegPostProcessor): | |
779 | ||
780 | def _prepare_filename(self, number, chapter, info): | |
781 | info = info.copy() | |
782 | info.update({ | |
783 | 'section_number': number, | |
784 | 'section_title': chapter.get('title'), | |
785 | 'section_start': chapter.get('start_time'), | |
786 | 'section_end': chapter.get('end_time'), | |
787 | }) | |
788 | return self._downloader.prepare_filename(info, 'chapter') | |
789 | ||
790 | def _ffmpeg_args_for_chapter(self, number, chapter, info): | |
791 | destination = self._prepare_filename(number, chapter, info) | |
792 | if not self._downloader._ensure_dir_exists(encodeFilename(destination)): | |
793 | return | |
794 | ||
dcf64d43 | 795 | chapter['filepath'] = destination |
72755351 | 796 | self.to_screen('Chapter %03d; Destination: %s' % (number, destination)) |
797 | return ( | |
798 | destination, | |
799 | ['-ss', compat_str(chapter['start_time']), | |
a94bfd6c | 800 | '-t', compat_str(chapter['end_time'] - chapter['start_time'])]) |
72755351 | 801 | |
802 | def run(self, info): | |
803 | chapters = info.get('chapters') or [] | |
804 | if not chapters: | |
805 | self.report_warning('There are no tracks to extract') | |
806 | return [], info | |
807 | ||
808 | self.to_screen('Splitting video by chapters; %d chapters found' % len(chapters)) | |
809 | for idx, chapter in enumerate(chapters): | |
810 | destination, opts = self._ffmpeg_args_for_chapter(idx + 1, chapter, info) | |
811 | self.real_run_ffmpeg([(info['filepath'], opts)], [(destination, ['-c', 'copy'])]) | |
812 | return [], info |