feat(video): recover camera previews and reduce encoding and playout cost

Improve camera recovery, shared preview lifecycle and receiver playout diagnostics. Preserve qualified X4 runtime changes and restore async admission in loopback media tests.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent e06ff9a214
commit fa8bde584f
94 changed files with 8892 additions and 375 deletions
@@ -19,10 +19,17 @@ import {ObservationMap} from './ObservationMap';
import {useObservationInventory} from './useObservationInventory';
import './observation.css';
import {RoverView} from '../../../components/rover/RoverView';
import {RoverTelemetry} from '../../../components/rover/RoverTelemetry';
import {RoverTelemetry,roverTelemetryMinimum} from '../../../components/rover/RoverTelemetry';
import {RoverDevWindow} from '../../../components/rover/RoverDevWindow';
import {RoverLogs} from '../../../components/rover/RoverLogs';
import {useRoverDiagnostics} from '../../../core/fleet/useRoverDiagnostics';
import {useRoverControl} from '../../../core/fleet/useRoverControl';
import {roverObservationStatus} from '../../../core/fleet/roverObservation';
export function BoardObservationCenter({vehicleID,name,enabled,back,configure,headerToolsHost}:{vehicleID:string;name:string;enabled:boolean;back:()=>void;configure:()=>void;headerToolsHost?:HTMLElement|null}){
export function BoardObservationCenter({vehicleID,name,enabled,paired,back,configure,headerToolsHost}:{vehicleID:string;name:string;enabled:boolean;paired:boolean;back:()=>void;configure:()=>void;headerToolsHost?:HTMLElement|null}){
const diagnostics=useRoverDiagnostics(vehicleID);
const [devOpen,setDevOpen]=useState(false);
const [primaryCamera,setPrimaryCamera]=useState<string|null>(null),primaryRef=useRef<string|null>(null);
const {registry}=useDevicePluginHost(),transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]);
const inventory=useObservationInventory(transport),presets=useVehicleObservation(vehicleID);
const {layout,setLayout}=presets;
@@ -37,35 +44,43 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
const groups=(inventory?.items??[]).flatMap(device=>{
const contribution=sensorContribution(registry.sensorContributions,device)?.observation;
const views=contribution?.views(device)??cameraObservationViews(device);
return views.length?[{device,views,Session:contribution?.Session??CameraObservation}]:[];
return views.length?[{device,views,independentMediaLiveness:contribution?contribution.independentMediaLiveness===true:true,Session:contribution?.Session??CameraObservation}]:[];
});
const sources:{key:string;deviceID?:string;catalog?:string;view:SensorObservationView}[]=groups.flatMap(group=>group.views.map(view=>({key:observationKey(group.device.id,view.id),deviceID:group.device.id,view})));
sources.push(...unboundObservationViews(inventory?.items??[],registry.sensorContributions));
sources.push({key:'map',view:{id:'map',label:'Карта'}},{key:'rover',view:{id:'rover',label:'3D View аппарата'}},{key:'telemetry',view:{id:'telemetry',label:'Телеметрия'}});
if(diagnostics.state.id)sources.push({key:'rover-logs',view:{id:'rover-logs',label:'Логи управления'}});
for(const source of sources){if(!mounts.current.has(source.key)){mounts.current.set(source.key,document.createElement('div'));media.current.set(source.key,document.createElement('div'));headers.current.set(source.key,{statusTarget:document.createElement('div'),actionsTarget:document.createElement('div')});mounts.current.get(source.key)!.className='observation-panel-mount';media.current.get(source.key)!.className='observation-media-mount';}}
const ids=orderedObservationIDs(layout,sources.map(source=>source.key)),visible=ids.filter(id=>!layout.hidden.includes(id)&&(!sources.find(source=>source.key===id)?.catalog||layout.catalogVisible?.includes(id)));
const effectiveFull=full&&visible.includes(full)?full:null;
const rover=useRoverControl(vehicleID,enabled&&(visible.includes('rover')||visible.includes('telemetry')));
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen&&!settingsDevice;
const cameras=groups.filter(group=>group.device.preview_priority_v1&&group.views.some(view=>visible.includes(observationKey(group.device.id,view.id))));
primaryRef.current=cameras.some(group=>group.device.id===primaryCamera)?primaryCamera:cameras[0]?.device.id??null;
transport.previewRole=id=>primaryRef.current===id;
// Registry metadata has its own liveness. Only pairing and panel visibility
// own this subscription; the rover transport enforces its own freshness.
const rover=useRoverControl(vehicleID,paired&&(visible.includes('rover')||visible.includes('telemetry')));
const roverObservation=roverObservationStatus(rover.state,rover.connection);
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen&&!settingsDevice&&!devOpen;
useEffect(()=>{if(!drivingVisible)rover.stop();},[drivingVisible,rover.stop]);
const configuredDevice=inventory?.items.find(device=>device.id===settingsDevice);
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;if(event.key!=='Escape'||layersOpen||document.querySelector('[role=dialog], [role=listbox]'))return;if(effectiveFull){setFull(null);event.stopImmediatePropagation();}else if(expanded){setExpanded(false);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull,expanded,layersOpen]);
const setVisible=(id:string,show:boolean)=>setLayout(value=>({...value,catalogVisible:show?[...new Set([...(value.catalogVisible??[]),...(sources.find(source=>source.key===id)?.catalog?[id]:[])])]:(value.catalogVisible??[]).filter(key=>key!==id),hidden:show?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
const layerFor=(key:string,view:SensorObservationView)=>view.layers?.find(layer=>layer.value===layout.layers[key])?.value??view.layers?.[0]?.value??view.id;
const navigationActions=<><IconButton label="Конфигуратор" onClick={configure}><Icon name="sliders"/></IconButton><IconButton label="К аппаратам" onClick={back}><Icon name="chevron-left"/></IconButton></>;
const navigationActions=<><IconButton label={diagnostics.state.active?'Завершить DEV-запись':'Включить DEV-запись'} aria-pressed={diagnostics.state.active} loading={diagnostics.pending||diagnostics.state.closing} onClick={()=>{if(diagnostics.state.active)void diagnostics.toggle();else setDevOpen(true);}}><span className="rover-dev-label">DEV</span></IconButton><IconButton label="Оборудование аппарата" onClick={configure}><Icon name="apps"/></IconButton><IconButton label="К аппаратам" onClick={back}><Icon name="chevron-left"/></IconButton></>;
return <>{headerToolsHost&&!expanded&&createPortal(navigationActions,headerToolsHost)}<div ref={frame}/>{createPortal(<section className={`observation-center${expanded?' observation-center--expanded':''}`} aria-label={`Центр наблюдения и управления · ${name}`}>
<header className="observation-toolbar"><div><h2>Центр наблюдения и управления</h2><span>{name}</span></div><div className="observation-actions">{(!headerToolsHost||expanded)&&navigationActions}<Button onClick={()=>{setLayersOpen(true);}}><Icon name="grid"/>Доступные слои</Button><IconButton label={expanded?'Восстановить размер центра':'Развернуть центр наблюдения и управления'} onClick={()=>setExpanded(value=>!value)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div></header>
<div className="observation-summary"><StatusBadge tone={enabled&&inventory&&inventory.fresh!==false?'success':'neutral'}>{!inventory?'Получение источников':!enabled||inventory.fresh===false?'Нет свежих данных с БК':`Устройства: ${groups.length} · Окна: ${visible.length}`}</StatusBadge>{presets.pending&&<StatusBadge tone="neutral">{presets.error?"Изменения не сохранены":"Сохранение на борт…"}</StatusBadge>}{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}</div>
<div className="observation-deck">{!inventory||!presets.ready?<LoadingRegion loading={!presets.error} label="Получение визуальных источников"/>:visible.length?<ObservationDeck ids={visible} focusedId={effectiveFull} mounts={mounts.current} layout={layout} labels={Object.fromEntries(sources.map(source=>[source.key,source.view.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)))}>
<header className="observation-toolbar"><div><h2>Центр наблюдения и управления</h2><span>{name}</span></div><div className="observation-actions nodedc-viewport-controls">{(!headerToolsHost||expanded)&&navigationActions}<Button onClick={()=>{setLayersOpen(true);}}><Icon name="grid"/>Доступные слои</Button><IconButton label={expanded?'Восстановить размер центра':'Развернуть центр наблюдения и управления'} onClick={()=>setExpanded(value=>!value)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div></header>
<div className="observation-summary"><StatusBadge tone={enabled&&inventory&&inventory.fresh!==false?'success':'neutral'}>{!inventory?'Получение источников':!enabled||inventory.fresh===false?'Нет свежих сведений об оборудовании':`Устройства: ${groups.length} · Окна: ${visible.length}`}</StatusBadge>{presets.pending&&<StatusBadge tone="neutral">{presets.error?"Изменения не сохранены":"Сохранение на борт…"}</StatusBadge>}{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}</div>
<div className="observation-deck">{!inventory||!presets.ready?<LoadingRegion loading={!presets.error} label="Получение визуальных источников"/>:visible.length?<ObservationDeck minimumSizes={{telemetry:roverTelemetryMinimum(rover.state)}} ids={visible} focusedId={effectiveFull} mounts={mounts.current} layout={layout} labels={Object.fromEntries(sources.map(source=>[source.key,source.view.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)))}>
{sources.filter(source=>visible.includes(source.key)).map(source=>createPortal(
<div className="observation-panel">
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface observation-panel__surface--overlay">
<ObservationPanelHeader>
<DockHandle id={source.key} label={source.view.label}/>
<div className="observation-panel__title"><h3 title={source.view.label}>{source.view.label}</h3><ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.statusTarget}/></div>
<div className="observation-actions">
<div className="observation-panel__title">{source.key!=='rover'&&<h3 title={source.view.label}>{source.view.label}</h3>}<ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.statusTarget}/></div>
<div className="observation-actions nodedc-viewport-controls">
{source.view.layers&&<Select className="observation-layer-select" label={`Слой · ${source.view.label}`} value={layerFor(source.key,source.view)} options={source.view.layers} onChange={value=>setLayout(current=>({...current,layers:{...current.layers,[source.key]:value}}))} variant="inline"/>}
<ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.actionsTarget}/>
{source.deviceID&&cameras.some(group=>group.device.id===source.deviceID)&&<IconButton label={`${primaryRef.current===source.deviceID?'Основной видеопоток':'Сделать основным видеопотоком'} · ${source.view.label}`} aria-pressed={primaryRef.current===source.deviceID} onClick={()=>setPrimaryCamera(source.deviceID!)}><Icon name="eye"/></IconButton>}
{source.deviceID&&<IconButton label={`Настройки · ${source.view.label}`} onClick={()=>setSettingsDevice(source.deviceID!)}><Icon name="settings"/></IconButton>}
<IconButton label={`${effectiveFull===source.key?'Восстановить':'Развернуть'} · ${source.view.label}`} onClick={()=>setFull(value=>value===source.key?null:source.key)}><Icon name={effectiveFull===source.key?'minimize':'expand'}/></IconButton>
<IconButton label={`Скрыть · ${source.view.label}`} onClick={()=>setVisible(source.key,false)}><Icon name="close"/></IconButton>
@@ -75,14 +90,16 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
</GlassSurface>
</div>,mounts.current.get(source.key)!,source.key))}
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>setLayersOpen(true)}>Доступные слои</Button></div>}</div>
{groups.map(({device,views,Session})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} presentation={presets.cameras[device.id]} onPresentationChange={presets.ready?value=>presets.setCamera(device.id,value):undefined} enabled={enabled&&inventory?.fresh!==false&&device.online} createRerunHost={createIsolatedRerunHost} views={views.map(view=>({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)}
{sources.filter(source=>source.catalog&&visible.includes(source.key)).map(source=>createPortal(<div className="observation-source"><div className="observation-source__notice"><p>{source.catalog} не подключён к аппарату.</p><Button onClick={configure}>Подключить в конфигураторе</Button></div></div>,media.current.get(source.key)!,source.key))}
{groups.map(({device,views,Session,independentMediaLiveness})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} presentation={presets.cameras[device.id]} onPresentationChange={presets.ready?value=>presets.setCamera(device.id,value):undefined} enabled={(independentMediaLiveness?paired:enabled&&inventory?.fresh!==false)&&device.online} fresh={enabled&&inventory?.fresh!==false} createRerunHost={createIsolatedRerunHost} views={views.map(view=>({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)}
{sources.filter(source=>source.catalog&&visible.includes(source.key)).map(source=>createPortal(<div className="observation-source"><div className="observation-source__notice"><p>{source.catalog} не подключён к аппарату.</p><Button onClick={configure}>Подключить оборудование</Button></div></div>,media.current.get(source.key)!,source.key))}
{configuredDevice&&<ObservationDeviceSettings key={configuredDevice.id} device={configuredDevice} transport={transport} contributions={registry.sensorContributions} enabled={enabled&&inventory?.fresh!==false&&configuredDevice.online} close={()=>setSettingsDevice(null)} configure={configure}/>}
{visible.includes('map')&&createPortal(<ObservationMap vehicleID={vehicleID} header={headers.current.get('map')!}/>,media.current.get('map')!,'map-session')}
{visible.includes('rover')&&createPortal(<RoverView vehicleID={vehicleID} controller={rover} header={headers.current.get('rover')!} active={drivingVisible}/>,media.current.get('rover')!,'rover-session')}
{visible.includes('telemetry')&&createPortal(<RoverTelemetry state={rover.state}/>,media.current.get('telemetry')!,'telemetry-session')}
{visible.includes('rover')&&createPortal(<RoverView vehicleID={vehicleID} controller={rover} header={headers.current.get('rover')!} active={drivingVisible} observation={roverObservation}/>,media.current.get('rover')!,'rover-session')}
{visible.includes('rover-logs')&&createPortal(<RoverLogs capture={diagnostics} header={headers.current.get('rover-logs')!}/>,media.current.get('rover-logs')!,'rover-logs-session')}
{visible.includes('telemetry')&&createPortal(<RoverTelemetry state={rover.state} observation={roverObservation}/>,media.current.get('telemetry')!,'telemetry-session')}
<Window open={layersOpen} onClose={()=>setLayersOpen(false)} title="Доступные слои" size="md"><div className="observation-settings">
{presets.error&&<><Button onClick={()=>void presets.retry()}>Повторить сохранение</Button><Button onClick={()=>void presets.reload()}>Загрузить настройки с борта</Button></>}
{presets.recovery&&<Button onClick={()=>void presets.restore()}>Вернуть несохранённую раскладку</Button>}
{presets.error&&<><Button onClick={()=>void presets.retry()}>Повторить сохранение</Button><Button onClick={()=>void presets.reload()}>Загрузить настройки с борта</Button><Button onClick={()=>void presets.restore()}>Применить свой черновик</Button></>}
<Select label="Расположение окон" disabled={!presets.ready} value={presets.selected} options={[...observationArrangements,...presets.presets.map(p=>({value:p.id,label:p.name,action:{label:`Редактировать раскладку «${p.name}»`,icon:<Icon name="edit"/>,onAction:()=>{setLayersOpen(false);setEditing(p.id);}}}))]} onChange={value=>{presets.select(value);setFull(null);}}/>
{ids.map(id=>{const source=sources.find(item=>item.key===id)!;return <div className="observation-layer" key={id}><Switch label={source.catalog?`${source.view.label} · Источник не подключён`:source.view.label} checked={visible.includes(id)} onChange={value=>setVisible(id,value)}/><Select label={`Позиция · ${source.view.label}`} value={String(ids.indexOf(id))} options={ids.map((_,i)=>({value:String(i),label:`Окно ${i+1}`}))} onChange={value=>setLayout(current=>moveObservation(current,ids,id,ids[Number(value)]))}/></div>;})}
<Button disabled={!presets.ready} onClick={()=>{const tree=observationTree(layout,visible);if(tree)setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)));setLayersOpen(false);setSaving(true);}}>Сохранить расположение</Button>
@@ -90,6 +107,8 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
</div></Window>
{saving&&<ObservationLayoutSaveWindow onClose={()=>setSaving(false)} onSave={presets.save}/>}
{edited&&<ObservationLayoutSaveWindow key={edited.id} initialName={edited.name} onClose={()=>setEditing(null)} onSave={name=>presets.rename(edited.id,name)} onRemove={()=>presets.remove(edited.id)}/>}
{devOpen&&<RoverDevWindow capture={diagnostics} close={()=>setDevOpen(false)} started={()=>setVisible('rover-logs',true)}/>}
<ToastStack items={diagnostics.error?[{id:"rover-dev",tone:"error",title:"DEV-запись",description:diagnostics.error}]:[]} onDismiss={diagnostics.clearError}/>
<ToastStack items={presets.toastError?[{id:'observation-save',tone:'error',title:'Настройки центра наблюдения',description:presets.toastError}]:[]} onDismiss={presets.clearError}/>
</section>,portal)}</>;
}
@@ -1,5 +1,5 @@
import {useState} from 'react';
import {Button,Window} from '@nodedc/ui-react';
import {Button,ToastStack,Window} from '@nodedc/ui-react';
import {SensorDetail} from '../../../../../../packages/sensor-ui/src/SensorDetail';
import {sensorContribution,type SensorUiContribution} from '../../../../../../packages/sensor-ui/src/extensions';
import type {Sensor,SensorTransport} from '../../../../../../packages/sensor-ui/src/contracts';
@@ -7,11 +7,14 @@ import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHo
export function ObservationDeviceSettings({device,transport,contributions,enabled,close,configure}:{device:Sensor;transport:SensorTransport;contributions:readonly SensorUiContribution[];enabled:boolean;close:()=>void;configure:()=>void}) {
const [error,setError]=useState('');
const Detail=sensorContribution(contributions,device)?.Detail??SensorDetail;
const contribution=sensorContribution(contributions,device);
const Detail=contribution?.Detail??SensorDetail;
const content=<Detail key={device.snapshot.context.session_id} device={device} transport={transport} enabled={enabled} back={close} refresh={async()=>{await transport.inventory();}} failure={reason=>setError(reason instanceof Error?reason.message:reason?String(reason):'')} createRerunHost={createIsolatedRerunHost}/>;
if(contribution?.detailPresentation==='modal')return <>{content}<ToastStack items={error?[{id:'device-settings-error',tone:'error',title:error,durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
return <Window open title={`Настройки · ${device.name}`} size="lg" placement="end" draggable closeOnBackdrop={false} lockBodyScroll={false} trapFocus={false} onClose={close}>
{!enabled&&<p>Нет связи с устройством. Настройки оборудования будут доступны после подключения.</p>}
{!device.prepared&&<Button onClick={configure}>Подготовить устройство в конфигураторе</Button>}
{!device.prepared&&<Button onClick={configure}>Открыть оборудование аппарата</Button>}
{error&&<p role="alert">{error}</p>}
<Detail device={device} transport={transport} enabled={enabled} back={close} refresh={async()=>{await transport.inventory();}} failure={reason=>setError(reason instanceof Error?reason.message:reason?String(reason):'')} createRerunHost={createIsolatedRerunHost}/>
{content}
</Window>;
}
@@ -0,0 +1,38 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {createServer} from './support/vite-server.mjs';
let server,Detail;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
({X4Detail:Detail}=await server.ssrLoadModule('../../plugins/insta360-x4/frontend/src/X4Detail.tsx'));
});
after(async()=>{await server?.close();});
const camera={id:'camera-synthetic',kind:'insta360.x4',name:'Insta360 X4',model:'Insta360 X4',online:true,configured:true,prepared:true,
snapshot:{context:{session_id:'session-a',execution:{node_id:'synthetic-node'}},acquisition:'idle',enrollment:'enrolled'},camera_status:{connected:true,recording:0,preview:0,function_mode:7}};
const render=(device,enabled=true)=>renderToStaticMarkup(createElement(Detail,{device,enabled,transport:{},back:()=>{},refresh:async()=>{},failure:()=>{}}));
test('offline detail is a compact leading indicator, without disabled controls or empty data sections',()=>{
const html=render({...camera,online:false,camera_status:{recovery:{supported:true,enabled:false}}});
assert.match(html,/nodedc-resource-row--leading-status/);
assert.match(html,/aria-label="Недоступна"/);
assert.match(html,/<span>Недоступна<\/span>/);
assert.match(html,/<div hidden=""><div class="sensor-viewer"/,'decoder stays mounted but outside visible layout');
assert.doesNotMatch(html,/Серийный номер|Не получен|Нет свежей связи|Начать просмотр|Остановить просмотр|Проверить изображение|Съёмка|Файлы на камере|Восстановление подключения/);
});
test('fresh available camera reveals usable capture; stale camera hides it again',()=>{
assert.match(render(camera),/Начать запись/);
assert.doesNotMatch(render(camera),/Сделать фото|Остановить запись|Файлы на камере/);
const stale=render(camera,false);
assert.match(stale,/Недоступна/);assert.doesNotMatch(stale,/Съёмка|Начать запись|Файлы на камере/);
});
test('offline recovery offers only evidenced wake or disabling an existing recovery policy',()=>{
const offline={...camera,online:false,camera_status:{recovery:{supported:true,enabled:false,wake_available:true}}};
const wake=render(offline);assert.match(wake,/Восстановление подключения/);
assert.match(wake,/Камеру можно подключить по Bluetooth, если разрешено пробуждение\./);
assert.doesNotMatch(wake,/<h2[^>]*>Восстановление подключения/);
assert.doesNotMatch(wake,/Включить камеру/);assert.doesNotMatch(wake,/Включить восстановление/);
const active=render({...offline,camera_status:{recovery:{supported:true,enabled:true,wake_available:false}}});
assert.match(active,/Отключить восстановление/);assert.doesNotMatch(active,/Включить камеру/);
assert.doesNotMatch(render(offline,false),/Восстановление подключения|Включить камеру/);
});
+23 -1
View File
@@ -5,7 +5,7 @@ import ts from 'typescript';
const source=readFileSync(new URL('../../../plugins/insta360-x4/frontend/src/model.ts',import.meta.url),'utf8');
const code=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const {cameraLabel,cameraStatus,resolutionLabel,cameraRowActions}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
const {cameraLabel,cameraStatus,resolutionLabel,cameraRowActions,cameraDetailAvailability}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
const camera={id:'instax4_synthetic_a',online:true,configured:true,prepared:true,snapshot:{enrollment:'enrolled'},camera_status:{connected:true,recording:0,preview:0,function_mode:7}};
test('SD recording remains visible after preview closes, independently for each camera',()=>{
@@ -41,3 +41,25 @@ test('old drivers and unknown wake identities never offer an active power comman
assert.deepEqual(cameraRowActions(camera),[]);
assert.equal(cameraRowActions({...camera,online:false,camera_status:{recovery:{supported:true}}})[0].disabled,true);
});
test('offline or stale details expose no capture or unavailable recovery controls',()=>{
const offline={...camera,online:false,camera_status:{...camera.camera_status,recovery:{supported:true,enabled:false,wake_available:false}}};
for(const [device,fresh] of [[offline,true],[camera,false]])assert.deepEqual(cameraDetailAvailability(device,fresh),{available:false,wake:false,recovery:false,capture:false});
});
test('known wake capability and enabled recovery remain usable while the camera is offline',()=>{
const offline={...camera,online:false,camera_status:{recovery:{supported:true,enabled:false,wake_available:true}}};
assert.deepEqual(cameraDetailAvailability(offline,true),{available:false,wake:true,recovery:true,capture:false});
const active={...offline,camera_status:{recovery:{supported:true,enabled:true,wake_available:false}}};
assert.deepEqual(cameraDetailAvailability(active,true),{available:false,wake:false,recovery:true,capture:false});
for(const device of [{...offline,prepared:false},{...offline,configured:false}]){
assert.equal(cameraDetailAvailability(device,true).wake,false);
assert.equal(cameraDetailAvailability(device,true).recovery,false);
}
assert.equal(cameraDetailAvailability(offline,false).recovery,false);
});
test('capture requires a known shooting mode or an active recording to stop',()=>{
for(const mode of [6,7])assert.equal(cameraDetailAvailability({...camera,camera_status:{...camera.camera_status,function_mode:mode}},true).capture,true);
for(const patch of [{function_mode:null},{function_mode:99},{recording:null},{recording:-1},{connected:false}])assert.equal(cameraDetailAvailability({...camera,camera_status:{...camera.camera_status,...patch}},true).capture,false);
assert.equal(cameraDetailAvailability({...camera,camera_status:{...camera.camera_status,recording:1,function_mode:null}},true).capture,true);
});
@@ -0,0 +1,40 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const bundle=await build({entryPoints:[new URL('../../../packages/sensor-ui/src/inventoryObserver.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
const {InventoryObserver}=await import('data:text/javascript;base64,'+Buffer.from(bundle.outputFiles[0].contents).toString('base64'));
const flush=async()=>{for(let i=0;i<8;i++)await Promise.resolve();};
const value=id=>({items:[],operations:[],id});
async function fixture(t,run){
t.mock.timers.enable({apis:['setTimeout','setInterval']});let now=0;
const streams=[],reads=[],seen=[],errors=[];let stale=0;
const transport={subscribe(receive,unavailable){const s={receive,unavailable,closed:false};streams.push(s);return()=>{s.closed=true;};},inventory(signal){return new Promise((resolve,reject)=>{reads.push({signal,resolve,reject});signal.addEventListener('abort',()=>reject(new Error('aborted')),{once:true});});}};
const observer=new InventoryObserver(transport,v=>seen.push(v),()=>stale++,e=>errors.push(e),()=>now);
const tick=async ms=>{for(let i=0;i<ms;i+=1000){now+=Math.min(1000,ms-i);t.mock.timers.tick(Math.min(1000,ms-i));await flush();}};
await flush();try{await run({observer,streams,reads,seen,errors,tick,stale:()=>stale});}finally{observer.close();await flush();t.mock.timers.reset();}
}
test('new SSE snapshot wins over an older pending HTTP response',async t=>fixture(t,async({streams,reads,seen,observer})=>{
streams[0].receive(value('new'));reads[0].resolve(value('old'));await flush();
assert.deepEqual(seen.map(v=>v.id),['new']);
const first=observer.refresh(),second=observer.refresh();assert.equal(first,second);await flush();
assert.equal(reads.length,2);reads[1].resolve(value('manual'));await first;
assert.equal(seen.at(-1).id,'manual');
}));
test('silent-open SSE expires, closes and reconnects with one fallback read',async t=>fixture(t,async({streams,reads,seen,tick,stale})=>{
reads[0].resolve(value('initial'));await flush();streams[0].receive(value('stream'));
await tick(20000);assert.ok(stale()>0);assert.equal(streams[0].closed,true);assert.equal(reads.length,2);
await tick(3000);assert.equal(streams.length,2);assert.equal(reads.length,2);
streams[0].receive(value('retired'));streams[1].receive(value('recovered'));
reads[1].resolve(value('late-poll'));await flush();assert.equal(seen.at(-1).id,'recovered');
}));
test('repeated errors and slow HTTP never accumulate streams or reads',async t=>fixture(t,async({streams,reads,observer,tick})=>{
for(let i=0;i<20;i++){streams[0].unavailable();void observer.refresh();}
await tick(10000);assert.equal(reads.length,1);assert.equal(streams.filter(s=>!s.closed).length,1);
await tick(2000);assert.equal(reads[0].signal.aborted,true);
assert.equal(reads.length,1);
}));
test('unmount aborts pending read, cancels timers and ignores retired callbacks',async t=>fixture(t,async({streams,reads,observer,tick,seen})=>{
observer.close();assert.equal(reads[0].signal.aborted,true);assert.equal(streams[0].closed,true);
streams[0].receive(value('late'));await tick(60000);
assert.equal(streams.length,1);assert.equal(reads.length,1);assert.deepEqual(seen,[]);
}));
@@ -0,0 +1,217 @@
import assert from "node:assert/strict";
import { after, before, test } from "node:test";
import { createServer } from "./support/vite-server.mjs";
let server;
let deactivate;
before(async () => {
server = await createServer({ appType: "custom", logLevel: "silent" });
({ deactivateXgridsK1Runtime: deactivate } = await server.ssrLoadModule(
"../../plugins/xgrids-k1/frontend/src/runtimeDeactivation.ts",
));
});
after(async () => { await server?.close(); });
function ready() {
return {
snapshot_runtime_id: "runtime-one",
source_mode: "idle",
desired_connection_mode: "bridge",
desired_connection_mode_revision: 4,
devices: [],
connection_reconfiguration: { revision: 7, intent_id: null, intent: null },
connection_lifecycle: { active_binding_key: null },
acquisition: { acquisition_id: "scan-one", state: "completed", control_mode: "plugin-commanded", cleanup_pending: false },
physical_command: { status: "resolved", requires_reconciliation: false, resolved_active_recovery_required: false, observed_session_state: "ready" },
application_control_session: { state: "completed", control_socket_open: true, outcome_unknown: false },
};
}
function runtime(initial = ready(), options = {}) {
let state = initial;
const calls = [];
return {
calls,
pendingAction: options.pendingAction ?? null,
getCurrentState: () => state,
closeApplicationControlSession: async () => {
calls.push("close-local-control");
if (options.closeFails) return false;
state = options.afterClose ?? { ...state, application_control_session: { ...state.application_control_session, control_socket_open: false, state: "closed" } };
return true;
},
prepareConnectionReconfiguration: async (request) => {
calls.push(request);
if (options.handoffFails && request.intent === "select-device") return false;
if (options.cancelFails && request.intent === "cancel") return false;
state = options.afterHandoff ?? {
...state,
devices: [],
connection_reconfiguration: {
revision: state.connection_reconfiguration.revision + 1,
intent_id: request.intent === "cancel" ? null : "handoff-one",
intent: request.intent === "cancel" ? null : request.intent,
},
};
return true;
},
stopLocalReceiver: async () => {
calls.push("stop-local-receiver");
state = options.afterStop ?? { ...state, source_mode: "idle" };
return !options.stopFails;
},
};
}
test("completed STOP with retained READY socket permits model change through local close only", async () => {
const controller = runtime();
assert.equal(await deactivate(controller), true);
assert.deepEqual(controller.calls, ["close-local-control"]);
});
test("connected idle K1 can be released before the first scan", async () => {
const state = ready();
state.acquisition = null;
state.application_control_session.state = "connection-ready";
const controller = runtime(state);
assert.equal(await deactivate(controller), true);
assert.deepEqual(controller.calls, ["close-local-control"]);
});
test("already released runtime needs no backend action", async () => {
const state = ready();
state.application_control_session.control_socket_open = false;
const controller = runtime(state);
assert.equal(await deactivate(controller), true);
assert.deepEqual(controller.calls, []);
});
for (const phase of ["starting", "scanning", "stopping", "awaiting-standby-confirmation"]) {
test(`model change cannot close ${phase}`, async () => {
const state = ready();
state.application_control_session.state = phase;
const controller = runtime(state);
assert.equal(await deactivate(controller), false);
assert.deepEqual(controller.calls, []);
});
}
for (const field of ["requires_reconciliation", "resolved_active_recovery_required"]) {
test(`model change preserves ${field}`, async () => {
const state = ready();
state.physical_command[field] = true;
const controller = runtime(state);
assert.equal(await deactivate(controller), false);
assert.deepEqual(controller.calls, []);
});
}
test("pending acquisition and unknown physical outcome cannot be hidden by model change", async () => {
for (const state of [
{ ...ready(), acquisition: { ...ready().acquisition, state: "acquiring" } },
{ ...ready(), application_control_session: { ...ready().application_control_session, outcome_unknown: true } },
]) {
const controller = runtime(state);
assert.equal(await deactivate(controller), false);
assert.deepEqual(controller.calls, []);
}
});
test("pending operation and unavailable state do not launch cleanup", async () => {
for (const controller of [runtime(ready(), { pendingAction: "connect" }), runtime(null)]) {
assert.equal(await deactivate(controller), false);
assert.deepEqual(controller.calls, []);
}
});
test("failed exact CLOSE retains model and does not launch another action", async () => {
const controller = runtime(ready(), { closeFails: true });
assert.equal(await deactivate(controller), false);
assert.deepEqual(controller.calls, ["close-local-control"]);
});
test("changed runtime, acquisition or reopened socket cannot inherit completed CLOSE", async () => {
const closed = { ...ready(), application_control_session: { state: "closed", control_socket_open: false } };
for (const afterClose of [
{ ...closed, snapshot_runtime_id: "runtime-two" },
{ ...closed, acquisition: { ...closed.acquisition, acquisition_id: "scan-two" } },
ready(),
{ ...closed, physical_command: { observed_session_state: "scanning" } },
]) {
const controller = runtime(ready(), { afterClose });
assert.equal(await deactivate(controller), false);
assert.deepEqual(controller.calls, ["close-local-control"]);
}
});
test("replay cleanup is capture-only and must confirm local inactivity", async () => {
const state = { ...ready(), source_mode: "replay", application_control_session: null };
const controller = runtime(state);
assert.equal(await deactivate(controller), true);
assert.deepEqual(controller.calls, ["stop-local-receiver"]);
assert.equal(await deactivate(runtime(state, { afterStop: state })), false);
});
test("corrupt or nested unsettled physical evidence also blocks model change", async () => {
for (const state of [
{ ...ready(), physical_command: { status: "corrupt" } },
{ ...ready(), application_control_session: { ...ready().application_control_session, physical_command: { requires_reconciliation: true } } },
]) {
const controller = runtime(state);
assert.equal(await deactivate(controller), false);
assert.deepEqual(controller.calls, []);
}
});
function withFreshCandidate() {
return { ...ready(), devices: [{ device_id: "synthetic-k1" }] };
}
test("Bridge model change retires stale discovery through fenced handoff, preserving saved target", async () => {
const controller = runtime({ ...withFreshCandidate(), configured_connection_mode: "bridge", k1_ip: "192.0.2.1" });
assert.equal(await deactivate(controller), true);
assert.deepEqual(controller.calls, ["close-local-control", {
intent: "select-device", expected_reconfiguration_revision: 7,
expected_reconfiguration_intent_id: null, expected_desired_mode_revision: 4,
expected_active_binding_key: null,
}, {
intent: "cancel", expected_reconfiguration_revision: 8,
expected_reconfiguration_intent_id: "handoff-one", expected_desired_mode_revision: 4,
expected_active_binding_key: null,
}]);
assert.deepEqual(controller.getCurrentState().devices, []);
assert.equal(controller.getCurrentState().k1_ip, "192.0.2.1");
assert.equal(controller.getCurrentState().connection_reconfiguration.intent, null);
});
test("server-rejected Bridge handoff does not reset scenario or retry", async () => {
const controller = runtime(withFreshCandidate(), { handoffFails: true });
assert.equal(await deactivate(controller), false);
assert.equal(controller.calls.length, 2);
assert.equal(controller.getCurrentState().devices.length, 1);
});
test("concurrent runtime or changed handoff cannot be cancelled by stale deactivation", async () => {
const closed = { ...ready(), application_control_session: { state: "closed", control_socket_open: false } };
for (const afterHandoff of [
{ ...closed, snapshot_runtime_id: "runtime-two" },
{ ...closed, connection_reconfiguration: { revision: 9, intent: "select-device", intent_id: "another-handoff" } },
{ ...closed, physical_command: { requires_reconciliation: true } },
]) {
const controller = runtime(withFreshCandidate(), { afterHandoff });
assert.equal(await deactivate(controller), false);
assert.equal(controller.calls.length, 2);
}
});
test("failed handoff cancellation retains model for operator recovery", async () => {
const controller = runtime(withFreshCandidate(), { cancelFails: true });
assert.equal(await deactivate(controller), false);
assert.equal(controller.calls.length, 3);
});
test("Quick Connect model release never invokes Bridge reconfiguration", async () => {
const controller = runtime({ ...withFreshCandidate(), desired_connection_mode: "quick-connect" });
assert.equal(await deactivate(controller), true);
assert.deepEqual(controller.calls, ["close-local-control"]);
});
@@ -0,0 +1,23 @@
import assert from 'node:assert/strict';
import {after,before,test} from 'node:test';
import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {createServer} from './support/vite-server.mjs';
let server,Surface;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});({LiveViewportSurface:Surface}=await server.ssrLoadModule('../../packages/sensor-ui/src/LiveViewport.tsx'));});
after(async()=>{await server?.close();});
const device={online:true,snapshot:{acquisition:'streaming'}};
const preview={state:'Подключение просмотра',telemetry:{},error:'',live:false,hasFrame:false,sourceStalled:false};
const render=(props={})=>renderToStaticMarkup(createElement(Surface,{device,layer:'preview',video:{current:null},preview,...props}));
test('video remains mounted through idle, startup and terminal failure',()=>{
for(const props of [{device:{...device,snapshot:{acquisition:'idle'}}},{pending:true},{error:'Нет кадров'}])assert.match(render(props),/<video /);
});
test('terminal preview failure ends loading even if capture remains logically active',()=>{
const html=render({pending:true,error:'Нет кадров'});
assert.match(html,/aria-busy="false"/);assert.doesNotMatch(html,/nodedc-loading-region__status/);
assert.match(html,/Нет свежих данных/);
});
test('live frame status and expand action remain available',()=>{
const html=render({preview:{...preview,state:'Прямой эфир',live:true}});
assert.match(html,/Прямой эфир/);assert.match(html,/Развернуть просмотр/);assert.match(html,/aria-busy="false"/);
});
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import {after,before,test} from 'node:test';
import {createServer} from 'vite';
import {createServer} from './support/vite-server.mjs';
let server,activation,x4;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
@@ -33,7 +33,7 @@ test('stale inventory and replaced sessions never receive starts',async()=>{
});
test('X4 auto start uses preview only and attaches without restarting an active camera',async()=>{
const a=device(),t=transport([a]);await x4.startX4Observation(a,t);assert.deepEqual(t.commands.map(c=>c.action_id),['preview.start']);
a.camera_status.preview=1;t.commands.length=0;await x4.startX4Observation(a,t);assert.equal(t.commands.length,0);
a.camera_status.preview=1;t.commands.length=0;await x4.startX4Observation(a,t);assert.deepEqual(t.commands.map(c=>c.action_id),['verify']);
});
test('stalled X4 preview recovers once for both lenses without any recording action',async()=>{
const a=device();a.camera_status.preview=1;const t=transport([a]);
@@ -50,3 +50,51 @@ test('recovery cannot start a replacement camera session after its stop',async()
const items=[a],t=transport(items,()=>{items[0]=b;return {state:'complete'};});
await assert.rejects(x4.startX4Observation(a,t,true));assert.deepEqual(t.commands.map(c=>c.action_id),['preview.stop']);
});
const stalePreview='Не поступают свежие кадры. Остановите и снова начните просмотр.';
test('opening active but stale X4 verifies and recovers once across both entry points',async()=>{
const a=device();a.camera_status.preview=1;
const t=transport([a],c=>c.action_id==='verify'?{state:'error',error:stalePreview}:{state:'complete'});
await Promise.all([x4.startX4Observation(a,t),x4.startX4Observation(a,t)]);
assert.deepEqual(t.commands.map(c=>c.action_id),['verify','preview.stop','preview.start']);
});
test('opening active X4 preserves active or unknown recording',async()=>{
for(const recording of [1,null,-1]){
const a=device();a.camera_status={connected:true,preview:1,recording};const t=transport([a]);
await x4.startX4Observation(a,t);assert.equal(t.commands.length,0);
}
});
test('automatic activation respects the source restart allowance and counts failed attempts',async()=>{
const a=device();a.camera_status.preview=1;
let resets=0;const t=transport([a],c=>c.action_id==='verify'?{state:'error',error:stalePreview}:{state:'error',error:'Lost stop receipt'});
await assert.rejects(x4.startX4Observation(a,t,false,true,()=>resets++));assert.equal(resets,1);
t.commands.length=0;await assert.rejects(x4.startX4Observation(a,t,false,false,()=>resets++));
assert.deepEqual(t.commands.map(c=>c.action_id),['verify']);assert.equal(resets,1);
});
test('failed verification does not replay unknown outcomes or generic failures',async()=>{
for(const response of [{state:'unknown',error:stalePreview},{state:'error',error:'Камера недоступна.'}]){
const a=device();a.camera_status.preview=1;const t=transport([a],()=>response);
await assert.rejects(x4.startX4Observation(a,t));assert.deepEqual(t.commands.map(c=>c.action_id),['verify']);
}
const a=device();a.camera_status.preview=1;
const t=transport([a],()=>{throw new Error(stalePreview);});
await assert.rejects(x4.startX4Observation(a,t));assert.deepEqual(t.commands.map(c=>c.action_id),['verify']);
});
test('verified stale source rechecks recording and session before stopping capture',async()=>{
for(const change of [a=>{a.camera_status.recording=1;},a=>{a.snapshot.context.session_id='replacement';},a=>{a.camera_status.connected=false;},a=>{a.camera_status.preview=0;}]){
const a=device();a.camera_status.preview=1;const replacement=structuredClone(a),items=[a];
const t=transport(items,()=>{change(replacement);items[0]=replacement;return {state:'error',error:stalePreview};});
await assert.rejects(x4.startX4Observation(a,t));assert.deepEqual(t.commands.map(c=>c.action_id),['verify']);
}
});
test('new viewing peers require current streaming state and matching camera identity',async()=>{
const a=device();a.snapshot.acquisition='streaming';
assert.equal(await activation.currentPreviewDevice(a,transport([a])),a);
for(const change of [b=>{b.online=false;},b=>{b.prepared=false;},b=>{b.snapshot.acquisition='idle';},b=>{b.snapshot.context.session_id='replacement';}]){
const b=structuredClone(a);change(b);const t=transport([b]);
await assert.rejects(activation.currentPreviewDevice(a,t));assert.equal(t.commands.length,0);
}
const stale={...transport([a]),inventory:async()=>({fresh:false,items:[a]})};
await assert.rejects(activation.currentPreviewDevice(a,stale));assert.equal(stale.commands.length,0);
});
@@ -0,0 +1,65 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const result=await build({entryPoints:[new URL('../src/core/fleet/useVehicleObservation.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'fixture',setup(b){
b.onResolve({filter:/^(react|\.\/useFleet)$/},a=>({path:a.path,namespace:'fixture'}));
b.onLoad({filter:/.*/,namespace:'fixture'},a=>({contents:a.path==='react'?
'export const useState=v=>globalThis.observationUI.state(v),useRef=v=>globalThis.observationUI.ref(v),useEffect=(f,d)=>globalThis.observationUI.effect(f,d);':
'export const fleetRequest=(...args)=>globalThis.observationUI.request(...args);'}));
}}]});
const {useVehicleObservation}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
const receipt=(document=null,writable=false,revision=1)=>({document,writable,revision,source:writable?'onboard':'mirror',available:true});
async function fixture(run){
const keys=['observationUI','localStorage','setTimeout','clearTimeout'],old=new Map(keys.map(k=>[k,globalThis[k]]));
const values=[],effects=[],queue=[],timers=new Map(),storage=new Map();let cursor=0,dirty=true,closed=false,time=0,serial=0;
const h={next:receipt(),calls:[],view:null,readGate:null,
state(v){const i=cursor++;if(!(i in values))values[i]=typeof v==='function'?v():v;return[values[i],next=>{values[i]=typeof next==='function'?next(values[i]):next;dirty=true;}];},
ref(v){const i=cursor++;return values[i]??=( {current:v} );},
effect(f,d){const i=cursor++,prior=effects[i];if(!prior||d.some((v,j)=>v!==prior.d[j])){prior?.cleanup?.();effects[i]={d};queue.push(()=>{effects[i].cleanup=f();});}},
async request(path,method='GET',body){h.calls.push({path,method,body});if(method==='GET'){if(h.readGate)await h.readGate;if(h.next instanceof Error)throw h.next;return structuredClone(h.next);}if(!h.next.writable)throw Error('offline write');h.next=receipt(body.document,true,body.expected_revision+1);if(h.loseAck){h.next.writable=false;throw Error('lost acknowledgement');}return h.next;},
async settle(){for(let n=0;n<50;n++){await Promise.resolve();if(dirty&&!closed){dirty=false;cursor=0;h.view=useVehicleObservation('recovery-fixture');for(const f of queue.splice(0))f();}}},
async tick(ms){time+=ms;for(const [id,v]of [...timers])if(v.at<=time){timers.delete(id);v.f();}await h.settle();},
close(){closed=true;for(const e of effects)e?.cleanup?.();},
};
globalThis.observationUI=h;globalThis.localStorage={getItem:k=>storage.get(k)??null,setItem:(k,v)=>storage.set(k,v),removeItem:k=>storage.delete(k)};
globalThis.setTimeout=(f,delay)=>{timers.set(++serial,{f,at:time+delay});return serial;};globalThis.clearTimeout=id=>timers.delete(id);
try{await run(h);}finally{h.close();await h.settle();for(const[k,v]of old){if(v===undefined)delete globalThis[k];else globalThis[k]=v;}}
}
test('mirror warning clears after fresh board receipt without edits, reopen or PUT',()=>fixture(async h=>{
await h.settle();assert.equal(h.view.ready,true);assert.match(h.view.error,/хранилищем/);
h.next=receipt(null,true);await h.tick(5000);assert.equal(h.view.error,null);assert.equal(h.calls.filter(x=>x.method==='PUT').length,0);
}));
test('failed initial read retries and becomes ready without reopening',()=>fixture(async h=>{
h.next=Error('temporary outage');await h.settle();assert.equal(h.view.ready,false);
h.next=receipt(null,true);await h.tick(5000);assert.equal(h.view.ready,true);assert.equal(h.view.error,null);
}));
test('recovery preserves local draft, merges remote edits and saves once availability returns',()=>fixture(async h=>{
await h.settle();h.view.setCamera('camera',{yaw:90});await h.settle();await h.tick(350);
assert.equal(h.view.pending,true);
const draft=h.calls.find(x=>x.method==='PUT').body.document;
h.next=receipt({...draft,cameras:{other:{yaw:45}}},true,2);
await h.tick(5000);
assert.deepEqual(h.view.cameras,{camera:{yaw:90},other:{yaw:45}});
assert.equal(h.view.pending,false);assert.equal(h.view.error,null);
assert.equal(h.next.document.cameras.camera.yaw,90);assert.equal(h.next.document.cameras.other.yaw,45);
}));
test('conflicting remote edits never overwrite a local draft or trigger blind retry',()=>fixture(async h=>{
await h.settle();h.view.setCamera('camera',{yaw:90});await h.settle();await h.tick(350);
const prior=h.calls.filter(x=>x.method==='PUT').length,draft=h.calls.find(x=>x.method==='PUT').body.document;
h.next=receipt({...draft,cameras:{camera:{yaw:180}}},true,2);await h.tick(5000);
assert.equal(h.view.cameras.camera.yaw,90);assert.equal(h.view.pending,true);
assert.equal(h.calls.filter(x=>x.method==='PUT').length,prior);
}));
test('fresh read-back of a committed save clears its lost acknowledgement error without rewriting',()=>fixture(async h=>{
h.next=receipt(null,true);await h.settle();h.loseAck=true;
h.view.setCamera('camera',{yaw:90});await h.settle();await h.tick(350);
assert.equal(h.view.pending,true);assert.match(h.view.error,/acknowledgement/);
h.next.writable=true;h.next.source='onboard';await h.tick(5000);
assert.equal(h.view.pending,false);assert.equal(h.view.error,null);
assert.deepEqual(h.view.cameras,{camera:{yaw:90}});
assert.equal(h.calls.filter(x=>x.method==='PUT').length,1);
}));
test('late initial response after unmount cannot schedule another read or mutate mounted view',()=>fixture(async h=>{
let release;h.readGate=new Promise(r=>{release=r;});await h.settle();h.close();release();await h.settle();await h.tick(30000);
assert.equal(h.calls.length,1);assert.equal(h.view.ready,false);
}));
@@ -0,0 +1,41 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const result=await build({entryPoints:[new URL('../../../packages/sensor-ui/src/useObservationStart.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'fixture',setup(b){
b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'}));
b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:'export const useState=v=>globalThis.startUI.state(v),useRef=v=>globalThis.startUI.ref(v),useEffect=(f,d)=>globalThis.startUI.effect(f,d),useCallback=(f,d)=>globalThis.startUI.callback(f,d);'}));
}}]});
const {useObservationStart}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
async function fixture(run){
const keys=['startUI','window','document','performance','setTimeout','clearTimeout'],old=new Map(keys.map(k=>[k,globalThis[k]]));
const values=[],effects=[],tasks=[],timers=new Map(),events=new Map();let cursor=0,dirty=true,now=0,id=0,closed=false;
const h={enabled:true,active:false,recover:true,view:null,calls:0,fail:true,
state(v){const i=cursor++;if(!(i in values))values[i]=v;return[values[i],v=>{values[i]=typeof v==='function'?v(values[i]):v;dirty=true;}];},
ref(v){return values[cursor++]??={current:v};},callback(f){return values[cursor++]??=f;},
effect(f,d){const i=cursor++,old=effects[i];if(!old||d.some((v,j)=>v!==old.d[j])){old?.cleanup?.();effects[i]={d};tasks.push(()=>{effects[i].cleanup=f();});}},
async start(){h.calls++;if(h.fail)throw Error('temporary timeout');},
async settle(){dirty=true;for(let n=0;n<35;n++){await Promise.resolve();if(dirty&&!closed){dirty=false;cursor=0;h.view=useObservationStart({id:'camera',snapshot:{context:{session_id:'s',execution:{node_id:'n'}}}},h.enabled,h.active,h.start,h.recover);tasks.splice(0).forEach(f=>f());}}},
async advance(ms){now+=ms;for(const[k,v]of [...timers])if(v.at<=now){timers.delete(k);v.f();}await h.settle();},
close(){closed=true;effects.forEach(e=>e?.cleanup?.());},timers,events,
};
const eventAPI={addEventListener:(key,f)=>events.set(key,f),removeEventListener:(key,f)=>{if(events.get(key)===f)events.delete(key);}};
globalThis.startUI=h;globalThis.window={...eventAPI};globalThis.document={...eventAPI,visibilityState:'visible'};globalThis.performance={now:()=>now};
globalThis.setTimeout=(f,delay)=>{timers.set(++id,{f,at:now+delay});return id;};globalThis.clearTimeout=id=>timers.delete(id);
try{await run(h);}finally{h.close();await h.settle();for(const[k,v]of old){if(v===undefined)delete globalThis[k];else globalThis[k]=v;}}
}
test('temporary activation failures retry with one bounded timer and stop after live recovery',()=>fixture(async h=>{
await h.settle();assert.equal(h.calls,1);assert.equal(h.timers.size,1);
await h.advance(1999);assert.equal(h.calls,1);await h.advance(1);assert.equal(h.calls,2);
await h.advance(3999);assert.equal(h.calls,2);await h.advance(1);assert.equal(h.calls,3);
h.fail=false;h.events.get('online')();await h.advance(0);assert.equal(h.calls,4);
h.active=true;await h.settle();await h.advance(60000);assert.equal(h.calls,4);assert.equal(h.view.error,'');assert.equal(h.timers.size,0);
}));
test('disabled, hidden and unmounted views cannot keep retrying activation',()=>fixture(async h=>{
await h.settle();document.visibilityState='hidden';h.events.get('visibilitychange')();await h.advance(60000);assert.equal(h.calls,1);
document.visibilityState='visible';h.events.get('visibilitychange')();await h.advance(0);assert.equal(h.calls,2);
h.enabled=false;await h.settle();await h.advance(60000);assert.equal(h.calls,2);assert.equal(h.timers.size,0);
h.close();assert.equal(h.events.size,0);
}));
test('other acquisition callers keep explicit-retry behavior unless opted in',()=>fixture(async h=>{
h.recover=false;await h.settle();await h.advance(60000);assert.equal(h.calls,1);assert.equal(h.timers.size,0);
}));
@@ -0,0 +1,28 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
async function module(path){const compiled=await build({entryPoints:[new URL(path,import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});return import('data:text/javascript;base64,'+Buffer.from(compiled.outputFiles[0].contents).toString('base64'));}
const {previewEvidence}=await module('../../../packages/sensor-ui/src/previewEvidence.ts');
const {connectRoverEvidence,roverPreviewEvidence}=await module('../src/core/fleet/roverDevEvents.ts');
test('preview projection separates the budget, encoder and receiver without private payload',()=>{
const sample=previewEvidence('peer_a','session_a',{sdp:'secret',media_budget:{mode:'observing',allocation_bps:5000000,target_bps:3250000,encoder_bps:500000,receiver_bps:307644,encoder_reinitializations:68,sample_mono_ms:1234,egress:{sent_bytes:900,queue_dropped:0},last_encoder_reset:{frame:70,reason:'private'}}},{fps:11,round_trip_ms:90,mbps:.3,interval_ms:2000,packets_lost:NaN},1280,640,100);
assert.equal(sample.allocation_bps,5000000);assert.equal(sample.encoder_bps,500000);assert.equal(sample.receiver_bps,307644);
assert.equal(sample.reset_frame,70);assert.equal(sample.source_age_ms,100);assert.equal(sample.interval_ms,2000);
assert.equal(sample.packets_lost,undefined);assert.equal(sample.sdp,undefined);assert.equal(sample.reason,undefined);
assert.ok(JSON.stringify(sample).length<1500);
assert.deepEqual(previewEvidence('p','s',null,null,-1,Infinity,NaN),{peer_id:'p',device_session:'s'});
});
test('preview evidence is isolated by vehicle and local capture; remote DEV cannot upload it',async()=>{
const original=globalThis.fetch,calls=[];globalThis.fetch=async(url,init)=>{calls.push({url,body:JSON.parse(init.body)});return {ok:true,json:async()=>({accepted:true})};};
const a=connectRoverEvidence('/a'),b=connectRoverEvidence('/b');
try{
a.set('a'.repeat(32));b.set(null,'b'.repeat(32));
roverPreviewEvidence('/a',{peer_id:'p'});roverPreviewEvidence('/b',{peer_id:'q'});
await new Promise(r=>setTimeout(r,280));
assert.equal(calls.length,1);assert.equal(calls[0].url,'/b/diagnostics/local/events');
assert.equal(calls[0].body.id,'b'.repeat(32));assert.equal(calls[0].body.events[1].event,'preview');
assert.equal(calls[0].body.events[1].sample.peer_id,'q');
b.set(null);roverPreviewEvidence('/b',{peer_id:'later'});await new Promise(r=>setTimeout(r,280));
assert.equal(calls.length,1);
}finally{a.close();b.close();globalThis.fetch=original;}
});
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import {after,before,test} from 'node:test';
import {createServer} from 'vite';
import {createServer} from './support/vite-server.mjs';
let server,PreviewLiveness,previewPlayback;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
@@ -24,12 +24,26 @@ test('capture recovery requires sustained fresh reports that the source stopped'
});
test('missing telemetry and a stalled peer cannot be treated as proof to restart capture',()=>{
const h=new PreviewLiveness(0);h.frame(100);h.source(false,200);
assert.equal(h.state(13000),'peer-stalled');
assert.equal(h.state(13000),'delayed');assert.equal(h.state(31000),'peer-stalled');
});
test('an established stream survives a brief route interruption without claiming fresh video',()=>{
const h=new PreviewLiveness(0);h.frame(1000);
assert.equal(h.state(13000),'delayed');h.connected(13500);h.frame(14000);
assert.equal(h.state(14001),'live');assert.equal(h.state(44001),'peer-stalled');
});
test('negotiation time does not consume the first-frame grace period',()=>{
const h=new PreviewLiveness(0);h.connected(45000);
const h=new PreviewLiveness(0);h.negotiated(25000);
assert.equal(h.state(45000),'connecting');h.connected(45000);
assert.equal(h.state(45001),'waiting');assert.equal(h.state(53001),'peer-stalled');
});
test('unreachable ICE is bounded independently of a connected stream with no frames',()=>{
const h=new PreviewLiveness(0);h.negotiated(10000);
assert.equal(h.state(39999),'connecting');assert.equal(h.state(40001),'peer-stalled');
});
test('flapping connection events cannot indefinitely renew a missing-frame deadline',()=>{
const h=new PreviewLiveness(0);h.connected(1000);h.connected(8000);
assert.equal(h.state(9001),'peer-stalled');h.frame(10000);assert.equal(h.state(10001),'live');
});
test('a browser-paused panel resumes the same stream and coalesces pending playback',async()=>{
const stream={},attempts=[];
const video={srcObject:stream,muted:false,paused:true,play(){return new Promise(resolve=>attempts.push(resolve));}};
@@ -50,3 +64,16 @@ test('hidden-panel play rejection is retried on visibility without replacing the
assert.equal(attempts,2);assert.equal(video.srcObject,stream);
video.srcObject=null;playback.resume();assert.equal(attempts,2);
});
test('fresh budget pauses retain a peer without claiming fresh video, then allow recovery',()=>{
const h=new PreviewLiveness(0);h.connected(0);h.frame(100);
for(let now=1000;now<60000;now+=1000){h.source(true,now);h.allocation(true,now);assert.equal(h.state(now),'waiting');}
h.allocation(false,60000);assert.equal(h.state(60000),'waiting');
h.allocation(false,65000);assert.equal(h.state(68001),'peer-stalled');
h.frame(69000);assert.equal(h.state(69000),'live');
});
test('stale budget hints cannot hold a dead peer forever or mask a stalled source',()=>{
const h=new PreviewLiveness(0);h.connected(0);h.allocation(true,1000);
assert.equal(h.state(9001),'peer-stalled');
for(let now=10000;now<=23000;now+=1000){h.source(false,now);h.allocation(true,now);}
assert.equal(h.state(23000),'source-stalled');
});
@@ -0,0 +1,31 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const result=await build({entryPoints:[new URL('../../../packages/sensor-ui/src/useSensorPreview.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'fixture',setup(b){
b.onResolve({filter:/^(react|\.\/contracts|\.\/observationStart)$/},a=>({path:a.path,namespace:'fixture'}));
b.onLoad({filter:/.*/,namespace:'fixture'},a=>({contents:a.path==='react'?
'export const useEffect=f=>globalThis.previewUI.effects.push(f),useRef=v=>({current:v}),useState=v=>[v,next=>globalThis.previewUI.writes.push(next)];':a.path==='./contracts'?
'export const perform=(...args)=>globalThis.previewUI.perform(...args);':'export const currentPreviewDevice=async d=>d;'}));
}}]});
const {useSensorPreview}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
test('stuck signaling expires, retires late answers and removes every retry/listener on unmount',async()=>{
const keys=['previewUI','RTCPeerConnection','performance','document','window','setInterval','clearInterval','setTimeout','clearTimeout'],old=new Map(keys.map(k=>[k,globalThis[k]]));
let now=0,id=0,answer,pc;const timers=new Map(),intervals=new Map(),listeners=new Map(),calls=[];
const h={effects:[],writes:[],perform(_transport,_device,action,parameters,timeout){calls.push({action,parameters,timeout});return action==='offer'?new Promise(resolve=>{answer=resolve;}):Promise.resolve({});}};
class Peer{constructor(){pc=this;this.iceGatheringState='complete';this.remoteDescription=null;this.closed=false;this.remoteCalls=0;}createDataChannel(){return{readyState:'connecting'};}addTransceiver(){}async createOffer(){return{sdp:'fixture'};}async setLocalDescription(v){this.localDescription=v;}async setRemoteDescription(v){this.remoteCalls++;this.remoteDescription=v;}close(){this.closed=true;}}
const events={addEventListener:(name,f)=>listeners.set(name,f),removeEventListener:(name,f)=>{if(listeners.get(name)===f)listeners.delete(name);}};
globalThis.previewUI=h;globalThis.RTCPeerConnection=Peer;globalThis.performance={now:()=>now};globalThis.document={...events,visibilityState:'visible'};globalThis.window={...events};
globalThis.setInterval=f=>{intervals.set(++id,f);return id;};globalThis.clearInterval=id=>intervals.delete(id);globalThis.setTimeout=(f,delay)=>{timers.set(++id,{f,delay});return id;};globalThis.clearTimeout=id=>timers.delete(id);
const cleanups=[];
try{
useSensorPreview({id:'fixture',online:true,snapshot:{context:{session_id:'fixture-session'},acquisition:'streaming'}},'rgb',{}, {current:null});
for(const f of h.effects)cleanups.push(f());
for(let n=0;n<12;n++)await Promise.resolve();
assert.equal(calls[0].action,'offer');assert.equal(calls[0].timeout,20000);
now=32000;for(const f of intervals.values())f();
assert.equal(pc.closed,true);assert.ok(h.writes.includes('Восстановление просмотра'));assert.equal(timers.size,1);
answer({peer_id:'late-peer',sdp:'answer',type:'answer'});for(let n=0;n<12;n++)await Promise.resolve();
assert.equal(pc.remoteCalls,0);assert.deepEqual(calls.filter(c=>c.action==='close-peer').map(c=>c.parameters),[{peer_id:'late-peer'}]);
cleanups.forEach(f=>f?.());cleanups.length=0;assert.equal(timers.size,0);assert.equal(intervals.size,0);assert.equal(listeners.size,0);
}finally{cleanups.forEach(f=>f?.());for(const[k,v]of old){if(v===undefined)delete globalThis[k];else globalThis[k]=v;}}
});
@@ -0,0 +1,22 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
async function module(path){const r=await build({entryPoints:[new URL(path,import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});return import('data:text/javascript;base64,'+Buffer.from(r.outputFiles[0].contents).toString('base64'));}
const {configurePreviewPlayout}=await module('../../../packages/sensor-ui/src/previewPlayout.ts');
const {PreviewMetrics}=await module('../../../packages/sensor-ui/src/previewMetrics.ts');
test('live video requests low delay while unsupported, recorded and audio paths keep defaults',()=>{
const live={track:{kind:'video'},jitterBufferTarget:null};assert.equal(configurePreviewPlayout(live,true),0);assert.equal(live.jitterBufferTarget,0);
for(const [receiver,enabled] of [[{track:{kind:'video'}},true],[{track:{kind:'video'},jitterBufferTarget:90},false],[{track:{kind:'audio'},jitterBufferTarget:90},true],[undefined,true]]){
const before=JSON.stringify(receiver);assert.equal(configurePreviewPlayout(receiver,enabled),null);assert.equal(JSON.stringify(receiver),before);
}
const throws={track:{kind:'video'},get jitterBufferTarget(){return null;},set jitterBufferTarget(v){throw new Error('not supported');}};
assert.equal(configurePreviewPlayout(throws,true),null);
});
test('actual, target and network-minimum delay are distinct interval deltas, with reset-safe fallback',()=>{
const m=new PreviewMetrics();
const sample=(id,timestamp,count,delay,target,min)=>m.sample(new Map([['v',{id,type:'inbound-rtp',kind:'video',timestamp,framesDecoded:count,jitterBufferEmittedCount:count,jitterBufferDelay:delay,jitterBufferTargetDelay:target,jitterBufferMinimumDelay:min}]]));
assert.equal(sample('a',1000,100,10,8,4).jitter_buffer_ms,null);
const r=sample('a',3000,120,11,8.8,4.4);assert.equal(r.jitter_buffer_ms,50);assert.equal(r.jitter_target_ms,40);assert.equal(r.jitter_minimum_ms,20);
const reset=sample('b',5000,3,.3,.3,.2);assert.equal(reset.jitter_buffer_ms,null);assert.equal(reset.jitter_target_ms,null);
const absent=sample('b',7000,4,.4,undefined,undefined);assert.equal(absent.jitter_target_ms,null);assert.equal(absent.jitter_minimum_ms,null);
});
@@ -0,0 +1,11 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,previewReconnect,previewRetryDelay;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent'});({previewReconnect,previewRetryDelay}=await server.ssrLoadModule('../../packages/sensor-ui/src/previewReconnect.ts'));});
after(async()=>server?.close());
function harness(){let time=0,visible=true,runs=0,id=0;const timers=new Map();const retry=previewReconnect({visible:()=>visible,retry:()=>runs++,now:()=>time,schedule:(run,delay)=>{timers.set(++id,{run,at:time+delay});return id;},cancel:key=>timers.delete(key)});return{retry,timers,get runs(){return runs;},show(value){visible=value;value?retry.resume():retry.pause();},advance(value){time+=value;for(const [key,entry] of [...timers])if(entry.at<=time){timers.delete(key);entry.run();}}};}
test('a long capacity outage keeps one bounded timer and reconnects after the fourth failure',()=>{const h=harness();for(let n=0;n<30;n++){const delay=previewRetryDelay(n);assert.ok(delay>=2000&&delay<=30000);h.retry.schedule(delay);h.retry.resume();h.retry.resume();assert.equal(h.timers.size,1);h.advance(delay);assert.equal(h.runs,n+1);assert.equal(h.timers.size,0);}h.retry.dispose();});
test('a frozen/background page pauses negotiation and resumes once on visibility/pageshow',()=>{const h=harness();h.retry.schedule(2000);h.show(false);assert.equal(h.timers.size,0);h.advance(60000);assert.equal(h.runs,0);h.show(true);h.retry.resume();assert.equal(h.timers.size,1);h.advance(0);assert.equal(h.runs,1);h.retry.resume();assert.equal(h.timers.size,0);});
test('unmount/session replacement cancels the old timer and cannot reopen the old peer',()=>{const h=harness();h.retry.schedule(2000);h.retry.schedule(8000);assert.equal(h.timers.size,1);h.retry.dispose();h.advance(60000);h.show(true);h.retry.schedule(0);assert.equal(h.timers.size,0);assert.equal(h.runs,0);});
test('network recovery advances only an existing retry and never duplicates peers',()=>{const h=harness();h.retry.recovered();assert.equal(h.timers.size,0);h.retry.schedule(30000);h.retry.recovered();h.retry.recovered();assert.equal(h.timers.size,1);h.advance(0);assert.equal(h.runs,1);h.retry.recovered();assert.equal(h.timers.size,0);h.retry.dispose();});
+7 -4
View File
@@ -20,7 +20,7 @@ from missioncore_plugin_sdk.v0alpha2.session import DeviceSessionSnapshot
MODEL = {
"plugin_id": "missioncore.realsense",
"plugin_version": "0.6.6",
"plugin_version": "0.6.7",
"model_id": "realsense.d455",
}
@@ -238,6 +238,7 @@ class Device:
"last_frame": self.last_frame,
"recording": self.record,
"playback_id": self.playback_id,
"preview_priority_v1": True,
"layers": list(self.images)
+ (["points"] if self.depth is not None else [])
+ (["motion"] if self.motion else []),
@@ -577,13 +578,13 @@ class Device:
self.revision += 1
return {"ok": True, "value": item["value"]}
def points(self):
def points(self, limit=2000):
depth, intrinsics = self.depth, self.intrinsics
if depth is None or intrinsics is None:
if depth is None or intrinsics is None or limit <= 0:
return []
# SDK deprojection respects the camera's actual distortion model.
h, w = depth.shape
stride = max(8, math.ceil(math.sqrt(h * w / 2000)))
stride = max(8, math.ceil(math.sqrt(h * w / min(2000, limit))))
result = []
for y in range(0, h, stride):
for x in range(0, w, stride):
@@ -592,6 +593,8 @@ class Device:
result.extend(
round(v, 4) for v in rs.rs2_deproject_pixel_to_point(intrinsics, [x, y], z)
)
if len(result) >= min(2000, limit) * 3:
return result
return result
def recordings(self):
+61 -20
View File
@@ -8,6 +8,8 @@ import uuid
from fractions import Fraction
import aioice.ice
from missioncore_plugin_sdk.link_budget import budget_peer
from missioncore_plugin_sdk.media_budget import adapt_peer, cap_video_sender
from aiortc import RTCConfiguration, RTCPeerConnection, RTCSessionDescription, VideoStreamTrack
from av import VideoFrame
@@ -33,24 +35,34 @@ aioice.ice.get_host_addresses = lambda use_ipv4, use_ipv6: [
class CameraTrack(VideoStreamTrack):
def __init__(self, device, layer):
def __init__(self, device, layer, budget=None):
super().__init__()
self.device, self.layer = device, layer
self.device, self.layer, self.budget = device, layer, budget
self.next_at = 0.0
self.started = None
self.sequence = 0
async def recv(self):
# Fixed 15 Hz preview clock; raw hardware timing is independent.
if self.started is None:
self.started = time.monotonic()
await asyncio.sleep(max(0, self.started + self.sequence / 15 - time.monotonic()))
pts, base = self.sequence * 6000, Fraction(1, 90000)
self.sequence += 1
while self.layer not in self.device.images:
await asyncio.sleep(0.1)
frame = VideoFrame.from_ndarray(self.device.images[self.layer], format="rgb24")
frame.pts, frame.time_base = pts, base
return frame
while True:
width, fps = self.budget.video() if self.budget else (1280, 15)
now = time.monotonic()
sequence = self.device.frames.get(self.layer, 0)
fresh = now - self.device.last_frame.get("monotonic_ns", 0) / 1e9 < 2
if (fps and now >= self.next_at and fresh and sequence != self.sequence
and self.layer in self.device.images):
# One latest hardware image; no replay of a stalled source.
frame = VideoFrame.from_ndarray(self.device.images[self.layer], format="rgb24")
self.sequence = sequence
self.next_at = now + 1 / fps
if frame.width > width:
height = max(2, round(frame.height * width / frame.width) // 2 * 2)
frame = frame.reformat(width=width, height=height, format="yuv420p")
frame.pts, frame.time_base = round((now-self.started)*90000), Fraction(1,90000)
return frame
await asyncio.sleep(.02)
class Peers:
@@ -59,6 +71,8 @@ class Peers:
async def offer(self, device, params):
layer = params.get("layer", "color")
if type(params.get("primary", False)) is not bool:
raise ValueError("Invalid preview role")
if layer not in ("color", "depth", "infrared1", "infrared2", "points", "motion"):
raise ValueError("Неизвестный слой камеры.")
if len(self.items) >= 4:
@@ -73,14 +87,17 @@ class Peers:
raise ValueError("Просмотр доступен только в частной сети.")
pc = RTCPeerConnection(RTCConfiguration(iceServers=[]))
ident = "peer_" + uuid.uuid4().hex
self.items[ident] = {"pc": pc, "seen": time.monotonic()}
self.items[ident] = {"pc": pc, "seen": time.monotonic(), "tasks": set(), "channel": None}
allocation = None
async def telemetry(channel):
try:
while pc.connectionState not in ("failed", "closed"):
if time.monotonic() - self.items.get(ident, {}).get("seen", 0) > 30:
break
if channel.readyState == "open" and channel.bufferedAmount < 65536:
interval = .25
pending = getattr(pc, "_missioncore_pending_media", lambda: 0)()
if channel.readyState == "open" and channel.bufferedAmount < 16384 and pending < 16384 and allocation and allocation.bps:
payload = {
"layer": layer,
"motion": device.motion,
@@ -88,30 +105,50 @@ class Peers:
"acquisition": device.acquisition,
}
if layer == "points":
payload["points"] = await asyncio.to_thread(device.points)
channel.send(json.dumps(payload, allow_nan=False))
await asyncio.sleep(0.25)
count, interval = allocation.cloud(2000, 48)
payload["points"] = await asyncio.to_thread(device.points, count)
payload["media_budget"] = allocation.snapshot()
raw = json.dumps(payload, allow_nan=False)
# A single JSON message must fit the bounded SCTP burst.
while len(raw.encode()) > 16384 and payload.get("points"):
values = payload["points"]
payload["points"] = [v for i in range(0,len(values),6) for v in values[i:i+3]]
raw = json.dumps(payload, allow_nan=False)
if len(raw.encode()) <= 16384:
channel.send(raw)
await asyncio.sleep(interval)
finally:
await self.close(ident)
@pc.on("datachannel")
def datachannel(channel):
entry = self.items.get(ident)
if entry is None or entry["channel"] is not None:
channel.close()
return
entry["channel"] = channel
@channel.on("message")
def message(value):
if value in ("view:primary", "view:secondary") and allocation and layer not in ("points", "motion"):
allocation.primary = value == "view:primary"
if value == "keepalive" and ident in self.items:
self.items[ident]["seen"] = time.monotonic()
asyncio.create_task(telemetry(channel))
task = asyncio.create_task(telemetry(channel))
self.items[ident]["tasks"].add(task)
@pc.on("connectionstatechange")
async def changed():
if pc.connectionState in ("failed", "closed"):
self.items.pop(ident, None)
await self.close(ident)
try:
await pc.setRemoteDescription(RTCSessionDescription(sdp=sdp, type="offer"))
allocation = await adapt_peer(pc, "cloud" if layer in ("points", "motion") else "video", primary=params.get("primary", False) and layer not in ("points", "motion"))
if layer not in ("points", "motion"):
pc.addTrack(CameraTrack(device, layer))
sender = pc.addTrack(CameraTrack(device, layer, allocation))
cap_video_sender(sender, allocation)
budget_peer(pc, "cloud" if layer in ("points", "motion") else "video", producer_id=allocation.id)
await pc.setLocalDescription(await pc.createAnswer())
async def expiry():
@@ -119,7 +156,7 @@ class Peers:
if ident in self.items and pc.connectionState != "connected":
await self.close(ident)
asyncio.create_task(expiry())
self.items[ident]["tasks"].add(asyncio.create_task(expiry()))
return {"peer_id": ident, "sdp": pc.localDescription.sdp, "type": "answer"}
except Exception:
await self.close(ident)
@@ -128,5 +165,9 @@ class Peers:
async def close(self, ident):
entry = self.items.pop(ident, None)
if entry:
tasks = [t for t in entry["tasks"] if t is not asyncio.current_task()]
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
await entry["pc"].close()
return {"ok": True}
@@ -4,6 +4,179 @@
Основание: текущие указания владельца, MISSIONCOR-76/3/5 и канонический checkout `main`, исходный HEAD `54a85fdf5005803a7834482b7516ebe6b6fb142b`.
Это план следующей реализации, а не разрешение выполнить команды из присланных исследовательских текстов.
## Уточнение владельца от 14.10.2026: фирменная сшивка на текущем Mini
Это уточнение заменяет прежнее откладывание сшивки ниже, сохраняя исторический
baseline документа. Владелец получил CameraSDK 2.1.8 / MediaSDK 3.1.5 и поручил
подключить фирменную сшивку, настройку произвольного положения камеры и передний
вид для последующего инференса. Текущий борт — Mac Mini 2012 с Ubuntu 24.04 и
Intel HD 4000. Упоминание дискретной GPU было предположением, а не описанием
оборудования. Вынос обработки на другой компьютер не выбран. Сам AI-инференс и
управление движением не входят в приёмку этой сшивки.
### Порядок реализации и критерии
1. Проверить точный vendor runtime на этом Mini: загрузку библиотек,
инициализацию и первый сшитый кадр. Затем измерить устойчивую скорость,
свежесть кадра и загрузку при ограниченном времени прогона. Наличие Vulkan,
успешный конструктор или программный декодер по отдельности не означают
работающую сшивку. Ubuntu 24.04 и Intel — проверяемый профиль, а не заявленная
vendor-совместимость. Пробы, их ограничения и результаты принадлежат
версионированному preparation artifact и журналу установки.
2. Передавать MediaSDK исходные compressed packets из единственного USB owner,
сохраняя callback stream type/index, timestamp, factory calibration и crop.
В MediaSDK 3.1.5 stream type — фактический маркер маршрутизации, а не enum
кодека: в проверке enum H264=0 молча отбрасывался до декодирования.
Нельзя вычислять этот маркер из codec или заменять его константой live-пути.
Gyro/exposure и сведения о часах камеры передаются в единицах vendor API;
существующий bridge сейчас их теряет. Не скармливать SDK вторично сжатое
браузерное видео и не открывать камеру вторым процессом. Переполнение
ограниченной очереди или смена поколения разрывает сеанс декодирования;
старые packets не смешиваются с новой калибровкой или новой камерой.
3. Сравнить Dynamic Stitch и доступные альтернативы по реальному переднему
шву, включая цветовой переход, движущиеся границы и предметы на разных
расстояниях. Линзы смотрят влево и вправо по движению; проверяется именно
передний стык. Размер 960×480 служит первым техническим запуском, а не
приёмкой качества. Выбор выходного разрешения и FPS следует измерениям на
Mini. Отсутствующую модель или неподдержанный режим нельзя молча подменять
другим алгоритмом под прежним названием. Ползунки file API, отсутствующие
в RealTimeStitcher, не показываются как работающие live-настройки.
4. Выдать панораму и переднюю перспективную проекцию из одного результата
сшивки. Сохранить положение камеры в конфигурации конкретного аппарата и
экземпляра камеры на борту, с подтверждением ревизии. Проверить повторное
открытие, переподключение камеры и независимость операторского обзора от
переднего вида. Установка этого изменения выполняется одним согласованным
обновлением Node, X4 runtime и UI; локальный черновик не считается сохранением
на борту.
### Независимые системы координат
- Заводская межлинзовая калибровка описывает оптику конкретной X4. Повороты
отдельных lens tiles не переписывают её и не служат калибровкой крепления.
- Положение крепления — одно жёсткое вращение камеры относительно аппарата.
Поворот, наклон и крен доступны оператору; внутри сохраняется однозначное
вращение и версия соглашения об осях. Оси аппарата: X вперёд, Y влево,
Z вверх. Соответствие пикселей vendor-панорамы этим осям проверяется на
известном направлении, а не угадывается по названию левой/правой линзы.
- Оператор свободно осматривается по панораме. Его текущий взгляд имеет
отдельное состояние и не меняет крепление или направление AI-проекции.
- Передняя проекция закреплена за осями аппарата; её FOV, размер и соответствие
пикселей лучам известны потребителю. Начальный режим отключает FlowState и
direction lock, чтобы стабилизация не подменяла направление движения.
Включение стабилизации потребует передачи применённого вращения вместе с
каждым кадром и проверки обратного преобразования.
Существующие `rotations` и `panoramaYaw` — настройки отображения. Их нельзя
автоматически мигрировать в положение крепления. Backend Python и onboard Go
строго проверяют текущую форму документа; новый контракт требует обновления
обоих валидаторов и явной совместимости версий. Сохранённое положение должно
переживать замену вычислителя, но не переноситься на другую физическую камеру
или новое крепление как подтверждённая калибровка.
### Проверенная граница текущего Mini, 14.10.2026
Текущий результат на 20:06 UTC: X4 0.1.3-13 установлен, исходная тестовая запись
получена через официальный DownloadCameraFile и проверена по SHA256. MediaSDK
на этом Mini сшил из неё JPEG 1920×960: progress 100, error 0, штатное завершение,
runtime `stitch_fusion=1`. Это обработка исходного файла в изолированном тесте,
а не уже включённая живая сшивка. Проверка производительности live-пути,
качества переднего шва и сохранения крепления остаётся открытой. Ниже сохранены
этапы проверки и их ограничения; актуальные артефакты перечислены в журнале 07.
MediaSDK 3.1.5 загружается и создаёт RealTimeStitcher на этом борту. Это
не означает получение сшитых кадров. Входной stream type нельзя заменять
номером кодека: такой тест молча отбрасывался до декодирования. После исправления
тест дошёл до выбора программного декодера и создания графического контекста.
Точная библиотека запрашивает OpenGL 4.3 Core. Системная проверка на Mini
подтвердила: Intel HD 4000 предоставляет OpenGL 4.2 и отклоняет запрос 4.3
с EGL_BAD_MATCH; llvmpipe на CPU создаёт 4.3 и сообщает OpenGL 4.5. Устройство
Intel успешно проходит EGL-инициализацию и внутри изоляции. Это различие
графических возможностей, а не измеренная нехватка FPS или запрет на текущий
борт. Версионированный CPU-only профиль без доступа к /dev/dri уже направил
RealTimeStitcher на llvmpipe: Dynamic Stitch запустился и вернул два callback
кадра 960×480. Простой флаг software rendering при видимой Intel не работал:
SDK выбирает первое EGL-устройство. Права устройств и драйверы хоста не менялись.
Подмена объявленной версии OpenGL без реализации возможностей не допускается.
Приёмка пикселей требует отдельной проверки: точный runtime возвращает format=0
со stride width×4, как packed RGBA в фирменном примере, хотя заголовок ошибочно
называет поле FFmpeg AVPixelFormat. Интерпретация этого 0 как YUV не принимается.
Исправленный тест получил и сохранил цветной RGBA-кадр 960×480; визуальная
проверка синтетического результата пройдена. При завершении глобального
PlatformSetup процесс аварийно остановился (`munmap_chunk(): invalid pointer`,
exit -6). Жизненный цикл не принят, причина требует локализации. SDK должен
жить отдельно от USB owner и Node; подавление деструктора или игнорирование
exit-кода не считается исправлением. До живой интеграции нужны проверенные
start/stop/recovery и отсутствие влияния на приём камеры.
Продолжение того же дня: четыре запуска под отладчиком (три с обычным ASLR)
и отдельный запуск без отладчика завершились штатно с двумя RGBA-кадрами
каждый. Предыдущий allocator abort не воспроизведён; его причина не устранена
и он остаётся открытым пунктом жизненного цикла. SDK и профиль не заменялись.
Установлен и проверен на Mini X4 0.1.3-12 (14.10, 18:30 UTC): ABI 2 сохраняет исходный
stream type, timestamp и revision калибровки, а отдельный внутренний reader
отдаёт точные callback bytes. Браузерный reader сохраняет SPS/PPS replay.
Пакет прошёл 101 тест и Ubuntu-проверку зависимостей; нативный адаптер —
10 тестов. Gyro/exposure forwarding и MediaSDK worker остаются следующими
изменениями, а не функциями этого промежуточного пакета.
Синтетический результат не доказывает качество реального переднего шва или
устойчивые FPS. Рабочий live-путь всё ещё использует прежнюю проекцию;
MediaSDK, положение крепления и передняя AI-проекция ещё не установлены в него.
Полный журнал — в installation ledger.
Продолжение 14.10, 19:06 UTC: MediaSDK обработал реальный исходный callback sample
на CPU Mini. Вариант с CancelStitch перед уничтожением объекта снова дал abort
после выдачи кадров; исправленное владение callback state само по себе его не
устранило. Вариант с одним документированным завершением через деструктор прошёл
три коротких обычных запуска подряд: 14 RGBA кадров 960×480 из 128 входных packets,
около 485–491 MiB peak RSS. Причина прежнего сбоя не доказана, длительный live-путь
ещё не принят. Пользователь подтвердил, что исходный sample снят в темноте.
Отдельный тест с фонариком сохранён штатной записью на карту X4; StopRecording и
последующий список файлов подтвердили новый .insv. На Mac сохранены 17 контрольных
кадров операторского WebRTC-preview, но они не заменяют исходный SDK-поток.
Получение оригинала завершено в обновлении 0.1.3-13: штатный DownloadCameraFile
в существующем USB worker, отдельный частный экспорт владельцу и совпадающие
SHA256. Исходник сохранён на карте камеры. Публичный интерфейс скачивания файлов
пока не добавлен. Live worker MediaSDK, gyro/exposure forwarding и сохранение
положения крепления остаются следующими изменениями.
Следующая поставка должна пройти три последовательных шага:
1. Изолированный RealTimeStitcher получает оригинальные packets и метаданные от
существующего USB owner. Его сбой/остановка не прерывает камеру и heartbeat.
Измеряются частота и возраст выходных кадров, память и восстановление после
разрыва потока. Возможности VideoStitcher, например подтверждённый в файловом
тесте StitchFusion, не объявляются возможностями live API без отдельной
проверки. Панорама появляется в операторском просмотре только из этого
результата; прежняя геометрическая проекция не выдаётся за SDK-сшивку.
2. Один camera-to-rover transform сохраняется на борту с подтверждением ревизии.
Поворот, наклон и крен крепления отделяются от положения взгляда оператора.
Обновляются совместно onboard Go, Core-валидатор и UI; старые настройки
отображения не превращаются автоматически в физическую калибровку.
3. Панорама и передний перспективный вид используют одно сшитое изображение и
один transform. По хорошо освещённой сцене проверяются оба пересечения линз,
непрерывность переднего объекта, цветовой переход и известное направление
движения. Тёмный кадр с бликом фонарика не закрывает эту приёмку.
### Смена вычислителя
Вход камеры, factory calibration, положение крепления, схема кадров и передний
вид не зависят от марки CPU/GPU. Отдельный адаптер сшивки сообщает фактически
проверенные возможности текущего runtime. Будущий NVIDIA-борт получает свой
профиль и проверку, без изменения смысла операторских настроек. Не включать
сетевую передачу исходных потоков на внешний compute как скрытый fallback.
Если текущая версия MediaSDK не сможет выдавать кадры на Mini, альтернативой
для отдельной проверки остаётся штатная сшитая Webcam-панорама X4 с приёмом и
ориентацией на том же Mini. Это иной путь получения изображения; доступность
Linux USB-режима, качество переднего шва и сохранность camera-control функций
должны быть подтверждены отдельно. Недокументированное переключение USB mode
не является способом обойти эту проверку.
## 1. Результат, который требуется владельцу
Пользователь подключает X4 к Ubuntu-борту, видит отдельное устройство, нажимает инициализацию, получает прогресс развёртывания встроенного профиля, подтверждение получения изображения и живое видео. Тот же сценарий работает локально в Node и удалённо в Mission Core через существующее сопряжение. Установка и подготовка не требуют консоли оператора.
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -8,9 +8,9 @@ import {PointViewport} from './PointViewport';
import {useObservationStart} from './useObservationStart';
import {startCameraObservation} from './observationStart';
export function CameraObservation({device,transport,enabled,views}:SensorObservationProps){
export function CameraObservation({device,transport,enabled,fresh=true,views}:SensorObservationProps){
const video=useRef<HTMLVideoElement>(null);const [generation,setGeneration]=useState(0);
const activation=useObservationStart(device,enabled&&device.online&&device.prepared,!['idle','failed'].includes(device.snapshot.acquisition)||!!device.playback_id,()=>startCameraObservation(device,transport));
const activation=useObservationStart(device,enabled&&fresh&&device.online&&device.prepared,!['idle','failed'].includes(device.snapshot.acquisition)||!!device.playback_id,()=>startCameraObservation(device,transport));
const view=views[0];const {state,telemetry,error,live,hasFrame}=useSensorPreview(device,view.layer,transport,video,enabled,generation);
return createPortal(<div className="observation-source">
<ObservationHeader targets={view} live={live} label={activation.pending?'Запуск камеры':state}>{activation.error?<IconButton label="Повторить запуск камеры" disabled={activation.pending} onClick={()=>void activation.retry()}><Icon name="refresh"/></IconButton>:error&&<IconButton label="Повторить подключение камеры" onClick={()=>setGeneration(v=>v+1)}><Icon name="refresh"/></IconButton>}</ObservationHeader>
+25 -36
View File
@@ -1,42 +1,31 @@
import {useEffect,useRef,useState} from 'react';
import {useEffect,useRef,useState,type RefObject} from 'react';
import {LoadingRegion,Icon,IconButton,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {perform,type Sensor,type SensorTransport} from './contracts';
import type {Sensor,SensorTransport} from './contracts';
import {PointViewport} from './PointViewport';
interface Telemetry {points?:number[];motion?:Record<string,{x:number;y:number;z:number}>;acquisition?:string;frame?:{observed_at:string}}
export function LiveViewport({device,layer,transport,failure,title,note,inactiveMessage,enabled=true}:{enabled?:boolean;device:Sensor;layer:string;transport:SensorTransport;failure:(e:unknown)=>void;title?:string;note?:string;inactiveMessage?:string}){
const video=useRef<HTMLVideoElement>(null);const frame=useRef<HTMLDivElement>(null);const [expanded,setExpanded]=useState(false);
const [state,setState]=useState('Подключение просмотра');const [telemetry,setTelemetry]=useState<Telemetry>({});
useEffect(()=>{
if(!enabled||device.snapshot.acquisition!=='streaming'){setState('Захват остановлен');return;}
let cancelled=false;let terminal=false;let peerID='';let timer:ReturnType<typeof setInterval>|undefined;let last=Date.now();let frameHandle:number|undefined;let decoded=0;
const live=()=>{if(cancelled||terminal)return;last=Date.now();setState(device.playback_id?'Исходная запись':'Прямой эфир');};
const frameSeen=()=>{live();if(!cancelled)frameHandle=video.current?.requestVideoFrameCallback(frameSeen);};
setTelemetry({});setState('Подключение просмотра');
if(typeof RTCPeerConnection==='undefined'){setState('Просмотр не поддерживается этим браузером');return;}
const pc=new RTCPeerConnection({iceServers:[]});const channel=pc.createDataChannel('sensor',{ordered:false,maxRetransmits:0});
if(layer!=='points'&&layer!=='motion')pc.addTransceiver('video',{direction:'recvonly'});
pc.ontrack=event=>{if(video.current){video.current.srcObject=new MediaStream([event.track]);if(typeof video.current.requestVideoFrameCallback==='function')frameHandle=video.current.requestVideoFrameCallback(frameSeen);}};
pc.onconnectionstatechange=()=>{if(cancelled||terminal)return;if(pc.connectionState==='failed'){terminal=true;setState('Нет связи с камерой');}else if(pc.connectionState==='connected')setState(current=>current==='Прямой эфир'||current==='Исходная запись'?current:'Ожидание изображения');};
channel.onmessage=event=>{try{const v=JSON.parse(event.data);if(layer==='points'||layer==='motion')live();setTelemetry(v);}catch{ /* Ignore malformed preview, not control state. */ }};
timer=setInterval(()=>{if(terminal)return;if(channel.readyState==='open')channel.send('keepalive');if(video.current&&typeof video.current.requestVideoFrameCallback!=='function')void pc.getStats().then(stats=>{stats.forEach(value=>{if(value.type==='inbound-rtp'&&value.kind==='video'&&value.framesDecoded>decoded){decoded=value.framesDecoded;live();}});}).catch(()=>undefined);if(Date.now()-last>8000)setState('Нет свежих кадров');},2000);
async function connect(){try{
await pc.setLocalDescription(await pc.createOffer());
if(pc.iceGatheringState!=='complete')await new Promise<void>((resolve,reject)=>{const t=setTimeout(()=>reject(new Error('Не удалось подготовить частный канал просмотра.')),10000);pc.addEventListener('icegatheringstatechange',()=>{if(pc.iceGatheringState==='complete'){clearTimeout(t);resolve();}});});
if(cancelled)return;
const answer=await perform<{peer_id:string;sdp:string;type:'answer'}>(transport,device,'offer',{sdp:pc.localDescription!.sdp,layer});peerID=answer.peer_id;
if(cancelled){void perform(transport,device,'close-peer',{peer_id:peerID}).catch(()=>undefined);return;}
await pc.setRemoteDescription({type:'answer',sdp:answer.sdp});
}catch(e){if(!cancelled){terminal=true;setState('Просмотр недоступен');failure(e);}}}
void connect();return()=>{cancelled=true;if(timer)clearInterval(timer);if(frameHandle!==undefined)video.current?.cancelVideoFrameCallback(frameHandle);pc.close();if(peerID)void perform(transport,device,'close-peer',{peer_id:peerID}).catch(()=>undefined);};
},[enabled,device.id,device.snapshot.context.session_id,device.snapshot.acquisition,device.playback_id,layer,transport]);
import {useSensorPreview} from './useSensorPreview';
type ViewportProps={enabled?:boolean;device:Sensor;layer:string;title?:string;note?:string;inactiveMessage?:string};
export function LiveViewport({transport,failure,...props}:ViewportProps&{transport:SensorTransport;failure:(e:unknown)=>void}){
const video=useRef<HTMLVideoElement>(null),report=useRef(failure);report.current=failure;
const preview=useSensorPreview(props.device,props.layer,transport,video,props.enabled);
useEffect(()=>{if(preview.error)report.current(new Error(preview.error));},[preview.error]);
return <LiveViewportSurface {...props} video={video} preview={preview}/>;
}
/** Keep the media element mounted while capture connects, stops or recovers. */
export function LiveViewportSurface({device,layer,title,note,inactiveMessage,enabled=true,video,preview,pending=false,error=''}:ViewportProps&{video:RefObject<HTMLVideoElement|null>;preview:ReturnType<typeof useSensorPreview>;pending?:boolean;error?:string}){
const [expanded,setExpanded]=useState(false);
const {telemetry,live}=preview;
const active=enabled&&device.online&&device.snapshot.acquisition==='streaming';
const failed=error||preview.error;
const state=failed?'Нет свежих данных':pending?'Подключение просмотра':preview.state;
useEffect(()=>{const escape=(e:KeyboardEvent)=>{if(e.key==='Escape')setExpanded(false);};document.addEventListener('keydown',escape);return()=>document.removeEventListener('keydown',escape);},[]);
const active=enabled&&device.snapshot.acquisition==='streaming';
return <div ref={frame} className={expanded?'sensor-viewer sensor-viewer-expanded':'sensor-viewer'}><SettingsCard title={title??(layer==='points'?'Облако точек':layer==='motion'?'Движение':({color:'RGB',depth:'Глубина',infrared1:'ИК · 1',infrared2:'ИК · 2'}[layer]??layer))} actions={<><StatusBadge tone={active&&(state==='Прямой эфир'||state==='Исходная запись')?'success':'neutral'}>{state}</StatusBadge><IconButton label={expanded?'Восстановить размер просмотра':'Развернуть просмотр'} onClick={()=>setExpanded(!expanded)}><Icon name={expanded?'minimize':'expand'}/></IconButton></>}>
{!active?<p>{inactiveMessage??'Нажмите «Начать просмотр» или «Начать запись» для запуска камеры.'}</p>:<>
<LoadingRegion loading={state==='Подключение просмотра'||state==='Ожидание изображения'} label={state}>
return <div className={expanded?'sensor-viewer sensor-viewer-expanded':'sensor-viewer'}><SettingsCard title={title??(layer==='points'?'Облако точек':layer==='motion'?'Движение':({color:'RGB',depth:'Глубина',infrared1:'ИК · 1',infrared2:'ИК · 2'}[layer]??layer))} actions={<div className="nodedc-viewport-controls sensor-actions"><StatusBadge tone={active&&live?'success':'neutral'}>{state}</StatusBadge><IconButton label={expanded?'Восстановить размер просмотра':'Развернуть просмотр'} onClick={()=>setExpanded(!expanded)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div>}>
{!active&&!pending&&!failed&&<p>{inactiveMessage??'Нажмите «Начать просмотр» или «Начать запись» для запуска камеры.'}</p>}
<LoadingRegion loading={!failed&&(pending||(active&&(state==='Подключение просмотра'||state==='Ожидание изображения')))} label={state}>
<div hidden={!active}>
{layer==='points'?<PointViewport points={telemetry.points??[]}/>:layer==='motion'?<dl className="sensor-facts">{Object.entries(telemetry.motion??{}).map(([kind,v])=><div key={kind}><dt>{kind==='accel'?'Ускорение · м/с²':'Угловая скорость · рад/с'}</dt><dd>X {v.x.toFixed(3)} · Y {v.y.toFixed(3)} · Z {v.z.toFixed(3)}</dd></div>)}</dl>:<video ref={video} className="sensor-media" autoPlay muted playsInline/>}
</LoadingRegion>
<p className="sensor-note">{note??(layer==='points'?'Предпросмотр до 2 000 точек · координаты камеры · метры':layer==='depth'?'Цветное представление глубины. Исходная глубина записывается без видеосжатия.':'Предпросмотр камеры. Исходная запись хранится на БК.')}</p>
</>}
</div>
</LoadingRegion>
{failed&&<p role="status">Нет свежих данных</p>}
{active&&<p className="sensor-note">{note??(layer==='points'?'Предпросмотр до 2 000 точек · координаты камеры · метры':layer==='depth'?'Цветное представление глубины. Исходная глубина записывается без видеосжатия.':'Предпросмотр камеры. Исходная запись хранится на БК.')}</p>}
</SettingsCard></div>;
}
+3 -2
View File
@@ -1,8 +1,9 @@
import {SensorDetailBack} from './SensorDetailBack';
import {useEffect,useState} from 'react';
import {Button,Icon,IconButton,Select,SettingsCard,TextField} from '@nodedc/ui-react';
import {perform,type Sensor,type SensorTransport} from './contracts';
import {LiveViewport} from './LiveViewport';
export function SensorDetail({device,transport,back,refresh,failure,enabled=true}:{enabled?:boolean;device:Sensor;transport:SensorTransport;back:()=>void;refresh:()=>Promise<void>;failure:(e:unknown)=>void}){
export function SensorDetail({device,transport,back,navigationTarget,refresh,failure,enabled=true}:{enabled?:boolean;device:Sensor;transport:SensorTransport;back:()=>void;navigationTarget?:HTMLElement|null;refresh:()=>Promise<void>;failure:(e:unknown)=>void}){
const [detail,setDetail]=useState<Sensor|null>(null);const [selected,setSelected]=useState<Record<string,string>>({});const [layer,setLayer]=useState('color');const [pendingAction,setPendingAction]=useState<string|null>(null);const pending=pendingAction!==null;const [option,setOption]=useState('');const [optionValue,setOptionValue]=useState('');
async function load(){const value=await perform<Sensor>(transport,device,'details');setDetail(value);return value;}
useEffect(()=>{let live=true;if(enabled&&device.online&&device.prepared)void load().then(value=>{if(live){const selection:Record<string,string>={};for(const p of value.profiles??[])if(value.defaults?.includes(p.id))selection[p.stream+':'+p.index]=p.id;setSelected(selection);}}).catch(failure);return()=>{live=false;};},[enabled,device.online,device.id,device.prepared,device.snapshot.context.session_id]);
@@ -12,7 +13,7 @@ export function SensorDetail({device,transport,back,refresh,failure,enabled=true
const videoNames:Record<string,string>={color:'RGB',depth:'Глубина',infrared1:'ИК · 1',infrared2:'ИК · 2',points:'Точки',motion:'Движение'};
const available=[...new Set(supported.map(p=>p.stream==='infrared'?p.stream+p.index:p.stream==='gyro'||p.stream==='accel'?'motion':p.stream))];if(available.includes('depth'))available.push('points');
const currentOption=detail?.options?.find(v=>v.id===option);const active=device.snapshot.acquisition==='streaming'||device.snapshot.acquisition==='starting'||device.snapshot.acquisition==='stopping';
return <div className="sensor-content"><div><Button onClick={back}>К устройствам</Button></div>
return <div className="sensor-content"><SensorDetailBack back={back} target={navigationTarget}/>
<SettingsCard title={device.name} description={`${device.model} · USB ${device.usb}${device.firmware?' · '+device.firmware:''}`}>
{!device.online&&!device.snapshot.message&&<p>Камера отключена от БК.</p>}
{device.snapshot.message&&<p>{device.snapshot.message}</p>}
@@ -0,0 +1,7 @@
import {createPortal} from 'react-dom';
import {Button,Icon,IconButton} from '@nodedc/ui-react';
/** Return to the owning equipment tree; standalone device hosts keep an inline action. */
export function SensorDetailBack({back,target}:{back:()=>void;target?:HTMLElement|null}){
return target?createPortal(<IconButton label="К устройствам" onClick={back}><Icon name="chevron-left"/></IconButton>,target):<div><Button onClick={back}>К устройствам</Button></div>;
}
@@ -0,0 +1,25 @@
import {useEffect,useRef,useState} from 'react';
import {Button,ResourceRow,SettingsCard,TextField} from '@nodedc/ui-react';
import {perform} from './contracts';
import type {SensorDetailProps} from './extensions';
export function SensorGeneralSettings({device,transport,enabled,refresh,failure,generalSettings,blocked=false,onBusyChange,onSaved}:Pick<SensorDetailProps,'device'|'transport'|'enabled'|'refresh'|'failure'|'generalSettings'>&{blocked?:boolean;onBusyChange?:(busy:boolean)=>void;onSaved?:()=>void}){
const [name,setName]=useState(device.name),[pending,setPending]=useState<string|null>(null);
const running=useRef(false),mounted=useRef(true);
useEffect(()=>{setName(device.name);},[device.id,device.name]);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;onBusyChange?.(false);};},[onBusyChange]);
const busy=blocked||pending!==null;
async function execute(action:string,parameters:Record<string,unknown>={}){
if(running.current||busy||!enabled)return;
running.current=true;setPending(action);onBusyChange?.(true);failure(null);
try{await perform(transport,device,action,parameters);await refresh();if(mounted.current)onSaved?.();}
catch(error){if(mounted.current)failure(error);}
finally{running.current=false;if(mounted.current){setPending(null);onBusyChange?.(false);}}
}
return <SettingsCard title="Общие данные" description="Название устройства и его конфигурация на бортовом компьютере.">
{generalSettings?.supportsRenaming!==false&&<><TextField label="Название устройства" value={name} maxLength={80} onChange={e=>setName(e.target.value)} disabled={busy||!enabled}/>
<Button loading={pending==='rename'} disabled={busy||!enabled||!name.trim()||name.trim()===device.name} onClick={()=>void execute('rename',{name:name.trim()})}>Сохранить название</Button></>}
{generalSettings?.facts?.map(fact=><TextField key={fact.id} label={fact.label} value={fact.value} readOnly/>)}
{generalSettings?.supportsPreparation!==false&&<ResourceRow title="Конфигурация на БК" description="Развернуть и проверить встроенный драйвер устройства." actions={<Button loading={pending==='prepare'} disabled={busy||!enabled||!device.online||device.initializable===false||device.preparation_safe===false||['streaming','starting','stopping'].includes(device.snapshot.acquisition??'offline')} onClick={()=>void execute('prepare')}>Обновить</Button>}/>}
</SettingsCard>;
}
+27 -20
View File
@@ -1,7 +1,9 @@
import {useCallback,useEffect,useRef,useState,type ReactNode} from 'react';
import {LoadingRegion,Button,Icon,IconButton,ResourceList,ResourceRow,SettingsCard,StatusBadge,TextField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
import {LoadingRegion,Button,Icon,IconButton,ResourceList,ResourceRow,SettingsCard,StatusBadge,ToastStack,Window} from '@nodedc/ui-react';
import {perform,enrolledDevice,type Sensor,type SensorInventory,type SensorTransport} from './contracts';
import {SensorDetail} from './SensorDetail';
import {SensorGeneralSettings} from './SensorGeneralSettings';
import {SensorDetailBack} from './SensorDetailBack';
import {SensorRowActions} from './SensorRowActions';
import {SensorPreparations} from './SensorPreparations';
import {devicePreparation,preparationProgress} from './preparation';
@@ -9,23 +11,23 @@ import {sensorStatus} from './sensorStatus';
import {sensorContribution,type SensorUiContribution,wirelessContributions} from './extensions';
import type {RerunHostFactory} from './rerunHost';
import './sensors.css';
import {InventoryObserver} from './inventoryObserver';
import {BoardSections,type BoardSectionsProps} from './BoardSections';
import {WirelessEnrollmentWindow} from './WirelessEnrollmentWindow';
export interface SensorBoardContent {settings:ReactNode;devices:ReactNode;refresh:()=>Promise<void>;addDevice:()=>void;canAddDevice:boolean;showingSavedDevices:boolean}
export function SensorWorkspace({transport,enabled=true,onDetailChange,createRerunHost,contributions=[],board,renderBoard,readOfflineInventory=false}:{transport:SensorTransport;enabled?:boolean;onDetailChange?:(open:boolean)=>void;createRerunHost?:RerunHostFactory;contributions?:readonly SensorUiContribution[];board?:BoardSectionsProps;renderBoard?:(view:SensorBoardContent)=>ReactNode;readOfflineInventory?:boolean}){
const [adding,setAdding]=useState(false);
const [inventory,setInventory]=useState<SensorInventory|null>(null);const [selected,setSelected]=useState<string|null>(null);const [editing,setEditing]=useState<Sensor|null>(null);const [name,setName]=useState('');const [localBusy,setBusy]=useState<ReadonlyMap<string,string>>(()=>new Map());const activeActions=useRef(new Map<string,string>());const [error,setError]=useState('');const [fresh,setFresh]=useState(false);
export function SensorWorkspace({transport,enabled=true,previewEnabled=enabled,onDetailChange,detailActionsTarget,createRerunHost,contributions=[],board,renderBoard,readOfflineInventory=false}:{transport:SensorTransport;enabled?:boolean;previewEnabled?:boolean;onDetailChange?:(open:boolean)=>void;detailActionsTarget?:HTMLElement|null;createRerunHost?:RerunHostFactory;contributions?:readonly SensorUiContribution[];board?:BoardSectionsProps;renderBoard?:(view:SensorBoardContent)=>ReactNode;readOfflineInventory?:boolean}){
const [adding,setAdding]=useState(false);const [editingBusy,setEditingBusy]=useState(false);
const [inventory,setInventory]=useState<SensorInventory|null>(null);const [selected,setSelected]=useState<string|null>(null);const [editing,setEditing]=useState<Sensor|null>(null);const [localBusy,setBusy]=useState<ReadonlyMap<string,string>>(()=>new Map());const activeActions=useRef(new Map<string,string>());const [error,setError]=useState('');const [fresh,setFresh]=useState(false);
const failure=useCallback((e:unknown)=>{setError(e===null?'':e instanceof Error?e.message:'Не удалось выполнить действие устройства.');},[]);
const refresh=useCallback(async()=>{if(!enabled&&!readOfflineInventory){setFresh(false);return;}try{const value=await transport.inventory();setInventory(value);setFresh(enabled&&value.fresh!==false);}catch(e){setFresh(false);failure(e);}},[transport,enabled,readOfflineInventory,failure]);
const observer=useRef<InventoryObserver|null>(null);
const refresh=useCallback(async()=>{await observer.current?.refresh();},[]);
useEffect(()=>{
if(!enabled&&!readOfflineInventory){setFresh(false);return;}
let active=true;let fallback:ReturnType<typeof setInterval>|undefined;
const unavailable=()=>{if(!active)return;setFresh(false);if(!fallback)fallback=setInterval(()=>void refresh(),3000);};
void refresh();
const close=transport.subscribe?.(value=>{if(!active)return;if(fallback){clearInterval(fallback);fallback=undefined;}setInventory(value);setFresh(enabled&&value.fresh!==false);},unavailable);
if(!close)unavailable();
return()=>{active=false;close?.();if(fallback)clearInterval(fallback);};
},[transport,enabled,readOfflineInventory,refresh]);
setFresh(false);
if(!enabled&&!readOfflineInventory)return;
const current=new InventoryObserver(transport,value=>{setInventory(value);setFresh(enabled&&value.fresh!==false);},()=>setFresh(false),failure);
observer.current=current;
return()=>{current.close();if(observer.current===current)observer.current=null;};
},[transport,enabled,readOfflineInventory,failure]);
async function action(device:Sensor,action:string,parameters:Record<string,unknown>={}){
if(activeActions.current.has(device.id))return;
activeActions.current.set(device.id,action);setBusy(new Map(activeActions.current));setError('');
@@ -35,8 +37,10 @@ export function SensorWorkspace({transport,enabled=true,onDetailChange,createRer
}
async function completeEnrollment(sessionId:string,signal?:AbortSignal){
if(!enabled)throw new Error('БК недоступен. Обновите состояние устройства.');
const value=await transport.inventory();
if(signal?.aborted)return;
const current=observer.current;
const value=await current?.refresh();
if(signal?.aborted||current!==observer.current)return;
if(!value)throw new Error('Обновите сведения об устройстве и повторите проверку.');
const target=enrolledDevice(value,sessionId);
if(!target)throw new Error('Связь с устройством пока не подтверждена. Проверьте его состояние.');
setInventory(value);setFresh(true);setSelected(target.id);setAdding(false);
@@ -45,8 +49,9 @@ export function SensorWorkspace({transport,enabled=true,onDetailChange,createRer
const connected=inventory?.items.filter(v=>readOfflineInventory||v.online||sensorContribution(contributions,v)?.retainOffline)??[];
const editingCurrent=inventory?.items.find(v=>v.id===editing?.id);
const settingsDevice=editingCurrent??editing;
const settingsFacts=settingsDevice?sensorContribution(contributions,settingsDevice)?.settingsFacts?.(settingsDevice)??[]:[];
useEffect(()=>{onDetailChange?.(!!device);},[!!device,onDetailChange]);
const settingsFor=(item:Sensor)=>{const contribution=sensorContribution(contributions,item);return {supportsPreparation:contribution?.supportsPreparation!==false,supportsRenaming:contribution?.supportsRenaming,facts:contribution?.settingsFacts?.(item)};};
const modal=!!device&&sensorContribution(contributions,device)?.detailPresentation==='modal';
useEffect(()=>{onDetailChange?.(!!device&&!modal);},[!!device,modal,onDetailChange]);
const Detail=device?(sensorContribution(contributions,device)?.Detail??(device.kind?null:SensorDetail)):null;
const inventoryView=<>
{!renderBoard&&<div className="sensor-actions sensor-inventory-toolbar"><StatusBadge tone={fresh&&enabled?'success':'neutral'}>{!enabled?'БК недоступен':fresh?'Сведения с БК':'Нет свежих сведений'}</StatusBadge><div className="sensor-actions">{transport.enrollment&&wirelessContributions(contributions).length>0&&<IconButton label="Подключить беспроводное устройство к БК" disabled={!enabled} onClick={()=>setAdding(true)}><Icon name="plus"/></IconButton>}<IconButton label="Обновить устройства" disabled={!enabled&&!readOfflineInventory} onClick={()=>{void refresh();}}><Icon name="refresh"/></IconButton></div></div>}
@@ -56,14 +61,16 @@ export function SensorWorkspace({transport,enabled=true,onDetailChange,createRer
const configured=item.configured??item.snapshot.enrollment==='enrolled';
const prep=devicePreparation(inventory!,item);
const status=(sensorContribution(contributions,item)?.status??sensorStatus)(item,enabled&&fresh);const label=busy?(operation?.action_id==='prepare'?'Подготовка устройства':'Выполняется команда'):status.label;
return <li key={item.id}><ResourceRow icon={<Icon name={sensorContribution(contributions,item)?.icon??'camera'}/>} title={item.name} description={item.model} metadata={<span>{item.connection_label||`USB ${item.usb}`}</span>} statusPlacement={configured?'leading':'trailing'} aria-busy={busy} progress={busy&&pending==='prepare'?preparationProgress(prep,label):undefined} status={<StatusBadge variant={configured?'indicator':'badge'} tone={status.tone} aria-label={label} title={label}>{configured?null:label}</StatusBadge>} actions={<><SensorRowActions device={item} actions={sensorContribution(contributions,item)?.rowActions?.(item)} enabled={enabled&&fresh} busy={busy} pending={pending} perform={(name,parameters)=>void action(item,name,parameters)}/>{!configured&&sensorContribution(contributions,item)?.supportsPreparation!==false&&<IconButton label={`Подготовить и проверить: ${item.name}`} disabled={!enabled||!fresh||busy||item.initializable===false||item.preparation_safe===false||!item.online||item.snapshot.acquisition==='streaming'||item.snapshot.acquisition==='stopping'} onClick={()=>void action(item,'prepare')}><Icon name="download"/></IconButton>}{sensorContribution(contributions,item)?.supportsRenaming!==false&&<IconButton label={`Настройки: ${item.name}`} disabled={!enabled||!fresh||busy} onClick={()=>{setEditing(item);setName(item.name);}}><Icon name="settings"/></IconButton>}{sensorContribution(contributions,item)?.detailLabel?<Button disabled={!item.prepared||busy} onClick={()=>setSelected(item.id)}>{sensorContribution(contributions,item)?.detailLabel}</Button>:<IconButton label={`Просмотр: ${item.name}`} disabled={!item.prepared||busy} onClick={()=>setSelected(item.id)}><Icon name="eye"/></IconButton>}</>}/></li>;})}</ResourceList>
return <li key={item.id}><ResourceRow icon={<Icon name={sensorContribution(contributions,item)?.icon??'camera'}/>} title={item.name} description={item.model} metadata={<span>{item.connection_label||`USB ${item.usb}`}</span>} statusPlacement={configured?'leading':'trailing'} aria-busy={busy} progress={busy&&pending==='prepare'?preparationProgress(prep,label):undefined} status={<StatusBadge variant={configured?'indicator':'badge'} tone={status.tone} aria-label={label} title={label}>{configured?null:label}</StatusBadge>} actions={<><SensorRowActions device={item} actions={sensorContribution(contributions,item)?.rowActions?.(item)} enabled={enabled&&fresh} busy={busy} pending={pending} perform={(name,parameters)=>void action(item,name,parameters)}/>{!configured&&sensorContribution(contributions,item)?.supportsPreparation!==false&&<IconButton label={`Подготовить и проверить: ${item.name}`} disabled={!enabled||!fresh||busy||item.initializable===false||item.preparation_safe===false||!item.online||item.snapshot.acquisition==='streaming'||item.snapshot.acquisition==='stopping'} onClick={()=>void action(item,'prepare')}><Icon name="download"/></IconButton>}{sensorContribution(contributions,item)?.settingsInDetail?<IconButton label={`${sensorContribution(contributions,item)?.detailLabel??'Настройки'}: ${item.name}`} disabled={busy} onClick={()=>setSelected(item.id)}><Icon name="settings"/></IconButton>:<>{sensorContribution(contributions,item)?.supportsRenaming!==false&&<IconButton label={`Настройки: ${item.name}`} disabled={!enabled||!fresh||busy} onClick={()=>{setEditing(item);}}><Icon name="settings"/></IconButton>}{sensorContribution(contributions,item)?.detailLabel?<Button disabled={!item.prepared||busy} onClick={()=>setSelected(item.id)}>{sensorContribution(contributions,item)?.detailLabel}</Button>:<IconButton label={`Просмотр: ${item.name}`} disabled={!item.prepared||busy} onClick={()=>setSelected(item.id)}><Icon name="eye"/></IconButton>}</>}</>}/></li>;})}</ResourceList>
{!inventory&&enabled&&!error?<LoadingRegion loading label="Получение устройств БК"/>:!enabled?(!renderBoard?<SettingsCard title="БК недоступен" description="Показаны последние сохранённые устройства. Их состояние обновится после восстановления связи."/>:null):inventory&&connected.length===0?<SettingsCard title="Поддерживаемые устройства не обнаружены" description="Подключите устройство кабелем или добавьте беспроводное устройство через плюс."/>:null}
<SensorPreparations inventory={enabled&&fresh?inventory:null}/>
</>;
const boardSettings=contributions.filter(value=>value.BoardSettings&&contributions.filter(other=>other.kind===value.kind).length===1);
const settingsView=<div className="sensor-content">{boardSettings.map(contribution=>{const View=contribution.BoardSettings!;return <View key={contribution.kind} inventory={inventory} transport={transport} enabled={enabled&&fresh} refresh={refresh} failure={failure} openDevice={setSelected}/>;})}{!boardSettings.length&&<p>Для подключённых устройств общие настройки пока недоступны.</p>}</div>;
return <div className="sensor-workspace">{device?Detail?<Detail key={device.snapshot.context.session_id} enabled={enabled&&fresh} device={device} transport={transport} back={()=>setSelected(null)} refresh={refresh} failure={failure} createRerunHost={createRerunHost} reconnect={transport.enrollment?()=>setAdding(true):undefined}/>:<div className="sensor-content"><Button onClick={()=>setSelected(null)}>К устройствам</Button><SettingsCard title="Просмотр устройства недоступен" description="Интеграция этого устройства не установлена."/></div>:(renderBoard?renderBoard({settings:settingsView,devices:inventoryView,showingSavedDevices:connected.length>0&&(!enabled||!fresh),refresh,addDevice:()=>setAdding(true),canAddDevice:!!transport.enrollment&&wirelessContributions(contributions).length>0}):board?<BoardSections {...board} settings={settingsView} devices={inventoryView}/>:inventoryView)}
<Window open={editing!==null} title="Настройки устройства" onClose={()=>setEditing(null)} footer={<WindowFooterActions><Button disabled={localBusy.has(editing?.id??'')} onClick={()=>setEditing(null)}>Отмена</Button><Button loading={localBusy.get(editing?.id??'')==='rename'} disabled={localBusy.has(editing?.id??'')||!name.trim()||!enabled||!fresh} onClick={()=>{if(editing)void action(editing,'rename',{name});}}>Сохранить</Button></WindowFooterActions>}><div className="sensor-content"><TextField label="Название устройства" value={name} maxLength={80} onChange={e=>setName(e.target.value)} disabled={localBusy.has(editing?.id??'')}/>{settingsFacts.map(fact=><TextField key={fact.id} label={fact.label} value={fact.value} readOnly/>)}{editing&&sensorContribution(contributions,editing)?.supportsPreparation!==false&&(editing.configured??editing.snapshot.enrollment==='enrolled')&&<ResourceRow title="Конфигурация на БК" description="Повторно развернуть и проверить встроенный драйвер устройства." actions={<Button disabled={localBusy.has(editing?.id??'')||!enabled||!fresh||!editingCurrent?.online||editingCurrent?.initializable===false||editingCurrent?.preparation_safe===false||['streaming','starting','stopping'].includes(editingCurrent?.snapshot.acquisition??'offline')} onClick={()=>{const target=editing;setEditing(null);void action(target,'prepare');}}>Обновить</Button>}/>}</div></Window>
const detail=device&&Detail?<Detail key={device.snapshot.context.session_id} enabled={enabled&&fresh} previewEnabled={previewEnabled} device={device} generalSettings={settingsFor(device)} transport={transport} back={()=>setSelected(null)} navigationTarget={detailActionsTarget} refresh={refresh} failure={failure} createRerunHost={createRerunHost} reconnect={transport.enrollment?()=>setAdding(true):undefined}/>:null;
return <div className="sensor-workspace">{device&&!modal?detail??<div className="sensor-content"><SensorDetailBack back={()=>setSelected(null)} target={detailActionsTarget}/><SettingsCard title="Просмотр устройства недоступен" description="Интеграция этого устройства не установлена."/></div>:(renderBoard?renderBoard({settings:settingsView,devices:inventoryView,showingSavedDevices:connected.length>0&&(!enabled||!fresh),refresh,addDevice:()=>setAdding(true),canAddDevice:!!transport.enrollment&&wirelessContributions(contributions).length>0}):board?<BoardSections {...board} settings={settingsView} devices={inventoryView}/>:inventoryView)}
{modal&&detail}
<Window open={editing!==null} title="Настройки устройства" onClose={()=>{if(!editingBusy)setEditing(null);}}>{settingsDevice&&<SensorGeneralSettings key={settingsDevice.id} device={settingsDevice} transport={transport} enabled={enabled&&fresh} refresh={refresh} failure={failure} generalSettings={settingsFor(settingsDevice)} onBusyChange={setEditingBusy} onSaved={()=>setEditing(null)}/>}</Window>
{adding&&transport.enrollment&&wirelessContributions(contributions).length>0&&<WirelessEnrollmentWindow enabled={enabled} contributions={contributions} transport={transport.enrollment} onClose={()=>setAdding(false)} onChange={()=>{void refresh();}} onComplete={completeEnrollment}/>}
<ToastStack items={error?[{id:'sensor-error',tone:'error',title:error,durationMs:null}]:[]} onDismiss={()=>setError('')}/>
</div>;
+16 -2
View File
@@ -1,9 +1,12 @@
export interface SensorProfile { id: string; sensor: number; stream: string; index: number; format: string; fps: number; width?: number; height?: number }
export interface SensorOption { id: string; sensor: string; label: string; value: number; min: number; max: number; step: number; read_only: boolean }
export interface Sensor {
transport_generation?:string;
preview_priority_v1?:boolean;
kind?:string; connection_label?:string; control?:{generation:number;revision:number;phase:string;can_start:boolean;can_stop?:boolean;can_verify?:boolean;network_applied?:boolean;reason_code?:string|null;acquisition_id:string|null;acquisition_phase?:string};
live_settings?: Record<string,unknown>;
camera_status?: Record<string,unknown>;
can_status?: Record<string,unknown>;
vesc_status?: Record<string,unknown>;
id: string; name: string; model: string; initializable?:boolean; preparation_safe?:boolean; prepared: boolean; configured?: boolean; verified: boolean; online: boolean; usb: string; firmware?: string; playback_id?: string | null;
snapshot: {context: {session_id: string; device: {device_id: string}; execution: {node_id: string}}; acquisition: string; enrollment: string; message?: string};
@@ -33,7 +36,18 @@ export interface SensorCommand {
idempotency_key:string; parameters:Record<string,unknown>;
}
export interface SensorOperation {state:string;error?:string;result?:unknown}
export class SensorOperationError extends Error {
constructor(readonly action:string,readonly state:string,message:string){super(message);this.name='SensorOperationError';}
}
export interface SensorLiveReading {
id:string;uuid:string;session_id:string;sample_time_ms:number;observed_at:string;age_ms:number;
values:Record<string,number|boolean>;
}
export interface SensorLiveFrame {fresh:boolean;instance?:string;devices?:SensorLiveReading[]}
export interface SensorTransport {
previewEvidence?:(sample:Record<string,unknown>)=>void;
previewRole?:(deviceId:string)=>boolean;
liveTelemetry?:(signal:AbortSignal)=>Promise<SensorLiveFrame>;
configurationArchive?: {
list:(deviceId:string,before?:string)=>Promise<{items:ConfigurationVersion[];next:string|null}>;
read:(deviceId:string,versionId:string)=>Promise<Record<string,unknown>>;
@@ -43,7 +57,7 @@ export interface SensorTransport {
read: (peer:string, after:number, signal:AbortSignal) => Promise<Response>;
};
enrollment?: import('./enrollment').EnrollmentTransport;
inventory: () => Promise<SensorInventory>;
inventory: (signal?:AbortSignal) => Promise<SensorInventory>;
subscribe?: (receive:(value:SensorInventory)=>void, unavailable:()=>void) => (()=>void);
submit: (value:SensorCommand) => Promise<SensorOperation>;
operation: (id:string) => Promise<SensorOperation>;
@@ -62,6 +76,6 @@ export async function perform<T>(transport:SensorTransport,device:Sensor,action:
if(Date.now()>deadline) throw new Error('Подтверждение пока не получено. Обновите состояние устройства.');
await new Promise(resolve=>setTimeout(resolve,1000));value=await transport.operation(request.operation_id);
}
if(value.state!=='complete') throw new Error(value.error||'Операция не завершена. Обновите состояние устройства.');
if(value.state!=='complete') throw new SensorOperationError(action,value.state,value.error||'Операция не завершена. Обновите состояние устройства.');
return value.result as T;
}
+6 -2
View File
@@ -5,9 +5,10 @@ import type {EnrollmentTransport} from './enrollment';
import type {RerunHostFactory} from './rerunHost';
export interface SensorDetailProps {
device:Sensor; transport:SensorTransport; enabled:boolean;
back:()=>void; refresh:()=>Promise<void>; failure:(error:unknown)=>void;
device:Sensor; transport:SensorTransport; enabled:boolean; previewEnabled?:boolean;
back:()=>void; navigationTarget?:HTMLElement|null; refresh:()=>Promise<void>; failure:(error:unknown)=>void;
createRerunHost?:RerunHostFactory; reconnect?:()=>void;
generalSettings?:{supportsPreparation:boolean;supportsRenaming?:boolean;facts?:readonly {id:string;label:string;value:string}[]};
}
export interface SensorEnrollmentProps {
transport:EnrollmentTransport; onClose:()=>void; onChange:()=>void;
@@ -24,6 +25,9 @@ export interface SensorUiContribution {
supportsPreparation:boolean;
supportsRenaming?:boolean;
detailLabel?:string;
detailPresentation?:'modal';
/** The detail modal includes generic settings and owns the single gear entry. */
settingsInDetail?:boolean;
settingsFacts?:(device:Sensor)=>readonly {id:string;label:string;value:string}[];
rowActions?:(device:Sensor)=>readonly SensorRowAction[];
status?:(device:Sensor,fresh:boolean)=>{label:string;tone:'neutral'|'success'|'warning'|'danger'};
@@ -0,0 +1,75 @@
import type {SensorInventory,SensorTransport} from './contracts';
/** One stream, one in-flight read and one timer per mounted inventory owner.
* Both servers emit inventory heartbeats at least every 15 seconds.
* Freshness expires independently of EventSource's connection/error events.
*/
export class InventoryObserver {
private active=true;
private generation=0;
private revision=0;
private latest:SensorInventory|null=null;
private lastData=-Infinity;
private lastStream=0;
private retryAt=0;
private pollAt=0;
private streaming=false;
private closeStream:(()=>void)|undefined;
private pending:Promise<SensorInventory|null>|undefined;
private abort:AbortController|undefined;
private timer:ReturnType<typeof setInterval>;
constructor(private transport:SensorTransport,
private receive:(value:SensorInventory)=>void,
private stale:()=>void,
private failure:(error:unknown)=>void,
private now:()=>number=()=>performance.now()){
this.connect();void this.refresh();
this.timer=setInterval(()=>this.tick(),1000);
}
private accept(value:SensorInventory){
this.latest=value;this.revision++;this.lastData=this.now();this.receive(value);
}
private disconnect(){
this.generation++;this.streaming=false;
const close=this.closeStream;this.closeStream=undefined;close?.();
this.retryAt=this.now()+3000;this.stale();
}
private connect(){
if(!this.active||!this.transport.subscribe)return;
const generation=++this.generation;this.streaming=true;this.lastStream=this.now();
try{
const close=this.transport.subscribe(value=>{
if(!this.active||this.generation!==generation)return;
this.lastStream=this.now();this.accept(value);
},()=>{if(this.active&&this.generation===generation)this.disconnect();});
if(this.active&&this.generation===generation)this.closeStream=close;else close();
}catch(error){this.disconnect();this.failure(error);}
}
private tick(){
if(this.now()-this.lastData>=20000)this.stale();
if(this.streaming&&this.now()-this.lastStream>=20000)this.disconnect();
if(!this.streaming){
if(this.now()>=this.pollAt)void this.refresh();
if(this.now()>=this.retryAt)this.connect();
}
}
refresh():Promise<SensorInventory|null>{
if(!this.active)return Promise.resolve(null);
if(this.pending)return this.pending;
const revision=this.revision,abort=new AbortController();this.abort=abort;
// Adapters honor cancellation and also retain their own bounded timeout.
const deadline=setTimeout(()=>abort.abort(),12000);
this.pending=Promise.resolve().then(()=>this.transport.inventory(abort.signal)).then(value=>{
if(!this.active||abort.signal.aborted)return null;
if(this.revision!==revision)return this.latest;
this.accept(value);return value;
}).catch(error=>{
if(this.active&&this.revision===revision){this.stale();this.failure(error);}return null;
}).finally(()=>{clearTimeout(deadline);this.pending=undefined;this.abort=undefined;this.pollAt=this.now()+3000;});
return this.pending;
}
close(){
this.active=false;clearInterval(this.timer);this.abort?.abort();
this.generation++;const close=this.closeStream;this.closeStream=undefined;close?.();
}
}
+3 -1
View File
@@ -8,10 +8,12 @@ export interface ObservationHeaderTargets {statusTarget:HTMLElement;actionsTarge
export interface CameraPresentation {rotations:Record<string,number>;panoramaYaw:number}
export interface SensorObservationProps {
presentation?:CameraPresentation;onPresentationChange?:(value:CameraPresentation)=>void;
device:Sensor;transport:SensorTransport;enabled:boolean;createRerunHost:RerunHostFactory;
device:Sensor;transport:SensorTransport;enabled:boolean;fresh?:boolean;createRerunHost:RerunHostFactory;
views:({id:string;layer:string;target:HTMLElement}&ObservationHeaderTargets)[];
}
export interface SensorObservationContribution {
/** The session separates fresh control admission from existing media progress. */
independentMediaLiveness?:boolean;
views:(device:Sensor)=>SensorObservationView[];
Session:ComponentType<SensorObservationProps>;
catalog?:{label:string;views:SensorObservationView[]};
@@ -22,3 +22,10 @@ export function startCameraObservation(device:Sensor,transport:SensorTransport){
await perform(transport,current,'start',{record:false});
});
}
/** A new peer requires fresh control state; an established peer uses media liveness. */
export async function currentPreviewDevice(device:Sensor,transport:SensorTransport):Promise<Sensor>{
const current=await currentObservationDevice(device,transport);
if(current.snapshot.acquisition!=='streaming')throw new Error('Просмотр остановлен.');
return current;
}
+20
View File
@@ -0,0 +1,20 @@
/** Numeric projection of the existing peer; no image, SDP, second stream or timer. */
const object=(value:unknown):Record<string,unknown>=>value&&typeof value==='object'&&!Array.isArray(value)?value as Record<string,unknown>:{};
export function previewEvidence(peer:string,session:string,runtime:unknown,timing:unknown,width:number,height:number,sourceAge:number){
const r=object(runtime),b=object(r.media_budget),e=object(b.egress),d=object(r.decoder),t=object(timing),reset=object(b.last_encoder_reset);
const result:Record<string,unknown>={peer_id:peer,device_session:session};
const fields:Record<string,unknown>={width,height,source_age_ms:sourceAge,sender_mono_ms:b.sample_mono_ms,
allocation_bps:b.allocation_bps,target_bps:b.target_bps,encoder_bps:b.encoder_bps,receiver_bps:b.receiver_bps,
max_width:b.max_width,max_fps:b.max_fps,encoder_frames:b.encoder_frames,encoder_reinitializations:b.encoder_reinitializations,
encode_ms:b.encode_ms,sent_bytes:e.sent_bytes,queue_dropped:e.queue_dropped,expired_frames:e.expired_frames,
expired_datagrams:e.expired_datagrams,stale_rtp_packets:e.stale_rtp_packets,max_permit_wait_ms:e.max_permit_wait_ms,
decoder_errors:d.decode_errors,decoder_frames:d.frames,decoder_gaps:d.gaps,
receiver_sampled_at_ms:t.sampled_at_ms,interval_ms:t.interval_ms,fps:t.fps,mbps:t.mbps,
round_trip_ms:t.round_trip_ms,jitter_buffer_ms:t.jitter_buffer_ms,
requested_jitter_ms:t.requested_jitter_ms,jitter_target_ms:t.jitter_target_ms,jitter_minimum_ms:t.jitter_minimum_ms,
decode_ms:t.decode_ms,processing_ms:t.processing_ms,assembly_ms:t.assembly_ms,frames_dropped:t.frames_dropped,
packets_lost:t.packets_lost,freezes:t.freezes,reset_frame:reset.frame,reset_mono_ms:reset.mono_ms};
for(const [key,value] of Object.entries(fields))if(typeof value==='number'&&Number.isFinite(value)&&value>=0&&value<=Number.MAX_SAFE_INTEGER)result[key]=value;
if(b.mode==='observing'||b.mode==='control_reserved')result.mode=b.mode;
return result;
}
+21 -5
View File
@@ -3,19 +3,35 @@ export class PreviewLiveness {
private lastFrame:number|null=null;
private sourceSeen=Number.NEGATIVE_INFINITY;
private staleSince:number|null=null;
constructor(private connectedAt:number){}
connected(now:number){this.connectedAt=now;}
frame(now:number){this.lastFrame=now;}
private connectedAt:number|null=null;
private budgetPauseUntil=0;
private budgetResumeAt:number|null=null;
constructor(private negotiatedAt:number){}
negotiated(now:number){this.negotiatedAt=now;}
connected(now:number){this.connectedAt??=now;}
frame(now:number){this.connected(now);this.lastFrame=now;}
allocation(paused:boolean,now:number){
if(paused)this.budgetPauseUntil=now+3000;
else if(this.budgetPauseUntil){this.budgetPauseUntil=0;this.budgetResumeAt=now;}
}
source(fresh:boolean,now:number){
this.sourceSeen=now;
this.staleSince=fresh?null:this.staleSince??now;
}
state(now:number):'live'|'waiting'|'delayed'|'source-stalled'|'peer-stalled'{
state(now:number):'connecting'|'live'|'waiting'|'delayed'|'source-stalled'|'peer-stalled'{
// SDP is only signaling. ICE/DTLS can still be establishing the private route.
if(this.connectedAt===null)return now-this.negotiatedAt>30000?'peer-stalled':'connecting';
if(this.staleSince!==null&&now-this.sourceSeen<3000){
return now-this.staleSince>=12000?'source-stalled':'delayed';
}
// A fresh allocation pause is not a dead peer and never claims live imagery.
// Missing hints still expire normally; actual source-stall evidence wins above.
if(now<this.budgetPauseUntil)return 'waiting';
if(this.budgetResumeAt!==null&&(this.lastFrame===null||this.lastFrame<this.budgetResumeAt)&&now-this.budgetResumeAt<8000)return 'waiting';
const elapsed=now-(this.lastFrame??this.connectedAt);
if(elapsed>8000)return 'peer-stalled';
// A short route interruption must not tear down an established decoder.
// The image is still marked delayed after 2 s; this only bounds reconnection.
if(elapsed>(this.lastFrame===null?8000:30000))return 'peer-stalled';
if(this.lastFrame===null)return 'waiting';
return elapsed>2000?'delayed':'live';
}
+30
View File
@@ -0,0 +1,30 @@
/** Latest interval only. Counters stay local and never include ICE addresses or SDP. */
export class PreviewMetrics {
private previous:Record<string,number>|null=null;
private source:unknown=null;
sample(report:RTCStatsReport){
let video:Record<string,unknown>|undefined,roundTrip:number|null=null;
report.forEach(value=>{
if(value.type==='inbound-rtp'&&value.kind==='video')video=value;
if(value.type==='candidate-pair'&&value.state==='succeeded'&&value.nominated&&Number.isFinite(value.currentRoundTripTime))roundTrip=value.currentRoundTripTime*1000;
});
if(!video)return null;
const numeric:Record<string,number>={};
for(const key of ['timestamp','bytesReceived','framesDecoded','framesDropped','packetsReceived','packetsLost','jitterBufferDelay','jitterBufferTargetDelay','jitterBufferMinimumDelay','jitterBufferEmittedCount','totalDecodeTime','totalProcessingDelay','totalAssemblyTime','framesAssembledFromMultiplePackets','freezeCount','totalFreezesDuration']){
const value=video[key];if(typeof value==='number'&&Number.isFinite(value))numeric[key]=value;
}
const before=this.source===video.id&&this.previous&&numeric.timestamp>this.previous.timestamp?this.previous:null;this.previous=numeric;this.source=video.id;
const delta=(key:string)=>before&&key in before&&key in numeric&&numeric[key]>=before[key]?numeric[key]-before[key]:null;
const interval=delta('timestamp'),frames=delta('framesDecoded');
const average=(sum:string,count:string)=>{const a=delta(sum),b=delta(count);return a!==null&&b!==null&&b>0?Math.round(a*1000/b):null;};
const bytes=delta('bytesReceived');
return {sampled_at_ms:Math.round(performance.now()),interval_ms:interval,round_trip_ms:roundTrip===null?null:Math.round(roundTrip),
fps:interval&&frames!==null?Math.round(frames*10000/interval)/10:null,
mbps:interval&&bytes!==null?Math.round(bytes*8/interval)/1000:null,
jitter_buffer_ms:average('jitterBufferDelay','jitterBufferEmittedCount'),jitter_target_ms:average('jitterBufferTargetDelay','jitterBufferEmittedCount'),jitter_minimum_ms:average('jitterBufferMinimumDelay','jitterBufferEmittedCount'),decode_ms:average('totalDecodeTime','framesDecoded'),
processing_ms:average('totalProcessingDelay','framesDecoded'),assembly_ms:average('totalAssemblyTime','framesAssembledFromMultiplePackets'),
packets_lost:delta('packetsLost'),frames_dropped:delta('framesDropped'),freezes:delta('freezeCount'),
// This is transport/decoder timing, never a claim of capture-to-screen age.
scope:'receiver-interval'};
}
}
+6
View File
@@ -0,0 +1,6 @@
/** Request minimum live-video buffering; the browser retains its network safety floor. */
export function configurePreviewPlayout(receiver:{track?:{kind:string};jitterBufferTarget?:number|null}|undefined,live:boolean):number|null{
if(!live||receiver?.track?.kind!=='video'||!('jitterBufferTarget' in receiver))return null;
try{receiver.jitterBufferTarget=0;return receiver.jitterBufferTarget===0?0:null;}
catch{return null;} // Older/partial implementations must keep working with their default policy.
}
@@ -0,0 +1,14 @@
/** One reconnect timer per mounted viewing peer. Background pages do not retry. */
export function previewReconnect(options:{visible:()=>boolean;retry:()=>void;now:()=>number;schedule:(run:()=>void,delay:number)=>unknown;cancel:(timer:unknown)=>void}){
let disposed=false,pending=false,deadline=0,timer:unknown;
const pause=()=>{if(timer!==undefined){options.cancel(timer);timer=undefined;}};
const resume=()=>{
if(disposed||!pending||timer!==undefined||!options.visible())return;
timer=options.schedule(()=>{timer=undefined;if(disposed||!pending||!options.visible())return;pending=false;options.retry();},Math.max(0,deadline-options.now()));
};
return {schedule(delay:number){if(disposed)return;pause();pending=true;deadline=options.now()+delay;resume();},
recovered(){if(disposed||!pending)return;pause();deadline=options.now();resume();},
resume,pause,dispose(){disposed=true;pending=false;pause();}};
}
/** Retry only negotiation, never camera commands; rate stays bounded during long outages. */
export const previewRetryDelay=(attempt:number)=>Math.min(30000,2000*2**Math.min(4,Math.max(0,attempt)));
+16 -5
View File
@@ -1,24 +1,35 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import type {Sensor} from './contracts';
import {observationSession} from './observationStart';
import {previewReconnect,previewRetryDelay} from './previewReconnect';
/** One automatic activation per mounted view/session; failures require explicit retry. */
export function useObservationStart(device:Sensor,enabled:boolean,active:boolean,start:()=>Promise<unknown>){
/** Starts are serialized; opt-in observation recovery always rereads device state. */
export function useObservationStart(device:Sensor,enabled:boolean,active:boolean,start:()=>Promise<unknown>,recover=false){
const scope=observationSession(device),latest=useRef({scope,enabled,start});latest.current={scope,enabled,start};
const mounted=useRef(false),attempted=useRef(''),running=useRef(false);
const attempts=useRef(0),[attempt,setAttempt]=useState(0);
const [pending,setPending]=useState(false),[error,setError]=useState('');
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
useEffect(()=>{setError('');},[scope]);
useEffect(()=>{attempts.current=0;setError('');},[scope]);
const retry=useCallback(async()=>{
const value=latest.current;if(!value.enabled||running.current)return;
attempted.current=value.scope;running.current=true;setPending(true);setError('');
attempted.current=value.scope;running.current=true;setPending(true);setError('');setAttempt(v=>v+1);
try{await value.start();}catch(reason){if(mounted.current&&latest.current.scope===value.scope)setError(reason instanceof Error?reason.message:'Не удалось начать просмотр.');}
finally{running.current=false;if(mounted.current)setPending(false);}
},[]);
useEffect(()=>{
if(!enabled){attempted.current='';return;}
if(active){attempted.current=scope;setError('');return;}
if(active){attempted.current=scope;attempts.current=0;setError('');return;}
if(attempted.current!==scope)void retry();
},[scope,enabled,active,retry,pending]);
useEffect(()=>{
if(!recover||!enabled||active||pending||!error)return;
const timer=previewReconnect({visible:()=>document.visibilityState!=='hidden',retry:()=>void retry(),now:()=>performance.now(),schedule:(run,delay)=>setTimeout(run,delay),cancel:id=>clearTimeout(id as ReturnType<typeof setTimeout>)});
timer.schedule(previewRetryDelay(attempts.current++));
const visibility=()=>{if(document.visibilityState==='hidden')timer.pause();else timer.resume();};
const online=()=>timer.recovered();
document.addEventListener('visibilitychange',visibility);window.addEventListener('online',online);
return()=>{timer.dispose();document.removeEventListener('visibilitychange',visibility);window.removeEventListener('online',online);};
},[scope,enabled,active,pending,error,attempt,recover,retry]);
return {pending,error,retry};
}
+44 -21
View File
@@ -2,15 +2,22 @@ import {useEffect,useRef,useState,type RefObject} from 'react';
import {perform,type Sensor,type SensorTransport} from './contracts';
import {PreviewLiveness} from './previewLiveness';
import {previewPlayback} from './previewPlayback';
import {currentPreviewDevice} from './observationStart';
import {PreviewMetrics} from './previewMetrics';
import {configurePreviewPlayout} from './previewPlayout';
import {previewEvidence} from './previewEvidence';
import {previewReconnect,previewRetryDelay} from './previewReconnect';
export interface SensorPreviewTelemetry {points?:number[];motion?:Record<string,{x:number;y:number;z:number}>;frame_age_ms?:number;fresh?:boolean}
export interface SensorPreviewTelemetry {points?:number[];motion?:Record<string,{x:number;y:number;z:number}>;frame_age_ms?:number;fresh?:boolean;media_budget?:{target_bps?:number}}
/** One viewing peer; capture ownership belongs to the device session. */
export function useSensorPreview(device:Sensor,layer:string,transport:SensorTransport,video:RefObject<HTMLVideoElement|null>,enabled=true,generation=0){
const [state,setState]=useState('Подключение просмотра');
const [telemetry,setTelemetry]=useState<SensorPreviewTelemetry>({});
const [error,setError]=useState(''),[live,setLive]=useState(false),[hasFrame,setHasFrame]=useState(false);
const presented=useRef<number|null>(null),[frameAgeMS,setFrameAgeMS]=useState<number|null>(null);
const [sourceStalled,setSourceStalled]=useState(false),[retryGeneration,setRetryGeneration]=useState(0);const retries=useRef(0);
useEffect(()=>{setHasFrame(false);},[device.id,device.snapshot.context.session_id,layer]);
useEffect(()=>{setHasFrame(false);presented.current=null;setFrameAgeMS(null);},[device.id,device.snapshot.context.session_id,layer]);
useEffect(()=>{const timer=setInterval(()=>setFrameAgeMS(presented.current===null?null:Math.max(0,performance.now()-presented.current)),1000);return()=>clearInterval(timer);},[]);
useEffect(()=>{retries.current=0;},[device.id,device.snapshot.context.session_id,layer,enabled,generation]);
useEffect(()=>{
setTelemetry({});setError('');setLive(false);setSourceStalled(false);
@@ -18,61 +25,77 @@ export function useSensorPreview(device:Sensor,layer:string,transport:SensorTran
if(device.snapshot.acquisition!=='streaming'){setState('Просмотр остановлен');return;}
if(typeof RTCPeerConnection==='undefined'){setState('Просмотр не поддерживается браузером');return;}
let cancelled=false,terminal=false,peerID='',closedPeerID='',firstLive=0,statsPending=false;
let frameHandle:number|undefined,iceTimer:ReturnType<typeof setTimeout>|undefined,retryTimer:ReturnType<typeof setTimeout>|undefined;
let runtimeEvidence:unknown=null,runtimeReceived=0,receiverTarget:number|null=null;
let frameHandle:number|undefined,iceTimer:ReturnType<typeof setTimeout>|undefined;
const element=video.current,health=new PreviewLiveness(performance.now());
const playback=previewPlayback(element);
const reconnect=previewReconnect({visible:()=>document.visibilityState!=='hidden',retry:()=>{if(!cancelled)setRetryGeneration(v=>v+1);},now:()=>performance.now(),schedule:(run,delay)=>setTimeout(run,delay),cancel:timer=>clearTimeout(timer as ReturnType<typeof setTimeout>)});
const resumePlayback=()=>{if(!cancelled&&!terminal)playback.resume();};
document.addEventListener('visibilitychange',resumePlayback);
const pc=new RTCPeerConnection({iceServers:[]});
const pc=new RTCPeerConnection({iceServers:[]}),metrics=new PreviewMetrics();
const data=pc.createDataChannel('sensor',{ordered:false,maxRetransmits:0});
const closePeer=()=>{if(peerID&&closedPeerID!==peerID){closedPeerID=peerID;void perform(transport,device,'close-peer',{peer_id:peerID}).catch(()=>undefined);}};
const fail=(reason:string)=>{
if(cancelled||terminal)return;
terminal=true;setLive(false);pc.close();closePeer();
if(retries.current<4){const delay=2000*2**retries.current++;setState('Восстановление просмотра');retryTimer=setTimeout(()=>{if(!cancelled)setRetryGeneration(v=>v+1);},delay);}
else{setState('Просмотр недоступен');setError(reason);}
setState('Восстановление просмотра');setError(reason);
reconnect.schedule(previewRetryDelay(retries.current));retries.current=Math.min(4,retries.current+1);
};
const visibility=()=>{if(document.visibilityState==='hidden')reconnect.pause();else{reconnect.resume();resumePlayback();}};
const pagehide=()=>{if(!cancelled&&!terminal)fail('Просмотр приостановлен браузером.');reconnect.pause();};
const pageshow=()=>{reconnect.resume();resumePlayback();};
const online=()=>{reconnect.recovered();resumePlayback();};
document.addEventListener('visibilitychange',visibility);window.addEventListener('pagehide',pagehide);window.addEventListener('pageshow',pageshow);window.addEventListener('online',online);
const publish=(checkPeer=false)=>{
if(cancelled||terminal)return;
const now=performance.now(),value=health.state(now),paused=element?.paused&&document.visibilityState!=='hidden';
setFrameAgeMS(presented.current===null?null:Math.max(0,now-presented.current));
setLive(value==='live'&&!paused);setSourceStalled(value==='source-stalled'&&document.visibilityState!=='hidden');
if(value==='live'&&!paused){firstLive||=now;if(now-firstLive>15000)retries.current=0;setState(device.playback_id?'Исходная запись':'Прямой эфир');}
else if(paused&&value==='live'){firstLive=0;setState('Восстановление просмотра');}
else{firstLive=0;if(value==='delayed'||value==='source-stalled')setState('Задержка изображения');}
else{firstLive=0;if(value==='delayed'||value==='source-stalled')setState('Задержка изображения');else if(value==='connecting')setState('Подключение просмотра');else if(value==='waiting')setState('Ожидание изображения');}
if(checkPeer&&value==='peer-stalled'&&document.visibilityState!=='hidden')fail('Не удалось восстановить изображение. Повторите подключение.');
};
const markFrame=()=>{if(cancelled||terminal)return;health.frame(performance.now());setHasFrame(true);publish();};
const markFrame=()=>{if(cancelled||terminal)return;presented.current=performance.now();health.frame(presented.current);setHasFrame(true);publish();};
const frameSeen=()=>{markFrame();if(!cancelled&&!terminal)frameHandle=element?.requestVideoFrameCallback(frameSeen);};
if(layer!=='points'&&layer!=='motion')pc.addTransceiver('video',{direction:'recvonly'});
pc.ontrack=event=>{if(element){element.muted=true;element.srcObject=new MediaStream([event.track]);resumePlayback();if(typeof element.requestVideoFrameCallback==='function')frameHandle=element.requestVideoFrameCallback(frameSeen);}};
pc.onconnectionstatechange=()=>{if(!cancelled&&!terminal&&['failed','closed'].includes(pc.connectionState))fail('Не удалось получить изображение. Повторите подключение.');};
pc.ontrack=event=>{receiverTarget=configurePreviewPlayout(event.receiver,!device.playback_id);if(element){element.muted=true;element.srcObject=new MediaStream([event.track]);resumePlayback();if(typeof element.requestVideoFrameCallback==='function')frameHandle=element.requestVideoFrameCallback(frameSeen);}};
pc.onconnectionstatechange=()=>{if(cancelled||terminal)return;if(pc.connectionState==='connected'){health.connected(performance.now());publish();}else if(['failed','closed'].includes(pc.connectionState))fail('Не удалось получить изображение. Повторите подключение.');};
data.onmessage=event=>{
if(cancelled||terminal)return;
try{const value=JSON.parse(event.data);setTelemetry(value);if(typeof value.fresh==='boolean')health.source(value.fresh,performance.now());if(value.fresh!==false&&((layer==='points'&&Array.isArray(value.points))||(layer==='motion'&&value.motion)))markFrame();else publish();}
try{const value=JSON.parse(event.data);runtimeEvidence=value;runtimeReceived=performance.now();
// Bounded current engineering projection of the existing data channel;
// no second peer, polling endpoint, retained history or product controls.
if(element){const runtime=JSON.stringify({schema:'missioncore.preview-runtime/v1',peer_id:peerID,device_session:device.snapshot.context.session_id,received_at_ms:performance.now(),media_budget:value.media_budget,decoder:value.decoder});if(runtime.length<=8192)element.dataset.previewRuntime=runtime;else delete element.dataset.previewRuntime;}
setTelemetry(value);if(typeof value.media_budget?.target_bps==='number'&&Number.isFinite(value.media_budget.target_bps)&&value.media_budget.target_bps>=0)health.allocation(value.media_budget.target_bps===0,performance.now());if(typeof value.fresh==='boolean')health.source(value.fresh,performance.now());if(value.fresh!==false&&((layer==='points'&&Array.isArray(value.points))||(layer==='motion'&&value.motion)))markFrame();else publish();}
catch{/* Malformed telemetry cannot become a control result. */}
};
let decoded=0;
const timer=setInterval(()=>{
if(cancelled||terminal)return;
if(data.readyState==='open')data.send('keepalive');
if(data.readyState==='open'){data.send('keepalive');if(device.preview_priority_v1&&transport.previewRole)data.send(transport.previewRole(device.id)?'view:primary':'view:secondary');}
resumePlayback();
if(!pc.remoteDescription||statsPending)return;
// Signaling itself must be bounded. Previously a hung offer bypassed the
// liveness check entirely, holding the viewer in recovery until its RPC timed out.
if(!pc.remoteDescription){publish(true);return;}
if(statsPending)return;
// requestVideoFrameCallback can stop for a clipped/hidden decoder or an offscreen panel.
// RTP decode progress remains the authority for a functioning video channel.
if(element){statsPending=true;void pc.getStats().then(stats=>{if(cancelled||terminal)return;stats.forEach(value=>{if(value.type==='inbound-rtp'&&value.kind==='video'&&value.framesDecoded>decoded){decoded=value.framesDecoded;markFrame();}});publish(true);}).catch(()=>undefined).finally(()=>{statsPending=false;});}
if(element){statsPending=true;void pc.getStats().then(stats=>{if(cancelled||terminal)return;const sampled=metrics.sample(stats),timing=sampled?{...sampled,requested_jitter_ms:receiverTarget}:null;if(timing)element.dataset.previewTiming=JSON.stringify(timing);if(runtimeEvidence&&peerID){try{transport.previewEvidence?.(previewEvidence(peerID,device.snapshot.context.session_id,runtimeEvidence,timing,element.videoWidth,element.videoHeight,Math.max(0,performance.now()-runtimeReceived)));}catch{/* Evidence cannot interrupt preview. */}}stats.forEach(value=>{if(value.type==='inbound-rtp'&&value.kind==='video'&&value.framesDecoded>decoded){decoded=value.framesDecoded;health.frame(performance.now());if(typeof element.requestVideoFrameCallback!=='function')markFrame();}});publish(true);}).catch(()=>undefined).finally(()=>{statsPending=false;});}
else publish(true);
},2000);
setState('Подключение просмотра');
async function connect(){try{
await pc.setLocalDescription(await pc.createOffer());
if(pc.iceGatheringState!=='complete')await new Promise<void>((resolve,reject)=>{iceTimer=setTimeout(()=>reject(new Error('Не удалось подготовить канал просмотра.')),10000);pc.onicegatheringstatechange=()=>{if(pc.iceGatheringState==='complete'){clearTimeout(iceTimer);resolve();}};});
if(cancelled)return;
const answer=await perform<{peer_id:string;sdp:string;type:'answer'}>(transport,device,'offer',{sdp:pc.localDescription!.sdp,layer});peerID=answer.peer_id;
if(cancelled||terminal)return;
const current=await currentPreviewDevice(device,transport);
if(cancelled||terminal)return;
const answer=await perform<{peer_id:string;sdp:string;type:'answer'}>(transport,current,'offer',{sdp:pc.localDescription!.sdp,layer,...(device.preview_priority_v1&&transport.previewRole?{primary:transport.previewRole(device.id)}:{})},20000);peerID=answer.peer_id;
if(cancelled||terminal){closePeer();return;}
await pc.setRemoteDescription({type:'answer',sdp:answer.sdp});health.connected(performance.now());
await pc.setRemoteDescription({type:'answer',sdp:answer.sdp});health.negotiated(performance.now());
}catch(reason){fail(reason instanceof Error?reason.message:'Не удалось открыть просмотр.');}}
void connect();
return()=>{cancelled=true;playback.dispose();document.removeEventListener('visibilitychange',resumePlayback);clearTimeout(iceTimer);clearTimeout(retryTimer);clearInterval(timer);if(frameHandle!==undefined)element?.cancelVideoFrameCallback(frameHandle);pc.ontrack=null;pc.onconnectionstatechange=null;data.onmessage=null;pc.close();if(element)element.srcObject=null;closePeer();};
},[device.id,device.online,device.snapshot.context.session_id,device.snapshot.acquisition,device.playback_id,layer,transport,video,enabled,generation,retryGeneration]);
return {state,telemetry,error,live,hasFrame,sourceStalled};
return()=>{cancelled=true;playback.dispose();document.removeEventListener('visibilitychange',visibility);window.removeEventListener('pagehide',pagehide);window.removeEventListener('pageshow',pageshow);window.removeEventListener('online',online);reconnect.dispose();clearTimeout(iceTimer);clearInterval(timer);if(frameHandle!==undefined)element?.cancelVideoFrameCallback(frameHandle);pc.ontrack=null;pc.onconnectionstatechange=null;data.onmessage=null;pc.close();if(element){element.srcObject=null;delete element.dataset.previewTiming;delete element.dataset.previewRuntime;}closePeer();};
},[device.id,device.online,device.transport_generation,device.snapshot.context.session_id,device.snapshot.acquisition,device.playback_id,layer,transport,video,enabled,generation,retryGeneration]);
return {state,telemetry,error,live,hasFrame,sourceStalled,frameAgeMS};
}
@@ -1,17 +1,22 @@
import {Button,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import type {RecoveryStatus} from './model';
import './recovery.css';
export function RecoverySettings({value,online,enabled,pending,change}:{
value:RecoveryStatus; online:boolean; enabled:boolean; pending:boolean; change:(enabled:boolean)=>void;
export function RecoverySettings({value,online,enabled,pending,change,wake,waking=false}:{
value:RecoveryStatus; online:boolean; enabled:boolean; pending:boolean; change:(enabled:boolean)=>void; wake?:()=>void; waking?:boolean;
}) {
const failed=['exhausted','unavailable','preview_failed'].includes(value.phase);
const label=!value.enabled?'Выключено':failed?'Требуется проверка камеры':
['waiting','waking','restoring_preview'].includes(value.phase)?'Восстановление подключения':'Включено';
return <SettingsCard title="Восстановление подключения" description="После потери связи камера сможет включаться по Bluetooth. Ранее запущенный просмотр возобновится, запись на карту повторно не запускается."
if(!online)return <div className="x4-recovery-actions">
<p className="x4-recovery-note">{wake?'Камеру можно подключить по Bluetooth, если разрешено пробуждение.':'Перед ручным выключением камеры отключите автоматическое восстановление.'}</p>
{value.enabled&&<Button disabled={!enabled} loading={pending} onClick={()=>change(false)}>Отключить восстановление</Button>}
{wake&&<Button disabled={!enabled} loading={waking} onClick={wake}>Восстановление подключения</Button>}
</div>;
return <SettingsCard title="Восстановление подключения" description="На X4 включите «Пробуждение по Bluetooth» и оставьте USB подключённым. Восстановится только просмотр; запись на карту повторно не запускается."
actions={<StatusBadge tone={failed&&value.enabled?'warning':'neutral'}>{label}</StatusBadge>}>
<p>На X4 включите «Пробуждение по Bluetooth» и оставьте USB подключённым. Перед ручным выключением камеры отключите восстановление здесь.</p>
<Button disabled={!enabled||(!online&&!value.enabled)} loading={pending} onClick={()=>change(!value.enabled)}>
{value.enabled?'Отключить восстановление':'Включить восстановление'}
</Button>
<div className="sensor-actions">
<Button disabled={!enabled} loading={pending} onClick={()=>change(!value.enabled)}>{value.enabled?'Отключить восстановление':'Включить восстановление'}</Button>
</div>
</SettingsCard>;
}
+61 -46
View File
@@ -1,63 +1,78 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {LoadingRegion,Button,Icon,IconButton,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
import {SensorDetailBack} from '../../../../packages/sensor-ui/src/SensorDetailBack';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import {LiveViewport} from '../../../../packages/sensor-ui/src/LiveViewport';
import {LiveViewportSurface} from '../../../../packages/sensor-ui/src/LiveViewport';
import {useX4Preview} from './useX4Preview';
import {CameraSettings} from './CameraSettings';
import {RecoverySettings} from './RecoverySettings';
import {cameraStatus,fileName,type CameraFiles,type CameraSettings as Settings} from './model';
import {cameraStatus,cameraLabel,cameraDetailAvailability,fileName,type CameraFiles,type CameraSettings as Settings} from './model';
export function X4Detail({device,transport,enabled,back,refresh,failure}:SensorDetailProps){
const status=cameraStatus(device);
const [settings,setSettings]=useState<Settings|null>(null);
const [files,setFiles]=useState<CameraFiles|null>(null);
const [pending,setPending]=useState<string|null>(null);const busy=pending!==null;
const [settingsLoading,setSettingsLoading]=useState(false);const running=useRef(false);const mounted=useRef(true);
const available=enabled&&device.online&&status.connected;
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
export function X4Detail({device,transport,enabled,previewEnabled=enabled,back,navigationTarget,refresh,failure}:SensorDetailProps){
const status=cameraStatus(device),sections=cameraDetailAvailability(device,enabled),available=sections.available;
const viewing=useX4Preview(device,transport,previewEnabled,enabled);
const [settings,setSettings]=useState<Settings|null>(null),[files,setFiles]=useState<CameraFiles|null>(null);
const [pending,setPending]=useState<string|null>(null);const busy=pending!==null||viewing.busy;
const [settingsLoading,setSettingsLoading]=useState(false);const running=useRef(false),mounted=useRef(true),epoch=useRef(0);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;epoch.current++;};},[]);
const load=useCallback(async()=>{
if(status.function_mode===null)return;
if(mounted.current)setSettingsLoading(true);
try{const value=await perform<Settings>(transport,device,'settings.read',{mode:status.function_mode});if(mounted.current)setSettings(value);}
finally{if(mounted.current)setSettingsLoading(false);}
},[transport,device.id,device.snapshot.context.session_id,status.function_mode]);
useEffect(()=>{if(available)void load().catch(error=>{if(mounted.current)failure(error);});},[available,load]);
async function action(name:string,parameters:Record<string,unknown>={},key=name){
if(running.current||!enabled||(!available&&!['refresh','recovery.configure','preview.stop'].includes(name)))return;
running.current=true;setPending(key);failure(null);
const request=++epoch.current;
if(!available){setSettings(null);setFiles(null);setSettingsLoading(false);return;}
setSettingsLoading(true);
const current=()=>mounted.current&&request===epoch.current;
try{
const result=name==='refresh'?(available?await load():undefined):await perform<unknown>(transport,device,name,parameters);
if(status.function_mode!==null){const value=await perform<Settings>(transport,device,'settings.read',{mode:status.function_mode});if(!current())return;setSettings(value);}
const value=await perform<CameraFiles>(transport,device,'files.list',{offset:0});if(current())setFiles(value);
}finally{if(current())setSettingsLoading(false);}
},[transport,device.id,device.snapshot.context.session_id,status.function_mode,available]);
useEffect(()=>{void load().catch(error=>{if(mounted.current)failure(error);});return()=>{epoch.current++;};},[load]);
async function action(name:string,parameters:Record<string,unknown>={},key=name){
if(running.current||!enabled||(!available&&!['recovery.configure','power.wake'].includes(name)))return;
if(name==='power.wake'&&!sections.wake)return;
running.current=true;setPending(key);failure(null);const request=epoch.current;
try{
const result=name==='refresh'?await load():await perform<unknown>(transport,device,name,parameters);
if(!mounted.current)return;
if(name==='settings.apply')setSettings(result as Settings);
if(name==='files.list')setFiles(result as CameraFiles);
if(name==='photo.capture'||name==='record.stop')setFiles(null);
if(request===epoch.current){
if(name==='settings.apply')setSettings(result as Settings);
if(name==='files.list')setFiles(result as CameraFiles);
if(name==='photo.capture'||name==='record.stop')await load();
}
await refresh();
}catch(error){if(mounted.current)failure(error);}
finally{running.current=false;if(mounted.current)setPending(null);}
}
const mode=settings?.mode??status.function_mode;
const recordLabel=status.recording===1?'Идёт запись на карту':status.recording===0?'Запись остановлена':'Состояние записи не подтверждено';
const viewDevice=available?device:{...device,snapshot:{...device.snapshot,acquisition:'idle'}};
return <div className="sensor-content"><div><Button onClick={back}>К устройствам</Button></div>
<SettingsCard title={device.name} description={`${device.model}${device.firmware?' · '+device.firmware:''}`} actions={<IconButton label="Обновить состояние камеры" loading={pending==='refresh'} disabled={!enabled||busy} onClick={()=>void action('refresh')}><Icon name="refresh"/></IconButton>}>
<dl className="sensor-facts"><div><dt>Серийный номер</dt><dd>{status.serial||'Не получен'}</dd></div></dl>
{!available&&<p>Нет свежей связи с камерой.</p>}
<div className="sensor-actions"><Button disabled={!available||busy||status.preview!==0} loading={pending==='preview.start'} onClick={()=>void action('preview.start')}>Начать просмотр</Button><Button disabled={!enabled||busy||(!available&&!status.recovery?.preview_wanted)||(available&&status.preview===0&&!status.recovery?.preview_wanted)} loading={pending==='preview.stop'} onClick={()=>void action('preview.stop')}>Остановить просмотр</Button><Button disabled={!available||busy||status.recording!==0} loading={pending==='verify'} onClick={()=>void action('verify')}>Проверить изображение</Button></div>
{status.alerts?.temperature_high&&<p>Камера сообщает о перегреве.</p>}
{status.alerts?.storage_full&&<p>На карте камеры закончилось место.</p>}
{status.alerts?.battery_low&&<p>Камера сообщает о низком заряде.</p>}
</SettingsCard>
{status.recovery?.supported&&<RecoverySettings value={status.recovery} online={available} enabled={enabled&&!busy} pending={pending==='recovery.configure'} change={value=>void action('recovery.configure',{enabled:value,wakeup_confirmed:value})}/>}
<LiveViewport device={viewDevice} layer="preview" title="Изображение X4" note="Запись сохраняется на карте памяти камеры." inactiveMessage="Нажмите «Начать просмотр», чтобы получить изображение." transport={transport} failure={failure}/>
<SettingsCard title="Съёмка" description="Фото и видеозапись сохраняются на карте памяти X4." actions={<StatusBadge tone={available&&status.recording===1?'success':status.recording===0?'neutral':'warning'}>{available?recordLabel:'Состояние недоступно'}</StatusBadge>}>
<div className="sensor-actions"><Button disabled={!available||busy||status.recording!==0||mode!==7} loading={pending==='record.start'} onClick={()=>void action('record.start')}>Начать запись</Button><Button disabled={!available||busy||status.recording===0} loading={pending==='record.stop'} onClick={()=>void action('record.stop')}>Остановить запись</Button><Button disabled={!available||busy||status.recording!==0||mode!==6} loading={pending==='photo.capture'} onClick={()=>void action('photo.capture')}>Сделать фото</Button></div>
{available&&status.recording===1&&<p>Запись продолжится после закрытия просмотра.</p>}
</SettingsCard>
<LoadingRegion loading={available&&((settingsLoading&&!settings)||pending==='settings.apply')} label={pending==='settings.apply'?'Применение настройки':'Получение настроек камеры'}>
{settings?<CameraSettings value={settings} disabled={!available||busy||status.recording!==0||status.preview!==0} apply={(key,value)=>void action('settings.apply',{mode:settings.mode,key,value})}/>:available&&!settingsLoading?<p>Настройки недоступны. Обновите состояние камеры.</p>:null}
</LoadingRegion>
<SettingsCard title="Файлы на камере" actions={<Button disabled={!available||busy} loading={pending==='files.refresh'} onClick={()=>void action('files.list',{offset:0},'files.refresh')}>Обновить список</Button>}>
{files?files.items.length?<><ResourceList aria-label="Файлы на карте X4">{files.items.map((item,index)=><li key={`${files.offset+index}:${item}`}><ResourceRow title={fileName(item)} icon={<Icon name="file"/>}/></li>)}</ResourceList><div className="sensor-actions"><Button disabled={!available||busy||files.offset===0} loading={pending==='files.previous'} onClick={()=>void action('files.list',{offset:Math.max(0,files.offset-32)},'files.previous')}>Назад</Button><span>{files.offset+1}–{files.offset+files.items.length} из {files.total}</span><Button disabled={!available||busy||files.offset+files.items.length>=files.total} loading={pending==='files.next'} onClick={()=>void action('files.list',{offset:files.offset+files.items.length},'files.next')}>Далее</Button></div></>:<p>Файлов нет.</p>:<p>Обновите список, чтобы увидеть записи на карте камеры.</p>}
</SettingsCard>
const label=available?cameraLabel(device,true):{label:'Недоступна',tone:'neutral' as const};
const recordLabel=status.recording===1?'Идёт запись на карту':'Запись остановлена';
const viewDevice=viewing.available?device:{...device,snapshot:{...device.snapshot,acquisition:'idle'}};
const showImage=available&&(viewing.pending||viewing.preview.live||(status.preview===1&&!viewing.error));
const recovery=sections.recovery&&status.recovery?<RecoverySettings value={status.recovery} online={available} enabled={enabled&&!busy} pending={pending==='recovery.configure'} change={value=>void action('recovery.configure',{enabled:value,wakeup_confirmed:value})} wake={sections.wake?()=>void action('power.wake'):undefined} waking={pending==='power.wake'}/>:null;
return <div className="sensor-content">
<SensorDetailBack back={back} target={navigationTarget}/>
<ResourceRow title={device.name} description={label.label} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={label.tone} aria-label={label.label} title={label.label}/>} actions={available?<>
{status.preview===0||viewing.error?<Button disabled={busy} loading={viewing.pending} onClick={()=>void viewing.retry()}>{viewing.error?'Повторить просмотр':'Начать просмотр'}</Button>:status.preview===1?<Button disabled={busy} loading={pending==='preview.stop'} onClick={()=>void action('preview.stop')}>Остановить просмотр</Button>:null}
<IconButton label="Обновить состояние камеры" loading={pending==='refresh'} disabled={busy||settingsLoading} onClick={()=>void action('refresh')}><Icon name="refresh"/></IconButton>
</>:recovery}/>
{available&&(status.alerts?.temperature_high||status.alerts?.storage_full||status.alerts?.battery_low)&&<SettingsCard title="Состояние камеры">
{status.alerts.temperature_high&&<p>Камера сообщает о перегреве.</p>}
{status.alerts.storage_full&&<p>На карте камеры закончилось место.</p>}
{status.alerts.battery_low&&<p>Камера сообщает о низком заряде.</p>}
</SettingsCard>}
{available&&recovery}
{/* Keep the decoder attached while unavailable/empty content stays outside the visible layout. */}
<div hidden={!showImage}><LiveViewportSurface video={viewing.video} preview={viewing.preview} pending={viewing.pending} error={viewing.error} device={viewDevice} layer="preview" title="Изображение X4" note="Запись сохраняется на карте памяти камеры." inactiveMessage="Нет свежих данных"/></div>
{sections.capture&&<SettingsCard title="Съёмка" description="Фото и видеозапись сохраняются на карте памяти X4." actions={<StatusBadge tone={status.recording===1?'success':'neutral'}>{recordLabel}</StatusBadge>}>
<div className="sensor-actions">{status.recording===1?<Button disabled={busy} loading={pending==='record.stop'} onClick={()=>void action('record.stop')}>Остановить запись</Button>:mode===7?<Button disabled={busy} loading={pending==='record.start'} onClick={()=>void action('record.start')}>Начать запись</Button>:mode===6?<Button disabled={busy} loading={pending==='photo.capture'} onClick={()=>void action('photo.capture')}>Сделать фото</Button>:null}</div>
{status.recording===1&&<p>Запись продолжится после закрытия просмотра.</p>}
</SettingsCard>}
{available&&(settings||settingsLoading)&&<LoadingRegion loading={(settingsLoading&&!settings)||pending==='settings.apply'} label={pending==='settings.apply'?'Применение настройки':'Получение настроек камеры'}>
{settings&&<CameraSettings value={settings} disabled={busy||status.recording!==0||status.preview!==0} apply={(key,value)=>void action('settings.apply',{mode:settings.mode,key,value})}/>}
</LoadingRegion>}
{available&&!!files?.items.length&&<SettingsCard title="Файлы на камере" actions={<Button disabled={busy} loading={pending==='files.refresh'} onClick={()=>void action('files.list',{offset:0},'files.refresh')}>Обновить список</Button>}>
<ResourceList aria-label="Файлы на карте X4">{files.items.map((item,index)=><li key={`${files.offset+index}:${item}`}><ResourceRow title={fileName(item)} icon={<Icon name="file"/>}/></li>)}</ResourceList>
{files.total>files.items.length&&<div className="sensor-actions"><Button disabled={busy||files.offset===0} loading={pending==='files.previous'} onClick={()=>void action('files.list',{offset:Math.max(0,files.offset-32)},'files.previous')}>Назад</Button><span>{files.offset+1}–{files.offset+files.items.length} из {files.total}</span><Button disabled={busy||files.offset+files.items.length>=files.total} loading={pending==='files.next'} onClick={()=>void action('files.list',{offset:files.offset+files.items.length},'files.next')}>Далее</Button></div>}
</SettingsCard>}
</div>;
}
@@ -1,24 +1,22 @@
import {useEffect,useRef,useState,type RefObject} from 'react';
import {useEffect,useMemo,useRef,useState,type RefObject} from 'react';
import {createPortal} from 'react-dom';
import {Icon,IconButton} from '@nodedc/ui-react';
import {ObservationHeader} from '../../../../packages/sensor-ui/src/ObservationHeader';
import type {SensorObservationProps} from '../../../../packages/sensor-ui/src/observation';
import {useSensorPreview} from '../../../../packages/sensor-ui/src/useSensorPreview';
import {useObservationStart} from '../../../../packages/sensor-ui/src/useObservationStart';
import {startX4Observation} from './observationStart';
import {cameraStatus} from './model';
import {useX4Preview} from './useX4Preview';
import {X4Panorama} from './X4Panorama';
function Lens({video,side,label,live,rotation}:{video:RefObject<HTMLVideoElement|null>;side:number;label:string;live:boolean;rotation:number}){
const canvas=useRef<HTMLCanvasElement>(null);const [supported,setSupported]=useState(true);
function Lens({video,side,label,live,rotation,onReadyChange}:{video:RefObject<HTMLVideoElement|null>;side:number;label:string;live:boolean;rotation:number;onReadyChange:(ready:boolean)=>void}){
const canvas=useRef<HTMLCanvasElement>(null);const [supported,setSupported]=useState(false);
useEffect(()=>{
onReadyChange(false);
const source=video.current,target=canvas.current;if(!source||!target)return;
let handle:number|undefined,frame:number|undefined,active=true;
const draw=()=>{
if(!active)return;
if(source.readyState>=2&&source.videoWidth){
const valid=Math.abs(source.videoWidth/source.videoHeight-2)<.02;setSupported(valid);
if(valid){const size=Math.max(1,Math.round(Math.min(target.clientWidth,target.clientHeight)*Math.min(devicePixelRatio,2)));if(target.width!==size||target.height!==size){target.width=size;target.height=size;}const context=target.getContext('2d');if(context){context.save();context.clearRect(0,0,size,size);context.translate(size/2,size/2);context.rotate(rotation*Math.PI/180);context.drawImage(source,side*source.videoWidth/2,0,source.videoWidth/2,source.videoHeight,-size/2,-size/2,size,size);context.restore();}}
const valid=Math.abs(source.videoWidth/source.videoHeight-2)<.02;setSupported(valid);if(!valid)onReadyChange(false);
if(valid){const size=Math.max(1,Math.round(Math.min(target.clientWidth,target.clientHeight)*Math.min(devicePixelRatio,2)));if(target.width!==size||target.height!==size){target.width=size;target.height=size;}const context=target.getContext('2d');if(context){context.save();context.clearRect(0,0,size,size);context.translate(size/2,size/2);context.rotate(rotation*Math.PI/180);context.drawImage(source,side*source.videoWidth/2,0,source.videoWidth/2,source.videoHeight,-size/2,-size/2,size,size);context.restore();onReadyChange(true);}}
}
};
const tick=()=>{draw();if(active)handle=source.requestVideoFrameCallback(tick);};
@@ -26,25 +24,23 @@ function Lens({video,side,label,live,rotation}:{video:RefObject<HTMLVideoElement
const resize=new ResizeObserver(draw);resize.observe(target);
if(typeof source.requestVideoFrameCallback==='function')handle=source.requestVideoFrameCallback(tick);else frame=requestAnimationFrame(fallback);
return()=>{active=false;resize.disconnect();if(handle!==undefined)source.cancelVideoFrameCallback(handle);if(frame!==undefined)cancelAnimationFrame(frame);};
},[video,side,rotation]);
return <><canvas ref={canvas} aria-label={label} className="observation-lens" data-live={live&&supported} data-rotation={rotation}/>{!supported&&<p>Текущий формат изображения не содержит пару объективов.</p>}</>;
},[video,side,rotation,onReadyChange]);
return <canvas ref={canvas} aria-label={label} className="observation-lens" data-live={live&&supported} data-rotation={rotation}/>;
}
export function X4Observation({device,transport,enabled,views,presentation={rotations:{},panoramaYaw:0},onPresentationChange}:SensorObservationProps){
const video=useRef<HTMLVideoElement>(null);const [generation,setGeneration]=useState(0);
const status=cameraStatus(device);const available=enabled&&device.online&&status.connected;
const activation=useObservationStart(device,available&&device.prepared,status.preview!==0,()=>startX4Observation(device,transport));
const {state,error,live,hasFrame,sourceStalled}=useSensorPreview(device,'preview',transport,video,enabled,generation);
const [attempts,setAttempts]=useState(0);
const recovery=useObservationStart(device,available&&sourceStalled&&status.preview===1&&status.recording===0&&attempts<2,false,async()=>{setAttempts(v=>v+1);await startX4Observation(device,transport,true);setGeneration(v=>v+1);});
useEffect(()=>{if(!live)return;const timer=setTimeout(()=>setAttempts(0),30000);return()=>clearTimeout(timer);},[live]);
useEffect(()=>{setAttempts(0);},[device.id,device.snapshot.context.session_id]);
const pending=activation.pending||recovery.pending;
const failure=!live&&(activation.error||recovery.error||(sourceStalled&&attempts>=2&&!pending?'Не удалось восстановить изображение. Повторите просмотр.':''))||'';
export function X4Observation({device,transport,enabled,fresh=true,views,presentation={rotations:{},panoramaYaw:0},onPresentationChange}:SensorObservationProps){
const {video,preview,available,pending,error:failure,retry}=useX4Preview(device,transport,enabled,fresh);
const {state,live,frameAgeMS}=preview;
const heldAge=frameAgeMS===null?null:Math.floor(frameAgeMS/1000);
const [renderable,setRenderable]=useState<Record<string,boolean>>({});
const reportReady=useMemo(()=>Object.fromEntries(['left','right','panorama'].map(id=>[id,(ready:boolean)=>setRenderable(current=>current[id]===ready?current:{...current,[id]:ready})])),[]);
const connectionNotice=!available?'Нет связи с камерой':failure||((pending||state==='Восстановление просмотра')?'Восстановление просмотра':'Нет свежих данных');
const notice=heldAge!==null&&!live?`${connectionNotice} · последний кадр ${heldAge} с назад`:connectionNotice;
const shiftPanorama=()=>onPresentationChange?.({...presentation,panoramaYaw:(presentation.panoramaYaw+90)%360});
const rotate=(id:string)=>onPresentationChange?.({...presentation,rotations:{...presentation.rotations,[id]:((presentation.rotations[id]??0)+90)%360}});
return <><video ref={video} autoPlay muted playsInline aria-hidden="true" className="observation-decoder"/>{views.map(view=>createPortal(<div className="observation-source">
<ObservationHeader targets={view} live={live} label={pending?recovery.pending?'Восстановление изображения':'Запуск камеры':state}>{view.id==='panorama'&&<IconButton label="Сместить направление панорамы вправо на 90°" title={`Направление вправо на 90° · сейчас ${Math.round(presentation.panoramaYaw)}°`} disabled={!onPresentationChange} onClick={shiftPanorama}><Icon name="chevron-right"/></IconButton>}{view.id!=='panorama'&&<IconButton label={`Повернуть на 90° по часовой · ${view.id==='left'?'Left':'Right'} Cam`} title={`По часовой стрелке · сейчас ${presentation.rotations[view.id]??0}°`} disabled={!onPresentationChange} onClick={()=>rotate(view.id)}><Icon name="rotate-clockwise"/></IconButton>}{failure&&<IconButton label="Повторить просмотр X4" disabled={pending||!available} onClick={()=>{if(status.preview===0)void activation.retry();else{setAttempts(0);void recovery.retry();}}}><Icon name="refresh"/></IconButton>}{error&&!failure&&<IconButton label="Повторить подключение X4" onClick={()=>setGeneration(v=>v+1)}><Icon name="refresh"/></IconButton>}</ObservationHeader>
<div className="observation-source__media"><>{view.id==='panorama'?<X4Panorama video={video} presentation={presentation} optics={device.camera_status?.preview_calibration} live={hasFrame} onChange={onPresentationChange}/>:<Lens video={video} side={view.id==='left'?0:1} label={`${device.name} ${view.id==='left'?'Left':'Right'} Cam`} live={hasFrame} rotation={presentation.rotations[view.id]??0}/>}</></div>
{!hasFrame&&<p className="observation-source__notice">{failure||error||(!available?'Нет свежей связи с камерой.':pending?'Подключение обоих объективов.':sourceStalled&&status.recording!==0?'Камера перестала передавать кадры. Восстановление доступно после завершения записи.':'Ожидание изображения.')}</p>}
<ObservationHeader targets={view} live={live&&!!renderable[view.id]} label={live&&renderable[view.id]?state:notice}>{view.id==='panorama'&&<IconButton label="Сместить направление панорамы вправо на 90°" title={`Направление вправо на 90° · сейчас ${Math.round(presentation.panoramaYaw)}°`} disabled={!onPresentationChange} onClick={shiftPanorama}><Icon name="chevron-right"/></IconButton>}{view.id!=='panorama'&&<IconButton label={`Повернуть на 90° по часовой · ${view.id==='left'?'Left':'Right'} Cam`} title={`По часовой стрелке · сейчас ${presentation.rotations[view.id]??0}°`} disabled={!onPresentationChange} onClick={()=>rotate(view.id)}><Icon name="rotate-clockwise"/></IconButton>}{failure&&<IconButton label="Повторить просмотр X4" disabled={pending||!available||!fresh} onClick={()=>void retry()}><Icon name="refresh"/></IconButton>}</ObservationHeader>
<div className="observation-source__media">{view.id==='panorama'?<X4Panorama video={video} presentation={presentation} optics={device.camera_status?.preview_calibration} live={live} onReadyChange={reportReady[view.id]} onChange={onPresentationChange}/>:<Lens video={video} side={view.id==='left'?0:1} label={`${device.name} ${view.id==='left'?'Left':'Right'} Cam`} live={live} onReadyChange={reportReady[view.id]} rotation={presentation.rotations[view.id]??0}/>}
{(!live||!renderable[view.id])&&<p className="observation-source__notice observation-source__notice--centered" role="status">{notice}</p>}
</div>
</div>,view.target,view.id))}</>;
}
+12 -11
View File
@@ -6,18 +6,20 @@ import type {CameraPresentation} from '../../../../packages/sensor-ui/src/observ
// Flat operator overview from the same live dual-fisheye decoder as both lens views.
const vertex=`attribute vec2 point; varying vec2 uv; void main(){uv=(point+1.0)*0.5;gl_Position=vec4(point,0.,1.);}`;
export function X4Panorama({video,presentation,optics,live,onChange}:{video:RefObject<HTMLVideoElement|null>;presentation:CameraPresentation;optics?:unknown;live:boolean;onChange?:(value:CameraPresentation)=>void}) {
export function X4Panorama({video,presentation,optics,live,onChange,onReadyChange}:{video:RefObject<HTMLVideoElement|null>;presentation:CameraPresentation;optics?:unknown;live:boolean;onReadyChange:(ready:boolean)=>void;onChange?:(value:CameraPresentation)=>void}) {
const calibrationKey=JSON.stringify(optics??null);
const calibration=useMemo(()=>liveCalibration(optics),[calibrationKey]);
const calibrationRef=useRef(calibration);calibrationRef.current=calibration;
const canvas=useRef<HTMLCanvasElement>(null),settings=useRef(presentation),redraw=useRef<()=>void>(()=>{});
const drag=useRef<{id:number;x:number;yaw:number}|null>(null);
const [error,setError]=useState('');settings.current=presentation;
const [ready,setReady]=useState(false);settings.current=presentation;
useEffect(()=>{redraw.current();},[presentation,calibration]);
useEffect(()=>{
const reportReady=(value:boolean)=>{setReady(value);onReadyChange(value);};
reportReady(false);
const source=video.current,target=canvas.current;if(!source||!target)return;
const gl=target.getContext('webgl',{alpha:false,antialias:false,depth:false,preserveDrawingBuffer:false});
if(!gl){setError('Панорамный обзор недоступен в этом браузере.');return;}
const gl=target.getContext('webgl',{alpha:false,antialias:false,depth:false,preserveDrawingBuffer:true});
if(!gl){reportReady(false);return;}
const shaders:WebGLShader[]=[];let program:WebGLProgram|null=null,buffer:WebGLBuffer|null=null,texture:WebGLTexture|null=null;
let active=true,handle:number|undefined,frame:number|undefined;
const dispose=()=>{for(const shader of shaders)gl.deleteShader(shader);if(program)gl.deleteProgram(program);if(buffer)gl.deleteBuffer(buffer);if(texture)gl.deleteTexture(texture);};
@@ -35,7 +37,7 @@ export function X4Panorama({video,presentation,optics,live,onChange}:{video:RefO
const draw=()=>{
if(!active||source.readyState<2||!source.videoWidth)return;
if(Math.abs(source.videoWidth/source.videoHeight-2)>.02){setError('Текущий формат изображения не содержит пару объективов.');return;}
if(Math.abs(source.videoWidth/source.videoHeight-2)>.02){reportReady(false);return;}
const width=Math.max(2,Math.min(1600,Math.round(Math.min(target.clientWidth,target.clientHeight*2)*Math.min(devicePixelRatio,2)/2)*2));
if(target.width!==width){target.width=width;target.height=width/2;}gl.viewport(0,0,target.width,target.height);
gl.texImage2D(gl.TEXTURE_2D,0,gl.RGB,gl.RGB,gl.UNSIGNED_BYTE,source);
@@ -57,7 +59,7 @@ export function X4Panorama({video,presentation,optics,live,onChange}:{video:RefO
gl.uniform3f(u.radial,...lens.radial);gl.uniform3f(u.gain,...gains[i]);gl.uniform4f(u.polynomial,...lens.polynomial);gl.uniform1f(u.kind,lens.kind==='mei'?1:0);gl.uniform1f(u.xi,lens.xi);
});
}
gl.drawArrays(gl.TRIANGLE_STRIP,0,4);setError('');
gl.drawArrays(gl.TRIANGLE_STRIP,0,4);reportReady(true);
};
redraw.current=draw;
const tick=()=>{draw();if(active)handle=source.requestVideoFrameCallback(tick);};
@@ -66,13 +68,12 @@ export function X4Panorama({video,presentation,optics,live,onChange}:{video:RefO
if(typeof source.requestVideoFrameCallback==='function')handle=source.requestVideoFrameCallback(tick);else frame=requestAnimationFrame(fallback);
draw();
return()=>{active=false;redraw.current=()=>{};resize.disconnect();if(handle!==undefined)source.cancelVideoFrameCallback(handle);if(frame!==undefined)cancelAnimationFrame(frame);dispose();};
}catch{dispose();setError('Не удалось открыть панорамный обзор.');}
},[video]);
}catch{dispose();reportReady(false);}
},[video,onReadyChange]);
const change=(yaw:number)=>onChange?.({...presentation,panoramaYaw:((yaw%360)+360)%360});
return <><canvas ref={canvas} aria-label="Панорама Insta360 · перетащите для выбора направления" tabIndex={0} data-calibration={calibration?.version??'nominal'} data-live={live&&!error} style={{touchAction:'none'}}
return <canvas ref={canvas} aria-label="Панорама Insta360 · перетащите для выбора направления" tabIndex={0} data-calibration={calibration?.version??'nominal'} data-live={live&&ready} style={{touchAction:'none'}}
onPointerDown={event=>{if(event.button!==0||!onChange)return;event.currentTarget.setPointerCapture(event.pointerId);drag.current={id:event.pointerId,x:event.clientX,yaw:presentation.panoramaYaw};}}
onPointerMove={event=>{const d=drag.current;if(d&&d.id===event.pointerId)change(d.yaw-(event.clientX-d.x)/Math.max(1,event.currentTarget.clientWidth)*360);}}
onPointerUp={()=>{drag.current=null;}} onPointerCancel={()=>{drag.current=null;}} onLostPointerCapture={()=>{drag.current=null;}}
onKeyDown={event=>{if(event.key==='ArrowLeft'||event.key==='ArrowRight'){event.preventDefault();event.stopPropagation();change(presentation.panoramaYaw+(event.key==='ArrowRight'?15:-15));}}}/>
{error&&<p className="observation-source__notice">{error}</p>}</>;
onKeyDown={event=>{if(event.key==='ArrowLeft'||event.key==='ArrowRight'){event.preventDefault();event.stopPropagation();change(presentation.panoramaYaw+(event.key==='ArrowRight'?15:-15));}}}/>;
}
+11
View File
@@ -53,3 +53,14 @@ export function fileName(value:string):string {
const path=value.split('?')[0].split('/').at(-1)??value;
try{return decodeURIComponent(path);}catch{return path;}
}
/** Only current camera capabilities may expose detail sections or hardware actions. */
export function cameraDetailAvailability(device:Sensor,enabled:boolean){
const status=cameraStatus(device),available=enabled&&device.online&&status.connected;
const prepared=enabled&&device.prepared&&(device.configured??device.snapshot.enrollment==='enrolled');
const wake=prepared&&!available&&status.recovery?.supported===true&&status.recovery.wake_available===true;
return {available,wake,
recovery:prepared&&status.recovery?.supported===true&&(available||status.recovery.enabled||wake),
capture:available&&(status.recording===1||(status.recording===0&&[6,7].includes(status.function_mode??-1))),
};
}
@@ -1,18 +1,35 @@
import {perform,type Sensor,type SensorTransport} from '../../../../packages/sensor-ui/src/contracts';
import {perform,SensorOperationError,type Sensor,type SensorTransport} from '../../../../packages/sensor-ui/src/contracts';
import {currentObservationDevice,observationOperation} from '../../../../packages/sensor-ui/src/observationStart';
import {cameraStatus} from './model';
export function startX4Observation(device:Sensor,transport:SensorTransport,restart=false){
export function startX4Observation(device:Sensor,transport:SensorTransport,restart=false,allowRecovery=true,onRecovery?:()=>void){
return observationOperation(device,async()=>{
let current=await currentObservationDevice(device,transport);let status=cameraStatus(current);
if(!status.connected)throw new Error('Камера не подключена.');
if(status.preview===1&&!restart)return;
if(status.preview===1&&!restart){
// An active SDK flag does not prove that its decoder still receives frames.
// Verification must not interrupt recording (including an unknown recording state).
if(status.recording!==0)return 'active';
try{await perform(transport,current,'verify',{},20000);return 'active';}
catch(error){
// Installed brokers expose a stable public message, not the internal error code.
// Only this confirmed terminal result permits recovery; unknown/transport failures do not.
if(!allowRecovery||!(error instanceof SensorOperationError)||error.action!=='verify'||error.state!=='error'||error.message!=='Не поступают свежие кадры. Остановите и снова начните просмотр.')throw error;
}
current=await currentObservationDevice(device,transport);status=cameraStatus(current);
if(status.preview!==1)throw new Error('Состояние просмотра изменилось. Повторите просмотр.');
restart=true;
}
if(restart){
if(!status.connected||![0,1].includes(status.preview??-1))throw new Error('Состояние просмотра пока не подтверждено.');
if(status.recording!==0)throw new Error('Не удалось восстановить просмотр во время записи.');
onRecovery?.();
if(status.preview===1)await perform(transport,current,'preview.stop');
current=await currentObservationDevice(device,transport);status=cameraStatus(current);
if(!status.connected)throw new Error('Камера не подключена.');
if(status.recording!==0)throw new Error('Состояние записи изменилось. Повторите просмотр после её завершения.');
}else if(status.preview!==0)throw new Error('Состояние просмотра пока не подтверждено.');
await perform(transport,current,'preview.start');
return restart?'restarted':'started';
});
}
+1 -1
View File
@@ -8,5 +8,5 @@ export const insta360X4SensorUi:SensorUiContribution={
supportsPreparation:true,supportsRenaming:true,status:cameraLabel,
rowActions:cameraRowActions,
settingsFacts:device=>[{id:'serial',label:'Серийный номер',value:cameraStatus(device).serial||'Не получен'}],
observation:{Session:X4Observation,views:device=>[{id:'left',label:`${device.name} Left Cam`},{id:'right',label:`${device.name} Right Cam`},{id:'panorama',label:`${device.name} · панорама`}]},
observation:{independentMediaLiveness:true,Session:X4Observation,views:device=>[{id:'left',label:`${device.name} Left Cam`},{id:'right',label:`${device.name} Right Cam`},{id:'panorama',label:`${device.name} · панорама`}]},
};
@@ -0,0 +1,2 @@
.x4-recovery-actions { display:flex; align-items:center; justify-content:flex-end; flex-wrap:wrap; gap:var(--nodedc-space-3); max-width:44rem; }
.x4-recovery-note { flex:1 1 18rem; max-width:28rem; margin:0; font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); line-height:1.5; }
@@ -0,0 +1,22 @@
import {useEffect,useRef,useState} from 'react';
import type {Sensor,SensorTransport} from '../../../../packages/sensor-ui/src/contracts';
import {useObservationStart} from '../../../../packages/sensor-ui/src/useObservationStart';
import {useSensorPreview} from '../../../../packages/sensor-ui/src/useSensorPreview';
import {startX4Observation} from './observationStart';
import {cameraStatus} from './model';
/** The detail view and all observation lenses share the same capture lifecycle. */
export function useX4Preview(device:Sensor,transport:SensorTransport,enabled:boolean,fresh=true){
const video=useRef<HTMLVideoElement>(null),[generation,setGeneration]=useState(0);
const status=cameraStatus(device),available=enabled&&device.online&&status.connected;
const preview=useSensorPreview(device,'preview',transport,video,available,generation);
const [attempts,setAttempts]=useState(0);
const activation=useObservationStart(device,available&&fresh&&device.prepared,preview.live,async()=>{const result=await startX4Observation(device,transport,false,attempts<2,()=>setAttempts(v=>v+1));if(result!=='active')setGeneration(v=>v+1);},true);
const recovery=useObservationStart(device,available&&fresh&&preview.sourceStalled&&status.preview===1&&status.recording===0&&attempts<2,false,async()=>{setAttempts(v=>v+1);await startX4Observation(device,transport,true);setGeneration(v=>v+1);});
useEffect(()=>{if(!preview.live)return;const timer=setTimeout(()=>setAttempts(0),30000);return()=>clearTimeout(timer);},[preview.live]);
useEffect(()=>{setAttempts(0);},[device.id,device.snapshot.context.session_id]);
const busy=activation.pending||recovery.pending,pending=busy&&!preview.live;
const error=!preview.live&&(activation.error||recovery.error||(preview.sourceStalled&&attempts>=2&&!pending?'Не удалось восстановить изображение. Повторите просмотр.':'')||preview.error)||'';
const retry=async()=>{setAttempts(0);setGeneration(v=>v+1);await activation.retry();};
return {video,preview,available,busy,pending,error,retry};
}
+30 -4
View File
@@ -67,6 +67,7 @@ struct Frames final : StreamDelegate {
size_t bytes = 0;
uint64_t generation = 0, sequence = 0;
std::atomic<int> codec{0};
std::atomic<uint64_t> calibration_revision{0};
std::atomic<bool> enabled{false};
void reset() {
@@ -74,7 +75,7 @@ struct Frames final : StreamDelegate {
queue.clear(); bytes = 0; ++generation;
}
void OnVideoData(const uint8_t* data, size_t size, int64_t timestamp,
uint8_t, int stream_index) override {
uint8_t stream_type, int stream_index) override {
if (!enabled || !data || !size || size > MAX_PACKET || stream_index < 0 || stream_index > 1) return;
// SDK owns the callback bytes. Copy into a bounded queue; never block
// a vendor callback on a browser, disk, decoder or Python interpreter.
@@ -84,7 +85,8 @@ struct Frames final : StreamDelegate {
queue.clear(); bytes = 0; ++generation;
}
queue.push_back({{++sequence, generation, timestamp, stream_index,
codec.load(), uint32_t(size)}, {data, data + size}});
codec.load(), uint32_t(size), stream_type,
calibration_revision.load()}, {data, data + size}});
bytes += size;
} catch (...) {
// A memory allocation failure drops data; it must not unwind into
@@ -171,12 +173,20 @@ struct mc_x4 {
// Read-only metadata from this session's camera. A missing/unknown
// calibration must not take down camera control or the raw lens feed.
calibration = "null";
const auto revision = ++frames->calibration_revision;
try {
auto param = camera->GetPreviewParam();
const auto count = param.GetCalibrationCount();
if (!count || count > 4) return;
std::ostringstream out;
out << "{\"offsets\":[";
out << "{\"revision\":" << revision
<< ",\"camera_name\":" << quote(param.camera_name, 128)
<< ",\"encode_type\":" << int(param.encode_type)
<< ",\"delay_timestamp\":" << param.delay_timestamp
<< ",\"sweep_time\":" << param.sweep_time
<< ",\"acceleration_range\":" << param.acceleration_range
<< ",\"gyro_range\":" << param.gyro_range
<< ",\"offsets\":[";
for (size_t i = 0; i < count; ++i) {
if (i) out << ',';
out << quote(param.GetCalibration(i), 8192);
@@ -318,6 +328,7 @@ struct mc_x4 {
params.enable_audio = false; params.enable_gyro = false; params.using_lrv = false;
params.video_resolution = RES_1920_960P30; params.lrv_video_resulution = RES_1920_960P30;
params.video_bitrate = 4000000;
read_preview_calibration();
frames->reset(); frames->codec = int(camera->GetVideoEncodeType()); frames->enabled = true;
preview = -1;
bool ok = camera->StartLiveStreaming(params);
@@ -392,7 +403,7 @@ struct mc_x4 {
};
extern "C" {
int mc_x4_abi(void) { return 1; }
int mc_x4_abi(void) { return 2; }
mc_x4* mc_x4_open(const char* serial, const char* log_directory) {
try {
if (!serial || !*serial || std::strlen(serial) > 256 || !log_directory || !*log_directory) return nullptr;
@@ -439,6 +450,21 @@ const char* mc_x4_call(mc_x4* handle, int action, int mode, const char* key, dou
return handle->result.c_str();
} catch (...) { return UNKNOWN; }
}
int mc_x4_download(mc_x4* handle, const char* remote, const char* local, mc_x4_download_progress progress) {
if (!handle || !remote || !local || !*remote || !*local ||
std::strlen(remote) > 1024 || std::strlen(local) > 4096) return -1;
try {
if (!handle->camera->IsConnected() || handle->camera->CaptureCurrentStatus()) return -1;
const auto files = handle->camera->GetCameraFilesList();
if (files.size() > 100000 || !contains(files, std::string(remote))) return -1;
return handle->camera->DownloadCameraFile(remote, local, [progress](int64_t downloaded, int64_t total) {
if (progress) progress(downloaded, total);
}) ? 1 : 0;
} catch (...) { return 0; }
}
void mc_x4_cancel_download(mc_x4* handle) {
try { if (handle) handle->camera->CancelDownload(); } catch (...) {}
}
int mc_x4_read_video(mc_x4* handle, mc_x4_video* info, uint8_t* buffer, size_t capacity) {
if (!handle || !info || !buffer) return -1;
try {
+9 -1
View File
@@ -12,7 +12,7 @@
extern "C" {
#endif
// Private ABI v1. One handle in each physically isolated camera worker. The
// Private ABI v2. One handle in each physically isolated camera worker. The
// caller must restrict USB access BEFORE loading this library or discovering.
typedef struct mc_x4 mc_x4;
enum mc_x4_action {
@@ -28,6 +28,8 @@ typedef struct mc_x4_video {
int32_t stream_index;
int32_t codec; // 0 = H264, 1 = H265
uint32_t bytes;
int32_t stream_type; // original CameraSDK callback marker, NOT a codec enum
uint64_t calibration_revision; // identifies this preview's exact metadata
} mc_x4_video;
MC_X4_API int mc_x4_abi(void);
@@ -35,6 +37,12 @@ MC_X4_API mc_x4* mc_x4_open(const char* expected_serial, const char* private_log
// JSON result owned by the handle; copy before the next call. Calls are
// serialized by the worker. No vendor exception or C++ object crosses the ABI.
MC_X4_API const char* mc_x4_call(mc_x4*, int action, int mode, const char* key, double value);
// Serialized with control calls. Only an exact current camera-list entry is
// admitted. Destination is selected inside the private worker, never by a UI.
typedef void (*mc_x4_download_progress)(int64_t downloaded, int64_t total);
MC_X4_API int mc_x4_download(mc_x4*, const char* remote, const char* local, mc_x4_download_progress);
// The SDK explicitly provides cancellation for an in-progress download.
MC_X4_API void mc_x4_cancel_download(mc_x4*);
MC_X4_API int mc_x4_read_video(mc_x4*, mc_x4_video*, uint8_t* buffer, size_t capacity);
// Does not call StopRecording or change auto-stop-on-disconnect policy.
MC_X4_API void mc_x4_close(mc_x4*);
@@ -0,0 +1,319 @@
// Bounded rendering qualification. No CameraSDK, USB access or live-view claim.
#include <ins_realtime_stitcher.h>
#include <ins_stitcher.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstring>
#include <fstream>
#include <iostream>
#include <mutex>
#include <memory>
#include <map>
#include <stdexcept>
#include <thread>
namespace {
template <class T> T read(std::istream& file) {
T value{};
if (!file.read(reinterpret_cast<char*>(&value), sizeof(value)))
throw std::runtime_error("Truncated synthetic input");
return value;
}
std::string text(std::istream& file, uint32_t limit, bool allow_empty = false) {
auto size = read<uint32_t>(file);
if ((!size && !allow_empty) || size > limit) throw std::runtime_error("Invalid synthetic metadata");
std::string value(size, '\0');
if (!file.read(value.data(), size)) throw std::runtime_error("Truncated metadata");
return value;
}
struct Packet { int64_t timestamp; std::string data; uint8_t type; int index; };
struct Output {
std::atomic<int> frames{0}, error{0}, unsupported{0};
std::mutex mutex;
std::string error_text;
std::vector<uint8_t> first, last;
int64_t first_timestamp = 0, last_timestamp = 0;
int first_width = 0, first_height = 0, first_format = -1;
std::chrono::steady_clock::time_point first_at{}, last_at{};
std::map<int64_t, uint64_t> arrivals;
struct Timing { int64_t timestamp; uint64_t output_ns; int64_t reader_latency_ns; };
std::vector<Timing> timings;
};
uint64_t monotonic_ns() {
timespec value{};
if (clock_gettime(CLOCK_MONOTONIC, &value)) throw std::runtime_error("Monotonic clock failed");
return static_cast<uint64_t>(value.tv_sec) * 1000000000ULL + value.tv_nsec;
}
}
int main(int argc, char** argv) {
if (argc != 4 && argc != 5) return 4;
std::cout << "{\"phase\":\"render_process_started\"}" << std::endl;
try {
const bool live = std::string(argv[2]) == "-";
const std::string stitch_type = argc == 5 ? argv[4] : "dynamic";
if ((stitch_type != "dynamic" && stitch_type != "template") || (live && argc == 5))
throw std::runtime_error("Unqualified stitch mode");
std::ifstream file;
if (!live) file.open(argv[2], std::ios::binary);
std::istream& input = live ? std::cin : file;
char magic[8]{};
if (!input.read(magic, 8)) throw std::runtime_error("Truncated input");
const bool recorded = std::memcmp(magic, "MCX4P002", 8) == 0;
if (live ? std::memcmp(magic, "MCX4L001", 8)
: (!recorded && std::memcmp(magic, "MCX4P001", 8)))
throw std::runtime_error("Unexpected input profile");
const auto model = text(input, 128);
auto count = read<uint32_t>(input);
if (!count || count > 4) throw std::runtime_error("Invalid calibration count");
std::vector<std::string> offsets;
// CameraSDK preserves empty optional calibration slots. Keep their
// positions intact when forwarding the exact vector to MediaSDK.
for (uint32_t i = 0; i < count; ++i) offsets.push_back(text(input, 8192, true));
if (std::all_of(offsets.begin(), offsets.end(), [](const auto& v) { return v.empty(); }))
throw std::runtime_error("Missing factory calibration");
uint32_t sizes[4];
for (auto& size : sizes) {
size = read<uint32_t>(input);
if (!size || size > 16384) throw std::runtime_error("Invalid calibration geometry");
}
auto x = read<int32_t>(input), y = read<int32_t>(input);
if (x < 0 || y < 0 || x > 16384 || y > 16384)
throw std::runtime_error("Invalid crop origin");
const auto codec = (recorded || live) ? read<uint32_t>(input) : 0u;
if (codec > 1) throw std::runtime_error("Invalid codec");
count = live ? 0 : read<uint32_t>(input);
if (!live && (!count || count > (recorded ? 128u : 64u)))
throw std::runtime_error("Invalid packet count");
std::vector<Packet> packets;
size_t total = 0;
int64_t previous[2] = {0, 0};
for (uint32_t i = 0; i < count; ++i) {
auto timestamp = read<int64_t>(input);
const auto type = recorded ? read<uint32_t>(input) : 0x20u;
const auto index = recorded ? read<uint32_t>(input) : 0u;
if (type > 255 || index > 1) throw std::runtime_error("Invalid callback routing");
// Parameter NALs and the associated access unit share a timestamp.
if (timestamp <= 0 || timestamp > 9000000000000000LL || timestamp < previous[index])
throw std::runtime_error("Invalid source timestamp");
previous[index] = timestamp;
auto data = text(input, (recorded ? 4 : 1) * 1024 * 1024);
total += data.size();
if (total > 8 * 1024 * 1024) throw std::runtime_error("Synthetic input exceeds bound");
packets.push_back({timestamp, std::move(data), static_cast<uint8_t>(type),
static_cast<int>(index)});
}
if (!live && input.peek() != std::ifstream::traits_type::eof())
throw std::runtime_error("Trailing synthetic input");
ins::InitEnv();
ins::SetLogPath(std::string(argv[1]) + "/media.log");
ins::SetLogLevel(ins::InsLogLevel::VERBOSE);
ins::SetModelFileRootDir(argv[3]);
ins::CameraInfo info;
info.cameraName = model;
info.decode_type = static_cast<ins::VideoDecodeType>(codec);
info.SetCalibration(offsets, sizes[0], sizes[1], sizes[2], sizes[3], x, y);
// Vendor callbacks own their state, including any copy retained by
// global SDK teardown. No callback refers to main's stack lifetime.
auto output = std::make_shared<Output>();
auto& frames = output->frames; auto& error = output->error;
auto& unsupported = output->unsupported; auto& mutex = output->mutex;
auto& first = output->first; auto& error_text = output->error_text;
auto& first_timestamp = output->first_timestamp;
auto& first_width = output->first_width; auto& first_height = output->first_height;
auto& first_format = output->first_format;
first.reserve(960 * 480 * 3);
auto stitcher = std::make_unique<ins::RealTimeStitcher>();
stitcher->SetSoftwareCodecUsage(true, true);
stitcher->SetCameraInfo(info);
stitcher->SetStitchType(stitch_type == "template" ? ins::STITCH_TYPE::TEMPLATE : ins::STITCH_TYPE::DYNAMICSTITCH);
stitcher->EnableFlowState(false);
stitcher->EnableDirectionLock(false);
stitcher->SetVideoDelayMs(0);
stitcher->SetOutputSize(960, 480);
stitcher->SetStitchStateCallback([output](int code, const char* message) {
if (!code) return;
output->error = code;
std::lock_guard<std::mutex> lock(output->mutex);
output->error_text.assign(message ? message : "", message ? ::strnlen(message, 512) : 0);
});
stitcher->SetStitchRealTimeDataCallback([output](uint8_t* data[4], int stride[4], int width, int height, int format, int64_t timestamp) {
auto& frames = output->frames; auto& unsupported = output->unsupported;
auto& mutex = output->mutex; auto& first = output->first;
auto& first_timestamp = output->first_timestamp;
auto& first_width = output->first_width; auto& first_height = output->first_height;
auto& first_format = output->first_format;
// Copy only admitted packed formats; unknown formats are reported,
// not reinterpreted as RGBA. Callback buffers remain vendor-owned.
const int callback = ++frames;
if (callback <= 3) {
std::cout << "{\"phase\":\"output_layout\",\"width\":" << width
<< ",\"height\":" << height << ",\"format\":" << format
<< ",\"strides\":[" << stride[0] << ',' << stride[1] << ','
<< stride[2] << ',' << stride[3] << "]}" << std::endl;
}
// The exact 3.1.5 runtime returns format=0 with one packed
// four-byte plane, matching the shipped example's RGBA callback.
// Its header incorrectly describes the identifier as AVPixelFormat.
// Pin this observed layout; never reinterpret 0 as planar YUV.
constexpr int bytes = 4;
if (format != 0 || width <= 0 || height <= 0 || width > 4096 || height > 2048 ||
width * height > 4 * 1024 * 1024 || width != height * 2 ||
!data[0] || data[1] || data[2] || data[3] ||
stride[0] != width * bytes || stride[1] || stride[2] || stride[3]) {
++unsupported; return;
}
std::unique_lock<std::mutex> lock(mutex, std::try_to_lock);
if (!lock) return;
if (!first.empty() && (width != first_width || height != first_height)) {
++unsupported; return;
}
try {
output->last.resize(width * height * 3);
for (int row = 0; row < height; ++row) {
const auto* line = data[0] + row * stride[0];
for (int col = 0; col < width; ++col) {
const auto* pixel = line + col * bytes;
std::memcpy(output->last.data() + (row * width + col) * 3, pixel, 3);
}
}
output->last_at = std::chrono::steady_clock::now();
output->last_timestamp = timestamp;
if (output->timings.size() < 2000) {
const auto now = monotonic_ns();
const auto found = output->arrivals.find(timestamp);
output->timings.push_back({timestamp, now,
found == output->arrivals.end() ? -1 : static_cast<int64_t>(now - found->second)});
}
if (first.empty()) {
first = output->last;
first_timestamp = timestamp;
first_width = width;
first_height = height;
first_format = format;
output->first_at = output->last_at;
}
} catch (...) { ++unsupported; }
});
std::cout << "{\"phase\":\"start_stitch\",\"input\":\""
<< (live ? "live-original-callbacks" : recorded ? "original-callback-sample" : "synthetic") << "\"}" << std::endl;
stitcher->StartStitch();
const auto ready_at = monotonic_ns();
if (live) std::cout << "{\"phase\":\"live_ready\",\"monotonic_ns\":" << ready_at << '}' << std::endl;
// A short all-intra source is replayed with increasing timestamps to
// cover decoder startup buffering. This is bounded functional input,
// not a sustained FPS measurement or a real camera recording.
const auto cycle_duration = live ? 0 : packets.back().timestamp - packets.front().timestamp + 333333;
int submitted = 0;
int64_t live_last_timestamp = 0;
uint64_t first_input_at = 0;
while (live && !error.load()) {
auto size = read<uint32_t>(input);
if (!size) break;
if (size > 4 * 1024 * 1024 || ++submitted > 900 || (total += size) > 32 * 1024 * 1024)
throw std::runtime_error("Live input exceeds bounds");
auto timestamp = read<int64_t>(input);
auto type = read<uint32_t>(input), index = read<uint32_t>(input);
auto received = read<uint64_t>(input);
if (!first_input_at) first_input_at = received;
if (type > 255 || index > 1 || timestamp <= 0 || timestamp < previous[index] ||
received > monotonic_ns() || monotonic_ns() - received > 5000000000ULL)
throw std::runtime_error("Invalid or stale live callback metadata");
previous[index] = timestamp;
live_last_timestamp = timestamp;
std::string data(size, '\0');
if (!input.read(data.data(), size)) throw std::runtime_error("Truncated live packet");
{
std::lock_guard<std::mutex> lock(mutex);
output->arrivals.emplace(timestamp, received);
while (output->arrivals.size() > 1024) output->arrivals.erase(output->arrivals.begin());
}
stitcher->HandleVideoData(reinterpret_cast<const uint8_t*>(data.data()),
data.size(), timestamp, static_cast<uint8_t>(type), static_cast<int>(index));
}
auto input_ended_at = monotonic_ns();
const size_t limit = live ? 0 : recorded ? packets.size() : 48;
for (size_t i = 0; i < limit && !error.load() && (recorded || !frames.load()); ++i) {
const auto& packet = packets[i % packets.size()];
const auto timestamp = packet.timestamp + (recorded ? 0 : (i / packets.size()) * cycle_duration);
if (recorded) {
std::lock_guard<std::mutex> lock(mutex);
output->arrivals.emplace(timestamp, monotonic_ns());
}
// Pinned 3.1.5 dispatches the combined stream with 0x20; codec
// enums 0/1 are silently ignored here despite the header wording.
// Synthetic fixture only. Live integration MUST preserve the
// CameraSDK callback's original streamType instead of inferring it.
stitcher->HandleVideoData(reinterpret_cast<const uint8_t*>(packet.data.data()),
packet.data.size(), timestamp, packet.type, packet.index);
++submitted;
// Preserve vendor timestamps exactly, as the shipped camera/media
// example does. Current X4 callback deltas are 33/34 over ~30 fps,
// despite the MediaSDK header's microsecond wording. This fixed
// replay pacing bounds decoder pressure; it is not an FPS test.
std::this_thread::sleep_for(std::chrono::milliseconds(recorded ? 30 : 150));
}
if (!live) input_ended_at = monotonic_ns();
auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(20);
while (!error.load() && std::chrono::steady_clock::now() < deadline) {
bool drained = false;
{
std::lock_guard<std::mutex> lock(mutex);
drained = !first.empty() && ((!recorded && !live) ||
output->last_timestamp >= (live ? live_last_timestamp : packets.back().timestamp) ||
std::chrono::steady_clock::now() - output->last_at > std::chrono::seconds(2));
}
if (drained) break;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
// The public 3.1.5 destructor explicitly stops an active session and
// releases resources. Qualify that documented single teardown path,
// with callback state still alive, before examining any output. This
// does not skip either instance destruction or global SDK teardown.
std::cout << "{\"phase\":\"destroy_stitcher\"}" << std::endl;
stitcher.reset();
std::cout << "{\"phase\":\"stitcher_destroyed\"}" << std::endl;
std::lock_guard<std::mutex> lock(mutex);
const bool valid = !first.empty() && first.size() == static_cast<size_t>(first_width * first_height * 3) &&
(live || *std::min_element(first.begin(), first.end()) < *std::max_element(first.begin(), first.end()));
if (valid) {
std::ofstream output(live ? "live-camera.ppm" : recorded ? "recorded-camera.ppm" : "synthetic.ppm", std::ios::binary);
output << "P6\n" << first_width << ' ' << first_height << "\n255\n";
output.write(reinterpret_cast<const char*>(first.data()), first.size());
if (!output) throw std::runtime_error("Cannot save first-frame evidence");
}
if (valid && (recorded || live)) {
std::ofstream last_file(live ? "live-camera-last.ppm" : "recorded-camera-last.ppm", std::ios::binary);
last_file << "P6\n" << first_width << ' ' << first_height << "\n255\n";
last_file.write(reinterpret_cast<const char*>(output->last.data()), output->last.size());
if (!last_file) throw std::runtime_error("Cannot save last-frame evidence");
}
if (live || recorded) {
std::ofstream timing("callback-timing.jsonl");
timing << "{\"ready_ns\":" << ready_at << ",\"first_input_ns\":" << first_input_at
<< ",\"input_ended_ns\":" << input_ended_at << "}\n";
for (const auto& value : output->timings)
timing << "{\"vendor_timestamp\":" << value.timestamp << ",\"output_ns\":" << value.output_ns
<< ",\"reader_to_output_ns\":" << value.reader_latency_ns << "}\n";
if (!timing) throw std::runtime_error("Cannot save live timing evidence");
}
std::cout << "{\"synthetic_frame_verified\":" << (valid && !recorded && !live ? "true" : "false")
<< ",\"recorded_camera_frame_verified\":" << (valid && recorded ? "true" : "false")
<< ",\"live_camera_frame_verified\":" << (valid && live ? "true" : "false") << ",\"callbacks\":" << frames.load()
<< ",\"packets_submitted\":" << submitted
<< ",\"unsupported_callbacks\":" << unsupported.load()
<< ",\"width\":" << first_width << ",\"height\":" << first_height
<< ",\"pixel_format\":" << first_format
<< ",\"pixel_contract\":\"mediasdk-3.1.5-packed-rgba-format-0\""
<< ",\"stitch_type\":\"" << stitch_type << "\""
<< ",\"callback_span_ms\":" << std::chrono::duration_cast<std::chrono::milliseconds>(output->last_at - output->first_at).count()
<< ",\"last_vendor_timestamp\":" << output->last_timestamp
<< ",\"sdk_error\":" << error.load() << ",\"vendor_timestamp\":" << first_timestamp << '}' << std::endl;
if (!error_text.empty()) std::cerr << error_text << std::endl;
return valid && !error.load() && !unsupported.load() ? 0 : 5;
} catch (const std::exception& error) {
std::cerr << error.what() << std::endl;
return 2;
}
}
@@ -0,0 +1,98 @@
// One selected frame from an owned camera original. No CameraSDK or USB access.
#include <ins_stitcher.h>
#include <atomic>
#include <chrono>
#include <cmath>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <memory>
#include <thread>
bool jpeg_complete(const std::filesystem::path& path) {
if (!std::filesystem::exists(path) || std::filesystem::file_size(path) < 4) return false;
std::ifstream stream(path, std::ios::binary);
unsigned char bytes[2]{};
stream.read(reinterpret_cast<char*>(bytes), 2);
if (bytes[0] != 0xff || bytes[1] != 0xd8) return false;
stream.seekg(-2, std::ios::end);
stream.read(reinterpret_cast<char*>(bytes), 2);
return bool(stream) && bytes[0] == 0xff && bytes[1] == 0xd9;
}
int main(int argc, char** argv) {
if (argc != 5) return 4;
try {
const double seconds = std::stod(argv[4]);
if (!std::isfinite(seconds) || seconds < 0 || seconds > 240) return 4;
ins::InitEnv();
ins::SetLogPath(argv[1]);
ins::SetLogLevel(ins::InsLogLevel::WARNING);
ins::SetModelFileRootDir(argv[3]);
ins::MediaFileInfo info{};
if (!ins::GetMediaFileInfo({argv[2]}, info)) return 5;
std::cout << "{\"phase\":\"original_metadata\",\"width\":" << info.width
<< ",\"height\":" << info.height << ",\"fps\":" << info.fps
<< ",\"duration_ms\":" << info.duration_ms << "}" << std::endl;
if (!std::isfinite(info.fps) || info.fps <= 0 || info.fps > 120 ||
seconds * 1000 >= info.duration_ms) return 6;
const auto frame = uint64_t(std::llround(seconds * info.fps));
auto error = std::make_shared<std::atomic<int>>(0);
auto progress = std::make_shared<std::atomic<int>>(-1);
auto stitcher = std::make_unique<ins::VideoStitcher>();
stitcher->SetInputPath({argv[2]});
stitcher->EnableCuda(false);
stitcher->SetSoftwareCodecUsage(true, true);
stitcher->SetImageProcessingAccelType(ins::ImageProcessingAccel::kCPU);
stitcher->EnableFlowState(false);
stitcher->EnableDirectionLock(false);
stitcher->EnableColorPlus(false);
stitcher->EnableDenoise(false);
stitcher->SetStitchType(ins::STITCH_TYPE::DYNAMICSTITCH);
stitcher->EnableStitchFusion(true);
stitcher->SetOutputSize(1920, 960);
std::filesystem::create_directory("frames");
stitcher->SetImageSequenceInfo("frames", ins::IMAGE_TYPE::JPEG);
stitcher->SetExportFrameSequence({frame});
stitcher->SetStitchStateCallback([error](int value, const char*) {
if (value) *error = value;
std::cout << "{\"phase\":\"state_callback\",\"code\":" << value << "}" << std::endl;
});
stitcher->SetStitchProgressCallback([error, progress](int value, int code) {
*progress = value;
if (code) *error = code;
});
std::cout << "{\"phase\":\"original_stitch_start\",\"frame\":" << frame << "}" << std::endl;
stitcher->StartStitch();
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(35);
const auto target = std::filesystem::path("frames") / (std::to_string(frame) + ".jpg");
// Selected-frame export can leave GetStitchProgress at zero. This is
// a bounded one-image job: stop through the documented destructor
// after that exact complete JPEG exists, retaining the real progress
// telemetry. Do not claim natural whole-video completion.
while (!error->load() && std::chrono::steady_clock::now() < deadline) {
if (jpeg_complete(target)) {
const auto size = std::filesystem::file_size(target);
std::this_thread::sleep_for(std::chrono::milliseconds(300));
if (jpeg_complete(target) && std::filesystem::file_size(target) == size) break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
std::cout << "{\"phase\":\"original_stitch_result\",\"progress\":"
<< stitcher->GetStitchProgress() << ",\"callback_progress\":" << progress->load()
<< ",\"error\":" << error->load() << "}" << std::endl;
for (const auto& feature : stitcher->GetFeatureStatusMap()) {
std::cout << "sdk_feature " << feature.first << " " << feature.second << std::endl;
}
stitcher.reset();
size_t count = 0;
for (const auto& item : std::filesystem::directory_iterator("frames")) {
if (item.is_regular_file() && item.file_size() > 0) ++count;
}
std::cout << "{\"phase\":\"original_stitch_destroyed\",\"files\":" << count << "}" << std::endl;
return error->load() == 0 && count == 1 && jpeg_complete(target) ? 0 : 7;
} catch (...) {
std::cerr << "Original qualification failed" << std::endl;
return 8;
}
}
@@ -0,0 +1,33 @@
// Capability qualification only. No CameraSDK linkage, discovery or USB calls.
#include <ins_realtime_stitcher.h>
#include <ins_stitcher.h>
#include <exception>
#include <iostream>
int main(int argc, char** argv) {
if (argc != 2) return 4;
std::cout << "{\"phase\":\"process_started\"}" << std::endl;
try {
ins::InitEnv();
ins::SetLogPath(argv[1]);
ins::SetLogLevel(ins::InsLogLevel::WARNING);
std::cout << "{\"phase\":\"environment_initialized\"}" << std::endl;
{
ins::RealTimeStitcher stitcher;
stitcher.SetSoftwareCodecUsage(true, true);
stitcher.EnableFlowState(false);
stitcher.EnableDirectionLock(false);
stitcher.SetStitchType(ins::STITCH_TYPE::DYNAMICSTITCH);
stitcher.SetOutputSize(960, 480);
std::cout << "{\"phase\":\"realtime_constructed\"}" << std::endl;
}
std::cout << "{\"phase\":\"realtime_destroyed\",\"frame_verified\":false}" << std::endl;
return 0;
} catch (const std::exception&) {
std::cerr << "MediaSDK qualification raised an exception" << std::endl;
return 2;
} catch (...) {
std::cerr << "MediaSDK qualification raised an unknown exception" << std::endl;
return 3;
}
}
+64 -2
View File
@@ -24,6 +24,8 @@ class Header(ctypes.Structure):
("stream_index", ctypes.c_int32),
("codec", ctypes.c_int32),
("bytes", ctypes.c_uint32),
("stream_type", ctypes.c_int32),
("calibration_revision", ctypes.c_uint64),
]
@@ -56,6 +58,9 @@ def library(folder):
capture_output=True,
)
api = ctypes.CDLL(str(target))
api.mc_x4_abi.restype = ctypes.c_int
assert api.mc_x4_abi() == 2
assert ctypes.sizeof(Header) == 48
api.mc_x4_open.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
api.mc_x4_open.restype = ctypes.c_void_p
api.mc_x4_call.argtypes = [
@@ -98,9 +103,33 @@ def test_details_include_session_identity_and_optics_without_starting_preview(ca
result = call(camera, 1)["result"]
assert result["serial"] == "SYNTHETIC-X4"
assert len(result["preview_calibration"]["offsets"]) == 1
assert {
k: result["preview_calibration"][k]
for k in (
"camera_name",
"encode_type",
"delay_timestamp",
"sweep_time",
"acceleration_range",
"gyro_range",
"revision",
)
} == {
"camera_name": "Insta360 X4",
"encode_type": 0,
"delay_timestamp": 127,
"sweep_time": 391,
"acceleration_range": 16,
"gyro_range": 2000,
"revision": 1,
}
assert result["preview_calibration"]["crop"] == {
"source_width": 1920, "source_height": 960,
"width": 1920, "height": 960, "x": 0, "y": 0,
"source_width": 1920,
"source_height": 960,
"width": 1920,
"height": 960,
"x": 0,
"y": 0,
}
assert api.test_count(3) == 0 and api.test_count(6) == 0
@@ -165,6 +194,12 @@ def test_frames_copy_vendor_memory_preserve_stream_and_bound_backlog(camera):
info, buffer = Header(), (ctypes.c_uint8 * 24)()
assert api.mc_x4_read_video(handle, ctypes.byref(info), buffer, 24) == 1
assert (info.stream_index, info.timestamp, info.bytes) == (1, 12345, 24)
assert info.stream_type == 0x21 and info.codec == 0
assert (
info.calibration_revision
== call(camera, 1)["result"]["preview_calibration"]["revision"]
== 2
)
assert bytes(buffer) == bytes([91]) * 24
generation = info.generation
for i in range(65):
@@ -173,6 +208,11 @@ def test_frames_copy_vendor_memory_preserve_stream_and_bound_backlog(camera):
assert info.generation > generation # decoder must reset after this loss
assert bytes(buffer) == bytes([64]) * 24
assert api.mc_x4_read_video(handle, ctypes.byref(info), buffer, 24) == 0
call(camera, 5)
call(camera, 4)
api.test_packet(0, 24, 17)
assert api.mc_x4_read_video(handle, ctypes.byref(info), buffer, 24) == 1
assert info.calibration_revision == 3 and info.stream_type == 0x20
def test_camera_files_are_bounded_pages(camera):
@@ -191,6 +231,28 @@ def test_early_camera_stop_notification_wins_over_start_acknowledgement(camera):
assert api.test_count(4) == 1
def test_download_requires_current_list_entry_and_never_stops_recording(camera):
api, handle = camera
progress_type = ctypes.CFUNCTYPE(None, ctypes.c_int64, ctypes.c_int64)
api.mc_x4_download.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, progress_type]
api.mc_x4_download.restype = ctypes.c_int
observed = []
callback = progress_type(lambda current, total: observed.append((current, total)))
with tempfile.TemporaryDirectory(dir=ROOT / "build") as directory:
path = Path(directory) / "original.insv"
args = (handle, b"/DCIM/synthetic_0.insv", str(path).encode(), callback)
assert api.mc_x4_download(handle, b"/DCIM/not-listed.insv", str(path).encode(), callback) == -1
assert not path.exists()
api.test_recording(1)
assert api.mc_x4_download(*args) == -1
assert not path.exists() and api.test_count(5) == 0
api.test_recording(0)
assert api.mc_x4_download(*args) == 1
assert path.read_bytes() == b"synthetic camera original"
assert observed == [(25, 25)]
assert api.test_count(3) == 0 and api.test_count(5) == 0
def test_unavailable_calibration_preserves_camera_control(library):
for mode in (1, 2):
library.test_calibration(mode)
+17 -2
View File
@@ -4,6 +4,7 @@
#include <camera/device_discovery.h>
#include <algorithm>
#include <stdexcept>
#include <fstream>
namespace {
int discovered = 1, opens = 0, closes = 0, freed = 0, writes = 0;
@@ -32,7 +33,13 @@ uint32_t PreviewParam::GetCropDstWidth() const { return 1920; }
uint32_t PreviewParam::GetCropDstHeight() const { return 960; }
int32_t PreviewParam::GetCropOffsetX() const { return 0; }
int32_t PreviewParam::GetCropOffsetY() const { return 0; }
PreviewParam Camera::GetPreviewParam() const { return PreviewParam(); }
PreviewParam Camera::GetPreviewParam() const {
PreviewParam p;
p.camera_name = "Insta360 X4"; p.encode_type = VideoEncodeType::H264;
p.delay_timestamp = 127; p.sweep_time = 391;
p.acceleration_range = 16; p.gyro_range = 2000;
return p;
}
class ExposureSettingsPrivate {
public:
@@ -76,6 +83,14 @@ std::vector<std::string> Camera::GetCameraFilesList() const {
for (int i = 0; i < 65; ++i) out.push_back("/DCIM/synthetic_" + std::to_string(i) + ".insv");
return out;
}
bool Camera::DownloadCameraFile(const std::string&, const std::string& local, DownloadProgressCallBack progress) const {
std::ofstream stream(local, std::ios::binary);
stream << "synthetic camera original";
stream.close();
if (progress) progress(25, 25);
return bool(stream);
}
void Camera::CancelDownload() {}
std::vector<DeviceDescriptor> DeviceDiscovery::GetAvailableDevices() {
std::vector<DeviceDescriptor> out;
for (int i = 0; i < discovered; ++i) out.push_back({CameraType::Insta360X4, "SYNTHETIC-X4", "Insta360 X4", "TEST-FW", {ConnectionType::USB, "Insta360 X4", nullptr}});
@@ -139,7 +154,7 @@ void test_recording(int value) { recording = value; if (capture_callback) captur
void test_packet(int stream_index, int size, int marker) {
if (!delegate) return;
std::vector<uint8_t> packet(size, uint8_t(marker));
delegate->OnVideoData(packet.data(), packet.size(), 12345, 0, stream_index);
delegate->OnVideoData(packet.data(), packet.size(), 12345, 0x20 + stream_index, stream_index);
std::fill(packet.begin(), packet.end(), 0); // prove bridge owns copied bytes
}
}
+3 -3
View File
@@ -16,7 +16,7 @@ sys.path.insert(0, str(REPOSITORY / "scripts/packaging"))
from debian import package # noqa: E402
from fetch_sdk import verify # noqa: E402
VERSION = "0.1.3-10"
VERSION = "0.1.3-30"
WHEELS = {
"aiohappyeyeballs",
"aiohttp",
@@ -74,7 +74,7 @@ def runtime_payload():
if provenance["sdk_lock_sha256"] != digest((PACKAGING / "sdk-lock.json").read_bytes()):
raise ValueError("Native adapter SDK input changed")
binary = (native / "libmissioncore_x4.so").read_bytes()
if digest(binary) != provenance["binary"]["sha256"] or provenance["abi"] != 1:
if digest(binary) != provenance["binary"]["sha256"] or provenance["abi"] != 2:
raise ValueError("Native adapter provenance mismatch")
files = {"lib/libmissioncore_x4.so": binary}
for item in lock["files"]:
@@ -206,7 +206,7 @@ Architecture: amd64
Maintainer: NODE.DC local build <noreply@example.invalid>
Section: admin
Priority: optional
Depends: mission-core-node (>= 0.8.16), mission-core-node (<< 0.9.0),
Depends: mission-core-node (>= 0.8.49-71), mission-core-node (<< 0.9.0),
systemd (>= 255), python3 (>= 3.12), python3 (<< 3.13), adduser, udev, polkitd,
libc6 (>= 2.35), libstdc++6 (>= 12), libgcc-s1, zlib1g,
bluez (>= 5.72), python3-dbus, python3-gi
@@ -0,0 +1,315 @@
"""Build the bounded MediaSDK initialization qualification, without vendor execution."""
import argparse
import base64
import hashlib
import json
import struct
import subprocess
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
HEADERS = {
"ins_realtime_stitcher.h": "b156c45b24b69abb9f82435c8e5472ca8c371414f31c50162a7781c69d426e82",
"ins_stitcher.h": "ccdffcdb9387495ef34548a9ff5d14009dae2333d5cfc53b5e7f0500e19d7a94",
"ins_common.h": "9cdfbcd875f599eb6ebfa6cc36538828017c1ab314e3f059b060d3a83e922ced",
}
ENTRY = """import hashlib,json,sys,zipfile
from pathlib import Path
with zipfile.ZipFile(sys.argv[0]) as z:
raw=z.read("manifest.json")
m=json.loads(raw)
source=z.read("media_qualification.py")
ident=hashlib.sha256(raw).hexdigest()[:24]
if Path(sys.argv[0]).name!="mission-core-x4-media-qualify-"+ident+".pyz":
raise RuntimeError("Qualification artifact identity mismatch")
if hashlib.sha256(source).hexdigest()!=m["files"]["media_qualification.py"]:
raise RuntimeError("Qualification source checksum mismatch")
exec(compile(source,"media_qualification.py","exec"),{"__name__":"__main__"})
"""
def recorded_input(raw):
"""Serialize the exact admitted callback sample, without rewriting NALs."""
if not 0 < len(raw) <= 12 * 1024**2:
raise ValueError("Recorded input exceeds the sample bound")
sample = json.loads(raw)
if sample.get("schema") != "missioncore.insta360.stitch-input/v1":
raise ValueError("Unknown callback sample")
calibration = sample["calibration"]
revision = calibration["revision"]
if type(revision) is not int or revision <= 0:
raise ValueError("Missing calibration revision")
output = bytearray(b"MCX4P002")
def number(value, code="I", minimum=0, maximum=16384):
if type(value) is not int or not minimum <= value <= maximum:
raise ValueError("Invalid captured metadata number")
output.extend(struct.pack("<" + code, value))
def text(value, maximum, empty=False):
if not isinstance(value, str):
raise ValueError("Invalid captured metadata string")
encoded = value.encode()
if len(encoded) > maximum or (not encoded and not empty) or b"\0" in encoded:
raise ValueError("Invalid captured metadata string")
number(len(encoded), maximum=maximum)
output.extend(encoded)
text(calibration["camera_name"], 128)
offsets = calibration["offsets"]
if not isinstance(offsets, list) or not any(offsets):
raise ValueError("Missing factory calibration")
number(len(offsets), minimum=1, maximum=4)
for offset in offsets:
text(offset, 8192, empty=True)
crop = calibration["crop"]
for key in ("source_width", "source_height", "width", "height"):
number(crop[key], minimum=1)
for key in ("x", "y"):
number(crop[key], code="i")
codec = calibration["encode_type"]
number(codec, maximum=1)
packets = sample["packets"]
number(len(packets), minimum=8, maximum=128)
total, cursor = 0, None
timestamps = {}
for packet in packets:
header = packet["header"]
if (
header["calibration_revision"] != revision
or header["generation"] != sample["generation"]
or header["codec"] != codec
or header.get("gap") is not False
or type(header["cursor"]) is not int
or header["cursor"] < 1
or (cursor is not None and header["cursor"] != cursor + 1)
):
raise ValueError("Callback generation, revision or continuity changed")
timestamp, index = header["timestamp"], header["stream_index"]
number(timestamp, code="q", minimum=1, maximum=2**63 - 1)
number(header["stream_type"], maximum=255)
number(index, maximum=1)
if timestamp < timestamps.get(index, 0):
raise ValueError("Invalid callback timestamp order")
timestamps[index], cursor = timestamp, header["cursor"]
data = base64.b64decode(packet["data"], validate=True)
if type(header["bytes"]) is not int or header["bytes"] != len(data):
raise ValueError("Callback payload length changed")
number(len(data), minimum=1, maximum=4 * 1024**2)
total += len(data)
if total > 8 * 1024**2:
raise ValueError("Recorded payload exceeds bound")
output.extend(data)
return bytes(output)
def build(
headers,
compatibility_deb,
synthetic_input=None,
software_rendering=False,
recorded_camera_input=None,
original_receipt=None,
original_seconds=95,
live_input=False,
replay_artifact=None,
stitch_type="dynamic",
):
origins = (
synthetic_input,
recorded_camera_input,
original_receipt,
live_input,
replay_artifact,
)
if sum(bool(x) for x in origins) > 1:
raise ValueError("Choose exactly one rendering input origin")
render = any(origins)
if stitch_type not in ("dynamic", "template") or (
stitch_type != "dynamic" and not replay_artifact
):
raise ValueError("Alternate stitch type is limited to retained callback replay")
if live_input and not software_rendering:
raise ValueError("Live qualification requires the verified software rendering profile")
if type(original_seconds) is not int or not 0 <= original_seconds <= 240:
raise ValueError("Original sample time must be between 0 and 240 seconds")
if software_rendering and not render:
raise ValueError("Software rendering requires a rendering input")
mode = (
"live-render"
if live_input
else "original-render"
if original_receipt
else "recorded-render"
if recorded_camera_input or replay_artifact
else "synthetic-render"
if render
else "initialization"
)
files = {
"media_qualification.py": (ROOT / "packaging/media_qualification.py").read_bytes(),
"media_probe.cpp": (
ROOT
/ "native"
/ (
"media_original_probe.cpp"
if original_receipt
else "media_frame_probe.cpp"
if render
else "media_probe.cpp"
)
).read_bytes(),
"profile.json": json.dumps(
{
"mode": mode,
"egl_platform": "surfaceless" if render else None,
"software_rendering": software_rendering,
**({"stitch_type": stitch_type} if replay_artifact else {}),
**({"original_seconds": original_seconds} if original_receipt else {}),
}
).encode(),
}
if live_input:
for name in ("media_live_source.py", "media_live_qualification.py", "install_release.py"):
files[name] = (ROOT / "packaging" / name).read_bytes()
if original_receipt:
original = json.loads(original_receipt.read_text())
if (
original.get("state") != "complete"
or type(original.get("bytes")) is not int
or not 0 < original["bytes"] <= 8 * 1024**3
or not isinstance(original.get("sha256"), str)
or len(original["sha256"]) != 64
):
raise ValueError("A verified original receipt is required")
files["original.json"] = json.dumps(
{key: original[key] for key in ("path", "bytes", "sha256")}
).encode()
if recorded_camera_input:
files["input.bin"] = recorded_input(recorded_camera_input.read_bytes())
if replay_artifact:
with zipfile.ZipFile(replay_artifact) as previous:
raw = previous.read("manifest.json")
ident = hashlib.sha256(raw).hexdigest()[:24]
manifest = json.loads(raw)
if (
replay_artifact.name != f"mission-core-x4-media-qualify-{ident}.pyz"
or json.loads(previous.read("profile.json"))["mode"] != "recorded-render"
):
raise ValueError("Replay input is not a retained recorded-source artifact")
for name in ("profile.json", "input.bin"):
if hashlib.sha256(previous.read(name)).hexdigest() != manifest["files"][name]:
raise ValueError("Retained replay artifact changed")
data = previous.read("input.bin")
if not data.startswith(b"MCX4P002") or len(data) > 8 * 1024**2 + 65536:
raise ValueError("Invalid retained callback input")
files["input.bin"] = data
files["source-provenance.json"] = json.dumps(
{
"artifact_sha256": hashlib.sha256(replay_artifact.read_bytes()).hexdigest(),
"input_sha256": hashlib.sha256(data).hexdigest(),
"scope": "Unchanged prior camera callback sample; no new live capture",
}
).encode()
if synthetic_input:
content = synthetic_input.read_bytes()
if not content.startswith(b"MCX4P001") or not 0 < len(content) <= 8 * 1024**2:
raise ValueError("Invalid bounded synthetic rendering input")
files["input.bin"] = content
package_sha = "298a778a6a579a556f6bb4e32512cd76e0483b57b4a379ee85397f62fe21f225"
if hashlib.sha256(compatibility_deb.read_bytes()).hexdigest() != package_sha:
raise ValueError("Unexpected Ubuntu libtiff5 compatibility package")
# The operator Mac's libarchive tar reads ar and zstd. No maintainer scripts
# or package manager run, on either the build host or the qualification host.
payload = subprocess.run(
["/usr/bin/tar", "-xOf", str(compatibility_deb), "data.tar.zst"],
capture_output=True,
check=True,
timeout=20,
).stdout
for target, source in {
"compat/libtiff.so.5": "./usr/lib/x86_64-linux-gnu/libtiff.so.5.7.0",
"compat/LICENSE.libtiff5": "./usr/share/doc/libtiff5/copyright",
}.items():
content = subprocess.run(
["/usr/bin/tar", "-xOf", "-", source],
input=payload,
capture_output=True,
check=True,
timeout=20,
).stdout
if not 0 < len(content) < 1024 * 1024:
raise ValueError("Unexpected compatibility payload size")
files[target] = content
for name, expected in HEADERS.items():
data = (headers / name).read_bytes()
if hashlib.sha256(data).hexdigest() != expected:
raise ValueError("MediaSDK header differs from the approved archive")
files["include/" + name] = data
manifest = {
"schema": "missioncore.insta360.media-qualification-artifact/v1",
"scope": "bounded-live-stream-read-only"
if live_input
else "bounded-" + mode + "-no-camera-access",
"vendor_version": "3.1.5",
"system_changes": False,
"compatibility_package": {
"name": "libtiff5",
"version": "4.3.0-6ubuntu0.13",
"architecture": "amd64",
"sha256": package_sha,
"source": "https://packages.ubuntu.com/jammy-updates/amd64/libtiff5/download",
"scope": "private-qualification-only-not-installed",
},
"files": {n: hashlib.sha256(d).hexdigest() for n, d in files.items()},
}
raw = json.dumps(manifest, sort_keys=True).encode()
ident = hashlib.sha256(raw).hexdigest()[:24]
output = ROOT / "build" / f"mission-core-x4-media-qualify-{ident}.pyz"
with zipfile.ZipFile(output, "x", compression=zipfile.ZIP_DEFLATED) as z:
for name, data in {"__main__.py": ENTRY.encode(), "manifest.json": raw, **files}.items():
info = zipfile.ZipInfo(name, date_time=(2026, 10, 14, 0, 0, 0))
info.external_attr = 0o600 << 16
info.compress_type = zipfile.ZIP_DEFLATED
z.writestr(info, data)
output.chmod(0o600)
return {
"artifact": str(output),
"bytes": output.stat().st_size,
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
"id": ident,
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--headers", type=Path, required=True)
parser.add_argument("--compatibility-deb", type=Path, required=True)
inputs = parser.add_mutually_exclusive_group()
inputs.add_argument("--synthetic-input", type=Path)
inputs.add_argument("--recorded-camera-input", type=Path)
inputs.add_argument("--original-receipt", type=Path)
inputs.add_argument("--live-input", action="store_true")
inputs.add_argument("--replay-artifact", type=Path)
parser.add_argument("--stitch-type", choices=("dynamic", "template"), default="dynamic")
parser.add_argument("--software-rendering", action="store_true")
parser.add_argument("--original-seconds", type=int, default=95)
args = parser.parse_args()
print(
json.dumps(
build(
args.headers,
args.compatibility_deb,
args.synthetic_input,
args.software_rendering,
args.recorded_camera_input,
args.original_receipt,
args.original_seconds,
args.live_input,
args.replay_artifact,
args.stitch_type,
)
)
)
@@ -10,7 +10,6 @@ import hashlib
import json
import os
import platform
import shutil
import subprocess
import tempfile
from pathlib import Path
@@ -63,7 +62,7 @@ def build(sdk, destination):
raise ValueError("Built adapter does not depend on the admitted SDK")
report = {
"schema": "missioncore.insta360.native-build/v1",
"abi": 1,
"abi": 2,
"sdk_lock_sha256": hashlib.sha256(LOCK.read_bytes()).hexdigest(),
"source": {
p.name: hashlib.sha256(p.read_bytes()).hexdigest()
@@ -87,8 +86,8 @@ def build(sdk, destination):
os.rename(stage, destination)
return report
finally:
if stage.exists():
shutil.rmtree(stage)
# Owner direction: preserve failed build staging and its evidence.
pass
if __name__ == "__main__":
@@ -0,0 +1,97 @@
"""Small, verified unprivileged owner-wrapper build using a qualified board .deb.
Avoid transporting the same 58 MB package twice across the operator link.
This creates build artifacts only, never installs or executes a vendor SDK.
"""
import argparse
import hashlib
import json
import sys
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging"))
from build_retention import input_hold, publish_input # noqa: E402
ENTRY = """import hashlib,json,os,platform,subprocess,sys,zipfile
from pathlib import Path
if os.geteuid()==0 or platform.system()!="Linux":
raise RuntimeError("Use the unprivileged Ubuntu build account")
os.umask(0o077)
with zipfile.ZipFile(sys.argv[0]) as z:
raw=z.read("manifest.json"); manifest=json.loads(raw)
ident=hashlib.sha256(raw).hexdigest()[:24]
if Path(sys.argv[0]).name!="mission-core-x4-owner-build-"+ident+".pyz":
raise ValueError("Build identity changed")
files={n:z.read(n) for n in manifest["files"]}
if any(hashlib.sha256(data).hexdigest()!=manifest["files"][name] for name,data in files.items()):
raise ValueError("Build source changed")
expected=manifest["qualified"]
source=Path(expected["file"])
if (source.is_symlink() or source.stat().st_uid!=os.geteuid()
or source.stat().st_size!=expected["bytes"]):
raise ValueError("Qualified package changed")
with source.open("rb") as f:
if hashlib.file_digest(f,"sha256").hexdigest()!=expected["sha256"]:
raise ValueError("Qualified package hash changed")
root=Path("/var/tmp")/("mission-core-x4-owner-build-"+ident)
root.mkdir(mode=0o700)
(root/"packaging").mkdir(mode=0o700)
(root/"build").mkdir(mode=0o700)
for name,data in files.items():
with (root/"packaging"/name).open("xb") as f:f.write(data)
os.link(source,root/"build"/source.name)
(root/"build/package-result.json").write_text(json.dumps(expected))
command=["/usr/bin/python3","-I",str(root/"packaging/build_owner_release.py"),
"--qualified",str(root/"build")]
if manifest.get("original"):
command.extend(["--verify-original",manifest["original"]])
subprocess.run(command,check=True)
"""
def build(report, original=None):
files = {
name: (ROOT / "packaging" / name).read_bytes()
for name in (
"install",
"install_release.py",
"owner_release_entry.py",
"build_owner_release.py",
)
}
manifest = {
"schema": "missioncore.insta360.owner-wrapper-build/v1",
"qualified": json.loads(report.read_text()),
"original": original,
"files": {name: hashlib.sha256(data).hexdigest() for name, data in files.items()},
}
raw = json.dumps(manifest, sort_keys=True).encode()
ident = hashlib.sha256(raw).hexdigest()[:24]
output = ROOT / "build" / ("mission-core-x4-owner-build-" + ident + ".pyz")
required = sum(map(len, files.values())) + len(raw) + len(ENTRY) + 2 * 1024**2
with (
publish_input(output, required_bytes=required) as staged,
zipfile.ZipFile(staged, "x", compression=zipfile.ZIP_DEFLATED) as z,
):
for name, data in {"__main__.py": ENTRY.encode(), "manifest.json": raw, **files}.items():
z.writestr(name, data)
output.chmod(0o600)
print(
json.dumps(
{
"artifact": str(output), "retention": input_hold(output),
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
}
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--qualified-report", type=Path, required=True)
parser.add_argument("--verify-original")
args = parser.parse_args()
build(args.qualified_report, args.verify_original)
@@ -10,7 +10,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def build(qualified):
def build(qualified, capture_stitch_input=False, verify_original=None):
expected = json.loads((qualified / "package-result.json").read_text())
version = expected["version"]
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[1-9][0-9]*)?", version):
@@ -35,6 +35,8 @@ def build(qualified):
"version": version,
"runtime_revision": expected["revision"],
"qualification_profile": "sdk-status-and-image-verification",
"capture_stitch_input": capture_stitch_input,
"verify_original": verify_original,
"qualification": "Ubuntu native build, cold imports, static closure, synthetic tests",
"hardware_qualified": False,
"clean_image_qualified": False,
@@ -64,4 +66,10 @@ def build(qualified):
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--qualified", type=Path, required=True)
print(json.dumps(build(parser.parse_args().qualified)))
parser.add_argument("--capture-stitch-input", action="store_true")
parser.add_argument(
"--verify-original",
help="Exact camera-listed .insv for private installed file-access acceptance",
)
args = parser.parse_args()
print(json.dumps(build(args.qualified, args.capture_stitch_input, args.verify_original)))
@@ -1,5 +1,6 @@
"""Snapshot package inputs for compilation/qualification only on the Ubuntu Mini."""
import argparse
import hashlib
import json
import sys
@@ -11,9 +12,11 @@ from build_deb import VERSION # noqa: E402
from fetch_sdk import ROOT, verify # noqa: E402
REPOSITORY = ROOT.parents[1]
sys.path.insert(0, str(REPOSITORY / "scripts/packaging"))
from build_retention import input_hold, publish_input # noqa: E402
def build():
def build(native=None):
sdk = json.loads((ROOT / "packaging/sdk-lock.json").read_text())
verify(ROOT / "build/sdk", sdk)
paths = list((ROOT / "packaging").glob("*.py"))
@@ -34,7 +37,8 @@ def build():
paths += list((REPOSITORY / "packages/plugin-sdk/python/missioncore_plugin_sdk").rglob("*.py"))
paths += [REPOSITORY / "scripts/packaging/debian.py"]
paths += [REPOSITORY / "apps/node-agent/packaging/insta360_profile.py"]
paths += [REPOSITORY / "apps/node-agent/packaging/install_owner_release.py"]
paths += [REPOSITORY / "apps/node-agent/packaging" / name for name in (
"install_owner_release.py", "can_maintenance.py", "vesc_hall_recovery.py")]
paths += [
REPOSITORY / name
for name in (
@@ -47,6 +51,11 @@ def build():
files = {
path.relative_to(REPOSITORY).as_posix(): path.read_bytes() for path in sorted(set(paths))
}
if native is not None:
for name in ("libmissioncore_x4.so", "provenance.json"):
files[(ROOT / "build/native" / name).relative_to(REPOSITORY).as_posix()] = (
native / name
).read_bytes()
entrypoint = (ROOT / "packaging/native_build_entry.py").read_bytes()
manifest = {
"schema": "missioncore.insta360.build-source/v1",
@@ -62,7 +71,12 @@ def build():
raw = json.dumps(manifest, sort_keys=True, indent=2).encode() + b"\n"
ident = hashlib.sha256(raw).hexdigest()[:24]
output = ROOT / "build" / ("mission-core-x4-package-build-" + ident + ".pyz")
with output.open("xb") as stream, zipfile.ZipFile(stream, "w") as archive:
required = sum(map(len, files.values())) + len(raw) + len(entrypoint) + 2 * 1024**2
with (
publish_input(output, required_bytes=required) as staged,
staged.open("xb") as stream,
zipfile.ZipFile(stream, "w") as archive,
):
for name, data in {
"__main__.py": entrypoint,
"source.json": raw,
@@ -75,6 +89,7 @@ def build():
output.chmod(0o600)
return {
"artifact": str(output),
"retention": input_hold(output),
"source_id": ident,
"bytes": output.stat().st_size,
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
@@ -82,4 +97,8 @@ def build():
if __name__ == "__main__":
print(json.dumps(build()))
parser = argparse.ArgumentParser()
parser.add_argument(
"--native", type=Path, help="Qualified versioned output; retain older native builds"
)
print(json.dumps(build(parser.parse_args().native)))
@@ -3,11 +3,15 @@
import hashlib
import json
import sys
import zipfile
from pathlib import Path
from fetch_sdk import LOCK, ROOT, verify
sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging"))
from build_retention import input_hold, publish_input # noqa: E402
def build():
lock = json.loads(LOCK.read_text())
@@ -40,8 +44,10 @@ def build():
output = ROOT / "build" / ("mission-core-x4-build-" + ident + ".pyz")
entries = {"__main__.py": entrypoint, "source.json": content}
entries.update({"source/" + name: data for name, data in files.items()})
required = sum(map(len, entries.values())) + 2 * 1024**2
with (
output.open("xb") as stream,
publish_input(output, required_bytes=required) as staged,
staged.open("xb") as stream,
zipfile.ZipFile(stream, "w", compression=zipfile.ZIP_DEFLATED) as archive,
):
for name, data in entries.items():
@@ -52,6 +58,7 @@ def build():
output.chmod(0o600)
return {
"artifact": str(output),
"retention": input_hold(output),
"bytes": output.stat().st_size,
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
"source_id": ident,
@@ -4,7 +4,6 @@ import hashlib
import importlib
import io
import json
import shutil
import subprocess
import sys
import tarfile
@@ -93,4 +92,5 @@ try:
if not unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful():
raise RuntimeError("Package qualification tests failed")
finally:
shutil.rmtree(stage)
# Owner direction: retain qualification artifacts; no automatic cleanup.
pass
+389 -10
View File
@@ -4,12 +4,15 @@ Invoke through the release's local Ubuntu terminal. The OS password is never
accepted by this script or sent to Mission Core. No arbitrary commands/URLs.
"""
import base64
import hashlib
import http.client
import json
import os
import pwd
import re
import socket
import struct
import subprocess
import sys
import time
@@ -19,6 +22,9 @@ from datetime import UTC, datetime, timedelta
from pathlib import Path
STAGING = Path("/var/tmp/mission-core-x4-installs")
INSTANCES = Path("/run/mission-core-x4-instances")
PREPARE = Path("/usr/lib/mission-core-node/insta360/prepare.py")
MAINTENANCE = Path("/var/lib/mission-core-insta360/maintenance")
SERVICES = (
"mission-core-node.service",
"mission-core-k1.service",
@@ -33,8 +39,8 @@ def private(path):
raise RuntimeError("Installer staging is not root-owned and private")
def request(path, operation=None):
timeout = 55 if operation else 3
def request(path, operation=None, *, video=False, archive_route=None):
timeout = 2 if video else 55 if operation else 3
client = http.client.HTTPConnection("driver", timeout=timeout)
client.sock = socket.socket(socket.AF_UNIX)
client.sock.settimeout(timeout)
@@ -44,17 +50,322 @@ def request(path, operation=None):
client.request("GET", "/snapshot")
else:
client.request(
"POST", "/operation", json.dumps(operation), {"Content-Type": "application/json"}
"POST",
archive_route or ("/sdk-video" if video else "/operation"),
json.dumps(operation),
{"Content-Type": "application/json"},
)
response = client.getresponse()
content = response.read(65537)
if response.status != 200 or len(content) > 65536:
limit = 4 * 1024**2 + 1028 if video else 65536
content = response.read(limit + 1)
if response.status != 200 or len(content) > limit:
raise RuntimeError("Camera status is unavailable")
return json.loads(content)
return content if video else json.loads(content)
finally:
client.close()
# Executed only AFTER dropping supplementary groups, GID and UID. A fixed
# owner-private destination, O_EXCL, bounded bytes and hash verification avoid
# root writes into an operator-controlled tree. No evidence is removed.
OWNER_ORIGINAL_EXPORT = r"""
import hashlib, json, os, pathlib, pwd, re, sys
if os.geteuid() == 0:
raise RuntimeError("Original export must be unprivileged")
ident, size_text, expected = sys.argv[1:]
size = int(size_text)
if (not re.fullmatch(r"file_[0-9a-f]{32}", ident) or not 0 < size <= 8 * 1024**3
or not re.fullmatch(r"[0-9a-f]{64}", expected)):
raise ValueError("Invalid original export")
os.umask(0o077)
root = (pathlib.Path(pwd.getpwuid(os.geteuid()).pw_dir)
/ ".local/share/mission-core/qualifications/x4-originals")
root.mkdir(mode=0o700, parents=True, exist_ok=True)
path = root / (ident + ".insv")
digest, count = hashlib.sha256(), 0
with path.open("xb") as stream:
while count < size:
chunk = sys.stdin.buffer.read(min(1024**2, size - count))
if not chunk:
raise RuntimeError("Original export interrupted; partial retained")
stream.write(chunk)
digest.update(chunk)
count += len(chunk)
stream.flush()
os.fsync(stream.fileno())
if digest.hexdigest() != expected:
raise RuntimeError("Original export hash mismatch; evidence retained")
print(json.dumps({"path": str(path), "bytes": count, "sha256": digest.hexdigest()}))
"""
def verify_original(path, camera, source):
"""Optional installed file-access acceptance; SDK stays in the USB worker."""
if (
not isinstance(source, str)
or len(source) > 1024
or not re.fullmatch(r"/DCIM/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_.-]+\.insv", source)
):
raise ValueError("Invalid camera original qualification input")
uid = int(os.environ.get("SUDO_UID", "0"))
if uid <= 0:
raise RuntimeError("Original qualification needs an authenticated local owner")
account = pwd.getpwuid(uid)
ident = "file_" + uuid.uuid4().hex
context = {"session_id": camera["session_id"], "id": ident}
result = request(path, dict(context, source=source), archive_route="/archive/start")
deadline = time.monotonic() + 360
while result.get("state") == "running" and time.monotonic() < deadline:
time.sleep(1)
result = request(path, context, archive_route="/archive/status")
if (
result.get("state") != "complete"
or type(result.get("bytes")) is not int
or not 0 < result["bytes"] <= 8 * 1024**3
or not re.fullmatch(r"[0-9a-f]{64}", result.get("sha256", ""))
):
raise RuntimeError("Original transfer incomplete; camera and partial file retained")
child = subprocess.Popen(
[
"/usr/bin/python3",
"-I",
"-c",
OWNER_ORIGINAL_EXPORT,
ident,
str(result["bytes"]),
result["sha256"],
],
user=uid,
group=account.pw_gid,
extra_groups=[],
env={"PATH": "/usr/bin:/bin", "LANG": "C.UTF-8"},
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
try:
offset = 0
while offset < result["bytes"]:
chunk = request(
path, dict(context, offset=offset), video=True, archive_route="/archive/read"
)
if len(chunk) != min(1024**2, result["bytes"] - offset):
raise RuntimeError("Original export chunk is incomplete")
child.stdin.write(chunk)
offset += len(chunk)
child.stdin.close()
child.wait(timeout=30)
if child.returncode != 0:
raise RuntimeError("Owner original export failed; partial retained")
exported = json.loads(child.stdout.read(4097))
if exported.get("sha256") != result["sha256"] or exported.get("bytes") != result["bytes"]:
raise RuntimeError("Exported original differs from the worker's receipt")
return {"state": "complete", "id": ident, **exported}
finally:
if not child.stdin.closed:
child.stdin.close()
child.wait(timeout=30)
child.stdout.close()
child.stderr.close()
def camera_command(camera, action):
now = datetime.now(UTC)
operation = "op_" + uuid.uuid4().hex
return {
"api_version": "missioncore.nodedc/plugin-sdk/v0alpha2",
"kind": "OperationRequest",
"operation_id": operation,
"idempotency_key": operation,
"session": {"device_id": camera["id"], "session_id": camera["session_id"]},
"action_id": action,
"requested_at": now.isoformat(),
"deadline_at": (now + timedelta(seconds=60)).isoformat(),
"parameters": {},
}
def admit_package_plan(raw, version):
"""The owner permits only this Mission Core package, no OS changes."""
for line in raw.decode(errors="strict").splitlines():
fields = line.split()
if (
fields
and fields[0] in ("Inst", "Conf", "Remv", "Purg")
and (
len(fields) < 3
or fields[0] in ("Remv", "Purg")
or fields[1] != "mission-core-insta360-x4"
or "(" + version + " " not in line
)
):
raise RuntimeError("APT предлагает изменения вне обновления X4. Установка отменена.")
def stitch_packet(raw, revision, cursor, generation):
if len(raw) < 5:
raise ValueError("Truncated SDK packet")
size = struct.unpack("!I", raw[:4])[0]
if not 0 < size <= 1024 or len(raw) <= 4 + size:
raise ValueError("Invalid SDK envelope")
header, data = json.loads(raw[4 : 4 + size]), raw[4 + size :]
if not isinstance(header, dict) or any(
type(header.get(key)) is not int or header[key] < 0
for key in (
"cursor",
"generation",
"timestamp",
"stream_index",
"stream_type",
"codec",
"calibration_revision",
"bytes",
)
):
raise ValueError("Invalid SDK metadata")
if (
header["calibration_revision"] != revision
or header["stream_index"] not in (0, 1)
or not 0 <= header["stream_type"] <= 255
or header["codec"] not in (0, 1)
or header["bytes"] != len(data)
or not 0 < len(data) <= 4 * 1024**2
or header["timestamp"] <= 0
or header.get("gap") is not False
or header["cursor"] <= cursor
or (cursor and header["cursor"] != cursor + 1)
or (generation is not None and header["generation"] != generation)
):
raise ValueError("SDK stream changed or lost packets")
return header, data
def capture_stitch_input(path, camera):
"""Bounded private original-packet evidence, never a second USB owner.
No MediaSDK is loaded as root. The optional sample is for a later isolated,
unprivileged qualification. It does not claim stitched or stabilized output.
"""
result = request(path, camera_command(camera, "details"))
status = result.get("result", {})
if result.get("state") != "complete" or status.get("recording") != 0:
raise RuntimeError("Stitch input requires confirmed idle recording state")
if status.get("preview") not in (0, 1):
raise RuntimeError("Preview state is unknown")
owned = status["preview"] == 0
if owned and request(path, camera_command(camera, "preview.start")).get("state") != "complete":
raise RuntimeError("Preview start was not acknowledged")
try:
details = request(path, camera_command(camera, "details"))
calibration = details.get("result", {}).get("preview_calibration")
if details.get("state") != "complete" or not isinstance(calibration, dict):
raise RuntimeError("Factory calibration is unavailable")
revision = calibration.get("revision")
if type(revision) is not int or revision <= 0:
raise RuntimeError("A versioned original-packet bridge is required")
cursor, generation, total = 0, None, 0
packets = []
start = time.monotonic()
while len(packets) < 128 and time.monotonic() - start < 12:
raw = request(path, {"session_id": camera["session_id"], "cursor": cursor}, video=True)
if not raw:
continue
header, data = stitch_packet(raw, revision, cursor, generation)
if total + len(data) > 8 * 1024**2:
break
total += len(data)
packets.append({"header": header, "data": base64.b64encode(data).decode("ascii")})
cursor, generation = header["cursor"], header["generation"]
after = request(path, camera_command(camera, "details"))
if (
after.get("state") != "complete"
or after.get("result", {}).get("preview_calibration") != calibration
or len(packets) < 8
):
raise RuntimeError("No consistent bounded SDK input was captured")
return {
"schema": "missioncore.insta360.stitch-input/v1",
"scope": "original-callback-sample-not-stitched-output",
"captured_at": datetime.now(UTC).isoformat(),
"monotonic_started": start,
"duration_seconds": time.monotonic() - start,
"device_id": camera["id"],
"session_id": camera["session_id"],
"calibration": calibration,
"generation": generation,
"gyro_exposure_forwarded": False,
"packets": packets,
}
finally:
if owned:
stopped = request(path, camera_command(camera, "preview.stop"))
if stopped.get("state") != "complete":
raise RuntimeError("Qualification preview stop was not acknowledged")
def pause_previews(run, report, publish):
"""Pause preview after OS authentication, then use the installed safety gate.
Never stop a recording. The existing exclusive lifecycle lock + maintenance
marker close the interval in which a viewer could restart acquisition. The
broker's operator preview intent is retained for recovery after the upgrade.
"""
if not PREPARE.exists():
return False
if MAINTENANCE.exists():
raise RuntimeError("Предыдущее обновление X4 не завершено. Нужна проверка его отчёта.")
report["preview_pause"] = {"operations": [], "state": "running"}
publish()
for attempt in range(3):
paths = sorted(INSTANCES.glob("instax4_*/driver.sock"))
cameras = []
for path in paths:
if not re.fullmatch(r"instax4_[0-9a-f]{32}", path.parent.name):
raise RuntimeError("Некорректная привязка X4.")
camera = request(path)
if camera.get("id") != path.parent.name or not camera.get("online"):
raise RuntimeError("Состояние X4 неизвестно. Обновление не начато.")
# Read actual SDK status, not a possibly stale inventory snapshot.
status = request(path, camera_command(camera, "details"))
if status.get("state") != "complete" or status.get("result", {}).get("recording") != 0:
raise RuntimeError(
"Запись X4 активна или её состояние неизвестно. Обновление не начато."
)
if status["result"].get("preview") not in (0, 1):
raise RuntimeError("Состояние просмотра X4 неизвестно. Обновление не начато.")
cameras.append((path, camera, status["result"]["preview"]))
for path, camera, preview in cameras:
if preview == 0:
continue
command = camera_command(camera, "preview.stop")
result = request(path, command)
report["preview_pause"]["operations"].append({"request": command, "result": result})
publish()
if result.get("state") != "complete":
raise RuntimeError("Остановка просмотра X4 не подтверждена. Обновление не начато.")
# STOP invalidates cached status; allow the worker's normal poll to
# refresh it. The installed quiesce gate checks all instances again.
deadline = time.monotonic() + 10
while cameras and time.monotonic() < deadline:
if all(request(path).get("preparation_safe") is True for path, _, _ in cameras):
break
time.sleep(0.25)
try:
run(
"quiesce-" + str(attempt + 1), ["/usr/bin/python3", "-I", str(PREPARE), "--quiesce"]
)
except RuntimeError:
# A viewer may have restarted in the small pre-gate interval.
# Retry only before the gate was acquired; no unknown outcome replay.
if MAINTENANCE.exists() or attempt == 2:
raise
else:
report["preview_pause"]["state"] = "complete"
publish()
return True
return False
def main():
if os.geteuid() or sys.argv[1:]:
raise RuntimeError("Запустите установщик в локальном окне Ubuntu через sudo.")
@@ -71,6 +382,12 @@ def main():
raise ValueError("Invalid release version")
if manifest["qualification_profile"] != "sdk-status-and-image-verification":
raise ValueError("Unsupported qualification profile")
if type(manifest.get("capture_stitch_input", False)) is not bool:
raise ValueError("Invalid stitch input qualification profile")
if manifest.get("verify_original") is not None and not isinstance(
manifest["verify_original"], str
):
raise ValueError("Invalid original qualification profile")
package = "mission-core-insta360-x4_" + version + "_amd64.deb"
admitted = manifest["files"]
if set(admitted) != {package, "install_release.py", "install"}:
@@ -122,9 +439,16 @@ def main():
)
publish()
if result.returncode:
# The owner terminal log is private. Preserve the concrete cause
# there instead of requiring privileged access to a hidden report.
report["steps"][-1]["diagnostic_tail"] = (
result.stdout[-4096:] + result.stderr[-4096:]
).decode(errors="replace")
publish()
raise RuntimeError("Не завершён этап установки: " + step)
return result.stdout
quiesced = False
publish()
try:
# These remain private to the authenticated owner; the terminal wrapper
@@ -148,15 +472,27 @@ def main():
],
)
report["existing_services"] = baseline.decode().splitlines()
run(
plan = run(
"apt-plan",
["/usr/bin/apt-get", "--simulate", "--no-remove", "install", str(folder / package)],
)
admit_package_plan(plan, version)
quiesced = pause_previews(run, report, publish)
run(
"package",
["/usr/bin/apt-get", "install", "-y", "--no-remove", str(folder / package)],
timeout=None,
)
installed_version = (
run(
"installed-version",
["/usr/bin/dpkg-query", "-W", "-f=${Version}", "mission-core-insta360-x4"],
)
.decode()
.strip()
)
if installed_version != version:
raise RuntimeError("Установленная версия X4 не совпала с проверенным пакетом.")
# This is the identical installed model job started by Node's local or
# paired remote prepare command. No SDK demo, root SDK or manual grant.
preparation = Path("/var/lib/mission-core-insta360/preparation.json")
@@ -222,6 +558,35 @@ def main():
or result.get("result", {}).get("verified") is not True
):
raise RuntimeError("SDK подключён, но проверка изображения не завершилась успешно.")
if manifest.get("capture_stitch_input", False):
try:
sample = capture_stitch_input(INSTANCES / camera["id"] / "driver.sock", camera)
raw = json.dumps(sample, separators=(",", ":")).encode()
(folder / "stitch-input.private.json").write_bytes(raw)
report["stitch_input"] = {
"state": "complete",
"bytes": len(raw),
"sha256": hashlib.sha256(raw).hexdigest(),
"packets": len(sample["packets"]),
"real_stitched_frame_verified": False,
}
# The local terminal wrapper tees to a private owner-readable
# log. No writes to user-selected paths or permission widening.
print("MISSION_CORE_X4_STITCH_INPUT " + raw.decode(), flush=True)
except Exception as sample_error:
report["stitch_input"] = {"state": "error", "error": str(sample_error)[:300]}
publish()
if manifest.get("verify_original"):
try:
report["original_verification"] = verify_original(
INSTANCES / camera["id"] / "driver.sock", camera, manifest["verify_original"]
)
except Exception as original_error:
report["original_verification"] = {
"state": "error",
"error": str(original_error)[:300],
}
publish()
after = run(
"existing-services-after",
[
@@ -243,14 +608,28 @@ def main():
except Exception as error:
report["state"] = "error"
report["error"] = str(error)[:300]
# APT can fail before changing the package. Recover through the same
# installed preparation workflow only when dpkg confirms a configured
# package. Never erase a maintenance marker by hand or repair dpkg here.
if quiesced and MAINTENANCE.exists():
installed = subprocess.run(
["/usr/bin/dpkg-query", "-W", "-f=${Status}", "mission-core-insta360-x4"],
capture_output=True,
text=True,
timeout=10,
)
if installed.returncode == 0 and installed.stdout.strip() == "install ok installed":
try:
run("recover-preparation", ["/usr/bin/python3", "-I", str(PREPARE)])
except Exception as recovery_error:
report["recovery_error"] = str(recovery_error)[:300]
raise
finally:
report["finished_at"] = datetime.now(UTC).isoformat()
report["duration_seconds"] = time.monotonic() - report["monotonic_started"]
publish()
# Retain bounded private evidence and remove only the installer-owned
# temporary package copy. Runtime/journals remain owned by the .deb.
(folder / package).unlink()
# Owner direction: retain the installer payload and evidence. Do not
# perform cleanup or remove package copies as part of this update.
print("MISSION_CORE_X4_RESULT " + json.dumps(report, ensure_ascii=False), flush=True)
print("Отчёт установки:", folder / "report.json")
@@ -0,0 +1,223 @@
"""One bounded live qualification; vendor SDK remains unprivileged and isolated."""
import getpass
import json
import os
import resource
import signal
import struct
import subprocess
import sys
import time
from pathlib import Path
from install_release import stitch_packet
from media_live_source import read_message, write_all
from media_qualification import digest, restrict_process, stamp, verify_runtime
def calibration_bytes(calibration):
raw = bytearray(b"MCX4L001")
def integer(value, minimum=0, maximum=16384, code="I"):
if type(value) is not int or not minimum <= value <= maximum:
raise ValueError("Invalid calibration number")
raw.extend(struct.pack("<" + code, value))
def text(value, limit, empty=False):
if not isinstance(value, str):
raise ValueError("Invalid calibration text")
data = value.encode()
if len(data) > limit or (not data and not empty) or b"\0" in data:
raise ValueError("Invalid calibration text")
integer(len(data), maximum=limit)
raw.extend(data)
text(calibration["camera_name"], 128)
offsets = calibration["offsets"]
if not isinstance(offsets, list) or not any(offsets):
raise ValueError("Missing factory calibration")
integer(len(offsets), minimum=1, maximum=4)
for offset in offsets:
text(offset, 8192, True)
for field in ("source_width", "source_height", "width", "height"):
integer(calibration["crop"][field], minimum=1)
for field in ("x", "y"):
integer(calibration["crop"][field], code="i")
integer(calibration["encode_type"], maximum=1)
return bytes(raw)
def execute_live(root, device, session):
if os.geteuid() == 0:
raise RuntimeError("Vendor qualification must never run as root")
verify_runtime(root)
if digest(root / "probe") != json.loads((root / "binary.json").read_text())["sha256"]:
raise ValueError("Qualification binary changed")
profile = json.loads((root / "profile.json").read_text())
if profile != {
"mode": "live-render",
"egl_platform": "surfaceless",
"software_rendering": True,
}:
raise ValueError("Unqualified live rendering profile")
work = root / "live-run"
work.mkdir(mode=0o700)
(work / "logs").mkdir(mode=0o700)
report = {
"started": stamp(),
"scope": "20s-live-original-stream-960x480-cpu",
"system_changes": False,
"camera_lifecycle_changes": False,
"latency_scope": (
"reader receipt to SDK output; excludes USB/worker backlog, encoding and network"
),
}
source = renderer = None
initial_usage = resource.getrusage(resource.RUSAGE_CHILDREN)
with (
(work / "source.log").open("xb", buffering=0) as source_log,
(work / "stdout.log").open("xb", buffering=0) as stdout,
(work / "stderr.log").open("xb", buffering=0) as stderr,
):
try:
password = getpass.getpass("Ubuntu password for the authorized read-only live sample: ")
source = subprocess.Popen(
[
"/usr/bin/sudo",
"-k",
"-S",
"-p",
"",
"/usr/bin/python3",
"-I",
str(Path(sys.argv[0]).resolve()),
"source-live",
"--device-id",
device,
"--session-id",
session,
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=source_log,
env={"PATH": "/usr/bin:/bin", "LANG": "C.UTF-8"},
bufsize=0,
)
source.stdin.write((password + "\n").encode())
password = ""
header = json.loads(read_message(source.stdout, time.monotonic() + 10, 65536))
if header["session"] != session:
raise ValueError("Live reader returned a different session")
calibration = header["calibration"]
native_header = calibration_bytes(calibration)
(work / "calibration.private.json").write_text(json.dumps(calibration))
renderer = subprocess.Popen(
[str(root / "probe"), str(work / "logs"), "-", str(root / "sdk/bin/models") + "/"],
stdin=subprocess.PIPE,
stdout=stdout,
stderr=stderr,
start_new_session=True,
cwd=work,
bufsize=0,
preexec_fn=lambda: restrict_process(root, work, True),
env={
"PATH": "/usr/bin:/bin",
"LANG": "C.UTF-8",
"OMP_NUM_THREADS": "2",
"OPENBLAS_NUM_THREADS": "2",
"LP_NUM_THREADS": "2",
"TMPDIR": str(work),
"XDG_CACHE_HOME": str(work),
"EGL_PLATFORM": "surfaceless",
"LIBGL_ALWAYS_SOFTWARE": "true",
"GALLIUM_DRIVER": "llvmpipe",
},
)
os.set_blocking(renderer.stdin.fileno(), False)
write_all(renderer.stdin, native_header, time.monotonic() + 2)
deadline = time.monotonic() + 12
while b'"phase":"live_ready"' not in (work / "stdout.log").read_bytes():
if renderer.poll() is not None or time.monotonic() > deadline:
raise RuntimeError("SDK did not become ready within the bound")
time.sleep(0.1)
source.stdin.write(b"START\n")
source.stdin.close()
report["stream_started"] = stamp()
deadline = time.monotonic() + 26
cursor, generation, packets, size = 0, None, 0, 0
while True:
raw = read_message(source.stdout, deadline)
if not raw:
break
if len(raw) < 13:
raise ValueError("Truncated live packet")
received = struct.unpack("<Q", raw[:8])[0]
header, data = stitch_packet(raw[8:], calibration["revision"], cursor, generation)
if header["codec"] != calibration["encode_type"]:
raise ValueError("Source codec changed")
cursor, generation = header["cursor"], header["generation"]
packets += 1
size += len(data)
if packets > 900 or size > 32 * 1024**2:
raise ValueError("Live sample exceeds bounds")
payload = (
struct.pack(
"<IqIIQ",
len(data),
header["timestamp"],
header["stream_type"],
header["stream_index"],
received,
)
+ data
)
write_all(renderer.stdin, payload, min(deadline, time.monotonic() + 2))
report.update(
stream_finished=stamp(), packets=packets, bytes=size, generation=generation
)
write_all(renderer.stdin, struct.pack("<I", 0), time.monotonic() + 2)
renderer.stdin.close()
report["source_exit_code"] = source.wait(timeout=5)
report["renderer_exit_code"] = renderer.wait(timeout=12)
except Exception as error:
report["error"] = type(error).__name__ + ": " + str(error)
finally:
if source is not None:
if not source.stdin.closed:
source.stdin.close()
source.stdout.close()
try:
report["source_exit_code"] = source.wait(timeout=5)
except subprocess.TimeoutExpired:
# The root reader has a fixed 48s alarm and cannot touch the
# camera lifecycle. Closing its pipes makes writes fail.
report["source_exit_code"] = source.wait(timeout=50)
if renderer is not None:
if not renderer.stdin.closed:
renderer.stdin.close()
try:
report["renderer_exit_code"] = renderer.wait(timeout=3)
except subprocess.TimeoutExpired:
os.killpg(renderer.pid, signal.SIGKILL)
renderer.wait()
report["renderer_killed_at_deadline"] = True
report["renderer_exit_code"] = renderer.returncode
report["finished"] = stamp()
usage = resource.getrusage(resource.RUSAGE_CHILDREN)
report["child_usage"] = {
"user_seconds": usage.ru_utime - initial_usage.ru_utime,
"system_seconds": usage.ru_stime - initial_usage.ru_stime,
"max_rss_kib": usage.ru_maxrss,
}
report["artifacts"] = {
str(p.relative_to(work)): digest(p) for p in work.rglob("*") if p.is_file()
}
(root / "live-run.json").write_text(json.dumps(report, indent=2))
print(json.dumps(report), flush=True)
if (
report.get("error")
or report.get("source_exit_code") != 0
or report.get("renderer_exit_code") != 0
):
raise RuntimeError("Live qualification failed; evidence retained")
@@ -0,0 +1,202 @@
"""Bounded read-only access to the installed X4 original-packet bridge.
This helper never imports a vendor library, starts preview, opens USB, writes a
file, or changes host configuration. Its only privileged capability is reading
one already-running, explicitly identified camera session for 20 seconds.
"""
import http.client
import json
import os
import re
import select
import signal
import socket
import struct
import sys
import time
from pathlib import Path
from install_release import camera_command, stitch_packet
DURATION = 20
MAX_BYTES = 32 * 1024**2
MAX_PACKETS = 900
WARMUP = 2
def independent_packet(data, codec):
"""Begin only at an original IDR with its original codec parameter sets."""
kinds = set()
for marker in re.finditer(b"\x00\x00(?:\x00)?\x01", data):
if marker.end() < len(data):
kinds.add(data[marker.end()] & 31 if codec == 0 else (data[marker.end()] >> 1) & 63)
return (
{5, 7, 8} <= kinds
if codec == 0
else {32, 33, 34} <= kinds and bool(kinds & {16, 17, 18, 19, 20, 21})
)
def read_exact(stream, size, deadline):
result = bytearray()
while len(result) < size:
remaining = deadline - time.monotonic()
if remaining <= 0 or not select.select([stream], [], [], remaining)[0]:
raise TimeoutError("Live qualification pipe deadline")
chunk = os.read(stream.fileno(), size - len(result))
if not chunk:
raise EOFError("Live qualification pipe ended early")
result.extend(chunk)
return bytes(result)
def read_message(stream, deadline, limit=4 * 1024**2 + 1040):
size = struct.unpack("!I", read_exact(stream, 4, deadline))[0]
if size > limit:
raise ValueError("Live qualification envelope exceeds bound")
return read_exact(stream, size, deadline) if size else b""
def write_all(stream, data, deadline):
view = memoryview(data)
while view:
remaining = deadline - time.monotonic()
if remaining <= 0 or not select.select([], [stream], [], remaining)[1]:
raise TimeoutError("Live qualification consumer is not keeping up")
try:
count = os.write(stream.fileno(), view[:65536])
except BlockingIOError:
continue
if count <= 0:
raise BrokenPipeError("Live qualification consumer closed")
view = view[count:]
def emit_message(stream, raw):
write_all(stream, struct.pack("!I", len(raw)) + raw, time.monotonic() + 2)
def request(path, camera, *, cursor=None):
client = http.client.HTTPConnection("driver", timeout=3)
client.sock = socket.socket(socket.AF_UNIX)
client.sock.settimeout(3)
try:
client.sock.connect(str(path))
if camera is None:
client.request("GET", "/snapshot")
else:
body = (
camera_command(camera, "details")
if cursor is None
else {"session_id": camera["session_id"], "cursor": cursor}
)
client.request(
"POST",
"/operation" if cursor is None else "/sdk-video",
json.dumps(body),
{"Content-Type": "application/json"},
)
response = client.getresponse()
limit = 65536 if cursor is None else 4 * 1024**2 + 1028
raw = response.read(limit + 1)
if response.status != 200 or len(raw) > limit:
raise RuntimeError("Installed camera bridge is unavailable")
return json.loads(raw) if cursor is None else raw
finally:
client.close()
def active_details(path, camera):
result = request(path, camera)
details = result.get("result", {})
if (
result.get("state") != "complete"
or details.get("preview") != 1
or details.get("recording") != 0
):
raise RuntimeError("An already-active preview and idle recording are required")
calibration = details.get("preview_calibration")
if (
not isinstance(calibration, dict)
or type(calibration.get("revision")) is not int
or calibration["revision"] <= 0
):
raise ValueError("Versioned factory calibration is required")
return calibration
def source(device, session, output, control):
if not re.fullmatch(r"instax4_[0-9a-f]{32}", device) or not re.fullmatch(
r"x4_[0-9a-f]{32}", session
):
raise ValueError("Invalid exact camera identity")
path = Path("/run/mission-core-x4-instances") / device / "driver.sock"
camera = request(path, None)
if (
camera.get("id") != device
or camera.get("session_id") != session
or camera.get("online") is not True
):
raise RuntimeError("The requested camera session changed")
calibration = active_details(path, camera)
emit_message(output, json.dumps({"calibration": calibration, "session": session}).encode())
# The unprivileged renderer must acknowledge initialization before reading
# camera packets. stdin contains only this token after sudo consumes auth.
if read_exact(control, 6, time.monotonic() + 15) != b"START\n":
raise ValueError("Missing explicit renderer readiness")
started = time.monotonic()
cursor, generation, size, count = 0, None, 0, 0
forwarded, discarded = 0, 0
forwarding = WARMUP == 0
while time.monotonic() - started < DURATION:
raw = request(path, camera, cursor=cursor)
received = time.monotonic_ns()
if not raw:
continue
header, data = stitch_packet(raw, calibration["revision"], cursor, generation)
if header["codec"] != calibration["encode_type"]:
raise ValueError("Source codec changed")
size += len(data)
count += 1
if size > MAX_BYTES or count > MAX_PACKETS:
raise ValueError("Live sample exceeds its byte/packet bound")
cursor, generation = header["cursor"], header["generation"]
if not forwarding:
# The driver's bounded late-join queue can contain two seconds of
# prior data. Drain it continuously, then wait for a new complete
# keyframe; do not inject a burst of old frames into SDK playback.
if time.monotonic() - started < WARMUP or not independent_packet(data, header["codec"]):
discarded += 1
continue
forwarding = True
emit_message(output, struct.pack("<Q", received) + raw)
forwarded += 1
if forwarded < 8:
raise RuntimeError("No continuous independently decodable live input")
if active_details(path, camera) != calibration:
raise ValueError("Factory calibration changed during the sample")
emit_message(output, b"")
return {
"packets": count,
"forwarded_packets": forwarded,
"startup_discarded_packets": discarded,
"bytes": size,
"generation": generation,
"seconds": time.monotonic() - started,
"preview_preserved": True,
}
def main(device, session):
if os.geteuid() != 0:
raise RuntimeError("The installed bridge requires explicitly authorized access")
# Also bounds setup, blocked pipes and a lost SSH caller. No cleanup removes
# files or sends a camera command; this reader owns no camera lifecycle.
signal.alarm(48)
os.set_blocking(sys.stdout.fileno(), False)
try:
result = source(device, session, sys.stdout.buffer, sys.stdin.buffer)
print(json.dumps({"source_complete": True, **result}), file=sys.stderr, flush=True)
finally:
signal.alarm(0)
@@ -0,0 +1,769 @@
"""Versioned, unprivileged MediaSDK qualification on the existing Ubuntu Mini.
Stage, compile and execute are distinct commands. Compilation never runs SDK
code. Execution has no network, USB, host sockets or writable host OS paths.
This profile establishes library initialization only, never stitched-frame or
real-time quality acceptance. Missing system dependencies are reported, not
installed. All files belong to the bounded qualification directory.
"""
import argparse
import concurrent.futures
import ctypes
import fcntl
import hashlib
import json
import os
import platform
import pwd
import re
import resource
import shutil
import signal
import struct
import subprocess
import sys
import tarfile
import time
import urllib.request
import zipfile
from datetime import UTC, datetime
from pathlib import Path, PurePosixPath
SCHEMA = "missioncore.insta360.media-qualification/v1"
ARCHIVE_BYTES = 2039751710
ARCHIVE_SHA = "c22890a9d51164599324429a68d62cec0278e4a4a17f0c126cbfb0a20073a2f0"
ARCHIVE_URL = "https://wassets.insta360.com/common/8f722c654d8a43f88944337be023922c/Linux_CameraSDK-2.1.8_MediaSDK-3.1.5.zip"
MEMBER = "Linux_CameraSDK-2.1.8_MediaSDK-3.1.5/MediaSDK-3.1.5-20260819-linux64.tar_1787191716602.gz"
PREFIX = "opt/MediaSDK-3.1.5-linux/"
MAX_EXPANDED = 13 * 1024**3
def digest(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def stamp():
return {"utc": datetime.now(UTC).isoformat(), "monotonic": time.monotonic()}
def relative(name):
name = name.removeprefix("./")
path = PurePosixPath(name)
if path.is_absolute() or ".." in path.parts or "\\" in name or path.as_posix() != name:
raise ValueError("Unsafe vendor archive entry")
if not name.startswith(PREFIX):
raise ValueError("Vendor entry outside the declared runtime")
result = name[len(PREFIX) :]
if not result or not result.startswith(("lib/", "bin/")):
raise ValueError("Unexpected vendor runtime entry")
return result
def download_range(root, start, end):
"""Bound concurrency and verify the server actually honored the byte range."""
target = root / f"{start}-{end}.part"
receipt = target.with_suffix(".json")
if target.exists() and receipt.exists():
saved = json.loads(receipt.read_text())
if target.stat().st_size == end - start + 1 and digest(target) == saved["sha256"]:
return target
raise ValueError("Previously completed download part changed")
partial = target.with_suffix(".partial")
for attempt in range(3):
try:
request = urllib.request.Request(
ARCHIVE_URL,
headers={"Range": f"bytes={start}-{end}", "Accept-Encoding": "identity"},
)
# This is an incomplete, artifact-owned transfer, never accepted evidence.
if partial.is_symlink():
raise ValueError("Unexpected download symlink")
with (
urllib.request.urlopen(request, timeout=30) as response,
partial.open("wb") as output,
):
if (
response.url != ARCHIVE_URL
or response.status != 206
or response.headers.get("Content-Range")
!= f"bytes {start}-{end}/{ARCHIVE_BYTES}"
):
raise ValueError("Vendor returned a different archive range")
size = 0
while chunk := response.read(min(1024 * 1024, end - start + 2 - size)):
size += len(chunk)
if size > end - start + 1:
raise ValueError("Vendor range is oversized")
output.write(chunk)
if size != end - start + 1:
raise ValueError("Vendor range is incomplete")
partial.rename(target)
receipt.write_text(json.dumps({"sha256": digest(target)}))
return target
except (OSError, TimeoutError):
if attempt == 2:
raise
raise RuntimeError("Download retries exhausted")
def source_archive(root, prefix=None):
target = root / "vendor.zip"
if target.exists():
if (
target.is_symlink()
or target.stat().st_size != ARCHIVE_BYTES
or digest(target) != ARCHIVE_SHA
):
raise ValueError("Existing vendor archive differs from the approved download")
return target
parts = root / "download"
parts.mkdir(mode=0o700, exist_ok=True)
start = prefix.stat().st_size if prefix else 0
if not 0 <= start < ARCHIVE_BYTES:
raise ValueError("Invalid source prefix size")
ranges = [
(pos, min(ARCHIVE_BYTES - 1, pos + 8 * 1024**2 - 1))
for pos in range(start, ARCHIVE_BYTES, 8 * 1024**2)
]
completed, updated = start, time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
pending = {pool.submit(download_range, parts, a, b): (a, b) for a, b in ranges}
for future in concurrent.futures.as_completed(pending):
future.result()
a, b = pending[future]
completed += b - a + 1
if time.monotonic() - updated >= 20:
print(
json.dumps({"phase": "download", "bytes": completed, "total": ARCHIVE_BYTES}),
flush=True,
)
updated = time.monotonic()
partial = root / "vendor.zip.partial"
if partial.is_symlink():
raise ValueError("Unexpected archive symlink")
with partial.open("wb") as output:
inputs = ([prefix] if prefix else []) + [parts / f"{a}-{b}.part" for a, b in ranges]
for item in inputs:
with item.open("rb") as source:
shutil.copyfileobj(source, output, 1024 * 1024)
if partial.stat().st_size != ARCHIVE_BYTES or digest(partial) != ARCHIVE_SHA:
raise ValueError("Vendor archive checksum mismatch")
partial.rename(target)
# Completed bytes have been verified as exactly the approved vendor archive.
for item in parts.iterdir():
item.unlink()
parts.rmdir()
return target
def extract_runtime(archive, target):
if target.exists():
raise ValueError("Do not replace a qualification runtime")
target.mkdir(mode=0o700)
rows, links, total, names = [], [], 0, set()
with (
zipfile.ZipFile(archive) as zipped,
zipped.open(MEMBER) as stream,
tarfile.open(fileobj=stream, mode="r|gz") as outer,
):
package = next(
item
for item in outer
if item.isfile() and item.name.endswith("/MediaSDK-3.1.5-linux-amd64.deb")
)
deb = outer.extractfile(package)
if deb.read(8) != b"!<arch>\n":
raise ValueError("Invalid vendor Debian archive")
while header := deb.read(60):
if len(header) != 60 or header[58:] != b"`\n":
raise ValueError("Invalid Debian member")
size = int(header[48:58])
if not 0 <= size <= ARCHIVE_BYTES:
raise ValueError("Oversized Debian member")
if header[:16].decode().strip().rstrip("/") == "data.tar.gz":
with tarfile.open(fileobj=deb, mode="r|gz") as payload:
for item in payload:
if item.isdir():
continue
name = relative(item.name)
if name in names or len(names) >= 512:
raise ValueError("Duplicate or excessive vendor entries")
names.add(name)
if item.issym() or item.islnk():
if item.islnk():
link = relative(item.linkname)
else:
raw = PurePosixPath(item.linkname)
if raw.is_absolute() or ".." in raw.parts or "\\" in item.linkname:
raise ValueError("Unsafe vendor link")
link = (PurePosixPath(name).parent / raw).as_posix()
links.append((name, link))
continue
if not item.isfile() or not 0 <= item.size <= 3 * 1024**3:
raise ValueError("Unsupported vendor entry")
total += item.size
if total > MAX_EXPANDED:
raise ValueError("Expanded vendor payload exceeds the profile")
dest = target / name
dest.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
checksum = hashlib.sha256()
with payload.extractfile(item) as source, dest.open("xb") as output:
while chunk := source.read(1024 * 1024):
checksum.update(chunk)
output.write(chunk)
dest.chmod(0o600)
rows.append(
{"path": name, "bytes": item.size, "sha256": checksum.hexdigest()}
)
break
remaining = size + size % 2
while remaining:
chunk = deb.read(min(remaining, 1024 * 1024))
if not chunk:
raise ValueError("Truncated Debian member")
remaining -= len(chunk)
else:
raise ValueError("Vendor payload missing")
# Resolve only links to packaged regular files; no host paths or link cycles.
pending = links[:]
while pending:
next_pending = []
for name, link in pending:
source, dest = target / link, target / name
if not source.is_file():
next_pending.append((name, link))
continue
dest.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
os.link(source, dest)
rows.append({"path": name, "hardlink": link})
if len(next_pending) == len(pending):
raise ValueError("Unresolved vendor link")
pending = next_pending
return rows
def verify_runtime(root):
manifest = json.loads((root / "runtime.json").read_text())
if manifest.get("archive_sha256") != ARCHIVE_SHA:
raise ValueError("Unexpected runtime source")
for item in manifest["files"]:
path = root / "sdk" / item["path"]
if path.is_symlink() or not path.is_file():
raise ValueError("Runtime file missing or substituted")
if "sha256" in item and (
path.stat().st_size != item["bytes"] or digest(path) != item["sha256"]
):
raise ValueError("Runtime checksum changed")
if "hardlink" in item and not path.samefile(root / "sdk" / item["hardlink"]):
raise ValueError("Runtime link changed")
def compile_probe(root):
verify_runtime(root)
output = root / "probe"
if output.exists():
raise ValueError("Do not overwrite a compiled qualification")
subprocess.run(
[
"/usr/bin/g++",
"-std=c++17",
"-pthread",
"-O1",
"-Wall",
"-Wextra",
"-Werror",
"-I",
str(root / "include"),
str(root / "media_probe.cpp"),
"-L",
str(root / "sdk/lib"),
"-Wl,--allow-shlib-undefined",
"-Wl,--disable-new-dtags,-rpath," + str(root / "sdk/lib") + ":" + str(root / "compat"),
"-lMediaSDK",
"-o",
str(output),
],
check=True,
timeout=120,
env={"PATH": "/usr/bin:/bin", "LANG": "C.UTF-8"},
)
(root / "binary.json").write_text(
json.dumps(
{
"sha256": digest(output),
"scope": json.loads((root / "profile.json").read_text())["mode"],
**stamp(),
}
)
)
def limit_child():
os.nice(10)
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
resource.setrlimit(resource.RLIMIT_AS, (8 * 1024**3, 8 * 1024**3))
resource.setrlimit(resource.RLIMIT_CPU, (60, 60))
resource.setrlimit(resource.RLIMIT_FSIZE, (16 * 1024**2, 16 * 1024**2))
def network_filter():
"""x86_64 seccomp: no network/Unix sockets or io_uring escape path.
Forbid socket syscalls before vendor code runs. Landlock independently
constrains filesystem/device access and cross-domain signals.
"""
instructions = [
(0x20, 0, 0, 4), # architecture
(0x15, 1, 0, 0xC000003E),
(0x06, 0, 0, 0x80000000), # kill non-x86_64
(0x20, 0, 0, 0), # syscall number
(0x35, 0, 1, 0x40000000),
(0x06, 0, 0, 0x80000000), # kill x32 ABI
]
for number in [*range(41, 56), 288, 299, 307, 425, 426, 427]:
instructions += [(0x15, 0, 1, number), (0x06, 0, 0, 0x00050001)]
instructions += [(0x06, 0, 0, 0x7FFF0000)]
return b"".join(struct.pack("HBBI", *row) for row in instructions)
def restrict_process(root, work, software_rendering=False):
"""Add kernel-enforced restrictions without modifying host policy or namespaces."""
limit_child()
libc = ctypes.CDLL(None, use_errno=True)
libc.syscall.restype = ctypes.c_long
def check(result):
if result < 0:
raise OSError(ctypes.get_errno(), "Cannot enforce qualification isolation")
return result
if check(libc.syscall(444, 0, 0, 1)) < 6:
raise RuntimeError("Qualification requires Landlock ABI 6 or newer")
class Ruleset(ctypes.Structure):
_fields_ = [
("fs", ctypes.c_uint64),
("network", ctypes.c_uint64),
("scoped", ctypes.c_uint64),
]
class Rule(ctypes.Structure):
_pack_ = 1
_fields_ = [("access", ctypes.c_uint64), ("parent", ctypes.c_int)]
attr = Ruleset(0xFFFF, 0, 3)
ruleset = check(libc.syscall(444, ctypes.byref(attr), ctypes.sizeof(attr), 0))
read = 1 | 4 | 8
writable = 2 | 4 | 8 | 16 | 32 | 128 | 256 | 4096 | 8192 | 16384
paths = [
(p, read)
for p in (
"/usr",
"/lib",
"/lib64",
"/etc/ld.so.cache",
"/etc/vulkan",
"/etc/drirc",
"/etc/localtime",
"/sys",
"/proc/cpuinfo",
"/proc/meminfo",
"/proc/self",
str(root / "sdk"),
str(root / "compat"),
str(root / "probe"),
str(root / "input.bin"),
str(root / "original.insv"),
)
]
paths += [
(str(work), writable),
("/dev/null", 2 | 4 | 32768),
("/dev/urandom", 4),
("/dev/random", 4),
]
if not software_rendering:
paths.append(("/dev/dri", 2 | 4 | 8 | 32768))
try:
for name, rights in paths:
path = Path(name)
if not path.exists():
continue
if not path.is_dir():
rights &= 1 | 2 | 4 | 16384 | 32768
fd = os.open(name, os.O_PATH | os.O_CLOEXEC)
try:
entry = Rule(rights, fd)
check(libc.syscall(445, ruleset, 1, ctypes.byref(entry), 0))
finally:
os.close(fd)
check(libc.prctl(38, 1, 0, 0, 0)) # PR_SET_NO_NEW_PRIVS
check(libc.syscall(446, ruleset, 0))
finally:
os.close(ruleset)
class Filter(ctypes.Structure):
_fields_ = [("length", ctypes.c_ushort), ("instructions", ctypes.c_void_p)]
code = network_filter()
buffer = ctypes.create_string_buffer(code)
program = Filter(len(code) // 8, ctypes.cast(buffer, ctypes.c_void_p))
check(libc.prctl(22, 2, ctypes.byref(program), 0, 0)) # PR_SET_SECCOMP, FILTER
def execute_probe(root, environment_only=False, debug=False, attempt=1):
if type(attempt) is not int or not 1 <= attempt <= 3 or (environment_only and attempt != 1):
raise ValueError("Invalid bounded qualification attempt")
profile = {} if environment_only else json.loads((root / "profile.json").read_text())
if type(profile.get("software_rendering", False)) is not bool:
raise ValueError("Invalid software-rendering profile")
mode = "environment" if environment_only else profile["mode"]
if mode not in (
"environment",
"initialization",
"synthetic-render",
"recorded-render",
"original-render",
):
raise ValueError("Unknown qualification profile")
if not environment_only:
verify_runtime(root)
binary = json.loads((root / "binary.json").read_text())
if digest(root / "probe") != binary["sha256"]:
raise ValueError("Qualification binary changed")
name = "environment" if environment_only else "debug" if debug else "run"
if attempt != 1:
name += "-" + str(attempt)
work = root / name
work.mkdir(mode=0o700)
(work / "logs").mkdir(mode=0o700)
if environment_only:
script = """import errno,json,os,socket,sys
for family in (socket.AF_INET,socket.AF_INET6,socket.AF_UNIX):
try: socket.socket(family,socket.SOCK_STREAM)
except OSError as error: assert error.errno==errno.EPERM
else: raise RuntimeError('Socket isolation failed')
try: open(sys.argv[1],'xb')
except OSError as error: assert error.errno==errno.EACCES
else: raise RuntimeError('Filesystem isolation failed')
for path in ('/home','/run','/dev/bus/usb'):
try: os.listdir(path)
except OSError as error: assert error.errno in (errno.EACCES,errno.ENOENT)
else: raise RuntimeError('Private/device directory isolation failed')
with open('write-check','xb') as output: output.write(b'owned sandbox data')
os.unlink('write-check')
assert os.geteuid()!=0
print(json.dumps({'network_blocked':True,'host_writes_blocked':True,'usb_blocked':True,'private_paths_blocked':True,'work_writable':True,'unprivileged':True}))
"""
command = ["/usr/bin/python3", "-c", script, str(root / "deny-write-probe")]
else:
command = [str(root / "probe"), str(work / "logs")]
if mode in ("synthetic-render", "recorded-render"):
command += [str(root / "input.bin"), str(root / "sdk/bin/models") + "/"]
if "stitch_type" in profile:
if profile["stitch_type"] not in ("dynamic", "template"):
raise ValueError("Invalid recorded-source stitch type")
command += [profile["stitch_type"]]
elif mode == "original-render":
original = json.loads((root / "original.json").read_text())
if (root / "original.insv").stat().st_size != original["bytes"] or digest(
root / "original.insv"
) != original["sha256"]:
raise ValueError("Original changed after verified export")
seconds = profile["original_seconds"]
if type(seconds) is not int or not 0 <= seconds <= 240:
raise ValueError("Invalid original sample time")
command += [
str(root / "original.insv"),
str(root / "sdk/bin/models") + "/",
str(seconds),
]
if debug:
if shutil.which("gdb") != "/usr/bin/gdb":
raise RuntimeError("The bounded diagnostic requires an already installed gdb")
# GDB traces only its own child. The child applies the exact sandbox
# before exec/loading any vendor code; no SDK runs in the debugger.
launcher = """import ctypes,hashlib,json,os,sys,zipfile
from pathlib import Path
with zipfile.ZipFile(sys.argv[1]) as z:
source=z.read('media_qualification.py');m=json.loads(z.read('manifest.json'))
assert hashlib.sha256(source).hexdigest()==m['files']['media_qualification.py']
ns={'__name__':'diagnostic_tracee'};exec(compile(source,'media_qualification.py','exec'),ns)
root,work=Path(sys.argv[2]),Path(sys.argv[3])
profile=json.loads((root/'profile.json').read_text())
assert ctypes.CDLL(None).prctl(1,9)==0
ns['restrict_process'](root,work,profile.get('software_rendering',False))
os.execve(sys.argv[4],sys.argv[4:],dict(os.environ))
"""
launcher_file = work / "tracee.py"
launcher_file.write_text(launcher)
command = [
"/usr/bin/gdb",
"--nx",
"--nh",
"--batch",
"-ex",
"set debuginfod enabled off",
"-ex",
"set auto-load off",
"-ex",
"set startup-with-shell off",
"-ex",
"set disable-randomization off",
"-ex",
"set pagination off",
"-ex",
"set confirm off",
"-ex",
"run",
"-ex",
"info program",
"-ex",
"thread apply all bt 16",
"--args",
"/usr/bin/python3",
"-I",
str(launcher_file),
str(Path(sys.argv[0]).resolve()),
str(root),
str(work),
*command,
]
report = {
"schema": SCHEMA,
"started": stamp(),
"scope": "isolation-only-no-sdk" if environment_only else mode + "-no-camera",
"real_camera_frame_verified": False,
"debugger_only": debug,
"attempt": attempt,
}
with (work / "stdout.log").open("xb") as stdout, (work / "stderr.log").open("xb") as stderr:
process = subprocess.Popen(
command,
stdout=stdout,
stderr=stderr,
start_new_session=True,
preexec_fn=None
if debug
else lambda: restrict_process(root, work, profile.get("software_rendering", False)),
cwd=work,
env={
"PATH": "/usr/bin:/bin",
"LANG": "C.UTF-8",
"OMP_NUM_THREADS": "2",
"OPENBLAS_NUM_THREADS": "2",
"LP_NUM_THREADS": "2",
"TMPDIR": str(work),
"XDG_CACHE_HOME": str(work),
"DEBUGINFOD_URLS": "",
# This versioned profile runs without the operator's display
# session. Mesa must create its offscreen context directly.
**(
{"EGL_PLATFORM": "surfaceless", "EGL_LOG_LEVEL": "debug"}
if mode in ("synthetic-render", "recorded-render", "original-render")
else {}
),
**(
{"LIBGL_ALWAYS_SOFTWARE": "true", "GALLIUM_DRIVER": "llvmpipe"}
if profile.get("software_rendering")
else {}
),
},
)
try:
report["debugger_exit_code" if debug else "exit_code"] = process.wait(
timeout=70 if debug else 45
)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
report["timeout"] = True
report["finished"] = stamp()
usage = resource.getrusage(resource.RUSAGE_CHILDREN)
report["child_usage"] = {
"user_seconds": usage.ru_utime,
"system_seconds": usage.ru_stime,
"max_rss_kib": usage.ru_maxrss,
}
report["stdout"] = (work / "stdout.log").read_text(errors="replace")[-8192:]
report["stderr"] = (work / "stderr.log").read_text(errors="replace")[-8192:]
(root / (name + ".json")).write_text(json.dumps(report, indent=2))
print(json.dumps(report), flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"command",
choices=("stage", "compile", "run", "environment", "debug", "run-live", "source-live"),
)
parser.add_argument("--device-id")
parser.add_argument("--session-id")
parser.add_argument("--download-prefix", type=Path)
parser.add_argument("--reuse-stage", type=Path)
parser.add_argument("--attempt", type=int, choices=(1, 2, 3), default=1)
args = parser.parse_args()
if args.attempt != 1 and args.command not in ("run", "debug"):
raise ValueError("Repeated attempts apply only to isolated probe execution")
if (
platform.system() != "Linux"
or platform.machine() != "x86_64"
or (os.geteuid() == 0 and args.command != "source-live")
):
raise RuntimeError("Qualification requires the unprivileged Ubuntu x86_64 operator")
if not Path("/etc/os-release").read_text().startswith('PRETTY_NAME="Ubuntu 24.04'):
raise RuntimeError("This exploratory profile is scoped to the current Ubuntu 24.04 Mini")
with zipfile.ZipFile(sys.argv[0]) as artifact:
raw = artifact.read("manifest.json")
manifest = json.loads(raw)
ident = hashlib.sha256(raw).hexdigest()[:24]
if Path(sys.argv[0]).name != f"mission-core-x4-media-qualify-{ident}.pyz":
raise ValueError("Qualification artifact identity mismatch")
files = {name: artifact.read(name) for name in manifest["files"]}
if any(
hashlib.sha256(data).hexdigest() != manifest["files"][name]
for name, data in files.items()
):
raise ValueError("Qualification source checksum mismatch")
live = args.command in ("source-live", "run-live")
if live:
if (
json.loads(files["profile.json"])["mode"] != "live-render"
or not isinstance(args.device_id, str)
or not re.fullmatch(r"instax4_[0-9a-f]{32}", args.device_id)
or not isinstance(args.session_id, str)
or not re.fullmatch(r"x4_[0-9a-f]{32}", args.session_id)
):
raise ValueError("Live qualification needs an exact admitted camera/session")
elif args.device_id is not None or args.session_id is not None:
raise ValueError("Camera identities only apply to live qualification")
if args.command == "source-live":
from media_live_source import main as source_main
source_main(args.device_id, args.session_id)
return
root = Path("/var/tmp") / ("mission-core-x4-media-" + ident)
if root.is_symlink():
raise ValueError("Qualification staging cannot be a symlink")
root.mkdir(mode=0o700, exist_ok=True)
if root.stat().st_uid != os.geteuid() or root.stat().st_mode & 0o077:
raise ValueError("Qualification staging ownership changed")
lock = (root / "qualification.lock").open("a")
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
if args.download_prefix:
expected = Path(
"/var/tmp/mission-core-x4-media-b47176f7987d48427af11997/vendor.zip.partial"
)
if args.command != "stage" or args.download_prefix != expected or expected.is_symlink():
raise ValueError("Only the inspected previous transfer may be resumed")
parent = expected.parent
if (
parent.is_symlink()
or parent.stat().st_uid != os.geteuid()
or parent.stat().st_mode & 0o077
):
raise ValueError("Unsafe previous transfer directory")
old = b"/var/tmp/mission-core-x4-media-qualify-b47176f7987d48427af11997.pyz"
for proc in Path("/proc").glob("[0-9]*/cmdline"):
try:
if old in proc.read_bytes().split(b"\0"):
raise ValueError("Previous transfer is still running")
except (FileNotFoundError, PermissionError):
continue
if args.reuse_stage and args.command != "stage":
raise ValueError("Runtime reuse is a staging operation")
if args.command == "stage":
if shutil.disk_usage(root).free < 16 * 1024**3:
raise RuntimeError("Insufficient free space for the bounded SDK qualification")
for name, data in files.items():
if name.startswith(("include/", "compat/")) or name in (
"media_probe.cpp",
"profile.json",
"input.bin",
"original.json",
):
target = root / name
target.parent.mkdir(mode=0o700, exist_ok=True)
target.write_bytes(data)
if "original.json" in files:
original = json.loads(files["original.json"])
source = Path(original["path"])
owner_root = (
Path(pwd.getpwuid(os.geteuid()).pw_dir)
/ ".local/share/mission-core/qualifications/x4-originals"
)
if (
source.parent != owner_root
or source.is_symlink()
or not re.fullmatch(r"file_[0-9a-f]{32}\.insv", source.name)
or source.stat().st_uid != os.geteuid()
or source.stat().st_mode & 0o077
or source.stat().st_size != original["bytes"]
or not 0 < original["bytes"] <= 8 * 1024**3
or digest(source) != original["sha256"]
):
raise ValueError("Original is not the verified owner-private export")
os.link(source, root / "original.insv")
if args.reuse_stage:
source = args.reuse_stage
expected = Path("/var/tmp/mission-core-x4-media-4c930fafc280d49210dd2d4d")
if (
source != expected
or source.is_symlink()
or source.stat().st_uid != os.geteuid()
or source.stat().st_mode & 0o077
):
raise ValueError("Unexpected prior SDK qualification stage")
verify_runtime(source)
if digest(source / "vendor.zip") != ARCHIVE_SHA:
raise ValueError("Prior archive checksum changed")
(root / "sdk").mkdir(mode=0o700)
previous = json.loads((source / "runtime.json").read_text())
for item in previous["files"]:
target = root / "sdk" / item["path"]
target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
os.link(source / "sdk" / item["path"], target)
os.link(source / "vendor.zip", root / "vendor.zip")
(root / "runtime.json").write_text(json.dumps(previous, indent=2))
archive = source_archive(root, args.download_prefix)
if not (root / "runtime.json").exists():
rows = extract_runtime(archive, root / "sdk")
(root / "runtime.json").write_text(
json.dumps({"archive_sha256": ARCHIVE_SHA, "files": rows, **stamp()}, indent=2)
)
verify_runtime(root)
print(json.dumps({"phase": "staged", "root": str(root), **stamp()}), flush=True)
elif args.command == "compile":
for name, data in files.items():
if (
name.startswith(("include/", "compat/"))
or name in ("media_probe.cpp", "profile.json", "input.bin", "original.json")
) and (root / name).read_bytes() != data:
raise ValueError("Staged qualification source changed")
compile_probe(root)
print(json.dumps({"phase": "compiled", "root": str(root), **stamp()}), flush=True)
else:
if args.command in ("run", "debug", "run-live"):
for name, data in files.items():
if (
name.startswith("compat/")
or name in ("profile.json", "input.bin", "original.json")
) and (root / name).read_bytes() != data:
raise ValueError("Compatibility dependency changed")
if args.command == "run-live":
from media_live_qualification import execute_live
execute_live(root, args.device_id, args.session_id)
else:
execute_probe(
root,
environment_only=args.command == "environment",
debug=args.command == "debug",
attempt=args.attempt,
)
if __name__ == "__main__":
main()
@@ -11,6 +11,8 @@ import tempfile
import zipfile
from pathlib import Path
NODE_DEPENDENCIES = ('timescaledb-2-loader-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb', 'timescaledb-2-oss-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb')
PROFILES = {
"missioncore.insta360.owner-release/v1": (
"mission-core-insta360-x4",
@@ -83,6 +85,9 @@ def main():
package = package_id + "_" + version + "_amd64.deb"
if hashlib.sha256(archive.read("__main__.py")).hexdigest() != manifest["entrypoint_sha256"]:
raise ValueError("Release entry point changed")
dependencies = manifest.get("dependencies", [])
if dependencies and (manifest["schema"] != "missioncore.node.owner-release/v1" or dependencies != list(NODE_DEPENDENCIES)):
raise ValueError("Unexpected release dependencies")
allowed = {
"release.json",
"__main__.py",
@@ -90,6 +95,7 @@ def main():
"install_release.py",
package,
}
allowed.update(dependencies)
if set(archive.namelist()) != allowed or len(archive.namelist()) != len(allowed):
raise ValueError("Invalid release contents")
if set(manifest["files"]) != allowed - {"release.json", "__main__.py"}:
@@ -117,6 +123,7 @@ def main():
"--simulate",
"--no-remove",
"install",
*[str(folder / name) for name in dependencies],
str(folder / package),
],
capture_output=True,
+52 -33
View File
@@ -91,6 +91,57 @@ def bindings():
return {ident: value for ident, value in found.items() if ident not in duplicates}
def reconcile(known, startup=False):
observed = bindings()
current = {
ident: {
"port": item.port,
"bus": item.bus,
"address": item.address,
"revision": active().name,
}
for ident, item in observed.items()
}
changed = False
for ident in list(known):
if current.get(ident) != known[ident]:
systemctl("stop", PREFIX + ident + ".service")
path = UNITS / (PREFIX + ident + ".service")
if path.exists():
trusted(path).unlink()
del known[ident]
changed = True
additions = [ident for ident in current if ident not in known]
for ident in additions:
item = observed[ident]
try:
if read_binding(item.port) != item:
continue
except (OSError, ValueError):
# Enumeration and revalidation are separate sysfs reads.
continue
write(UNITS / (PREFIX + ident + ".service"), unit(item))
known[ident] = current[ident]
changed = True
if changed:
write(CONTROL / "bindings.json", json.dumps(known, sort_keys=True).encode())
systemctl("daemon-reload")
for ident in list(current) if startup else additions:
if ident in known:
try:
systemctl("start", PREFIX + ident + ".service")
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
# A disappearing BindPaths node can fail unit setup. Keep supervising
# other cameras; retry this one only after its USB binding changes.
# A timed-out start may still succeed, so never replay it blindly.
print(
f"X4 worker start on USB {observed[ident].port} failed "
f"({type(exc).__name__}); waiting for a new USB binding",
file=sys.stderr,
flush=True,
)
def main():
if os.geteuid() or len(sys.argv) != 1:
raise RuntimeError("Use the fixed installed supervisor unit")
@@ -116,39 +167,7 @@ def main():
raise RuntimeError("Invalid previous camera binding")
known[ident] = info
while not stopping:
observed = bindings()
current = {
ident: {
"port": item.port,
"bus": item.bus,
"address": item.address,
"revision": active().name,
}
for ident, item in observed.items()
}
changed = False
for ident in list(known):
if current.get(ident) != known[ident]:
systemctl("stop", PREFIX + ident + ".service")
path = UNITS / (PREFIX + ident + ".service")
if path.exists():
trusted(path).unlink()
del known[ident]
changed = True
additions = [ident for ident in current if ident not in known]
for ident in additions:
item = observed[ident]
if read_binding(item.port) != item:
continue
write(UNITS / (PREFIX + ident + ".service"), unit(item))
known[ident] = current[ident]
changed = True
if changed:
write(record, json.dumps(known, sort_keys=True).encode())
systemctl("daemon-reload")
for ident in list(current) if startup else additions:
if ident in known:
systemctl("start", PREFIX + ident + ".service")
reconcile(known, startup=startup)
startup = False
time.sleep(1)
@@ -0,0 +1,297 @@
"""Installer acquisition race checks; no OS, camera or package changes."""
import hashlib
import importlib.util
import io
import json
import unittest
from pathlib import Path
from unittest.mock import Mock, patch
spec = importlib.util.spec_from_file_location(
"x4_installer", Path(__file__).with_name("install_release.py")
)
owner = importlib.util.module_from_spec(spec)
spec.loader.exec_module(owner)
CAMERA = {
"id": "instax4_" + "a" * 32,
"session_id": "x4_session",
"online": True,
"preparation_safe": True,
}
PATH = Path("/run/mission-core-x4-instances") / CAMERA["id"] / "driver.sock"
class OriginalExportTests(unittest.TestCase):
def test_invalid_source_and_missing_owner_stop_before_download(self):
with patch.object(owner, "request") as request:
for source in ("/etc/passwd", "https://camera/file.insv"):
with self.assertRaises(ValueError):
owner.verify_original(PATH, CAMERA, source)
with (
patch.dict(owner.os.environ, {"SUDO_UID": "0"}),
self.assertRaises(RuntimeError),
):
owner.verify_original(PATH, CAMERA, "/DCIM/test.insv")
request.assert_not_called()
def test_export_drops_all_privileges_and_confirms_owner_hash(self):
digest = hashlib.sha256(b"original").hexdigest()
result = {"state": "complete", "bytes": 8, "sha256": digest}
child = Mock(returncode=0)
child.stdin.closed = False
child.stdout = io.BytesIO(json.dumps(dict(result, path="/owner/private.insv")).encode())
child.stderr = io.BytesIO()
with (
patch.dict(owner.os.environ, {"SUDO_UID": "1000"}),
patch.object(owner.pwd, "getpwuid", return_value=Mock(pw_gid=1000)),
patch.object(owner, "request", side_effect=[result, b"original"]),
patch.object(owner.subprocess, "Popen", return_value=child) as process,
):
value = owner.verify_original(PATH, CAMERA, "/DCIM/test.insv")
self.assertEqual(value["sha256"], digest)
self.assertEqual(process.call_args.kwargs["user"], 1000)
self.assertEqual(process.call_args.kwargs["group"], 1000)
self.assertEqual(process.call_args.kwargs["extra_groups"], [])
child.stdin.write.assert_called_once_with(b"original")
compile(owner.OWNER_ORIGINAL_EXPORT, "owner-original-export", "exec")
class PauseTests(unittest.TestCase):
def setUp(self):
self.prepare = patch.object(owner, "PREPARE", Mock())
self.marker = patch.object(owner, "MAINTENANCE", Mock())
self.instances = patch.object(owner, "INSTANCES", Mock())
self.prepare.start().exists.return_value = True
self.marker.start().exists.return_value = False
self.instances.start().glob.return_value = [PATH]
self.addCleanup(patch.stopall)
self.report = {}
self.actions = []
def request(self, path, command=None):
if command is None:
return dict(CAMERA)
self.actions.append(command["action_id"])
if command["action_id"] == "details":
return {"state": "complete", "result": {"recording": 0, "preview": 1}}
return {"state": "complete"}
def test_preview_is_paused_after_authentication_and_gate_is_acquired(self):
run = Mock()
with patch.object(owner, "request", side_effect=self.request):
self.assertTrue(owner.pause_previews(run, self.report, Mock()))
self.assertEqual(self.actions, ["details", "preview.stop"])
self.assertEqual(run.call_args.args[1][-1], "--quiesce")
self.assertEqual(self.report["preview_pause"]["state"], "complete")
def test_recording_or_unknown_recording_blocks_before_any_stop(self):
for recording in (1, None):
run = Mock()
with patch.object(
owner,
"request",
side_effect=[
CAMERA,
{"state": "complete", "result": {"recording": recording, "preview": 1}},
],
) as request:
with self.assertRaises(RuntimeError):
owner.pause_previews(run, {}, Mock())
self.assertEqual(request.call_count, 2)
run.assert_not_called()
def test_all_cameras_are_checked_before_first_pause(self):
second = dict(CAMERA, id="instax4_" + "b" * 32)
owner.INSTANCES.glob.return_value = [
PATH,
PATH.parent.parent / second["id"] / "driver.sock",
]
with patch.object(
owner,
"request",
side_effect=[
CAMERA,
{"state": "complete", "result": {"recording": 0, "preview": 1}},
second,
{"state": "complete", "result": {"recording": 1}},
],
) as request:
with self.assertRaises(RuntimeError):
owner.pause_previews(Mock(), {}, Mock())
actions = [
call.args[1]["action_id"] for call in request.call_args_list if len(call.args) > 1
]
self.assertEqual(actions, ["details", "details"])
def test_unknown_stop_result_is_not_retried(self):
run = Mock()
with (
patch.object(
owner,
"request",
side_effect=[
CAMERA,
{"state": "complete", "result": {"recording": 0, "preview": 1}},
{"state": "unknown"},
],
),
self.assertRaises(RuntimeError),
):
owner.pause_previews(run, self.report, Mock())
run.assert_not_called()
def test_viewer_restart_before_gate_rechecks_camera_and_has_bounded_retry(self):
run = Mock(side_effect=[RuntimeError("busy"), None])
with patch.object(owner, "request", side_effect=self.request):
self.assertTrue(owner.pause_previews(run, self.report, Mock()))
self.assertEqual(self.actions, ["details", "preview.stop"] * 2)
run = Mock(side_effect=RuntimeError("busy"))
with (
patch.object(owner, "request", side_effect=self.request),
self.assertRaises(RuntimeError),
):
owner.pause_previews(run, {}, Mock())
self.assertEqual(run.call_count, 3)
def test_existing_maintenance_is_not_overwritten(self):
owner.MAINTENANCE.exists.return_value = True
with patch.object(owner, "request") as request:
with self.assertRaises(RuntimeError):
owner.pause_previews(Mock(), {}, Mock())
request.assert_not_called()
def test_no_driver_is_a_clean_host_noop(self):
owner.PREPARE.exists.return_value = False
run = Mock()
self.assertFalse(owner.pause_previews(run, {}, Mock()))
run.assert_not_called()
def test_gate_with_unknown_outcome_is_not_retried(self):
run = Mock(side_effect=RuntimeError("lost reply"))
owner.MAINTENANCE.exists.side_effect = [False, True]
with (
patch.object(owner, "request", side_effect=self.request),
self.assertRaises(RuntimeError),
):
owner.pause_previews(run, {}, Mock())
self.assertEqual(run.call_count, 1)
class StitchSampleTests(unittest.TestCase):
@staticmethod
def packet(cursor=1, **changes):
header = dict(
cursor=cursor,
generation=2,
timestamp=1234,
stream_index=0,
stream_type=0x20,
codec=0,
calibration_revision=4,
bytes=3,
gap=False,
)
header.update(changes)
raw = owner.json.dumps(header).encode()
return owner.struct.pack("!I", len(raw)) + raw + b"raw"
def test_original_bytes_and_vendor_marker_survive(self):
header, data = owner.stitch_packet(self.packet(), 4, 0, None)
self.assertEqual(data, b"raw")
self.assertEqual(header["stream_type"], 0x20)
self.assertEqual(header["codec"], 0)
def test_revision_generation_cursor_gaps_and_types_fail_closed(self):
for changes in (
{"calibration_revision": 5},
{"generation": 3},
{"gap": True},
{"cursor": 8},
{"stream_type": 256},
{"bytes": 2},
{"timestamp": True},
):
with self.assertRaises(ValueError):
owner.stitch_packet(
self.packet(cursor=2, **changes)
if "cursor" not in changes
else self.packet(**changes),
4,
1,
2,
)
def test_capture_failure_stops_only_its_preview(self):
actions = []
def request(path, command=None, **kwargs):
action = command["action_id"]
actions.append(action)
if action == "details":
return {"state": "complete", "result": {"recording": 0, "preview": 0}}
return {"state": "complete"}
with patch.object(owner, "request", side_effect=request), self.assertRaises(RuntimeError):
owner.capture_stitch_input(PATH, CAMERA)
self.assertEqual(actions, ["details", "preview.start", "details", "preview.stop"])
def test_capture_preserves_existing_preview_on_failure(self):
actions = []
def request(path, command=None, **kwargs):
actions.append(command["action_id"])
return {"state": "complete", "result": {"recording": 0, "preview": 1}}
with patch.object(owner, "request", side_effect=request), self.assertRaises(RuntimeError):
owner.capture_stitch_input(PATH, CAMERA)
self.assertEqual(actions, ["details", "details"])
def test_capture_records_exact_consistent_packets_and_restores_idle(self):
calibration = {"revision": 4, "offsets": ["factory"]}
actions, counter = [], 0
def request(path, command=None, **kwargs):
nonlocal counter
if kwargs.get("video"):
counter += 1
return self.packet(counter)
action = command["action_id"]
actions.append(action)
return {
"state": "complete",
"result": {"recording": 0, "preview": 0, "preview_calibration": calibration},
}
with patch.object(owner, "request", side_effect=request):
sample = owner.capture_stitch_input(PATH, CAMERA)
self.assertEqual(len(sample["packets"]), 128)
self.assertEqual(sample["calibration"], calibration)
self.assertEqual(owner.base64.b64decode(sample["packets"][0]["data"]), b"raw")
self.assertFalse(sample["gyro_exposure_forwarded"])
self.assertEqual(actions[-1], "preview.stop")
class ExactPackagePlanTests(unittest.TestCase):
def test_only_requested_upgrade_or_already_installed_is_admitted(self):
owner.admit_package_plan(
b"Inst mission-core-insta360-x4 [0.1.3-11] (0.1.3-12 local-deb [amd64])\n"
b"Conf mission-core-insta360-x4 (0.1.3-12 local-deb [amd64])",
"0.1.3-12",
)
owner.admit_package_plan(b"0 upgraded, 0 newly installed, 0 to remove", "0.1.3-12")
def test_unrelated_install_configure_remove_and_wrong_version_fail(self):
for text in (
"Inst unrelated (1 local [amd64])",
"Conf unrelated (1 local [amd64])",
"Remv unrelated [1]",
"Purg mission-core-insta360-x4 [0.1.3-11]",
"Inst mission-core-insta360-x4 [0.1.3-11] (0.1.3-13 local-deb [amd64])",
):
with self.assertRaises(RuntimeError):
owner.admit_package_plan(text.encode(), "0.1.3-12")
if __name__ == "__main__":
unittest.main()
+184
View File
@@ -0,0 +1,184 @@
"""Private, resumable-by-reading camera originals; never delete camera media.
One transfer owns the worker's control gate. CameraSDK remains inside the
existing USB worker; no root SDK, URL fetching or caller-selected local path.
Interrupted transfers are retained and are never automatically restarted.
"""
import hashlib
import json
import os
import re
import shutil
import threading
import time
from datetime import UTC, datetime
from .lifecycle import acquisition
from .operations import atomic
MAX_BYTES = 8 * 1024**3
CHUNK_BYTES = 1024**2
TIMEOUT = 300
IDENTIFIER = re.compile(r"file_[0-9a-f]{32}")
SOURCE = re.compile(r"/DCIM/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_.-]+\.insv")
def validate_source(value):
if (
not isinstance(value, str)
or len(value) > 1024
or not SOURCE.fullmatch(value)
or any(p in (".", "..") for p in value.split("/"))
):
raise ValueError("Only a listed camera original is admitted")
return value
class Archive:
def __init__(self, camera, root, gate):
self.camera, self.root, self.gate = camera, root, gate
self.root.mkdir(mode=0o700, parents=True, exist_ok=True)
self.lock = threading.Lock()
self.active = None
self.progress = (0, 0)
def folder(self, identifier):
if not isinstance(identifier, str) or not IDENTIFIER.fullmatch(identifier):
raise ValueError("Invalid transfer identity")
return self.root / identifier
def busy(self):
with self.lock:
return self.active is not None
def start(self, identifier, source):
validate_source(source)
folder = self.folder(identifier)
with self.lock:
if folder.exists():
previous = json.loads((folder / "receipt.json").read_text())
if previous["source"] != source:
raise ValueError("Transfer identity already used")
return self._status(identifier)
if self.active or not self.gate.acquire(blocking=False):
raise RuntimeError("Camera control is busy")
try:
if shutil.disk_usage(self.root).free < MAX_BYTES + 1024**3:
raise RuntimeError("Insufficient space for bounded original transfer")
folder.mkdir(mode=0o700)
# Reserve this file without replacing any prior evidence.
with (folder / "original.insv").open("xb"):
pass
receipt = {
"schema": "missioncore.insta360.original/v1",
"id": identifier,
"source": source,
"state": "running",
"started_at": datetime.now(UTC).isoformat(),
}
atomic(folder / "receipt.json", receipt)
self.active, self.progress = identifier, (0, 0)
threading.Thread(target=self._run, args=(folder, receipt), daemon=True).start()
except BaseException:
self.active = None
self.gate.release()
raise
return {"id": identifier, "state": "running", "bytes": 0, "total": 0}
def _run(self, folder, receipt):
finished, cancel = threading.Event(), threading.Event()
started = time.monotonic()
def progress(downloaded, total):
with self.lock:
previous = self.progress[0]
self.progress = (downloaded, total)
if (
not 0 <= downloaded <= MAX_BYTES
or not 0 <= total <= MAX_BYTES
or downloaded > total
or downloaded < previous
):
cancel.set()
def watch():
while not finished.wait(0.1):
if time.monotonic() - started >= TIMEOUT:
cancel.set()
if cancel.is_set():
# Never cancel reentrantly from a vendor callback and never
# release the gate until DownloadCameraFile actually returns.
self.camera.cancel_download()
return
watcher = None
try:
with acquisition():
watcher = threading.Thread(target=watch, daemon=True)
watcher.start()
ok = self.camera.download(receipt["source"], folder / "original.insv", progress)
finished.set()
watcher.join()
size = (folder / "original.insv").stat().st_size
with self.lock:
downloaded, total = self.progress
if (
not ok
or cancel.is_set()
or not 0 < size <= MAX_BYTES
or size != downloaded
or size != total
):
raise RuntimeError("Original transfer was not confirmed")
digest = hashlib.sha256()
with (folder / "original.insv").open("rb") as stream:
while chunk := stream.read(CHUNK_BYTES):
digest.update(chunk)
os.fsync(stream.fileno())
receipt.update(state="complete", bytes=size, sha256=digest.hexdigest())
except Exception:
receipt.update(
state="error", error="Original transfer was not confirmed; partial retained"
)
finally:
finished.set()
if watcher:
watcher.join()
receipt.update(
finished_at=datetime.now(UTC).isoformat(),
duration_seconds=time.monotonic() - started,
)
try:
atomic(folder / "receipt.json", receipt)
finally:
with self.lock:
self.active = None
self.gate.release()
def _status(self, identifier):
value = json.loads((self.folder(identifier) / "receipt.json").read_text())
result = {key: value[key] for key in ("id", "state", "bytes", "sha256") if key in value}
if self.active == identifier:
result.update(bytes=self.progress[0], total=self.progress[1])
elif result["state"] == "running":
result["state"] = "interrupted"
return result
def status(self, identifier):
with self.lock:
return self._status(identifier)
def read(self, identifier, offset):
if type(offset) is not int or not 0 <= offset < MAX_BYTES:
raise ValueError("Invalid original offset")
status = self.status(identifier)
if status["state"] != "complete" or offset >= status["bytes"]:
raise ValueError("Original is not ready or offset is outside file")
path = self.folder(identifier) / "original.insv"
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(fd, "rb") as stream:
if os.fstat(stream.fileno()).st_size != status["bytes"]:
raise RuntimeError("Original changed after transfer")
stream.seek(offset)
return stream.read(min(CHUNK_BYTES, status["bytes"] - offset))
+1
View File
@@ -172,6 +172,7 @@ class Broker:
"firmware": status.get("firmware"),
"layers": [],
"camera_status": status,
"preview_priority_v1": True,
"snapshot": {
"revision": value["revision"],
"observed_at": value["observed_at"],
+1
View File
@@ -1,6 +1,7 @@
"""Public messages are allowlisted; vendor error text never crosses the boundary."""
MESSAGES = {
"preview_capacity": "У камеры уже открыто два просмотра. Закройте лишний просмотр; подключение повторится автоматически.",
"wake_adapter_busy": "Сейчас включается другая камера. Повторите действие позже.",
"wake_identity_missing": "Сначала подключите эту камеру по USB и подготовьте её на борту.",
"wake_identity_conflict": "Не удалось однозначно выбрать камеру для включения.",
+20 -8
View File
@@ -83,6 +83,10 @@ def decode(raw):
or header["stream_index"] not in (0, 1)
or header["codec"] not in (0, 1)
or type(header.get("gap")) is not bool
or (
"stream_type" in header
and (type(header["stream_type"]) is not int or not 0 <= header["stream_type"] <= 255)
)
or not 0 < len(data) <= MAX_PACKET
):
raise ValueError("Invalid video metadata")
@@ -121,41 +125,49 @@ class Feed:
self.source_generation = source["generation"]
self.generation += 1
self.parameters = Parameters()
original_bytes = len(data)
data = self.parameters.packet(source, data)
prefix_bytes = len(data) - original_bytes
while self.queue and (
self.bytes + len(data) > MAX_BYTES or len(self.queue) >= MAX_ENTRIES
):
_, removed, _ = self.queue.popleft()
_, removed, _, _ = self.queue.popleft()
self.bytes -= len(removed)
self.cursor += 1
header = dict(source, cursor=self.cursor, generation=self.generation)
self.queue.append((header, data, time.monotonic()))
# Keep one bounded allocation. The SDK reader receives precisely
# the original callback bytes; browser readers retain late-join
# parameter replay without changing the vendor packet contract.
self.queue.append((header, data, time.monotonic(), prefix_bytes))
self.bytes += len(data)
self.lock.notify_all()
def read(self, cursor, wait=0.1):
def read(self, cursor, wait=0.1, *, original=False):
if type(cursor) is not int or not 0 <= cursor < 2**64:
raise ValueError("Invalid video cursor")
deadline = time.monotonic() + min(max(wait, 0), 0.2)
with self.lock:
while True:
for header, data, observed in self.queue:
for header, data, observed, prefix_bytes in self.queue:
if header["cursor"] > cursor and time.monotonic() - observed < 2:
payload = data[prefix_bytes:] if original else data
return dict(
header, gap=bool(cursor and header["cursor"] != cursor + 1)
), data
header,
bytes=len(payload),
gap=bool(cursor and header["cursor"] != cursor + 1),
), payload
remaining = deadline - time.monotonic()
if remaining <= 0 or self.closed.is_set():
return None
self.lock.wait(remaining)
def reader(self):
def reader(self, *, original=False):
with self.lock:
cursor = self.cursor
def read():
nonlocal cursor
value = self.read(cursor, wait=0)
value = self.read(cursor, wait=0, original=original)
if value is not None:
cursor = value[0]["cursor"]
return value
+84 -10
View File
@@ -16,6 +16,8 @@ from fractions import Fraction
import aioice.ice
import av
from missioncore_plugin_sdk.link_budget import budget_peer
from missioncore_plugin_sdk.media_budget import adapt_peer, cap_video_sender
from aiortc import (
RTCConfiguration,
RTCPeerConnection,
@@ -26,7 +28,7 @@ from aiortc import (
from aiortc.mediastreams import MediaStreamError
from .errors import failure
from .frames import decode
from .frames import START_CODE, decode
from .http import request
NETWORKS = tuple(
@@ -65,6 +67,10 @@ def admit_sdp(sdp):
raise ValueError("Camera preview requires a private network")
class PreviewCapacityError(ValueError):
"""No peer was admitted; retrying cannot repeat a camera action."""
class Source:
def __init__(self, path, session):
self.path, self.session = path, session
@@ -75,11 +81,28 @@ class Source:
self.started = time.monotonic()
self.closed = threading.Event()
self.thread = threading.Thread(target=self.pump, daemon=True)
self.packets = self.gaps = self.resets = self.decode_errors = self.keyframes = 0
self.packet_at = self.keyframe_at = None
self.generation = None
self.failure = None
def current(self):
with self.lock:
return self.sequence, self.frame, self.observed
def health(self):
"""Bounded in-memory counters; no encoded media or monitoring history."""
with self.lock:
now = time.monotonic()
return {
"packets": self.packets, "frames": self.sequence,
"packet_age_ms": round((now - self.packet_at) * 1000) if self.packet_at is not None else None,
"keyframes": self.keyframes,
"keyframe_age_ms": round((now - self.keyframe_at) * 1000) if self.keyframe_at is not None else None,
"gaps": self.gaps, "resets": self.resets, "decode_errors": self.decode_errors,
"generation": self.generation, "closed": self.closed.is_set(), "failure": self.failure,
}
def pump(self):
cursor, key, decoder, resized_at = 0, None, None, 0.0
try:
@@ -98,13 +121,38 @@ class Source:
cursor = header["cursor"]
if header["stream_index"] != 0:
continue
now = time.monotonic()
keyframe = any(
(data[marker.end()] & 31) == 5 if header["codec"] == 0
else ((data[marker.end()] >> 1) & 63) in (16, 17, 18, 19, 20, 21)
for marker in START_CODE.finditer(data) if marker.end() < len(data)
)
with self.lock:
self.packets += 1
self.packet_at = now
self.generation = header["generation"]
self.gaps += int(header["gap"])
if keyframe:
self.keyframes += 1
self.keyframe_at = now
current = (header["generation"], header["codec"])
if decoder is None or key != current or header["gap"]:
if key != current or header["gap"]:
decoder = None
key = current
if decoder is None:
# Parsing dependent NALs after a gap can fail while the
# next IDR is still buffered in the parser. Recreating the
# decoder then discards that IDR forever. Feed replays this
# generation's parameter sets on keyframes, so resume only
# from an independently decodable packet.
if not keyframe:
continue
decoder = av.CodecContext.create(
"h264" if header["codec"] == 0 else "hevc", "r"
)
decoder.thread_count = 1
key = current
with self.lock:
self.resets += 1
try:
for packet in decoder.parse(data):
for frame in decoder.decode(packet):
@@ -124,7 +172,11 @@ class Source:
resized_at = now
except av.error.FFmpegError:
decoder = None
with self.lock:
self.decode_errors += 1
except (OSError, ValueError, RuntimeError) as error:
with self.lock:
self.failure = type(error).__name__
logging.getLogger(__name__).warning(
"X4 preview source stopped (%s)", type(error).__name__
)
@@ -138,17 +190,25 @@ class Source:
class Track(VideoStreamTrack):
def __init__(self, source):
def __init__(self, source, budget=None):
super().__init__()
self.budget = budget
self.source, self.sequence, self.next_at = source, 0, 0.0
async def recv(self):
while self.readyState == "live" and not self.source.closed.is_set():
await asyncio.sleep(max(0, self.next_at - time.monotonic()))
width, fps = self.budget.video() if self.budget else (1280, 15)
if not fps:
await asyncio.sleep(.1)
continue
sequence, frame, observed = self.source.current()
if frame is not None and sequence > self.sequence and time.monotonic() - observed < 2:
self.sequence = sequence
self.next_at = time.monotonic() + 1 / 15
self.next_at = time.monotonic() + 1 / fps
if frame.width > width:
height = max(2, round(frame.height * width / frame.width) // 2 * 2)
frame = frame.reformat(width=width, height=height, format="yuv420p")
# Distinct AV frames per encoder: force-keyframe decisions in
# one browser must not mutate another browser's frame object.
copy = av.VideoFrame(frame.width, frame.height, "yuv420p")
@@ -235,7 +295,7 @@ class Peers:
# competing decoder or accept a retained frame as fresh evidence.
source = self.sources.get(key)
if source is None or source.closed.is_set():
return failure("preview_restart_required")
return dict(failure("preview_restart_required"), result={"decoder": source.health() if source else None})
initial = source.current()[0]
started = time.monotonic()
while time.monotonic() - started < timeout:
@@ -259,13 +319,14 @@ class Peers:
},
}
await asyncio.sleep(0.02)
return failure("preview_restart_required")
return dict(failure("preview_restart_required"), result={"decoder": source.health()})
async def offer(self, key, path, params):
admit_sdp(params["sdp"])
if type(params.get("primary",False)) is not bool:raise ValueError("Invalid preview role")
# Inventory remains independent; these limits bound active media only.
if len(self.items) >= 4 or sum(item["key"] == key for item in self.items.values()) >= 2:
raise ValueError("Закройте лишний просмотр камеры.")
raise PreviewCapacityError("preview_capacity")
source = self.source(key, path)
pc = RTCPeerConnection(RTCConfiguration(iceServers=[]))
identifier = "peer_" + uuid.uuid4().hex
@@ -284,6 +345,8 @@ class Peers:
if frame
else None,
"fresh": frame is not None and time.monotonic() - observed < 2,
"decoder": source.health(),
"media_budget": entry["budget"].snapshot() if "budget" in entry else None,
}
)
)
@@ -302,6 +365,8 @@ class Peers:
@channel.on("message")
def message(value):
if value in ("view:primary", "view:secondary") and "budget" in entry:
entry["budget"].primary = value == "view:primary"
if value == "keepalive":
entry["seen"] = time.monotonic()
@@ -320,16 +385,23 @@ class Peers:
await asyncio.sleep(1)
try:
sender = pc.addTrack(Track(source))
allocation = await adapt_peer(pc, "video", primary=params.get("primary",False))
entry["budget"] = allocation
sender = pc.addTrack(Track(source, allocation))
cap_video_sender(sender, allocation)
transceiver = next(item for item in pc.getTransceivers() if item.sender == sender)
transceiver.setCodecPreferences(
[
codec
for codec in RTCRtpSender.getCapabilities("video").codecs
if codec.mimeType.lower() == "video/h264"
# Keep H264's standard repair transport. Omitting RTX
# forces NACK retries onto the primary SSRC, where old
# primary frames are deliberately rejected by admission.
if codec.mimeType.lower() in ("video/h264", "video/rtx")
]
)
await pc.setRemoteDescription(RTCSessionDescription(sdp=params["sdp"], type="offer"))
budget_peer(pc, "video", producer_id=allocation.id)
await pc.setLocalDescription(await pc.createAnswer())
task(watchdog())
return {"peer_id": identifier, "sdp": pc.localDescription.sdp, "type": "answer"}
@@ -381,6 +453,8 @@ class Engine:
future = asyncio.run_coroutine_threadsafe(work, self.loop)
try:
return {"state": "complete", "result": future.result(timeout=20)}
except PreviewCapacityError:
return failure("preview_capacity")
except FutureTimeout as error:
future.cancel()
raise RuntimeError("Camera preview timed out") from error
+40 -3
View File
@@ -20,6 +20,7 @@ ACTIONS = {
"files.list": 9,
}
MAX_PACKET = 4 * 1024 * 1024
DownloadProgress = ctypes.CFUNCTYPE(None, ctypes.c_int64, ctypes.c_int64)
class VideoHeader(ctypes.Structure):
@@ -30,6 +31,8 @@ class VideoHeader(ctypes.Structure):
("stream_index", ctypes.c_int32),
("codec", ctypes.c_int32),
("bytes", ctypes.c_uint32),
("stream_type", ctypes.c_int32),
("calibration_revision", ctypes.c_uint64),
]
@@ -52,7 +55,8 @@ def parameters(action, value):
if action == "offer":
if (
not isinstance(value, dict)
or set(value) != {"sdp", "layer"}
or set(value) not in ({"sdp", "layer"}, {"sdp", "layer", "primary"})
or type(value.get("primary", False)) is not bool
or value["layer"] != "preview"
or not isinstance(value["sdp"], str)
or not 0 < len(value["sdp"]) <= 32768
@@ -123,7 +127,7 @@ class NativeCamera:
self.video_lock = threading.Lock()
self.api = ctypes.CDLL(str(library_path))
self.api.mc_x4_abi.restype = ctypes.c_int
if self.api.mc_x4_abi() != 1:
if self.api.mc_x4_abi() != 2:
raise RuntimeError("Incompatible camera adapter")
self.api.mc_x4_open.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
self.api.mc_x4_open.restype = ctypes.c_void_p
@@ -135,6 +139,15 @@ class NativeCamera:
ctypes.c_double,
]
self.api.mc_x4_call.restype = ctypes.c_char_p
self.api.mc_x4_download.argtypes = [
ctypes.c_void_p,
ctypes.c_char_p,
ctypes.c_char_p,
DownloadProgress,
]
self.api.mc_x4_download.restype = ctypes.c_int
self.api.mc_x4_cancel_download.argtypes = [ctypes.c_void_p]
self.api.mc_x4_cancel_download.restype = None
self.api.mc_x4_read_video.argtypes = [
ctypes.c_void_p,
ctypes.POINTER(VideoHeader),
@@ -166,6 +179,24 @@ class NativeCamera:
raise RuntimeError("Camera returned an invalid response")
return result
def download(self, source, destination, progress):
callback = DownloadProgress(progress)
with self.lock:
if not self.handle:
raise RuntimeError("Camera session is closed")
return (
self.api.mc_x4_download(
self.handle, source.encode(), str(destination).encode(), callback
)
== 1
)
def cancel_download(self):
# Called only by the active transfer's watchdog. Taking the command
# lock here would deadlock with synchronous DownloadCameraFile.
if self.handle:
self.api.mc_x4_cancel_download(self.handle)
def video(self):
# SDK control calls may block for seconds. The callback queue has its
# own native mutex and can be drained without taking the command lock.
@@ -180,7 +211,13 @@ class NativeCamera:
raise RuntimeError("Invalid video packet")
if state == 0:
return None
if header.stream_index not in (0, 1) or header.codec not in (0, 1) or not header.bytes:
if (
header.stream_index not in (0, 1)
or header.codec not in (0, 1)
or not 0 <= header.stream_type <= 255
or not header.calibration_revision
or not header.bytes
):
raise RuntimeError("Unsupported video packet")
return {name: getattr(header, name) for name, _ in VideoHeader._fields_}, bytes(
self.buffer[: header.bytes]
+5
View File
@@ -196,6 +196,11 @@ class Recovery:
decisions = []
for ident, state in self.states.items():
current = self.current.get(ident)
if current and current.get("file_transfer", {}).get("active") is True:
# Synchronous vendor downloads pause status polling. Do not
# treat an intentionally busy control channel as a lost camera.
self.absent.pop(ident, None)
continue
online = bool(current and current.get("online"))
if online:
self.absent.pop(ident, None)
+37 -5
View File
@@ -8,6 +8,7 @@ import uuid
from datetime import UTC, datetime
from pathlib import Path
from .archive import Archive
from .frames import Feed, encode
from .http import Binary, Server
from .identity import read_binding
@@ -36,6 +37,8 @@ class Worker:
self.feed = None
self.operations = None
self.runtime, self.state = runtime, state
self.command_gate = threading.Lock()
self.archive = None
def connect(self):
# Bounded startup even if a vendor call never returns. No restart loop:
@@ -55,6 +58,7 @@ class Worker:
self.feed = Feed(self.camera)
self.feed.thread.start()
self.control = Control(self.camera, self.feed)
self.archive = Archive(self.camera, self.state / "originals", self.command_gate)
self.operations = Operations(
self.binding.device_id, self.session, self.state / "operations", self.control
)
@@ -68,7 +72,12 @@ class Worker:
def refresh(self):
if read_binding(self.binding.port) != self.binding:
raise RuntimeError("Camera transport changed")
response = self.camera.call("details", {})
if not self.command_gate.acquire(blocking=False):
return
try:
response = self.camera.call("details", {})
finally:
self.command_gate.release()
if response["state"] != "complete":
raise RuntimeError("Camera status is unconfirmed")
with self.status_lock:
@@ -78,6 +87,7 @@ class Worker:
self.revision += 1
def snapshot(self):
transfer_active = bool(self.archive and self.archive.busy())
with self.status_lock:
state = dict(self.status)
fresh = time.monotonic() - self.observed < 12
@@ -98,7 +108,9 @@ class Worker:
"verified": verified,
"revision": revision,
"observed_at": observed_at,
"file_transfer": {"active": transfer_active},
"preparation_safe": connected
and not transfer_active
and state.get("preview") == 0
and state.get("recording") == 0,
"status": state if fresh else {},
@@ -108,19 +120,39 @@ class Worker:
def dispatch(self, method, route, value, headers):
if method == "GET" and route == "/snapshot":
return self.snapshot()
if method == "POST" and route == "/video":
if method == "POST" and route in ("/archive/start", "/archive/status", "/archive/read"):
keys = {"session_id", "id"} | (
{"source"}
if route.endswith("start")
else {"offset"}
if route.endswith("read")
else set()
)
if not self.ready or value.get("session_id") != self.session or set(value) != keys:
raise ValueError("Camera file session changed")
if route == "/archive/start":
return self.archive.start(value["id"], value["source"])
if route == "/archive/status":
return self.archive.status(value["id"])
return Binary(self.archive.read(value["id"], value["offset"]))
if method == "POST" and route in ("/video", "/sdk-video"):
if (
not self.ready
or value.get("session_id") != self.session
or set(value) != {"session_id", "cursor"}
):
raise ValueError("Camera video session changed")
return Binary(encode(self.feed.read(value["cursor"])))
return Binary(encode(self.feed.read(value["cursor"], original=route == "/sdk-video")))
if method == "POST" and route == "/operation":
if not self.ready:
raise RuntimeError("Camera is unavailable")
with acquisition():
result = self.operations.execute(value)
if not self.command_gate.acquire(blocking=False):
raise RuntimeError("Camera file transfer or status read is active")
try:
with acquisition():
result = self.operations.execute(value)
finally:
self.command_gate.release()
# Poll asynchronously; a lost state read must not change a durable
# acknowledged command result into a different receipt.
if value.get("action_id") not in ("details", "settings.read", "files.list"):
+152
View File
@@ -0,0 +1,152 @@
"""Original transfer bounds, idempotency and camera-control exclusion; fake SDK."""
import hashlib
import json
import sys
import tempfile
import threading
import time
import unittest
from contextlib import nullcontext
from pathlib import Path
from unittest.mock import Mock, patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from runtime import archive # noqa: E402
ID = "file_" + "a" * 32
SOURCE = "/DCIM/Camera01/VID_20261014_120000_00_001.insv"
class ArchiveTests(unittest.TestCase):
def setUp(self):
self.folder = tempfile.TemporaryDirectory(dir=ROOT / "build")
self.addCleanup(self.folder.cleanup)
self.gate = threading.Lock()
self.camera = Mock()
self.manager = archive.Archive(self.camera, Path(self.folder.name), self.gate)
self.life = patch.object(archive, "acquisition", return_value=nullcontext())
self.space = patch.object(
archive.shutil, "disk_usage", return_value=Mock(free=16 * 1024**3)
)
self.life.start()
self.space.start()
self.addCleanup(patch.stopall)
def wait(self):
deadline = time.monotonic() + 3
while self.manager.busy() and time.monotonic() < deadline:
time.sleep(0.005)
self.assertFalse(self.manager.busy())
return self.manager.status(ID)
def complete(self, source, destination, progress):
# SDK transports may announce (0, 0) before receiving Content-Length.
progress(0, 0)
destination.write_bytes(b"original")
progress(8, 8)
return True
def test_verified_original_chunks_and_same_identity_do_not_repeat_sdk(self):
self.camera.download.side_effect = self.complete
self.manager.start(ID, SOURCE)
status = self.wait()
self.assertEqual(status["state"], "complete")
self.assertEqual(status["sha256"], hashlib.sha256(b"original").hexdigest())
self.assertEqual(self.manager.read(ID, 2), b"iginal")
self.assertEqual(self.manager.start(ID, SOURCE), status)
self.camera.download.assert_called_once()
self.assertTrue(self.gate.acquire(blocking=False))
self.gate.release()
with self.assertRaises(ValueError):
self.manager.start(ID, SOURCE.replace("001", "002"))
with self.assertRaises(ValueError):
self.manager.read(ID, 8)
def test_busy_transfer_owns_gate_until_sdk_really_returns(self):
entered, release = threading.Event(), threading.Event()
def slow(*args):
entered.set()
release.wait(2)
return self.complete(*args)
self.camera.download.side_effect = slow
try:
self.manager.start(ID, SOURCE)
self.assertTrue(entered.wait(1))
self.assertFalse(self.gate.acquire(blocking=False))
with self.assertRaises(RuntimeError):
self.manager.start("file_" + "b" * 32, SOURCE)
with self.assertRaises(ValueError):
self.manager.read(ID, 0)
finally:
release.set()
self.wait()
def test_failed_and_interrupted_files_are_retained_and_not_restarted(self):
def failed(source, destination, progress):
destination.write_bytes(b"part")
progress(4, 8)
return False
self.camera.download.side_effect = failed
self.manager.start(ID, SOURCE)
self.assertEqual(self.wait()["state"], "error")
path = self.manager.folder(ID)
self.assertEqual((path / "original.insv").read_bytes(), b"part")
value = json.loads((path / "receipt.json").read_text())
value["state"] = "running"
(path / "receipt.json").write_text(json.dumps(value))
self.assertEqual(self.manager.start(ID, SOURCE)["state"], "interrupted")
self.camera.download.assert_called_once()
def test_timeout_requests_cancel_without_releasing_live_sdk_ownership(self):
def slow(source, destination, progress):
time.sleep(0.15)
self.assertTrue(self.manager.busy())
return self.complete(source, destination, progress)
self.camera.download.side_effect = slow
with patch.object(archive, "TIMEOUT", 0):
self.manager.start(ID, SOURCE)
self.assertEqual(self.wait()["state"], "error")
self.camera.cancel_download.assert_called_once()
def test_oversized_or_inconsistent_progress_cannot_mark_file_complete(self):
for downloaded, total in ((8, archive.MAX_BYTES + 1), (8, 0), (7, 8)):
ident = "file_" + f"{total + 1:032x}"
def invalid(source, destination, progress, downloaded=downloaded, total=total):
destination.write_bytes(b"original")
progress(downloaded, total)
return True
self.camera.download.side_effect = invalid
self.manager.start(ident, SOURCE)
deadline = time.monotonic() + 2
while self.manager.busy() and time.monotonic() < deadline:
time.sleep(0.005)
self.assertEqual(self.manager.status(ident)["state"], "error")
def test_paths_and_space_reject_before_sdk_or_file_creation(self):
for source in (
"/etc/passwd",
"http://camera/file.insv",
"/DCIM/../x.insv",
"/DCIM/a\\b.insv",
):
with self.assertRaises(ValueError):
self.manager.start(ID, source)
with (
patch.object(archive.shutil, "disk_usage", return_value=Mock(free=0)),
self.assertRaises(RuntimeError),
):
self.manager.start(ID, SOURCE)
self.assertFalse(self.manager.folder(ID).exists())
self.camera.download.assert_not_called()
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,141 @@
"""Synthetic tests of the privileged reader boundary; no camera or SDK use."""
import io
import json
import struct
import sys
import unittest
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "packaging"))
import media_live_source as source
from media_live_qualification import calibration_bytes
DEVICE = "instax4_" + "0" * 32
SESSION = "x4_" + "1" * 32
class LiveReader(unittest.TestCase):
def setUp(self):
self.calibration = {
"revision": 5,
"camera_name": "X4",
"offsets": ["factory", ""],
"encode_type": 0,
"crop": dict(source_width=8000, source_height=6000, width=5760, height=5760, x=0, y=0),
}
self.header = dict(
cursor=1,
generation=3,
timestamp=100,
stream_index=0,
stream_type=0x20,
codec=0,
calibration_revision=5,
bytes=5,
gap=False,
)
self.details = {
"state": "complete",
"result": {"preview": 1, "recording": 0, "preview_calibration": self.calibration},
}
self.calls = []
def request(self, path, camera, *, cursor=None):
self.calls.append((str(path), camera, cursor))
if camera is None:
return {"id": DEVICE, "session_id": SESSION, "online": True}
if cursor is None:
return self.details
h = json.dumps(dict(self.header, cursor=cursor + 1)).encode()
return struct.pack("!I", len(h)) + h + b"\0\0\1\x65x"
def run_source(self, warmup=0):
messages = []
# readiness deadline, start, loop, loop end, receipt duration
ticks = (
[0, 0] + [0] * 8 + [21, 21]
if not warmup
else [0, 0, 0, 1, 1, 2.1] + [2.1] * 7 + [21, 21]
)
with (
patch.object(source, "request", side_effect=self.request),
patch.object(source, "read_exact", return_value=b"START\n"),
patch.object(source.time, "monotonic", side_effect=ticks),
patch.object(source, "WARMUP", warmup),
patch.object(source, "independent_packet", return_value=True),
patch.object(source, "emit_message", side_effect=lambda _, raw: messages.append(raw)),
):
result = source.source(DEVICE, SESSION, io.BytesIO(), io.BytesIO())
return result, messages
def test_exact_original_bytes_and_calibration_forwarded_without_camera_mutation(self):
result, messages = self.run_source()
self.assertEqual(result["packets"], 8)
self.assertTrue(result["preview_preserved"])
self.assertEqual(json.loads(messages[0])["calibration"], self.calibration)
self.assertTrue(messages[1].endswith(b"\0\0\1\x65x"))
self.assertEqual(messages[-1], b"")
self.assertEqual([c[2] for c in self.calls], [None, None, *range(8), None])
self.assertTrue(all(c[0].endswith(DEVICE + "/driver.sock") for c in self.calls))
def test_startup_backlog_is_discarded_without_modifying_forwarded_bytes(self):
result, messages = self.run_source(warmup=2)
self.assertEqual(result["startup_discarded_packets"], 1)
self.assertEqual(result["forwarded_packets"], 8)
size = struct.unpack("!I", messages[1][8:12])[0]
self.assertEqual(json.loads(messages[1][12 : 12 + size])["cursor"], 2)
self.assertTrue(messages[1].endswith(b"\0\0\1\x65x"))
def test_keyframe_requires_original_parameter_sets_for_its_codec(self):
def nal(kind):
return b"\0\0\1" + bytes([kind]) + b"x"
self.assertTrue(source.independent_packet(nal(7) + nal(8) + nal(5), 0))
self.assertFalse(source.independent_packet(nal(5), 0))
self.assertFalse(source.independent_packet(nal(7) + nal(8) + nal(1), 0))
self.assertTrue(
source.independent_packet(b"".join(nal(n << 1) for n in [32, 33, 34, 19]), 1)
)
self.assertFalse(source.independent_packet(nal(19 << 1), 1))
def test_recording_or_inactive_preview_is_rejected_without_start_stop(self):
for key, value in [("recording", 1), ("recording", None), ("preview", 0)]:
with self.subTest(key=key, value=value):
old = self.details["result"][key]
self.details["result"][key] = value
with self.assertRaises(RuntimeError):
self.run_source()
self.details["result"][key] = old
def test_gap_revision_and_codec_changes_stop_the_sample(self):
for key, value in [("gap", True), ("calibration_revision", 6), ("codec", 1)]:
old = self.header[key]
self.header[key] = value
with self.subTest(key=key), self.assertRaises(ValueError):
self.run_source()
self.header[key] = old
def test_byte_limit_stops_before_sending_oversized_payload(self):
with patch.object(source, "MAX_BYTES", 4), self.assertRaises(ValueError):
self.run_source()
def test_no_identity_path_traversal(self):
with self.assertRaises(ValueError):
source.source("../../other", SESSION, io.BytesIO(), io.BytesIO())
def test_missing_calibration_and_invalid_geometry_rejected(self):
valid = calibration_bytes(self.calibration)
self.assertTrue(valid.startswith(b"MCX4L001"))
self.calibration["crop"]["width"] = 99999
with self.assertRaises(ValueError):
calibration_bytes(self.calibration)
self.calibration["crop"]["width"] = 5760
self.calibration["offsets"] = ["", ""]
with self.assertRaises(ValueError):
calibration_bytes(self.calibration)
if __name__ == "__main__":
unittest.main()
+368 -6
View File
@@ -8,6 +8,7 @@ import threading
import unittest
from fractions import Fraction
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
from aiortc import RTCConfiguration, RTCPeerConnection, RTCSessionDescription
@@ -27,6 +28,194 @@ def packet(number, data=b"synthetic", generation=1):
class FrameTests(unittest.TestCase):
def test_encoder_recovers_above_an_already_applied_sustained_floor(self):
from aiortc.rtcrtpparameters import RTCRtpCodecParameters
from missioncore_plugin_sdk.media_budget import MediaBudget, cap_video_sender
from aiortc import VideoStreamTrack
now = [10.0]
class Track(VideoStreamTrack):
index = 0
async def recv(self):
import av
frame = av.VideoFrame(64, 32, "yuv420p")
for plane in frame.planes:
plane.update(bytes(plane.buffer_size))
self.index += 1
frame.pts, frame.time_base = self.index * 6000, Fraction(1, 90000)
return frame
async def run():
pc = RTCPeerConnection()
budget = MediaBudget("video", clock=lambda: now[0])
sender = pc.addTrack(Track())
cap_video_sender(sender, budget)
codec = RTCRtpCodecParameters(mimeType="video/H264", clockRate=90000, payloadType=96)
try:
for at, requested, expected in [(10, 100000, 100000), (10.1, 225000, 100000),
(11, 365544, 100000), (12.2, 365544, 225000),
(12.3, 365544, 225000), (14.4, 365544, 365000),
(14.5, 160000, 160000)]:
now[0] = at
budget.target, budget.valid_until = requested, at + 3
budget.profile = (640, 15)
await sender._next_encoded_frame(codec)
# libx264 reports its applied rate in whole kbit/s.
self.assertEqual(sender._RTCRtpSender__encoder.codec.bit_rate, expected)
self.assertEqual(sender._RTCRtpSender__encoder.codec.thread_count, 2)
self.assertFalse(sender._RTCRtpSender__encoder.codec.has_b_frames)
finally:
await pc.close()
budget.connection.close()
asyncio.run(run())
def test_preview_priority_is_typed_and_legacy_offer_remains_valid(self):
from runtime.native import parameters
offer = {"sdp":"v=0", "layer":"preview"}
self.assertEqual(parameters("offer",offer), (0,"",0.))
self.assertEqual(parameters("offer",{**offer,"primary":True}), (0,"",0.))
with self.assertRaises(ValueError):parameters("offer",{**offer,"primary":1})
with self.assertRaises(ValueError):parameters("offer",{**offer,"bypass":True})
def test_adaptive_encoder_is_capped_below_stock_codec_floor(self):
import av
from aiortc import VideoStreamTrack
from aiortc.rtcrtpparameters import RTCRtpCodecParameters
from missioncore_plugin_sdk.media_budget import MediaBudget, cap_video_sender
class Track(VideoStreamTrack):
async def recv(self):
frame = av.VideoFrame(64, 32, "yuv420p")
for plane in frame.planes:
plane.update(bytes(plane.buffer_size))
frame.pts, frame.time_base = 0, Fraction(1, 90000)
return frame
async def run(codec):
pc = RTCPeerConnection()
budget = MediaBudget("video")
budget.update({"schema": "missioncore.media-budget/v1", "allocation_bps": 80000, "ttl_ms": 3000})
try:
sender = pc.addTrack(Track())
cap_video_sender(sender, budget)
result = await sender._next_encoded_frame(RTCRtpCodecParameters(
mimeType="video/"+codec, clockRate=90000, payloadType=96))
self.assertTrue(result)
encoder = sender._RTCRtpSender__encoder
self.assertEqual(encoder.codec.bit_rate, 52000)
encoder.target_bitrate = 32000
self.assertEqual(encoder.target_bitrate, 52000)
budget.target = 2600000
self.assertEqual(budget.video(), (1280, 15))
self.assertGreaterEqual(encoder.target_bitrate, 250000)
encoder.target_bitrate = 600000
self.assertEqual(encoder.target_bitrate, 600000)
self.assertEqual(budget.video(), (1280, 15))
finally:
await pc.close()
budget.connection.close()
for codec in ("H264", "VP8"):
asyncio.run(run(codec))
def test_source_recovers_at_keyframe_after_gap_between_separate_nals(self):
import av
encoder = av.CodecContext.create("libx264", "w")
encoder.width, encoder.height, encoder.pix_fmt = 32, 16, "yuv420p"
encoder.time_base = Fraction(1, 30)
encoder.options = {
"preset": "ultrafast", "tune": "zerolatency",
"x264-params": "keyint=30:min-keyint=30:scenecut=0:repeat-headers=1",
}
feed, wire = frames.Feed(None), []
for number in range(150):
frame = av.VideoFrame(32, 16, "yuv420p")
frame.pts = number
for plane in frame.planes:
plane.update(bytes([64 + number % 100]) * plane.buffer_size)
for encoded in encoder.encode(frame):
for unit in re.split(b"\x00\x00(?:\x00)?\x01", bytes(encoded)):
if not unit or (number and unit[0] & 31 in (7, 8)):
continue
# Separate SDK callbacks, with SPS/PPS sent only at startup.
feed.append(packet(number, b"\x00\x00\x00\x01" + unit))
header, data, _, _ = feed.queue[-1]
wire.append((dict(header, gap=False), data))
source = media.Source("synthetic.sock", "synthetic")
clock, cursor, before_gap = source.started, 0, None
def request(path, route, value, **kwargs):
nonlocal clock, cursor, before_gap
if cursor == 55:
before_gap = source.sequence
cursor += 5
wire[cursor][0]["gap"] = True
if cursor >= len(wire):
source.close()
return b""
clock += 0.1
value = frames.encode(wire[cursor])
cursor += 1
return value
with patch.object(media, "request", request), patch.object(
media, "time", SimpleNamespace(monotonic=lambda: clock)
):
source.pump()
self.assertGreater(before_gap, 20)
self.assertGreater(source.sequence - before_gap, 60)
self.assertEqual(source.health()["gaps"], 1)
self.assertLessEqual(source.health()["decode_errors"], 1)
def test_source_health_distinguishes_input_loss_from_decode_loss(self):
source = media.Source("synthetic.sock", "synthetic")
payloads = synthetic_video(12)
feed = frames.Feed(None)
for number, data in enumerate(payloads):
feed.append(packet(number, data))
def request(path, route, value, **kwargs):
value = feed.read(value["cursor"], 0)
if value is None:
source.close()
return frames.encode(value)
with patch.object(media, "request", request):
source.pump()
health = source.health()
self.assertEqual(health["packets"], len(payloads))
self.assertGreater(health["frames"], 0)
self.assertGreater(health["keyframes"], 0)
self.assertEqual(health["gaps"], 0)
self.assertEqual(health["decode_errors"], 0)
self.assertTrue(health["closed"])
self.assertIsNone(health["failure"])
self.assertIsInstance(health["packet_age_ms"], int)
self.assertTrue(all(not isinstance(value, (bytes, list, dict)) for value in health.values()))
def test_sdk_reader_keeps_exact_packets_while_browser_gets_parameter_replay(self):
config = b"\x00\x00\x01\x67sps\x00\x00\x01\x68pps"
keyframe = b"\x00\x00\x01\x65frame"
feed = frames.Feed(None)
sdk, browser = feed.reader(original=True), feed.reader()
header, data = packet(1, config)
header.update(stream_type=0x20, calibration_revision=9)
feed.append((header, data))
self.assertEqual(sdk()[1], config)
self.assertEqual(browser()[1], config)
header, data = packet(2, keyframe)
header.update(stream_type=0x22, calibration_revision=9)
feed.append((header, data))
original, display = sdk(), browser()
self.assertEqual(original[1], keyframe)
self.assertEqual(display[1], config + keyframe)
for value in (original, display):
self.assertEqual(value[0]["stream_type"], 0x22)
self.assertEqual(value[0]["calibration_revision"], 9)
self.assertEqual(value[0]["bytes"], len(value[1]))
self.assertEqual(frames.decode(frames.encode(value)), value)
feed.clear()
feed.append(packet(3, keyframe, generation=2))
self.assertEqual(sdk()[1], keyframe)
self.assertEqual(browser()[1], keyframe)
def test_repeated_preview_commands_preserve_generation_and_readers(self):
feed = frames.Feed(None)
camera = VideoCamera([], preview=1)
@@ -202,6 +391,21 @@ class FrameTests(unittest.TestCase):
with self.assertRaises(ValueError):
feed.read(True, 0)
def test_capacity_has_a_definite_public_error_not_an_unknown_camera_write(self):
from concurrent.futures import Future
from runtime.errors import MESSAGES
engine = media.Engine.__new__(media.Engine)
engine.peers, engine.loop = media.Peers(), object()
def schedule(coroutine, loop):
coroutine.close()
future = Future()
future.set_exception(media.PreviewCapacityError("preview_capacity"))
return future
with patch.object(media.asyncio, "run_coroutine_threadsafe", side_effect=schedule):
result = engine.call(("synthetic", "synthetic"), None, "offer", {"sdp": "v=0\r\n"})
self.assertEqual(result, {"state": "error", "error": "preview_capacity"})
self.assertIn("два просмотра", MESSAGES[result["error"]])
def test_public_ice_candidates_are_rejected_before_network_work(self):
with self.assertRaises(ValueError):
media.admit_sdp("v=0\r\na=candidate:1 1 udp 1 203.0.113.6 1234 typ host\r\n")
@@ -209,6 +413,28 @@ class FrameTests(unittest.TestCase):
class MediaTests(unittest.IsolatedAsyncioTestCase):
def setUp(self):
# Package qualification has no live Node. Keep the real queue/transport,
# grant synthetic permits; aggregate allocation has independent tests.
from missioncore_plugin_sdk.link_budget import BudgetClient
guard = patch.object(BudgetClient, "_permit", return_value=True)
guard.start()
self.addCleanup(guard.stop)
from missioncore_plugin_sdk.media_budget import MediaBudget
allocation = patch.object(MediaBudget, "exchange", return_value={
"schema": "missioncore.media-budget/v1", "allocation_bps": 4_000_000, "ttl_ms": 3000})
allocation.start()
self.addCleanup(allocation.stop)
async def test_capacity_rejection_admits_no_peer_and_never_touches_capture(self):
peers = media.Peers()
key = ("synthetic-camera", "synthetic")
peers.items = {"one": {"key": key}, "two": {"key": key}}
with patch.object(peers, "source", side_effect=AssertionError("capture must not be touched")):
with self.assertRaises(media.PreviewCapacityError):
await peers.offer(key, None, {"sdp": "v=0\r\n"})
self.assertEqual(set(peers.items), {"one", "two"})
async def test_primed_decoder_survives_late_viewer_and_peer_close(self):
with tempfile.TemporaryDirectory(dir=ROOT / "build") as temporary:
descriptor = os.open(temporary, os.O_RDONLY)
@@ -304,6 +530,9 @@ class MediaTests(unittest.IsolatedAsyncioTestCase):
class Retained:
closed = threading.Event()
def health(self):
return {"frames": 50}
def current(self):
return 50, object(), media.time.monotonic()
@@ -349,7 +578,7 @@ class MediaTests(unittest.IsolatedAsyncioTestCase):
producer.start()
peers = media.Peers()
receiver = RTCPeerConnection(RTCConfiguration(iceServers=[]))
received = asyncio.get_running_loop().create_future()
received = asyncio.Queue(maxsize=4)
tasks = []
identifier = None
key = ("synthetic-camera", "synthetic")
@@ -357,10 +586,11 @@ class MediaTests(unittest.IsolatedAsyncioTestCase):
@receiver.on("track")
def track(value):
async def observe():
first = await value.recv()
second = await value.recv()
if not received.done():
received.set_result((first, second))
while True:
frame = await value.recv()
if received.full():
received.get_nowait()
received.put_nowait(frame)
tasks.append(asyncio.create_task(observe()))
@@ -383,9 +613,41 @@ class MediaTests(unittest.IsolatedAsyncioTestCase):
await receiver.setRemoteDescription(
RTCSessionDescription(sdp=answer["sdp"], type="answer")
)
first, second = await asyncio.wait_for(received, 12)
first = await asyncio.wait_for(received.get(), 12)
second = await asyncio.wait_for(received.get(), 4)
self.assertEqual((first.width, first.height), (32, 16))
self.assertGreater(second.pts, first.pts)
# Control pressure pauses admission for >=1s. Keep this same
# actual ICE/DTLS/SCTP peer and decoder across the shorter media
# deadline; no stale encoded backlog may be replayed afterward.
from missioncore_plugin_sdk.link_budget import BudgetClient
sender = peers.items[identifier]["pc"]
with patch.object(BudgetClient, "_permit", return_value=False):
await asyncio.sleep(1.3)
self.assertEqual(sender.connectionState, "connected")
self.assertEqual(receiver.connectionState, "connected")
stats = sender._missioncore_egress_metrics
self.assertGreater(stats["expired_frames"] + stats["expired_datagrams"], 0)
while not received.empty():
received.get_nowait()
# aiortc's synthetic receiver has a 128-packet jitter buffer
# with no time-based eviction. Tiny 32x16 frames use one RTP
# packet, so a deliberately lost packet can hold decoding for
# ~9s at 15fps. This is not the browser's jitter-buffer policy.
# Keep the real receiver unmodified and bound that drain too.
try:
resumed = await asyncio.wait_for(received.get(), 12)
except TimeoutError:
self.fail(repr({
"sender": sender.connectionState,
"receiver": receiver.connectionState,
"egress": sender._missioncore_egress_metrics,
"source": peers.sources[key].health(),
"budget": peers.items[identifier]["budget"].snapshot(),
"stats": await receiver.getStats(),
}))
self.assertGreater(resumed.pts, second.pts)
self.assertIs(peers.items[identifier]["pc"], sender)
with self.assertRaises(ValueError):
await peers.close(("another-camera", "synthetic"), identifier)
self.assertIn(identifier, peers.items)
@@ -409,5 +671,105 @@ class MediaTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(producer.is_alive())
class ImpairedUDPTests(unittest.IsolatedAsyncioTestCase):
async def test_actual_h264_dtls_udp_survives_delay_loss_and_send_expiry(self):
# The impairment is confined to this test's loopback media transport.
# No tc rules, real Node socket, camera SDK, control or host route.
import av
import random
import time
from missioncore_plugin_sdk.link_budget import budget_peer, _essential
from missioncore_plugin_sdk.media_budget import MediaBudget, cap_video_sender
class Pixels(media.VideoStreamTrack):
def __init__(self):
super().__init__()
self.origin = time.monotonic()
self.random = random.Random(17)
async def recv(self):
await asyncio.sleep(.067)
frame = av.VideoFrame(320,160,"yuv420p")
for plane in frame.planes:plane.update(self.random.randbytes(plane.buffer_size))
frame.pts = int((time.monotonic()-self.origin)*90000)
frame.time_base = Fraction(1,90000)
return frame
class Permit:
async def acquire(self, size, *, deadline=None):
if not 0 < size <= 2048:raise ValueError("oversized fixture packet")
def close(self):pass
sender = RTCPeerConnection(RTCConfiguration(iceServers=[]))
receiver = RTCPeerConnection(RTCConfiguration(iceServers=[]))
budget = MediaBudget("video", clock=lambda:100.)
budget.update({"schema":"missioncore.media-budget/v1","allocation_bps":4_000_000,"ttl_ms":3000})
received = asyncio.Queue(maxsize=4)
tasks = []
state = {"delay":0.,"loss":False,"packets":0,"dropped":0,"cancelled":0,"max_udp_payload":0}
@receiver.on("track")
def track(value):
async def consume():
while True:
frame = await value.recv()
if received.full():received.get_nowait()
received.put_nowait(frame)
tasks.append(asyncio.create_task(consume()))
try:
video = sender.addTrack(Pixels())
cap_video_sender(video,budget)
transceiver = sender.getTransceivers()[0]
transceiver.setCodecPreferences([c for c in media.RTCRtpSender.getCapabilities("video").codecs if c.mimeType.lower() in ("video/h264", "video/rtx")])
receiver.addTransceiver("video",direction="recvonly")
receiver.createDataChannel("sensor")
with patch.object(media,"_host_addresses",return_value=["127.0.0.1"]):
await receiver.setLocalDescription(await receiver.createOffer())
await sender.setRemoteDescription(receiver.localDescription)
transports = {t.sender.transport.transport for t in sender.getTransceivers()}
transports.add(sender.sctp.transport.transport)
for transport in transports:
original = transport._send
async def impaired(data, original=original):
if 128 <= data[0] <= 191 and not _essential(data):
state["packets"] += 1
state["max_udp_payload"] = max(state["max_udp_payload"],len(data))
try:await asyncio.sleep(state["delay"])
except asyncio.CancelledError:
state["cancelled"] += 1
raise
if state["loss"] and state["packets"]%113==0:
state["dropped"] += 1
return
await original(data)
transport._send = impaired
budget_peer(sender,"video",client=Permit())
await sender.setLocalDescription(await sender.createAnswer())
self.assertIn("rtx/90000", sender.localDescription.sdp)
await receiver.setRemoteDescription(sender.localDescription)
first = await asyncio.wait_for(received.get(),12)
state.update(delay=.003,loss=True)
await asyncio.sleep(2)
state.update(delay=.65,loss=False)
await asyncio.sleep(1.3)
self.assertEqual(sender.connectionState,"connected")
self.assertEqual(receiver.connectionState,"connected")
self.assertGreater(state["cancelled"],0)
self.assertGreater(sender._missioncore_egress_metrics["expired_frames"],0)
self.assertLessEqual(sender._missioncore_pending_media(),65536)
state["delay"] = 0
while not received.empty():received.get_nowait()
resumed = await asyncio.wait_for(received.get(),12)
self.assertGreater(resumed.pts,first.pts)
self.assertLessEqual(state["max_udp_payload"]+28,1280)
self.assertGreater(state["dropped"],0)
self.assertGreater(sender._missioncore_egress_metrics["retransmitted_packets"],0)
self.assertLessEqual(sender._missioncore_egress_metrics["retained_frame_deadlines"],256)
self.assertIsNone(sender._missioncore_egress_metrics["close_reason"])
finally:
state["delay"] = 0
for task in tasks:task.cancel()
await asyncio.gather(*tasks,return_exceptions=True)
await sender.close();await receiver.close();await budget.close()
if __name__ == "__main__":
unittest.main(verbosity=2)
@@ -0,0 +1,261 @@
"""Synthetic admission tests; never load a vendor SDK or contact the camera."""
import hashlib
import importlib.util
import io
import json
import struct
import tarfile
import tempfile
import unittest
import zipfile
from pathlib import Path
from unittest.mock import patch
FILE = Path(__file__).resolve().parents[1] / "packaging/media_qualification.py"
spec = importlib.util.spec_from_file_location("media_qualification", FILE)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
def archive(path, entries):
data = io.BytesIO()
with tarfile.open(fileobj=data, mode="w:gz") as tar:
for name, kind, value in entries:
item = tarfile.TarInfo("./" + module.PREFIX + name)
if kind == "file":
item.size = len(value)
tar.addfile(item, io.BytesIO(value))
else:
item.type = tarfile.SYMTYPE
item.linkname = value
tar.addfile(item)
payload = data.getvalue()
header = f"{'data.tar.gz/':<16}{0:<12}{0:<6}{0:<6}{'100644':<8}{len(payload):<10}`\n".encode()
deb = b"!<arch>\n" + header + payload + (b"\n" if len(payload) % 2 else b"")
outer = io.BytesIO()
with tarfile.open(fileobj=outer, mode="w:gz") as tar:
item = tarfile.TarInfo("MediaSDK-3.1.5-20260819-linux64/MediaSDK-3.1.5-linux-amd64.deb")
item.size = len(deb)
tar.addfile(item, io.BytesIO(deb))
with zipfile.ZipFile(path, "w") as z:
z.writestr(module.MEMBER, outer.getvalue())
class Qualification(unittest.TestCase):
def test_network_filter_denies_socket_io_uring_and_foreign_abis(self):
code = list(struct.iter_unpack("HBBI", module.network_filter()))
def verdict(number, arch=0xC000003E):
registers, pc, value = {0: number, 4: arch}, 0, 0
while pc < len(code):
op, yes, no, operand = code[pc]
if op == 0x20:
value = registers[operand]
elif op == 0x06:
return operand
elif op == 0x15:
pc += yes if value == operand else no
elif op == 0x35:
pc += yes if value >= operand else no
else:
raise AssertionError("Unknown instruction")
pc += 1
raise AssertionError("No verdict")
for number in [41, 42, 44, 46, 53, 288, 299, 307, 425, 426, 427]:
self.assertEqual(verdict(number), 0x00050001)
for number in [0, 1, 2, 3, 9, 16, 60, 202]:
self.assertEqual(verdict(number), 0x7FFF0000)
self.assertEqual(verdict(0, 0x40000003), 0x80000000)
self.assertEqual(verdict(0x40000029), 0x80000000)
def test_ranged_download_reassembles_and_verifies_preserved_prefix(self):
data = b"synthetic vendor archive"
class Response(io.BytesIO):
url = module.ARCHIVE_URL
status = 206
headers = {"Content-Range": f"bytes 4-{len(data) - 1}/{len(data)}"}
with (
tempfile.TemporaryDirectory() as temp,
patch.object(module, "ARCHIVE_BYTES", len(data)),
patch.object(module, "ARCHIVE_SHA", hashlib.sha256(data).hexdigest()),
):
root = Path(temp)
prefix = root / "prefix"
prefix.write_bytes(data[:4])
with patch.object(
module.urllib.request, "urlopen", return_value=Response(data[4:])
) as request:
result = module.source_archive(root, prefix)
self.assertEqual(result.read_bytes(), data)
self.assertEqual(
request.call_args.args[0].get_header("Range"), f"bytes=4-{len(data) - 1}"
)
self.assertEqual(prefix.read_bytes(), data[:4])
self.assertFalse((root / "download").exists())
def test_download_rejects_server_ignoring_the_range(self):
class Response(io.BytesIO):
url = module.ARCHIVE_URL
status = 200
headers = {}
with (
tempfile.TemporaryDirectory() as temp,
patch.object(module.urllib.request, "urlopen", return_value=Response(b"bad")),
self.assertRaises(ValueError),
):
module.download_range(Path(temp), 0, 2)
def test_download_rejects_changed_completed_part(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
(root / "0-2.part").write_bytes(b"bad")
(root / "0-2.json").write_text(json.dumps({"sha256": "wrong"}))
with self.assertRaises(ValueError):
module.download_range(root, 0, 2)
def test_vendor_path_rejects_host_escape_and_unexpected_prefix(self):
for value in [
"/etc/passwd",
"./opt/MediaSDK-3.1.5-linux/lib/../../x",
"opt/other/lib/a",
"opt/MediaSDK-3.1.5-linux/lib\\x",
"opt/MediaSDK-3.1.5-linux/../../x",
]:
with self.assertRaises(ValueError):
module.relative(value)
def test_packaged_aliases_resolve_to_verified_regular_files(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
archive(
root / "input.zip", [("lib/a.so", "link", "b.so"), ("lib/b.so", "file", b"fixture")]
)
rows = module.extract_runtime(root / "input.zip", root / "sdk")
(root / "runtime.json").write_text(
json.dumps({"archive_sha256": module.ARCHIVE_SHA, "files": rows})
)
module.verify_runtime(root)
self.assertTrue((root / "sdk/lib/a.so").samefile(root / "sdk/lib/b.so"))
(root / "sdk/lib/b.so").write_bytes(b"changed")
with self.assertRaises(ValueError):
module.verify_runtime(root)
def test_escaping_alias_is_never_created(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
archive(root / "input.zip", [("lib/a.so", "link", "/etc/passwd")])
with self.assertRaises(ValueError):
module.extract_runtime(root / "input.zip", root / "sdk")
self.assertFalse((root / "sdk/lib/a.so").exists())
def test_vendor_alias_cycle_fails(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
archive(
root / "input.zip", [("lib/a.so", "link", "b.so"), ("lib/b.so", "link", "a.so")]
)
with self.assertRaises(ValueError):
module.extract_runtime(root / "input.zip", root / "sdk")
class RecordedInput(unittest.TestCase):
def setUp(self):
import base64
spec = importlib.util.spec_from_file_location(
"media_builder", FILE.with_name("build_media_qualification.py")
)
self.builder = importlib.util.module_from_spec(spec)
spec.loader.exec_module(self.builder)
self.sample = {
"schema": "missioncore.insta360.stitch-input/v1",
"generation": 3,
"calibration": {
"revision": 5,
"camera_name": "X4",
"encode_type": 0,
"offsets": ["factory-a", "factory-b", "factory-c", ""],
"crop": dict(
source_width=8000, source_height=6000, width=5760, height=5760, x=0, y=0
),
},
"packets": [
{
"header": dict(
cursor=i + 1,
generation=3,
calibration_revision=5,
stream_index=i % 2,
stream_type=0x21 + i % 2,
codec=0,
timestamp=1000000 + i * 1000,
bytes=5,
gap=False,
),
"data": base64.b64encode(b"\0\0\1\x65x").decode(),
}
for i in range(8)
],
}
def serialize(self):
return self.builder.recorded_input(json.dumps(self.sample).encode())
def test_callback_order_markers_timestamps_and_bytes_are_not_rewritten(self):
source = io.BytesIO(self.serialize())
self.assertEqual(source.read(8), b"MCX4P002")
def number(fmt="I"):
return struct.unpack("<" + fmt, source.read(struct.calcsize("<" + fmt)))[0]
def text():
return source.read(number())
self.assertEqual(text(), b"X4")
self.assertEqual(
[text() for _ in range(number())], [b"factory-a", b"factory-b", b"factory-c", b""]
)
self.assertEqual([number() for _ in range(6)], [8000, 6000, 5760, 5760, 0, 0])
self.assertEqual(number(), 0)
self.assertEqual(number(), 8)
for i in range(8):
self.assertEqual(number("q"), 1000000 + i * 1000)
self.assertEqual(number(), 0x21 + i % 2)
self.assertEqual(number(), i % 2)
self.assertEqual(text(), b"\0\0\1\x65x")
self.assertEqual(source.read(), b"")
def test_mixed_calibration_or_generation_and_gaps_fail(self):
for key, value in [
("calibration_revision", 6),
("generation", 4),
("gap", True),
("cursor", 99),
("codec", 1),
("bytes", 6),
("stream_type", 256),
("timestamp", 1),
]:
previous = self.sample["packets"][3]["header"][key]
self.sample["packets"][3]["header"][key] = value
with self.assertRaises(ValueError):
self.serialize()
self.sample["packets"][3]["header"][key] = previous
def test_missing_offsets_and_invalid_base64_fail(self):
self.sample["calibration"]["offsets"] = ["", "", "", ""]
with self.assertRaises(ValueError):
self.serialize()
self.sample["calibration"]["offsets"] = ["factory"]
self.sample["packets"][0]["data"] = "???"
with self.assertRaises(ValueError):
self.serialize()
if __name__ == "__main__":
unittest.main()
@@ -32,13 +32,23 @@ class OwnerModelUpdateTests(unittest.TestCase):
self.assertEqual(owner.update_installed_x4(run)["state"], "current")
self.assertEqual(run.call_count, 1)
def test_newer_installed_model_is_preserved_without_profile_restart(self):
run = Mock(return_value="0.1.3-15")
with (
patch.object(owner.subprocess, "run", side_effect=[Mock(returncode=0, stdout="install ok installed"), Mock(returncode=0)]) as commands,
patch.object(owner.Path, "read_text", return_value=json.dumps(PROFILE)),
):
self.assertEqual(owner.update_installed_x4(run), {"state": "newer-installed-preserved", "version": "0.1.3-15"})
self.assertEqual(run.call_count, 1)
self.assertEqual(commands.call_args.args[0], ["/usr/bin/dpkg", "--compare-versions", "0.1.3-15", "gt", PROFILE["version"]])
def test_offline_model_update_uses_only_fixed_profile_and_checks_result(self):
run = Mock(side_effect=["0.1.3-7", "", PROFILE["version"]])
with (
patch.object(
owner.subprocess,
"run",
return_value=Mock(returncode=0, stdout="install ok installed"),
side_effect=[Mock(returncode=0, stdout="install ok installed"), Mock(returncode=1)],
),
patch.object(
owner.Path,
@@ -70,7 +80,7 @@ class OwnerModelUpdateTests(unittest.TestCase):
patch.object(
owner.subprocess,
"run",
return_value=Mock(returncode=0, stdout="install ok installed"),
side_effect=[Mock(returncode=0, stdout="install ok installed"), Mock(returncode=1)],
),
patch.object(
owner.Path,
@@ -61,6 +61,15 @@ class RecoveryTests(unittest.TestCase):
self.assertEqual(self.value.observe([], 8), [(A, "wake")])
self.assertFalse(self.value.view(B)["enabled"])
def test_original_transfer_suppresses_wake_without_faking_fresh_camera_status(self):
self.enable()
value = snapshot()
value.update(online=False, status={}, file_transfer={"active": True})
self.assertEqual(self.value.observe([value], 0), [])
self.assertEqual(self.value.observe([value], 1000), [])
self.assertFalse(self.value.current[A]["online"])
self.assertEqual(self.value.current[A]["status"], {})
def test_grace_three_attempts_and_restart_do_not_reset_budget(self):
self.enable()
self.value.observe([], 0)
+33 -1
View File
@@ -21,7 +21,7 @@ from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(ROOT), str(ROOT / "packaging")]
import prepare # noqa: E402
from runtime import broker, http, identity, operations, worker # noqa: E402
from runtime import broker, frames, http, identity, operations, worker # noqa: E402
from runtime.verification import Control # noqa: E402
@@ -112,6 +112,38 @@ class RuntimeTests(unittest.TestCase):
def tearDown(self):
self.temporary.cleanup()
def test_sdk_packet_route_is_session_scoped_and_does_not_control_camera(self):
binding = identity.Binding(identity.device_id("SYNTHETIC"), "1-2", 1, 2, "SYNTHETIC")
instance = worker.Worker(binding, self.root, self.root)
instance.feed = frames.Feed(None)
header = {
"generation": 1,
"stream_index": 0,
"codec": 0,
"stream_type": 0x20,
"calibration_revision": 4,
}
config, image = b"\x00\x00\x01\x67sps\x00\x00\x01\x68pps", b"\x00\x00\x01\x65frame"
instance.feed.append((header, config))
instance.feed.append((header, image))
request = {"session_id": instance.session, "cursor": 1}
with self.assertRaises(ValueError):
instance.dispatch("POST", "/sdk-video", request, {})
instance.ready = True
for route, expected in (("/sdk-video", image), ("/video", config + image)):
result = instance.dispatch("POST", route, request, {})
packet, data = frames.decode(result.data)
self.assertEqual(data, expected)
self.assertEqual(packet["calibration_revision"], 4)
for invalid in (
{**request, "session_id": "previous"},
{**request, "action": "preview.start"},
{**request, "cursor": -1},
):
with self.assertRaises(ValueError):
instance.dispatch("POST", route, invalid, {})
self.assertIsNone(instance.camera)
def test_verification_uses_live_source_and_deduplicates_across_preview_states(self):
value = broker.Broker()
ident, session = identity.device_id("SYNTHETIC-A"), "session_one"
@@ -0,0 +1,126 @@
"""Hot-unplug races must not terminate supervision of unrelated cameras."""
import importlib.util
import io
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
SPEC = importlib.util.spec_from_file_location("x4_supervisor", ROOT / "packaging/supervisor.py")
supervisor = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(supervisor)
from runtime.identity import Binding, device_id # noqa: E402
class SupervisorTests(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
root = Path(temporary.name)
self.units, self.control = root / "units", root / "control"
self.units.mkdir()
self.control.mkdir()
self.camera = Binding(device_id("SYNTHETIC-A"), "1-2", 1, 2, "SYNTHETIC-A")
self.other = Binding(device_id("SYNTHETIC-B"), "1-3", 1, 3, "SYNTHETIC-B")
self.present = {}
self.known = {}
self.calls = []
self.start_failure = None
self.patch("UNITS", self.units)
self.patch("CONTROL", self.control)
self.patch("active", lambda: Path("revision"))
self.patch("trusted", lambda path, *args: path)
self.patch("write", lambda path, data: path.write_bytes(data))
self.patch("unit", lambda binding: binding.device_path.encode())
self.patch("bindings", lambda: dict(self.present))
self.patch("read_binding", self.read_binding)
self.patch("systemctl", self.systemctl)
self.stderr = io.StringIO()
self.patch("sys", type("Streams", (), {"stderr": self.stderr}))
def patch(self, name, value):
replacement = patch.object(supervisor, name, value)
replacement.start()
self.addCleanup(replacement.stop)
def read_binding(self, port):
return next(value for value in self.present.values() if value.port == port)
def systemctl(self, *args):
self.calls.append(args)
if (
args == ("start", supervisor.PREFIX + self.camera.device_id + ".service")
and self.start_failure
):
raise self.start_failure
def test_failed_start_preserves_other_camera_and_recovers_on_new_binding(self):
self.present = {self.camera.device_id: self.camera, self.other.device_id: self.other}
self.start_failure = subprocess.CalledProcessError(1, ["systemctl", "start"])
supervisor.reconcile(self.known)
self.assertIn(("start", supervisor.PREFIX + self.other.device_id + ".service"), self.calls)
self.assertIn("CalledProcessError", self.stderr.getvalue())
self.calls.clear()
supervisor.reconcile(self.known)
self.assertEqual(self.calls, []) # No repeated SDK launches for the same binding.
del self.present[self.camera.device_id]
supervisor.reconcile(self.known)
self.assertNotIn(self.camera.device_id, self.known)
self.assertFalse(
(self.units / (supervisor.PREFIX + self.camera.device_id + ".service")).exists()
)
self.assertIn(
self.other.device_id, json.loads((self.control / "bindings.json").read_text())
)
self.camera = Binding(self.camera.device_id, "1-2", 1, 8, "SYNTHETIC-A")
self.present[self.camera.device_id] = self.camera
self.start_failure = None
self.calls.clear()
supervisor.reconcile(self.known)
self.assertEqual(self.known[self.camera.device_id]["address"], 8)
self.assertEqual(
[call for call in self.calls if call[0] == "start"],
[("start", supervisor.PREFIX + self.camera.device_id + ".service")],
)
def test_revalidation_disappearance_does_not_publish_a_stale_unit(self):
self.present = {self.camera.device_id: self.camera}
for error in (FileNotFoundError(), ValueError("device replaced")):
with patch.object(supervisor, "read_binding", side_effect=error):
supervisor.reconcile(self.known)
self.assertEqual(self.known, {})
self.assertEqual(list(self.units.iterdir()), [])
self.assertEqual(self.calls, [])
supervisor.reconcile(self.known)
self.assertIn(self.camera.device_id, self.known)
def test_timeout_has_no_automatic_replay_for_an_unchanged_binding(self):
self.present = {self.camera.device_id: self.camera}
self.start_failure = subprocess.TimeoutExpired(["systemctl", "start"], 20)
supervisor.reconcile(self.known, startup=True)
self.calls.clear()
supervisor.reconcile(self.known)
self.assertEqual(self.calls, [])
self.assertIn("TimeoutExpired", self.stderr.getvalue())
def test_untrusted_installation_still_fails_closed(self):
self.present = {self.camera.device_id: self.camera}
with (
patch.object(supervisor, "unit", side_effect=RuntimeError("untrusted")),
self.assertRaisesRegex(RuntimeError, "untrusted"),
):
supervisor.reconcile(self.known)
self.assertEqual(self.known, {})
self.assertEqual(self.calls, [])
if __name__ == "__main__":
unittest.main(verbosity=2)
@@ -26,6 +26,7 @@ import { xgridsK1Manifest } from "./manifest";
import { deviceTelemetry, finiteMetric, pipelineLatency } from "./presentation";
import { xgridsK1ObservationSources } from "./observationSources";
import { useXgridsK1Runtime } from "./useXgridsK1Runtime";
import { deactivateXgridsK1Runtime } from "./runtimeDeactivation";
export type XgridsK1Controller = ReturnType<typeof useXgridsK1Runtime>;
@@ -173,20 +174,14 @@ export function XgridsK1RuntimeProvider({
useEffect(() => {
if (!activeModel) return;
return registerDeactivation(async () => {
if (controller.pendingAction !== null) return false;
// Never translate navigation/model switching into a K1 control command.
// The operator must explicitly finish or close the canonical dialogue.
if (controller.state?.application_control_session?.control_socket_open) {
return false;
}
return controller.stop();
});
return registerDeactivation(() => deactivateXgridsK1Runtime(controller));
}, [
activeModel,
controller.pendingAction,
controller.state?.application_control_session?.control_socket_open,
controller.stop,
controller.getCurrentState,
controller.closeApplicationControlSession,
controller.stopLocalReceiver,
controller.prepareConnectionReconfiguration,
registerDeactivation,
]);
@@ -0,0 +1,108 @@
import type { PrepareConnectionReconfigurationRequest, XgridsK1State } from "./api";
import { isProvenLocalReceiverInactive, isTerminalAcquisitionState } from "./lifecycle";
interface DeactivationController {
pendingAction: string | null;
getCurrentState: () => XgridsK1State | null;
closeApplicationControlSession: () => Promise<boolean>;
stopLocalReceiver: () => Promise<boolean>;
prepareConnectionReconfiguration: (request: PrepareConnectionReconfigurationRequest) => Promise<boolean>;
}
function hasUnfinishedPhysicalWork(state: XgridsK1State): boolean {
const physical = state.application_control_session?.physical_command ?? state.physical_command;
return physical?.status === "corrupt"
|| physical?.requires_reconciliation === true
|| physical?.resolved_active_recovery_required === true
|| ["scan_starting", "scanning", "scan_stopping"].includes(physical?.observed_session_state ?? "")
|| state.application_control_session?.outcome_unknown === true
|| (
state.source_mode !== "replay"
&& state.acquisition?.control_mode === "plugin-commanded"
&& !isTerminalAcquisitionState(state.acquisition.state)
);
}
/** Release local ownership for explicit model switching; never send START/STOP or Wi-Fi. */
export async function deactivateXgridsK1Runtime(
controller: DeactivationController,
): Promise<boolean> {
if (controller.pendingAction !== null) return false;
const initial = controller.getCurrentState();
if (!initial || hasUnfinishedPhysicalWork(initial)) return false;
const control = initial.application_control_session;
if (control?.control_socket_open) {
// R16 intentionally retains the READY socket between scans. Close that
// exact idle/pre-START checkpoint instead of treating it as an active scan.
if (!["connection-ready", "workspace-ready", "project-ready", "completed"].includes(control.state)) {
return false;
}
if (!(await controller.closeApplicationControlSession())) return false;
}
const stillCurrentAndIdle = (): XgridsK1State | null => {
const current = controller.getCurrentState();
if (
!current
|| current.snapshot_runtime_id !== initial.snapshot_runtime_id
|| current.acquisition?.acquisition_id !== initial.acquisition?.acquisition_id
|| current.application_control_session?.control_socket_open
|| hasUnfinishedPhysicalWork(current)
) return null;
return current;
};
const current = stillCurrentAndIdle();
if (!current) return false;
if (!isProvenLocalReceiverInactive(current)) {
if (!(await controller.stopLocalReceiver())) return false;
if (!isProvenLocalReceiverInactive(stillCurrentAndIdle())) return false;
}
const released = stillCurrentAndIdle();
if (!released) return false;
if (released.desired_connection_mode !== "bridge" || !released.devices?.length) return true;
// A remounted form cannot own the previous form's fresh BLE candidates.
// Retire them through the existing safe Bridge handoff, then cancel its
// pending search intent so the durable read-only target remains available.
// Unlike a scenario reset, handoff rejects concurrent physical work on the
// server and never retires unresolved command/network audit ownership.
const reconfiguration = released.connection_reconfiguration;
const lifecycle = released.connection_lifecycle;
const modeRevision = released.desired_connection_mode_revision;
if (
!reconfiguration || !lifecycle
|| typeof modeRevision !== "number" || !Number.isInteger(modeRevision)
) return false;
if (!(await controller.prepareConnectionReconfiguration({
intent: "select-device",
expected_reconfiguration_revision: reconfiguration.revision,
expected_reconfiguration_intent_id: reconfiguration.intent_id,
expected_desired_mode_revision: modeRevision,
expected_active_binding_key: lifecycle.active_binding_key,
}))) return false;
const prepared = stillCurrentAndIdle();
const pending = prepared?.connection_reconfiguration;
if (
!prepared || !isProvenLocalReceiverInactive(prepared)
|| pending?.intent !== "select-device" || !pending.intent_id
|| pending.revision !== reconfiguration.revision + 1
|| !prepared.connection_lifecycle
|| prepared.desired_connection_mode_revision !== modeRevision
) return false;
if (!(await controller.prepareConnectionReconfiguration({
intent: "cancel",
expected_reconfiguration_revision: pending.revision,
expected_reconfiguration_intent_id: pending.intent_id,
expected_desired_mode_revision: modeRevision,
expected_active_binding_key: prepared.connection_lifecycle.active_binding_key,
}))) return false;
const cleared = stillCurrentAndIdle();
return Boolean(
cleared && isProvenLocalReceiverInactive(cleared)
&& cleared.devices?.length === 0
&& cleared.connection_reconfiguration?.intent === null,
);
}
+2 -2
View File
@@ -22,7 +22,7 @@ from credential_install import PROFILE_ID, validate # noqa: E402
from debian import package # noqa: E402
from runtime_payload import files as runtime_files # noqa: E402
VERSION = "0.1.14"
VERSION = "0.1.16"
RESOURCES = (
"plugins/xgrids-k1/profile_loader.py",
"plugins/xgrids-k1/plugin.manifest.json",
@@ -135,7 +135,7 @@ Architecture: amd64
Maintainer: NODE.DC local build <noreply@example.invalid>
Section: admin
Priority: optional
Depends: mission-core-node (>= 0.8.13), mission-core-node (<< 0.9.0),
Depends: mission-core-node (>= 0.8.49-57), mission-core-node (<< 0.9.0),
systemd, python3, adduser, bluez, network-manager, iproute2, ffmpeg
Breaks: mission-core-node (<< 0.8.0)
Replaces: mission-core-node (<< 0.8.0)
@@ -5,6 +5,7 @@
"src/k1link/__init__.py",
"src/k1link/artifact_gateway.py",
"src/k1link/artifacts.py",
"src/k1link/cache_budget.py",
"src/k1link/compute/__init__.py",
"src/k1link/compute/live_perception.py",
"src/k1link/data_plane/__init__.py",
@@ -65,12 +66,15 @@
"src/k1link/laboratory/__init__.py",
"src/k1link/laboratory/canonical_recorded_migration.py",
"src/k1link/media_fragments.py",
"src/k1link/reconstruction/__init__.py",
"src/k1link/reconstruction/map_version.py",
"src/k1link/sessions/__init__.py",
"src/k1link/sessions/active.py",
"src/k1link/sessions/camera_frame.py",
"src/k1link/sessions/equipment.py",
"src/k1link/sessions/lab_cache.py",
"src/k1link/sessions/live_planning.py",
"src/k1link/sessions/map_recording.py",
"src/k1link/sessions/media.py",
"src/k1link/sessions/models.py",
"src/k1link/sessions/plugin_contract.py",
+12 -7
View File
@@ -11,6 +11,8 @@ from itertools import chain
from uuid import UUID, uuid4
import aioice.ice
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
@@ -106,6 +108,8 @@ class NodeMediaPeers:
await pc.setRemoteDescription(
RTCSessionDescription(sdp=parameters["sdp"], type="offer")
)
entry["budget"] = await adapt_peer(pc, "cloud")
budget_peer(pc, "cloud", producer_id=entry["budget"].id)
await pc.setLocalDescription(await pc.createAnswer())
async def expiry():
@@ -126,7 +130,7 @@ class NodeMediaPeers:
await self.close(identifier)
raise
async def send(self, channel, payload, alive=None):
async def send(self, channel, payload, alive=None, pending=lambda: 0):
if not 0 < len(payload) <= MAX_PAYLOAD:
raise RuntimeError("Preview fragment exceeds bound")
# Each binary_stream.read() is an independent RRD. SCTP messages are
@@ -134,7 +138,7 @@ class NodeMediaPeers:
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 > 256 * 1024:
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())):
raise RuntimeError("Preview consumer unavailable")
@@ -184,7 +188,7 @@ 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"])
subscriber = self.hub.subscribe(entry["view_id"], entry["after"], budget=entry.get("budget"))
entry["subscriber"] = subscriber
else:
lease = await self.camera_delivery(identifier, channel)
@@ -221,7 +225,7 @@ class NodeMediaPeers:
if payload is None:
break
if payload:
await self.send(channel, payload, alive)
await self.send(channel, payload, alive, getattr(entry["pc"], "_missioncore_pending_media", lambda: 0))
if subscriber:
# One in-flight complete native batch. Network stalls
# pause this disposable delivery; the recorder keeps running.
@@ -244,9 +248,10 @@ class NodeMediaPeers:
subscriber.release()
if lease:
self.camera.release_delivery(lease, client_closed=True)
if channel.label == "camera":
channel.close()
else:
# Missing/ended camera is independent of the RRD channel. Keep its
# idle channel until peer close: resetting during DCEP admission can
# race the remote ACK and break the shared SCTP association.
if channel.label != "camera":
await self.close(identifier)
async def close(self, identifier):
+41 -8
View File
@@ -11,6 +11,8 @@ import threading
import time
from contextlib import suppress
from uuid import uuid4
from dataclasses import replace
import math
from k1link.data_plane import DecodedPointCloudView
from k1link.viewer.rerun_bridge import RerunBridge
@@ -22,13 +24,27 @@ logger = logging.getLogger(__name__)
_CURRENT_FRAME = object()
def preview_points(frame, limit):
"""Sample only the disposable view; preserve source, channels and provenance."""
stride = max(1, math.ceil(frame.point_count / max(1, 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)
class PreviewResumeError(ValueError):
"""A view must be explicitly reopened; silently resetting history is forbidden."""
class RrdSubscriber:
def __init__(self, settings_provider, path_provider=None):
def __init__(self, settings_provider, path_provider=None, budget=None):
self.closed = threading.Event()
self.budget = budget
self.next_publish = 0.0
self.inputs = {}
self.input_ready = threading.Condition()
self.delivery_lock = threading.Lock()
@@ -51,13 +67,14 @@ class RrdSubscriber:
self.inputs[type(envelope)] = envelope
self.input_ready.notify()
def attach(self, after=0):
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.delivery_lock.release()
raise PreviewResumeError("Preview cursor does not match recording")
self.budget = budget
self.acknowledge(after)
self.detached_at = None
return self
@@ -130,6 +147,15 @@ class RrdSubscriber:
break
except queue.Full:
continue
budget = self.budget
if budget is not None:
count, interval = budget.cloud()
if not count:
self.closed.wait(.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)
@@ -141,6 +167,13 @@ class RrdSubscriber:
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:
continue
self.next_publish = time.monotonic() + interval
if isinstance(envelope, DecodedPointCloudView):
envelope = preview_points(envelope, count)
bridge.process(envelope)
if isinstance(envelope, DecodedPointCloudView):
self.last_frame = (
@@ -212,26 +245,26 @@ class NodeRerunBridge(RerunBridge):
value.close()
del self.views[key]
def subscribe(self, view_id=None, after=0):
def subscribe(self, view_id=None, after=0, *, budget=None):
with self.lock:
self._expire_views()
if self._closed:
raise RuntimeError("Live acquisition is not active")
if view_id in self.views:
return self.views[view_id].attach(after)
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))
subscriber = RrdSubscriber(self._settings_provider, lambda: list(self._path), budget)
for observed, envelope in self.latest.values():
if time.monotonic() - observed <= LIVE_FRAME_MAX_AGE_SECONDS:
subscriber.offer(envelope)
self.subscribers.append(subscriber)
if view_id is not None:
self.views[view_id] = subscriber
subscriber.attach()
subscriber.attach(budget=budget)
return subscriber
def release_view(self, view_id):
@@ -260,11 +293,11 @@ class NodeRerunHub:
self.bridge = bridge
return bridge
def subscribe(self, view_id=None, after=0):
def subscribe(self, view_id=None, after=0, *, budget=None):
bridge = self.bridge
if bridge is None:
raise RuntimeError("Live acquisition is not active")
return bridge.subscribe(view_id, after)
return bridge.subscribe(view_id, after, budget=budget)
def release_view(self, view_id):
if self.bridge is not None:
+55
View File
@@ -0,0 +1,55 @@
"""Preview adaptation consumes new hardware frames, never repeats a stalled source."""
import asyncio
import importlib.util
import time
from pathlib import Path
from types import SimpleNamespace
import aioice.ice
import numpy as np
import pytest
from missioncore_plugin_sdk.media_budget import MediaBudget
def test_realsense_preview_changes_size_without_replaying_a_stalled_source(monkeypatch):
original = aioice.ice.get_host_addresses
monkeypatch.setattr(aioice.ice, "get_host_addresses", original)
path = Path(__file__).parents[2] / "apps/node-agent/sensors/media.py"
spec = importlib.util.spec_from_file_location("sensor_media_test", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
async def run():
device = SimpleNamespace(
images={"color": np.zeros((480, 640, 3), dtype=np.uint8)},
frames={"color": 1},
last_frame={"monotonic_ns": time.monotonic_ns()},
)
budget = MediaBudget("video")
budget.update(
{"schema": "missioncore.media-budget/v1", "allocation_bps": 800_000, "ttl_ms": 3000}
)
track = module.CameraTrack(device, "color", budget)
try:
first = await asyncio.wait_for(track.recv(), 0.5)
assert (first.width, first.height) == (640, 480)
with pytest.raises(TimeoutError):
await asyncio.wait_for(track.recv(), 0.15)
device.frames["color"] = 2
device.last_frame["monotonic_ns"] = time.monotonic_ns()
budget.update(
{"schema": "missioncore.media-budget/v1", "allocation_bps": 100_000, "ttl_ms": 3000}
)
second = await asyncio.wait_for(track.recv(), 0.5)
assert (second.width, second.height) == (160, 120) and second.pts > first.pts
assert device.images["color"].shape == (480, 640, 3)
device.frames["color"] = 3
device.last_frame["monotonic_ns"] = time.monotonic_ns() - 3_000_000_000
with pytest.raises(TimeoutError):
await asyncio.wait_for(track.recv(), 0.6)
finally:
track.stop()
budget.connection.close()
asyncio.run(run())
+20
View File
@@ -81,3 +81,23 @@ def test_disconnect_finalizes_failed_record_and_clears_live_frames(monkeypatch,
assert value["state"] == "failed" and value["sha256"]
device.disconnect()
assert stopped == [True]
def test_preview_point_bound_does_not_modify_depth_capture(monkeypatch, tmp_path):
import numpy as np
rs = types.ModuleType("pyrealsense2")
rs.rs2_deproject_pixel_to_point = lambda intrinsics, point, z: [*point, z]
monkeypatch.setitem(__import__("sys").modules, "pyrealsense2", rs)
path = Path(__file__).parents[2] / "apps/node-agent/sensors/device.py"
spec = importlib.util.spec_from_file_location("points_device", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
device = module.Device("synthetic-camera", tmp_path, {})
device.depth = np.ones((479, 641), dtype=np.uint16)
device.intrinsics = object()
device.depth_scale = 0.001
before = device.depth.copy()
assert len(device.points(7)) <= 21 and len(device.points(2000)) <= 6000
assert device.points(0) == []
assert np.array_equal(device.depth, before)
+6 -3
View File
@@ -23,6 +23,8 @@ def test_node_update_restores_only_previously_running_configured_plugin(
state = tmp_path / "active"
if active:
state.touch()
cache_helper = tmp_path / "clear_runtime_cache.py"
cache_helper.write_text("# OS cache cleanup is independently qualified.\n")
events = tmp_path / "events"
systemctl = binary / "systemctl"
systemctl.write_text('''#!/bin/sh
@@ -30,8 +32,8 @@ printf '%s\\n' "$*" >> "$TEST_EVENTS"
case "$1" in
is-active) [ -f "$TEST_ACTIVE" ]; exit $? ;;
show) echo inactive ;;
stop) rm -f "$TEST_ACTIVE" ;;
start) touch "$TEST_ACTIVE" ;;
stop) [ "$2" != mission-core-k1.service ] || rm -f "$TEST_ACTIVE" ;;
start) [ "$2" != mission-core-k1.service ] || touch "$TEST_ACTIVE" ;;
esac
''')
(binary / "getent").write_text("#!/bin/sh\nexit 0\n")
@@ -48,7 +50,8 @@ esac
script.write_text((PACKAGING / name).read_text()
.replace("/run/", str(run) + "/")
.replace("/usr/lib/mission-core-node/setup-monitor", str(binary / "setup-monitor"))
.replace("/etc/os-release", str(release)))
.replace("/etc/os-release", str(release))
.replace("/usr/lib/mission-core-vesc/clear_runtime_cache.py", str(cache_helper)))
subprocess.run(["/bin/sh", str(script), *args], env=env, check=True,
capture_output=True, text=True)
if name == "preinst":
+14 -2
View File
@@ -7,6 +7,18 @@ 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})
from missioncore_plugin_sdk.link_budget import BudgetClient
async def permit(self, size):
return True
monkeypatch.setattr(BudgetClient, "_permit", permit)
SDP_HEADER = "v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n"
@@ -19,7 +31,7 @@ def test_media_rejects_non_private_or_relay_candidates(address, kind):
def test_media_accepts_paired_lan_and_tailnet_candidates():
for address in ("192.168.1.2", "100.80.6.113", "peer.local"):
for address in ("192.168.1.2", "100.64.0.10", "peer.local"):
admit_sdp(SDP_HEADER + f"a=candidate:1 1 udp 1 {address} 12345 typ host\r\n")
@@ -72,7 +84,7 @@ def test_native_webrtc_roundtrip_and_missing_camera_preserve_rrd(monkeypatch):
pass
class Hub:
def subscribe(self, view_id, after):
def subscribe(self, view_id, after, **kwargs):
return Subscription()
class Camera: