diff --git a/docs/dev/service-architecture.md b/docs/dev/service-architecture.md
index a73769ad..d27dc865 100644
--- a/docs/dev/service-architecture.md
+++ b/docs/dev/service-architecture.md
@@ -373,7 +373,8 @@ A typical `get_tracks` therefore looks like fetching the manifest text with
When a period's fragment timeline starts again near 0, as in a stitched ad stream that
packages each part of the title on its own, the merge moves that period to follow the
periods it keeps before it. A timeline that continues is not changed, so the gaps of filtered ad
- periods stay in it. Plain WebVTT periods and HLS subtitles across `EXT-X-DISCONTINUITY` blocks
+ periods stay in it. Audio that runs past a period join is cut where the next period
+ starts. Plain WebVTT periods and HLS subtitles across `EXT-X-DISCONTINUITY` blocks
get the same treatment: fVTT through its tfdt, and WebVTT through its cue times, which move to
the block's playlist start when that puts more cues inside the block.
- **HLS** re-fetches the media playlist at download time, recovers `SUPPLEMENTAL-CODECS`
diff --git a/tests/core/test_dash_period_rebase.py b/tests/core/test_dash_period_rebase.py
index 43d5c26c..66e35a6c 100644
--- a/tests/core/test_dash_period_rebase.py
+++ b/tests/core/test_dash_period_rebase.py
@@ -15,8 +15,9 @@ from lxml import etree
from unshackle.core.config import config
from unshackle.core.manifests import DASH, HLS
from unshackle.core.manifests.dash import PeriodRebase, mdhd_timescale, tfdt_fields
-from unshackle.core.manifests.ism_init import box, full_box
+from unshackle.core.manifests.ism_init import box, build_sinf, full_box
from unshackle.core.manifests.snapshot import fragments, unpack
+from unshackle.core.manifests.trim import trim_overlaps
from unshackle.core.tracks import Tracks
from unshackle.core.tracks.track import DownloadContext, Track
@@ -305,3 +306,195 @@ def test_download_track_rebases_webvtt_periods(server: ThreadingHTTPServer, tmp_
"00:00:02.100",
"00:00:03.100",
]
+
+
+def audio_fragment(
+ decode_time: int,
+ samples: int,
+ duration: int = 1024,
+ encrypted: bool = False,
+ per_sample_durations: bool = True,
+ roll: bool = False,
+ extra: bytes = b"",
+) -> bytes:
+ """A moof of one-byte samples, then an mdat holding each sample's index.
+
+ encrypted adds senc, saiz and saio; roll adds an sbgp that puts the samples in two roll groups; extra goes in
+ the traf as it is.
+ """
+ tfhd_flags, defaults = (0x020000, b"") if per_sample_durations else (0x020008, struct.pack(">I", duration))
+ tfhd = full_box(b"tfhd", 0, tfhd_flags, struct.pack(">I", 1) + defaults)
+ tfdt = full_box(b"tfdt", 1, 0, struct.pack(">Q", decode_time))
+ entry = struct.pack(">II", duration, 1) if per_sample_durations else struct.pack(">I", 1)
+ trun_size = 8 + 4 + 8 + len(entry) * samples
+ half = samples // 2
+ sbgp = full_box(b"sbgp", 0, 0, b"roll" + struct.pack(">IIIII", 2, half, 1, samples - half, 2)) if roll else b""
+ head = 8 + 16 + 8 + len(tfhd) + len(tfdt) + trun_size + len(sbgp) + len(extra)
+ senc = saiz = saio = b""
+ if encrypted:
+ ivs = b"".join(struct.pack(">QHHI", n, 1, 0, 1) for n in range(samples))
+ senc = full_box(b"senc", 0, 0x2, struct.pack(">I", samples) + ivs)
+ saiz = full_box(b"saiz", 0, 0, struct.pack(">BI", 16, samples))
+ saio = full_box(b"saio", 0, 0, struct.pack(">II", 1, head + 16))
+ moof_size = head + len(senc) + len(saiz) + len(saio)
+ flags = 0x301 if per_sample_durations else 0x201
+ trun = full_box(b"trun", 0, flags, struct.pack(">II", samples, moof_size + 8) + entry * samples)
+ traf = box(b"traf", tfhd + tfdt + trun + sbgp + extra + senc + saiz + saio)
+ return box(b"moof", box(b"mfhd", b"\0" * 8) + traf) + box(b"mdat", bytes(range(samples)))
+
+
+def encrypted_init(timescale: int) -> bytes:
+ mdhd = full_box(b"mdhd", 0, 0, struct.pack(">III", 0, 0, timescale) + b"\0" * 8)
+ enca = box(b"enca", b"\0" * 28 + build_sinf(b"mp4a", b"\1" * 16, 8))
+ stsd = full_box(b"stsd", 0, 0, struct.pack(">I", 1) + enca)
+ return box(b"ftyp", b"iso6") + box(b"moov", box(b"trak", box(b"mdia", mdhd + box(b"minf", box(b"stbl", stsd)))))
+
+
+def box_at(data: bytes, kind: bytes) -> int:
+ return data.index(kind) - 4
+
+
+JOIN = 3 * 1024 + 100
+
+
+def overlapping(**kwargs: Any) -> bytes:
+ """Five samples, then a period join two samples before they end."""
+ return audio_fragment(0, 5, **kwargs) + audio_fragment(JOIN, 2, **kwargs)
+
+
+def test_trim_overlaps_drops_the_audio_past_the_next_period(tmp_path: Path) -> None:
+ path = tmp_path / "audio.mp4"
+ path.write_bytes(init_segment(48000) + box(b"sidx", b"\0" * 24) + overlapping())
+
+ assert trim_overlaps(path, {JOIN}) == 2
+
+ data = path.read_bytes()
+ assert b"sidx" not in data and b"free" in data
+ assert tfdts(data) == [0, JOIN]
+ mdat = box_at(data, b"mdat")
+ assert data[mdat : mdat + 11] == struct.pack(">I", 11) + b"mdat" + bytes(range(3))
+ assert trim_overlaps(path, {JOIN}) == 0
+
+
+def test_download_track_trims_audio_that_overlaps_the_next_period(server: ThreadingHTTPServer, tmp_path: Path) -> None:
+ # period 0 is 2 s in the manifest but its audio runs to 2.5 s; period 1 restarts at 0
+ for path, data in {
+ "/a0/init.mp4": init_segment(1000),
+ "/a0/1.m4s": audio_fragment(0, 3, 500),
+ "/a0/2.m4s": audio_fragment(1500, 2, 500),
+ "/a1/init.mp4": init_segment(1000),
+ "/a1/1.m4s": audio_fragment(0, 2, 500),
+ "/a1/2.m4s": audio_fragment(1000, 2, 500),
+ }.items():
+ server.routes[path] = data # type: ignore[attr-defined]
+ periods = "".join(
+ f"""
+
+
+
+
+ """
+ for p in (0, 1)
+ )
+ mpd = f"""
+
+ http://127.0.0.1:{server.server_address[1]}/{periods}"""
+ audio = DASH.from_text(mpd, "http://127.0.0.1/manifest.mpd").to_tracks(language="en").audio[0]
+ ctx = DownloadContext(
+ save_path=tmp_path / "out.mp4", save_dir=tmp_path / "a0_segments", progress=partial(lambda **kw: None)
+ )
+
+ DASH.download_track(audio, ctx)
+
+ data = (tmp_path / "out.mp4").read_bytes()
+ assert tfdts(data) == [0, 1500, 2000, 3000]
+ counts = [int.from_bytes(data[m.start() + 8 : m.start() + 12], "big") for m in re.finditer(b"trun", data)]
+ assert counts == [3, 1, 2, 2]
+
+
+def test_trim_overlaps_cuts_the_encryption_boxes_with_the_samples(tmp_path: Path) -> None:
+ path = tmp_path / "audio.mp4"
+ second = audio_fragment(JOIN, 2, encrypted=True, roll=True)
+ path.write_bytes(encrypted_init(48000) + audio_fragment(0, 5, encrypted=True, roll=True) + second)
+
+ assert trim_overlaps(path, {JOIN}) == 2
+
+ data = path.read_bytes()
+ moof, senc, saiz, saio, trun, sbgp, mdat = (
+ box_at(data, k) for k in (b"moof", b"senc", b"saiz", b"saio", b"trun", b"sbgp", b"mdat")
+ )
+ assert int.from_bytes(data[senc + 12 : senc + 16], "big") == 3
+ assert int.from_bytes(data[senc : senc + 4], "big") == 16 + 3 * 16
+ assert int.from_bytes(data[saiz + 13 : saiz + 17], "big") == 3
+ assert int.from_bytes(data[saio + 16 : saio + 20], "big") == senc + 16 - moof
+ assert struct.unpack_from(">IIIII", data, sbgp + 16) == (2, 2, 1, 1, 2)
+ assert int.from_bytes(data[trun + 16 : trun + 20], "big") == mdat + 8 - moof
+ assert data[mdat + 8 : mdat + 11] == bytes(range(3))
+ assert data.endswith(second)
+
+
+def test_trim_overlaps_reads_default_durations(tmp_path: Path) -> None:
+ path = tmp_path / "audio.mp4"
+ path.write_bytes(init_segment(48000) + overlapping(per_sample_durations=False))
+ assert trim_overlaps(path, {JOIN}) == 2
+
+
+def test_trim_overlaps_drops_a_fragment_wholly_past_the_next_one(tmp_path: Path) -> None:
+ path = tmp_path / "audio.mp4"
+ path.write_bytes(
+ init_segment(48000) + audio_fragment(0, 3) + audio_fragment(3 * 1024, 3) + audio_fragment(3 * 1024 + 400, 2)
+ )
+ assert trim_overlaps(path, {3 * 1024 + 400}) == 3
+ data = path.read_bytes()
+ assert tfdts(data) == [0, 3 * 1024 + 400]
+ assert data.count(b"mdat") == 2
+
+
+@pytest.mark.parametrize(
+ ("fragments", "joins"),
+ [
+ pytest.param([(0, 3), (3 * 1024, 3)], {3 * 1024}, id="continuous"),
+ pytest.param([(0, 5), (JOIN, 2)], {0}, id="overlap-away-from-a-join"),
+ pytest.param([(0, 4), (4096, 4), (8192, 4), (100, 4)], {4096}, id="backwards-tfdt"),
+ ],
+)
+def test_trim_overlaps_cuts_only_at_a_join(tmp_path: Path, fragments: list, joins: set) -> None:
+ path = tmp_path / "audio.mp4"
+ original = init_segment(48000) + b"".join(audio_fragment(t, n) for t, n in fragments)
+ path.write_bytes(original)
+ assert trim_overlaps(path, joins) == 0
+ assert path.read_bytes() == original
+
+
+@pytest.mark.parametrize(
+ "tail",
+ [
+ pytest.param(struct.pack(">I", 0) + b"mdat" + b"\0" * 8, id="size-0"),
+ pytest.param(struct.pack(">I", 1) + b"mdat" + struct.pack(">Q", 24) + b"\0" * 8, id="64-bit-size"),
+ pytest.param(box(b"mdat", b"\0" * 8)[:-2], id="truncated"),
+ ],
+)
+def test_trim_overlaps_leaves_a_file_it_cannot_read_to_the_end(tmp_path: Path, tail: bytes) -> None:
+ path = tmp_path / "audio.mp4"
+ original = init_segment(48000) + overlapping() + tail
+ path.write_bytes(original)
+ assert trim_overlaps(path, {JOIN}) == 0
+ assert path.read_bytes() == original
+
+
+def test_trim_overlaps_bounds_the_sample_count(tmp_path: Path) -> None:
+ tfhd = full_box(b"tfhd", 0, 0x020018, struct.pack(">III", 1, 1024, 1))
+ tfdt = full_box(b"tfdt", 1, 0, struct.pack(">Q", 0))
+ trun = full_box(b"trun", 0, 0x001, struct.pack(">II", 0xFFFFFFFF, 0))
+ huge = box(b"moof", box(b"traf", tfhd + tfdt + trun)) + box(b"mdat", b"\0" * 4)
+ path = tmp_path / "audio.mp4"
+ path.write_bytes(init_segment(48000) + huge + audio_fragment(100, 2))
+ assert trim_overlaps(path, {100}) == 0
+
+
+def test_trim_overlaps_logs_a_fragment_it_cannot_rewrite(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
+ path = tmp_path / "audio.mp4"
+ path.write_bytes(init_segment(48000) + overlapping(extra=box(b"sdtp", b"\0" * 4)))
+ with caplog.at_level("DEBUG", logger="DASH"):
+ assert trim_overlaps(path, {JOIN}) == 0
+ assert "1 overlapping audio fragments" in caplog.text
diff --git a/unshackle/core/manifests/dash.py b/unshackle/core/manifests/dash.py
index d16dbe27..3b55031d 100644
--- a/unshackle/core/manifests/dash.py
+++ b/unshackle/core/manifests/dash.py
@@ -35,6 +35,7 @@ from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine
from unshackle.core.drm.segment_decrypt import SEGMENT_DRM_T, SegmentDecrypter, can_use
from unshackle.core.drm.verify import decrypt_track, walk
from unshackle.core.events import events
+from unshackle.core.manifests.trim import trim_overlaps
from unshackle.core.session import RnetSession
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
from unshackle.core.tracks.track import (
@@ -191,7 +192,8 @@ class PeriodRebase:
that is later. Any other period keeps the shift before it, or drops it when its own timeline is
nearer its output start, so a continuous timeline keeps its decode times and gaps. A track whose
first period starts later in the output but whose timeline starts near 0 is placed at that start.
- Only tfdt moves; sidx, emsg and prft stay as they are.
+ Only tfdt moves; sidx, emsg and prft stay as they are. ``joins`` collects the output decode time of
+ each period after the first.
"""
def __init__(self, periods: dict[int, tuple[float, float, float]], timescale: int) -> None:
@@ -200,6 +202,7 @@ class PeriodRebase:
self.offset = 0
self.base: Optional[int] = None
self.previous: Optional[tuple[int, int, int]] = None
+ self.joins: set[int] = set()
def append(self, dst: BinaryIO, segment_file: Path) -> None:
period = self.periods.get(int(segment_file.stem))
@@ -245,6 +248,8 @@ class PeriodRebase:
self.offset = max(target, previous_end) - media_start
elif self.offset and abs(media_start - target) < abs(media_start + self.offset - target):
self.offset = max(0, previous_end - media_start)
+ if self.previous:
+ self.joins.add(first + self.offset)
self.previous = (first + self.offset, length, media_start + self.offset + length)
@@ -962,6 +967,13 @@ class DASH:
segment_file.unlink()
progress(advance=1)
+ if rebase and rebase.joins and isinstance(track, Audio):
+ try:
+ if dropped := trim_overlaps(save_path, rebase.joins):
+ log.debug(f"Dropped {dropped} audio samples that overlap the next period: {save_path.name}")
+ except Exception as e:
+ log.warning(f"Could not trim the audio overlaps of {save_path.name}: {e}")
+
track.path = save_path
events.emit(events.Types.TRACK_DOWNLOADED, track=track)
diff --git a/unshackle/core/manifests/trim.py b/unshackle/core/manifests/trim.py
new file mode 100644
index 00000000..767b0d47
--- /dev/null
+++ b/unshackle/core/manifests/trim.py
@@ -0,0 +1,293 @@
+"""Drop the audio samples that run past a period join in a merged fragmented MP4."""
+
+from __future__ import annotations
+
+import logging
+import mmap
+from pathlib import Path
+from typing import Collection, NamedTuple, Optional, cast
+
+from unshackle.core.drm.verify import ENTRY_FIELDS, children, walk
+from unshackle.core.manifests.ism_init import box
+
+log = logging.getLogger("DASH")
+
+TRIMMABLE_TRAF = {b"tfhd", b"tfdt", b"trun", b"senc", b"saiz", b"saio", b"sbgp", b"sgpd"}
+GROUPING = (b"sbgp", b"sgpd")
+CENC = {b"senc", b"saiz", b"saio"}
+
+Runs = tuple[int, list[tuple[int, int]]]
+
+
+def child_boxes(data: bytes, start: int, end: int) -> list[tuple[bytes, int, int]]:
+ """(type, start, end) of each box in data[start:end]; unlike verify.children it stops at a size 0 or 64-bit box."""
+ boxes = []
+ while start + 8 <= end:
+ size = int.from_bytes(data[start : start + 4], "big")
+ if size < 8 or start + size > end:
+ break
+ boxes.append((data[start + 4 : start + 8], start, start + size))
+ start += size
+ return boxes
+
+
+def be32(data: bytes, at: int) -> int:
+ return int.from_bytes(data[at : at + 4], "big")
+
+
+def aux_start(data: bytes, start: int) -> int:
+ """The offset after the full box header and optional aux_info_type of a saiz or saio box at ``start``."""
+ return start + 12 + 8 * (data[start + 11] & 0x1)
+
+
+class FragmentSamples(NamedTuple):
+ """The samples of a moof with one traf and one trun, and where trim_overlaps can cut them."""
+
+ decode_time: int
+ durations: list[int]
+ sizes: list[int]
+ traf: tuple[int, int]
+ children: list[tuple[bytes, int, int]]
+ fields: int
+ width: int
+ lead: int
+ senc: list[int]
+ groups: dict[int, Runs]
+ trimmable: bool
+
+
+def senc_ends(data: bytes, start: int, end: int, iv_size: int) -> Optional[list[int]]:
+ """The end offset of each sample entry of a senc box, or None when the entries do not fill it exactly."""
+ flags, pos, ends = be32(data, start + 8) & 0xFFFFFF, start + 16, []
+ for _ in range(be32(data, start + 12)):
+ pos += iv_size
+ if flags & 0x2:
+ if pos + 2 > end:
+ return None
+ pos += 2 + 6 * int.from_bytes(data[pos : pos + 2], "big")
+ if pos > end:
+ return None
+ ends.append(pos)
+ return ends if pos == end else None
+
+
+def cenc_entries(
+ data: bytes, named: dict[bytes, tuple[int, int]], moof: int, count: int, iv_size: int
+) -> Optional[list[int]]:
+ """The senc entry ends of a traf whose senc, saiz and saio describe ``count`` samples, saio pointing at senc."""
+ if not CENC <= named.keys() or iv_size < 0:
+ return None
+ (senc, senc_end), (saiz, saiz_end), (saio, _) = named[b"senc"], named[b"saiz"], named[b"saio"]
+ ends = senc_ends(data, senc, senc_end, iv_size)
+ sizes, offsets = aux_start(data, saiz), aux_start(data, saio)
+ width = 8 if data[saio + 8] == 1 else 4
+ fits = (
+ ends is not None
+ and len(ends) == count
+ and be32(data, sizes + 1) == count
+ and bool(data[sizes] or sizes + 5 + count <= saiz_end)
+ and be32(data, offsets) == 1
+ and int.from_bytes(data[offsets + 4 : offsets + 4 + width], "big") == senc - moof + 16
+ )
+ return ends if fits else None
+
+
+def group_runs(data: bytes, start: int, end: int) -> Optional[Runs]:
+ """The entry count offset and (sample count, group index) runs of an sbgp box, or None when they overrun it."""
+ at = start + 16 + 4 * (data[start + 8] == 1)
+ count = be32(data, at)
+ if at + 4 + 8 * count != end:
+ return None
+ return at, [(be32(data, at + 4 + 8 * n), be32(data, at + 8 + 8 * n)) for n in range(count)]
+
+
+def read_samples(
+ data: bytes, moof: tuple[int, int], mdat: Optional[tuple[int, int]], defaults: tuple[int, int], iv_size: int
+) -> Optional[FragmentSamples]:
+ """Parse a moof and the mdat right after it; None when it has no single traf with a tfdt and one bounded trun."""
+ start, end = moof
+ trafs = [b for b in child_boxes(data, start + 8, end) if b[0] == b"traf"]
+ if len(trafs) != 1:
+ return None
+ traf = trafs[0][1:]
+ kids = child_boxes(data, traf[0] + 8, traf[1])
+ named = {k: (s, e) for k, s, e in kids}
+ truns = [c for c in kids if c[0] == b"trun"]
+ if b"tfdt" not in named or b"tfhd" not in named or len(truns) != 1 or mdat is None:
+ return None
+ tfdt, tfdt_end = named[b"tfdt"]
+ tfdt_width = 8 if data[tfdt + 8] == 1 else 4
+ tfhd, tfhd_end = named[b"tfhd"]
+ tfhd_flags = be32(data, tfhd + 8) & 0xFFFFFF
+ _, trun, trun_end = truns[0]
+ flags, count = be32(data, trun + 8) & 0xFFFFFF, be32(data, trun + 12)
+ fields = trun + 16 + 4 * bool(flags & 0x1) + 4 * bool(flags & 0x4)
+ width = 4 * bin(flags & 0xF00).count("1")
+ duration, size = defaults
+ at = tfhd + 16 + 8 * bool(tfhd_flags & 0x1) + 4 * bool(tfhd_flags & 0x2)
+ if tfhd_flags & 0x8:
+ duration, at = be32(data, at), at + 4
+ if tfhd_flags & 0x10:
+ size, at = be32(data, at), at + 4
+ payload = mdat[1] - mdat[0] - 8
+ if (
+ tfdt + 12 + tfdt_width > tfdt_end
+ or at > tfhd_end
+ or fields + count * width > trun_end
+ or (not width and count * max(size, 1) > payload)
+ ):
+ return None
+ decode_time = int.from_bytes(data[tfdt + 12 : tfdt + 12 + tfdt_width], "big")
+ durations, sizes = [], []
+ for entry in range(fields, fields + count * width, width) if width else [fields] * count:
+ durations.append(be32(data, entry) if flags & 0x100 else duration)
+ sizes.append(be32(data, entry + 4 * bool(flags & 0x100)) if flags & 0x200 else size)
+
+ lead = int.from_bytes(data[trun + 16 : trun + 20], "big", signed=True) - (end - start) - 8
+ groups = {s: runs for k, s, e in kids if k == b"sbgp" and (runs := group_runs(data, s, e))}
+ single = [k for k, _, _ in kids if k not in GROUPING]
+ ends = cenc_entries(data, named, start, count, iv_size) if CENC & named.keys() else []
+ trimmable = (
+ ends is not None
+ and set(named) <= TRIMMABLE_TRAF
+ and len(single) == len(set(single))
+ and len(groups) == sum(k == b"sbgp" for k, _, _ in kids)
+ and all(sum(n for n, _ in runs) == count for _, runs in groups.values())
+ and not tfhd_flags & 0x1
+ and bool(flags & 0x1)
+ and 0 <= lead
+ and lead + sum(sizes) <= payload
+ )
+ return FragmentSamples(
+ decode_time, durations, sizes, traf, kids, fields, width, lead, ends or [], groups, trimmable
+ )
+
+
+def rebuild_fragment(
+ data: bytes, moof: tuple[int, int], mdat: tuple[int, int], fragment: FragmentSamples, kept: int
+) -> bytes:
+ """The moof and mdat of a fragment cut to its first ``kept`` samples, with trun, senc, saiz, saio and sbgp to match."""
+ count = kept.to_bytes(4, "big")
+ pieces: list[bytes] = []
+ at: dict[bytes, int] = {}
+ for kind, s, e in fragment.children:
+ at[kind] = sum(map(len, pieces))
+ if kind == b"trun":
+ piece = box(kind, data[s + 8 : s + 12] + count + data[s + 16 : fragment.fields + kept * fragment.width])
+ elif kind == b"senc":
+ piece = box(kind, data[s + 8 : s + 12] + count + data[s + 16 : fragment.senc[kept - 1]])
+ elif kind == b"saiz":
+ p = aux_start(data, s)
+ piece = box(kind, data[s + 8 : p + 1] + count + (b"" if data[p] else data[p + 5 : p + 5 + kept]))
+ elif kind == b"sbgp":
+ p, runs = fragment.groups[s]
+ cut, left = b"", kept
+ for samples, group in runs:
+ take = min(samples, left)
+ if not take:
+ break
+ cut += take.to_bytes(4, "big") + group.to_bytes(4, "big")
+ left -= take
+ piece = box(kind, data[s + 8 : p] + (len(cut) // 8).to_bytes(4, "big") + cut)
+ else:
+ piece = data[s:e]
+ pieces.append(piece)
+ traf_start, traf_end = fragment.traf
+ out = bytearray(data[moof[0] : traf_start] + box(b"traf", b"".join(pieces)) + data[traf_end : moof[1]])
+ out[0:4] = len(out).to_bytes(4, "big")
+ traf_body = traf_start - moof[0] + 8
+ trun = traf_body + at[b"trun"] + 16
+ out[trun : trun + 4] = (len(out) + 8 + fragment.lead).to_bytes(4, "big", signed=True)
+ if b"saio" in at:
+ saio = traf_body + at[b"saio"]
+ field, width = aux_start(out, saio) + 4, 8 if out[saio + 8] == 1 else 4
+ out[field : field + width] = (traf_body + at[b"senc"] + 16).to_bytes(width, "big")
+ payload = data[mdat[0] + 8 : mdat[0] + 8 + fragment.lead + sum(fragment.sizes[:kept])]
+ return bytes(out) + box(b"mdat", payload)
+
+
+def sample_iv_size(data: bytes, start: int, end: int) -> int:
+ """The per-sample IV size in the first CENC tenc of a moov, or -1 when it has none."""
+ for kind, body, box_end in walk(data, start, end):
+ if kind != b"stsd":
+ continue
+ for entry_kind, entry, entry_end in children(data, body + 8, box_end):
+ for fields in ENTRY_FIELDS.get(entry_kind, ()):
+ boxes = list(walk(data, entry + fields, entry_end))
+ if any(k == b"sinf" for k, _, _ in boxes):
+ return next((data[b + 7] for k, b, e in boxes if k == b"tenc" and e - b >= 8), -1)
+ return -1
+
+
+def trim_overlaps(path: Path, joins: Collection[int]) -> int:
+ """Drop the samples of a fragment that start after the period join that follows it; returns how many it dropped.
+
+ A restarted period begins at the manifest end of the one before it, but that period's audio can run past
+ its end, and a player plays every sample in turn, so each join would push the audio later. ``joins`` holds
+ the decode time of each period start; a sample before one stays while its middle falls before it. A file
+ it cannot read to the end stays as it is, and a sidx becomes a free box, as the fragment sizes change.
+ """
+ if not joins or not path.stat().st_size:
+ return 0
+ temp = path.with_suffix(path.suffix + ".trim")
+ try:
+ with open(path, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mapped:
+ dropped = write_trimmed(cast(bytes, mapped), temp, joins)
+ if dropped:
+ temp.replace(path)
+ return dropped
+ finally:
+ temp.unlink(missing_ok=True)
+
+
+def write_trimmed(data: bytes, temp: Path, joins: Collection[int]) -> int:
+ """Write ``data`` with the samples past each join dropped to ``temp``; returns 0 and writes nothing when none."""
+ top = child_boxes(data, 0, len(data))
+ moov = next(((s, e) for k, s, e in top if k == b"moov"), None)
+ if not moov or top[-1][2] != len(data):
+ return 0
+ trex = next((b for k, b, _ in walk(data, moov[0] + 8, moov[1]) if k == b"trex"), None)
+ defaults = (be32(data, trex + 12), be32(data, trex + 16)) if trex is not None else (0, 0)
+ iv_size = sample_iv_size(data, moov[0] + 8, moov[1])
+
+ fragments: list[tuple[int, FragmentSamples]] = []
+ for i, (kind, start, end) in enumerate(top):
+ if kind == b"moof":
+ mdat = top[i + 1][1:] if i + 1 < len(top) and top[i + 1][0] == b"mdat" else None
+ if fragment := read_samples(data, (start, end), mdat, defaults, iv_size):
+ fragments.append((i, fragment))
+
+ keep: dict[int, int] = {}
+ untrimmable = 0
+ for (i, fragment), (_, following) in zip(fragments, fragments[1:]):
+ join = following.decode_time
+ if join not in joins or fragment.decode_time + sum(fragment.durations) <= join:
+ continue
+ if not fragment.trimmable:
+ untrimmable += 1
+ continue
+ kept, at = 0, fragment.decode_time
+ for duration in fragment.durations:
+ if at + duration / 2 >= join:
+ break
+ kept, at = kept + 1, at + duration
+ if kept < len(fragment.durations):
+ keep[i] = kept
+ if untrimmable:
+ log.debug(f"Left {untrimmable} overlapping audio fragments it cannot rewrite: {temp.stem}")
+ if not keep:
+ return 0
+
+ by_index = dict(fragments)
+ with open(temp, "wb") as out:
+ for i, (kind, start, end) in enumerate(top):
+ if i - 1 in keep and kind == b"mdat":
+ continue
+ if kind == b"sidx":
+ out.write(data[start : start + 4] + b"free" + data[start + 8 : end])
+ elif i in keep:
+ if keep[i]:
+ out.write(rebuild_fragment(data, (start, end), top[i + 1][1:], by_index[i], keep[i]))
+ else:
+ out.write(data[start:end])
+ return sum(len(by_index[i].durations) - kept for i, kept in keep.items())