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