From 9ad2bc8c7b75a08b1683cca84be3467171d101fd Mon Sep 17 00:00:00 2001 From: Caglar Pir Date: Tue, 1 Dec 2026 12:45:40 +0100 Subject: [PATCH] Add transform_mp4_cut to build the upload of a part of a video transform_mp4_cut() is transform_mp4() for a part of a video. It keeps the samples from the last sync sample presented by the start of the part to the first sync sample from which every frame is presented after its end, so every frame of the part decodes, nothing is encoded again, and the source is read for those samples only. The leading frames of an open GOP are decoded after its sync sample but presented before it, so the cut runs on past a sync sample whose leading frames are presented by the end. The part starts at time 0 of the new video: the sample generator is made for the decoding time of the start of the cut, which is the time of the frames in the new video, so the CAMM samples it adds are timed on them. The creation time of the new video is moved to the start of the cut, in whole seconds. In an open GOP, the frames decoded after the first sync sample but presented before it reference the GOP before, which is not kept, so they are left out. Other video tracks, such as the second lens of a 360 camera, are cut at the same time, or MP4CutError is raised; each ends at a sync sample of its own. The duration of each track and its single edit span the frames it presents, from the earliest to the end of the latest. MP4CutError is also raised for a part where a video track presents no frame, or with no time (NaN). MP4Header holds the ftyp and moov boxes, read once for all the parts of a video. Nothing calls it yet: uploading a video in parts comes in a follow-up. --- mapillary_tools/mp4/simple_mp4_builder.py | 292 +++++++++++++ tests/unit/test_simple_mp4_cut.py | 491 ++++++++++++++++++++++ 2 files changed, 783 insertions(+) create mode 100644 tests/unit/test_simple_mp4_cut.py diff --git a/mapillary_tools/mp4/simple_mp4_builder.py b/mapillary_tools/mp4/simple_mp4_builder.py index 69630005..bc827356 100644 --- a/mapillary_tools/mp4/simple_mp4_builder.py +++ b/mapillary_tools/mp4/simple_mp4_builder.py @@ -7,6 +7,8 @@ import dataclasses import io +import itertools +import math import typing as T from . import ( @@ -374,6 +376,296 @@ def transform_mp4( return build_mp4(ftyp_data, moov_children, sample_readers) +class MP4CutError(ValueError): + """The video cannot be cut where asked (see transform_mp4_cut())""" + + +@dataclasses.dataclass(frozen=True) +class MP4Header: + """ + The data of the ftyp and moov boxes of an MP4 file, read once to cut the + file more than once (see transform_mp4_cut()) + """ + + ftyp_data: bytes + moov_data: bytes + + @classmethod + def read(cls, src_fp: T.BinaryIO) -> MP4Header: + src_fp.seek(0) + ftyp_data = sparser.parse_mp4_data_firstx(src_fp, [b"ftyp"]) + src_fp.seek(0) + moov_data = sparser.parse_mp4_data_firstx(src_fp, [b"moov"]) + return cls(ftyp_data=ftyp_data, moov_data=moov_data) + + +@dataclasses.dataclass(frozen=True) +class MP4Cut: + """A part of a video, as transform_mp4_cut() cuts it""" + + stream: io_utils.ChainedIO + # Where the part starts and ends in the source video, in seconds of the + # time of its first video track (see transform_mp4_cut()): the decoding + # times of the first sample kept, and of the end of the last one, of the + # video track that runs the longest + start: float + end: float + + +@dataclasses.dataclass(frozen=True) +class _TrackCut: + timescale: int + # The samples of the track, in decoding order + samples: list[RawSample] + # The samples kept: samples[start:end] + start: int + end: int + + @property + def start_time(self) -> float: + return sum(s.timedelta for s in self.samples[: self.start]) / self.timescale + + @property + def duration(self) -> int: + """In the media timescale""" + return sum(s.timedelta for s in self.samples[self.start : self.end]) + + @property + def end_time(self) -> float: + return self.start_time + self.duration / self.timescale + + +def _composition_times(samples: T.Sequence[RawSample]) -> list[int]: + """The composition times of samples in decoding order, edit lists aside""" + return [ + dt + s.composition_offset + for dt, s in zip( + itertools.accumulate((s.timedelta for s in samples), initial=0), samples + ) + ] + + +def _plan_track_cut(trak: BoxDict, start: float, end: float) -> _TrackCut: + """ + The samples of the track to keep to present it from **start** to **end** + (seconds from the decoding time of its first sample): from the last sync + sample decoded and presented by **start**, to the first sync sample from + which every sample is presented after **end**, left out. The leading + pictures of an open GOP are decoded after its sync sample, but presented + before it, maybe by **end** + """ + mdhd = cparser.find_box_at_pathx(trak, [b"trak", b"mdia", b"mdhd"]) + timescale = T.cast(T.Dict[str, T.Any], mdhd["data"])["timescale"] + stbl_box = cparser.find_box_at_pathx(trak, [b"trak", b"mdia", b"minf", b"stbl"]) + _, raw_samples = sample_parser.extract_raw_samples_from_stbl_data( + T.cast(bytes, stbl_box["data"]) + ) + samples = list(raw_samples) + if not samples: + # As in a fragmented MP4, whose samples are listed after its moov box + raise MP4CutError("The video track lists no samples") + + start_ts, end_ts = start * timescale, end * timescale + composition_times = _composition_times(samples) + presentation_end = max( + ct + s.timedelta for ct, s in zip(composition_times, samples) + ) + if presentation_end <= start_ts or end_ts < min(composition_times): + raise MP4CutError( + f"The video track presents no frame from {start} to {end} seconds" + ) + + start_idx = 0 + dt = 0 + for idx, s in enumerate(samples): + if start_ts < dt: + break + if s.is_sync and composition_times[idx] <= start_ts: + start_idx = idx + dt += s.timedelta + + # The earliest composition time of each sample and those decoded after it + later_min = composition_times[:] + for idx in range(len(samples) - 2, -1, -1): + later_min[idx] = min(later_min[idx], later_min[idx + 1]) + end_idx = next( + ( + idx + for idx in range(start_idx + 1, len(samples)) + if samples[idx].is_sync and end_ts < later_min[idx] + ), + len(samples), + ) + + return _TrackCut(timescale, samples, start_idx, end_idx) + + +def _drop_leading_pictures(samples: T.Sequence[RawSample]) -> list[RawSample]: + """ + Leave out the samples, after the first one (a sync sample), that are + presented before it. In an open GOP they reference the GOP before, which + is not kept, so no decoder could show them. Each one's duration goes to + the sample before it, so the samples after it keep their times + """ + if not samples: + return [] + first_composition_time = samples[0].composition_offset + kept: list[RawSample] = [samples[0]] + dt = samples[0].timedelta + for s in samples[1:]: + if not s.is_sync and dt + s.composition_offset < first_composition_time: + kept[-1] = kept[-1]._replace(timedelta=kept[-1].timedelta + s.timedelta) + else: + kept.append(s) + dt += s.timedelta + return kept + + +def _set_duration(boxdata: dict[str, T.Any], duration: int) -> None: + boxdata["duration"] = duration + if UINT32_MAX < duration: + boxdata["version"] = 1 + + +def _apply_track_cut(trak: BoxDict, movie_timescale: int, cut: _TrackCut) -> int: + """ + Keep only the samples of the cut in the track, with its durations and + edit list set to them. Return its duration in the movie timescale + """ + kept = _drop_leading_pictures(cut.samples[cut.start : cut.end]) + + stbl_box = cparser.find_box_at_pathx(trak, [b"trak", b"mdia", b"minf", b"stbl"]) + descriptions, _ = sample_parser.extract_raw_samples_from_stbl_data( + T.cast(bytes, stbl_box["data"]) + ) + stbl_box["data"] = _STBLChildrenBuilderConstruct.build_boxlist( + build_stbl_from_raw_samples(descriptions, kept) + ) + + # Whatever edits the source had, present the part from its first frame + # to its last: one edit from the earliest composition time + composition_times = _composition_times(kept) + earliest = min(composition_times) + presentation_duration = ( + max(ct + s.timedelta for ct, s in zip(composition_times, kept)) - earliest + ) + movie_duration = presentation_duration * movie_timescale // cut.timescale + + mdhd = cparser.find_box_at_pathx(trak, [b"trak", b"mdia", b"mdhd"]) + _set_duration( + T.cast(T.Dict[str, T.Any], mdhd["data"]), sum(s.timedelta for s in kept) + ) + # That of its edits + tkhd = cparser.find_box_at_pathx(trak, [b"trak", b"tkhd"]) + _set_duration(T.cast(T.Dict[str, T.Any], tkhd["data"]), movie_duration) + + trak_children = T.cast(T.List[BoxDict], trak["data"]) + trak_children[:] = [box for box in trak_children if box["type"] != b"edts"] + elst: BoxDict = { + "type": b"elst", + "data": { + "version": 1, + "entries": [ + { + "segment_duration": movie_duration, + "media_time": earliest, + "media_rate_integer": 1, + "media_rate_fraction": 0, + } + ], + }, + } + # Right after tkhd, as ISO/IEC 14496-12 orders them + trak_children.insert(1, {"type": b"edts", "data": [elst]}) + + return movie_duration + + +def transform_mp4_cut( + src_fp: T.BinaryIO, + header: MP4Header, + start: float, + end: float, + sample_generator_factory: T.Callable[ + [float], T.Callable[[T.BinaryIO, list[BoxDict]], T.Iterator[io.IOBase]] + ] + | None = None, +) -> MP4Cut: + """ + Like transform_mp4(), but keep only the part of the video from **start** + to **end**, in seconds from the decoding time of the first sample of its + first video track: the time that the samples of a CAMM track have + against it, edit lists aside. **header** is that of **src_fp**. + + The part starts at a sync sample decoded and presented by **start**, and + ends before the first sync sample from which every frame is presented + after **end**: every frame presented in between decodes from the samples + kept, and no frame is encoded again. The source is read for those + samples only. Other video tracks, such as the second lens of a 360 + camera, are cut at the same time, and end at a sync sample of their own, + which may be later; raise MP4CutError if no sync sample of theirs is + there, or if a video track presents no frame from **start** to **end**. + + The part starts at time 0 of the new video. **sample_generator_factory** + is called with its start in the source (MP4Cut.start), and returns the + sample generator of transform_mp4(), to time the samples that it adds + on the new video. The creation time of the new video is that of the + source plus its start, in whole seconds as the movie header gives it. + """ + if math.isnan(start) or math.isnan(end): + raise MP4CutError(f"The cut has no time: from {start} to {end}") + if end < start: + raise MP4CutError(f"The cut ends ({end}) before it starts ({start})") + + moov_children = _MOOVChildrenParserConstruct.parse_boxlist(header.moov_data) + moov_children = list(_filter_moov_children_boxes(moov_children)) + movie_timescale = find_movie_timescale(moov_children) + + traks = list(_filter_trak_boxes(moov_children)) + if not traks: + raise MP4CutError("No video track found") + + track_cuts = [_plan_track_cut(trak, start, end) for trak in traks] + first_cut = track_cuts[0] + cut_start = first_cut.start_time + for cut in track_cuts[1:]: + # Within a millisecond, as the tracks may have other timescales + if 0.001 < abs(cut.start_time - cut_start): + raise MP4CutError( + f"The video tracks have no sync sample at the same time near {start} seconds: {cut_start} and {cut.start_time} seconds" + ) + + movie_duration = max( + _apply_track_cut(trak, movie_timescale, cut) + for trak, cut in zip(traks, track_cuts) + ) + mvhd = cparser.find_box_at_pathx(moov_children, [b"mvhd"]) + mvhd_data = T.cast(T.Dict[str, T.Any], mvhd["data"]) + _set_duration(mvhd_data, movie_duration) + # Zero if unknown + if mvhd_data.get("creation_time"): + mvhd_data["creation_time"] += round(cut_start) + if UINT32_MAX < mvhd_data["creation_time"]: + mvhd_data["version"] = 1 + + sample_readers: list[io.IOBase] = [ + io_utils.SlicedIO(src_fp, sample.offset, sample.size) + for sample in iterate_samples(moov_children) + ] + if sample_generator_factory is not None: + sample_readers.extend( + sample_generator_factory(cut_start)(src_fp, moov_children) + ) + + _update_all_trak_tkhd(moov_children) + + return MP4Cut( + stream=build_mp4(header.ftyp_data, moov_children, sample_readers), + start=cut_start, + end=max(cut.end_time for cut in track_cuts), + ) + + def build_mp4( ftyp_data: bytes, moov_children: T.Sequence[BoxDict], diff --git a/tests/unit/test_simple_mp4_cut.py b/tests/unit/test_simple_mp4_cut.py new file mode 100644 index 00000000..3321a89f --- /dev/null +++ b/tests/unit/test_simple_mp4_cut.py @@ -0,0 +1,491 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import annotations + +import dataclasses +import io +import math +import typing as T + +import pytest + +from mapillary_tools import geo +from mapillary_tools.camm import camm_builder, camm_parser +from mapillary_tools.mp4 import ( + construct_mp4_parser as cparser, + mp4_sample_parser as sample_parser, + simple_mp4_builder as builder, +) + +_FTYP_DATA = b"isom" + (512).to_bytes(4, "big") + b"isomiso2avc1mp41" +_STBLBuilder = cparser.Box32ConstructBuilder( + T.cast(cparser.SwitchMapType, cparser.CMAP[b"stbl"]) +) + + +@dataclasses.dataclass +class _Track: + name: str + handler: bytes + timescale: int + timedeltas: list[int] + syncs: set[int] + composition_offsets: list[int] | None = None + + def sample_data(self, idx: int) -> bytes: + return f"{self.name}{idx:04d};".encode() + + def raw_samples(self) -> list[sample_parser.RawSample]: + return [ + sample_parser.RawSample( + description_idx=1, + offset=0, + size=len(self.sample_data(idx)), + timedelta=delta, + composition_offset=( + self.composition_offsets[idx] if self.composition_offsets else 0 + ), + is_sync=idx in self.syncs, + ) + for idx, delta in enumerate(self.timedeltas) + ] + + def trak(self) -> cparser.BoxDict: + stbl = builder.build_stbl_from_raw_samples( + [{"format": b"avc1", "data_reference_index": 1, "data": b""}], + self.raw_samples(), + ) + duration = sum(self.timedeltas) + return { + "type": b"trak", + "data": [ + {"type": b"tkhd", "data": {"version": 0, "duration": duration}}, + { + "type": b"edts", + "data": [ + { + "type": b"elst", + "data": { + "version": 0, + "entries": [ + { + "segment_duration": duration, + "media_time": 0, + "media_rate_integer": 1, + "media_rate_fraction": 0, + } + ], + }, + } + ], + }, + { + "type": b"mdia", + "data": [ + { + "type": b"mdhd", + "data": { + "version": 0, + "creation_time": 0, + "modification_time": 0, + "timescale": self.timescale, + "duration": duration, + "language": 21956, + }, + }, + { + "type": b"hdlr", + "data": {"handler_type": self.handler, "name": ""}, + }, + { + "type": b"minf", + "data": [ + { + "type": b"stbl", + "data": _STBLBuilder.build_boxlist(stbl), + } + ], + }, + ], + }, + ], + } + + +def _build_mp4(tracks: T.Sequence[_Track]) -> bytes: + """An MP4 file of the tracks, 1000 movie timescale units a second""" + moov_children: list[cparser.BoxDict] = [ + { + "type": b"mvhd", + "data": { + "version": 0, + "creation_time": 0, + "modification_time": 0, + "timescale": 1000, + "duration": 0, + "next_track_ID": len(tracks) + 1, + }, + }, + *(track.trak() for track in tracks), + ] + readers = [ + io.BytesIO(track.sample_data(idx)) + for track in tracks + for idx in range(len(track.timedeltas)) + ] + return builder.build_mp4(_FTYP_DATA, moov_children, readers).read() + + +def _video(name="v", syncs=frozenset({0, 10, 20}), composition_offsets=None) -> _Track: + """30 frames of 1 second, a sync sample every 10""" + return _Track(name, b"vide", 1000, [1000] * 30, set(syncs), composition_offsets) + + +def _audio() -> _Track: + return _Track("a", b"soun", 48000, [48000] * 30, set(range(30))) + + +def _cut(data: bytes, start: float, end: float, **kwargs) -> builder.MP4Cut: + fp = io.BytesIO(data) + return builder.transform_mp4_cut( + fp, builder.MP4Header.read(fp), start, end, **kwargs + ) + + +def _parse(cut: builder.MP4Cut) -> tuple[bytes, sample_parser.MovieBoxParser]: + data = cut.stream.read() + return data, sample_parser.MovieBoxParser.parse_stream(io.BytesIO(data)) + + +def _sample_names(data: bytes, track: sample_parser.TrackBoxParser) -> list[str]: + return [ + data[s.offset : s.offset + s.size].decode().rstrip(";") + for s in track.extract_raw_samples() + ] + + +def test_cut_keeps_the_gops_around_the_range(): + cut = _cut(_build_mp4([_video(), _audio()]), 12, 18) + + assert (cut.start, cut.end) == (10, 20) + data, moov = _parse(cut) + # The audio track is left out, as transform_mp4() leaves it out + (track,) = moov.extract_tracks() + assert _sample_names(data, track) == [f"v{idx:04d}" for idx in range(10, 20)] + samples = list(track.extract_samples()) + assert samples[0].exact_time == 0 + assert samples[0].raw_sample.is_sync + assert [s.raw_sample.is_sync for s in samples[1:]] == [False] * 9 + assert track.extract_mdhd_boxdata()["duration"] == 10_000 + assert track.extract_tkhd_boxdata()["duration"] == 10_000 + assert moov.extract_mvhd_boxdata()["duration"] == 10_000 + elst = track.extract_elst_boxdata() + assert elst is not None + assert [(e["segment_duration"], e["media_time"]) for e in elst["entries"]] == [ + (10_000, 0) + ] + + +@pytest.mark.parametrize( + "start, end, expected", + [ + # The frame at 20 seconds is presented at the end: its GOP is kept + (10, 20, (10, 30)), + (10, 19.5, (10, 20)), + (0, 5, (0, 10)), + (25, 100, (20, 30)), + (-1, 0, (0, 10)), + ], +) +def test_cut_ends(start, end, expected): + cut = _cut(_build_mp4([_video()]), start, end) + + assert (cut.start, cut.end) == expected + data, moov = _parse(cut) + assert _sample_names(data, moov.extract_track_at(0)) == [ + f"v{idx:04d}" for idx in range(*expected) + ] + + +def test_cut_b_frames_presented_from_the_earliest(): + # Decoded I P B B P B B, presented I B B P B B P, one frame late + gop = [1000, 3000, 0, 0, 3000, 0, 0] + video = _Track("v", b"vide", 1000, [1000] * 28, {0, 7, 14, 21}, gop * 4) + + # The sync sample at 7 seconds is presented at 8 + cut = _cut(_build_mp4([video]), 9.5, 12) + + assert (cut.start, cut.end) == (7, 14) + data, moov = _parse(cut) + track = moov.extract_track_at(0) + assert _sample_names(data, track) == [f"v{idx:04d}" for idx in range(7, 14)] + assert [s.composition_offset for s in track.extract_raw_samples()] == gop + elst = track.extract_elst_boxdata() + assert elst is not None + assert [(e["segment_duration"], e["media_time"]) for e in elst["entries"]] == [ + (7000, 1000) + ] + + +def test_cut_starts_at_a_sync_sample_presented_by_the_start(): + gop = [1000, 3000, 0, 0, 3000, 0, 0] + video = _Track("v", b"vide", 1000, [1000] * 28, {0, 7, 14, 21}, gop * 4) + + # Decoded at 7 seconds, but presented at 8, after the start + cut = _cut(_build_mp4([video]), 7.5, 12) + + assert (cut.start, cut.end) == (0, 14) + + +def test_cut_leaves_out_the_leading_pictures_of_an_open_gop(): + offsets = [0] * 30 + # The sync sample at 10 seconds is presented at 12, after two frames + # that reference the GOP before it + offsets[10:13] = [2000, -1000, -1000] + video = _video(composition_offsets=offsets) + + cut = _cut(_build_mp4([video]), 12.5, 14) + + assert (cut.start, cut.end) == (10, 20) + data, moov = _parse(cut) + track = moov.extract_track_at(0) + assert _sample_names(data, track) == ["v0010"] + [ + f"v{idx:04d}" for idx in range(13, 20) + ] + samples = list(track.extract_samples()) + # The frames after them keep their times + assert [s.exact_time for s in samples] == [0, *range(3, 10)] + assert [s.exact_composition_time for s in samples] == [2, *range(3, 10)] + assert track.extract_mdhd_boxdata()["duration"] == 10_000 + + +def test_cut_other_video_tracks_at_the_same_time(): + cut = _cut(_build_mp4([_video("v"), _audio(), _video("w")]), 12, 18) + + data, moov = _parse(cut) + first, second = moov.extract_tracks() + assert _sample_names(data, first) == [f"v{idx:04d}" for idx in range(10, 20)] + assert _sample_names(data, second) == [f"w{idx:04d}" for idx in range(10, 20)] + assert [t.extract_tkhd_boxdata()["track_ID"] for t in (first, second)] == [1, 2] + + +def test_cut_fails_without_sync_samples_at_the_same_time(): + data = _build_mp4([_video("v"), _video("w", syncs={0, 5, 15, 25})]) + + with pytest.raises(builder.MP4CutError): + _cut(data, 12, 18) + + +def test_cut_fails_if_it_ends_before_it_starts(): + with pytest.raises(builder.MP4CutError): + _cut(_build_mp4([_video()]), 18, 12) + + +def test_cut_reads_only_the_samples_kept(): + data = _build_mp4([_video(), _audio()]) + read: list[tuple[int, int]] = [] + + class _Reader(io.BytesIO): + def read(self, n=-1): + offset = self.tell() + chunk = super().read(n) + read.append((offset, len(chunk))) + return chunk + + fp = _Reader(data) + header = builder.MP4Header.read(fp) + read.clear() + cut = builder.transform_mp4_cut(fp, header, 12, 18) + assert read == [] + cut.stream.read() + + video = _video() + assert b"".join(data[offset : offset + size] for offset, size in read) == b"".join( + video.sample_data(idx) for idx in range(10, 20) + ) + + +def test_cut_times_added_samples_on_the_new_video(): + points = [ + geo.Point(time=t, lat=59.5 + t / 10_000, lon=11.6, alt=None, angle=None) + for t in (12.5, 15.0, 17.5) + ] + starts: list[float] = [] + + def factory(cut_start: float): + starts.append(cut_start) + return camm_builder.camm_sample_generator2( + camm_parser.CAMMInfo( + mini_gps=[ + dataclasses.replace(p, time=p.time - cut_start) for p in points + ] + ) + ) + + cut = _cut(_build_mp4([_video()]), 12.5, 17.5, sample_generator_factory=factory) + + assert starts == [10] + camm_info = camm_parser.extract_camm_info(T.cast(T.BinaryIO, cut.stream)) + assert camm_info is not None + assert [round(p.time, 3) for p in camm_info.mini_gps or []] == [2.5, 5.0, 7.5] + + +def test_cut_a_video_of_one_gop_whole(): + # The H.265 video track of this video has negative composition offsets + # and one sync sample + path = "tests/data/videos/sample-5s_h265.mp4" + with open(path, "rb") as fp: + source = sample_parser.MovieBoxParser.parse_stream(fp) + source_samples = list(source.extract_track_at(0).extract_raw_samples()) + cut = builder.transform_mp4_cut(fp, builder.MP4Header.read(fp), 1, 2) + target = sample_parser.MovieBoxParser.parse_stream( + T.cast(T.BinaryIO, cut.stream) + ) + + assert cut.start == 0 + target_samples = list(target.extract_track_at(0).extract_raw_samples()) + assert [ + (s.size, s.timedelta, s.composition_offset, s.is_sync) for s in target_samples + ] == [ + (s.size, s.timedelta, s.composition_offset, s.is_sync) for s in source_samples + ] + + +def test_cut_keeps_the_leading_pictures_presented_by_the_end(): + offsets = [0] * 30 + # The sync sample at 10 seconds is presented at 12, after two frames, + # presented at 10 and 11, that are decoded after it + offsets[10:13] = [2000, -1000, -1000] + video = _video(composition_offsets=offsets) + + cut = _cut(_build_mp4([video]), 2, 10.5) + + # The frame presented at 10 seconds is decoded after the sync sample at + # 10 seconds, so the cut runs on to the next one + assert (cut.start, cut.end) == (0, 20) + + +def test_cut_ends_by_presentation_time(): + gop = [1000, 3000, 0, 0, 3000, 0, 0] + video = _Track("v", b"vide", 1000, [1000] * 28, {0, 7, 14, 21}, gop * 4) + + # The sync sample at 14 seconds is presented at 15, after the end + cut = _cut(_build_mp4([video]), 9.5, 14.5) + + assert (cut.start, cut.end) == (7, 14) + + +def test_cut_times_added_samples_on_the_frames_of_the_new_video(): + # Decoded I P B B P B B, presented I B B P B B P, one frame late + gop = [1000, 3000, 0, 0, 3000, 0, 0] + video = _Track("v", b"vide", 1000, [1000] * 28, {0, 7, 14, 21}, gop * 4) + # The composition times of the frames, against which the points are + # timed: the sync sample at 7 seconds is presented at 8 + source_frames = { + idx + offset // 1000: f"v{idx:04d}" for idx, offset in enumerate(gop * 4) + } + times = [9, 10, 11, 12, 13] + points = [ + geo.Point(time=t, lat=59.5 + t / 10_000, lon=11.6, alt=None, angle=None) + for t in times + ] + + def factory(cut_start: float): + return camm_builder.camm_sample_generator2( + camm_parser.CAMMInfo( + mini_gps=[ + dataclasses.replace(p, time=p.time - cut_start) for p in points + ] + ) + ) + + cut = _cut(_build_mp4([video]), 9, 13, sample_generator_factory=factory) + + data, moov = _parse(cut) + track = moov.extract_track_at(0) + names = _sample_names(data, track) + frames = { + round(s.exact_composition_time, 3): name + for s, name in zip(track.extract_samples(), names) + } + camm_info = camm_parser.extract_camm_info(io.BytesIO(data)) + assert camm_info is not None + # Each point is on the frame it is on in the source + assert [frames[round(p.time, 3)] for p in camm_info.mini_gps or []] == [ + source_frames[t] for t in times + ] + + +def test_cut_presents_every_frame_kept(): + offsets = [0] * 30 + # The last frame is presented a frame late, as when a cut of the source + # left out the frames presented before it + offsets[29] = 1000 + video = _video(composition_offsets=offsets) + + cut = _cut(_build_mp4([video]), 25, 30) + + _, moov = _parse(cut) + track = moov.extract_track_at(0) + assert track.extract_mdhd_boxdata()["duration"] == 10_000 + # The last frame is presented from 10 to 11 seconds + assert track.extract_tkhd_boxdata()["duration"] == 11_000 + assert moov.extract_mvhd_boxdata()["duration"] == 11_000 + elst = track.extract_elst_boxdata() + assert elst is not None + assert [(e["segment_duration"], e["media_time"]) for e in elst["entries"]] == [ + (11_000, 0) + ] + + +def test_cut_replaces_the_edit_list(): + cut = _cut(_build_mp4([_video()]), 12, 18) + + boxes = cparser.MP4WithoutSTBLParserConstruct.parse_boxlist(cut.stream.read()) + trak = cparser.find_box_at_pathx(boxes, [b"moov", b"trak"]) + assert [box["type"] for box in T.cast(T.List[cparser.BoxDict], trak["data"])] == [ + b"tkhd", + b"edts", + b"mdia", + ] + + +def test_cut_ends_with_the_video_track_that_runs_the_longest(): + data = _build_mp4([_video("v"), _video("w", syncs={0, 10, 25})]) + + cut = _cut(data, 12, 18) + + assert (cut.start, cut.end) == (10, 25) + data, moov = _parse(cut) + first, second = moov.extract_tracks() + assert _sample_names(data, second) == [f"w{idx:04d}" for idx in range(10, 25)] + assert moov.extract_mvhd_boxdata()["duration"] == 15_000 + + +@pytest.mark.parametrize( + "start, end", + [(31, 40), (30, 30), (-3, -1), (math.nan, 5), (5, math.nan)], +) +def test_cut_fails_where_no_frame_is_presented(start, end): + with pytest.raises(builder.MP4CutError): + _cut(_build_mp4([_video()]), start, end) + + +def test_cut_moves_the_creation_time_to_its_start(): + data = _build_mp4([_video()]) + moov_start = data.index(b"mvhd") - 4 + # creation_time, after the version and the flags of the mvhd box + creation_time = moov_start + 8 + 4 + data = ( + data[:creation_time] + + (3_700_000_000).to_bytes(4, "big") + + data[creation_time + 4 :] + ) + + cut = _cut(data, 12.6, 18) + + _, moov = _parse(cut) + assert moov.extract_mvhd_boxdata()["creation_time"] == 3_700_000_010