7 from .common import AudioConversionError, PostProcessor
10 compat_subprocess_get_DEVNULL,
20 class FFmpegPostProcessorError(PostProcessingError):
23 class FFmpegPostProcessor(PostProcessor):
24 def __init__(self,downloader=None):
25 PostProcessor.__init__(self, downloader)
26 self._exes = self.detect_executables()
29 def detect_executables():
32 subprocess.Popen([exe, '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
36 programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
37 return dict((program, executable(program)) for program in programs)
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.')
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
48 [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
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()
55 stderr = stderr.decode('utf-8', 'replace')
56 msg = stderr.strip().split('\n')[-1]
57 raise FFmpegPostProcessorError(msg)
59 def run_ffmpeg(self, path, out_path, opts):
60 self.run_ffmpeg_multiple_files([path], out_path, opts)
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'-'):
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
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.')
83 self._exes['avprobe'] or self._exes['ffprobe'],
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:
90 except (IOError, OSError):
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:
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.')
106 acodec_opts = ['-acodec', codec]
107 opts = ['-vn'] + acodec_opts + more_opts
109 FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
110 except FFmpegPostProcessorError as err:
111 raise AudioConversionError(err.msg)
113 def run(self, information):
114 path = information['filepath']
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')
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
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
130 extension = filecodec
131 if filecodec == 'aac':
132 more_opts = ['-f', 'adts']
133 if filecodec == 'vorbis':
137 acodec = 'libmp3lame'
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]
144 more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality + 'k']
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
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]
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':
162 if self._preferredcodec == 'wav':
164 more_opts += ['-f', 'wav']
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
169 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
171 self._nopostoverwrites = True
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)
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)
180 etype,e,tb = sys.exc_info()
181 if isinstance(e, AudioConversionError):
182 msg = u'audio conversion failed: ' + e.msg
184 msg = u'error running ' + (self._exes['avconv'] and 'avconv' or 'ffmpeg')
185 raise PostProcessingError(msg)
187 # Try to update the date time for extracted audio file.
188 if information.get('filetime') is not None:
190 os.utime(encodeFilename(new_path), (time.time(), information['filetime']))
192 self._downloader.report_warning(u'Cannot update utime of audio file')
194 information['filepath'] = new_path
195 return self._nopostoverwrites,information
198 class FFmpegVideoConvertor(FFmpegPostProcessor):
199 def __init__(self, downloader=None,preferedformat=None):
200 super(FFmpegVideoConvertor, self).__init__(downloader)
201 self._preferedformat=preferedformat
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
218 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
219 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
407 def __init__(self, downloader=None, subtitlesformat='srt'):
408 super(FFmpegEmbedSubtitlePP, self).__init__(downloader)
409 self._subformat = subtitlesformat
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])
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
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]
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'])
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))
442 return True, information
445 class FFmpegMetadataPP(FFmpegPostProcessor):
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']
458 self._downloader.to_screen(u'[ffmpeg] There isn\'t any metadata to add')
461 filename = info['filepath']
462 temp_filename = prepend_extension(filename, 'temp')
464 options = ['-c', 'copy']
465 for (name, value) in metadata.items():
466 options.extend(['-metadata', '%s=%s' % (name, value)])
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))
475 class FFmpegMergerPP(FFmpegPostProcessor):
477 filename = info['filepath']
478 args = ['-c', 'copy']
479 self.run_ffmpeg_multiple_files(info['__files_to_merge'], filename, args)