Persist rover observation configuration and calibrate Insta360 panorama

This commit is contained in:
DCCONSTRUCTIONS
2026-10-09 18:17:54 +03:00
parent c43b097a3a
commit b4dab01f2a
36 changed files with 1271 additions and 50 deletions
@@ -0,0 +1,30 @@
# Panorama optical conventions
`frontend/src/panoramaCalibration.ts` adapts calibration layouts and projection
conventions from [GyroView](https://github.com/bubo-squared/GyroView), revision
`ae5c22b155ab4ec9c28d141e61340ca2d6f94994`. This is not Insta360 Media SDK.
Legacy radius angles, polynomial normalization and lens-pose signs are
open-source interpretations; they require qualification on the actual live camera.
No GyroView application, recording parser or dependency tree is included.
MIT License
Copyright (c) 2026 Bubo²
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -40,6 +40,7 @@ export function X4Detail({device,transport,enabled,back,refresh,failure}:SensorD
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>}
@@ -7,8 +7,9 @@ import {useSensorPreview} from '../../../../packages/sensor-ui/src/useSensorPrev
import {useObservationStart} from '../../../../packages/sensor-ui/src/useObservationStart';
import {startX4Observation} from './observationStart';
import {cameraStatus} from './model';
import {X4Panorama} from './X4Panorama';
function Lens({video,side,label,live}:{video:RefObject<HTMLVideoElement|null>;side:number;label:string;live:boolean}){
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);
useEffect(()=>{
const source=video.current,target=canvas.current;if(!source||!target)return;
@@ -17,7 +18,7 @@ function Lens({video,side,label,live}:{video:RefObject<HTMLVideoElement|null>;si
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;}target.getContext('2d')?.drawImage(source,side*source.videoWidth/2,0,source.videoWidth/2,source.videoHeight,0,0,size,size);}
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 tick=()=>{draw();if(active)handle=source.requestVideoFrameCallback(tick);};
@@ -25,10 +26,10 @@ function Lens({video,side,label,live}:{video:RefObject<HTMLVideoElement|null>;si
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]);
return <><canvas ref={canvas} aria-label={label} className="observation-lens" data-live={live&&supported}/>{!supported&&<p>Текущий формат изображения не содержит пару объективов.</p>}</>;
},[video,side,rotation]);
return <><canvas ref={canvas} aria-label={label} className="observation-lens" data-live={live&&supported} data-rotation={rotation}/>{!supported&&<p>Текущий формат изображения не содержит пару объективов.</p>}</>;
}
export function X4Observation({device,transport,enabled,views}:SensorObservationProps){
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));
@@ -39,9 +40,11 @@ export function X4Observation({device,transport,enabled,views}:SensorObservation
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?'Не удалось восстановить изображение. Повторите просмотр.':''))||'';
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}>{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"><Lens video={video} side={view.id==='left'?0:1} label={`${device.name} ${view.id==='left'?'Left':'Right'} Cam`} live={hasFrame}/></div>
<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>}
</div>,view.target,view.id))}</>;
}
@@ -0,0 +1,78 @@
import {useEffect,useMemo,useRef,useState,type RefObject} from 'react';
import {liveCalibration,lensDirection,type Vec3} from './panoramaCalibration';
import {overlapGains} from './panoramaExposure';
import {panoramaFragment as fragment} from './panoramaShader';
import type {CameraPresentation} from '../../../../packages/sensor-ui/src/observation';
// 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}) {
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;
useEffect(()=>{redraw.current();},[presentation,calibration]);
useEffect(()=>{
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 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);};
try {
const compile=(type:number,code:string)=>{const shader=gl.createShader(type);if(!shader)throw Error('shader');shaders.push(shader);gl.shaderSource(shader,code);gl.compileShader(shader);if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS))throw Error('shader');return shader;};
program=gl.createProgram();if(!program)throw Error('program');gl.attachShader(program,compile(gl.VERTEX_SHADER,vertex));gl.attachShader(program,compile(gl.FRAGMENT_SHADER,fragment));gl.linkProgram(program);if(!gl.getProgramParameter(program,gl.LINK_STATUS))throw Error('link');gl.useProgram(program);
buffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);
const attribute=gl.getAttribLocation(program,'point');gl.enableVertexAttribArray(attribute);gl.vertexAttribPointer(attribute,2,gl.FLOAT,false,0,0);
texture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,texture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);
const rotations=gl.getUniformLocation(program,'rotation'),heading=gl.getUniformLocation(program,'heading'),calibrated=gl.getUniformLocation(program,'calibrated');
const uniforms=[0,1].map(i=>Object.fromEntries(['pose','center','focal','tangential','radial','gain','polynomial','kind','xi'].map(name=>[name,gl.getUniformLocation(program!,name+i)])));
const meter=document.createElement('canvas');meter.width=384;meter.height=192;
const meterContext=meter.getContext('2d',{willReadFrequently:true});
let lastSample=0,lastOptics='',gains:readonly [Vec3,Vec3]=[[1,1,1],[1,1,1]];
const draw=()=>{
if(!active||source.readyState<2||!source.videoWidth)return;
if(Math.abs(source.videoWidth/source.videoHeight-2)>.02){setError('Текущий формат изображения не содержит пару объективов.');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);
const current=settings.current;gl.uniform2f(rotations,(current.rotations.left??0)*Math.PI/180,(current.rotations.right??0)*Math.PI/180);gl.uniform1f(heading,current.panoramaYaw*Math.PI/180);
const optical=calibrationRef.current;gl.uniform1f(calibrated,optical?1:0);
if(optical){
const turns=[current.rotations.left??0,current.rotations.right??0];
const key=JSON.stringify([optical,turns]);if(key!==lastOptics){lastOptics=key;lastSample=0;gains=[[1,1,1],[1,1,1]];}
const now=performance.now();
if(meterContext&&now-lastSample>=1000){
try{meterContext.drawImage(source,0,0,meter.width,meter.height);const found=overlapGains(meterContext.getImageData(0,0,meter.width,meter.height).data,meter.width,meter.height,optical,turns);
if(found){const weight=lastSample?1-Math.exp(-(now-lastSample)/1500):1;gains=found.map((v,i)=>v.map((n,c)=>gains[i][c]+(n-gains[i][c])*weight)) as unknown as readonly [Vec3,Vec3];}
}catch{/* Exposure metering cannot interrupt the live projection. */}
lastSample=now;
}
optical.lenses.forEach((lens,i)=>{const u=uniforms[i];
const matrix=([[1,0,0],[0,1,0],[0,0,1]] as Vec3[]).flatMap(ray=>lensDirection(ray,lens,i,turns[i]));
gl.uniformMatrix3fv(u.pose,false,matrix);gl.uniform2f(u.center,...lens.center);gl.uniform2f(u.focal,...lens.focal);gl.uniform2f(u.tangential,...lens.tangential);
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('');
};
redraw.current=draw;
const tick=()=>{draw();if(active)handle=source.requestVideoFrameCallback(tick);};
const fallback=()=>{draw();if(active)frame=requestAnimationFrame(fallback);};
const resize=new ResizeObserver(draw);resize.observe(target);
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]);
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'}}
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>}</>;
}
+2 -2
View File
@@ -15,7 +15,7 @@ export function cameraRowActions(device:Sensor):readonly SensorRowAction[] {
export interface CameraStatus {
connected:boolean; preview:number|null; recording:number|null; function_mode:number|null;
firmware?:string; battery?:{level:number}; storage?:{free_bytes:number};
firmware?:string; serial?:string; battery?:{level:number}; storage?:{free_bytes:number};
alerts?:{battery_low?:boolean;storage_full?:boolean;temperature_high?:boolean};
recovery?:RecoveryStatus;
}
@@ -29,7 +29,7 @@ export interface CameraFiles {items:string[];offset:number;total:number}
const state=(value:unknown)=>value===0||value===1||value===-1?value:null;
export function cameraStatus(device:Sensor):CameraStatus {
const value=device.camera_status??{};
return {...value,connected:value.connected===true,preview:state(value.preview),recording:state(value.recording),
return {...value,serial:typeof value.serial==='string'&&value.serial.length<=256?value.serial:undefined,connected:value.connected===true,preview:state(value.preview),recording:state(value.recording),
function_mode:typeof value.function_mode==='number'&&Number.isInteger(value.function_mode)?value.function_mode:null} as CameraStatus;
}
export function cameraLabel(device:Sensor,fresh:boolean):{label:string;tone:'neutral'|'success'|'warning'|'danger'} {
@@ -0,0 +1,104 @@
/** Optical calibration layout informed by GyroView (MIT), pinned in THIRD_PARTY_NOTICES.md.
* Factory strings describe sensor pixels, independently of operator display rotations.
* Unknown/malformed versions are rejected instead of silently becoming a calibration.
*/
export type Vec3 = readonly [number,number,number];
export interface LensOptics {
kind:'radial'|'mei'; center:readonly [number,number]; orientation:Vec3;
polynomial:readonly [number,number,number,number];
focal:readonly [number,number]; xi:number; radial:Vec3; tangential:readonly [number,number];
}
export interface PanoramaCalibration {version:1|2|3; width:number;height:number;lenses:readonly [LensOptics,LensOptics]}
const radians=Math.PI/180;
const polynomial=(c:readonly number[],theta:number)=>theta*(c[0]+theta*(c[1]+theta*(c[2]+theta*c[3])));
const bounded=(v:number,limit:number)=>Number.isFinite(v)&&Math.abs(v)<=limit;
export function parseCalibration(value:unknown):PanoramaCalibration|null {
if(typeof value!=='string'||value.length>8192)return null;
const tokens=value.split('_');if(tokens.some(t=>t.trim()===''))return null;
const a=tokens.map(Number);if(a.some(v=>!bounded(v,1e9))||a[0]!==2)return null;
const version=a.length===16?1:a.length===34?2:a.length===40?3:null;if(!version)return null;
const word=a.at(-1)!;if(!Number.isInteger(word)||word<0||word>0xffffffff||(version!==1&&Math.floor(word/65536)!==version))return null;
const stride=version===1?6:version===2?16:19;
const width=version===1?a[13]:a[1+(version===2?13:16)];
const height=version===1?a[14]:a[1+(version===2?14:17)];
if(width<2||width>65536||height<1||height>32768||width<height||width>height*4)return null;
const lenses:LensOptics[]=[];
for(let i=0;i<2;i++){
const b=a.slice(1+i*stride,1+(i+1)*stride);
if(version!==1&&(b[version===2?13:16]!==width||b[version===2?14:17]!==height))return null;
const center:readonly [number,number]=version===3?[b[3],b[4]]:[b[1],b[2]];
if(center[0]<i*width/2||center[0]>(i+1)*width/2||center[1]<0||center[1]>height)return null;
const orientation=b.slice(version===3?5:3,version===3?8:6) as unknown as Vec3;
if(orientation.some(v=>!bounded(v,360)))return null;
const lens:LensOptics={kind:version===3?'mei':'radial',center,orientation,polynomial:[0,0,0,0],focal:[1,1],xi:0,radial:[0,0,0],tangential:[0,0]};
if(version===3){
if(b[0]<0||b[0]>3||b[1]<=0||b[2]<=0||b[1]>width*2||b[2]>height*4||b.slice(11,16).some(v=>!bounded(v,100)))return null;
lens.xi=b[0];lens.focal=[b[1],b[2]];lens.radial=[b[11],b[12],b[13]];lens.tangential=[b[14],b[15]];
}else{
if(b[0]<=0||b[0]>height)return null;
// The legacy angular scale is an open-source convention, not a vendor guarantee.
if(version===1)lens.polynomial=[b[0]/(96*radians),0,0,0];
else {
const c=b.slice(9,13),edge=polynomial(c,100*radians);if(edge<=0)return null;
lens.polynomial=c.map(v=>v*b[0]/edge) as unknown as LensOptics['polynomial'];
let previous=0;for(let t=1;t<=100;t++){const r=polynomial(lens.polynomial,t*radians);if(!Number.isFinite(r)||r<=previous)return null;previous=r;}
}
}
lenses.push(lens);
}
return {version,width,height,lenses:lenses as unknown as PanoramaCalibration['lenses']};
}
/** Existing operator left/right rotations own the mounting; factory residuals refine it.
* Input rays use the viewer's x-forward/y-right/z-up convention. Lens 0 is the left half.
*/
export function lensDirection(ray:Vec3,lens:LensOptics,index:number,rotation:number):Vec3 {
let [x,y,z]=[-ray[1],-ray[2],-ray[0]];
const [yaw,pitch,roll]=lens.orientation.map(v=>v*radians);
[x,z]=[Math.cos(yaw)*x+Math.sin(yaw)*z,-Math.sin(yaw)*x+Math.cos(yaw)*z];
[y,z]=[Math.cos(pitch)*y-Math.sin(pitch)*z,Math.sin(pitch)*y+Math.cos(pitch)*z];
if(index===1){y=-y;z=-z;}
const residual=roll-Math.round(roll/(Math.PI/2))*(Math.PI/2);
const angle=(index===1?Math.PI:0)-rotation*radians-residual;
return [Math.cos(angle)*x-Math.sin(angle)*y,Math.sin(angle)*x+Math.cos(angle)*y,z];
}
export function projectLens(calibration:PanoramaCalibration,index:0|1,ray:Vec3,rotation:number):readonly [number,number]|null {
const lens=calibration.lenses[index],[x,y,z]=lensDirection(ray,lens,index,rotation),theta=Math.atan2(Math.hypot(x,y),z);
if(theta>100*radians)return null;
let px:number,py:number;
if(lens.kind==='radial'){
const r=polynomial(lens.polynomial,theta),norm=Math.max(Math.hypot(x,y),1e-9);px=lens.center[0]+r*x/norm;py=lens.center[1]+r*y/norm;
}else{
const denominator=z+lens.xi;if(denominator<=1e-6)return null;
const u=x/denominator,v=y/denominator,r2=u*u+v*v,[k1,k2,k3]=lens.radial,[p1,p2]=lens.tangential;
const scale=1+r2*(k1+r2*(k2+r2*k3));
px=lens.center[0]+lens.focal[0]*(scale*u+2*p1*u*v+p2*(r2+2*u*u));
py=lens.center[1]+lens.focal[1]*(scale*v+p1*(r2+2*v*v)+2*p2*u*v);
}
if(!Number.isFinite(px)||!Number.isFinite(py)||px<index*calibration.width/2||px>(index+1)*calibration.width/2||py<0||py>calibration.height)return null;
return [px/calibration.width,py/calibration.height];
}
/** The live X4 packs a centred square crop from each rectangular sensor. SDK offsets
* shift that crop relative to the centre. Keep this mapping separate from lens optics.
*/
export function liveCalibration(value:unknown):PanoramaCalibration|null {
if(!value||typeof value!=='object')return null;
const data=value as {offsets?:unknown;crop?:Record<string,unknown>};
if(!Array.isArray(data.offsets)||data.offsets.length>4)return null;
const candidates=data.offsets.map(parseCalibration).filter((v):v is PanoramaCalibration=>v!==null);
// Prefer the explicit unified camera model, avoiding the legacy radius-angle guess.
const c=candidates.find(v=>v.version===3)??candidates.find(v=>v.version===2)??candidates[0];if(!c)return null;
const crop=data.crop;if(!crop)return null;
const [sw,sh,w,h,x,y]=['source_width','source_height','width','height','x','y'].map(k=>crop[k]);
if([sw,sh,w,h,x,y].some(v=>typeof v!=='number'||!Number.isInteger(v)||!bounded(v,65536)))return null;
const sourceWidth=sw as number,sourceHeight=sh as number,width=w as number,height=h as number;
if(sourceWidth!==c.width/2||sourceHeight!==c.height||width<=0||height<=0||width!==height||width>sourceWidth||height>sourceHeight)return null;
const ox=(sourceWidth-width)/2+(x as number),oy=(sourceHeight-height)/2+(y as number);
if(ox<0||oy<0||ox+width>sourceWidth||oy+height>sourceHeight)return null;
return {...c,width:2,height:1,lenses:c.lenses.map((lens,i)=>({...lens,
center:[i+(lens.center[0]-i*sourceWidth-ox)/width,(lens.center[1]-oy)/height],
focal:[lens.focal[0]/width,lens.focal[1]/height],
polynomial:lens.polynomial.map(v=>v/width),
})) as unknown as PanoramaCalibration['lenses']};
}
@@ -0,0 +1,20 @@
import {projectLens,type PanoramaCalibration,type Vec3} from './panoramaCalibration';
const median=(values:number[])=>{values.sort((a,b)=>a-b);return values[Math.floor(values.length/2)];};
/** Robust same-direction overlap samples, never whole-lens averages of different scenery.
* Bounded 384-ray analysis once per second, in the decoded display signal. It avoids clipping
* and limits correction to 33%; nearby parallax must not drive unlimited colour changes.
*/
export function overlapGains(pixels:Uint8ClampedArray,width:number,height:number,calibration:PanoramaCalibration,rotations:readonly number[]):readonly [Vec3,Vec3]|null {
const ratios:number[][]=[[],[],[]];
for(const side of [-1,1])for(let lat=-72;lat<=72;lat+=3)for(const delta of [-2,0,2]){
const latitude=lat*Math.PI/180,longitude=(side*90+delta)*Math.PI/180;
const ray:Vec3=[Math.cos(latitude)*Math.cos(longitude),Math.cos(latitude)*Math.sin(longitude),Math.sin(latitude)];
const a=projectLens(calibration,0,ray,rotations[0]),b=projectLens(calibration,1,ray,rotations[1]);if(!a||!b)continue;
const sample=(uv:readonly number[])=>4*(Math.min(height-1,Math.floor(uv[1]*height))*width+Math.min(width-1,Math.floor(uv[0]*width)));
const ai=sample(a),bi=sample(b);
for(let channel=0;channel<3;channel++){const av=pixels[ai+channel],bv=pixels[bi+channel];if(av>18&&bv>18&&av<235&&bv<235)ratios[channel].push(Math.log(bv/av));}
}
if(ratios.some(v=>v.length<32))return null;
const gain=ratios.map(values=>{const middle=median(values);const inliers=values.filter(v=>Math.abs(v-middle)<.25);return inliers.length<24?1:Math.exp(Math.max(-Math.log(4/3),Math.min(Math.log(4/3),median(inliers)/2)));}) as unknown as Vec3;
return [gain,gain.map(v=>1/v) as unknown as Vec3];
}
@@ -0,0 +1,38 @@
// GPU projection from the camera's own optical parameters; one existing video texture.
const lens=(i:number)=>`
uniform mat3 pose${i}; uniform vec2 center${i},focal${i},tangential${i};
uniform vec3 radial${i},gain${i}; uniform vec4 polynomial${i}; uniform float kind${i},xi${i};
vec4 lens${i}(vec3 ray){
vec3 d=pose${i}*ray;float theta=atan(length(d.xy),d.z);vec2 pixel;
if(kind${i}<.5){
vec4 c=polynomial${i};float r=theta*(c.x+theta*(c.y+theta*(c.z+theta*c.w)));
pixel=center${i}+r*d.xy/max(length(d.xy),.000001);
}else{
vec2 p=d.xy/max(d.z+xi${i},.000001);float r2=dot(p,p);vec3 k=radial${i};vec2 t=tangential${i};
float scale=1.+r2*(k.x+r2*(k.y+r2*k.z));
vec2 distorted=scale*p+vec2(2.*t.x*p.x*p.y+t.y*(r2+2.*p.x*p.x),t.x*(r2+2.*p.y*p.y)+2.*t.y*p.x*p.y);
pixel=center${i}+focal${i}*distorted;
}
vec3 color=texture2D(image,vec2(pixel.x*.5,pixel.y)).rgb;
float valid=step(${i}.,pixel.x)*step(pixel.x,${i+1}.)*step(0.,pixel.y)*step(pixel.y,1.);
float weight=(1.-smoothstep(radians(87.),radians(93.),theta))*valid;
return vec4(color*gain${i},weight);
}`;
export const panoramaFragment=`precision highp float;
varying vec2 uv; uniform sampler2D image; uniform vec2 rotation; uniform float heading,calibrated;
const float PI=3.141592653589793;
${lens(0)}${lens(1)}
void main(){
float longitude=(uv.x-.5)*2.*PI+heading,latitude=(uv.y-.5)*PI;
vec3 ray=vec3(cos(latitude)*cos(longitude),cos(latitude)*sin(longitude),sin(latitude));
if(calibrated>.5){
vec4 a=lens0(ray),b=lens1(ray);float total=a.a+b.a;
if(total>.00001){gl_FragColor=vec4((a.rgb*a.a+b.rgb*b.a)/total,1.);return;}
}
// Compatibility view for old drivers or unrecognised calibration, without fake blending.
bool front=ray.x>=0.;float transverse=length(ray.yz),theta=atan(transverse,abs(ray.x));
vec2 p=vec2(front?ray.y:-ray.y,-ray.z)*theta/max(transverse,.000001)*(.495/(PI*.5));
float a=front?rotation.y:rotation.x;
p=vec2(cos(a)*p.x+sin(a)*p.y,-sin(a)*p.x+cos(a)*p.y);
gl_FragColor=texture2D(image,vec2((front?.5:0.)+(p.x+.5)*.5,p.y+.5));
}`;
+3 -2
View File
@@ -1,11 +1,12 @@
import type {SensorUiContribution} from '../../../../packages/sensor-ui/src/extensions';
import {X4Detail} from './X4Detail';
import {cameraLabel,cameraRowActions} from './model';
import {cameraLabel,cameraRowActions,cameraStatus} from './model';
import {X4Observation} from './X4Observation';
export const insta360X4SensorUi:SensorUiContribution={
kind:'insta360.x4',Detail:X4Detail,icon:'camera',retainOffline:true,
supportsPreparation:true,supportsRenaming:true,status:cameraLabel,
rowActions:cameraRowActions,
observation:{Session:X4Observation,views:device=>[{id:'left',label:`${device.name} Left Cam`},{id:'right',label:`${device.name} Right Cam`}]},
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} · панорама`}]},
};
+31 -3
View File
@@ -24,8 +24,8 @@ constexpr size_t MAX_PACKET = 4 * 1024 * 1024;
constexpr size_t MAX_QUEUE = 8 * 1024 * 1024;
constexpr size_t MAX_RESULT = 60 * 1024;
std::string quote(const std::string& value) {
if (value.size() > 1024) throw std::runtime_error("oversized SDK string");
std::string quote(const std::string& value, size_t limit = 1024) {
if (value.size() > limit) throw std::runtime_error("oversized SDK string");
std::ostringstream out;
out << '"';
for (unsigned char c : value) {
@@ -111,7 +111,7 @@ struct mc_x4 {
std::shared_ptr<Camera> camera;
std::shared_ptr<Frames> frames = std::make_shared<Frames>();
std::shared_ptr<Notifications> notifications = std::make_shared<Notifications>();
std::string firmware, result;
std::string firmware, serial, calibration = "null", result;
bool opened = false;
int preview = 0;
// Only the isolated worker calls control methods; callbacks use separate
@@ -145,6 +145,8 @@ struct mc_x4 {
}
}
std::string result = "{\"firmware\":" + quote(firmware) +
",\"serial\":" + quote(serial) +
",\"preview_calibration\":" + calibration +
",\"connected\":" + (connected ? "true" : "false") +
",\"preview\":" + std::to_string(preview) +
",\"recording\":" + std::to_string(notifications->recording) +
@@ -165,6 +167,30 @@ struct mc_x4 {
return complete(result);
}
void read_preview_calibration() {
// 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";
try {
auto param = camera->GetPreviewParam();
const auto count = param.GetCalibrationCount();
if (!count || count > 4) return;
std::ostringstream out;
out << "{\"offsets\":[";
for (size_t i = 0; i < count; ++i) {
if (i) out << ',';
out << quote(param.GetCalibration(i), 8192);
}
out << "],\"crop\":{\"source_width\":" << param.GetCropSrcWidth()
<< ",\"source_height\":" << param.GetCropSrcHeight()
<< ",\"width\":" << param.GetCropDstWidth()
<< ",\"height\":" << param.GetCropDstHeight()
<< ",\"x\":" << param.GetCropOffsetX()
<< ",\"y\":" << param.GetCropOffsetY() << "}}";
calibration = out.str();
} catch (...) { calibration = "null"; }
}
std::string settings(CameraFunctionMode mode) {
if (!mode_supported(mode)) return INVALID;
if (!camera->SyncPhotographyOptions(mode)) return UNKNOWN;
@@ -380,11 +406,13 @@ mc_x4* mc_x4_open(const char* serial, const char* log_directory) {
const auto& device = handle->descriptors.front();
if (device.camera_type != CameraType::Insta360X4 || device.info.connection_type != ConnectionType::USB || device.serial_number != serial) return nullptr;
handle->firmware = device.fw_version;
handle->serial = device.serial_number;
handle->camera = std::make_shared<Camera>(device.info);
handle->camera->SetServicePort(9099); // private network namespace per instance
handle->camera->SetTimeout(10000);
handle->opened = handle->camera->Open();
if (!handle->opened) return nullptr;
handle->read_preview_calibration();
auto n = handle->notifications;
handle->camera->SetCaptureStateNotification([n](bool active) {
std::lock_guard<std::mutex> lock(n->mutex);
@@ -93,6 +93,18 @@ def test_discovery_never_selects_first_of_multiple_cameras(library):
assert library.test_count(0) == 0 and library.test_count(2) == 2
def test_details_include_session_identity_and_optics_without_starting_preview(camera):
api, _ = camera
result = call(camera, 1)["result"]
assert result["serial"] == "SYNTHETIC-X4"
assert len(result["preview_calibration"]["offsets"]) == 1
assert result["preview_calibration"]["crop"] == {
"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
def test_preview_stop_and_close_do_not_stop_recording(camera):
api, handle = camera
assert call(camera, 6)["state"] == "complete"
@@ -179,6 +191,20 @@ def test_early_camera_stop_notification_wins_over_start_acknowledgement(camera):
assert api.test_count(4) == 1
def test_unavailable_calibration_preserves_camera_control(library):
for mode in (1, 2):
library.test_calibration(mode)
handle = library.mc_x4_open(b"SYNTHETIC-X4", b"/unused")
assert handle
try:
result = call((library, handle), 1)["result"]
assert result["serial"] == "SYNTHETIC-X4"
assert result["preview_calibration"] is None
assert library.test_count(3) == 0 and library.test_count(6) == 0
finally:
library.mc_x4_close(handle)
class TestNativeBridge(unittest.TestCase):
@classmethod
def setUpClass(cls):
+18 -2
View File
@@ -10,7 +10,7 @@ int discovered = 1, opens = 0, closes = 0, freed = 0, writes = 0;
int record_starts = 0, record_stops = 0, previews = 0, preview_stops = 0;
bool recording = false, start_ack = true, preview_ack = true, connected = true;
bool stop_before_ack = false;
int function_mode = 7;
int function_mode = 7, calibration_mode = 0;
std::shared_ptr<ins_camera::StreamDelegate> delegate;
ins_camera::CaptureStateCallBack capture_callback;
std::shared_ptr<ins_camera::CaptureSettings> capture;
@@ -19,6 +19,21 @@ std::shared_ptr<ins_camera::ExposureSettings> exposure;
namespace ins_camera {
class CameraImpl {};
struct PreviewParam::Impl {};
PreviewParam::PreviewParam() = default;
PreviewParam::~PreviewParam() = default;
PreviewParam::PreviewParam(PreviewParam&&) noexcept = default;
PreviewParam& PreviewParam::operator=(PreviewParam&&) noexcept = default;
size_t PreviewParam::GetCalibrationCount() const { if (calibration_mode == 1) throw std::runtime_error("unavailable"); return calibration_mode == 2 ? 5 : 1; }
std::string PreviewParam::GetCalibration(size_t) const { return "2_480_480_480_0_0_0_480_1440_480_0_0_0_1920_960_0"; }
uint32_t PreviewParam::GetCropSrcWidth() const { return 1920; }
uint32_t PreviewParam::GetCropSrcHeight() const { return 960; }
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(); }
class ExposureSettingsPrivate {
public:
int iso = 100, ev = 0;
@@ -109,13 +124,14 @@ void ExposureSettings::SetExposureMode(PhotographyOptions_ExposureMode value) {
extern "C" {
void test_reset() {
discovered = 1; opens = closes = freed = writes = record_starts = record_stops = previews = preview_stops = 0;
recording = stop_before_ack = false; connected = start_ack = preview_ack = true; function_mode = 7;
recording = stop_before_ack = false; connected = start_ack = preview_ack = true; function_mode = 7; calibration_mode = 0;
delegate.reset(); capture_callback = nullptr;
capture = std::make_shared<ins_camera::CaptureSettings>(); exposure = std::make_shared<ins_camera::ExposureSettings>();
}
int test_count(int which) {
switch (which) { case 0: return opens; case 1: return closes; case 2: return freed; case 3: return writes; case 4: return record_starts; case 5: return record_stops; case 6: return previews; case 7: return preview_stops; default: return -1; }
}
void test_calibration(int mode) { calibration_mode = mode; }
void test_discovered(int count) { discovered = count; }
void test_ack(int type, int value) { if (type == 0) start_ack = value; else if (type == 1) preview_ack = value; else stop_before_ack = value; }
void test_connected(int value) { connected = value; }
+1 -1
View File
@@ -16,7 +16,7 @@ sys.path.insert(0, str(REPOSITORY / "scripts/packaging"))
from debian import package # noqa: E402
from fetch_sdk import verify # noqa: E402
VERSION = "0.1.3-9"
VERSION = "0.1.3-10"
WHEELS = {
"aiohappyeyeballs",
"aiohttp",