]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/postprocessor/ffmpeg.py
Imported Upstream version 2015.11.27.1
[youtubedl] / youtube_dl / postprocessor / ffmpeg.py
1 from __future__ import unicode_literals
2
3 import io
4 import os
5 import subprocess
6 import time
7
8
9 from .common import AudioConversionError, PostProcessor
10
11 from ..compat import (
12 compat_subprocess_get_DEVNULL,
13 )
14 from ..utils import (
15 encodeArgument,
16 encodeFilename,
17 get_exe_version,
18 is_outdated_version,
19 PostProcessingError,
20 prepend_extension,
21 shell_quote,
22 subtitles_filename,
23 dfxp2srt,
24 ISO639Utils,
25 )
26
27
28 class FFmpegPostProcessorError(PostProcessingError):
29 pass
30
31
32 class FFmpegPostProcessor(PostProcessor):
33 def __init__(self, downloader=None):
34 PostProcessor.__init__(self, downloader)
35 self._determine_executables()
36
37 def check_version(self):
38 if not self.available:
39 raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
40
41 required_version = '10-0' if self.basename == 'avconv' else '1.0'
42 if is_outdated_version(
43 self._versions[self.basename], required_version):
44 warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
45 self.basename, self.basename, required_version)
46 if self._downloader:
47 self._downloader.report_warning(warning)
48
49 @staticmethod
50 def get_versions(downloader=None):
51 return FFmpegPostProcessor(downloader)._versions
52
53 def _determine_executables(self):
54 programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
55 prefer_ffmpeg = self._downloader.params.get('prefer_ffmpeg', False)
56
57 self.basename = None
58 self.probe_basename = None
59
60 self._paths = None
61 self._versions = None
62 if self._downloader:
63 location = self._downloader.params.get('ffmpeg_location')
64 if location is not None:
65 if not os.path.exists(location):
66 self._downloader.report_warning(
67 'ffmpeg-location %s does not exist! '
68 'Continuing without avconv/ffmpeg.' % (location))
69 self._versions = {}
70 return
71 elif not os.path.isdir(location):
72 basename = os.path.splitext(os.path.basename(location))[0]
73 if basename not in programs:
74 self._downloader.report_warning(
75 'Cannot identify executable %s, its basename should be one of %s. '
76 'Continuing without avconv/ffmpeg.' %
77 (location, ', '.join(programs)))
78 self._versions = {}
79 return None
80 location = os.path.dirname(os.path.abspath(location))
81 if basename in ('ffmpeg', 'ffprobe'):
82 prefer_ffmpeg = True
83
84 self._paths = dict(
85 (p, os.path.join(location, p)) for p in programs)
86 self._versions = dict(
87 (p, get_exe_version(self._paths[p], args=['-version']))
88 for p in programs)
89 if self._versions is None:
90 self._versions = dict(
91 (p, get_exe_version(p, args=['-version'])) for p in programs)
92 self._paths = dict((p, p) for p in programs)
93
94 if prefer_ffmpeg:
95 prefs = ('ffmpeg', 'avconv')
96 else:
97 prefs = ('avconv', 'ffmpeg')
98 for p in prefs:
99 if self._versions[p]:
100 self.basename = p
101 break
102
103 if prefer_ffmpeg:
104 prefs = ('ffprobe', 'avprobe')
105 else:
106 prefs = ('avprobe', 'ffprobe')
107 for p in prefs:
108 if self._versions[p]:
109 self.probe_basename = p
110 break
111
112 @property
113 def available(self):
114 return self.basename is not None
115
116 @property
117 def executable(self):
118 return self._paths[self.basename]
119
120 @property
121 def probe_available(self):
122 return self.probe_basename is not None
123
124 @property
125 def probe_executable(self):
126 return self._paths[self.probe_basename]
127
128 def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
129 self.check_version()
130
131 oldest_mtime = min(
132 os.stat(encodeFilename(path)).st_mtime for path in input_paths)
133
134 opts += self._configuration_args()
135
136 files_cmd = []
137 for path in input_paths:
138 files_cmd.extend([
139 encodeArgument('-i'),
140 encodeFilename(self._ffmpeg_filename_argument(path), True)
141 ])
142 cmd = ([encodeFilename(self.executable, True), encodeArgument('-y')] +
143 files_cmd +
144 [encodeArgument(o) for o in opts] +
145 [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
146
147 if self._downloader.params.get('verbose', False):
148 self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
149 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
150 stdout, stderr = p.communicate()
151 if p.returncode != 0:
152 stderr = stderr.decode('utf-8', 'replace')
153 msg = stderr.strip().split('\n')[-1]
154 raise FFmpegPostProcessorError(msg)
155 self.try_utime(out_path, oldest_mtime, oldest_mtime)
156
157 def run_ffmpeg(self, path, out_path, opts):
158 self.run_ffmpeg_multiple_files([path], out_path, opts)
159
160 def _ffmpeg_filename_argument(self, fn):
161 # Always use 'file:' because the filename may contain ':' (ffmpeg
162 # interprets that as a protocol) or can start with '-' (-- is broken in
163 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
164 return 'file:' + fn
165
166
167 class FFmpegExtractAudioPP(FFmpegPostProcessor):
168 def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
169 FFmpegPostProcessor.__init__(self, downloader)
170 if preferredcodec is None:
171 preferredcodec = 'best'
172 self._preferredcodec = preferredcodec
173 self._preferredquality = preferredquality
174 self._nopostoverwrites = nopostoverwrites
175
176 def get_audio_codec(self, path):
177
178 if not self.probe_available:
179 raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
180 try:
181 cmd = [
182 encodeFilename(self.probe_executable, True),
183 encodeArgument('-show_streams'),
184 encodeFilename(self._ffmpeg_filename_argument(path), True)]
185 if self._downloader.params.get('verbose', False):
186 self._downloader.to_screen('[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
187 handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE, stdin=subprocess.PIPE)
188 output = handle.communicate()[0]
189 if handle.wait() != 0:
190 return None
191 except (IOError, OSError):
192 return None
193 audio_codec = None
194 for line in output.decode('ascii', 'ignore').split('\n'):
195 if line.startswith('codec_name='):
196 audio_codec = line.split('=')[1].strip()
197 elif line.strip() == 'codec_type=audio' and audio_codec is not None:
198 return audio_codec
199 return None
200
201 def run_ffmpeg(self, path, out_path, codec, more_opts):
202 if codec is None:
203 acodec_opts = []
204 else:
205 acodec_opts = ['-acodec', codec]
206 opts = ['-vn'] + acodec_opts + more_opts
207 try:
208 FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
209 except FFmpegPostProcessorError as err:
210 raise AudioConversionError(err.msg)
211
212 def run(self, information):
213 path = information['filepath']
214
215 filecodec = self.get_audio_codec(path)
216 if filecodec is None:
217 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
218
219 more_opts = []
220 if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
221 if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
222 # Lossless, but in another container
223 acodec = 'copy'
224 extension = 'm4a'
225 more_opts = ['-bsf:a', 'aac_adtstoasc']
226 elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
227 # Lossless if possible
228 acodec = 'copy'
229 extension = filecodec
230 if filecodec == 'aac':
231 more_opts = ['-f', 'adts']
232 if filecodec == 'vorbis':
233 extension = 'ogg'
234 else:
235 # MP3 otherwise.
236 acodec = 'libmp3lame'
237 extension = 'mp3'
238 more_opts = []
239 if self._preferredquality is not None:
240 if int(self._preferredquality) < 10:
241 more_opts += ['-q:a', self._preferredquality]
242 else:
243 more_opts += ['-b:a', self._preferredquality + 'k']
244 else:
245 # We convert the audio (lossy)
246 acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
247 extension = self._preferredcodec
248 more_opts = []
249 if self._preferredquality is not None:
250 # The opus codec doesn't support the -aq option
251 if int(self._preferredquality) < 10 and extension != 'opus':
252 more_opts += ['-q:a', self._preferredquality]
253 else:
254 more_opts += ['-b:a', self._preferredquality + 'k']
255 if self._preferredcodec == 'aac':
256 more_opts += ['-f', 'adts']
257 if self._preferredcodec == 'm4a':
258 more_opts += ['-bsf:a', 'aac_adtstoasc']
259 if self._preferredcodec == 'vorbis':
260 extension = 'ogg'
261 if self._preferredcodec == 'wav':
262 extension = 'wav'
263 more_opts += ['-f', 'wav']
264
265 prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
266 new_path = prefix + sep + extension
267
268 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
269 if (new_path == path or
270 (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
271 self._downloader.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path)
272 return [], information
273
274 try:
275 self._downloader.to_screen('[ffmpeg] Destination: ' + new_path)
276 self.run_ffmpeg(path, new_path, acodec, more_opts)
277 except AudioConversionError as e:
278 raise PostProcessingError(
279 'audio conversion failed: ' + e.msg)
280 except Exception:
281 raise PostProcessingError('error running ' + self.basename)
282
283 # Try to update the date time for extracted audio file.
284 if information.get('filetime') is not None:
285 self.try_utime(
286 new_path, time.time(), information['filetime'],
287 errnote='Cannot update utime of audio file')
288
289 information['filepath'] = new_path
290 information['ext'] = extension
291
292 return [path], information
293
294
295 class FFmpegVideoConvertorPP(FFmpegPostProcessor):
296 def __init__(self, downloader=None, preferedformat=None):
297 super(FFmpegVideoConvertorPP, self).__init__(downloader)
298 self._preferedformat = preferedformat
299
300 def run(self, information):
301 path = information['filepath']
302 if information['ext'] == self._preferedformat:
303 self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
304 return [], information
305 options = []
306 if self._preferedformat == 'avi':
307 options.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
308 prefix, sep, ext = path.rpartition('.')
309 outpath = prefix + sep + self._preferedformat
310 self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
311 self.run_ffmpeg(path, outpath, options)
312 information['filepath'] = outpath
313 information['format'] = self._preferedformat
314 information['ext'] = self._preferedformat
315 return [path], information
316
317
318 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
319 def run(self, information):
320 if information['ext'] not in ['mp4', 'mkv']:
321 self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4 or mkv files')
322 return [], information
323 subtitles = information.get('requested_subtitles')
324 if not subtitles:
325 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
326 return [], information
327
328 sub_langs = list(subtitles.keys())
329 filename = information['filepath']
330 sub_filenames = [subtitles_filename(filename, lang, sub_info['ext']) for lang, sub_info in subtitles.items()]
331 input_files = [filename] + sub_filenames
332
333 opts = [
334 '-map', '0',
335 '-c', 'copy',
336 # Don't copy the existing subtitles, we may be running the
337 # postprocessor a second time
338 '-map', '-0:s',
339 ]
340 if information['ext'] == 'mp4':
341 opts += ['-c:s', 'mov_text']
342 for (i, lang) in enumerate(sub_langs):
343 opts.extend(['-map', '%d:0' % (i + 1)])
344 lang_code = ISO639Utils.short2long(lang)
345 if lang_code is not None:
346 opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
347
348 temp_filename = prepend_extension(filename, 'temp')
349 self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
350 self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
351 os.remove(encodeFilename(filename))
352 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
353
354 return sub_filenames, information
355
356
357 class FFmpegMetadataPP(FFmpegPostProcessor):
358 def run(self, info):
359 metadata = {}
360 if info.get('title') is not None:
361 metadata['title'] = info['title']
362 if info.get('upload_date') is not None:
363 metadata['date'] = info['upload_date']
364 if info.get('artist') is not None:
365 metadata['artist'] = info['artist']
366 elif info.get('uploader') is not None:
367 metadata['artist'] = info['uploader']
368 elif info.get('uploader_id') is not None:
369 metadata['artist'] = info['uploader_id']
370 if info.get('description') is not None:
371 metadata['description'] = info['description']
372 metadata['comment'] = info['description']
373 if info.get('webpage_url') is not None:
374 metadata['purl'] = info['webpage_url']
375 if info.get('album') is not None:
376 metadata['album'] = info['album']
377
378 if not metadata:
379 self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
380 return [], info
381
382 filename = info['filepath']
383 temp_filename = prepend_extension(filename, 'temp')
384
385 if info['ext'] == 'm4a':
386 options = ['-vn', '-acodec', 'copy']
387 else:
388 options = ['-c', 'copy']
389
390 for (name, value) in metadata.items():
391 options.extend(['-metadata', '%s=%s' % (name, value)])
392
393 self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
394 self.run_ffmpeg(filename, temp_filename, options)
395 os.remove(encodeFilename(filename))
396 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
397 return [], info
398
399
400 class FFmpegMergerPP(FFmpegPostProcessor):
401 def run(self, info):
402 filename = info['filepath']
403 temp_filename = prepend_extension(filename, 'temp')
404 args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
405 self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
406 self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
407 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
408 return info['__files_to_merge'], info
409
410 def can_merge(self):
411 # TODO: figure out merge-capable ffmpeg version
412 if self.basename != 'avconv':
413 return True
414
415 required_version = '10-0'
416 if is_outdated_version(
417 self._versions[self.basename], required_version):
418 warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
419 'youtube-dl will download single file media. '
420 'Update %s to version %s or newer to fix this.') % (
421 self.basename, self.basename, required_version)
422 if self._downloader:
423 self._downloader.report_warning(warning)
424 return False
425 return True
426
427
428 class FFmpegFixupStretchedPP(FFmpegPostProcessor):
429 def run(self, info):
430 stretched_ratio = info.get('stretched_ratio')
431 if stretched_ratio is None or stretched_ratio == 1:
432 return [], info
433
434 filename = info['filepath']
435 temp_filename = prepend_extension(filename, 'temp')
436
437 options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
438 self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
439 self.run_ffmpeg(filename, temp_filename, options)
440
441 os.remove(encodeFilename(filename))
442 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
443
444 return [], info
445
446
447 class FFmpegFixupM4aPP(FFmpegPostProcessor):
448 def run(self, info):
449 if info.get('container') != 'm4a_dash':
450 return [], info
451
452 filename = info['filepath']
453 temp_filename = prepend_extension(filename, 'temp')
454
455 options = ['-c', 'copy', '-f', 'mp4']
456 self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
457 self.run_ffmpeg(filename, temp_filename, options)
458
459 os.remove(encodeFilename(filename))
460 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
461
462 return [], info
463
464
465 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
466 def __init__(self, downloader=None, format=None):
467 super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
468 self.format = format
469
470 def run(self, info):
471 subs = info.get('requested_subtitles')
472 filename = info['filepath']
473 new_ext = self.format
474 new_format = new_ext
475 if new_format == 'vtt':
476 new_format = 'webvtt'
477 if subs is None:
478 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
479 return [], info
480 self._downloader.to_screen('[ffmpeg] Converting subtitles')
481 for lang, sub in subs.items():
482 ext = sub['ext']
483 if ext == new_ext:
484 self._downloader.to_screen(
485 '[ffmpeg] Subtitle file for %s is already in the requested'
486 'format' % new_ext)
487 continue
488 new_file = subtitles_filename(filename, lang, new_ext)
489
490 if ext == 'dfxp' or ext == 'ttml':
491 self._downloader.report_warning(
492 'You have requested to convert dfxp (TTML) subtitles into another format, '
493 'which results in style information loss')
494
495 dfxp_file = subtitles_filename(filename, lang, ext)
496 srt_file = subtitles_filename(filename, lang, 'srt')
497
498 with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
499 srt_data = dfxp2srt(f.read())
500
501 with io.open(srt_file, 'wt', encoding='utf-8') as f:
502 f.write(srt_data)
503
504 ext = 'srt'
505 subs[lang] = {
506 'ext': 'srt',
507 'data': srt_data
508 }
509
510 if new_ext == 'srt':
511 continue
512
513 self.run_ffmpeg(
514 subtitles_filename(filename, lang, ext),
515 new_file, ['-f', new_format])
516
517 with io.open(new_file, 'rt', encoding='utf-8') as f:
518 subs[lang] = {
519 'ext': ext,
520 'data': f.read(),
521 }
522
523 return [], info