8 from .common import AudioConversionError, PostProcessor
12 compat_subprocess_get_DEVNULL,
23 def get_version(executable):
24 """ Returns the version of the specified executable,
25 or False if the executable is not present """
27 out, err = subprocess.Popen(
28 [executable, '-version'],
29 stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
32 firstline = out.partition(b'\n')[0].decode('ascii', 'ignore')
33 m = re.search(r'version\s+([0-9._-a-zA-Z]+)', firstline)
40 class FFmpegPostProcessorError(PostProcessingError):
44 class FFmpegPostProcessor(PostProcessor):
45 def __init__(self, downloader=None, deletetempfiles=False):
46 PostProcessor.__init__(self, downloader)
47 self._versions = self.get_versions()
48 self._deletetempfiles = deletetempfiles
50 def check_version(self):
51 if not self._executable:
52 raise FFmpegPostProcessorError(u'ffmpeg or avconv not found. Please install one.')
54 REQUIRED_VERSION = '1.0'
55 if is_outdated_version(
56 self._versions[self._executable], REQUIRED_VERSION):
57 warning = u'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
58 self._executable, self._executable, REQUIRED_VERSION)
60 self._downloader.report_warning(warning)
64 programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
65 return dict((program, get_version(program)) for program in programs)
68 def _executable(self):
69 if self._downloader.params.get('prefer_ffmpeg', False):
70 prefs = ('ffmpeg', 'avconv')
72 prefs = ('avconv', 'ffmpeg')
79 def _probe_executable(self):
80 if self._downloader.params.get('prefer_ffmpeg', False):
81 prefs = ('ffprobe', 'avprobe')
83 prefs = ('avprobe', 'ffprobe')
89 def _uses_avconv(self):
90 return self._executable == 'avconv'
92 def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
96 for path in input_paths:
97 files_cmd.extend(['-i', encodeFilename(path, True)])
98 cmd = ([self._executable, '-y'] + files_cmd
99 + [encodeArgument(o) for o in opts] +
100 [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
102 if self._downloader.params.get('verbose', False):
103 self._downloader.to_screen(u'[debug] ffmpeg command line: %s' % shell_quote(cmd))
104 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
105 stdout, stderr = p.communicate()
106 if p.returncode != 0:
107 stderr = stderr.decode('utf-8', 'replace')
108 msg = stderr.strip().split('\n')[-1]
109 raise FFmpegPostProcessorError(msg)
110 if self._deletetempfiles:
111 for ipath in input_paths:
114 def run_ffmpeg(self, path, out_path, opts):
115 self.run_ffmpeg_multiple_files([path], out_path, opts)
117 def _ffmpeg_filename_argument(self, fn):
118 # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
119 if fn.startswith(u'-'):
124 class FFmpegExtractAudioPP(FFmpegPostProcessor):
125 def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
126 FFmpegPostProcessor.__init__(self, downloader)
127 if preferredcodec is None:
128 preferredcodec = 'best'
129 self._preferredcodec = preferredcodec
130 self._preferredquality = preferredquality
131 self._nopostoverwrites = nopostoverwrites
133 def get_audio_codec(self, path):
135 if not self._probe_executable:
136 raise PostProcessingError(u'ffprobe or avprobe not found. Please install one.')
139 self._probe_executable,
141 encodeFilename(self._ffmpeg_filename_argument(path), True)]
142 handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE)
143 output = handle.communicate()[0]
144 if handle.wait() != 0:
146 except (IOError, OSError):
149 for line in output.decode('ascii', 'ignore').split('\n'):
150 if line.startswith('codec_name='):
151 audio_codec = line.split('=')[1].strip()
152 elif line.strip() == 'codec_type=audio' and audio_codec is not None:
156 def run_ffmpeg(self, path, out_path, codec, more_opts):
160 acodec_opts = ['-acodec', codec]
161 opts = ['-vn'] + acodec_opts + more_opts
163 FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
164 except FFmpegPostProcessorError as err:
165 raise AudioConversionError(err.msg)
167 def run(self, information):
168 path = information['filepath']
170 filecodec = self.get_audio_codec(path)
171 if filecodec is None:
172 raise PostProcessingError(u'WARNING: unable to obtain file audio codec with ffprobe')
174 uses_avconv = self._uses_avconv()
176 if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
177 if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
178 # Lossless, but in another container
181 more_opts = ['-bsf:a' if uses_avconv else '-absf', 'aac_adtstoasc']
182 elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
183 # Lossless if possible
185 extension = filecodec
186 if filecodec == 'aac':
187 more_opts = ['-f', 'adts']
188 if filecodec == 'vorbis':
192 acodec = 'libmp3lame'
195 if self._preferredquality is not None:
196 if int(self._preferredquality) < 10:
197 more_opts += ['-q:a' if uses_avconv else '-aq', self._preferredquality]
199 more_opts += ['-b:a' if uses_avconv else '-ab', self._preferredquality + 'k']
201 # We convert the audio (lossy)
202 acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
203 extension = self._preferredcodec
205 if self._preferredquality is not None:
206 # The opus codec doesn't support the -aq option
207 if int(self._preferredquality) < 10 and extension != 'opus':
208 more_opts += ['-q:a' if uses_avconv else '-aq', self._preferredquality]
210 more_opts += ['-b:a' if uses_avconv else '-ab', self._preferredquality + 'k']
211 if self._preferredcodec == 'aac':
212 more_opts += ['-f', 'adts']
213 if self._preferredcodec == 'm4a':
214 more_opts += ['-bsf:a' if uses_avconv else '-absf', 'aac_adtstoasc']
215 if self._preferredcodec == 'vorbis':
217 if self._preferredcodec == 'wav':
219 more_opts += ['-f', 'wav']
221 prefix, sep, ext = path.rpartition(u'.') # not os.path.splitext, since the latter does not work on unicode in all setups
222 new_path = prefix + sep + extension
224 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
226 self._nopostoverwrites = True
229 if self._nopostoverwrites and os.path.exists(encodeFilename(new_path)):
230 self._downloader.to_screen(u'[youtube] Post-process file %s exists, skipping' % new_path)
232 self._downloader.to_screen(u'[' + self._executable + '] Destination: ' + new_path)
233 self.run_ffmpeg(path, new_path, acodec, more_opts)
235 etype,e,tb = sys.exc_info()
236 if isinstance(e, AudioConversionError):
237 msg = u'audio conversion failed: ' + e.msg
239 msg = u'error running ' + self._executable
240 raise PostProcessingError(msg)
242 # Try to update the date time for extracted audio file.
243 if information.get('filetime') is not None:
245 os.utime(encodeFilename(new_path), (time.time(), information['filetime']))
247 self._downloader.report_warning(u'Cannot update utime of audio file')
249 information['filepath'] = new_path
250 return self._nopostoverwrites,information
253 class FFmpegVideoConvertor(FFmpegPostProcessor):
254 def __init__(self, downloader=None,preferedformat=None):
255 super(FFmpegVideoConvertor, self).__init__(downloader)
256 self._preferedformat=preferedformat
258 def run(self, information):
259 path = information['filepath']
260 prefix, sep, ext = path.rpartition(u'.')
261 outpath = prefix + sep + self._preferedformat
262 if information['ext'] == self._preferedformat:
263 self._downloader.to_screen(u'[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
264 return True,information
265 self._downloader.to_screen(u'['+'ffmpeg'+'] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) +outpath)
266 self.run_ffmpeg(path, outpath, [])
267 information['filepath'] = outpath
268 information['format'] = self._preferedformat
269 information['ext'] = self._preferedformat
270 return False,information
273 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
274 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
462 def __init__(self, downloader=None, subtitlesformat='srt'):
463 super(FFmpegEmbedSubtitlePP, self).__init__(downloader)
464 self._subformat = subtitlesformat
467 def _conver_lang_code(cls, code):
468 """Convert language code from ISO 639-1 to ISO 639-2/T"""
469 return cls._lang_map.get(code[:2])
471 def run(self, information):
472 if information['ext'] != u'mp4':
473 self._downloader.to_screen(u'[ffmpeg] Subtitles can only be embedded in mp4 files')
474 return True, information
475 if not information.get('subtitles'):
476 self._downloader.to_screen(u'[ffmpeg] There aren\'t any subtitles to embed')
477 return True, information
479 sub_langs = [key for key in information['subtitles']]
480 filename = information['filepath']
481 input_files = [filename] + [subtitles_filename(filename, lang, self._subformat) for lang in sub_langs]
483 opts = ['-map', '0:0', '-map', '0:1', '-c:v', 'copy', '-c:a', 'copy']
484 for (i, lang) in enumerate(sub_langs):
485 opts.extend(['-map', '%d:0' % (i+1), '-c:s:%d' % i, 'mov_text'])
486 lang_code = self._conver_lang_code(lang)
487 if lang_code is not None:
488 opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
489 opts.extend(['-f', 'mp4'])
491 temp_filename = filename + u'.temp'
492 self._downloader.to_screen(u'[ffmpeg] Embedding subtitles in \'%s\'' % filename)
493 self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
494 os.remove(encodeFilename(filename))
495 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
497 return True, information
500 class FFmpegMetadataPP(FFmpegPostProcessor):
503 if info.get('title') is not None:
504 metadata['title'] = info['title']
505 if info.get('upload_date') is not None:
506 metadata['date'] = info['upload_date']
507 if info.get('uploader') is not None:
508 metadata['artist'] = info['uploader']
509 elif info.get('uploader_id') is not None:
510 metadata['artist'] = info['uploader_id']
513 self._downloader.to_screen(u'[ffmpeg] There isn\'t any metadata to add')
516 filename = info['filepath']
517 temp_filename = prepend_extension(filename, 'temp')
519 if info['ext'] == u'm4a':
520 options = ['-vn', '-acodec', 'copy']
522 options = ['-c', 'copy']
524 for (name, value) in metadata.items():
525 options.extend(['-metadata', '%s=%s' % (name, value)])
527 self._downloader.to_screen(u'[ffmpeg] Adding metadata to \'%s\'' % filename)
528 self.run_ffmpeg(filename, temp_filename, options)
529 os.remove(encodeFilename(filename))
530 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
534 class FFmpegMergerPP(FFmpegPostProcessor):
536 filename = info['filepath']
537 args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0', '-shortest']
538 self._downloader.to_screen(u'[ffmpeg] Merging formats into "%s"' % filename)
539 self.run_ffmpeg_multiple_files(info['__files_to_merge'], filename, args)
543 class FFmpegAudioFixPP(FFmpegPostProcessor):
545 filename = info['filepath']
546 temp_filename = prepend_extension(filename, 'temp')
548 options = ['-vn', '-acodec', 'copy']
549 self._downloader.to_screen(u'[ffmpeg] Fixing audio file "%s"' % filename)
550 self.run_ffmpeg(filename, temp_filename, options)
552 os.remove(encodeFilename(filename))
553 os.rename(encodeFilename(temp_filename), encodeFilename(filename))