SPB Git

Repository Public

config.ts 4.8 KB 68 lines typescript

1import crypto from "node:crypto";2import fs from "node:fs";3import path from "node:path";4import { getNum, getSetting } from "../db";5import { env } from "../env";67// Relay engine configuration. MediaMTX only ever listens on the loopback interface: the single way in from outside is8// the authenticated /relay/… route of this application.910export const SEGMENT_SEC = 2;11export const relayDir = () => path.join(env.dataDir, "relay");12export const configPath = () => path.join(relayDir(), "mediamtx.yml");13export const recordDir = () => path.join(relayDir(), "rec");14export const ports = () => { const b = env.relayPort; return { hls: b, api: b + 1, playback: b + 2, rtsp: b + 3 }; };15export const hlsBase = () => `http://127.0.0.1:${ports().hls}`;16export const apiBase = () => `http://127.0.0.1:${ports().api}`;17export const playbackBase = () => `http://127.0.0.1:${ports().playback}`;18/** Publishing credential of the ingest processes: derived from APP_SECRET, never stored, only valid from 127.0.0.1. */19export const publishPass = () => crypto.createHmac("sha256", env.appSecret).update("relay-publish").digest("hex").slice(0, 32);20export const publishUrl = (relayId: string) => `rtsp://ingest:${publishPass()}@127.0.0.1:${ports().rtsp}/${relayId}`;21export const enabled = () => getSetting("relay_enabled") === "1";2223export interface Limits { maxRelays: number; maxTranscodes: number; maxSessions: number; bufferSec: number; idleSec: number; outKbps: number; videoKbps: number; timeshiftMin: number; reconnectMax: number }24export const limits = (): Limits => ({25  maxRelays: getNum("relay_max_relays"), maxTranscodes: getNum("relay_max_transcodes"), maxSessions: getNum("relay_max_sessions"), bufferSec: getNum("relay_buffer_sec"),26  idleSec: getNum("relay_idle_sec"), outKbps: getNum("relay_out_kbps"), videoKbps: getNum("relay_video_kbps"), timeshiftMin: getNum("relay_timeshift_min"), reconnectMax: getNum("relay_reconnect_max"),27});2829/** Relay identifiers are MediaMTX path names: `r…` plain, `t…` recorded (timeshift). */30export const RELAY_ID = /^[rt][0-9a-z]{1,40}$/;3132export function renderConfig(appDir: string): string {33  const p = ports(); const l = limits();34  // The window kept by the server is the playback buffer plus a margin; players sit `bufferSec` behind the live edge.35  const segments = Math.max(4, Math.ceil(l.bufferSec / SEGMENT_SEC) + 3);36  const ingest = `${process.execPath} --import tsx ${path.join(appDir, "src/relay/ingest.ts")}`;37  // When a source drops, MediaMTX closes the path and its readers ("alwaysAvailable" cannot be combined with on-demand38  // paths): the player then reopens its session, which starts the relay again. See docs/RELAY.md, « Reconnexion ».39  const onDemand = (extra: string[] = []) => [`    runOnDemand: ${JSON.stringify(ingest)}`, "    runOnDemandRestart: no", "    runOnDemandStartTimeout: 40s", "    runOnDemandCloseAfter: 5s", ...extra];40  return [41    "# Generated by SP TV (src/server/relay/config.ts) — do not edit: it is rewritten when the relay settings change.",42    "logLevel: info", "logDestinations: [stdout]", "readTimeout: 20s", "writeTimeout: 20s",43    "api: yes", `apiAddress: 127.0.0.1:${p.api}`,44    "playback: yes", `playbackAddress: 127.0.0.1:${p.playback}`, "playbackAllowOrigins: []",45    "rtsp: yes", "rtspTransports: [tcp]", `rtspAddress: 127.0.0.1:${p.rtsp}`,46    "rtmp: no", "webrtc: no", "srt: no", "moq: no", "metrics: no", "pprof: no",47    "hls: yes", `hlsAddress: 127.0.0.1:${p.hls}`, "hlsAllowOrigins: []", "hlsVariant: mpegts",48    `hlsSegmentDuration: ${SEGMENT_SEC}s`, `hlsSegmentCount: ${segments}`, `hlsMuxerCloseAfter: ${Math.max(10, l.idleSec)}s`,49    "authMethod: internal",50    "authInternalUsers:",51    "  - user: ingest", `    pass: ${publishPass()}`, '    ips: ["127.0.0.1", "::1"]', "    permissions:", "      - action: publish",52    "  - user: any", "    pass:", '    ips: ["127.0.0.1", "::1"]', "    permissions:", "      - action: read", "      - action: playback", "      - action: api",53    "paths:",54    '  "~^r[0-9a-z]+$":', ...onDemand(),55    '  "~^t[0-9a-z]+$":', ...onDemand(["    record: yes", `    recordPath: ${JSON.stringify(path.join(recordDir(), "%path/%Y-%m-%d_%H-%M-%S-%f"))}`, "    recordFormat: fmp4", "    recordSegmentDuration: 10m", `    recordDeleteAfter: ${Math.max(5, l.timeshiftMin)}m`]),56    "",57  ].join("\n");58}5960/** Writes the configuration file (MediaMTX reloads it by itself). Returns true when it changed. */61export function writeConfig(appDir = process.cwd()): boolean {62  fs.mkdirSync(relayDir(), { recursive: true, mode: 0o700 }); fs.mkdirSync(recordDir(), { recursive: true, mode: 0o700 });63  const next = renderConfig(appDir); const file = configPath();64  if (fs.existsSync(file) && fs.readFileSync(file, "utf8") === next) return false;65  fs.writeFileSync(file, next, { mode: 0o600 }); fs.chmodSync(file, 0o600);66  return true;67}68
Files main
Menu

Theme