Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : server/src/recorder.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// Enregistreur NVR : un FFmpeg par caméra, copie du flux principal sans réencodage, segments ~60 s.43// Cycle d'un segment : spool/<cam>/<horodatage>.mkv.partial → vérification ffprobe + SHA-25644// → publication atomique dans l'archive → ligne de catalogue. Le tampon n'est libéré qu'après confirmation.45import { spawn, type ChildProcess } from 'node:child_process';46import fs from 'node:fs';47import path from 'node:path';48import type { Camera } from './cameras.ts';49import type { Config } from './config.ts';50import { addEvent, type DB } from './db.ts';51import { streamName } from './go2rtc.ts';52import { logger, redact } from './log.ts';53import { probe, remux, sha256File } from './media.ts';54import { parseStamp, relPathFor, verifyVolume } from './storage.ts';5556const GAP_TOLERANCE_MS = 2500;5758export type RecorderState = 'stopped' | 'starting' | 'recording' | 'backoff' | 'suspended';5960export class CameraRecorder {61 private child: ChildProcess | null = null;62 private wanted = false;63 private state: RecorderState = 'stopped';64 private restarts = 0;65 private consecutiveFailures = 0;66 private retryTimer: NodeJS.Timeout | null = null;67 private lastGrowthAt = 0;68 private lastSize = -1;69 private lastSegmentAt = 0;70 private alertedNoSegment = false;71 private processing = new Set<string>();72 private queue: Promise<void> = Promise.resolve();73 private stopReason: string | null = null;74 private withAudio = false;75 private log;76 private cfg: Config;77 private db: DB;78 public cam: Camera;7980 constructor(cfg: Config, db: DB, cam: Camera) {81 this.cfg = cfg;82 this.db = db;83 this.cam = cam;84 this.log = logger(`rec:${cam.id}`);85 fs.mkdirSync(this.spool, { recursive: true, mode: 0o700 });86 }8788 get spool(): string {89 return path.join(this.cfg.spoolDir, this.cam.id);90 }91 get currentState(): RecorderState {92 return this.state;93 }94 get audio(): boolean {95 return this.withAudio;96 }9798 private setState(state: RecorderState, error?: string | null): void {99 this.state = state;100 this.db101 .prepare('UPDATE camera_state SET recorder_state = ?, recorder_since_ms = ?, recorder_restarts = ?, last_error = COALESCE(?, last_error), updated_ms = ? WHERE camera_id = ?')102 .run(state, Date.now(), this.restarts, error ?? null, Date.now(), this.cam.id);103 }104105 /** Démarre (ou maintient) l'enregistrement. */106 start(): void {107 this.wanted = true;108 if (this.child || this.retryTimer) return;109 this.spawnFfmpeg();110 }111112 private spawnFfmpeg(): void {113 this.retryTimer = null;114 if (!this.wanted) return;115 this.withAudio = this.cam.recordAudio;116 const src = `rtsp://127.0.0.1:${this.cfg.go2rtc.rtspPort}/${streamName(this.cam.id, 'main', true)}?video${this.withAudio ? '&audio' : ''}`;117 const args = ['-hide_banner', '-loglevel', 'warning', '-nostdin', '-rtsp_transport', 'tcp', '-timeout', '15000000', '-i', src, '-map', '0:v:0'];118 if (this.withAudio) args.push('-map', '0:a:0?');119 args.push(120 '-c', 'copy',121 '-f', 'segment',122 '-segment_time', String(this.cfg.recording.segmentSeconds),123 '-segment_atclocktime', '1',124 '-reset_timestamps', '1',125 '-strftime', '1',126 '-segment_format', 'matroska',127 '-segment_list', 'pipe:1',128 '-segment_list_type', 'flat',129 path.join(this.spool, '%Y%m%dT%H%M%SZ.mkv.partial'),130 );131 this.setState('starting');132 const child = spawn(this.cfg.ffmpegBin, args, { stdio: ['ignore', 'pipe', 'pipe'], env: { TZ: 'UTC', PATH: '/usr/bin:/bin' } });133 this.child = child;134 this.lastGrowthAt = Date.now();135 this.lastSize = -1;136 const startedAt = Date.now();137 let errTail = '';138 child.stdout?.on('data', () => this.scanSpool());139 child.stderr?.on('data', (d: Buffer) => {140 errTail = (errTail + d.toString()).slice(-600);141 });142 child.on('exit', (code, signal) => {143 this.child = null;144 this.scanSpool(true);145 const ran = Date.now() - startedAt;146 if (!this.wanted) {147 this.setState('stopped');148 return;149 }150 this.restarts++;151 this.consecutiveFailures = ran > 120000 ? 0 : this.consecutiveFailures + 1;152 const base = Math.min(60000, 1000 * 2 ** Math.min(this.consecutiveFailures, 6));153 const delay = Math.round(base * (0.7 + Math.random() * 0.6));154 const reason = this.stopReason || redact(errTail.trim().split('\n').pop() || `code ${code} signal ${signal}`).slice(0, 200);155 this.stopReason = null;156 this.log.warn('ffmpeg arrêté, relance', { code, signal, delayMs: delay, reason });157 this.setState('backoff', reason);158 this.retryTimer = setTimeout(() => this.spawnFfmpeg(), delay);159 });160 this.log.info('enregistrement lancé', { pid: child.pid, audio: this.withAudio });161 }162163 /** Arrêt propre : FFmpeg finalise le segment courant sur SIGTERM. */164 async stop(reason = 'arrêt demandé'): Promise<void> {165 this.wanted = false;166 if (this.retryTimer) {167 clearTimeout(this.retryTimer);168 this.retryTimer = null;169 }170 const child = this.child;171 if (child) {172 this.stopReason = reason;173 await new Promise<void>((resolve) => {174 const t = setTimeout(() => child.kill('SIGKILL'), 6000);175 child.once('exit', () => {176 clearTimeout(t);177 resolve();178 });179 child.kill('SIGTERM');180 });181 }182 this.scanSpool(true);183 await this.queue;184 this.setState('stopped');185 }186187 async restart(reason: string): Promise<void> {188 await this.stop(reason);189 this.start();190 }191192 /** Surveillance : pas de croissance du fichier courant → relance ; pas de segment valide → alerte. */193 tick(): void {194 this.scanSpool();195 if (!this.child) return;196 const now = Date.now();197 const cur = this.currentPartial();198 const size = cur ? safeSize(path.join(this.spool, cur)) : -1;199 if (size !== this.lastSize) {200 this.lastSize = size;201 this.lastGrowthAt = now;202 if (this.state === 'starting' && size > 0) this.setState('recording');203 } else if (now - this.lastGrowthAt > this.cfg.recording.stallSeconds * 1000) {204 this.log.warn('flux figé, relance du worker');205 this.stopReason = 'flux figé (aucune donnée reçue)';206 this.lastGrowthAt = now;207 this.child.kill('SIGKILL');208 }209 const ref = Math.max(this.lastSegmentAt, 0);210 if (this.wanted && ref > 0 && now - ref > this.cfg.recording.noSegmentAlertSeconds * 1000) {211 if (!this.alertedNoSegment) {212 this.alertedNoSegment = true;213 addEvent(this.db, { cameraId: this.cam.id, type: 'recording_stalled', severity: 'critical', message: `Aucun segment valide depuis ${Math.round((now - ref) / 1000)} s` });214 }215 }216 }217218 markStartReference(): void {219 if (!this.lastSegmentAt) this.lastSegmentAt = Date.now();220 }221222 private currentPartial(): string | null {223 const files = listPartials(this.spool);224 return files.length ? files[files.length - 1] : null;225 }226227 /** Détecte les segments fermés (tous les .partial sauf le plus récent tant que FFmpeg tourne). */228 scanSpool(all = false): void {229 const files = listPartials(this.spool);230 const closed = all || !this.child ? files : files.slice(0, -1);231 for (const f of closed) {232 if (this.processing.has(f)) continue;233 this.processing.add(f);234 this.queue = this.queue235 .then(() => this.finalize(f))236 .catch((e) => this.log.error('finalisation échouée', { file: f, err: String(e?.message || e) }))237 .finally(() => this.processing.delete(f));238 }239 // segments déjà vérifiés mais pas encore archivés (archive indisponible)240 for (const f of listReady(this.spool)) {241 if (this.processing.has(f)) continue;242 this.processing.add(f);243 this.queue = this.queue244 .then(() => this.archive(f))245 .catch((e) => this.log.error('archivage échoué', { file: f, err: String(e?.message || e) }))246 .finally(() => this.processing.delete(f));247 }248 }249250 /** Vérifie un segment fermé puis le publie atomiquement dans le tampon sous son nom définitif. */251 private async finalize(partialName: string): Promise<void> {252 const partial = path.join(this.spool, partialName);253 if (!fs.existsSync(partial)) return;254 const startMs = parseStamp(partialName);255 if (startMs === null) return this.quarantine(partial, 'nom inattendu');256 let p = await probe(this.cfg, partial);257 let recovered = false;258 if (!p || p.durationMs < 500) {259 // segment interrompu (coupure, arrêt brutal) : tentative de réparation par remux260 const fixed = partial + '.fix';261 const ok = await remux(this.cfg, partial, fixed, 'matroska');262 const p2 = ok ? await probe(this.cfg, fixed) : null;263 if (p2 && p2.durationMs >= 500) {264 fs.renameSync(fixed, partial);265 p = p2;266 recovered = true;267 } else {268 try {269 fs.unlinkSync(fixed);270 } catch {271 /* rien */272 }273 return this.quarantine(partial, 'illisible');274 }275 }276 const ready = partial.replace(/\.partial$/, '');277 fs.renameSync(partial, ready);278 if (recovered) fs.writeFileSync(ready + '.recovered', '');279 await this.archive(path.basename(ready));280 }281282 /** Copie vers l'archive (vérifiée), inscrit au catalogue, puis libère le tampon. */283 private async archive(readyName: string): Promise<void> {284 const ready = path.join(this.spool, readyName);285 if (!fs.existsSync(ready)) return;286 const startMs = parseStamp(readyName);287 if (startMs === null) return;288 const vol = verifyVolume(this.cfg);289 if (!vol.ok) return; // on garde le segment dans le tampon ; la supervision alerte290 const p = await probe(this.cfg, ready);291 if (!p) return this.quarantine(ready, 'illisible à l’archivage');292 const sha = await sha256File(ready);293 const rel = relPathFor(this.cam.id, startMs);294 const dest = path.join(this.cfg.archiveDir, rel);295 fs.mkdirSync(path.dirname(dest), { recursive: true, mode: 0o700 });296 const recovered = fs.existsSync(ready + '.recovered');297 const existing = this.db.prepare('SELECT id FROM segments WHERE rel_path = ?').get(rel);298 if (!existing) {299 try {300 fs.renameSync(ready, dest);301 } catch (e: any) {302 if (e?.code !== 'EXDEV') throw e;303 // archive sur un autre volume : copie, vérification d'intégrité, puis publication atomique304 const tmp = dest + '.incoming';305 fs.copyFileSync(ready, tmp);306 const fd = fs.openSync(tmp, 'r');307 fs.fsyncSync(fd);308 fs.closeSync(fd);309 if ((await sha256File(tmp)) !== sha || fs.statSync(tmp).size !== fs.statSync(ready).size) {310 fs.unlinkSync(tmp);311 throw new Error('copie d’archive non conforme');312 }313 fs.renameSync(tmp, dest);314 fs.unlinkSync(ready);315 }316 const endMs = startMs + p.durationMs;317 const prev = this.db.prepare('SELECT end_ms FROM segments WHERE camera_id = ? AND start_ms < ? ORDER BY start_ms DESC LIMIT 1').get(this.cam.id, startMs) as { end_ms: number } | undefined;318 const discontinuity = prev ? (startMs - prev.end_ms > GAP_TOLERANCE_MS ? 1 : 0) : 0;319 this.db320 .prepare(321 'INSERT INTO segments (camera_id, start_ms, end_ms, duration_ms, codec, width, height, has_audio, size_bytes, rel_path, state, sha256, discontinuity, created_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(rel_path) DO NOTHING',322 )323 .run(this.cam.id, startMs, endMs, p.durationMs, p.codec, p.width, p.height, p.hasAudio ? 1 : 0, p.sizeBytes, rel, recovered ? 'recovered' : 'archived', sha, discontinuity, Date.now());324 const bitrate = p.durationMs > 0 ? Math.round((p.sizeBytes * 8000) / p.durationMs) : 0;325 this.db.prepare('UPDATE camera_state SET last_segment_end_ms = MAX(COALESCE(last_segment_end_ms, 0), ?), last_bitrate_bps = ?, updated_ms = ? WHERE camera_id = ?').run(endMs, bitrate, Date.now(), this.cam.id);326 if (prev && discontinuity && startMs - prev.end_ms > 5000) {327 addEvent(this.db, {328 cameraId: this.cam.id,329 type: 'recording_gap',330 severity: 'warning',331 tsMs: prev.end_ms,332 message: `Trou d’enregistrement de ${Math.round((startMs - prev.end_ms) / 1000)} s`,333 data: { fromMs: prev.end_ms, toMs: startMs },334 });335 }336 if (endMs > this.lastSegmentAt) this.lastSegmentAt = Math.max(endMs, Date.now() - 1000);337 if (this.alertedNoSegment) {338 this.alertedNoSegment = false;339 addEvent(this.db, { cameraId: this.cam.id, type: 'recording_resumed', severity: 'info', message: 'Enregistrement rétabli' });340 }341 } else {342 // déjà catalogué (reprise après coupure) : pas de doublon343 try {344 fs.unlinkSync(ready);345 } catch {346 /* rien */347 }348 }349 try {350 fs.unlinkSync(ready + '.recovered');351 } catch {352 /* rien */353 }354 }355356 private quarantine(file: string, why: string): void {357 const dir = path.join(this.cfg.quarantineDir, this.cam.id);358 fs.mkdirSync(dir, { recursive: true, mode: 0o700 });359 const dest = path.join(dir, path.basename(file).replace(/\.partial$/, ''));360 try {361 if (safeSize(file) <= 0) fs.unlinkSync(file);362 else fs.renameSync(file, dest);363 } catch {364 /* rien */365 }366 this.log.warn('segment isolé', { file: path.basename(file), why });367 addEvent(this.db, { cameraId: this.cam.id, type: 'segment_quarantined', severity: 'warning', message: `Segment ${why} isolé : ${path.basename(dest)}` });368 }369370 spoolBytes(): number {371 let t = 0;372 try {373 for (const f of fs.readdirSync(this.spool)) t += safeSize(path.join(this.spool, f));374 } catch {375 /* rien */376 }377 return t;378 }379380 pendingReady(): number {381 return listReady(this.spool).length;382 }383}384385function safeSize(file: string): number {386 try {387 return fs.statSync(file).size;388 } catch {389 return -1;390 }391}392function listPartials(dir: string): string[] {393 try {394 return fs.readdirSync(dir).filter((f) => /^\d{8}T\d{6}Z\.mkv\.partial$/.test(f)).sort();395 } catch {396 return [];397 }398}399function listReady(dir: string): string[] {400 try {401 return fs.readdirSync(dir).filter((f) => /^\d{8}T\d{6}Z\.mkv$/.test(f)).sort();402 } catch {403 return [];404 }405}406