Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
292 changes: 292 additions & 0 deletions mapillary_tools/mp4/simple_mp4_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import dataclasses
import io
import itertools
import math
import typing as T

from . import (
Expand Down Expand Up @@ -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],
Expand Down
Loading
Loading