]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/postprocessor/ffmpeg.py
New upstream version 2017.03.26
[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 EXT_TO_OUT_FORMATS = {
29 'aac': 'adts',
30 'flac': 'flac',
31 'm4a': 'ipod',
32 'mka': 'matroska',
33 'mkv': 'matroska',
34 'mpg': 'mpeg',
35 'ogv': 'ogg',
36 'ts': 'mpegts',
37 'wma': 'asf',
38 'wmv': 'asf',
39 }
40 ACODECS = {
41 'mp3': 'libmp3lame',
42 'aac': 'aac',
43 'flac': 'flac',
44 'm4a': 'aac',
45 'opus': 'opus',
46 'vorbis': 'libvorbis',
47 'wav': None,
48 }
49
50
51 class FFmpegPostProcessorError(PostProcessingError):
52 pass
53
54
55 class FFmpegPostProcessor(PostProcessor):
56 def __init__(self, downloader=None):
57 PostProcessor.__init__(self, downloader)
58 self._determine_executables()
59
60 def check_version(self):
61 if not self.available:
62 raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
63
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)
69 if self._downloader:
70 self._downloader.report_warning(warning)
71
72 @staticmethod
73 def get_versions(downloader=None):
74 return FFmpegPostProcessor(downloader)._versions
75
76 def _determine_executables(self):
77 programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
78 prefer_ffmpeg = False
79
80 self.basename = None
81 self.probe_basename = None
82
83 self._paths = None
84 self._versions = None
85 if self._downloader:
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))
93 self._versions = {}
94 return
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)))
102 self._versions = {}
103 return None
104 location = os.path.dirname(os.path.abspath(location))
105 if basename in ('ffmpeg', 'ffprobe'):
106 prefer_ffmpeg = True
107
108 self._paths = dict(
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']))
112 for p in programs)
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)
117
118 if prefer_ffmpeg:
119 prefs = ('ffmpeg', 'avconv')
120 else:
121 prefs = ('avconv', 'ffmpeg')
122 for p in prefs:
123 if self._versions[p]:
124 self.basename = p
125 break
126
127 if prefer_ffmpeg:
128 prefs = ('ffprobe', 'avprobe')
129 else:
130 prefs = ('avprobe', 'ffprobe')
131 for p in prefs:
132 if self._versions[p]:
133 self.probe_basename = p
134 break
135
136 @property
137 def available(self):
138 return self.basename is not None
139
140 @property
141 def executable(self):
142 return self._paths[self.basename]
143
144 @property
145 def probe_available(self):
146 return self.probe_basename is not None
147
148 @property
149 def probe_executable(self):
150 return self._paths[self.probe_basename]
151
152 def get_audio_codec(self, path):
153 if not self.probe_available:
154 raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
155 try:
156 cmd = [
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:
165 return None
166 except (IOError, OSError):
167 return None
168 audio_codec = None
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:
173 return audio_codec
174 return None
175
176 def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
177 self.check_version()
178
179 oldest_mtime = min(
180 os.stat(encodeFilename(path)).st_mtime for path in input_paths)
181
182 opts += self._configuration_args()
183
184 files_cmd = []
185 for path in input_paths:
186 files_cmd.extend([
187 encodeArgument('-i'),
188 encodeFilename(self._ffmpeg_filename_argument(path), True)
189 ])
190 cmd = ([encodeFilename(self.executable, True), encodeArgument('-y')] +
191 files_cmd +
192 [encodeArgument(o) for o in opts] +
193 [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
194
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)
204
205 def run_ffmpeg(self, path, out_path, opts):
206 self.run_ffmpeg_multiple_files([path], out_path, opts)
207
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
214
215
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
224
225 def run_ffmpeg(self, path, out_path, codec, more_opts):
226 if codec is None:
227 acodec_opts = []
228 else:
229 acodec_opts = ['-acodec', codec]
230 opts = ['-vn'] + acodec_opts + more_opts
231 try:
232 FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
233 except FFmpegPostProcessorError as err:
234 raise AudioConversionError(err.msg)
235
236 def run(self, information):
237 path = information['filepath']
238
239 filecodec = self.get_audio_codec(path)
240 if filecodec is None:
241 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
242
243 more_opts = []
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
247 acodec = 'copy'
248 extension = 'm4a'
249 more_opts = ['-bsf:a', 'aac_adtstoasc']
250 elif filecodec in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
251 # Lossless if possible
252 acodec = 'copy'
253 extension = filecodec
254 if filecodec == 'aac':
255 more_opts = ['-f', 'adts']
256 if filecodec == 'vorbis':
257 extension = 'ogg'
258 else:
259 # MP3 otherwise.
260 acodec = 'libmp3lame'
261 extension = 'mp3'
262 more_opts = []
263 if self._preferredquality is not None:
264 if int(self._preferredquality) < 10:
265 more_opts += ['-q:a', self._preferredquality]
266 else:
267 more_opts += ['-b:a', self._preferredquality + 'k']
268 else:
269 # We convert the audio (lossy if codec is lossy)
270 acodec = ACODECS[self._preferredcodec]
271 extension = self._preferredcodec
272 more_opts = []
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]
277 else:
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':
284 extension = 'ogg'
285 if self._preferredcodec == 'wav':
286 extension = 'wav'
287 more_opts += ['-f', 'wav']
288
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
291
292 information['filepath'] = new_path
293 information['ext'] = extension
294
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
300
301 try:
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)
307 except Exception:
308 raise PostProcessingError('error running ' + self.basename)
309
310 # Try to update the date time for extracted audio file.
311 if information.get('filetime') is not None:
312 self.try_utime(
313 new_path, time.time(), information['filetime'],
314 errnote='Cannot update utime of audio file')
315
316 return [path], information
317
318
319 class FFmpegVideoConvertorPP(FFmpegPostProcessor):
320 def __init__(self, downloader=None, preferedformat=None):
321 super(FFmpegVideoConvertorPP, self).__init__(downloader)
322 self._preferedformat = preferedformat
323
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
329 options = []
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
340
341
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')
348 if not subtitles:
349 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
350 return [], information
351
352 filename = information['filepath']
353
354 ext = information['ext']
355 sub_langs = []
356 sub_filenames = []
357 webm_vtt_warn = False
358
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))
364 else:
365 if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt':
366 webm_vtt_warn = True
367 self._downloader.to_screen('[ffmpeg] Only WebVTT subtitles can be embedded in webm files')
368
369 if not sub_langs:
370 return [], information
371
372 input_files = [filename] + sub_filenames
373
374 opts = [
375 '-map', '0',
376 '-c', 'copy',
377 # Don't copy the existing subtitles, we may be running the
378 # postprocessor a second time
379 '-map', '-0:s',
380 ]
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])
388
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))
394
395 return sub_filenames, information
396
397
398 class FFmpegMetadataPP(FFmpegPostProcessor):
399 def run(self, info):
400 metadata = {}
401
402 def add(meta_list, info_list=None):
403 if not info_list:
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]
413 break
414
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'))
421 add('genre')
422 add('album')
423 add('album_artist')
424 add('disc', 'disc_number')
425
426 if not metadata:
427 self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
428 return [], info
429
430 filename = info['filepath']
431 temp_filename = prepend_extension(filename, 'temp')
432
433 if info['ext'] == 'm4a':
434 options = ['-vn', '-acodec', 'copy']
435 else:
436 options = ['-c', 'copy']
437
438 for (name, value) in metadata.items():
439 options.extend(['-metadata', '%s=%s' % (name, value)])
440
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))
445 return [], info
446
447
448 class FFmpegMergerPP(FFmpegPostProcessor):
449 def run(self, info):
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
457
458 def can_merge(self):
459 # TODO: figure out merge-capable ffmpeg version
460 if self.basename != 'avconv':
461 return True
462
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)
470 if self._downloader:
471 self._downloader.report_warning(warning)
472 return False
473 return True
474
475
476 class FFmpegFixupStretchedPP(FFmpegPostProcessor):
477 def run(self, info):
478 stretched_ratio = info.get('stretched_ratio')
479 if stretched_ratio is None or stretched_ratio == 1:
480 return [], info
481
482 filename = info['filepath']
483 temp_filename = prepend_extension(filename, 'temp')
484
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)
488
489 os.remove(encodeFilename(filename))
490 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
491
492 return [], info
493
494
495 class FFmpegFixupM4aPP(FFmpegPostProcessor):
496 def run(self, info):
497 if info.get('container') != 'm4a_dash':
498 return [], info
499
500 filename = info['filepath']
501 temp_filename = prepend_extension(filename, 'temp')
502
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)
506
507 os.remove(encodeFilename(filename))
508 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
509
510 return [], info
511
512
513 class FFmpegFixupM3u8PP(FFmpegPostProcessor):
514 def run(self, info):
515 filename = info['filepath']
516 if self.get_audio_codec(filename) == 'aac':
517 temp_filename = prepend_extension(filename, 'temp')
518
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)
522
523 os.remove(encodeFilename(filename))
524 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
525 return [], info
526
527
528 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
529 def __init__(self, downloader=None, format=None):
530 super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
531 self.format = format
532
533 def run(self, info):
534 subs = info.get('requested_subtitles')
535 filename = info['filepath']
536 new_ext = self.format
537 new_format = new_ext
538 if new_format == 'vtt':
539 new_format = 'webvtt'
540 if subs is None:
541 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
542 return [], info
543 self._downloader.to_screen('[ffmpeg] Converting subtitles')
544 sub_filenames = []
545 for lang, sub in subs.items():
546 ext = sub['ext']
547 if ext == new_ext:
548 self._downloader.to_screen(
549 '[ffmpeg] Subtitle file for %s is already in the requested format' % new_ext)
550 continue
551 old_file = subtitles_filename(filename, lang, ext)
552 sub_filenames.append(old_file)
553 new_file = subtitles_filename(filename, lang, new_ext)
554
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')
559
560 dfxp_file = old_file
561 srt_file = subtitles_filename(filename, lang, 'srt')
562
563 with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
564 srt_data = dfxp2srt(f.read())
565
566 with io.open(srt_file, 'wt', encoding='utf-8') as f:
567 f.write(srt_data)
568 old_file = srt_file
569
570 subs[lang] = {
571 'ext': 'srt',
572 'data': srt_data
573 }
574
575 if new_ext == 'srt':
576 continue
577 else:
578 sub_filenames.append(srt_file)
579
580 self.run_ffmpeg(old_file, new_file, ['-f', new_format])
581
582 with io.open(new_file, 'rt', encoding='utf-8') as f:
583 subs[lang] = {
584 'ext': new_ext,
585 'data': f.read(),
586 }
587
588 return sub_filenames, info