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:
@@ -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>;
|
||||
}
|
||||
|
||||
@@ -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))}</>;
|
||||
}
|
||||
|
||||
@@ -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));}}}/>;
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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()
|
||||
@@ -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))
|
||||
@@ -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,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": "Не удалось однозначно выбрать камеру для включения.",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"):
|
||||
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
Reference in New Issue
Block a user