Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : server/src/live.ts9 * Module : server10 * 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 */4142// Direct : relais authentifié vers la passerelle locale (MSE sur WebSocket, HLS en repli, instantané JPEG).43// Le navigateur ne fournit jamais d'URL : seulement un identifiant de caméra du registre et un profil.44import type http from 'node:http';45import net from 'node:net';46import type { Duplex } from 'node:stream';47import type { Camera } from './cameras.ts';48import type { Config } from './config.ts';49import { streamName } from './go2rtc.ts';50import { HttpError } from './httpx.ts';5152export type LiveTarget = { cam: Camera; profile: 'main' | 'sub'; audio: boolean };5354export function parseTarget(cams: Camera[], q: URLSearchParams): LiveTarget {55 const cam = cams.find((c) => c.id === q.get('camera'));56 if (!cam) throw new HttpError(404, 'camera_not_found');57 const profile = q.get('profile') === 'main' ? 'main' : 'sub';58 const audio = q.get('audio') === '1';59 if (audio && !(cam.liveAudio && cam.capabilities.audio)) throw new HttpError(403, 'audio_disabled', 'audio en direct désactivé pour cette caméra');60 return { cam, profile, audio };61}6263const liveSockets = new Map<string, Set<Duplex>>();6465export function closeSessionSockets(sessionId: string): void {66 for (const s of liveSockets.get(sessionId) || []) s.destroy();67 liveSockets.delete(sessionId);68}69export function closeAllSockets(): void {70 for (const id of [...liveSockets.keys()]) closeSessionSockets(id);71}72export function liveViewerCount(): number {73 let n = 0;74 for (const s of liveSockets.values()) n += s.size;75 return n;76}7778/** Relais WebSocket brut vers go2rtc (127.0.0.1) après autorisation ; coupé si la session est révoquée. */79export function proxyWebSocket(cfg: Config, req: http.IncomingMessage, socket: Duplex, head: Buffer, target: LiveTarget, sessionId: string): void {80 const key = String(req.headers['sec-websocket-key'] || '');81 if (!/^[A-Za-z0-9+/=]{16,64}$/.test(key)) {82 socket.destroy();83 return;84 }85 const src = streamName(target.cam.id, target.profile, target.audio);86 const upstream = net.connect({ host: '127.0.0.1', port: cfg.go2rtc.apiPort });87 const set = liveSockets.get(sessionId) || new Set<Duplex>();88 liveSockets.set(sessionId, set);89 set.add(socket);90 const cleanup = () => {91 set.delete(socket);92 upstream.destroy();93 socket.destroy();94 };95 upstream.setTimeout(0);96 upstream.on('connect', () => {97 upstream.write(98 `GET /api/ws?src=${encodeURIComponent(src)} HTTP/1.1\r\nHost: 127.0.0.1:${cfg.go2rtc.apiPort}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${key}\r\nSec-WebSocket-Version: 13\r\n\r\n`,99 );100 if (head.length) upstream.write(head);101 upstream.pipe(socket);102 socket.pipe(upstream);103 });104 upstream.on('error', cleanup);105 upstream.on('close', cleanup);106 socket.on('error', cleanup);107 socket.on('close', cleanup);108}109110async function upstreamFetch(cfg: Config, pathAndQuery: string, timeoutMs: number): Promise<Response> {111 try {112 return await fetch(`http://127.0.0.1:${cfg.go2rtc.apiPort}${pathAndQuery}`, { signal: AbortSignal.timeout(timeoutMs), redirect: 'error' });113 } catch {114 throw new HttpError(502, 'gateway_unavailable', 'passerelle vidéo indisponible');115 }116}117118async function pipeResponse(up: Response, res: http.ServerResponse, contentType: string): Promise<void> {119 if (!up.ok || !up.body) throw new HttpError(up.status === 404 ? 404 : 502, 'stream_unavailable', 'flux indisponible');120 res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': 'no-store' });121 const reader = up.body.getReader();122 res.on('close', () => void reader.cancel().catch(() => {}));123 for (;;) {124 const { done, value } = await reader.read();125 if (done) break;126 if (!res.write(value)) await new Promise((r) => res.once('drain', r));127 }128 res.end();129}130131/** Liste de lecture HLS maîtresse d'une caméra (repli Safari / navigateurs sans MSE). */132export async function hlsMaster(cfg: Config, res: http.ServerResponse, target: LiveTarget): Promise<void> {133 const src = streamName(target.cam.id, target.profile, target.audio);134 const up = await upstreamFetch(cfg, `/api/stream.m3u8?src=${encodeURIComponent(src)}&mp4`, 15000);135 await pipeResponse(up, res, 'application/vnd.apple.mpegurl');136}137138const HLS_FILES: Record<string, string> = {139 'playlist.m3u8': 'application/vnd.apple.mpegurl',140 'init.mp4': 'video/mp4',141 'segment.m4s': 'video/iso.segment',142 'segment.ts': 'video/mp2t',143};144145/** Fichiers d'une session HLS (identifiant aléatoire et éphémère émis par la passerelle). */146export async function hlsFile(cfg: Config, res: http.ServerResponse, file: string, q: URLSearchParams): Promise<void> {147 const type = HLS_FILES[file];148 const id = q.get('id') || '';149 if (!type || !/^[A-Za-z0-9]{4,32}$/.test(id)) throw new HttpError(404, 'not_found');150 const extra = q.get('n') && /^\d{1,9}$/.test(q.get('n')!) ? `&n=${q.get('n')}` : '';151 const up = await upstreamFetch(cfg, `/api/hls/${file}?id=${id}${extra}`, 20000);152 await pipeResponse(up, res, type);153}154155const snapCache = new Map<string, { at: number; data: Buffer }>();156const snapInflight = new Map<string, Promise<Buffer>>();157158/** Instantané JPEG réel de la caméra (jamais d'image de substitution) ; mis en cache 2 s côté serveur. */159export async function snapshot(cfg: Config, target: LiveTarget): Promise<{ data: Buffer; atMs: number }> {160 const key = `${target.cam.id}:${target.profile}`;161 const c = snapCache.get(key);162 if (c && Date.now() - c.at < 2000) return { data: c.data, atMs: c.at };163 let p = snapInflight.get(key);164 if (!p) {165 p = (async () => {166 const up = await upstreamFetch(cfg, `/api/frame.jpeg?src=${encodeURIComponent(streamName(target.cam.id, target.profile, false))}`, 15000);167 if (!up.ok) throw new HttpError(503, 'snapshot_unavailable', 'image indisponible (caméra hors ligne ?)');168 const data = Buffer.from(await up.arrayBuffer());169 if (data.length < 500 || data[0] !== 0xff || data[1] !== 0xd8) throw new HttpError(503, 'snapshot_unavailable');170 snapCache.set(key, { at: Date.now(), data });171 return data;172 })().finally(() => snapInflight.delete(key));173 snapInflight.set(key, p);174 }175 const data = await p;176 return { data, atMs: snapCache.get(key)?.at || Date.now() };177}178