Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : web/src/components/LiveTile.tsx9 * Module : components10 * 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, useRef, useState, type ReactNode } from 'react';43import type { CameraDto } from '../api';44import { useNow } from '../ctx';45import { fmtAgo, fmtTime } from '../fmt';46import { IconCamera, IconFullscreen, IconPip } from '../icons';47import { LivePlayer, type LiveInfo, type LiveStats, type Transport } from '../live';48import { usePrefs } from '../prefs';49import { useZoom } from '../zoom';5051type Props = {52 cam: CameraDto;53 index: number;54 profile: 'main' | 'sub';55 audio?: boolean;56 muted?: boolean;57 transport?: Transport;58 small?: boolean;59 zoomable?: boolean;60 thirds?: boolean;61 filter?: string;62 showStats?: boolean;63 onOpen?: () => void;64 onInfo?: (i: LiveInfo) => void;65 videoRef?: (v: HTMLVideoElement | null) => void;66 onFullscreen?: () => void;67 className?: string;68 children?: ReactNode;69};7071/** Moniteur en direct. L'état affiché vient du lecteur (le temps de lecture avance) et non d'une supposition. */72export function LiveTile({ cam, index, profile, audio = false, muted = true, transport = 'auto', small, zoomable, thirds, filter, showStats, onOpen, onInfo, videoRef, onFullscreen, className, children }: Props) {73 const prefs = usePrefs();74 const ref = useRef<HTMLVideoElement>(null);75 const playerRef = useRef<LivePlayer | null>(null);76 const [info, setInfo] = useState<LiveInfo>({ state: 'connecting', transport: null, lastFrameAt: 0, codec: null, attempt: 0 });77 const [stats, setStats] = useState<LiveStats | null>(null);78 const now = useNow(1000);79 const onInfoRef = useRef(onInfo);80 onInfoRef.current = onInfo;81 const z = useZoom();82 const statsOn = showStats ?? prefs.stats;8384 useEffect(() => {85 const v = ref.current;86 if (!v) return;87 const q = `camera=${encodeURIComponent(cam.id)}&profile=${profile}${audio ? '&audio=1' : ''}`;88 const player = new LivePlayer(v, {89 wsPath: `/api/live/ws?${q}`,90 hlsPath: `/api/live/hls/stream.m3u8?${q}`,91 audio,92 transport,93 onInfo: (i) => {94 setInfo(i);95 onInfoRef.current?.(i);96 },97 });98 playerRef.current = player;99 player.start();100 return () => {101 playerRef.current = null;102 player.stop();103 };104 }, [cam.id, profile, audio, transport]);105106 useEffect(() => {107 if (ref.current) ref.current.muted = muted;108 }, [muted]);109110 useEffect(() => {111 if (!statsOn) return setStats(null);112 const t = window.setInterval(() => setStats(playerRef.current?.stats() || null), 1000);113 return () => clearInterval(t);114 }, [statsOn]);115116 const live = info.state === 'live';117 const res = cam.profiles.find((p) => p.role === profile);118 const idx = String(index + 1).padStart(2, '0');119 const pip = () => {120 const v = ref.current as any;121 if (!v) return;122 if (document.pictureInPictureElement) void document.exitPictureInPicture();123 else if (v.requestPictureInPicture) void v.requestPictureInPicture().catch(() => {});124 else if (v.webkitSetPresentationMode) v.webkitSetPresentationMode('picture-in-picture');125 };126 const canPip = typeof document !== 'undefined' && ('pictureInPictureEnabled' in document || 'webkitSetPresentationMode' in HTMLVideoElement.prototype);127128 return (129 <div className={`tile ${prefs.fit === 'cover' ? 'cover' : ''} ${small ? 'small' : ''} ${live ? 'is-live' : ''} ${className || ''}`}>130 <div className="stage" ref={zoomable ? z.stage : undefined} {...(zoomable ? z.handlers : {})}>131 <video132 ref={(v) => {133 (ref as any).current = v;134 videoRef?.(v);135 }}136 style={{ ...(zoomable ? z.style : {}), filter: filter || undefined }}137 muted138 playsInline139 autoPlay140 aria-label={`Direct — ${cam.name}`}141 />142 </div>143 {!live && (144 <div className={`veil ${info.state}`} role="status">145 {info.state === 'connecting' ? (146 <>147 <div className="spinner" />148 <span className="mono">CONNEXION AU FLUX</span>149 </>150 ) : (151 <>152 <b>{info.state === 'stalled' ? 'Flux interrompu' : 'Hors ligne'}</b>153 <span className="mono">{info.lastFrameAt ? `dernière image ${fmtAgo(info.lastFrameAt, now)} · ${fmtTime(info.lastFrameAt)}` : cam.status.reachable ? 'aucune image reçue' : 'caméra injoignable sur le réseau'}</span>154 <span className="faint mono">nouvelle tentative automatique{info.attempt > 1 ? ` · ${info.attempt}` : ''}</span>155 </>156 )}157 </div>158 )}159 {onOpen && <button className="hit" onClick={onOpen} aria-label={`Ouvrir ${cam.name}`} />}160 <div className="marks" aria-hidden="true" />161 {thirds && <div className="thirds" aria-hidden="true" />}162 <div className="top">163 {live ? <span className="badge live">Direct</span> : <span className="badge off">{info.state === 'connecting' ? 'Connexion' : 'Hors ligne'}</span>}164 {!!cam.status.lastMotionMs && now - cam.status.lastMotionMs < 15000 && <span className="badge motion">Mouvement</span>}165 {cam.status.recConfirmed && (166 <span className="badge rec" title="Dernier segment archivé il y a moins de trois minutes">167 Rec168 </span>169 )}170 </div>171 {zoomable && z.zoom > 1.01 && <span className="badge zoomtag">{z.zoom.toFixed(1).replace('.', ',')}×</span>}172 {statsOn && !small && live && stats && (173 <div className="osd" aria-hidden="true">174 {[175 `${(info.transport || '').toUpperCase()} ${info.codec || ''}`.trim(),176 `${stats.width}×${stats.height}${res?.fps ? ` @${res.fps}` : ''}`,177 stats.kbps !== null ? `${stats.kbps >= 1000 ? (stats.kbps / 1000).toFixed(2) + ' Mbit/s' : Math.round(stats.kbps) + ' kbit/s'}` : null,178 stats.liveLagS !== null ? `retard ${stats.liveLagS.toFixed(1).replace('.', ',')} s` : null,179 stats.frames !== null ? `perdues ${stats.dropped}/${stats.frames}` : null,180 ]181 .filter(Boolean)182 .join('\n')}183 </div>184 )}185 <div className="label">186 <span className="idx">{idx}</span>187 <span className="nm">{cam.name}</span>188 {live && res?.width && (189 <span className="res">190 {res.width}×{res.height}191 </span>192 )}193 </div>194 {!small && (195 <div className="quick">196 {canPip && (197 <button onClick={pip} aria-label="Image dans l’image" title="Image dans l’image">198 <IconPip />199 </button>200 )}201 <a href={`/api/cameras/${encodeURIComponent(cam.id)}/snapshot?profile=main&download=1`} download style={{ display: 'contents' }}>202 <button aria-label="Instantané" title="Instantané" tabIndex={-1}>203 <IconCamera />204 </button>205 </a>206 {onFullscreen && (207 <button onClick={onFullscreen} aria-label="Plein écran" title="Plein écran">208 <IconFullscreen />209 </button>210 )}211 </div>212 )}213 {children}214 </div>215 );216}217