Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : web/src/pages/Camera.tsx9 * Module : pages10 * Repository : https://git.spboucher.ai/maclustr-vision11 * Project Website : https://camera.spboucher.ai12 * Created : 2026-11-3013 * Last Modified : 2026-11-3014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { useEffect, useMemo, useRef, useState } from 'react';43import { isTyping } from '../App';44import { api, type RangeDto } from '../api';45import { LiveTile } from '../components/LiveTile';46import { Link, useApp, usePoll } from '../ctx';47import { fmtAgo, fmtBitrate, fmtDuration, fmtTime } from '../fmt';48import { IconArrow, IconBack, IconCamera, IconExitFullscreen, IconFullscreen, IconGrid, IconHistory, IconMute, IconStats, IconVolume } from '../icons';49import { hevcSupported, mseSupported, nativeHls, type LiveInfo, type Transport } from '../live';50import { setPrefs, usePrefs } from '../prefs';5152export function CameraPage({ id }: { id: string }) {53 const { cameras, toast } = useApp();54 const prefs = usePrefs();55 const cam = cameras.find((c) => c.id === id);56 const index = cameras.findIndex((c) => c.id === id);57 const hevc = useMemo(() => hevcSupported(), []);58 const [profile, setProfile] = useState<'main' | 'sub'>(hevc && prefs.quality !== 'sub' ? 'main' : 'sub');59 const [transport, setTransport] = useState<Transport>('auto');60 const [audio, setAudio] = useState(false);61 const [fs, setFs] = useState(false);62 const [thirds, setThirds] = useState(false);63 const [img, setImg] = useState({ b: 100, c: 100, s: 100 });64 const [info, setInfo] = useState<LiveInfo | null>(null);65 const wrap = useRef<HTMLDivElement>(null);66 const video = useRef<HTMLVideoElement | null>(null);6768 useEffect(() => {69 const on = () => setFs(!!document.fullscreenElement);70 document.addEventListener('fullscreenchange', on);71 return () => document.removeEventListener('fullscreenchange', on);72 }, []);7374 const recent = usePoll(75 async () => {76 const now = Date.now();77 return api<{ ranges: RangeDto[]; gaps: RangeDto[]; segments: number; bytes: number }>(`/api/recordings/timeline?cameraId=${encodeURIComponent(id)}&from=${now - 6 * 3600000}&to=${now}`);78 },79 30000,80 [id],81 );8283 const audioAllowed = !!cam && cam.settings.liveAudio && cam.capabilities.audio;84 function toggleFs() {85 const el = wrap.current?.querySelector('.tile') as any;86 const v = video.current as any;87 if (document.fullscreenElement) return void document.exitFullscreen();88 if (el?.requestFullscreen) return void el.requestFullscreen().catch(() => setFs((x) => !x));89 if (v?.webkitEnterFullscreen) return void v.webkitEnterFullscreen(); // iPhone : plein écran natif de la vidéo90 setFs((x) => !x);91 }92 const toggleAudio = () => (audioAllowed ? setAudio((a) => !a) : toast('Son en direct désactivé pour cette caméra (Réglages)'));9394 useEffect(() => {95 const on = (e: KeyboardEvent) => {96 if (isTyping(e) || e.metaKey || e.ctrlKey || e.altKey) return;97 const k = e.key.toLowerCase();98 if (k === 'f') toggleFs();99 else if (k === 'm') toggleAudio();100 else if (k === 'i') setPrefs({ stats: !prefs.stats });101 };102 window.addEventListener('keydown', on);103 return () => window.removeEventListener('keydown', on);104 });105106 if (!cam) return <div className="card empty">{cameras.length ? 'Caméra inconnue.' : 'Chargement…'}</div>;107108 const res = cam.profiles.find((p) => p.role === profile);109 const covered = recent.data ? recent.data.ranges.reduce((a, r) => a + (r.endMs - r.startMs), 0) / 1000 : null;110 const filter = img.b !== 100 || img.c !== 100 || img.s !== 100 ? `brightness(${img.b}%) contrast(${img.c}%) saturate(${img.s}%)` : undefined;111 const slider = (label: string, k: 'b' | 'c' | 's') => (112 <label className="field">113 <span>114 {label} · <span className="mono">{img[k]} %</span>115 </span>116 <input type="range" min={40} max={200} step={5} value={img[k]} onChange={(e) => setImg((x) => ({ ...x, [k]: Number(e.target.value) }))} />117 </label>118 );119120 return (121 <>122 <div className="page-head">123 <Link to="/" className="btn icon">124 <IconBack />125 <span className="sr-only">Retour au mur de moniteurs</span>126 </Link>127 <h1>128 <span className="mono" style={{ color: 'var(--accent)', marginRight: 10, fontSize: '0.72em', letterSpacing: '0.08em' }}>129 {String(index + 1).padStart(2, '0')}130 </span>131 {cam.name}132 <span className="sub mono">{(cam.model || 'Caméra').toUpperCase()}</span>133 </h1>134 </div>135 <div className="cam-layout">136 <div className="stack" ref={wrap}>137 <LiveTile cam={cam} index={index} profile={profile} audio={audio && audioAllowed} muted={!audio} transport={transport} zoomable thirds={thirds} filter={filter} onInfo={setInfo} videoRef={(v) => (video.current = v)} onFullscreen={toggleFs} className={fs && !document.fullscreenElement ? 'fs' : ''}>138 {fs && (139 <button className="btn icon" style={{ position: 'absolute', right: 14, bottom: 44, zIndex: 6 }} onClick={toggleFs} aria-label="Quitter le plein écran">140 <IconExitFullscreen />141 </button>142 )}143 </LiveTile>144 <div className="controls">145 <div className="seg" role="group" aria-label="Qualité">146 <button aria-pressed={profile === 'main'} onClick={() => setProfile('main')} disabled={!hevc} title={hevc ? '' : 'HEVC 4K non pris en charge par ce navigateur'}>147 4K148 </button>149 <button aria-pressed={profile === 'sub'} onClick={() => setProfile('sub')}>150 720P151 </button>152 </div>153 <button className={`btn icon ${audio ? 'on' : ''}`} onClick={toggleAudio} aria-pressed={audio} aria-label={audio ? 'Couper le son' : 'Activer le son'} title="Son (M)">154 {audio ? <IconVolume /> : <IconMute />}155 </button>156 <button className={`btn icon ${prefs.stats ? 'on' : ''}`} onClick={() => setPrefs({ stats: !prefs.stats })} aria-pressed={prefs.stats} aria-label="Statistiques techniques" title="Statistiques techniques (I)">157 <IconStats />158 </button>159 <button className={`btn icon ${thirds ? 'on' : ''}`} onClick={() => setThirds((t) => !t)} aria-pressed={thirds} aria-label="Grille des tiers" title="Grille des tiers">160 <IconGrid />161 </button>162 <a className="btn icon" href={`/api/cameras/${encodeURIComponent(cam.id)}/snapshot?profile=main&download=1`} download aria-label="Instantané" title="Instantané">163 <IconCamera />164 </a>165 <button className="btn icon" onClick={toggleFs} aria-label="Plein écran" title="Plein écran (F)">166 <IconFullscreen />167 </button>168 <div className="grow" />169 <Link to={`/history?camera=${encodeURIComponent(cam.id)}`} className="btn">170 <IconHistory />171 Historique172 </Link>173 </div>174 <p className="faint" style={{ fontSize: 12.5 }}>175 Molette ou pincement pour zoomer dans l’image, glisser pour la déplacer, double-clic pour revenir.176 </p>177 {!hevc && <div className="notice">Ce navigateur ne décode pas le flux principal (HEVC 4K) : le direct utilise le profil 720p. Safari, ou Chrome avec décodage matériel, affiche la 4K.</div>}178 </div>179 <div className="stack">180 {cam.capabilities.ptz && cam.settings.ptzEnabled && <PtzPad cameraId={cam.id} />}181 <div className="card pad stack">182 <h2>État</h2>183 <dl className="kv">184 <dt>Réseau</dt>185 <dd>{cam.status.reachable ? 'Joignable' : 'Injoignable'}</dd>186 <dt>Direct</dt>187 <dd>{info ? ({ live: 'En direct', connecting: 'Connexion', stalled: 'Interrompu', offline: 'Hors ligne' } as const)[info.state] : '—'}</dd>188 <dt>Transport</dt>189 <dd className="mono">{info?.transport ? `${info.transport.toUpperCase()}${info.codec ? ' · ' + info.codec : ''}` : '—'}</dd>190 <dt>Résolution</dt>191 <dd className="mono">{res?.width ? `${res.width}×${res.height} · ${res.fps} i/s` : '—'}</dd>192 <dt>Enregistrement</dt>193 <dd>{cam.status.recConfirmed ? 'Confirmé' : cam.settings.recordEnabled ? `Non confirmé (${cam.status.recorderState})` : 'Désactivé'}</dd>194 <dt>Dernier segment</dt>195 <dd className="mono">{cam.status.lastSegmentEndMs ? `${fmtTime(cam.status.lastSegmentEndMs)} · ${fmtAgo(cam.status.lastSegmentEndMs)}` : '—'}</dd>196 <dt>Débit enregistré</dt>197 <dd className="mono">{fmtBitrate(cam.status.bitrateBps)}</dd>198 <dt>6 dernières heures</dt>199 <dd className="mono">{covered === null ? '—' : `${fmtDuration(covered)} · ${recent.data!.gaps.length} trou(s)`}</dd>200 <dt>Micrologiciel</dt>201 <dd className="mono">{cam.firmware?.split(' ')[0] || '—'}</dd>202 </dl>203 {cam.status.lastError && <div className="notice warn">{cam.status.lastError}</div>}204 </div>205 <details className="card pad">206 <summary className="cap" style={{ cursor: 'pointer', minHeight: 28 }}>207 Options avancées208 </summary>209 <div className="stack" style={{ marginTop: 14 }}>210 <h2>Image (affichage seulement)</h2>211 {slider('Luminosité', 'b')}212 {slider('Contraste', 'c')}213 {slider('Saturation', 's')}214 <button className="btn small" onClick={() => setImg({ b: 100, c: 100, s: 100 })} disabled={!filter}>215 Réinitialiser l’image216 </button>217 <p className="faint" style={{ fontSize: 12.5 }}>218 Ces réglages ne modifient que l’affichage sur cet appareil ; l’enregistrement garde l’image d’origine.219 </p>220 <h2>Transport du direct</h2>221 <div className="seg" role="group" aria-label="Transport">222 <button aria-pressed={transport === 'auto'} onClick={() => setTransport('auto')}>223 AUTO224 </button>225 <button aria-pressed={transport === 'mse'} onClick={() => setTransport('mse')} disabled={!mseSupported()}>226 MSE227 </button>228 <button aria-pressed={transport === 'hls'} onClick={() => setTransport('hls')} disabled={!nativeHls()}>229 HLS230 </button>231 </div>232 <p className="faint" style={{ fontSize: 12.5 }}>233 MSE sur WebSocket : faible latence, passe par le tunnel HTTPS. HLS : repli natif de Safari, quelques secondes de retard.234 </p>235 </div>236 </details>237 </div>238 </div>239 </>240 );241}242243function PtzPad({ cameraId }: { cameraId: string }) {244 const { toast } = useApp();245 const prefs = usePrefs();246 const timer = useRef<number | null>(null);247 const [active, setActive] = useState('');248 const send = (body: unknown) => api(`/api/cameras/${encodeURIComponent(cameraId)}/ptz`, { method: 'POST', body }).catch((e) => toast(e.message));249 const stop = (notify = true) => {250 if (timer.current) {251 clearInterval(timer.current);252 timer.current = null;253 setActive('');254 if (notify) void send({ action: 'stop' });255 }256 };257 const start = (dir: string, pan: number, tilt: number) => {258 stop(false);259 setActive(dir);260 const v = prefs.ptzSpeed;261 void send({ action: 'move', pan: pan * v, tilt: tilt * v, durationMs: 700 });262 timer.current = window.setInterval(() => void send({ action: 'move', pan: pan * v, tilt: tilt * v, durationMs: 700 }), 550);263 };264 useEffect(() => () => stop(), []);265 // flèches du clavier : maintien = déplacement266 useEffect(() => {267 const map: Record<string, [string, number, number]> = { ArrowUp: ['up', 0, 1], ArrowDown: ['down', 0, -1], ArrowLeft: ['left', -1, 0], ArrowRight: ['right', 1, 0] };268 const down = (e: KeyboardEvent) => {269 if (isTyping(e) || !e.shiftKey || e.repeat || !map[e.key]) return;270 e.preventDefault();271 start(...map[e.key]);272 };273 const up = (e: KeyboardEvent) => map[e.key] && stop();274 window.addEventListener('keydown', down);275 window.addEventListener('keyup', up);276 return () => {277 window.removeEventListener('keydown', down);278 window.removeEventListener('keyup', up);279 };280 });281 const btn = (dir: 'up' | 'down' | 'left' | 'right', pan: number, tilt: number, col: number, row: number, label: string) => (282 <button283 className={active === dir ? 'active' : ''}284 style={{ gridColumn: col, gridRow: row }}285 aria-label={label}286 onPointerDown={(e) => {287 e.currentTarget.setPointerCapture(e.pointerId);288 start(dir, pan, tilt);289 }}290 onPointerUp={() => stop()}291 onPointerCancel={() => stop()}292 onKeyDown={(e) => (e.key === ' ' || e.key === 'Enter') && !e.repeat && start(dir, pan, tilt)}293 onKeyUp={(e) => (e.key === ' ' || e.key === 'Enter') && stop()}294 onContextMenu={(e) => e.preventDefault()}295 >296 <IconArrow dir={dir} />297 </button>298 );299 return (300 <div className="card pad stack">301 <h2>Orientation (PTZ)</h2>302 <div className="row" style={{ justifyContent: 'center' }}>303 <div className="ptz">304 {btn('up', 0, 1, 2, 1, 'Monter')}305 {btn('left', -1, 0, 1, 2, 'Tourner à gauche')}306 <div className="c" aria-hidden="true" />307 {btn('right', 1, 0, 3, 2, 'Tourner à droite')}308 {btn('down', 0, -1, 2, 3, 'Descendre')}309 </div>310 </div>311 <label className="field">312 <span>313 Vitesse · <span className="mono">{Math.round(prefs.ptzSpeed * 100)} %</span>314 </span>315 <input type="range" min={0.15} max={1} step={0.05} value={prefs.ptzSpeed} onChange={(e) => setPrefs({ ptzSpeed: Number(e.target.value) })} />316 </label>317 <p className="faint" style={{ fontSize: 12.5 }}>318 Maintenir pour déplacer ; la caméra s’arrête au relâchement. Au clavier : <kbd>Maj</kbd> + flèches.319 </p>320 </div>321 );322}323