Spaces:
Running
Running
Z Agent commited on
Commit ·
4a90d00
1
Parent(s): 7cdd985
proxy: parallel-range segment booster (boost=1) + faithful error relay + EXT-X-MEDIA URI rewrite
Browse files- _boosted_segment: 4 concurrent Range fetches per big segment (>1MB) — acek-cdn
per-connection throttles ~450KB/s (token sp=500); parallel ranges verified
4x aggregate. Falls back to single-stream on any inconsistency.
- _proxy_do: upstream error statuses relayed BEFORE playlist handling — an HTML
error page on a .m3u8 URL is no longer rewritten into a fake 200 playlist.
- _m3u8_rewrite: URI= attributes (EXT-X-MEDIA audio tracks, i-frames) now
resolved against the upstream base and routed through the proxy — fixes
relative-audio-URI players resolving against the wrong base (404 loops).
257 unmodified lines2582592602612622632648 unmodified lines27327427527627727810 unmodified lines2892902912922932942959 unmodified lines30530630730830931026 unmodified lines33733833934034134230 unmodified lines373374375376377378379380381382383384385386387388389257 unmodified linesdef _m3u8_rewrite(content: str, base_url: str, ref: str = None, ua: str = None, origin: str = None) -> str:"""Rewrite every URI inside an m3u8 playlist to an absolute /proxy_range URL."""def _wrap(u: str) -> str:absu = urljoin(base_url, u)return _proxy_wrap(absu, ref, ua, origin)8 unmodified linesreturn f'URI="{_wrap(mm.group(1))}"'ls = re.sub(r'URI="([^"]+)"', key_uri, ls)out_lines.append(ls)elif ls.startswith("#"):out_lines.append(ls)else:10 unmodified linesreturn hasync def _proxy_do(u: str, ref: str, ua: str, origin: str, range_header: str = None, head_only: bool = False):headers = _proxy_headers(ref, ua, origin)if range_header:headers["Range"] = range_header9 unmodified linesctype = (resp.headers.get("content-type") or "application/octet-stream").lower()final_url = str(resp.url)# NOTE: never partially-buffer the body and try to resume - an abandoned httpx# async iterator closes the underlying stream. Playlist detection relies on the# final (post-redirect) URL and the upstream content-type, which covers every26 unmodified linesheaders={"Cache-Control": "no-cache", "Access-Control-Allow-Origin": "*"},)# binary stream (mp4/mkv/ts/segment): pipe with Range support# pass upstream errors through faithfully so players can fall backif resp.status_code not in (200, 206):30 unmodified lines@app.api_route("/proxy", methods=["GET", "HEAD"], include_in_schema=False)async def proxy_stream(u: str, ref: str = None, ua: str = None, origin: str = None, request: Request = None):"""Stream proxy (Range-capable, header-injecting, m3u8-rewriting)."""range_header = request.headers.get("range") if request is not None else Nonereturn await _proxy_do(u, ref, ua, origin, range_header, head_only=(request is not None and request.method == "HEAD"))@app.api_route("/proxy_range", methods=["GET", "HEAD"], include_in_schema=False)async def proxy_range(request: Request, u: str, ref: str = None, ua: str = None, origin: str = None):"""Proxy that honors the client's Range header (for players that seek)."""range_header = request.headers.get("range")return await _proxy_do(u, ref, ua, origin, range_header, head_only=(request.method == "HEAD"))# ---------- HubCloud family resolver (MediaVanced hubcloud.py, generalized) ----------257 unmodified lines2582592602612622632642652662672682692702718 unmodified lines28028128228328428528628728828929029129229310 unmodified lines3043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523539 unmodified lines36336436536636736836937037137237337437537637737837938038126 unmodified lines40840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246330 unmodified lines494495496497498499500501502503504505506507508509510257 unmodified linesdef _m3u8_rewrite(content: str, base_url: str, ref: str = None, ua: str = None, origin: str = None) -> str:"""Rewrite every URI inside an m3u8 playlist to an absolute /proxy_range URL.URI= attributes are rewritten too (not only KEY/MAP): multi-audio masters(e.g. m4uplay/acek) carry their audio track playlists in#EXT-X-MEDIA:...URI="index-a1.m3u8?..." attributes. Leaving them relativeused to break players that resolved them against the proxy URL instead ofthe upstream base (404 -> audioTrackLoadError retry loops -> the streamnever starts even though the languages parsed fine)."""def _wrap(u: str) -> str:absu = urljoin(base_url, u)return _proxy_wrap(absu, ref, ua, origin)8 unmodified linesreturn f'URI="{_wrap(mm.group(1))}"'ls = re.sub(r'URI="([^"]+)"', key_uri, ls)out_lines.append(ls)elif ls.startswith("#") and 'URI="' in ls:# #EXT-X-MEDIA (audio tracks), #EXT-X-I-FRAME-STREAM-INF, session-data# and any other tag carrying a URI= attribute: resolve it against the# upstream base and route it through this proxy, same as plain lines.def attr_uri(mm):return f'URI="{_wrap(mm.group(1))}"'ls = re.sub(r'URI="([^"]+)"', attr_uri, ls)out_lines.append(ls)elif ls.startswith("#"):out_lines.append(ls)else:10 unmodified linesreturn hasync def _boosted_segment(u: str, headers: dict, total: int, parts: int = 4):"""Fetch a binary segment as `parts` parallel HTTP Range requests andreassemble. Returns the full bytes on success, or None on ANY problem(caller falls back to the normal single-stream path). Segments arebounded (a few MB), so buffering the reassembled body is fine."""step = total // partsif step < 256 * 1024:return Nonebounds = []start = 0for i in range(parts):end = total - 1 if i == parts - 1 else start + step - 1bounds.append((start, end))start = end + 1async def fetch_range(s: int, e: int) -> bytes:c = httpx.AsyncClient(timeout=httpx.Timeout(90, connect=15), follow_redirects=True)try:h = dict(headers)h["Range"] = f"bytes={s}-{e}"req = c.build_request("GET", u, headers=h)r = await c.send(req, stream=True)if r.status_code != 206:await r.aclose()raise RuntimeError(f"range fetch status {r.status_code}")data = await r.aread()await r.aclose()if len(data) != e - s + 1:raise RuntimeError(f"range {s}-{e} gave {len(data)}B")return datafinally:await c.aclose()try:chunks = await asyncio.gather(*[fetch_range(s, e) for (s, e) in bounds])data = b"".join(chunks)if len(data) != total:return Nonereturn dataexcept Exception:return Noneasync def _proxy_do(u: str, ref: str, ua: str, origin: str, range_header: str = None, head_only: bool = False, boost: int = 0):headers = _proxy_headers(ref, ua, origin)if range_header:headers["Range"] = range_header9 unmodified linesctype = (resp.headers.get("content-type") or "application/octet-stream").lower()final_url = str(resp.url)# Upstream errors are relayed FAITHFULLY (status code + short body) BEFORE# any playlist handling: an HTML error page whose URL happens to end in# .m3u8 must NOT be rewritten into a fake 200 playlist - hls.js would parse# garbage forever and the player would spin instead of failing honestly.if resp.status_code not in (200, 206):try:err_body = (await resp.aread())[:400]finally:await resp.aclose()await client.aclose()return Response(content=err_body, status_code=resp.status_code,media_type="text/plain", headers={"Access-Control-Allow-Origin": "*"})# NOTE: never partially-buffer the body and try to resume - an abandoned httpx# async iterator closes the underlying stream. Playlist detection relies on the# final (post-redirect) URL and the upstream content-type, which covers every26 unmodified linesheaders={"Cache-Control": "no-cache", "Access-Control-Allow-Origin": "*"},)# ── Parallel-range segment booster (boost=1) ─────────────────────────────# Some CDNs per-CONNECTION throttle (acek-cdn's token carries sp=500 →# ~450KB/s per connection). A 5MB video segment then takes ~11s: hls.js's# default 20s frag timeout is one hiccup away from killing playback# ("languages show, duration shows, then the server stops responding").# The SAME CDN happily serves parallel Range requests at full per-# connection speed (verified 206 + 4x aggregate), so for big segments we# fetch 4 ranges concurrently and reassemble. Falls back to the normal# single-stream path on ANY inconsistency (no content-length, wrong# status, size mismatch) - the booster is strictly best-effort.if boost and not range_header and resp.status_code == 200:try:total = int(resp.headers.get("content-length") or 0)except Exception:total = 0if total >= 1_000_000:try:await resp.aclose()finally:await client.aclose()boosted = await _boosted_segment(u, headers, total)if boosted is not None:ctype_b = ctype if (ctype and "text/html" not in ctype) else "application/octet-stream"return Response(content=boosted,media_type=ctype_b,headers={"Access-Control-Allow-Origin": "*","Accept-Ranges": "bytes","Content-Length": str(total),"Cache-Control": "no-cache",},)# booster failed -> reconnect and stream normally belowtry:client = httpx.AsyncClient(timeout=httpx.Timeout(90, connect=15), follow_redirects=True)req = client.build_request("GET", u, headers=headers)resp = await client.send(req, stream=True)if resp.status_code not in (200, 206):try:err_body = (await resp.aread())[:400]finally:await resp.aclose()await client.aclose()return Response(content=err_body, status_code=resp.status_code,media_type="text/plain", headers={"Access-Control-Allow-Origin": "*"})except Exception:return JSONResponse({"error": "proxy fetch failed"}, status_code=502,headers={"Access-Control-Allow-Origin": "*"})# binary stream (mp4/mkv/ts/segment): pipe with Range support# pass upstream errors through faithfully so players can fall backif resp.status_code not in (200, 206):30 unmodified lines@app.api_route("/proxy", methods=["GET", "HEAD"], include_in_schema=False)async def proxy_stream(u: str, ref: str = None, ua: str = None, origin: str = None, boost: int = 0, request: Request = None):"""Stream proxy (Range-capable, header-injecting, m3u8-rewriting)."""range_header = request.headers.get("range") if request is not None else Nonereturn await _proxy_do(u, ref, ua, origin, range_header, head_only=(request is not None and request.method == "HEAD"), boost=boost)@app.api_route("/proxy_range", methods=["GET", "HEAD"], include_in_schema=False)async def proxy_range(request: Request, u: str, ref: str = None, ua: str = None, origin: str = None, boost: int = 0):"""Proxy that honors the client's Range header (for players that seek)."""range_header = request.headers.get("range")return await _proxy_do(u, ref, ua, origin, range_header, head_only=(request.method == "HEAD"), boost=boost)# ---------- HubCloud family resolver (MediaVanced hubcloud.py, generalized) ----------
main.py+127-6