From 066f817f802a12221cf7df9e793f921732a68299 Mon Sep 17 00:00:00 2001 From: Hyeong Seok <41688671+hyngsk@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:12:10 +0900 Subject: [PATCH] Restart recorder and motion ffmpeg when they stop making progress When the camera behind go2rtc drops and go2rtc reconnects within a few seconds, the RTSP consumers keep their connection but the RTP timestamps jump. The recorder ffmpeg then stops writing the segment (it buffers in memory until it exits) and the motion ffmpeg stops printing scene scores. Neither process exits, so the exit-based restart never kicks in and recording/motion detection stay dead until the container restarts. Supervisor gets an optional stallMs: when a running process has not reported progress() for that long, it is sent SIGINT (SIGKILL after 5 s) and the normal exit path restarts it. - motion: every scene score line counts as progress (stallMs 60 s) - recorder: growth of the segment being written, checked by the existing 20 s scan, counts as progress (stallMs 90 s) Seen with a camera whose RTSP server restarts every few minutes: the current segment stayed at 48 bytes and no motion events were raised after a reconnect; SIGINT flushed the buffered segment and both recovered. --- server/src/motion.ts | 6 ++++- server/src/proc.ts | 35 +++++++++++++++++++++++++++ server/src/recorder.ts | 15 +++++++++++- server/test/proc.test.ts | 52 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 106 insertions(+), 2 deletions(-) create mode 100644 server/test/proc.test.ts diff --git a/server/src/motion.ts b/server/src/motion.ts index 71e2c13..c574673 100644 --- a/server/src/motion.ts +++ b/server/src/motion.ts @@ -182,7 +182,9 @@ export class MotionDetector { }, onStderr: (line) => { const score = parseSceneScore(line); - if (score === undefined || Date.now() - startedAt < 5000) return; + if (score === undefined) return; + det.sup.progress(); + if (Date.now() - startedAt < 5000) return; for (const ev of tracker.feed(Date.now(), score)) this.dispatch(det, ev); }, onExit: () => { @@ -190,6 +192,8 @@ export class MotionDetector { }, minBackoffMs: 5000, maxBackoffMs: 120_000, + // Scene scores arrive twice a second; with -skip_frame nokey they come in bursts per keyframe. + stallMs: 60_000, }), }; this.dets.set(cam.id, det); diff --git a/server/src/proc.ts b/server/src/proc.ts index a332a1f..75c465a 100644 --- a/server/src/proc.ts +++ b/server/src/proc.ts @@ -29,6 +29,12 @@ export type SupervisorOpts = { minBackoffMs?: number; maxBackoffMs?: number; healthyAfterMs?: number; + /** + * Restart the process when it keeps running but `progress()` has not been called for this long. + * ffmpeg can stay alive without producing anything, e.g. after the camera behind go2rtc reconnects + * and the RTP timestamps jump; it never exits, so the exit-based restart alone does not recover it. + */ + stallMs?: number; }; export class Supervisor { @@ -37,6 +43,8 @@ export class Supervisor { private backoff: number; private timer?: ReturnType; private startedAt = 0; + private lastProgress = 0; + private stallTimer?: ReturnType; lastError?: string; restarts = 0; readonly log: Logger; @@ -57,9 +65,33 @@ export class Supervisor { start(): void { if (!this.stopped) return; this.stopped = false; + const stallMs = this.opts.stallMs; + if (stallMs && stallMs > 0) { + clearInterval(this.stallTimer); + this.stallTimer = setInterval(() => this.checkStall(stallMs), Math.min(10_000, Math.max(1000, stallMs / 3))); + } this.spawn(); } + /** Marks that the process produced output, see `stallMs`. */ + progress(): void { + this.lastProgress = Date.now(); + } + + private checkStall(stallMs: number) { + const p = this.proc; + if (!p || p.exitCode !== null || this.stopped) return; + const idle = Date.now() - Math.max(this.lastProgress, this.startedAt); + if (idle < stallMs) return; + this.lastError = `no progress for ${Math.round(idle / 1000)}s`; + this.log.warn(`${this.lastError}, restarting`); + this.lastProgress = Date.now(); + p.kill("SIGINT"); // lets ffmpeg finish the current file; handleExit() schedules the restart + setTimeout(() => { + if (this.proc === p && p.exitCode === null) p.kill("SIGKILL"); + }, 5000); + } + private spawn(): void { if (this.stopped) return; const spec = this.opts.command(); @@ -77,6 +109,7 @@ export class Supervisor { }); this.proc = proc; this.startedAt = Date.now(); + this.lastProgress = this.startedAt; this.opts.onStart?.(); void readLines(proc.stdout, (l) => this.opts.onStdout?.(l)); void readLines(proc.stderr, (l) => { @@ -112,6 +145,8 @@ export class Supervisor { async stop(): Promise { this.stopped = true; clearTimeout(this.timer); + clearInterval(this.stallTimer); + this.stallTimer = undefined; const p = this.proc; this.proc = undefined; if (!p) return; diff --git a/server/src/recorder.ts b/server/src/recorder.ts index f0843f8..7883612 100644 --- a/server/src/recorder.ts +++ b/server/src/recorder.ts @@ -24,7 +24,7 @@ export type RecorderDeps = { getCamera: (cameraId: string) => CameraRecord | undefined; }; -type Entry = { sup: Supervisor; key: string; cam: CameraRecord; lastSegmentAt: number; lastError?: string }; +type Entry = { sup: Supervisor; key: string; cam: CameraRecord; lastSegmentAt: number; lastError?: string; lastSize?: string }; export function buildRecordArgs(o: { ffmpeg: string; @@ -150,6 +150,8 @@ export class Recorder { }, minBackoffMs: 3000, maxBackoffMs: 60_000, + // The segment being written grows continuously; doScan() (every 20 s) reports growth as progress. + stallMs: 90_000, }), }; this.entries.set(cam.id, entry); @@ -176,6 +178,17 @@ export class Recorder { for (const f of readdirSync(join(dir, day))) if (/^\d{6}\.mp4$/.test(f)) files.push(`${day}/${f}`); } files.sort(); + const newest = files[files.length - 1]; + if (entry && newest) { + try { + const st = statSync(join(dir, newest)); + const mark = `${newest}:${st.size}`; + if (mark !== entry.lastSize) { + entry.lastSize = mark; + entry.sup.progress(); + } + } catch {} + } const active = !includeNewest && entry?.sup.running; const finished = active ? files.slice(0, -1) : files; for (const rel of finished) { diff --git a/server/test/proc.test.ts b/server/test/proc.test.ts new file mode 100644 index 0000000..fd48fe4 --- /dev/null +++ b/server/test/proc.test.ts @@ -0,0 +1,52 @@ +import { expect, test } from "bun:test"; +import { Supervisor } from "../src/proc.ts"; + +test("supervisor restarts a process that stops making progress", async () => { + let starts = 0; + const sup = new Supervisor("stall-test", { + command: () => ({ cmd: ["sleep", "30"] }), + onStart: () => { + starts++; + }, + minBackoffMs: 50, + stallMs: 1000, + }); + sup.start(); + await Bun.sleep(2600); + await sup.stop(); + expect(starts).toBeGreaterThanOrEqual(2); + expect(sup.lastError).toContain("no progress"); +}); + +test("progress() keeps a quiet but healthy process running", async () => { + let starts = 0; + const sup = new Supervisor("stall-test-ok", { + command: () => ({ cmd: ["sleep", "30"] }), + onStart: () => { + starts++; + }, + minBackoffMs: 50, + stallMs: 1000, + }); + sup.start(); + const t = setInterval(() => sup.progress(), 200); + await Bun.sleep(2600); + clearInterval(t); + await sup.stop(); + expect(starts).toBe(1); +}); + +test("without stallMs a silent process is left alone", async () => { + let starts = 0; + const sup = new Supervisor("no-stall", { + command: () => ({ cmd: ["sleep", "30"] }), + onStart: () => { + starts++; + }, + minBackoffMs: 50, + }); + sup.start(); + await Bun.sleep(1500); + await sup.stop(); + expect(starts).toBe(1); +});