fix(mediaplayer): play YouTube live streams (long CDN URLs were being truncated) - #986
Merged
dooly123 merged 4 commits intoJul 27, 2026
Merged
Conversation
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
.m3u8in the URL, but theparsed path was capped at 1024 characters. A YouTube live URL is around 1100, so the
.m3u8on 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.
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.
TransformAccessArrayor are otherwise batched. I have not added per-frametransform.position/transform.rotation/transform.localPositioncalls inside loops. Whenever I need both position and rotation, I use the combined APIs —SetPositionAndRotation/SetLocalPositionAndRotationfor writes,GetPositionAndRotation/GetLocalPositionAndRotationfor reads — instead of two separate property accesses; the combined call does one local-to-world matrix traversal instead of two.Resources.Load, no direct asset references that pull large content into memory on scene load.GetComponent/AddComponentwhere avoidable — Where unavoidable, the result is cached on a field, and anyGetComponent<T>is replaced withTryGetComponent<T>(out var x)— bareGetComponentwill be denied.TryGetComponentis the modern API (Unity 2019.2+) and skips the Editor-only GC allocationGetComponentcauses when a component is missing: Unity wraps thenullreturn in a managed "fake null" object so its overloaded==operator can still detect destroyed C++ objects, and constructing that wrapper allocates;TryGetComponentreturns aboolplusoutparameter and never builds the wrapper. None of these calls run insideUpdate,LateUpdate,FixedUpdate, jobs, or other per-frame code paths.BasisEventDriver— Any new per-frame work hooks intoBasisEventDriverrather than adding standaloneUpdate/LateUpdate/FixedUpdatecallbacks on a MonoBehaviour.BasisEventDriveris bulletproof, or guarded bytry/catch—BasisEventDriverruns 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 atry/catchthat contains the failure and surfaces it throughBasisDebug— logged once / rate-limited, never every frame (see the existingHVRBasisBuiltInAddresses.Simulate()guard for the pattern). Expect this to be scrutinized closely in review.{ get; set; }properties or access lockdowns — Public fields are fine; Basis is meant to be read and modified freely, so don't wall things offprivate/internalwithout 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.Instancesingletons, callers reassigningType.Instanceis allowed; if that would break your code, log a warning or throw — don't block the assignment. Locking down access is not your call.BasisLocalCameraDriver— Code that needs the local camera (transform, projection, rig data, etc.) pulls it fromBasisLocalCameraDriverrather than looking one up itself. Don't roll a separate camera discovery path.BasisDebug— All new logging calls go throughBasisDebug.Log/BasisDebug.LogWarning/BasisDebug.LogError(with an appropriateLogTag) instead ofUnityEngine.Debug.Log/Debug.LogWarning/Debug.LogError.BasisDebugroutes through Basis's tagged, color-coded logger and respects the project-wideLoggingDisabledtoggle so logging can be killed at runtime; bareDebug.Logcalls bypass that and will be denied.FindObjectOfType/FindObjectsOfType/GameObject.Find/FindGameObjectsWithTagto 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.newon reference types, no LINQ, nostringconcatenation/interpolation, no boxing, noforeachover interface-typed collections. Allocate once at init and reuse the buffer.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_EDITORand remove (or leave gated) before merge..Count(lists) /.Length(arrays) into a localintbefore the loop instead of re-reading the property each iteration. PreferT[](with a separate length int when the array is over-sized) overList<T>where the data is hot — Unity's mono BCL doesn't exposeCollectionsMarshal.AsSpan(List<T>), so a list can't be fed intoSpan<T>/ unsafe paths cleanly. Where the perf justifies it, drop intoSpan<T>/reflocals /Unsafe.As/unsafepointer 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.
Input / control mode coverage:
Where applicable, confirm these flows still work after your changes:
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.