1 from __future__ import unicode_literals
10 from .common import AudioConversionError, PostProcessor
12 from ..compat import (
13 compat_subprocess_get_DEVNULL,
30 EXT_TO_OUT_FORMATS = {
48 'vorbis': 'libvorbis',
53 class FFmpegPostProcessorError(PostProcessingError):
57 class FFmpegPostProcessor(PostProcessor):
58 def __init__(self, downloader=None):
59 PostProcessor.__init__(self, downloader)
60 self._determine_executables()
62 def check_version(self):
63 if not self.available:
64 raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
66 required_version = '10-0' if self.basename == 'avconv' else '1.0'
67 if is_outdated_version(
68 self._versions[self.basename], required_version):
69 warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
70 self.basename, self.basename, required_version)
72 self._downloader.report_warning(warning)
75 def get_versions(downloader=None):
76 return FFmpegPostProcessor(downloader)._versions
78 def _determine_executables(self):
79 programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
82 def get_ffmpeg_version(path):
83 ver = get_exe_version(path, args=['-version'])
86 r'([0-9.]+)-0ubuntu0\.[0-9.]+$', # Ubuntu
87 r'n([0-9.]+)$', # Arch Linux
90 mobj = re.match(regex, ver)
96 self.probe_basename = None
101 prefer_ffmpeg = self._downloader.params.get('prefer_ffmpeg', True)
102 location = self._downloader.params.get('ffmpeg_location')
103 if location is not None:
104 if not os.path.exists(location):
105 self._downloader.report_warning(
106 'ffmpeg-location %s does not exist! '
107 'Continuing without avconv/ffmpeg.' % (location))
110 elif not os.path.isdir(location):
111 basename = os.path.splitext(os.path.basename(location))[0]
112 if basename not in programs:
113 self._downloader.report_warning(
114 'Cannot identify executable %s, its basename should be one of %s. '
115 'Continuing without avconv/ffmpeg.' %
116 (location, ', '.join(programs)))
119 location = os.path.dirname(os.path.abspath(location))
120 if basename in ('ffmpeg', 'ffprobe'):
124 (p, os.path.join(location, p)) for p in programs)
125 self._versions = dict(
126 (p, get_ffmpeg_version(self._paths[p])) for p in programs)
127 if self._versions is None:
128 self._versions = dict(
129 (p, get_ffmpeg_version(p)) for p in programs)
130 self._paths = dict((p, p) for p in programs)
132 if prefer_ffmpeg is False:
133 prefs = ('avconv', 'ffmpeg')
135 prefs = ('ffmpeg', 'avconv')
137 if self._versions[p]:
141 if prefer_ffmpeg is False:
142 prefs = ('avprobe', 'ffprobe')
144 prefs = ('ffprobe', 'avprobe')
146 if self._versions[p]:
147 self.probe_basename = p
152 return self.basename is not None
155 def executable(self):
156 return self._paths[self.basename]
159 def probe_available(self):
160 return self.probe_basename is not None
163 def probe_executable(self):
164 return self._paths[self.probe_basename]
166 def get_audio_codec(self, path):
167 if not self.probe_available:
168 raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
171 encodeFilename(self.probe_executable, True),
172 encodeArgument('-show_streams'),
173 encodeFilename(self._ffmpeg_filename_argument(path), True)]
174 if self._downloader.params.get('verbose', False):
175 self._downloader.to_screen('[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
176 handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE, stdin=subprocess.PIPE)
177 output = handle.communicate()[0]
178 if handle.wait() != 0:
180 except (IOError, OSError):
183 for line in output.decode('ascii', 'ignore').split('\n'):
184 if line.startswith('codec_name='):
185 audio_codec = line.split('=')[1].strip()
186 elif line.strip() == 'codec_type=audio' and audio_codec is not None:
190 def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
194 os.stat(encodeFilename(path)).st_mtime for path in input_paths)
196 opts += self._configuration_args()
199 for path in input_paths:
201 encodeArgument('-i'),
202 encodeFilename(self._ffmpeg_filename_argument(path), True)
204 cmd = ([encodeFilename(self.executable, True), encodeArgument('-y')] +
206 [encodeArgument(o) for o in opts] +
207 [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
209 if self._downloader.params.get('verbose', False):
210 self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
211 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
212 stdout, stderr = p.communicate()
213 if p.returncode != 0:
214 stderr = stderr.decode('utf-8', 'replace')
215 msg = stderr.strip().split('\n')[-1]
216 raise FFmpegPostProcessorError(msg)
217 self.try_utime(out_path, oldest_mtime, oldest_mtime)
219 def run_ffmpeg(self, path, out_path, opts):
220 self.run_ffmpeg_multiple_files([path], out_path, opts)
222 def _ffmpeg_filename_argument(self, fn):
223 # Always use 'file:' because the filename may contain ':' (ffmpeg
224 # interprets that as a protocol) or can start with '-' (-- is broken in
225 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
226 # Also leave '-' intact in order not to break streaming to stdout.
227 return 'file:' + fn if fn != '-' else fn
230 class FFmpegExtractAudioPP(FFmpegPostProcessor):
231 def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
232 FFmpegPostProcessor.__init__(self, downloader)
233 if preferredcodec is None:
234 preferredcodec = 'best'
235 self._preferredcodec = preferredcodec
236 self._preferredquality = preferredquality
237 self._nopostoverwrites = nopostoverwrites
239 def run_ffmpeg(self, path, out_path, codec, more_opts):
243 acodec_opts = ['-acodec', codec]
244 opts = ['-vn'] + acodec_opts + more_opts
246 FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
247 except FFmpegPostProcessorError as err:
248 raise AudioConversionError(err.msg)
250 def run(self, information):
251 path = information['filepath']
253 filecodec = self.get_audio_codec(path)
254 if filecodec is None:
255 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
258 if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
259 if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
260 # Lossless, but in another container
263 more_opts = ['-bsf:a', 'aac_adtstoasc']
264 elif filecodec in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
265 # Lossless if possible
267 extension = filecodec
268 if filecodec == 'aac':
269 more_opts = ['-f', 'adts']
270 if filecodec == 'vorbis':
274 acodec = 'libmp3lame'
277 if self._preferredquality is not None:
278 if int(self._preferredquality) < 10:
279 more_opts += ['-q:a', self._preferredquality]
281 more_opts += ['-b:a', self._preferredquality + 'k']
283 # We convert the audio (lossy if codec is lossy)
284 acodec = ACODECS[self._preferredcodec]
285 extension = self._preferredcodec
287 if self._preferredquality is not None:
288 # The opus codec doesn't support the -aq option
289 if int(self._preferredquality) < 10 and extension != 'opus':
290 more_opts += ['-q:a', self._preferredquality]
292 more_opts += ['-b:a', self._preferredquality + 'k']
293 if self._preferredcodec == 'aac':
294 more_opts += ['-f', 'adts']
295 if self._preferredcodec == 'm4a':
296 more_opts += ['-bsf:a', 'aac_adtstoasc']
297 if self._preferredcodec == 'vorbis':
299 if self._preferredcodec == 'wav':
301 more_opts += ['-f', 'wav']
303 prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
304 new_path = prefix + sep + extension
306 information['filepath'] = new_path
307 information['ext'] = extension
309 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
310 if (new_path == path or
311 (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
312 self._downloader.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path)
313 return [], information
316 self._downloader.to_screen('[ffmpeg] Destination: ' + new_path)
317 self.run_ffmpeg(path, new_path, acodec, more_opts)
318 except AudioConversionError as e:
319 raise PostProcessingError(
320 'audio conversion failed: ' + e.msg)
322 raise PostProcessingError('error running ' + self.basename)
324 # Try to update the date time for extracted audio file.
325 if information.get('filetime') is not None:
327 new_path, time.time(), information['filetime'],
328 errnote='Cannot update utime of audio file')
330 return [path], information
333 class FFmpegVideoConvertorPP(FFmpegPostProcessor):
334 def __init__(self, downloader=None, preferedformat=None):
335 super(FFmpegVideoConvertorPP, self).__init__(downloader)
336 self._preferedformat = preferedformat
338 def run(self, information):
339 path = information['filepath']
340 if information['ext'] == self._preferedformat:
341 self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
342 return [], information
344 if self._preferedformat == 'avi':
345 options.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
346 prefix, sep, ext = path.rpartition('.')
347 outpath = prefix + sep + self._preferedformat
348 self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
349 self.run_ffmpeg(path, outpath, options)
350 information['filepath'] = outpath
351 information['format'] = self._preferedformat
352 information['ext'] = self._preferedformat
353 return [path], information
356 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
357 def run(self, information):
358 if information['ext'] not in ('mp4', 'webm', 'mkv'):
359 self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4, webm or mkv files')
360 return [], information
361 subtitles = information.get('requested_subtitles')
363 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
364 return [], information
366 filename = information['filepath']
368 ext = information['ext']
371 webm_vtt_warn = False
373 for lang, sub_info in subtitles.items():
374 sub_ext = sub_info['ext']
375 if ext != 'webm' or ext == 'webm' and sub_ext == 'vtt':
376 sub_langs.append(lang)
377 sub_filenames.append(subtitles_filename(filename, lang, sub_ext))
379 if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt':
381 self._downloader.to_screen('[ffmpeg] Only WebVTT subtitles can be embedded in webm files')
384 return [], information
386 input_files = [filename] + sub_filenames
391 # Don't copy the existing subtitles, we may be running the
392 # postprocessor a second time
395 if information['ext'] == 'mp4':
396 opts += ['-c:s', 'mov_text']
397 for (i, lang) in enumerate(sub_langs):
398 opts.extend(['-map', '%d:0' % (i + 1)])
399 lang_code = ISO639Utils.short2long(lang) or lang
400 opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
402 temp_filename = prepend_extension(filename, 'temp')
403 self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
404 self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
405 os.remove(encodeFilename(filename))
406 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
408 return sub_filenames, information
411 class FFmpegMetadataPP(FFmpegPostProcessor):
415 def add(meta_list, info_list=None):
417 info_list = meta_list
418 if not isinstance(meta_list, (list, tuple)):
419 meta_list = (meta_list,)
420 if not isinstance(info_list, (list, tuple)):
421 info_list = (info_list,)
422 for info_f in info_list:
423 if info.get(info_f) is not None:
424 for meta_f in meta_list:
425 metadata[meta_f] = info[info_f]
428 add('title', ('track', 'title'))
429 add('date', 'upload_date')
430 add(('description', 'comment'), 'description')
431 add('purl', 'webpage_url')
432 add('track', 'track_number')
433 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
437 add('disc', 'disc_number')
440 self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
443 filename = info['filepath']
444 temp_filename = prepend_extension(filename, 'temp')
445 in_filenames = [filename]
448 if info['ext'] == 'm4a':
449 options.extend(['-vn', '-acodec', 'copy'])
451 options.extend(['-c', 'copy'])
453 for (name, value) in metadata.items():
454 options.extend(['-metadata', '%s=%s' % (name, value)])
456 chapters = info.get('chapters', [])
458 metadata_filename = replace_extension(filename, 'meta')
459 with io.open(metadata_filename, 'wt', encoding='utf-8') as f:
460 def ffmpeg_escape(text):
461 return re.sub(r'(=|;|#|\\|\n)', r'\\\1', text)
463 metadata_file_content = ';FFMETADATA1\n'
464 for chapter in chapters:
465 metadata_file_content += '[CHAPTER]\nTIMEBASE=1/1000\n'
466 metadata_file_content += 'START=%d\n' % (chapter['start_time'] * 1000)
467 metadata_file_content += 'END=%d\n' % (chapter['end_time'] * 1000)
468 chapter_title = chapter.get('title')
470 metadata_file_content += 'title=%s\n' % ffmpeg_escape(chapter_title)
471 f.write(metadata_file_content)
472 in_filenames.append(metadata_filename)
473 options.extend(['-map_metadata', '1'])
475 self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
476 self.run_ffmpeg_multiple_files(in_filenames, temp_filename, options)
478 os.remove(metadata_filename)
479 os.remove(encodeFilename(filename))
480 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
484 class FFmpegMergerPP(FFmpegPostProcessor):
486 filename = info['filepath']
487 temp_filename = prepend_extension(filename, 'temp')
488 args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
489 self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
490 self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
491 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
492 return info['__files_to_merge'], info
495 # TODO: figure out merge-capable ffmpeg version
496 if self.basename != 'avconv':
499 required_version = '10-0'
500 if is_outdated_version(
501 self._versions[self.basename], required_version):
502 warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
503 'youtube-dl will download single file media. '
504 'Update %s to version %s or newer to fix this.') % (
505 self.basename, self.basename, required_version)
507 self._downloader.report_warning(warning)
512 class FFmpegFixupStretchedPP(FFmpegPostProcessor):
514 stretched_ratio = info.get('stretched_ratio')
515 if stretched_ratio is None or stretched_ratio == 1:
518 filename = info['filepath']
519 temp_filename = prepend_extension(filename, 'temp')
521 options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
522 self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
523 self.run_ffmpeg(filename, temp_filename, options)
525 os.remove(encodeFilename(filename))
526 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
531 class FFmpegFixupM4aPP(FFmpegPostProcessor):
533 if info.get('container') != 'm4a_dash':
536 filename = info['filepath']
537 temp_filename = prepend_extension(filename, 'temp')
539 options = ['-c', 'copy', '-f', 'mp4']
540 self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
541 self.run_ffmpeg(filename, temp_filename, options)
543 os.remove(encodeFilename(filename))
544 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
549 class FFmpegFixupM3u8PP(FFmpegPostProcessor):
551 filename = info['filepath']
552 if self.get_audio_codec(filename) == 'aac':
553 temp_filename = prepend_extension(filename, 'temp')
555 options = ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
556 self._downloader.to_screen('[ffmpeg] Fixing malformed AAC bitstream in "%s"' % filename)
557 self.run_ffmpeg(filename, temp_filename, options)
559 os.remove(encodeFilename(filename))
560 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
564 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
565 def __init__(self, downloader=None, format=None):
566 super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
570 subs = info.get('requested_subtitles')
571 filename = info['filepath']
572 new_ext = self.format
574 if new_format == 'vtt':
575 new_format = 'webvtt'
577 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
579 self._downloader.to_screen('[ffmpeg] Converting subtitles')
581 for lang, sub in subs.items():
584 self._downloader.to_screen(
585 '[ffmpeg] Subtitle file for %s is already in the requested format' % new_ext)
587 old_file = subtitles_filename(filename, lang, ext)
588 sub_filenames.append(old_file)
589 new_file = subtitles_filename(filename, lang, new_ext)
591 if ext in ('dfxp', 'ttml', 'tt'):
592 self._downloader.report_warning(
593 'You have requested to convert dfxp (TTML) subtitles into another format, '
594 'which results in style information loss')
597 srt_file = subtitles_filename(filename, lang, 'srt')
599 with open(dfxp_file, 'rb') as f:
600 srt_data = dfxp2srt(f.read())
602 with io.open(srt_file, 'wt', encoding='utf-8') as f:
614 sub_filenames.append(srt_file)
616 self.run_ffmpeg(old_file, new_file, ['-f', new_format])
618 with io.open(new_file, 'rt', encoding='utf-8') as f:
624 return sub_filenames, info