Merge branch 'master' of https://github.com/aurium/youtube-dl into aurium-master
[youtube-dl] / 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         files_cmd = []
135         for path in input_paths:
136             files_cmd.extend([encodeArgument('-i'), encodeFilename(path, True)])
137         cmd = ([encodeFilename(self.executable, True), encodeArgument('-y')] +
138                files_cmd +
139                [encodeArgument(o) for o in opts] +
140                [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
141
142         if self._downloader.params.get('verbose', False):
143             self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
144         p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
145         stdout, stderr = p.communicate()
146         if p.returncode != 0:
147             stderr = stderr.decode('utf-8', 'replace')
148             msg = stderr.strip().split('\n')[-1]
149             raise FFmpegPostProcessorError(msg)
150         self.try_utime(out_path, oldest_mtime, oldest_mtime)
151
152     def run_ffmpeg(self, path, out_path, opts):
153         self.run_ffmpeg_multiple_files([path], out_path, opts)
154
155     def _ffmpeg_filename_argument(self, fn):
156         # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
157         if fn.startswith('-'):
158             return './' + fn
159         return fn
160
161
162 class FFmpegExtractAudioPP(FFmpegPostProcessor):
163     def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
164         FFmpegPostProcessor.__init__(self, downloader)
165         if preferredcodec is None:
166             preferredcodec = 'best'
167         self._preferredcodec = preferredcodec
168         self._preferredquality = preferredquality
169         self._nopostoverwrites = nopostoverwrites
170
171     def get_audio_codec(self, path):
172
173         if not self.probe_available:
174             raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
175         try:
176             cmd = [
177                 encodeFilename(self.probe_executable, True),
178                 encodeArgument('-show_streams'),
179                 encodeFilename(self._ffmpeg_filename_argument(path), True)]
180             if self._downloader.params.get('verbose', False):
181                 self._downloader.to_screen('[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
182             handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE, stdin=subprocess.PIPE)
183             output = handle.communicate()[0]
184             if handle.wait() != 0:
185                 return None
186         except (IOError, OSError):
187             return None
188         audio_codec = None
189         for line in output.decode('ascii', 'ignore').split('\n'):
190             if line.startswith('codec_name='):
191                 audio_codec = line.split('=')[1].strip()
192             elif line.strip() == 'codec_type=audio' and audio_codec is not None:
193                 return audio_codec
194         return None
195
196     def run_ffmpeg(self, path, out_path, codec, more_opts):
197         if codec is None:
198             acodec_opts = []
199         else:
200             acodec_opts = ['-acodec', codec]
201         opts = ['-vn'] + acodec_opts + more_opts
202         try:
203             FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
204         except FFmpegPostProcessorError as err:
205             raise AudioConversionError(err.msg)
206
207     def run(self, information):
208         path = information['filepath']
209
210         filecodec = self.get_audio_codec(path)
211         if filecodec is None:
212             raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
213
214         more_opts = []
215         if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
216             if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
217                 # Lossless, but in another container
218                 acodec = 'copy'
219                 extension = 'm4a'
220                 more_opts = ['-bsf:a', 'aac_adtstoasc']
221             elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
222                 # Lossless if possible
223                 acodec = 'copy'
224                 extension = filecodec
225                 if filecodec == 'aac':
226                     more_opts = ['-f', 'adts']
227                 if filecodec == 'vorbis':
228                     extension = 'ogg'
229             else:
230                 # MP3 otherwise.
231                 acodec = 'libmp3lame'
232                 extension = 'mp3'
233                 more_opts = []
234                 if self._preferredquality is not None:
235                     if int(self._preferredquality) < 10:
236                         more_opts += ['-q:a', self._preferredquality]
237                     else:
238                         more_opts += ['-b:a', self._preferredquality + 'k']
239         else:
240             # We convert the audio (lossy)
241             acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
242             extension = self._preferredcodec
243             more_opts = []
244             if self._preferredquality is not None:
245                 # The opus codec doesn't support the -aq option
246                 if int(self._preferredquality) < 10 and extension != 'opus':
247                     more_opts += ['-q:a', self._preferredquality]
248                 else:
249                     more_opts += ['-b:a', self._preferredquality + 'k']
250             if self._preferredcodec == 'aac':
251                 more_opts += ['-f', 'adts']
252             if self._preferredcodec == 'm4a':
253                 more_opts += ['-bsf:a', 'aac_adtstoasc']
254             if self._preferredcodec == 'vorbis':
255                 extension = 'ogg'
256             if self._preferredcodec == 'wav':
257                 extension = 'wav'
258                 more_opts += ['-f', 'wav']
259
260         prefix, sep, ext = path.rpartition('.')  # not os.path.splitext, since the latter does not work on unicode in all setups
261         new_path = prefix + sep + extension
262
263         # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
264         if (new_path == path or
265                 (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
266             self._downloader.to_screen('[youtube] Post-process file %s exists, skipping' % new_path)
267             return [], information
268
269         try:
270             self._downloader.to_screen('[' + self.basename + '] Destination: ' + new_path)
271             self.run_ffmpeg(path, new_path, acodec, more_opts)
272         except AudioConversionError as e:
273             raise PostProcessingError(
274                 'audio conversion failed: ' + e.msg)
275         except Exception:
276             raise PostProcessingError('error running ' + self.basename)
277
278         # Try to update the date time for extracted audio file.
279         if information.get('filetime') is not None:
280             self.try_utime(
281                 new_path, time.time(), information['filetime'],
282                 errnote='Cannot update utime of audio file')
283
284         information['filepath'] = new_path
285         information['ext'] = extension
286
287         return [path], information
288
289
290 class FFmpegVideoConvertorPP(FFmpegPostProcessor):
291     def __init__(self, downloader=None, preferedformat=None):
292         super(FFmpegVideoConvertorPP, self).__init__(downloader)
293         self._preferedformat = preferedformat
294
295     def run(self, information):
296         path = information['filepath']
297         prefix, sep, ext = path.rpartition('.')
298         ext = self._preferedformat
299         options = self._extra_cmd_args
300         if self._preferedformat == 'xvid':
301             ext = 'avi'
302             options.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
303         outpath = prefix + sep + ext
304         if information['ext'] == self._preferedformat:
305             self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
306             return [], information
307         self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
308         self.run_ffmpeg(path, outpath, options)
309         information['filepath'] = outpath
310         information['format'] = self._preferedformat
311         information['ext'] = ext
312         return [path], information
313
314
315 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
316     def run(self, information):
317         if information['ext'] not in ['mp4', 'mkv']:
318             self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4 or mkv files')
319             return [], information
320         subtitles = information.get('requested_subtitles')
321         if not subtitles:
322             self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
323             return [], information
324
325         sub_langs = list(subtitles.keys())
326         filename = information['filepath']
327         sub_filenames = [subtitles_filename(filename, lang, sub_info['ext']) for lang, sub_info in subtitles.items()]
328         input_files = [filename] + sub_filenames
329
330         opts = [
331             '-map', '0',
332             '-c', 'copy',
333             # Don't copy the existing subtitles, we may be running the
334             # postprocessor a second time
335             '-map', '-0:s',
336         ]
337         if information['ext'] == 'mp4':
338             opts += ['-c:s', 'mov_text']
339         for (i, lang) in enumerate(sub_langs):
340             opts.extend(['-map', '%d:0' % (i + 1)])
341             lang_code = ISO639Utils.short2long(lang)
342             if lang_code is not None:
343                 opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
344
345         temp_filename = prepend_extension(filename, 'temp')
346         self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
347         self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
348         os.remove(encodeFilename(filename))
349         os.rename(encodeFilename(temp_filename), encodeFilename(filename))
350
351         return sub_filenames, information
352
353
354 class FFmpegMetadataPP(FFmpegPostProcessor):
355     def run(self, info):
356         metadata = {}
357         if info.get('title') is not None:
358             metadata['title'] = info['title']
359         if info.get('upload_date') is not None:
360             metadata['date'] = info['upload_date']
361         if info.get('artist') is not None:
362             metadata['artist'] = info['artist']
363         elif info.get('uploader') is not None:
364             metadata['artist'] = info['uploader']
365         elif info.get('uploader_id') is not None:
366             metadata['artist'] = info['uploader_id']
367         if info.get('description') is not None:
368             metadata['description'] = info['description']
369             metadata['comment'] = info['description']
370         if info.get('webpage_url') is not None:
371             metadata['purl'] = info['webpage_url']
372         if info.get('album') is not None:
373             metadata['album'] = info['album']
374
375         if not metadata:
376             self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
377             return [], info
378
379         filename = info['filepath']
380         temp_filename = prepend_extension(filename, 'temp')
381
382         if info['ext'] == 'm4a':
383             options = ['-vn', '-acodec', 'copy']
384         else:
385             options = ['-c', 'copy']
386
387         for (name, value) in metadata.items():
388             options.extend(['-metadata', '%s=%s' % (name, value)])
389
390         self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
391         self.run_ffmpeg(filename, temp_filename, options)
392         os.remove(encodeFilename(filename))
393         os.rename(encodeFilename(temp_filename), encodeFilename(filename))
394         return [], info
395
396
397 class FFmpegMergerPP(FFmpegPostProcessor):
398     def run(self, info):
399         filename = info['filepath']
400         temp_filename = prepend_extension(filename, 'temp')
401         args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
402         self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
403         self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
404         os.rename(encodeFilename(temp_filename), encodeFilename(filename))
405         return info['__files_to_merge'], info
406
407     def can_merge(self):
408         # TODO: figure out merge-capable ffmpeg version
409         if self.basename != 'avconv':
410             return True
411
412         required_version = '10-0'
413         if is_outdated_version(
414                 self._versions[self.basename], required_version):
415             warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
416                        'youtube-dl will download single file media. '
417                        'Update %s to version %s or newer to fix this.') % (
418                            self.basename, self.basename, required_version)
419             if self._downloader:
420                 self._downloader.report_warning(warning)
421             return False
422         return True
423
424
425 class FFmpegFixupStretchedPP(FFmpegPostProcessor):
426     def run(self, info):
427         stretched_ratio = info.get('stretched_ratio')
428         if stretched_ratio is None or stretched_ratio == 1:
429             return [], info
430
431         filename = info['filepath']
432         temp_filename = prepend_extension(filename, 'temp')
433
434         options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
435         self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
436         self.run_ffmpeg(filename, temp_filename, options)
437
438         os.remove(encodeFilename(filename))
439         os.rename(encodeFilename(temp_filename), encodeFilename(filename))
440
441         return [], info
442
443
444 class FFmpegFixupM4aPP(FFmpegPostProcessor):
445     def run(self, info):
446         if info.get('container') != 'm4a_dash':
447             return [], info
448
449         filename = info['filepath']
450         temp_filename = prepend_extension(filename, 'temp')
451
452         options = ['-c', 'copy', '-f', 'mp4']
453         self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
454         self.run_ffmpeg(filename, temp_filename, options)
455
456         os.remove(encodeFilename(filename))
457         os.rename(encodeFilename(temp_filename), encodeFilename(filename))
458
459         return [], info
460
461
462 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
463     def __init__(self, downloader=None, format=None):
464         super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
465         self.format = format
466
467     def run(self, info):
468         subs = info.get('requested_subtitles')
469         filename = info['filepath']
470         new_ext = self.format
471         new_format = new_ext
472         if new_format == 'vtt':
473             new_format = 'webvtt'
474         if subs is None:
475             self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
476             return [], info
477         self._downloader.to_screen('[ffmpeg] Converting subtitles')
478         for lang, sub in subs.items():
479             ext = sub['ext']
480             if ext == new_ext:
481                 self._downloader.to_screen(
482                     '[ffmpeg] Subtitle file for %s is already in the requested'
483                     'format' % new_ext)
484                 continue
485             new_file = subtitles_filename(filename, lang, new_ext)
486
487             if ext == 'dfxp' or ext == 'ttml':
488                 self._downloader.report_warning(
489                     'You have requested to convert dfxp (TTML) subtitles into another format, '
490                     'which results in style information loss')
491
492                 dfxp_file = subtitles_filename(filename, lang, ext)
493                 srt_file = subtitles_filename(filename, lang, 'srt')
494
495                 with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
496                     srt_data = dfxp2srt(f.read())
497
498                 with io.open(srt_file, 'wt', encoding='utf-8') as f:
499                     f.write(srt_data)
500
501                 ext = 'srt'
502                 subs[lang] = {
503                     'ext': 'srt',
504                     'data': srt_data
505                 }
506
507                 if new_ext == 'srt':
508                     continue
509
510             self.run_ffmpeg(
511                 subtitles_filename(filename, lang, ext),
512                 new_file, ['-f', new_format])
513
514             with io.open(new_file, 'rt', encoding='utf-8') as f:
515                 subs[lang] = {
516                     'ext': ext,
517                     'data': f.read(),
518                 }
519
520         return [], info