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