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