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