diff --git a/apps/control-station/src/components/simulation/streamFrame.ts b/apps/control-station/src/components/simulation/streamFrame.ts index 2d7335f4..9db7177f 100644 --- a/apps/control-station/src/components/simulation/streamFrame.ts +++ b/apps/control-station/src/components/simulation/streamFrame.ts @@ -1,4 +1,5 @@ import { AppStreamer, StreamType, LogLevel, EventStatus } from "@nvidia/ov-web-rtc"; +import { StreamDiagnostics } from "../../core/simulation/streamDiagnostics"; import type { AiStreamEndpoint } from "../../core/simulation/aiPolygon"; import "@nodedc/tokens/tokens.css"; import "./streamFrame.css"; @@ -19,17 +20,22 @@ window.addEventListener("message",(e:MessageEvent)=>{ started=true; const endpoint=e.data.endpoint as AiStreamEndpoint; fitVideo(endpoint.width,endpoint.height); + const diagnostics=new StreamDiagnostics(); let frames=0,measuredAt=performance.now(),decoded=0; - const frame=()=>{frames++;video.requestVideoFrameCallback(frame);}; + const frame:VideoFrameRequestCallback=(now,metadata)=>{ + frames++;diagnostics.observeFrame(now,metadata);video.requestVideoFrameCallback(frame); + }; video.requestVideoFrameCallback(frame); - setInterval(()=>{ + const timer=setInterval(()=>{ const now=performance.now(); // Presentation callbacks can be throttled independently of decoding in a // background view. Prefer decoded, non-dropped video frames for telemetry. const quality=video.getVideoPlaybackQuality?.(); const total=quality?quality.totalVideoFrames-quality.droppedVideoFrames:decoded+frames; const count=Math.max(0,total-decoded); - if(count>0)report("live",count*1000/(now-measuredAt)); + const fps=count*1000/(now-measuredAt); + video.dataset.streamDiagnostics=JSON.stringify(diagnostics.snapshot(now,fps)); + if(count>0)report("live",fps); decoded=total;frames=0;measuredAt=now; },1000); const stream=new AppStreamer(); @@ -42,6 +48,7 @@ window.addEventListener("message",(e:MessageEvent)=>{ maxReconnects:0,connectivityTimeout:5000, onStart:event=>{if(event.status===EventStatus.ERROR||event.status===EventStatus.CANCELED)report("failed");}, onStop:()=>report("failed"), + onStreamStats:event=>diagnostics.observeNative(performance.now(),event.data?.stats), }}).catch(()=>report("failed")); - window.addEventListener("pagehide",()=>{void stream.terminate(false).catch(()=>undefined);},{once:true}); + window.addEventListener("pagehide",()=>{clearInterval(timer);delete video.dataset.streamDiagnostics;void stream.terminate(false).catch(()=>undefined);},{once:true}); }); diff --git a/apps/control-station/src/core/simulation/streamDiagnostics.ts b/apps/control-station/src/core/simulation/streamDiagnostics.ts new file mode 100644 index 00000000..47bca5ff --- /dev/null +++ b/apps/control-station/src/core/simulation/streamDiagnostics.ts @@ -0,0 +1,46 @@ +/** One expiring diagnostic sample; never a recording or a control input. */ +export interface StreamFrameTiming { + expectedDisplayTime: number; + captureTime?: number; + receiveTime?: number; + processingDuration?: number; +} +const finite = (value: unknown): number | null => + typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; +const elapsed = (later: number, earlier: number | undefined) => { + if (earlier === undefined || finite(earlier) === null) return null; + const value = later - earlier; + return value >= 0 && value <= 60_000 ? value : null; +}; +export class StreamDiagnostics { + private native: { at: number; values: Record } | null = null; + private frame: { at: number; values: Record } | null = null; + observeNative(now: number, input: unknown) { + if (!input || typeof input !== "object") return; + const value = input as Record; + const fields = {fps: "fps", round_trip_ms: "rtd", decode_ms: "avgDecodeTime", + bitrate_mbps: "currentBitrate", available_mbps: "totalBandwidth", bandwidth_percent: "utilizedBandwidth", + frame_loss_total: "frameLoss", packet_loss_total: "packetLoss", + width: "streamingResolutionWidth", height: "streamingResolutionHeight"}; + this.native = { at: now, values: Object.fromEntries(Object.entries(fields) + .map(([key, source]) => [key, finite(value[source])])) }; + this.native.values.codec = typeof value.codec === "string" && /^[a-z0-9._-]{1,32}$/i.test(value.codec) ? value.codec : null; + } + observeFrame(now: number, value: StreamFrameTiming) { + // WebRTC captureTime is the browser's RTCP-based remote clock estimate. + // Never subtract a Worker monotonic clock from performance.now(). + this.frame = { at: now, values: { + estimated_capture_to_present_ms: elapsed(value.expectedDisplayTime, value.captureTime), + receive_to_present_ms: elapsed(value.expectedDisplayTime, value.receiveTime), + frame_decode_ms: finite(value.processingDuration) === null ? null : value.processingDuration! * 1000, + }}; + } + snapshot(now: number, decodedFps: number) { + const fresh = (sample:T|null) => + sample && now >= sample.at && now-sample.at <= 3000 ? sample : null; + const native=fresh(this.native), frame=fresh(this.frame); + return {schema_version:"missioncore.stream-diagnostics/v1", sampled_at_ms:now, + decoded_fps:finite(decodedFps), native:native ? {...native.values, age_ms:now-native.at} : null, + presentation:frame ? {...frame.values, age_ms:now-frame.at} : null}; + } +} diff --git a/apps/control-station/test/streamDiagnostics.test.mjs b/apps/control-station/test/streamDiagnostics.test.mjs new file mode 100644 index 00000000..c616f652 --- /dev/null +++ b/apps/control-station/test/streamDiagnostics.test.mjs @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {test} from 'node:test'; +import ts from 'typescript'; +const code=ts.transpileModule(readFileSync(new URL('../src/core/simulation/streamDiagnostics.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText; +const {StreamDiagnostics}=await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); +test('network round trip, decode and estimated presentation delay retain separate units',()=>{ + const d=new StreamDiagnostics();d.observeNative(100,{fps:8,rtd:42,avgDecodeTime:3,currentBitrate:9,codec:'H264'}); + d.observeFrame(105,{expectedDisplayTime:106,captureTime:40,receiveTime:96,processingDuration:.003}); + const s=d.snapshot(110,7.8);assert.equal(s.native.round_trip_ms,42);assert.equal(s.native.decode_ms,3); + assert.equal(s.presentation.estimated_capture_to_present_ms,66);assert.equal(s.presentation.receive_to_present_ms,10); + assert.equal(s.presentation.frame_decode_ms,3);assert.equal(s.decoded_fps,7.8); +}); +test('missing remote clock estimates and invalid SDK fields remain unknown, not zero latency',()=>{ + const d=new StreamDiagnostics();d.observeNative(0,{rtd:NaN,avgDecodeTime:-1,fps:0,codec:'secret://endpoint',extra:'ignored'}); + d.observeFrame(1,{expectedDisplayTime:2});const s=d.snapshot(2,0); + assert.equal(s.native.fps,0);assert.equal(s.native.round_trip_ms,null);assert.equal(s.native.decode_ms,null); + assert.equal(s.native.codec,null);assert.equal(s.native.extra,undefined);assert.equal(s.presentation.estimated_capture_to_present_ms,null); +}); +test('stalled native and presentation samples expire independently after three seconds',()=>{ + const d=new StreamDiagnostics();d.observeNative(0,{fps:8});d.observeFrame(2500,{expectedDisplayTime:2501}); + assert.equal(d.snapshot(3001,0).native,null);assert.ok(d.snapshot(3001,0).presentation); + assert.equal(d.snapshot(5501,0).presentation,null); +}); +test('invalid clock order cannot become a claimed end-to-end measurement',()=>{ + const d=new StreamDiagnostics();d.observeFrame(100,{expectedDisplayTime:100,captureTime:110,receiveTime:-1}); + assert.equal(d.snapshot(100,8).presentation.estimated_capture_to_present_ms,null); + assert.equal(d.snapshot(100,8).presentation.receive_to_present_ms,null); +}); diff --git a/docs/AI_POLYGON_ROUTE_PLANNING.md b/docs/AI_POLYGON_ROUTE_PLANNING.md index ac3d0102..6d67d3a2 100644 --- a/docs/AI_POLYGON_ROUTE_PLANNING.md +++ b/docs/AI_POLYGON_ROUTE_PLANNING.md @@ -157,3 +157,54 @@ terrain необходимо сверять observation ID: одинаковос отсутствие фактического продвижения не снимаются этим механизмом. Истечение срока не обновляет watchdog, не пополняет бюджет recovery, не засчитывает продвижение и не меняет `no_go`, сенсорную опору или допуск движения. + +## Доставка операторского изображения, 09.10.2026 + +Основное окно получает framebuffer Worker через `omni.kit.livestream.app` +(установлен 10.3.1), native WebRTC 10.7.0 и браузерный `@nvidia/ov-web-rtc` +6.7.0. Core согласует запуск; медиапоток идёт непосредственно в браузер по +существующему частному соединению. Цель 1280×720 / 30 FPS не является +измеренной частотой рендера. В прерванном run 11 Worker выдавал около 7,8 FPS; +замена транспорта сама по себе не создаёт недостающих исходных кадров. + +Сегментация, детекция и панорама пока принадлежат другому пути: JPEG/JSON, +ограничитель публикации 0,5 с, отдельная отправка Worker → Core каждые 0,5 с, +браузерный опрос через 0,5 с после ответа. Эти интервалы могут складываться; +они не доказывают конкретную сетевую задержку. `frame_age_ms` основной +телеметрии относится к использованному perception-кадру, а не к показанному +видеокадру. Медленные AI-слои не должны определять частоту операторского видео. + +`streamDiagnostics.ts` сохраняет один текущий образец SDK (кодек, bitrate, +FPS, RTT, decode, потери) и один образец browser video frame timing. +Они доступны для инженерной проверки в `data-stream-diagnostics` элемента +видео, истекают через 3 секунды и не записываются в постоянную телеметрию. +Параметры соединения и произвольные поля SDK не копируются. Для WebRTC +`captureTime` — оценка удалённых часов браузером через RTCP; соответствующее +время capture-to-present явно называется estimated. Отсутствующий timestamp +остаётся unknown. Нельзя вычитать Worker monotonic из браузерных часов или +выдавать RTT/2 за измеренную одностороннюю задержку. Диагностика не участвует +в native admission, управлении или выборе целей. + +Следующий performance gate сопоставляет render FPS/стоимость сенсоров, +SDK/браузерные decode и delivery, потери и фактический путь соединения на +одном native UI-заезде. WebRTC остаётся основой низкой задержки. Перенос +дополнительных изображений в управляемые медиапотоки (например, GStreamer +webrtcsink с аппаратным encoder) требует отдельной версии Worker-адаптера, +ограниченных очередей последних кадров, адаптации bitrate и измеренной +совместимости декодера. Это следующий этап, а не уже выполненная миграция. +Новый relay/SFU или другой codec не добавляется лишь по названию; его польза +должна быть измерена. Частота и точность сенсоров автономии, исходные Gaussian- +атрибуты и журнал доказательств сохраняют отдельные требования. + +Первый native UI-замер run 12: активная симуляция 7–8 декодированных FPS, +RTT 5–9 мс, decode около 3 мс, нулевые счётчики потерь в снятых образцах. +Пауза через UI дала 27–28 FPS на том же соединении; продолжение вернуло 7–8. +В большинстве снятых образцов receive-to-present было 15–18 мс, но после +продолжения отмечено 264 мс. `captureTime` отсутствовал: полная задержка от +генерации кадра не измерена, latency gate не закрыт. Это короткое сравнение, +не P95 длительного заезда и не проверка WAN под потерями. В 3394 сохранённых +perception-образцах run 11 RGB readback P50/P95 ≈15/16 мс, range_capture +≈78/94 мс. `MountedRange.capture` вызывает scalar native first-hit query +в цикле Python внутри главного цикла; перенос/пакетирование этой работы требует +проверки привязки всех лучей к исходной позе, self-occlusion и unknown. +Уменьшать число лучей или продлевать свежесть ради FPS этим выводом не разрешается.