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