fix(manifests): rebase restarting timelines across dash periods and hls discontinuities

Shift tfdt of stitched DASH periods and HLS fVTT blocks, and WebVTT cues per period or block, so subtitles and timestamps stay in sync across ad breaks.
This commit is contained in:
imSp4rky
2026-11-23 10:51:40 -07:00
parent 9693cbd39c
commit 138782f38b
8 changed files with 711 additions and 18 deletions
+6
View File
@@ -370,6 +370,12 @@ A typical `get_tracks` therefore looks like fetching the manifest text with
- **DASH** enumerates tracks from only the *first* content period, but downloads segments
from *all* content periods matching the representation. The parser reads `SegmentTemplate`,
`SegmentList`, and `SegmentBase` addressing, and `$Number%0Nd$` padding.
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
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`
from raw text (python-m3u8 drops it) to detect Dolby Vision composite streams, and uses
the media-sequence-number IV for AES-128 keys that have no explicit IV.
+307
View File
@@ -0,0 +1,307 @@
import re
import struct
import threading
from functools import partial
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from io import BytesIO
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Iterator
import pytest
import requests
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.snapshot import fragments, unpack
from unshackle.core.tracks import Tracks
from unshackle.core.tracks.track import DownloadContext, Track
def fragment(*times: int, version: int = 1) -> bytes:
"""A moof with one traf per decode time, then an empty mdat."""
trafs = b"".join(
box(b"traf", full_box(b"tfdt", version, 0, struct.pack(">Q" if version == 1 else ">I", t))) for t in times
)
return box(b"moof", trafs) + box(b"mdat", b"")
def init_segment(timescale: int, version: int = 0) -> bytes:
times = struct.pack(">QQ", 0, 0) if version == 1 else struct.pack(">II", 0, 0)
mdhd = full_box(b"mdhd", version, 0, times + struct.pack(">I", timescale) + b"\0" * 12)
return box(b"ftyp", b"iso6") + box(b"moov", box(b"trak", box(b"mdia", mdhd)))
def tfdts(data: bytes) -> list[int]:
return [value for _, _, value in tfdt_fields(data)]
def merge(
tmp_path: Path, segments: list[bytes], periods: dict[int, tuple[float, float, float]], timescale: int = 1000
) -> bytes:
rebase, dst = PeriodRebase(periods, timescale), BytesIO()
for i, data in enumerate(segments):
path = tmp_path / f"{i:02}.mp4"
path.write_bytes(data)
rebase.append(dst, path)
return dst.getvalue()
def test_restarting_periods_follow_each_other(tmp_path: Path) -> None:
# three periods of 10 s, 20 s and 5 s, each packaged with its own timeline from 0
segments = [fragment(0), fragment(5000), fragment(0), fragment(10000), fragment(0, version=0)]
merged = merge(tmp_path, segments, {0: (0, 10, 0), 2: (10, 20, 0), 4: (30, 5, 0)})
assert tfdts(merged) == [0, 5000, 10000, 20000, 30000]
def test_a_period_the_track_lacks_keeps_its_time(tmp_path: Path) -> None:
# the track has no segments in the 20 s period between the two it holds
merged = merge(tmp_path, [fragment(0), fragment(0)], {0: (0, 10, 0), 1: (30, 5, 0)})
assert tfdts(merged) == [0, 30000]
def test_presentation_time_offset_marks_the_period_start(tmp_path: Path) -> None:
# the second period's first segment starts 500 ms before its presentationTimeOffset
merged = merge(tmp_path, [fragment(0), fragment(1500)], {0: (0, 10, 0), 1: (10, 10, 2)})
assert tfdts(merged) == [0, 9500]
def test_restart_below_the_previous_end_is_caught(tmp_path: Path) -> None:
merged = merge(tmp_path, [fragment(100000), fragment(100500)], {0: (0, 10, 0), 1: (10, 10, 0)})
assert tfdts(merged) == [100000, 110000]
def test_continuous_timeline_is_unchanged(tmp_path: Path) -> None:
# absolute timestamps with a filtered ad between the periods keep their gap
segments = [fragment(0), fragment(5000), fragment(40000), fragment(45000)]
assert merge(tmp_path, segments, {0: (0, 10, 0), 2: (10, 10, 0)}) == b"".join(segments)
def test_every_traf_is_shifted(tmp_path: Path) -> None:
merged = merge(tmp_path, [fragment(0), fragment(0, 2000)], {0: (0, 4, 0), 1: (4, 4, 0)})
assert tfdts(merged) == [0, 4000, 6000]
def test_32_bit_overflow_raises(tmp_path: Path) -> None:
segments = [fragment(0), fragment(0, version=0)]
with pytest.raises(ValueError, match="32-bit"):
merge(tmp_path, segments, {0: (0, 2.0**32 / 1000, 0), 1: (2.0**32 / 1000, 1, 0)})
def test_short_tfdt_is_skipped() -> None:
truncated = box(b"moof", box(b"traf", box(b"tfdt", b"")))
assert tfdt_fields(truncated) == []
assert tfdt_fields(truncated + b"tfdt") == []
@pytest.mark.parametrize("version", [0, 1])
def test_mdhd_timescale(version: int) -> None:
assert mdhd_timescale(init_segment(15360, version)) == 15360
assert mdhd_timescale(box(b"ftyp", b"iso6")) is None
@pytest.mark.parametrize(
("periods", "expected"),
[
('<Period duration="PT4S"/><Period start="PT4S"/><Period start="PT10S"/>', [4.0, 6.0, 20.0]),
('<Period/><Period start="PT10S"/>', [10.0, 20.0]),
('<Period duration="PT10S"/><Period/>', [10.0, 20.0]),
('<Period start="PT5S"/><Period start="PT2S"/>', [None, 28.0]),
("<Period/><Period/>", [None, None]),
],
)
def test_period_durations(periods: str, expected: list) -> None:
mpd = etree.fromstring(f'<MPD mediaPresentationDuration="PT30S">{periods}</MPD>')
assert DASH.period_durations(mpd) == expected
def test_presentation_time_offset_reads_the_merged_template() -> None:
aset = etree.fromstring(
'<AdaptationSet><SegmentTemplate timescale="1000" presentationTimeOffset="2500"/></AdaptationSet>'
)
assert DASH.presentation_time_offset(aset, etree.SubElement(aset, "Representation")) == 2.5
assert DASH.presentation_time_offset(etree.Element("AdaptationSet"), etree.Element("Representation")) == 0.0
def test_hls_discontinuity_starts() -> None:
segments = [SimpleNamespace(discontinuity=d, duration=t) for d, t in ((True, 4), (False, 4), (True, 3), (False, 1))]
assert HLS.discontinuity_starts(segments) == [0.0, 8.0, 12.0]
def test_remote_fragment_writes_each_period_duration() -> None:
mpd = DASH.from_text(
"""<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT30S">
<Period id="a" start="PT0S"><AdaptationSet contentType="video" mimeType="video/mp4" lang="en">
<Representation id="v" codecs="avc1.640028" bandwidth="1" width="1" height="1"><BaseURL>a.mp4</BaseURL></Representation>
</AdaptationSet></Period>
<Period id="ad" start="PT10S"><AdaptationSet contentType="video" mimeType="video/mp4" lang="en">
<Representation id="v" codecs="avc1.640028" bandwidth="1" width="1" height="1"><BaseURL>ad.mp4</BaseURL></Representation>
</AdaptationSet></Period>
<Period id="b" start="PT20S"><AdaptationSet contentType="video" mimeType="video/mp4" lang="en">
<Representation id="v" codecs="avc1.640028" bandwidth="1" width="1" height="1"><BaseURL>b.mp4</BaseURL></Representation>
</AdaptationSet></Period>
</MPD>""",
"https://example.test/manifest.mpd",
)
tracks = mpd.to_tracks(language="en", period_filter=lambda period: period.get("id") == "ad")
own = Tracks()
own.add(tracks.videos[0])
# a fragment is built for a track whose AdaptationSet is not in its manifest tree
own.videos[0].data["dash"]["adaptation_set"] = etree.fromstring(
etree.tostring(own.videos[0].data["dash"]["adaptation_set"])
)
[entry] = fragments(own, 1, {})
periods = unpack(entry["data"], [1 << 20]).findall("Period")
assert [p.get("duration") for p in periods] == ["PT10S", "PT10S"]
class Handler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
body = self.server.routes.get(self.path.split("?")[0]) # type: ignore[attr-defined]
self.send_response(200 if body is not None else 404)
self.send_header("Content-Length", str(len(body or b"")))
self.end_headers()
self.wfile.write(body or b"")
def log_message(self, *args: Any) -> None:
pass
@pytest.fixture
def server() -> Iterator[ThreadingHTTPServer]:
srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
srv.routes = {} # type: ignore[attr-defined]
for p in (0, 1):
srv.routes[f"/p{p}/init.mp4"] = init_segment(1000) # type: ignore[attr-defined]
for n, t in ((1, 0), (2, 1000)):
srv.routes[f"/p{p}/{n}.m4s"] = fragment(t) # type: ignore[attr-defined]
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
yield srv
srv.shutdown()
thread.join(timeout=5)
def restarting_mpd(port: int) -> str:
periods = "".join(
f"""<Period id="{p}" duration="PT2S"><AdaptationSet contentType="video" mimeType="video/mp4" lang="en">
<Representation id="v0" codecs="avc1.640028" bandwidth="1000000" width="1920" height="1080">
<SegmentTemplate timescale="1000" startNumber="1" initialization="p{p}/init.mp4" media="p{p}/$Number$.m4s">
<SegmentTimeline><S t="0" d="1000" r="1"/></SegmentTimeline>
</SegmentTemplate>
</Representation></AdaptationSet></Period>"""
for p in (0, 1)
)
return f"""<?xml version="1.0"?>
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT4S">
<BaseURL>http://127.0.0.1:{port}/</BaseURL>{periods}</MPD>"""
@pytest.mark.parametrize("rolling", [True, False], ids=["rolling-merge", "post-merge"])
def test_download_track_rebases_restarting_periods(
server: ThreadingHTTPServer, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, rolling: bool
) -> None:
monkeypatch.setattr(Track, "get_key_id", lambda self, *args, **kwargs: None)
monkeypatch.setattr(config, "merge_segments", rolling)
track = DASH.from_text(restarting_mpd(server.server_address[1]), "http://127.0.0.1/manifest.mpd").to_tracks(
language="en"
)
video = track.videos[0]
ctx = DownloadContext(
save_path=tmp_path / "out.mp4", save_dir=tmp_path / "v0_segments", progress=partial(lambda **kw: None)
)
DASH.download_track(video, ctx)
assert tfdts((tmp_path / "out.mp4").read_bytes()) == [0, 1000, 2000, 3000]
def test_a_track_missing_the_first_period_is_placed_at_its_start(tmp_path: Path) -> None:
merged = merge(tmp_path, [fragment(0), fragment(5000), fragment(0)], {0: (10, 10, 0), 2: (20, 5, 0)})
assert tfdts(merged) == [10000, 15000, 20000]
def test_a_restart_after_a_continuous_gap_follows_the_previous_period(tmp_path: Path) -> None:
segments = [fragment(0), fragment(5000), fragment(40000), fragment(45000), fragment(0)]
merged = merge(tmp_path, segments, {0: (0, 10, 0), 2: (10, 10, 0), 4: (20, 5, 0)})
assert tfdts(merged) == [0, 5000, 40000, 45000, 50000]
def test_a_period_back_on_the_first_timeline_leaves_the_restart_shift(tmp_path: Path) -> None:
# an unfiltered 30 s ad restarts at 0 between two parts of one continuous timeline
merged = merge(
tmp_path, [fragment(0), fragment(0), fragment(600000)], {0: (0, 600, 0), 1: (600, 30, 0), 2: (630, 600, 600)}
)
assert tfdts(merged) == [0, 600000, 630000]
def test_mdhd_too_short_has_no_timescale() -> None:
assert mdhd_timescale(box(b"moov", box(b"mdhd", b""))) is None
assert mdhd_timescale(box(b"moov", box(b"mdhd", b"\0" * 4)) + box(b"free", b"\0" * 16)) is None
def test_number_template_counts_segments_to_the_next_period_start() -> None:
mpd = DASH.from_text(
"""<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT16S">
<Period id="a" start="PT0S"/>
<Period id="b" start="PT10S"><AdaptationSet contentType="video" mimeType="video/mp4" lang="en">
<Representation id="v" codecs="avc1.640028" bandwidth="1" width="1" height="1">
<SegmentTemplate timescale="1000" duration="2000" startNumber="1" media="$Number$.m4s"/>
</Representation></AdaptationSet></Period>
</MPD>""",
"https://example.test/manifest.mpd",
)
period = mpd.manifest.findall("Period")[1]
aset = period.find("AdaptationSet")
_, segments, *_ = DASH.get_period_segments(
period,
aset,
aset.find("Representation"),
mpd.manifest,
Track(url="https://example.test/", language="en"),
"https://example.test/manifest.mpd",
requests.Session(),
probe_kid=False,
)
assert len(segments) == 3
def webvtt_mpd(port: int) -> str:
periods = "".join(
f"""<Period id="{p}" duration="PT2S"><AdaptationSet contentType="text" mimeType="text/vtt" lang="en">
<Representation id="s0" bandwidth="1">
<SegmentTemplate timescale="1000" startNumber="1" media="p{p}/$Number$.vtt">
<SegmentTimeline><S t="0" d="1000" r="1"/></SegmentTimeline>
</SegmentTemplate>
</Representation></AdaptationSet></Period>"""
for p in (0, 1)
)
return f"""<?xml version="1.0"?>
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT4S">
<BaseURL>http://127.0.0.1:{port}/</BaseURL>{periods}</MPD>"""
def test_download_track_rebases_webvtt_periods(server: ThreadingHTTPServer, tmp_path: Path) -> None:
for p in (0, 1):
for n, cue in ((1, "00:00:00.100"), (2, "00:00:01.100")):
server.routes[f"/p{p}/{n}.vtt"] = f"WEBVTT\n\n{cue} --> {cue[:-3]}900\nline\n\n".encode() # type: ignore[attr-defined]
track = (
DASH.from_text(webvtt_mpd(server.server_address[1]), "http://127.0.0.1/manifest.mpd")
.to_tracks(language="en")
.subtitles[0]
)
ctx = DownloadContext(
save_path=tmp_path / "out.vtt", save_dir=tmp_path / "s0_segments", progress=partial(lambda **kw: None)
)
DASH.download_track(track, ctx)
assert re.findall(r"(\S+) -->", (tmp_path / "out.vtt").read_text()) == [
"00:00:00.100",
"00:00:01.100",
"00:00:02.100",
"00:00:03.100",
]
+111
View File
@@ -0,0 +1,111 @@
from functools import partial
from http.server import ThreadingHTTPServer
from pathlib import Path
from types import SimpleNamespace
from typing import Optional
from tests.core.test_dash_period_rebase import fragment, init_segment, server, tfdts
from unshackle.core.manifests import HLS
from unshackle.core.tracks import Subtitle
from unshackle.core.tracks.track import DownloadContext
from unshackle.core.utils.webvtt import CUE_TIMES, shift_webvtt, webvtt_block_offsets
__all__ = ["server"]
def block(*cues: str, local: str = "00:00:00.000") -> str:
head = f"WEBVTT\nX-TIMESTAMP-MAP=MPEGTS:90000,LOCAL:{local}\n\n"
return head + "".join(f"{cue} --> {cue[:-3]}999\ntext\n\n" for cue in cues)
def starts(text: str) -> list[str]:
return [m[2] for m in CUE_TIMES.finditer(text)]
def rebase(texts: list[str], bounds_ms: list[int]) -> list[str]:
return [shift_webvtt(t, o) for t, o in zip(texts, webvtt_block_offsets(texts, bounds_ms))]
def test_restarting_blocks_move_to_their_playlist_start() -> None:
texts = [block("00:00:01.000", "00:06:10.000"), block("00:00:00.023"), block("00:00:30.000")]
out = rebase(texts, [0, 372933, 717166, 1419000])
assert [starts(t) for t in out] == [["00:00:01.000", "00:06:10.000"], ["00:06:12.956"], ["00:12:27.166"]]
def test_absolute_cue_times_are_not_changed() -> None:
# a cue carried over the block boundary starts just before the block, not before its middle
texts = [block("00:00:01.000"), block("00:09:58.000", "00:10:05.000")]
assert rebase(texts, [0, 600000, 1200000]) == texts
def test_a_late_first_cue_still_restarts() -> None:
texts = [block("00:00:01.000"), block("00:00:40.000")]
assert starts(rebase(texts, [0, 60000, 120000])[1]) == ["00:01:40.000"]
def test_a_cue_carried_over_a_short_block_is_not_a_restart() -> None:
carried = "WEBVTT\n\n00:00:01.000 --> 00:00:08.000\nt\n\n00:00:20.000 --> 00:00:21.000\nt\n"
texts = [block("00:00:01.000"), carried]
assert rebase(texts, [0, 6000, 60000]) == texts
def test_local_time_marks_the_block_start() -> None:
texts = [block("00:00:01.000"), block("00:00:12.000", local="00:00:10.000")]
assert starts(rebase(texts, [0, 60000, 120000])[1]) == ["00:01:02.000"]
def test_shift_clamps_at_zero() -> None:
assert starts(shift_webvtt(block("00:00:01.000"), -5000)) == ["00:00:00.000"]
def test_discontinuity_files_are_rewritten(tmp_path: Path) -> None:
segments = [SimpleNamespace(discontinuity=d, duration=t) for d, t in ((True, 5), (False, 5), (True, 5))]
files = [tmp_path / "0.vtt", tmp_path / "1.vtt"]
files[0].write_bytes(block("00:00:01.000").encode())
files[1].write_bytes(block("00:00:02.000").replace("\n", "\r\n").encode())
HLS.discontinuity_append(Subtitle(url="", language="en", codec=Subtitle.Codec.WebVTT), segments, files)
assert starts(files[0].read_text()) == ["00:00:01.000"]
assert b"00:00:12.000 --> " in files[1].read_bytes()
assert b"\r\n" in files[1].read_bytes()
MASTER = """#EXTM3U
#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="English",LANGUAGE="en",DEFAULT=YES,URI="subs.m3u8"
#EXT-X-STREAM-INF:BANDWIDTH=1000000,RESOLUTION=1920x1080,CODECS="avc1.640028",SUBTITLES="subs"
media.m3u8
"""
def playlist(names: list[str], init: str = "") -> bytes:
head = f'#EXT-X-MAP:URI="{init}"\n' if init else ""
blocks = "#EXT-X-DISCONTINUITY\n".join(f"{head}#EXTINF:4.0,\n{name}\n" for name in names)
return f"#EXTM3U\n#EXT-X-VERSION:6\n#EXT-X-TARGETDURATION:4\n{blocks}#EXT-X-ENDLIST\n".encode()
def download(server: ThreadingHTTPServer, tmp_path: Path, codec: Optional[Subtitle.Codec] = None) -> Path:
url = f"http://127.0.0.1:{server.server_address[1]}/master.m3u8"
track = HLS.from_text(MASTER, url=url).to_tracks(language="en").subtitles[0]
if codec:
track.codec = codec
ctx = DownloadContext(
save_path=tmp_path / "out", save_dir=tmp_path / "s0_segments", progress=partial(lambda **kw: None)
)
HLS.download_track(track, ctx)
return tmp_path / "out"
def test_download_track_rebases_webvtt_blocks(server: ThreadingHTTPServer, tmp_path: Path) -> None:
server.routes["/subs.m3u8"] = playlist(["a.vtt", "b.vtt"]) # type: ignore[attr-defined]
server.routes["/a.vtt"] = block("00:00:01.000").encode() # type: ignore[attr-defined]
server.routes["/b.vtt"] = block("00:00:01.000").encode() # type: ignore[attr-defined]
assert starts(download(server, tmp_path).read_text()) == ["00:00:01.000", "00:00:05.000"]
def test_download_track_rebases_fvtt_blocks(server: ThreadingHTTPServer, tmp_path: Path) -> None:
server.routes["/subs.m3u8"] = playlist(["a.m4s", "b.m4s"], init="init.mp4") # type: ignore[attr-defined]
server.routes["/init.mp4"] = init_segment(1000) # type: ignore[attr-defined]
server.routes["/a.m4s"] = fragment(0) # type: ignore[attr-defined]
server.routes["/b.m4s"] = fragment(0) # type: ignore[attr-defined]
assert tfdts(download(server, tmp_path, Subtitle.Codec.fVTT).read_bytes()) == [0, 4000]
+198 -6
View File
@@ -4,8 +4,11 @@ import base64
import html
import logging
import math
import mmap
import os
import re
import shutil
from bisect import bisect_right
from concurrent.futures import Future
from contextlib import ExitStack, closing
from copy import deepcopy
@@ -30,7 +33,7 @@ from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNL
from unshackle.core.downloaders.requests import parse_content_range
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
from unshackle.core.drm.verify import decrypt_track, walk
from unshackle.core.events import events
from unshackle.core.session import RnetSession
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
@@ -44,6 +47,7 @@ from unshackle.core.utilities import is_close_match, log_event, try_ensure_utf8
from unshackle.core.utils import run_proxy
from unshackle.core.utils.bitrate import ranged_get
from unshackle.core.utils.redact import safe_display_url
from unshackle.core.utils.webvtt import shift_webvtt, webvtt_block_offsets
from unshackle.core.utils.xml import load_xml
DOLBY_CHANNEL_SCHEMES = (
@@ -90,6 +94,16 @@ def missing_language(where: str, fallback: Any) -> MissingLanguageError:
return MissingLanguageError(f"No language for {where}")
def rebase_webvtt_files(groups: list[list[Path]], bounds_ms: list[int]) -> None:
"""Rewrite the WebVTT segment files of each period or discontinuity block, shifted by webvtt_block_offsets."""
texts = [[try_ensure_utf8(path.read_bytes()).decode("utf8") for path in group] for group in groups]
for group, parts, offset in zip(groups, texts, webvtt_block_offsets(["\n\n".join(t) for t in texts], bounds_ms)):
if not offset:
continue
for path, text in zip(group, parts):
path.write_bytes(shift_webvtt(text, offset).encode("utf8"))
def append_segment(dst: BinaryIO, segment_file: Path, is_text_subtitle: bool) -> None:
"""Append one segment file to the output, with the text subtitle fixups when they apply."""
if is_text_subtitle:
@@ -147,6 +161,93 @@ class RollingMerge:
return self.cursor
def mdhd_timescale(init_data: bytes) -> Optional[int]:
"""The media timescale of the first track in an init segment, or None when it has no mdhd."""
for kind, body, box_end in walk(init_data):
if kind == b"mdhd":
at = body + (20 if body < box_end and init_data[body] == 1 else 12)
return int.from_bytes(init_data[at : at + 4], "big") if at + 4 <= box_end else None
return None
def tfdt_fields(data: bytes) -> list[tuple[int, int, int]]:
"""(offset, width, value) of each tfdt baseMediaDecodeTime in a fragment; a tfdt too short for its field is skipped."""
fields = []
for kind, body, box_end in walk(data):
if kind != b"tfdt" or box_end - body < 8:
continue
width = 8 if data[body] == 1 else 4
if body + 4 + width <= box_end:
fields.append((body + 4, width, int.from_bytes(data[body + 4 : body + 4 + width], "big")))
return fields
class PeriodRebase:
"""Appends segments and moves the tfdt of each period whose timeline restarts to its place in the output.
A stitched manifest can package each content period on its own, so every period starts at tfdt 0
again. A period whose first tfdt falls before the middle of the previous period restarted: its
presentationTimeOffset moves to the period's output start, or to the previous period's end when
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.
"""
def __init__(self, periods: dict[int, tuple[float, float, float]], timescale: int) -> None:
self.periods = periods
self.timescale = timescale
self.offset = 0
self.base: Optional[int] = None
self.previous: Optional[tuple[int, int, int]] = None
def append(self, dst: BinaryIO, segment_file: Path) -> None:
period = self.periods.get(int(segment_file.stem))
if period is None and not self.offset:
append_segment(dst, segment_file, is_text_subtitle=False)
return
with open(segment_file, "rb") as src:
fields: list[tuple[int, int, int]] = []
if os.fstat(src.fileno()).st_size:
with mmap.mmap(src.fileno(), 0, access=mmap.ACCESS_READ) as data:
fields = tfdt_fields(cast(bytes, data))
if period and fields:
self.start_period(fields[0][2], *period)
start = dst.tell()
shutil.copyfileobj(src, dst, 1024 * 1024)
if self.offset and fields:
end = dst.tell()
for at, width, value in fields:
shifted = value + self.offset
if not 0 <= shifted < 1 << (width * 8):
raise ValueError(f"Shifted tfdt {shifted} does not fit its {width * 8}-bit field: {segment_file}")
dst.seek(start + at)
dst.write(shifted.to_bytes(width, "big"))
dst.seek(end)
def start_period(self, first: int, out_start: float, duration: float, pto: float) -> None:
"""Set the shift for a period from its first tfdt and its manifest timing.
A period's media start is its presentationTimeOffset, or its first tfdt when it declares none.
"""
media_start = round(pto * self.timescale) if pto else first
placed = round(out_start * self.timescale)
length = round(duration * self.timescale)
if self.base is None:
if placed and media_start < placed // 2:
self.base, self.offset = 0, placed - media_start
else:
self.base = media_start - placed
elif self.previous:
previous_first, previous_length, previous_end = self.previous
target = self.base + placed
if first + self.offset < previous_first + previous_length // 2:
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)
self.previous = (first + self.offset, length, media_start + self.offset + length)
def rep_shape(adaptation_set: Element, rep: Element) -> tuple[Optional[str], ...]:
"""The attributes a Representation must keep to continue a track into another Period."""
return tuple(DASH.get_attr(a, adaptation_set, rep) for a in ("codecs", "width", "height", "audioSamplingRate"))
@@ -510,9 +611,18 @@ class DASH:
segment_timescale: float = 0
init_data: Optional[bytes] = None
track_kid: Optional[UUID] = None
period_starts: dict[int, tuple[float, float, float]] = {}
timed = True
content_periods = [p for p in all_periods if DASH.is_content_period(p, filtered_period_ids)]
period_count = len(content_periods)
durations = dict(zip(map(id, all_periods), DASH.period_durations(manifest)))
content_timing: list[tuple[Optional[float], Optional[float]]] = []
elapsed: Optional[float] = 0.0
for content_period in content_periods:
duration = durations[id(content_period)]
content_timing.append((elapsed, duration))
elapsed = elapsed + duration if elapsed is not None and duration is not None else None
if period_count > 1:
log.debug(f"Multi-period manifest detected with {period_count} content periods")
@@ -543,6 +653,7 @@ class DASH:
session=session,
probe_kid=period_idx == 0,
window=config.sample,
duration=content_timing[period_idx][1],
)
if period_idx == 0:
@@ -551,10 +662,18 @@ class DASH:
track_kid = p_kid
segment_timescale = p_timescale
first_segment = len(segments)
for seg in p_segments:
if seg not in seen_segments:
seen_segments.add(seg)
segments.append(seg)
if len(segments) > first_segment:
out_start, duration = content_timing[period_idx]
if out_start is None or duration is None:
timed = False
else:
pto = DASH.presentation_time_offset(matched_as, matched_rep)
period_starts[first_segment] = (out_start, duration, pto)
segment_durations.extend(p_durations)
if config.sample and segments:
break
@@ -704,6 +823,13 @@ class DASH:
if use_segment_decrypt and init_data:
decrypter = SegmentDecrypter(cast(SEGMENT_DRM_T, drm), init_data, save_dir.parent, max_workers)
rebase: Optional[PeriodRebase] = None
known = timed and len(period_starts) > 1
timescale = mdhd_timescale(init_data) if known and init_data and not is_text_subtitle else None
if timescale:
rebase = PeriodRebase(period_starts, timescale)
append = rebase.append if rebase else partial(append_segment, is_text_subtitle=is_text_subtitle)
merger: Optional[RollingMerge] = None
try:
with ExitStack() as stack:
@@ -712,7 +838,7 @@ class DASH:
head = decrypter.init_bytes() if decrypter else init_data
if head:
output.write(head)
merger = RollingMerge(output)
merger = RollingMerge(output, append)
# an exception raised in this body (a decrypt failure re-raised by the merge)
# must close the generator now, so its finally aborts the workers
@@ -816,13 +942,22 @@ class DASH:
)
raise FileNotFoundError(error_msg)
if known and is_text_subtitle and track.codec == Subtitle.Codec.WebVTT:
firsts = sorted(period_starts)
groups: list[list[Path]] = [[] for _ in firsts]
for segment_file in segments_to_merge:
groups[bisect_right(firsts, int(segment_file.stem)) - 1].append(segment_file)
last_start, last_duration, _ = period_starts[firsts[-1]]
bounds = [*(period_starts[i][0] for i in firsts), last_start + last_duration]
rebase_webvtt_files(groups, [round(t * 1000) for t in bounds])
with open(save_path, "wb") as f:
if init_data:
f.write(init_data)
if len(segments_to_merge) > 1:
progress(downloaded="Merging", completed=0, total=len(segments_to_merge))
for segment_file in segments_to_merge:
append_segment(f, segment_file, is_text_subtitle)
append(f, segment_file)
segment_file.unlink()
progress(advance=1)
@@ -947,6 +1082,59 @@ class DASH:
return False
return True
@staticmethod
def period_durations(manifest: ElementTree) -> list[Optional[float]]:
"""The duration in seconds of every Period, None where the manifest does not give it.
A Period without @start starts at 0 when it is the first, else where the previous Period
ends (ISO/IEC 23009-1 5.3.2.1). A Period without @duration lasts to the next Period's start,
or to the end of the presentation. A duration that is not positive counts as unknown.
"""
periods = manifest.findall("Period")
starts: list[Optional[float]] = []
for i, period in enumerate(periods):
previous = periods[i - 1] if i else None
if period.get("start"):
starts.append(DASH.pt_to_sec(period.get("start")))
elif previous is None:
starts.append(0.0)
elif starts[-1] is not None and previous.get("duration"):
starts.append(cast(float, starts[-1]) + DASH.pt_to_sec(previous.get("duration")))
else:
starts.append(None)
total = manifest.get("mediaPresentationDuration")
durations: list[Optional[float]] = []
for i, (period, start) in enumerate(zip(periods, starts)):
duration: Optional[float] = None
if period.get("duration"):
duration = DASH.pt_to_sec(period.get("duration"))
elif start is not None and i + 1 < len(periods):
following = starts[i + 1]
duration = following - start if following is not None else None
elif start is not None and total:
duration = DASH.pt_to_sec(total) - start
durations.append(duration if duration is not None and duration > 0 else None)
return durations
@staticmethod
def period_duration(manifest: ElementTree, period: Element) -> Optional[float]:
"""The duration in seconds of one Period, by DASH.period_durations."""
index = next((i for i, p in enumerate(manifest.findall("Period")) if p is period), None)
if index is None:
return DASH.pt_to_sec(period.get("duration")) if period.get("duration") else None
return DASH.period_durations(manifest)[index]
@staticmethod
def presentation_time_offset(adaptation_set: Element, representation: Element) -> float:
"""The presentationTimeOffset of a Representation's segment element in seconds, 0 when it has none."""
element = DASH.merge_segment_templates(adaptation_set, representation)
for name in ("SegmentList", "SegmentBase"):
if element is None:
element = DASH.find_segment_element(name, adaptation_set, representation)
if element is None:
return 0.0
return int(element.get("presentationTimeOffset") or 0) / (float(element.get("timescale") or 1) or 1.0)
@staticmethod
def merge_segment_templates(adaptation_set: Element, representation: Element) -> Optional[Element]:
"""
@@ -984,6 +1172,7 @@ class DASH:
session: Union[Session, RnetSession],
probe_kid: bool = True,
window: Optional[tuple[int, int]] = None,
duration: Optional[float] = None,
) -> tuple[
Optional[bytes],
list[tuple[str, Optional[str]]],
@@ -999,6 +1188,7 @@ class DASH:
the caller needs neither the init data nor the Key ID of this period. False
drops the FFprobe call, and also the init request where the rest of the parse
does not need those bytes.
duration: The Period's duration in seconds, when the caller already has it.
Returns:
A tuple of (init_data, segments, segment_timescale, segment_durations, track_kid).
@@ -1012,7 +1202,10 @@ class DASH:
adaptation_set_base_url = urljoin(period_base_url, adaptation_set.findtext("BaseURL") or "")
rep_base_url = urljoin(adaptation_set_base_url, representation.findtext("BaseURL") or "")
period_duration = period.get("duration") or manifest.get("mediaPresentationDuration")
total = manifest.get("mediaPresentationDuration")
period_duration = (
duration or DASH.period_duration(manifest, period) or (DASH.pt_to_sec(total) if total else None)
)
init_data: Optional[bytes] = None
segment_template = DASH.merge_segment_templates(adaptation_set, representation)
@@ -1081,7 +1274,7 @@ class DASH:
if next_time:
end_time = int(next_time)
elif period_duration:
end_time = timeline_start + DASH.pt_to_sec(period_duration) * segment_timescale
end_time = timeline_start + period_duration * segment_timescale
else:
raise ValueError("Duration of the Period was unable to be determined.")
# round off float noise from the duration so it cannot add a segment
@@ -1113,7 +1306,6 @@ class DASH:
else:
if not period_duration:
raise ValueError("Duration of the Period was unable to be determined.")
period_duration = DASH.pt_to_sec(period_duration)
segment_duration = float(segment_template.get("duration")) or 1
if not end_number:
+37 -4
View File
@@ -10,9 +10,10 @@ import shutil
import subprocess
import time
from contextlib import ExitStack, closing
from functools import partial
from itertools import accumulate
from pathlib import Path
from typing import Any, Optional, Union, cast
from typing import Any, BinaryIO, Callable, Optional, Union, cast
from urllib.parse import urljoin, urlparse
from uuid import UUID
from zlib import crc32
@@ -35,7 +36,14 @@ from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, MonaLisa, PlayRead
from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use
from unshackle.core.drm.verify import decrypt_track
from unshackle.core.events import events
from unshackle.core.manifests.dash import RollingMerge, missing_language
from unshackle.core.manifests.dash import (
PeriodRebase,
RollingMerge,
append_segment,
mdhd_timescale,
missing_language,
rebase_webvtt_files,
)
from unshackle.core.session import RnetResponse, RnetSession, utf8_text
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, assert_fragments_decrypted
@@ -1241,10 +1249,10 @@ class HLS:
if isinstance(track, (Video, Audio)):
HLS.merge_segments(segments=segments_to_merge, save_path=save_path, progress=progress)
else:
append = HLS.discontinuity_append(track, wanted_segments, segments_to_merge)
with open(save_path, "wb") as f:
for discontinuity_file in segments_to_merge:
with open(discontinuity_file, "rb") as src:
shutil.copyfileobj(src, f, 1024 * 1024)
append(f, discontinuity_file)
f.flush()
os.fsync(f.fileno())
discontinuity_file.unlink()
@@ -1264,6 +1272,31 @@ class HLS:
events.emit(events.Types.TRACK_DOWNLOADED, track=track)
@staticmethod
def discontinuity_starts(wanted_segments: list[Any]) -> list[float]:
"""Start in seconds of each discontinuity block, counted as download_track numbers the blocks, then the end."""
ends = list(accumulate((segment.duration or 0 for segment in wanted_segments), initial=0.0))
return [0.0, *(ends[i] for i, segment in enumerate(wanted_segments) if i and segment.discontinuity), ends[-1]]
@staticmethod
def discontinuity_append(
track: AnyTrack, wanted_segments: list[Any], blocks: list[Path]
) -> Callable[[BinaryIO, Path], None]:
"""The append for merging subtitle discontinuity blocks, each placed at its playlist start when it restarts.
WebVTT blocks are rewritten by rebase_webvtt_files before the merge; fVTT blocks merge through a PeriodRebase.
"""
plain = partial(append_segment, is_text_subtitle=False)
bounds = HLS.discontinuity_starts(wanted_segments)
if not isinstance(track, Subtitle) or len(blocks) < 2 or len(bounds) != len(blocks) + 1:
return plain
if track.codec == Subtitle.Codec.WebVTT:
rebase_webvtt_files([[block] for block in blocks], [round(t * 1000) for t in bounds])
elif track.codec == Subtitle.Codec.fVTT and (timescale := mdhd_timescale(blocks[0].read_bytes())):
periods = {i: (bounds[i], bounds[i + 1] - bounds[i], 0.0) for i in range(len(blocks))}
return PeriodRebase(periods, timescale).append
return plain
@staticmethod
def merge_segments(segments: list[Path], save_path: Path, progress: Optional[Any] = None) -> int:
"""
+12 -3
View File
@@ -168,9 +168,18 @@ def fragments(tracks: Tracks, level: int, counts: dict[int, int]) -> list[dict[s
root.append(deepcopy(child))
period = dash.get("period")
representation = dash.get("representation")
root.append(one_track_period(period, adaptation_set, representation))
periods = manifest.findall("Period")
durations = dict(zip(map(id, periods), DASH.period_durations(manifest)))
def kept(source: Any, new_period: Any) -> None:
"""Append a fragment period with its duration written out, as the periods dropped beside it are gone."""
duration = durations.get(id(source))
if duration is not None and not new_period.get("duration"):
new_period.set("duration", f"PT{duration:.6f}".rstrip("0").rstrip(".") + "S")
root.append(new_period)
kept(period, one_track_period(period, adaptation_set, representation))
if period is not None and period in periods:
filtered = set(dash.get("filtered_period_ids") or [])
rep_id = dash.get("representation_id") or (representation.get("id") if representation is not None else None)
@@ -179,7 +188,7 @@ def fragments(tracks: Tracks, level: int, counts: dict[int, int]) -> list[dict[s
continue
found = DASH.resolve_representation(later, rep_id, adaptation_set)
if found is not None:
root.append(one_track_period(later, *found))
kept(later, one_track_period(later, *found))
out.append(
{
+10 -4
View File
@@ -7,7 +7,7 @@ import time
from collections import OrderedDict, defaultdict
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable, Hashable, Optional, Sequence, Union
from typing import TYPE_CHECKING, Callable, Hashable, Optional, Sequence, Union, cast
from urllib.parse import urljoin
from requests import Session
@@ -285,9 +285,12 @@ def extract_dash(track: "Track", session: Union[Session, RnetSession]) -> list[S
stored_period = data.get("period")
track_url = track.url if isinstance(track.url, str) else track.url[0]
content_periods = [p for p in manifest.findall("Period") if DASH.is_content_period(p, filtered_period_ids)]
periods = manifest.findall("Period")
durations = dict(zip(map(id, periods), DASH.period_durations(manifest)))
content_periods = [p for p in periods if DASH.is_content_period(p, filtered_period_ids)]
raw_segments: list[tuple[str, Optional[str]]] = []
kept: list[Optional[float]] = []
for period in content_periods:
# rep ids are only unique within an AdaptationSet, so resolve like DASH.download_track
if period is stored_period:
@@ -305,12 +308,15 @@ def extract_dash(track: "Track", session: Union[Session, RnetSession]) -> list[S
track=track,
track_url=track_url,
session=session,
duration=durations[id(period)],
)
raw_segments.extend(period_segments)
kept.append(durations[id(period)])
total_duration: Optional[float] = None
# the kept periods only, so filtered ad time does not lower the estimate
total_duration: Optional[float] = sum(cast(list[float], kept)) if kept and None not in kept else None
mpd_duration = manifest.get("mediaPresentationDuration")
if mpd_duration:
if total_duration is None and mpd_duration:
total_duration = DASH.pt_to_sec(mpd_duration)
return uniform_segments(raw_segments, total_duration)
+30 -1
View File
@@ -5,6 +5,7 @@ TIMESTAMP = r"(?:\d+:)?\d{2}:\d{2}\.\d{3}"
# Timing line: optional hours, verbatim settings tail.
TIMING = re.compile(rf"^({TIMESTAMP})[ \t]+-->[ \t]+({TIMESTAMP})(.*)$")
CUE_TIMES = re.compile(rf"(?m)^([ \t]*)({TIMESTAMP})([ \t]+-->[ \t]+)({TIMESTAMP})")
TIMESTAMP_MAP_LOCAL = re.compile(rf"X-TIMESTAMP-MAP=[^\n]*LOCAL:({TIMESTAMP})", re.IGNORECASE)
def timestamp_ms(ts: str) -> int:
@@ -91,9 +92,37 @@ def rebase_webvtt(text: str, offset_ms: int, segment_ms: int = 0) -> str:
first = CUE_TIMES.search(text)
if offset_ms <= 0 or not first or timestamp_ms(first[2]) < offset_ms - segment_ms:
return text
return shift_webvtt(text, -offset_ms)
def shift_webvtt(text: str, delta_ms: int) -> str:
"""Add delta_ms to every cue time, clamped at 0."""
def shift(ts: str) -> str:
ms = max(timestamp_ms(ts) - offset_ms, 0)
ms = max(timestamp_ms(ts) + delta_ms, 0)
return f"{ms // 3_600_000:02}:{ms // 60_000 % 60:02}:{ms // 1000 % 60:02}.{ms % 1000:03}"
return CUE_TIMES.sub(lambda m: f"{m[1]}{shift(m[2])}{m[3]}{shift(m[4])}", text)
def webvtt_block_offsets(texts: list[str], bounds_ms: list[int]) -> list[int]:
"""The cue shift in ms of each WebVTT discontinuity block or period, so cues that restart land in its window.
bounds_ms holds each block's playlist start and, last, the end of the final block. A block takes
whichever shift puts more of its cues inside its window: the shift of the block before it, or the
one that puts its X-TIMESTAMP-MAP LOCAL time on the block start; a tie keeps the shift before it.
This assumes each block's MPEGTS is the first video PTS of the same block.
"""
offsets, offset = [], 0
for text, start, end in zip(texts, bounds_ms, bounds_ms[1:]):
cues = [(timestamp_ms(m[2]), timestamp_ms(m[4])) for m in CUE_TIMES.finditer(text)]
local = TIMESTAMP_MAP_LOCAL.search(text)
restart = start - (timestamp_ms(local[1]) if local else 0)
def inside(shift: int) -> int:
return sum(cue_start + shift < end and cue_end + shift > start for cue_start, cue_end in cues)
if inside(restart) > inside(offset):
offset = restart
offsets.append(offset)
return offsets