1 from __future__ import unicode_literals
9 from .common import AudioConversionError, PostProcessor
11 from ..compat import (
12 compat_subprocess_get_DEVNULL,
26 class FFmpegPostProcessorError(PostProcessingError):
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()
36 def check_version(self):
37 if not self.available:
38 raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
40 required_version = '10-0' if self.basename == '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)
46 self._downloader.report_warning(warning)
49 def get_versions(downloader=None):
50 return FFmpegPostProcessor(downloader)._versions
52 def _determine_executables(self):
53 programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
54 prefer_ffmpeg = self._downloader.params.get('prefer_ffmpeg', False)
57 self.probe_basename = None
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))
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)))
79 location = os.path.dirname(os.path.abspath(location))
80 if basename in ('ffmpeg', 'ffprobe'):
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']))
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)
94 prefs = ('ffmpeg', 'avconv')
96 prefs = ('avconv', 'ffmpeg')
103 prefs = ('ffprobe', 'avprobe')
105 prefs = ('avprobe', 'ffprobe')
107 if self._versions[p]:
108 self.probe_basename = p
113 return self.basename is not None
116 def executable(self):
117 return self._paths[self.basename]
120 def probe_executable(self):
121 return self._paths[self.probe_basename]
123 def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
127 os.stat(encodeFilename(path)).st_mtime for path in input_paths)
130 for path in input_paths:
131 files_cmd.extend([encodeArgument('-i'), encodeFilename(path, True)])
132 cmd = ([encodeFilename(self.executable, True), encodeArgument('-y')] +
134 [encodeArgument(o) for o in opts] +
135 [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
137 if self._downloader.params.get('verbose', False):
138 self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
139 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
140 stdout, stderr = p.communicate()
141 if p.returncode != 0:
142 stderr = stderr.decode('utf-8', 'replace')
143 msg = stderr.strip().split('\n')[-1]
144 raise FFmpegPostProcessorError(msg)
145 os.utime(encodeFilename(out_path), (oldest_mtime, oldest_mtime))
146 if self._deletetempfiles:
147 for ipath in input_paths:
150 def run_ffmpeg(self, path, out_path, opts):
151 self.run_ffmpeg_multiple_files([path], out_path, opts)
153 def _ffmpeg_filename_argument(self, fn):
154 # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
155 if fn.startswith('-'):
160 class FFmpegExtractAudioPP(FFmpegPostProcessor):
161 def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
162 FFmpegPostProcessor.__init__(self, downloader)
163 if preferredcodec is None:
164 preferredcodec = 'best'
165 self._preferredcodec = preferredcodec
166 self._preferredquality = preferredquality
167 self._nopostoverwrites = nopostoverwrites
169 def get_audio_codec(self, path):
171 if not self.probe_executable:
172 raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
175 encodeFilename(self.probe_executable, True),
176 encodeArgument('-show_streams'),
177 encodeFilename(self._ffmpeg_filename_argument(path), True)]
178 if self._downloader.params.get('verbose', False):
179 self._downloader.to_screen('[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
180 handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE, stdin=subprocess.PIPE)
181 output = handle.communicate()[0]
182 if handle.wait() != 0:
184 except (IOError, OSError):
187 for line in output.decode('ascii', 'ignore').split('\n'):
188 if line.startswith('codec_name='):
189 audio_codec = line.split('=')[1].strip()
190 elif line.strip() == 'codec_type=audio' and audio_codec is not None:
194 def run_ffmpeg(self, path, out_path, codec, more_opts):
198 acodec_opts = ['-acodec', codec]
199 opts = ['-vn'] + acodec_opts + more_opts
201 FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
202 except FFmpegPostProcessorError as err:
203 raise AudioConversionError(err.msg)
205 def run(self, information):
206 path = information['filepath']
208 filecodec = self.get_audio_codec(path)
209 if filecodec is None:
210 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
213 if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
214 if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
215 # Lossless, but in another container
218 more_opts = ['-bsf:a', 'aac_adtstoasc']
219 elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
220 # Lossless if possible
222 extension = filecodec
223 if filecodec == 'aac':
224 more_opts = ['-f', 'adts']
225 if filecodec == 'vorbis':
229 acodec = 'libmp3lame'
232 if self._preferredquality is not None:
233 if int(self._preferredquality) < 10:
234 more_opts += ['-q:a', self._preferredquality]
236 more_opts += ['-b:a', self._preferredquality + 'k']
238 # We convert the audio (lossy)
239 acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
240 extension = self._preferredcodec
242 if self._preferredquality is not None:
243 # The opus codec doesn't support the -aq option
244 if int(self._preferredquality) < 10 and extension != 'opus':
245 more_opts += ['-q:a', self._preferredquality]
247 more_opts += ['-b:a', self._preferredquality + 'k']
248 if self._preferredcodec == 'aac':
249 more_opts += ['-f', 'adts']
250 if self._preferredcodec == 'm4a':
251 more_opts += ['-bsf:a', 'aac_adtstoasc']
252 if self._preferredcodec == 'vorbis':
254 if self._preferredcodec == 'wav':
256 more_opts += ['-f', 'wav']
258 prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
259 new_path = prefix + sep + extension
261 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
263 self._nopostoverwrites = True
266 if self._nopostoverwrites and os.path.exists(encodeFilename(new_path)):
267 self._downloader.to_screen('[youtube] Post-process file %s exists, skipping' % new_path)
269 self._downloader.to_screen('[' + self.basename + '] Destination: ' + new_path)
270 self.run_ffmpeg(path, new_path, acodec, more_opts)
271 except AudioConversionError as e:
272 raise PostProcessingError(
273 'audio conversion failed: ' + e.msg)
275 raise PostProcessingError('error running ' + self.basename)
277 # Try to update the date time for extracted audio file.
278 if information.get('filetime') is not None:
280 os.utime(encodeFilename(new_path), (time.time(), information['filetime']))
282 self._downloader.report_warning('Cannot update utime of audio file')
284 information['filepath'] = new_path
285 return self._nopostoverwrites, information
288 class FFmpegVideoConvertorPP(FFmpegPostProcessor):
289 def __init__(self, downloader=None, preferedformat=None):
290 super(FFmpegVideoConvertorPP, self).__init__(downloader)
291 self._preferedformat = preferedformat
293 def run(self, information):
294 path = information['filepath']
295 prefix, sep, ext = path.rpartition('.')
296 outpath = prefix + sep + self._preferedformat
297 if information['ext'] == self._preferedformat:
298 self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
299 return True, information
300 self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
301 self.run_ffmpeg(path, outpath, [])
302 information['filepath'] = outpath
303 information['format'] = self._preferedformat
304 information['ext'] = self._preferedformat
305 return False, information
308 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
309 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
498 def _conver_lang_code(cls, code):
499 """Convert language code from ISO 639-1 to ISO 639-2/T"""
500 return cls._lang_map.get(code[:2])
502 def run(self, information):
503 if information['ext'] != 'mp4':
504 self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4 files')
505 return True, information
506 subtitles = information.get('requested_subtitles')
508 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
509 return True, information
511 sub_langs = list(subtitles.keys())
512 filename = information['filepath']
513 input_files = [filename] + [subtitles_filename(filename, lang, sub_info['ext']) for lang, sub_info in subtitles.items()]
518 # Don't copy the existing subtitles, we may be running the
519 # postprocessor a second time
523 for (i, lang) in enumerate(sub_langs):
524 opts.extend(['-map', '%d:0' % (i + 1)])
525 lang_code = self._conver_lang_code(lang)
526 if lang_code is not None:
527 opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
529 temp_filename = prepend_extension(filename, 'temp')
530 self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
531 self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
532 os.remove(encodeFilename(filename))
533 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
535 return True, information
538 class FFmpegMetadataPP(FFmpegPostProcessor):
541 if info.get('title') is not None:
542 metadata['title'] = info['title']
543 if info.get('upload_date') is not None:
544 metadata['date'] = info['upload_date']
545 if info.get('artist') is not None:
546 metadata['artist'] = info['artist']
547 elif info.get('uploader') is not None:
548 metadata['artist'] = info['uploader']
549 elif info.get('uploader_id') is not None:
550 metadata['artist'] = info['uploader_id']
551 if info.get('description') is not None:
552 metadata['description'] = info['description']
553 metadata['comment'] = info['description']
554 if info.get('webpage_url') is not None:
555 metadata['purl'] = info['webpage_url']
556 if info.get('album') is not None:
557 metadata['album'] = info['album']
560 self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
563 filename = info['filepath']
564 temp_filename = prepend_extension(filename, 'temp')
566 if info['ext'] == 'm4a':
567 options = ['-vn', '-acodec', 'copy']
569 options = ['-c', 'copy']
571 for (name, value) in metadata.items():
572 options.extend(['-metadata', '%s=%s' % (name, value)])
574 self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
575 self.run_ffmpeg(filename, temp_filename, options)
576 os.remove(encodeFilename(filename))
577 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
581 class FFmpegMergerPP(FFmpegPostProcessor):
583 filename = info['filepath']
584 args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
585 self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
586 self.run_ffmpeg_multiple_files(info['__files_to_merge'], filename, args)
590 class FFmpegAudioFixPP(FFmpegPostProcessor):
592 filename = info['filepath']
593 temp_filename = prepend_extension(filename, 'temp')
595 options = ['-vn', '-acodec', 'copy']
596 self._downloader.to_screen('[ffmpeg] Fixing audio file "%s"' % filename)
597 self.run_ffmpeg(filename, temp_filename, options)
599 os.remove(encodeFilename(filename))
600 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
605 class FFmpegFixupStretchedPP(FFmpegPostProcessor):
607 stretched_ratio = info.get('stretched_ratio')
608 if stretched_ratio is None or stretched_ratio == 1:
611 filename = info['filepath']
612 temp_filename = prepend_extension(filename, 'temp')
614 options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
615 self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
616 self.run_ffmpeg(filename, temp_filename, options)
618 os.remove(encodeFilename(filename))
619 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
624 class FFmpegFixupM4aPP(FFmpegPostProcessor):
626 if info.get('container') != 'm4a_dash':
629 filename = info['filepath']
630 temp_filename = prepend_extension(filename, 'temp')
632 options = ['-c', 'copy', '-f', 'mp4']
633 self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
634 self.run_ffmpeg(filename, temp_filename, options)
636 os.remove(encodeFilename(filename))
637 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
642 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
643 def __init__(self, downloader=None, format=None):
644 super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
648 subs = info.get('requested_subtitles')
649 filename = info['filepath']
650 new_ext = self.format
652 if new_format == 'vtt':
653 new_format = 'webvtt'
655 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
657 self._downloader.to_screen('[ffmpeg] Converting subtitles')
658 for lang, sub in subs.items():
661 self._downloader.to_screen(
662 '[ffmpeg] Subtitle file for %s is already in the requested'
665 new_file = subtitles_filename(filename, lang, new_ext)
667 subtitles_filename(filename, lang, ext),
668 new_file, ['-f', new_format])
670 with io.open(new_file, 'rt', encoding='utf-8') as f: