Compare commits

...
4 Commits
Author SHA1 Message Date
imSp4rky 0c58575a5b perf(dash): collapse single-file tracks that have a sidx gap 2026-10-25 13:23:53 -06:00
imSp4rky 43fcb030f8 fix(tracks): read sidx boxes with struct so concurrent tracks parse correctly 2026-10-25 13:22:08 -06:00
imSp4rky 2dc458f8b4 fix(subtitle): rebase live-clock dash webvtt cues by presentationTimeOffset
Live-to-VOD replays carry cue times on the live media clock, which overflowed the SRT conversion and dropped every cue.
2026-10-25 13:15:34 -06:00
imSp4rky cb2ffdb55a fix(tunnel): accept fake-ip dns answers for --local-proxy host names
A TUN-mode VPN with fake-IP DNS answers names from 198.18.0.0/15 or 2001:2::/48, which the LAN guard refused, so every dial failed. Refused hosts now warn once.
2026-10-25 12:22:28 -06:00
12 changed files with 307 additions and 112 deletions
+5
View File
@@ -318,6 +318,11 @@ The service traffic stays encrypted from the server to the service, so the clien
encrypted bytes. The client refuses to connect to `localhost`, and to a host name or IP address
that resolves only to a loopback, private or link-local address, so the server cannot reach
your local network.
A VPN or proxy app in TUN mode with fake-IP DNS answers a host name with an address from
`198.18.0.0/15` or `2001:2::/48` and maps it back to the real host. The client accepts that
address for a host name, but not as an IP address from the server. An app set to a different
fake-IP range does not work with `--local-proxy`. With fake-IP DNS, the client cannot see the
real address of a host name, so it cannot stop a host name that points into your local network.
!!! note "Each request crosses the tunnel twice"
A request from the server goes to your machine and then to the service, so it takes
+2 -2
View File
@@ -34,7 +34,7 @@ STREAMS: list[tuple[str, str]] = [
("sony-1a", "https://dash.akamaized.net/dash264/TestCases/1a/sony/SNE_DASH_SD_CASE1A_REVISED.mpd"),
]
guard_results: list[bool] = []
guard_results: list[Optional[tuple[int, int]]] = []
def install_guard_spy() -> bool:
@@ -43,7 +43,7 @@ def install_guard_spy() -> bool:
if orig is None:
return False
def spy(is_subtitle: bool, segments: Any, init_len: Optional[int]) -> bool:
def spy(is_subtitle: bool, segments: Any, init_len: int) -> Optional[tuple[int, int]]:
result = orig(is_subtitle, segments, init_len)
guard_results.append(result)
return result
+10 -11
View File
@@ -4,15 +4,13 @@ resource instead of per-segment files + merge."""
from __future__ import annotations
from typing import Optional
from unshackle.core.manifests import DASH
URL = "https://cdn/media.mp4"
def collapsible(segments, init_len: Optional[int], is_subtitle: bool = False) -> bool:
return DASH.collapsible_single_url(is_subtitle, segments, init_len)
def collapsible(segments, init_len: int, is_subtitle: bool = False) -> bool:
return DASH.collapsible_single_url(is_subtitle, segments, init_len) is not None
def test_segmentbase_single_range_eligible():
@@ -29,10 +27,6 @@ def test_subtitle_never_eligible():
assert collapsible([(URL, "863-999999")], init_len=863, is_subtitle=True) is False
def test_missing_init_len_ineligible():
assert collapsible([(URL, "863-999999")], init_len=None) is False
def test_missing_range_ineligible():
assert collapsible([(URL, None)], init_len=863) is False
assert collapsible([(URL, "863-1999"), (URL, None)], init_len=863) is False
@@ -43,9 +37,14 @@ def test_mixed_urls_ineligible():
assert collapsible(segments, init_len=863) is False
def test_first_segment_gap_after_init_ineligible():
# first media byte does not immediately follow the init prefix
assert collapsible([(URL, "900-1999")], init_len=863) is False
def test_first_segment_gap_after_init_left_to_prefix_check():
# the gap may be the sidx; single_url_prefix_matches decides from the bytes
segments = [(URL, "900-1999"), (URL, "2000-2999")]
assert DASH.collapsible_single_url(False, segments, 863) == (900, 2999)
def test_first_segment_inside_init_ineligible():
assert collapsible([(URL, "800-1999")], init_len=863) is False
def test_gap_between_segments_ineligible():
+85 -44
View File
@@ -18,6 +18,7 @@ localhost server, asserting that:
from __future__ import annotations
import shutil
import struct
import threading
from functools import partial
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -99,48 +100,6 @@ def base(srv) -> str:
return f"http://127.0.0.1:{srv.server_address[1]}/"
def collapse_mpd(srv) -> str:
# SegmentList on one media.mp4: init is bytes [0, INIT_LEN), media ranges cover the rest
# contiguously -> collapsible_single_url returns the URL and download_track collapses.
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>
<Period id="0">
<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 range="0-{INIT_LEN - 1}"/>
<SegmentURL mediaRange="{INIT_LEN}-5119"/>
<SegmentURL mediaRange="5120-{len(PARENT) - 1}"/>
</SegmentList>
</Representation>
</AdaptationSet>
</Period>
</MPD>"""
def clipped_mpd(srv) -> str:
# same parent, but the ranges stop short of its end -> the collapsed file must be trimmed
# to the last indexed byte, not left holding the parent's trailing bytes.
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>
<Period id="0">
<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 range="0-{INIT_LEN - 1}"/>
<SegmentURL mediaRange="{INIT_LEN}-5119"/>
<SegmentURL mediaRange="5120-{CLIP_END}"/>
</SegmentList>
</Representation>
</AdaptationSet>
</Period>
</MPD>"""
def mixed_mpd(srv) -> str:
# Two SegmentURLs on distinct paths -> mixed URLs -> predicate False -> segmented path.
return f"""<?xml version="1.0"?>
@@ -160,6 +119,33 @@ def mixed_mpd(srv) -> str:
</MPD>"""
def sidx_box(sizes: list[int]) -> bytes:
# version 0 sidx: one MEDIA reference per size, each starting with a SAP
refs = b"".join(struct.pack(">III", size, 1, 0x90000000) for size in sizes)
body = struct.pack(">IIIIIHH", 0, 1, 1, 0, 0, 0, len(sizes)) + refs
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)
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>
<Period id="0">
<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>
</Representation>
</AdaptationSet>
</Period>
</MPD>"""
def make_track(mpd: str, srv):
return DASH.from_text(mpd, url=f"{base(srv)}manifest.mpd").to_tracks(language="en").videos[0]
@@ -174,7 +160,7 @@ def make_ctx(tmp_path, name="out.mp4"):
def test_collapse_downloads_parent_whole_in_one_direct_request(server, tmp_path):
server.routes["/media.mp4"] = PARENT
track = make_track(collapse_mpd(server), server)
track = make_track(ranged_mpd(server, [(INIT_LEN, 5119), (5120, len(PARENT) - 1)]), server)
ctx = make_ctx(tmp_path, "collapsed.mp4")
DASH.download_track(track, ctx)
@@ -194,7 +180,8 @@ def test_collapse_downloads_parent_whole_in_one_direct_request(server, tmp_path)
def test_collapse_trims_parent_bytes_past_the_last_segment(server, tmp_path):
server.routes["/media.mp4"] = PARENT
track = make_track(clipped_mpd(server), server)
# the ranges stop short of the parent's end, so the collapsed file must be trimmed
track = make_track(ranged_mpd(server, [(INIT_LEN, 5119), (5120, CLIP_END)]), server)
ctx = make_ctx(tmp_path, "clipped.mp4")
DASH.download_track(track, ctx)
@@ -203,6 +190,60 @@ def test_collapse_trims_parent_bytes_past_the_last_segment(server, tmp_path):
assert ctx.save_path.read_bytes() == PARENT[: CLIP_END + 1]
def test_collapse_keeps_the_sidx_between_init_and_first_segment(server, tmp_path):
media = [bytes([0xC0]) * 3000, bytes([0xD1]) * 2000]
head = PARENT[:INIT_LEN] + sidx_box([len(m) for m in media])
parent = head + b"".join(media)
server.routes["/media.mp4"] = parent
ranges = [(len(head), len(head) + 2999), (len(head) + 3000, len(parent) - 1)]
ctx = make_ctx(tmp_path, "sidx.mp4")
DASH.download_track(make_track(ranged_mpd(server, ranges), server), ctx)
assert ctx.save_path.read_bytes() == parent
assert [path for path, rng in server.requests if rng is None] == ["/media.mp4"]
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)
media = bytes([0xC0]) * 3000
server.routes["/media.mp4"] = PARENT[:INIT_LEN] + gap + media
start = INIT_LEN + len(gap)
ctx = make_ctx(tmp_path, "gap.mp4")
DASH.download_track(make_track(ranged_mpd(server, [(start, start + 2999)]), server), ctx)
assert ctx.save_path.read_bytes() == PARENT[:INIT_LEN] + media
assert not [path for path, rng in server.requests if rng is None]
def test_sidx_indexing_more_than_the_listed_segments_takes_segmented_path(server, tmp_path):
# the file carries a post-roll after the listed segments, and the sidx indexes it too
media, post_roll = bytes([0xC0]) * 3000, bytes([0xEE]) * 500
head = PARENT[:INIT_LEN] + sidx_box([len(media), len(post_roll)])
server.routes["/media.mp4"] = head + media + post_roll
ctx = make_ctx(tmp_path, "post-roll.mp4")
DASH.download_track(make_track(ranged_mpd(server, [(len(head), len(head) + 2999)]), server), ctx)
assert ctx.save_path.read_bytes() == PARENT[:INIT_LEN] + media
def test_init_from_another_file_takes_segmented_path(server, tmp_path):
# the media ranges start where an init of the same length would end, but the init is elsewhere
init = bytes([0x11]) * INIT_LEN
server.routes["/init.bin"] = init
server.routes["/media.mp4"] = PARENT
ranges = [(INIT_LEN, 5119), (5120, len(PARENT) - 1)]
ctx = make_ctx(tmp_path, "init-elsewhere.mp4")
DASH.download_track(make_track(ranged_mpd(server, ranges, init='sourceURL="init.bin"'), server), ctx)
assert ctx.save_path.read_bytes() == init + PARENT[INIT_LEN:]
assert not [path for path, rng in server.requests if rng is None and path == "/media.mp4"]
def test_non_collapse_takes_segmented_merge_path(server, tmp_path):
server.routes["/init.bin"] = INIT2
server.routes["/part0.bin"] = PART0
+47 -4
View File
@@ -28,6 +28,7 @@ from unshackle.core.tunnel import (
TunnelClient,
connect_public,
frame,
is_fake_ip,
is_public_ip,
tunnel_proxy,
)
@@ -106,24 +107,66 @@ def test_the_client_refuses_a_target_on_its_own_network(server: str, target: int
@pytest.mark.parametrize(
("address", "public"),
[("8.8.8.8", True), ("127.0.0.1", False), ("192.168.1.10", False), ("10.0.0.1", False), ("::1", False)],
[
("8.8.8.8", True),
("127.0.0.1", False),
("192.168.1.10", False),
("10.0.0.1", False),
("::1", False),
("198.18.2.36", False),
],
)
def test_is_public_ip(address: str, public: bool) -> None:
assert is_public_ip(address) is public
@pytest.mark.parametrize(
("address", "fake"),
[
("198.18.2.36", True),
("198.19.255.1", True),
("198.20.0.1", False),
("::ffff:198.18.0.1", False),
("2001:2::1", True),
("2001:2:1::1", False),
("fdfe:dcba:9876::1", False),
],
)
def test_is_fake_ip(address: str, fake: bool) -> None:
assert is_fake_ip(address) is fake
def test_a_name_that_resolves_to_a_fake_ip_is_dialled(monkeypatch: pytest.MonkeyPatch) -> None:
async def resolve(self: object, host: str, port: int, **_: object) -> list:
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("198.18.2.36", port))]
dialled: list[str] = []
async def open_connection(address: str, port: int) -> tuple:
dialled.append(address)
return None, None
monkeypatch.setattr(asyncio.BaseEventLoop, "getaddrinfo", resolve)
monkeypatch.setattr(asyncio, "open_connection", open_connection)
asyncio.run(connect_public("api.example", 443))
assert dialled == ["198.18.2.36"]
def test_localhost_is_refused() -> None:
with pytest.raises(PermissionError):
asyncio.run(connect_public("localhost", 443))
def test_a_name_that_resolves_to_a_local_address_is_refused(monkeypatch: pytest.MonkeyPatch) -> None:
@pytest.mark.parametrize(("host", "address"), [("rebind.example", "192.168.1.1"), ("198.18.0.1", "198.18.0.1")])
def test_a_target_that_resolves_to_a_local_address_is_refused(
monkeypatch: pytest.MonkeyPatch, host: str, address: str
) -> None:
async def resolve(self: object, host: str, port: int, **_: object) -> list:
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("192.168.1.1", port))]
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (address, port))]
monkeypatch.setattr(asyncio.BaseEventLoop, "getaddrinfo", resolve)
with pytest.raises(PermissionError):
asyncio.run(connect_public("rebind.example", 443))
asyncio.run(connect_public(host, 443))
def local_proxy_ctx(params: dict, typed: set) -> click.Context:
+18
View File
@@ -345,6 +345,24 @@ def test_parse_sidx_refuses_what_it_cannot_cut() -> None:
assert parse_sidx(sidx_box(count=3)[:-4], 0) == (0, [])
def test_parse_sidx_is_right_when_tracks_parse_at_the_same_time() -> None:
boxes = {758: sidx_box(count=758), 1408: sidx_box(count=1408, size=500)}
wrong: list[int] = []
def parse(count: int) -> None:
for _ in range(100):
if len(parse_sidx(boxes[count], 0)[1]) != count:
wrong.append(count)
threads = [threading.Thread(target=parse, args=(count,)) for count in (758, 1408, 758, 1408)]
for thread in threads:
thread.start()
for thread in threads:
thread.join(timeout=30)
assert not wrong
assert not any(thread.is_alive() for thread in threads)
def test_parse_sidx_refuses_a_box_that_counts_more_references_than_it_holds() -> None:
box = bytearray(sidx_box(count=3))
box[30:32] = (5).to_bytes(2, "big")
+14 -1
View File
@@ -10,7 +10,7 @@ survive, while duplicate headers collapse and boundary-duplicate cues dedupe.
from __future__ import annotations
from unshackle.core.utils.webvtt import merge_segmented_webvtt
from unshackle.core.utils.webvtt import merge_segmented_webvtt, rebase_webvtt, timestamp_ms
# Two segments, each a full WebVTT document with its own X-TIMESTAMP-MAP header,
# as they arrive concatenated from a DASH/HLS subtitle stream. The first cue carries
@@ -118,3 +118,16 @@ def test_merge_skips_malformed_timing_line():
out = merge_segmented_webvtt(vtt)
assert "Good" in out
assert "Broken" not in out
def test_rebase_moves_live_clock_cues_to_zero():
vtt = "WEBVTT\n\n498024:05:44.300 --> 498024:05:44.829 line:0.01%\nText\n"
out = rebase_webvtt(vtt, timestamp_ms("498024:00:14.700"))
assert "00:05:29.600 --> 00:05:30.129 line:0.01%\nText" in out
def test_rebase_leaves_presentation_time_cues_alone():
# a second pass, or a VOD period with a non-zero offset, must not shift again
vtt = "WEBVTT\n\n00:05:29.600 --> 00:05:30.129\nText\n"
assert rebase_webvtt(vtt, 1_792_886_414_700) == vtt
assert rebase_webvtt(vtt, 0) == vtt
+55 -26
View File
@@ -40,6 +40,7 @@ from unshackle.core.tracks.track import (
)
from unshackle.core.utilities import is_close_match, log_event, try_ensure_utf8
from unshackle.core.utils import run_proxy
from unshackle.core.utils.bitrate import ranged_get
from unshackle.core.utils.redact import safe_display_url
from unshackle.core.utils.xml import load_xml
@@ -558,14 +559,17 @@ class DASH:
downloader = track.downloader
# When every segment is a byte range of one parent resource and init is its [0, len)
# prefix, the whole resource is itself a valid MP4, so one direct download to save_path
# replaces the per-segment files, init write and merge pass.
collapse_single_url = not config.sample and DASH.collapsible_single_url(
isinstance(track, Subtitle),
segments,
len(init_data) if init_data is not None else None,
# A parent resource that is itself a valid MP4 downloads in one pass to save_path,
# replacing the per-segment files, init write and merge pass.
collapse_span = (
DASH.collapsible_single_url(isinstance(track, Subtitle), segments, len(init_data))
if init_data is not None and not config.sample
else None
)
if collapse_span and init_data:
if not DASH.single_url_prefix_matches(session, segments[0][0], collapse_span, init_data):
collapse_span = None
collapse_single_url = collapse_span is not None
use_segment_decrypt = not collapse_single_url and bool(init_data) and can_use(drm, config.decryption)
# subtitle segments are tiny, the post-download merge costs nothing there
@@ -674,9 +678,9 @@ class DASH:
save_path.unlink(missing_ok=True)
raise
if collapse_single_url:
if collapse_span:
with open(save_path, "r+b") as collapsed:
collapsed.truncate(int(segments[-1][1].split("-")[1]) + 1)
collapsed.truncate(collapse_span[1] + 1)
elif merger:
for control_file in save_dir.glob("*.!dev"):
control_file.unlink(missing_ok=True)
@@ -805,42 +809,67 @@ class DASH:
def collapsible_single_url(
is_subtitle: bool,
segments: list[tuple[str, Optional[str]]],
init_len: Optional[int],
) -> bool:
init_len: int,
) -> Optional[tuple[int, int]]:
"""
Whether every segment is a byte range of one parent resource whose [0, init_len)
prefix is the init segment, so unshackle can download the whole resource in one pass.
Get the first and last byte of the segments when every segment is a byte range of one
parent resource that follows an init of init_len bytes, so unshackle can download the
whole resource in one pass.
Returns False for subtitle tracks, an unknown init length, mixed URLs, malformed
ranges, and anything but one gapless run in document order starting at the init
prefix. A gap would pull bytes the segmented merge path excludes (a period the
manifest filters out) into the collapsed file, so it fails closed.
Returns None for subtitle tracks, mixed URLs, malformed ranges, and anything but one
gapless run in document order. A gap between segments would pull bytes the segmented
merge path excludes (a period the manifest filters out) into the collapsed file, so it
fails closed. A gap before the first segment passes here, and single_url_prefix_matches
must then prove that it is the index.
"""
if is_subtitle or init_len is None or not segments:
return False
if is_subtitle or not segments:
return None
first_url = segments[0][0]
ranges: list[tuple[int, int]] = []
for url, bytes_range in segments:
if url != first_url or not bytes_range:
return False
return None
parts = bytes_range.split("-")
if len(parts) != 2 or not parts[0] or not parts[1]:
return False
return None
try:
start, end = int(parts[0]), int(parts[1])
except ValueError:
return False
return None
if end < start:
return False
return None
ranges.append((start, end))
prev_end = init_len - 1
if ranges[0][0] < init_len:
return None
prev_end = ranges[0][0] - 1
for start, end in ranges:
if start != prev_end + 1:
return False
return None
prev_end = end
return True
return ranges[0][0], prev_end
@staticmethod
def single_url_prefix_matches(
session: Union[Session, RnetSession],
url: str,
span: tuple[int, int],
init_data: bytes,
) -> bool:
"""
Whether the resource at url starts with init_data and, when bytes sit between the init
and the first byte of span, whether they are one sidx that indexes exactly span.
Fetches the resource up to the start of span.
"""
first_start, last_end = span
head = ranged_get(url, session, f"bytes=0-{first_start - 1}")
if not head or len(head) != first_start or not head.startswith(init_data):
return False
if first_start == len(init_data):
return True
_, subsegments = parse_sidx(head[len(init_data) :], len(init_data))
return bool(subsegments) and subsegments[0][1] == first_start and subsegments[-1][2] == last_end
@staticmethod
def is_content_period(period: Element, filtered_period_ids: list[str]) -> bool:
+9 -1
View File
@@ -27,7 +27,7 @@ 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.utils.subprocess import log_tool_run
from unshackle.core.utils.webvtt import merge_segmented_webvtt
from unshackle.core.utils.webvtt import merge_segmented_webvtt, rebase_webvtt
# silence srt library INFO logging
logging.getLogger("srt").setLevel(logging.ERROR)
@@ -280,6 +280,14 @@ class Subtitle(Track):
text = self.path.read_text("utf8")
text = Subtitle.strip_webvtt_timestamp_map(text)
if self.descriptor == Track.Descriptor.DASH:
from unshackle.core.manifests import DASH
template = DASH.merge_segment_templates(
self.data["dash"]["adaptation_set"], self.data["dash"]["representation"]
)
if template is not None:
offset = template.get("presentationTimeOffset", "0")
text = rebase_webvtt(text, int(offset) * 1000 // int(template.get("timescale", "1")))
if len(self.data["dash"]["segment_durations"]) > 1:
text = merge_segmented_webvtt(
text,
+16 -16
View File
@@ -18,9 +18,7 @@ from uuid import UUID
from zlib import crc32
import click
from construct import ConstructError
from langcodes import Language
from pymp4.parser import Box
from requests import Session
from requests.adapters import HTTPAdapter, Retry
@@ -360,23 +358,25 @@ def parse_sidx(data: bytes, offset: int) -> tuple[int, list[tuple[int, int, int]
Returns the timescale and one (start time, first byte, last byte) for each subsegment. The list
is empty when the box is not a ``sidx`` or when it points at more indexes and not at media.
"""
# read by hand: pymp4's Box.parse gives wrong results when two threads parse at once
size, header = int.from_bytes(data[:4], "big"), 32 if data[8:9] == b"\x00" else 40
# pymp4 loops forever on a box that counts more references than its size holds
if data[4:8] != b"sidx" or size < header + 12 * int.from_bytes(data[header - 2 : header], "big"):
count = int.from_bytes(data[header - 2 : header], "big")
if data[4:8] != b"sidx" or len(data) < header or min(size, len(data)) < header + 12 * count:
return 0, []
try:
box = Box.parse(data)
except ConstructError:
return 0, []
if any(reference.reference_type != "MEDIA" for reference in box.references):
return 0, []
start, byte = box.earliest_presentation_time, offset + box.end + box.first_offset
if header == 32:
timescale, start, first_offset = struct.unpack_from(">III", data, 16)
else:
timescale, start, first_offset = struct.unpack_from(">IQQ", data, 16)
byte = offset + size + first_offset
subsegments: list[tuple[int, int, int]] = []
for reference in box.references:
subsegments.append((start, byte, byte + reference.referenced_size - 1))
start += reference.segment_duration
byte += reference.referenced_size
return box.timescale, subsegments
for i in range(count):
word, duration = struct.unpack_from(">II", data, header + 12 * i)
if word >> 31:
return 0, []
subsegments.append((start, byte, byte + (word & 0x7FFFFFFF) - 1))
start += duration
byte += word & 0x7FFFFFFF
return timescale, subsegments
@dataclass
+26 -6
View File
@@ -30,6 +30,7 @@ HEARTBEAT = 20
GRACE = 60
RELINK_WAIT = 10
OPEN_TIMEOUT = 15
FAKE_IP_POOLS = (ipaddress.ip_network("198.18.0.0/15"), ipaddress.ip_network("2001:2::/48"))
MAX_TUNNELS = 4
MAX_STREAMS = 256
CHUNK = 65536
@@ -282,20 +283,32 @@ async def close_tunnels(_: web.Application) -> None:
await tunnel.close()
def is_public_ip(address: str) -> bool:
def parse_ip(address: str) -> Optional[ipaddress.IPv4Address | ipaddress.IPv6Address]:
try:
return ipaddress.ip_address(address.partition("%")[0]).is_global
return ipaddress.ip_address(address.partition("%")[0])
except ValueError:
return False
return None
def is_public_ip(address: str) -> bool:
return (ip := parse_ip(address)) is not None and ip.is_global
def is_fake_ip(address: str) -> bool:
"""True for an address from a pool that fake-IP DNS in a TUN-mode VPN or proxy hands out for a name."""
return (ip := parse_ip(address)) is not None and any(ip in pool for pool in FAKE_IP_POOLS)
async def connect_public(host: str, port: int) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
"""Connect to the first public address of ``host``. The server picks the targets, so a name that resolves
only to the client's own machine or LAN is refused."""
only to the client's own machine or LAN is refused. A fake IP passes only when it comes from a name lookup:
the TUN maps it back to the real host, which the client cannot check."""
infos = await asyncio.get_running_loop().getaddrinfo(host, port, type=socket.SOCK_STREAM)
addresses = [info[4][0] for info in infos if is_public_ip(str(info[4][0]))]
resolved = [str(info[4][0]) for info in infos]
from_name = parse_ip(host) is None
addresses = [a for a in resolved if is_public_ip(a) or (from_name and is_fake_ip(a))]
if not addresses:
raise PermissionError(f"{host} resolves only to local addresses")
raise PermissionError(f"{host} resolves only to local addresses ({', '.join(resolved)})")
error: OSError = OSError(f"could not connect to {host}")
for address in addresses:
try:
@@ -316,6 +329,7 @@ class TunnelClient:
self.lost = False
self.ready = threading.Event()
self.relays: set[asyncio.Task[None]] = set()
self.refused: set[str] = set()
self.thread = threading.Thread(target=lambda: asyncio.run(self.run()), name="tunnel", daemon=True)
self.loop: Optional[asyncio.AbstractEventLoop] = None
self.task: Optional[asyncio.Task[None]] = None
@@ -401,6 +415,12 @@ class TunnelClient:
async def open(self, link: Link, sid: int, host: str, port: int) -> None:
try:
reader, writer = await connect_public(host, port)
except PermissionError as e:
if host not in self.refused: # the server retries, so warn once per host
self.refused.add(host)
log.warning(f"Tunnel refused {e}")
await link.close_stream(sid)
return
except (OSError, ValueError, asyncio.TimeoutError) as e: # the idna codec raises ValueError on a bad hostname
log.debug(f"Tunnel dial to {host}:{port} failed: {e}")
await link.close_stream(sid)
+20 -1
View File
@@ -1,8 +1,10 @@
import re
from typing import Optional
TIMESTAMP = r"(?:\d+:)?\d{2}:\d{2}\.\d{3}"
# Timing line: optional hours, verbatim settings tail.
TIMING = re.compile(r"^((?:\d+:)?\d{2}:\d{2}\.\d{3})[ \t]+-->[ \t]+((?:\d+:)?\d{2}:\d{2}\.\d{3})(.*)$")
TIMING = re.compile(rf"^({TIMESTAMP})[ \t]+-->[ \t]+({TIMESTAMP})(.*)$")
CUE_TIMES = re.compile(rf"(?m)^([ \t]*)({TIMESTAMP})([ \t]+-->[ \t]+)({TIMESTAMP})")
def timestamp_ms(ts: str) -> int:
@@ -75,3 +77,20 @@ def merge_segmented_webvtt(vtt_raw: str, segment_durations: Optional[list[int]]
blocks = headers + [f"{c[0]} --> {c[1]}{c[2]}\n{c[3]}" for c in cues]
return "WEBVTT\n\n" + "\n\n".join(blocks) + "\n"
def rebase_webvtt(text: str, offset_ms: int) -> str:
"""
Subtract offset_ms from every cue time when the cues sit on the media timeline of a DASH
period whose presentationTimeOffset is offset_ms, as a live replay's do. Cues that start
below the offset are already presentation times, so the text stays as it is.
"""
first = CUE_TIMES.search(text)
if offset_ms <= 0 or not first or timestamp_ms(first[2]) < offset_ms:
return text
def shift(ts: str) -> str:
ms = max(timestamp_ms(ts) - offset_ms, 0)
return f"{ms // 3_600_000:02}:{ms // 60_000 % 60:02}:{ms // 1000 % 60:02}.{ms % 1000:03}"
return CUE_TIMES.sub(lambda m: f"{m[1]}{shift(m[2])}{m[3]}{shift(m[4])}", text)