Datasets:
Download code/evaluation-code/v0.2-0c2690ae/apps/console/web/src/Media.tsx from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/apps/console/web/src/Media.tsx
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/evaluation-code/v0.2-0c2690ae/apps/console/web/src/Media.tsx
-
curl -L -o Media.tsx https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/apps/console/web/src/Media.tsx
10.9 kB
| import {useEffect, useRef, useState} from 'react'; | |
| import type {MediaFrameResponse, MediaFrameSelection, MediaRoute, RenderMedia} from './contract.ts'; | |
| import type {ReviewClock} from './clock.ts'; | |
| import {getJSON} from './api.ts'; | |
| import {explanation, errorText} from './text.ts'; | |
| import {NativePlayback} from './native-playback.ts'; | |
| import {recordPresentation, lastPresentation} from './media-clock.ts'; | |
| function object(value: unknown): Record<string, unknown> { | |
| return value !== null && typeof value === 'object' ? value as Record<string, unknown> : {}; | |
| } | |
| function maximum(value: unknown, unit: string): string { | |
| const q = object(object(value).quantiles)['1']; | |
| return typeof q === 'number' ? `${q.toPrecision(4)} ${unit}` : '无'; | |
| } | |
| function RouteVideo({route, selection, summary, native}: {route: MediaRoute; selection: MediaFrameSelection | null; summary: Record<string, unknown>; native: boolean}) { | |
| const video = useRef<HTMLVideoElement>(null), canvas = useRef<HTMLCanvasElement>(null); | |
| type Picture = {index: number; pts: number; url: string}; | |
| const painted = useRef<Picture | null>(null); | |
| const pending = useRef<((pts: number) => void) | null>(null); | |
| const [drawn, setDrawn] = useState<Picture | null>(null), [error, setError] = useState(''); | |
| useEffect(() => { | |
| if(native)return; | |
| const v=video.current!;let active=true,callback:number; | |
| painted.current=null; | |
| const presented=(_: number, info: VideoFrameCallbackMetadata) => { | |
| if(!active)return; | |
| if(v.currentSrc===new URL(route.url,location.href).href) { | |
| recordPresentation(v,route.url,info.mediaTime);pending.current?.(info.mediaTime); | |
| } | |
| callback=v.requestVideoFrameCallback(presented); | |
| }; | |
| // NativePlayback takes callback ownership while playing. The shared cache | |
| // survives mode/window changes, including an already displayed final frame. | |
| callback=v.requestVideoFrameCallback(presented); | |
| return ()=>{active=false;v.cancelVideoFrameCallback(callback);}; | |
| },[route,native]); | |
| useEffect(() => { | |
| const v = video.current!, c = canvas.current!; | |
| let active = true, timer: ReturnType<typeof setTimeout> | null = null; | |
| if (native) {painted.current = null; return;} | |
| v.pause(); | |
| setError(''); setDrawn(null); | |
| if (!selection) return; | |
| if (selection.status !== 'recording') { | |
| c.getContext('2d')!.clearRect(0, 0, c.width, c.height); painted.current = null; | |
| return; | |
| } | |
| const paint = (pts: number) => { | |
| if (!active) return; | |
| c.getContext('2d')!.drawImage(v, 0, 0, c.width, c.height); | |
| const picture={index:selection.frame_index!,pts,url:route.url}; | |
| painted.current=picture;setError('');setDrawn(picture); | |
| }; | |
| const presented=(pts: number)=>{ | |
| if(!active || Math.abs(pts-selection.local_s!)>=.5/route.fps)return; | |
| if(timer)clearTimeout(timer);paint(pts); | |
| }; | |
| const seek = () => { | |
| if (!active) return; | |
| // Verify an already observed frame against the public local-time rows; | |
| // currentTime alone is never evidence of the decoded frame identity. | |
| const index=route.frames.findIndex(f=>f.frame_index===selection.frame_index); | |
| const upper=route.frames[index+1]?.local_s ?? v.duration; | |
| const stillCurrent=index>=0 && !v.seeking && v.readyState>=2 && v.paused | |
| && v.currentTime>=route.frames[index].local_s-1e-9 | |
| && (v.currentTime<upper || (v.ended && index===route.frames.length-1)); | |
| const picture=painted.current; | |
| if(stillCurrent && picture!==null && picture.index===selection.frame_index && picture.url===route.url) { | |
| setDrawn({...picture});return; | |
| } | |
| const actual=lastPresentation(v,route.url); | |
| if(stillCurrent && actual!==null && Math.abs(actual.pts-selection.local_s!)<1e-5) { | |
| paint(actual.pts);return; | |
| } | |
| // Both times and the frame identity come from frame_at_world on Python. | |
| // requestVideoFrameCallback confirms the decoded picture, not just seeked. | |
| pending.current=presented; | |
| timer = setTimeout(() => {if (active) setError('等待目标帧超时');}, 10000); | |
| v.currentTime = selection.seek_local_s!; | |
| }; | |
| if (v.readyState >= 1) seek(); else v.addEventListener('loadedmetadata', seek, {once: true}); | |
| return () => { | |
| active = false; v.removeEventListener('loadedmetadata', seek); | |
| if(pending.current===presented)pending.current=null; | |
| if (timer) clearTimeout(timer); | |
| }; | |
| }, [route, selection, native]); | |
| const recording = selection?.status === 'recording'; | |
| const ready = recording && drawn!==null && drawn.index === selection.frame_index && drawn.url===route.url && !error; | |
| const camera = object(object(summary.camera)[route.observer_id]); | |
| const body = object(object(summary.body)[route.observer_id]); | |
| return <section className={'media-route' + (selection?.status === 'not_recording' ? ' idle' : '')} data-media-observer={route.observer_id} | |
| data-media-status={error ? 'error' : selection?.status === 'not_recording' ? 'not_recording' : ready ? 'recording' : 'loading'} | |
| data-frame-index={ready ? drawn!.index : ''} data-world-s={selection?.world_s ?? ''} | |
| data-presented-local-s={ready ? drawn!.pts : ''}> | |
| <h3>{route.observer_id} <small>{route.width}×{route.height} · {route.fps} fps</small></h3> | |
| <div className="media-picture"> | |
| <video ref={video} src={route.url} muted playsInline preload="auto" aria-hidden="true" className="media-decoder" style={{visibility: recording ? 'visible' : 'hidden'}} | |
| onError={() => setError('录像解码失败:' + (video.current?.error?.code ?? '未知错误'))} /> | |
| <canvas ref={canvas} width={route.width} height={route.height} hidden={native || !ready} aria-label={route.observer_id + ' 当前录像画面'} /> | |
| {!ready && <p role="status">{error || (selection?.status === 'not_recording' ? '未在录' : '正在载入目标帧…')}</p>} | |
| </div> | |
| <details className="route-debug"><summary>录像窗口 [{route.window_world_span[0]}, {route.window_world_span[1]}) 秒 · 读回偏差</summary> | |
| <p>镜头读回最大偏差:位置 {maximum(camera.position_error_m, 'm')} · 朝向 {maximum(camera.forward_angle_error_rad, 'rad')}</p> | |
| <p>机身读回最大偏差:位置 {maximum(body.position_error_m, 'm')} · 朝向 {maximum(body.yaw_error_rad, 'rad')}</p> | |
| <details><summary>provisional_mount:{route.provisional_mount.provisional === true ? '暂定' : route.provisional_mount.provisional === false ? '已登记' : '无'}</summary><pre>{JSON.stringify(route.provisional_mount, null, 2)}</pre></details></details> | |
| </section>; | |
| } | |
| const QUALITY: Record<string, string> = {NOT_CHECKED: '未检查', PASS: '通过', FAIL: '不通过'}; | |
| export function MediaPanel({media, segmentId, clock}: {media: RenderMedia; segmentId: string; clock: ReviewClock}) { | |
| const panel = useRef<HTMLDivElement>(null); | |
| const hold = useRef({}); | |
| const native = useRef<NativePlayback | null>(null); | |
| const [nativeMode, setNativeMode] = useState(false); | |
| const [packet, setPacket] = useState<MediaFrameResponse | null>(null), [error, setError] = useState(''); | |
| useEffect(() => { | |
| const node = panel.current!; | |
| const update = () => { | |
| if(native.current) {clock.release(hold.current); return;} | |
| const ready = !!packet && packet.routes.every(expected => { | |
| const element = Array.from(node.querySelectorAll<HTMLElement>('[data-media-observer]')) | |
| .find(e => e.dataset.mediaObserver === expected.observer_id); | |
| return element?.dataset.mediaStatus === expected.status && (expected.status !== 'recording' | |
| || Number(element.dataset.frameIndex) === expected.frame_index); | |
| }); | |
| node.dataset.mediaReady = String(ready); | |
| if (ready) clock.release(hold.current); else clock.hold(hold.current); | |
| if(ready && clock.snapshot().playing && !native.current) { | |
| native.current = new NativePlayback(node,media.routes,clock,message=>{setError(message);clock.setPlaying(false);}); | |
| setNativeMode(true); | |
| } | |
| }; | |
| const observer = new MutationObserver(update); | |
| observer.observe(node, {subtree: true, attributes: true, attributeFilter: ['data-media-status', 'data-frame-index']}); | |
| update(); return () => observer.disconnect(); | |
| }, [packet, clock, media]); | |
| useEffect(() => { | |
| let timer: ReturnType<typeof setTimeout> | null = null, controller: AbortController | null = null; | |
| let revision = 0, lastRequest = -Infinity, active = true; | |
| const request = (world: number) => { | |
| timer = null; lastRequest = performance.now(); controller?.abort(); | |
| const own = ++revision; controller = new AbortController(); setPacket(null); | |
| getJSON<MediaFrameResponse>('/api/v1/segments/' + encodeURIComponent(segmentId) + '/media-frame?world_s=' + world, controller.signal) | |
| .then(value => { | |
| if (!active || own !== revision) return; | |
| if (value.schema !== 'render-media-frames/1' || value.obs_id !== media.obs_id || value.world_s !== world) throw Error('录像时钟响应身份不符'); | |
| setError(''); setPacket(value); | |
| }).catch(e => {if (active && own === revision && e.name !== 'AbortError') setError(errorText(e));}); | |
| }; | |
| const unsubscribe = clock.subscribe(({time, playing, speed}) => { | |
| if(native.current) { | |
| if(playing && time === native.current.world) { | |
| if(speed !== native.current.speed)native.current.setSpeed(speed); | |
| return; | |
| } | |
| native.current.stop();native.current=null;setNativeMode(false); | |
| } | |
| // Manual seeks, pauses and steps still use the authoritative PTS packet. | |
| clock.hold(hold.current); panel.current!.dataset.mediaReady = 'false'; setPacket(null); | |
| if (timer) {clearTimeout(timer); timer = null;} | |
| const delay = playing ? Math.max(0, 50 - (performance.now() - lastRequest)) : 0; | |
| if (delay) timer = setTimeout(() => request(clock.snapshot().time), delay); else request(time); | |
| }); | |
| return () => {active = false; unsubscribe(); native.current?.stop();native.current=null;clock.release(hold.current); if (timer) clearTimeout(timer); controller?.abort();}; | |
| }, [clock, media, segmentId]); | |
| return <div ref={panel} className="media-panel" style={{gridTemplateColumns: `repeat(${Math.max(1, Math.min(media.routes.length, 3))}, minmax(0, 1fr))`}} data-media-id={media.obs_id} data-media-world-s={packet?.world_s ?? ''} data-media-ready="false"> | |
| <h2>渲染录像</h2>{error && <p role="alert">{error}</p>} | |
| {media.routes.map(route => <RouteVideo key={route.observer_id} route={route} | |
| selection={packet?.routes.find(r => r.observer_id === route.observer_id) || null} summary={media.readback_summary} native={nativeMode} />)} | |
| <details className="route-debug"><summary>画面可用:{QUALITY[String(media.quality.status)] || String(media.quality.status)}</summary>{explanation(media.quality.reason)}</details> | |
| </div>; | |
| } | |