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