Skip to content

fix(mediaplayer): play YouTube live streams (long CDN URLs were being truncated) - #986

Merged
dooly123 merged 4 commits into
BasisVR:developerfrom
towneh:fix/mediaplayer-hls-long-uris
Jul 27, 2026
Merged

fix(mediaplayer): play YouTube live streams (long CDN URLs were being truncated)#986
dooly123 merged 4 commits into
BasisVR:developerfrom
towneh:fix/mediaplayer-hls-long-uris

Conversation

@towneh

@towneh towneh commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

Summary

YouTube live streams wouldn't play. Pasting a live URL left the player retrying for about
15 seconds and then stopping, with nothing in the log to say why.

Two problems, both from long URLs being shortened without complaint:

  • Wrong handler. The player picks the HLS path by looking for .m3u8 in the URL, but the
    parsed path was capped at 1024 characters. A YouTube live URL is around 1100, so the .m3u8
    on the end got cut off and the stream was handed to the plain-download path instead. That
    found no video and gave up quietly, which is why nothing was logged.
  • HLS limits too small. With that fixed, the playlist hit three more caps. YouTube live
    playlists are about 3.7 MB, list the whole DVR window (~2900 segments), and carry signed
    segment URLs of ~1150 characters. All three were over the limit, and each was trimmed
    silently.

The caps now fit real CDN URLs. Anything that still doesn't fit is dropped and fails clearly,
rather than being stored as a shortened URL the server just rejects. Live playlists also keep
the newest segments instead of the oldest, since the live edge is what actually plays.

Required checks

All boxes below must be ticked before this PR can merge. If a check is genuinely N/A, tick it anyway and explain under Notes.

  • Tested — I built and ran this locally. The change works in the editor and (where relevant) in a built player.
  • Transform access is combined and limited — In hot paths, transform reads/writes go through TransformAccessArray or are otherwise batched. I have not added per-frame transform.position / transform.rotation / transform.localPosition calls inside loops. Whenever I need both position and rotation, I use the combined APIs — SetPositionAndRotation / SetLocalPositionAndRotation for writes, GetPositionAndRotation / GetLocalPositionAndRotation for reads — instead of two separate property accesses; the combined call does one local-to-world matrix traversal instead of two.
  • Addressables used for asset/memory loading — Any new asset loads go through Addressables. No new Resources.Load, no direct asset references that pull large content into memory on scene load.
  • No new GetComponent / AddComponent where avoidable — Where unavoidable, the result is cached on a field, and any GetComponent<T> is replaced with TryGetComponent<T>(out var x) — bare GetComponent will be denied. TryGetComponent is the modern API (Unity 2019.2+) and skips the Editor-only GC allocation GetComponent causes when a component is missing: Unity wraps the null return in a managed "fake null" object so its overloaded == operator can still detect destroyed C++ objects, and constructing that wrapper allocates; TryGetComponent returns a bool plus out parameter and never builds the wrapper. None of these calls run inside Update, LateUpdate, FixedUpdate, jobs, or other per-frame code paths.
  • Per-frame work is scheduled through BasisEventDriver — Any new per-frame work hooks into BasisEventDriver rather than adding standalone Update / LateUpdate / FixedUpdate callbacks on a MonoBehaviour.
  • Anything added to BasisEventDriver is bulletproof, or guarded by try/catchBasisEventDriver runs the single per-frame tick that drives the whole framework (network apply, local player sim, blendshapes, JigglePhysics, nameplates, and more) as one sequential chain. An unhandled exception anywhere in that chain aborts the rest of the tick, so every step after the throwing one is silently skipped for that frame. New work added to the driver must either be guaranteed not to throw, or be wrapped in a try/catch that contains the failure and surfaces it through BasisDebug — logged once / rate-limited, never every frame (see the existing HVRBasisBuiltInAddresses.Simulate() guard for the pattern). Expect this to be scrutinized closely in review.
  • Considered jobification — I asked whether this work can be moved to a Unity Job (Burst-compiled where possible). If it can, it is. If it cannot, the reason is in Notes.
  • No needless { get; set; } properties or access lockdowns — Public fields are fine; Basis is meant to be read and modified freely, so don't wall things off private/internal without a real reason. Don't wrap a field in { get; set; } when the accessors do nothing — property accessors have a real performance cost vs direct field access, and the lead maintainer prefers plain fields (or a method / setter-only property when only the setter needs logic) over a noop-getter pair. For .Instance singletons, callers reassigning Type.Instance is allowed; if that would break your code, log a warning or throw — don't block the assignment. Locking down access is not your call.
  • Camera access goes through BasisLocalCameraDriver — Code that needs the local camera (transform, projection, rig data, etc.) pulls it from BasisLocalCameraDriver rather than looking one up itself. Don't roll a separate camera discovery path.
  • Logging uses BasisDebug — All new logging calls go through BasisDebug.Log / BasisDebug.LogWarning / BasisDebug.LogError (with an appropriate LogTag) instead of UnityEngine.Debug.Log / Debug.LogWarning / Debug.LogError. BasisDebug routes through Basis's tagged, color-coded logger and respects the project-wide LoggingDisabled toggle so logging can be killed at runtime; bare Debug.Log calls bypass that and will be denied.
  • No scene-wide discovery for dependencies — New code is architected so it does not need FindObjectOfType / FindObjectsOfType / GameObject.Find / FindGameObjectsWithTag to locate what it depends on. References are wired in — registered through an existing manager/driver, injected at init, or passed in by the caller — rather than discovered by scanning the scene at runtime. If a scene scan is genuinely unavoidable, justify it under Notes.
  • No allocations in hot paths — Per-frame code (Update / LateUpdate / FixedUpdate, simulation loops, jobs, anything called once per frame or more) does not allocate. No new on reference types, no LINQ, no string concatenation/interpolation, no boxing, no foreach over interface-typed collections. Allocate once at init and reuse the buffer.
  • No debugging in hot paths — No log calls of any kind on per-frame paths, including BasisDebug. Hot-path logging floods the console and incurs cost on every frame regardless of whether the message is filtered out downstream. If a hot-path log is needed while iterating, gate it behind #if UNITY_EDITOR and remove (or leave gated) before merge.
  • Hot-path collection access is optimized — Cache .Count (lists) / .Length (arrays) into a local int before the loop instead of re-reading the property each iteration. Prefer T[] (with a separate length int when the array is over-sized) over List<T> where the data is hot — Unity's mono BCL doesn't expose CollectionsMarshal.AsSpan(List<T>), so a list can't be fed into Span<T> / unsafe paths cleanly. Where the perf justifies it, drop into Span<T> / ref locals / Unsafe.As / unsafe pointer code to skip bounds checks and copies, and call out the invariants you're relying on under Notes so reviewers can sanity-check them.

Testing details

Tick the platforms you actually tested on. Leave the rest unticked — these are informational and do not block merge.

  • Windows
  • Linux
  • Android
  • iOS
  • macOS

Input / control mode coverage:

  • Tested in VR (note headset under Notes)
  • Tested in desktop / non-VR mode
  • Tested with phone controls (mobile touch input)
  • N/A — change does not touch player/XR/input code

Where applicable, confirm these flows still work after your changes:

  • Hot-switching (desktop ↔ VR mode swap at runtime)
  • Avatar swapping
  • Server swapping (joining / leaving / changing servers)
  • N/A — change does not touch any of the above

Notes

This is all in the native media plugin (C) plus one line in a testing doc, so most of the
required checks have nothing to apply to. There are no Unity objects, transforms, components,
Addressables, cameras, per-frame code or scene lookups in the change. Ticked as N/A per the
instructions above.

Verified in the editor against a YouTube live stream: 12 minutes of continuous playback with
audio and video in sync, no dropped frames and no stalls. Also re-checked HLS VOD and
multi-variant playlists to make sure the wider limits didn't disturb them.

The native plugin binaries are rebuilt and committed alongside the source change.

towneh added 4 commits July 27, 2026 17:45
…ists

YouTube live streams never played. The native HLS source gave up before
fetching a single segment byte, and three limits in basis_hls.c compounded to
cause it. A YouTube live media playlist is ~3.7 MB, lists the whole
2880-segment DVR window, and signs each segment URI at ~1150 characters:

- HLS_MAX_PLAYLIST (1 MiB) truncated the body mid-URI and returned it as
  though complete.
- HLS_MAX_ITEMS kept the *first* 512 segments of that window, so the retained
  list ended hours behind the live edge the start cursor was set to. No item
  ever matched the cursor, every reload enqueued nothing, and the source quit
  after HLS_MAX_EMPTY_RELOADS.
- HLS_MAX_URI (1024) clipped every URI to 1023 characters, which the CDN
  answers 403 to. That is the failure that would have surfaced next.

Raise the URI cap to 2048, matching the core's url[2048], and the playlist cap
to 8 MiB. Retain the newest items for a live playlist instead of the oldest,
since the live edge is what plays; VOD still keeps the head it starts from.
Where a URI still doesn't fit, drop it rather than store a prefix, because a
clipped URI is indistinguishable downstream from a real authorisation failure.
A playlist yielding no fetchable item now fails the open instead of leaving the
producer to reload fruitlessly.

The playlist struct is ~1 MiB at the wider URI cap, so both parse sites
heap-allocate it rather than hold it on the stack; reload_and_enqueue runs on
the producer thread.

Verified by driving the real source against a captured YouTube live playlist
(2880 segments, 1136-character URIs): it now requests the four segments at the
live edge with URIs byte-identical to the playlist, where before it made nine
playlist fetches and requested no segment at all. VOD (Mux, 64 segments) and
master-to-variant selection are unchanged. All three cases run clean under
ASan/UBSan, and fuzz_hls reported nothing.

Also advance the part counter whether or not the part was retained. A part is
only dropped once the array is full, after which nothing further is retained
either, so no stored item can currently be given a stale index — but keeping
the counter independent of retention matches how seg_index is counted and
stops a later change to the retention policy from silently renumbering parts.

Resolution is checked for fit too. A relative reference is concatenated onto
the base URL, so the result can overrun the destination where neither part
alone would, and the clipped remainder still reads as a well-formed absolute
URL. resolve_url now reports whether the result fit, and callers drop the
reference instead of storing one the origin will refuse; segment and part
references resolve into a scratch buffer first, so a failure never leaves a
claimed slot without a URI.
run_http_like picks the HLS source by testing the parsed path for ".m3u8",
but basis_url_t.path was 1024 bytes and basis_url_parse silently clipped
anything longer. A YouTube live manifest URL is ~1110 characters with a
~1078-character path, so the clip removed the trailing "/playlist/index.m3u8"
and the URL fell through to the plain byte-source path — which fetched the
playlist text and handed it to the TS demuxer, found no media, and returned
cleanly. No error was raised, so the demux loop retried it six times and
settled on ENDED.

Size the path buffer to hold the path of any URL the engine accepts (its own
url buffer is 2048), and reject an over-long path instead of truncating: the
value is dispatched on, so a clipped one silently reroutes the URL to the
wrong handler rather than failing somewhere it can be reported. open_impl now
rejects an over-long URL for the same reason — it stored a prefix that every
later fetch would re-send, which the origin refuses with nothing to
distinguish it from a real authorisation failure.

Verified over the real network by driving the source through the WinHTTP
provider: the manifest URL parses with its ".m3u8" tail intact and dispatches
to HLS, then stitches ~3 MB of media from segment URLs of ~1170 characters.
Short URLs parse unchanged. fuzz_url ran 19.7M cases and fuzz_hls a further
pass, both clean.
Its media playlist is the one that stresses the HLS parser's size limits —
a whole DVR window of segments, megabytes of text, and segment URIs past 1 KB
— so the row is worth re-running after any HLS change.
Windows x64 and Android arm64, both RIST-enabled, rebuilt from the HLS and
URL-dispatch fixes above. Windows is verified in the editor; Android arm64 is
built from the same platform-neutral sources but has had no device pass.
@towneh
towneh requested a review from dooly123 July 27, 2026 17:43
@towneh towneh added the bug Something isn't working label Jul 27, 2026
@dooly123
dooly123 merged commit 4a31977 into BasisVR:developer Jul 27, 2026
15 checks passed
@towneh
towneh deleted the fix/mediaplayer-hls-long-uris branch July 27, 2026 18:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants