1 from __future__
import unicode_literals
9 from .common
import AudioConversionError
, PostProcessor
11 from ..compat
import (
12 compat_subprocess_get_DEVNULL
,
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']
81 self
.probe_basename
= None
86 prefer_ffmpeg
= self
._downloader
.params
.get('prefer_ffmpeg', False)
87 location
= self
._downloader
.params
.get('ffmpeg_location')
88 if location
is not None:
89 if not os
.path
.exists(location
):
90 self
._downloader
.report_warning(
91 'ffmpeg-location %s does not exist! '
92 'Continuing without avconv/ffmpeg.' % (location
))
95 elif not os
.path
.isdir(location
):
96 basename
= os
.path
.splitext(os
.path
.basename(location
))[0]
97 if basename
not in programs
:
98 self
._downloader
.report_warning(
99 'Cannot identify executable %s, its basename should be one of %s. '
100 'Continuing without avconv/ffmpeg.' %
101 (location
, ', '.join(programs
)))
104 location
= os
.path
.dirname(os
.path
.abspath(location
))
105 if basename
in ('ffmpeg', 'ffprobe'):
109 (p
, os
.path
.join(location
, p
)) for p
in programs
)
110 self
._versions
= dict(
111 (p
, get_exe_version(self
._paths
[p
], args
=['-version']))
113 if self
._versions
is None:
114 self
._versions
= dict(
115 (p
, get_exe_version(p
, args
=['-version'])) for p
in programs
)
116 self
._paths
= dict((p
, p
) for p
in programs
)
119 prefs
= ('ffmpeg', 'avconv')
121 prefs
= ('avconv', 'ffmpeg')
123 if self
._versions
[p
]:
128 prefs
= ('ffprobe', 'avprobe')
130 prefs
= ('avprobe', 'ffprobe')
132 if self
._versions
[p
]:
133 self
.probe_basename
= p
138 return self
.basename
is not None
141 def executable(self
):
142 return self
._paths
[self
.basename
]
145 def probe_available(self
):
146 return self
.probe_basename
is not None
149 def probe_executable(self
):
150 return self
._paths
[self
.probe_basename
]
152 def get_audio_codec(self
, path
):
153 if not self
.probe_available
:
154 raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
157 encodeFilename(self
.probe_executable
, True),
158 encodeArgument('-show_streams'),
159 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)]
160 if self
._downloader
.params
.get('verbose', False):
161 self
._downloader
.to_screen('[debug] %s command line: %s' % (self
.basename
, shell_quote(cmd
)))
162 handle
= subprocess
.Popen(cmd
, stderr
=compat_subprocess_get_DEVNULL(), stdout
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
163 output
= handle
.communicate()[0]
164 if handle
.wait() != 0:
166 except (IOError, OSError):
169 for line
in output
.decode('ascii', 'ignore').split('\n'):
170 if line
.startswith('codec_name='):
171 audio_codec
= line
.split('=')[1].strip()
172 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
176 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
):
180 os
.stat(encodeFilename(path
)).st_mtime
for path
in input_paths
)
182 opts
+= self
._configuration
_args
()
185 for path
in input_paths
:
187 encodeArgument('-i'),
188 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)
190 cmd
= ([encodeFilename(self
.executable
, True), encodeArgument('-y')] +
192 [encodeArgument(o
) for o
in opts
] +
193 [encodeFilename(self
._ffmpeg
_filename
_argument
(out_path
), True)])
195 if self
._downloader
.params
.get('verbose', False):
196 self
._downloader
.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd
))
197 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
198 stdout
, stderr
= p
.communicate()
199 if p
.returncode
!= 0:
200 stderr
= stderr
.decode('utf-8', 'replace')
201 msg
= stderr
.strip().split('\n')[-1]
202 raise FFmpegPostProcessorError(msg
)
203 self
.try_utime(out_path
, oldest_mtime
, oldest_mtime
)
205 def run_ffmpeg(self
, path
, out_path
, opts
):
206 self
.run_ffmpeg_multiple_files([path
], out_path
, opts
)
208 def _ffmpeg_filename_argument(self
, fn
):
209 # Always use 'file:' because the filename may contain ':' (ffmpeg
210 # interprets that as a protocol) or can start with '-' (-- is broken in
211 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
212 # Also leave '-' intact in order not to break streaming to stdout.
213 return 'file:' + fn
if fn
!= '-' else fn
216 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
217 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
218 FFmpegPostProcessor
.__init
__(self
, downloader
)
219 if preferredcodec
is None:
220 preferredcodec
= 'best'
221 self
._preferredcodec
= preferredcodec
222 self
._preferredquality
= preferredquality
223 self
._nopostoverwrites
= nopostoverwrites
225 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
229 acodec_opts
= ['-acodec', codec
]
230 opts
= ['-vn'] + acodec_opts
+ more_opts
232 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
233 except FFmpegPostProcessorError
as err
:
234 raise AudioConversionError(err
.msg
)
236 def run(self
, information
):
237 path
= information
['filepath']
239 filecodec
= self
.get_audio_codec(path
)
240 if filecodec
is None:
241 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
244 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
245 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
246 # Lossless, but in another container
249 more_opts
= ['-bsf:a', 'aac_adtstoasc']
250 elif filecodec
in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
251 # Lossless if possible
253 extension
= filecodec
254 if filecodec
== 'aac':
255 more_opts
= ['-f', 'adts']
256 if filecodec
== 'vorbis':
260 acodec
= 'libmp3lame'
263 if self
._preferredquality
is not None:
264 if int(self
._preferredquality
) < 10:
265 more_opts
+= ['-q:a', self
._preferredquality
]
267 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
269 # We convert the audio (lossy if codec is lossy)
270 acodec
= ACODECS
[self
._preferredcodec
]
271 extension
= self
._preferredcodec
273 if self
._preferredquality
is not None:
274 # The opus codec doesn't support the -aq option
275 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
276 more_opts
+= ['-q:a', self
._preferredquality
]
278 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
279 if self
._preferredcodec
== 'aac':
280 more_opts
+= ['-f', 'adts']
281 if self
._preferredcodec
== 'm4a':
282 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
283 if self
._preferredcodec
== 'vorbis':
285 if self
._preferredcodec
== 'wav':
287 more_opts
+= ['-f', 'wav']
289 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
290 new_path
= prefix
+ sep
+ extension
292 information
['filepath'] = new_path
293 information
['ext'] = extension
295 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
296 if (new_path
== path
or
297 (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)))):
298 self
._downloader
.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path
)
299 return [], information
302 self
._downloader
.to_screen('[ffmpeg] Destination: ' + new_path
)
303 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
304 except AudioConversionError
as e
:
305 raise PostProcessingError(
306 'audio conversion failed: ' + e
.msg
)
308 raise PostProcessingError('error running ' + self
.basename
)
310 # Try to update the date time for extracted audio file.
311 if information
.get('filetime') is not None:
313 new_path
, time
.time(), information
['filetime'],
314 errnote
='Cannot update utime of audio file')
316 return [path
], information
319 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
320 def __init__(self
, downloader
=None, preferedformat
=None):
321 super(FFmpegVideoConvertorPP
, self
).__init
__(downloader
)
322 self
._preferedformat
= preferedformat
324 def run(self
, information
):
325 path
= information
['filepath']
326 if information
['ext'] == self
._preferedformat
:
327 self
._downloader
.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path
, self
._preferedformat
))
328 return [], information
330 if self
._preferedformat
== 'avi':
331 options
.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
332 prefix
, sep
, ext
= path
.rpartition('.')
333 outpath
= prefix
+ sep
+ self
._preferedformat
334 self
._downloader
.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information
['ext'], self
._preferedformat
) + outpath
)
335 self
.run_ffmpeg(path
, outpath
, options
)
336 information
['filepath'] = outpath
337 information
['format'] = self
._preferedformat
338 information
['ext'] = self
._preferedformat
339 return [path
], information
342 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
343 def run(self
, information
):
344 if information
['ext'] not in ('mp4', 'webm', 'mkv'):
345 self
._downloader
.to_screen('[ffmpeg] Subtitles can only be embedded in mp4, webm or mkv files')
346 return [], information
347 subtitles
= information
.get('requested_subtitles')
349 self
._downloader
.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
350 return [], information
352 filename
= information
['filepath']
354 ext
= information
['ext']
357 webm_vtt_warn
= False
359 for lang
, sub_info
in subtitles
.items():
360 sub_ext
= sub_info
['ext']
361 if ext
!= 'webm' or ext
== 'webm' and sub_ext
== 'vtt':
362 sub_langs
.append(lang
)
363 sub_filenames
.append(subtitles_filename(filename
, lang
, sub_ext
))
365 if not webm_vtt_warn
and ext
== 'webm' and sub_ext
!= 'vtt':
367 self
._downloader
.to_screen('[ffmpeg] Only WebVTT subtitles can be embedded in webm files')
370 return [], information
372 input_files
= [filename
] + sub_filenames
377 # Don't copy the existing subtitles, we may be running the
378 # postprocessor a second time
381 if information
['ext'] == 'mp4':
382 opts
+= ['-c:s', 'mov_text']
383 for (i
, lang
) in enumerate(sub_langs
):
384 opts
.extend(['-map', '%d:0' % (i
+ 1)])
385 lang_code
= ISO639Utils
.short2long(lang
)
386 if lang_code
is not None:
387 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
389 temp_filename
= prepend_extension(filename
, 'temp')
390 self
._downloader
.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename
)
391 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
392 os
.remove(encodeFilename(filename
))
393 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
395 return sub_filenames
, information
398 class FFmpegMetadataPP(FFmpegPostProcessor
):
402 def add(meta_list
, info_list
=None):
404 info_list
= meta_list
405 if not isinstance(meta_list
, (list, tuple)):
406 meta_list
= (meta_list
,)
407 if not isinstance(info_list
, (list, tuple)):
408 info_list
= (info_list
,)
409 for info_f
in info_list
:
410 if info
.get(info_f
) is not None:
411 for meta_f
in meta_list
:
412 metadata
[meta_f
] = info
[info_f
]
415 add('title', ('track', 'title'))
416 add('date', 'upload_date')
417 add(('description', 'comment'), 'description')
418 add('purl', 'webpage_url')
419 add('track', 'track_number')
420 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
424 add('disc', 'disc_number')
427 self
._downloader
.to_screen('[ffmpeg] There isn\'t any metadata to add')
430 filename
= info
['filepath']
431 temp_filename
= prepend_extension(filename
, 'temp')
433 if info
['ext'] == 'm4a':
434 options
= ['-vn', '-acodec', 'copy']
436 options
= ['-c', 'copy']
438 for (name
, value
) in metadata
.items():
439 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
441 self
._downloader
.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename
)
442 self
.run_ffmpeg(filename
, temp_filename
, options
)
443 os
.remove(encodeFilename(filename
))
444 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
448 class FFmpegMergerPP(FFmpegPostProcessor
):
450 filename
= info
['filepath']
451 temp_filename
= prepend_extension(filename
, 'temp')
452 args
= ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
453 self
._downloader
.to_screen('[ffmpeg] Merging formats into "%s"' % filename
)
454 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
455 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
456 return info
['__files_to_merge'], info
459 # TODO: figure out merge-capable ffmpeg version
460 if self
.basename
!= 'avconv':
463 required_version
= '10-0'
464 if is_outdated_version(
465 self
._versions
[self
.basename
], required_version
):
466 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
467 'youtube-dl will download single file media. '
468 'Update %s to version %s or newer to fix this.') % (
469 self
.basename
, self
.basename
, required_version
)
471 self
._downloader
.report_warning(warning
)
476 class FFmpegFixupStretchedPP(FFmpegPostProcessor
):
478 stretched_ratio
= info
.get('stretched_ratio')
479 if stretched_ratio
is None or stretched_ratio
== 1:
482 filename
= info
['filepath']
483 temp_filename
= prepend_extension(filename
, 'temp')
485 options
= ['-c', 'copy', '-aspect', '%f' % stretched_ratio
]
486 self
._downloader
.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename
)
487 self
.run_ffmpeg(filename
, temp_filename
, options
)
489 os
.remove(encodeFilename(filename
))
490 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
495 class FFmpegFixupM4aPP(FFmpegPostProcessor
):
497 if info
.get('container') != 'm4a_dash':
500 filename
= info
['filepath']
501 temp_filename
= prepend_extension(filename
, 'temp')
503 options
= ['-c', 'copy', '-f', 'mp4']
504 self
._downloader
.to_screen('[ffmpeg] Correcting container in "%s"' % filename
)
505 self
.run_ffmpeg(filename
, temp_filename
, options
)
507 os
.remove(encodeFilename(filename
))
508 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
513 class FFmpegFixupM3u8PP(FFmpegPostProcessor
):
515 filename
= info
['filepath']
516 if self
.get_audio_codec(filename
) == 'aac':
517 temp_filename
= prepend_extension(filename
, 'temp')
519 options
= ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
520 self
._downloader
.to_screen('[ffmpeg] Fixing malformated aac bitstream in "%s"' % filename
)
521 self
.run_ffmpeg(filename
, temp_filename
, options
)
523 os
.remove(encodeFilename(filename
))
524 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
528 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
529 def __init__(self
, downloader
=None, format
=None):
530 super(FFmpegSubtitlesConvertorPP
, self
).__init
__(downloader
)
534 subs
= info
.get('requested_subtitles')
535 filename
= info
['filepath']
536 new_ext
= self
.format
538 if new_format
== 'vtt':
539 new_format
= 'webvtt'
541 self
._downloader
.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
543 self
._downloader
.to_screen('[ffmpeg] Converting subtitles')
545 for lang
, sub
in subs
.items():
548 self
._downloader
.to_screen(
549 '[ffmpeg] Subtitle file for %s is already in the requested format' % new_ext
)
551 old_file
= subtitles_filename(filename
, lang
, ext
)
552 sub_filenames
.append(old_file
)
553 new_file
= subtitles_filename(filename
, lang
, new_ext
)
555 if ext
== 'dfxp' or ext
== 'ttml' or ext
== 'tt':
556 self
._downloader
.report_warning(
557 'You have requested to convert dfxp (TTML) subtitles into another format, '
558 'which results in style information loss')
561 srt_file
= subtitles_filename(filename
, lang
, 'srt')
563 with io
.open(dfxp_file
, 'rt', encoding
='utf-8') as f
:
564 srt_data
= dfxp2srt(f
.read())
566 with io
.open(srt_file
, 'wt', encoding
='utf-8') as f
:
578 sub_filenames
.append(srt_file
)
580 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
582 with io
.open(new_file
, 'rt', encoding
='utf-8') as f
:
588 return sub_filenames
, info