]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/postprocessor/ffmpeg.py
debian/watch: Make use of the signing key from upstream.
[youtubedl] / youtube_dl / postprocessor / ffmpeg.py
1 import os
2 import subprocess
3 import sys
4 import time
5
6
7 from .common import AudioConversionError, PostProcessor
8
9 from ..utils import (
10 check_executable,
11 compat_subprocess_get_DEVNULL,
12 encodeArgument,
13 encodeFilename,
14 PostProcessingError,
15 prepend_extension,
16 shell_quote,
17 subtitles_filename,
18 )
19
20
21
22 class FFmpegPostProcessorError(PostProcessingError):
23 pass
24
25 class FFmpegPostProcessor(PostProcessor):
26 def __init__(self,downloader=None):
27 PostProcessor.__init__(self, downloader)
28 self._exes = self.detect_executables()
29
30 @staticmethod
31 def detect_executables():
32 programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
33 return dict((program, check_executable(program, ['-version'])) for program in programs)
34
35 def _get_executable(self):
36 if self._downloader.params.get('prefer_ffmpeg', False):
37 return self._exes['ffmpeg'] or self._exes['avconv']
38 else:
39 return self._exes['avconv'] or self._exes['ffmpeg']
40
41 def _uses_avconv(self):
42 return self._get_executable() == self._exes['avconv']
43
44 def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
45 if not self._get_executable():
46 raise FFmpegPostProcessorError(u'ffmpeg or avconv not found. Please install one.')
47
48 files_cmd = []
49 for path in input_paths:
50 files_cmd.extend(['-i', encodeFilename(path, True)])
51 cmd = ([self._get_executable(), '-y'] + files_cmd
52 + [encodeArgument(o) for o in opts] +
53 [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
54
55 if self._downloader.params.get('verbose', False):
56 self._downloader.to_screen(u'[debug] ffmpeg command line: %s' % shell_quote(cmd))
57 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
58 stdout, stderr = p.communicate()
59 if p.returncode != 0:
60 stderr = stderr.decode('utf-8', 'replace')
61 msg = stderr.strip().split('\n')[-1]
62 raise FFmpegPostProcessorError(msg)
63
64 def run_ffmpeg(self, path, out_path, opts):
65 self.run_ffmpeg_multiple_files([path], out_path, opts)
66
67 def _ffmpeg_filename_argument(self, fn):
68 # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
69 if fn.startswith(u'-'):
70 return u'./' + fn
71 return fn
72
73
74 class FFmpegExtractAudioPP(FFmpegPostProcessor):
75 def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
76 FFmpegPostProcessor.__init__(self, downloader)
77 if preferredcodec is None:
78 preferredcodec = 'best'
79 self._preferredcodec = preferredcodec
80 self._preferredquality = preferredquality
81 self._nopostoverwrites = nopostoverwrites
82
83 def get_audio_codec(self, path):
84 if not self._exes['ffprobe'] and not self._exes['avprobe']:
85 raise PostProcessingError(u'ffprobe or avprobe not found. Please install one.')
86 try:
87 cmd = [
88 self._exes['avprobe'] or self._exes['ffprobe'],
89 '-show_streams',
90 encodeFilename(self._ffmpeg_filename_argument(path), True)]
91 handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE)
92 output = handle.communicate()[0]
93 if handle.wait() != 0:
94 return None
95 except (IOError, OSError):
96 return None
97 audio_codec = None
98 for line in output.decode('ascii', 'ignore').split('\n'):
99 if line.startswith('codec_name='):
100 audio_codec = line.split('=')[1].strip()
101 elif line.strip() == 'codec_type=audio' and audio_codec is not None:
102 return audio_codec
103 return None
104
105 def run_ffmpeg(self, path, out_path, codec, more_opts):
106 if codec is None:
107 acodec_opts = []
108 else:
109 acodec_opts = ['-acodec', codec]
110 opts = ['-vn'] + acodec_opts + more_opts
111 try:
112 FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
113 except FFmpegPostProcessorError as err:
114 raise AudioConversionError(err.msg)
115
116 def run(self, information):
117 path = information['filepath']
118
119 filecodec = self.get_audio_codec(path)
120 if filecodec is None:
121 raise PostProcessingError(u'WARNING: unable to obtain file audio codec with ffprobe')
122
123 uses_avconv = self._uses_avconv()
124 more_opts = []
125 if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
126 if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
127 # Lossless, but in another container
128 acodec = 'copy'
129 extension = 'm4a'
130 more_opts = ['-bsf:a' if uses_avconv else '-absf', 'aac_adtstoasc']
131 elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
132 # Lossless if possible
133 acodec = 'copy'
134 extension = filecodec
135 if filecodec == 'aac':
136 more_opts = ['-f', 'adts']
137 if filecodec == 'vorbis':
138 extension = 'ogg'
139 else:
140 # MP3 otherwise.
141 acodec = 'libmp3lame'
142 extension = 'mp3'
143 more_opts = []
144 if self._preferredquality is not None:
145 if int(self._preferredquality) < 10:
146 more_opts += ['-q:a' if uses_avconv else '-aq', self._preferredquality]
147 else:
148 more_opts += ['-b:a' if uses_avconv else '-ab', self._preferredquality + 'k']
149 else:
150 # We convert the audio (lossy)
151 acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
152 extension = self._preferredcodec
153 more_opts = []
154 if self._preferredquality is not None:
155 # The opus codec doesn't support the -aq option
156 if int(self._preferredquality) < 10 and extension != 'opus':
157 more_opts += ['-q:a' if uses_avconv else '-aq', self._preferredquality]
158 else:
159 more_opts += ['-b:a' if uses_avconv else '-ab', self._preferredquality + 'k']
160 if self._preferredcodec == 'aac':
161 more_opts += ['-f', 'adts']
162 if self._preferredcodec == 'm4a':
163 more_opts += ['-bsf:a' if uses_avconv else '-absf', 'aac_adtstoasc']
164 if self._preferredcodec == 'vorbis':
165 extension = 'ogg'
166 if self._preferredcodec == 'wav':
167 extension = 'wav'
168 more_opts += ['-f', 'wav']
169
170 prefix, sep, ext = path.rpartition(u'.') # not os.path.splitext, since the latter does not work on unicode in all setups
171 new_path = prefix + sep + extension
172
173 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
174 if new_path == path:
175 self._nopostoverwrites = True
176
177 try:
178 if self._nopostoverwrites and os.path.exists(encodeFilename(new_path)):
179 self._downloader.to_screen(u'[youtube] Post-process file %s exists, skipping' % new_path)
180 else:
181 self._downloader.to_screen(u'[' + self._get_executable() + '] Destination: ' + new_path)
182 self.run_ffmpeg(path, new_path, acodec, more_opts)
183 except:
184 etype,e,tb = sys.exc_info()
185 if isinstance(e, AudioConversionError):
186 msg = u'audio conversion failed: ' + e.msg
187 else:
188 msg = u'error running ' + self._get_executable()
189 raise PostProcessingError(msg)
190
191 # Try to update the date time for extracted audio file.
192 if information.get('filetime') is not None:
193 try:
194 os.utime(encodeFilename(new_path), (time.time(), information['filetime']))
195 except:
196 self._downloader.report_warning(u'Cannot update utime of audio file')
197
198 information['filepath'] = new_path
199 return self._nopostoverwrites,information
200
201
202 class FFmpegVideoConvertor(FFmpegPostProcessor):
203 def __init__(self, downloader=None,preferedformat=None):
204 super(FFmpegVideoConvertor, self).__init__(downloader)
205 self._preferedformat=preferedformat
206
207 def run(self, information):
208 path = information['filepath']
209 prefix, sep, ext = path.rpartition(u'.')
210 outpath = prefix + sep + self._preferedformat
211 if information['ext'] == self._preferedformat:
212 self._downloader.to_screen(u'[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
213 return True,information
214 self._downloader.to_screen(u'['+'ffmpeg'+'] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) +outpath)
215 self.run_ffmpeg(path, outpath, [])
216 information['filepath'] = outpath
217 information['format'] = self._preferedformat
218 information['ext'] = self._preferedformat
219 return False,information
220
221
222 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
223 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
224 _lang_map = {
225 'aa': 'aar',
226 'ab': 'abk',
227 'ae': 'ave',
228 'af': 'afr',
229 'ak': 'aka',
230 'am': 'amh',
231 'an': 'arg',
232 'ar': 'ara',
233 'as': 'asm',
234 'av': 'ava',
235 'ay': 'aym',
236 'az': 'aze',
237 'ba': 'bak',
238 'be': 'bel',
239 'bg': 'bul',
240 'bh': 'bih',
241 'bi': 'bis',
242 'bm': 'bam',
243 'bn': 'ben',
244 'bo': 'bod',
245 'br': 'bre',
246 'bs': 'bos',
247 'ca': 'cat',
248 'ce': 'che',
249 'ch': 'cha',
250 'co': 'cos',
251 'cr': 'cre',
252 'cs': 'ces',
253 'cu': 'chu',
254 'cv': 'chv',
255 'cy': 'cym',
256 'da': 'dan',
257 'de': 'deu',
258 'dv': 'div',
259 'dz': 'dzo',
260 'ee': 'ewe',
261 'el': 'ell',
262 'en': 'eng',
263 'eo': 'epo',
264 'es': 'spa',
265 'et': 'est',
266 'eu': 'eus',
267 'fa': 'fas',
268 'ff': 'ful',
269 'fi': 'fin',
270 'fj': 'fij',
271 'fo': 'fao',
272 'fr': 'fra',
273 'fy': 'fry',
274 'ga': 'gle',
275 'gd': 'gla',
276 'gl': 'glg',
277 'gn': 'grn',
278 'gu': 'guj',
279 'gv': 'glv',
280 'ha': 'hau',
281 'he': 'heb',
282 'hi': 'hin',
283 'ho': 'hmo',
284 'hr': 'hrv',
285 'ht': 'hat',
286 'hu': 'hun',
287 'hy': 'hye',
288 'hz': 'her',
289 'ia': 'ina',
290 'id': 'ind',
291 'ie': 'ile',
292 'ig': 'ibo',
293 'ii': 'iii',
294 'ik': 'ipk',
295 'io': 'ido',
296 'is': 'isl',
297 'it': 'ita',
298 'iu': 'iku',
299 'ja': 'jpn',
300 'jv': 'jav',
301 'ka': 'kat',
302 'kg': 'kon',
303 'ki': 'kik',
304 'kj': 'kua',
305 'kk': 'kaz',
306 'kl': 'kal',
307 'km': 'khm',
308 'kn': 'kan',
309 'ko': 'kor',
310 'kr': 'kau',
311 'ks': 'kas',
312 'ku': 'kur',
313 'kv': 'kom',
314 'kw': 'cor',
315 'ky': 'kir',
316 'la': 'lat',
317 'lb': 'ltz',
318 'lg': 'lug',
319 'li': 'lim',
320 'ln': 'lin',
321 'lo': 'lao',
322 'lt': 'lit',
323 'lu': 'lub',
324 'lv': 'lav',
325 'mg': 'mlg',
326 'mh': 'mah',
327 'mi': 'mri',
328 'mk': 'mkd',
329 'ml': 'mal',
330 'mn': 'mon',
331 'mr': 'mar',
332 'ms': 'msa',
333 'mt': 'mlt',
334 'my': 'mya',
335 'na': 'nau',
336 'nb': 'nob',
337 'nd': 'nde',
338 'ne': 'nep',
339 'ng': 'ndo',
340 'nl': 'nld',
341 'nn': 'nno',
342 'no': 'nor',
343 'nr': 'nbl',
344 'nv': 'nav',
345 'ny': 'nya',
346 'oc': 'oci',
347 'oj': 'oji',
348 'om': 'orm',
349 'or': 'ori',
350 'os': 'oss',
351 'pa': 'pan',
352 'pi': 'pli',
353 'pl': 'pol',
354 'ps': 'pus',
355 'pt': 'por',
356 'qu': 'que',
357 'rm': 'roh',
358 'rn': 'run',
359 'ro': 'ron',
360 'ru': 'rus',
361 'rw': 'kin',
362 'sa': 'san',
363 'sc': 'srd',
364 'sd': 'snd',
365 'se': 'sme',
366 'sg': 'sag',
367 'si': 'sin',
368 'sk': 'slk',
369 'sl': 'slv',
370 'sm': 'smo',
371 'sn': 'sna',
372 'so': 'som',
373 'sq': 'sqi',
374 'sr': 'srp',
375 'ss': 'ssw',
376 'st': 'sot',
377 'su': 'sun',
378 'sv': 'swe',
379 'sw': 'swa',
380 'ta': 'tam',
381 'te': 'tel',
382 'tg': 'tgk',
383 'th': 'tha',
384 'ti': 'tir',
385 'tk': 'tuk',
386 'tl': 'tgl',
387 'tn': 'tsn',
388 'to': 'ton',
389 'tr': 'tur',
390 'ts': 'tso',
391 'tt': 'tat',
392 'tw': 'twi',
393 'ty': 'tah',
394 'ug': 'uig',
395 'uk': 'ukr',
396 'ur': 'urd',
397 'uz': 'uzb',
398 've': 'ven',
399 'vi': 'vie',
400 'vo': 'vol',
401 'wa': 'wln',
402 'wo': 'wol',
403 'xh': 'xho',
404 'yi': 'yid',
405 'yo': 'yor',
406 'za': 'zha',
407 'zh': 'zho',
408 'zu': 'zul',
409 }
410
411 def __init__(self, downloader=None, subtitlesformat='srt'):
412 super(FFmpegEmbedSubtitlePP, self).__init__(downloader)
413 self._subformat = subtitlesformat
414
415 @classmethod
416 def _conver_lang_code(cls, code):
417 """Convert language code from ISO 639-1 to ISO 639-2/T"""
418 return cls._lang_map.get(code[:2])
419
420 def run(self, information):
421 if information['ext'] != u'mp4':
422 self._downloader.to_screen(u'[ffmpeg] Subtitles can only be embedded in mp4 files')
423 return True, information
424 if not information.get('subtitles'):
425 self._downloader.to_screen(u'[ffmpeg] There aren\'t any subtitles to embed')
426 return True, information
427
428 sub_langs = [key for key in information['subtitles']]
429 filename = information['filepath']
430 input_files = [filename] + [subtitles_filename(filename, lang, self._subformat) for lang in sub_langs]
431
432 opts = ['-map', '0:0', '-map', '0:1', '-c:v', 'copy', '-c:a', 'copy']
433 for (i, lang) in enumerate(sub_langs):
434 opts.extend(['-map', '%d:0' % (i+1), '-c:s:%d' % i, 'mov_text'])
435 lang_code = self._conver_lang_code(lang)
436 if lang_code is not None:
437 opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
438 opts.extend(['-f', 'mp4'])
439
440 temp_filename = filename + u'.temp'
441 self._downloader.to_screen(u'[ffmpeg] Embedding subtitles in \'%s\'' % filename)
442 self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
443 os.remove(encodeFilename(filename))
444 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
445
446 return True, information
447
448
449 class FFmpegMetadataPP(FFmpegPostProcessor):
450 def run(self, info):
451 metadata = {}
452 if info.get('title') is not None:
453 metadata['title'] = info['title']
454 if info.get('upload_date') is not None:
455 metadata['date'] = info['upload_date']
456 if info.get('uploader') is not None:
457 metadata['artist'] = info['uploader']
458 elif info.get('uploader_id') is not None:
459 metadata['artist'] = info['uploader_id']
460
461 if not metadata:
462 self._downloader.to_screen(u'[ffmpeg] There isn\'t any metadata to add')
463 return True, info
464
465 filename = info['filepath']
466 temp_filename = prepend_extension(filename, 'temp')
467
468 if info['ext'] == u'm4a':
469 options = ['-vn', '-acodec', 'copy']
470 else:
471 options = ['-c', 'copy']
472
473 for (name, value) in metadata.items():
474 options.extend(['-metadata', '%s=%s' % (name, value)])
475
476 self._downloader.to_screen(u'[ffmpeg] Adding metadata to \'%s\'' % filename)
477 self.run_ffmpeg(filename, temp_filename, options)
478 os.remove(encodeFilename(filename))
479 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
480 return True, info
481
482
483 class FFmpegMergerPP(FFmpegPostProcessor):
484 def run(self, info):
485 filename = info['filepath']
486 args = ['-c', 'copy']
487 self._downloader.to_screen(u'[ffmpeg] Merging formats into "%s"' % filename)
488 self.run_ffmpeg_multiple_files(info['__files_to_merge'], filename, args)
489 return True, info
490
491
492 class FFmpegAudioFixPP(FFmpegPostProcessor):
493 def run(self, info):
494 filename = info['filepath']
495 temp_filename = prepend_extension(filename, 'temp')
496
497 options = ['-vn', '-acodec', 'copy']
498 self._downloader.to_screen(u'[ffmpeg] Fixing audio file "%s"' % filename)
499 self.run_ffmpeg(filename, temp_filename, options)
500
501 os.remove(encodeFilename(filename))
502 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
503
504 return True, info