SPB Git

Repository Public

ingest.ts 5.0 KB 71 lines typescript

1import { spawn, type ChildProcess } from "node:child_process";2import { closeDb, now, run } from "../server/db";3import { ffmpegPath } from "../server/library";4import { eligibility, streamRow } from "../server/relay/access";5import { limits, publishUrl, RELAY_ID } from "../server/relay/config";6import { event } from "../server/relay/events";7import { activeRelays, alive, getRelay } from "../server/relay/relays";8import { resolveInput } from "../server/relay/sources";9import { ffmpegArgs, type Plan } from "../server/relay/transcode";1011// Ingest process of one relay. MediaMTX starts it when the first player asks for the path named in MTX_PATH and sends12// it SIGINT once the last player has gone. It keeps one FFmpeg alive between the source and MediaMTX and reconnects,13// with a growing delay, when the source drops. It never prints an address, a credential or FFmpeg's command line.1415const id = process.env.MTX_PATH ?? "";16let stopping = false, child: ChildProcess | null = null, wake: (() => void) | null = null;17const sleep = (ms: number) => new Promise<void>((r) => { const t = setTimeout(r, ms); wake = () => { clearTimeout(t); r(); }; });18const setState = (state: string, error?: string | null) => run("UPDATE relays SET state = ?, last_error = COALESCE(?, last_error) WHERE id = ?", state, error ?? null, id);19const clean = (s: string) => s.replace(/\b(?:https?|rtsps?):\/\/\S+/gi, "(adresse)").replace(/\s+/g, " ").trim().slice(-240);2021function fail(message: string): never {22  run("UPDATE relays SET state = 'failed', last_error = ?, stopped_at = ?, pid = NULL, ffmpeg_pid = NULL, clients = 0 WHERE id = ?", message, now(), id);23  event("error", "ingest", message, id); closeDb(); process.exit(1);24}2526async function main() {27  if (!RELAY_ID.test(id)) process.exit(1);28  const relay = getRelay(id);29  // A path nobody prepared through the application is never served.30  if (!relay?.plan) process.exit(1);31  const row = streamRow(relay.stream_id); if (!row) fail("Le flux de ce relais n'existe plus");32  const ok = eligibility(row); if (!ok.ok) fail(ok.reason);33  const bin = ffmpegPath(); if (!bin) fail("FFmpeg n'est pas installé sur ce nœud");34  if (activeRelays().filter((r) => r.id !== id && alive(r.pid)).length >= limits().maxRelays) fail(`Nombre maximal de relais simultanés atteint (${limits().maxRelays})`);35  const plan = JSON.parse(relay.plan) as Plan;3637  for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => {38    stopping = true; wake?.();39    if (child && child.exitCode === null) { child.kill("SIGTERM"); setTimeout(() => child?.kill("SIGKILL"), 3000).unref(); }40  });41  run("UPDATE relays SET state = 'starting', pid = ?, ffmpeg_pid = NULL, started_at = ?, ready_at = NULL, stopped_at = NULL, restarts = 0, last_error = NULL, in_changed_at = NULL, bytes_in = 0, bytes_out = 0 WHERE id = ?", process.pid, now(), id);42  event("info", "ingest", `Relais démarré à la demande (${plan.mode === "copy" ? "copie sans réencodage" : plan.mode === "transcode" ? "transcodage" : "audio seul"})`, id);4344  let failures = 0;45  while (!stopping) {46    let args: string[];47    try { args = ffmpegArgs(id, await resolveInput(row), plan, publishUrl(id), limits()); }48    catch (e) { if (++failures > limits().reconnectMax) fail(`Source inaccessible : ${clean((e as Error).message)}`); setState("reconnecting", clean((e as Error).message)); await sleep(Math.min(15, 2 ** (failures - 1)) * 1000); continue; }49    const started = now(); let err = "";50    child = spawn(bin, args, { stdio: ["ignore", "ignore", "pipe"] });51    run("UPDATE relays SET ffmpeg_pid = ?, state = CASE WHEN state = 'reconnecting' THEN 'starting' ELSE state END, in_changed_at = NULL WHERE id = ?", child.pid ?? null, id);52    child.stderr!.on("data", (d: Buffer) => { err = (err + d.toString()).slice(-2000); });53    const code = await new Promise<number | null>((resolve) => { child!.on("exit", (c) => resolve(c)); child!.on("error", () => resolve(-1)); });54    child = null;55    if (stopping) break;56    if (now() - started > 60_000) failures = 0;57    failures++;58    const lines = err.split("\n").map((l) => l.trim()).filter(Boolean);59    const why = clean(lines[lines.length - 1] ?? (code === 0 ? "la source a terminé le flux" : `FFmpeg a quitté (code ${code})`));60    if (failures > limits().reconnectMax) fail(`Flux abandonné après ${limits().reconnectMax} tentatives de reconnexion : ${why}`);61    const wait = Math.min(15, 2 ** (failures - 1));62    run("UPDATE relays SET state = 'reconnecting', restarts = restarts + 1, last_error = ?, ffmpeg_pid = NULL WHERE id = ?", why, id);63    event("warn", "ingest", `Flux interrompu (${why}) — reconnexion ${failures}/${limits().reconnectMax} dans ${wait} s`, id);64    await sleep(wait * 1000);65  }66  run("UPDATE relays SET state = 'stopped', stopped_at = ?, pid = NULL, ffmpeg_pid = NULL, clients = 0 WHERE id = ? AND state != 'failed'", now(), id);67  event("info", "ingest", "Relais arrêté : plus aucun lecteur", id);68  closeDb(); process.exit(0);69}70main().catch((e) => { try { fail(clean((e as Error).message)); } catch { process.exit(1); } });71
Files main
Menu

Theme