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