refactor(manifests): merge downloaded DASH and ISM segments through segment_pipeline.merge_downloaded

This commit is contained in:
imSp4rky
2026-12-02 20:08:08 -07:00
parent 46a3bc0ad2
commit d2418414a0
5 changed files with 215 additions and 168 deletions
+54
View File
@@ -0,0 +1,54 @@
"""The ISM merge: the rolling path ends the download phase, and a text subtitle merges behind its init as UTF-8."""
from __future__ import annotations
from tests.core.test_rolling_merge_hls_ism import base, ism_track, make_ctx
from tests.core.test_rolling_merge_hls_ism import no_cancel as no_cancel # noqa: F401
from tests.core.test_rolling_merge_hls_ism import server as server # noqa: F401
from unshackle.core.config import config
from unshackle.core.manifests import ISM
from unshackle.core.manifests import ism as ism_module
from unshackle.core.tracks.segment_store import SegmentStore
CUES = [b"1\n00:00:00,000 --> 00:00:01,000\n‎one\n\n", b"2\n00:00:02,000 --> 00:00:03,000\n‏two\n\n"]
def test_a_text_subtitle_merges_behind_its_init_with_the_entities_as_characters(server, tmp_path, monkeypatch):
monkeypatch.setattr(config, "merge_segments", False)
firsts: list[bytes | None] = []
def init_segment(track, session_drm, first_segment=None):
firsts.append(first_segment)
return b"INIT"
monkeypatch.setattr(ISM, "init_segment", staticmethod(init_segment))
for i, cue in enumerate(CUES):
server.routes[f"/x.ism/text{i * 20000000}.srt"] = cue
manifest = f"""<?xml version="1.0"?>
<SmoothStreamingMedia MajorVersion="2" MinorVersion="0" Duration="40000000" TimeScale="10000000">
<StreamIndex Type="text" Name="text" Language="en" Url="text{{start_time}}.srt">
<QualityLevel Index="0" Bitrate="1000" FourCC="SRT"/>
<c t="0" d="20000000" r="{len(CUES)}"/>
</StreamIndex>
</SmoothStreamingMedia>
"""
track = ISM.from_text(manifest, f"{base(server)}x.ism/manifest").to_tracks().subtitles[0]
ctx = make_ctx(tmp_path, "subtitle.srt")
ISM.download_track(track, ctx)
assert firsts == [CUES[0]]
assert ctx.save_path.read_bytes() == b"INIT" + b"".join(CUES).replace(b"&lrm;", "\u200e".encode()).replace(
b"&rlm;", "\u200f".encode()
)
def test_the_rolling_merge_ends_the_download_phase_before_it_checks_the_count(server, tmp_path, monkeypatch):
monkeypatch.setattr(config, "merge_segments", True)
calls: list[str] = []
monkeypatch.setattr(SegmentStore, "merging", lambda self: calls.append("merging"))
monkeypatch.setattr(ism_module, "check_merged", lambda *args: calls.append("check_merged"))
ISM.download_track(ism_track(server), make_ctx(tmp_path, "audio.mp4"))
assert calls == ["merging", "check_merged"]
+61
View File
@@ -24,6 +24,7 @@ from unshackle.core.manifests.segment_pipeline import (
complete_track,
fetch_segments,
license_drm,
merge_downloaded,
)
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks.segment_store import SegmentStore
@@ -427,3 +428,63 @@ def test_complete_track_without_drm_skips_the_decryption(tmp_path, seen):
assert seen == []
assert track.path == ctx.save_path
assert ctx.statuses == ["Downloaded"]
class FakeStore:
"""Records when the merge ends the download phase."""
def __init__(self, calls: list[str]) -> None:
self.calls = calls
def merging(self) -> None:
self.calls.append("merging")
def segment_dir(ctx: DownloadContext, parts: list[bytes]) -> list[Path]:
ctx.save_dir.mkdir()
files = [ctx.save_dir / f"{i}.mp4" for i in range(len(parts))]
for path, data in zip(files, parts, strict=True):
path.write_bytes(data)
return files
def test_merge_downloaded_writes_the_init_then_each_segment_and_removes_it(tmp_path):
ctx = make_ctx(tmp_path)
files = segment_dir(ctx, PARTS[:3])
calls: list[str] = []
def append(dst, path):
calls.append(path.name)
dst.write(path.read_bytes())
merge_downloaded(
SimpleNamespace(id="EXAMPLE"), # type: ignore[arg-type]
ctx,
"DASH",
FakeStore(calls), # type: ignore[arg-type]
INIT,
append,
prepare=lambda segment_files: calls.append(f"prepare {len(segment_files)}"),
)
assert ctx.save_path.read_bytes() == INIT + b"".join(PARTS[:3])
assert calls == ["merging", "prepare 3", "0.mp4", "1.mp4", "2.mp4"]
assert not any(path.exists() for path in files)
assert ctx.statuses == ["Merging"] # type: ignore[attr-defined]
def test_merge_downloaded_without_segments_raises(tmp_path):
ctx = make_ctx(tmp_path)
calls: list[str] = []
track = SimpleNamespace(id="EXAMPLE")
store = FakeStore(calls)
with pytest.raises(FileNotFoundError, match="Output directory does not exist"):
merge_downloaded(track, ctx, "ISM", store, None, pytest.fail) # type: ignore[arg-type]
assert calls == []
ctx.save_dir.mkdir()
with pytest.raises(FileNotFoundError, match="No segment files found"):
merge_downloaded(track, ctx, "ISM", store, None, pytest.fail) # type: ignore[arg-type]
assert calls == ["merging"]
assert not ctx.save_path.exists()