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