1 from __future__ import unicode_literals
9 from .common import AudioConversionError, PostProcessor
11 from ..compat import (
12 compat_subprocess_get_DEVNULL,
27 class FFmpegPostProcessorError(PostProcessingError):
31 class FFmpegPostProcessor(PostProcessor):
32 def __init__(self, downloader=None):
33 PostProcessor.__init__(self, downloader)
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.')
41 def check_outdated(self):
42 required_version = '10-0' if self.basename == 'avconv' else '1.0'
43 if is_outdated_version(
44 self._versions[self.basename], required_version):
45 warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
46 self.basename, self.basename, required_version)
48 self._downloader.report_warning(warning)
53 def get_versions(downloader=None):
54 return FFmpegPostProcessor(downloader)._versions
56 def _determine_executables(self):
57 programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
58 prefer_ffmpeg = self._downloader.params.get('prefer_ffmpeg', False)
61 self.probe_basename = None
66 location = self._downloader.params.get('ffmpeg_location')
67 if location is not None:
68 if not os.path.exists(location):
69 self._downloader.report_warning(
70 'ffmpeg-location %s does not exist! '
71 'Continuing without avconv/ffmpeg.' % (location))
74 elif not os.path.isdir(location):
75 basename = os.path.splitext(os.path.basename(location))[0]
76 if basename not in programs:
77 self._downloader.report_warning(
78 'Cannot identify executable %s, its basename should be one of %s. '
79 'Continuing without avconv/ffmpeg.' %
80 (location, ', '.join(programs)))
83 location = os.path.dirname(os.path.abspath(location))
84 if basename in ('ffmpeg', 'ffprobe'):
88 (p, os.path.join(location, p)) for p in programs)
89 self._versions = dict(
90 (p, get_exe_version(self._paths[p], args=['-version']))
92 if self._versions is None:
93 self._versions = dict(
94 (p, get_exe_version(p, args=['-version'])) for p in programs)
95 self._paths = dict((p, p) for p in programs)
98 prefs = ('ffmpeg', 'avconv')
100 prefs = ('avconv', 'ffmpeg')
102 if self._versions[p]:
107 prefs = ('ffprobe', 'avprobe')
109 prefs = ('avprobe', 'ffprobe')
111 if self._versions[p]:
112 self.probe_basename = p
117 return self.basename is not None
120 def executable(self):
121 return self._paths[self.basename]
124 def probe_available(self):
125 return self.probe_basename is not None
128 def probe_executable(self):
129 return self._paths[self.probe_basename]
131 def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
135 os.stat(encodeFilename(path)).st_mtime for path in input_paths)
138 for path in input_paths:
139 files_cmd.extend([encodeArgument('-i'), encodeFilename(path, True)])
140 cmd = ([encodeFilename(self.executable, True), encodeArgument('-y')] +
142 [encodeArgument(o) for o in opts] +
143 [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
145 if self._downloader.params.get('verbose', False):
146 self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
147 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
148 stdout, stderr = p.communicate()
149 if p.returncode != 0:
150 stderr = stderr.decode('utf-8', 'replace')
151 msg = stderr.strip().split('\n')[-1]
152 raise FFmpegPostProcessorError(msg)
153 self.try_utime(out_path, oldest_mtime, oldest_mtime)
155 def run_ffmpeg(self, path, out_path, opts):
156 self.run_ffmpeg_multiple_files([path], out_path, opts)
158 def _ffmpeg_filename_argument(self, fn):
159 # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
160 if fn.startswith('-'):
165 class FFmpegExtractAudioPP(FFmpegPostProcessor):
166 def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
167 FFmpegPostProcessor.__init__(self, downloader)
168 if preferredcodec is None:
169 preferredcodec = 'best'
170 self._preferredcodec = preferredcodec
171 self._preferredquality = preferredquality
172 self._nopostoverwrites = nopostoverwrites
174 def get_audio_codec(self, path):
176 if not self.probe_available:
177 raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
180 encodeFilename(self.probe_executable, True),
181 encodeArgument('-show_streams'),
182 encodeFilename(self._ffmpeg_filename_argument(path), True)]
183 if self._downloader.params.get('verbose', False):
184 self._downloader.to_screen('[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
185 handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE, stdin=subprocess.PIPE)
186 output = handle.communicate()[0]
187 if handle.wait() != 0:
189 except (IOError, OSError):
192 for line in output.decode('ascii', 'ignore').split('\n'):
193 if line.startswith('codec_name='):
194 audio_codec = line.split('=')[1].strip()
195 elif line.strip() == 'codec_type=audio' and audio_codec is not None:
199 def run_ffmpeg(self, path, out_path, codec, more_opts):
203 acodec_opts = ['-acodec', codec]
204 opts = ['-vn'] + acodec_opts + more_opts
206 FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
207 except FFmpegPostProcessorError as err:
208 raise AudioConversionError(err.msg)
210 def run(self, information):
211 path = information['filepath']
213 filecodec = self.get_audio_codec(path)
214 if filecodec is None:
215 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
218 if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
219 if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
220 # Lossless, but in another container
223 more_opts = ['-bsf:a', 'aac_adtstoasc']
224 elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
225 # Lossless if possible
227 extension = filecodec
228 if filecodec == 'aac':
229 more_opts = ['-f', 'adts']
230 if filecodec == 'vorbis':
234 acodec = 'libmp3lame'
237 if self._preferredquality is not None:
238 if int(self._preferredquality) < 10:
239 more_opts += ['-q:a', self._preferredquality]
241 more_opts += ['-b:a', self._preferredquality + 'k']
243 # We convert the audio (lossy)
244 acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
245 extension = self._preferredcodec
247 if self._preferredquality is not None:
248 # The opus codec doesn't support the -aq option
249 if int(self._preferredquality) < 10 and extension != 'opus':
250 more_opts += ['-q:a', self._preferredquality]
252 more_opts += ['-b:a', self._preferredquality + 'k']
253 if self._preferredcodec == 'aac':
254 more_opts += ['-f', 'adts']
255 if self._preferredcodec == 'm4a':
256 more_opts += ['-bsf:a', 'aac_adtstoasc']
257 if self._preferredcodec == 'vorbis':
259 if self._preferredcodec == 'wav':
261 more_opts += ['-f', 'wav']
263 prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
264 new_path = prefix + sep + extension
266 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
267 if (new_path == path or
268 (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
269 self._downloader.to_screen('[youtube] Post-process file %s exists, skipping' % new_path)
270 return [], information
273 self._downloader.to_screen('[' + self.basename + '] Destination: ' + new_path)
274 self.run_ffmpeg(path, new_path, acodec, more_opts)
275 except AudioConversionError as e:
276 raise PostProcessingError(
277 'audio conversion failed: ' + e.msg)
279 raise PostProcessingError('error running ' + self.basename)
281 # Try to update the date time for extracted audio file.
282 if information.get('filetime') is not None:
284 new_path, time.time(), information['filetime'],
285 errnote='Cannot update utime of audio file')
287 information['filepath'] = new_path
288 information['ext'] = extension
290 return [path], information
293 class FFmpegVideoConvertorPP(FFmpegPostProcessor):
294 def __init__(self, downloader=None, preferedformat=None):
295 super(FFmpegVideoConvertorPP, self).__init__(downloader)
296 self._preferedformat = preferedformat
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 [], 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 [path], information
313 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
314 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
503 def _conver_lang_code(cls, code):
504 """Convert language code from ISO 639-1 to ISO 639-2/T"""
505 return cls._lang_map.get(code[:2])
507 def run(self, information):
508 if information['ext'] not in ['mp4', 'mkv']:
509 self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4 or mkv files')
510 return [], information
511 subtitles = information.get('requested_subtitles')
513 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
514 return [], information
516 sub_langs = list(subtitles.keys())
517 filename = information['filepath']
518 sub_filenames = [subtitles_filename(filename, lang, sub_info['ext']) for lang, sub_info in subtitles.items()]
519 input_files = [filename] + sub_filenames
524 # Don't copy the existing subtitles, we may be running the
525 # postprocessor a second time
528 if information['ext'] == 'mp4':
529 opts += ['-c:s', 'mov_text']
530 for (i, lang) in enumerate(sub_langs):
531 opts.extend(['-map', '%d:0' % (i + 1)])
532 lang_code = self._conver_lang_code(lang)
533 if lang_code is not None:
534 opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
536 temp_filename = prepend_extension(filename, 'temp')
537 self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
538 self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
539 os.remove(encodeFilename(filename))
540 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
542 return sub_filenames, information
545 class FFmpegMetadataPP(FFmpegPostProcessor):
548 if info.get('title') is not None:
549 metadata['title'] = info['title']
550 if info.get('upload_date') is not None:
551 metadata['date'] = info['upload_date']
552 if info.get('artist') is not None:
553 metadata['artist'] = info['artist']
554 elif info.get('uploader') is not None:
555 metadata['artist'] = info['uploader']
556 elif info.get('uploader_id') is not None:
557 metadata['artist'] = info['uploader_id']
558 if info.get('description') is not None:
559 metadata['description'] = info['description']
560 metadata['comment'] = info['description']
561 if info.get('webpage_url') is not None:
562 metadata['purl'] = info['webpage_url']
563 if info.get('album') is not None:
564 metadata['album'] = info['album']
567 self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
570 filename = info['filepath']
571 temp_filename = prepend_extension(filename, 'temp')
573 if info['ext'] == 'm4a':
574 options = ['-vn', '-acodec', 'copy']
576 options = ['-c', 'copy']
578 for (name, value) in metadata.items():
579 options.extend(['-metadata', '%s=%s' % (name, value)])
581 self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
582 self.run_ffmpeg(filename, temp_filename, options)
583 os.remove(encodeFilename(filename))
584 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
588 class FFmpegMergerPP(FFmpegPostProcessor):
590 filename = info['filepath']
591 temp_filename = prepend_extension(filename, 'temp')
592 args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
593 self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
594 self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
595 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
596 return info['__files_to_merge'], info
599 class FFmpegFixupStretchedPP(FFmpegPostProcessor):
601 stretched_ratio = info.get('stretched_ratio')
602 if stretched_ratio is None or stretched_ratio == 1:
605 filename = info['filepath']
606 temp_filename = prepend_extension(filename, 'temp')
608 options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
609 self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
610 self.run_ffmpeg(filename, temp_filename, options)
612 os.remove(encodeFilename(filename))
613 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
618 class FFmpegFixupM4aPP(FFmpegPostProcessor):
620 if info.get('container') != 'm4a_dash':
623 filename = info['filepath']
624 temp_filename = prepend_extension(filename, 'temp')
626 options = ['-c', 'copy', '-f', 'mp4']
627 self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
628 self.run_ffmpeg(filename, temp_filename, options)
630 os.remove(encodeFilename(filename))
631 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
636 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
637 def __init__(self, downloader=None, format=None):
638 super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
642 subs = info.get('requested_subtitles')
643 filename = info['filepath']
644 new_ext = self.format
646 if new_format == 'vtt':
647 new_format = 'webvtt'
649 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
651 self._downloader.to_screen('[ffmpeg] Converting subtitles')
652 for lang, sub in subs.items():
655 self._downloader.to_screen(
656 '[ffmpeg] Subtitle file for %s is already in the requested'
659 new_file = subtitles_filename(filename, lang, new_ext)
661 if ext == 'dfxp' or ext == 'ttml':
662 self._downloader.report_warning(
663 'You have requested to convert dfxp (TTML) subtitles into another format, '
664 'which results in style information loss')
666 dfxp_file = subtitles_filename(filename, lang, ext)
667 srt_file = subtitles_filename(filename, lang, 'srt')
669 with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
670 srt_data = dfxp2srt(f.read())
672 with io.open(srt_file, 'wt', encoding='utf-8') as f:
685 subtitles_filename(filename, lang, ext),
686 new_file, ['-f', new_format])
688 with io.open(new_file, 'rt', encoding='utf-8') as f: