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