mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-24 18:05:07 +00:00
Compare commits
2
Commits
0c58575a5b
...
af2ec8112c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af2ec8112c | ||
|
|
8151946ec0 |
@@ -9,6 +9,8 @@ localhost server, asserting that:
|
||||
- a SegmentList whose ranges collapse fetches the parent resource whole in one direct
|
||||
(Range-less) request and writes a byte-correct file at ``save_path``, leaving no
|
||||
segment dir or ``.!dev`` artifacts, and
|
||||
- a SegmentBase track writes the parent byte for byte, when the server sends its total
|
||||
length and when it sends an unknown (``*``) one, and
|
||||
- a track with mixed segment URLs still takes the per-segment download-and-merge path, and
|
||||
- that same segmented path raises ``DownloadCancelled`` when a sibling track's failure has
|
||||
already set ``DOWNLOAD_CANCELLED``, instead of treating the segments the cancel left
|
||||
@@ -57,10 +59,12 @@ class _Handler(BaseHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
return
|
||||
if rng:
|
||||
start, end = (int(x) for x in rng.removeprefix("bytes=").split("-"))
|
||||
first, _, last = rng.removeprefix("bytes=").partition("-")
|
||||
start, end = int(first), int(last) if last else len(body) - 1
|
||||
chunk = body[start : end + 1]
|
||||
self.send_response(206)
|
||||
self.send_header("Content-Range", f"bytes {start}-{end}/{len(body)}")
|
||||
total = "*" if server.unknown_total else len(body)
|
||||
self.send_header("Content-Range", f"bytes {start}-{end}/{total}")
|
||||
body = chunk
|
||||
else:
|
||||
self.send_response(200)
|
||||
@@ -78,6 +82,7 @@ def server():
|
||||
srv.lock = threading.Lock()
|
||||
srv.requests = []
|
||||
srv.routes = {}
|
||||
srv.unknown_total = False
|
||||
thread = threading.Thread(target=srv.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
yield srv
|
||||
@@ -126,9 +131,8 @@ def sidx_box(sizes: list[int]) -> bytes:
|
||||
return struct.pack(">I", 8 + len(body)) + b"sidx" + body
|
||||
|
||||
|
||||
def ranged_mpd(srv, ranges: list[tuple[int, int]], init: str = f'range="0-{INIT_LEN - 1}"') -> str:
|
||||
# SegmentList of byte ranges on one media.mp4, with the given Initialization attributes
|
||||
segment_urls = "\n".join(f' <SegmentURL mediaRange="{s}-{e}"/>' for s, e in ranges)
|
||||
def media_mpd(srv, segments: str) -> str:
|
||||
# one Representation on media.mp4, described by the given segment element
|
||||
return f"""<?xml version="1.0"?>
|
||||
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011">
|
||||
<BaseURL>{base(srv)}</BaseURL>
|
||||
@@ -136,16 +140,35 @@ def ranged_mpd(srv, ranges: list[tuple[int, int]], init: str = f'range="0-{INIT_
|
||||
<AdaptationSet contentType="video" mimeType="video/mp4" lang="en">
|
||||
<Representation id="v0" codecs="avc1.640028" bandwidth="1000000" width="1920" height="1080">
|
||||
<BaseURL>media.mp4</BaseURL>
|
||||
<SegmentList timescale="1">
|
||||
<Initialization {init}/>
|
||||
{segment_urls}
|
||||
</SegmentList>
|
||||
{segments}
|
||||
</Representation>
|
||||
</AdaptationSet>
|
||||
</Period>
|
||||
</MPD>"""
|
||||
|
||||
|
||||
def ranged_mpd(srv, ranges: list[tuple[int, int]], init: str = f'range="0-{INIT_LEN - 1}"') -> str:
|
||||
# SegmentList of byte ranges on one media.mp4, with the given Initialization attributes
|
||||
segment_urls = "\n".join(f' <SegmentURL mediaRange="{s}-{e}"/>' for s, e in ranges)
|
||||
return media_mpd(
|
||||
srv,
|
||||
f""" <SegmentList timescale="1">
|
||||
<Initialization {init}/>
|
||||
{segment_urls}
|
||||
</SegmentList>""",
|
||||
)
|
||||
|
||||
|
||||
def segment_base_mpd(srv) -> str:
|
||||
# the media range comes from the init response, not the manifest
|
||||
return media_mpd(
|
||||
srv,
|
||||
f""" <SegmentBase>
|
||||
<Initialization range="0-{INIT_LEN - 1}"/>
|
||||
</SegmentBase>""",
|
||||
)
|
||||
|
||||
|
||||
def make_track(mpd: str, srv):
|
||||
return DASH.from_text(mpd, url=f"{base(srv)}manifest.mpd").to_tracks(language="en").videos[0]
|
||||
|
||||
@@ -204,6 +227,27 @@ def test_collapse_keeps_the_sidx_between_init_and_first_segment(server, tmp_path
|
||||
assert [path for path, rng in server.requests if rng is None] == ["/media.mp4"]
|
||||
|
||||
|
||||
def test_segment_base_collapse_ends_at_the_last_byte(server, tmp_path):
|
||||
server.routes["/media.mp4"] = PARENT
|
||||
ctx = make_ctx(tmp_path, "segment_base.mp4")
|
||||
|
||||
DASH.download_track(make_track(segment_base_mpd(server), server), ctx)
|
||||
|
||||
# the media range ends at total - 1, so the truncate after the collapse adds no byte
|
||||
assert ctx.save_path.read_bytes() == PARENT
|
||||
|
||||
|
||||
def test_segment_base_unknown_total_fetches_the_rest_open_ended(server, tmp_path):
|
||||
server.routes["/media.mp4"] = PARENT
|
||||
server.unknown_total = True
|
||||
ctx = make_ctx(tmp_path, "unknown_total.mp4")
|
||||
|
||||
DASH.download_track(make_track(segment_base_mpd(server), server), ctx)
|
||||
|
||||
assert ctx.save_path.read_bytes() == PARENT
|
||||
assert ("/media.mp4", f"bytes={INIT_LEN}-") in server.requests
|
||||
|
||||
|
||||
def test_leading_gap_that_is_not_a_sidx_takes_segmented_path(server, tmp_path):
|
||||
# a filtered period cut from the same file leaves a gap of media, not an index
|
||||
gap = struct.pack(">I", 1000) + b"moof" + bytes(992)
|
||||
|
||||
@@ -185,6 +185,6 @@ def test_segment_base_range_survives_a_skipped_probe(server, probes):
|
||||
probe_kid=False,
|
||||
)
|
||||
|
||||
assert segments == [(f"{base(server)}p1.mp4", f"{INIT_LEN}-{len(MEDIA)}")]
|
||||
assert segments == [(f"{base(server)}p1.mp4", f"{INIT_LEN}-{len(MEDIA) - 1}")]
|
||||
assert track_kid is None
|
||||
assert not probes
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""get_boxes must give each thread its own box when tracks read their init segments at the same time."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
import threading
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from unshackle.core.utilities import get_boxes
|
||||
|
||||
|
||||
def tenc_init(kid: UUID, version: int, crypt_skip: int) -> bytes:
|
||||
body = struct.pack(">B3s", version, b"\0\0\0") + bytes([0, crypt_skip if version else 0]) + b"\x01\x10" + kid.bytes
|
||||
return b"\x00" * 8 + struct.pack(">I", 8 + len(body)) + b"tenc" + body
|
||||
|
||||
|
||||
def test_get_boxes_finds_the_tenc() -> None:
|
||||
kid = uuid4()
|
||||
(box,) = get_boxes(tenc_init(kid, 1, 0x19), b"tenc")
|
||||
assert box.key_ID == kid
|
||||
|
||||
|
||||
def test_get_boxes_is_right_when_tracks_parse_at_the_same_time() -> None:
|
||||
cases = [(uuid4(), version, crypt_skip) for version, crypt_skip in ((0, 0), (1, 0x19), (1, 0x91), (1, 0x55))] * 2
|
||||
failures: list[str] = []
|
||||
|
||||
def parse(kid: UUID, version: int, crypt_skip: int) -> None:
|
||||
data = tenc_init(kid, version, crypt_skip)
|
||||
for _ in range(1500):
|
||||
try:
|
||||
boxes = list(get_boxes(data, b"tenc"))
|
||||
except Exception as e:
|
||||
failures.append(repr(e))
|
||||
continue
|
||||
if [box.key_ID for box in boxes] != [kid]:
|
||||
failures.append("wrong or missing tenc")
|
||||
|
||||
threads = [threading.Thread(target=parse, args=case) for case in cases]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join(timeout=120)
|
||||
assert not failures, failures[:3]
|
||||
assert not any(thread.is_alive() for thread in threads)
|
||||
@@ -27,6 +27,7 @@ from requests import Session
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
|
||||
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 SegmentDecrypter, can_use
|
||||
from unshackle.core.drm.verify import decrypt_track
|
||||
@@ -1104,9 +1105,10 @@ class DASH:
|
||||
init_data = res.content
|
||||
if probe_kid:
|
||||
track_kid = track.get_key_id(init_data)
|
||||
total_size = res.headers.get("Content-Range", "").split("/")[-1]
|
||||
if total_size:
|
||||
media_range = f"{len(init_data)}-{total_size}"
|
||||
content_range = parse_content_range(res.headers.get("Content-Range"))
|
||||
if content_range:
|
||||
_, init_end, total = content_range
|
||||
media_range = f"{init_end + 1}-{'' if total is None else total - 1}"
|
||||
|
||||
subsegments: list[tuple[int, int, int]] = []
|
||||
index_range = segment_base.get("indexRange")
|
||||
|
||||
@@ -25,7 +25,7 @@ from subtitle_filter import Subtitles
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.tracks.track import Track
|
||||
from unshackle.core.utilities import try_ensure_utf8, with_script
|
||||
from unshackle.core.utilities import PYMP4_LOCK, try_ensure_utf8, with_script
|
||||
from unshackle.core.utils.subprocess import log_tool_run
|
||||
from unshackle.core.utils.webvtt import merge_segmented_webvtt, rebase_webvtt
|
||||
|
||||
@@ -737,10 +737,10 @@ class Subtitle(Track):
|
||||
caption_set = pycaption.SRTReader().read(text)
|
||||
elif codec == Subtitle.Codec.fTTML:
|
||||
caption_lists: dict[str, pycaption.CaptionList] = defaultdict(pycaption.CaptionList)
|
||||
with PYMP4_LOCK:
|
||||
boxes = MP4.parse_stream(BytesIO(data))
|
||||
for segment in (
|
||||
Subtitle.parse(box.data, Subtitle.Codec.TimedTextMarkupLang)
|
||||
for box in MP4.parse_stream(BytesIO(data))
|
||||
if box.type == b"mdat"
|
||||
Subtitle.parse(box.data, Subtitle.Codec.TimedTextMarkupLang) for box in boxes if box.type == b"mdat"
|
||||
):
|
||||
for lang in segment.get_languages():
|
||||
caption_lists[lang].extend(segment.get_captions(lang))
|
||||
@@ -923,7 +923,9 @@ class Subtitle(Track):
|
||||
child["type"] = child.get("type") or child.get("format")
|
||||
yield child
|
||||
|
||||
for box in flatten_boxes(MP4.parse_stream(BytesIO(data))):
|
||||
with PYMP4_LOCK:
|
||||
boxes = MP4.parse_stream(BytesIO(data))
|
||||
for box in flatten_boxes(boxes):
|
||||
# init
|
||||
if box.type == b"mdhd":
|
||||
timescale = box.timescale
|
||||
@@ -963,7 +965,8 @@ class Subtitle(Track):
|
||||
if not saw_trun_box:
|
||||
raise ValueError("The TRUN box was not found in the Segmented WebVTT.")
|
||||
|
||||
vttc_boxes = MP4.parse_stream(BytesIO(box.data))
|
||||
with PYMP4_LOCK:
|
||||
vttc_boxes = MP4.parse_stream(BytesIO(box.data))
|
||||
current_time = base_time + period_start
|
||||
|
||||
for sample, vttc_box in zip(samples, vttc_boxes):
|
||||
|
||||
@@ -9,6 +9,7 @@ import os
|
||||
import re
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
import unicodedata
|
||||
@@ -456,6 +457,11 @@ def resolve_sort_langs(
|
||||
return resolved
|
||||
|
||||
|
||||
# construct 2.8 gives each bit-field struct one shared stream, so two threads in a pymp4
|
||||
# parse or build of a box with bit fields (tenc, senc, trun, sidx, ...) read each other's bytes
|
||||
PYMP4_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def get_boxes(data: bytes, box_type: bytes, as_bytes: bool = False) -> Box: # type: ignore
|
||||
"""
|
||||
Scan a byte array for a wanted MP4/ISOBMFF box, then parse and yield each find.
|
||||
@@ -506,14 +512,13 @@ def get_boxes(data: bytes, box_type: bytes, as_bytes: bool = False) -> Box: # t
|
||||
box_start = pos - 4
|
||||
|
||||
try:
|
||||
box = Box.parse(data[box_start:])
|
||||
if as_bytes:
|
||||
box = Box.build(box)
|
||||
with PYMP4_LOCK:
|
||||
box = Box.parse(data[box_start:])
|
||||
built = Box.build(box)
|
||||
|
||||
yield box
|
||||
yield built if as_bytes else box
|
||||
|
||||
box_size = len(Box.build(box))
|
||||
offset = box_start + box_size
|
||||
offset = box_start + len(built)
|
||||
|
||||
except IOError:
|
||||
break
|
||||
|
||||
Reference in New Issue
Block a user