1 from __future__
import unicode_literals
10 from .common
import AudioConversionError
, PostProcessor
27 EXT_TO_OUT_FORMATS
= {
45 'vorbis': 'libvorbis',
50 class FFmpegPostProcessorError(PostProcessingError
):
54 class FFmpegPostProcessor(PostProcessor
):
55 def __init__(self
, downloader
=None):
56 PostProcessor
.__init
__(self
, downloader
)
57 self
._determine
_executables
()
59 def check_version(self
):
60 if not self
.available
:
61 raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
63 required_version
= '10-0' if self
.basename
== 'avconv' else '1.0'
64 if is_outdated_version(
65 self
._versions
[self
.basename
], required_version
):
66 warning
= 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
67 self
.basename
, self
.basename
, required_version
)
69 self
._downloader
.report_warning(warning
)
72 def get_versions(downloader
=None):
73 return FFmpegPostProcessor(downloader
)._versions
75 def _determine_executables(self
):
76 programs
= ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
79 def get_ffmpeg_version(path
):
80 ver
= get_exe_version(path
, args
=['-version'])
83 r
'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1]
84 r
'n([0-9.]+)$', # Arch Linux
85 # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/
88 mobj
= re
.match(regex
, ver
)
94 self
.probe_basename
= None
99 prefer_ffmpeg
= self
._downloader
.params
.get('prefer_ffmpeg', True)
100 location
= self
._downloader
.params
.get('ffmpeg_location')
101 if location
is not None:
102 if not os
.path
.exists(location
):
103 self
._downloader
.report_warning(
104 'ffmpeg-location %s does not exist! '
105 'Continuing without avconv/ffmpeg.' % (location
))
108 elif not os
.path
.isdir(location
):
109 basename
= os
.path
.splitext(os
.path
.basename(location
))[0]
110 if basename
not in programs
:
111 self
._downloader
.report_warning(
112 'Cannot identify executable %s, its basename should be one of %s. '
113 'Continuing without avconv/ffmpeg.' %
114 (location
, ', '.join(programs
)))
117 location
= os
.path
.dirname(os
.path
.abspath(location
))
118 if basename
in ('ffmpeg', 'ffprobe'):
122 (p
, os
.path
.join(location
, p
)) for p
in programs
)
123 self
._versions
= dict(
124 (p
, get_ffmpeg_version(self
._paths
[p
])) for p
in programs
)
125 if self
._versions
is None:
126 self
._versions
= dict(
127 (p
, get_ffmpeg_version(p
)) for p
in programs
)
128 self
._paths
= dict((p
, p
) for p
in programs
)
130 if prefer_ffmpeg
is False:
131 prefs
= ('avconv', 'ffmpeg')
133 prefs
= ('ffmpeg', 'avconv')
135 if self
._versions
[p
]:
139 if prefer_ffmpeg
is False:
140 prefs
= ('avprobe', 'ffprobe')
142 prefs
= ('ffprobe', 'avprobe')
144 if self
._versions
[p
]:
145 self
.probe_basename
= p
150 return self
.basename
is not None
153 def executable(self
):
154 return self
._paths
[self
.basename
]
157 def probe_available(self
):
158 return self
.probe_basename
is not None
161 def probe_executable(self
):
162 return self
._paths
[self
.probe_basename
]
164 def get_audio_codec(self
, path
):
165 if not self
.probe_available
and not self
.available
:
166 raise PostProcessingError('ffprobe/avprobe and ffmpeg/avconv not found. Please install one.')
168 if self
.probe_available
:
170 encodeFilename(self
.probe_executable
, True),
171 encodeArgument('-show_streams')]
174 encodeFilename(self
.executable
, True),
175 encodeArgument('-i')]
176 cmd
.append(encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True))
177 if self
._downloader
.params
.get('verbose', False):
178 self
._downloader
.to_screen(
179 '[debug] %s command line: %s' % (self
.basename
, shell_quote(cmd
)))
180 handle
= subprocess
.Popen(
181 cmd
, stderr
=subprocess
.PIPE
,
182 stdout
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
183 stdout_data
, stderr_data
= handle
.communicate()
184 expected_ret
= 0 if self
.probe_available
else 1
185 if handle
.wait() != expected_ret
:
187 except (IOError, OSError):
189 output
= (stdout_data
if self
.probe_available
else stderr_data
).decode('ascii', 'ignore')
190 if self
.probe_available
:
192 for line
in output
.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:
198 # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME
200 r
'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)',
206 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
):
210 os
.stat(encodeFilename(path
)).st_mtime
for path
in input_paths
)
212 opts
+= self
._configuration
_args
()
215 for path
in input_paths
:
217 encodeArgument('-i'),
218 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)
220 cmd
= ([encodeFilename(self
.executable
, True), encodeArgument('-y')] +
222 [encodeArgument(o
) for o
in opts
] +
223 [encodeFilename(self
._ffmpeg
_filename
_argument
(out_path
), True)])
225 if self
._downloader
.params
.get('verbose', False):
226 self
._downloader
.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd
))
227 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
228 stdout
, stderr
= p
.communicate()
229 if p
.returncode
!= 0:
230 stderr
= stderr
.decode('utf-8', 'replace')
231 msg
= stderr
.strip().split('\n')[-1]
232 raise FFmpegPostProcessorError(msg
)
233 self
.try_utime(out_path
, oldest_mtime
, oldest_mtime
)
235 def run_ffmpeg(self
, path
, out_path
, opts
):
236 self
.run_ffmpeg_multiple_files([path
], out_path
, opts
)
238 def _ffmpeg_filename_argument(self
, fn
):
239 # Always use 'file:' because the filename may contain ':' (ffmpeg
240 # interprets that as a protocol) or can start with '-' (-- is broken in
241 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
242 # Also leave '-' intact in order not to break streaming to stdout.
243 return 'file:' + fn
if fn
!= '-' else fn
246 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
247 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
248 FFmpegPostProcessor
.__init
__(self
, downloader
)
249 if preferredcodec
is None:
250 preferredcodec
= 'best'
251 self
._preferredcodec
= preferredcodec
252 self
._preferredquality
= preferredquality
253 self
._nopostoverwrites
= nopostoverwrites
255 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
259 acodec_opts
= ['-acodec', codec
]
260 opts
= ['-vn'] + acodec_opts
+ more_opts
262 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
263 except FFmpegPostProcessorError
as err
:
264 raise AudioConversionError(err
.msg
)
266 def run(self
, information
):
267 path
= information
['filepath']
269 filecodec
= self
.get_audio_codec(path
)
270 if filecodec
is None:
271 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
274 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
275 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
276 # Lossless, but in another container
279 more_opts
= ['-bsf:a', 'aac_adtstoasc']
280 elif filecodec
in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
281 # Lossless if possible
283 extension
= filecodec
284 if filecodec
== 'aac':
285 more_opts
= ['-f', 'adts']
286 if filecodec
== 'vorbis':
290 acodec
= 'libmp3lame'
293 if self
._preferredquality
is not None:
294 if int(self
._preferredquality
) < 10:
295 more_opts
+= ['-q:a', self
._preferredquality
]
297 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
299 # We convert the audio (lossy if codec is lossy)
300 acodec
= ACODECS
[self
._preferredcodec
]
301 extension
= self
._preferredcodec
303 if self
._preferredquality
is not None:
304 # The opus codec doesn't support the -aq option
305 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
306 more_opts
+= ['-q:a', self
._preferredquality
]
308 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
309 if self
._preferredcodec
== 'aac':
310 more_opts
+= ['-f', 'adts']
311 if self
._preferredcodec
== 'm4a':
312 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
313 if self
._preferredcodec
== 'vorbis':
315 if self
._preferredcodec
== 'wav':
317 more_opts
+= ['-f', 'wav']
319 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
320 new_path
= prefix
+ sep
+ extension
322 information
['filepath'] = new_path
323 information
['ext'] = extension
325 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
326 if (new_path
== path
or
327 (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)))):
328 self
._downloader
.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path
)
329 return [], information
332 self
._downloader
.to_screen('[ffmpeg] Destination: ' + new_path
)
333 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
334 except AudioConversionError
as e
:
335 raise PostProcessingError(
336 'audio conversion failed: ' + e
.msg
)
338 raise PostProcessingError('error running ' + self
.basename
)
340 # Try to update the date time for extracted audio file.
341 if information
.get('filetime') is not None:
343 new_path
, time
.time(), information
['filetime'],
344 errnote
='Cannot update utime of audio file')
346 return [path
], information
349 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
350 def __init__(self
, downloader
=None, preferedformat
=None):
351 super(FFmpegVideoConvertorPP
, self
).__init
__(downloader
)
352 self
._preferedformat
= preferedformat
354 def run(self
, information
):
355 path
= information
['filepath']
356 if information
['ext'] == self
._preferedformat
:
357 self
._downloader
.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path
, self
._preferedformat
))
358 return [], information
360 if self
._preferedformat
== 'avi':
361 options
.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
362 prefix
, sep
, ext
= path
.rpartition('.')
363 outpath
= prefix
+ sep
+ self
._preferedformat
364 self
._downloader
.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information
['ext'], self
._preferedformat
) + outpath
)
365 self
.run_ffmpeg(path
, outpath
, options
)
366 information
['filepath'] = outpath
367 information
['format'] = self
._preferedformat
368 information
['ext'] = self
._preferedformat
369 return [path
], information
372 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
373 def run(self
, information
):
374 if information
['ext'] not in ('mp4', 'webm', 'mkv'):
375 self
._downloader
.to_screen('[ffmpeg] Subtitles can only be embedded in mp4, webm or mkv files')
376 return [], information
377 subtitles
= information
.get('requested_subtitles')
379 self
._downloader
.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
380 return [], information
382 filename
= information
['filepath']
384 ext
= information
['ext']
387 webm_vtt_warn
= False
389 for lang
, sub_info
in subtitles
.items():
390 sub_ext
= sub_info
['ext']
391 if ext
!= 'webm' or ext
== 'webm' and sub_ext
== 'vtt':
392 sub_langs
.append(lang
)
393 sub_filenames
.append(subtitles_filename(filename
, lang
, sub_ext
))
395 if not webm_vtt_warn
and ext
== 'webm' and sub_ext
!= 'vtt':
397 self
._downloader
.to_screen('[ffmpeg] Only WebVTT subtitles can be embedded in webm files')
400 return [], information
402 input_files
= [filename
] + sub_filenames
407 # Don't copy the existing subtitles, we may be running the
408 # postprocessor a second time
410 # Don't copy Apple TV chapters track, bin_data (see #19042, #19024,
411 # https://trac.ffmpeg.org/ticket/6016)
414 if information
['ext'] == 'mp4':
415 opts
+= ['-c:s', 'mov_text']
416 for (i
, lang
) in enumerate(sub_langs
):
417 opts
.extend(['-map', '%d:0' % (i
+ 1)])
418 lang_code
= ISO639Utils
.short2long(lang
) or lang
419 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
421 temp_filename
= prepend_extension(filename
, 'temp')
422 self
._downloader
.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename
)
423 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
424 os
.remove(encodeFilename(filename
))
425 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
427 return sub_filenames
, information
430 class FFmpegMetadataPP(FFmpegPostProcessor
):
434 def add(meta_list
, info_list
=None):
436 info_list
= meta_list
437 if not isinstance(meta_list
, (list, tuple)):
438 meta_list
= (meta_list
,)
439 if not isinstance(info_list
, (list, tuple)):
440 info_list
= (info_list
,)
441 for info_f
in info_list
:
442 if info
.get(info_f
) is not None:
443 for meta_f
in meta_list
:
444 metadata
[meta_f
] = info
[info_f
]
447 add('title', ('track', 'title'))
448 add('date', 'upload_date')
449 add(('description', 'comment'), 'description')
450 add('purl', 'webpage_url')
451 add('track', 'track_number')
452 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
456 add('disc', 'disc_number')
459 self
._downloader
.to_screen('[ffmpeg] There isn\'t any metadata to add')
462 filename
= info
['filepath']
463 temp_filename
= prepend_extension(filename
, 'temp')
464 in_filenames
= [filename
]
467 if info
['ext'] == 'm4a':
468 options
.extend(['-vn', '-acodec', 'copy'])
470 options
.extend(['-c', 'copy'])
472 for (name
, value
) in metadata
.items():
473 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
475 chapters
= info
.get('chapters', [])
477 metadata_filename
= replace_extension(filename
, 'meta')
478 with io
.open(metadata_filename
, 'wt', encoding
='utf-8') as f
:
479 def ffmpeg_escape(text
):
480 return re
.sub(r
'(=|;|#|\\|\n)', r
'\\\1', text
)
482 metadata_file_content
= ';FFMETADATA1\n'
483 for chapter
in chapters
:
484 metadata_file_content
+= '[CHAPTER]\nTIMEBASE=1/1000\n'
485 metadata_file_content
+= 'START=%d\n' % (chapter
['start_time'] * 1000)
486 metadata_file_content
+= 'END=%d\n' % (chapter
['end_time'] * 1000)
487 chapter_title
= chapter
.get('title')
489 metadata_file_content
+= 'title=%s\n' % ffmpeg_escape(chapter_title
)
490 f
.write(metadata_file_content
)
491 in_filenames
.append(metadata_filename
)
492 options
.extend(['-map_metadata', '1'])
494 self
._downloader
.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename
)
495 self
.run_ffmpeg_multiple_files(in_filenames
, temp_filename
, options
)
497 os
.remove(metadata_filename
)
498 os
.remove(encodeFilename(filename
))
499 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
503 class FFmpegMergerPP(FFmpegPostProcessor
):
505 filename
= info
['filepath']
506 temp_filename
= prepend_extension(filename
, 'temp')
507 args
= ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
508 self
._downloader
.to_screen('[ffmpeg] Merging formats into "%s"' % filename
)
509 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
510 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
511 return info
['__files_to_merge'], info
514 # TODO: figure out merge-capable ffmpeg version
515 if self
.basename
!= 'avconv':
518 required_version
= '10-0'
519 if is_outdated_version(
520 self
._versions
[self
.basename
], required_version
):
521 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
522 'youtube-dl will download single file media. '
523 'Update %s to version %s or newer to fix this.') % (
524 self
.basename
, self
.basename
, required_version
)
526 self
._downloader
.report_warning(warning
)
531 class FFmpegFixupStretchedPP(FFmpegPostProcessor
):
533 stretched_ratio
= info
.get('stretched_ratio')
534 if stretched_ratio
is None or stretched_ratio
== 1:
537 filename
= info
['filepath']
538 temp_filename
= prepend_extension(filename
, 'temp')
540 options
= ['-c', 'copy', '-aspect', '%f' % stretched_ratio
]
541 self
._downloader
.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename
)
542 self
.run_ffmpeg(filename
, temp_filename
, options
)
544 os
.remove(encodeFilename(filename
))
545 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
550 class FFmpegFixupM4aPP(FFmpegPostProcessor
):
552 if info
.get('container') != 'm4a_dash':
555 filename
= info
['filepath']
556 temp_filename
= prepend_extension(filename
, 'temp')
558 options
= ['-c', 'copy', '-f', 'mp4']
559 self
._downloader
.to_screen('[ffmpeg] Correcting container 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 FFmpegFixupM3u8PP(FFmpegPostProcessor
):
570 filename
= info
['filepath']
571 if self
.get_audio_codec(filename
) == 'aac':
572 temp_filename
= prepend_extension(filename
, 'temp')
574 options
= ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
575 self
._downloader
.to_screen('[ffmpeg] Fixing malformed AAC bitstream in "%s"' % filename
)
576 self
.run_ffmpeg(filename
, temp_filename
, options
)
578 os
.remove(encodeFilename(filename
))
579 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
583 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
584 def __init__(self
, downloader
=None, format
=None):
585 super(FFmpegSubtitlesConvertorPP
, self
).__init
__(downloader
)
589 subs
= info
.get('requested_subtitles')
590 filename
= info
['filepath']
591 new_ext
= self
.format
593 if new_format
== 'vtt':
594 new_format
= 'webvtt'
596 self
._downloader
.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
598 self
._downloader
.to_screen('[ffmpeg] Converting subtitles')
600 for lang
, sub
in subs
.items():
603 self
._downloader
.to_screen(
604 '[ffmpeg] Subtitle file for %s is already in the requested format' % new_ext
)
606 old_file
= subtitles_filename(filename
, lang
, ext
)
607 sub_filenames
.append(old_file
)
608 new_file
= subtitles_filename(filename
, lang
, new_ext
)
610 if ext
in ('dfxp', 'ttml', 'tt'):
611 self
._downloader
.report_warning(
612 'You have requested to convert dfxp (TTML) subtitles into another format, '
613 'which results in style information loss')
616 srt_file
= subtitles_filename(filename
, lang
, 'srt')
618 with open(dfxp_file
, 'rb') as f
:
619 srt_data
= dfxp2srt(f
.read())
621 with io
.open(srt_file
, 'wt', encoding
='utf-8') as f
:
633 sub_filenames
.append(srt_file
)
635 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
637 with io
.open(new_file
, 'rt', encoding
='utf-8') as f
:
643 return sub_filenames
, info