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