Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { SettingsStore, type Settings } from "./settings.ts";
import { CameraStore, cameraJson, go2rtcSources, isPush, recordsOnEvent, type CameraRecord, type CameraStatus, type CameraJson } from "./cameras.ts";
import { Recordings, type RecordingRow } from "./recordings.ts";
import { Push } from "./push.ts";
import { Go2rtc, codecSummary, freePort, type StreamDef } from "./go2rtc.ts";
import { AudioRecovery, Go2rtc, audioMissing, codecSummary, freePort, type StreamDef } from "./go2rtc.ts";
import { Recorder } from "./recorder.ts";
import { MotionDetector, segmentDecidable, shouldKeepSegment } from "./motion.ts";
import { Storage } from "./storage/index.ts";
Expand All @@ -35,7 +35,7 @@ const log = logger("app");

type GatewayLink = { url: string; siteId: string; secret: string; siteName?: string; enabled: boolean };

type LiveStatus = CameraStatus & { bytes?: number; bytesAt?: number; probed?: boolean; probing?: boolean; lastProbeAttempt?: number; ptzChecked?: boolean };
type LiveStatus = CameraStatus & { bytes?: number; bytesAt?: number; probed?: boolean; probing?: boolean; lastProbeAttempt?: number; ptzChecked?: boolean; audioWatch?: AudioRecovery };

export type HandleMeta = { tunnel?: { role: string; user?: string; base?: string } };

Expand Down Expand Up @@ -321,6 +321,7 @@ export class App {
l.bytesAt = now;
if (sum.codec) l.codec = sum.codec === "h265" ? "hevc" : sum.codec;
if (!l.probed && !l.probing && now - (l.lastProbeAttempt ?? 0) > 60_000) void this.probe(cam, l);
if (cam.kind !== "eufy" && !isPush(cam.kind)) this.watchAudio(cam, l, audioMissing(streams[cam.streamKey], cam.streamKey), now);
} else if (cam.kind === "eufy") {
l.bytes = undefined;
const serial = cam.fields.serial ?? "";
Expand All @@ -337,6 +338,26 @@ export class App {
}
}

private audioRestartAt = 0;

private watchAudio(cam: CameraRecord, l: LiveStatus, missing: boolean | undefined, now: number) {
l.audioWatch ??= new AudioRecovery();
const act = l.audioWatch.check(now, missing, !!cam.caps.audio);
if (act === "reconnect") {
if (now - this.audioRestartAt < 15_000) return;
this.audioRestartAt = now;
log.warn(`${cam.name}: camera stream has no audio track, reconnecting cameras`);
void this.go2rtc.restart().catch((e) => log.warn(`go2rtc restart failed: ${errMsg(e)}`));
} else if (act === "give-up") {
log.warn(`${cam.name}: camera still sends no audio after reconnecting, treating it as video only`);
this.cameras.setCaps(cam.id, { audio: false });
this.emitCamera(cam.id);
} else if (act === "restored") {
this.cameras.setCaps(cam.id, { audio: true });
this.emitCamera(cam.id);
}
}

private async probe(cam: CameraRecord, l: LiveStatus) {
l.probing = true;
l.lastProbeAttempt = Date.now();
Expand All @@ -348,8 +369,10 @@ export class App {
l.width = p.width;
l.height = p.height;
l.fps = p.fps;
const audio = !!p.audio;
if (!!cam.caps.audio !== audio) this.cameras.setCaps(cam.id, { audio });
// A camera that had audio keeps the flag when this probe sees none: right after a
// camera restart the track is often missing, and watchAudio reconnects and clears the
// flag only if it never comes back.
if (p.audio && !cam.caps.audio) this.cameras.setCaps(cam.id, { audio: true });
this.emitCamera(cam.id);
}
} finally {
Expand Down
60 changes: 60 additions & 0 deletions server/src/go2rtc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,16 @@ export class Go2rtc {
await this.readyPromise;
}

// Restart go2rtc so every camera connection is made again from scratch. Deleting and
// re-adding a stream over the API does not do this: go2rtc only drops the name, and the
// running producer keeps serving the consumers it already has.
async restart(): Promise<void> {
if (!this.sup.running) return;
await this.sup.restart();
this.readyPromise = this.waitReady();
await this.readyPromise;
}

async stop(): Promise<void> {
await this.sup.stop();
}
Expand Down Expand Up @@ -262,4 +272,54 @@ export function codecSummary(info: StreamInfo | undefined): { online: boolean; c
return { online, codec, audio, bytes };
}

// Whether the camera's own connection is up without an audio track. Our transcoders
// (ffmpeg:<stream>#audio=...) read from the stream itself, so they are left out.
// undefined: the camera is not connected right now.
export function audioMissing(info: StreamInfo | undefined, stream: string): boolean | undefined {
let connected = false;
for (const p of info?.producers ?? []) {
const src = `${p.url ?? ""} ${p.source ?? ""}`;
if (src.startsWith(`ffmpeg:${stream}#`) || src.includes(`source=ffmpeg:${stream}`)) continue;
if (!p.medias?.length) continue;
connected = true;
if (p.medias.some((m) => /^audio, recvonly\b/.test(m))) return false;
}
return connected ? true : undefined;
}

// Some cameras answer the first DESCRIBE after their RTSP server restarts with video only.
// go2rtc keeps that connection, and when it reconnects it only re-attaches the tracks it
// already had, so the audio never comes back by itself. When a camera that has audio sends
// none for a while, ask for a fresh connection, backing off; give up after the last delay.
export class AudioRecovery {
private since?: number;
private tries = 0;
private gaveUp = false;

constructor(private delays = [15_000, 60_000, 300_000]) {}

check(now: number, missing: boolean | undefined, expected: boolean): "reconnect" | "give-up" | "restored" | undefined {
if (missing === false) {
const back = this.gaveUp;
this.since = undefined;
this.tries = 0;
this.gaveUp = false;
return back ? "restored" : undefined;
}
if (missing === undefined || !expected || this.gaveUp) {
this.since = undefined;
return;
}
this.since ??= now;
if (now - this.since < this.delays[Math.min(this.tries, this.delays.length - 1)]!) return;
this.since = undefined;
if (this.tries >= this.delays.length) {
this.gaveUp = true;
return "give-up";
}
this.tries++;
return "reconnect";
}
}

export { errMsg };
41 changes: 40 additions & 1 deletion server/test/media.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { parseSegmentPath } from "../src/media.ts";
import { buildGo2rtcYaml, codecSummary } from "../src/go2rtc.ts";
import { AudioRecovery, audioMissing, buildGo2rtcYaml, codecSummary } from "../src/go2rtc.ts";
import { buildRecordArgs } from "../src/recorder.ts";

describe("HLS playlist rewrite", () => {
Expand Down Expand Up @@ -97,3 +97,42 @@ describe("go2rtc config and recorder args", () => {
expect(s).toContain("-tag:v hvc1");
});
});

describe("audio recovery", () => {
const cam = (medias: string[]) => ({ url: "rtsp://cam/main", medias });
const opus = { source: "exec:ffmpeg -i rtsp://127.0.0.1:1/s?audio&source=ffmpeg:s -c:a libopus", medias: ["audio, recvonly, OPUS/48000/2"] };

test("audio missing only when the camera connection itself has none", () => {
expect(audioMissing({ producers: [cam(["video, recvonly, H264", "audio, recvonly, MPEG4-GENERIC/16000/2"])], consumers: [] }, "s")).toBe(false);
expect(audioMissing({ producers: [cam(["video, recvonly, H264"]), opus, { url: "ffmpeg:s#audio=aac" }], consumers: [] }, "s")).toBe(true);
expect(audioMissing({ producers: [cam(["video, recvonly, H264", "audio, sendonly, PCMA/8000"])], consumers: [] }, "s")).toBe(true);
expect(audioMissing({ producers: [{ url: "rtsp://cam/main" }, { url: "ffmpeg:s#audio=opus" }], consumers: [] }, "s")).toBeUndefined();
expect(audioMissing(undefined, "s")).toBeUndefined();
});

test("reconnects after the delay, backs off, then gives up", () => {
const r = new AudioRecovery([10, 20]);
expect(r.check(0, true, true)).toBeUndefined();
expect(r.check(10, true, true)).toBe("reconnect");
expect(r.check(11, undefined, true)).toBeUndefined();
expect(r.check(12, true, true)).toBeUndefined();
expect(r.check(32, true, true)).toBe("reconnect");
expect(r.check(33, true, true)).toBeUndefined();
expect(r.check(53, true, true)).toBe("give-up");
expect(r.check(1000, true, true)).toBeUndefined();
expect(r.check(1001, false, true)).toBe("restored");
expect(r.check(1002, false, true)).toBeUndefined();
});

test("audio coming back resets the backoff; cameras without audio are left alone", () => {
const r = new AudioRecovery([10, 20]);
r.check(0, true, true);
expect(r.check(10, true, true)).toBe("reconnect");
expect(r.check(11, false, true)).toBeUndefined();
r.check(12, true, true);
expect(r.check(22, true, true)).toBe("reconnect");
const n = new AudioRecovery([10]);
expect(n.check(0, true, false)).toBeUndefined();
expect(n.check(100, true, false)).toBeUndefined();
});
});