]>
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 | ||
8c25f81b | 13 | from ..utils import ( |
f07b74fc | 14 | encodeArgument, |
496c1923 | 15 | encodeFilename, |
95807118 | 16 | get_exe_version, |
48844745 | 17 | is_outdated_version, |
496c1923 PH |
18 | PostProcessingError, |
19 | prepend_extension, | |
20 | shell_quote, | |
21 | subtitles_filename, | |
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): |
48844745 | 237 | self.check_version() |
496c1923 | 238 | |
52afb2ac PH |
239 | oldest_mtime = min( |
240 | os.stat(encodeFilename(path)).st_mtime for path in input_paths) | |
43bc8890 | 241 | |
ce52c7c1 S |
242 | cmd = [encodeFilename(self.executable, True), encodeArgument('-y')] |
243 | # avconv does not have repeat option | |
244 | if self.basename == 'ffmpeg': | |
245 | cmd += [encodeArgument('-loglevel'), encodeArgument('repeat+info')] | |
5b1ecbb3 | 246 | |
247 | def make_args(file, pre=[], post=[], *args, **kwargs): | |
248 | args = pre + self._configuration_args(*args, **kwargs) + post | |
249 | return ( | |
250 | [encodeArgument(o) for o in args] | |
251 | + [encodeFilename(self._ffmpeg_filename_argument(file), True)]) | |
252 | ||
253 | for i, path in enumerate(input_paths): | |
7a5c1cfe | 254 | cmd += make_args(path, post=['-i'], exe='%s_i%d' % (self.basename, i + 1), use_default_arg=False) |
5b1ecbb3 | 255 | cmd += make_args(out_path, pre=opts, exe=self.basename) |
496c1923 | 256 | |
f446cc66 | 257 | self.write_debug('ffmpeg command line: %s' % shell_quote(cmd)) |
cffcbc02 | 258 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) |
f5b1bca9 | 259 | stdout, stderr = process_communicate_or_kill(p) |
496c1923 | 260 | if p.returncode != 0: |
06167fbb | 261 | stderr = stderr.decode('utf-8', 'replace').strip() |
06869367 | 262 | if self.get_param('verbose', False): |
06167fbb | 263 | self.report_error(stderr) |
264 | raise FFmpegPostProcessorError(stderr.split('\n')[-1]) | |
dd29eb7f | 265 | self.try_utime(out_path, oldest_mtime, oldest_mtime) |
06167fbb | 266 | return stderr.decode('utf-8', 'replace') |
cc55d088 | 267 | |
496c1923 | 268 | def run_ffmpeg(self, path, out_path, opts): |
ece8a2a1 | 269 | return self.run_ffmpeg_multiple_files([path], out_path, opts) |
496c1923 PH |
270 | |
271 | def _ffmpeg_filename_argument(self, fn): | |
8a7bbd16 JMF |
272 | # Always use 'file:' because the filename may contain ':' (ffmpeg |
273 | # interprets that as a protocol) or can start with '-' (-- is broken in | |
274 | # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details) | |
b9f2fdd3 | 275 | # Also leave '-' intact in order not to break streaming to stdout. |
06167fbb | 276 | if fn.startswith(('http://', 'https://')): |
277 | return fn | |
d868f43c | 278 | return 'file:' + fn if fn != '-' else fn |
496c1923 PH |
279 | |
280 | ||
281 | class FFmpegExtractAudioPP(FFmpegPostProcessor): | |
1de75fa1 | 282 | COMMON_AUDIO_EXTENSIONS = ('wav', 'flac', 'm4a', 'aiff', 'mp3', 'ogg', 'mka', 'opus', 'wma') |
283 | ||
496c1923 PH |
284 | def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False): |
285 | FFmpegPostProcessor.__init__(self, downloader) | |
286 | if preferredcodec is None: | |
287 | preferredcodec = 'best' | |
288 | self._preferredcodec = preferredcodec | |
289 | self._preferredquality = preferredquality | |
290 | self._nopostoverwrites = nopostoverwrites | |
291 | ||
496c1923 | 292 | def run_ffmpeg(self, path, out_path, codec, more_opts): |
496c1923 PH |
293 | if codec is None: |
294 | acodec_opts = [] | |
295 | else: | |
296 | acodec_opts = ['-acodec', codec] | |
297 | opts = ['-vn'] + acodec_opts + more_opts | |
298 | try: | |
299 | FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts) | |
300 | except FFmpegPostProcessorError as err: | |
301 | raise AudioConversionError(err.msg) | |
302 | ||
303 | def run(self, information): | |
304 | path = information['filepath'] | |
1de75fa1 | 305 | orig_ext = information['ext'] |
306 | ||
307 | if self._preferredcodec == 'best' and orig_ext in self.COMMON_AUDIO_EXTENSIONS: | |
308 | self.to_screen('Skipping audio extraction since the file is already in a common audio format') | |
55b53b33 | 309 | return [], information |
496c1923 PH |
310 | |
311 | filecodec = self.get_audio_codec(path) | |
312 | if filecodec is None: | |
3aa578ca | 313 | raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe') |
496c1923 PH |
314 | |
315 | more_opts = [] | |
316 | if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'): | |
317 | if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']: | |
318 | # Lossless, but in another container | |
319 | acodec = 'copy' | |
320 | extension = 'm4a' | |
467d3c9a | 321 | more_opts = ['-bsf:a', 'aac_adtstoasc'] |
21bfcd3d | 322 | elif filecodec in ['aac', 'flac', 'mp3', 'vorbis', 'opus']: |
496c1923 PH |
323 | # Lossless if possible |
324 | acodec = 'copy' | |
325 | extension = filecodec | |
326 | if filecodec == 'aac': | |
327 | more_opts = ['-f', 'adts'] | |
328 | if filecodec == 'vorbis': | |
329 | extension = 'ogg' | |
330 | else: | |
331 | # MP3 otherwise. | |
332 | acodec = 'libmp3lame' | |
333 | extension = 'mp3' | |
334 | more_opts = [] | |
335 | if self._preferredquality is not None: | |
336 | if int(self._preferredquality) < 10: | |
467d3c9a | 337 | more_opts += ['-q:a', self._preferredquality] |
496c1923 | 338 | else: |
467d3c9a | 339 | more_opts += ['-b:a', self._preferredquality + 'k'] |
496c1923 | 340 | else: |
21bfcd3d PH |
341 | # We convert the audio (lossy if codec is lossy) |
342 | acodec = ACODECS[self._preferredcodec] | |
496c1923 PH |
343 | extension = self._preferredcodec |
344 | more_opts = [] | |
345 | if self._preferredquality is not None: | |
346 | # The opus codec doesn't support the -aq option | |
347 | if int(self._preferredquality) < 10 and extension != 'opus': | |
467d3c9a | 348 | more_opts += ['-q:a', self._preferredquality] |
496c1923 | 349 | else: |
467d3c9a | 350 | more_opts += ['-b:a', self._preferredquality + 'k'] |
496c1923 PH |
351 | if self._preferredcodec == 'aac': |
352 | more_opts += ['-f', 'adts'] | |
353 | if self._preferredcodec == 'm4a': | |
467d3c9a | 354 | more_opts += ['-bsf:a', 'aac_adtstoasc'] |
496c1923 PH |
355 | if self._preferredcodec == 'vorbis': |
356 | extension = 'ogg' | |
357 | if self._preferredcodec == 'wav': | |
358 | extension = 'wav' | |
359 | more_opts += ['-f', 'wav'] | |
360 | ||
3aa578ca | 361 | prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups |
496c1923 | 362 | new_path = prefix + sep + extension |
0b94dbb1 | 363 | |
2273e2c5 PM |
364 | information['filepath'] = new_path |
365 | information['ext'] = extension | |
496c1923 PH |
366 | |
367 | # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly. | |
3089bc74 S |
368 | if (new_path == path |
369 | or (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))): | |
1b77b347 | 370 | self.to_screen('Post-process file %s exists, skipping' % new_path) |
592e97e8 | 371 | return [], information |
496c1923 PH |
372 | |
373 | try: | |
1b77b347 | 374 | self.to_screen('Destination: ' + new_path) |
ce81b141 | 375 | self.run_ffmpeg(path, new_path, acodec, more_opts) |
70a1165b JMF |
376 | except AudioConversionError as e: |
377 | raise PostProcessingError( | |
378 | 'audio conversion failed: ' + e.msg) | |
379 | except Exception: | |
380 | raise PostProcessingError('error running ' + self.basename) | |
496c1923 PH |
381 | |
382 | # Try to update the date time for extracted audio file. | |
383 | if information.get('filetime') is not None: | |
dd29eb7f S |
384 | self.try_utime( |
385 | new_path, time.time(), information['filetime'], | |
386 | errnote='Cannot update utime of audio file') | |
496c1923 | 387 | |
592e97e8 | 388 | return [path], information |
496c1923 PH |
389 | |
390 | ||
efe87a10 FS |
391 | class FFmpegVideoRemuxerPP(FFmpegPostProcessor): |
392 | def __init__(self, downloader=None, preferedformat=None): | |
393 | super(FFmpegVideoRemuxerPP, self).__init__(downloader) | |
06167fbb | 394 | self._preferedformats = preferedformat.lower().split('/') |
efe87a10 FS |
395 | |
396 | def run(self, information): | |
397 | path = information['filepath'] | |
06167fbb | 398 | sourceext, targetext = information['ext'].lower(), None |
399 | for pair in self._preferedformats: | |
400 | kv = pair.split('>') | |
401 | if len(kv) == 1 or kv[0].strip() == sourceext: | |
402 | targetext = kv[-1].strip() | |
403 | break | |
404 | ||
405 | _skip_msg = ( | |
406 | 'could not find a mapping for %s' if not targetext | |
407 | else 'already is in target format %s' if sourceext == targetext | |
408 | else None) | |
409 | if _skip_msg: | |
17912249 | 410 | self.to_screen('Not remuxing media file %s; %s' % (path, _skip_msg % sourceext)) |
efe87a10 | 411 | return [], information |
06167fbb | 412 | |
e0da59fe | 413 | options = ['-c', 'copy', '-map', '0', '-dn'] |
06167fbb | 414 | if targetext in ['mp4', 'm4a', 'mov']: |
415 | options.extend(['-movflags', '+faststart']) | |
416 | prefix, sep, oldext = path.rpartition('.') | |
417 | outpath = prefix + sep + targetext | |
418 | self.to_screen('Remuxing video from %s to %s; Destination: %s' % (sourceext, targetext, outpath)) | |
efe87a10 FS |
419 | self.run_ffmpeg(path, outpath, options) |
420 | information['filepath'] = outpath | |
06167fbb | 421 | information['format'] = targetext |
422 | information['ext'] = targetext | |
efe87a10 FS |
423 | return [path], information |
424 | ||
425 | ||
4f026faf | 426 | class FFmpegVideoConvertorPP(FFmpegPostProcessor): |
5f6a1245 | 427 | def __init__(self, downloader=None, preferedformat=None): |
4f026faf | 428 | super(FFmpegVideoConvertorPP, self).__init__(downloader) |
5f6a1245 | 429 | self._preferedformat = preferedformat |
496c1923 PH |
430 | |
431 | def run(self, information): | |
432 | path = information['filepath'] | |
496c1923 | 433 | if information['ext'] == self._preferedformat: |
1b77b347 | 434 | self.to_screen('Not converting video file %s - already is in target format %s' % (path, self._preferedformat)) |
592e97e8 | 435 | return [], information |
15006fed S |
436 | options = [] |
437 | if self._preferedformat == 'avi': | |
438 | options.extend(['-c:v', 'libxvid', '-vtag', 'XVID']) | |
439 | prefix, sep, ext = path.rpartition('.') | |
440 | outpath = prefix + sep + self._preferedformat | |
1b77b347 | 441 | self.to_screen('Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath) |
d84f1d14 | 442 | self.run_ffmpeg(path, outpath, options) |
496c1923 PH |
443 | information['filepath'] = outpath |
444 | information['format'] = self._preferedformat | |
f72b0a60 | 445 | information['ext'] = self._preferedformat |
592e97e8 | 446 | return [path], information |
496c1923 PH |
447 | |
448 | ||
449 | class FFmpegEmbedSubtitlePP(FFmpegPostProcessor): | |
cffab0ee | 450 | def __init__(self, downloader=None, already_have_subtitle=False): |
451 | super(FFmpegEmbedSubtitlePP, self).__init__(downloader) | |
452 | self._already_have_subtitle = already_have_subtitle | |
453 | ||
496c1923 | 454 | def run(self, information): |
40025ee2 | 455 | if information['ext'] not in ('mp4', 'webm', 'mkv'): |
1b77b347 | 456 | self.to_screen('Subtitles can only be embedded in mp4, webm or mkv files') |
592e97e8 | 457 | return [], information |
c84dd8a9 JMF |
458 | subtitles = information.get('requested_subtitles') |
459 | if not subtitles: | |
1b77b347 | 460 | self.to_screen('There aren\'t any subtitles to embed') |
592e97e8 | 461 | return [], information |
496c1923 | 462 | |
496c1923 | 463 | filename = information['filepath'] |
40025ee2 S |
464 | |
465 | ext = information['ext'] | |
466 | sub_langs = [] | |
467 | sub_filenames = [] | |
468 | webm_vtt_warn = False | |
06167fbb | 469 | mp4_ass_warn = False |
40025ee2 S |
470 | |
471 | for lang, sub_info in subtitles.items(): | |
472 | sub_ext = sub_info['ext'] | |
503d4a44 | 473 | if sub_ext == 'json': |
06167fbb | 474 | self.report_warning('JSON subtitles cannot be embedded') |
503d4a44 | 475 | elif ext != 'webm' or ext == 'webm' and sub_ext == 'vtt': |
40025ee2 | 476 | sub_langs.append(lang) |
824fa511 | 477 | sub_filenames.append(subtitles_filename(filename, lang, sub_ext, ext)) |
40025ee2 S |
478 | else: |
479 | if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt': | |
480 | webm_vtt_warn = True | |
06167fbb | 481 | self.report_warning('Only WebVTT subtitles can be embedded in webm files') |
482 | if not mp4_ass_warn and ext == 'mp4' and sub_ext == 'ass': | |
483 | mp4_ass_warn = True | |
484 | self.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues') | |
40025ee2 S |
485 | |
486 | if not sub_langs: | |
487 | return [], information | |
488 | ||
14523ed9 | 489 | input_files = [filename] + sub_filenames |
496c1923 | 490 | |
e205db3b | 491 | opts = [ |
e0da59fe | 492 | '-c', 'copy', '-map', '0', '-dn', |
e205db3b JMF |
493 | # Don't copy the existing subtitles, we may be running the |
494 | # postprocessor a second time | |
495 | '-map', '-0:s', | |
7f903dd8 T |
496 | # Don't copy Apple TV chapters track, bin_data (see #19042, #19024, |
497 | # https://trac.ffmpeg.org/ticket/6016) | |
498 | '-map', '-0:d', | |
e205db3b | 499 | ] |
083c1bb9 N |
500 | if information['ext'] == 'mp4': |
501 | opts += ['-c:s', 'mov_text'] | |
496c1923 | 502 | for (i, lang) in enumerate(sub_langs): |
2875cf01 | 503 | opts.extend(['-map', '%d:0' % (i + 1)]) |
04fb6928 S |
504 | lang_code = ISO639Utils.short2long(lang) or lang |
505 | opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code]) | |
496c1923 | 506 | |
2875cf01 | 507 | temp_filename = prepend_extension(filename, 'temp') |
06167fbb | 508 | self.to_screen('Embedding subtitles in "%s"' % filename) |
496c1923 PH |
509 | self.run_ffmpeg_multiple_files(input_files, temp_filename, opts) |
510 | os.remove(encodeFilename(filename)) | |
511 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
512 | ||
cffab0ee | 513 | files_to_delete = [] if self._already_have_subtitle else sub_filenames |
514 | return files_to_delete, information | |
496c1923 PH |
515 | |
516 | ||
517 | class FFmpegMetadataPP(FFmpegPostProcessor): | |
518 | def run(self, info): | |
519 | metadata = {} | |
4bd143a3 S |
520 | |
521 | def add(meta_list, info_list=None): | |
522 | if not info_list: | |
523 | info_list = meta_list | |
524 | if not isinstance(meta_list, (list, tuple)): | |
525 | meta_list = (meta_list,) | |
526 | if not isinstance(info_list, (list, tuple)): | |
527 | info_list = (info_list,) | |
528 | for info_f in info_list: | |
529 | if info.get(info_f) is not None: | |
530 | for meta_f in meta_list: | |
531 | metadata[meta_f] = info[info_f] | |
532 | break | |
533 | ||
2791e80b S |
534 | # See [1-4] for some info on media metadata/metadata supported |
535 | # by ffmpeg. | |
536 | # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/ | |
537 | # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata | |
538 | # 3. https://kodi.wiki/view/Video_file_tagging | |
2791e80b | 539 | |
4bd143a3 S |
540 | add('title', ('track', 'title')) |
541 | add('date', 'upload_date') | |
542 | add(('description', 'comment'), 'description') | |
543 | add('purl', 'webpage_url') | |
544 | add('track', 'track_number') | |
545 | add('artist', ('artist', 'creator', 'uploader', 'uploader_id')) | |
546 | add('genre') | |
547 | add('album') | |
548 | add('album_artist') | |
549 | add('disc', 'disc_number') | |
2791e80b S |
550 | add('show', 'series') |
551 | add('season_number') | |
552 | add('episode_id', ('episode', 'episode_id')) | |
553 | add('episode_sort', 'episode_number') | |
496c1923 PH |
554 | |
555 | if not metadata: | |
1b77b347 | 556 | self.to_screen('There isn\'t any metadata to add') |
592e97e8 | 557 | return [], info |
496c1923 PH |
558 | |
559 | filename = info['filepath'] | |
560 | temp_filename = prepend_extension(filename, 'temp') | |
fa2a36d9 | 561 | in_filenames = [filename] |
e0da59fe | 562 | options = ['-map', '0', '-dn'] |
496c1923 | 563 | |
3aa578ca | 564 | if info['ext'] == 'm4a': |
fa2a36d9 | 565 | options.extend(['-vn', '-acodec', 'copy']) |
39c68260 | 566 | else: |
fa2a36d9 | 567 | options.extend(['-c', 'copy']) |
39c68260 | 568 | |
496c1923 PH |
569 | for (name, value) in metadata.items(): |
570 | options.extend(['-metadata', '%s=%s' % (name, value)]) | |
571 | ||
fa2a36d9 | 572 | chapters = info.get('chapters', []) |
573 | if chapters: | |
5192ee17 | 574 | metadata_filename = replace_extension(filename, 'meta') |
fa2a36d9 | 575 | with io.open(metadata_filename, 'wt', encoding='utf-8') as f: |
576 | def ffmpeg_escape(text): | |
577 | return re.sub(r'(=|;|#|\\|\n)', r'\\\1', text) | |
578 | ||
579 | metadata_file_content = ';FFMETADATA1\n' | |
580 | for chapter in chapters: | |
581 | metadata_file_content += '[CHAPTER]\nTIMEBASE=1/1000\n' | |
582 | metadata_file_content += 'START=%d\n' % (chapter['start_time'] * 1000) | |
583 | metadata_file_content += 'END=%d\n' % (chapter['end_time'] * 1000) | |
584 | chapter_title = chapter.get('title') | |
585 | if chapter_title: | |
586 | metadata_file_content += 'title=%s\n' % ffmpeg_escape(chapter_title) | |
587 | f.write(metadata_file_content) | |
588 | in_filenames.append(metadata_filename) | |
589 | options.extend(['-map_metadata', '1']) | |
590 | ||
de6000d9 | 591 | if '__infojson_filename' in info and info['ext'] in ('mkv', 'mka'): |
06167fbb | 592 | old_stream, new_stream = self.get_stream_number( |
593 | filename, ('tags', 'mimetype'), 'application/json') | |
594 | if old_stream is not None: | |
595 | options.extend(['-map', '-0:%d' % old_stream]) | |
596 | new_stream -= 1 | |
597 | ||
598 | options.extend([ | |
de6000d9 | 599 | '-attach', info['__infojson_filename'], |
06167fbb | 600 | '-metadata:s:%d' % new_stream, 'mimetype=application/json' |
601 | ]) | |
602 | ||
1b77b347 | 603 | self.to_screen('Adding metadata to \'%s\'' % filename) |
fa2a36d9 | 604 | self.run_ffmpeg_multiple_files(in_filenames, temp_filename, options) |
605 | if chapters: | |
606 | os.remove(metadata_filename) | |
496c1923 PH |
607 | os.remove(encodeFilename(filename)) |
608 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
592e97e8 | 609 | return [], info |
496c1923 PH |
610 | |
611 | ||
612 | class FFmpegMergerPP(FFmpegPostProcessor): | |
613 | def run(self, info): | |
614 | filename = info['filepath'] | |
5b5fbc08 | 615 | temp_filename = prepend_extension(filename, 'temp') |
d03cfdce | 616 | args = ['-c', 'copy'] |
617 | for (i, fmt) in enumerate(info['requested_formats']): | |
618 | if fmt.get('acodec') != 'none': | |
619 | args.extend(['-map', '%u:a:0' % (i)]) | |
620 | if fmt.get('vcodec') != 'none': | |
621 | args.extend(['-map', '%u:v:0' % (i)]) | |
1b77b347 | 622 | self.to_screen('Merging formats into "%s"' % filename) |
5b5fbc08 JMF |
623 | self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args) |
624 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
d47aeb22 | 625 | return info['__files_to_merge'], info |
496c1923 | 626 | |
13763ce5 S |
627 | def can_merge(self): |
628 | # TODO: figure out merge-capable ffmpeg version | |
629 | if self.basename != 'avconv': | |
630 | return True | |
631 | ||
632 | required_version = '10-0' | |
633 | if is_outdated_version( | |
634 | self._versions[self.basename], required_version): | |
635 | warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, ' | |
7a5c1cfe | 636 | 'yt-dlp will download single file media. ' |
13763ce5 S |
637 | 'Update %s to version %s or newer to fix this.') % ( |
638 | self.basename, self.basename, required_version) | |
f446cc66 | 639 | self.report_warning(warning) |
13763ce5 S |
640 | return False |
641 | return True | |
642 | ||
0c14e2fb | 643 | |
6271f1ca PH |
644 | class FFmpegFixupStretchedPP(FFmpegPostProcessor): |
645 | def run(self, info): | |
646 | stretched_ratio = info.get('stretched_ratio') | |
647 | if stretched_ratio is None or stretched_ratio == 1: | |
592e97e8 | 648 | return [], info |
6271f1ca PH |
649 | |
650 | filename = info['filepath'] | |
651 | temp_filename = prepend_extension(filename, 'temp') | |
652 | ||
e0da59fe | 653 | options = ['-c', 'copy', '-map', '0', '-dn', '-aspect', '%f' % stretched_ratio] |
1b77b347 | 654 | self.to_screen('Fixing aspect ratio in "%s"' % filename) |
6271f1ca PH |
655 | self.run_ffmpeg(filename, temp_filename, options) |
656 | ||
657 | os.remove(encodeFilename(filename)) | |
658 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
659 | ||
592e97e8 | 660 | return [], info |
62cd676c PH |
661 | |
662 | ||
663 | class FFmpegFixupM4aPP(FFmpegPostProcessor): | |
664 | def run(self, info): | |
665 | if info.get('container') != 'm4a_dash': | |
592e97e8 | 666 | return [], info |
62cd676c PH |
667 | |
668 | filename = info['filepath'] | |
669 | temp_filename = prepend_extension(filename, 'temp') | |
670 | ||
e0da59fe | 671 | options = ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4'] |
1b77b347 | 672 | self.to_screen('Correcting container in "%s"' % filename) |
62cd676c PH |
673 | self.run_ffmpeg(filename, temp_filename, options) |
674 | ||
675 | os.remove(encodeFilename(filename)) | |
676 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
677 | ||
592e97e8 | 678 | return [], info |
e9fade72 JMF |
679 | |
680 | ||
f17f8651 | 681 | class FFmpegFixupM3u8PP(FFmpegPostProcessor): |
682 | def run(self, info): | |
683 | filename = info['filepath'] | |
30d9e209 RA |
684 | if self.get_audio_codec(filename) == 'aac': |
685 | temp_filename = prepend_extension(filename, 'temp') | |
f17f8651 | 686 | |
e0da59fe | 687 | options = ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc'] |
1b77b347 | 688 | self.to_screen('Fixing malformed AAC bitstream in "%s"' % filename) |
30d9e209 | 689 | self.run_ffmpeg(filename, temp_filename, options) |
f17f8651 | 690 | |
30d9e209 RA |
691 | os.remove(encodeFilename(filename)) |
692 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
f17f8651 | 693 | return [], info |
694 | ||
695 | ||
e9fade72 JMF |
696 | class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor): |
697 | def __init__(self, downloader=None, format=None): | |
698 | super(FFmpegSubtitlesConvertorPP, self).__init__(downloader) | |
699 | self.format = format | |
700 | ||
701 | def run(self, info): | |
702 | subs = info.get('requested_subtitles') | |
703 | filename = info['filepath'] | |
704 | new_ext = self.format | |
705 | new_format = new_ext | |
706 | if new_format == 'vtt': | |
707 | new_format = 'webvtt' | |
708 | if subs is None: | |
1b77b347 | 709 | self.to_screen('There aren\'t any subtitles to convert') |
592e97e8 | 710 | return [], info |
1b77b347 | 711 | self.to_screen('Converting subtitles') |
e04398e3 | 712 | sub_filenames = [] |
e9fade72 JMF |
713 | for lang, sub in subs.items(): |
714 | ext = sub['ext'] | |
715 | if ext == new_ext: | |
1b77b347 | 716 | self.to_screen('Subtitle file for %s is already in the requested format' % new_ext) |
e9fade72 | 717 | continue |
503d4a44 | 718 | elif ext == 'json': |
1b77b347 | 719 | self.to_screen( |
720 | 'You have requested to convert json subtitles into another format, ' | |
503d4a44 | 721 | 'which is currently not possible') |
722 | continue | |
824fa511 | 723 | old_file = subtitles_filename(filename, lang, ext, info.get('ext')) |
e04398e3 | 724 | sub_filenames.append(old_file) |
824fa511 | 725 | new_file = subtitles_filename(filename, lang, new_ext, info.get('ext')) |
bf6427d2 | 726 | |
40fcba5e | 727 | if ext in ('dfxp', 'ttml', 'tt'): |
f446cc66 | 728 | self.report_warning( |
1b77b347 | 729 | 'You have requested to convert dfxp (TTML) subtitles into another format, ' |
bf6427d2 YCH |
730 | 'which results in style information loss') |
731 | ||
e04398e3 | 732 | dfxp_file = old_file |
824fa511 | 733 | srt_file = subtitles_filename(filename, lang, 'srt', info.get('ext')) |
bf6427d2 | 734 | |
3869028f | 735 | with open(dfxp_file, 'rb') as f: |
bf6427d2 YCH |
736 | srt_data = dfxp2srt(f.read()) |
737 | ||
738 | with io.open(srt_file, 'wt', encoding='utf-8') as f: | |
739 | f.write(srt_data) | |
7e62c2eb | 740 | old_file = srt_file |
bf6427d2 | 741 | |
bf6427d2 YCH |
742 | subs[lang] = { |
743 | 'ext': 'srt', | |
744 | 'data': srt_data | |
745 | } | |
746 | ||
747 | if new_ext == 'srt': | |
748 | continue | |
7b8b007c JMF |
749 | else: |
750 | sub_filenames.append(srt_file) | |
bf6427d2 | 751 | |
e04398e3 | 752 | self.run_ffmpeg(old_file, new_file, ['-f', new_format]) |
e9fade72 JMF |
753 | |
754 | with io.open(new_file, 'rt', encoding='utf-8') as f: | |
755 | subs[lang] = { | |
3547d265 | 756 | 'ext': new_ext, |
e9fade72 JMF |
757 | 'data': f.read(), |
758 | } | |
759 | ||
e04398e3 | 760 | return sub_filenames, info |