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
= {
41 class FFmpegPostProcessorError(PostProcessingError
):
45 class FFmpegPostProcessor(PostProcessor
):
46 def __init__(self
, downloader
=None):
47 PostProcessor
.__init
__(self
, downloader
)
48 self
._determine
_executables
()
50 def check_version(self
):
51 if not self
.available
:
52 raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
54 required_version
= '10-0' if self
.basename
== 'avconv' else '1.0'
55 if is_outdated_version(
56 self
._versions
[self
.basename
], required_version
):
57 warning
= 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
58 self
.basename
, self
.basename
, required_version
)
60 self
._downloader
.report_warning(warning
)
63 def get_versions(downloader
=None):
64 return FFmpegPostProcessor(downloader
)._versions
66 def _determine_executables(self
):
67 programs
= ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
71 self
.probe_basename
= None
76 prefer_ffmpeg
= self
._downloader
.params
.get('prefer_ffmpeg', False)
77 location
= self
._downloader
.params
.get('ffmpeg_location')
78 if location
is not None:
79 if not os
.path
.exists(location
):
80 self
._downloader
.report_warning(
81 'ffmpeg-location %s does not exist! '
82 'Continuing without avconv/ffmpeg.' % (location
))
85 elif not os
.path
.isdir(location
):
86 basename
= os
.path
.splitext(os
.path
.basename(location
))[0]
87 if basename
not in programs
:
88 self
._downloader
.report_warning(
89 'Cannot identify executable %s, its basename should be one of %s. '
90 'Continuing without avconv/ffmpeg.' %
91 (location
, ', '.join(programs
)))
94 location
= os
.path
.dirname(os
.path
.abspath(location
))
95 if basename
in ('ffmpeg', 'ffprobe'):
99 (p
, os
.path
.join(location
, p
)) for p
in programs
)
100 self
._versions
= dict(
101 (p
, get_exe_version(self
._paths
[p
], args
=['-version']))
103 if self
._versions
is None:
104 self
._versions
= dict(
105 (p
, get_exe_version(p
, args
=['-version'])) for p
in programs
)
106 self
._paths
= dict((p
, p
) for p
in programs
)
109 prefs
= ('ffmpeg', 'avconv')
111 prefs
= ('avconv', 'ffmpeg')
113 if self
._versions
[p
]:
118 prefs
= ('ffprobe', 'avprobe')
120 prefs
= ('avprobe', 'ffprobe')
122 if self
._versions
[p
]:
123 self
.probe_basename
= p
128 return self
.basename
is not None
131 def executable(self
):
132 return self
._paths
[self
.basename
]
135 def probe_available(self
):
136 return self
.probe_basename
is not None
139 def probe_executable(self
):
140 return self
._paths
[self
.probe_basename
]
142 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
):
146 os
.stat(encodeFilename(path
)).st_mtime
for path
in input_paths
)
148 opts
+= self
._configuration
_args
()
151 for path
in input_paths
:
153 encodeArgument('-i'),
154 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)
156 cmd
= ([encodeFilename(self
.executable
, True), encodeArgument('-y')] +
158 [encodeArgument(o
) for o
in opts
] +
159 [encodeFilename(self
._ffmpeg
_filename
_argument
(out_path
), True)])
161 if self
._downloader
.params
.get('verbose', False):
162 self
._downloader
.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd
))
163 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
164 stdout
, stderr
= p
.communicate()
165 if p
.returncode
!= 0:
166 stderr
= stderr
.decode('utf-8', 'replace')
167 msg
= stderr
.strip().split('\n')[-1]
168 raise FFmpegPostProcessorError(msg
)
169 self
.try_utime(out_path
, oldest_mtime
, oldest_mtime
)
171 def run_ffmpeg(self
, path
, out_path
, opts
):
172 self
.run_ffmpeg_multiple_files([path
], out_path
, opts
)
174 def _ffmpeg_filename_argument(self
, fn
):
175 # Always use 'file:' because the filename may contain ':' (ffmpeg
176 # interprets that as a protocol) or can start with '-' (-- is broken in
177 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
178 # Also leave '-' intact in order not to break streaming to stdout.
179 return 'file:' + fn
if fn
!= '-' else fn
182 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
183 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
184 FFmpegPostProcessor
.__init
__(self
, downloader
)
185 if preferredcodec
is None:
186 preferredcodec
= 'best'
187 self
._preferredcodec
= preferredcodec
188 self
._preferredquality
= preferredquality
189 self
._nopostoverwrites
= nopostoverwrites
191 def get_audio_codec(self
, path
):
193 if not self
.probe_available
:
194 raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
197 encodeFilename(self
.probe_executable
, True),
198 encodeArgument('-show_streams'),
199 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)]
200 if self
._downloader
.params
.get('verbose', False):
201 self
._downloader
.to_screen('[debug] %s command line: %s' % (self
.basename
, shell_quote(cmd
)))
202 handle
= subprocess
.Popen(cmd
, stderr
=compat_subprocess_get_DEVNULL(), stdout
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
203 output
= handle
.communicate()[0]
204 if handle
.wait() != 0:
206 except (IOError, OSError):
209 for line
in output
.decode('ascii', 'ignore').split('\n'):
210 if line
.startswith('codec_name='):
211 audio_codec
= line
.split('=')[1].strip()
212 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
216 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
220 acodec_opts
= ['-acodec', codec
]
221 opts
= ['-vn'] + acodec_opts
+ more_opts
223 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
224 except FFmpegPostProcessorError
as err
:
225 raise AudioConversionError(err
.msg
)
227 def run(self
, information
):
228 path
= information
['filepath']
230 filecodec
= self
.get_audio_codec(path
)
231 if filecodec
is None:
232 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
235 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
236 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
237 # Lossless, but in another container
240 more_opts
= ['-bsf:a', 'aac_adtstoasc']
241 elif filecodec
in ['aac', 'mp3', 'vorbis', 'opus']:
242 # Lossless if possible
244 extension
= filecodec
245 if filecodec
== 'aac':
246 more_opts
= ['-f', 'adts']
247 if filecodec
== 'vorbis':
251 acodec
= 'libmp3lame'
254 if self
._preferredquality
is not None:
255 if int(self
._preferredquality
) < 10:
256 more_opts
+= ['-q:a', self
._preferredquality
]
258 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
260 # We convert the audio (lossy)
261 acodec
= {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self
._preferredcodec
]
262 extension
= self
._preferredcodec
264 if self
._preferredquality
is not None:
265 # The opus codec doesn't support the -aq option
266 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
267 more_opts
+= ['-q:a', self
._preferredquality
]
269 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
270 if self
._preferredcodec
== 'aac':
271 more_opts
+= ['-f', 'adts']
272 if self
._preferredcodec
== 'm4a':
273 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
274 if self
._preferredcodec
== 'vorbis':
276 if self
._preferredcodec
== 'wav':
278 more_opts
+= ['-f', 'wav']
280 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
281 new_path
= prefix
+ sep
+ extension
283 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
284 if (new_path
== path
or
285 (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)))):
286 self
._downloader
.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path
)
287 return [], information
290 self
._downloader
.to_screen('[ffmpeg] Destination: ' + new_path
)
291 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
292 except AudioConversionError
as e
:
293 raise PostProcessingError(
294 'audio conversion failed: ' + e
.msg
)
296 raise PostProcessingError('error running ' + self
.basename
)
298 # Try to update the date time for extracted audio file.
299 if information
.get('filetime') is not None:
301 new_path
, time
.time(), information
['filetime'],
302 errnote
='Cannot update utime of audio file')
304 information
['filepath'] = new_path
305 information
['ext'] = extension
307 return [path
], information
310 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
311 def __init__(self
, downloader
=None, preferedformat
=None):
312 super(FFmpegVideoConvertorPP
, self
).__init
__(downloader
)
313 self
._preferedformat
= preferedformat
315 def run(self
, information
):
316 path
= information
['filepath']
317 if information
['ext'] == self
._preferedformat
:
318 self
._downloader
.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path
, self
._preferedformat
))
319 return [], information
321 if self
._preferedformat
== 'avi':
322 options
.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
323 prefix
, sep
, ext
= path
.rpartition('.')
324 outpath
= prefix
+ sep
+ self
._preferedformat
325 self
._downloader
.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information
['ext'], self
._preferedformat
) + outpath
)
326 self
.run_ffmpeg(path
, outpath
, options
)
327 information
['filepath'] = outpath
328 information
['format'] = self
._preferedformat
329 information
['ext'] = self
._preferedformat
330 return [path
], information
333 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
334 def run(self
, information
):
335 if information
['ext'] not in ('mp4', 'webm', 'mkv'):
336 self
._downloader
.to_screen('[ffmpeg] Subtitles can only be embedded in mp4, webm or mkv files')
337 return [], information
338 subtitles
= information
.get('requested_subtitles')
340 self
._downloader
.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
341 return [], information
343 filename
= information
['filepath']
345 ext
= information
['ext']
348 webm_vtt_warn
= False
350 for lang
, sub_info
in subtitles
.items():
351 sub_ext
= sub_info
['ext']
352 if ext
!= 'webm' or ext
== 'webm' and sub_ext
== 'vtt':
353 sub_langs
.append(lang
)
354 sub_filenames
.append(subtitles_filename(filename
, lang
, sub_ext
))
356 if not webm_vtt_warn
and ext
== 'webm' and sub_ext
!= 'vtt':
358 self
._downloader
.to_screen('[ffmpeg] Only WebVTT subtitles can be embedded in webm files')
361 return [], information
363 input_files
= [filename
] + sub_filenames
368 # Don't copy the existing subtitles, we may be running the
369 # postprocessor a second time
372 if information
['ext'] == 'mp4':
373 opts
+= ['-c:s', 'mov_text']
374 for (i
, lang
) in enumerate(sub_langs
):
375 opts
.extend(['-map', '%d:0' % (i
+ 1)])
376 lang_code
= ISO639Utils
.short2long(lang
)
377 if lang_code
is not None:
378 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
380 temp_filename
= prepend_extension(filename
, 'temp')
381 self
._downloader
.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename
)
382 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
383 os
.remove(encodeFilename(filename
))
384 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
386 return sub_filenames
, information
389 class FFmpegMetadataPP(FFmpegPostProcessor
):
393 def add(meta_list
, info_list
=None):
395 info_list
= meta_list
396 if not isinstance(meta_list
, (list, tuple)):
397 meta_list
= (meta_list
,)
398 if not isinstance(info_list
, (list, tuple)):
399 info_list
= (info_list
,)
400 for info_f
in info_list
:
401 if info
.get(info_f
) is not None:
402 for meta_f
in meta_list
:
403 metadata
[meta_f
] = info
[info_f
]
406 add('title', ('track', 'title'))
407 add('date', 'upload_date')
408 add(('description', 'comment'), 'description')
409 add('purl', 'webpage_url')
410 add('track', 'track_number')
411 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
415 add('disc', 'disc_number')
418 self
._downloader
.to_screen('[ffmpeg] There isn\'t any metadata to add')
421 filename
= info
['filepath']
422 temp_filename
= prepend_extension(filename
, 'temp')
424 if info
['ext'] == 'm4a':
425 options
= ['-vn', '-acodec', 'copy']
427 options
= ['-c', 'copy']
429 for (name
, value
) in metadata
.items():
430 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
432 self
._downloader
.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename
)
433 self
.run_ffmpeg(filename
, temp_filename
, options
)
434 os
.remove(encodeFilename(filename
))
435 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
439 class FFmpegMergerPP(FFmpegPostProcessor
):
441 filename
= info
['filepath']
442 temp_filename
= prepend_extension(filename
, 'temp')
443 args
= ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
444 self
._downloader
.to_screen('[ffmpeg] Merging formats into "%s"' % filename
)
445 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
446 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
447 return info
['__files_to_merge'], info
450 # TODO: figure out merge-capable ffmpeg version
451 if self
.basename
!= 'avconv':
454 required_version
= '10-0'
455 if is_outdated_version(
456 self
._versions
[self
.basename
], required_version
):
457 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
458 'youtube-dl will download single file media. '
459 'Update %s to version %s or newer to fix this.') % (
460 self
.basename
, self
.basename
, required_version
)
462 self
._downloader
.report_warning(warning
)
467 class FFmpegFixupStretchedPP(FFmpegPostProcessor
):
469 stretched_ratio
= info
.get('stretched_ratio')
470 if stretched_ratio
is None or stretched_ratio
== 1:
473 filename
= info
['filepath']
474 temp_filename
= prepend_extension(filename
, 'temp')
476 options
= ['-c', 'copy', '-aspect', '%f' % stretched_ratio
]
477 self
._downloader
.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename
)
478 self
.run_ffmpeg(filename
, temp_filename
, options
)
480 os
.remove(encodeFilename(filename
))
481 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
486 class FFmpegFixupM4aPP(FFmpegPostProcessor
):
488 if info
.get('container') != 'm4a_dash':
491 filename
= info
['filepath']
492 temp_filename
= prepend_extension(filename
, 'temp')
494 options
= ['-c', 'copy', '-f', 'mp4']
495 self
._downloader
.to_screen('[ffmpeg] Correcting container in "%s"' % filename
)
496 self
.run_ffmpeg(filename
, temp_filename
, options
)
498 os
.remove(encodeFilename(filename
))
499 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
504 class FFmpegFixupM3u8PP(FFmpegPostProcessor
):
506 filename
= info
['filepath']
507 temp_filename
= prepend_extension(filename
, 'temp')
509 options
= ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
510 self
._downloader
.to_screen('[ffmpeg] Fixing malformated aac bitstream in "%s"' % filename
)
511 self
.run_ffmpeg(filename
, temp_filename
, options
)
513 os
.remove(encodeFilename(filename
))
514 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
519 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
520 def __init__(self
, downloader
=None, format
=None):
521 super(FFmpegSubtitlesConvertorPP
, self
).__init
__(downloader
)
525 subs
= info
.get('requested_subtitles')
526 filename
= info
['filepath']
527 new_ext
= self
.format
529 if new_format
== 'vtt':
530 new_format
= 'webvtt'
532 self
._downloader
.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
534 self
._downloader
.to_screen('[ffmpeg] Converting subtitles')
536 for lang
, sub
in subs
.items():
539 self
._downloader
.to_screen(
540 '[ffmpeg] Subtitle file for %s is already in the requested'
543 old_file
= subtitles_filename(filename
, lang
, ext
)
544 sub_filenames
.append(old_file
)
545 new_file
= subtitles_filename(filename
, lang
, new_ext
)
547 if ext
== 'dfxp' or ext
== 'ttml' or ext
== 'tt':
548 self
._downloader
.report_warning(
549 'You have requested to convert dfxp (TTML) subtitles into another format, '
550 'which results in style information loss')
553 srt_file
= subtitles_filename(filename
, lang
, 'srt')
555 with io
.open(dfxp_file
, 'rt', encoding
='utf-8') as f
:
556 srt_data
= dfxp2srt(f
.read())
558 with io
.open(srt_file
, 'wt', encoding
='utf-8') as f
:
570 sub_filenames
.append(srt_file
)
572 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
574 with io
.open(new_file
, 'rt', encoding
='utf-8') as f
:
580 return sub_filenames
, info