]> jfr.im git - yt-dlp.git/blobdiff - youtube_dlc/postprocessor/ffmpeg.py
Cleanup some code and fix typos
[yt-dlp.git] / youtube_dlc / postprocessor / ffmpeg.py
index dbc736c50930670303783c047ce261067a57c744..0982bea81370317703910f404ff06f54c6362a53 100644 (file)
@@ -5,6 +5,7 @@
 import subprocess
 import time
 import re
+import json
 
 
 from .common import AudioConversionError, PostProcessor
@@ -20,7 +21,9 @@
     subtitles_filename,
     dfxp2srt,
     ISO639Utils,
+    process_communicate_or_kill,
     replace_extension,
+    traverse_dict,
 )
 
 
@@ -58,15 +61,14 @@ def __init__(self, downloader=None):
 
     def check_version(self):
         if not self.available:
-            raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
+            raise FFmpegPostProcessorError('ffmpeg not found. Please install')
 
         required_version = '10-0' if self.basename == 'avconv' else '1.0'
         if is_outdated_version(
                 self._versions[self.basename], required_version):
             warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
                 self.basename, self.basename, required_version)
-            if self._downloader:
-                self._downloader.report_warning(warning)
+            self.report_warning(warning)
 
     @staticmethod
     def get_versions(downloader=None):
@@ -96,21 +98,21 @@ def get_ffmpeg_version(path):
         self._paths = None
         self._versions = None
         if self._downloader:
-            prefer_ffmpeg = self._downloader.params.get('prefer_ffmpeg', True)
-            location = self._downloader.params.get('ffmpeg_location')
+            prefer_ffmpeg = self.get_param('prefer_ffmpeg', True)
+            location = self.get_param('ffmpeg_location')
             if location is not None:
                 if not os.path.exists(location):
-                    self._downloader.report_warning(
+                    self.report_warning(
                         'ffmpeg-location %s does not exist! '
-                        'Continuing without avconv/ffmpeg.' % (location))
+                        'Continuing without ffmpeg.' % (location))
                     self._versions = {}
                     return
                 elif not os.path.isdir(location):
                     basename = os.path.splitext(os.path.basename(location))[0]
                     if basename not in programs:
-                        self._downloader.report_warning(
+                        self.report_warning(
                             'Cannot identify executable %s, its basename should be one of %s. '
-                            'Continuing without avconv/ffmpeg.' %
+                            'Continuing without ffmpeg.' %
                             (location, ', '.join(programs)))
                         self._versions = {}
                         return None
@@ -163,7 +165,7 @@ def probe_executable(self):
 
     def get_audio_codec(self, path):
         if not self.probe_available and not self.available:
-            raise PostProcessingError('ffprobe/avprobe and ffmpeg/avconv not found. Please install one.')
+            raise PostProcessingError('ffprobe and ffmpeg not found. Please install')
         try:
             if self.probe_available:
                 cmd = [
@@ -174,13 +176,11 @@ def get_audio_codec(self, path):
                     encodeFilename(self.executable, True),
                     encodeArgument('-i')]
             cmd.append(encodeFilename(self._ffmpeg_filename_argument(path), True))
-            if self._downloader.params.get('verbose', False):
-                self._downloader.to_screen(
-                    '[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
+            self.write_debug('%s command line: %s' % (self.basename, shell_quote(cmd)))
             handle = subprocess.Popen(
                 cmd, stderr=subprocess.PIPE,
                 stdout=subprocess.PIPE, stdin=subprocess.PIPE)
-            stdout_data, stderr_data = handle.communicate()
+            stdout_data, stderr_data = process_communicate_or_kill(handle)
             expected_ret = 0 if self.probe_available else 1
             if handle.wait() != expected_ret:
                 return None
@@ -203,13 +203,43 @@ def get_audio_codec(self, path):
                 return mobj.group(1)
         return None
 
+    def get_metadata_object(self, path, opts=[]):
+        if self.probe_basename != 'ffprobe':
+            if self.probe_available:
+                self.report_warning('Only ffprobe is supported for metadata extraction')
+            raise PostProcessingError('ffprobe not found. Please install.')
+        self.check_version()
+
+        cmd = [
+            encodeFilename(self.probe_executable, True),
+            encodeArgument('-hide_banner'),
+            encodeArgument('-show_format'),
+            encodeArgument('-show_streams'),
+            encodeArgument('-print_format'),
+            encodeArgument('json'),
+        ]
+
+        cmd += opts
+        cmd.append(encodeFilename(self._ffmpeg_filename_argument(path), True))
+        self.write_debug('ffprobe command line: %s' % shell_quote(cmd))
+        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
+        stdout, stderr = p.communicate()
+        return json.loads(stdout.decode('utf-8', 'replace'))
+
+    def get_stream_number(self, path, keys, value):
+        streams = self.get_metadata_object(path)['streams']
+        num = next(
+            (i for i, stream in enumerate(streams) if traverse_dict(stream, keys, casesense=False) == value),
+            None)
+        return num, len(streams)
+
     def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
         self.check_version()
 
         oldest_mtime = min(
             os.stat(encodeFilename(path)).st_mtime for path in input_paths)
 
-        opts += self._configuration_args()
+        opts += self._configuration_args(exe=self.basename)
 
         files_cmd = []
         for path in input_paths:
@@ -225,24 +255,27 @@ def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
                 + [encodeArgument(o) for o in opts]
                 + [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
 
-        if self._downloader.params.get('verbose', False):
-            self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
+        self.write_debug('ffmpeg command line: %s' % shell_quote(cmd))
         p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
-        stdout, stderr = p.communicate()
+        stdout, stderr = process_communicate_or_kill(p)
         if p.returncode != 0:
-            stderr = stderr.decode('utf-8', 'replace')
-            msg = stderr.strip().split('\n')[-1]
-            raise FFmpegPostProcessorError(msg)
+            stderr = stderr.decode('utf-8', 'replace').strip()
+            if self.get_param('verbose', False):
+                self.report_error(stderr)
+            raise FFmpegPostProcessorError(stderr.split('\n')[-1])
         self.try_utime(out_path, oldest_mtime, oldest_mtime)
+        return stderr.decode('utf-8', 'replace')
 
     def run_ffmpeg(self, path, out_path, opts):
-        self.run_ffmpeg_multiple_files([path], out_path, opts)
+        return self.run_ffmpeg_multiple_files([path], out_path, opts)
 
     def _ffmpeg_filename_argument(self, fn):
         # Always use 'file:' because the filename may contain ':' (ffmpeg
         # interprets that as a protocol) or can start with '-' (-- is broken in
         # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
         # Also leave '-' intact in order not to break streaming to stdout.
+        if fn.startswith(('http://', 'https://')):
+            return fn
         return 'file:' + fn if fn != '-' else fn
 
 
@@ -328,11 +361,11 @@ def run(self, information):
         # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
         if (new_path == path
                 or (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
-            self._downloader.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path)
+            self.to_screen('Post-process file %s exists, skipping' % new_path)
             return [], information
 
         try:
-            self._downloader.to_screen('[ffmpeg] Destination: ' + new_path)
+            self.to_screen('Destination: ' + new_path)
             self.run_ffmpeg(path, new_path, acodec, more_opts)
         except AudioConversionError as e:
             raise PostProcessingError(
@@ -349,6 +382,41 @@ def run(self, information):
         return [path], information
 
 
+class FFmpegVideoRemuxerPP(FFmpegPostProcessor):
+    def __init__(self, downloader=None, preferedformat=None):
+        super(FFmpegVideoRemuxerPP, self).__init__(downloader)
+        self._preferedformats = preferedformat.lower().split('/')
+
+    def run(self, information):
+        path = information['filepath']
+        sourceext, targetext = information['ext'].lower(), None
+        for pair in self._preferedformats:
+            kv = pair.split('>')
+            if len(kv) == 1 or kv[0].strip() == sourceext:
+                targetext = kv[-1].strip()
+                break
+
+        _skip_msg = (
+            'could not find a mapping for %s' if not targetext
+            else 'already is in target format %s' if sourceext == targetext
+            else None)
+        if _skip_msg:
+            self.to_screen('Not remuxing media file %s; %s' % (path, _skip_msg % sourceext))
+            return [], information
+
+        options = ['-c', 'copy', '-map', '0', '-dn']
+        if targetext in ['mp4', 'm4a', 'mov']:
+            options.extend(['-movflags', '+faststart'])
+        prefix, sep, oldext = path.rpartition('.')
+        outpath = prefix + sep + targetext
+        self.to_screen('Remuxing video from %s to %s; Destination: %s' % (sourceext, targetext, outpath))
+        self.run_ffmpeg(path, outpath, options)
+        information['filepath'] = outpath
+        information['format'] = targetext
+        information['ext'] = targetext
+        return [path], information
+
+
 class FFmpegVideoConvertorPP(FFmpegPostProcessor):
     def __init__(self, downloader=None, preferedformat=None):
         super(FFmpegVideoConvertorPP, self).__init__(downloader)
@@ -357,14 +425,14 @@ def __init__(self, downloader=None, preferedformat=None):
     def run(self, information):
         path = information['filepath']
         if information['ext'] == self._preferedformat:
-            self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
+            self.to_screen('Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
             return [], information
         options = []
         if self._preferedformat == 'avi':
             options.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
         prefix, sep, ext = path.rpartition('.')
         outpath = prefix + sep + self._preferedformat
-        self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
+        self.to_screen('Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
         self.run_ffmpeg(path, outpath, options)
         information['filepath'] = outpath
         information['format'] = self._preferedformat
@@ -373,13 +441,17 @@ def run(self, information):
 
 
 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
+    def __init__(self, downloader=None, already_have_subtitle=False):
+        super(FFmpegEmbedSubtitlePP, self).__init__(downloader)
+        self._already_have_subtitle = already_have_subtitle
+
     def run(self, information):
         if information['ext'] not in ('mp4', 'webm', 'mkv'):
-            self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4, webm or mkv files')
+            self.to_screen('Subtitles can only be embedded in mp4, webm or mkv files')
             return [], information
         subtitles = information.get('requested_subtitles')
         if not subtitles:
-            self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
+            self.to_screen('There aren\'t any subtitles to embed')
             return [], information
 
         filename = information['filepath']
@@ -388,16 +460,22 @@ def run(self, information):
         sub_langs = []
         sub_filenames = []
         webm_vtt_warn = False
+        mp4_ass_warn = False
 
         for lang, sub_info in subtitles.items():
             sub_ext = sub_info['ext']
-            if ext != 'webm' or ext == 'webm' and sub_ext == 'vtt':
+            if sub_ext == 'json':
+                self.report_warning('JSON subtitles cannot be embedded')
+            elif ext != 'webm' or ext == 'webm' and sub_ext == 'vtt':
                 sub_langs.append(lang)
                 sub_filenames.append(subtitles_filename(filename, lang, sub_ext, ext))
             else:
                 if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt':
                     webm_vtt_warn = True
-                    self._downloader.to_screen('[ffmpeg] Only WebVTT subtitles can be embedded in webm files')
+                    self.report_warning('Only WebVTT subtitles can be embedded in webm files')
+            if not mp4_ass_warn and ext == 'mp4' and sub_ext == 'ass':
+                mp4_ass_warn = True
+                self.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues')
 
         if not sub_langs:
             return [], information
@@ -405,8 +483,7 @@ def run(self, information):
         input_files = [filename] + sub_filenames
 
         opts = [
-            '-map', '0',
-            '-c', 'copy',
+            '-c', 'copy', '-map', '0', '-dn',
             # Don't copy the existing subtitles, we may be running the
             # postprocessor a second time
             '-map', '-0:s',
@@ -422,12 +499,13 @@ def run(self, information):
             opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
 
         temp_filename = prepend_extension(filename, 'temp')
-        self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
+        self.to_screen('Embedding subtitles in "%s"' % filename)
         self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
         os.remove(encodeFilename(filename))
         os.rename(encodeFilename(temp_filename), encodeFilename(filename))
 
-        return sub_filenames, information
+        files_to_delete = [] if self._already_have_subtitle else sub_filenames
+        return files_to_delete, information
 
 
 class FFmpegMetadataPP(FFmpegPostProcessor):
@@ -452,7 +530,6 @@ def add(meta_list, info_list=None):
         # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
         # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
         # 3. https://kodi.wiki/view/Video_file_tagging
-        # 4. http://atomicparsley.sourceforge.net/mpeg-4files.html
 
         add('title', ('track', 'title'))
         add('date', 'upload_date')
@@ -470,13 +547,13 @@ def add(meta_list, info_list=None):
         add('episode_sort', 'episode_number')
 
         if not metadata:
-            self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
+            self.to_screen('There isn\'t any metadata to add')
             return [], info
 
         filename = info['filepath']
         temp_filename = prepend_extension(filename, 'temp')
         in_filenames = [filename]
-        options = []
+        options = ['-map', '0', '-dn']
 
         if info['ext'] == 'm4a':
             options.extend(['-vn', '-acodec', 'copy'])
@@ -505,7 +582,19 @@ def ffmpeg_escape(text):
                 in_filenames.append(metadata_filename)
                 options.extend(['-map_metadata', '1'])
 
-        self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
+        if '__infojson_filename' in info and info['ext'] in ('mkv', 'mka'):
+            old_stream, new_stream = self.get_stream_number(
+                filename, ('tags', 'mimetype'), 'application/json')
+            if old_stream is not None:
+                options.extend(['-map', '-0:%d' % old_stream])
+                new_stream -= 1
+
+            options.extend([
+                '-attach', info['__infojson_filename'],
+                '-metadata:s:%d' % new_stream, 'mimetype=application/json'
+            ])
+
+        self.to_screen('Adding metadata to \'%s\'' % filename)
         self.run_ffmpeg_multiple_files(in_filenames, temp_filename, options)
         if chapters:
             os.remove(metadata_filename)
@@ -518,8 +607,13 @@ class FFmpegMergerPP(FFmpegPostProcessor):
     def run(self, info):
         filename = info['filepath']
         temp_filename = prepend_extension(filename, 'temp')
-        args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
-        self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
+        args = ['-c', 'copy']
+        for (i, fmt) in enumerate(info['requested_formats']):
+            if fmt.get('acodec') != 'none':
+                args.extend(['-map', '%u:a:0' % (i)])
+            if fmt.get('vcodec') != 'none':
+                args.extend(['-map', '%u:v:0' % (i)])
+        self.to_screen('Merging formats into "%s"' % filename)
         self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
         os.rename(encodeFilename(temp_filename), encodeFilename(filename))
         return info['__files_to_merge'], info
@@ -536,8 +630,7 @@ def can_merge(self):
                        'youtube-dlc will download single file media. '
                        'Update %s to version %s or newer to fix this.') % (
                            self.basename, self.basename, required_version)
-            if self._downloader:
-                self._downloader.report_warning(warning)
+            self.report_warning(warning)
             return False
         return True
 
@@ -551,8 +644,8 @@ def run(self, info):
         filename = info['filepath']
         temp_filename = prepend_extension(filename, 'temp')
 
-        options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
-        self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
+        options = ['-c', 'copy', '-map', '0', '-dn', '-aspect', '%f' % stretched_ratio]
+        self.to_screen('Fixing aspect ratio in "%s"' % filename)
         self.run_ffmpeg(filename, temp_filename, options)
 
         os.remove(encodeFilename(filename))
@@ -569,8 +662,8 @@ def run(self, info):
         filename = info['filepath']
         temp_filename = prepend_extension(filename, 'temp')
 
-        options = ['-c', 'copy', '-f', 'mp4']
-        self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
+        options = ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4']
+        self.to_screen('Correcting container in "%s"' % filename)
         self.run_ffmpeg(filename, temp_filename, options)
 
         os.remove(encodeFilename(filename))
@@ -585,8 +678,8 @@ def run(self, info):
         if self.get_audio_codec(filename) == 'aac':
             temp_filename = prepend_extension(filename, 'temp')
 
-            options = ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
-            self._downloader.to_screen('[ffmpeg] Fixing malformed AAC bitstream in "%s"' % filename)
+            options = ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
+            self.to_screen('Fixing malformed AAC bitstream in "%s"' % filename)
             self.run_ffmpeg(filename, temp_filename, options)
 
             os.remove(encodeFilename(filename))
@@ -607,22 +700,26 @@ def run(self, info):
         if new_format == 'vtt':
             new_format = 'webvtt'
         if subs is None:
-            self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
+            self.to_screen('There aren\'t any subtitles to convert')
             return [], info
-        self._downloader.to_screen('[ffmpeg] Converting subtitles')
+        self.to_screen('Converting subtitles')
         sub_filenames = []
         for lang, sub in subs.items():
             ext = sub['ext']
             if ext == new_ext:
-                self._downloader.to_screen(
-                    '[ffmpeg] Subtitle file for %s is already in the requested format' % new_ext)
+                self.to_screen('Subtitle file for %s is already in the requested format' % new_ext)
+                continue
+            elif ext == 'json':
+                self.to_screen(
+                    'You have requested to convert json subtitles into another format, '
+                    'which is currently not possible')
                 continue
             old_file = subtitles_filename(filename, lang, ext, info.get('ext'))
             sub_filenames.append(old_file)
             new_file = subtitles_filename(filename, lang, new_ext, info.get('ext'))
 
             if ext in ('dfxp', 'ttml', 'tt'):
-                self._downloader.report_warning(
+                self.report_warning(
                     'You have requested to convert dfxp (TTML) subtitles into another format, '
                     'which results in style information loss')