SPB Git

Repository Public

go2rtc.ts 6.9 KB 217 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Vision8 * File             : server/src/go2rtc.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// Passerelle vidéo go2rtc : un seul flux amont par profil de caméra, partagé entre le NVR et le direct.43// Écoute uniquement sur 127.0.0.1 ; la configuration générée contient les identifiants caméra (mode 0600).44import { spawn, type ChildProcess } from 'node:child_process';45import fs from 'node:fs';46import path from 'node:path';47import type { Camera } from './cameras.ts';48import { rtspUrl } from './cameras.ts';49import type { Config } from './config.ts';50import { logger, redact } from './log.ts';51import { run } from './media.ts';5253const log = logger('go2rtc');5455export function streamName(cameraId: string, profile: 'main' | 'sub', audio: boolean): string {56  return `${cameraId}_${profile}${audio ? '' : '_v'}`;57}5859export function renderConfig(cfg: Config, cams: Camera[]): string {60  const q = (s: string) => JSON.stringify(s);61  const lines: string[] = [62    '# Généré par MacLustr Vision — ne pas modifier, ne pas commiter (contient des identifiants).',63    'api:',64    `  listen: "127.0.0.1:${cfg.go2rtc.apiPort}"`,65    '  origin: ""',66    'rtsp:',67    `  listen: "127.0.0.1:${cfg.go2rtc.rtspPort}"`,68    'webrtc:',69    '  listen: ""',70    'srtp:',71    '  listen: ""',72    'ffmpeg:',73    `  bin: ${q(cfg.ffmpegBin)}`,74    'log:',75    '  level: info',76    '  format: text',77    'streams:',78  ];79  for (const c of cams) {80    for (const profile of ['main', 'sub'] as const) {81      const full = streamName(c.id, profile, true);82      lines.push(`  ${full}:`);83      lines.push(`    - ${q(rtspUrl(c, profile))}`);84      lines.push(`    - ${q(`ffmpeg:${full}#audio=aac`)}`);85      lines.push(`  ${streamName(c.id, profile, false)}:`);86      lines.push(`    - ${q(`rtsp://127.0.0.1:${cfg.go2rtc.rtspPort}/${full}?video`)}`);87    }88  }89  return lines.join('\n') + '\n';90}9192export class Go2rtc {93  private child: ChildProcess | null = null;94  private stopping = false;95  private restarts = 0;96  private timer: NodeJS.Timeout | null = null;97  private cfg: Config;98  private getCameras: () => Camera[];99  public startedAt = 0;100101  constructor(cfg: Config, getCameras: () => Camera[]) {102    this.cfg = cfg;103    this.getCameras = getCameras;104  }105106  private get bin() {107    return path.join(this.cfg.binDir, 'go2rtc');108  }109  private get confPath() {110    return path.join(this.cfg.configDir, 'go2rtc.yaml');111  }112  private get pidPath() {113    return path.join(this.cfg.dataDir, 'go2rtc.pid');114  }115116  private async killStale(): Promise<void> {117    try {118      const pid = parseInt(fs.readFileSync(this.pidPath, 'utf8'), 10);119      if (!pid) return;120      const r = await run('/bin/ps', ['-p', String(pid), '-o', 'command=']);121      if (r.stdout.includes(this.bin)) {122        log.warn('ancien go2rtc encore en vie, arrêt', { pid });123        process.kill(pid, 'SIGTERM');124        await new Promise((res) => setTimeout(res, 1500));125        try {126          process.kill(pid, 'SIGKILL');127        } catch {128          /* déjà arrêté */129        }130      }131    } catch {132      /* pas de pidfile */133    }134  }135136  writeConfig(): void {137    fs.writeFileSync(this.confPath, renderConfig(this.cfg, this.getCameras()), { mode: 0o600 });138    fs.chmodSync(this.confPath, 0o600);139  }140141  async start(): Promise<void> {142    this.stopping = false;143    await this.killStale();144    this.spawnChild();145  }146147  private spawnChild(): void {148    this.writeConfig();149    const child = spawn(this.bin, ['-config', this.confPath], { stdio: ['ignore', 'pipe', 'pipe'], env: { PATH: '/opt/homebrew/bin:/usr/bin:/bin', HOME: process.env.HOME || '' } });150    this.child = child;151    this.startedAt = Date.now();152    if (child.pid) fs.writeFileSync(this.pidPath, String(child.pid));153    const onData = (d: Buffer) => {154      for (const line of d.toString().split('\n')) {155        const t = line.trim();156        if (!t) continue;157        if (/ (ERR|WRN|FTL|PNC) /.test(t)) log.warn(redact(t).slice(0, 400));158        else log.debug(redact(t).slice(0, 400));159      }160    };161    child.stdout?.on('data', onData);162    child.stderr?.on('data', onData);163    child.on('exit', (code, signal) => {164      this.child = null;165      if (this.stopping) return;166      this.restarts++;167      const delay = Math.min(30000, 1000 * 2 ** Math.min(this.restarts, 5)) * (0.7 + Math.random() * 0.6);168      log.error('go2rtc arrêté, relance', { code, signal, delayMs: Math.round(delay) });169      this.timer = setTimeout(() => this.spawnChild(), delay);170    });171    log.info('go2rtc démarré', { pid: child.pid });172  }173174  async restart(): Promise<void> {175    await this.stop();176    await this.start();177  }178179  async stop(): Promise<void> {180    this.stopping = true;181    if (this.timer) clearTimeout(this.timer);182    const child = this.child;183    if (!child) return;184    await new Promise<void>((resolve) => {185      const t = setTimeout(() => {186        child.kill('SIGKILL');187      }, 4000);188      child.once('exit', () => {189        clearTimeout(t);190        resolve();191      });192      child.kill('SIGTERM');193    });194    try {195      fs.unlinkSync(this.pidPath);196    } catch {197      /* rien */198    }199  }200201  async healthy(): Promise<boolean> {202    try {203      const r = await fetch(`http://127.0.0.1:${this.cfg.go2rtc.apiPort}/api/streams`, { signal: AbortSignal.timeout(3000) });204      return r.ok;205    } catch {206      return false;207    }208  }209210  get running(): boolean {211    return !!this.child;212  }213  get restartCount(): number {214    return this.restarts;215  }216}217
Files main
Menu

Theme