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