diff --git a/AGENTS.md b/AGENTS.md index dccfc1c0..31469faf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,7 +5,7 @@ - This is U-Jagd 1.2.0 (`src/core/version.py`); current saves are v14-only. Treat these as compatibility contracts, not changelog entries. - Resolve conflicts in this order: executable code and focused tests; packaged JSON/runtime resources; `pyproject.toml` and provenance/license notices; `README.md`; design/history documents under `docs/`. A plan or old comment is not an implementation contract. - Preserve explicit compatibility tests and user data unless a task intentionally changes the contract. Add a regression test for behavior changes. -- Older phase/milestone labels under `docs/GDD.md`, `docs/implementation-plan.md`, `docs/plan-0.1.6.md`, and `docs/plan-0.1.7.md` are historical. Current resumable work is tracked in `docs/plan-0.1.8.md` and `docs/resume.md`. +- Older phase/milestone labels under `docs/GDD.md`, `docs/implementation-plan.md`, `docs/plan-0.1.6.md`, and `docs/plan-0.1.7.md` are historical. Current resumable work is tracked in `docs/plan-1.3.md` and `docs/resume.md`. ## Architecture @@ -24,7 +24,7 @@ - World position/range is nautical miles, speed is knots, simulation duration is seconds, depth is metres, frequency is Hz, and headings/bearings are nautical degrees: 0 north, clockwise; movement uses `x += sin(course)`, `y -= cos(course)`. - At 1x, one real second is one simulation second. Convert knots with `kn / 3600`; do not add hidden tactical compression. `GAME_TIME_PER_SEC` advances the 24-hour clock separately. -- The game always runs in real time: there is no time acceleration and no pause. Menus and overlays opened over a mission (help/manual, options, save/load, quit confirmation, nations, F8 analyzer, F9 administration, live traffic) and focus loss own input only and never stop the simulation. `Game.update()` subdivides each frame to at most `PHYS_SUBSTEP_S` subject to `PHYS_SUBSTEP_MAX`; the main loop (`Game._frame_dt`) never advances a frame by more than `SIM_FRAME_DT_MAX` (0.1 s) but catches up slow frames from a bounded debt (`SIM_CATCHUP_MAX_S`, 1 s), and never after the main menu, load or reset, so sim time (and the sonar audio produced in it) keeps pace with wall-clock playback. Preserve swept collision behavior and the update ordering in `_update_sim()`. +- The game always runs in real time: there is no time acceleration and no pause. Menus and overlays opened over a mission (help/manual, options, save/load, quit confirmation, nations, F8 analyzer, F9 administration, live traffic) and focus loss own input only and never stop the simulation. `Game.update()` subdivides each frame to at most `PHYS_SUBSTEP_S` subject to `PHYS_SUBSTEP_MAX`; the main loop (`Game._frame_dt`) never advances a frame by more than `SIM_FRAME_DT_MAX` (0.1 s) but catches up slow frames from a bounded debt (`SIM_CATCHUP_MAX_S`, 2.5 s), and never after the main menu, load or reset, so sim time (and the sonar audio produced in it) keeps pace with wall-clock playback. Preserve swept collision behavior and the update ordering in `_update_sim()`. - Only states without a running mission (splash, main menu and its editors, game over) do not advance simulation. Cosmetic/UI timers and audio cadence use wall time where the code says so. - Same seed, world mode, and input/update sequence must produce the same state. Use explicit local `random.Random` streams, stable hashes, stable iteration/order, and saved RNG states. Never introduce simulation dependence on global randomness, hash randomization, rendering frequency, audio availability, or wall clock. - Save/load must preserve deterministic continuation, entity ID progression, generated coastline/bathymetry snapshots, pending sensor/projectile state, and operator focus. When adding random draws, consider stream/order compatibility and update determinism and round-trip tests. diff --git a/data/commander/js/audio/audio.js b/data/commander/js/audio/audio.js index 5bb90e47..b7ca1cf2 100644 --- a/data/commander/js/audio/audio.js +++ b/data/commander/js/audio/audio.js @@ -15,9 +15,10 @@ const audioPollRoutes = {helicopter: "/api/v2/helicopter/audio", uboot_sonar: "/ // Blocks arrive at real-time rate, so the standing buffer is the start lead. It // must outlast a browser main-thread stall or a Wi-Fi hiccup, otherwise every // such hiccup is an audible gap; live listening tolerates the extra latency. -const sonarAudioStartLead = 1.0; -const sonarAudioTargetAhead = 1.5; -const sonarAudioMaxSources = 12; +// (HTTP fallback without AudioWorklet; the worklet keeps the same two-second lead.) +const sonarAudioStartLead = 2.0; +const sonarAudioTargetAhead = 2.5; +const sonarAudioMaxSources = 24; export const sonarGainValue = () => { const value = Number($("volume").value) / 200; const helicopterLevel = S.session?.station === "helicopter" @@ -89,9 +90,9 @@ export function renderSonarAudio(key) { export function stopSonarAudio(key = "sonar_live_off") { S.sonarAudioGeneration += 1; S.sonarAudioEnabled = false; - S.sonarAudioMetrics = {buffered: 0, gaps: 0, concealed: 0, rate: 1, stale: false}; + S.sonarAudioMetrics = {buffered: 0, gaps: 0, evictions: 0, dropped: 0, concealed: 0, rate: 1, stale: false}; window.uJagdAudioDiagnostics = Object.freeze({bufferedSeconds: 0, - sequenceGaps: 0, droppedBlocks: 0, concealedBlocks: 0, playbackRate: 1, + sequenceGaps: 0, droppedBlocks: 0, evictedBlocks: 0, concealedBlocks: 0, playbackRate: 1, stale: false, transport: "off"}); clearTimeout(S.sonarAudioTimer); S.sonarAudioTimer = null; @@ -144,7 +145,11 @@ export function openSonarAudioSocket() { let socket; try { const scheme = location.protocol === "https:" ? "wss:" : "ws:"; - socket = new WebSocket(`${scheme}//${location.host}/ws/v2/${audioRoute(role)}/audio`, "u-jagd-audio-v2"); + // Resume behind the last accepted block: the host never re-sends audio + // the worklet already holds, and numbering never restarts within a run. + const resume = Number.isSafeInteger(S.sonarAudioSequence) && S.sonarAudioSequence >= 0 + ? `?after=${S.sonarAudioSequence}` : ""; + socket = new WebSocket(`${scheme}//${location.host}/ws/v2/${audioRoute(role)}/audio${resume}`, "u-jagd-audio-v2"); } catch (_) { scheduleSonarAudioPoll(0); return; } socket.binaryType = "arraybuffer"; S.sonarAudioSocket = socket; @@ -165,7 +170,7 @@ export function openSonarAudioSocket() { if (S.sonarAudioSocket === socket) S.sonarAudioSocket = null; if (current()) { scheduleSonarAudioPoll(0); - S.sonarAudioReconnect = setTimeout(openSonarAudioSocket, 2000); + S.sonarAudioReconnect = setTimeout(openSonarAudioSocket, 500); } else if (resumable()) { // The host's local input advanced the epoch: reconnect at once. clearTimeout(S.sonarAudioReconnect); diff --git a/data/commander/js/input/wiring.js b/data/commander/js/input/wiring.js index a557d09d..89ff72c9 100644 --- a/data/commander/js/input/wiring.js +++ b/data/commander/js/input/wiring.js @@ -686,8 +686,8 @@ export function init() { if (data?.type === "metrics") { S.sonarAudioMetrics = data; window.uJagdAudioDiagnostics = Object.freeze({ - bufferedSeconds: Math.max(0, Math.min(6, data.buffered * .25)), - sequenceGaps: data.gaps, droppedBlocks: data.evictions, + bufferedSeconds: Math.max(0, Math.min(8, data.buffered * .25)), + sequenceGaps: data.gaps, droppedBlocks: data.dropped, evictedBlocks: data.evictions, concealedBlocks: data.concealed, playbackRate: data.rate, stale: data.stale, transport: S.sonarAudioSocket ? "websocket" : "http"}); } diff --git a/data/commander/sonar-audio-worklet.js b/data/commander/sonar-audio-worklet.js index 0ce938bf..b96aca38 100644 --- a/data/commander/sonar-audio-worklet.js +++ b/data/commander/sonar-audio-worklet.js @@ -6,18 +6,22 @@ * non-periodic granular stand-in built from the last half second and refills * to REFILL_BLOCKS before fresh audio resumes; after STALE_S without data a * low neutral noise marks the stream stale. Crossfades are applied only at - * real discontinuities, never at ordinary block joins. */ + * real discontinuities, never at ordinary block joins. + * + * The two-second lead (PRIME_BLOCKS, TARGET_S) outlasts a Wi-Fi power-save + * hiccup, a browser main-thread stall and the host's bounded catch-up after + * a slow frame; MAX_BLOCKS bounds the delay when a tab resumes. */ const BLOCK = 1024; const SOURCE_RATE = 4096; -const PRIME_BLOCKS = 5; -const MAX_BLOCKS = 12; -const REFILL_BLOCKS = 2; -const TARGET_S = 1.0; +const PRIME_BLOCKS = 8; +const MAX_BLOCKS = 24; +const REFILL_BLOCKS = 4; +const TARGET_S = 2.0; const RATE_MAX = .02; const RATE_STEP = .0025; const RATE_GAIN = .05; const LEVEL_SMOOTHING = .05; -const STALE_S = 2; +const STALE_S = 3; const GRAIN = 512; class SonarAudioProcessor extends AudioWorkletProcessor { @@ -27,6 +31,7 @@ class SonarAudioProcessor extends AudioWorkletProcessor { for (let i = 0; i < GRAIN; i++) this.window[i] = Math.sin(Math.PI * (i + .5) / GRAIN); this.gaps = 0; this.evictions = 0; + this.dropped = 0; this.concealed = 0; this.outputFrames = 0; this.noise = 0x5a17; @@ -36,7 +41,9 @@ class SonarAudioProcessor extends AudioWorkletProcessor { if (data?.type === "reset") { this.resetStream(); return; } if (data?.type !== "pcm" || !(data.bytes instanceof ArrayBuffer) || data.bytes.byteLength !== 2048 || !Number.isSafeInteger(data.sequence) || data.sequence < 1) return; - if (this.lastSequence !== null && data.sequence <= this.lastSequence) return; + // Sequences never go backwards within a host run: an old or repeated + // number is a duplicate (a reconnect re-sent it) and is counted, not played. + if (this.lastSequence !== null && data.sequence <= this.lastSequence) { this.dropped++; return; } const gap = this.lastSequence !== null && data.sequence !== this.lastSequence + 1; if (gap) this.gaps++; this.lastSequence = data.sequence; @@ -180,7 +187,7 @@ class SonarAudioProcessor extends AudioWorkletProcessor { if (this.outputFrames >= sampleRate) { this.outputFrames -= sampleRate; this.port.postMessage({type: "metrics", buffered: this.blocks.length + (this.current ? 1 - this.cursor / BLOCK : 0), - gaps: this.gaps, evictions: this.evictions, concealed: this.concealed, + gaps: this.gaps, evictions: this.evictions, dropped: this.dropped, concealed: this.concealed, rate: this.rate, stale: this.stale}); } return true; diff --git a/data/manual/02-sonar.de.md b/data/manual/02-sonar.de.md index 8900f110..5330cca8 100644 --- a/data/manual/02-sonar.de.md +++ b/data/manual/02-sonar.de.md @@ -111,7 +111,7 @@ Gefechtslage: - Verstärkung (`I`/`O`) ändert nur Anzeige und Audio, nicht die Ortung. Schwarzwert (`Ctrl+I`/`Ctrl+O`) und Kontrast (`Shift+I`/`Shift+O`) heben schwache Spuren hervor; `Shift+C` wechselt die Phosphorfarbe. - `D` oder `A`/`B`/`H` wählen Breitband-, gefiltertes oder Überlagerungs-Abhören. Überlagerung verschiebt das tiefe Band auf etwa 700 Hz, damit tiefe Töne hörbar werden. -- Das Abhör-Audio läuft etwa eine Sekunde hinter der Anzeige, damit es auch unter Last nicht aussetzt. Nach dem Schwenken der Abhörpeilung geht der alte Strahl nach etwa einer Sekunde in den neuen über; der Ton bricht nicht ab. +- Das Abhör-Audio läuft etwa anderthalb Sekunden hinter der Anzeige (Remote-Crew-Browser etwa zwei Sekunden), damit es auch unter Last nicht aussetzt. Nach dem Schwenken der Abhörpeilung geht der alte Strahl nach dieser Verzögerung in den neuen über; der Ton bricht nicht ab. - TAS unter die gemessene Schicht legen, um tiefe Ziele zu hören; das HMS für flache Ziele nutzen. Beide Arrays arbeiten parallel. - Die TMA-Seite zeigt die aus der übernommenen Lösung abgeleitete Annäherungsrate: positiv heißt, das Ziel kommt näher. - Weichen TAS und HMS um 9 Grad oder mehr ab, den Kontakt als möglichen Geist behandeln (die Anzeige markiert ihn) und durch eine Wende klären. diff --git a/data/manual/02-sonar.en.md b/data/manual/02-sonar.en.md index 46b7f66d..142f8e90 100644 --- a/data/manual/02-sonar.en.md +++ b/data/manual/02-sonar.en.md @@ -110,7 +110,7 @@ Combat situation: - Gain (`I`/`O`) changes display and audio only, not detection. Black level (`Ctrl+I`/`Ctrl+O`) and contrast (`Shift+I`/`Shift+O`) help faint traces stand out; `Shift+C` changes the phosphor colour. - `D` or `A`/`B`/`H` choose broadband, filtered or heterodyne audition. Heterodyne shifts the low band up to about 700 Hz so low tonals become audible. -- The listening audio runs about one second behind the display so a busy moment never interrupts it. After steering the listening bearing the old beam fades into the new one after about a second; the stream is not cut. +- The listening audio runs about one and a half seconds behind the display (Remote Crew browsers about two seconds) so a busy moment never interrupts it. After steering the listening bearing the old beam fades into the new one after that delay; the stream is not cut. - Put the TAS below the measured layer to hear deep targets; keep the HMS for shallow ones. Both arrays run in parallel. - The TMA page shows the closing rate derived from the accepted solution: positive means the target is closing. - If the TAS and HMS disagree by 9 degrees or more, treat the contact as a possible ghost (the display flags it) and turn to resolve it. diff --git a/docs/commander-protocol.de.md b/docs/commander-protocol.de.md index 539afcd3..1b082cc9 100644 --- a/docs/commander-protocol.de.md +++ b/docs/commander-protocol.de.md @@ -131,19 +131,26 @@ wird im Hauptthread anhand des projizierten Sonar-Abhörmodus sowie der Einstell für Band, Notch und Gain gefiltert. Der Server hält die letzten 40 Blöcke (zehn Sekunden), damit ein kurz stockender Client der Reihe nach aufholt; ältere Blöcke werden verworfen und als Diskontinuität gemeldet. Der Browser startet die Wiedergabe -etwa eine Sekunde hinter dem neuesten Block. Das AudioWorklet regelt diesen -Vorlauf, indem es den Strom um höchstens 2 % schneller oder langsamer liest; -Uhrendrift und Jitter leeren oder überfüllen ihn so nicht. Bei einem Unterlauf -spielt es einen nicht periodischen, granular aus der letzten halben Sekunde -erzeugten Ersatz und puffert eine halbe Sekunde nach, bevor frische Daten -weiterlaufen; nach zwei Sekunden ohne Daten spielt es leises neutrales Rauschen -und kennzeichnet den Strom als veraltet. Überblendet wird nur an echten -Brüchen. Der uConsole-Mixer-Worker nutzt denselben elastischen Vorlauf, dieselbe -Verdeckung und dieselbe Zwei-Sekunden-Grenze. Ein vorübergehender Fehler der +etwa zwei Sekunden (acht Blöcke) hinter dem neuesten Block. Das AudioWorklet regelt +diesen Vorlauf, indem es den Strom um höchstens 2 % schneller oder langsamer liest; +Uhrendrift und Jitter leeren oder überfüllen ihn so nicht; es hält höchstens sechs +Sekunden. Bei einem Unterlauf spielt es einen nicht periodischen, granular aus der +letzten halben Sekunde erzeugten Ersatz und puffert eine Sekunde (vier Blöcke) nach, +bevor frische Daten weiterlaufen; nach drei Sekunden ohne Daten spielt es leises +neutrales Rauschen und kennzeichnet den Strom als veraltet. Überblendet wird nur an +echten Brüchen. Der uConsole-Mixer-Worker nutzt dasselbe elastische Verfahren mit +1,5 s Vorlauf, fünf Sekunden Warteschlangengrenze und derselben Drei-Sekunden-Regel; +die Hauptschleife holt bis zu 2,5 s eines hängenden Frames nach, Audio dieser Länge +wird also verdeckt, nie abgeschnitten. Ein vorübergehender Fehler der Zustandsabfrage oder HTTP 503 verwirft gepuffertes Audio nicht; der Audio-Endpunkt -prüft Sitzung und Stationsrecht weiterhin bei jeder Anfrage. -Ein neu gestarteter Stream setzt eine gegenüber seiner Blocknummer vorauseilende -Browser-Blocknummer zurück. Es gibt kein dauerhaftes Eigenschiff-Ambientgeräusch, +prüft Sitzung und Stationsrecht weiterhin bei jeder Anfrage. Die Blocknummerierung +ist über die Lebensdauer des Host-Prozesses monoton: Ein geleerter Stream (ein +Epoch-Schritt nach lokaler Eingabe am Host, eine neue Freigabe) zählt oberhalb aller +bisher gesendeten Nummern weiter und überspringt eine, sodass der Neustart als Lücke +erscheint; ein umgestimmter Empfänger (Peilungsschwenk) überspringt ebenfalls eine +Nummer, damit Browser überblenden statt fremdes Audio zu verbinden. Nur eine Nummer +vor allem je Veröffentlichten (Neustart des Hosts) wird mit Diskontinuität +zurückgesetzt. Es gibt kein dauerhaftes Eigenschiff-Ambientgeräusch, weder lokal noch im Browser; die Tonfreigabe aktiviert nur synthetisierte Alarm-/Gefechtseffekt-Signale und diesen Live-Sonar-/Hubschrauber-Stream. @@ -151,19 +158,28 @@ Der zusaetzliche Audio-WebSocket verwendet das Subprotokoll `u-jagd-audio-v2`, das HttpOnly-Sitzungscookie, den genauen Origin sowie aktive Station und Audiofreigabe. Jede binaere Nachricht mit 2060 Byte enthaelt `UJA2`, eine Little-Endian-Sequenznummer mit 64 Bit und 1024 Mono-PCM-Samples mit 16 Bit -bei 4096 Hz. Sequenzluecken zeigen verworfene Bloecke an. Nach einem langsamen -Client sendet der Server hoechstens die neuesten vier ausstehenden Bloecke. +bei 4096 Hz. Sequenzluecken zeigen uebersprungene Bloecke, einen Epoch-Schritt +oder einen Peilungsschwenk an. Ein ohne Cursor geoeffneter Socket erhaelt hoechstens +die neuesten acht ausstehenden Bloecke; ein Reconnect uebergibt `?after=` +(streng geprueft), sodass nichts erneut gesendet wird, was das Worklet schon haelt; +eine doppelte Nummer zaehlt das Worklet und verwirft sie. Der Audio-Socket +toleriert einen Sendestau von sechs Sekunden, bevor er schliesst. Die HTTP-Abfrage bleibt der Fallback. Beide Transporte nehmen weder Browseraudio noch Simulationsbefehle an. Für die Diagnose auf dem Gerät schreibt `U_JAGD_AUDIO_DEBUG=1` begrenzte, kontaktfreie Werte zu Receiver-Blockrate, Mixer-Unterläufen, verdeckten -Blöcken, Ratenkorrektur, Pufferstand und Verlusten nach +Blöcken, Ratenkorrektur, Pufferstand, leer gelaufenem Mixerkanal, verspäteten +Worker-Durchläufen, Eingangslücken und Verlusten nach `~/.u-jagd/audio_debug.log`; `U_JAGD_PERF_DEBUG=1` ergänzt in `perf_debug.log` -Frame-Spitzen und das Nachholen der Simulationszeit. Im Browser zeigen die -Entwicklerwerkzeuge `window.uJagdAudioDiagnostics` mit Puffersekunden, -Sequenzlücken, verworfenen und verdeckten Blöcken, Wiedergaberate, -Veraltet-Zustand und Transport. Beides bleibt außerhalb der Spielstände. +Frame-Spitzen, die Hauptthread-Zeiten je Phase (Simulation, Audio, Remote-Crew- +Veröffentlichung, Ereignisse, Live-Verkehr, Zeichnen) und das Nachholen der +Simulationszeit. Im Browser zeigen die Entwicklerwerkzeuge +`window.uJagdAudioDiagnostics` mit Puffersekunden, Sequenzlücken, verworfenen +Duplikaten, verdrängten und verdeckten Blöcken, Wiedergaberate, Veraltet-Zustand +und Transport. `tools/audio_soak.py` fährt die gesamte Kette headless mit +simulierten Browsern (oder als Client auf einem anderen Rechner) und meldet die +Kontinuität. Beide Protokolle bleiben außerhalb der Spielstände. Die Sonarrollenprojektion erhält nur die begrenzte Eigenschifffahrt und die TAS-Handhabungsgrenzen, die zur Erklärung eines diff --git a/docs/commander-protocol.md b/docs/commander-protocol.md index c873be18..126b8196 100644 --- a/docs/commander-protocol.md +++ b/docs/commander-protocol.md @@ -115,32 +115,45 @@ are hard-bounded. Sonar audio is live-only, separately granted, bound to the active sonar generation, and filtered on the main thread using the projected Sonar audition mode, band, notch, and gain. The server keeps the last 40 blocks (ten seconds) so a briefly stalled client catches up in order; older blocks are dropped -and reported as a discontinuity. The browser starts playback about one second behind the newest -block. Its AudioWorklet steers that lead by reading the stream up to 2 % faster or slower, -so clock drift and jitter neither drain nor overflow it. On an underrun it plays a -non-periodic granular stand-in built from the last half second and refills half a second -before fresh audio resumes; after two seconds without data it plays quiet neutral noise and -marks the stream stale. Crossfades are applied only at real discontinuities. The uConsole -mixer worker uses the same elastic lead, concealment and two-second limit. A transient -state-poll failure or HTTP 503 does not discard queued audio; the audio endpoint -still checks session and station authority on each request. A restarted stream -rebases a browser cursor that is ahead of its new sequence. There is no continuous -own-ship ambience sound, locally or in the browser; sound opt-in only enables -synthesized alert/combat-effect cues and this live sonar/helicopter stream. +and reported as a discontinuity. The browser starts playback about two seconds (eight +blocks) behind the newest block. Its AudioWorklet steers that lead by reading the stream +up to 2 % faster or slower, so clock drift and jitter neither drain nor overflow it; it +holds at most six seconds. On an underrun it plays a non-periodic granular stand-in built +from the last half second and refills one second (four blocks) before fresh audio resumes; +after three seconds without data it plays quiet neutral noise and marks the stream stale. +Crossfades are applied only at real discontinuities. The uConsole mixer worker uses the +same elastic scheme with a 1.5 s lead, a five-second queue limit and the same +three-second stale rule; the main loop catches up to 2.5 s of a stalled frame, so audio +of that length is concealed, never cut. A transient state-poll failure or HTTP 503 does +not discard queued audio; the audio endpoint still checks session and station authority +on each request. Block numbering is monotonic for the life of the host process: a +cleared stream (a world-epoch step after the host's local input, a fresh grant) continues +above every number sent before and skips one, so the restart is a gap; a retuned +receiver skips one number as well, so browsers crossfade instead of joining unrelated +audio. Only a cursor ahead of everything ever published (a host restart) is rebased +with a discontinuity. There is no continuous own-ship ambience sound, locally or in the +browser; sound opt-in only enables synthesized alert/combat-effect cues and this live +sonar/helicopter stream. The optional audio WebSocket uses subprotocol `u-jagd-audio-v2`, the HttpOnly session cookie, exact Origin, active station and audio grant. Each 2060-byte binary message is `UJA2`, a little-endian unsigned 64-bit sequence, and 1024 mono signed 16-bit -samples at 4096 Hz. Sequence gaps signal dropped blocks; the server sends at most -the newest four pending blocks after a slow client. HTTP audio polling remains the -fallback. Neither transport accepts browser audio or simulation commands. +samples at 4096 Hz. Sequence gaps signal skipped blocks, an epoch step or a retune. A +socket opened without a cursor receives at most the newest eight pending blocks; a +reconnect passes `?after=` (strictly validated) so nothing the worklet already +holds is re-sent, and a duplicate number is counted and discarded by the worklet. The +audio socket tolerates a six-second send stall before it closes. HTTP audio polling +remains the fallback. Neither transport accepts browser audio or simulation commands. For on-device diagnosis, `U_JAGD_AUDIO_DEBUG=1` writes bounded, contact-free receiver block rate, mixer underruns, concealed blocks, rate correction, queue -fill and loss counters to `~/.u-jagd/audio_debug.log`; `U_JAGD_PERF_DEBUG=1` -adds frame-time peaks and simulation catch-up to `perf_debug.log`. Browser +fill, mixer channel idle events, late worker iterations, input gaps and loss +counters to `~/.u-jagd/audio_debug.log`; `U_JAGD_PERF_DEBUG=1` adds frame-time +peaks, per-phase main-thread times (simulation, audio, Remote Crew publish, events, +live traffic, draw) and simulation catch-up to `perf_debug.log`. Browser developer tools can read the bounded `window.uJagdAudioDiagnostics` snapshot -(buffer seconds, sequence gaps, dropped blocks, concealed blocks, playback -rate, stale state and transport). Neither is persisted in -game saves. +(buffer seconds, sequence gaps, dropped duplicate blocks, evicted blocks, concealed +blocks, playback rate, stale state and transport). `tools/audio_soak.py` runs the +whole chain headless with simulated browsers (or as a client on another machine) +and reports continuity. Neither log is persisted in game saves. The Sonar role receives only bounded own-ship speed and TAS handling limits needed to explain a disabled array control; hover reasons never inspect hidden entities. diff --git a/docs/install-uconsole.en.md b/docs/install-uconsole.en.md index 1b891ef9..1c3a840d 100644 --- a/docs/install-uconsole.en.md +++ b/docs/install-uconsole.en.md @@ -111,6 +111,21 @@ Continue to launch the game itself without `sudo`. The helper can only create and remove the transient U-Jagd hotspot. Remove the system integration with `sudo ./packaging/uconsole/install-hotspot-helper.sh --uninstall`. +**Wi-Fi power saving:** the Compute Module's Wi-Fi driver (brcmfmac) switches the +radio off between packets in power-save mode, which causes latency spikes of a +few hundred milliseconds that browsers may hear as sonar dropouts. Turn power +saving off on the uConsole for Remote Crew (`iw dev wlan0 get power_save` shows +the state): + +```sh +sudo iw dev wlan0 set power_save off +``` + +Permanently through NetworkManager: create +`/etc/NetworkManager/conf.d/wifi-powersave.conf` containing `[connection]` and +`wifi.powersave = 2`, then restart the service. The same applies to browser PCs +on that Wi-Fi. + **Security:** HTTP is unencrypted. Use only a trusted LAN. No Internet hosting, wildcard binding, CDN, remote ROE/time/save controls, or hidden entity data are exposed. See [Remote Crew setup](commander-coop.md) and diff --git a/docs/install-uconsole.md b/docs/install-uconsole.md index 05bd543b..8aefc7f5 100644 --- a/docs/install-uconsole.md +++ b/docs/install-uconsole.md @@ -116,6 +116,21 @@ das Erzeugen und Entfernen des fluechtigen U-Jagd-Hotspots. Zum Entfernen der Systemintegration dient `sudo ./packaging/uconsole/install-hotspot-helper.sh --uninstall`. +**WLAN-Stromsparen:** Der WLAN-Treiber des Compute Module (brcmfmac) schaltet +im Stromsparmodus die Funkverbindung zwischen Paketen ab; das erzeugt +Latenzspitzen von einigen hundert Millisekunden, die im Browser als Sonar- +Aussetzer hörbar werden können. Für Remote Crew das Stromsparen auf dem uConsole +abschalten (`iw dev wlan0 get power_save` zeigt den Zustand): + +```sh +sudo iw dev wlan0 set power_save off +``` + +Dauerhaft über NetworkManager: eine Datei +`/etc/NetworkManager/conf.d/wifi-powersave.conf` mit `[connection]` und +`wifi.powersave = 2` anlegen und den Dienst neu starten. Dasselbe gilt für +Browser-PCs im selben WLAN. + **Sicherheit:** HTTP ist unverschlüsselt. Nur in einem vertrauenswürdigen LAN verwenden. Internet-Hosting, Wildcard-Bindung, CDN, entfernte ROE-/Zeit-/Speichersteuerung oder verborgene Entitätsdaten werden nicht diff --git a/docs/manual/manual.de.md b/docs/manual/manual.de.md index b985fd8e..04c12fb7 100644 --- a/docs/manual/manual.de.md +++ b/docs/manual/manual.de.md @@ -377,7 +377,7 @@ Gefechtslage: - Verstärkung (`I`/`O`) ändert nur Anzeige und Audio, nicht die Ortung. Schwarzwert (`Ctrl+I`/`Ctrl+O`) und Kontrast (`Shift+I`/`Shift+O`) heben schwache Spuren hervor; `Shift+C` wechselt die Phosphorfarbe. - `D` oder `A`/`B`/`H` wählen Breitband-, gefiltertes oder Überlagerungs-Abhören. Überlagerung verschiebt das tiefe Band auf etwa 700 Hz, damit tiefe Töne hörbar werden. -- Das Abhör-Audio läuft etwa eine Sekunde hinter der Anzeige, damit es auch unter Last nicht aussetzt. Nach dem Schwenken der Abhörpeilung geht der alte Strahl nach etwa einer Sekunde in den neuen über; der Ton bricht nicht ab. +- Das Abhör-Audio läuft etwa anderthalb Sekunden hinter der Anzeige (Remote-Crew-Browser etwa zwei Sekunden), damit es auch unter Last nicht aussetzt. Nach dem Schwenken der Abhörpeilung geht der alte Strahl nach dieser Verzögerung in den neuen über; der Ton bricht nicht ab. - TAS unter die gemessene Schicht legen, um tiefe Ziele zu hören; das HMS für flache Ziele nutzen. Beide Arrays arbeiten parallel. - Die TMA-Seite zeigt die aus der übernommenen Lösung abgeleitete Annäherungsrate: positiv heißt, das Ziel kommt näher. - Weichen TAS und HMS um 9 Grad oder mehr ab, den Kontakt als möglichen Geist behandeln (die Anzeige markiert ihn) und durch eine Wende klären. diff --git a/docs/manual/manual.en.md b/docs/manual/manual.en.md index 908a0c94..364d8fa0 100644 --- a/docs/manual/manual.en.md +++ b/docs/manual/manual.en.md @@ -376,7 +376,7 @@ Combat situation: - Gain (`I`/`O`) changes display and audio only, not detection. Black level (`Ctrl+I`/`Ctrl+O`) and contrast (`Shift+I`/`Shift+O`) help faint traces stand out; `Shift+C` changes the phosphor colour. - `D` or `A`/`B`/`H` choose broadband, filtered or heterodyne audition. Heterodyne shifts the low band up to about 700 Hz so low tonals become audible. -- The listening audio runs about one second behind the display so a busy moment never interrupts it. After steering the listening bearing the old beam fades into the new one after about a second; the stream is not cut. +- The listening audio runs about one and a half seconds behind the display (Remote Crew browsers about two seconds) so a busy moment never interrupts it. After steering the listening bearing the old beam fades into the new one after that delay; the stream is not cut. - Put the TAS below the measured layer to hear deep targets; keep the HMS for shallow ones. Both arrays run in parallel. - The TMA page shows the closing rate derived from the accepted solution: positive means the target is closing. - If the TAS and HMS disagree by 9 degrees or more, treat the contact as a possible ghost (the display flags it) and turn to resolve it. diff --git a/docs/resume.md b/docs/resume.md index 99a30374..2e8d717e 100644 --- a/docs/resume.md +++ b/docs/resume.md @@ -1073,3 +1073,51 @@ ist exakt; v11-Staende von 1.0.0 werden abgelehnt. Versioniert als 1.1.0. Verhalten der 4-s-Radarumlaeufe auf dem OPZ-Bild. - Merge: der Branch entstand parallel zu einer Handbuch-Session auf `main` (AGENTS.md, README, Handbuch); beim Zusammenfuehren diese Dateien pruefen. + +## Sonar-Audio ohne Aussetzer (2026-09-26) + +Die seit dem 22.09. offene Diagnose der Browser-Aussetzer ist abgeschlossen; die +Analyse lief auf dem Zielgeraet (CM5, 16 GB) mit dem neuen Lasttest. + +- Ursache der Aussetzer "nach Tastendruck am uConsole": jede lokale + Eingabeaenderung (F1, F9, Optionen, Zahleneingabe) erhoehte die Welt-Epoche, + `prepare_*_audio` leerte den Ring und setzte die Blocknummer auf 0. Der + Browser verband den Socket neu, das Worklet behielt aber `lastSequence` und + verwarf jeden neuen Block (`sequence <= lastSequence`), bis die Zaehlung den + alten Stand ueberholte: Granular-Ersatz, dann Stale-Rauschen, so lange, wie + der Client vorher zugehoert hatte. Fix: Nummerierung je Rolle monoton ueber + die Server-Lebensdauer (Clear ueberspringt eine Nummer), Retune markiert eine + Diskontinuitaet (`mark_audio_discontinuity`), Reconnect mit `?after=` statt + Neusendung, Duplikate werden im Worklet gezaehlt statt stumm verworfen. +- Messung: Empfaenger-Synthese 4-19 ms pro 0,25-s-Block (2-24 Quellen), Filter, + Resampling und PCM zusammen unter 0,6 ms; die Audioerzeugung war nie das + Problem. Der Remote-Crew-Publish kostete pro 2-Hz-Veroeffentlichung 60-120 ms + Hauptthread (5 Mio. `deepcopy`-Aufrufe, Requantisierung der kompletten + 600-s-Sonar-Historien, `json.loads`/Re-Encode der Sonarprojektion, Roster pro + Frame). Nach Zeilen-Cache je Sonarstation (schwach referenziert, exakt gleiche + Ergebnisse), flachen Rollenkopien, Bytes-basierter Kompaktprojektion und 4-Hz- + Roster: rund ein Sechstel der Pump-Zeit. +- Puffer fuer 16 GB: lokal Vorlauf/Ziel 1,5 s, Warteschlange 5 s, Refill 1 s, + Stale 3 s, SDL-Mixerpuffer 2048 Samples (93 ms); Browser Prime/Ziel 2 s, Max + 6 s, Refill 4 Bloecke, Stale 3 s; `SIM_CATCHUP_MAX_S` 2,5 s (Invariante: + Warteschlange >= Ziel + Catch-up + Block, damit im Aufholen nie ein Block + abgelehnt und aus dem Zwei-Block-Empfaengerfenster verdraengt wird); + Audio-Socket 6 s Sendetoleranz, neueste acht Bloecke fuer cursorlose Sockets. +- Neue Zaehler: `channel_idle` (Mixerkanal leer bei geprimtem Strom = hoerbarer + Dip), `pump_late`/`pump_late_max_ms`, `input_gaps`; `perf_debug.log` mit + `commander_max_ms`, `events_ms`, `traffic_ms`; Server `audio_stream_stats()` + (uebersprungene Bloecke, Sendetimeouts, Diskontinuitaeten, Verbindungen); + Browser `droppedBlocks`/`evictedBlocks`. +- `tools/audio_soak.py host` (echter Mixer oder `--dummy-audio`, N Clients, + Epoch-Sprung/Retune-Takt, `--profile`) und `client` (PC im WLAN). Ergebnis + auf dem CM5 mit echtem Mixer, 9 Clients, 14 Epoch-Spruengen, 4 Retunes ueber + 67 s: 0 Unterlaeufe, 0 leere Kanaele, 0 Stillen > 0,75 s in beiden Streams, + frame_max ausserhalb des Starts 168 ms (vor Phase D), sim_dropped 0. +- Regressionstests: monotone Sequenzen je Rolle, Resume-Cursor, Duplikat- + Zaehlung im Worklet, Bridge-Diskontinuitaet bei Retune, Browsertest prueft + jetzt weiterlaufende, streng steigende Bloecke nach Epoch-Spruengen, Idle-/ + Late-Zaehler, Puffer-Invariante, Soak-Werkzeug headless. +- Offen: Hoerabnahme mit echtem Browser-PC ueber WLAN (`tools/audio_soak.py + client`, `window.uJagdAudioDiagnostics`), WLAN-Stromsparen am uConsole + abschalten (docs/install-uconsole). `test_real_v2_role_states_survive_...` + (Helikopter-LOFAR-Ansicht zu klein) schlug bereits vor dieser Arbeit fehl. diff --git a/src/audio/engine.py b/src/audio/engine.py index 33abc8f0..20cd013a 100644 --- a/src/audio/engine.py +++ b/src/audio/engine.py @@ -26,20 +26,30 @@ class AudioEngine: ALERT_CHANNEL = 3 FADE_MS = 35 SONAR_HOLD_MAX = 2 - SONAR_BUFFER_S = 1.0 - SONAR_BUFFER_MAX_S = 2.0 + # Buffered listening starts once SONAR_BUFFER_S is queued (the standing + # lead behind the display) and retains at most SONAR_BUFFER_MAX_S. The + # maximum must cover target + SIM_CATCHUP_MAX_S + one block (with margin), + # so a catch-up burst after a long frame never rejects a block (a rejected + # block would be evicted from the receiver's two-block window: a gap). + SONAR_BUFFER_S = 1.5 + SONAR_BUFFER_MAX_S = 5.0 # Elastic buffered playback: the queued (not yet mixer-held) duration is # steered towards SONAR_TARGET_S by resampling at most SONAR_RATE_MAX # faster or slower, in SONAR_RATE_STEP increments. After an underrun the # queue refills to SONAR_REFILL_S under concealment instead of stuttering. - SONAR_TARGET_S = 0.5 + # The 1.5 s lead outlasts main-thread stalls (Remote Crew publication, + # catch-up frames) that the 2 % steering could never make up. + SONAR_TARGET_S = 1.5 SONAR_RATE_MAX = 0.02 SONAR_RATE_STEP = 0.0025 SONAR_RATE_GAIN = 0.05 SONAR_LEVEL_SMOOTHING = 0.05 - SONAR_REFILL_S = 0.5 - SONAR_STALE_S = 2.0 + SONAR_REFILL_S = 1.0 + SONAR_STALE_S = 3.0 SONAR_CONCEAL_GRAIN_S = 0.128 + # A pump iteration later than this counts as late: the mixer holds only + # the current and one queued block, so a starved worker lets it run dry. + SONAR_PUMP_LATE_S = 0.25 # Post-limiter per-channel PCM ceilings, NOT input volume caps. The gains # keep all three reserved buses below full scale even at coincident peaks. @@ -84,6 +94,16 @@ class AudioEngine: self.sonar_stale = False self.sonar_local_underruns = 0 self.sonar_neutral_blocks = 0 + # True audible gaps: the primed mixer channel was found idle. + self.sonar_channel_idle = 0 + # Worker scheduling: iterations later than SONAR_PUMP_LATE_S, and the + # longest gap between two iterations since the last debug line. + self.sonar_pump_late = 0 + self.sonar_pump_late_max_s = 0.0 + self._sonar_pump_last_at = None + # Receiver sequence breaks seen by the producer (retunes and blocks + # the frame loop never got to play before the receiver replaced them). + self.sonar_input_gaps = 0 self._sonar_hold_streak = 0 self._sonar_buffer = deque() self._sonar_buffer_duration = 0.0 @@ -305,8 +325,8 @@ class AudioEngine: With hold=True an idle channel re-plays the previous block (bounded to SONAR_HOLD_MAX consecutive holds) before the new one, so simulation clock lag does not open a silent gap at the 4 Hz block boundary. - Buffered local listening retains at most two seconds of sounds. The - mixer still holds only its current and next sound. + Buffered local listening retains at most SONAR_BUFFER_MAX_S of sounds. + The mixer still holds only its current and next sound. Volume spans 0..1 before the bus limiter. Linear streaming resampling delays by one source sample, so interpolation never predicts a future sample or replaces the start of every block with a constant crossfade. @@ -535,14 +555,28 @@ class AudioEngine: with self._sonar_lock: if (not self._sonar_buffered or not self.available or pygame.mixer.get_init() is None): + self._sonar_pump_last_at = None return try: if not self._sonar_primed: if self._sonar_buffer_duration < self.SONAR_BUFFER_S - 1e-6: return self._sonar_primed = True + self._sonar_pump_last_at = None + now = time.monotonic() + if self._sonar_pump_last_at is not None: + gap = now - self._sonar_pump_last_at + if gap > self.SONAR_PUMP_LATE_S: + self.sonar_pump_late += 1 + self.sonar_pump_late_max_s = max(self.sonar_pump_late_max_s, gap) + self._sonar_pump_last_at = now if self._sonar_channel.get_queue() is not None: return + if (self._sonar_last_fresh_at is not None + and not self._sonar_channel.get_busy()): + # The mixer ran dry between two iterations: an audible dip + # (the next play() fades in) that no other counter sees. + self.sonar_channel_idle += 1 if (self._sonar_refilling and self._sonar_buffer_duration >= self.SONAR_REFILL_S - 1e-6): self._sonar_refilling = False @@ -621,6 +655,7 @@ class AudioEngine: def discontinue_sonar_input(self) -> None: """Restart resampling after a lost receiver block without cutting playback.""" with self._sonar_lock: + self.sonar_input_gaps += 1 self._sonar_rate = None self._sonar_input_count = 0 self._sonar_output_count = 0 @@ -667,6 +702,7 @@ class AudioEngine: self._sonar_last_fresh_at = None self.sonar_stale = False self._sonar_hold_streak = 0 + self._sonar_pump_last_at = None def stop(self) -> None: self.stop_sonar() @@ -755,17 +791,23 @@ class AudioEngine: produced = (0 if self._audio_debug_receiver_last is None else max(0, receiver_blocks - self._audio_debug_receiver_last)) self._audio_debug_receiver_last = receiver_blocks + with self._sonar_lock: + late_max_ms = self.sonar_pump_late_max_s * 1000.0 + self.sonar_pump_late_max_s = 0.0 line = ("t={t:.1f} receiver_blocks_per_s={rb} sonar_drops={sd} " "sonar_holds={sh} alert_drops={ad} " "sonar_underruns={su} sonar_concealed={sc} sonar_neutral={sn} " "sonar_stale={ss} buffer_s={bs:.2f} rate_adj={ra:+.4f} " - "evictions={ev} rate={r} ch={c}\n").format( + "channel_idle={ci} pump_late={pl} pump_late_max_ms={pm:.0f} " + "input_gaps={ig} evictions={ev} rate={r} ch={c}\n").format( sc=self.sonar_concealed_blocks, ra=self.sonar_rate_adjust, t=time.monotonic(), sd=self.sonar_dropped_blocks, sh=self.sonar_holds, ad=self.alert_dropped_events, ev=evictions, rb=produced, su=self.sonar_local_underruns, sn=self.sonar_neutral_blocks, ss=int(self.sonar_stale), bs=self._sonar_buffer_duration, + ci=self.sonar_channel_idle, pl=self.sonar_pump_late, pm=late_max_ms, + ig=self.sonar_input_gaps, r=self.sample_rate, c=self.channels) append_bounded_log(config.SAVE_DIR, "audio_debug.log", line, self.DEBUG_LOG_MAX_BYTES) diff --git a/src/commander/bridge.py b/src/commander/bridge.py index d3729cea..bcfdfcf6 100644 --- a/src/commander/bridge.py +++ b/src/commander/bridge.py @@ -1744,8 +1744,10 @@ class CommanderBridge: navigation_authority=self._navigation_lease, navigation=self.navigation_proposal) self._publish_events_v2(server, game) + # Fresh objects per publication, encoded above and never mutated + # afterwards; _publish_role_simlog copies the ones it appends. self._last_v2_states = (None if redacted or world_replaced else - {role: deepcopy(states[role]) for role in ROLES}) + {role: states[role] for role in ROLES}) self._last_publish = now self._dirty = False @@ -1810,7 +1812,10 @@ class CommanderBridge: return for sequence, samples in receiver.blocks_since(self._audio_receiver_sequence): if sequence != self._audio_receiver_sequence + 1: + # The receiver restarted (retune): the browser must crossfade. self._audio_filter.reset_audition_audio() + if hasattr(server, "mark_audio_discontinuity"): + server.mark_audio_discontinuity("sonar") self._audio_filter.audition_mode = game.sonar.audition_mode self._audio_filter.band_low_hz = game.sonar.band_low_hz self._audio_filter.band_high_hz = game.sonar.band_high_hz @@ -1852,6 +1857,8 @@ class CommanderBridge: audition = self._uboot_audio_filter if sequence != self._uboot_audio_receiver_sequence + 1: audition.reset_audition_audio() + if hasattr(server, "mark_audio_discontinuity"): + server.mark_audio_discontinuity("uboot_sonar") audition.audition_mode = sonar.audition_mode audition.band_low_hz = sonar.band_low_hz audition.band_high_hz = sonar.band_high_hz @@ -1898,6 +1905,8 @@ class CommanderBridge: audition = self._helicopter_audio_filter if sequence != self._helicopter_audio_receiver_sequence + 1: audition.reset_audition_audio() + if hasattr(server, "mark_audio_discontinuity"): + server.mark_audio_discontinuity("helicopter") controls = game.helo_audition audition.audition_mode = controls.audition_mode audition.band_low_hz = controls.band_low_hz diff --git a/src/commander/local.py b/src/commander/local.py index 2a80a0e6..7e73d5d5 100644 --- a/src/commander/local.py +++ b/src/commander/local.py @@ -46,6 +46,7 @@ class CommanderConsole: self.selection = 0 self.connected = False self.active_crew = False + self._statuses_cache = None self.pairing_code = None self._prepared = False self._translations = None @@ -353,7 +354,12 @@ class CommanderConsole: self.connected = self.server.connected self.active_crew = False if hasattr(self.server, "client_statuses"): - statuses = self.server.client_statuses() + # Building the roster copies every session; 4 Hz is plenty for + # the two flags read here and saves main-thread time per frame. + if (self._statuses_cache is None or self._statuses_cache[0] != id(self.server) + or now - self._statuses_cache[1] >= .25): + self._statuses_cache = (id(self.server), now, self.server.client_statuses()) + statuses = self._statuses_cache[2] self.connected = self.connected or bool(statuses) self.active_crew = self.active_crew or any( status["active_station"] in ROLES for status in statuses) diff --git a/src/commander/projections.py b/src/commander/projections.py index c13eaba5..39a93cf3 100644 --- a/src/commander/projections.py +++ b/src/commander/projections.py @@ -7,6 +7,7 @@ simulation object. from copy import deepcopy import math +import weakref from src.core import config, opfor, plot from src.core.autocrew import AUTOCREW_STATIONS @@ -61,8 +62,16 @@ def _own_navigation(game): "rudder_angle", "yaw_rate", "turn_radius_nm")} +_ATOMIC = (type(None), bool, int, float, str) + + +def _detach(value): + """Detached copy of a projection value; scalars need no deepcopy call.""" + return value if type(value) in _ATOMIC else deepcopy(value) + + def _observation(row, fields): - observation = {key: deepcopy(row[key]) for key in fields} + observation = {key: _detach(row[key]) for key in fields} if "label" in observation and "_display_id" in row: observation["label"] = row["_display_id"] return observation @@ -270,6 +279,37 @@ def _sonar_station_down(game): return bool(down()) if down is not None else game.damage.station_down("sonar") +# Quantized history rows per sonar workstation. A history row is appended once +# and never changes, so its projected bins depend only on the row and the +# operator settings; recomputing 600 s of rows on every 2 Hz publication was +# the largest main-thread cost of Remote Crew. Keyed weakly by the workstation +# (no aliasing after a world reset); rows are keyed by identity and stamp and +# pruned to the rows still shown, so the cache is bounded by the histories. +_ROW_CACHE = weakref.WeakKeyDictionary() + + +def _cached_rows(sonar, name, settings, stamps, rows, compute): + """Return ``[(stamp, bins)]`` for the rows, computing only unseen ones.""" + caches = _ROW_CACHE.get(sonar) + if caches is None: + caches = _ROW_CACHE[sonar] = {} + cache = caches.get(name) + if cache is None or cache[0] != settings: + cache = caches[name] = (settings, {}) + previous = cache[1] + current = {} + result = [] + for stamp, values in zip(stamps, rows): + key = (id(values), stamp) + bins = previous.get(key) + if bins is None: + bins = compute(values) + current[key] = bins + result.append((stamp, bins)) + caches[name] = (settings, current) + return result + + def _sonar_visualization(game, rows, sonar_refs): sonar = game.sonar receiver = sonar.receiver @@ -284,11 +324,15 @@ def _sonar_visualization(game, rows, sonar_refs): bb_bins = _BROADBAND_LONG_BINS_MAX if long_available else _BROADBAND_BINS_MAX bb_rows = list(bb_source)[-bb_limit:] bb_times = list(bb_time_source)[-len(bb_rows):] - for stamp, values in zip(bb_times, bb_rows): + bb_gain = 10 ** (sonar.gain_db / 20) + + def broadband_bins(values): source_bins = (_mean_binned_series(values, bb_bins) if long_available else _series(values, bb_bins)) - bins = [round(min(1.0, max(0.0, value * 10 ** (sonar.gain_db / 20))), 5) - for value in source_bins] + return [round(min(1.0, max(0.0, value * bb_gain)), 5) for value in source_bins] + + for stamp, bins in _cached_rows(sonar, "broadband", (long_available, sonar.gain_db), + bb_times, bb_rows, broadband_bins): age = _age(game.sim_t, stamp) if age is not None and bins: broadband.append(dict(age_s=age, bins=bins)) @@ -297,9 +341,25 @@ def _sonar_visualization(game, rows, sonar_refs): lf_rows = list(sonar.lofar_history)[-_HISTORY_ROWS_MAX:] lf_times = list(sonar.lofar_times)[-len(lf_rows):] lf_bearings = list(sonar.lofar_bearings)[-len(lf_rows):] - for stamp, bearing, values in zip(lf_times, lf_bearings, lf_rows): - bins = [round(value, 5) for value in sonar.process_lofar_column( + # Everything process_lofar_column reads besides the column itself. The + # own-shaft notch follows the observer's speed continuously, so the key + # holds the set of notched bins, which only changes when a bin enters or + # leaves the window: exact results, no recompute while accelerating. + shaft = 10.0 + 1.9 * observer.speed + notched = (tuple(index for index in range(config.LOFAR_BINS) + if abs(config.lofar_bin_freq(index) - shaft) < 5.0) + if sonar.notch_enabled else ()) + lofar_settings = (sonar.gain_db, sonar.band_low_hz, sonar.band_high_hz, + bool(sonar.notch_enabled), getattr(sonar, "operator_notch_hz", None), + notched) + + def lofar_bins(values): + return [round(value, 5) for value in sonar.process_lofar_column( _series(values, config.LOFAR_BINS), observer)] + + for (stamp, bins), bearing in zip( + _cached_rows(sonar, "lofar", lofar_settings, lf_times, lf_rows, lofar_bins), + lf_bearings): age = _age(game.sim_t, stamp) if age is not None and _number(bearing) is not None and bins: lofar.append(dict(age_s=age, bearing=_number(bearing), bins=bins)) @@ -344,8 +404,9 @@ def _sonar_visualization(game, rows, sonar_refs): demon_history = [] dm_rows = list(getattr(sonar, "demon_history", ()))[-_DEMON_HISTORY_ROWS_MAX:] dm_times = list(getattr(sonar, "demon_times", ()))[-len(dm_rows):] - for stamp, values in zip(dm_times, dm_rows): - bins = [round(value, 5) for value in _series(values, 80)] + for stamp, bins in _cached_rows( + sonar, "demon", (), dm_times, dm_rows, + lambda values: [round(value, 5) for value in _series(values, 80)]): age = _age(game.sim_t, stamp) if age is not None and bins: demon_history.append(dict(age_s=age, bins=bins)) @@ -1061,17 +1122,20 @@ def build_role_states(game, status, rows, target_ref, focus_ref, ref_by_track, "eloka": _eloka(game, rows, esm_refs, candidate_refs), } result = {} + overview = [dict(station=key, enabled=bool(game.autocrew.enabled[key]), + status=game.autocrew.status(game, key)) + for key in AUTOCREW_STATIONS] for role in ROLE_NAMES: - state = deepcopy(common) + # Shallow per-role copies: the common blocks are fresh for this + # publication, shared read-only between roles, encoded at once and + # never mutated afterwards (a deep copy per role cost more than the + # projection itself on the uConsole). + state = dict(common) state["role"] = role - overview = [dict(station=key, enabled=bool(game.autocrew.enabled[key]), - status=game.autocrew.status(game, key)) - for key in AUTOCREW_STATIONS] - if role != "eloka": - state["audio"]["events"] = [ - event for event in state["audio"]["events"] - if event["cue"] != "esm_contact" - ] + state["audio"] = dict(common["audio"], events=[ + dict(event) for event in common["audio"]["events"] + if role == "eloka" or event["cue"] != "esm_contact" + ]) state["autocrew"] = dict(enabled=bool(game.autocrew.enabled[role]), status=game.autocrew.status(game, role)) # The whole crew's automation state (as the uConsole F3 overview): diff --git a/src/commander/server.py b/src/commander/server.py index 60014351..56ffe657 100644 --- a/src/commander/server.py +++ b/src/commander/server.py @@ -78,6 +78,13 @@ SONAR_AUDIO_BYTES = 2048 # Ten seconds of blocks: a client that stalls for a moment catches up in order # instead of losing audio; older blocks are dropped and reported as a discontinuity. SONAR_AUDIO_RING_BLOCKS = 40 +# A (re)connecting audio socket without a resume cursor receives at most this +# many pending blocks (the browser's priming lead); older ones are skipped and +# the skip shows up as a sequence gap. +SONAR_AUDIO_RESUME_BLOCKS = 8 +# Inactivity timeout of an upgraded audio socket. A Wi-Fi stall shorter than +# this keeps the stream; the request-phase timeout (1.5 s) does not apply. +AUDIO_SOCKET_TIMEOUT_S = 6.0 SONAR_AUDIO_FRAMES = 1024 SONAR_AUDIO_RATE = 4096 SONAR_STREAM_ROUTE = "/ws/v2/sonar" @@ -88,6 +95,18 @@ _AUDIO_POLL_ROUTES = {"/api/v2/sonar/audio": "sonar", "/api/v2/helicopter/audio": "helicopter", "/api/v2/uboot/audio": "uboot_sonar"} VOICE_STREAM_ROUTE = "/ws/v2/voice" +_AUDIO_RESUME_QUERY = re.compile(r"after=(0|[1-9][0-9]{0,15})").fullmatch + + +def _audio_resume_cursor(query: str): + """None (no cursor), an int cursor, or False for a malformed query.""" + if query == "": + return None + match = _AUDIO_RESUME_QUERY(query) + if match is None: + return False + value = int(match.group(1)) + return value if value <= _SAFE_INTEGER_MAX else False SONAR_STREAM_MAGIC = b"UJS2" SONAR_STREAM_VERSION = 1 SONAR_STREAM_HEADER_BYTES = 60 @@ -812,6 +831,7 @@ class CommanderServer: self._uboot_audio_sequence = 0 self._audio_condition = threading.Condition(self._lock) self._audio_clients = {} + self._audio_stats = {} self._sonar_stream_sequence = 0 self._sonar_stream_context = None self._sonar_stream_payload = None @@ -1000,21 +1020,36 @@ class CommanderServer: self._rotate_code_locked() def _clear_sonar_audio_locked(self): + # Numbering never restarts while the server lives: a browser worklet + # de-duplicates by sequence, so a restart at 1 would make it drop every + # new block until the count passed the old one. A cleared stream that + # had content skips one number so the restart shows as a gap. + if self._sonar_audio: + self._sonar_audio_sequence += 1 self._sonar_audio.clear() self._sonar_audio_context = None - self._sonar_audio_sequence = 0 self._audio_condition.notify_all() def _clear_helicopter_audio_locked(self): + # Numbering never restarts while the server lives: a browser worklet + # de-duplicates by sequence, so a restart at 1 would make it drop every + # new block until the count passed the old one. A cleared stream that + # had content skips one number so the restart shows as a gap. + if self._helicopter_audio: + self._helicopter_audio_sequence += 1 self._helicopter_audio.clear() self._helicopter_audio_context = None - self._helicopter_audio_sequence = 0 self._audio_condition.notify_all() def _clear_uboot_audio_locked(self): + # Numbering never restarts while the server lives: a browser worklet + # de-duplicates by sequence, so a restart at 1 would make it drop every + # new block until the count passed the old one. A cleared stream that + # had content skips one number so the restart shows as a gap. + if self._uboot_audio: + self._uboot_audio_sequence += 1 self._uboot_audio.clear() self._uboot_audio_context = None - self._uboot_audio_sequence = 0 self._audio_condition.notify_all() def _clear_role_audio_locked(self, role): @@ -1916,14 +1951,17 @@ class CommanderServer: if (role == "sonar" and state.get("role") == "sonar" and isinstance(state.get("sonar"), dict) and isinstance(state["sonar"].get("visualization"), dict)): - compact = json.loads(state_bytes.decode("ascii")) - visual = compact["sonar"]["visualization"] - visual["broadband"]["history"] = [] - visual["lofar"]["history"] = [] - visual["lofar"]["spectrum"] = [] - visual["demon"]["history"] = [] - visual["demon"]["spectrum"] = [] - compact_sonar = _json_bytes(compact) + # Shallow copies down to the streamed arrays: the poll view + # shares every other (immutable, already encoded) value. + visual = dict(state["sonar"]["visualization"]) + for name, keys in (("broadband", ("history",)), + ("lofar", ("history", "spectrum")), + ("demon", ("history", "spectrum"))): + section = visual.get(name) + if isinstance(section, dict): + visual[name] = dict(section, **{key: [] for key in keys}) + compact_sonar = _json_bytes( + dict(state, sonar=dict(state["sonar"], visualization=visual))) with self._lock: self._v2_states = encoded_states self._v2_charts = encoded_charts @@ -2143,6 +2181,45 @@ class CommanderServer: with self._lock: self._clear_uboot_audio_locked() + def mark_audio_discontinuity(self, role: str) -> bool: + """Skip one sequence number of a live stream (main thread only). + + The receiver restarted (a retuned listening bearing), so the next block + does not continue the previous waveform. Every browser transport sees + the gap and crossfades instead of joining unrelated audio. Nothing is + marked on an unbound stream. + """ + if threading.current_thread() is not threading.main_thread(): + raise RuntimeError("audio discontinuity requires the main thread") + if role not in SONAR_AUDIO_ROLES: + raise ValueError("unknown audio role") + with self._lock: + if self._audio_ring(role)[1] is None: + return False + if role == "sonar": + self._sonar_audio_sequence += 1 + elif role == "helicopter": + self._helicopter_audio_sequence += 1 + else: + self._uboot_audio_sequence += 1 + self.audio_stream_stats_locked(role)["discontinuities"] += 1 + return True + + def audio_stream_stats_locked(self, role: str) -> dict: + """Bounded per-role transport counters (diagnostics only).""" + stats = self._audio_stats.get(role) + if stats is None: + stats = self._audio_stats[role] = { + "skipped_blocks": 0, "send_timeouts": 0, "discontinuities": 0, + "connections": 0} + return stats + + def audio_stream_stats(self) -> dict: + """Detached copy of the per-role audio transport counters.""" + with self._lock: + return {role: dict(self.audio_stream_stats_locked(role)) + for role in SONAR_AUDIO_ROLES} + def _uboot_audio_holder_locked(self): return next(((digest, session) for digest, session in self._sessions_v2.items() @@ -2197,6 +2274,7 @@ class CommanderServer: return False if self._uboot_audio_sequence >= _SAFE_INTEGER_MAX: self._clear_uboot_audio_locked() + self._uboot_audio_sequence = 0 self._uboot_audio_context = context self._uboot_audio_sequence += 1 self._uboot_audio.append((self._uboot_audio_sequence, pcm)) @@ -2246,6 +2324,10 @@ class CommanderServer: != station_generation or context != self._helicopter_audio_context): self._clear_helicopter_audio_locked() return False + if self._helicopter_audio_sequence >= _SAFE_INTEGER_MAX: + self._clear_helicopter_audio_locked() + self._helicopter_audio_sequence = 0 + self._helicopter_audio_context = context self._helicopter_audio_sequence += 1 self._helicopter_audio.append((self._helicopter_audio_sequence, pcm)) self._audio_condition.notify_all() @@ -2304,6 +2386,7 @@ class CommanderServer: return False if self._sonar_audio_sequence >= _SAFE_INTEGER_MAX: self._clear_sonar_audio_locked() + self._sonar_audio_sequence = 0 self._sonar_audio_context = context self._sonar_audio_sequence += 1 self._sonar_audio.append((self._sonar_audio_sequence, pcm)) @@ -2789,8 +2872,12 @@ class _Handler(BaseHTTPRequestHandler): pass self.close_connection = True - def _audio_websocket(self, role): - """Send detached PCM to the current audio lease; never read game state.""" + def _audio_websocket(self, role, after=None): + """Send detached PCM to the current audio lease; never read game state. + + ``after`` is the browser's last accepted sequence: a reconnect resumes + behind it instead of re-sending blocks the worklet already holds. + """ owner = self.server.owner allowed_origins = self.server.allowed_origins(self.headers.get("Host")) if (self.headers.get("Origin") not in allowed_origins @@ -2833,6 +2920,7 @@ class _Handler(BaseHTTPRequestHandler): self._reply(409, {"error": "stream_exists"}) return owner._audio_clients[client_key] = marker + owner.audio_stream_stats_locked(role)["connections"] += 1 accept = base64.b64encode(hashlib.sha1( key.encode("ascii") + _WEBSOCKET_GUID).digest()).decode("ascii") self.send_response_only(101) @@ -2852,7 +2940,11 @@ class _Handler(BaseHTTPRequestHandler): self.connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) except (OSError, AttributeError): pass - last_sequence = None + try: + self.connection.settimeout(AUDIO_SOCKET_TIMEOUT_S) + except OSError: + pass + last_sequence = after try: while True: with owner._audio_condition: @@ -2874,12 +2966,20 @@ class _Handler(BaseHTTPRequestHandler): continue # A slow socket skips old samples; never build an unbounded # per-client backlog or hold the simulation lock while sending. - sequence, pcm = available[-4] if len(available) > 4 else available[0] + if len(available) > SONAR_AUDIO_RESUME_BLOCKS: + owner.audio_stream_stats_locked(role)["skipped_blocks"] += ( + len(available) - SONAR_AUDIO_RESUME_BLOCKS) + sequence, pcm = available[-SONAR_AUDIO_RESUME_BLOCKS] + else: + sequence, pcm = available[0] last_sequence = sequence current["last_get"] = time.monotonic() self.connection.sendall(_websocket_frame( b"UJA2" + struct.pack(" { if (!ok) throw new Error(label); }; 'X-U-Jagd-Audio-Sequence':'1', 'X-U-Jagd-Audio-Discontinuity':'0'}})); await pending; check(S.sonarAudioSequence === 1 && starts.length === 1, 'metadata refresh dropped valid audio'); - check(starts[0] >= 2.0 && starts[0] <= 2.1, 'bounded startup jitter buffer'); + check(starts[0] >= 3.0 && starts[0] <= 3.1, 'bounded startup jitter buffer'); check(timers.has(S.sonarAudioTimer), 'audio poll not rescheduled'); S.audio.currentTime = 1.1; globalThis.fetch = async () => new Response(new Uint8Array(2048), {status:200, headers:{ @@ -76,7 +76,7 @@ const check = (ok, label) => { if (!ok) throw new Error(label); }; 'X-U-Jagd-Sample-Rate':'4096', 'X-U-Jagd-Audio-Frames':'1024', 'X-U-Jagd-Audio-Sequence':'3', 'X-U-Jagd-Audio-Discontinuity':'0'}}); await pollSonarAudio(); - check(starts.length === 3 && starts[2] >= 9.0 && starts[2] <= 9.1, + check(starts.length === 3 && starts[2] >= 10.0 && starts[2] <= 10.1, 'proxied PCM or underrun was rejected'); const queued = S.sonarAudioSources.at(-1); globalThis.fetch = async () => new Response(new Uint8Array(2048), {status:200, headers:{ diff --git a/tests/test_commander_audio_worklet.py b/tests/test_commander_audio_worklet.py index 0606b61f..31560d90 100644 --- a/tests/test_commander_audio_worklet.py +++ b/tests/test_commander_audio_worklet.py @@ -39,19 +39,20 @@ try { } }; - // Startup waits for five blocks, then plays the joined tone without steps. + // Startup waits for eight blocks (two seconds), then plays the joined tone without steps. + const PRIME = 8; sampleRate = 48000; let stream = new Processor(); - for (let i = 1; i <= 4; i++) feed(stream, i); + for (let i = 1; i < PRIME; i++) feed(stream, i); run(stream, 1280); if (stream.primed || output[0][0].some(x => x !== 0)) throw Error('early start'); - let sequence = 5; + let sequence = PRIME; feed(stream, sequence); const played = []; // Producer 1 % slow against the audio clock: steered, never concealed. - let produced = 5 * 12000; + let produced = PRIME * 12000; for (let frame = 0; frame < 48000 * 60; frame += 128) { - if (frame * .99 >= produced - 5 * 12000) { feed(stream, ++sequence); produced += 12000; } + if (frame * .99 >= produced - PRIME * 12000) { feed(stream, ++sequence); produced += 12000; } run(stream, 128, frame > 48000 * 50 ? played : null); } if (!stream.primed || stream.concealed !== 0 || stream.stale) throw Error('drift underrun ' + stream.concealed); @@ -61,30 +62,34 @@ try { // A 97 Hz tone at 48 kHz moves at most ~0.0031 per sample at 0.244 peak. if (maxStep > .004) throw Error('block join step ' + maxStep); - // Stall: non-periodic concealment, then stale neutral noise. + // Stall: non-periodic concealment, then stale neutral noise (after 3 s). sampleRate = 4096; stream = new Processor(); - for (let i = 1; i <= 5; i++) feed(stream, i); - run(stream, 5 * 1024 + 256); + for (let i = 1; i <= PRIME; i++) feed(stream, i); + run(stream, PRIME * 1024 + 256); if (stream.concealed < 1 || stream.stale) throw Error('conceal'); const first = Array.from(stream.current); run(stream, 1024); if (first.every((x, i) => x === stream.current[i])) throw Error('concealment repeats'); - run(stream, 3 * 4096); + run(stream, 4 * 4096); if (!stream.stale || !stream.port.messages.some(x => x.type === 'stale' && x.value)) throw Error('stale'); if (!output[0][0].some(x => x !== 0)) throw Error('neutral noise'); - // One block is not enough to resume; two are. - feed(stream, 7); - run(stream, 512); + // Three blocks are not enough to resume (REFILL_BLOCKS = 4); the fourth is. + let next = PRIME + 2; + for (let i = 0; i < 3; i++) { feed(stream, next++); run(stream, 512); } if (!stream.stale || stream.gaps < 1) throw Error('refill'); - feed(stream, 8); + feed(stream, next++); run(stream, 256); if (stream.stale || !stream.port.messages.some(x => x.type === 'stale' && !x.value)) throw Error('recovery'); - for (let i = 9; i <= 40; i++) feed(stream, i); - if (stream.blocks.length > 12 || stream.evictions < 1) throw Error('backpressure'); + for (; next <= 80; next++) feed(stream, next); + if (stream.blocks.length > 24 || stream.evictions < 1) throw Error('backpressure'); + // A re-sent (old or repeated) sequence is a duplicate: counted, never queued. + const queued = stream.blocks.length; + feed(stream, 80); feed(stream, 12); + if (stream.dropped !== 2 || stream.blocks.length !== queued) throw Error('duplicate ' + stream.dropped); run(stream, 4096); const metrics = stream.port.messages.filter(x => x.type === 'metrics').at(-1); - if (!metrics || !('concealed' in metrics) || !('rate' in metrics)) throw Error('metrics'); + if (!metrics || !('concealed' in metrics) || !('rate' in metrics) || metrics.dropped !== 2) throw Error('metrics'); stream.port.onmessage({data:{type:'reset'}}); if (stream.blocks.length || stream.primed || stream.lastSequence !== null) throw Error('reset'); document.documentElement.dataset.result = 'passed'; diff --git a/tests/test_commander_bridge.py b/tests/test_commander_bridge.py index 1fd836dc..6509150f 100644 --- a/tests/test_commander_bridge.py +++ b/tests/test_commander_bridge.py @@ -275,3 +275,47 @@ def test_only_main_thread_may_access_game(game): (bridge.reject_proposal, (game,))): with pytest.raises(RuntimeError, match="main thread"): executor.submit(method, *args).result() + + +class AudioServer(Server): + """Fake transport recording the live-audio publication calls.""" + + def __init__(self): + super().__init__() + self.audio = [] + self.discontinuities = [] + + def prepare_sonar_audio(self, *, world_session, world_epoch): + return 1 + + def publish_sonar_audio(self, pcm, *, world_session, world_epoch, station_generation): + assert type(pcm) is bytes and len(pcm) == 2048 + self.audio.append(pcm) + return True + + def mark_audio_discontinuity(self, role): + self.discontinuities.append(role) + return True + + +def test_retuned_receiver_marks_exactly_one_audio_discontinuity(game): + """A listening-bearing change restarts the receiver; browsers must crossfade.""" + bridge, server = CommanderBridge(), AudioServer() + receiver = game.sonar.receiver + now = 100.0 + bridge.pump(game, server, now=now) # binds the stream, skips retained blocks + for _ in range(3): + game.update(.25) + now += .25 + bridge.pump(game, server, now=now) + assert len(server.audio) >= 2 and server.discontinuities == [] + published = len(server.audio) + game.set_sonar_listen_bearing(receiver_bearing := 135.0) + assert receiver.sequence >= 0 and not receiver.blocks_since(-1) + for _ in range(3): + game.update(.25) + now += .25 + bridge.pump(game, server, now=now) + assert len(server.audio) > published + assert server.discontinuities == ["sonar"] + assert game.sonar.listen_bearing == receiver_bearing diff --git a/tests/test_commander_sessions_v2.py b/tests/test_commander_sessions_v2.py index 86edd49d..5bde2fb6 100644 --- a/tests/test_commander_sessions_v2.py +++ b/tests/test_commander_sessions_v2.py @@ -677,11 +677,80 @@ def test_sonar_audio_endpoint_is_bounded_context_bound_and_does_not_renew_presen status, headers, payload = request( server, "/api/v2/sonar/audio", "POST", body, cookie, session["csrf"]) assert status == 200 and payload == blocks[0] - assert headers["X-U-Jagd-Audio-Sequence"] == "1" + # Numbering never restarts within a server run: the cleared stream skips + # one number (the restart is a gap), then continues above the old cursor. + assert headers["X-U-Jagd-Audio-Sequence"] == str(len(blocks) + 2) + assert headers["X-U-Jagd-Audio-Discontinuity"] == "1" + # A cursor ahead of everything ever published (a host restart) is rebased. + body["after"] = len(blocks) + 10 + status, headers, payload = request( + server, "/api/v2/sonar/audio", "POST", body, cookie, session["csrf"]) + assert status == 200 and payload == blocks[0] + assert headers["X-U-Jagd-Audio-Sequence"] == str(len(blocks) + 2) assert headers["X-U-Jagd-Audio-Discontinuity"] == "1" assert lock_checks and all(lock_checks), "audio socket writes must not block the main-thread lock" +@pytest.mark.parametrize("role", ("sonar", "uboot_sonar", "helicopter")) +def test_audio_sequence_is_monotonic_across_clears_and_context_changes(server, role): + """An epoch step clears the ring but never renumbers from 1. + + The browser worklet de-duplicates by sequence; a restart at 1 made it drop + every new block until the count passed the old one (minutes of silence + after any host key press). Clears and retunes now appear as gaps. + """ + _, cookie, _, paired = pair_v2(server, "Audio") + client_id = paired["client_id"] + assert server.grant_station(client_id, role) + assert server.set_client_grant(client_id, role, "sonar_audio", True) + prepare = {"sonar": server.prepare_sonar_audio, "uboot_sonar": server.prepare_uboot_audio, + "helicopter": server.prepare_helicopter_audio}[role] + publish = {"sonar": server.publish_sonar_audio, "uboot_sonar": server.publish_uboot_audio, + "helicopter": server.publish_helicopter_audio}[role] + ring = lambda: server._audio_ring(role)[0] + pcm = bytes(transport.SONAR_AUDIO_BYTES) + generation = prepare(world_session="world-a", world_epoch=7) + assert generation is not None + for _ in range(3): + assert publish(pcm, world_session="world-a", world_epoch=7, station_generation=generation) + assert [entry[0] for entry in ring()] == [1, 2, 3] + # Idle clears of an already empty stream do not burn numbers. + server.clear_sonar_audio(); server.clear_uboot_audio(); server.clear_helicopter_audio() + assert prepare(world_session="world-a", world_epoch=7) == generation + server.clear_sonar_audio(); server.clear_uboot_audio(); server.clear_helicopter_audio() + # The host's local input advanced the epoch: new context, ring cleared, + # numbering continues above the old cursor with one skipped number. + assert prepare(world_session="world-a", world_epoch=8) == generation + assert publish(pcm, world_session="world-a", world_epoch=8, station_generation=generation) + assert [entry[0] for entry in ring()] == [5] + # A retuned receiver marks a discontinuity: one number is skipped. + assert server.mark_audio_discontinuity(role) is True + assert publish(pcm, world_session="world-a", world_epoch=8, station_generation=generation) + assert [entry[0] for entry in ring()] == [5, 7] + assert server.audio_stream_stats()[role]["discontinuities"] == 1 + # Other roles are independent and unbound streams are never marked. + other = next(name for name in transport.SONAR_AUDIO_ROLES if name != role) + assert server.mark_audio_discontinuity(other) is False + with pytest.raises(ValueError): + server.mark_audio_discontinuity("weapons") + route = {"sonar": "/api/v2/sonar/audio", "uboot_sonar": "/api/v2/uboot/audio", + "helicopter": "/api/v2/helicopter/audio"}[role] + session = request(server, "/api/v2/session", cookie=cookie)[2] + body = {"protocol": 2, "after": 3, "world_session": "world-a", "world_epoch": 8, + "station_generation": session["station_generation"], + "active_generation": session["active_generation"]} + # A cursor older than the cleared ring is an overrun: newest block, gap. + status, headers, _ = request(server, route, "POST", body, cookie, session["csrf"]) + assert status == 200 and headers["X-U-Jagd-Audio-Sequence"] == "7" + assert headers["X-U-Jagd-Audio-Discontinuity"] == "1" + body["after"] = 5 + status, headers, _ = request(server, route, "POST", body, cookie, session["csrf"]) + assert status == 200 and headers["X-U-Jagd-Audio-Sequence"] == "7" + assert headers["X-U-Jagd-Audio-Discontinuity"] == "0" # the browser sees 5 -> 7 itself + body["after"] = 7 + assert request(server, route, "POST", body, cookie, session["csrf"])[0] == 204 + + def test_sonar_audio_fails_closed_for_auth_schema_role_grant_and_context(server): _, cookie, _, paired = pair_v2(server, "Sonar") body = {"protocol": 2, "after": None, "world_session": "world-a", diff --git a/tests/test_commander_sonar_websocket.py b/tests/test_commander_sonar_websocket.py index 613715a5..fe459cc4 100644 --- a/tests/test_commander_sonar_websocket.py +++ b/tests/test_commander_sonar_websocket.py @@ -113,7 +113,10 @@ def test_audio_websocket_is_leased_sequenced_and_revoked(server, role): generation = prepare(world_session="audio-world", world_epoch=3) assert generation is not None pcm = bytes(transport.SONAR_AUDIO_BYTES) - for _ in range(6): + # Ten pending blocks: a fresh socket gets the newest eight (the browser's + # priming lead), the first two are skipped. + published = transport.SONAR_AUDIO_RESUME_BLOCKS + 2 + for _ in range(published): assert publish(pcm, world_session="audio-world", world_epoch=3, station_generation=generation) host, port = server.address @@ -148,6 +151,7 @@ def test_audio_websocket_is_leased_sequenced_and_revoked(server, role): payload = frame[4:4 + size] assert len(payload) == 2060 and payload[:4] == b"UJA2" assert struct.unpack(" published + + +def test_audio_websocket_resumes_behind_the_browser_cursor(server): + """``?after=N`` resumes a reconnect without re-sending held blocks.""" + _, cookie, _, paired = pair_v2(server, "Resume") + client_id = paired["client_id"] + assert server.grant_station(client_id, "sonar") + assert server.set_client_grant(client_id, "sonar", "sonar_audio", True) + generation = server.prepare_sonar_audio(world_session="audio-world", world_epoch=1) + blocks = [bytes([value]) * transport.SONAR_AUDIO_BYTES for value in range(1, 13)] + for pcm in blocks: + assert server.publish_sonar_audio(pcm, world_session="audio-world", + world_epoch=1, station_generation=generation) + host, port = server.address + + def handshake(query): + key = base64.b64encode(os.urandom(16)).decode("ascii") + return (f"GET /ws/v2/sonar/audio{query} HTTP/1.1\r\nHost: {host}:{port}\r\n" + f"Origin: http://{host}:{port}\r\nUpgrade: websocket\r\n" + f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n" + "Sec-WebSocket-Version: 13\r\nSec-WebSocket-Protocol: u-jagd-audio-v2\r\n" + f"Cookie: {cookie}\r\n\r\n").encode("ascii") + + def first_frame(query): + with socket.create_connection(server.address, timeout=3) as connection: + connection.settimeout(3) + connection.sendall(handshake(query)) + received = bytearray() + while b"\r\n\r\n" not in received: + received.extend(connection.recv(4096)) + headers, frame = bytes(received).split(b"\r\n\r\n", 1) + if not headers.startswith(b"HTTP/1.1 101"): + return headers.split(b"\r\n", 1)[0], None + while len(frame) < 16: + frame += connection.recv(4096) + return headers.split(b"\r\n", 1)[0], struct.unpack(" 0: + recovered.append(game._frame_dt(0.0)) + assert sum(recovered) == pytest.approx(config.SIM_CATCHUP_MAX_S) + assert game._sim_dropped_s == 0.0 # A hang beyond the catch-up bound drops only the excess. assert game._frame_dt(3.0) == pytest.approx(config.SIM_FRAME_DT_MAX) assert game._sim_dropped_s == pytest.approx(3.0 - config.SIM_CATCHUP_MAX_S) @@ -180,6 +187,8 @@ def test_perf_debug_log_is_opt_in_throttled_and_does_not_affect_sim( assert "fps=2" in lines[0] assert "sim_ms=" in lines[0] and "audio_ms=" in lines[0] assert "commander_ms=" in lines[0] and "draw_ms=" in lines[0] + assert "commander_max_ms=" in lines[0] and "events_ms=" in lines[0] + assert "traffic_ms=" in lines[0] debug._perf_debug_log(0.8) assert len((debug_root / "perf_debug.log").read_text().splitlines()) == 1 debug._perf_debug_log(0.3) diff --git a/tests/test_opfor_web.py b/tests/test_opfor_web.py index 85a351d3..e049a501 100644 --- a/tests/test_opfor_web.py +++ b/tests/test_opfor_web.py @@ -29,11 +29,16 @@ PROBE = r''' // Count delivered submarine audio blocks on either transport, and the // world epochs the browser sees in its state polls. let blocks = 0; + const sequences = []; const epochs = new Set(); const NativeSocket = window.WebSocket, nativeFetch = window.fetch; window.WebSocket = function (url, protocol) { const socket = new NativeSocket(url, protocol); - if (String(url).endsWith('/ws/v2/uboot/audio')) socket.addEventListener('message', () => { blocks++; }); + if (String(url).includes('/ws/v2/uboot/audio')) socket.addEventListener('message', ({data}) => { + blocks++; + if (data instanceof ArrayBuffer && data.byteLength === 2060) + sequences.push(Number(new DataView(data).getBigUint64(4, true))); + }); return socket; }; window.WebSocket.prototype = NativeSocket.prototype; @@ -41,7 +46,10 @@ PROBE = r''' window.fetch = async (...args) => { const response = await nativeFetch(...args); const url = String(args[0]); - if (url.endsWith('/api/v2/uboot/audio') && response.status === 200) blocks++; + if (url.endsWith('/api/v2/uboot/audio') && response.status === 200) { + blocks++; + sequences.push(Number(response.headers.get('x-u-jagd-audio-sequence'))); + } if (url.includes('/api/v2/state') && response.status === 200) response.clone().json().then((state) => { if (state.role) epochs.add(state.epoch); }, () => {}); return response; @@ -75,6 +83,18 @@ PROBE = r''' await until(() => epochs.size >= seen + 2, () => `no epoch steps: ${[...epochs]}`); if ($('sonar-live-toggle').getAttribute('aria-pressed') !== 'true') throw new Error(`live sonar switched off by host input: ${$('sonar-live-status').textContent}`); + // Audio keeps flowing after the host's input: at least two seconds of new + // blocks arrive, every sequence is higher than the one before (a restart + // at 1 would make the worklet drop them all), and nothing went stale. + root.dataset.stage = 'audio after host input'; + const before = blocks; + await until(() => blocks >= before + 8, () => `audio stalled after host input: ${blocks - before} blocks`); + for (let i = 1; i < sequences.length; i++) + if (!(sequences[i] > sequences[i - 1])) throw new Error(`sequence went backwards: ${sequences[i - 1]} -> ${sequences[i]}`); + const diagnostics = window.uJagdAudioDiagnostics || {}; + if (diagnostics.stale === true || diagnostics.droppedBlocks > 0) + throw new Error(`worklet dropped audio: ${JSON.stringify(diagnostics)}`); + root.dataset.sequences = String(sequences.length); } run().then(() => { root.dataset.opforTest = 'passed'; }, (error) => { root.dataset.opforTest = 'failed'; diff --git a/tests/test_tools_audio_soak.py b/tests/test_tools_audio_soak.py new file mode 100644 index 00000000..b187b75e --- /dev/null +++ b/tests/test_tools_audio_soak.py @@ -0,0 +1,38 @@ +"""The audio soak tool runs headless, isolates user data and reports continuity.""" + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.mark.timeout(240) +def test_audio_soak_tool_runs_headless_and_reports_ok(tmp_path): + fake_home = tmp_path / "home" + fake_home.mkdir() + (fake_home / ".u-jagd").mkdir() + marker = fake_home / ".u-jagd" / "settings.json" + marker.write_text("{}", encoding="utf-8") + env = dict(os.environ, HOME=str(fake_home), SDL_VIDEODRIVER="dummy", + SDL_AUDIODRIVER="dummy") + env.pop("U_JAGD_AUDIO_DEBUG", None) + env.pop("U_JAGD_PERF_DEBUG", None) + result = subprocess.run( + [sys.executable, str(ROOT / "tools" / "audio_soak.py"), "host", + "--dummy-audio", "--duration", "8", "--clients", "3", + "--bump-every", "3", "--retune-every", "4"], + cwd=ROOT, env=env, capture_output=True, text=True, timeout=200) + assert result.returncode == 0, result.stdout + result.stderr + out = result.stdout + assert "RESULT: OK" in out + assert "stream sonar:" in out and "stream uboot_sonar:" in out + assert "backwards 0" in out and "silences_over_2.0s 0" in out + assert "local mixer: underruns 0" in out + assert "epoch steps" in out + # The tool never writes into the caller's ~/.u-jagd. + assert sorted(path.name for path in (fake_home / ".u-jagd").iterdir()) == ["settings.json"] + assert marker.read_text(encoding="utf-8") == "{}" diff --git a/tools/audio_soak.py b/tools/audio_soak.py new file mode 100644 index 00000000..c0ad5f8a --- /dev/null +++ b/tools/audio_soak.py @@ -0,0 +1,559 @@ +"""Sonar-audio soak test: continuity of the local mixer and Remote Crew streams. + +Offline diagnostics tool, not a runtime resource. Two modes: + +``host`` runs the real game loop (``Game.run``) headless on this machine with +``--clients`` simulated Remote Crew browsers: every audio role (frigate sonar, +boat sonar, helicopter) consumes its WebSocket PCM stream, the other roles poll +state at 2 Hz, and the host's own input advances the world epoch every +``--bump-every`` seconds (the case that used to silence browsers). The local +mixer plays the frigate's sonar room at the same time (``--dummy-audio`` for +CI). The summary reports frame time, catch-up, local underruns, mixer idle +events, and per-stream gaps and arrival jitter; the exit code is non-zero on +any audible defect. + +``client`` pairs with a running game from another machine (a PC on the Wi-Fi +the browsers use), waits until the host grants an audio station in F9, and +measures that stream's continuity over the real network. + +Everything the host mode writes (settings, saves, debug logs) goes to a +temporary directory; the user's ``~/.u-jagd`` is never touched. +""" + +from __future__ import annotations + +import argparse +import base64 +import http.client +import json +import os +import re +import socket +import statistics +import struct +import sys +import threading +import time +from contextlib import closing +from tempfile import TemporaryDirectory +from urllib.parse import urlsplit + +AUDIO_ROLES = ("sonar", "uboot_sonar", "helicopter") +AUDIO_ROUTES = {"sonar": "sonar", "helicopter": "helicopter", "uboot_sonar": "uboot"} +BLOCK_S = 0.25 +# A missing block longer than the browser's standing lead is an audible gap. +GAP_S = 2.0 +SILENCE_S = 0.75 + + +class Session: + """One paired protocol-v2 client (cookie, CSRF token, client id).""" + + def __init__(self, host: str, port: int, name: str, code: str): + self.host, self.port, self.name = host, port, name + status, headers, body = self.request("/api/v2/pair", "POST", + {"code": code, "name": name}) + if status != 200: + raise RuntimeError(f"pairing failed for {name}: {status} {body}") + token = headers["Set-Cookie"].split(";", 1)[0] + self.cookie = token + self.csrf = body["csrf"] + self.client_id = body["client_id"] + self.station = None + self.poll_errors = 0 + self.polls = 0 + self.poll_latency_ms: list[float] = [] + + def request(self, path, method="GET", body=None, cookie=None): + headers = {} + if method == "POST": + headers.update({"Origin": f"http://{self.host}:{self.port}", + "Content-Type": "application/json"}) + cookie = getattr(self, "cookie", None) if cookie is None else cookie + if cookie: + headers["Cookie"] = cookie + if getattr(self, "csrf", None) and method == "POST": + headers["X-U-Jagd-CSRF"] = self.csrf + payload = None if body is None else json.dumps(body).encode("utf-8") + with closing(http.client.HTTPConnection(self.host, self.port, timeout=5)) as connection: + connection.request(method, path, body=payload, headers=headers) + response = connection.getresponse() + data = response.read() + response_headers = dict(response.getheaders()) + if response_headers.get("Content-Type", "").startswith("application/json"): + data = json.loads(data) + return response.status, response_headers, data + + def poll_state(self): + started = time.monotonic() + try: + status, _, body = self.request("/api/v2/state") + except (OSError, http.client.HTTPException, ValueError): + self.poll_errors += 1 + return None + self.poll_latency_ms.append((time.monotonic() - started) * 1000.0) + self.polls += 1 + if status != 200: + self.poll_errors += 1 + return None + return body + + def poll_session(self): + try: + status, _, body = self.request("/api/v2/session") + except (OSError, http.client.HTTPException, ValueError): + return None + if status == 200 and isinstance(body, dict): + self.station = body.get("station") + return body + return None + + +class AudioStream(threading.Thread): + """Browser-like consumer of one role's audio WebSocket (with resume cursor).""" + + def __init__(self, session: Session, role: str, stop: threading.Event): + super().__init__(name=f"soak-audio-{role}", daemon=True) + self.session, self.role, self.stop = session, role, stop + self.arrivals: list[float] = [] + self.sequences: list[int] = [] + self.gaps = 0 # sequence jumps (epoch step, retune, skip) + self.backwards = 0 # numbering went backwards: the old worklet-drop bug + self.reconnects = 0 + self.refusals = 0 # 4xx handshakes (not yet granted, revoked) + self.silences: list[float] = [] # intervals without a block > SILENCE_S + self.first_block_at = None + self.last_block_at = None + self.connected_since = None + self.last_sequence = None + + def run(self): + while not self.stop.is_set(): + try: + self._stream_once() + except (OSError, ValueError, struct.error): + pass + if self.stop.is_set(): + break + self.reconnects += 1 + # The browser reconnects at once after an epoch step, 0.5 s otherwise. + self.stop.wait(0.1) + + def _handshake(self): + key = base64.b64encode(os.urandom(16)).decode("ascii") + query = f"?after={self.last_sequence}" if self.last_sequence is not None else "" + host, port = self.session.host, self.session.port + return (f"GET /ws/v2/{AUDIO_ROUTES[self.role]}/audio{query} HTTP/1.1\r\n" + f"Host: {host}:{port}\r\nOrigin: http://{host}:{port}\r\n" + "Upgrade: websocket\r\nConnection: Upgrade\r\n" + f"Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n" + "Sec-WebSocket-Protocol: u-jagd-audio-v2\r\n" + f"Cookie: {self.session.cookie}\r\n\r\n").encode("ascii") + + def _stream_once(self): + with socket.create_connection((self.session.host, self.session.port), timeout=5) as connection: + connection.sendall(self._handshake()) + received = bytearray() + while b"\r\n\r\n" not in received: + chunk = connection.recv(4096) + if not chunk: + return + received.extend(chunk) + headers, buffer = bytes(received).split(b"\r\n\r\n", 1) + if not headers.startswith(b"HTTP/1.1 101"): + self.refusals += 1 + self.stop.wait(1.0) + return + self.connected_since = time.monotonic() + buffer = bytearray(buffer) + connection.settimeout(0.5) + while not self.stop.is_set(): + while True: + frame = self._parse_frame(buffer) + if frame is None: + break + opcode, payload = frame + if opcode == 8: + return + if opcode == 2 and len(payload) == 2060 and payload[:4] == b"UJA2": + self._accept(struct.unpack(" SILENCE_S: + self.silences.append(now - self.last_block_at) + if self.first_block_at is None: + self.first_block_at = now + self.last_block_at = now + self.last_sequence = sequence + self.arrivals.append(now) + self.sequences.append(sequence) + + def summary(self) -> dict: + deltas = [b - a for a, b in zip(self.arrivals, self.arrivals[1:])] + def percentile(values, fraction): + if not values: + return 0.0 + ordered = sorted(values) + return ordered[min(len(ordered) - 1, int(round(fraction * (len(ordered) - 1))))] + return { + "role": self.role, + "blocks": len(self.arrivals), + "seconds": round(len(self.arrivals) * BLOCK_S, 2), + "gaps": self.gaps, + "backwards": self.backwards, + "reconnects": self.reconnects, + "refusals": self.refusals, + "silences_over_%.2fs" % SILENCE_S: len(self.silences), + "silences_over_%.1fs" % GAP_S: sum(1 for value in self.silences if value > GAP_S), + "longest_silence_s": round(max(self.silences, default=0.0), 2), + "interarrival_p50_ms": round(1000 * percentile(deltas, .5), 1), + "interarrival_p99_ms": round(1000 * percentile(deltas, .99), 1), + "interarrival_max_ms": round(1000 * max(deltas, default=0.0), 1), + } + + +class Poller(threading.Thread): + """2 Hz state poll plus a 1 Hz session refresh, like the browser.""" + + def __init__(self, session: Session, stop: threading.Event): + super().__init__(name=f"soak-poll-{session.name}", daemon=True) + self.session, self.stop = session, stop + + def run(self): + next_session = 0.0 + while not self.stop.wait(0.5): + self.session.poll_state() + if time.monotonic() >= next_session: + self.session.poll_session() + next_session = time.monotonic() + 1.0 + + +def _percentile_ms(values, fraction): + if not values: + return 0.0 + ordered = sorted(values) + return round(ordered[min(len(ordered) - 1, int(round(fraction * (len(ordered) - 1))))], 1) + + +def _parse_debug_lines(path: str) -> list[dict]: + rows = [] + if not os.path.exists(path): + return rows + with open(path, encoding="utf-8") as handle: + for line in handle: + row = {} + for key, value in re.findall(r"(\w+)=([-+]?[0-9.]+)", line): + try: + row[key] = float(value) + except ValueError: + pass + if row: + rows.append(row) + return rows + + +def run_host(args) -> int: + with TemporaryDirectory(prefix="u-jagd-audio-soak-") as home: + # Isolate settings, saves and debug logs before anything reads ~/.u-jagd. + os.environ["HOME"] = home + os.environ["SDL_VIDEODRIVER"] = "dummy" + if args.dummy_audio: + os.environ["SDL_AUDIODRIVER"] = "dummy" + os.environ["U_JAGD_AUDIO_DEBUG"] = "1" + os.environ["U_JAGD_PERF_DEBUG"] = "1" + sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + import pygame + from src.core import config + from src.core.game import Game + from src.core.station import Station + from src.commander.server import ROLES + + save_dir = os.path.join(home, ".u-jagd") + config.SAVE_DIR = save_dir + config.SAVE_PATH = os.path.join(save_dir, "save.json") + game = Game(seed=args.seed, start_menu=False, audio_enabled=True, language="en") + game.station = Station.SONAR + game.sonar_audio_enabled = True + console = game.commander + console.port = args.port + console.activate(game) + if console.address is None: + print(f"host: transport did not start ({console.error})", file=sys.stderr) + return 2 + console.bridge.allowed = True + server = console.server + host, port = console.address + print(f"host: listening on {host}:{port}, pairing code {console.pairing_code}, " + f"mixer {'dummy' if args.dummy_audio else pygame.mixer.get_init()}") + + # Pair the simulated browsers and grant every station: audio roles first. + roles = [role for role in AUDIO_ROLES if role != "helicopter" or args.helicopter] + roles += [role for role in ROLES if role not in roles] + sessions = [] + for index in range(min(args.clients, len(roles))): + session = Session(host, port, f"soak-{index}", console.pairing_code) + role = roles[index] + if not server.grant_station(session.client_id, role): + print(f"host: could not grant {role} to {session.name}", file=sys.stderr) + return 2 + if role in AUDIO_ROLES: + server.set_client_grant(session.client_id, role, "sonar_audio", True) + session.station = role + sessions.append(session) + stop = threading.Event() + streams = [AudioStream(session, session.station, stop) + for session in sessions if session.station in AUDIO_ROLES] + pollers = [Poller(session, stop) for session in sessions] + for thread in (*streams, *pollers): + thread.start() + + # Host input from the main thread, exactly where the game reads it. + counters = {"bumps": 0, "retunes": 0} + schedule = {"bump": time.monotonic() + args.bump_every if args.bump_every else None, + "retune": time.monotonic() + args.retune_every if args.retune_every else None} + original_pump = console.pump + + def pump(current): + now = time.monotonic() + if schedule["bump"] is not None and now >= schedule["bump"]: + # F1 opens the help overlay; Esc closes it. Each transition is + # an input-owner change, i.e. a world epoch step for browsers. + for key in (pygame.K_F1, pygame.K_ESCAPE): + current.handle_event(pygame.event.Event( + pygame.KEYDOWN, key=key, mod=0, unicode="", scancode=0)) + counters["bumps"] += 1 + schedule["bump"] = now + args.bump_every + if schedule["retune"] is not None and now >= schedule["retune"]: + current.set_sonar_listen_bearing((current.sonar.listen_bearing + 47.0) % 360.0) + counters["retunes"] += 1 + schedule["retune"] = now + args.retune_every + original_pump(current) + + profiler = None + if args.profile: + import cProfile + profiler = cProfile.Profile() + timed_pump = pump + + def pump(current): # noqa: F811 - profiled wrapper of the same pump + profiler.enable() + try: + timed_pump(current) + finally: + profiler.disable() + + console.pump = pump + game.auto_quit = int(args.duration * game.frame_rate()) + epoch_before = console.bridge.status["epoch"] + started = time.monotonic() + try: + game.run() + finally: + stop.set() + elapsed = time.monotonic() - started + for thread in (*streams, *pollers): + thread.join(timeout=3.0) + epochs = console.bridge.status["epoch"] - epoch_before + stats = server.audio_stream_stats() + if profiler is not None: + import pstats + print("\n=== commander pump profile (main thread) ===") + report_stats = pstats.Stats(profiler) + report_stats.sort_stats("tottime").print_stats(25) + report_stats.sort_stats("cumulative").print_stats(r"src[\\/]commander", 25) + perf = _parse_debug_lines(os.path.join(save_dir, "perf_debug.log")) + audio_rows = _parse_debug_lines(os.path.join(save_dir, "audio_debug.log")) + return report(args, elapsed, epochs, counters, streams, sessions, stats, perf, + audio_rows) + + +def report(args, elapsed, epochs, counters, streams, sessions, stats, perf, audio_rows) -> int: + failures = [] + print(f"\n=== audio soak: {elapsed:.1f} s wall, {len(sessions)} clients, " + f"{counters['bumps']} host input bursts ({epochs} epoch steps), " + f"{counters['retunes']} retunes ===") + if perf: + fps = [row.get("fps", 0) for row in perf] + frame_max = max(row.get("frame_max_ms", 0) for row in perf) + dropped = max(row.get("sim_dropped_ms", 0) for row in perf) + commander = statistics.fmean(row.get("commander_ms", 0) for row in perf) + commander_max = max(row.get("commander_max_ms", 0) for row in perf) + print(f"frames: fps min/mean {min(fps):.0f}/{statistics.fmean(fps):.1f}, " + f"frame_max {frame_max:.0f} ms, commander mean {commander:.2f} ms " + f"(max {commander_max:.0f} ms), sim_dropped {dropped:.0f} ms") + if dropped > 0: + failures.append(f"simulation time dropped ({dropped:.0f} ms)") + else: + print("frames: no perf_debug.log written") + if audio_rows: + last = audio_rows[-1] + print("local mixer: underruns {:.0f}, concealed {:.0f}, neutral {:.0f}, " + "channel_idle {:.0f}, pump_late {:.0f} (max {:.0f} ms), drops {:.0f}, " + "input_gaps {:.0f}, buffer {:.2f} s".format( + last.get("sonar_underruns", 0), last.get("sonar_concealed", 0), + last.get("sonar_neutral", 0), last.get("channel_idle", 0), + last.get("pump_late", 0), + max(row.get("pump_late_max_ms", 0) for row in audio_rows), + last.get("sonar_drops", 0), last.get("input_gaps", 0), + last.get("buffer_s", 0))) + for key, label in (("sonar_underruns", "local underruns"), + ("channel_idle", "mixer channel idle events"), + ("sonar_drops", "rejected local blocks")): + if last.get(key, 0) > 0: + failures.append(f"{label}: {last[key]:.0f}") + # Every retune breaks the receiver sequence once; anything beyond that + # is a block the frame loop never played. (evictions counts ordinary + # ring rotation of the two-block receiver window, not loss.) + if last.get("input_gaps", 0) > counters["retunes"]: + failures.append(f"local input gaps {last['input_gaps']:.0f} for " + f"{counters['retunes']} retunes") + slow = [row for row in perf if row.get("frame_max_ms", 0) > 100] + if slow: + first_t = perf[0].get("t", 0) + print("slow seconds (frame_max > 100 ms):") + for row in slow[:8]: + print(" +{:5.1f}s fps {:2.0f} frame_max {:5.0f} ms sim {:5.1f} audio {:4.1f} " + "commander {:5.1f} (max {:4.0f}) events {:4.1f} traffic {:4.1f} " + "draw {:5.1f} lag {:4.0f}".format( + row.get("t", 0) - first_t, row.get("fps", 0), row.get("frame_max_ms", 0), + row.get("sim_ms", 0), row.get("audio_ms", 0), row.get("commander_ms", 0), + row.get("commander_max_ms", 0), row.get("events_ms", 0), + row.get("traffic_ms", 0), row.get("draw_ms", 0), row.get("sim_lag_ms", 0))) + else: + print("local mixer: no audio_debug.log written") + allowed_gaps = counters["bumps"] + counters["retunes"] + for stream in streams: + summary = stream.summary() + role_stats = stats.get(stream.role, {}) + print(f"stream {stream.role}: " + ", ".join( + f"{key} {value}" for key, value in summary.items() if key != "role") + + f"; server skipped {role_stats.get('skipped_blocks', 0)}, " + f"send timeouts {role_stats.get('send_timeouts', 0)}, " + f"discontinuities {role_stats.get('discontinuities', 0)}, " + f"connections {role_stats.get('connections', 0)}") + if summary["blocks"] == 0: + if stream.role == "helicopter": + print(" (no helicopter audio: the dipping sonar was not in the water)") + else: + failures.append(f"{stream.role}: no audio received") + continue + if summary["backwards"]: + failures.append(f"{stream.role}: sequence went backwards {summary['backwards']}x") + if summary["gaps"] > allowed_gaps + stream.reconnects: + failures.append(f"{stream.role}: {summary['gaps']} gaps for " + f"{allowed_gaps} host events") + if summary["silences_over_%.1fs" % GAP_S]: + failures.append(f"{stream.role}: {summary['silences_over_%.1fs' % GAP_S]} " + f"silences over {GAP_S} s") + latencies = [value for session in sessions for value in session.poll_latency_ms] + errors = sum(session.poll_errors for session in sessions) + polls = sum(session.polls for session in sessions) + print(f"state polls: {polls} ok, {errors} errors, latency p50/p99/max " + f"{_percentile_ms(latencies, .5)}/{_percentile_ms(latencies, .99)}/" + f"{_percentile_ms(latencies, 1.0)} ms") + if failures: + print("RESULT: FAIL\n - " + "\n - ".join(failures)) + return 1 + print("RESULT: OK") + return 0 + + +def run_client(args) -> int: + parts = urlsplit(args.connect) + host, port = parts.hostname, parts.port or 80 + session = Session(host, port, args.name, args.code) + print(f"client: paired as {session.name}; waiting for an audio station grant (F9 on the host)") + deadline = time.monotonic() + args.duration + while time.monotonic() < deadline: + body = session.poll_session() + if body and body.get("station") in AUDIO_ROLES and body["grants"].get("sonar_audio"): + break + time.sleep(1.0) + else: + print("client: no audio station granted in time") + return 2 + role = session.station + print(f"client: streaming {role} for {args.duration:.0f} s") + stop = threading.Event() + stream = AudioStream(session, role, stop) + poller = Poller(session, stop) + stream.start() + poller.start() + started = time.monotonic() + try: + while time.monotonic() - started < args.duration: + time.sleep(1.0) + finally: + stop.set() + stream.join(timeout=3.0) + poller.join(timeout=3.0) + return report(args, time.monotonic() - started, 0, {"bumps": 0, "retunes": 0}, + [stream], [session], {}, [], []) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + modes = parser.add_subparsers(dest="mode", required=True) + host = modes.add_parser("host", help="run the game headless with simulated browsers") + host.add_argument("--duration", type=float, default=60.0, help="seconds of play") + host.add_argument("--clients", type=int, default=9, help="paired browsers (max 15 roles)") + host.add_argument("--bump-every", type=float, default=15.0, + help="seconds between host input bursts (0 = never)") + host.add_argument("--retune-every", type=float, default=0.0, + help="seconds between listening-bearing changes (0 = never)") + host.add_argument("--seed", type=int, default=1234) + host.add_argument("--port", type=int, default=0, help="listener port (0 = ephemeral)") + host.add_argument("--dummy-audio", action="store_true", + help="SDL dummy audio driver (CI); default plays through the mixer") + host.add_argument("--helicopter", action="store_true", + help="also lease the helicopter (audio only once its sonar is wet)") + host.add_argument("--profile", action="store_true", + help="cProfile the Remote Crew pump on the main thread") + client = modes.add_parser("client", help="consume one audio stream from another machine") + client.add_argument("--connect", required=True, help="http://host:port of the game") + client.add_argument("--code", required=True, help="pairing code shown in F9") + client.add_argument("--name", default="soak-client") + client.add_argument("--duration", type=float, default=120.0) + args = parser.parse_args(argv) + return run_host(args) if args.mode == "host" else run_client(args) + + +if __name__ == "__main__": + sys.exit(main())