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

Improve camera recovery, shared preview lifecycle and receiver playout diagnostics. Preserve qualified X4 runtime changes and restore async admission in loopback media tests.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent e06ff9a214
commit fa8bde584f
94 changed files with 8892 additions and 375 deletions
+61 -46
View File
@@ -1,63 +1,78 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {LoadingRegion,Button,Icon,IconButton,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
import {SensorDetailBack} from '../../../../packages/sensor-ui/src/SensorDetailBack';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import {LiveViewport} from '../../../../packages/sensor-ui/src/LiveViewport';
import {LiveViewportSurface} from '../../../../packages/sensor-ui/src/LiveViewport';
import {useX4Preview} from './useX4Preview';
import {CameraSettings} from './CameraSettings';
import {RecoverySettings} from './RecoverySettings';
import {cameraStatus,fileName,type CameraFiles,type CameraSettings as Settings} from './model';
import {cameraStatus,cameraLabel,cameraDetailAvailability,fileName,type CameraFiles,type CameraSettings as Settings} from './model';
export function X4Detail({device,transport,enabled,back,refresh,failure}:SensorDetailProps){
const status=cameraStatus(device);
const [settings,setSettings]=useState<Settings|null>(null);
const [files,setFiles]=useState<CameraFiles|null>(null);
const [pending,setPending]=useState<string|null>(null);const busy=pending!==null;
const [settingsLoading,setSettingsLoading]=useState(false);const running=useRef(false);const mounted=useRef(true);
const available=enabled&&device.online&&status.connected;
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
export function X4Detail({device,transport,enabled,previewEnabled=enabled,back,navigationTarget,refresh,failure}:SensorDetailProps){
const status=cameraStatus(device),sections=cameraDetailAvailability(device,enabled),available=sections.available;
const viewing=useX4Preview(device,transport,previewEnabled,enabled);
const [settings,setSettings]=useState<Settings|null>(null),[files,setFiles]=useState<CameraFiles|null>(null);
const [pending,setPending]=useState<string|null>(null);const busy=pending!==null||viewing.busy;
const [settingsLoading,setSettingsLoading]=useState(false);const running=useRef(false),mounted=useRef(true),epoch=useRef(0);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;epoch.current++;};},[]);
const load=useCallback(async()=>{
if(status.function_mode===null)return;
if(mounted.current)setSettingsLoading(true);
try{const value=await perform<Settings>(transport,device,'settings.read',{mode:status.function_mode});if(mounted.current)setSettings(value);}
finally{if(mounted.current)setSettingsLoading(false);}
},[transport,device.id,device.snapshot.context.session_id,status.function_mode]);
useEffect(()=>{if(available)void load().catch(error=>{if(mounted.current)failure(error);});},[available,load]);
async function action(name:string,parameters:Record<string,unknown>={},key=name){
if(running.current||!enabled||(!available&&!['refresh','recovery.configure','preview.stop'].includes(name)))return;
running.current=true;setPending(key);failure(null);
const request=++epoch.current;
if(!available){setSettings(null);setFiles(null);setSettingsLoading(false);return;}
setSettingsLoading(true);
const current=()=>mounted.current&&request===epoch.current;
try{
const result=name==='refresh'?(available?await load():undefined):await perform<unknown>(transport,device,name,parameters);
if(status.function_mode!==null){const value=await perform<Settings>(transport,device,'settings.read',{mode:status.function_mode});if(!current())return;setSettings(value);}
const value=await perform<CameraFiles>(transport,device,'files.list',{offset:0});if(current())setFiles(value);
}finally{if(current())setSettingsLoading(false);}
},[transport,device.id,device.snapshot.context.session_id,status.function_mode,available]);
useEffect(()=>{void load().catch(error=>{if(mounted.current)failure(error);});return()=>{epoch.current++;};},[load]);
async function action(name:string,parameters:Record<string,unknown>={},key=name){
if(running.current||!enabled||(!available&&!['recovery.configure','power.wake'].includes(name)))return;
if(name==='power.wake'&&!sections.wake)return;
running.current=true;setPending(key);failure(null);const request=epoch.current;
try{
const result=name==='refresh'?await load():await perform<unknown>(transport,device,name,parameters);
if(!mounted.current)return;
if(name==='settings.apply')setSettings(result as Settings);
if(name==='files.list')setFiles(result as CameraFiles);
if(name==='photo.capture'||name==='record.stop')setFiles(null);
if(request===epoch.current){
if(name==='settings.apply')setSettings(result as Settings);
if(name==='files.list')setFiles(result as CameraFiles);
if(name==='photo.capture'||name==='record.stop')await load();
}
await refresh();
}catch(error){if(mounted.current)failure(error);}
finally{running.current=false;if(mounted.current)setPending(null);}
}
const mode=settings?.mode??status.function_mode;
const recordLabel=status.recording===1?'Идёт запись на карту':status.recording===0?'Запись остановлена':'Состояние записи не подтверждено';
const viewDevice=available?device:{...device,snapshot:{...device.snapshot,acquisition:'idle'}};
return <div className="sensor-content"><div><Button onClick={back}>К устройствам</Button></div>
<SettingsCard title={device.name} description={`${device.model}${device.firmware?' · '+device.firmware:''}`} actions={<IconButton label="Обновить состояние камеры" loading={pending==='refresh'} disabled={!enabled||busy} onClick={()=>void action('refresh')}><Icon name="refresh"/></IconButton>}>
<dl className="sensor-facts"><div><dt>Серийный номер</dt><dd>{status.serial||'Не получен'}</dd></div></dl>
{!available&&<p>Нет свежей связи с камерой.</p>}
<div className="sensor-actions"><Button disabled={!available||busy||status.preview!==0} loading={pending==='preview.start'} onClick={()=>void action('preview.start')}>Начать просмотр</Button><Button disabled={!enabled||busy||(!available&&!status.recovery?.preview_wanted)||(available&&status.preview===0&&!status.recovery?.preview_wanted)} loading={pending==='preview.stop'} onClick={()=>void action('preview.stop')}>Остановить просмотр</Button><Button disabled={!available||busy||status.recording!==0} loading={pending==='verify'} onClick={()=>void action('verify')}>Проверить изображение</Button></div>
{status.alerts?.temperature_high&&<p>Камера сообщает о перегреве.</p>}
{status.alerts?.storage_full&&<p>На карте камеры закончилось место.</p>}
{status.alerts?.battery_low&&<p>Камера сообщает о низком заряде.</p>}
</SettingsCard>
{status.recovery?.supported&&<RecoverySettings value={status.recovery} online={available} enabled={enabled&&!busy} pending={pending==='recovery.configure'} change={value=>void action('recovery.configure',{enabled:value,wakeup_confirmed:value})}/>}
<LiveViewport device={viewDevice} layer="preview" title="Изображение X4" note="Запись сохраняется на карте памяти камеры." inactiveMessage="Нажмите «Начать просмотр», чтобы получить изображение." transport={transport} failure={failure}/>
<SettingsCard title="Съёмка" description="Фото и видеозапись сохраняются на карте памяти X4." actions={<StatusBadge tone={available&&status.recording===1?'success':status.recording===0?'neutral':'warning'}>{available?recordLabel:'Состояние недоступно'}</StatusBadge>}>
<div className="sensor-actions"><Button disabled={!available||busy||status.recording!==0||mode!==7} loading={pending==='record.start'} onClick={()=>void action('record.start')}>Начать запись</Button><Button disabled={!available||busy||status.recording===0} loading={pending==='record.stop'} onClick={()=>void action('record.stop')}>Остановить запись</Button><Button disabled={!available||busy||status.recording!==0||mode!==6} loading={pending==='photo.capture'} onClick={()=>void action('photo.capture')}>Сделать фото</Button></div>
{available&&status.recording===1&&<p>Запись продолжится после закрытия просмотра.</p>}
</SettingsCard>
<LoadingRegion loading={available&&((settingsLoading&&!settings)||pending==='settings.apply')} label={pending==='settings.apply'?'Применение настройки':'Получение настроек камеры'}>
{settings?<CameraSettings value={settings} disabled={!available||busy||status.recording!==0||status.preview!==0} apply={(key,value)=>void action('settings.apply',{mode:settings.mode,key,value})}/>:available&&!settingsLoading?<p>Настройки недоступны. Обновите состояние камеры.</p>:null}
</LoadingRegion>
<SettingsCard title="Файлы на камере" actions={<Button disabled={!available||busy} loading={pending==='files.refresh'} onClick={()=>void action('files.list',{offset:0},'files.refresh')}>Обновить список</Button>}>
{files?files.items.length?<><ResourceList aria-label="Файлы на карте X4">{files.items.map((item,index)=><li key={`${files.offset+index}:${item}`}><ResourceRow title={fileName(item)} icon={<Icon name="file"/>}/></li>)}</ResourceList><div className="sensor-actions"><Button disabled={!available||busy||files.offset===0} loading={pending==='files.previous'} onClick={()=>void action('files.list',{offset:Math.max(0,files.offset-32)},'files.previous')}>Назад</Button><span>{files.offset+1}–{files.offset+files.items.length} из {files.total}</span><Button disabled={!available||busy||files.offset+files.items.length>=files.total} loading={pending==='files.next'} onClick={()=>void action('files.list',{offset:files.offset+files.items.length},'files.next')}>Далее</Button></div></>:<p>Файлов нет.</p>:<p>Обновите список, чтобы увидеть записи на карте камеры.</p>}
</SettingsCard>
const label=available?cameraLabel(device,true):{label:'Недоступна',tone:'neutral' as const};
const recordLabel=status.recording===1?'Идёт запись на карту':'Запись остановлена';
const viewDevice=viewing.available?device:{...device,snapshot:{...device.snapshot,acquisition:'idle'}};
const showImage=available&&(viewing.pending||viewing.preview.live||(status.preview===1&&!viewing.error));
const recovery=sections.recovery&&status.recovery?<RecoverySettings value={status.recovery} online={available} enabled={enabled&&!busy} pending={pending==='recovery.configure'} change={value=>void action('recovery.configure',{enabled:value,wakeup_confirmed:value})} wake={sections.wake?()=>void action('power.wake'):undefined} waking={pending==='power.wake'}/>:null;
return <div className="sensor-content">
<SensorDetailBack back={back} target={navigationTarget}/>
<ResourceRow title={device.name} description={label.label} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={label.tone} aria-label={label.label} title={label.label}/>} actions={available?<>
{status.preview===0||viewing.error?<Button disabled={busy} loading={viewing.pending} onClick={()=>void viewing.retry()}>{viewing.error?'Повторить просмотр':'Начать просмотр'}</Button>:status.preview===1?<Button disabled={busy} loading={pending==='preview.stop'} onClick={()=>void action('preview.stop')}>Остановить просмотр</Button>:null}
<IconButton label="Обновить состояние камеры" loading={pending==='refresh'} disabled={busy||settingsLoading} onClick={()=>void action('refresh')}><Icon name="refresh"/></IconButton>
</>:recovery}/>
{available&&(status.alerts?.temperature_high||status.alerts?.storage_full||status.alerts?.battery_low)&&<SettingsCard title="Состояние камеры">
{status.alerts.temperature_high&&<p>Камера сообщает о перегреве.</p>}
{status.alerts.storage_full&&<p>На карте камеры закончилось место.</p>}
{status.alerts.battery_low&&<p>Камера сообщает о низком заряде.</p>}
</SettingsCard>}
{available&&recovery}
{/* Keep the decoder attached while unavailable/empty content stays outside the visible layout. */}
<div hidden={!showImage}><LiveViewportSurface video={viewing.video} preview={viewing.preview} pending={viewing.pending} error={viewing.error} device={viewDevice} layer="preview" title="Изображение X4" note="Запись сохраняется на карте памяти камеры." inactiveMessage="Нет свежих данных"/></div>
{sections.capture&&<SettingsCard title="Съёмка" description="Фото и видеозапись сохраняются на карте памяти X4." actions={<StatusBadge tone={status.recording===1?'success':'neutral'}>{recordLabel}</StatusBadge>}>
<div className="sensor-actions">{status.recording===1?<Button disabled={busy} loading={pending==='record.stop'} onClick={()=>void action('record.stop')}>Остановить запись</Button>:mode===7?<Button disabled={busy} loading={pending==='record.start'} onClick={()=>void action('record.start')}>Начать запись</Button>:mode===6?<Button disabled={busy} loading={pending==='photo.capture'} onClick={()=>void action('photo.capture')}>Сделать фото</Button>:null}</div>
{status.recording===1&&<p>Запись продолжится после закрытия просмотра.</p>}
</SettingsCard>}
{available&&(settings||settingsLoading)&&<LoadingRegion loading={(settingsLoading&&!settings)||pending==='settings.apply'} label={pending==='settings.apply'?'Применение настройки':'Получение настроек камеры'}>
{settings&&<CameraSettings value={settings} disabled={busy||status.recording!==0||status.preview!==0} apply={(key,value)=>void action('settings.apply',{mode:settings.mode,key,value})}/>}
</LoadingRegion>}
{available&&!!files?.items.length&&<SettingsCard title="Файлы на камере" actions={<Button disabled={busy} loading={pending==='files.refresh'} onClick={()=>void action('files.list',{offset:0},'files.refresh')}>Обновить список</Button>}>
<ResourceList aria-label="Файлы на карте X4">{files.items.map((item,index)=><li key={`${files.offset+index}:${item}`}><ResourceRow title={fileName(item)} icon={<Icon name="file"/>}/></li>)}</ResourceList>
{files.total>files.items.length&&<div className="sensor-actions"><Button disabled={busy||files.offset===0} loading={pending==='files.previous'} onClick={()=>void action('files.list',{offset:Math.max(0,files.offset-32)},'files.previous')}>Назад</Button><span>{files.offset+1}–{files.offset+files.items.length} из {files.total}</span><Button disabled={busy||files.offset+files.items.length>=files.total} loading={pending==='files.next'} onClick={()=>void action('files.list',{offset:files.offset+files.items.length},'files.next')}>Далее</Button></div>}
</SettingsCard>}
</div>;
}