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