1 from __future__ import unicode_literals
10 from .common import AudioConversionError, PostProcessor
19 process_communicate_or_kill,
28 EXT_TO_OUT_FORMATS = {
46 'vorbis': 'libvorbis',
51 class FFmpegPostProcessorError(PostProcessingError):
55 class FFmpegPostProcessor(PostProcessor):
56 def __init__(self, downloader=None):
57 PostProcessor.__init__(self, downloader)
58 self._determine_executables()
60 def check_version(self):
61 if not self.available:
62 raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
64 required_version = '10-0' if self.basename == 'avconv' else '1.0'
65 if is_outdated_version(
66 self._versions[self.basename], required_version):
67 warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
68 self.basename, self.basename, required_version)
70 self._downloader.report_warning(warning)
73 def get_versions(downloader=None):
74 return FFmpegPostProcessor(downloader)._versions
76 def _determine_executables(self):
77 programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
80 def get_ffmpeg_version(path):
81 ver = get_exe_version(path, args=['-version'])
84 r'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1]
85 r'n([0-9.]+)$', # Arch Linux
86 # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/
89 mobj = re.match(regex, ver)
95 self.probe_basename = None
100 prefer_ffmpeg = self._downloader.params.get('prefer_ffmpeg', True)
101 location = self._downloader.params.get('ffmpeg_location')
102 if location is not None:
103 if not os.path.exists(location):
104 self._downloader.report_warning(
105 'ffmpeg-location %s does not exist! '
106 'Continuing without avconv/ffmpeg.' % (location))
109 elif not os.path.isdir(location):
110 basename = os.path.splitext(os.path.basename(location))[0]
111 if basename not in programs:
112 self._downloader.report_warning(
113 'Cannot identify executable %s, its basename should be one of %s. '
114 'Continuing without avconv/ffmpeg.' %
115 (location, ', '.join(programs)))
118 location = os.path.dirname(os.path.abspath(location))
119 if basename in ('ffmpeg', 'ffprobe'):
123 (p, os.path.join(location, p)) for p in programs)
124 self._versions = dict(
125 (p, get_ffmpeg_version(self._paths[p])) for p in programs)
126 if self._versions is None:
127 self._versions = dict(
128 (p, get_ffmpeg_version(p)) for p in programs)
129 self._paths = dict((p, p) for p in programs)
131 if prefer_ffmpeg is False:
132 prefs = ('avconv', 'ffmpeg')
134 prefs = ('ffmpeg', 'avconv')
136 if self._versions[p]:
140 if prefer_ffmpeg is False:
141 prefs = ('avprobe', 'ffprobe')
143 prefs = ('ffprobe', 'avprobe')
145 if self._versions[p]:
146 self.probe_basename = p
151 return self.basename is not None
154 def executable(self):
155 return self._paths[self.basename]
158 def probe_available(self):
159 return self.probe_basename is not None
162 def probe_executable(self):
163 return self._paths[self.probe_basename]
165 def get_audio_codec(self, path):
166 if not self.probe_available and not self.available:
167 raise PostProcessingError('ffprobe/avprobe and ffmpeg/avconv not found. Please install one.')
169 if self.probe_available:
171 encodeFilename(self.probe_executable, True),
172 encodeArgument('-show_streams')]
175 encodeFilename(self.executable, True),
176 encodeArgument('-i')]
177 cmd.append(encodeFilename(self._ffmpeg_filename_argument(path), True))
178 if self._downloader.params.get('verbose', False):
179 self._downloader.to_screen(
180 '[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
181 handle = subprocess.Popen(
182 cmd, stderr=subprocess.PIPE,
183 stdout=subprocess.PIPE, stdin=subprocess.PIPE)
184 stdout_data, stderr_data = process_communicate_or_kill(handle)
185 expected_ret = 0 if self.probe_available else 1
186 if handle.wait() != expected_ret:
188 except (IOError, OSError):
190 output = (stdout_data if self.probe_available else stderr_data).decode('ascii', 'ignore')
191 if self.probe_available:
193 for line in output.split('\n'):
194 if line.startswith('codec_name='):
195 audio_codec = line.split('=')[1].strip()
196 elif line.strip() == 'codec_type=audio' and audio_codec is not None:
199 # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME
201 r'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)',
207 def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
211 os.stat(encodeFilename(path)).st_mtime for path in input_paths)
213 opts += self._configuration_args()
216 for path in input_paths:
218 encodeArgument('-i'),
219 encodeFilename(self._ffmpeg_filename_argument(path), True)
221 cmd = [encodeFilename(self.executable, True), encodeArgument('-y')]
222 # avconv does not have repeat option
223 if self.basename == 'ffmpeg':
224 cmd += [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
226 + [encodeArgument(o) for o in opts]
227 + [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
229 if self._downloader.params.get('verbose', False):
230 self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
231 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
232 stdout, stderr = process_communicate_or_kill(p)
233 if p.returncode != 0:
234 stderr = stderr.decode('utf-8', 'replace')
235 msgs = stderr.strip().split('\n')
237 if self._downloader.params.get('verbose', False):
238 self._downloader.to_screen('[debug] ' + '\n'.join(msgs[:-1]))
239 raise FFmpegPostProcessorError(msg)
240 self.try_utime(out_path, oldest_mtime, oldest_mtime)
242 def run_ffmpeg(self, path, out_path, opts):
243 self.run_ffmpeg_multiple_files([path], out_path, opts)
245 def _ffmpeg_filename_argument(self, fn):
246 # Always use 'file:' because the filename may contain ':' (ffmpeg
247 # interprets that as a protocol) or can start with '-' (-- is broken in
248 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
249 # Also leave '-' intact in order not to break streaming to stdout.
250 return 'file:' + fn if fn != '-' else fn
253 class FFmpegExtractAudioPP(FFmpegPostProcessor):
254 def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
255 FFmpegPostProcessor.__init__(self, downloader)
256 if preferredcodec is None:
257 preferredcodec = 'best'
258 self._preferredcodec = preferredcodec
259 self._preferredquality = preferredquality
260 self._nopostoverwrites = nopostoverwrites
262 def run_ffmpeg(self, path, out_path, codec, more_opts):
266 acodec_opts = ['-acodec', codec]
267 opts = ['-vn'] + acodec_opts + more_opts
269 FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
270 except FFmpegPostProcessorError as err:
271 raise AudioConversionError(err.msg)
273 def run(self, information):
274 path = information['filepath']
276 filecodec = self.get_audio_codec(path)
277 if filecodec is None:
278 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
281 if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
282 if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
283 # Lossless, but in another container
286 more_opts = ['-bsf:a', 'aac_adtstoasc']
287 elif filecodec in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
288 # Lossless if possible
290 extension = filecodec
291 if filecodec == 'aac':
292 more_opts = ['-f', 'adts']
293 if filecodec == 'vorbis':
297 acodec = 'libmp3lame'
300 if self._preferredquality is not None:
301 if int(self._preferredquality) < 10:
302 more_opts += ['-q:a', self._preferredquality]
304 more_opts += ['-b:a', self._preferredquality + 'k']
306 # We convert the audio (lossy if codec is lossy)
307 acodec = ACODECS[self._preferredcodec]
308 extension = self._preferredcodec
310 if self._preferredquality is not None:
311 # The opus codec doesn't support the -aq option
312 if int(self._preferredquality) < 10 and extension != 'opus':
313 more_opts += ['-q:a', self._preferredquality]
315 more_opts += ['-b:a', self._preferredquality + 'k']
316 if self._preferredcodec == 'aac':
317 more_opts += ['-f', 'adts']
318 if self._preferredcodec == 'm4a':
319 more_opts += ['-bsf:a', 'aac_adtstoasc']
320 if self._preferredcodec == 'vorbis':
322 if self._preferredcodec == 'wav':
324 more_opts += ['-f', 'wav']
326 prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
327 new_path = prefix + sep + extension
329 information['filepath'] = new_path
330 information['ext'] = extension
332 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
334 or (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
335 self._downloader.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path)
336 return [], information
339 self._downloader.to_screen('[ffmpeg] Destination: ' + new_path)
340 self.run_ffmpeg(path, new_path, acodec, more_opts)
341 except AudioConversionError as e:
342 raise PostProcessingError(
343 'audio conversion failed: ' + e.msg)
345 raise PostProcessingError('error running ' + self.basename)
347 # Try to update the date time for extracted audio file.
348 if information.get('filetime') is not None:
350 new_path, time.time(), information['filetime'],
351 errnote='Cannot update utime of audio file')
353 return [path], information
356 class FFmpegVideoConvertorPP(FFmpegPostProcessor):
357 def __init__(self, downloader=None, preferedformat=None):
358 super(FFmpegVideoConvertorPP, self).__init__(downloader)
359 self._preferedformat = preferedformat
361 def run(self, information):
362 path = information['filepath']
363 if information['ext'] == self._preferedformat:
364 self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
365 return [], information
367 if self._preferedformat == 'avi':
368 options.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
369 prefix, sep, ext = path.rpartition('.')
370 outpath = prefix + sep + self._preferedformat
371 self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
372 self.run_ffmpeg(path, outpath, options)
373 information['filepath'] = outpath
374 information['format'] = self._preferedformat
375 information['ext'] = self._preferedformat
376 return [path], information
379 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
380 def run(self, information):
381 if information['ext'] not in ('mp4', 'webm', 'mkv'):
382 self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4, webm or mkv files')
383 return [], information
384 subtitles = information.get('requested_subtitles')
386 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
387 return [], information
389 filename = information['filepath']
391 ext = information['ext']
394 webm_vtt_warn = False
396 for lang, sub_info in subtitles.items():
397 sub_ext = sub_info['ext']
398 if ext != 'webm' or ext == 'webm' and sub_ext == 'vtt':
399 sub_langs.append(lang)
400 sub_filenames.append(subtitles_filename(filename, lang, sub_ext, ext))
402 if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt':
404 self._downloader.to_screen('[ffmpeg] Only WebVTT subtitles can be embedded in webm files')
407 return [], information
409 input_files = [filename] + sub_filenames
414 # Don't copy the existing subtitles, we may be running the
415 # postprocessor a second time
417 # Don't copy Apple TV chapters track, bin_data (see #19042, #19024,
418 # https://trac.ffmpeg.org/ticket/6016)
421 if information['ext'] == 'mp4':
422 opts += ['-c:s', 'mov_text']
423 for (i, lang) in enumerate(sub_langs):
424 opts.extend(['-map', '%d:0' % (i + 1)])
425 lang_code = ISO639Utils.short2long(lang) or lang
426 opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
428 temp_filename = prepend_extension(filename, 'temp')
429 self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
430 self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
431 os.remove(encodeFilename(filename))
432 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
434 return sub_filenames, information
437 class FFmpegMetadataPP(FFmpegPostProcessor):
441 def add(meta_list, info_list=None):
443 info_list = meta_list
444 if not isinstance(meta_list, (list, tuple)):
445 meta_list = (meta_list,)
446 if not isinstance(info_list, (list, tuple)):
447 info_list = (info_list,)
448 for info_f in info_list:
449 if info.get(info_f) is not None:
450 for meta_f in meta_list:
451 metadata[meta_f] = info[info_f]
454 # See [1-4] for some info on media metadata/metadata supported
456 # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
457 # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
458 # 3. https://kodi.wiki/view/Video_file_tagging
459 # 4. http://atomicparsley.sourceforge.net/mpeg-4files.html
461 add('title', ('track', 'title'))
462 add('date', 'upload_date')
463 add(('description', 'comment'), 'description')
464 add('purl', 'webpage_url')
465 add('track', 'track_number')
466 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
470 add('disc', 'disc_number')
471 add('show', 'series')
473 add('episode_id', ('episode', 'episode_id'))
474 add('episode_sort', 'episode_number')
477 self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
480 filename = info['filepath']
481 temp_filename = prepend_extension(filename, 'temp')
482 in_filenames = [filename]
485 if info['ext'] == 'm4a':
486 options.extend(['-vn', '-acodec', 'copy'])
488 options.extend(['-c', 'copy'])
490 for (name, value) in metadata.items():
491 options.extend(['-metadata', '%s=%s' % (name, value)])
493 chapters = info.get('chapters', [])
495 metadata_filename = replace_extension(filename, 'meta')
496 with io.open(metadata_filename, 'wt', encoding='utf-8') as f:
497 def ffmpeg_escape(text):
498 return re.sub(r'(=|;|#|\\|\n)', r'\\\1', text)
500 metadata_file_content = ';FFMETADATA1\n'
501 for chapter in chapters:
502 metadata_file_content += '[CHAPTER]\nTIMEBASE=1/1000\n'
503 metadata_file_content += 'START=%d\n' % (chapter['start_time'] * 1000)
504 metadata_file_content += 'END=%d\n' % (chapter['end_time'] * 1000)
505 chapter_title = chapter.get('title')
507 metadata_file_content += 'title=%s\n' % ffmpeg_escape(chapter_title)
508 f.write(metadata_file_content)
509 in_filenames.append(metadata_filename)
510 options.extend(['-map_metadata', '1'])
512 self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
513 self.run_ffmpeg_multiple_files(in_filenames, temp_filename, options)
515 os.remove(metadata_filename)
516 os.remove(encodeFilename(filename))
517 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
521 class FFmpegMergerPP(FFmpegPostProcessor):
523 filename = info['filepath']
524 temp_filename = prepend_extension(filename, 'temp')
525 args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
526 self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
527 self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
528 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
529 return info['__files_to_merge'], info
532 # TODO: figure out merge-capable ffmpeg version
533 if self.basename != 'avconv':
536 required_version = '10-0'
537 if is_outdated_version(
538 self._versions[self.basename], required_version):
539 warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
540 'youtube-dl will download single file media. '
541 'Update %s to version %s or newer to fix this.') % (
542 self.basename, self.basename, required_version)
544 self._downloader.report_warning(warning)
549 class FFmpegFixupStretchedPP(FFmpegPostProcessor):
551 stretched_ratio = info.get('stretched_ratio')
552 if stretched_ratio is None or stretched_ratio == 1:
555 filename = info['filepath']
556 temp_filename = prepend_extension(filename, 'temp')
558 options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
559 self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
560 self.run_ffmpeg(filename, temp_filename, options)
562 os.remove(encodeFilename(filename))
563 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
568 class FFmpegFixupM4aPP(FFmpegPostProcessor):
570 if info.get('container') != 'm4a_dash':
573 filename = info['filepath']
574 temp_filename = prepend_extension(filename, 'temp')
576 options = ['-c', 'copy', '-f', 'mp4']
577 self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
578 self.run_ffmpeg(filename, temp_filename, options)
580 os.remove(encodeFilename(filename))
581 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
586 class FFmpegFixupM3u8PP(FFmpegPostProcessor):
588 filename = info['filepath']
589 if self.get_audio_codec(filename) == 'aac':
590 temp_filename = prepend_extension(filename, 'temp')
592 options = ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
593 self._downloader.to_screen('[ffmpeg] Fixing malformed AAC bitstream in "%s"' % filename)
594 self.run_ffmpeg(filename, temp_filename, options)
596 os.remove(encodeFilename(filename))
597 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
601 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
602 def __init__(self, downloader=None, format=None):
603 super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
607 subs = info.get('requested_subtitles')
608 filename = info['filepath']
609 new_ext = self.format
611 if new_format == 'vtt':
612 new_format = 'webvtt'
614 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
616 self._downloader.to_screen('[ffmpeg] Converting subtitles')
618 for lang, sub in subs.items():
621 self._downloader.to_screen(
622 '[ffmpeg] Subtitle file for %s is already in the requested format' % new_ext)
624 old_file = subtitles_filename(filename, lang, ext, info.get('ext'))
625 sub_filenames.append(old_file)
626 new_file = subtitles_filename(filename, lang, new_ext, info.get('ext'))
628 if ext in ('dfxp', 'ttml', 'tt'):
629 self._downloader.report_warning(
630 'You have requested to convert dfxp (TTML) subtitles into another format, '
631 'which results in style information loss')
634 srt_file = subtitles_filename(filename, lang, 'srt', info.get('ext'))
636 with open(dfxp_file, 'rb') as f:
637 srt_data = dfxp2srt(f.read())
639 with io.open(srt_file, 'wt', encoding='utf-8') as f:
651 sub_filenames.append(srt_file)
653 self.run_ffmpeg(old_file, new_file, ['-f', new_format])
655 with io.open(new_file, 'rt', encoding='utf-8') as f:
661 return sub_filenames, info