]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/postprocessor/ffmpeg.py
debian/control: Confirm that the package conforms to policy 3.9.6.
[youtubedl] / youtube_dl / postprocessor / ffmpeg.py
1 import os
2 import re
3 import subprocess
4 import sys
5 import time
6
7
8 from .common import AudioConversionError, PostProcessor
9
10 from ..utils import (
11 compat_subprocess_get_DEVNULL,
12 encodeArgument,
13 encodeFilename,
14 is_outdated_version,
15 PostProcessingError,
16 prepend_extension,
17 shell_quote,
18 subtitles_filename,
19 )
20
21
22 def get_version(executable):
23 """ Returns the version of the specified executable,
24 or False if the executable is not present """
25 try:
26 out, err = subprocess.Popen(
27 [executable, '-version'],
28 stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
29 except OSError:
30 return False
31 firstline = out.partition(b'\n')[0].decode('ascii', 'ignore')
32 m = re.search(r'version\s+([0-9._-a-zA-Z]+)', firstline)
33 if not m:
34 return u'present'
35 else:
36 return m.group(1)
37
38
39 class FFmpegPostProcessorError(PostProcessingError):
40 pass
41
42
43 class FFmpegPostProcessor(PostProcessor):
44 def __init__(self, downloader=None, deletetempfiles=False):
45 PostProcessor.__init__(self, downloader)
46 self._versions = self.get_versions()
47 self._deletetempfiles = deletetempfiles
48
49 def check_version(self):
50 if not self._executable:
51 raise FFmpegPostProcessorError(u'ffmpeg or avconv not found. Please install one.')
52
53 REQUIRED_VERSION = '1.0'
54 if is_outdated_version(
55 self._versions[self._executable], REQUIRED_VERSION):
56 warning = u'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
57 self._executable, self._executable, REQUIRED_VERSION)
58 if self._downloader:
59 self._downloader.report_warning(warning)
60
61 @staticmethod
62 def get_versions():
63 programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
64 return dict((program, get_version(program)) for program in programs)
65
66 @property
67 def _executable(self):
68 if self._downloader.params.get('prefer_ffmpeg', False):
69 prefs = ('ffmpeg', 'avconv')
70 else:
71 prefs = ('avconv', 'ffmpeg')
72 for p in prefs:
73 if self._versions[p]:
74 return p
75 return None
76
77 @property
78 def _probe_executable(self):
79 if self._downloader.params.get('prefer_ffmpeg', False):
80 prefs = ('ffprobe', 'avprobe')
81 else:
82 prefs = ('avprobe', 'ffprobe')
83 for p in prefs:
84 if self._versions[p]:
85 return p
86 return None
87
88 def _uses_avconv(self):
89 return self._executable == 'avconv'
90
91 def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
92 self.check_version()
93
94 files_cmd = []
95 for path in input_paths:
96 files_cmd.extend(['-i', encodeFilename(path, True)])
97 cmd = ([self._executable, '-y'] + files_cmd
98 + [encodeArgument(o) for o in opts] +
99 [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
100
101 if self._downloader.params.get('verbose', False):
102 self._downloader.to_screen(u'[debug] ffmpeg command line: %s' % shell_quote(cmd))
103 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
104 stdout, stderr = p.communicate()
105 if p.returncode != 0:
106 stderr = stderr.decode('utf-8', 'replace')
107 msg = stderr.strip().split('\n')[-1]
108 raise FFmpegPostProcessorError(msg)
109 if self._deletetempfiles:
110 for ipath in input_paths:
111 os.remove(ipath)
112
113 def run_ffmpeg(self, path, out_path, opts):
114 self.run_ffmpeg_multiple_files([path], out_path, opts)
115
116 def _ffmpeg_filename_argument(self, fn):
117 # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
118 if fn.startswith(u'-'):
119 return u'./' + fn
120 return fn
121
122
123 class FFmpegExtractAudioPP(FFmpegPostProcessor):
124 def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
125 FFmpegPostProcessor.__init__(self, downloader)
126 if preferredcodec is None:
127 preferredcodec = 'best'
128 self._preferredcodec = preferredcodec
129 self._preferredquality = preferredquality
130 self._nopostoverwrites = nopostoverwrites
131
132 def get_audio_codec(self, path):
133
134 if not self._probe_executable:
135 raise PostProcessingError(u'ffprobe or avprobe not found. Please install one.')
136 try:
137 cmd = [
138 self._probe_executable,
139 '-show_streams',
140 encodeFilename(self._ffmpeg_filename_argument(path), True)]
141 handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE)
142 output = handle.communicate()[0]
143 if handle.wait() != 0:
144 return None
145 except (IOError, OSError):
146 return None
147 audio_codec = None
148 for line in output.decode('ascii', 'ignore').split('\n'):
149 if line.startswith('codec_name='):
150 audio_codec = line.split('=')[1].strip()
151 elif line.strip() == 'codec_type=audio' and audio_codec is not None:
152 return audio_codec
153 return None
154
155 def run_ffmpeg(self, path, out_path, codec, more_opts):
156 if codec is None:
157 acodec_opts = []
158 else:
159 acodec_opts = ['-acodec', codec]
160 opts = ['-vn'] + acodec_opts + more_opts
161 try:
162 FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
163 except FFmpegPostProcessorError as err:
164 raise AudioConversionError(err.msg)
165
166 def run(self, information):
167 path = information['filepath']
168
169 filecodec = self.get_audio_codec(path)
170 if filecodec is None:
171 raise PostProcessingError(u'WARNING: unable to obtain file audio codec with ffprobe')
172
173 uses_avconv = self._uses_avconv()
174 more_opts = []
175 if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
176 if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
177 # Lossless, but in another container
178 acodec = 'copy'
179 extension = 'm4a'
180 more_opts = ['-bsf:a' if uses_avconv else '-absf', 'aac_adtstoasc']
181 elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
182 # Lossless if possible
183 acodec = 'copy'
184 extension = filecodec
185 if filecodec == 'aac':
186 more_opts = ['-f', 'adts']
187 if filecodec == 'vorbis':
188 extension = 'ogg'
189 else:
190 # MP3 otherwise.
191 acodec = 'libmp3lame'
192 extension = 'mp3'
193 more_opts = []
194 if self._preferredquality is not None:
195 if int(self._preferredquality) < 10:
196 more_opts += ['-q:a' if uses_avconv else '-aq', self._preferredquality]
197 else:
198 more_opts += ['-b:a' if uses_avconv else '-ab', self._preferredquality + 'k']
199 else:
200 # We convert the audio (lossy)
201 acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
202 extension = self._preferredcodec
203 more_opts = []
204 if self._preferredquality is not None:
205 # The opus codec doesn't support the -aq option
206 if int(self._preferredquality) < 10 and extension != 'opus':
207 more_opts += ['-q:a' if uses_avconv else '-aq', self._preferredquality]
208 else:
209 more_opts += ['-b:a' if uses_avconv else '-ab', self._preferredquality + 'k']
210 if self._preferredcodec == 'aac':
211 more_opts += ['-f', 'adts']
212 if self._preferredcodec == 'm4a':
213 more_opts += ['-bsf:a' if uses_avconv else '-absf', 'aac_adtstoasc']
214 if self._preferredcodec == 'vorbis':
215 extension = 'ogg'
216 if self._preferredcodec == 'wav':
217 extension = 'wav'
218 more_opts += ['-f', 'wav']
219
220 prefix, sep, ext = path.rpartition(u'.') # not os.path.splitext, since the latter does not work on unicode in all setups
221 new_path = prefix + sep + extension
222
223 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
224 if new_path == path:
225 self._nopostoverwrites = True
226
227 try:
228 if self._nopostoverwrites and os.path.exists(encodeFilename(new_path)):
229 self._downloader.to_screen(u'[youtube] Post-process file %s exists, skipping' % new_path)
230 else:
231 self._downloader.to_screen(u'[' + self._executable + '] Destination: ' + new_path)
232 self.run_ffmpeg(path, new_path, acodec, more_opts)
233 except:
234 etype,e,tb = sys.exc_info()
235 if isinstance(e, AudioConversionError):
236 msg = u'audio conversion failed: ' + e.msg
237 else:
238 msg = u'error running ' + self._executable
239 raise PostProcessingError(msg)
240
241 # Try to update the date time for extracted audio file.
242 if information.get('filetime') is not None:
243 try:
244 os.utime(encodeFilename(new_path), (time.time(), information['filetime']))
245 except:
246 self._downloader.report_warning(u'Cannot update utime of audio file')
247
248 information['filepath'] = new_path
249 return self._nopostoverwrites,information
250
251
252 class FFmpegVideoConvertor(FFmpegPostProcessor):
253 def __init__(self, downloader=None,preferedformat=None):
254 super(FFmpegVideoConvertor, self).__init__(downloader)
255 self._preferedformat=preferedformat
256
257 def run(self, information):
258 path = information['filepath']
259 prefix, sep, ext = path.rpartition(u'.')
260 outpath = prefix + sep + self._preferedformat
261 if information['ext'] == self._preferedformat:
262 self._downloader.to_screen(u'[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
263 return True,information
264 self._downloader.to_screen(u'['+'ffmpeg'+'] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) +outpath)
265 self.run_ffmpeg(path, outpath, [])
266 information['filepath'] = outpath
267 information['format'] = self._preferedformat
268 information['ext'] = self._preferedformat
269 return False,information
270
271
272 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
273 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
274 _lang_map = {
275 'aa': 'aar',
276 'ab': 'abk',
277 'ae': 'ave',
278 'af': 'afr',
279 'ak': 'aka',
280 'am': 'amh',
281 'an': 'arg',
282 'ar': 'ara',
283 'as': 'asm',
284 'av': 'ava',
285 'ay': 'aym',
286 'az': 'aze',
287 'ba': 'bak',
288 'be': 'bel',
289 'bg': 'bul',
290 'bh': 'bih',
291 'bi': 'bis',
292 'bm': 'bam',
293 'bn': 'ben',
294 'bo': 'bod',
295 'br': 'bre',
296 'bs': 'bos',
297 'ca': 'cat',
298 'ce': 'che',
299 'ch': 'cha',
300 'co': 'cos',
301 'cr': 'cre',
302 'cs': 'ces',
303 'cu': 'chu',
304 'cv': 'chv',
305 'cy': 'cym',
306 'da': 'dan',
307 'de': 'deu',
308 'dv': 'div',
309 'dz': 'dzo',
310 'ee': 'ewe',
311 'el': 'ell',
312 'en': 'eng',
313 'eo': 'epo',
314 'es': 'spa',
315 'et': 'est',
316 'eu': 'eus',
317 'fa': 'fas',
318 'ff': 'ful',
319 'fi': 'fin',
320 'fj': 'fij',
321 'fo': 'fao',
322 'fr': 'fra',
323 'fy': 'fry',
324 'ga': 'gle',
325 'gd': 'gla',
326 'gl': 'glg',
327 'gn': 'grn',
328 'gu': 'guj',
329 'gv': 'glv',
330 'ha': 'hau',
331 'he': 'heb',
332 'hi': 'hin',
333 'ho': 'hmo',
334 'hr': 'hrv',
335 'ht': 'hat',
336 'hu': 'hun',
337 'hy': 'hye',
338 'hz': 'her',
339 'ia': 'ina',
340 'id': 'ind',
341 'ie': 'ile',
342 'ig': 'ibo',
343 'ii': 'iii',
344 'ik': 'ipk',
345 'io': 'ido',
346 'is': 'isl',
347 'it': 'ita',
348 'iu': 'iku',
349 'ja': 'jpn',
350 'jv': 'jav',
351 'ka': 'kat',
352 'kg': 'kon',
353 'ki': 'kik',
354 'kj': 'kua',
355 'kk': 'kaz',
356 'kl': 'kal',
357 'km': 'khm',
358 'kn': 'kan',
359 'ko': 'kor',
360 'kr': 'kau',
361 'ks': 'kas',
362 'ku': 'kur',
363 'kv': 'kom',
364 'kw': 'cor',
365 'ky': 'kir',
366 'la': 'lat',
367 'lb': 'ltz',
368 'lg': 'lug',
369 'li': 'lim',
370 'ln': 'lin',
371 'lo': 'lao',
372 'lt': 'lit',
373 'lu': 'lub',
374 'lv': 'lav',
375 'mg': 'mlg',
376 'mh': 'mah',
377 'mi': 'mri',
378 'mk': 'mkd',
379 'ml': 'mal',
380 'mn': 'mon',
381 'mr': 'mar',
382 'ms': 'msa',
383 'mt': 'mlt',
384 'my': 'mya',
385 'na': 'nau',
386 'nb': 'nob',
387 'nd': 'nde',
388 'ne': 'nep',
389 'ng': 'ndo',
390 'nl': 'nld',
391 'nn': 'nno',
392 'no': 'nor',
393 'nr': 'nbl',
394 'nv': 'nav',
395 'ny': 'nya',
396 'oc': 'oci',
397 'oj': 'oji',
398 'om': 'orm',
399 'or': 'ori',
400 'os': 'oss',
401 'pa': 'pan',
402 'pi': 'pli',
403 'pl': 'pol',
404 'ps': 'pus',
405 'pt': 'por',
406 'qu': 'que',
407 'rm': 'roh',
408 'rn': 'run',
409 'ro': 'ron',
410 'ru': 'rus',
411 'rw': 'kin',
412 'sa': 'san',
413 'sc': 'srd',
414 'sd': 'snd',
415 'se': 'sme',
416 'sg': 'sag',
417 'si': 'sin',
418 'sk': 'slk',
419 'sl': 'slv',
420 'sm': 'smo',
421 'sn': 'sna',
422 'so': 'som',
423 'sq': 'sqi',
424 'sr': 'srp',
425 'ss': 'ssw',
426 'st': 'sot',
427 'su': 'sun',
428 'sv': 'swe',
429 'sw': 'swa',
430 'ta': 'tam',
431 'te': 'tel',
432 'tg': 'tgk',
433 'th': 'tha',
434 'ti': 'tir',
435 'tk': 'tuk',
436 'tl': 'tgl',
437 'tn': 'tsn',
438 'to': 'ton',
439 'tr': 'tur',
440 'ts': 'tso',
441 'tt': 'tat',
442 'tw': 'twi',
443 'ty': 'tah',
444 'ug': 'uig',
445 'uk': 'ukr',
446 'ur': 'urd',
447 'uz': 'uzb',
448 've': 'ven',
449 'vi': 'vie',
450 'vo': 'vol',
451 'wa': 'wln',
452 'wo': 'wol',
453 'xh': 'xho',
454 'yi': 'yid',
455 'yo': 'yor',
456 'za': 'zha',
457 'zh': 'zho',
458 'zu': 'zul',
459 }
460
461 def __init__(self, downloader=None, subtitlesformat='srt'):
462 super(FFmpegEmbedSubtitlePP, self).__init__(downloader)
463 self._subformat = subtitlesformat
464
465 @classmethod
466 def _conver_lang_code(cls, code):
467 """Convert language code from ISO 639-1 to ISO 639-2/T"""
468 return cls._lang_map.get(code[:2])
469
470 def run(self, information):
471 if information['ext'] != u'mp4':
472 self._downloader.to_screen(u'[ffmpeg] Subtitles can only be embedded in mp4 files')
473 return True, information
474 if not information.get('subtitles'):
475 self._downloader.to_screen(u'[ffmpeg] There aren\'t any subtitles to embed')
476 return True, information
477
478 sub_langs = [key for key in information['subtitles']]
479 filename = information['filepath']
480 input_files = [filename] + [subtitles_filename(filename, lang, self._subformat) for lang in sub_langs]
481
482 opts = ['-map', '0:0', '-map', '0:1', '-c:v', 'copy', '-c:a', 'copy']
483 for (i, lang) in enumerate(sub_langs):
484 opts.extend(['-map', '%d:0' % (i+1), '-c:s:%d' % i, 'mov_text'])
485 lang_code = self._conver_lang_code(lang)
486 if lang_code is not None:
487 opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
488 opts.extend(['-f', 'mp4'])
489
490 temp_filename = filename + u'.temp'
491 self._downloader.to_screen(u'[ffmpeg] Embedding subtitles in \'%s\'' % filename)
492 self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
493 os.remove(encodeFilename(filename))
494 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
495
496 return True, information
497
498
499 class FFmpegMetadataPP(FFmpegPostProcessor):
500 def run(self, info):
501 metadata = {}
502 if info.get('title') is not None:
503 metadata['title'] = info['title']
504 if info.get('upload_date') is not None:
505 metadata['date'] = info['upload_date']
506 if info.get('uploader') is not None:
507 metadata['artist'] = info['uploader']
508 elif info.get('uploader_id') is not None:
509 metadata['artist'] = info['uploader_id']
510
511 if not metadata:
512 self._downloader.to_screen(u'[ffmpeg] There isn\'t any metadata to add')
513 return True, info
514
515 filename = info['filepath']
516 temp_filename = prepend_extension(filename, 'temp')
517
518 if info['ext'] == u'm4a':
519 options = ['-vn', '-acodec', 'copy']
520 else:
521 options = ['-c', 'copy']
522
523 for (name, value) in metadata.items():
524 options.extend(['-metadata', '%s=%s' % (name, value)])
525
526 self._downloader.to_screen(u'[ffmpeg] Adding metadata to \'%s\'' % filename)
527 self.run_ffmpeg(filename, temp_filename, options)
528 os.remove(encodeFilename(filename))
529 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
530 return True, info
531
532
533 class FFmpegMergerPP(FFmpegPostProcessor):
534 def run(self, info):
535 filename = info['filepath']
536 args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0', '-shortest']
537 self._downloader.to_screen(u'[ffmpeg] Merging formats into "%s"' % filename)
538 self.run_ffmpeg_multiple_files(info['__files_to_merge'], filename, args)
539 return True, info
540
541
542 class FFmpegAudioFixPP(FFmpegPostProcessor):
543 def run(self, info):
544 filename = info['filepath']
545 temp_filename = prepend_extension(filename, 'temp')
546
547 options = ['-vn', '-acodec', 'copy']
548 self._downloader.to_screen(u'[ffmpeg] Fixing audio file "%s"' % filename)
549 self.run_ffmpeg(filename, temp_filename, options)
550
551 os.remove(encodeFilename(filename))
552 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
553
554 return True, info