SPB Git

Repository Public

playback.ts 12.9 KB 279 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Vision8 * File             : server/src/playback.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// Lecture de l'historique (remux MP4 à la demande, mis en cache) et exports MP4 d'une période.43import { spawn } from 'node:child_process';44import crypto from 'node:crypto';45import fs from 'node:fs';46import path from 'node:path';47import type { Config } from './config.ts';48import { addEvent, type DB } from './db.ts';49import { HttpError } from './httpx.ts';50import { logger } from './log.ts';51import { remux, run } from './media.ts';52import { resolveArchivePath } from './storage.ts';5354const log = logger('playback');55const inflight = new Map<number, Promise<string>>();5657/** Retourne le chemin d'un MP4 lisible par les navigateurs pour un segment du catalogue. */58export async function playbackFile(cfg: Config, db: DB, id: number, compat = false): Promise<string> {59  const row = db.prepare("SELECT id, rel_path, state FROM segments WHERE id = ?").get(id) as { id: number; rel_path: string; state: string } | undefined;60  if (!row || row.state === 'missing') throw new HttpError(404, 'segment_not_found');61  const src = resolveArchivePath(cfg, row.rel_path);62  if (!fs.existsSync(src)) throw new HttpError(404, 'segment_file_missing');63  const out = path.join(cfg.cacheDir, `${row.id}${compat ? '.h264' : ''}.mp4`);64  if (fs.existsSync(out)) {65    const now = new Date();66    try {67      fs.utimesSync(out, now, fs.statSync(out).mtime);68    } catch {69      /* rien */70    }71    return out;72  }73  const key = compat ? -id : id;74  let p = inflight.get(key);75  if (!p) {76    p = (async () => {77      const tmp = `${out}.${process.pid}.tmp`;78      const ok = compat ? await transcodeCompat(cfg, src, tmp) : await remux(cfg, src, tmp, 'mp4');79      if (!ok) {80        try {81          fs.unlinkSync(tmp);82        } catch {83          /* rien */84        }85        throw new HttpError(500, 'remux_failed', 'segment illisible');86      }87      fs.renameSync(tmp, out);88      return out;89    })().finally(() => inflight.delete(key));90    inflight.set(key, p);91  }92  return p;93}9495/**96 * Lecture de compatibilité : H.264 720p pour les navigateurs sans décodeur HEVC.97 * Encodage matériel VideoToolbox (Apple Silicon), repli logiciel libx264. L'archive reste intacte.98 */99let compatQueue: Promise<unknown> = Promise.resolve();100async function transcodeCompat(cfg: Config, input: string, output: string): Promise<boolean> {101  const job = async () => {102    const base = ['-hide_banner', '-v', 'error', '-nostdin', '-y', '-i', input, '-map', '0:v:0', '-map', '0:a?', '-vf', 'scale=1280:-2', '-c:a', 'aac', '-b:a', '64k', '-movflags', '+faststart', '-f', 'mp4'];103    const at = base.indexOf('-c:a');104    const withCodec = (codec: string[]) => [...base.slice(0, at), ...codec, ...base.slice(at), output];105    let r = await run(cfg.ffmpegBin, withCodec(['-c:v', 'h264_videotoolbox', '-b:v', '2500k', '-pix_fmt', 'yuv420p']), { timeoutMs: 180000 });106    if (r.code !== 0) r = await run(cfg.ffmpegBin, withCodec(['-c:v', 'libx264', '-preset', 'veryfast', '-crf', '24', '-pix_fmt', 'yuv420p']), { timeoutMs: 300000 });107    return r.code === 0;108  };109  // une conversion à la fois : ne jamais concurrencer l'enregistrement110  const p = compatQueue.then(job, job);111  compatQueue = p.catch(() => {});112  return p;113}114115export type ExportRow = { id: string; camera_id: string; from_ms: number; to_ms: number; state: string; progress: number; size_bytes: number | null; file_name: string | null; error: string | null; created_ms: number; finished_ms: number | null; expires_ms: number | null };116117export class Exporter {118  private queue: string[] = [];119  private running = false;120  private cfg: Config;121  private db: DB;122  constructor(cfg: Config, db: DB) {123    this.cfg = cfg;124    this.db = db;125    // exports interrompus par un redémarrage : marqués en échec, jamais présentés comme terminés126    db.prepare("UPDATE exports SET state = 'failed', error = 'interrompu par un redémarrage', finished_ms = ? WHERE state IN ('queued','running')").run(Date.now());127  }128129  create(cameraId: string, fromMs: number, toMs: number, timezone: string): string {130    const pending = this.db.prepare("SELECT COUNT(*) AS n FROM exports WHERE state IN ('queued','running')").get() as { n: number };131    if (pending.n >= 4) throw new HttpError(429, 'too_many_exports', 'trop d’exports en cours');132    const n = this.db.prepare("SELECT COUNT(*) AS n FROM segments WHERE camera_id = ? AND end_ms > ? AND start_ms < ? AND state IN ('archived','recovered')").get(cameraId, fromMs, toMs) as { n: number };133    if (!n.n) throw new HttpError(404, 'no_recordings', 'aucun enregistrement sur cette période');134    const id = crypto.randomBytes(12).toString('hex');135    const f = new Intl.DateTimeFormat('sv-SE', { timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });136    const stamp = f.format(new Date(fromMs)).replace(/[: ]/g, '-').replace(/-(\d\d)-(\d\d)-(\d\d)$/, '_$1h$2m$3');137    const fileName = `vision_${cameraId}_${stamp}.mp4`;138    this.db.prepare('INSERT INTO exports (id, camera_id, from_ms, to_ms, state, file_name, created_ms) VALUES (?, ?, ?, ?, ?, ?, ?)').run(id, cameraId, fromMs, toMs, 'queued', fileName, Date.now());139    this.queue.push(id);140    void this.pump();141    return id;142  }143144  filePath(id: string): string {145    if (!/^[a-f0-9]{24}$/.test(id)) throw new HttpError(404, 'not_found');146    return path.join(this.cfg.exportsDir, `${id}.mp4`);147  }148149  remove(id: string): boolean {150    const file = this.filePath(id);151    const r = this.db.prepare("DELETE FROM exports WHERE id = ? AND state NOT IN ('running')").run(id);152    if (r.changes) {153      try {154        fs.unlinkSync(file);155      } catch {156        /* rien */157      }158    }159    return r.changes > 0;160  }161162  private async pump(): Promise<void> {163    if (this.running) return;164    this.running = true;165    try {166      for (;;) {167        const id = this.queue.shift();168        if (!id) break;169        await this.runOne(id).catch((e) => {170          log.error('export échoué', { id, err: String(e?.message || e) });171          this.db.prepare("UPDATE exports SET state = 'failed', error = ?, finished_ms = ? WHERE id = ?").run(String(e?.message || e).slice(0, 300), Date.now(), id);172        });173      }174    } finally {175      this.running = false;176    }177  }178179  private async runOne(id: string): Promise<void> {180    const ex = this.db.prepare('SELECT * FROM exports WHERE id = ?').get(id) as ExportRow | undefined;181    if (!ex) return;182    const segs = this.db183      .prepare("SELECT start_ms, end_ms, rel_path, codec FROM segments WHERE camera_id = ? AND end_ms > ? AND start_ms < ? AND state IN ('archived','recovered') ORDER BY start_ms")184      .all(ex.camera_id, ex.from_ms, ex.to_ms) as { start_ms: number; end_ms: number; rel_path: string; codec: string | null }[];185    const files = segs.map((s) => ({ ...s, abs: resolveArchivePath(this.cfg, s.rel_path) })).filter((s) => fs.existsSync(s.abs));186    if (!files.length) throw new Error('aucun fichier lisible sur cette période');187    this.db.prepare("UPDATE exports SET state = 'running', progress = 0 WHERE id = ?").run(id);188    const listFile = path.join(this.cfg.exportsDir, `${id}.txt`);189    fs.writeFileSync(listFile, files.map((f) => `file '${f.abs.replace(/'/g, "'\\''")}'`).join('\n') + '\n', { mode: 0o600 });190    const out = this.filePath(id);191    const tmp = out + '.tmp';192    const offsetS = Math.max(0, (ex.from_ms - files[0].start_ms) / 1000);193    const durS = Math.max(1, (Math.min(ex.to_ms, files[files.length - 1].end_ms) - Math.max(ex.from_ms, files[0].start_ms)) / 1000);194    const args = ['-hide_banner', '-v', 'error', '-nostdin', '-y', '-f', 'concat', '-safe', '0', '-ss', offsetS.toFixed(3), '-i', listFile, '-t', durS.toFixed(3), '-map', '0:v:0', '-map', '0:a?', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '64k'];195    if (files[0].codec === 'hevc') args.push('-tag:v', 'hvc1');196    args.push('-avoid_negative_ts', 'make_zero', '-movflags', '+faststart', '-progress', 'pipe:1', '-f', 'mp4', tmp);197    const code = await new Promise<number | null>((resolve) => {198      const child = spawn(this.cfg.ffmpegBin, args, { stdio: ['ignore', 'pipe', 'pipe'] });199      let err = '';200      let last = 0;201      child.stdout.on('data', (d: Buffer) => {202        const m = /out_time_us=(\d+)/g;203        let x: RegExpExecArray | null;204        let us = 0;205        const text = d.toString();206        while ((x = m.exec(text))) us = Number(x[1]);207        if (us && Date.now() - last > 700) {208          last = Date.now();209          this.db.prepare('UPDATE exports SET progress = ? WHERE id = ?').run(Math.min(0.99, us / 1e6 / durS), id);210        }211      });212      child.stderr.on('data', (d: Buffer) => {213        err = (err + d).slice(-400);214      });215      const timer = setTimeout(() => child.kill('SIGKILL'), 30 * 60000);216      child.on('close', (c) => {217        clearTimeout(timer);218        if (c !== 0) log.warn('ffmpeg export', { err: err.trim().slice(-200) });219        resolve(c);220      });221      child.on('error', () => resolve(-1));222    });223    try {224      fs.unlinkSync(listFile);225    } catch {226      /* rien */227    }228    if (code !== 0 || !fs.existsSync(tmp) || fs.statSync(tmp).size < 1000) {229      try {230        fs.unlinkSync(tmp);231      } catch {232        /* rien */233      }234      throw new Error('la conversion a échoué');235    }236    fs.renameSync(tmp, out);237    const size = fs.statSync(out).size;238    this.db.prepare("UPDATE exports SET state = 'done', progress = 1, size_bytes = ?, finished_ms = ?, expires_ms = ? WHERE id = ?").run(size, Date.now(), Date.now() + this.cfg.retention.exportTtlHours * 3600000, id);239    addEvent(this.db, { cameraId: ex.camera_id, type: 'export_ready', message: `Export MP4 prêt (${(size / 1e6).toFixed(1)} Mo)`, data: { exportId: id, fromMs: ex.from_ms, toMs: ex.to_ms }, tsMs: Date.now() });240  }241}242243const thumbInflight = new Map<string, Promise<string>>();244245/** Vignette JPEG extraite d'un segment réellement enregistré à l'instant demandé (mise en cache sous events/). */246export async function thumbnail(cfg: Config, db: DB, cameraId: string, tMs: number): Promise<string> {247  const seg = db248    .prepare("SELECT id, start_ms, end_ms, rel_path FROM segments WHERE camera_id = ? AND start_ms <= ? AND end_ms > ? AND state IN ('archived','recovered') ORDER BY start_ms DESC LIMIT 1")249    .get(cameraId, tMs, tMs) as { id: number; start_ms: number; end_ms: number; rel_path: string } | undefined;250  if (!seg) throw new HttpError(404, 'no_recording_at_time');251  const src = resolveArchivePath(cfg, seg.rel_path);252  const bucket = Math.floor(tMs / 10000) * 10000;253  const dir = path.join(cfg.eventsDir, cameraId);254  const out = path.join(dir, `${bucket}.jpg`);255  if (fs.existsSync(out)) return out;256  const key = `${cameraId}:${bucket}`;257  let p = thumbInflight.get(key);258  if (!p) {259    p = (async () => {260      fs.mkdirSync(dir, { recursive: true, mode: 0o700 });261      const tmp = `${out}.${process.pid}.tmp`;262      const offset = Math.max(0, (bucket - seg.start_ms) / 1000);263      const r = await run(cfg.ffmpegBin, ['-hide_banner', '-v', 'error', '-nostdin', '-y', '-ss', offset.toFixed(2), '-i', src, '-frames:v', '1', '-vf', 'scale=480:-2', '-q:v', '6', '-f', 'mjpeg', tmp], { timeoutMs: 20000 });264      if (r.code !== 0 || !fs.existsSync(tmp) || fs.statSync(tmp).size < 300) {265        try {266          fs.unlinkSync(tmp);267        } catch {268          /* rien */269        }270        throw new HttpError(404, 'thumbnail_unavailable');271      }272      fs.renameSync(tmp, out);273      return out;274    })().finally(() => thumbInflight.delete(key));275    thumbInflight.set(key, p);276  }277  return p;278}279
Files main
Menu

Theme