Video editing with Python
Add support for multiple streams and metadata parsing to 'ffmpeg_parse_infos' (#1466)
Álvaro Mondéjar2482d139dd55
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5d85dd24..bac2832d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Support for `copy.copy(clip)` and `copy.deepcopy(clip)` with same behaviour as `clip.copy()` [\#1442](https://github.com/Zulko/moviepy/pull/1442)- `audio.fx.multiply_stereo_volume` to control volume by audio channels [\#1424](https://github.com/Zulko/moviepy/pull/1424)- Support for retrieve clip frames number using `clip.n_frames` [\#1471](https://github.com/Zulko/moviepy/pull/1471)+- `video.io.ffmpeg_reader.ffmpeg_parse_infos` returns data from all streams by FFmpeg inputs in attribute `inputs` [\#1466](https://github.com/Zulko/moviepy/pull/1466)+- `video.io.ffmpeg_reader.ffmpeg_parse_infos` returns metadata of the container in attribute `metadata` [\#1466](https://github.com/Zulko/moviepy/pull/1466)### Changed <!-- for changes in existing functionality -->- Lots of method and parameter names have been changed. This will be explained better in the documentation soon. See https://github.com/Zulko/moviepy/pull/1170 for more information. [\#1170](https://github.com/Zulko/moviepy/pull/1170)diff --git a/media/sintel_with_15_chapters.mp4 b/media/sintel_with_14_chapters.mp4similarity index 100%rename from media/sintel_with_15_chapters.mp4rename to media/sintel_with_14_chapters.mp4diff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.pyindex ddf9fdb9..b8a381c3 100644--- a/moviepy/audio/io/readers.py+++ b/moviepy/audio/io/readers.py@@ -59,10 +59,6 @@ class FFMPEG_AudioReader:self.nchannels = nchannelsinfos = ffmpeg_parse_infos(filename, decode_file=decode_file)self.duration = infos["duration"]- if "video_duration" in infos:- self.duration = infos["video_duration"]- else:- self.duration = infos["duration"]self.bitrate = infos["audio_bitrate"]self.infos = infosself.proc = Nonediff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.pyindex 9f0f36cc..926ec3be 100644--- a/moviepy/video/io/ffmpeg_reader.py+++ b/moviepy/video/io/ffmpeg_reader.py@@ -3,6 +3,7 @@ This module implements all the functions to read a video or a pictureusing ffmpeg. It is quite ugly, as there are many pitfalls to avoid"""+import osimport reimport subprocess as spimport warnings@@ -30,11 +31,15 @@ class FFMPEG_VideoReader:self.filename = filenameself.proc = Noneinfos = ffmpeg_parse_infos(- filename, decode_file, print_infos, check_duration, fps_source+ filename,+ check_duration=check_duration,+ fps_source=fps_source,+ decode_file=decode_file,+ print_infos=print_infos,)self.fps = infos["video_fps"]self.size = infos["video_size"]- self.rotation = infos["video_rotation"]+ self.rotation = infos.get("video_rotation", 0)if target_resolution:if None in target_resolution:@@ -277,103 +282,314 @@ def ffmpeg_read_image(filename, with_mask=True, pixel_format=None):return im-def ffmpeg_parse_infos(- filename,- decode_file=False,- print_infos=False,- check_duration=True,- fps_source="fps",-):- """Get file infos using ffmpeg.+class FFmpegInfosParser:+ """Finite state ffmpeg `-i` command option file information parser.+ Is designed to parse the output fast, in one loop. Iterates line by+ line of the `ffmpeg -i <filename> [-f null -]` command output changing+ the internal state of the parser.- Returns a dictionnary with the fields:- "video_found", "video_fps", "duration", "video_n_frames",- "video_duration", "video_bitrate","audio_found", "audio_fps", "audio_bitrate"+ Parameters+ ----------- "video_duration" is slightly smaller than "duration" to avoid- fetching the uncomplete frames at the end, which raises an error.+ filename+ Name of the file parsed, only used to raise accurate error messages.++ infos+ Information returned by FFmpeg.++ fps_source+ Indicates what source data will be preferably used to retrieve fps data.++ check_duration+ Enable or disable the parsing of the duration of the file. Useful to+ skip the duration check, for example, for images.+ decode_file+ Indicates if the whole file has been decoded. The duration parsing strategy+ will differ depending on this argument."""- # Open the file in a pipe, read output- cmd = [FFMPEG_BINARY, "-i", filename]- if decode_file:- cmd.extend(["-f", "null", "-"])- popen_params = cross_platform_popen_params(- {- "bufsize": 10 ** 5,- "stdout": sp.PIPE,- "stderr": sp.PIPE,- "stdin": sp.DEVNULL,- }- )+ def __init__(+ self,+ infos,+ filename,+ fps_source="fps",+ check_duration=True,+ decode_file=False,+ ):+ self.infos = infos+ self.filename = filename+ self.check_duration = check_duration+ self.fps_source = fps_source+ self.duration_tag_separator = "time=" if decode_file else "Duration: "- proc = sp.Popen(cmd, **popen_params)- (output, error) = proc.communicate()- infos = error.decode("utf8", errors="ignore")+ self._reset_state()- proc.terminate()- del proc+ def _reset_state(self):+ """Reinitializes the state of the parser. Used internally at+ initialization and at the end of the parsing process.+ """+ # could be 2 possible types of metadata:+ # - file_metadata: Metadata of the container. Here are the tags setted+ # by the user using `-metadata` ffmpeg option+ # - stream_metadata: Metadata for each stream of the container.+ self._inside_file_metadata = False++ # this state is neeeded if `duration_tag_separator == "time="` because+ # execution of ffmpeg decoding the whole file using `-f null -` appends+ # to the output a the blocks "Stream mapping:" and "Output:", which+ # should be ignored+ self._inside_output = False++ # flag which indicates that a default stream has not been found yet+ self._default_stream_found = False++ # current input file, stream and chapter, which will be built at runtime+ self._current_input_file = {"streams": []}+ self._current_stream = None+ self._current_chapter = None++ def parse(self):+ """Parses the information returned by FFmpeg in stderr executing their binary+ for a file with ``-i`` option and returns a dictionary with all data needed+ by moviepy.+ """+ result = {+ "video_found": False,+ "audio_found": False,+ "metadata": {},+ "inputs": [],+ }+ # chapters by input file+ input_chapters = []++ for line in self.infos.splitlines()[1:]:+ if (+ self.duration_tag_separator == "time="+ and self.check_duration+ and "time=" in line+ ):+ # parse duration using file decodification+ result["duration"] = self.parse_duration(line)+ elif self._inside_output or line[0] != " ":+ if self.duration_tag_separator == "time=" and not self._inside_output:+ self._inside_output = True+ # skip lines like "At least one output file must be specified"+ elif not self._inside_file_metadata and line.startswith(" Metadata:"):+ # enter " Metadata:" group+ self._inside_file_metadata = True+ elif line.startswith(" Duration:"):+ # exit " Metadata:" group+ self._inside_file_metadata = False+ if self.check_duration and self.duration_tag_separator == "Duration: ":+ result["duration"] = self.parse_duration(line)++ # parse global bitrate (in kb/s)+ bitrate_match = re.search(r"bitrate: (\d+) kb/s", line)+ result["bitrate"] = (+ int(bitrate_match.group(1)) if bitrate_match else None+ )- if print_infos:- # print the whole info text returned by FFMPEG- print(infos)+ # parse start time (in seconds)+ start_match = re.search(r"start: (\d+\.?\d+)", line)+ result["start"] = float(start_match.group(1)) if start_match else None+ elif self._inside_file_metadata:+ # file metadata line+ field, value = self.parse_metadata_field_value(line)+ result["metadata"].update({field: value})+ elif line.startswith(" Stream "):+ # exit stream " Metadata:"+ if self._current_stream:+ self._current_input_file["streams"].append(self._current_stream)++ # get input number, stream number, language and type+ main_info_match = re.search(+ r"^\s{4}Stream\s#(\d+):(\d+)\(?(\w+)?\)?:\s(\w+):", line+ )+ (+ input_number,+ stream_number,+ language,+ stream_type,+ ) = main_info_match.groups()+ input_number = int(input_number)+ stream_number = int(stream_number)+ stream_type_lower = stream_type.lower()++ # start builiding the current stream+ self._current_stream = {+ "input_number": input_number,+ "stream_number": stream_number,+ "stream_type": stream_type_lower,+ "language": language if language != "und" else None,+ "default": not self._default_stream_found+ or line.endswith("(default)"),+ }+ self._default_stream_found = True++ # for default streams, set their numbers globally, so it's+ # easy to get without iterating all+ if self._current_stream["default"]:+ result[f"default_{stream_type_lower}_input_number"] = input_number+ result[f"default_{stream_type_lower}_stream_number"] = stream_number++ # exit chapter+ if self._current_chapter:+ input_chapters[input_number].append(self._current_chapter)+ self._current_chapter = None++ if "input_number" not in self._current_input_file:+ # first input file+ self._current_input_file["input_number"] = input_number+ elif self._current_input_file["input_number"] != input_number:+ # new input file++ # include their chapters if there are for this input file+ if len(input_chapters) >= input_number + 1:+ self._current_input_file["chapters"] = input_chapters[+ input_number+ ]++ # add new input file to result+ result["inputs"].append(self._current_input_file)+ self._current_input_file = {"input_number": input_number}++ # parse relevant data by stream type+ try:+ global_data, stream_data = self.parse_data_by_stream_type(+ stream_type, line+ )+ except NotImplementedError as exc:+ warnings.warn(+ f"{str(exc)}\nffmpeg output:\n\n{self.infos}", UserWarning+ )+ else:+ result.update(global_data)+ self._current_stream.update(stream_data)+ elif line.startswith(" Metadata:"):+ # enter group " Metadata:"+ continue+ elif self._current_stream:+ # stream metadata line+ if "metadata" not in self._current_stream:+ self._current_stream["metadata"] = {}++ field, value = self.parse_metadata_field_value(line)+ if self._current_stream["stream_type"] == "video":+ field, value = self.video_metadata_type_casting(field, value)+ if field == "rotate":+ result["video_rotation"] = value+ self._current_stream["metadata"][field] = value+ elif line.startswith(" Chapter"):+ # Chapter data line+ if self._current_chapter:+ # there is a previews chapter?+ if len(input_chapters) < self._current_chapter["input_number"] + 1:+ input_chapters.append([])+ # include in the chapters by input matrix+ input_chapters[self._current_chapter["input_number"]].append(+ self._current_chapter+ )- lines = infos.splitlines()- if "No such file or directory" in lines[-1]:- raise IOError(- (- "MoviePy error: the file %s could not be found!\n"- "Please check that you entered the correct "- "path."- )- % filename- )+ # extract chapter data+ chapter_data_match = re.search(+ r"^ Chapter #(\d+):(\d+): start (\d+\.?\d+?), end (\d+\.?\d+?)",+ line,+ )+ input_number, chapter_number, start, end = chapter_data_match.groups()++ # start building the chapter+ self._current_chapter = {+ "input_number": int(input_number),+ "chapter_number": int(chapter_number),+ "start": float(start),+ "end": float(end),+ }+ elif self._current_chapter:+ # inside chapter metadata+ if "metadata" not in self._current_chapter:+ self._current_chapter["metadata"] = {}+ field, value = self.parse_metadata_field_value(line)+ self._current_chapter["metadata"][field] = value++ # last input file, must be included in the result+ if self._current_input_file:+ self._current_input_file["streams"].append(self._current_stream)+ # include their chapters, if there are+ if len(input_chapters) == self._current_input_file["input_number"] + 1:+ self._current_input_file["chapters"] = input_chapters[+ self._current_input_file["input_number"]+ ]+ result["inputs"].append(self._current_input_file)++ # some video duration utilities+ if result["video_found"] and self.check_duration:+ result["video_n_frames"] = int(result["duration"] * result["video_fps"])+ result["video_duration"] = result["duration"]+ else:+ result["video_n_frames"] = 1+ result["video_duration"] = None+ # We could have also recomputed duration from the number of frames, as follows:+ # >>> result['video_duration'] = result['video_n_frames'] / result['video_fps']- result = dict()+ # reset state of the parser+ self._reset_state()- # get duration (in seconds)- result["duration"] = None+ return result- if check_duration:+ def parse_data_by_stream_type(self, stream_type, line):+ """Parses data from "Stream ... {stream_type}" line."""try:- if decode_file:- line = [line for line in lines if "time=" in line][-1]- else:- line = [line for line in lines if "Duration:" in line][-1]- match = re.findall("([0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9])", line)[0]- result["duration"] = convert_to_seconds(match)- except Exception:- raise IOError(- f"MoviePy error: failed to read the duration of file {filename}.\n"- f"Here are the file infos returned by ffmpeg:\n\n{infos}"+ return {+ "Audio": self.parse_audio_stream_data,+ "Video": self.parse_video_stream_data,+ "Data": lambda _line: ({}, {}),+ }[stream_type](line)+ except KeyError:+ raise NotImplementedError(+ f"{stream_type} stream parsing is not supported by moviepy and"+ " will be ignored")- # get the output line that speaks about video- lines_video = [- line for line in lines if " Video: " in line and re.search(r"\d+x\d+", line)- ]+ def parse_audio_stream_data(self, line):+ """Parses data from "Stream ... Audio" line."""+ global_data, stream_data = ({"audio_found": True}, {})+ try:+ stream_data["fps"] = int(re.search(r" (\d+) Hz", line).group(1))+ except (AttributeError, ValueError):+ # AttributeError: 'NoneType' object has no attribute 'group'+ # ValueError: invalid literal for int() with base 10: '<string>'+ stream_data["fps"] = "unknown"+ match_audio_bitrate = re.search(r"(\d+) kb/s", line)+ stream_data["bitrate"] = (+ int(match_audio_bitrate.group(1)) if match_audio_bitrate else None+ )+ if self._current_stream["default"]:+ global_data["audio_fps"] = stream_data["fps"]+ global_data["audio_bitrate"] = stream_data["bitrate"]+ return (global_data, stream_data)- result["video_found"] = lines_video != []+ def parse_video_stream_data(self, line):+ """Parses data from "Stream ... Video" line."""+ global_data, stream_data = ({"video_found": True}, {})- if result["video_found"]:try:- line = lines_video[0]-- # get the size, of the form 460x320 (w x h)- match = re.search(" [0-9]*x[0-9]*(,| )", line)- size = list(map(int, line[match.start() : match.end() - 1].split("x")))- result["video_size"] = size+ match_video_size = re.search(r" (\d+)x(\d+)[,\s]", line)+ if match_video_size:+ # size, of the form 460x320 (w x h)+ stream_data["size"] = [int(num) for num in match_video_size.groups()]except Exception:raise IOError((- "MoviePy error: failed to read video dimensions in file %s.\n"- "Here are the file infos returned by ffmpeg:\n\n%s"+ "MoviePy error: failed to read video dimensions in"+ " file '%s'.\nHere are the file infos returned by"+ "ffmpeg:\n\n%s")- % (filename, infos)+ % (self.filename, self.infos))- match_bit = re.search(r"(\d+) kb/s", line)- result["video_bitrate"] = int(match_bit.group(1)) if match_bit else None++ match_bitrate = re.search(r"(\d+) kb/s", line)+ stream_data["bitrate"] = int(match_bitrate.group(1)) if match_bitrate else None# Get the frame rate. Sometimes it's 'tbr', sometimes 'fps', sometimes# tbc, and sometimes tbc/2...@@ -383,91 +599,171 @@ def ffmpeg_parse_infos(# If result is near from x*1000/1001 where x is 23,24,25,50,# replace by x*1000/1001 (very common case for the fps).- def get_tbr():- match = re.search("( [0-9]*.| )[0-9]* tbr", line)-- # Sometimes comes as e.g. 12k. We need to replace that with 12000.- s_tbr = line[match.start() : match.end()].split(" ")[1]- if "k" in s_tbr:- tbr = float(s_tbr.replace("k", "")) * 1000- else:- tbr = float(s_tbr)- return tbr-- def get_fps():- match = re.search("( [0-9]*.| )[0-9]* fps", line)- fps = float(line[match.start() : match.end()].split(" ")[1])- return fps-- if fps_source == "tbr":+ if self.fps_source == "fps":try:- result["video_fps"] = get_tbr()- except Exception:- result["video_fps"] = get_fps()-- elif fps_source == "fps":+ fps = self.parse_fps(line)+ except (AttributeError, ValueError):+ fps = self.parse_tbr(line)+ elif self.fps_source == "tbr":try:- result["video_fps"] = get_fps()- except Exception:- result["video_fps"] = get_tbr()+ fps = self.parse_tbr(line)+ except (AttributeError, ValueError):+ fps = self.parse_fps(line)+ else:+ raise ValueError(+ ("fps source '%s' not supported parsing the video '%s'")+ % (self.fps_source, self.filename)+ )# It is known that a fps of 24 is often written as 24000/1001# but then ffmpeg nicely rounds it to 23.98, which we hate.coef = 1000.0 / 1001.0- fps = result["video_fps"]for x in [23, 24, 25, 30, 50]:if (fps != x) and abs(fps - x * coef) < 0.01:- result["video_fps"] = x * coef+ fps = x * coef+ stream_data["fps"] = fps- if check_duration:- result["video_n_frames"] = int(result["duration"] * result["video_fps"])- result["video_duration"] = result["duration"]+ if self._current_stream["default"]:+ global_data["video_size"] = stream_data.get("size", None)+ global_data["video_bitrate"] = stream_data.get("bitrate", None)+ global_data["video_fps"] = stream_data["fps"]+ return (global_data, stream_data)++ def parse_fps(self, line):+ return float(re.search(r" (\d+.?\d*) fps", line).group(1))++ def parse_tbr(self, line):+ s_tbr = re.search(r" (\d+.?\d*k?) tbr", line).group(1)++ # Sometimes comes as e.g. 12k. We need to replace that with 12000.+ if s_tbr[-1] == "k":+ tbr = float(s_tbr[:-1]) * 1000else:- result["video_n_frames"] = 1- result["video_duration"] = None- # We could have also recomputed the duration from the number- # of frames, as follows:- # >>> result['video_duration'] = result['video_n_frames'] / result['video_fps']+ tbr = float(s_tbr)+ return tbr- # get the video rotation info.+ def parse_duration(self, line):+ """Parse the duration from the line that outputs the duration of+ the container.+ """try:- rotation_lines = [- line- for line in lines- if "rotate :" in line and re.search(r"\d+$", line)- ]- if len(rotation_lines):- rotation_line = rotation_lines[0]- match = re.search(r"\d+$", rotation_line)- result["video_rotation"] = int(- rotation_line[match.start() : match.end()]- )- else:- result["video_rotation"] = 0+ time_raw_string = line.split(self.duration_tag_separator)[-1]+ match_duration = re.search(+ r"([0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9])",+ time_raw_string,+ )+ return convert_to_seconds(match_duration.group(1))except Exception:raise IOError((- "MoviePy error: failed to read video rotation in file %s.\n"+ "MoviePy error: failed to read the duration of file '%s'.\n""Here are the file infos returned by ffmpeg:\n\n%s")- % (filename, infos)+ % (self.filename, self.infos))- lines_audio = [line for line in lines if " Audio: " in line]+ def parse_metadata_field_value(+ self,+ line,+ ):+ """Returns a tuple with a metadata field-value pair given a ffmpeg `-i`+ command output line.+ """+ raw_field, raw_value = line.split(":", 1)+ return (raw_field.strip(" "), raw_value.strip(" "))- result["audio_found"] = lines_audio != []+ def video_metadata_type_casting(self, field, value):+ """Cast needed video metadata fields to other types than the default str."""+ if field == "rotate":+ return (field, float(value))+ return (field, value)- if result["audio_found"]:- line = lines_audio[0]- try:- match = re.search(" [0-9]* Hz", line)- hz_string = line[- match.start() + 1 : match.end() - 3- ] # Removes the 'hz' from the end- result["audio_fps"] = int(hz_string)- except Exception:- result["audio_fps"] = "unknown"- match_bit = re.search(r"(\d+) kb/s", line)- result["audio_bitrate"] = int(match_bit.group(1)) if match_bit else None- return result+def ffmpeg_parse_infos(+ filename,+ check_duration=True,+ fps_source="fps",+ decode_file=False,+ print_infos=False,+):+ """Get the information of a file using ffmpeg.++ Returns a dictionary with next fields:++ - ``"duration"``+ - ``"metadata"``+ - ``"inputs"``+ - ``"video_found"``+ - ``"video_fps"``+ - ``"video_n_frames"``+ - ``"video_duration"``+ - ``"video_bitrate"``+ - ``"video_metadata"``+ - ``"audio_found"``+ - ``"audio_fps"``+ - ``"audio_bitrate"``+ - ``"audio_metadata"``++ Note that "video_duration" is slightly smaller than "duration" to avoid+ fetching the uncomplete frames at the end, which raises an error.++ Parameters+ ----------++ filename+ Name of the file parsed, only used to raise accurate error messages.++ infos+ Information returned by FFmpeg.++ fps_source+ Indicates what source data will be preferably used to retrieve fps data.++ check_duration+ Enable or disable the parsing of the duration of the file. Useful to+ skip the duration check, for example, for images.++ decode_file+ Indicates if the whole file must be read to retrieve their duration.+ This is needed for some files in order to get the correct duration (see+ https://github.com/Zulko/moviepy/pull/1222).+ """+ # Open the file in a pipe, read output+ cmd = [FFMPEG_BINARY, "-hide_banner", "-i", filename]+ if decode_file:+ cmd.extend(["-f", "null", "-"])++ popen_params = cross_platform_popen_params(+ {+ "bufsize": 10 ** 5,+ "stdout": sp.PIPE,+ "stderr": sp.PIPE,+ "stdin": sp.DEVNULL,+ }+ )++ proc = sp.Popen(cmd, **popen_params)+ (output, error) = proc.communicate()+ infos = error.decode("utf8", errors="ignore")++ proc.terminate()+ del proc++ if print_infos:+ # print the whole info text returned by FFMPEG+ print(infos)++ try:+ return FFmpegInfosParser(+ infos,+ filename,+ fps_source=fps_source,+ check_duration=check_duration,+ decode_file=decode_file,+ ).parse()+ except Exception as exc:+ if os.path.isdir(filename):+ raise IsADirectoryError(f"'{filename}' is a directory")+ elif not os.path.exists(filename):+ raise FileNotFoundError(f"'{filename}' not found")+ raise excdiff --git a/tests/test_VideoClip.py b/tests/test_VideoClip.pyindex 65678354..5251a3ff 100644--- a/tests/test_VideoClip.py+++ b/tests/test_VideoClip.py@@ -310,7 +310,7 @@ def test_copied_videoclip_write_videofile():copied_clip.write_videofile(output_filepath)copied_clip_from_file = VideoFileClip(output_filepath)- assert list(copied_clip.size) == list(copied_clip_from_file.size)+ assert list(copied_clip.size) == copied_clip_from_file.sizeassert copied_clip.duration == copied_clip_from_file.durationdiff --git a/tests/test_ffmpeg_reader.py b/tests/test_ffmpeg_reader.pyindex d214b6aa..8a344f55 100644--- a/tests/test_ffmpeg_reader.py+++ b/tests/test_ffmpeg_reader.py@@ -1,14 +1,24 @@"""FFmpeg reader tests meant to be run with pytest."""+import os+import subprocess+import pytestimport numpy as np+from moviepy.config import FFMPEG_BINARY+from moviepy.audio.AudioClip import AudioClip+from moviepy.video.VideoClip import BitmapClipfrom moviepy.video.io.ffmpeg_reader import ffmpeg_parse_infos, FFMPEG_VideoReader+from moviepy.utils import close_all_clips++from tests.test_helper import TMP_DIRdef test_ffmpeg_parse_infos():d = ffmpeg_parse_infos("media/big_buck_bunny_432_433.webm")assert d["duration"] == 1.0+ assert d["audio_fps"] == 44100d = ffmpeg_parse_infos("media/pigs_in_a_polka.gif")assert d["video_size"] == [314, 273]@@ -18,27 +28,250 @@ def test_ffmpeg_parse_infos():d = ffmpeg_parse_infos("media/video_with_failing_audio.mp4")assert d["audio_found"]assert d["audio_fps"] == 44100+ assert d["audio_bitrate"] == 127d = ffmpeg_parse_infos("media/crunching.mp3")assert d["audio_found"]assert d["audio_fps"] == 48000+ assert d["metadata"]["artist"] == "SoundJay.com Sound Effects"- d = ffmpeg_parse_infos("media/sintel_with_15_chapters.mp4")+ d = ffmpeg_parse_infos("media/sintel_with_14_chapters.mp4")+ assert d["audio_found"]+ assert d["video_found"]assert d["audio_bitrate"]assert d["video_bitrate"]-def test_ffmpeg_parse_infos_duration():- infos = ffmpeg_parse_infos("media/big_buck_bunny_0_30.webm")- assert infos["video_n_frames"] == 720+def test_ffmpeg_parse_infos_video_nframes():+ d = ffmpeg_parse_infos("media/big_buck_bunny_0_30.webm")+ assert d["video_n_frames"] == 720++ d = ffmpeg_parse_infos("media/bitmap.mp4")+ assert d["video_n_frames"] == 5+++ ("decode_file", "expected_duration"),+ (+ (False, 30),+ (True, 30.02),+ ),+ ids=(+ "decode_file=False",+ "decode_file=True",+ ),+)+def test_ffmpeg_parse_infos_decode_file(decode_file, expected_duration):+ """Test `decode_file` argument of `ffmpeg_parse_infos` function."""+ d = ffmpeg_parse_infos("media/big_buck_bunny_0_30.webm", decode_file=decode_file)+ assert d["duration"] == expected_duration++ # check metadata is fine+ assert len(d["metadata"]) == 1++ # check input+ assert len(d["inputs"]) == 1++ # check streams+ streams = d["inputs"][0]["streams"]+ assert len(streams) == 2+ assert streams[0]["stream_type"] == "video"+ assert streams[0]["stream_number"] == 0+ assert streams[0]["fps"] == 24+ assert streams[0]["size"] == [1280, 720]+ assert streams[0]["default"] is True+ assert streams[0]["language"] is None++ assert streams[1]["stream_type"] == "audio"+ assert streams[1]["stream_number"] == 1+ assert streams[1]["fps"] == 44100+ assert streams[1]["default"] is True+ assert streams[1]["language"] is None+++def test_ffmpeg_parse_infos_multiple_audio_streams():+ """Check that ``ffmpeg_parse_infos`` can parse multiple audio streams."""+ # Create two mono audio files+ clip_440_filepath = os.path.join(+ TMP_DIR, "ffmpeg_parse_infos_multiple_streams_440.mp3"+ )+ clip_880_filepath = os.path.join(+ TMP_DIR, "ffmpeg_parse_infos_multiple_streams_880.mp3"+ )+ multiple_streams_filepath = os.path.join(+ TMP_DIR, "ffmpeg_parse_infos_multiple_streams.mp4"+ )++ make_frame_440 = lambda t: np.array(+ [+ np.sin(440 * 2 * np.pi * t),+ ]+ )+ make_frame_880 = lambda t: np.array(+ [+ np.sin(880 * 2 * np.pi * t),+ ]+ )- infos = ffmpeg_parse_infos("media/bitmap.mp4")- assert infos["video_n_frames"] == 5+ clip_440 = AudioClip(make_frame_440, fps=22050, duration=0.01)+ clip_880 = AudioClip(make_frame_880, fps=22050, duration=0.01)+ clip_440.write_audiofile(clip_440_filepath)+ clip_880.write_audiofile(clip_880_filepath)++ # create a MP4 file with multiple streams+ cmd = [+ FFMPEG_BINARY,+ "-y",+ "-i",+ clip_440_filepath,+ "-i",+ clip_880_filepath,+ "-map",+ "0:a:0",+ "-map",+ "0:a:0",+ multiple_streams_filepath,+ ]+ with open(os.devnull, "w") as stderr:+ subprocess.check_call(cmd, stderr=stderr)++ # check that `ffmpeg_parse_infos` can parse all the streams data+ d = ffmpeg_parse_infos(multiple_streams_filepath)++ # number of inputs and streams+ assert len(d["inputs"]) == 1+ assert len(d["inputs"][0]["streams"]) == 2++ default_stream = d["inputs"][0]["streams"][0]+ ignored_stream = d["inputs"][0]["streams"][1]++ # default, only the first+ assert default_stream["default"]+ assert not ignored_stream["default"]++ # streams and inputs numbers+ assert default_stream["stream_number"] == 0+ assert ignored_stream["stream_number"] == 1+ assert default_stream["input_number"] == 0+ assert ignored_stream["input_number"] == 0++ # stream type+ assert default_stream["stream_type"] == "audio"+ assert ignored_stream["stream_type"] == "audio"++ # cleanup+ for filepath in [clip_440_filepath, clip_880_filepath, multiple_streams_filepath]:+ os.remove(filepath)+ close_all_clips(locals())+++def test_ffmpeg_parse_infos_metadata():+ """Check that `ffmpeg_parse_infos` is able to retrieve metadata from files."""+ filepath = os.path.join(TMP_DIR, "ffmpeg_parse_infos_metadata.mkv")+ if os.path.isfile(filepath):+ os.remove(filepath)++ # create video with 2 streams, video and audio+ audioclip = AudioClip(+ lambda t: np.sin(440 * 2 * np.pi * t), fps=22050+ ).with_duration(1)+ videoclip = BitmapClip([["RGB"]], fps=1).with_duration(1).with_audio(audioclip)++ # build metadata key-value pairs which will be passed to ``ffmpeg_params``+ # argument of ``videoclip.write_videofile``+ metadata = {+ "file": {+ "title": "Fóò",+ "comment": "bar",+ "description": "BAZ",+ "synopsis": "Testing",+ },+ "video": {+ "author": "Querty",+ "title": "hello",+ "description": "asdf",+ },+ "audio": {"track": "1", "title": "wtr", "genre": "lilihop"},+ }++ ffmpeg_params = []+ for metadata_type, data in metadata.items():+ option = "-metadata"+ if metadata_type in ["video", "audio"]:+ option += ":s:%s:0" % ("v" if metadata_type == "video" else "a")+ for field, value in data.items():+ ffmpeg_params.extend([option, f"{field}={value}"])++ languages = {+ "audio": "eng",+ "video": "spa",+ }+ ffmpeg_params.extend(+ [+ "-metadata:s:a:0",+ "language=" + languages["audio"],+ "-metadata:s:v:0",+ "language=" + languages["video"],+ ]+ )+ # create file with metadata included+ videoclip.write_videofile(filepath, codec="libx264", ffmpeg_params=ffmpeg_params)-def test_ffmpeg_parse_infos_for_i926():- d = ffmpeg_parse_infos("media/sintel_with_15_chapters.mp4")- assert d["audio_found"]+ # get information about created file+ d = ffmpeg_parse_infos(filepath)++ def get_value_from_dict_using_lower_key(field, dictionary):+ """Obtains a value from a dictionary using a key, no matter if the key+ is uppercased in the dictionary. This function is needed because+ some media containers convert to uppercase metadata field names.+ """+ value = None+ for d_field, d_value in dictionary.items():+ if str(d_field).lower() == field:+ value = d_value+ break+ return value++ # assert file metadata+ for field, value in metadata["file"].items():+ assert get_value_from_dict_using_lower_key(field, d["metadata"]) == value++ # assert streams metadata+ streams = {"audio": None, "video": None}+ for stream in d["inputs"][0]["streams"]:+ streams[stream["stream_type"]] = stream++ for stream_type, stream in streams.items():+ for field, value in metadata[stream_type].items():+ assert (+ get_value_from_dict_using_lower_key(field, stream["metadata"]) == value+ )++ # assert stream languages+ for stream_type, stream in streams.items():+ assert stream["language"] == languages[stream_type]++ os.remove(filepath)++ close_all_clips(locals())+++def test_ffmpeg_parse_infos_chapters():+ """Check that `ffmpeg_parse_infos` can parse chapters with their metadata."""+ d = ffmpeg_parse_infos("media/sintel_with_14_chapters.mp4")++ chapters = d["inputs"][0]["chapters"]++ num_chapters_expected = 14++ assert len(chapters) == num_chapters_expected+ for num in range(0, len(chapters)):+ assert chapters[num]["chapter_number"] == num+ assert chapters[num]["end"] == (num + 1) / 10+ assert chapters[num]["start"] == num / 10+ assert chapters[num]["metadata"]["title"]+ assert isinstance(chapters[num]["metadata"]["title"], str)def test_sequential_frame_pos():