Repository Public
1import crypto from "node:crypto";2import { all, get, now, run } from "../db";3import { RelayRefused, type Policy, type StreamRow } from "./access";4import { limits } from "./config";5import { event } from "./events";6import { resolveInput } from "./sources";7import { activeTranscodes, probeInput, type Plan } from "./transcode";89// RelayManager — one relay = one incoming connection to a source, published once in MediaMTX and read by any number of10// players. Relays are started on demand by MediaMTX (first reader) and stopped by it when the last reader has gone.1112export interface Relay {13 id: string; stream_id: number; channel_id: string; source_id: number; shared: number; record: number; owner: string | null; plan: string | null; mode: string | null;14 vcodec: string | null; acodec: string | null; width: number | null; height: number | null; probed_at: number | null; state: string; pid: number | null; ffmpeg_pid: number | null;15 created_at: number; started_at: number | null; ready_at: number | null; stopped_at: number | null; restarts: number; last_error: string | null;16 bytes_in: number; bytes_out: number; in_changed_at: number | null; clients: number;17}18export const ACTIVE = "('starting','running','reconnecting')";19export const isActive = (r: Pick<Relay, "state">) => r.state === "starting" || r.state === "running" || r.state === "reconnecting";20export const getRelay = (id: string) => get<Relay>("SELECT * FROM relays WHERE id = ?", id);21export const activeRelays = () => all<Relay>(`SELECT * FROM relays WHERE state IN ${ACTIVE} ORDER BY started_at`);22export const alive = (pid: number | null | undefined) => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch { return false; } };2324/** A shared relay is keyed by its stream; a source that does not allow sharing gets one relay per signed-in session. */25export function relayId(streamId: number, policy: Policy, auth: string): string {26 const base = (policy.record ? "t" : "r") + streamId.toString(36);27 return policy.share ? base : `${base}x${crypto.createHash("sha256").update(auth).digest("hex").slice(0, 10)}`;28}2930const PROBE_TTL = 6 * 3600_000;3132/** Finds the relay to use for a stream — the existing one when there is one — after checking every limit. */33export async function ensure(row: StreamRow, policy: Policy, auth: string): Promise<Relay> {34 const id = relayId(row.id, policy, auth); const l = limits();35 let r = getRelay(id);36 if (r && isActive(r) && alive(r.pid)) { event("info", "relay", `Relais réutilisé pour « ${row.channel_name} »`, id); return r; }3738 const active = activeRelays().filter((x) => alive(x.pid));39 if (active.length >= l.maxRelays) throw new RelayRefused(`Nombre maximal de relais simultanés atteint (${l.maxRelays})`, 503);40 // Never more upstream connections than the source allows.41 if (policy.maxConnections && active.filter((x) => x.source_id === row.source_id).length >= policy.maxConnections)42 throw new RelayRefused(`Cette source n'autorise que ${policy.maxConnections} connexion(s) simultanée(s)`, 503);4344 let plan: Plan | null = null; let probedAt = now();45 if (r?.plan && r.probed_at && now() - r.probed_at < PROBE_TTL && r.state !== "failed") { plan = JSON.parse(r.plan) as Plan; probedAt = r.probed_at; }46 if (!plan) {47 const input = await resolveInput(row);48 try { plan = await probeInput(input); } catch (e) { event("warn", "relay", `Analyse impossible pour « ${row.channel_name} » : ${(e as Error).message}`, id); throw new RelayRefused((e as Error).message, 502); }49 }50 if (plan.mode === "transcode" && activeTranscodes(id) >= l.maxTranscodes) throw new RelayRefused(`Nombre maximal de transcodages simultanés atteint (${l.maxTranscodes})`, 503);5152 run(`INSERT INTO relays(id, stream_id, channel_id, source_id, shared, record, owner, plan, mode, vcodec, acodec, width, height, probed_at, state, created_at)53 VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?, 'idle', ?)54 ON CONFLICT(id) DO UPDATE SET stream_id = excluded.stream_id, channel_id = excluded.channel_id, source_id = excluded.source_id, shared = excluded.shared, record = excluded.record,55 owner = excluded.owner, plan = excluded.plan, mode = excluded.mode, vcodec = excluded.vcodec, acodec = excluded.acodec, width = excluded.width, height = excluded.height,56 probed_at = excluded.probed_at,57 state = CASE WHEN relays.state IN ${ACTIVE} THEN 'idle' ELSE relays.state END, last_error = NULL`,58 id, row.id, row.channel_id, row.source_id, Number(policy.share), Number(policy.record), policy.share ? null : auth, JSON.stringify(plan), plan.mode,59 plan.video?.codec ?? null, plan.audio?.codec ?? null, plan.video?.width ?? null, plan.video?.height ?? null, probedAt, now());60 r = getRelay(id)!;61 event("info", "relay", `Relais préparé pour « ${row.channel_name} » (${plan.mode === "copy" ? "copie sans réencodage" : plan.mode === "transcode" ? `transcodage ${plan.video?.codec} → H.264` : "audio seul"})`, id);62 return r;63}6465/** Stops a relay now: its ingest process is asked to end and its sessions are closed. */66export function stop(id: string, reason: string): boolean {67 const r = getRelay(id); if (!r) return false;68 run("UPDATE relay_sessions SET ended_at = ?, end_reason = ? WHERE relay_id = ? AND ended_at IS NULL", now(), reason, id);69 if (alive(r.pid)) { try { process.kill(r.pid!, "SIGINT"); } catch { /* already gone */ } }70 run("UPDATE relays SET state = 'stopped', stopped_at = ?, clients = 0 WHERE id = ?", now(), id);71 event("info", "relay", `Relais arrêté (${reason})`, id);72 return true;73}74