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)
181 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
182 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
183 FFmpegPostProcessor
.__init
__(self
, downloader
)
184 if preferredcodec
is None:
185 preferredcodec
= 'best'
186 self
._preferredcodec
= preferredcodec
187 self
._preferredquality
= preferredquality
188 self
._nopostoverwrites
= nopostoverwrites
190 def get_audio_codec(self
, path
):
192 if not self
.probe_available
:
193 raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
196 encodeFilename(self
.probe_executable
, True),
197 encodeArgument('-show_streams'),
198 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)]
199 if self
._downloader
.params
.get('verbose', False):
200 self
._downloader
.to_screen('[debug] %s command line: %s' % (self
.basename
, shell_quote(cmd
)))
201 handle
= subprocess
.Popen(cmd
, stderr
=compat_subprocess_get_DEVNULL(), stdout
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
202 output
= handle
.communicate()[0]
203 if handle
.wait() != 0:
205 except (IOError, OSError):
208 for line
in output
.decode('ascii', 'ignore').split('\n'):
209 if line
.startswith('codec_name='):
210 audio_codec
= line
.split('=')[1].strip()
211 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
215 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
219 acodec_opts
= ['-acodec', codec
]
220 opts
= ['-vn'] + acodec_opts
+ more_opts
222 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
223 except FFmpegPostProcessorError
as err
:
224 raise AudioConversionError(err
.msg
)
226 def run(self
, information
):
227 path
= information
['filepath']
229 filecodec
= self
.get_audio_codec(path
)
230 if filecodec
is None:
231 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
234 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
235 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
236 # Lossless, but in another container
239 more_opts
= ['-bsf:a', 'aac_adtstoasc']
240 elif filecodec
in ['aac', 'mp3', 'vorbis', 'opus']:
241 # Lossless if possible
243 extension
= filecodec
244 if filecodec
== 'aac':
245 more_opts
= ['-f', 'adts']
246 if filecodec
== 'vorbis':
250 acodec
= 'libmp3lame'
253 if self
._preferredquality
is not None:
254 if int(self
._preferredquality
) < 10:
255 more_opts
+= ['-q:a', self
._preferredquality
]
257 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
259 # We convert the audio (lossy)
260 acodec
= {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}
[self
._preferredcodec
]
261 extension
= self
._preferredcodec
263 if self
._preferredquality
is not None:
264 # The opus codec doesn't support the -aq option
265 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
266 more_opts
+= ['-q:a', self
._preferredquality
]
268 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
269 if self
._preferredcodec
== 'aac':
270 more_opts
+= ['-f', 'adts']
271 if self
._preferredcodec
== 'm4a':
272 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
273 if self
._preferredcodec
== 'vorbis':
275 if self
._preferredcodec
== 'wav':
277 more_opts
+= ['-f', 'wav']
279 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
280 new_path
= prefix
+ sep
+ extension
282 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
283 if (new_path
== path
or
284 (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)))):
285 self
._downloader
.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path
)
286 return [], information
289 self
._downloader
.to_screen('[ffmpeg] Destination: ' + new_path
)
290 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
291 except AudioConversionError
as e
:
292 raise PostProcessingError(
293 'audio conversion failed: ' + e
.msg
)
295 raise PostProcessingError('error running ' + self
.basename
)
297 # Try to update the date time for extracted audio file.
298 if information
.get('filetime') is not None:
300 new_path
, time
.time(), information
['filetime'],
301 errnote
='Cannot update utime of audio file')
303 information
['filepath'] = new_path
304 information
['ext'] = extension
306 return [path
], information
309 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
310 def __init__(self
, downloader
=None, preferedformat
=None):
311 super(FFmpegVideoConvertorPP
, self
).__init
__(downloader
)
312 self
._preferedformat
= preferedformat
314 def run(self
, information
):
315 path
= information
['filepath']
316 if information
['ext'] == self
._preferedformat
:
317 self
._downloader
.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path
, self
._preferedformat
))
318 return [], information
320 if self
._preferedformat
== 'avi':
321 options
.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
322 prefix
, sep
, ext
= path
.rpartition('.')
323 outpath
= prefix
+ sep
+ self
._preferedformat
324 self
._downloader
.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information
['ext'], self
._preferedformat
) + outpath
)
325 self
.run_ffmpeg(path
, outpath
, options
)
326 information
['filepath'] = outpath
327 information
['format'] = self
._preferedformat
328 information
['ext'] = self
._preferedformat
329 return [path
], information
332 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
333 def run(self
, information
):
334 if information
['ext'] not in ('mp4', 'webm', 'mkv'):
335 self
._downloader
.to_screen('[ffmpeg] Subtitles can only be embedded in mp4, webm or mkv files')
336 return [], information
337 subtitles
= information
.get('requested_subtitles')
339 self
._downloader
.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
340 return [], information
342 filename
= information
['filepath']
344 ext
= information
['ext']
347 webm_vtt_warn
= False
349 for lang
, sub_info
in subtitles
.items():
350 sub_ext
= sub_info
['ext']
351 if ext
!= 'webm' or ext
== 'webm' and sub_ext
== 'vtt':
352 sub_langs
.append(lang
)
353 sub_filenames
.append(subtitles_filename(filename
, lang
, sub_ext
))
355 if not webm_vtt_warn
and ext
== 'webm' and sub_ext
!= 'vtt':
357 self
._downloader
.to_screen('[ffmpeg] Only WebVTT subtitles can be embedded in webm files')
360 return [], information
362 input_files
= [filename
] + sub_filenames
367 # Don't copy the existing subtitles, we may be running the
368 # postprocessor a second time
371 if information
['ext'] == 'mp4':
372 opts
+= ['-c:s', 'mov_text']
373 for (i
, lang
) in enumerate(sub_langs
):
374 opts
.extend(['-map', '%d:0' % (i
+ 1)])
375 lang_code
= ISO639Utils
.short2long(lang
)
376 if lang_code
is not None:
377 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
379 temp_filename
= prepend_extension(filename
, 'temp')
380 self
._downloader
.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename
)
381 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
382 os
.remove(encodeFilename(filename
))
383 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
385 return sub_filenames
, information
388 class FFmpegMetadataPP(FFmpegPostProcessor
):
391 if info
.get('title') is not None:
392 metadata
['title'] = info
['title']
393 if info
.get('upload_date') is not None:
394 metadata
['date'] = info
['upload_date']
395 if info
.get('artist') is not None:
396 metadata
['artist'] = info
['artist']
397 elif info
.get('uploader') is not None:
398 metadata
['artist'] = info
['uploader']
399 elif info
.get('uploader_id') is not None:
400 metadata
['artist'] = info
['uploader_id']
401 if info
.get('description') is not None:
402 metadata
['description'] = info
['description']
403 metadata
['comment'] = info
['description']
404 if info
.get('webpage_url') is not None:
405 metadata
['purl'] = info
['webpage_url']
406 if info
.get('album') is not None:
407 metadata
['album'] = info
['album']
410 self
._downloader
.to_screen('[ffmpeg] There isn\'t any metadata to add')
413 filename
= info
['filepath']
414 temp_filename
= prepend_extension(filename
, 'temp')
416 if info
['ext'] == 'm4a':
417 options
= ['-vn', '-acodec', 'copy']
419 options
= ['-c', 'copy']
421 for (name
, value
) in metadata
.items():
422 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
424 self
._downloader
.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename
)
425 self
.run_ffmpeg(filename
, temp_filename
, options
)
426 os
.remove(encodeFilename(filename
))
427 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
431 class FFmpegMergerPP(FFmpegPostProcessor
):
433 filename
= info
['filepath']
434 temp_filename
= prepend_extension(filename
, 'temp')
435 args
= ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
436 self
._downloader
.to_screen('[ffmpeg] Merging formats into "%s"' % filename
)
437 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
438 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
439 return info
['__files_to_merge'], info
442 # TODO: figure out merge-capable ffmpeg version
443 if self
.basename
!= 'avconv':
446 required_version
= '10-0'
447 if is_outdated_version(
448 self
._versions
[self
.basename
], required_version
):
449 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
450 'youtube-dl will download single file media. '
451 'Update %s to version %s or newer to fix this.') % (
452 self
.basename
, self
.basename
, required_version
)
454 self
._downloader
.report_warning(warning
)
459 class FFmpegFixupStretchedPP(FFmpegPostProcessor
):
461 stretched_ratio
= info
.get('stretched_ratio')
462 if stretched_ratio
is None or stretched_ratio
== 1:
465 filename
= info
['filepath']
466 temp_filename
= prepend_extension(filename
, 'temp')
468 options
= ['-c', 'copy', '-aspect', '%f' % stretched_ratio
]
469 self
._downloader
.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename
)
470 self
.run_ffmpeg(filename
, temp_filename
, options
)
472 os
.remove(encodeFilename(filename
))
473 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
478 class FFmpegFixupM4aPP(FFmpegPostProcessor
):
480 if info
.get('container') != 'm4a_dash':
483 filename
= info
['filepath']
484 temp_filename
= prepend_extension(filename
, 'temp')
486 options
= ['-c', 'copy', '-f', 'mp4']
487 self
._downloader
.to_screen('[ffmpeg] Correcting container in "%s"' % filename
)
488 self
.run_ffmpeg(filename
, temp_filename
, options
)
490 os
.remove(encodeFilename(filename
))
491 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
496 class FFmpegFixupM3u8PP(FFmpegPostProcessor
):
498 filename
= info
['filepath']
499 temp_filename
= prepend_extension(filename
, 'temp')
501 options
= ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
502 self
._downloader
.to_screen('[ffmpeg] Fixing malformated aac bitstream in "%s"' % filename
)
503 self
.run_ffmpeg(filename
, temp_filename
, options
)
505 os
.remove(encodeFilename(filename
))
506 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
511 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
512 def __init__(self
, downloader
=None, format
=None):
513 super(FFmpegSubtitlesConvertorPP
, self
).__init
__(downloader
)
517 subs
= info
.get('requested_subtitles')
518 filename
= info
['filepath']
519 new_ext
= self
.format
521 if new_format
== 'vtt':
522 new_format
= 'webvtt'
524 self
._downloader
.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
526 self
._downloader
.to_screen('[ffmpeg] Converting subtitles')
528 for lang
, sub
in subs
.items():
531 self
._downloader
.to_screen(
532 '[ffmpeg] Subtitle file for %s is already in the requested'
535 old_file
= subtitles_filename(filename
, lang
, ext
)
536 sub_filenames
.append(old_file
)
537 new_file
= subtitles_filename(filename
, lang
, new_ext
)
539 if ext
== 'dfxp' or ext
== 'ttml':
540 self
._downloader
.report_warning(
541 'You have requested to convert dfxp (TTML) subtitles into another format, '
542 'which results in style information loss')
545 srt_file
= subtitles_filename(filename
, lang
, 'srt')
547 with io
.open(dfxp_file
, 'rt', encoding
='utf-8') as f
:
548 srt_data
= dfxp2srt(f
.read())
550 with io
.open(srt_file
, 'wt', encoding
='utf-8') as f
:
562 sub_filenames
.append(srt_file
)
564 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
566 with io
.open(new_file
, 'rt', encoding
='utf-8') as f
:
572 return sub_filenames
, info