using UdonSharp;
using UnityEngine;
using VRC.SDK3.Video.Components.AVPro;
using VRC.SDKBase;
using VRC.SDK3.StringLoading;
using VRC.Udon.Common.Interfaces;
using System.Text;
using VRC.SDK3.Components.Video;

namespace Yamadev.YamachanWebUnit
{
    // ==========================================================================================================
    // DM Modified WebUnit v5.6 (shipped from DM Local Playlist 1.1.2). v5.6 = v5.5 with the
    // changes marked "DM v5.6" (PLAYBACK-01, 2026-11-12; Docs/PLAYBACK01_V56_DESIGN_20261112.md):
    //  - Transport player state. Every transport player reports its answers (ready / start / end / error): player A to
    //    this Client directly, B..K through a DmWebUnitTransportRelay on their objects. The answers carry no request
    //    id, and one LoadURL gives ready + start, ready only, or start only; a start came up to 16 s after its ready
    //    (2026-11-12). So each player has one state, and gets a LoadURL only when idle (one LoadURL at a time):
    //      idle -> LoadURL -> in flight -> ready -> settling -> start / end / error, or 20 s -> idle
    //                                  \-> start / end / error -------------------------------> idle
    //    In flight: the byte may not have reached the server, and a LoadURL here blocked the main thread for seconds
    //    (past 10 s Udon halted this Client). Settling: a late start of this LoadURL may still come; it is not taken
    //    as the answer of the next one. An answer while idle is a late answer; it is logged and ignored. In flight
    //    for 300 s without an answer (observed: up to 149 s): the player is set aside (unavailable) until it answers.
    //    A player without a relay is never used. 20 s is a test value, not a fixed specification.
    //  - Order per position. The server keeps, per position, the byte that arrived last. A byte of an older request
    //    can arrive seconds after a byte of a newer one (seen 2026-11-12: two positions of the old ID in the new one).
    //    So a byte is not sent while the player that carried the same position for an older request is in flight.
    //  - Bounded wait. Waiting never blocks (the send loop simply returns). When a request has waited 120 s in total,
    //    it fails: OnRequestError plus a PlayerError on the YamaPlayer handle it marked (DM's automatic retry may
    //    follow), unless it was stopped or its track changed, which ends it without an error.
    //  - Stop / other track. While a request is in flight, the track check runs every 0.5 s (from 1 s after the request);
    //    a request whose track is no longer current stops sending at once (v5.5: only when every byte was sent).
    //  - Long wait inside a request (R2-F1, 2026-11-13). Bytes 0-7 sent, byte 8 held 71 s, bytes 8-10 sent: the
    //    server resolved only the last 3 characters (truncated ID). Observed without loss: up to 21 s from byte 0 to
    //    the last byte (16 s between two bytes). Why the earlier bytes were lost is not known. There is no message
    //    that clears the server, but sending the same ID again from byte 0 writes every position again with the same
    //    byte, so earlier bytes of this request (kept or lost, arriving early or late) cannot change the result. So a
    //    byte after byte 0 is not sent when the previous byte of this pass was sent more than 20 s ago (test value);
    //    the request is sent again from byte 0 instead (the same per-position order and player states apply), at most
    //    2 times. After that the request fails like the 120 s case (the waits of every pass count toward the 120 s).
    //    The gap, not the age of the pass, is checked: with few free players a pass takes about 45 s (one player, 4.2 s
    //    each) without any long gap, and an age limit of 20 s made such passes start again until they failed (r3 L2).
    //  DmRevision 7, DmBuildRevision 7. The scheduler values of v5.4 (11 players, 4.2 s, 0.2 s, 0.5 s) are unchanged.
    // ----------------------------------------------------------------------------------------------------------
    // DM Modified WebUnit v5.5 CANDIDATE (not reviewed, not a product file yet). v5.5 = v5.4 with two changes marked
    // "DM v5.5": the handles are marked as loading during a send (a stop then drops the request), and the request after
    // an unread one waits 5 s before it is handed over (bytes of the unread request stay on the server by position).
    // DM Modified WebUnit v5.4 (production variant) — personal use only, not for redistribution.
    // v5.4 = v5.2 with 11 transport players (A + DmExtraPlayers B..K), a reuse cooldown of 4.2 s (v5.2: 1.4 s),
    // DmRevision 6 and the code revision DmBuildRevision 6. The 11 bytes of a YouTube id therefore never reuse a
    // player inside one request (a reused player that was still opening its previous URL blocked the main thread for
    // up to about 1.3 s in v5.2). Real-client diagnostic (3B, 2026-10-23): no LoadURL of 200 ms or more in 55 sends.
    // The v5.2 text below still describes four players and 1.4 s; read those numbers as 11 and 4.2 s.
    // Based on YamachanWebUnit 1.1.0 Runtime/Client.cs (official SHA256
    // 57c6be2a92d2cb442d51acfc361cd49e9ef09a6d003258d2b7bb50b4e4ff7e7c). Every change is marked "DM MODIFIED".
    //
    // Why: the official loop calls LoadURL every 0.2 s (twice per byte) on one transport player. A LoadURL that
    // arrives while that player is still opening the previous rtsp URL blocks the main thread until the open ends
    // (about 2 s on the first byte of a session, about 0.3 s on every later byte).
    //
    // What: four transport players (this object's player A plus DmExtraPlayers B, C, D, which a build step adds as
    // child objects). One LoadURL per byte, on the next player in A -> B -> C -> D order that is out of its cooldown.
    // Cooldowns count from the moment LoadURL RETURNED: 4.2 s after a player's first LoadURL of the session, 1.4 s
    // after later ones. Any two LoadURLs are at least 0.2 s apart. The request completes 0.5 s after the last one.
    // These four values were validated in a real client on 2026-10-06 and are constants on purpose.
    //
    // Request handling (DM-WU4-002): a request from the same receiver while one is in flight REPLACES it (official:
    // the new one was dropped and the old one completed, so the old video started). A request from another receiver
    // is rejected with its own OnRequestError. A request is completed only if the receiver's player still wants the
    // ID that was sent (read-only check of YamaPlayer's current track; skipped for receivers that are not YamaPlayer).
    //
    // Post-resolve guard (v5.1): when a request completes, the receiver starts the main video request. In two real
    // client runs (official Client and v5), transport LoadURLs issued within about 5 s after that moment were not
    // processed by VRChat at all. So the first LoadURL of a new request is held until 5.5 s after the previous
    // OnRequestSuccess. This is an observed guard interval, not a documented VRChat rule. It only acts when a new
    // track is requested right after the previous one was handed over; normal playback never waits.
    //
    // If the transport players are not all usable, the request is sent with the official loop and an error is logged.
    // The URL table, the server endpoints and the Receiver callbacks are unchanged.
    // ==========================================================================================================
    [RequireComponent(typeof(VRCAVProVideoPlayer))]
    [UdonBehaviourSyncMode(BehaviourSyncMode.None)]
    public class Client : UdonSharpBehaviour
    {
        public int SendTimes = 2;
        public int MaxLength = 100;
        public string ApiBase = "api.yamachan.moe";
        public VRCUrl[] Urls;

        // DM MODIFIED: transport players B, C, D (set by the DM build step; never edited at runtime).
        public VRCAVProVideoPlayer[] DmExtraPlayers;
        // DM MODIFIED: revision of this file, checked by the DM build step.
        public int DmRevision = 7; // DM v5.6 (v5.4 and v5.5: 6, v5.2: 5)
        // DM v5.4: code revision for the DM build step. A const is compiled into the type and never stored
        // in a scene, so a DmRevision value saved with a scene-placed Client cannot hide which Client code is installed.
        public const int DmBuildRevision = 7; // DM v5.6
        // DM MODIFIED: 1 = a request of the same receiver replaces the request in flight (DM-WU4-002). Callers that
        // refuse to start a request while the official Client is busy read this together with DmRevision.
        public int DmRequestReplacement = 1;

        // DM MODIFIED: validated scheduler values. Do not change without a new real-client validation.
        const int DmPlayerCount = 11; // DM v5.4 (v5.2: 4)
        const float DmFirstUseCooldown = 4.2f;
        const float DmReuseCooldown = 4.2f; // DM v5.4 (v5.2: 1.4f)
        const float DmMinInterval = 0.2f;
        const float DmFinalWait = 0.5f;
        // DM MODIFIED: observed guard interval after OnRequestSuccess (see the header). Separate from the player cooldowns.
        const float DmPostResolveGuard = 5.5f;
        // DM v5.5: wait after an unread request, and the loading mark of YamaPlayer's handles.
        const float DmUnreadFinalWait = 5f;
        float _dmFinalWait = DmFinalWait;
        // The handles this Client marked. The mark also writes a negative value, unique per mark, into _lastLoaded (nothing
        // in YamaPlayer reads it). Every PlayUrl of YamaPlayer writes Time.time (0 or more) there, so the value still being
        // the mark means no load of YamaPlayer started since, even in the same frame. Only then the mark is undone, and the
        // previous _lastLoaded comes back.
        UdonSharpBehaviour[] _dmMarkedHandles = new UdonSharpBehaviour[0];
        float[] _dmMarkedLoaded = new float[0], _dmMarkedSentinel = new float[0];
        // The number of the next mark, 1 to DmMarkCycle. Every value is exact as a float, and it starts again only after a
        // million marks: every mark is undone or overwritten by YamaPlayer before the next request, so no old one is left.
        public const int DmMarkCycle = 1000000;
        int _dmMarkSerial;

        VRCAVProVideoPlayer _player;

        bool _isLoading = false;
        VRCUrl[] _queue = new VRCUrl[0];
        int _current = 0;
        VRCUrl _requestApi;
        float _lastRequestTime = 0f;
        Receiver _receiver;

        // DM MODIFIED: request identity. _dmGeneration changes whenever the request in flight changes, so delayed
        // events and download callbacks that belong to an earlier request are ignored.
        int _dmGeneration;
        int _dmDownloadGeneration = -1;
        bool _dmDownloadScheduled, _dmDownloading;
        string _dmData = "";
        // DM MODIFIED: highest number of leading bytes that were sent since the server state was last consumed by a
        // completed request. A shorter ID cannot be sent safely while that is larger than its length.
        int _dmServerLength;
        // DM MODIFIED: scheduler state. Use counts and return times are kept for the whole session.
        bool _dmScheduler, _dmStarted;
        float[] _dmLastReturn = new float[DmPlayerCount];
        int[] _dmUseCount = new int[DmPlayerCount];
        int _dmNextSlot;
        float _dmEligibleAt, _dmLastAnyReturn = -100f, _dmFirstAt;
        int _dmSent;
        float _dmWorstCallMs;
        // DM MODIFIED: post-resolve guard. _dmLastSuccessAt = when this Client last called OnRequestSuccess.
        float _dmLastSuccessAt = -100f, _dmGuardUntil, _dmRequestAt, _dmGuardWaitMs;
        // DM v5.6: transport player state (see the header). Index = transport player (0 = A, 1.. = DmExtraPlayers).
        const int DmIdle = 0;
        const int DmInFlight = 1;
        const int DmSettling = 2;
        const int DmUnavailable = 3;
        const int DmAnswerReady = 1;
        const int DmAnswerStart = 2;
        const int DmAnswerEnd = 3;
        const int DmAnswerError = 4;
        const float DmOpenStaleSeconds = 300f;
        const float DmSettleSeconds = 20f; // test value (observed: start up to 16 s after ready), not a fixed spec
        const float DmSendWaitMax = 120f;
        const float DmWantedCheckInterval = 0.5f;
        // Set by a relay right before it calls DmTransportReady / Start / End / Error or DmTransportRelayReady.
        public int DmTransportAnswer = -1;
        int[] _dmState = new int[DmPlayerCount];
        float[] _dmStateAt = new float[DmPlayerCount];
        int[] _dmOpenGen = new int[DmPlayerCount];
        int[] _dmOpenPos = new int[DmPlayerCount];
        bool[] _dmRelay = new bool[DmPlayerCount];
        float _dmWaitFrom = -1f, _dmWaitLogAt, _dmWaitTotal, _dmNextWantedCheck;
        int _dmLateAnswers, _dmSettleExpired;
        bool _dmRelayWarned;
        // DM v5.6 (R2-F1): a pass = bytes 0..n-1 of a request. _dmPassLast = when the last byte of this pass was sent.
        const float DmPassMaxGap = 20f; // test value (gap observed without loss: 16 s; lost: 71 s), not a fixed spec
        const int DmPassRestartMax = 2;
        float _dmPassLast;
        int _dmPassRestarts, _dmRestartsTotal;

        public bool IsLoading => _isLoading || _requestApi != null;

        void Start()
        {
            _player = GetComponent<VRCAVProVideoPlayer>();
        }

        void Update() {
            if (!_isLoading) return;

            // DM MODIFIED: the scheduler replaces the fixed 0.2 s loop.
            if (_dmScheduler) { DmSchedulerUpdate(); return; }

            if (Time.realtimeSinceStartup < _dmGuardUntil) return; // DM MODIFIED: post-resolve guard
            if (Time.time - _lastRequestTime < 0.2f) return;

            if (_current == _queue.Length)
            {
                if (_dmFinalWait > DmFinalWait && Time.realtimeSinceStartup - _dmLastAnyReturn < _dmFinalWait) return; // DM v5.5
                DmFinish(); // DM MODIFIED: completion moved into one place
                return;
            }

            _lastRequestTime = Time.time;
            VRCUrl url = _queue[_current];
            _current++;
            if (_current > _dmServerLength) _dmServerLength = _current; // DM MODIFIED

            for (int i = 0; i < SendTimes; i++)
            {
                _player.LoadURL(url);
            }
            _dmLastAnyReturn = Time.realtimeSinceStartup; // DM MODIFIED
        }

        // DM MODIFIED: one LoadURL per byte on the next transport player (A -> B -> C -> D order) that is out of its
        // cooldown. Cooldowns count from the moment LoadURL returned, so a LoadURL that blocked does not shorten them.
        void DmSchedulerUpdate()
        {
            float now = Time.realtimeSinceStartup;
            if (now >= _dmNextWantedCheck) // DM v5.6
            {
                _dmNextWantedCheck = now + DmWantedCheckInterval;
                bool stopped = DmStoppedByPlayer();
                if (stopped || !DmStillWanted())
                {
                    Debug.LogWarning("[DM Modified WebUnit] v5.6: " + (stopped ? "the player was stopped" : "the track of the request in flight is no longer current") + "; sending stops (" + _current + " of " + _queue.Length + " bytes sent)");
                    DmAbort(false);
                    return;
                }
            }
            if (!_dmStarted)
            {
                if (now < _dmGuardUntil) return; // post-resolve guard: nothing is sent yet
                _dmGuardWaitMs = _dmGuardUntil > 0f ? (now - _dmRequestAt) * 1000f : 0f;
                _dmStarted = true; _dmFirstAt = now; _dmSent = 0; _dmWorstCallMs = 0f;
            }
            if (_current == _queue.Length)
            {
                if (now - _dmLastAnyReturn < _dmFinalWait) return; // DM v5.5
                Debug.Log("[DM Modified WebUnit] v5.6 scheduler: " + _dmSent + " LoadURL on " + DmPlayerCount + " transport players in " + Mathf.RoundToInt((now - _dmFirstAt) * 1000f) + " ms, worst call " + Mathf.RoundToInt(_dmWorstCallMs) + " ms, post-resolve guard waited " + Mathf.RoundToInt(_dmGuardWaitMs) + " ms, waited for busy players " + Mathf.RoundToInt(_dmWaitTotal * 1000f) + " ms, sent again from byte 0: " + _dmPassRestarts + " (session: late answers ignored " + _dmLateAnswers + ", settling ended by time " + _dmSettleExpired + ", sent again " + _dmRestartsTotal + ")");
                DmFinish();
                return;
            }

            if (now < _dmEligibleAt) return; // global minimum interval (and the wait after a replaced request)

            bool positionOpen = DmPositionBlocked(_current, now); // DM v5.6
            int slot = -1; float cooldown = 0f;
            for (int k = 0; k < DmPlayerCount; k++)
            {
                int s = (_dmNextSlot + k) % DmPlayerCount;
                if (DmBusy(s, now)) continue; // DM v5.6: a LoadURL only on an idle player
                float c = _dmUseCount[s] == 0 ? 0f : _dmUseCount[s] == 1 ? DmFirstUseCooldown : DmReuseCooldown;
                if (_dmUseCount[s] == 0 || now - _dmLastReturn[s] >= c) { slot = s; cooldown = c; break; }
            }
            if (positionOpen || slot < 0) // DM v5.6: wait without blocking, at most DmSendWaitMax in total per request
            {
                if (_dmWaitFrom < 0f) { _dmWaitFrom = now; _dmWaitLogAt = now; }
                else if (_dmWaitTotal + (now - _dmWaitFrom) >= DmSendWaitMax)
                {
                    Debug.LogError("[DM Modified WebUnit] v5.6: the request waited " + Mathf.RoundToInt(DmSendWaitMax) + " s in total for busy transport players; it fails");
                    DmAbort(true);
                    return;
                }
                else if (now - _dmWaitLogAt >= 10f) { _dmWaitLogAt = now; Debug.Log("[DM Modified WebUnit] v5.6: waiting " + Mathf.RoundToInt(_dmWaitTotal + (now - _dmWaitFrom)) + " s in total for byte " + _current + " (" + (positionOpen ? "its position is still in flight for an older request" : "every player is cooling down, in flight, settling or unavailable") + ")"); }
                return;
            }
            if (_dmWaitFrom >= 0f)
            {
                _dmWaitTotal += now - _dmWaitFrom; _dmWaitFrom = -1f;
                if (_dmWaitTotal >= DmSendWaitMax) // DM v5.6: checked again just before sending resumes
                {
                    Debug.LogError("[DM Modified WebUnit] v5.6: the request waited " + Mathf.RoundToInt(DmSendWaitMax) + " s in total for busy transport players; it fails");
                    DmAbort(true);
                    return;
                }
            }
            if (_current > 0 && now - _dmPassLast > DmPassMaxGap) // DM v5.6 (R2-F1): see the header
            {
                if (_dmPassRestarts >= DmPassRestartMax)
                {
                    Debug.LogError("[DM Modified WebUnit] v5.6: byte " + _current + " would be sent " + Mathf.RoundToInt(now - _dmPassLast) + " s after byte " + (_current - 1) + ", and the request was already sent again from byte 0 " + DmPassRestartMax + " times; it fails");
                    DmAbort(true);
                    return;
                }
                _dmPassRestarts++; _dmRestartsTotal++;
                Debug.LogWarning("[DM Modified WebUnit] v5.6: byte " + _current + " would be sent " + Mathf.RoundToInt(now - _dmPassLast) + " s after byte " + (_current - 1) + " (more than " + Mathf.RoundToInt(DmPassMaxGap) + " s); the request is sent again from byte 0 (" + _dmPassRestarts + " of " + DmPassRestartMax + ")");
                _current = 0;
                return; // byte 0 goes through the position order and the player choice on the next frame
            }

            _dmPassLast = now; // DM v5.6 (R2-F1): the gap is counted from the last byte sent
            VRCUrl url = _queue[_current];
            _current++;
            if (_current > _dmServerLength) _dmServerLength = _current;
            float before = Time.realtimeSinceStartup;
            if (slot == 0) _player.LoadURL(url);
            else DmExtraPlayers[slot - 1].LoadURL(url);
            float after = Time.realtimeSinceStartup;
            float callMs = (after - before) * 1000f;
            if (callMs > _dmWorstCallMs) _dmWorstCallMs = callMs;
            _dmSent++;
            _dmLastReturn[slot] = after; _dmUseCount[slot]++;
            _dmState[slot] = DmInFlight; _dmStateAt[slot] = after; _dmOpenGen[slot] = _dmGeneration; _dmOpenPos[slot] = _current - 1; // DM v5.6
            _dmNextSlot = (slot + 1) % DmPlayerCount;
            _dmLastAnyReturn = after; _dmEligibleAt = after + DmMinInterval;
        }

        // DM v5.6: a relay on transport player B..K says it is there (at its Start).
        public void DmTransportRelayReady()
        {
            int s = DmTransportAnswer; DmTransportAnswer = -1;
            if (s >= 1 && s < DmPlayerCount) _dmRelay[s] = true;
        }

        // DM v5.6: transport player B..K answered (through its relay; DmTransportAnswer = its slot).
        public void DmTransportReady() { DmRelayAnswer(DmAnswerReady); }
        public void DmTransportStart() { DmRelayAnswer(DmAnswerStart); }
        public void DmTransportEnd() { DmRelayAnswer(DmAnswerEnd); }
        public void DmTransportError() { DmRelayAnswer(DmAnswerError); }

        void DmRelayAnswer(int kind)
        {
            int s = DmTransportAnswer; DmTransportAnswer = -1;
            if (s >= 1 && s < DmPlayerCount) DmAnswer(s, kind);
        }

        // DM v5.6: transport player A (this object) answered.
        public override void OnVideoReady() { DmAnswer(0, DmAnswerReady); }
        public override void OnVideoStart() { DmAnswer(0, DmAnswerStart); }
        public override void OnVideoEnd() { DmAnswer(0, DmAnswerEnd); }
        public override void OnVideoError(VideoError videoError) { DmAnswer(0, DmAnswerError); }

        // DM v5.6: an answer belongs to the one LoadURL the player was given (a player gets a LoadURL only when idle).
        // ready: in flight -> settling (a start may follow); start / end / error: -> idle. While idle: a late answer of
        // a LoadURL whose settling ended by time; it changes nothing.
        void DmAnswer(int s, int kind)
        {
            int state = _dmState[s];
            string what = kind == DmAnswerReady ? "ready" : kind == DmAnswerStart ? "start" : kind == DmAnswerEnd ? "end" : "error";
            if (state == DmIdle)
            {
                _dmLateAnswers++;
                Debug.LogWarning("[DM Modified WebUnit] v5.6: transport player " + s + " gave a late answer (" + what + ") while idle; ignored (" + _dmLateAnswers + " in this session)");
                return;
            }
            if (state == DmUnavailable) Debug.LogWarning("[DM Modified WebUnit] v5.6: transport player " + s + " answered (" + what + ") after it was set aside; it can be used again");
            if (kind == DmAnswerReady)
            {
                if (state != DmSettling) { _dmState[s] = DmSettling; _dmStateAt[s] = Time.realtimeSinceStartup; }
                return;
            }
            _dmState[s] = DmIdle;
        }

        // DM v5.6: not idle (in flight, settling, unavailable) or without a relay. Applies the two time limits:
        // settling ends DmSettleSeconds after the ready; in flight for DmOpenStaleSeconds -> unavailable (logged).
        bool DmBusy(int s, float now)
        {
            int state = _dmState[s];
            if (state == DmSettling && now - _dmStateAt[s] >= DmSettleSeconds) { _dmState[s] = DmIdle; _dmSettleExpired++; state = DmIdle; }
            else if (state == DmInFlight && now - _dmStateAt[s] >= DmOpenStaleSeconds)
            {
                _dmState[s] = DmUnavailable; state = DmUnavailable;
                Debug.LogError("[DM Modified WebUnit] v5.6: transport player " + s + " gave no answer for " + Mathf.RoundToInt(DmOpenStaleSeconds) + " s; it is set aside until it answers");
            }
            if (state != DmIdle) return true;
            return s >= 1 && !_dmRelay[s];
        }

        // DM v5.6: a byte of an older request at this position may still reach the server while its player is in
        // flight (after a ready or start the server has answered that LoadURL). An unavailable player (300 s) no longer
        // holds its position.
        bool DmPositionBlocked(int pos, float now)
        {
            for (int s = 0; s < DmPlayerCount; s++)
            {
                if (_dmOpenPos[s] != pos || _dmOpenGen[s] == _dmGeneration) continue;
                DmBusy(s, now);
                if (_dmState[s] == DmInFlight) return true;
            }
            return false;
        }

        // DM v5.6: YamaPlayer stopped a handle this request marked as loading (VideoPlayerHandle.Stop clears _loading
        // and leaves our sentinel in _lastLoaded; YamaPlayer's own PlayUrl would have replaced the sentinel).
        bool DmStoppedByPlayer()
        {
            for (int i = 0; i < _dmMarkedHandles.Length; i++)
            {
                UdonSharpBehaviour handle = _dmMarkedHandles[i];
                if (!Utilities.IsValid(handle)) continue;
                object loaded = handle.GetProgramVariable("_lastLoaded");
                object loading = handle.GetProgramVariable("_loading");
                if (loaded == null || loading == null || (float)loaded != _dmMarkedSentinel[i]) continue;
                if (!(bool)loading) return true;
            }
            return false;
        }

        // DM v5.6: ends the request in flight without completing it. failed: its receiver gets OnRequestError, and
        // because YamaPlayer's VideoResolver ignores OnRequestError, the YamaPlayer handle this request marked as
        // loading also gets a video error (VideoError.PlayerError, as a failed load of the player itself), so YamaPlayer
        // and its listeners (DM's automatic retry, which retries PlayerError only) see a failed load, not a silent stop.
        void DmAbort(bool failed)
        {
            Receiver receiver = _receiver;
            if (failed && (DmStoppedByPlayer() || !DmStillWanted()))
            {
                Debug.LogWarning("[DM Modified WebUnit] v5.6: the request was stopped or its track changed before the failure; it ends without an error");
                failed = false;
            }
            UdonSharpBehaviour errorHandle = null;
            if (failed)
            {
                for (int i = 0; i < _dmMarkedHandles.Length && errorHandle == null; i++)
                {
                    UdonSharpBehaviour handle = _dmMarkedHandles[i];
                    if (!Utilities.IsValid(handle)) continue;
                    object loaded = handle.GetProgramVariable("_lastLoaded");
                    object loading = handle.GetProgramVariable("_loading");
                    if (loaded != null && loading != null && (bool)loading && (float)loaded == _dmMarkedSentinel[i]) errorHandle = handle;
                }
            }
            _isLoading = false;
            _current = 0;
            _dmWaitFrom = -1f;
            DmMarkLoading(false);
            clear();
            if (failed && Utilities.IsValid(receiver)) receiver.OnRequestError();
            if (errorHandle != null)
            {
                errorHandle.SetProgramVariable("onVideoErrorVideoError", VideoError.PlayerError);
                errorHandle.SendCustomEvent("_onVideoError");
            }
        }

        // DM MODIFIED: every byte was sent. Complete the request only if it is still the one the receiver wants.
        void DmFinish()
        {
            _isLoading = false;
            _current = 0;
            DmMarkLoading(false); // DM v5.5

            if (!DmStillWanted())
            {
                Debug.LogWarning("[DM Modified WebUnit] request for '" + _dmData + "' is no longer the current track; it is dropped and nothing is played for it");
                clear();
                return;
            }

            if (_requestApi.Equals(VRCUrl.Empty))
            {
                // clear() first: the callback may start a new request.
                Receiver receiver = _receiver;
                clear();
                _dmServerLength = 0; // the receiver now asks the server for this ID, which consumes the server state
                _dmLastSuccessAt = Time.realtimeSinceStartup; // origin of the post-resolve guard
                receiver.OnRequestSuccess(null);
                return;
            }

            _dmDownloadScheduled = true;
            _dmDownloadGeneration = _dmGeneration;
            SendCustomEventDelayedSeconds(nameof(StartDownload), 0.3f);
        }

        // DM MODIFIED: read-only check of the receiver's YamaPlayer (VideoResolver._controller, Controller._track =
        // object[] { player type, title, VRCUrl, original url }). False only on positive evidence that the player's
        // current track is a different one; a receiver without these variables is not checked.
        bool DmStillWanted()
        {
            if (!Utilities.IsValid(_receiver)) return false;
            object controllerObject = _receiver.GetProgramVariable("_controller");
            if (controllerObject == null) return true;
            IUdonEventReceiver controller = (IUdonEventReceiver)controllerObject;
            object trackObject = controller.GetProgramVariable("_track");
            if (trackObject == null) return true;
            object[] track = (object[])trackObject;
            if (track.Length < 4) return true;
            string url = (string)track[3];
            if (string.IsNullOrEmpty(url))
            {
                VRCUrl vrcUrl = (VRCUrl)track[2];
                url = vrcUrl == null ? "" : vrcUrl.Get();
            }
            return !string.IsNullOrEmpty(_dmData) && url.Contains(_dmData);
        }

        // DM MODIFIED: all four transport players present, distinct and active.
        bool DmPlayersUsable()
        {
            if (!Utilities.IsValid(_player)) return false;
            if (DmExtraPlayers == null || DmExtraPlayers.Length != DmPlayerCount - 1) return false;
            for (int i = 0; i < DmExtraPlayers.Length; i++)
            {
                VRCAVProVideoPlayer extra = DmExtraPlayers[i];
                if (!Utilities.IsValid(extra)) return false;
                if (extra == _player) return false;
                if (!extra.gameObject.activeInHierarchy) return false;
                for (int k = 0; k < i; k++) if (DmExtraPlayers[k] == extra) return false;
            }
            return true;
        }

        // DM v5.5: while a request is sent, YamaPlayer's handles are stopped and not loading, so VideoPlayerHandle.Stop
        // returns at once and a stop is lost. They are marked as loading (the truth: this request is loading) until the
        // request ends. A stop then runs YamaPlayer's own OnVideoStop, which clears the track, and DmStillWanted drops it.
        // Receivers that are not a YamaPlayer resolver are not touched.
        void DmMarkLoading(bool loading)
        {
            if (!loading)
            {
                for (int i = 0; i < _dmMarkedHandles.Length; i++)
                {
                    UdonSharpBehaviour previous = _dmMarkedHandles[i];
                    if (!Utilities.IsValid(previous)) continue;
                    object previousLoaded = previous.GetProgramVariable("_lastLoaded");
                    if (previousLoaded == null || (float)previousLoaded != _dmMarkedSentinel[i]) continue; // YamaPlayer's own load: not ours
                    previous.SetProgramVariable("_loading", false);
                    previous.SetProgramVariable("_lastLoaded", _dmMarkedLoaded[i]);
                }
                _dmMarkedHandles = new UdonSharpBehaviour[0];
                _dmMarkedLoaded = new float[0];
                _dmMarkedSentinel = new float[0];
                return;
            }
            DmMarkLoading(false); // a replacing request marks again from a clean state
            if (!Utilities.IsValid(_receiver)) return;
            object controllerObject = _receiver.GetProgramVariable("_controller");
            if (controllerObject == null) return;
            object handlesObject = ((IUdonEventReceiver)controllerObject).GetProgramVariable("_videoPlayerHandles");
            if (handlesObject == null) return;
            Component[] handles = (Component[])handlesObject;
            UdonSharpBehaviour[] marked = new UdonSharpBehaviour[handles.Length * 2];
            float[] loadedAt = new float[handles.Length * 2];
            float[] sentinel = new float[handles.Length * 2];
            int count = 0;
            for (int i = 0; i < handles.Length; i++)
            {
                UdonSharpBehaviour handle = (UdonSharpBehaviour)handles[i];
                if (!Utilities.IsValid(handle)) continue;
                object fallback = handle.GetProgramVariable("_fallbackHandle");
                for (int k = 0; k < 2; k++)
                {
                    UdonSharpBehaviour target = k == 0 ? handle : (fallback == null ? null : (UdonSharpBehaviour)fallback);
                    if (!Utilities.IsValid(target)) continue;
                    object targetLoading = target.GetProgramVariable("_loading");
                    object targetLoaded = target.GetProgramVariable("_lastLoaded");
                    if (targetLoading == null || targetLoaded == null || (bool)targetLoading) continue; // already loading: YamaPlayer's, not ours
                    _dmMarkSerial = _dmMarkSerial % DmMarkCycle + 1;
                    sentinel[count] = -(float)_dmMarkSerial;
                    target.SetProgramVariable("_loading", true);
                    target.SetProgramVariable("_lastLoaded", sentinel[count]);
                    marked[count] = target; loadedAt[count] = (float)targetLoaded; count++;
                }
            }
            _dmMarkedHandles = new UdonSharpBehaviour[count];
            _dmMarkedLoaded = new float[count];
            _dmMarkedSentinel = new float[count];
            for (int i = 0; i < count; i++) { _dmMarkedHandles[i] = marked[i]; _dmMarkedLoaded[i] = loadedAt[i]; _dmMarkedSentinel[i] = sentinel[i]; }
        }

        public void StartDownload()
        {
            // DM MODIFIED: ignore the delayed event of a request that was replaced meanwhile.
            if (!_dmDownloadScheduled || _dmDownloadGeneration != _dmGeneration || _requestApi == null) return;
            _dmDownloadScheduled = false;
            _dmDownloading = true;
            VRCStringDownloader.LoadUrl(_requestApi, (IUdonEventReceiver)this);
        }

        public override void OnStringLoadSuccess(IVRCStringDownload result)
        {
            if (!DmDownloadIsCurrent(result)) return; // DM MODIFIED
            _dmDownloading = false;
            Receiver receiver = _receiver;
            clear();
            _dmServerLength = 0;
            _dmLastSuccessAt = Time.realtimeSinceStartup;
            receiver.OnRequestSuccess(result);
        }

        public override void OnStringLoadError(IVRCStringDownload result)
        {
            if (!DmDownloadIsCurrent(result)) return; // DM MODIFIED
            _dmDownloading = false;
            Receiver receiver = _receiver;
            clear();
            receiver.OnRequestError();
        }

        // DM MODIFIED: a download result counts only for the request that started it.
        bool DmDownloadIsCurrent(IVRCStringDownload result)
        {
            if (!_dmDownloading || _dmDownloadGeneration != _dmGeneration) return false;
            if (_requestApi == null || !Utilities.IsValid(_receiver)) return false;
            return result == null || result.Url == null || result.Url.Get() == _requestApi.Get();
        }

        void clear()
        {
            _queue = new VRCUrl[0];
            _requestApi = null;
            _receiver = null;
        }

        public bool Request(VRCUrl req, string data, Receiver target)
        {
            // DM MODIFIED: errors go to the receiver of the request that is refused (official: to the receiver of
            // the request in flight, which is null when the Client is idle).
            if (!Utilities.IsValid(target)) return false;
            if (req == null || data == null) { target.OnRequestError(); return false; }

            byte[] byteData = Encoding.UTF8.GetBytes(data);
            if (byteData.Length > MaxLength )
            {
                target.OnRequestError();
                return false;
            }

            bool replaced = false;
            if (IsLoading)
            {
                if (target != _receiver)
                {
                    Debug.LogWarning("[DM Modified WebUnit] busy with a request of another receiver; the new request for '" + data + "' is refused");
                    target.OnRequestError();
                    return false;
                }
                // DM MODIFIED (DM-WU4-002): the newer request of the same receiver replaces the one in flight.
                replaced = true;
            }

            // DM MODIFIED: from here on the request in flight (if any) is no longer valid.
            _dmGeneration++;
            _dmDownloadScheduled = false;
            _dmDownloading = false;

            if (byteData.Length < _dmServerLength)
            {
                // Bytes of an earlier, unfinished request are still on the server beyond the end of this ID, and they
                // cannot be removed. Sending this ID could resolve to a different video, so nothing is sent.
                Debug.LogError("[DM Modified WebUnit] '" + data + "' (" + byteData.Length + " bytes) cannot be sent safely: " + _dmServerLength + " bytes of an unfinished request are on the server. Play a track with an ID of at least that length first.");
                _isLoading = false;
                _current = 0;
                DmMarkLoading(false); // DM v5.5: before clear(), which forgets the receiver
                clear();
                target.OnRequestError();
                return false;
            }

            _queue = new VRCUrl[byteData.Length];
            for (int i = 0; i < byteData.Length; i++)
            {
                VRCUrl targetUrl = Urls[i * 256 + byteData[i]];
                _queue[i] = targetUrl;
            }

            _requestApi = req;
            _receiver = target;
            _isLoading = true;
            _current = 0;

            // DM MODIFIED: choose the send loop for this request.
            _dmData = data;
            _dmStarted = false;
            // DM v5.6
            _dmWaitFrom = -1f; _dmWaitTotal = 0f;
            _dmPassRestarts = 0; _dmPassLast = Time.realtimeSinceStartup; // R2-F1 (every byte sent sets it again)
            _dmNextWantedCheck = Time.realtimeSinceStartup + 1f;
            if (!_dmRelayWarned)
            {
                int missing = 0;
                for (int s = 1; s < DmPlayerCount; s++) if (!_dmRelay[s]) missing++;
                if (missing > 0) { _dmRelayWarned = true; Debug.LogError("[DM Modified WebUnit] v5.6: " + missing + " transport players have no answer relay; they are not used"); }
            }
            // DM MODIFIED: post-resolve guard, counted from the last OnRequestSuccess of this Client.
            _dmRequestAt = Time.realtimeSinceStartup;
            _dmGuardUntil = 0f; _dmGuardWaitMs = 0f;
            if (_dmRequestAt - _dmLastSuccessAt < DmPostResolveGuard)
            {
                _dmGuardUntil = _dmLastSuccessAt + DmPostResolveGuard;
                Debug.Log("[DM Modified WebUnit] post-resolve guard: the previous request completed " + Mathf.RoundToInt((_dmRequestAt - _dmLastSuccessAt) * 1000f) + " ms ago; the first LoadURL for '" + data + "' waits " + Mathf.RoundToInt((_dmGuardUntil - _dmRequestAt) * 1000f) + " ms");
            }
            // DM v5.5: bytes of an unread request are still on the server; this request waits until its own have arrived.
            _dmFinalWait = _dmServerLength > 0 ? DmUnreadFinalWait : DmFinalWait;
            DmMarkLoading(true);
            bool wantScheduler = true;
            _dmScheduler = wantScheduler;
            if (_dmScheduler && !DmPlayersUsable())
            {
                _dmScheduler = false;
                Debug.LogError("[DM Modified WebUnit] the 11 transport players are not all present and active; this request uses the official loop");
            }
            if (replaced)
            {
                // The last LoadURL of the replaced request needs the same time to reach the server as the last
                // byte of a normal request, or it could arrive after a byte of this request.
                float wait = _dmLastAnyReturn + DmFinalWait - Time.realtimeSinceStartup;
                if (wait > 0f)
                {
                    if (_dmEligibleAt < _dmLastAnyReturn + DmFinalWait) _dmEligibleAt = _dmLastAnyReturn + DmFinalWait;
                    _lastRequestTime = Time.time + wait - 0.2f;
                }
                Debug.Log("[DM Modified WebUnit] the request in flight was replaced by '" + data + "'");
            }

            return true;
        }

        public int GetPercentage() {
            if (!_isLoading) return 100;

            return Mathf.RoundToInt((float)_current / (float)_queue.Length * 100);
        }
    }
}
