Repository Public
1import { execFile, execFileSync } from "node:child_process";2import fs from "node:fs";3import path from "node:path";4import { get } from "../db";5import { ffmpegPath, ffprobePath } from "../library";6import { relayDir, type Limits } from "./config";7import type { Input } from "./sources";89// TranscodeManager — decides, from a real probe of the input, what FFmpeg has to do. The relay always publishes H.264 +10// AAC (what every browser, phone and television plays): video already in H.264 8-bit is copied untouched; anything else11// is re-encoded, with Apple VideoToolbox when this machine has it. Audio is always normalised to AAC (negligible cost).1213export interface Plan {14 mode: "copy" | "transcode" | "audio";15 video: { index: number; codec: string; width: number | null; height: number | null; copy: boolean } | null;16 audio: { index: number; codec: string } | null;17 /** Finite input (file, recorded playlist): must be read at its natural speed. */18 realtime: boolean; uniform: boolean;19}20/** Protocols FFmpeg may use for a network input: no local files, no exotic transports. */21const NET_PROTOCOLS = "http,https,tcp,tls,crypto";22const netOpts = ["-rw_timeout", "15000000", "-protocol_whitelist", NET_PROTOCOLS];2324interface FfStream { index: number; codec_type: string; codec_name?: string; width?: number; height?: number; pix_fmt?: string; disposition?: { attached_pic?: number } }25interface FfProbe { streams?: FfStream[]; programs?: { program_id: number; streams?: { index: number }[] }[]; format?: { duration?: string } }2627function ffprobe(args: string[], timeoutMs: number): Promise<FfProbe> {28 const bin = ffprobePath(); if (!bin) return Promise.reject(new Error("ffprobe n'est pas installé sur ce nœud"));29 return new Promise((resolve, reject) => {30 execFile(bin, ["-v", "error", ...args, "-show_entries", "stream=index,codec_type,codec_name,width,height,pix_fmt:stream_disposition=attached_pic:program=program_id:program_stream=index:format=duration", "-of", "json"], { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => {31 if (err) return reject(new Error(explainProbe(String(stderr || err.message))));32 try { resolve(JSON.parse(stdout) as FfProbe); } catch { reject(new Error("Réponse illisible de ffprobe")); }33 });34 });35}36export function explainProbe(stderr: string): string {37 if (/SAMPLE-AES|drm|widevine|playready|fairplay|encrypted/i.test(stderr)) return "Flux protégé (DRM) : il n'est pas relayé";38 if (/40[13]|Forbidden|Unauthorized/i.test(stderr)) return "La source refuse l'accès (authentification ou restriction géographique) : rien n'est contourné";39 if (/404|Not Found/i.test(stderr)) return "La source ne publie plus ce flux (404)";40 if (/timed out|Timeout|Connection refused|resolve|Network is unreachable/i.test(stderr)) return "La source ne répond pas";41 return "Flux illisible par FFmpeg";42}4344export function choose(p: FfProbe, input: Input): Plan {45 const streams = p.streams ?? [];46 const videos = streams.filter((s) => s.codec_type === "video" && !s.disposition?.attached_pic && s.codec_name && s.codec_name !== "mjpeg" && s.codec_name !== "png");47 // Best picture up to 1080p; above that only when nothing smaller exists.48 const fit = videos.filter((v) => (v.height ?? 0) <= 1080).sort((a, b) => (b.height ?? 0) - (a.height ?? 0))[0] ?? [...videos].sort((a, b) => (a.height ?? 0) - (b.height ?? 0))[0];49 const audios = streams.filter((s) => s.codec_type === "audio" && s.codec_name);50 const prog = fit ? p.programs?.find((g) => g.streams?.some((s) => s.index === fit.index)) : undefined;51 const audio = (prog ? audios.find((a) => prog.streams?.some((s) => s.index === a.index)) : undefined) ?? audios[0];52 if (!fit && !audio) throw new Error("Aucune piste vidéo ou audio dans ce flux");53 const uniform = input.type === "files" && input.files.length > 1;54 const copy = !!fit && !uniform && fit.codec_name === "h264" && (!fit.pix_fmt || /^yuvj?420p$/.test(fit.pix_fmt));55 return {56 mode: !fit ? "audio" : copy ? "copy" : "transcode",57 video: fit ? { index: fit.index, codec: fit.codec_name!, width: fit.width ?? null, height: fit.height ?? null, copy } : null,58 audio: audio ? { index: audio.index, codec: audio.codec_name! } : null,59 realtime: input.type === "files" || Number(p.format?.duration) > 0, uniform,60 };61}6263export async function probeInput(input: Input): Promise<Plan> {64 if (input.type === "url") return choose(await ffprobe([...netOpts, "-i", input.url], 25_000), input);65 // A home channel made of several files is always re-encoded to one uniform format: the first file gives the picture size.66 return choose(await ffprobe(["-i", input.files[0]], 20_000), input);67}6869let vt: boolean | undefined;70/** Whether this FFmpeg has the Apple hardware H.264 encoder. */71export function hasVideoToolbox(): boolean {72 if (vt !== undefined) return vt;73 try { vt = /h264_videotoolbox/.test(execFileSync(ffmpegPath() ?? "ffmpeg", ["-hide_banner", "-encoders"], { encoding: "utf8", timeout: 8000 })); } catch { vt = false; }74 return vt;75}7677export function ffmpegArgs(relayId: string, input: Input, plan: Plan, target: string, l: Pick<Limits, "videoKbps">): string[] {78 const a = ["-hide_banner", "-loglevel", "warning", "-nostdin"];79 if (input.type === "url") a.push(...netOpts, "-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_delay_max", "5", ...(plan.realtime ? ["-re"] : []), "-i", input.url);80 else if (input.files.length === 1) a.push("-re", "-stream_loop", "-1", "-i", input.files[0]);81 else {82 const dir = path.join(relayDir(), "lists"); fs.mkdirSync(dir, { recursive: true, mode: 0o700 });83 const list = path.join(dir, `${relayId}.txt`);84 fs.writeFileSync(list, input.files.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n") + "\n", { mode: 0o600 });85 a.push("-re", "-stream_loop", "-1", "-f", "concat", "-safe", "0", "-i", list);86 }87 if (plan.video) a.push("-map", plan.uniform ? "0:v:0" : `0:${plan.video.index}`);88 if (plan.audio) a.push("-map", plan.uniform ? "0:a:0?" : `0:${plan.audio.index}`);89 a.push("-sn", "-dn");90 if (plan.video?.copy) a.push("-c:v", "copy");91 else if (plan.video) {92 const h = plan.uniform ? 720 : Math.min(1080, plan.video.height || 1080);93 const rate = Math.min(l.videoKbps, h <= 360 ? 900 : h <= 480 ? 1600 : h <= 720 ? 3500 : 6000);94 const vf = plan.uniform ? "scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2,fps=30,format=yuv420p" : "scale='min(1920,iw)':-2,format=yuv420p";95 a.push(...(hasVideoToolbox() ? ["-c:v", "h264_videotoolbox", "-realtime", "1"] : ["-c:v", "libx264", "-preset", "veryfast", "-tune", "zerolatency"]),96 "-b:v", `${rate}k`, "-maxrate", `${Math.round(rate * 1.3)}k`, "-bufsize", `${rate * 2}k`, "-vf", vf, "-force_key_frames", "expr:gte(t,n_forced*2)");97 }98 if (plan.audio) a.push("-c:a", "aac", "-b:a", "160k", "-ac", "2", "-ar", "48000");99 a.push("-f", "rtsp", "-rtsp_transport", "tcp", target);100 return a;101}102103/** Relays currently re-encoding video. */104export const activeTranscodes = (exceptId?: string) => get<{ n: number }>("SELECT COUNT(*) n FROM relays WHERE mode = 'transcode' AND state IN ('starting','running','reconnecting') AND id != ?", exceptId ?? "")!.n;105