diff --git a/apps/control-station/scripts/install-rerun-navigation.mjs b/apps/control-station/scripts/install-rerun-navigation.mjs index 642a88d7..40aaa524 100644 --- a/apps/control-station/scripts/install-rerun-navigation.mjs +++ b/apps/control-station/scripts/install-rerun-navigation.mjs @@ -32,6 +32,26 @@ const additions = { }, }; +// Preserve the exact previous patch as an audited upgrade path. +for (const [name, addition] of Object.entries(additions)) { + addition.previousCode = addition.code; + if (name === "index.d.ts") { + addition.code += " set_height_slice(lower: number | null, upper: number | null): boolean;\n get_height_bounds(): {min: number; max: number} | null;\n"; + } else { + const typed = name === "index.ts"; + addition.code += ` set_height_slice(lower${typed ? ": number | null" : ""}, upper${typed ? ": number | null" : ""})${typed ? ": boolean" : ""} { + if (!this.#handle) throw new Error("Rerun viewer is stopped"); + const off = lower === null && upper === null; + return this.#handle.nodedc_height_slice(off ? undefined : (lower ?? -3e38), off ? undefined : (upper ?? 3e38)); + } + get_height_bounds()${typed ? ": {min: number; max: number} | null" : ""} { + if (!this.#handle) throw new Error("Rerun viewer is stopped"); + return JSON.parse(this.#handle.nodedc_height_bounds() ?? "null"); + } +`; + } +} + // Validate the complete set before changing any installed file. A package // upgrade, corrupt artifact or independently modified wrapper fails closed. const writes = []; @@ -39,9 +59,9 @@ for (const [name, identity] of Object.entries(manifest.files)) { const current = readFileSync(resolve(packageRoot, name)); let output; if (additions[name]) { - const { marker, code } = additions[name]; + const { marker, code, previousCode } = additions[name]; const source = current.toString("utf8"); - const original = source.includes(code) ? source.replace(code, "") : source; + const original = source.includes(code) ? source.replace(code, "") : source.replace(previousCode, ""); if (sha(original) !== identity.upstreamSha256 || original.split(marker).length !== 2) { throw new Error(`Unexpected upstream wrapper: ${name}`); } @@ -49,7 +69,7 @@ for (const [name, identity] of Object.entries(manifest.files)) { } else { output = readFileSync(resolve(vendorRoot, identity.artifact)); if (sha(output) !== identity.sha256) throw new Error(`Corrupt navigation artifact: ${name}`); - if (![identity.upstreamSha256, identity.sha256].includes(sha(current))) { + if (![identity.upstreamSha256, identity.previousArtifactSha256, identity.sha256].includes(sha(current))) { throw new Error(`Unexpected installed runtime: ${name}`); } } diff --git a/apps/control-station/src/components/RerunViewport.tsx b/apps/control-station/src/components/RerunViewport.tsx index b6a2b583..020a4501 100644 --- a/apps/control-station/src/components/RerunViewport.tsx +++ b/apps/control-station/src/components/RerunViewport.tsx @@ -2,8 +2,7 @@ import { useEffect, useRef, useState } from "react"; import { createIsolatedRerunHost } from "./rerun/isolatedRerunHost"; import { keepRecordedBlueprintSession } from "../core/observation/recordedBlueprintLifecycle"; import { - RECORDED_RERUN_ORBITAL_EYE, - RECORDED_RERUN_PLAN_EYE, + selectRecordedRerunCameraEye, type RecordedRerunCameraEye, } from "./rerun/recordedRerunCameraJournal"; @@ -148,10 +147,7 @@ export interface RerunViewportProps { interface RerunBlueprintChannel { endpointUrl: string; cameraContract?: string | null; - appliedFollowTrajectory?: boolean | null; - pendingFollowCameraEye?: RecordedRerunCameraEye | null; getCameraEye?: () => RecordedRerunCameraEye | null; - getCurrentTimeNs?: () => number | null; channel: { readonly ready: boolean; send_rrd: (rrdBytes: Uint8Array) => void; @@ -1649,16 +1645,9 @@ function RerunViewportInstance({ blueprintChannel = { endpointUrl: recordedBlueprintUrl, cameraContract: null, - appliedFollowTrajectory: null, - pendingFollowCameraEye: null, getCameraEye: () => "get_camera_eye" in viewer ? viewer.get_camera_eye() : null, - getCurrentTimeNs: () => { - const currentIdentity = recordedIdentityRef.current; - if (!currentIdentity) return null; - return viewer.get_current_time(currentIdentity.recordingId, "session_time"); - }, channel, }; blueprintChannelRef.current = blueprintChannel; @@ -2114,29 +2103,7 @@ function RerunViewportInstance({ ); const cameraContractChanged = active.cameraContract !== cameraContract; const abort = new AbortController(); - const previousFollow = active.appliedFollowTrajectory ?? false; - const enablingFollow = recordedFollowTrajectory && !previousFollow; - const disablingFollow = !recordedFollowTrajectory && previousFollow; - const transitionEye = (enablingFollow || disablingFollow) - ? active.getCameraEye?.() - : null; - if (enablingFollow && transitionEye) { - active.pendingFollowCameraEye = transitionEye; - } else if (disablingFollow) { - active.pendingFollowCameraEye = null; - } - const pendingFollowEye = recordedFollowTrajectory - ? active.pendingFollowCameraEye ?? null - : null; - const requestBlueprint = async ( - cameraEye?: RecordedRerunCameraEye, - eyeRelativeToTracking = false, - reactivateUpdates = false, - ) => { - const currentTimeNs = active.getCurrentTimeNs?.(); - if (eyeRelativeToTracking && currentTimeNs == null) { - throw new Error("Recorded tracking cursor is unavailable"); - } + const requestBlueprint = async (cameraEye?: RecordedRerunCameraEye) => { return fetchRecordedBlueprintRrd(recordedBlueprintUrl, {...sceneSettings, showPoints: sceneSettings.showPoints && !pointDisplay.hidePoints}, identity, { displayPointBank: pointDisplay.bank, @@ -2152,12 +2119,11 @@ function RerunViewportInstance({ unifiedCameraShare: recordedUnifiedCameraShare, planView: recordedPlanView, cameraEye, - eyeRelativeToTracking, - // Only following-eye transitions need a pose at the cursor. Supplying - // time for display-only updates makes the API scan the entire archive - // for camera bounds, although neither the camera nor its pose changed. - currentTimeNs: eyeRelativeToTracking ? currentTimeNs : undefined, - reactivateUpdates, + // The native controller owns continuous tracking and its world eye. + // Reinterpreting this as a rig-relative eye snaps an off-centre view + // back onto the rig. It also needlessly scans the recording for a pose. + eyeRelativeToTracking: false, + reactivateUpdates: true, }); }; const canApply = () => ( @@ -2175,43 +2141,14 @@ function RerunViewportInstance({ return true; }; void (async () => { - const firstEye = disablingFollow - ? transitionEye ?? undefined - : !enablingFollow && (cameraContractChanged || pendingFollowEye) - ? pendingFollowEye ?? (recordedPlanView ? RECORDED_RERUN_PLAN_EYE : RECORDED_RERUN_ORBITAL_EYE) - : !enablingFollow ? active.getCameraEye?.() ?? undefined : undefined; - const firstEyeIsTrackingRelative = Boolean(firstEye) && ( - disablingFollow || recordedFollowTrajectory + // Reactivating a blueprint replaces the edited native store. Carry its + // actual eye through follow/layer/display changes in one update; only + // explicit reset and plan/3D changes select a startup preset. + const cameraEye = selectRecordedRerunCameraEye( + cameraContractChanged, recordedPlanView, active.getCameraEye?.() ?? null, ); - const firstPayload = await requestBlueprint( - firstEye, - firstEyeIsTrackingRelative, - // Upstream copies incoming blueprints into an active store. Every - // settings update must activate it; merely appending rows is invisible. - // Activation copies the incoming blueprint store, not the operator's - // edited store. Preserve its actual native eye on display-only updates; - // omitting the eye resurrects the embedded startup camera. - true, - ); - if (!applyPayload(firstPayload)) return; - active.cameraContract = cameraContract; - active.appliedFollowTrajectory = recordedFollowTrajectory; - if (!enablingFollow || !transitionEye) { - if (pendingFollowEye && firstEye === pendingFollowEye) { - active.pendingFollowCameraEye = null; - } - return; - } - - // Rerun 0.36.3 intentionally fits a newly tracked transform to its - // bounding box. Apply the operator's relative eye on the next native - // frame, after tracking is established, to retain direction and zoom. - await new Promise((resolve) => window.requestAnimationFrame(() => resolve())); - await new Promise((resolve) => window.requestAnimationFrame(() => resolve())); - if (!canApply()) return; - const stabilizedPayload = await requestBlueprint(transitionEye, true, true); - if (!applyPayload(stabilizedPayload)) return; - active.pendingFollowCameraEye = null; + const payload = await requestBlueprint(cameraEye); + if (applyPayload(payload)) active.cameraContract = cameraContract; })().catch((error: unknown) => { // The recording remains usable with its embedded default blueprint. // A later settings change retries through the same small channel. diff --git a/apps/control-station/src/components/rerun/isolatedRerunHost.ts b/apps/control-station/src/components/rerun/isolatedRerunHost.ts index da018653..c045e932 100644 --- a/apps/control-station/src/components/rerun/isolatedRerunHost.ts +++ b/apps/control-station/src/components/rerun/isolatedRerunHost.ts @@ -7,18 +7,58 @@ export function createIsolatedRerunHost(host: HTMLElement) { let frame: HTMLIFrameElement | null = host.ownerDocument.createElement("iframe"); frame.title = "Синхронизированная запись"; frame.className = "rerun-viewport__runtime"; - frame.src = "/rerun-runtime.html"; + frame.loading = "eager"; + let navigation: number | undefined; let disposed = false; let releaseFacade: (() => void) | null = null; let releaseInput: (() => void) | null = null; let frameWindow: RerunFrameWindow | null = null; let rejectReady: ((reason: Error) => void) | null = null; let timer: ReturnType | undefined; + const bootstrapAbort = new AbortController(); + let markup: string | null = null; + let fetching = false; + const scheduleNavigation = () => { + if (disposed || navigation !== undefined) return; + const window = host.ownerDocument.defaultView; + const navigate = () => { + navigation = undefined; + if (disposed) return; + // Observation portals may exist before the asynchronous dock is mounted. + // Start the isolated realm only once its host belongs to the document. + if (host.isConnected === false) { + scheduleNavigation(); + return; + } + frame!.src = "/rerun-runtime.html"; + if (markup === null) { + if (fetching) return; + fetching = true; + // Fetch only the bundled, same-origin document. Inline it into the + // isolated realm so startup does not depend on a deferred iframe + // document navigation inside a dock/portal. Its assets use root URLs. + void fetch("/rerun-runtime.html", {signal: bootstrapAbort.signal, credentials: "same-origin", redirect: "error"}) + .then(response => { if (!response.ok) throw new Error("Recorded viewer host failed to load"); return response.text(); }) + .then(value => { if (!disposed) { markup = value; scheduleNavigation(); } }) + .catch(() => { if (!disposed) { rejectReady?.(new Error("Recorded viewer host failed to load")); dispose(); } }); + return; + } + frame!.srcdoc = markup; + if (frame!.parentNode !== host) host.append(frame!); + }; + // A background operator tab may suspend animation frames completely. + // Bootstrap must progress independently of painting or focus. + if (window?.setTimeout) navigation = window.setTimeout(navigate, 50); + else navigate(); + }; const dispose = () => { if (disposed) return; disposed = true; + if (navigation !== undefined) host.ownerDocument.defaultView?.clearTimeout(navigation); clearTimeout(timer); + bootstrapAbort.abort(); + delete host.dataset.rerunCamera; frame!.onload = null; frame!.onerror = null; releaseInput?.(); @@ -32,6 +72,7 @@ export function createIsolatedRerunHost(host: HTMLElement) { frameWindow = null; frame!.remove(); frame = null; + markup = null; rejectReady?.(new Error("Recorded viewer was disposed")); rejectReady = null; } @@ -39,21 +80,38 @@ export function createIsolatedRerunHost(host: HTMLElement) { const ready = new Promise<{ viewer: RecordedRerunViewer; mount: HTMLElement }>((resolve, reject) => { rejectReady = reject; - frame!.onload = () => { + const handleLoad = () => { if (disposed) return; try { frameWindow = frame!.contentWindow as RerunFrameWindow | null; const api = frameWindow?.missionCoreRerun; + if (!api && frame!.contentDocument?.URL === "about:blank") { + return; + } if (!api || api.version !== 2) throw new Error("Recorded viewer host is unavailable"); const owner = createRecordedRerunFacade((request, bytes) => { const current = frameWindow?.missionCoreRerun; if (!current) throw new Error("Recorded viewer was disposed"); - return current.invoke(request, bytes); + const response = current.invoke(request, bytes); + // Bounded, read-only evidence of the rendered eye at the existing + // playback poll. No extra timer, transport, history or camera writes. + if (JSON.parse(request).method === "get_current_time") { + try { + const eye = JSON.parse(current.invoke('{"method":"get-camera-eye"}')); + host.dataset.rerunCamera = JSON.stringify({ + timeNs: JSON.parse(response).result ?? null, eye: eye.result ?? null, + }); + } catch { delete host.dataset.rerunCamera; } + } + return response; }); releaseFacade = owner.dispose; api.connect(owner.notify); releaseInput = relayIsolatedRerunInput(host, frameWindow, frame); clearTimeout(timer); + bootstrapAbort.abort(); + if (navigation !== undefined) host.ownerDocument.defaultView?.clearTimeout(navigation); + navigation = undefined; rejectReady = null; frame!.onload = null; frame!.onerror = null; @@ -63,15 +121,21 @@ export function createIsolatedRerunHost(host: HTMLElement) { dispose(); } }; - frame!.onerror = () => { + const handleError = () => { reject(new Error("Recorded viewer host failed to load")); dispose(); }; + const bind = (element: HTMLIFrameElement) => { + element.onload = () => { if (frame === element) handleLoad(); }; + element.onerror = () => { if (frame === element) handleError(); }; + }; + bind(frame!); timer = setTimeout(() => { reject(new Error("Recorded viewer host timed out")); dispose(); }, 30_000); + }); - host.append(frame); + scheduleNavigation(); return { ready, dispose }; } diff --git a/apps/control-station/src/components/rerun/recordedRerunCameraJournal.ts b/apps/control-station/src/components/rerun/recordedRerunCameraJournal.ts index d7f64370..477fd35a 100644 --- a/apps/control-station/src/components/rerun/recordedRerunCameraJournal.ts +++ b/apps/control-station/src/components/rerun/recordedRerunCameraJournal.ts @@ -26,3 +26,14 @@ export function readNativeRerunCameraEye(value: unknown): RecordedRerunCameraEye }; return { position: vector("position"), lookTarget: vector("lookTarget"), eyeUp: vector("eyeUp") }; } + +/** Select an eye for blueprint replacement, never implement camera motion. */ +export function selectRecordedRerunCameraEye( + cameraContractChanged: boolean, + planView: boolean, + currentEye: RecordedRerunCameraEye | null, +): RecordedRerunCameraEye | undefined { + return cameraContractChanged + ? (planView ? RECORDED_RERUN_PLAN_EYE : RECORDED_RERUN_ORBITAL_EYE) + : currentEye ?? undefined; +} diff --git a/apps/control-station/src/components/rerun/recordedRerunFacade.ts b/apps/control-station/src/components/rerun/recordedRerunFacade.ts index e42e7d5c..72d7cccc 100644 --- a/apps/control-station/src/components/rerun/recordedRerunFacade.ts +++ b/apps/control-station/src/components/rerun/recordedRerunFacade.ts @@ -12,6 +12,8 @@ export type RecordedRerunViewer = Pick & { open_channel: (name?: string) => Channel; get_camera_eye: () => RecordedRerunCameraEye | null; + set_height_slice: (lower:number|null,upper:number|null)=>boolean; + get_height_bounds: ()=>{min:number;max:number}|null; }; /** Parent-owned values only. No SDK Promise or foreign prototype escapes. */ @@ -88,6 +90,8 @@ export function createRecordedRerunFacade(invoke: RerunInvoke | null) { set_current_time: (...args) => command("set_current_time", args), set_playing: (...args) => command("set_playing", args), get_camera_eye: () => command("get-camera-eye"), + set_height_slice: (lower,upper) => command("set-height-slice",[lower,upper]), + get_height_bounds: () => command("get-height-bounds"), }; return { facade, dispose, notify }; } diff --git a/apps/control-station/src/components/rerun/recordedRerunOwner.ts b/apps/control-station/src/components/rerun/recordedRerunOwner.ts index b42a2c05..252baf5a 100644 --- a/apps/control-station/src/components/rerun/recordedRerunOwner.ts +++ b/apps/control-station/src/components/rerun/recordedRerunOwner.ts @@ -80,6 +80,13 @@ export function createRecordedRerunOwner(create: () => WebViewer, mount: HTMLEle case "get-camera-eye": result = readNativeRerunCameraEye( (required() as WebViewer & { get_camera_eye?(): unknown }).get_camera_eye?.(), ); break; + case "set-height-slice": { + const [lower,upper]=args; + if ([lower,upper].some(v=>v!==null&&(typeof v!=="number"||!Number.isFinite(v))) || + (lower!==null&&upper!==null&&lower>upper)) throw new Error("Invalid height slice"); + result=(required() as WebViewer & {set_height_slice?(lower:number|null,upper:number|null):boolean}).set_height_slice?.(lower,upper)??false; + } break; + case "get-height-bounds": result=(required() as WebViewer & {get_height_bounds?():{min:number;max:number}|null}).get_height_bounds?.()??null; break; case "open": required().open(args[0]); break; case "close": required().close(args[0]); break; case "override_panel_state": required().override_panel_state(args[0], args[1]); break; diff --git a/apps/control-station/test/liveRerunPlayback.test.mjs b/apps/control-station/test/liveRerunPlayback.test.mjs new file mode 100644 index 00000000..a551e55a --- /dev/null +++ b/apps/control-station/test/liveRerunPlayback.test.mjs @@ -0,0 +1,26 @@ +import assert from 'node:assert/strict'; +import {before,after,test} from 'node:test'; +import {createServer} from './support/vite-server.mjs'; +let server,create; +before(async()=>{server=await createServer({appType:'custom',logLevel:'silent'});({liveRerunPlayback:create}=await server.ssrLoadModule('../../packages/sensor-ui/src/liveRerunPlayback.ts'));}); +after(async()=>{await server?.close();}); +function fixture(){ + const data={id:'a',range:{min:0,max:10e9},time:10e9,playing:false,calls:[]}; + const viewer={get_active_recording_id:()=>data.id,get_time_range:()=>({...data.range}),get_current_time:()=>data.time,get_playing:()=>data.playing,set_current_time:(_id,_timeline,time)=>{data.calls.push(['time',time]);data.time=time;},set_playing:(_id,playing)=>{data.calls.push(['play',playing]);data.playing=playing;}}; + return {data,controller:create(viewer)}; +} +test('rewind pauses only the playhead, retains new data and returns to the latest received frame',()=>{ + const {data,controller:c}=fixture();assert.equal(c.read().live,true); + const count=data.calls.length;c.read();assert.equal(data.calls.length,count,'an unchanged range must not enqueue native commands'); + c.seek(3e9);assert.equal(data.time,3e9);assert.equal(data.playing,false); + data.range.max=20e9;const paused=c.read();assert.equal(paused.currentNs,3e9);assert.equal(paused.rangeNs.max,20e9);assert.equal(paused.live,false); + c.setPlaying(true);assert.equal(data.time,3e9);assert.equal(data.playing,true); + data.time=4e9;assert.equal(c.read().currentNs,4e9); + assert.equal(c.jumpToLive().currentNs,20e9);data.range.max=21e9;assert.equal(c.read().currentNs,21e9); +}); +test('native retention and acquisition changes cannot expose an expired history cursor',()=>{ + const {data,controller:c}=fixture();c.read();c.seek(-1);assert.equal(data.time,0); + data.range.min=5e9;assert.equal(c.read().currentNs,5e9); + c.seek(Infinity);assert.equal(data.time,5e9); + data.id='b';data.range={min:50e9,max:51e9};assert.equal(c.read().live,true);assert.equal(data.time,51e9); +}); diff --git a/apps/control-station/test/recordedRerunCameraJournal.test.mjs b/apps/control-station/test/recordedRerunCameraJournal.test.mjs index 74f52efe..02494138 100644 --- a/apps/control-station/test/recordedRerunCameraJournal.test.mjs +++ b/apps/control-station/test/recordedRerunCameraJournal.test.mjs @@ -3,11 +3,11 @@ import { readFileSync } from "node:fs"; import { after, before, test } from "node:test"; import { createServer } from "./support/vite-server.mjs"; -let server, readNativeRerunCameraEye; +let server, readNativeRerunCameraEye, selectRecordedRerunCameraEye; before(async () => { server = await createServer({ appType: "custom", logLevel: "silent", server: { middlewareMode: true } }); - ({ readNativeRerunCameraEye } = await server.ssrLoadModule( + ({ readNativeRerunCameraEye, selectRecordedRerunCameraEye } = await server.ssrLoadModule( "/src/components/rerun/recordedRerunCameraJournal.ts")); }); after(async () => { await server?.close(); }); @@ -34,9 +34,22 @@ test("iframe owner reads the native camera and installs no shadow input listener assert.doesNotMatch(owner + camera, /createRecordedRerunCameraJournal|addEventListener|Math\.exp/); }); -test("display blueprint activation carries the current native eye, not the embedded preset", () => { +test("follow and display changes preserve an off-centre world eye, including looking away", () => { + const eye = { position: [120, 40, 25], lookTarget: [120, 40, 45], eyeUp: [0, 1, 0] }; + assert.deepEqual(selectRecordedRerunCameraEye(false, false, eye), eye); + assert.deepEqual(selectRecordedRerunCameraEye(false, true, eye), eye); + assert.equal(selectRecordedRerunCameraEye(false, false, null), undefined); +}); + +test("only explicit reset or plan/3D changes choose a camera preset", () => { + const eye = { position: [120, 40, 25], lookTarget: [120, 40, 45], eyeUp: [0, 1, 0] }; + assert.deepEqual(selectRecordedRerunCameraEye(true, false, eye).lookTarget, [0, 0, 0]); + assert.deepEqual(selectRecordedRerunCameraEye(true, true, eye).position, [0, 0, 30]); +}); + +test("recorded adapter preserves the native eye in one world-space activation", () => { const viewport = readFileSync(new URL("../src/components/RerunViewport.tsx", import.meta.url), "utf8"); - assert.match(viewport, /!enablingFollow \? active\.getCameraEye\?\.\(\) \?\? undefined : undefined/); - assert.match(viewport, /requestBlueprint\(\s*firstEye,\s*firstEyeIsTrackingRelative,/); - assert.match(viewport, /currentTimeNs: eyeRelativeToTracking \? currentTimeNs : undefined/); + assert.match(viewport, /selectRecordedRerunCameraEye\(\s*cameraContractChanged, recordedPlanView, active\.getCameraEye/); + assert.match(viewport, /eyeRelativeToTracking: false/); + assert.doesNotMatch(viewport, /pendingFollowCameraEye|stabilizedPayload|firstEyeIsTrackingRelative/); }); diff --git a/apps/control-station/test/recordedViewerResourceLifecycle.test.mjs b/apps/control-station/test/recordedViewerResourceLifecycle.test.mjs index 04a053b5..edec3312 100644 --- a/apps/control-station/test/recordedViewerResourceLifecycle.test.mjs +++ b/apps/control-station/test/recordedViewerResourceLifecycle.test.mjs @@ -26,6 +26,7 @@ function fixture(t, { stopFails = false } = {}) { timers.set(++timerId, fn); return timerId; }); t.mock.method(globalThis, "clearTimeout", (id) => timers.delete(id)); + t.mock.method(globalThis, "fetch", async () => ({ok: true, text: async () => "
"})); const listeners = new Map(); const viewer = { stop() { stops++; if (stopFails) throw new Error("partial start"); } }; const mount = {}; @@ -39,7 +40,10 @@ function fixture(t, { stopFails = false } = {}) { }; const host = { dataset: {}, ownerDocument: { createElement(name) { assert.equal(name, "iframe"); return frame; - } }, append(child) { assert.equal(child, frame); } }; + } }, append(child) { + assert.equal(child, frame); + assert.equal(child.src, '/rerun-runtime.html', 'URL must precede browsing-context insertion'); + } }; return { host, frame, viewer, mount, timers, listeners, counts: () => ({ creates, stops, removals }) }; } @@ -87,6 +91,27 @@ test("recorded realm terminates on close even if upstream stop throws", async (t assert.equal(ready.viewer.ready, false); }); +test("playback poll publishes only the latest native eye and removes it on disposal", async (t) => { + const f = fixture(t); + let time = 1; + let position = [300, 7, 8]; + f.viewer.get_current_time = () => time; + f.viewer.get_camera_eye = () => ({ position, lookTarget: [298, 9, 0], eyeUp: [0, 0, 1] }); + const scope = createIsolatedRerunHost(f.host); + f.frame.onload(); + const { viewer } = await scope.ready; + assert.equal(viewer.get_current_time("recording", "session_time"), 1); + assert.deepEqual(JSON.parse(f.host.dataset.rerunCamera).eye.position, [300, 7, 8]); + time = 2; + position = [310, 9, 8]; + assert.equal(viewer.get_current_time("recording", "session_time"), 2); + const latest = JSON.parse(f.host.dataset.rerunCamera); + assert.equal(latest.timeNs, 2); + assert.deepEqual(latest.eye.position, position); + scope.dispose(); + assert.equal(f.host.dataset.rerunCamera, undefined); +}); + test("native frame input relays Escape and leaves pointer ownership inside Rerun", () => { const listeners = new Map(), events = []; class ParentEvent { constructor(type, init) { this.type = type; Object.assign(this, init); } } @@ -146,6 +171,95 @@ test("close before frame load cancels startup and cannot reopen", async (t) => { assert.equal(f.timers.size, 0); }); +test("detached observation portal navigates only after attachment and cancels pending navigation", async (t) => { + const f = fixture(t), frames = new Map(); let sequence = 0; + f.host.isConnected = f.frame.isConnected = false; + f.host.ownerDocument.defaultView = { + requestAnimationFrame() { throw new Error('Background tab does not paint'); }, + setTimeout(fn) { frames.set(++sequence, fn); return sequence; }, + clearTimeout(id) { frames.delete(id); }, + }; + const tick = () => { const [id, fn] = frames.entries().next().value; frames.delete(id); fn(); }; + const scope = createIsolatedRerunHost(f.host); + tick(); tick(); + assert.equal(f.frame.src, undefined); + f.host.isConnected = f.frame.isConnected = true; + tick(); assert.equal(f.frame.src, '/rerun-runtime.html'); + f.frame.onload(); await scope.ready; scope.dispose(); + assert.equal(frames.size, 0); + + f.host.isConnected = f.frame.isConnected = false; + const pending = createIsolatedRerunHost(f.host); + const rejection = assert.rejects(pending.ready, /disposed/); + pending.dispose(); await rejection; + assert.equal(frames.size, 0); +}); + +test("initial blank load is ignored while the bundled document is fetched within its deadline", async (t) => { + const f = fixture(t), navigations = new Map(); let sequence = 0; + f.host.ownerDocument.defaultView = { + setTimeout(fn) { navigations.set(++sequence, fn); return sequence; }, + clearTimeout(id) { navigations.delete(id); }, + }; + const tick = () => { const [id, fn] = navigations.entries().next().value; navigations.delete(id); fn(); }; + const scope = createIsolatedRerunHost(f.host); + const deadline = [...f.timers.keys()]; + tick(); + const api = f.frame.contentWindow.missionCoreRerun; + delete f.frame.contentWindow.missionCoreRerun; + f.frame.contentDocument = {URL: "about:blank"}; + f.frame.onload(); f.frame.onload(); + assert.equal(navigations.size, 0); + assert.deepEqual([...f.timers.keys()], deadline); + assert.equal(f.frame.src, "/rerun-runtime.html"); + f.frame.contentWindow.missionCoreRerun = api; + f.frame.contentDocument.URL = "http://localhost/rerun-runtime.html"; + f.frame.onload(); await scope.ready; + assert.equal(navigations.size, 0); + scope.dispose(); + assert.equal(f.timers.size, 0); +}); + +test("bundled document is fetched once and installed before the isolated realm is attached", async (t) => { + const f = fixture(t); let requests = 0, attached = 0; + t.mock.method(globalThis, 'fetch', async (url, options) => { + assert.equal(url, '/rerun-runtime.html'); + assert.equal(options.redirect, 'error'); requests++; + return {ok:true, text:async()=>'runtime'}; + }); + f.host.append = frame => { assert.equal(frame.srcdoc, 'runtime'); attached++; }; + const scope = createIsolatedRerunHost(f.host); + await new Promise(setImmediate); + assert.equal(requests, 1); assert.equal(attached, 1); + f.frame.onload(); await scope.ready; scope.dispose(); + assert.equal(f.timers.size, 0); +}); + +test("closing during document fetch cancels it and late content cannot attach a frame", async (t) => { + const f = fixture(t); let finish, signal, attached = 0; + t.mock.method(globalThis, 'fetch', (_url, options) => { + signal=options.signal; return new Promise(resolve=>{finish=resolve;}); + }); + f.host.append = () => attached++; + const scope = createIsolatedRerunHost(f.host); + const rejected = assert.rejects(scope.ready, /disposed/); + scope.dispose(); await rejected; + assert.equal(signal.aborted, true); + finish({ok:true,text:async()=>'late'}); + await new Promise(setImmediate); + assert.equal(attached, 0); assert.equal(f.counts().creates, 0); + assert.equal(f.timers.size, 0); +}); + +test("document fetch failure releases the empty realm and its deadline", async (t) => { + const f = fixture(t); + t.mock.method(globalThis, 'fetch', async()=>({ok:false})); + const scope = createIsolatedRerunHost(f.host); + await assert.rejects(scope.ready, /failed to load/); + assert.equal(f.counts().removals, 1); + assert.equal(f.timers.size, 0); +}); + test("closing during SDK startup also releases a late successful start", async () => { let finish, stops = 0; const owner = bridge({ diff --git a/apps/control-station/test/rerunViewportAtomicAdmission.test.mjs b/apps/control-station/test/rerunViewportAtomicAdmission.test.mjs index 669af6cd..37106819 100644 --- a/apps/control-station/test/rerunViewportAtomicAdmission.test.mjs +++ b/apps/control-station/test/rerunViewportAtomicAdmission.test.mjs @@ -252,9 +252,9 @@ test("recorded RRD bytes are never split across LogChannel.send_rrd calls", asyn assert.match(source, /recordedPerceptionLayers\.costmap !== undefined && status !== "ready"/); assert.match(source, /perceptionLayers\.costmap === undefined \? \{\} : \{\s*show_costmap: perceptionLayers\.costmap,\s*reactivate_updates: true/s); // Ordinary archives need activation too, not only the LAB costmap path. - assert.match(source, /requestBlueprint\(\s*firstEye,\s*firstEyeIsTrackingRelative,[\s\S]*?\n\s*true,\s*\);/); + assert.match(source, /cameraEye,\s*[\s\S]*?eyeRelativeToTracking: false,\s*reactivateUpdates: true,/); // Display changes must not trigger a full-file camera-bounds scan. - assert.match(source, /currentTimeNs: eyeRelativeToTracking \? currentTimeNs : undefined/); + assert.doesNotMatch(source, /currentTimeNs: eyeRelativeToTracking|Recorded tracking cursor is unavailable/); assert.match(source, /viewer\.start\(\s*rerunViewerInitialSource\(resolvedSource\)/s); assert.doesNotMatch(source, /rerunViewerOpenOptions/); assert.match( diff --git a/apps/control-station/test/rerunWebViewerVendor.test.mjs b/apps/control-station/test/rerunWebViewerVendor.test.mjs index 0bb8dff0..f89bd0e8 100644 --- a/apps/control-station/test/rerunWebViewerVendor.test.mjs +++ b/apps/control-station/test/rerunWebViewerVendor.test.mjs @@ -37,6 +37,8 @@ test("generated JS and native WASM share one ABI including the camera snapshot", const wasm = new WebAssembly.Module(readFileSync(resolve(packageRoot, "re_viewer_bg.wasm"))); const names = new Set(WebAssembly.Module.exports(wasm).map(item => item.name)); assert.ok(names.has("webhandle_nodedc_camera_eye")); + assert.ok(names.has("webhandle_nodedc_height_slice")); + assert.ok(names.has("webhandle_nodedc_height_bounds")); for (const [, name] of glue.matchAll(/\bwasm\.([a-zA-Z_$][\w$]*)/g)) { assert.ok(names.has(name), `Missing WASM export: ${name}`); } diff --git a/apps/control-station/vendor/rerun-web-viewer-0.36.3/NODEDC_NAVIGATION.patch b/apps/control-station/vendor/rerun-web-viewer-0.36.3/NODEDC_NAVIGATION.patch index 413be2c7..45443f5b 100644 --- a/apps/control-station/vendor/rerun-web-viewer-0.36.3/NODEDC_NAVIGATION.patch +++ b/apps/control-station/vendor/rerun-web-viewer-0.36.3/NODEDC_NAVIGATION.patch @@ -1,3 +1,93 @@ +--- a/crates/viewer/re_renderer/shader/point_cloud.wgsl ++++ b/crates/viewer/re_renderer/shader/point_cloud.wgsl +@@ -19,7 +19,7 @@ + // 256bytes in order to allow them to be buffer-suballocations. + // However, wgpu doesn't know this at this point and therefore requires `DownlevelFlags::BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED` + // if we wouldn't add padding here, which isn't available on WebGL. +- _padding: vec4f, ++ height_slice: vec4f, + }; + @group(1) @binding(3) + var draw_data: DrawDataUniformBuffer; +@@ -147,6 +147,12 @@ + out.point_center = point_data.pos; + out.quad_offset_from_center = quad.pos_in_world - point_data.pos; + out.picking_instance_id = point_data.picking_instance_id; ++ // Whole point quads outside the display slice are clipped in every pass. ++ // This preserves point IDs and affects retained history immediately. ++ if draw_data.height_slice.z > 0.0 && ++ (point_data.pos.z < draw_data.height_slice.x || point_data.pos.z > draw_data.height_slice.y) { ++ out.position = vec4f(2.0, 2.0, 2.0, 1.0); ++ } + + return out; + } +--- a/crates/viewer/re_renderer/src/point_cloud_builder.rs ++++ b/crates/viewer/re_renderer/src/point_cloud_builder.rs +@@ -24,6 +24,7 @@ + pub(crate) batches: Vec, + + pub(crate) radius_boost_in_ui_points_for_outlines: f32, ++ pub(crate) nodedc_height_slice: Option<[f32; 2]>, + } + + impl<'ctx> PointCloudBuilder<'ctx> { +@@ -35,7 +36,14 @@ + picking_instance_ids_buffer: DataTextureSource::new(ctx), + batches: Vec::with_capacity(16), + radius_boost_in_ui_points_for_outlines: 0.0, +- } ++ nodedc_height_slice: None, ++ } ++ } ++ ++ /// Clip in world coordinates in the existing point vertex shader, including ++ /// picking/outlines. Cached geometry and source point indices stay intact. ++ pub fn nodedc_height_slice(&mut self, range: Option<[f32; 2]>) { ++ self.nodedc_height_slice = range.filter(|r| r[0].is_finite() && r[1].is_finite() && r[0] <= r[1]); + } + + /// Returns number of points that can be added without reallocation. +--- a/crates/viewer/re_renderer/src/renderer/point_cloud.rs ++++ b/crates/viewer/re_renderer/src/renderer/point_cloud.rs +@@ -132,7 +132,8 @@ + #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] + pub struct DrawDataUniformBuffer { + pub radius_boost_in_ui_points: wgpu_buffer_types::F32RowPadded, +- pub end_padding: [wgpu_buffer_types::PaddingRow; 16 - 1], ++ pub height_slice: wgpu_buffer_types::Vec4, ++ pub end_padding: [wgpu_buffer_types::PaddingRow; 16 - 2], + } + + /// Uniform buffer that changes for every batch of points. +@@ -340,6 +341,7 @@ + picking_instance_ids_buffer, + batches, + radius_boost_in_ui_points_for_outlines, ++ nodedc_height_slice, + } = builder; + + let point_renderer = ctx.renderer::(); +@@ -388,16 +390,19 @@ + "PointCloudDrawData::picking_instance_id_texture", + )?; + ++ let height_slice = nodedc_height_slice.map_or(glam::Vec4::ZERO, |r| glam::vec4(r[0], r[1], 1.0, 0.0)); + let draw_data_uniform_buffer_bindings = create_and_fill_uniform_buffer_batch( + ctx, + "PointCloudDrawData::DrawDataUniformBuffer".into(), + [ + gpu_data::DrawDataUniformBuffer { + radius_boost_in_ui_points: 0.0.into(), ++ height_slice: height_slice.into(), + end_padding: Default::default(), + }, + gpu_data::DrawDataUniformBuffer { + radius_boost_in_ui_points: radius_boost_in_ui_points_for_outlines.into(), ++ height_slice: height_slice.into(), + end_padding: Default::default(), + }, + ] --- a/crates/viewer/re_view_spatial/src/eye.rs +++ b/crates/viewer/re_view_spatial/src/eye.rs @@ -2,7 +2,7 @@ @@ -9,7 +99,16 @@ use re_sdk_types::blueprint::components::{AngularSpeed, Eye3DKind}; use re_sdk_types::components::{LinearSpeed, Position3D, Vector3D}; use re_view::controls::{ -@@ -214,6 +214,8 @@ +@@ -199,6 +199,8 @@ + /// This should not be used to get the current tracked entity, get that + /// via view properties instead. + pub last_tracked_entity: Option, ++ // NODE.DC: prior entity position, not a replacement camera controller. ++ last_tracked_position: Option, + + interpolation: Option, + +@@ -214,6 +216,8 @@ pub last_look_target: Option, pub last_orbit_radius: Option, pub last_eye_up: Option, @@ -18,7 +117,7 @@ } #[derive(Clone, Debug, PartialEq, re_byte_size::SizeBytes)] -@@ -241,6 +243,7 @@ +@@ -241,6 +245,7 @@ fov_y: Option, did_interact: bool, @@ -26,7 +125,7 @@ } impl EyeController { -@@ -250,16 +253,8 @@ +@@ -250,16 +255,8 @@ /// Avoids breaking the view by zooming in too far. pub const MIN_ORBIT_DISTANCE: f32 = Eye::PERSPECTIVE_NEAR_PLANE * 2.0; @@ -45,7 +144,7 @@ fn get_eye(&self) -> Eye { Eye { -@@ -317,6 +312,10 @@ +@@ -317,6 +314,10 @@ .0, ); @@ -56,7 +155,7 @@ Ok(Self { pos, look_target, -@@ -325,6 +324,7 @@ +@@ -325,6 +326,7 @@ eye_up, did_interact: false, fov_y, @@ -64,7 +163,7 @@ }) } -@@ -482,12 +482,45 @@ +@@ -482,10 +484,68 @@ let up = rot * Vec3::Y; let right = rot * -Vec3::X; // TODO(emilk): why do we need a negation here? O.o @@ -84,8 +183,24 @@ self.pos += translate; self.look_target += translate; - } - ++ } ++ ++ /// Move the existing eye by the tracked entity's translation, retaining ++ /// the operator's offset, orientation and radius. Admission does not jump. ++ fn follow_translation(&mut self, previous: Option, current: Vec3) { ++ if let Some(previous) = previous { ++ let delta = current - previous; ++ if delta.is_finite() && delta != Vec3::ZERO { ++ self.pos += delta; ++ self.look_target += delta; ++ // The next frame reconstructs this rig from the blueprint. ++ // Its existing write gate must also commit autonomous tracking, ++ // otherwise every frame falls back to the last manual eye. ++ self.did_interact = true; ++ } ++ } ++ } ++ + /// Translate the whole rig, not its orientation/radius, onto the grid. + /// Called only by deliberate navigation while not following an entity. + fn anchor_orbit_to_grid(&mut self) { @@ -97,6 +212,15 @@ + } + } + ++ /// Ground only an automatic fallback; explicit/saved eyes retain height. ++ fn anchor_fallback_orbit_to_grid(&mut self, has_explicit_target: bool) { ++ if !has_explicit_target && self.kind == Eye3DKind::Orbital { ++ let before = self.look_target; ++ self.anchor_orbit_to_grid(); ++ self.did_interact |= self.look_target != before; ++ } ++ } ++ + fn zoom_orbit(&mut self, zoom_factor: f32) { + if !zoom_factor.is_finite() || zoom_factor <= 0.0 { + return; @@ -105,12 +229,10 @@ + .clamp(Self::MIN_ORBIT_DISTANCE, Self::MAX_ORBITAL_RADIUS); + self.pos = self.look_target - self.fwd() * new_radius; + self.did_interact = true; -+ } -+ + } + fn handle_drag(&mut self, response: &egui::Response, drag_threshold: f32) { - if response.drag_delta().length() > drag_threshold { - let roll = response.dragged_by(ROLL_MOUSE) -@@ -513,7 +546,7 @@ +@@ -513,7 +573,7 @@ } /// Handle zoom/scroll input. @@ -119,7 +241,7 @@ let zoom_factor = egui_ctx.input(|input| { // egui's default horizontal_scroll_modifier is shift, which is also our speed-up modifier. // This means that a user who wants to speed up scroll-to-zoom will generate a horizontal scroll delta. -@@ -528,22 +561,7 @@ +@@ -528,22 +588,7 @@ match self.kind { Eye3DKind::Orbital => { @@ -143,7 +265,7 @@ } Eye3DKind::FirstPerson => { // Move along the forward axis when zooming in first person mode. -@@ -707,25 +725,6 @@ +@@ -707,25 +752,6 @@ } } @@ -169,7 +291,7 @@ pub fn find_camera(cameras: &[PinholeWrapper], needle: &EntityPath) -> Option { let mut found_camera = None; -@@ -744,6 +743,103 @@ +@@ -744,6 +770,173 @@ fn ease_out(t: f32) -> f32 { 1. - (1. - t) * (1. - t) @@ -193,6 +315,76 @@ + } + + #[test] ++ fn following_commits_motion_without_manual_input_across_frames() { ++ let initial = controller(); ++ let mut saved = (initial.pos, initial.look_target, initial.eye_up); ++ let mut previous = Vec3::ZERO; ++ for target in [vec3(1.0, 2.0, 0.5), vec3(5.0, -3.0, 1.0), vec3(9.0, 7.0, 2.0)] { ++ // Each native frame reads the last saved blueprint, not the previous ++ // temporary controller. No mouse interaction opens the write gate. ++ let mut frame = controller(); ++ (frame.pos, frame.look_target, frame.eye_up) = saved; ++ frame.follow_translation(Some(previous), target); ++ assert!(frame.did_interact, "tracking must reach save_to_blueprint"); ++ assert!((frame.pos - initial.pos - target).length() < 0.001); ++ assert!((frame.look_target - initial.look_target - target).length() < 0.001); ++ assert_eq!(frame.eye_up, initial.eye_up); ++ assert!((frame.radius() - initial.radius()).abs() < 0.001); ++ saved = (frame.pos, frame.look_target, frame.eye_up); ++ previous = target; ++ } ++ } ++ ++ #[test] ++ fn following_admission_idle_and_invalid_pose_do_not_write_camera() { ++ for (previous, current) in [ ++ (None, vec3(12.0, 8.0, 2.0)), ++ (Some(Vec3::ZERO), Vec3::ZERO), ++ (Some(Vec3::ZERO), Vec3::splat(f32::NAN)), ++ (Some(Vec3::ZERO), Vec3::splat(f32::INFINITY)), ++ ] { ++ let mut c = controller(); ++ let before = (c.pos, c.look_target, c.eye_up); ++ c.follow_translation(previous, current); ++ assert_eq!((c.pos, c.look_target, c.eye_up), before); ++ assert!(!c.did_interact); ++ } ++ } ++ ++ #[test] ++ fn following_keeps_admission_eye_and_manual_offset() { ++ let mut c = controller(); ++ let before = (c.pos, c.look_target, c.eye_up); ++ c.follow_translation(None, vec3(12.0, 8.0, 2.0)); ++ assert_eq!((c.pos, c.look_target, c.eye_up), before); ++ c.translate(egui::vec2(4.0, 3.0)); ++ c.rotate(egui::vec2(2.0, 1.0)); ++ c.zoom_orbit(2.0); ++ let before = (c.pos, c.look_target, c.eye_up, c.radius()); ++ let movement = vec3(900.0, -230.0, 3.0); ++ c.follow_translation(Some(Vec3::ZERO), movement); ++ assert!((c.pos - before.0 - movement).length() < 0.001); ++ assert!((c.look_target - before.1 - movement).length() < 0.001); ++ assert_eq!(c.eye_up, before.2); ++ assert!((c.radius() - before.3).abs() < 0.001); ++ } ++ ++ #[test] ++ fn saved_eye_keeps_height_when_tracking_is_disabled() { ++ let mut c = controller(); ++ c.pos += vec3(0.0, 0.0, 40.0); ++ c.look_target += vec3(0.0, 0.0, 40.0); ++ let before = (c.pos, c.look_target, c.radius()); ++ c.anchor_fallback_orbit_to_grid(true); ++ assert_eq!((c.pos, c.look_target, c.radius()), before); ++ assert!(!c.did_interact); ++ c.anchor_fallback_orbit_to_grid(false); ++ assert_eq!(c.look_target.z, 0.0); ++ assert!((c.radius() - before.2).abs() < 0.0001); ++ assert!(c.did_interact); ++ } ++ ++ #[test] + fn pan_is_on_grid_and_moves_the_whole_rig() { + let mut c = controller(); + let offset = c.pos - c.look_target; @@ -273,23 +465,24 @@ } impl EyeState { -@@ -804,9 +900,32 @@ +@@ -804,8 +997,32 @@ } } -+ // Anchor before the first paint, not on the first orbit drag. This -+ // avoids a one-off camera jump when the scene-bounds fallback is high. -+ if tracking_entity.is_none() && eye_controller.kind == Eye3DKind::Orbital -+ && (eye_controller.grid_plane.normal.dot(eye_controller.look_target) -+ - eye_controller.grid_plane.d).abs() > 1.0e-5 -+ { -+ eye_controller.anchor_orbit_to_grid(); -+ eye_controller.did_interact = true; ++ // Anchor scene-bounds fallbacks before first paint, but never project ++ // an explicitly saved eye onto the grid when tracking is switched off. ++ if tracking_entity.is_none() { ++ let has_explicit_target = eye_property ++ .component_or_empty::( ++ EyeControls3D::descriptor_look_target().component, ++ )? ++ .is_some(); ++ eye_controller.anchor_fallback_orbit_to_grid(has_explicit_target); + } + // Handle spinning before inputs because some inputs depend on view direction. self.handle_spinning(ctx, eye_property, &mut eye_controller)?; - ++ + // NODE.DC: pin manual map navigation to the XY grid. Tracking and + // explicit camera presets retain their own target until manual input. + let manual_input = response.drag_delta().length_sq() > 0.0 @@ -302,11 +495,125 @@ + eye_controller.anchor_orbit_to_grid(); + } + } -+ + // We do input before tracking entity, because the input can cause the eye // to stop tracking. - let gamepad_navigation_status = eye_controller.handle_input( -@@ -1241,6 +1360,7 @@ +@@ -892,15 +1109,14 @@ + + let new_tracking = self.last_tracked_entity.as_ref() != Some(&tracking_entity); + if new_tracking { +- self.start_interpolation(); ++ self.last_tracked_position = None; + self.last_tracked_entity = Some(tracking_entity.clone()); +- } +- +- // If the position that doesn't move by changing the eye's rotation changed. +- let did_eye_orbit_center_change = match eye_controller.kind { +- Eye3DKind::FirstPerson => eye_controller.pos != old_pos, +- Eye3DKind::Orbital => eye_controller.look_target != old_look_target, +- }; ++ if find_camera(cameras, &tracking_entity).is_some() { ++ self.start_interpolation(); ++ } else { ++ self.stop_interpolation(); ++ } ++ } + + if let Some(target_eye) = find_camera(cameras, &tracking_entity) { + if eye_controller.did_interact +@@ -942,51 +1158,12 @@ + .region_of_interest_per_entity + .get(&tracking_entity.hash()) + { +- // If we're tracking something new, set the current position & look target to the correct view. +- if new_tracking { +- let fwd = eye_controller.fwd(); +- let radius = entity_bbox.centered_bounding_sphere_radius() * 1.5; +- let radius = if radius < 0.0001 { +- // Handle zero-sized bounding boxes: +- (bounding_boxes +- .region_of_interest_current +- .centered_bounding_sphere_radius() +- * 1.5) +- .at_least(0.02) +- } else { +- radius +- }; +- eye_controller.pos = eye_controller.look_target - fwd * radius; +- // Force write of pos and look target to not use fallbacks for that. +- eye_property.save_blueprint_component( +- ctx.viewer_ctx, +- &EyeControls3D::descriptor_position(), +- &Position3D::from(eye_controller.pos), +- ); +- +- eye_property.save_blueprint_component( +- ctx.viewer_ctx, +- &EyeControls3D::descriptor_look_target(), +- &Position3D::from(eye_controller.look_target), +- ); +- } +- +- let orbit_radius = eye_controller.pos.distance(eye_controller.look_target); +- ++ // Preserve the entire eye at admission, including off-center pan. ++ // Subsequent target translation moves the same native rig. Manual ++ // orbit/pan/zoom has already run above and remains authoritative. + let pos = entity_bbox.center(); +- +- let fwd = eye_controller.fwd(); +- +- match eye_controller.kind { +- Eye3DKind::FirstPerson => { +- eye_controller.pos = pos; +- eye_controller.look_target = pos + fwd; +- } +- Eye3DKind::Orbital => { +- eye_controller.look_target = pos; +- eye_controller.pos = pos - fwd * orbit_radius; +- } +- } ++ eye_controller.follow_translation(self.last_tracked_position, pos); ++ self.last_tracked_position = Some(pos); + } + + self.last_look_target = Some(eye_controller.look_target); +@@ -994,26 +1171,17 @@ + self.last_orbit_radius = + Some(eye_controller.pos.distance(eye_controller.look_target)); + +- // When we stop tracking, set the blueprint eye state to the tracked view. +- if eye_controller.did_interact && did_eye_orbit_center_change { +- eye_controller.save_to_blueprint( +- ctx.viewer_ctx, +- eye_property, +- old_pos, +- old_look_target, +- old_eye_up, +- ); +- +- eye_property.clear_blueprint_component( +- ctx.viewer_ctx, +- EyeControls3D::descriptor_tracking_entity(), +- ); +- } else { +- return Some(eye_controller.get_eye()); +- } ++ // Commit only changed native components. This keeps the next frame ++ // relative to the displayed eye, without HTTP, pointer replay or a ++ // second navigation loop. Panning never silently disables Follow. ++ eye_controller.save_to_blueprint( ++ ctx.viewer_ctx, eye_property, old_pos, old_look_target, old_eye_up, ++ ); ++ return Some(eye_controller.get_eye()); + } + } else { + self.last_tracked_entity = None; ++ self.last_tracked_position = None; + } + + None +@@ -1241,6 +1409,7 @@ }; self.last_eye = Some(eye); @@ -314,28 +621,66 @@ Ok(eye) } ---- a/crates/viewer/re_viewer_context/src/view/view_states.rs -+++ b/crates/viewer/re_viewer_context/src/view/view_states.rs -@@ -173,6 +173,13 @@ - } +--- a/crates/viewer/re_view_spatial/src/ui.rs ++++ b/crates/viewer/re_view_spatial/src/ui.rs +@@ -51,6 +51,8 @@ + #[derive(Clone, Default, re_byte_size::SizeBytes)] + pub struct SpatialViewState { + pub bounding_boxes: SceneBoundingBoxes, ++ /// Optional display-only world-Z slice. No data/store/accumulation mutation. ++ pub nodedc_height_slice: Option<[f32; 2]>, + pub show_bounding_box: bool, - impl ViewStates { -+ /// NODE.DC: read-only per-recording state access for native camera snapshots. -+ pub fn states_for_store<'a>(&'a self, store_id: &'a StoreId) -> impl Iterator { -+ self.states.iter().filter_map(move |((id, _), state)| { -+ (id == store_id).then_some(state.as_ref()) -+ }) -+ } -+ - pub fn get(&self, store_id: &StoreId, view_id: ViewId) -> Option<&dyn ViewState> { - self.states - .get(&(store_id.clone(), view_id)) + pub show_smoothed_bbox: bool, +--- a/crates/viewer/re_view_spatial/src/visualizers/points3d.rs ++++ b/crates/viewer/re_view_spatial/src/visualizers/points3d.rs +@@ -416,6 +416,9 @@ + let output = VisualizerExecutionOutput::default(); + + let mut point_builder = PointCloudBuilder::new(ctx.viewer_ctx.render_ctx()); ++ if let Some(state) = ctx.view_state.as_any().downcast_ref::() { ++ point_builder.nodedc_height_slice(state.nodedc_height_slice); ++ } + point_builder.radius_boost_in_ui_points_for_outlines( + re_view::SIZE_BOOST_IN_POINTS_FOR_POINT_OUTLINES, + ); --- a/crates/viewer/re_viewer/src/web.rs +++ b/crates/viewer/re_viewer/src/web.rs -@@ -384,6 +384,26 @@ - let recording = hub.entity_db(recording_id)?; - +@@ -386,6 +386,59 @@ Some(recording.store_id().recording_id().to_string()) + } + ++ /// Local presentation only; finite bounds are validated before any state changes. ++ #[wasm_bindgen] ++ pub fn nodedc_height_slice(&self, lower: Option, upper: Option) -> bool { ++ let range = match (lower, upper) { ++ (None, None) => None, ++ (Some(lo), Some(hi)) if lo.is_finite() && hi.is_finite() && lo <= hi => Some([lo, hi]), ++ _ => return false, ++ }; ++ let Some(mut app) = self.runner.app_mut::() else { return false; }; ++ let Some(store_id) = app.active_recording_id().cloned() else { return false; }; ++ let mut found = false; ++ for state in app.state.view_states.states_for_store_mut(&store_id) { ++ if let Some(state) = state.as_any_mut().downcast_mut::() { ++ state.nodedc_height_slice = range; ++ found = true; ++ } ++ } ++ if found { app.egui_ctx.request_repaint(); } ++ found ++ } ++ ++ #[wasm_bindgen] ++ pub fn nodedc_height_bounds(&self) -> Option { ++ let app = self.runner.app_mut::()?; ++ let store_id = app.active_recording_id()?; ++ let state = app.state.view_states.states_for_store(store_id) ++ .filter_map(|state| state.as_any().downcast_ref::()) ++ .max_by(|a,b| a.state_3d.eye_state.last_render_time.total_cmp(&b.state_3d.eye_state.last_render_time))?; ++ let bounds = state.bounding_boxes.region_of_interest_current; ++ if !bounds.is_finite() { return None; } ++ Some(serde_json::json!({"min":bounds.min.z,"max":bounds.max.z}).to_string()) + } + + /// NODE.DC navigation/v1. Last rendered native eye, never a replay of DOM deltas. @@ -356,6 +701,30 @@ + "lookTarget": eye_state.last_look_target?.to_array(), + "eyeUp": eye_state.last_eye_up?.to_array(), + }).to_string()) - } - ++ } ++ //TODO(#10737): we should refer to logical recordings using store id (recording id is ambiguous) + #[wasm_bindgen] + pub fn set_active_recording_id(&self, recording_id: &str) { +--- a/crates/viewer/re_viewer_context/src/view/view_states.rs ++++ b/crates/viewer/re_viewer_context/src/view/view_states.rs +@@ -173,6 +173,19 @@ + } + + impl ViewStates { ++ /// NODE.DC: read-only per-recording state access for native camera snapshots. ++ pub fn states_for_store<'a>(&'a self, store_id: &'a StoreId) -> impl Iterator { ++ self.states.iter().filter_map(move |((id, _), state)| { ++ (id == store_id).then_some(state.as_ref()) ++ }) ++ } ++ ++ pub fn states_for_store_mut<'a>(&'a mut self, store_id: &'a StoreId) -> impl Iterator { ++ self.states.iter_mut().filter_map(move |((id, _), state)| { ++ (id == store_id).then_some(state.as_mut()) ++ }) ++ } ++ + pub fn get(&self, store_id: &StoreId, view_id: ViewId) -> Option<&dyn ViewState> { + self.states + .get(&(store_id.clone(), view_id)) diff --git a/apps/control-station/vendor/rerun-web-viewer-0.36.3/README.md b/apps/control-station/vendor/rerun-web-viewer-0.36.3/README.md index dbcd504a..f2656d51 100644 --- a/apps/control-station/vendor/rerun-web-viewer-0.36.3/README.md +++ b/apps/control-station/vendor/rerun-web-viewer-0.36.3/README.md @@ -15,6 +15,8 @@ portable source patch and paired generated runtime. Keep the upstream licenses. are not shaders and must not enter the build. 4. On Worker006, create a temporary container from the pinned Rust image in the manifest, with 4 CPUs, 16 GB memory, no GPU, no ports and no private data. + This build raised its own CPU quota to 8, then 16 after checking spare host + capacity; no Docker Desktop resource settings or other containers changed. Use the `ndc-` name and NODE.DC ownership labels required by AGENTS.md. Copy the archive to `/work/patched-source.tar.gz` and the repository's `scripts/build-rerun-navigation.sh` to `/work/build-rerun-navigation.sh`. diff --git a/apps/control-station/vendor/rerun-web-viewer-0.36.3/navigation-build.json b/apps/control-station/vendor/rerun-web-viewer-0.36.3/navigation-build.json index 4b083f16..58c9a1b9 100644 --- a/apps/control-station/vendor/rerun-web-viewer-0.36.3/navigation-build.json +++ b/apps/control-station/vendor/rerun-web-viewer-0.36.3/navigation-build.json @@ -3,33 +3,50 @@ "upstreamVersion": "0.36.3", "upstreamCommit": "6ded109d33c549e98185f7c95fa8009d44e4adef", "upstreamArchiveSha256": "3f92aef3f33f63c79b275b5c66a65d73192e75967cbcd3d1f16c75010996f896", - "patchSha256": "a893a4b4e7523cca88284316c88b930c3b91ba973ed3f954c9ca632f71252e64", + "patchSha256": "91ac2a6edb93f20e8f38670a2f58e99f1218fe07f8a3fceefec136df509537d6", "cargoLockSha256": "74cdf9c3c8c5dbe5a368f1a9a58b011e2a45720843b30e552bc7b1d8ac21d791", "buildScriptSha256": "e3cbd5da889403eda3ffba7c020b6075bdfb025b823d1bf503b639f59688135a", - "buildDate": "2026-09-21", + "buildDate": "2026-11-03", "rustImage": "rust:1.95-bookworm@sha256:6258907abe69656e41cd992e0b705cdcfabcbbe3db374f92ed2d47121282d4a1", "binaryenVersion": "117", "binaryenArchiveSha256": "3dc677006555b355ea2da5e82602065a161d5e83eaefd3f759afa00b96e83212", "wasmBindgenVersion": "0.2.126", - "nativeTestsPassed": 6, + "nativeTestsPassed": 10, "files": { - "index.js": { "upstreamSha256": "009aa5f66c8674ea268a91926c00e2f82cc7a7b7e5535056d93bd4656d6f6812" }, - "index.ts": { "upstreamSha256": "087b25170f720a28aa69c411903133286238900050ac775d2cc511b919846696" }, - "index.d.ts": { "upstreamSha256": "649637dad4e50ef4f2310fc1920b580d16832226a0dda5238355059bf167efba" }, + "index.js": { + "upstreamSha256": "009aa5f66c8674ea268a91926c00e2f82cc7a7b7e5535056d93bd4656d6f6812" + }, + "index.ts": { + "upstreamSha256": "087b25170f720a28aa69c411903133286238900050ac775d2cc511b919846696" + }, + "index.d.ts": { + "upstreamSha256": "649637dad4e50ef4f2310fc1920b580d16832226a0dda5238355059bf167efba" + }, "re_viewer.js": { "upstreamSha256": "d2a94836dd0e6de40538c4d657cfb423b1803e354e6ee0cd550735eb5aaab09b", "artifact": "re_viewer.nodedc.js", - "sha256": "610d89abffcc5c329797e77794ae2ab5b426c80a5b23fd24064c7d47c6583d3a" + "sha256": "7cf2396b18d1b6ab80af03826b94ed8a658071704fbe7b58b860265aab46d19c", + "previousArtifactSha256": "7cf2396b18d1b6ab80af03826b94ed8a658071704fbe7b58b860265aab46d19c" }, "re_viewer.d.ts": { "upstreamSha256": "9a77a4e1e1aa8311185a3f275bf326a8fff2844e468e561c59d5f0ee7aa6debe", "artifact": "re_viewer.nodedc.d.ts", - "sha256": "cfbf010d66560af919aa68d255a6ddc7120829f8ee8f27a41f56d943cd54e598" + "sha256": "cafb702c9d3c37d01012afa358f337cfcc8ba3e101bfdacfb03455de972166c7", + "previousArtifactSha256": "cafb702c9d3c37d01012afa358f337cfcc8ba3e101bfdacfb03455de972166c7" }, "re_viewer_bg.wasm": { "upstreamSha256": "02d6d9c3a569d3faceb01cf89104342d970fc85e7c31a08dedd357b6c7104d2f", "artifact": "re_viewer_bg.nodedc.wasm", - "sha256": "2b661de545ac90bb950eda1a28fc5a7c3ce4ca7f5bb24894789acf7589495185" + "sha256": "309ff802d9be926fd58cbf3e36819d7da02bd4e580f44d2f636214d18ec3eac3", + "previousArtifactSha256": "18e4d6fa8889ac73ecfc366df720a88678d9de2fcabd3302bb8b259147c78906" } - } + }, + "buildCpuRange": [ + 8, + 16 + ], + "buildMemoryGiB": 16, + "qualificationScriptSha256": "ebd65eb3b2143ffe5f8b3e0f718653a836a4cdb76375f47c93fdaf616a041e50", + "regressionBeforeFix": "following_commits_motion_without_manual_input_across_frames: expected failure", + "patchedSourceArchiveSha256": "bfc8297d5cb73059981aff47c7b7638e07a782b854f57fe65a92c16fe041ee1e" } diff --git a/apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer.nodedc.d.ts b/apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer.nodedc.d.ts index e89ac10d..ab89017b 100644 --- a/apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer.nodedc.d.ts +++ b/apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer.nodedc.d.ts @@ -69,6 +69,11 @@ declare namespace wasm_bindgen { * excludes states retained for a previously selected/reset pane. */ nodedc_camera_eye(): string | undefined; + nodedc_height_bounds(): string | undefined; + /** + * Local presentation only; finite bounds are validated before any state changes. + */ + nodedc_height_slice(lower?: number | null, upper?: number | null): boolean; /** * Open a new channel for streaming data. * @@ -115,6 +120,8 @@ declare interface InitOutput { readonly webhandle_has_panicked: (a: number) => number; readonly webhandle_new: (a: any) => [number, number, number]; readonly webhandle_nodedc_camera_eye: (a: number) => [number, number]; + readonly webhandle_nodedc_height_bounds: (a: number) => [number, number]; + readonly webhandle_nodedc_height_slice: (a: number, b: number, c: number) => number; readonly webhandle_open_channel: (a: number, b: number, c: number, d: number, e: number) => void; readonly webhandle_override_panel_state: (a: number, b: number, c: number, d: number, e: number) => [number, number]; readonly webhandle_panic_callstack: (a: number) => [number, number]; diff --git a/apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer.nodedc.js b/apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer.nodedc.js index 3b63e8d2..f9c89dd7 100644 --- a/apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer.nodedc.js +++ b/apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer.nodedc.js @@ -256,6 +256,28 @@ const exports = { __proto__: null }; } return v1; } + /** + * @returns {string | undefined} + */ + nodedc_height_bounds() { + const ret = wasm.webhandle_nodedc_height_bounds(this.__wbg_ptr); + let v1; + if (ret[0] !== 0) { + v1 = getStringFromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + } + return v1; + } + /** + * Local presentation only; finite bounds are validated before any state changes. + * @param {number | null} [lower] + * @param {number | null} [upper] + * @returns {boolean} + */ + nodedc_height_slice(lower, upper) { + const ret = wasm.webhandle_nodedc_height_slice(this.__wbg_ptr, isLikeNone(lower) ? Number.MAX_SAFE_INTEGER : Math.fround(lower), isLikeNone(upper) ? Number.MAX_SAFE_INTEGER : Math.fround(upper)); + return ret !== 0; + } /** * Open a new channel for streaming data. * diff --git a/apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer_bg.nodedc.wasm b/apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer_bg.nodedc.wasm index 4430a34a..97bba7a6 100644 --- a/apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer_bg.nodedc.wasm +++ b/apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer_bg.nodedc.wasm @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:2b661de545ac90bb950eda1a28fc5a7c3ce4ca7f5bb24894789acf7589495185 -size 50469154 +oid sha256:309ff802d9be926fd58cbf3e36819d7da02bd4e580f44d2f636214d18ec3eac3 +size 50472312 diff --git a/docs/adr/0052-native-rerun-grid-navigation.md b/docs/adr/0052-native-rerun-grid-navigation.md index 1c50cdae..6fb125fc 100644 --- a/docs/adr/0052-native-rerun-grid-navigation.md +++ b/docs/adr/0052-native-rerun-grid-navigation.md @@ -23,14 +23,28 @@ gesture is introduced. orbital rotation leaves the pivot fixed. Scene changes cannot choose a new pivot after operator navigation. The guide grid is not a measured terrain model. - Initial fallback height is projected before rendering, not at the start of - the first rotation. Active interpolation stops on manual navigation. + the first rotation. Explicit or saved eyes retain their height when tracking + is disabled; only an absent blueprint target uses the fallback projection. + Active interpolation stops on manual navigation. - Zoom changes distance to the pivot. The scene-diagonal zoom-out cap is removed. Upstream's 0.02 m collision-with-pivot guard and a finite 1e17 arithmetic guard remain; these are not route-distance limits. Passing through the pivot would reverse orbital direction, so it is deliberately not implemented. -- Explicit tracking remains distinct from fixed-pivot inspection. While following, - Rerun may move the target with the tracked entity. First-person movement keeps - upstream behavior. Reset and plan/3D switches remain explicit preset actions. +- Explicit tracking remains distinct from fixed-pivot inspection. Following an + entity preserves the current eye at admission, then translates position and + look target by the entity's movement. The operator may pan, orbit, zoom or + look away without releasing tracking or being recentered. The manually chosen + offset, direction and radius remain authoritative. Disabling Follow retains + the world eye. Reset and plan/3D switches remain explicit preset actions. +- The per-frame controller is reconstructed from the active blueprint. Target + movement must open the existing `did_interact` write gate, just as manual + movement does; otherwise `save_to_blueprint` discards it and the next frame + returns to the last manual pose. Admission, zero delta and invalid translation + do not write. Regression coverage includes consecutive frames with no input. +- Recorded follow and display activation carry the actual native world eye in + one update. The former two-phase relative-eye workaround for upstream auto-fit + is obsolete: it reset `look_target` to the rig and discarded off-centre pan. + No second camera-motion loop or per-frame HTTP query is introduced. - A read-only native snapshot supplies the last rendered eye to the existing iframe facade. The approximate DOM-input camera journal is removed. Snapshots cross the disposable iframe as copied primitive JSON only; no native handle or diff --git a/packages/sensor-ui/src/liveRerunPlayback.ts b/packages/sensor-ui/src/liveRerunPlayback.ts new file mode 100644 index 00000000..61d6c867 --- /dev/null +++ b/packages/sensor-ui/src/liveRerunPlayback.ts @@ -0,0 +1,55 @@ +import type {LiveRerunViewer} from './rerunHost'; + +export type LivePlaybackState = { + recordingId:string|null; rangeNs:{min:number;max:number}|null; + currentNs:number|null; playing:boolean; live:boolean; +}; +export const emptyLivePlayback:LivePlaybackState={recordingId:null,rangeNs:null,currentNs:null,playing:false,live:true}; + +/** Controls only the native retained recording. Never closes its input channel. */ +export function liveRerunPlayback(viewer:LiveRerunViewer){ + let state:LivePlaybackState={...emptyLivePlayback}; + const timeline='stream_time'; + const clamp=(time:number,range:{min:number;max:number})=>Math.min(Math.max(time,range.min),range.max); + const read=()=>{ + const id=viewer.get_active_recording_id(); + if(!id)return state; + if(id!==state.recordingId)state={...emptyLivePlayback,recordingId:id}; + const next=viewer.get_time_range(id,timeline); + if(!next||!Number.isFinite(next.min)||!Number.isFinite(next.max)||next.max<=next.min)return state; + const previous=state.rangeNs; + const current=viewer.get_current_time?.(id,timeline)??next.max; + if(state.live){ + // Advance only when new data arrives, not on every status poll. The native + // store remains open while a historical cursor is paused or playing. + if(!previous||next.max!==previous.max){ + viewer.set_current_time(id,timeline,next.max);viewer.set_playing(id,false); + } + state={...state,rangeNs:next,currentNs:next.max,playing:true}; + }else{ + const bounded=clamp(current,next); + if(bounded!==current)viewer.set_current_time(id,timeline,bounded); + state={...state,rangeNs:next,currentNs:bounded,playing:viewer.get_playing?.(id)??false}; + } + return state; + }; + const seek=(time:number)=>{ + if(!Number.isFinite(time))return state; + const {recordingId:id,rangeNs:range}=read();if(!id||!range)return state; + const currentNs=clamp(time,range); + viewer.set_current_time(id,timeline,currentNs);viewer.set_playing(id,false); + return state={...state,currentNs,playing:false,live:false}; + }; + const setPlaying=(playing:boolean)=>{ + const {recordingId:id,rangeNs:range,currentNs}=read();if(!id||!range)return state; + if(state.live&&!playing)viewer.set_current_time(id,timeline,currentNs??range.max); + viewer.set_playing(id,playing); + return state={...state,live:false,playing}; + }; + const jumpToLive=()=>{ + const {recordingId:id,rangeNs:range}=read();if(!id||!range)return state; + viewer.set_current_time(id,timeline,range.max);viewer.set_playing(id,false); + return state={...state,currentNs:range.max,playing:true,live:true}; + }; + return {read,seek,setPlaying,jumpToLive}; +} diff --git a/packages/sensor-ui/src/pluginSdk.ts b/packages/sensor-ui/src/pluginSdk.ts index ad7ac325..613ab7c6 100644 --- a/packages/sensor-ui/src/pluginSdk.ts +++ b/packages/sensor-ui/src/pluginSdk.ts @@ -1,6 +1,7 @@ export * from './contracts'; export type * from './enrollment'; export type * from './rerunHost'; +export * from './useLiveRerunPlayback'; export type * from './extensions'; export type * from './observation'; export {ObservationHeader} from './ObservationHeader'; diff --git a/packages/sensor-ui/src/rerunHost.ts b/packages/sensor-ui/src/rerunHost.ts index 7d7c6717..3369f122 100644 --- a/packages/sensor-ui/src/rerunHost.ts +++ b/packages/sensor-ui/src/rerunHost.ts @@ -1,10 +1,16 @@ /** Native renderer capability supplied by each host, independent of device APIs. */ export interface LiveRerunViewer { + readonly ready?:boolean; start:(source:string|string[]|null,parent:HTMLElement,options:{width:string;height:string;hide_welcome_screen:boolean;enable_history:boolean;theme?:'dark'|'light';allow_fullscreen?:boolean;panel_state_overrides?:Record})=>Promise; open_channel:(name:string)=>{ready:boolean;send_rrd:(bytes:Uint8Array)=>void;close:()=>void}; override_panel_state:(panel:'top'|'blueprint'|'selection'|'time',state:'hidden'|'collapsed'|'expanded')=>void; + get_camera_eye?:()=>{position:readonly number[];lookTarget:readonly number[];eyeUp:readonly number[]}|null; + set_height_slice?:(lower:number|null,upper:number|null)=>boolean; + get_height_bounds?:()=>{min:number;max:number}|null; get_active_recording_id:()=>string|null; get_active_timeline:(id:string)=>string|null; + get_current_time?:(id:string,timeline:string)=>number; + get_playing?:(id:string)=>boolean; get_time_range:(id:string,timeline:string)=>{min:number;max:number}|null; set_active_timeline:(id:string,timeline:string)=>void; set_current_time:(id:string,timeline:string,time:number)=>void; diff --git a/packages/sensor-ui/src/useLiveRerunPlayback.ts b/packages/sensor-ui/src/useLiveRerunPlayback.ts new file mode 100644 index 00000000..442e8569 --- /dev/null +++ b/packages/sensor-ui/src/useLiveRerunPlayback.ts @@ -0,0 +1,21 @@ +import {useEffect,useRef,useState} from 'react'; +import type {LiveRerunViewer} from './rerunHost'; +import {emptyLivePlayback,liveRerunPlayback} from './liveRerunPlayback'; + +export function useLiveRerunPlayback(viewer:LiveRerunViewer|null,acquisition:string){ + const controller=useRef|null>(null); + const [state,setState]=useState(emptyLivePlayback); + useEffect(()=>{ + setState(emptyLivePlayback); + if(!viewer)return; + const current=liveRerunPlayback(viewer);controller.current=current; + const poll=()=>{try{setState(current.read());}catch{/* Native recording may be between frames. */}}; + poll();const timer=setInterval(poll,250); + return()=>{clearInterval(timer);if(controller.current===current)controller.current=null;}; + },[viewer,acquisition]); + const update=(action:(value:NonNullable)=>typeof state)=>{ + const current=controller.current;if(!current)return; + try{setState(action(current));}catch{/* Teardown does not own acquisition control. */} + }; + return {state,seek:(time:number)=>update(c=>c.seek(time)),setPlaying:(playing:boolean)=>update(c=>c.setPlaying(playing)),jumpToLive:()=>update(c=>c.jumpToLive())}; +} diff --git a/src/k1link/viewer/node_local_media.py b/src/k1link/viewer/node_local_media.py index 9a4ccc80..5a9bfa5f 100644 --- a/src/k1link/viewer/node_local_media.py +++ b/src/k1link/viewer/node_local_media.py @@ -70,24 +70,34 @@ async def start_local(peers, parameters): for identifier, entry in list(peers.items.items()): if entry.get("local") and entry["view_id"] == view_id: await peers.close(identifier) - if len(peers.items) >= 2: + camera_only = parameters.get("media") == "camera" + if sum((entry.get("media") == "camera") == camera_only for entry in peers.items.values()) >= 2: raise ValueError("Close another live viewer") + labels = ( + ("camera",) + if camera_only + else ("rrd",) + if parameters.get("media") == "cloud" + else ("rrd", "camera") + ) connection = LocalConnection() identifier = "peer_" + uuid4().hex entry = { "pc": connection, "seen": time.monotonic(), "tasks": [], - "labels": {"rrd", "camera"}, + "labels": set(labels), + "media": "camera" if camera_only else "cloud", "view_id": view_id, "after": after, "subscriber": None, + "settings": peers.scene_settings(parameters.get("settings")), "local": True, "reading": False, } peers.items[identifier] = entry connection.push(0, json.dumps({"peer_id": identifier, "media_protocol": MEDIA_PROTOCOL})) - for label in ("rrd", "camera"): + for label in labels: entry["tasks"].append( asyncio.create_task(peers.deliver(identifier, LocalChannel(connection, label))) ) diff --git a/src/k1link/viewer/node_media.py b/src/k1link/viewer/node_media.py index 9b12e66f..644ba24b 100644 --- a/src/k1link/viewer/node_media.py +++ b/src/k1link/viewer/node_media.py @@ -7,19 +7,19 @@ import logging import queue import time from contextlib import suppress -from itertools import chain from uuid import UUID, uuid4 import aioice.ice +from aiortc import RTCConfiguration, RTCPeerConnection, RTCSessionDescription from missioncore_plugin_sdk.link_budget import budget_peer from missioncore_plugin_sdk.media_budget import adapt_peer -from aiortc import RTCConfiguration, RTCPeerConnection, RTCSessionDescription from .node_rerun import PreviewResumeError MEDIA_PROTOCOL = "missioncore.node-preview/v3" MAX_PAYLOAD = 8 * 1024 * 1024 FRAGMENT_BYTES = 16384 +CLOUD_FRAGMENT_BYTES = 1024 logger = logging.getLogger(__name__) PRIVATE_NETWORKS = tuple( @@ -36,11 +36,16 @@ def private(address): return False -def admit_sdp(sdp): +def admit_sdp(sdp, *, camera=False): if not isinstance(sdp, str) or not 1 <= len(sdp) <= 32768: raise ValueError("Invalid media invitation") media = [line for line in sdp.splitlines() if line.startswith("m=")] - if not sdp.startswith("v=0") or len(media) != 1 or not media[0].startswith("m=application "): + admitted = ["m=video ", "m=application "] if camera else ["m=application "] + if ( + not sdp.startswith("v=0") + or len(media) != len(admitted) + or any(sum(line.startswith(prefix) for line in media) != 1 for prefix in admitted) + ): raise ValueError("A single data-channel media section is required") for line in sdp.splitlines(): if line.startswith("a=candidate:"): @@ -62,24 +67,84 @@ class NodeMediaPeers: value for value in original(use_ipv4=True, use_ipv6=False) if private(value) ] + @staticmethod + def scene_settings(value): + if value is None: + return None + from k1link.device_plugins.xgrids_k1.facade import ViewerSettingsRequest + + from .rerun_bridge import RerunSceneSettings + + return RerunSceneSettings(**ViewerSettingsRequest.model_validate(value).model_dump()) + + def snapshot(self): + now = time.monotonic() + source = getattr(self, "camera_source", None) + sequence, frame, observed = source.current() if source else (0, None, 0) + bridge = self.hub.bridge + return { + "peers": [{"media": entry.get("media", "cloud"), + "local": entry.get("local", False), + "state": getattr(entry["pc"], "connectionState", "local"), + "seen_age_ms": round((now - entry["seen"]) * 1000), + "view_id": entry.get("view_id"), + "channels": sorted(entry.get("labels", ())), + "subscribed": entry.get("subscriber") is not None, + "allocation_bps": getattr(entry.get("budget"), "allocation", 0), + "target_bps": getattr(entry.get("budget"), "bps", 0), + "egress": getattr(entry["pc"], "_missioncore_egress_metrics", {})} + for entry in self.items.values()], + "views": [] if bridge is None else [ + {"view_id": key, "closed": sub.closed.is_set(), + "attached": sub.delivery_lock.locked(), "sequence": sub.batch_sequence, + "pending": sub.pending is not None, "queued": sub.output.qsize(), + "detached_age_ms": None if sub.detached_at is None + else round((now-sub.detached_at)*1000)} + for key, sub in list(bridge.views.items())], + "camera": {"decoded_frames": sequence, + "decode_age_ms": round((now-observed)*1000) if observed else None, + "width": frame.width if frame else None}, + } + async def offer(self, parameters): + if parameters.get("media") == "camera": + from .node_camera import camera_offer + + return await camera_offer(self, parameters) admit_sdp(parameters.get("sdp")) view_id, after = parameters.get("view_id"), parameters.get("after", 0) if not isinstance(view_id, str) or str(UUID(view_id)) != view_id: raise ValueError("Preview view identifier required") if type(after) is not int or not 0 <= after <= 2**53 - 1: raise ValueError("Invalid preview cursor") - if len(self.items) >= 2: + # Like local preview recovery, replacement of this exact view releases + # its previous transport before admission. The RRD cursor is preserved. + for identifier, entry in list(self.items.items()): + if entry.get("view_id") == view_id: + await self.close(identifier) + if sum(entry.get("media") != "camera" for entry in self.items.values()) >= 2: raise ValueError("Close another live viewer") pc = RTCPeerConnection(RTCConfiguration(iceServers=[])) identifier = "peer_" + uuid4().hex - entry = {"pc": pc, "seen": time.monotonic(), "tasks": [], "labels": set(), - "view_id": view_id, "after": after, "subscriber": None} + entry = { + "pc": pc, + "seen": time.monotonic(), + "tasks": [], + "labels": set(), + "view_id": view_id, + "after": after, + "subscriber": None, + "settings": self.scene_settings(parameters.get("settings")), + } self.items[identifier] = entry @pc.on("datachannel") def datachannel(channel): - if channel.label not in {"rrd", "camera"} or channel.label in entry["labels"]: + # Camera now has its own video offer and budget. A retained old + # page can still request raw fMP4 here; admitting it under the + # small reliable cloud grant floods SCTP and starves cloud ACKs. + # Retire only that obsolete channel, preserving the RRD owner. + if channel.label != "rrd" or channel.label in entry["labels"]: channel.close() return entry["labels"].add(channel.label) @@ -88,9 +153,13 @@ class NodeMediaPeers: def message(value): if value == "keepalive": entry["seen"] = time.monotonic() - elif channel.label == "rrd" and isinstance(value, str) and len(value) < 80: + elif channel.label == "rrd" and isinstance(value, str) and len(value) < 2048: try: ack = json.loads(value) + if set(ack) == {"settings"}: + entry["settings"] = self.scene_settings(ack["settings"]) + if entry["subscriber"] is not None: + entry["subscriber"].settings_override = entry["settings"] sequence = ack.get("ack") if type(sequence) is int and entry["subscriber"] is not None: entry["subscriber"].acknowledge(sequence) @@ -109,13 +178,19 @@ class NodeMediaPeers: RTCSessionDescription(sdp=parameters["sdp"], type="offer") ) entry["budget"] = await adapt_peer(pc, "cloud") + # The subscriber reports observed full-frame demand through this + # same lease. Node still owns allocation and packet admission. budget_peer(pc, "cloud", producer_id=entry["budget"].id) await pc.setLocalDescription(await pc.createAnswer()) async def expiry(): - await asyncio.sleep(25) - if pc.connectionState != "connected": - await self.close(identifier) + # A connected peer without an opened RRD channel never enters + # deliver(). Its lease still expires like every other observer. + while identifier in self.items: + if time.monotonic() - entry["seen"] > 30: + await self.close(identifier) + return + await asyncio.sleep(1) entry["tasks"].append(asyncio.create_task(expiry())) return { @@ -130,20 +205,49 @@ class NodeMediaPeers: await self.close(identifier) raise - async def send(self, channel, payload, alive=None, pending=lambda: 0): + async def send(self, channel, payload, alive=None, pending=lambda: 0, *, budget=None): if not 0 < len(payload) <= MAX_PAYLOAD: raise RuntimeError("Preview fragment exceeds bound") # Each binary_stream.read() is an independent RRD. SCTP messages are # transport fragments, never independently decodable RRD files. - parts = (payload[offset:offset + FRAGMENT_BYTES] - for offset in range(0, len(payload), FRAGMENT_BYTES)) - for part in chain((b"MCF1" + len(payload).to_bytes(4, "big"),), parts): - while channel.readyState != "open" or channel.bufferedAmount > 16384 or pending() > 16384: - if (channel.readyState in {"closed", "closing"} - or (alive is not None and not alive())): + def fragments(): + yield b"MCF1" + len(payload).to_bytes(4, "big") + offset = 0 + while offset < len(payload): + # Keep only a few milliseconds of an allocation ahead of the + # shared packet gate. A fixed 1 KiB/10 ms polling cycle imposed + # its own ~0.8 Mbit/s ceiling even after Node granted more. + size = FRAGMENT_BYTES if budget is None else min( + FRAGMENT_BYTES, max(CLOUD_FRAGMENT_BYTES, int(budget.bps / 8 * 0.005)) + ) + yield payload[offset:offset + size] + offset += size + + next_send = 0.0 + for part in fragments(): + while ( + channel.readyState != "open" + or channel.bufferedAmount > len(part) + or pending() > (0 if budget is not None else FRAGMENT_BYTES) + or (budget is not None and (budget.bps <= 0 or time.monotonic() < next_send)) + ): + if channel.readyState in {"closed", "closing"} or ( + alive is not None and not alive() + ): raise RuntimeError("Preview consumer unavailable") - await asyncio.sleep(0.01) + delay = next_send - time.monotonic() + await asyncio.sleep( + min(0.01, delay) if budget is not None and budget.bps > 0 and delay > 0 + else 0.001 if budget is not None and budget.bps > 0 else 0.01 + ) channel.send(part) + if budget is not None: + # Pace complete RRD bytes before SCTP fragmentation. A 16 KiB + # burst at a small cloud grant exceeds the common datagram + # deadline and causes reliable retransmission/head-of-line + # delay. Keep that safety gate, charge framing headroom here, + # and never exceed the existing producer target or replay RRD. + next_send = time.monotonic() + (len(part) + 96) * 8 / max(1, budget.bps) await asyncio.sleep(0) async def camera_delivery(self, identifier, channel): @@ -156,11 +260,14 @@ class NodeMediaPeers: recording = state.get("recording") or {} if recording.get("source_end_expected"): break - if (state.get("generation") is not None and delivery.get("media_type") - and recording.get("active") is True - and recording.get("producer_alive") is True - and recording.get("media_ready") is True - and recording.get("active_epoch") == state["generation"]): + if ( + state.get("generation") is not None + and delivery.get("media_type") + and recording.get("active") is True + and recording.get("producer_alive") is True + and recording.get("media_ready") is True + and recording.get("active_epoch") == state["generation"] + ): try: lease = await asyncio.to_thread( self.camera.open_delivery, state["generation"], require_recording=True @@ -171,9 +278,14 @@ class NodeMediaPeers: await asyncio.sleep(0.25) continue try: - channel.send(json.dumps({ - "type": "camera-ready", "mime": delivery["media_type"], - })) + channel.send( + json.dumps( + { + "type": "camera-ready", + "mime": delivery["media_type"], + } + ) + ) except BaseException: self.camera.release_delivery(lease, client_closed=True) raise @@ -188,14 +300,24 @@ class NodeMediaPeers: if channel.label == "rrd": # Admission only takes a short in-process lock. Keep it on this # task so cancellation cannot orphan an attached subscription. - subscriber = self.hub.subscribe(entry["view_id"], entry["after"], budget=entry.get("budget")) + subscriber = self.hub.subscribe( + entry["view_id"], + entry["after"], + **{ + key: entry[key] + for key in ("budget", "settings") + if entry.get(key) is not None + }, + ) entry["subscriber"] = subscriber else: lease = await self.camera_delivery(identifier, channel) if lease is None: return + def alive(): return identifier in self.items and time.monotonic() - entry["seen"] < 30 + while alive(): if subscriber: batch = subscriber.next_batch(wait=False) @@ -205,8 +327,15 @@ class NodeMediaPeers: await asyncio.sleep(0.025) continue sequence, payload, frame = batch - channel.send(json.dumps({"type": "rrd-batch", "sequence": sequence, - "lidar": subscriber.snapshot(frame)})) + channel.send( + json.dumps( + { + "type": "rrd-batch", + "sequence": sequence, + "lidar": subscriber.snapshot(frame), + } + ) + ) else: try: segment = await asyncio.to_thread(lease.segments.get, 0.5) @@ -225,7 +354,13 @@ class NodeMediaPeers: if payload is None: break if payload: - await self.send(channel, payload, alive, getattr(entry["pc"], "_missioncore_pending_media", lambda: 0)) + await self.send( + channel, + payload, + alive, + getattr(entry["pc"], "_missioncore_pending_media", lambda: 0), + budget=entry.get("budget") if subscriber else None, + ) if subscriber: # One in-flight complete native batch. Network stalls # pause this disposable delivery; the recorder keeps running. @@ -241,8 +376,12 @@ class NodeMediaPeers: except asyncio.CancelledError: pass except Exception as error: - logger.warning("Node preview delivery failed channel=%s exception=%s", - channel.label, type(error).__name__) + logger.warning( + "Node preview delivery failed channel=%s exception=%s reason=%s", + channel.label, + type(error).__name__, + str(error)[:160], + ) finally: if subscriber: subscriber.release() @@ -257,6 +396,14 @@ class NodeMediaPeers: async def close(self, identifier): entry = self.items.pop(identifier, None) if entry: + if "track" in entry: + entry["track"].stop() + source = entry.get("source") + if source is not None and not any( + item.get("source") is source for item in self.items.values() + ): + source.close() + await asyncio.to_thread(source.thread.join, 1.0) tasks = [task for task in entry["tasks"] if task is not asyncio.current_task()] for task in tasks: task.cancel() diff --git a/src/k1link/viewer/node_rerun.py b/src/k1link/viewer/node_rerun.py index 74d05e25..d495674d 100644 --- a/src/k1link/viewer/node_rerun.py +++ b/src/k1link/viewer/node_rerun.py @@ -6,13 +6,13 @@ viewer. Only complete, acknowledged RRD batches leave that outbox. """ import logging +import math import queue import threading import time from contextlib import suppress -from uuid import uuid4 from dataclasses import replace -import math +from uuid import uuid4 from k1link.data_plane import DecodedPointCloudView from k1link.viewer.rerun_bridge import RerunBridge @@ -20,6 +20,8 @@ from k1link.viewer.rerun_bridge import RerunBridge MAX_ENCODED_CHUNK = 8 * 1024 * 1024 LIVE_FRAME_MAX_AGE_SECONDS = 2.0 RESUME_GRACE_SECONDS = 300.0 +MAX_ACTIVE_VIEWS = 2 +MAX_DETACHED_VIEWS = 2 logger = logging.getLogger(__name__) _CURRENT_FRAME = object() @@ -30,10 +32,14 @@ def preview_points(frame, limit): if stride == 1: return frame indices = range(0, frame.point_count, stride) - return replace(frame, positions_xyz=frame.positions_xyz[::stride], - intensities=frame.intensities[::stride] if frame.intensities is not None else None, - colors_rgb=b"".join(frame.colors_rgb[i*3:i*3+3] for i in indices) - if frame.colors_rgb is not None else None) + return replace( + frame, + positions_xyz=frame.positions_xyz[::stride], + intensities=frame.intensities[::stride] if frame.intensities is not None else None, + colors_rgb=b"".join(frame.colors_rgb[i * 3 : i * 3 + 3] for i in indices) + if frame.colors_rgb is not None + else None, + ) class PreviewResumeError(ValueError): @@ -41,10 +47,14 @@ class PreviewResumeError(ValueError): class RrdSubscriber: - def __init__(self, settings_provider, path_provider=None, budget=None): + def __init__(self, settings_provider, path_provider=None, budget=None, settings=None): self.closed = threading.Event() self.budget = budget - self.next_publish = 0.0 + self.source_period = None + self.source_received_ns = None + self.source_points = 0 + self.encoded_frame_bytes = 0 + self.encoded_sequence = 0 self.inputs = {} self.input_ready = threading.Condition() self.delivery_lock = threading.Lock() @@ -53,7 +63,8 @@ class RrdSubscriber: self.detached_at = None self.path_provider = path_provider self.output = queue.Queue(maxsize=2) - self.settings_provider = settings_provider + self.settings_override = settings + self.settings_provider = lambda: self.settings_override or settings_provider() self.last_frame = None self.thread = threading.Thread(target=self.run, name="node-rerun-view", daemon=True) self.thread.start() @@ -65,13 +76,33 @@ class RrdSubscriber: # Keep one latest envelope per modality: a pose burst must not # starve PCL, and no network wait reaches the acquisition producer. self.inputs[type(envelope)] = envelope + if isinstance(envelope, DecodedPointCloudView): + received = envelope.context.received_monotonic_ns + if received is not None and self.source_received_ns is not None: + period = (received - self.source_received_ns) / 1e9 + if 0 < period <= LIVE_FRAME_MAX_AGE_SECONDS: + self.source_period = period if self.source_period is None else ( + self.source_period * 0.8 + period * 0.2 + ) + self.source_received_ns = received + self.source_points = envelope.point_count + self.refresh_demand() self.input_ready.notify() + def refresh_demand(self): + if self.budget is None or self.source_period is None: + return + # Full native bytes observed at source cadence, plus the existing SDK + # wire headroom. Demand is advice, never a permit or independent cap. + size = max(self.encoded_frame_bytes, self.source_points * 16 + 2048) + self.budget.demand_bps = min(100_000_000, math.ceil(size * 8 / self.source_period / 0.65)) + def attach(self, after=0, budget=None): if self.closed.is_set() or not self.delivery_lock.acquire(blocking=False): raise RuntimeError("Preview is closed or still attached") if after != self.batch_sequence and not ( - self.pending is not None and after == self.batch_sequence - 1): + self.pending is not None and after == self.batch_sequence - 1 + ): self.delivery_lock.release() raise PreviewResumeError("Preview cursor does not match recording") self.budget = budget @@ -111,9 +142,12 @@ class RrdSubscriber: def snapshot(self, frame=_CURRENT_FRAME): frame = self.last_frame if frame is _CURRENT_FRAME else frame - return {"type": "lidar-state", "sequence": frame[0] if frame else 0, - "age_ms": max(0, (time.monotonic_ns() - frame[1]) / 1_000_000) if frame else None, - "points": frame[2] if frame else 0} + return { + "type": "lidar-state", + "sequence": frame[0] if frame else 0, + "age_ms": max(0, (time.monotonic_ns() - frame[1]) / 1_000_000) if frame else None, + "points": frame[2] if frame else 0, + } def close(self): self.closed.set() @@ -128,8 +162,11 @@ class RrdSubscriber: return "webrtc+rrd://" + str(uuid4()) try: - bridge = PreviewRerunBridge(settings_provider=self.settings_provider, - recording_output=output, path_provider=self.path_provider) + bridge = PreviewRerunBridge( + settings_provider=self.settings_provider, + recording_output=output, + path_provider=self.path_provider, + ) bridge.begin_session() while not self.closed.is_set(): payload = binary.read() @@ -138,6 +175,10 @@ class RrdSubscriber: if payload and len(payload) > MAX_ENCODED_CHUNK: break if payload: + if self.last_frame is not None and self.last_frame[0] != self.encoded_sequence: + self.encoded_sequence = self.last_frame[0] + self.encoded_frame_bytes = len(payload) + self.refresh_demand() # Backpressure is a pause, never EOF. At most two encoded # batches plus this one and the in-flight batch are retained. # Do not drop encoded bytes or restart a native recording. @@ -149,38 +190,44 @@ class RrdSubscriber: continue budget = self.budget if budget is not None: - count, interval = budget.cloud() - if not count: - self.closed.wait(.1) + # Encode the next latest view only after the receiver has + # accepted its predecessor. Preserve native RRD order while + # coalescing disposable input instead of queuing old scenes. + while not self.closed.is_set() and ( + self.pending is not None or not self.output.empty() + ): + self.closed.wait(0.025) + if self.closed.is_set(): + break + if budget.bps <= 0: + self.closed.wait(0.1) continue - # Wait before taking the coalesced latest input. Already - # encoded RRD batches keep their original reliable order. - self.closed.wait(max(0, self.next_publish-time.monotonic())) with self.input_ready: if not self.inputs: self.input_ready.wait(timeout=0.1) if not self.inputs: continue - envelope = self.inputs.pop(next(iter(self.inputs))) - received = envelope.context.received_monotonic_ns - if (received is not None + envelopes = list(self.inputs.values()) + self.inputs.clear() + # Coalesce modalities together. Alternating a pose-only batch + # with PCL paid two delivery intervals and repeated old PCL age. + # The sender's existing byte pacing + ACK supplies backpressure; + # no additional FPS hold and no spatial decimation are needed. + for envelope in sorted(envelopes, key=lambda item: item.context.sequence): + received = envelope.context.received_monotonic_ns + if ( + received is not None and (time.monotonic_ns() - received) / 1_000_000_000 - > LIVE_FRAME_MAX_AGE_SECONDS): - continue - if budget is not None: - count, interval = budget.cloud() - if not count: + > LIVE_FRAME_MAX_AGE_SECONDS + ): continue - self.next_publish = time.monotonic() + interval + bridge.process(envelope) if isinstance(envelope, DecodedPointCloudView): - envelope = preview_points(envelope, count) - bridge.process(envelope) - if isinstance(envelope, DecodedPointCloudView): - self.last_frame = ( - envelope.context.sequence, - envelope.context.received_monotonic_ns or time.monotonic_ns(), - envelope.point_count, - ) + self.last_frame = ( + envelope.context.sequence, + envelope.context.received_monotonic_ns or time.monotonic_ns(), + envelope.point_count, + ) except Exception as error: logger.warning("Node RRD subscriber failed exception=%s", type(error).__name__) finally: @@ -196,6 +243,11 @@ class PreviewRerunBridge(RerunBridge): self.path_provider = path_provider super().__init__(**kwargs) + def _apply_latest_settings(self): + # Each native pane owns its canonical blueprint and camera. Updating + # point production must not replace that pane with a default layout. + self._settings = self._settings_provider() + def _append_trajectory_pose(self, position, source_time_ns): if self.path_provider is None: return super()._append_trajectory_pose(position, source_time_ns) @@ -240,24 +292,41 @@ class NodeRerunBridge(RerunBridge): def _expire_views(self): for key, value in list(self.views.items()): - if (value.closed.is_set() or (value.detached_at is not None - and time.monotonic() - value.detached_at > RESUME_GRACE_SECONDS)): + if value.closed.is_set() or ( + value.detached_at is not None + and time.monotonic() - value.detached_at > RESUME_GRACE_SECONDS + ): value.close() del self.views[key] + # A disappeared browser keeps a bounded resume cache, not an active + # viewport slot. Retain the newest detached recordings; eviction is + # explicit on resume (PreviewResumeError), never a replacement RRD. + detached = sorted( + ((value.detached_at, key) for key, value in self.views.items() + if value.detached_at is not None), + ) + for _, key in detached[:-MAX_DETACHED_VIEWS]: + self.views.pop(key).close() + self.subscribers = [v for v in self.subscribers if not v.closed.is_set()] - def subscribe(self, view_id=None, after=0, *, budget=None): + def subscribe(self, view_id=None, after=0, *, budget=None, settings=None): with self.lock: self._expire_views() if self._closed: raise RuntimeError("Live acquisition is not active") + # Enforce the same active limit for both new and resumed consumers. + # Detached outboxes remain bounded separately and cannot prevent a + # fresh page from opening its first viewport after a reload. + if sum(v.detached_at is None for v in self.subscribers) >= MAX_ACTIVE_VIEWS: + raise RuntimeError("Close another live viewer") if view_id in self.views: + self.views[view_id].settings_override = settings return self.views[view_id].attach(after, budget) if after: raise PreviewResumeError("Preview recording expired; reopen the view") - self.subscribers = [v for v in self.subscribers if not v.closed.is_set()] - if len(self.subscribers) >= 2: - raise RuntimeError("Close another live viewer") - subscriber = RrdSubscriber(self._settings_provider, lambda: list(self._path), budget) + subscriber = RrdSubscriber( + self._settings_provider, lambda: list(self._path), budget, settings + ) for observed, envelope in self.latest.values(): if time.monotonic() - observed <= LIVE_FRAME_MAX_AGE_SECONDS: subscriber.offer(envelope) @@ -293,11 +362,11 @@ class NodeRerunHub: self.bridge = bridge return bridge - def subscribe(self, view_id=None, after=0, *, budget=None): + def subscribe(self, view_id=None, after=0, *, budget=None, settings=None): bridge = self.bridge if bridge is None: raise RuntimeError("Live acquisition is not active") - return bridge.subscribe(view_id, after, budget=budget) + return bridge.subscribe(view_id, after, budget=budget, settings=settings) def release_view(self, view_id): if self.bridge is not None: diff --git a/src/k1link/viewer/recorded.py b/src/k1link/viewer/recorded.py index 864b410c..6bf85e88 100644 --- a/src/k1link/viewer/recorded.py +++ b/src/k1link/viewer/recorded.py @@ -153,6 +153,7 @@ def recorded_blueprint( settings: RerunSceneSettings, *, display_point_bank: str | None = None, + timeline: Literal["session_time", "stream_time"] = SESSION_TIMELINE, include_initial_playback_state: bool = True, active_view: RecordedView = "spatial", view_reset_generation: Literal[0, 1] = 0, @@ -178,7 +179,7 @@ def recorded_blueprint( if accumulation > 0: time_ranges = [ rr.VisibleTimeRange( - SESSION_TIMELINE, + timeline, start=rr.TimeRangeBoundary.cursor_relative(seconds=-accumulation), end=rr.TimeRangeBoundary.cursor_relative(), ) @@ -412,12 +413,15 @@ def recorded_blueprint( else base_root_id ) + if timeline == "stream_time": + root_container = spatial_view + if include_initial_playback_state: return rrb.Blueprint( root_container, rrb.TimePanel( - timeline=SESSION_TIMELINE, - play_state="paused", + timeline=timeline, + play_state="following" if timeline == "stream_time" else "paused", state="hidden", ), auto_layout=False, @@ -436,6 +440,7 @@ def recorded_blueprint_rrd( settings: RerunSceneSettings, *, display_point_bank: str | None = None, + timeline: Literal["session_time", "stream_time"] = SESSION_TIMELINE, application_id: str = APPLICATION_ID, recording_id: str, blueprint_session_id: str | None = None, @@ -452,6 +457,7 @@ def recorded_blueprint_rrd( show_costmap: bool = False, follow_trajectory: bool = False, reactivate_updates: bool = False, + initialize_playback: bool = True, eye_position: tuple[float, float, float] | None = None, eye_look_target: tuple[float, float, float] | None = None, eye_up: tuple[float, float, float] | None = None, @@ -466,7 +472,8 @@ def recorded_blueprint_rrd( return recorded_blueprint( settings, display_point_bank=display_point_bank, - include_initial_playback_state=False, + timeline=timeline, + include_initial_playback_state=timeline == "stream_time" and initialize_playback, active_view=active_view, view_reset_generation=view_reset_generation, unified_perception=unified_perception, diff --git a/tests/test_node_media.py b/tests/test_node_media.py index 86b8893d..b00d43d1 100644 --- a/tests/test_node_media.py +++ b/tests/test_node_media.py @@ -1,5 +1,6 @@ import asyncio import queue +import time from uuid import uuid4 import pytest @@ -7,11 +8,13 @@ from aiortc import RTCConfiguration, RTCPeerConnection, RTCSessionDescription from k1link.viewer.node_media import MEDIA_PROTOCOL, NodeMediaPeers, admit_sdp + @pytest.fixture(autouse=True) def synthetic_link_budget(monkeypatch): from missioncore_plugin_sdk.media_budget import MediaBudget monkeypatch.setattr(MediaBudget, "exchange", lambda self, active=True: { - "schema": "missioncore.media-budget/v1", "allocation_bps": 4_000_000, "ttl_ms": 3000}) + "schema": "missioncore.media-budget/v1", + "allocation_bps": min(4_000_000, self.demand_bps), "ttl_ms": 3000}) from missioncore_plugin_sdk.link_budget import BudgetClient async def permit(self, size): return True @@ -22,6 +25,41 @@ def synthetic_link_budget(monkeypatch): SDP_HEADER = "v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n" +def test_cloud_delivery_paces_small_fragments_and_pauses_without_a_grant(): + """The common 500 ms deadline must not eat a 16 KiB reliable cloud burst.""" + from types import SimpleNamespace + + async def run(): + budget = SimpleNamespace(bps=0) + sent = [] + + class Channel: + readyState = "open" + bufferedAmount = 0 + + def send(self, data): + sent.append((time.monotonic(), data)) + + payload = bytes(range(256)) * 16 + peers = NodeMediaPeers(None, None) + task = asyncio.create_task(peers.send(Channel(), payload, budget=budget)) + try: + await asyncio.sleep(0.03) + assert sent == [] + budget.bps = 32000 + await asyncio.wait_for(task, 3) + assert sent[0][1] == b"MCF1" + len(payload).to_bytes(4, "big") + assert b"".join(data for _, data in sent[1:]) == payload + assert all(len(data) <= 1024 for _, data in sent) + for (before, data), (after, _) in zip(sent, sent[1:], strict=False): + assert after - before >= (len(data) + 96) * 8 / budget.bps * 0.95 + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + asyncio.run(run()) + + @pytest.mark.parametrize( "address,kind", [("8.8.8.8", "host"), ("192.168.1.2", "relay"), ("::1", "host")] ) @@ -57,6 +95,32 @@ def test_failed_media_offer_retires_peer_without_camera_channel(monkeypatch): asyncio.run(run()) +def test_replacing_exact_view_releases_old_peer_without_evicting_other_view(monkeypatch): + async def reject(*_): + raise ValueError("Invalid remote description") + + monkeypatch.setattr(RTCPeerConnection, "setRemoteDescription", reject) + + async def run(): + peers = NodeMediaPeers(None, None) + view = str(uuid4()) + old, other = RTCPeerConnection(), RTCPeerConnection() + peers.items = { + "old": {"view_id": view, "pc": old, "tasks": []}, + "other": {"view_id": str(uuid4()), "pc": other, "tasks": []}, + } + try: + with pytest.raises(ValueError, match="Invalid remote description"): + await peers.offer({"sdp": SDP_HEADER, "view_id": view, "after": 7}) + assert old.connectionState == "closed" + assert other.connectionState != "closed" + assert list(peers.items) == ["other"] + finally: + await peers.close_all() + + asyncio.run(run()) + + def test_native_webrtc_roundtrip_and_missing_camera_preserve_rrd(monkeypatch): """One bounded loopback peer, no STUN/TURN, device or external network.""" import aioice.ice @@ -133,6 +197,9 @@ def test_native_webrtc_roundtrip_and_missing_camera_preserve_rrd(monkeypatch): assert b"".join(payloads[1:]) == payload assert all(len(part) <= 16384 for part in payloads[1:]) assert answer["peer_id"] in peers.items + preview_budget = peers.items[answer['peer_id']]['budget'] + assert preview_budget.demand_bps == 2_000_000 + assert preview_budget.bps == 1_300_000 assert channel.readyState == "open" finally: await client.close() @@ -142,6 +209,32 @@ def test_native_webrtc_roundtrip_and_missing_camera_preserve_rrd(monkeypatch): asyncio.run(run()) +def test_healthy_cloud_grant_is_not_capped_by_fragment_poll_interval(): + from types import SimpleNamespace + + async def run(): + sent = [] + + class Channel: + readyState = "open" + bufferedAmount = 0 + + def send(self, data): + sent.append(data) + + payload = bytes(range(256)) * 512 + peers = NodeMediaPeers(None, None) + # One bounded in-memory frame; this is not a network capacity test. + await asyncio.wait_for( + peers.send(Channel(), payload, budget=SimpleNamespace(bps=8_000_000)), .8, + ) + assert b''.join(sent[1:]) == payload + assert max(map(len, sent)) > 1024 + assert max(map(len, sent)) <= 16384 + + asyncio.run(run()) + + def test_camera_waits_for_post_calibration_producer_and_delivers_metadata(): class Camera: calls = 0 @@ -184,8 +277,8 @@ def test_installed_camera_uses_declared_os_ffmpeg(): assert "iproute2, ffmpeg" in (root / "plugins/xgrids-k1/packaging/build_deb.py").read_text() -def test_native_rrd_idle_does_not_close_camera_or_peer(monkeypatch): - """Regression: the real binary sink, two media channels, idle then resume.""" +def test_native_rrd_idle_resume_rejects_legacy_camera_without_closing_cloud(monkeypatch): + """An old page cannot put video on the cloud budget; its RRD still works.""" import json import time from types import SimpleNamespace @@ -211,9 +304,7 @@ def test_native_rrd_idle_does_not_close_camera_or_peer(monkeypatch): "media_ready": True, "active_epoch": 1}} def open_delivery(self, generation, *, require_recording=False): - assert require_recording - assert generation == 1 - return self.lease + raise AssertionError("Cloud peer must not open a camera delivery") def release_delivery(self, lease, **_): self.released.append(lease) @@ -229,7 +320,7 @@ def test_native_rrd_idle_does_not_close_camera_or_peer(monkeypatch): client = RTCPeerConnection(RTCConfiguration(iceServers=[])) rrd = client.createDataChannel("rrd", ordered=True) video = client.createDataChannel("camera", ordered=True) - ready, resumed, camera_frame = asyncio.Event(), asyncio.Event(), asyncio.Event() + ready, resumed, camera_closed = asyncio.Event(), asyncio.Event(), asyncio.Event() batch_sequence, remaining = 0, 0 @@ -249,10 +340,9 @@ def test_native_rrd_idle_does_not_close_camera_or_peer(monkeypatch): rrd.send(json.dumps({"ack": batch_sequence})) ready.set() - @video.on("message") - def camera_message(data): - if data == b"synthetic-camera-fragment": - camera_frame.set() + @video.on("close") + def camera_close(): + camera_closed.set() try: await client.setLocalDescription(await client.createOffer()) @@ -263,19 +353,19 @@ def test_native_rrd_idle_does_not_close_camera_or_peer(monkeypatch): RTCSessionDescription(sdp=answer["sdp"], type="answer") ) await asyncio.wait_for(ready.wait(), 8) + await asyncio.wait_for(camera_closed.wait(), 5) await asyncio.sleep(1.5) assert answer["peer_id"] in peers.items - assert rrd.readyState == video.readyState == "open" + assert rrd.readyState == "open" and video.readyState == "closed" + assert peers.items[answer["peer_id"]]["labels"] == {"rrd"} assert not camera.released now = time.monotonic_ns() hub.process(DecodedPointCloudView( ConsumerFrameContext(1, time.time_ns(), now, now, 1, True), "world", ((1.0, 2.0, 3.0),), b"\x01", )) - camera.lease.segments.queue.put(("media", b"synthetic-camera-fragment")) await asyncio.wait_for(resumed.wait(), 5) - await asyncio.wait_for(camera_frame.wait(), 5) - assert rrd.readyState == video.readyState == "open" + assert rrd.readyState == "open" and video.readyState == "closed" finally: await client.close() await peers.close_all() diff --git a/tests/test_node_rerun.py b/tests/test_node_rerun.py index 2acb4aae..0d082334 100644 --- a/tests/test_node_rerun.py +++ b/tests/test_node_rerun.py @@ -138,3 +138,120 @@ def test_closing_view_releases_capacity_without_waiting_for_resume_grace(): bridge.close() for sub in views: sub.thread.join(timeout=3) + + +def test_reloading_page_reuses_active_capacity_without_resetting_live_view(): + """Unloaded pages cannot send retire_view; their peers only detach later.""" + import pytest + + from k1link.viewer.node_rerun import PreviewResumeError + + bridge = NodeRerunBridge() + views = [] + try: + live = bridge.subscribe("other-live-window") + views.append(live) + live_batch = live.next_batch() + for index in range(6): + sub = bridge.subscribe(f"page-{index}") + views.append(sub) + batch = sub.next_batch() + assert batch and batch[1].startswith(b"RRF2") + sub.release() # Transport lost; no explicit viewport retirement. + # Two detached cursors plus the active window remain. Re-entering a + # recent view keeps its exact native recording and unacknowledged RRD. + resumed = bridge.subscribe("page-5", batch[0] - 1) + assert resumed is sub and resumed.next_batch() == batch + assert live.next_batch() == live_batch + assert len(bridge.subscribers) <= 4 + with pytest.raises(RuntimeError, match="another live viewer"): + bridge.subscribe("third-active-window") + resumed.release() + with pytest.raises(PreviewResumeError, match="expired"): + bridge.subscribe("page-0", 1) + assert "page-0" not in bridge.views + finally: + bridge.close() + for sub in views: + sub.thread.join(timeout=3) + assert all(not sub.thread.is_alive() for sub in views) + + +def test_resuming_detached_view_cannot_exceed_active_limit(): + import pytest + bridge = NodeRerunBridge() + views = [] + try: + detached = bridge.subscribe("detached") + views.append(detached) + batch = detached.next_batch() + detached.release() + for name in ("active-a", "active-b"): + views.append(bridge.subscribe(name)) + with pytest.raises(RuntimeError, match="another live viewer"): + bridge.subscribe("detached", batch[0] - 1) + assert not detached.delivery_lock.locked() + assert detached.next_batch() == batch + views[-1].release() + assert bridge.subscribe("detached", batch[0] - 1) is detached + detached.release() + finally: + bridge.close() + for sub in views: + sub.thread.join(timeout=3) + + +def test_budgeted_preview_coalesces_until_ack_without_losing_native_recording(): + class Budget: + bps = 64000 + + bridge = NodeRerunBridge() + sub = bridge.subscribe('synthetic-budgeted-view', budget=Budget()) + try: + first = sub.next_batch() + assert first and first[1].startswith(b'RRF2') + for sequence in range(1, 21): + bridge.process(points(sequence)) + time.sleep(0.12) + assert sub.pending is first + assert sub.output.empty() + assert sub.snapshot()['sequence'] == 0 + sub.acknowledge(first[0]) + drain_until(sub, lambda: sub.snapshot()['sequence'] == 20) + assert sub.snapshot()['points'] == 1 + assert not sub.closed.is_set() + finally: + bridge.close() + sub.thread.join(timeout=3) + + +def test_slow_cloud_keeps_full_spatial_frame_and_reports_source_demand(): + from dataclasses import replace + + from missioncore_plugin_sdk.media_budget import MediaBudget + + budget = MediaBudget("cloud") + budget.update({ + "schema": "missioncore.media-budget/v1", "allocation_bps": 4000, "ttl_ms": 3000, + }) + bridge = NodeRerunBridge() + sub = bridge.subscribe('full-detail', budget=budget) + try: + initial = sub.next_batch() + first = points(1, age=0.1) + positions = tuple((i * .01, i % 10 * .2, i % 30 * .03) for i in range(4000)) + first = replace(first, positions_xyz=positions, intensities=b'\x01' * 4000) + bridge.process(first) + latest = replace(first, context=points(2).context) + bridge.process(latest) + assert sub.pending == initial and sub.output.empty() + assert budget.demand_bps > 256000 + sub.acknowledge(initial[0]) + drain_until(sub, lambda: sub.snapshot()['sequence'] == 2) + assert sub.snapshot()['points'] == latest.point_count == 4000 + assert first.positions_xyz == positions + assert not sub.closed.is_set() + finally: + bridge.close() + sub.thread.join(timeout=3) + budget.connection.close()