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 get_audio_codec(self
, path
):
143 if not self
.probe_available
:
144 raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
147 encodeFilename(self
.probe_executable
, True),
148 encodeArgument('-show_streams'),
149 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)]
150 if self
._downloader
.params
.get('verbose', False):
151 self
._downloader
.to_screen('[debug] %s command line: %s' % (self
.basename
, shell_quote(cmd
)))
152 handle
= subprocess
.Popen(cmd
, stderr
=compat_subprocess_get_DEVNULL(), stdout
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
153 output
= handle
.communicate()[0]
154 if handle
.wait() != 0:
156 except (IOError, OSError):
159 for line
in output
.decode('ascii', 'ignore').split('\n'):
160 if line
.startswith('codec_name='):
161 audio_codec
= line
.split('=')[1].strip()
162 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
166 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
):
170 os
.stat(encodeFilename(path
)).st_mtime
for path
in input_paths
)
172 opts
+= self
._configuration
_args
()
175 for path
in input_paths
:
177 encodeArgument('-i'),
178 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)
180 cmd
= ([encodeFilename(self
.executable
, True), encodeArgument('-y')] +
182 [encodeArgument(o
) for o
in opts
] +
183 [encodeFilename(self
._ffmpeg
_filename
_argument
(out_path
), True)])
185 if self
._downloader
.params
.get('verbose', False):
186 self
._downloader
.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd
))
187 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
188 stdout
, stderr
= p
.communicate()
189 if p
.returncode
!= 0:
190 stderr
= stderr
.decode('utf-8', 'replace')
191 msg
= stderr
.strip().split('\n')[-1]
192 raise FFmpegPostProcessorError(msg
)
193 self
.try_utime(out_path
, oldest_mtime
, oldest_mtime
)
195 def run_ffmpeg(self
, path
, out_path
, opts
):
196 self
.run_ffmpeg_multiple_files([path
], out_path
, opts
)
198 def _ffmpeg_filename_argument(self
, fn
):
199 # Always use 'file:' because the filename may contain ':' (ffmpeg
200 # interprets that as a protocol) or can start with '-' (-- is broken in
201 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
202 # Also leave '-' intact in order not to break streaming to stdout.
203 return 'file:' + fn
if fn
!= '-' else fn
206 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
207 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
208 FFmpegPostProcessor
.__init
__(self
, downloader
)
209 if preferredcodec
is None:
210 preferredcodec
= 'best'
211 self
._preferredcodec
= preferredcodec
212 self
._preferredquality
= preferredquality
213 self
._nopostoverwrites
= nopostoverwrites
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 information
['filepath'] = new_path
283 information
['ext'] = extension
285 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
286 if (new_path
== path
or
287 (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)))):
288 self
._downloader
.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path
)
289 return [], information
292 self
._downloader
.to_screen('[ffmpeg] Destination: ' + new_path
)
293 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
294 except AudioConversionError
as e
:
295 raise PostProcessingError(
296 'audio conversion failed: ' + e
.msg
)
298 raise PostProcessingError('error running ' + self
.basename
)
300 # Try to update the date time for extracted audio file.
301 if information
.get('filetime') is not None:
303 new_path
, time
.time(), information
['filetime'],
304 errnote
='Cannot update utime of audio file')
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
):
392 def add(meta_list
, info_list
=None):
394 info_list
= meta_list
395 if not isinstance(meta_list
, (list, tuple)):
396 meta_list
= (meta_list
,)
397 if not isinstance(info_list
, (list, tuple)):
398 info_list
= (info_list
,)
399 for info_f
in info_list
:
400 if info
.get(info_f
) is not None:
401 for meta_f
in meta_list
:
402 metadata
[meta_f
] = info
[info_f
]
405 add('title', ('track', 'title'))
406 add('date', 'upload_date')
407 add(('description', 'comment'), 'description')
408 add('purl', 'webpage_url')
409 add('track', 'track_number')
410 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
414 add('disc', 'disc_number')
417 self
._downloader
.to_screen('[ffmpeg] There isn\'t any metadata to add')
420 filename
= info
['filepath']
421 temp_filename
= prepend_extension(filename
, 'temp')
423 if info
['ext'] == 'm4a':
424 options
= ['-vn', '-acodec', 'copy']
426 options
= ['-c', 'copy']
428 for (name
, value
) in metadata
.items():
429 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
431 self
._downloader
.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename
)
432 self
.run_ffmpeg(filename
, temp_filename
, options
)
433 os
.remove(encodeFilename(filename
))
434 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
438 class FFmpegMergerPP(FFmpegPostProcessor
):
440 filename
= info
['filepath']
441 temp_filename
= prepend_extension(filename
, 'temp')
442 args
= ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
443 self
._downloader
.to_screen('[ffmpeg] Merging formats into "%s"' % filename
)
444 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
445 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
446 return info
['__files_to_merge'], info
449 # TODO: figure out merge-capable ffmpeg version
450 if self
.basename
!= 'avconv':
453 required_version
= '10-0'
454 if is_outdated_version(
455 self
._versions
[self
.basename
], required_version
):
456 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
457 'youtube-dl will download single file media. '
458 'Update %s to version %s or newer to fix this.') % (
459 self
.basename
, self
.basename
, required_version
)
461 self
._downloader
.report_warning(warning
)
466 class FFmpegFixupStretchedPP(FFmpegPostProcessor
):
468 stretched_ratio
= info
.get('stretched_ratio')
469 if stretched_ratio
is None or stretched_ratio
== 1:
472 filename
= info
['filepath']
473 temp_filename
= prepend_extension(filename
, 'temp')
475 options
= ['-c', 'copy', '-aspect', '%f' % stretched_ratio
]
476 self
._downloader
.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename
)
477 self
.run_ffmpeg(filename
, temp_filename
, options
)
479 os
.remove(encodeFilename(filename
))
480 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
485 class FFmpegFixupM4aPP(FFmpegPostProcessor
):
487 if info
.get('container') != 'm4a_dash':
490 filename
= info
['filepath']
491 temp_filename
= prepend_extension(filename
, 'temp')
493 options
= ['-c', 'copy', '-f', 'mp4']
494 self
._downloader
.to_screen('[ffmpeg] Correcting container in "%s"' % filename
)
495 self
.run_ffmpeg(filename
, temp_filename
, options
)
497 os
.remove(encodeFilename(filename
))
498 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
503 class FFmpegFixupM3u8PP(FFmpegPostProcessor
):
505 filename
= info
['filepath']
506 if self
.get_audio_codec(filename
) == 'aac':
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
))
518 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
519 def __init__(self
, downloader
=None, format
=None):
520 super(FFmpegSubtitlesConvertorPP
, self
).__init
__(downloader
)
524 subs
= info
.get('requested_subtitles')
525 filename
= info
['filepath']
526 new_ext
= self
.format
528 if new_format
== 'vtt':
529 new_format
= 'webvtt'
531 self
._downloader
.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
533 self
._downloader
.to_screen('[ffmpeg] Converting subtitles')
535 for lang
, sub
in subs
.items():
538 self
._downloader
.to_screen(
539 '[ffmpeg] Subtitle file for %s is already in the requested format' % new_ext
)
541 old_file
= subtitles_filename(filename
, lang
, ext
)
542 sub_filenames
.append(old_file
)
543 new_file
= subtitles_filename(filename
, lang
, new_ext
)
545 if ext
== 'dfxp' or ext
== 'ttml' or ext
== 'tt':
546 self
._downloader
.report_warning(
547 'You have requested to convert dfxp (TTML) subtitles into another format, '
548 'which results in style information loss')
551 srt_file
= subtitles_filename(filename
, lang
, 'srt')
553 with io
.open(dfxp_file
, 'rt', encoding
='utf-8') as f
:
554 srt_data
= dfxp2srt(f
.read())
556 with io
.open(srt_file
, 'wt', encoding
='utf-8') as f
:
568 sub_filenames
.append(srt_file
)
570 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
572 with io
.open(new_file
, 'rt', encoding
='utf-8') as f
:
578 return sub_filenames
, info