mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-03 06:25:10 +00:00
fix(snapshot): keep every manifest tree of a shared URL and restore each track from its own tree
This commit is contained in:
@@ -1135,7 +1135,7 @@ Requires an authenticated remote session. Otherwise it returns `404 SESSION_NOT_
|
|||||||
|
|
||||||
Get tracks and chapters for a specific title within the remote session. Body: `{ "title_id": "..." }` (required). Unlike `list-tracks`, track objects here **include** download URLs, along with session headers/cookies and manifest data the client needs to download directly. A slow answer arrives as a [slow response](#slow-responses).
|
Get tracks and chapters for a specific title within the remote session. Body: `{ "title_id": "..." }` (required). Unlike `list-tracks`, track objects here **include** download URLs, along with session headers/cookies and manifest data the client needs to download directly. A slow answer arrives as a [slow response](#slow-responses).
|
||||||
|
|
||||||
`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.
|
`manifests` holds each served DASH/ISM manifest once. One URL can have more than one entry, such as when a service merges a second manifest under the same URL. `track_ids` names the tracks that each entry restores, and the client matches such a track only in that entry's manifest. 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.
|
`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.
|
||||||
|
|
||||||
@@ -1149,7 +1149,7 @@ Get tracks and chapters for a specific title within the remote session. Body: `{
|
|||||||
"subtitles": [ { "id": "s-1", "url": "https://..." } ],
|
"subtitles": [ { "id": "s-1", "url": "https://..." } ],
|
||||||
"chapters": [ { "timestamp": "00:00:00.000", "name": "Intro" } ],
|
"chapters": [ { "timestamp": "00:00:00.000", "name": "Intro" } ],
|
||||||
"attachments": [ { "url": "https://...", "name": "font.ttf", "mime_type": "font/ttf", "description": "" } ],
|
"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" ] } ],
|
"manifests": [ { "type": "dash", "url": "https://...", "data": "<base64 zlib xml>", "track_ids": [ "v-1", "a-1" ], "filtered_period_ids": [ "ad-1" ] } ],
|
||||||
"track_manifests": [ { "track_id": "s-1", "type": "dash", "url": "https://...", "data": "<base64 zlib xml>" } ],
|
"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>" } ],
|
"hls_playlists": [ { "track_id": "v-1", "url": "https://...", "data": "<base64 zlib m3u8>" } ],
|
||||||
"session_headers": { "User-Agent": "..." },
|
"session_headers": { "User-Agent": "..." },
|
||||||
|
|||||||
@@ -223,3 +223,71 @@ def test_an_export_from_a_remote_client_imports_every_track(tmp_path):
|
|||||||
imported = export_and_import(tmp_path, round_trip(tracks))
|
imported = export_and_import(tmp_path, round_trip(tracks))
|
||||||
assert (len(imported.videos), len(imported.audio)) == (1, 1)
|
assert (len(imported.videos), len(imported.audio)) == (1, 1)
|
||||||
assert stitched(imported.videos[0]) == ["main-1", "main-2", "main-3"]
|
assert stitched(imported.videos[0]) == ["main-1", "main-2", "main-3"]
|
||||||
|
|
||||||
|
|
||||||
|
OTHER_MPD = mpd("""
|
||||||
|
<Period id="main-1" duration="PT30S">
|
||||||
|
<AdaptationSet contentType="audio" mimeType="audio/mp4" lang="en">
|
||||||
|
<Representation id="a1" codecs="mp4a.40.2" bandwidth="128000" audioSamplingRate="48000">
|
||||||
|
<SegmentTemplate media="other/a1_$Number$.m4s" initialization="other/a1_init.mp4"
|
||||||
|
duration="4" timescale="1" startNumber="1"/>
|
||||||
|
</Representation>
|
||||||
|
<Representation id="a2" codecs="mp4a.40.2" bandwidth="256000" audioSamplingRate="96000">
|
||||||
|
<SegmentTemplate media="other/a2_$Number$.m4s" initialization="other/a2_init.mp4"
|
||||||
|
duration="4" timescale="1" startNumber="1"/>
|
||||||
|
</Representation>
|
||||||
|
</AdaptationSet>
|
||||||
|
</Period>""")
|
||||||
|
|
||||||
|
|
||||||
|
def two_trees(other_url: str = URL) -> Tracks:
|
||||||
|
"""The tracks of two manifests under one URL, the way a service merges a second release.
|
||||||
|
|
||||||
|
Its first audio track has the attributes and the parser id of the first tree's audio, so the
|
||||||
|
service gives every track an id of its own.
|
||||||
|
"""
|
||||||
|
tracks = Tracks()
|
||||||
|
tracks.manifest_url = URL
|
||||||
|
other = DASH.from_text(OTHER_MPD, other_url).to_tracks(language="en")
|
||||||
|
for index, track in enumerate([*service_tracks(), *other]):
|
||||||
|
track.id = f"EXAMPLE-{index}"
|
||||||
|
tracks.add(track)
|
||||||
|
return tracks
|
||||||
|
|
||||||
|
|
||||||
|
def media(track: Track) -> str:
|
||||||
|
return track.data["dash"]["representation"].find("SegmentTemplate").get("media")
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_tree_under_one_url_restores_its_own_tracks():
|
||||||
|
tracks = two_trees()
|
||||||
|
client = round_trip(tracks)
|
||||||
|
assert {t.id: media(t) for t in client} == {t.id: media(t) for t in tracks}
|
||||||
|
assert stitched(client.videos[0]) == ["main-1", "main-2", "main-3"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("other_url", [URL, URL + "?sig=2"])
|
||||||
|
def test_an_import_restores_every_tree_under_one_url(tmp_path, other_url):
|
||||||
|
tracks = two_trees(other_url)
|
||||||
|
imported = export_and_import(tmp_path, tracks)
|
||||||
|
assert sorted(media(t) for t in imported) == sorted(media(t) for t in tracks)
|
||||||
|
|
||||||
|
|
||||||
|
def test_one_tree_parsed_twice_is_saved_once():
|
||||||
|
first, second = service_tracks(), service_tracks()
|
||||||
|
tracks = Tracks(first.videos[0], second.audio[0])
|
||||||
|
saved = capture(tracks)["manifests"]
|
||||||
|
assert len(saved) == 1
|
||||||
|
assert sorted(saved[0]["track_ids"]) == sorted(str(t.id) for t in tracks)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_snapshot_without_track_ids_still_restores():
|
||||||
|
tracks = service_tracks()
|
||||||
|
saved = json.loads(json.dumps(capture(tracks)))
|
||||||
|
for entry in saved["manifests"]:
|
||||||
|
entry.pop("track_ids", None)
|
||||||
|
client = Tracks()
|
||||||
|
for track in tracks:
|
||||||
|
client.add(track_from_dict(track_to_dict(track)))
|
||||||
|
restore(client, saved)
|
||||||
|
assert {t.id: media(t) for t in client} == {t.id: media(t) for t in tracks}
|
||||||
|
|||||||
@@ -465,11 +465,11 @@ class ImportService(TitleSource):
|
|||||||
parsed_ids = {str(t.id) for t in tracks}
|
parsed_ids = {str(t.id) for t in tracks}
|
||||||
url_dicts = [t for t in tracks_map.values() if t.get("descriptor", "URL") == "URL"]
|
url_dicts = [t for t in tracks_map.values() if t.get("descriptor", "URL") == "URL"]
|
||||||
# Merge back only tracks from another manifest, such as a separate HEVC one, or that
|
# Merge back only tracks from another manifest, such as a separate HEVC one, or that
|
||||||
# the snapshot keeps as a one-track fragment; the re-parse already covers manifest_url's
|
# the snapshot restores by id (a one-track fragment, another tree of the same URL); the
|
||||||
# own. Query stripped when comparing, since a service can sign the URL it fetches and
|
# re-parse already covers the rest. Query stripped when comparing, since a service can
|
||||||
# register the bare one for the same manifest.
|
# sign the URL it fetches and register the bare one for the same manifest.
|
||||||
manifest_base = str(manifest_url).split("?")[0]
|
manifest_base = str(manifest_url).split("?")[0]
|
||||||
fragments = snapshot.fragment_ids(entry.get("snapshot"))
|
fragments = snapshot.restored_ids(entry.get("snapshot"), str(manifest_url))
|
||||||
foreign_dicts = [
|
foreign_dicts = [
|
||||||
t
|
t
|
||||||
for t in tracks_map.values()
|
for t in tracks_map.values()
|
||||||
|
|||||||
@@ -55,13 +55,11 @@ def restore(tracks: Tracks, snapshot: Any, language: Any = None) -> None:
|
|||||||
def parse(snapshot: Any, url: str, language: Any = None) -> Tracks | None:
|
def parse(snapshot: Any, url: str, language: Any = None) -> Tracks | None:
|
||||||
"""Every track of the saved whole manifest for ``url``, with its filtered periods, else None.
|
"""Every track of the saved whole manifest for ``url``, with its filtered periods, else None.
|
||||||
|
|
||||||
The URL also matches without its query, since a service can sign the URL it fetches. A saved
|
The URL also matches without its query, since a service can sign the URL it fetches. Of several
|
||||||
|
trees of one URL this is the largest; ``restored_ids`` names the tracks of the others. A saved
|
||||||
manifest that does not parse gives None, so the caller can fetch the manifest instead.
|
manifest that does not parse gives None, so the caller can fetch the manifest instead.
|
||||||
"""
|
"""
|
||||||
saved = [m for m in entries(snapshot, "manifests") if isinstance(m.get("url"), str)]
|
entry = whole_manifest(snapshot, url)
|
||||||
entry = next((m for m in saved if m["url"] == url), None) or next(
|
|
||||||
(m for m in saved if m["url"].split("?")[0] == url.split("?")[0]), None
|
|
||||||
)
|
|
||||||
if entry is None:
|
if entry is None:
|
||||||
return None
|
return None
|
||||||
try:
|
try:
|
||||||
@@ -74,9 +72,31 @@ def parse(snapshot: Any, url: str, language: Any = None) -> Tracks | None:
|
|||||||
return tracks if tracks is not None and list(tracks) else None
|
return tracks if tracks is not None and list(tracks) else None
|
||||||
|
|
||||||
|
|
||||||
def fragment_ids(snapshot: Any) -> set[str]:
|
def whole_manifest(snapshot: Any, url: str) -> dict[str, Any] | None:
|
||||||
"""The ids of the tracks the snapshot holds a one-track fragment for."""
|
"""The entry ``parse`` reads: the first saved whole manifest of ``url``, else of ``url`` without its query."""
|
||||||
return {str(e["track_id"]) for e in entries(snapshot, "track_manifests") if e.get("track_id") is not None}
|
saved = [m for m in entries(snapshot, "manifests") if isinstance(m.get("url"), str)]
|
||||||
|
return next((m for m in saved if m["url"] == url), None) or next(
|
||||||
|
(m for m in saved if m["url"].split("?")[0] == url.split("?")[0]), None
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def restored_ids(snapshot: Any, url: str) -> set[str]:
|
||||||
|
"""The ids of the tracks that ``restore`` binds by id and ``parse(snapshot, url)`` does not give.
|
||||||
|
|
||||||
|
These are the tracks with a one-track fragment and the tracks of each other saved whole manifest.
|
||||||
|
"""
|
||||||
|
picked = whole_manifest(snapshot, url)
|
||||||
|
ids = {str(e["track_id"]) for e in entries(snapshot, "track_manifests") if e.get("track_id") is not None}
|
||||||
|
for entry in entries(snapshot, "manifests"):
|
||||||
|
if entry is not picked:
|
||||||
|
ids |= track_ids(entry)
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def track_ids(entry: dict[str, Any]) -> set[str]:
|
||||||
|
"""The ids of the tracks a whole-manifest entry restores; an entry from an older capture names none."""
|
||||||
|
ids = entry.get("track_ids")
|
||||||
|
return set(map(str, ids)) if isinstance(ids, list) else set()
|
||||||
|
|
||||||
|
|
||||||
def entries(snapshot: Any, key: str) -> list[dict[str, Any]]:
|
def entries(snapshot: Any, key: str) -> list[dict[str, Any]]:
|
||||||
@@ -120,12 +140,14 @@ def counted(manifest: Any, tag: str, counts: dict[int, int]) -> int:
|
|||||||
|
|
||||||
|
|
||||||
def whole_manifests(tracks: Tracks, level: int, counts: dict[int, int]) -> list[dict[str, Any]]:
|
def whole_manifests(tracks: Tracks, level: int, counts: dict[int, int]) -> list[dict[str, Any]]:
|
||||||
"""One entry per manifest URL, and for DASH its filtered period ids.
|
"""One entry per manifest tree of each URL, with the ids of its tracks, and for DASH its filtered period ids.
|
||||||
|
|
||||||
When tracks of one URL point at different trees (a one-track fragment restored on a remote
|
One URL can hold several trees (a service that merges a second manifest under it), so each entry
|
||||||
client, or a tree a service built for one track), capture saves the tree with the most tracks.
|
names the tracks it restores. A tree whose every track has a one-track fragment (a fragment
|
||||||
|
restored on a remote client) is left out when another tree holds its URL. Capture saves equal trees
|
||||||
|
once, and the largest tree of a URL first, which is the one a reader that takes only the first entry expects.
|
||||||
"""
|
"""
|
||||||
best: dict[str, tuple[int, str, dict[str, Any]]] = {}
|
trees: dict[str, dict[int, dict[str, Any]]] = {}
|
||||||
for track in tracks:
|
for track in tracks:
|
||||||
if not track.url:
|
if not track.url:
|
||||||
continue
|
continue
|
||||||
@@ -136,19 +158,38 @@ def whole_manifests(tracks: Tracks, level: int, counts: dict[int, int]) -> list[
|
|||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
continue
|
continue
|
||||||
url = str(track.url)
|
tree = trees.setdefault(str(track.url), {}).setdefault(
|
||||||
if url not in best or size > best[url][0]:
|
id(data["manifest"]), {"kind": kind, "data": data, "size": size, "ids": [], "fragmented": True}
|
||||||
best[url] = (size, kind, data)
|
)
|
||||||
|
tree["ids"].append(str(track.id))
|
||||||
|
tree["fragmented"] = tree["fragmented"] and has_fragment(data, counts)
|
||||||
|
|
||||||
out: list[dict[str, Any]] = []
|
out: list[dict[str, Any]] = []
|
||||||
for url, (_, kind, data) in best.items():
|
for url, by_tree in trees.items():
|
||||||
entry: dict[str, Any] = {"type": kind, "url": url, "data": pack(data["manifest"], level)}
|
group = sorted(by_tree.values(), key=lambda t: t["size"], reverse=True)
|
||||||
if kind == "dash":
|
saved: dict[tuple[Any, ...], dict[str, Any]] = {}
|
||||||
entry["filtered_period_ids"] = list(data.get("filtered_period_ids") or [])
|
for tree in [t for t in group if not t["fragmented"]] or group[:1]:
|
||||||
out.append(entry)
|
kind, data = tree["kind"], tree["data"]
|
||||||
|
raw = etree.tostring(data["manifest"], xml_declaration=True, encoding="UTF-8")
|
||||||
|
periods = list(data.get("filtered_period_ids") or []) if kind == "dash" else None
|
||||||
|
key = (kind, raw, *(periods or []))
|
||||||
|
if key not in saved:
|
||||||
|
saved[key] = {"type": kind, "url": url, "data": deflate(raw, level), "track_ids": []}
|
||||||
|
if periods is not None:
|
||||||
|
saved[key]["filtered_period_ids"] = periods
|
||||||
|
saved[key]["track_ids"] += tree["ids"]
|
||||||
|
out += saved.values()
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def has_fragment(dash: dict[str, Any], counts: dict[int, int]) -> bool:
|
||||||
|
"""Whether ``fragments`` saves a one-track MPD for a track with this DASH data."""
|
||||||
|
manifest, adaptation_set = dash.get("manifest"), dash.get("adaptation_set")
|
||||||
|
if manifest is None or adaptation_set is None:
|
||||||
|
return False
|
||||||
|
return adaptation_set.getroottree().getroot() is not manifest or counted(manifest, ".//Representation", counts) <= 1
|
||||||
|
|
||||||
|
|
||||||
def one_track_period(period: Any, adaptation_set: Any, representation: Any) -> Any:
|
def one_track_period(period: Any, adaptation_set: Any, representation: Any) -> Any:
|
||||||
"""A copy of ``period`` that holds only this AdaptationSet, cut to ``representation`` when there is one."""
|
"""A copy of ``period`` that holds only this AdaptationSet, cut to ``representation`` when there is one."""
|
||||||
new_period = etree.Element("Period", dict(period.attrib) if period is not None else {})
|
new_period = etree.Element("Period", dict(period.attrib) if period is not None else {})
|
||||||
@@ -175,12 +216,10 @@ def fragments(tracks: Tracks, level: int, counts: dict[int, int]) -> list[dict[s
|
|||||||
out: list[dict[str, Any]] = []
|
out: list[dict[str, Any]] = []
|
||||||
for track in tracks:
|
for track in tracks:
|
||||||
dash = track.data.get("dash") or {}
|
dash = track.data.get("dash") or {}
|
||||||
manifest = dash.get("manifest")
|
if not has_fragment(dash, counts):
|
||||||
adaptation_set = dash.get("adaptation_set")
|
|
||||||
if manifest is None or adaptation_set is None:
|
|
||||||
continue
|
|
||||||
if adaptation_set.getroottree().getroot() is manifest and counted(manifest, ".//Representation", counts) > 1:
|
|
||||||
continue
|
continue
|
||||||
|
manifest = dash["manifest"]
|
||||||
|
adaptation_set = dash["adaptation_set"]
|
||||||
|
|
||||||
root = etree.Element("MPD", dict(manifest.attrib))
|
root = etree.Element("MPD", dict(manifest.attrib))
|
||||||
for child in manifest:
|
for child in manifest:
|
||||||
@@ -326,12 +365,17 @@ def has_data(track: Any) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def restore_manifests(tracks: Tracks, saved: list[dict[str, Any]], budget: list[int], fallback: Any = None) -> None:
|
def restore_manifests(tracks: Tracks, saved: list[dict[str, Any]], budget: list[int], fallback: Any = None) -> None:
|
||||||
"""Re-parse each whole manifest and copy ``data`` to the tracks that match, by id or by attributes."""
|
"""Re-parse each whole manifest and copy ``data`` to the tracks that match, by id or by attributes.
|
||||||
|
|
||||||
|
A track that an entry's ``track_ids`` names matches only in that entry's tree. A snapshot
|
||||||
|
from an older capture names none, and an entry that does not parse binds none, so those
|
||||||
|
tracks match in every tree.
|
||||||
|
"""
|
||||||
targets = [t for t in tracks if not has_data(t)]
|
targets = [t for t in tracks if not has_data(t)]
|
||||||
if not targets:
|
if not targets:
|
||||||
return
|
return
|
||||||
language = next((t.language for t in tracks if t.language and str(t.language) != "und"), fallback)
|
language = next((t.language for t in tracks if t.language and str(t.language) != "und"), fallback)
|
||||||
parsed: list[Any] = []
|
parsed: list[tuple[set[str], list[Any]]] = []
|
||||||
for entry in saved:
|
for entry in saved:
|
||||||
if not isinstance(entry.get("data"), str) or not isinstance(entry.get("url"), str):
|
if not isinstance(entry.get("data"), str) or not isinstance(entry.get("url"), str):
|
||||||
continue
|
continue
|
||||||
@@ -340,11 +384,12 @@ def restore_manifests(tracks: Tracks, saved: list[dict[str, Any]], budget: list[
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.warning("Failed to re-parse %s manifest from %s: %s", entry.get("type"), entry.get("url"), e)
|
log.warning("Failed to re-parse %s manifest from %s: %s", entry.get("type"), entry.get("url"), e)
|
||||||
continue
|
continue
|
||||||
if local is not None:
|
parsed.append((track_ids(entry), list(local or [])))
|
||||||
parsed += list(local)
|
every = [t for _, local_tracks in parsed for t in local_tracks]
|
||||||
|
|
||||||
for track in targets:
|
for track in targets:
|
||||||
matched = match_track(track, parsed)
|
own = next((local_tracks for ids, local_tracks in parsed if str(track.id) in ids), every)
|
||||||
|
matched = match_track(track, own)
|
||||||
if matched and has_data(matched):
|
if matched and has_data(matched):
|
||||||
track.data.update(matched.data)
|
track.data.update(matched.data)
|
||||||
track.descriptor = matched.descriptor
|
track.descriptor = matched.descriptor
|
||||||
|
|||||||
Reference in New Issue
Block a user