]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/postprocessor/ffmpeg.py
[metadatafromtitle] Remove unused exception class
[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 EXT_TO_OUT_FORMATS = {
29     "aac": "adts",
30     "m4a": "ipod",
31     "mka": "matroska",
32     "mkv": "matroska",
33     "mpg": "mpeg",
34     "ogv": "ogg",
35     "ts": "mpegts",
36     "wma": "asf",
37     "wmv": "asf",
38 }
39
40
41 class FFmpegPostProcessorError(PostProcessingError):
42     pass
43
44
45 class FFmpegPostProcessor(PostProcessor):
46     def __init__(self, downloader=None):
47         PostProcessor.__init__(self, downloader)
48         self._determine_executables()
49
50     def check_version(self):
51         if not self.available:
52             raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
53
54         required_version = '10-0' if self.basename == 'avconv' else '1.0'
55         if is_outdated_version(
56                 self._versions[self.basename], required_version):
57             warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
58                 self.basename, self.basename, required_version)
59             if self._downloader:
60                 self._downloader.report_warning(warning)
61
62     @staticmethod
63     def get_versions(downloader=None):
64         return FFmpegPostProcessor(downloader)._versions
65
66     def _determine_executables(self):
67         programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
68         prefer_ffmpeg = False
69
70         self.basename = None
71         self.probe_basename = None
72
73         self._paths = None
74         self._versions = None
75         if self._downloader:
76             prefer_ffmpeg = self._downloader.params.get('prefer_ffmpeg', False)
77             location = self._downloader.params.get('ffmpeg_location')
78             if location is not None:
79                 if not os.path.exists(location):
80                     self._downloader.report_warning(
81                         'ffmpeg-location %s does not exist! '
82                         'Continuing without avconv/ffmpeg.' % (location))
83                     self._versions = {}
84                     return
85                 elif not os.path.isdir(location):
86                     basename = os.path.splitext(os.path.basename(location))[0]
87                     if basename not in programs:
88                         self._downloader.report_warning(
89                             'Cannot identify executable %s, its basename should be one of %s. '
90                             'Continuing without avconv/ffmpeg.' %
91                             (location, ', '.join(programs)))
92                         self._versions = {}
93                         return None
94                     location = os.path.dirname(os.path.abspath(location))
95                     if basename in ('ffmpeg', 'ffprobe'):
96                         prefer_ffmpeg = True
97
98                 self._paths = dict(
99                     (p, os.path.join(location, p)) for p in programs)
100                 self._versions = dict(
101                     (p, get_exe_version(self._paths[p], args=['-version']))
102                     for p in programs)
103         if self._versions is None:
104             self._versions = dict(
105                 (p, get_exe_version(p, args=['-version'])) for p in programs)
106             self._paths = dict((p, p) for p in programs)
107
108         if prefer_ffmpeg:
109             prefs = ('ffmpeg', 'avconv')
110         else:
111             prefs = ('avconv', 'ffmpeg')
112         for p in prefs:
113             if self._versions[p]:
114                 self.basename = p
115                 break
116
117         if prefer_ffmpeg:
118             prefs = ('ffprobe', 'avprobe')
119         else:
120             prefs = ('avprobe', 'ffprobe')
121         for p in prefs:
122             if self._versions[p]:
123                 self.probe_basename = p
124                 break
125
126     @property
127     def available(self):
128         return self.basename is not None
129
130     @property
131     def executable(self):
132         return self._paths[self.basename]
133
134     @property
135     def probe_available(self):
136         return self.probe_basename is not None
137
138     @property
139     def probe_executable(self):
140         return self._paths[self.probe_basename]
141
142     def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
143         self.check_version()
144
145         oldest_mtime = min(
146             os.stat(encodeFilename(path)).st_mtime for path in input_paths)
147
148         opts += self._configuration_args()
149
150         files_cmd = []
151         for path in input_paths:
152             files_cmd.extend([
153                 encodeArgument('-i'),
154                 encodeFilename(self._ffmpeg_filename_argument(path), True)
155             ])
156         cmd = ([encodeFilename(self.executable, True), encodeArgument('-y')] +
157                files_cmd +
158                [encodeArgument(o) for o in opts] +
159                [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
160
161         if self._downloader.params.get('verbose', False):
162             self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
163         p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
164         stdout, stderr = p.communicate()
165         if p.returncode != 0:
166             stderr = stderr.decode('utf-8', 'replace')
167             msg = stderr.strip().split('\n')[-1]
168             raise FFmpegPostProcessorError(msg)
169         self.try_utime(out_path, oldest_mtime, oldest_mtime)
170
171     def run_ffmpeg(self, path, out_path, opts):
172         self.run_ffmpeg_multiple_files([path], out_path, opts)
173
174     def _ffmpeg_filename_argument(self, fn):
175         # Always use 'file:' because the filename may contain ':' (ffmpeg
176         # interprets that as a protocol) or can start with '-' (-- is broken in
177         # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
178         # Also leave '-' intact in order not to break streaming to stdout.
179         return 'file:' + fn if fn != '-' else fn
180
181
182 class FFmpegExtractAudioPP(FFmpegPostProcessor):
183     def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
184         FFmpegPostProcessor.__init__(self, downloader)
185         if preferredcodec is None:
186             preferredcodec = 'best'
187         self._preferredcodec = preferredcodec
188         self._preferredquality = preferredquality
189         self._nopostoverwrites = nopostoverwrites
190
191     def get_audio_codec(self, path):
192
193         if not self.probe_available:
194             raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
195         try:
196             cmd = [
197                 encodeFilename(self.probe_executable, True),
198                 encodeArgument('-show_streams'),
199                 encodeFilename(self._ffmpeg_filename_argument(path), True)]
200             if self._downloader.params.get('verbose', False):
201                 self._downloader.to_screen('[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
202             handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE, stdin=subprocess.PIPE)
203             output = handle.communicate()[0]
204             if handle.wait() != 0:
205                 return None
206         except (IOError, OSError):
207             return None
208         audio_codec = None
209         for line in output.decode('ascii', 'ignore').split('\n'):
210             if line.startswith('codec_name='):
211                 audio_codec = line.split('=')[1].strip()
212             elif line.strip() == 'codec_type=audio' and audio_codec is not None:
213                 return audio_codec
214         return None
215
216     def run_ffmpeg(self, path, out_path, codec, more_opts):
217         if codec is None:
218             acodec_opts = []
219         else:
220             acodec_opts = ['-acodec', codec]
221         opts = ['-vn'] + acodec_opts + more_opts
222         try:
223             FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
224         except FFmpegPostProcessorError as err:
225             raise AudioConversionError(err.msg)
226
227     def run(self, information):
228         path = information['filepath']
229
230         filecodec = self.get_audio_codec(path)
231         if filecodec is None:
232             raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
233
234         more_opts = []
235         if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
236             if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
237                 # Lossless, but in another container
238                 acodec = 'copy'
239                 extension = 'm4a'
240                 more_opts = ['-bsf:a', 'aac_adtstoasc']
241             elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
242                 # Lossless if possible
243                 acodec = 'copy'
244                 extension = filecodec
245                 if filecodec == 'aac':
246                     more_opts = ['-f', 'adts']
247                 if filecodec == 'vorbis':
248                     extension = 'ogg'
249             else:
250                 # MP3 otherwise.
251                 acodec = 'libmp3lame'
252                 extension = 'mp3'
253                 more_opts = []
254                 if self._preferredquality is not None:
255                     if int(self._preferredquality) < 10:
256                         more_opts += ['-q:a', self._preferredquality]
257                     else:
258                         more_opts += ['-b:a', self._preferredquality + 'k']
259         else:
260             # We convert the audio (lossy)
261             acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
262             extension = self._preferredcodec
263             more_opts = []
264             if self._preferredquality is not None:
265                 # The opus codec doesn't support the -aq option
266                 if int(self._preferredquality) < 10 and extension != 'opus':
267                     more_opts += ['-q:a', self._preferredquality]
268                 else:
269                     more_opts += ['-b:a', self._preferredquality + 'k']
270             if self._preferredcodec == 'aac':
271                 more_opts += ['-f', 'adts']
272             if self._preferredcodec == 'm4a':
273                 more_opts += ['-bsf:a', 'aac_adtstoasc']
274             if self._preferredcodec == 'vorbis':
275                 extension = 'ogg'
276             if self._preferredcodec == 'wav':
277                 extension = 'wav'
278                 more_opts += ['-f', 'wav']
279
280         prefix, sep, ext = path.rpartition('.')  # not os.path.splitext, since the latter does not work on unicode in all setups
281         new_path = prefix + sep + extension
282
283         # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
284         if (new_path == path or
285                 (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
286             self._downloader.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path)
287             return [], information
288
289         try:
290             self._downloader.to_screen('[ffmpeg] Destination: ' + new_path)
291             self.run_ffmpeg(path, new_path, acodec, more_opts)
292         except AudioConversionError as e:
293             raise PostProcessingError(
294                 'audio conversion failed: ' + e.msg)
295         except Exception:
296             raise PostProcessingError('error running ' + self.basename)
297
298         # Try to update the date time for extracted audio file.
299         if information.get('filetime') is not None:
300             self.try_utime(
301                 new_path, time.time(), information['filetime'],
302                 errnote='Cannot update utime of audio file')
303
304         information['filepath'] = new_path
305         information['ext'] = extension
306
307         return [path], information
308
309
310 class FFmpegVideoConvertorPP(FFmpegPostProcessor):
311     def __init__(self, downloader=None, preferedformat=None):
312         super(FFmpegVideoConvertorPP, self).__init__(downloader)
313         self._preferedformat = preferedformat
314
315     def run(self, information):
316         path = information['filepath']
317         if information['ext'] == self._preferedformat:
318             self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
319             return [], information
320         options = []
321         if self._preferedformat == 'avi':
322             options.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
323         prefix, sep, ext = path.rpartition('.')
324         outpath = prefix + sep + self._preferedformat
325         self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
326         self.run_ffmpeg(path, outpath, options)
327         information['filepath'] = outpath
328         information['format'] = self._preferedformat
329         information['ext'] = self._preferedformat
330         return [path], information
331
332
333 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
334     def run(self, information):
335         if information['ext'] not in ('mp4', 'webm', 'mkv'):
336             self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4, webm or mkv files')
337             return [], information
338         subtitles = information.get('requested_subtitles')
339         if not subtitles:
340             self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
341             return [], information
342
343         filename = information['filepath']
344
345         ext = information['ext']
346         sub_langs = []
347         sub_filenames = []
348         webm_vtt_warn = False
349
350         for lang, sub_info in subtitles.items():
351             sub_ext = sub_info['ext']
352             if ext != 'webm' or ext == 'webm' and sub_ext == 'vtt':
353                 sub_langs.append(lang)
354                 sub_filenames.append(subtitles_filename(filename, lang, sub_ext))
355             else:
356                 if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt':
357                     webm_vtt_warn = True
358                     self._downloader.to_screen('[ffmpeg] Only WebVTT subtitles can be embedded in webm files')
359
360         if not sub_langs:
361             return [], information
362
363         input_files = [filename] + sub_filenames
364
365         opts = [
366             '-map', '0',
367             '-c', 'copy',
368             # Don't copy the existing subtitles, we may be running the
369             # postprocessor a second time
370             '-map', '-0:s',
371         ]
372         if information['ext'] == 'mp4':
373             opts += ['-c:s', 'mov_text']
374         for (i, lang) in enumerate(sub_langs):
375             opts.extend(['-map', '%d:0' % (i + 1)])
376             lang_code = ISO639Utils.short2long(lang)
377             if lang_code is not None:
378                 opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
379
380         temp_filename = prepend_extension(filename, 'temp')
381         self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
382         self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
383         os.remove(encodeFilename(filename))
384         os.rename(encodeFilename(temp_filename), encodeFilename(filename))
385
386         return sub_filenames, information
387
388
389 class FFmpegMetadataPP(FFmpegPostProcessor):
390     def run(self, info):
391         metadata = {}
392
393         def add(meta_list, info_list=None):
394             if not info_list:
395                 info_list = meta_list
396             if not isinstance(meta_list, (list, tuple)):
397                 meta_list = (meta_list,)
398             if not isinstance(info_list, (list, tuple)):
399                 info_list = (info_list,)
400             for info_f in info_list:
401                 if info.get(info_f) is not None:
402                     for meta_f in meta_list:
403                         metadata[meta_f] = info[info_f]
404                     break
405
406         add('title', ('track', 'title'))
407         add('date', 'upload_date')
408         add(('description', 'comment'), 'description')
409         add('purl', 'webpage_url')
410         add('track', 'track_number')
411         add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
412         add('genre')
413         add('album')
414         add('album_artist')
415         add('disc', 'disc_number')
416
417         if not metadata:
418             self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
419             return [], info
420
421         filename = info['filepath']
422         temp_filename = prepend_extension(filename, 'temp')
423
424         if info['ext'] == 'm4a':
425             options = ['-vn', '-acodec', 'copy']
426         else:
427             options = ['-c', 'copy']
428
429         for (name, value) in metadata.items():
430             options.extend(['-metadata', '%s=%s' % (name, value)])
431
432         self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
433         self.run_ffmpeg(filename, temp_filename, options)
434         os.remove(encodeFilename(filename))
435         os.rename(encodeFilename(temp_filename), encodeFilename(filename))
436         return [], info
437
438
439 class FFmpegMergerPP(FFmpegPostProcessor):
440     def run(self, info):
441         filename = info['filepath']
442         temp_filename = prepend_extension(filename, 'temp')
443         args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
444         self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
445         self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
446         os.rename(encodeFilename(temp_filename), encodeFilename(filename))
447         return info['__files_to_merge'], info
448
449     def can_merge(self):
450         # TODO: figure out merge-capable ffmpeg version
451         if self.basename != 'avconv':
452             return True
453
454         required_version = '10-0'
455         if is_outdated_version(
456                 self._versions[self.basename], required_version):
457             warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
458                        'youtube-dl will download single file media. '
459                        'Update %s to version %s or newer to fix this.') % (
460                            self.basename, self.basename, required_version)
461             if self._downloader:
462                 self._downloader.report_warning(warning)
463             return False
464         return True
465
466
467 class FFmpegFixupStretchedPP(FFmpegPostProcessor):
468     def run(self, info):
469         stretched_ratio = info.get('stretched_ratio')
470         if stretched_ratio is None or stretched_ratio == 1:
471             return [], info
472
473         filename = info['filepath']
474         temp_filename = prepend_extension(filename, 'temp')
475
476         options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
477         self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
478         self.run_ffmpeg(filename, temp_filename, options)
479
480         os.remove(encodeFilename(filename))
481         os.rename(encodeFilename(temp_filename), encodeFilename(filename))
482
483         return [], info
484
485
486 class FFmpegFixupM4aPP(FFmpegPostProcessor):
487     def run(self, info):
488         if info.get('container') != 'm4a_dash':
489             return [], info
490
491         filename = info['filepath']
492         temp_filename = prepend_extension(filename, 'temp')
493
494         options = ['-c', 'copy', '-f', 'mp4']
495         self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
496         self.run_ffmpeg(filename, temp_filename, options)
497
498         os.remove(encodeFilename(filename))
499         os.rename(encodeFilename(temp_filename), encodeFilename(filename))
500
501         return [], info
502
503
504 class FFmpegFixupM3u8PP(FFmpegPostProcessor):
505     def run(self, info):
506         filename = info['filepath']
507         temp_filename = prepend_extension(filename, 'temp')
508
509         options = ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
510         self._downloader.to_screen('[ffmpeg] Fixing malformated aac bitstream in "%s"' % filename)
511         self.run_ffmpeg(filename, temp_filename, options)
512
513         os.remove(encodeFilename(filename))
514         os.rename(encodeFilename(temp_filename), encodeFilename(filename))
515
516         return [], info
517
518
519 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
520     def __init__(self, downloader=None, format=None):
521         super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
522         self.format = format
523
524     def run(self, info):
525         subs = info.get('requested_subtitles')
526         filename = info['filepath']
527         new_ext = self.format
528         new_format = new_ext
529         if new_format == 'vtt':
530             new_format = 'webvtt'
531         if subs is None:
532             self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
533             return [], info
534         self._downloader.to_screen('[ffmpeg] Converting subtitles')
535         sub_filenames = []
536         for lang, sub in subs.items():
537             ext = sub['ext']
538             if ext == new_ext:
539                 self._downloader.to_screen(
540                     '[ffmpeg] Subtitle file for %s is already in the requested'
541                     'format' % new_ext)
542                 continue
543             old_file = subtitles_filename(filename, lang, ext)
544             sub_filenames.append(old_file)
545             new_file = subtitles_filename(filename, lang, new_ext)
546
547             if ext == 'dfxp' or ext == 'ttml' or ext == 'tt':
548                 self._downloader.report_warning(
549                     'You have requested to convert dfxp (TTML) subtitles into another format, '
550                     'which results in style information loss')
551
552                 dfxp_file = old_file
553                 srt_file = subtitles_filename(filename, lang, 'srt')
554
555                 with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
556                     srt_data = dfxp2srt(f.read())
557
558                 with io.open(srt_file, 'wt', encoding='utf-8') as f:
559                     f.write(srt_data)
560                 old_file = srt_file
561
562                 subs[lang] = {
563                     'ext': 'srt',
564                     'data': srt_data
565                 }
566
567                 if new_ext == 'srt':
568                     continue
569                 else:
570                     sub_filenames.append(srt_file)
571
572             self.run_ffmpeg(old_file, new_file, ['-f', new_format])
573
574             with io.open(new_file, 'rt', encoding='utf-8') as f:
575                 subs[lang] = {
576                     'ext': new_ext,
577                     'data': f.read(),
578                 }
579
580         return sub_filenames, info