feat(hls): carry a held media playlist over --remote and export, inflate gzip segments, add own_stream_only mux opt-in

This commit is contained in:
imSp4rky
2026-12-02 11:12:02 -07:00
parent ccdd14c845
commit 9842a61d3f
27 changed files with 404 additions and 62 deletions
+2
View File
@@ -201,6 +201,8 @@ def playlist_track(text: str, init_data: bytes = b"") -> Video:
track.url = "https://example.test/video.m3u8"
track.descriptor = Video.Descriptor.HLS
track.drm = None
track.data = {}
track.from_file = None
track.needs_drm_loading = True
track.session = RouteSession({"video.m3u8": text.encode(), "init.mp4": init_data})
return track
+3 -1
View File
@@ -169,7 +169,9 @@ def test_first_fragment_skips_the_header_boxes_of_a_one_file_track(monkeypatch:
def test_first_segment_of_an_hls_playlist_keeps_its_byte_offset() -> None:
playlist = '#EXTM3U\n#EXT-X-MAP:URI="init.mp4"\n#EXTINF:6.0,\n#EXT-X-BYTERANGE:5000@1200\nmedia.mp4\n'
session = SimpleNamespace(get=lambda url, timeout: SimpleNamespace(status_code=200, text=playlist))
track = SimpleNamespace(url="https://cdn/v/index.m3u8", data={}, descriptor=Video.Descriptor.HLS, from_file=None)
track = SimpleNamespace(
url="https://cdn/v/index.m3u8", data={}, descriptor=Video.Descriptor.HLS, held_playlist=lambda: None
)
assert hdr10plus.first_segment(track, session) == ("https://cdn/v/media.mp4", 1200) # type: ignore[arg-type]
+5 -1
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
from functools import partial
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -128,5 +129,8 @@ def test_import_reads_the_kid_of_a_playlist_whose_key_has_none() -> None:
def get(url: str, headers: Any = None) -> Any:
return SimpleNamespace(text=playlist(keyed_segment(NO_KID_PSSH)), ok=True, content=b"init")
track = SimpleNamespace(id="vid", url="https://example.test/media.m3u8", get_key_id=lambda init: INIT_KID)
track = SimpleNamespace(
id="vid", url="https://example.test/media.m3u8", get_key_id=lambda init: INIT_KID, held_playlist=lambda: None
)
track.playlist_text = partial(Track.playlist_text, track)
assert hls_playlist_kids(track, SimpleNamespace(get=get)) == {INIT_KID}
+1 -1
View File
@@ -680,7 +680,7 @@ def test_the_server_takes_the_same_key_id_of_a_stitched_playlist(
assert track.drm is not None
assert [drm.kids for drm in track.drm] == [[KID], [KID]]
assert session.requests == ["media.m3u8", *requests]
assert session.requests == requests
@pytest.mark.parametrize(
+2
View File
@@ -63,6 +63,8 @@ def make_track(res: requests.Response) -> Video:
track.url = "https://example.com/video/720.m3u8"
track.session = FakeSession(res)
track.drm = None
track.data = {}
track.from_file = None
track.needs_drm_loading = True
return track
+26
View File
@@ -0,0 +1,26 @@
"""A segment whose body is gzip with no Content-Encoding header is inflated before the merge; no other body is."""
from __future__ import annotations
import gzip
import pytest
from tests.core.test_rolling_merge_hls_ism import INIT, PARTS, hls_track, make_ctx, no_cancel, server # noqa: F401
from unshackle.core.manifests import HLS
@pytest.mark.parametrize(
"body, expected",
[
pytest.param(gzip.compress, lambda part: part, id="gzip"),
pytest.param(lambda part: b"\x1f\x8b\x08" + part, lambda part: b"\x1f\x8b\x08" + part, id="gzip-magic-only"),
pytest.param(lambda part: gzip.compress(part)[:-4], lambda part: gzip.compress(part)[:-4], id="cut-gzip"),
],
)
def test_only_a_whole_gzip_segment_is_inflated(body, expected, server, tmp_path): # noqa: F811
for i, part in enumerate(PARTS):
server.routes[f"/part{i}.m4s"] = body(part)
ctx = make_ctx(tmp_path, "out.mp4")
HLS.download_track(hls_track(server, False), ctx)
assert ctx.save_path.read_bytes() == INIT + b"".join(map(expected, PARTS))
+17
View File
@@ -286,6 +286,23 @@ def test_mp4_names_skip_the_extra_tracks_of_a_3d_video_file(tmp_path: Path, mp4b
assert command[command.index("-name") + 1] == "3=English"
def test_an_mp4_mux_adds_only_the_own_stream_of_each_file(tmp_path: Path, mp4box_commands: list[list[str]]) -> None:
video = stereo_video(tmp_path, stereo=False)
video.data["own_stream_only"] = True
video.path.write_bytes(box(b"moov", box(b"trak") + box(b"trak")))
audio = Audio(url="https://x/a.mp4", language="en", codec=Audio.Codec.EC3, name="English")
audio.path = tmp_path / "a.mp4"
audio.path.write_bytes(b"\x00" * 16)
audio.data["own_stream_only"] = True
source = video.path
Tracks([video, audio])._mux_mp4(title="Film", output_path=tmp_path / "out.mkv")
command = mp4box_commands[0]
adds = [command[i + 1] for i, arg in enumerate(command) if arg == "-add"]
assert adds[0].startswith(f"{source}#video:")
assert "#audio:" in adds[1]
assert command[command.index("-name") + 1] == "2=English"
def test_a_3d_mux_that_loses_its_second_view_warns(
tmp_path: Path, mp4box_commands: list[list[str]], caplog: pytest.LogCaptureFixture
) -> None:
@@ -52,6 +52,7 @@ def hls_track() -> Video:
track.url = "https://cdn.example.invalid/media.m3u8"
track.descriptor = Track.Descriptor.HLS
track.data = {}
track.from_file = None
track.drm = None
track.session = None
return track
+109
View File
@@ -0,0 +1,109 @@
"""An HLS track whose media playlist is held as text, or read from a file, over a remote round trip and an export.
The server side serializes the tracks reply with its manifest snapshot, the client side rebuilds the tracks from
the JSON and downloads them from a loopback server.
"""
from __future__ import annotations
import json
import logging
from pathlib import Path
import pytest
import requests
from tests.core.test_rolling_merge_hls_ism import INIT, PARTS, base, make_ctx, no_cancel, server # noqa: F401
from tests.core.test_wire import json_copy, movie
from unshackle.core.import_service import resolve_import_manifest_data
from unshackle.core.manifests import HLS
from unshackle.core.manifests.snapshot import capture
from unshackle.core.tracks import Tracks, Video
from unshackle.core.wire import apply_tracks_reply, serialize_tracks_reply, track_from_dict
def media_playlist(prefix: str = "") -> str:
lines = ["#EXTM3U", "#EXT-X-VERSION:6", "#EXT-X-TARGETDURATION:4", f'#EXT-X-MAP:URI="{prefix}init.mp4"']
for i in range(len(PARTS)):
lines += ["#EXTINF:4.0,", f"{prefix}part{i}.m4s"]
return "\n".join([*lines, "#EXT-X-ENDLIST"])
def video(url: str, **kwargs) -> Video:
return Video(
url,
"en",
descriptor=Video.Descriptor.HLS,
codec=Video.Codec.AVC,
width=1920,
height=1080,
bitrate=1_000_000,
id_="v1",
**kwargs,
)
def held(srv, text: str | None = None) -> Video:
return video(base(srv), data={"hls": {"playlist_text": text or media_playlist()}})
def from_file(tmp_path: Path, text: str) -> Video:
path = tmp_path / "server" / "Video_v1.m3u8"
path.parent.mkdir()
path.write_text(text, encoding="utf-8")
return video(path.as_uri(), from_file=path)
def round_trip(track: Video) -> Tracks:
"""The tracks a remote client rebuilds from the tracks reply of a server that holds ``track``."""
tracks = Tracks(track)
reply = json_copy({**serialize_tracks_reply(movie(), tracks, [], None, lambda data: data), **capture(tracks)})
assert "file:" not in json.dumps(reply)
return apply_tracks_reply(reply, movie(), requests.Session())
def downloaded(track: Video, tmp_path: Path) -> bytes:
ctx = make_ctx(tmp_path, "out.mp4")
HLS.download_track(track, ctx)
return ctx.save_path.read_bytes()
def test_a_held_playlist_downloads_on_the_client(server, tmp_path): # noqa: F811
client = round_trip(held(server))
assert downloaded(client.videos[0], tmp_path) == INIT + b"".join(PARTS)
def test_a_from_file_playlist_downloads_on_the_client(server, tmp_path): # noqa: F811
client = round_trip(from_file(tmp_path, media_playlist(base(server))))
assert downloaded(client.videos[0], tmp_path) == INIT + b"".join(PARTS)
def test_an_export_import_keeps_the_held_playlist(server, tmp_path): # noqa: F811
track = held(server)
imported = Tracks(track_from_dict(json_copy(track.to_dict())))
saved = json_copy(capture(Tracks(track)))
resolve_import_manifest_data(imported, "HLS", session=requests.Session(), language="en", title=movie(), saved=saved)
assert downloaded(imported.videos[0], tmp_path) == INIT + b"".join(PARTS)
def test_the_client_takes_no_playlist_from_the_service_data(server): # noqa: F811
tracks = Tracks(held(server))
reply = json_copy({**serialize_tracks_reply(movie(), tracks, [], None, lambda data: data), **capture(tracks)})
reply["hls_playlists"] = []
reply["video"][0]["data"] = {"hls": {"playlist_text": media_playlist("file:///etc/")}}
assert apply_tracks_reply(reply, movie(), requests.Session()).videos[0].held_playlist() is None
@pytest.mark.parametrize(
"make",
[
pytest.param(lambda srv, tmp: from_file(tmp, media_playlist()), id="relative-to-a-server-file"),
pytest.param(lambda srv, tmp: held(srv, media_playlist("file:///etc/")), id="file-segment"),
pytest.param(lambda srv, tmp: held(srv, "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\nm.m3u8\n"), id="variant"),
],
)
def test_the_client_refuses_a_playlist_it_must_not_download(make, server, tmp_path, caplog): # noqa: F811
with caplog.at_level(logging.WARNING):
client = round_trip(make(server, tmp_path))
assert not client.videos
assert [r.getMessage() for r in caplog.records if r.name == "snapshot"][0].startswith("Refusing track v1: ")
+6 -1
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
from functools import partial
from types import SimpleNamespace
import click
@@ -12,6 +13,7 @@ import responses
from tests.remote.sessions import hold_session, session_entry
from unshackle.core.api import handlers
from unshackle.core.remote_service import RemoteClient, RemoteService
from unshackle.core.tracks.track import Track
pytestmark = pytest.mark.unit
@@ -43,7 +45,10 @@ def make_session(monkeypatch, track):
async def test_handler_returns_unwanted_absolute_uris(monkeypatch):
track = SimpleNamespace(url=BASE, OnSegmentFilter=lambda segment: "ad" in segment.uri)
track = SimpleNamespace(
id="t1", url=BASE, OnSegmentFilter=lambda segment: "ad" in segment.uri, held_playlist=lambda: None
)
track.playlist_text = partial(Track.playlist_text, track)
make_session(monkeypatch, track)
response = await handlers.session_segment_filter_handler({"track_id": "t1"}, "s1")
@@ -4,7 +4,7 @@ from types import SimpleNamespace
import pytest
from unshackle.core import binaries
from unshackle.core.tracks import Tracks, Video
from unshackle.core.tracks import Audio, Tracks, Video
from unshackle.core.tracks.tracks import file_track_ids
@@ -81,6 +81,27 @@ def test_embedded_audio_options_are_left_out_when_the_file_has_no_audio(tmp_path
assert "--track-name" not in args
@pytest.mark.parametrize("own", [True, False])
def test_a_video_with_own_stream_only_muxes_without_its_audio(tmp_path, mux_args, own):
args = mux_args(
Tracks(downloaded(make_video("v1", audio_language="ko", own_stream_only=own), tmp_path)),
{"video": 0, "audio": 1},
)
assert ("--no-audio" in args) == own
assert ("--track-name" in args) != own
@pytest.mark.parametrize("own", [True, False])
def test_an_audio_track_with_own_stream_only_muxes_without_its_video(tmp_path, mux_args, own):
audio = Audio(url="https://example.test/a.m3u8", language="th", codec=Audio.Codec.AAC)
audio.data["own_stream_only"] = own
audio.path = tmp_path / "a.ts"
audio.path.write_bytes(b"\x00" * 16)
args = mux_args(Tracks(audio), {"video": 0, "audio": 1})
assert ("--no-video" in args) == own
assert args[args.index("--language") + 1] == ("1:th" if own else "0:th")
def test_repack_and_mux_share_the_embedded_audio_name():
assert make_video("v1", audio_language="zh").embedded_audio_name() == "Chinese"
assert make_video("v1", audio_language="zh", audio_language_name="Mandarin").embedded_audio_name() == "Mandarin"