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
+3 -1
View File
@@ -690,7 +690,9 @@ See the [DRM & CDM reference](../guide/drm-and-cdm.md) for the full picture.
Override any of these to react to pipeline stages (all no-ops by default):
`on_segment_downloaded`, `on_track_downloaded`, `on_track_decrypted`,
`on_track_repacked`, `on_track_multiplex`. `on_track_downloaded` runs once per track, after
unshackle decrypted the track and after `on_track_decrypted`. Also override `search()` to yield
unshackle decrypted the track and after `on_track_decrypted`. A `--remote` client runs none
of these hooks and no `track.downloader` of the service, so put what the client needs in
`track.data`, or leave it to core. Also override `search()` to yield
`SearchResult` objects for `unshackle search`.
!!! warning "Set `ANONYMOUS_SEARCH` only for a search that needs no account"
+3
View File
@@ -1137,6 +1137,8 @@ Get tracks and chapters for a specific title within the remote session. Body: `{
`manifests` holds each served DASH/ISM manifest once. For DASH, `filtered_period_ids` names the periods that the download skips, such as ad periods. A service can build an AdaptationSet of its own that the served manifest does not contain. `track_manifests` holds a one-track MPD for each such track, and the client re-parses that in place of the whole manifest. That MPD starts at the period of the track and keeps the content periods after it.
`hls_playlists` holds the media playlist text of each HLS track that the service holds as text, with the track URL. A `file:` URL is never sent: such an entry has `url` set to `null`. The client keeps an entry only when it parses as a media playlist whose segment URIs are absolute `http` or `https` URLs, and is for the same URL as its track. Otherwise it logs `Refusing track <id>: its HLS playlist ...` and drops the track.
=== "Response `200`"
```json
@@ -1149,6 +1151,7 @@ Get tracks and chapters for a specific title within the remote session. Body: `{
"attachments": [ { "url": "https://...", "name": "font.ttf", "mime_type": "font/ttf", "description": "" } ],
"manifests": [ { "type": "dash", "url": "https://...", "data": "<base64 zlib xml>", "filtered_period_ids": [ "ad-1" ] } ],
"track_manifests": [ { "track_id": "s-1", "type": "dash", "url": "https://...", "data": "<base64 zlib xml>" } ],
"hls_playlists": [ { "track_id": "v-1", "url": "https://...", "data": "<base64 zlib m3u8>" } ],
"session_headers": { "User-Agent": "..." },
"session_cookies": { "sid": "..." },
"session_cookie_jar": [ { "name": "sid", "value": "...", "domain": ".example.com", "path": "/", "secure": true } ],
+3 -1
View File
@@ -214,7 +214,9 @@ hood the client walks a remote session through its lifecycle.
downloading. A service can build an AdaptationSet of its own that the served
manifest does not contain. Each such track gets a one-track MPD in
`track_manifests`, with the content periods after its own, and the client
re-parses that instead. The client skips the same DASH periods as the server. Any
re-parses that instead. An HLS track whose service holds its media playlist as text
gets that text in `hls_playlists`. The client drops the track when the text is not a
media playlist with absolute `http` or `https` segment URIs. The client skips the same DASH periods as the server. Any
`session_headers` and cookies the server used are merged into the
client's local HTTP session. Each cookie in `session_cookie_jar` keeps its
domain, path and `secure` flag, so it goes only to its own hosts. `session_cookies` carries
+16
View File
@@ -295,6 +295,13 @@ track that it downloads. Over `--remote`, the client asks the server for the URL
each track it downloads, and the server calls the callable then. A track whose callable
fails gets no URL, and its download fails.
When the service has the media playlist of an HLS track as text and no playlist URL, set
`track.data["hls"]["playlist_text"]` to the text, and set `url` to a URL that its segment URIs
resolve against. unshackle downloads from the text and does not fetch a playlist. A `from_file`
playlist works the same way. Over `--remote` and in an export, the text goes with the track,
but a `file:` URL does not. The client accepts the text only as a media playlist whose segment
URIs are absolute `http` or `https` URLs, and drops the track otherwise.
### `Video`
`Video` adds `codec`, `range`, `bitrate`, `width`, `height`, `fps`, `scan_type`, and
@@ -310,6 +317,12 @@ closed-caption descriptors. The relevant enums:
Both `Video` and `Audio` store `bitrate` in **bits per second** (rounded up). The
string form displays kb/s, and `--vbitrate` and `--abitrate` compare in kb/s.
When the file of a track also holds a track of another kind, set `track.data["own_stream_only"] = True`
on the track. The mux then takes from that file only the track of the same kind: the video of a video
track, or the audio of an audio track. Use it for a video file with in-band audio that the
service also gives as audio tracks, or for an audio version that comes as a whole video file.
The value also goes to a `--remote` client. A track without it muxes everything in its file.
### `Audio`
`Audio` adds `bitrate`, `channels`, `joc` (Joint Object Coding, the Atmos indicator),
@@ -413,6 +426,9 @@ least one and no track is left.
- **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.
- **Segments** of each format: unshackle inflates a segment body that is one whole gzip member
before the merge, up to a size limit. A CDN can send such a body with no `Content-Encoding`
header. Any other body stays as it is, such as AES-128 ciphertext that starts with the gzip magic.
- **ISM** has no list of segments and no init segments: the parser synthesizes segment URLs
from the `<c>` fragment timeline, and rebuilds a `moov`/`ftyp` init box from `CodecPrivateData`
(supported for AVC, HEVC, DV-over-HEVC, AAC, EC-3, and TTML). A track id covers the manifest
+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"
+2 -5
View File
@@ -85,7 +85,7 @@ from unshackle.core.remote_protocol import (
)
from unshackle.core.run_plan import SESSION_DL_KEYS, PlanError, served_plan
from unshackle.core.services import Services
from unshackle.core.session import RnetSession, utf8_text
from unshackle.core.session import RnetSession
from unshackle.core.title_source import service_licence
from unshackle.core.titles import Episode, Song
from unshackle.core.tunnel import (
@@ -3654,10 +3654,7 @@ async def session_segment_filter_handler(
def unwanted_segments() -> list[str]:
import m3u8
response = session.service_instance.session.get(track.url)
if not getattr(response, "ok", True):
raise ValueError(f"playlist request failed: {response.status_code}")
playlist = m3u8.loads(utf8_text(response), uri=str(track.url))
playlist = m3u8.loads(track.playlist_text(session.service_instance.session), uri=str(track.url))
return [segment.absolute_uri for segment in playlist.segments if segment_filter(segment)]
async with session.work():
+2 -2
View File
@@ -21,7 +21,7 @@ from unshackle.core.constants import AnyTrack
from unshackle.core.drm import key_args as drm_key_args
from unshackle.core.drm.decrypters import decrypt_cenc, mp4decrypt, shaka_decrypt
from unshackle.core.drm.verify import PIFF_TENC, TENC, has_encrypted_entry, walk
from unshackle.core.session import AnySession, utf8_text
from unshackle.core.session import AnySession
from unshackle.core.utilities import get_boxes
from unshackle.core.utils import run_proxy
from unshackle.core.utils.subprocess import ffprobe
@@ -237,7 +237,7 @@ class CencDrm:
if track.descriptor == track.Descriptor.HLS:
m3u_url = track.url
assert isinstance(m3u_url, str)
master = m3u8.loads(utf8_text(session.get(m3u_url)), uri=m3u_url)
master = m3u8.loads(track.playlist_text(session), uri=m3u_url)
boxes.extend(
Box.parse(base64.b64decode(key_data(key)))
for key in (master.session_keys or master.keys)
+2 -7
View File
@@ -11,7 +11,6 @@ from unshackle.core.drm import WHOLE_FILE_DRM
from unshackle.core.drm.playready import PlayReady
from unshackle.core.drm.widevine import Widevine
from unshackle.core.manifests import DASH, HLS, ISM
from unshackle.core.session import utf8_text
from unshackle.core.tracks import Track
from unshackle.core.utils import run_proxy
@@ -104,12 +103,8 @@ def fairplay_only(track: Any, session: Any = None) -> bool:
if track.descriptor is not Track.Descriptor.HLS:
return False
try:
if track.from_file:
playlist = m3u8.load(str(track.from_file))
else:
track.ensure_url()
response = (track.session or session or run_proxy.fallback_session()).get(track.url)
playlist = m3u8.loads(utf8_text(response), track.url)
track.ensure_url()
playlist = m3u8.loads(track.playlist_text(track.session or session or run_proxy.fallback_session()), track.url)
except Exception as e:
log.debug(f"Could not read the playlist of {track.id} for its key tags: {e!r}")
return False
+5 -6
View File
@@ -24,7 +24,7 @@ from unshackle.core.manifests import DASH, HLS, ISM, MissingLanguageError, snaps
from unshackle.core.proxies.resolve import REGION_QUERY
from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.remote_service import resolve_proxy_arg, segment_uri_filter
from unshackle.core.session import failure_response, record_requests, utf8_text
from unshackle.core.session import failure_response, record_requests
from unshackle.core.title_source import KeyArrival, TitleSource
from unshackle.core.titles import Episode, Movies, Series, Title_T, Titles_T, remap_titles
from unshackle.core.tracks import Audio, Chapter, Chapters, Subtitle, Tracks, Video
@@ -73,7 +73,7 @@ def hls_playlist_kids(track: Any, session: requests.Session | None = None) -> se
"""
http = session or requests.Session()
try:
playlist = m3u8.loads(utf8_text(http.get(str(track.url))), uri=str(track.url))
playlist = m3u8.loads(track.playlist_text(http), uri=str(track.url))
keys = [k for k in playlist.keys if k is not None and k.method != "NONE"]
except Exception as e:
log.warning(f"Cannot read the media playlist of {track.id} for its KIDs: {e!r}")
@@ -136,7 +136,7 @@ def resolve_import_manifest_data(
saved: dict[str, Any] | None = None,
content_periods: dict[str, list[str]] | None = None,
) -> None:
"""Fill ``track.data`` for DASH/ISM tracks rebuilt from export dicts.
"""Fill ``track.data`` for DASH/ISM tracks rebuilt from export dicts, and the saved HLS playlist text of each track.
Exports can be without ``manifest_url`` (for example, when the service never set
``title.tracks.manifest_url``) or carry one MPD per adaptation set. A track takes its
@@ -144,6 +144,7 @@ def resolve_import_manifest_data(
matched to a locally parsed representation before download. A track that matches none is
dropped with a warning, since without its manifest data it fails only when it downloads.
"""
snapshot.restore_playlists(tracks, saved)
if manifest_type not in MANIFEST_DATA_KEYS:
return
@@ -189,9 +190,7 @@ def resolve_import_manifest_data(
unmatched = {str(track.id) for track in pending if not track.data.get(data_key)}
for track_id in unmatched:
log.warning(f"Skipping exported track {track_id}: its {manifest_type} manifest no longer lists it")
tracks.select_video(lambda t: str(t.id) not in unmatched)
tracks.select_audio(lambda t: str(t.id) not in unmatched)
tracks.select_subtitles(lambda t: str(t.id) not in unmatched)
tracks.drop(unmatched)
def parse_codec(codec: type[E], parse: Callable[[str], E], value: Any) -> E | None:
+2 -2
View File
@@ -675,8 +675,8 @@ class HLS:
log = logging.getLogger("HLS")
assert isinstance(track.url, str)
if track.from_file:
master = m3u8.load(str(track.from_file))
if (text := track.held_playlist()) is not None:
master = m3u8.loads(text, uri=track.url)
else:
response = session.get(track.url)
if not isinstance(response, (requests.Response, RnetResponse)):
@@ -8,6 +8,7 @@ from __future__ import annotations
import html
import shutil
import zlib
from collections.abc import Callable, Iterator
from concurrent.futures import Future
from contextlib import ExitStack, closing, contextmanager
@@ -118,6 +119,29 @@ LICENSABLE: dict[Track.Descriptor, tuple[type, ...]] = {
"""The DRM systems the licence step licenses, by the kind of manifest the track comes from."""
def inflate_gzip(path: Path) -> None:
"""Inflate in place a segment whose body is one whole gzip member, which a CDN can send with no Content-Encoding.
Any other body stays as it is: AES-128 ciphertext can start with the gzip magic too.
"""
with open(path, "rb") as f:
if f.read(3) != b"\x1f\x8b\x08":
return
from unshackle.core.api.compression import MAX_INFLATE_BYTES
decompressor = zlib.decompressobj(31)
try:
data = decompressor.decompress(path.read_bytes(), MAX_INFLATE_BYTES + 1)
except zlib.error:
return
if len(data) > MAX_INFLATE_BYTES:
raise ValueError(f"Segment {path.name} inflates beyond {MAX_INFLATE_BYTES} bytes")
if decompressor.eof and not decompressor.unused_data:
inflated = path.with_name(path.name + ".inflated")
inflated.write_bytes(data)
inflated.replace(path)
def license_drm(
track: AnyTrack,
drm: DRM_T | None,
@@ -220,6 +244,7 @@ def fetch_segments(
# a service downloader that ignores skip fetched a segment the store holds
file_downloaded.unlink(missing_ok=True)
continue
inflate_gzip(file_downloaded)
events.emit(events.Types.SEGMENT_DOWNLOADED, track=track, segment=file_downloaded)
future = decrypter.submit(file_downloaded, decrypted(file_downloaded)) if decrypter else None
if merger:
+88 -11
View File
@@ -1,8 +1,9 @@
"""The manifest snapshot: the DASH and ISM parser state of a title's tracks, saved for --remote and export/import.
``capture`` saves each manifest tree as the service left it, with its filtered periods, plus a
one-track fragment for each track that the full tree cannot identify again. ``restore`` gives
that state back to tracks rebuilt somewhere else, where the service code does not run.
one-track fragment for each track that the full tree cannot identify again, plus the media playlist
text of each HLS track that holds one. ``restore`` and ``restore_playlists`` give that state back to tracks
rebuilt somewhere else, where the service code does not run.
"""
from __future__ import annotations
@@ -12,7 +13,9 @@ import logging
import zlib
from copy import deepcopy
from typing import Any
from urllib.parse import urljoin, urlparse
import m3u8
from lxml import etree
from unshackle.core.manifests.dash import DASH, MissingLanguageError
@@ -32,7 +35,11 @@ MAX_SNAPSHOT_BYTES = 32 * 1024 * 1024
def capture(tracks: Tracks, level: int = zlib.Z_DEFAULT_COMPRESSION) -> Snapshot:
"""The snapshot of these tracks, JSON-safe, at zlib ``level`` (0 gives an uncompressed zlib stream)."""
counts: dict[int, int] = {}
return {"manifests": whole_manifests(tracks, level, counts), "track_manifests": fragments(tracks, level, counts)}
return {
"manifests": whole_manifests(tracks, level, counts),
"track_manifests": fragments(tracks, level, counts),
"hls_playlists": playlists(tracks, level),
}
def restore(tracks: Tracks, snapshot: Any, language: Any = None) -> None:
@@ -78,18 +85,31 @@ def entries(snapshot: Any, key: str) -> list[dict[str, Any]]:
return [e for e in value if isinstance(e, dict)] if isinstance(value, list) else []
def shared_url(url: Any) -> str | None:
"""``url`` as a string, else None for no URL or a file: URL, which names a path on this machine only."""
return str(url) if url and not str(url).lower().startswith("file:") else None
def deflate(data: bytes, level: int) -> str:
return base64.b64encode(zlib.compress(data, level)).decode("ascii")
def inflate(data: str, budget: list[int]) -> bytes:
"""The saved bytes. ``budget[0]`` is the inflated byte count still allowed; this call takes its share."""
from unshackle.core.api.compression import safe_inflate
out = safe_inflate(base64.b64decode(data), budget[0])
budget[0] -= len(out)
return out
def pack(element: Any, level: int) -> str:
xml_bytes = etree.tostring(element, xml_declaration=True, encoding="UTF-8")
return base64.b64encode(zlib.compress(xml_bytes, level)).decode("ascii")
return deflate(etree.tostring(element, xml_declaration=True, encoding="UTF-8"), level)
def unpack(data: str, budget: list[int]) -> Any:
"""The saved tree. ``budget[0]`` is the inflated byte count still allowed; this call takes its share."""
from unshackle.core.api.compression import safe_inflate
xml_bytes = safe_inflate(base64.b64decode(data), budget[0])
budget[0] -= len(xml_bytes)
return etree.fromstring(xml_bytes)
"""The saved tree, inflated within ``budget`` as ``inflate`` does."""
return etree.fromstring(inflate(data, budget))
def counted(manifest: Any, tag: str, counts: dict[int, int]) -> int:
@@ -203,6 +223,63 @@ def fragments(tracks: Tracks, level: int, counts: dict[int, int]) -> list[dict[s
return out
def playlists(tracks: Tracks, level: int) -> list[dict[str, Any]]:
"""The media playlist text of each track that holds one, with the track URL it resolves against.
A ``from_file`` playlist is read here, so the other side never needs this machine's path.
"""
out: list[dict[str, Any]] = []
for track in tracks:
if track.descriptor is not Track.Descriptor.HLS:
continue
try:
text = track.held_playlist()
except (OSError, UnicodeDecodeError) as e:
log.warning("Not saving the playlist of track %s: %s", track.id, e)
continue
if text is not None:
out.append({"track_id": str(track.id), "url": shared_url(track.url), "data": deflate(text.encode(), level)})
return out
def check_playlist(text: str, url: str | None) -> None:
"""Raise ValueError unless ``text`` is a media playlist whose every segment and init URI is http(s)."""
playlist = m3u8.loads(text, uri=url)
if playlist.is_variant or not playlist.segments:
raise ValueError("is not a media playlist")
for segment in playlist.segments:
for uri in filter(None, (segment.uri, segment.init_section and segment.init_section.uri)):
scheme = urlparse(urljoin(url or "", uri)).scheme
if scheme not in ("http", "https"):
raise ValueError(f"has a {scheme or 'relative'} segment URI")
def restore_playlists(tracks: Tracks, snapshot: Any) -> None:
"""Give each track the playlist text the snapshot holds for it, by track id, and drop a track whose text fails.
The text must pass ``check_playlist`` against the URL it was saved with, so a peer cannot name a local file.
"""
budget = [MAX_SNAPSHOT_BYTES]
by_id = {str(t.id): t for t in tracks}
refused: set[str] = set()
for entry in entries(snapshot, "hls_playlists"):
track = by_id.get(str(entry.get("track_id")))
if track is None or not isinstance(entry.get("data"), str):
continue
url = entry.get("url") if isinstance(entry.get("url"), str) else None
try:
if url is not None and url != track.url:
raise ValueError("was saved for another URL")
text = inflate(entry["data"], budget).decode("utf-8")
check_playlist(text, url)
except Exception as e:
log.warning("Refusing track %s: its HLS playlist %s", track.id, e)
refused.add(str(track.id))
continue
track.data["hls"]["playlist_text"] = text
tracks.drop(refused)
def restore_fragments(tracks: Tracks, saved: list[dict[str, Any]], budget: list[int]) -> None:
"""Fill ``track.data`` from the one-track fragments, by track id. This runs before the whole-manifest restore."""
by_id = {str(t.id): t for t in tracks}
+26 -1
View File
@@ -617,6 +617,8 @@ class Track:
- playlist: m3u8.model.Playlist - The primary track information.
- media: m3u8.model.Media - The audio/subtitle track information.
- segment_durations: list[int] - A list of each segment's duration.
- playlist_text: str - The media playlist, set by a service that has its text and no
playlist URL. Its segment URIs resolve against the track URL.
- "dash" used by the DASH class.
- manifest: lxml.ElementTree - DASH MPD manifest.
- period: lxml.Element - The period of this track.
@@ -625,6 +627,11 @@ class Track:
- timescale: int - The timescale of the track's segments.
- segment_durations: list[int] - A list of each segment's duration.
A service can set:
- "own_stream_only": bool - Mux only the track of the same kind from the file: a video
without the audio its file holds, or an audio track without the video in its file.
You should not add, change, or remove any data within reserved keys.
You may use their data, but note that these values can change or be removed
at any point.
@@ -998,6 +1005,24 @@ class Track:
return self.load_drm_from_playlist()
def held_playlist(self) -> str | None:
"""The HLS media playlist text the track holds: ``data["hls"]["playlist_text"]``, else the ``from_file`` text."""
text = (self.data.get("hls") or {}).get("playlist_text")
if text is None and self.from_file:
text = self.from_file.read_text(encoding="utf-8")
return text
def playlist_text(self, session: Any, **kwargs: Any) -> str:
"""The HLS media playlist text the track holds, else the one at its URL; a response that is not ok raises."""
text = self.held_playlist()
if text is None:
assert isinstance(self.url, str)
response = session.get(self.url, **kwargs)
if not getattr(response, "ok", True):
raise ValueError(f"Failed to request the media playlist of track {self.id}: {response.status_code}")
text = utf8_text(response)
return text
def load_drm_from_playlist(self, session: Any = None, bridge: bool = False) -> bool:
"""Load the Widevine and PlayReady DRM of the EXT-X-KEY and EXT-X-SESSION-KEY tags of this track's playlist.
@@ -1015,7 +1040,7 @@ class Track:
session = self.session or session or run_proxy.fallback_session()
try:
assert isinstance(self.url, str)
playlist = m3u8.loads(utf8_text(session.get(self.url)), self.url)
playlist = m3u8.loads(self.playlist_text(session), self.url)
except Exception as e:
raise ValueError(f"Failed to load DRM from playlist for track {self.id}: {e}") # noqa: B904
+23 -9
View File
@@ -574,6 +574,12 @@ class Tracks:
def select_subtitles(self, x: Callable[[Subtitle], bool]) -> None:
self.subtitles = list(filter(x, self.subtitles))
def drop(self, ids: set[str]) -> None:
"""Remove the video, audio and subtitle tracks whose id is in ``ids``."""
self.select_video(lambda t: str(t.id) not in ids)
self.select_audio(lambda t: str(t.id) not in ids)
self.select_subtitles(lambda t: str(t.id) not in ids)
def filter(self, predicate: Callable[[AnyTrack], bool]) -> Tracks:
"""Return a new Tracks with tracks filtered by predicate, preserving metadata."""
new_tracks = Tracks(manifest_url=self.manifest_url)
@@ -834,11 +840,14 @@ class Tracks:
delay = round((track.sample_start - sample_base) * 1000) if config.sample else 0
moov = read_top_level_box(source, b"moov")
flags = "" if moov else ":tkhd=enable,movie,preview:ID=-1"
cl.extend(["-add", f"{source}:lang={track.mux_language}{flags}" + (f":delay={delay}" if delay else "")])
only = f"#{'video' if isinstance(track, Video) else 'audio'}" if track.data.get("own_stream_only") else ""
cl.extend(
["-add", f"{source}{only}:lang={track.mux_language}{flags}" + (f":delay={delay}" if delay else "")]
)
name = "" if isinstance(track, Video) else (track.get_track_name() or "")
if name:
names.extend(["-name", f"{track_id + 1}={name}"])
track_id += mp4_track_count(moov)
track_id += 1 if only else mp4_track_count(moov)
if not track_id:
raise ValueError("No tracks provided, at least one track must be provided.")
@@ -1125,7 +1134,9 @@ class Tracks:
)
a = ids.get("audio")
if vt.data.get("audio_language") and a is not None:
if vt.data.get("own_stream_only"):
video_args.append("--no-audio")
elif vt.data.get("audio_language") and a is not None:
video_args.extend(
[
"--language",
@@ -1147,21 +1158,24 @@ class Tracks:
audio_default = i == preferred_audio_idx
else:
audio_default = at.is_original_lang
own_only = bool(at.data.get("own_stream_only"))
a = file_track_ids(at.path).get("audio", 0) if own_only else 0
cl.extend(
[
"--track-name",
f"0:{at.get_track_name() or ''}",
f"{a}:{at.get_track_name() or ''}",
"--language",
f"0:{at.mux_language}",
f"{a}:{at.mux_language}",
"--default-track",
f"0:{audio_default}",
f"{a}:{audio_default}",
"--visual-impaired-flag",
f"0:{at.descriptive}",
f"{a}:{at.descriptive}",
"--original-flag",
f"0:{at.is_original_lang}",
f"{a}:{at.is_original_lang}",
"--compression",
"0:none",
f"{a}:none",
*sample_sync(at.sample_start),
*(["--no-video"] if own_only else []),
"(",
str(at.path),
")",
+2 -3
View File
@@ -15,7 +15,7 @@ from requests import Session
from unshackle.core.binaries import FFProbe
from unshackle.core.constants import TrackT
from unshackle.core.session import RnetSession, unrecorded, utf8_text
from unshackle.core.session import RnetSession, unrecorded
from unshackle.core.utils.subprocess import log_tool_run
if TYPE_CHECKING:
@@ -357,8 +357,7 @@ def extract_hls(track: Track, session: Session | RnetSession) -> list[Segment]:
import m3u8
playlist_url = track.url if isinstance(track.url, str) else track.url[0]
res = session.get(playlist_url, timeout=PROBE_TIMEOUT)
playlist = m3u8.loads(utf8_text(res), uri=playlist_url)
playlist = m3u8.loads(track.playlist_text(session, timeout=PROBE_TIMEOUT), uri=playlist_url)
return hls_segments(playlist.segments)
+2 -3
View File
@@ -211,9 +211,8 @@ def first_segment(track: Track, session: Session | RnetSession) -> tuple[str, in
seg_url, byte_range = segments[0]
return seg_url, int((byte_range or "").partition("-")[0] or 0)
if track.descriptor == Track.Descriptor.HLS:
if track.from_file:
text = track.from_file.read_text(encoding="utf-8")
else:
text = track.held_playlist()
if text is None:
res = session.get(url, timeout=PROBE_TIMEOUT)
if getattr(res, "status_code", 0) != 200:
return None
+6 -6
View File
@@ -32,7 +32,7 @@ from unshackle.core.config import config
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
from unshackle.core.drm import WHOLE_FILE_DRM, BlowfishStripe, ClearKeyCENC, ClearKeyCTR, PlayReady, Widevine
from unshackle.core.manifests import HLS
from unshackle.core.manifests.snapshot import restore
from unshackle.core.manifests.snapshot import restore, restore_playlists, shared_url
from unshackle.core.titles import Album, Episode, Movie, Music, Song, Title_T
from unshackle.core.titles.availability import availability_metadata
from unshackle.core.titles.music import MUSIC_DATA_KEYS, MUSIC_FIELDS, SONG_FIELDS, song_metadata
@@ -524,7 +524,7 @@ def apply_service_track_data(tracks: Tracks, data: dict[str, Any]) -> None:
track = by_id.get(str(entry.get("id")))
extra = entry.get("data")
if track is not None and isinstance(extra, dict):
track.data.update(extra)
track.data.update({k: v for k, v in extra.items() if k not in MANIFEST_DATA_KEYS})
def cookie_values(cookies: list[dict[str, Any]]) -> dict[str, str]:
@@ -585,6 +585,7 @@ def apply_tracks_reply(reply: dict[str, Any], title: Title_T, session: requests.
if k.lower() not in ("host", "content-length", "content-type"):
session.headers[k] = v
apply_session_cookies(session, reply)
restore_playlists(tracks, reply)
restore(tracks, reply)
apply_service_track_data(tracks, reply)
return tracks
@@ -642,12 +643,12 @@ def original_audio_ids(tracks: list[Audio], title: Title_T) -> set:
def url_fields(track: Any) -> dict[str, Any]:
"""The URL of a track for the track list, or ``resolve_url`` for a track that resolves its URL on use.
Such a track keeps its lookup until a client asks the segments route for its URL.
Such a track keeps its lookup until a client asks the segments route for its URL. A file: URL is not sent.
"""
url = getattr(track, "url", None)
if not url and getattr(track, "resolve_url", None):
return {"resolve_url": True}
return {"url": str(url)} if url else {}
return {"url": shared} if (shared := shared_url(url)) else {}
def served_url(track: Any) -> str | None:
@@ -658,8 +659,7 @@ def served_url(track: Any) -> str | None:
except Exception as e:
server_log.warning(f"Could not resolve the URL of track {track.id}: {e}")
return None
url = getattr(track, "url", None)
return str(url) if url else None
return shared_url(getattr(track, "url", None))
def serialize_video_track(track: Video, include_url: bool = False) -> dict[str, Any]: