SPB Git

Repository Public

motion.ts 12.0 KB 295 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Vision8 * File             : server/src/motion.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// Détection de mouvement, entièrement locale : différence d'images sur le profil secondaire, à fréquence réduite.43// FFmpeg décode le flux déjà partagé par la passerelle et fournit de petites images en niveaux de gris ; l'analyse44// se fait ici. Ce n'est PAS une reconnaissance de personnes ou d'objets, et elle ne bloque jamais l'enregistrement.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 type { DB } from './db.ts';51import { streamName } from './go2rtc.ts';52import { logger } from './log.ts';5354export const GRID_W = 16;55export const GRID_H = 9;56const W = 160;57const H = 90;58const CELL = 10;59const FPS = 4;60const QUIET_MS = 6000;61const MAX_EVENT_MS = 5 * 60000;62// incrustation de la caméra (horodatage en haut à gauche) : toujours ignorée63const OSD_CELLS = new Set([0, 1, 2, 3, 4, 5, 6, 7]);6465export type MotionHit = { cameraId: string; eventId: number; tsMs: number };6667/** Analyse pure (testable) : une image après l'autre, retourne les cellules actives. */68export class MotionAnalyzer {69  private bg: Float32Array | null = null;70  private frames = 0;71  private streak = 0;72  sensitivity = 5;73  ignore = new Set<number>();7475  /** Réapprend le fond sans rien déclencher (pendant un déplacement PTZ commandé). */76  relearn(frame: Uint8Array): void {77    if (!this.bg) this.bg = Float32Array.from(frame);78    else for (let i = 0; i < this.bg.length; i++) this.bg[i] += (frame[i] - this.bg[i]) * 0.5;79    this.streak = 0;80  }8182  /** Retourne { cells, global } ; `motion` n'est vrai qu'après deux images consécutives actives. */83  feed(frame: Uint8Array): { motion: boolean; cells: number[]; global: boolean } {84    if (!this.bg) {85      this.bg = Float32Array.from(frame);86      this.frames = 1;87      return { motion: false, cells: [], global: false };88    }89    const bg = this.bg;90    const pixT = 26 - this.sensitivity * 1.6; // sensibilité 5 → écart de 18 niveaux91    const cellT = Math.round(CELL * CELL * (0.32 - this.sensitivity * 0.022)); // sensibilité 5 → 21 % de la cellule92    const counts = new Uint16Array(GRID_W * GRID_H);93    for (let y = 0; y < H; y++) {94      const cy = (y / CELL) | 0;95      for (let x = 0; x < W; x++) {96        const i = y * W + x;97        const d = Math.abs(frame[i] - bg[i]);98        const changed = d > pixT;99        if (changed) counts[cy * GRID_W + ((x / CELL) | 0)]++;100        // le fond suit lentement la scène ; plus lentement encore là où ça bouge101        bg[i] += (frame[i] - bg[i]) * (changed ? 0.012 : 0.06);102      }103    }104    this.frames++;105    const cells: number[] = [];106    let raw = 0;107    for (let c = 0; c < counts.length; c++) {108      if (counts[c] >= cellT) {109        raw++;110        if (!OSD_CELLS.has(c) && !this.ignore.has(c)) cells.push(c);111      }112    }113    // changement global (éclairage, bascule infrarouge, déplacement PTZ) : pas un mouvement, on réapprend le fond114    const global = raw > GRID_W * GRID_H * 0.55;115    if (global) {116      for (let i = 0; i < bg.length; i++) bg[i] += (frame[i] - bg[i]) * 0.5;117      this.streak = 0;118      return { motion: false, cells: [], global: true };119    }120    if (this.frames < FPS * 4) return { motion: false, cells: [], global: false }; // apprentissage du fond121    this.streak = cells.length ? this.streak + 1 : 0;122    return { motion: this.streak >= 2, cells, global: false };123  }124}125126export class MotionDetector {127  private child: ChildProcess | null = null;128  private wanted = false;129  private retry: NodeJS.Timeout | null = null;130  private fails = 0;131  private analyzer = new MotionAnalyzer();132  private buf: Buffer = Buffer.alloc(0);133  private event: { id: number; startMs: number; lastMs: number; peak: number; cells: Set<number> } | null = null;134  private lastNotifyMs = 0;135  private lastFrameAt = 0;136  private suppressUntil = 0;137  private log;138  private cfg: Config;139  private db: DB;140  private onMotion: (hit: MotionHit, notify: boolean) => void;141  cam: Camera;142143  constructor(cfg: Config, db: DB, cam: Camera, onMotion: (hit: MotionHit, notify: boolean) => void) {144    this.cfg = cfg;145    this.db = db;146    this.cam = cam;147    this.onMotion = onMotion;148    this.log = logger(`motion:${cam.id}`);149  }150151  get running(): boolean {152    return !!this.child;153  }154155  private setState(s: string): void {156    this.db.prepare('UPDATE camera_state SET motion_state = ? WHERE camera_id = ?').run(s, this.cam.id);157  }158159  /** Applique les réglages courants de la caméra (sans relancer l'analyse). */160  configure(cam: Camera): void {161    this.cam = cam;162    this.analyzer.sensitivity = cam.motionSensitivity;163    this.analyzer.ignore = new Set(cam.motionIgnore);164  }165166  /** Un déplacement commandé de la caméra n'est pas un mouvement dans la scène. */167  suppress(ms: number): void {168    this.suppressUntil = Math.max(this.suppressUntil, Date.now() + ms);169  }170171  start(): void {172    this.wanted = true;173    if (this.child || this.retry) return;174    this.spawn();175  }176177  private spawn(): void {178    this.retry = null;179    if (!this.wanted) return;180    this.analyzer = new MotionAnalyzer();181    this.configure(this.cam);182    this.buf = Buffer.alloc(0);183    const src = `rtsp://127.0.0.1:${this.cfg.go2rtc.rtspPort}/${streamName(this.cam.id, 'sub', true)}?video`;184    const args = ['-hide_banner', '-loglevel', 'error', '-nostdin', '-rtsp_transport', 'tcp', '-timeout', '15000000', '-i', src, '-an', '-vf', `fps=${FPS},scale=${W}:${H},format=gray`, '-f', 'rawvideo', 'pipe:1'];185    const child = spawn(this.cfg.ffmpegBin, args, { stdio: ['ignore', 'pipe', 'ignore'], env: { PATH: '/usr/bin:/bin' } });186    this.child = child;187    const startedAt = Date.now();188    this.lastFrameAt = startedAt;189    this.setState('running');190    child.stdout!.on('data', (d: Buffer) => this.onData(d));191    child.on('exit', () => {192      this.child = null;193      this.closeEvent();194      if (!this.wanted) return this.setState('stopped');195      this.fails = Date.now() - startedAt > 120000 ? 0 : this.fails + 1;196      const delay = Math.min(60000, 2000 * 2 ** Math.min(this.fails, 5)) * (0.7 + Math.random() * 0.6);197      this.setState('backoff');198      this.retry = setTimeout(() => this.spawn(), delay);199    });200  }201202  stop(): void {203    this.wanted = false;204    if (this.retry) clearTimeout(this.retry);205    this.retry = null;206    this.child?.kill('SIGKILL');207  }208209  /** Surveillance : un analyseur figé est relancé. */210  tick(): void {211    if (this.child && Date.now() - this.lastFrameAt > 30000) {212      this.log.warn('analyse figée, relance');213      this.child.kill('SIGKILL');214    }215    if (this.event && Date.now() - this.event.lastMs > QUIET_MS) this.closeEvent();216  }217218  private onData(d: Buffer): void {219    this.buf = this.buf.length ? Buffer.concat([this.buf, d]) : d;220    const size = W * H;221    while (this.buf.length >= size) {222      const frame = this.buf.subarray(0, size);223      this.buf = this.buf.subarray(size);224      this.lastFrameAt = Date.now();225      try {226        this.onFrame(frame);227      } catch (e: any) {228        this.log.error('analyse', { err: String(e?.message || e) });229      }230    }231  }232233  private onFrame(frame: Uint8Array): void {234    const now = Date.now();235    if (now < this.suppressUntil) return this.analyzer.relearn(frame);236    const r = this.analyzer.feed(frame);237    if (r.motion) {238      if (!this.event) {239        const res = this.db240          .prepare("INSERT INTO events (ts_ms, camera_id, type, severity, message, data) VALUES (?, ?, 'motion', 'info', ?, ?)")241          .run(now, this.cam.id, 'Mouvement détecté', JSON.stringify({ fromMs: now, toMs: null, hasImage: false }));242        const id = Number(res.lastInsertRowid);243        this.event = { id, startMs: now, lastMs: now, peak: r.cells.length, cells: new Set(r.cells) };244        this.db.prepare('UPDATE camera_state SET last_motion_ms = ? WHERE camera_id = ?').run(now, this.cam.id);245        const notify = now - this.lastNotifyMs >= this.cam.motionCooldownS * 1000;246        if (notify) this.lastNotifyMs = now;247        this.onMotion({ cameraId: this.cam.id, eventId: id, tsMs: now }, notify);248      } else {249        this.event.lastMs = now;250        this.event.peak = Math.max(this.event.peak, r.cells.length);251        for (const c of r.cells) this.event.cells.add(c);252        if (now - this.event.startMs > 1000 && Math.floor(now / 5000) !== Math.floor((now - 250) / 5000)) this.db.prepare('UPDATE camera_state SET last_motion_ms = ? WHERE camera_id = ?').run(now, this.cam.id);253        if (now - this.event.startMs > MAX_EVENT_MS) this.closeEvent();254      }255    } else if (this.event && now - this.event.lastMs > QUIET_MS) this.closeEvent();256  }257258  private closeEvent(): void {259    const e = this.event;260    if (!e) return;261    this.event = null;262    const hasImage = fs.existsSync(motionImagePath(this.cfg, this.cam.id, e.id));263    const dur = Math.max(1, Math.round((e.lastMs - e.startMs) / 1000));264    this.db265      .prepare('UPDATE events SET message = ?, data = ? WHERE id = ?')266      .run(`Mouvement pendant ${dur} s`, JSON.stringify({ fromMs: e.startMs, toMs: e.lastMs, hasImage, peakCells: e.peak, cells: [...e.cells].sort((a, b) => a - b) }), e.id);267    this.db.prepare('UPDATE camera_state SET last_motion_ms = ? WHERE camera_id = ?').run(e.lastMs, this.cam.id);268  }269}270271export function motionImagePath(cfg: Config, cameraId: string, eventId: number): string {272  return path.join(cfg.eventsDir, cameraId, `motion-${eventId}.jpg`);273}274275/** Image réelle au moment du déclenchement (instantané de la passerelle), rattachée à l'événement. */276export async function saveMotionImage(cfg: Config, db: DB, hit: MotionHit): Promise<void> {277  try {278    const r = await fetch(`http://127.0.0.1:${cfg.go2rtc.apiPort}/api/frame.jpeg?src=${encodeURIComponent(streamName(hit.cameraId, 'sub', false))}`, { signal: AbortSignal.timeout(10000) });279    if (!r.ok) return;280    const data = Buffer.from(await r.arrayBuffer());281    if (data.length < 500 || data[0] !== 0xff || data[1] !== 0xd8) return;282    const file = motionImagePath(cfg, hit.cameraId, hit.eventId);283    fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });284    fs.writeFileSync(file, data, { mode: 0o600 });285    const row = db.prepare('SELECT data FROM events WHERE id = ?').get(hit.eventId) as { data: string } | undefined;286    if (row) {287      const d = JSON.parse(row.data || '{}');288      d.hasImage = true;289      db.prepare('UPDATE events SET data = ? WHERE id = ?').run(JSON.stringify(d), hit.eventId);290    }291  } catch {292    /* pas d'image : l'événement reste valable */293  }294}295
Files main
Menu

Theme