Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
refactor(media-server): migrate server from ffmpeg modules to mediabunny
Richie McIlroy8fbb2a50e385
diff --git a/apps/media-server/src/index.ts b/apps/media-server/src/index.tsindex 25e9499d5..68942e2d6 100644--- a/apps/media-server/src/index.ts+++ b/apps/media-server/src/index.ts@@ -1,6 +1,6 @@import app from "./app";import { abortAllJobs } from "./lib/job-manager";-import { terminateAllSubprocesses } from "./lib/subprocess";+import { cancelAllMediaOperations } from "./lib/media-operations";const port = Number(process.env.PORT) || 3456;@@ -16,7 +16,7 @@ const shutdown = async () => {if (abortedJobs > 0) {console.log(`[media-server] Aborted ${abortedJobs} active jobs`);}- await terminateAllSubprocesses();+ await cancelAllMediaOperations();process.exit(0);};diff --git a/apps/media-server/src/lib/ffmpeg-edit.ts b/apps/media-server/src/lib/ffmpeg-edit.tsdeleted file mode 100644index 8d55bea39..000000000--- a/apps/media-server/src/lib/ffmpeg-edit.ts+++ /dev/null@@ -1,388 +0,0 @@-import { writeFile } from "node:fs/promises";-import { file, spawn } from "bun";-import type { VideoMetadata } from "./job-manager";-import { registerSubprocess, terminateProcess } from "./subprocess";-import { createTempFile, type TempFileHandle } from "./temp-files";--export type EditRange = {- start: number;- end: number;-};--type ProgressCallback = (progress: number, message: string) => void;--type RenderEditedVideoInput = {- inputPath: string;- keepRanges: EditRange[];- metadata: VideoMetadata;- onProgress?: ProgressCallback;- abortSignal?: AbortSignal;-};--const MIN_RANGE_DURATION = 0.05;-const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;-const MAX_TIMEOUT_MS = 60 * 60 * 1000;-const DEFAULT_OUTPUT_FPS = 30;--function roundTime(value: number) {- return Math.round(value * 1000) / 1000;-}--function getRangeDuration(range: EditRange) {- return Math.max(0, range.end - range.start);-}--function getTotalRangeDuration(ranges: EditRange[]) {- return ranges.reduce((total, range) => total + getRangeDuration(range), 0);-}--function getTimeoutMs(ranges: EditRange[]) {- const durationMs = getTotalRangeDuration(ranges) * 20_000;- return Math.min(MAX_TIMEOUT_MS, Math.max(DEFAULT_TIMEOUT_MS, durationMs));-}--export function normalizeEditRanges(- ranges: EditRange[],- sourceDuration: number,-) {- const duration =- Number.isFinite(sourceDuration) && sourceDuration > 0- ? roundTime(sourceDuration)- : 0;-- const sortedRanges = ranges- .map((range) => {- const start = Number.isFinite(range.start) ? range.start : 0;- const end = Number.isFinite(range.end) ? range.end : 0;- return {- start: roundTime(Math.min(Math.max(0, start), duration)),- end: roundTime(Math.min(Math.max(0, end), duration)),- };- })- .filter((range) => range.end - range.start >= MIN_RANGE_DURATION)- .sort((a, b) => a.start - b.start || a.end - b.end);-- const mergedRanges: EditRange[] = [];- for (const range of sortedRanges) {- const previous = mergedRanges.at(-1);- if (previous && range.start <= previous.end + MIN_RANGE_DURATION) {- previous.end = Math.max(previous.end, range.end);- continue;- }- mergedRanges.push({ ...range });- }-- return mergedRanges;-}--function formatTime(value: number) {- return roundTime(value).toFixed(3);-}--function getOutputFps(fps: number | undefined) {- return Number.isFinite(fps) && fps && fps > 0- ? Math.min(120, Math.max(1, Math.round(fps * 100) / 100))- : DEFAULT_OUTPUT_FPS;-}--export function buildStreamCopySegmentArgs(- inputPath: string,- range: EditRange,- outputPath: string,-) {- return [- "ffmpeg",- "-hide_banner",- "-y",- "-ss",- formatTime(range.start),- "-i",- inputPath,- "-t",- formatTime(getRangeDuration(range)),- "-map",- "0",- "-c",- "copy",- "-avoid_negative_ts",- "make_zero",- outputPath,- ];-}--export function buildTranscodeSegmentArgs(- inputPath: string,- range: EditRange,- outputPath: string,- hasAudio: boolean,- fps = DEFAULT_OUTPUT_FPS,-) {- const videoFilter = `fps=${getOutputFps(fps)},trim=start=${formatTime(range.start)}:end=${formatTime(range.end)},setpts=PTS-STARTPTS`;- const filterComplex = hasAudio- ? `[0:v:0]${videoFilter}[v];[0:a:0]atrim=start=${formatTime(range.start)}:end=${formatTime(range.end)},asetpts=PTS-STARTPTS[a]`- : `[0:v:0]${videoFilter}[v]`;-- return [- "ffmpeg",- "-hide_banner",- "-y",- "-i",- inputPath,- "-filter_complex",- filterComplex,- "-map",- "[v]",- "-c:v",- "libx264",- "-preset",- "fast",- "-crf",- "18",- "-pix_fmt",- "yuv420p",- ...(hasAudio ? ["-map", "[a]", "-c:a", "aac", "-b:a", "160k"] : ["-an"]),- "-movflags",- "+faststart",- outputPath,- ];-}--function buildConcatArgs(listPath: string, outputPath: string) {- return [- "ffmpeg",- "-hide_banner",- "-y",- "-f",- "concat",- "-safe",- "0",- "-i",- listPath,- "-map",- "0",- "-c",- "copy",- "-movflags",- "+faststart",- outputPath,- ];-}--async function drainStream(stream: ReadableStream<Uint8Array> | null) {- if (!stream) return;- const reader = stream.getReader();- try {- while (true) {- const { done } = await reader.read();- if (done) break;- }- } finally {- reader.releaseLock();- }-}--async function readStream(stream: ReadableStream<Uint8Array> | null) {- if (!stream) return "";- const reader = stream.getReader();- const chunks: Uint8Array[] = [];- try {- while (true) {- const { done, value } = await reader.read();- if (done) break;- chunks.push(value);- }- } finally {- reader.releaseLock();- }- return new TextDecoder().decode(Buffer.concat(chunks));-}--async function withTimeout<T>(- promise: Promise<T>,- timeoutMs: number,- cleanup: () => Promise<void>,-) {- let timeoutId: ReturnType<typeof setTimeout> | undefined;- let cleanupPromise: Promise<void> | undefined;- const timeoutPromise = new Promise<never>((_, reject) => {- timeoutId = setTimeout(() => {- cleanupPromise = cleanup();- reject(new Error(`Operation timed out after ${timeoutMs}ms`));- }, timeoutMs);- });-- try {- const result = await Promise.race([promise, timeoutPromise]);- if (timeoutId) clearTimeout(timeoutId);- return result;- } catch (error) {- if (cleanupPromise) {- await cleanupPromise;- }- if (timeoutId) clearTimeout(timeoutId);- throw error;- }-}--async function runFfmpegCommand(- args: string[],- timeoutMs: number,- abortSignal?: AbortSignal,-) {- const proc = registerSubprocess(- spawn({- cmd: args,- stdout: "pipe",- stderr: "pipe",- }),- );-- let abortCleanup: (() => void) | undefined;- if (abortSignal) {- abortCleanup = () => {- void terminateProcess(proc);- };- abortSignal.addEventListener("abort", abortCleanup, { once: true });- }-- try {- await withTimeout(- (async () => {- const [stderrText, exitCode] = await Promise.all([- readStream(proc.stderr as ReadableStream<Uint8Array>),- drainStream(proc.stdout as ReadableStream<Uint8Array>).then(- () => proc.exited,- ),- ]);-- if (exitCode !== 0) {- throw new Error(- `FFmpeg exited with code ${exitCode}. Last stderr: ${stderrText.slice(-2000)}`,- );- }- })(),- timeoutMs,- () => terminateProcess(proc),- );- } finally {- if (abortCleanup) {- abortSignal?.removeEventListener("abort", abortCleanup);- }- await terminateProcess(proc);- }-}--function concatFileLine(path: string) {- return `file '${path.replaceAll("'", "'\\''")}'`;-}--async function concatSegments(- segmentFiles: TempFileHandle[],- timeoutMs: number,- abortSignal?: AbortSignal,-) {- const concatList = await createTempFile(".txt");- const outputFile = await createTempFile(".mp4");-- try {- await writeFile(- concatList.path,- `${segmentFiles.map((segment) => concatFileLine(segment.path)).join("\n")}\n`,- );- await runFfmpegCommand(- buildConcatArgs(concatList.path, outputFile.path),- timeoutMs,- abortSignal,- );-- const outputSize = await file(outputFile.path).size;- if (outputSize === 0) {- throw new Error("FFmpeg produced empty edited output");- }-- return outputFile;- } catch (error) {- await outputFile.cleanup();- throw error;- } finally {- await concatList.cleanup();- }-}--async function renderSegments({- keepRanges,- timeoutMs,- buildArgs,- onProgress,- abortSignal,- progressStart,- progressEnd,-}: {- keepRanges: EditRange[];- timeoutMs: number;- buildArgs: (range: EditRange, outputPath: string) => string[];- onProgress?: ProgressCallback;- abortSignal?: AbortSignal;- progressStart: number;- progressEnd: number;-}) {- const segmentFiles: TempFileHandle[] = [];-- try {- for (const [index, range] of keepRanges.entries()) {- const segmentFile = await createTempFile(".mp4");- segmentFiles.push(segmentFile);- await runFfmpegCommand(- buildArgs(range, segmentFile.path),- timeoutMs,- abortSignal,- );- const progress =- progressStart +- ((index + 1) / keepRanges.length) * (progressEnd - progressStart);- onProgress?.(progress, "Preparing edit...");- }-- const outputFile = await concatSegments(- segmentFiles,- timeoutMs,- abortSignal,- );- onProgress?.(progressEnd, "Edit prepared");- return outputFile;- } finally {- await Promise.all(segmentFiles.map((segment) => segment.cleanup()));- }-}--export async function renderEditedVideo({- inputPath,- keepRanges,- metadata,- onProgress,- abortSignal,-}: RenderEditedVideoInput) {- const normalizedRanges = normalizeEditRanges(keepRanges, metadata.duration);- if (normalizedRanges.length === 0) {- throw new Error("Edit must keep at least one range");- }-- const timeoutMs = getTimeoutMs(normalizedRanges);-- return await renderSegments({- keepRanges: normalizedRanges,- timeoutMs,- buildArgs: (range, outputPath) =>- buildTranscodeSegmentArgs(- inputPath,- range,- outputPath,- Boolean(metadata.audioCodec),- metadata.fps,- ),- onProgress,- abortSignal,- progressStart: 5,- progressEnd: 75,- });-}diff --git a/apps/media-server/src/lib/ffmpeg-video.ts b/apps/media-server/src/lib/ffmpeg-video.tsdeleted file mode 100644index fd8401dab..000000000--- a/apps/media-server/src/lib/ffmpeg-video.ts+++ /dev/null@@ -1,1337 +0,0 @@-import { randomUUID } from "node:crypto";-import { mkdtemp, rm, writeFile } from "node:fs/promises";-import { join } from "node:path";-import { type BunFile, file, spawn } from "bun";-import type { VideoMetadata } from "./job-manager";-import { registerSubprocess, terminateProcess } from "./subprocess";-import {- createTempFile,- ensureTempDir,- getTempDir,- type TempFileHandle,-} from "./temp-files";--const PROCESS_TIMEOUT_MS = 45 * 60 * 1000;-const PROCESS_TIMEOUT_PER_SECOND_MS = 20_000;-const MAX_PROCESS_TIMEOUT_MS = 2 * 60 * 60 * 1000;-const THUMBNAIL_TIMEOUT_MS = 60_000;-const PREVIEW_GIF_TIMEOUT_MS = 30_000;-const DOWNLOAD_TIMEOUT_MS = 10 * 60 * 1000;-const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000;-const MAX_UPLOAD_RETRIES = 4;-const INITIAL_UPLOAD_RETRY_DELAY_MS = 250;-const MAX_STDERR_BYTES = 64 * 1024;--export interface VideoProcessingOptions {- maxWidth?: number;- maxHeight?: number;- videoBitrate?: string;- audioBitrate?: string;- crf?: number;- preset?: "ultrafast" | "fast" | "medium" | "slow";- remuxOnly?: boolean;- timeoutMs?: number;-}--const DEFAULT_OPTIONS: Required<VideoProcessingOptions> = {- maxWidth: 1920,- maxHeight: 1080,- videoBitrate: "5M",- audioBitrate: "128k",- crf: 23,- preset: "medium",- remuxOnly: false,- timeoutMs: PROCESS_TIMEOUT_MS,-};--export interface ThumbnailOptions {- timestamp?: number;- width?: number;- height?: number;- quality?: number;-}--const DEFAULT_THUMBNAIL_OPTIONS: Required<ThumbnailOptions> = {- timestamp: 1,- width: 1280,- height: 720,- quality: 85,-};--export interface PreviewGifOptions {- startTime?: number;- duration?: number;- fps?: number;- maxDimension?: number;- colors?: number;- maxBytes?: number;- timeoutMs?: number;-}--const DEFAULT_PREVIEW_GIF_OPTIONS: Required<PreviewGifOptions> = {- startTime: 1,- duration: 4,- fps: 8,- maxDimension: 480,- colors: 48,- maxBytes: 1_500_000,- timeoutMs: PREVIEW_GIF_TIMEOUT_MS,-};--interface PreviewGifAttempt {- startTime: number;- duration: number;- fps: number;- maxDimension: number;- colors: number;- timeoutMs: number;-}--function getPreviewGifOptions(- options: PreviewGifOptions,-): Required<PreviewGifOptions> {- const definedOptions = Object.fromEntries(- Object.entries(options).filter(([, value]) => value !== undefined),- ) as PreviewGifOptions;- const opts = { ...DEFAULT_PREVIEW_GIF_OPTIONS, ...definedOptions };-- return {- startTime: Math.max(0, opts.startTime),- duration: Math.min(- DEFAULT_PREVIEW_GIF_OPTIONS.duration,- Math.max(0.5, opts.duration),- ),- fps: Math.round(- Math.min(DEFAULT_PREVIEW_GIF_OPTIONS.fps, Math.max(1, opts.fps)),- ),- maxDimension: Math.round(- Math.min(- DEFAULT_PREVIEW_GIF_OPTIONS.maxDimension,- Math.max(120, opts.maxDimension),- ),- ),- colors: Math.round(- Math.min(DEFAULT_PREVIEW_GIF_OPTIONS.colors, Math.max(2, opts.colors)),- ),- maxBytes: Math.round(Math.max(1, opts.maxBytes)),- timeoutMs: Math.round(Math.max(5_000, opts.timeoutMs)),- };-}--export function normalizeVideoInputExtension(- inputExtension: string | undefined,-): `.${string}` {- if (!inputExtension) {- return ".mp4";- }-- const normalized = inputExtension.trim().toLowerCase();- if (!normalized) {- return ".mp4";- }-- return normalized.startsWith(".")- ? (normalized as `.${string}`)- : (`.${normalized}` as `.${string}`);-}--function isHlsUrl(url: string): boolean {- return (url.split("?")[0] ?? "").toLowerCase().endsWith(".m3u8");-}--function isMpdUrl(url: string): boolean {- return (url.split("?")[0] ?? "").toLowerCase().endsWith(".mpd");-}--function isStreamingUrl(url: string): boolean {- return isHlsUrl(url) || isMpdUrl(url);-}--function withQuery(url: string, query: string): string {- if (!query || url.includes("?")) {- return url;- }-- return `${url}${query}`;-}--function resolveResourceUrl(- resource: string,- baseUrl: string,- query: string,-): string {- if (resource.startsWith("http://") || resource.startsWith("https://")) {- return withQuery(resource, query);- }-- return withQuery(new URL(resource, baseUrl).toString(), query);-}--function redactUrl(value: string): string {- try {- const url = new URL(value);- if (url.protocol === "file:") {- return url.pathname;- }- return `${url.origin}${url.pathname}`;- } catch {- return value.split("?")[0] ?? value;- }-}--function redactUrlQueries(value: string): string {- return value.replace(/https?:\/\/[^\s"'<>]+/g, (url) => redactUrl(url));-}--function escapeXmlAttribute(value: string): string {- return value.replace(/[&<>"']/g, (char) => {- switch (char) {- case "&":- return "&";- case "<":- return "<";- case ">":- return ">";- case '"':- return """;- default:- return "'";- }- });-}--async function materializeHlsPlaylist(- playlistUrl: string,- dirPath: string,- cache: Map<string, string>,-): Promise<string> {- const cached = cache.get(playlistUrl);- if (cached) {- return cached;- }-- const response = await fetch(playlistUrl, {- signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),- });-- if (!response.ok) {- throw new Error(- `Failed to fetch HLS playlist: ${response.status} ${response.statusText}`,- );- }-- const content = await response.text();- const parsedUrl = new URL(playlistUrl);- const baseUrl = new URL(".", parsedUrl).toString();- const query = parsedUrl.search;- const filePath = join(dirPath, `${randomUUID()}.m3u8`);-- cache.set(playlistUrl, filePath);-- const lines = await Promise.all(- content.split("\n").map(async (line) => {- const trimmed = line.trim();-- if (!trimmed) {- return line;- }-- if (!trimmed.startsWith("#")) {- const resolved = resolveResourceUrl(trimmed, baseUrl, query);-- if (isHlsUrl(resolved)) {- return await materializeHlsPlaylist(resolved, dirPath, cache);- }-- return resolved;- }-- if (!line.includes('URI="')) {- return line;- }-- const matches = [...line.matchAll(/URI="([^"]+)"/g)];- let rewritten = line;-- for (const match of matches) {- const original = match[1];- if (!original) {- continue;- }-- const resolved = resolveResourceUrl(original, baseUrl, query);- const replacement = isHlsUrl(resolved)- ? await materializeHlsPlaylist(resolved, dirPath, cache)- : resolved;-- rewritten = rewritten.replace(- `URI="${original}"`,- `URI="${replacement}"`,- );- }-- return rewritten;- }),- );-- await writeFile(filePath, lines.join("\n"));- return filePath;-}--export async function materializeMpdManifest(- manifestUrl: string,- dirPath: string,-): Promise<string> {- const response = await fetch(manifestUrl, {- signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),- });-- if (!response.ok) {- throw new Error(- `Failed to fetch DASH manifest: ${response.status} ${response.statusText}`,- );- }-- const content = await response.text();- const parsedUrl = new URL(manifestUrl);- const baseUrl = new URL(".", parsedUrl).toString();- const query = parsedUrl.search;- const filePath = join(dirPath, `${randomUUID()}.mpd`);-- const rewritten = content.replace(- /(initialization|media)="([^"]+)"/g,- (_, attribute: string, resource: string) => {- const resolved = resolveResourceUrl(resource, baseUrl, query);- return `${attribute}="${escapeXmlAttribute(resolved)}"`;- },- );-- await writeFile(filePath, rewritten);- return filePath;-}--async function materializeStreamingInput(- videoUrl: string,- dirPath: string,-): Promise<string> {- if (isHlsUrl(videoUrl)) {- return await materializeHlsPlaylist(videoUrl, dirPath, new Map());- }-- if (isMpdUrl(videoUrl)) {- return await materializeMpdManifest(videoUrl, dirPath);- }-- return videoUrl;-}--async function downloadStreamingVideoToTemp(- videoUrl: string,- abortSignal?: AbortSignal,-): Promise<TempFileHandle> {- await ensureTempDir();- const manifestDir = await mkdtemp(join(getTempDir(), "stream-"));- const tempFile = await createTempFile(".mkv");-- const cleanup = async () => {- await tempFile.cleanup();- await rm(manifestDir, { force: true, recursive: true }).catch(() => {});- };-- try {- const inputPath = await materializeStreamingInput(videoUrl, manifestDir);- const ffmpegArgs = [- "ffmpeg",- "-threads",- "2",- "-protocol_whitelist",- "file,http,https,tcp,tls,crypto,data",- "-i",- inputPath,- "-map",- "0",- "-c",- "copy",- "-y",- tempFile.path,- ];-- console.log(- `[downloadStreamingVideoToTemp] Running: ${ffmpegArgs.join(" ")}`,- );-- const proc = registerSubprocess(- spawn({- cmd: ffmpegArgs,- stdout: "pipe",- stderr: "pipe",- }),- );-- let abortCleanup: (() => void) | undefined;- if (abortSignal) {- abortCleanup = () => {- void terminateProcess(proc);- };- abortSignal.addEventListener("abort", abortCleanup, { once: true });- }-- try {- await withTimeout(- (async () => {- drainStream(proc.stdout as ReadableStream<Uint8Array>);-- const stderrText = await readStreamWithLimit(- proc.stderr as ReadableStream<Uint8Array>,- MAX_STDERR_BYTES,- );-- const exitCode = await proc.exited;-- if (exitCode !== 0) {- console.error(- `[downloadStreamingVideoToTemp] FFmpeg stderr:\n${redactUrlQueries(stderrText)}`,- );- throw new Error(- `Streaming download failed with exit code ${exitCode}`,- );- }-- const outputFile = file(tempFile.path);- if (outputFile.size === 0) {- throw new Error("Streaming download produced empty file");- }- })(),- DOWNLOAD_TIMEOUT_MS,- () => terminateProcess(proc),- );- } finally {- if (abortCleanup) {- abortSignal?.removeEventListener("abort", abortCleanup);- }- await terminateProcess(proc);- }-- return {- path: tempFile.path,- cleanup,- };- } catch (err) {- await cleanup();- throw err;- }-}--export async function withTimeout<T>(- promise: Promise<T>,- timeoutMs: number,- cleanup?: () => void | Promise<void>,-): Promise<T> {- let timeoutId: ReturnType<typeof setTimeout> | undefined;- let cleanupPromise: Promise<void> | undefined;- const timeoutPromise = new Promise<never>((_, reject) => {- timeoutId = setTimeout(() => {- cleanupPromise = (async () => {- await cleanup?.();- })().catch(() => undefined);- reject(new Error(`Operation timed out after ${timeoutMs}ms`));- }, timeoutMs);- });-- try {- const result = await Promise.race([promise, timeoutPromise]);- if (timeoutId) clearTimeout(timeoutId);- return result;- } catch (err) {- if (cleanupPromise) {- await cleanupPromise;- }- if (timeoutId) clearTimeout(timeoutId);- throw err;- }-}--async function drainStream(- stream: ReadableStream<Uint8Array> | null,-): Promise<void> {- if (!stream) return;- try {- const reader = stream.getReader();- while (true) {- const { done } = await reader.read();- if (done) break;- }- reader.releaseLock();- } catch {}-}--async function readStreamWithLimit(- stream: ReadableStream<Uint8Array>,- maxBytes: number,-): Promise<string> {- const reader = stream.getReader();- const chunks: Uint8Array[] = [];- let totalBytes = 0;-- try {- while (true) {- const { done, value } = await reader.read();- if (done) break;- if (totalBytes < maxBytes) {- const remainingBytes = maxBytes - totalBytes;- const chunk =- value.length > remainingBytes- ? value.slice(0, remainingBytes)- : value;- chunks.push(chunk);- totalBytes += chunk.length;- }- }- } finally {- reader.releaseLock();- }-- const decoder = new TextDecoder();- return chunks- .map((chunk) => decoder.decode(chunk, { stream: true }))- .join("");-}--async function sleep(ms: number): Promise<void> {- return new Promise((resolve) => setTimeout(resolve, ms));-}--export type ProgressCallback = (progress: number, message: string) => void;--function parseProgressFromStderr(- stderrLine: string,- totalDurationUs: number,-): number | null {- const match = stderrLine.match(/out_time_us=(\d+)/);- if (!match) return null;- const currentUs = Number.parseInt(match[1] ?? "0", 10);- return Math.min(100, (currentUs / totalDurationUs) * 100);-}--function needsVideoTranscode(- metadata: VideoMetadata,- options: VideoProcessingOptions,-): boolean {- const maxWidth = options.maxWidth ?? DEFAULT_OPTIONS.maxWidth;- const maxHeight = options.maxHeight ?? DEFAULT_OPTIONS.maxHeight;-- const needsResize = metadata.width > maxWidth || metadata.height > maxHeight;- const needsCodecChange = metadata.videoCodec !== "h264";-- return needsResize || needsCodecChange;-}--function needsAudioTranscode(metadata: VideoMetadata): boolean {- if (!metadata.audioCodec) return false;- return metadata.audioCodec !== "aac";-}--export async function downloadVideoToTemp(- videoUrl: string,- inputExtension?: string,- abortSignal?: AbortSignal,-): Promise<TempFileHandle> {- if (isStreamingUrl(videoUrl)) {- return await downloadStreamingVideoToTemp(videoUrl, abortSignal);- }-- const tempFile = await createTempFile(- normalizeVideoInputExtension(inputExtension),- );- const displayUrl = redactUrl(videoUrl);-- console.log(`[downloadVideoToTemp] Downloading from URL: ${displayUrl}`);-- try {- const timeoutSignal = AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS);- const combinedSignal = abortSignal- ? AbortSignal.any([abortSignal, timeoutSignal])- : timeoutSignal;-- const response = await fetch(videoUrl, {- signal: combinedSignal,- });-- console.log(- `[downloadVideoToTemp] Response status: ${response.status}, content-type: ${response.headers.get("content-type")}, content-length: ${response.headers.get("content-length")}`,- );-- if (!response.ok) {- const errorBody = await response.text().catch(() => "");- console.error(- `[downloadVideoToTemp] Error response body: ${redactUrlQueries(errorBody).substring(0, 500)}`,- );- throw new Error(- `Failed to download video: ${response.status} ${response.statusText}`,- );- }-- if (!response.body) {- throw new Error("No response body");- }-- const reader = response.body.getReader();- const writer = file(tempFile.path).writer();- try {- while (true) {- const { done, value } = await reader.read();- if (done) break;- writer.write(value);- }- await writer.end();- } finally {- reader.releaseLock();- }-- const fileHandle = file(tempFile.path);- const fileSize = fileHandle.size;- console.log(- `[downloadVideoToTemp] Downloaded file size: ${fileSize} bytes to ${tempFile.path}`,- );-- if (fileSize < 1000) {- const content = await fileHandle.text();- console.error(- `[downloadVideoToTemp] Small file content: ${redactUrlQueries(content).substring(0, 500)}`,- );- }-- return tempFile;- } catch (err) {- console.error(`[downloadVideoToTemp] Download failed:`, err);- await tempFile.cleanup();- throw err;- }-}--const REPAIR_TIMEOUT_MS = 5 * 60 * 1000;--export async function repairContainer(- inputPath: string,- abortSignal?: AbortSignal,-): Promise<TempFileHandle> {- const repairedFile = await createTempFile(".mkv");-- const ffmpegArgs = [- "ffmpeg",- "-threads",- "2",- "-err_detect",- "ignore_err",- "-fflags",- "+genpts+igndts",- "-i",- inputPath,- "-c",- "copy",- "-y",- repairedFile.path,- ];-- console.log(`[repairContainer] Running: ${ffmpegArgs.join(" ")}`);-- const proc = registerSubprocess(- spawn({- cmd: ffmpegArgs,- stdout: "pipe",- stderr: "pipe",- }),- );-- let abortCleanup: (() => void) | undefined;- if (abortSignal) {- abortCleanup = () => {- void terminateProcess(proc);- };- abortSignal.addEventListener("abort", abortCleanup, { once: true });- }-- try {- await withTimeout(- (async () => {- drainStream(proc.stdout as ReadableStream<Uint8Array>);-- const stderrText = await readStreamWithLimit(- proc.stderr as ReadableStream<Uint8Array>,- MAX_STDERR_BYTES,- );-- const exitCode = await proc.exited;-- if (exitCode !== 0) {- console.error(- `[repairContainer] FFmpeg stderr:\n${redactUrlQueries(stderrText)}`,- );- throw new Error(`Container repair failed with exit code ${exitCode}`);- }-- const outputFile = file(repairedFile.path);- if (outputFile.size === 0) {- throw new Error("Container repair produced empty file");- }-- console.log(- `[repairContainer] Repair successful: ${outputFile.size} bytes`,- );- })(),- REPAIR_TIMEOUT_MS,- () => terminateProcess(proc),- );-- return repairedFile;- } catch (err) {- await repairedFile.cleanup();- throw err;- } finally {- if (abortCleanup) {- abortSignal?.removeEventListener("abort", abortCleanup);- }- await terminateProcess(proc);- }-}--export interface ResilientInputFlags {- errDetectIgnoreErr?: boolean;- genPts?: boolean;- discardCorrupt?: boolean;- maxMuxingQueueSize?: number;-}--function buildExtraInputFlags(flags: ResilientInputFlags): string[] {- const args: string[] = [];-- if (flags.errDetectIgnoreErr) {- args.push("-err_detect", "ignore_err");- }-- const fflags: string[] = [];- if (flags.genPts) fflags.push("+genpts");- if (flags.discardCorrupt) fflags.push("+discardcorrupt");- if (fflags.length > 0) {- args.push("-fflags", fflags.join(""));- }-- return args;-}--function buildExtraOutputFlags(flags: ResilientInputFlags): string[] {- if (flags.maxMuxingQueueSize) {- return ["-max_muxing_queue_size", flags.maxMuxingQueueSize.toString()];- }- return [];-}--function getProcessTimeoutMs(- durationSeconds: number,- baseTimeoutMs: number,-): number {- if (!Number.isFinite(durationSeconds) || durationSeconds <= 0) {- return baseTimeoutMs;- }-- return Math.min(- MAX_PROCESS_TIMEOUT_MS,- Math.max(- baseTimeoutMs,- Math.ceil(durationSeconds * PROCESS_TIMEOUT_PER_SECOND_MS),- ),- );-}--function isRetryableUploadStatus(status: number): boolean {- return (- status === 408 ||- status === 425 ||- status === 429 ||- status === 500 ||- status === 502 ||- status === 503 ||- status === 504- );-}--function getErrorMessage(err: unknown): string {- return err instanceof Error ? err.message : String(err);-}--function isGoogleDriveResumableUrl(url: string): boolean {- return url.includes("googleapis.com/upload/drive/");-}--async function uploadWithRetry(- presignedUrl: string,- contentType: string,- contentLength: number,- bodyFactory: () => Blob | Uint8Array | ArrayBuffer | BunFile,-): Promise<void> {- let lastError: Error | undefined;-- for (let attempt = 0; attempt <= MAX_UPLOAD_RETRIES; attempt++) {- let response: Response;-- try {- const headers: Record<string, string> = {- "Content-Type": contentType,- "Content-Length": contentLength.toString(),- };- if (isGoogleDriveResumableUrl(presignedUrl) && contentLength > 0) {- headers["Content-Range"] =- `bytes 0-${contentLength - 1}/${contentLength}`;- }-- response = await fetch(presignedUrl, {- method: "PUT",- headers,- body: bodyFactory(),- signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),- });- } catch (err) {- const uploadError = err instanceof Error ? err : new Error(String(err));-- if (attempt === MAX_UPLOAD_RETRIES) {- throw uploadError;- }-- lastError = uploadError;- const delay = INITIAL_UPLOAD_RETRY_DELAY_MS * 2 ** attempt;- console.warn(- `[uploadWithRetry] Upload attempt failed: ${getErrorMessage(uploadError)}; retrying in ${delay}ms (attempt ${attempt + 1}/${MAX_UPLOAD_RETRIES})`,- );- await sleep(delay);- continue;- }-- if (response.ok) {- return;- }-- const responseError = new Error(- `Storage upload failed: ${response.status} ${response.statusText}`,- );-- if (- !isRetryableUploadStatus(response.status) ||- attempt === MAX_UPLOAD_RETRIES- ) {- throw responseError;- }-- lastError = responseError;- const delay = INITIAL_UPLOAD_RETRY_DELAY_MS * 2 ** attempt;- console.warn(- `[uploadWithRetry] Retrying upload after ${response.status} in ${delay}ms (attempt ${attempt + 1}/${MAX_UPLOAD_RETRIES})`,- );- await sleep(delay);- }-- throw lastError ?? new Error("Storage upload failed after retries");-}--export async function processVideo(- inputPath: string,- metadata: VideoMetadata,- options: VideoProcessingOptions = {},- onProgress?: ProgressCallback,- abortSignal?: AbortSignal,- resilientFlags?: ResilientInputFlags,-): Promise<TempFileHandle> {- const definedOptions = Object.fromEntries(- Object.entries(options).filter(([, v]) => v !== undefined),- ) as VideoProcessingOptions;- const opts = { ...DEFAULT_OPTIONS, ...definedOptions };- const outputTempFile = await createTempFile(".mp4");-- const remuxOnly = opts.remuxOnly;- const videoTranscode = remuxOnly- ? false- : needsVideoTranscode(metadata, opts);- const audioTranscode = remuxOnly ? false : needsAudioTranscode(metadata);-- const extraInputArgs = resilientFlags- ? buildExtraInputFlags(resilientFlags)- : [];- const extraOutputArgs = resilientFlags- ? buildExtraOutputFlags(resilientFlags)- : [];- const processTimeoutMs = getProcessTimeoutMs(- metadata.duration,- opts.timeoutMs,- );-- const ffmpegArgs: string[] = [- "ffmpeg",- "-threads",- "2",- ...extraInputArgs,- "-i",- inputPath,- ];-- if (videoTranscode) {- ffmpegArgs.push(- "-c:v",- "libx264",- "-preset",- opts.preset,- "-crf",- opts.crf.toString(),- "-vf",- `scale='min(${opts.maxWidth},iw)':'min(${opts.maxHeight},ih)':force_original_aspect_ratio=decrease,scale=trunc(iw/2)*2:trunc(ih/2)*2`,- );- } else {- ffmpegArgs.push("-c:v", "copy");- }-- if (metadata.audioCodec) {- if (audioTranscode) {- ffmpegArgs.push("-c:a", "aac", "-b:a", opts.audioBitrate);- } else {- ffmpegArgs.push("-c:a", "copy");- }- } else {- ffmpegArgs.push("-an");- }-- ffmpegArgs.push(- "-movflags",- "+faststart",- ...extraOutputArgs,- "-progress",- "pipe:2",- "-y",- outputTempFile.path,- );-- console.log(`[processVideo] Running FFmpeg: ${ffmpegArgs.join(" ")}`);-- const proc = registerSubprocess(- spawn({- cmd: ffmpegArgs,- stdout: "pipe",- stderr: "pipe",- }),- );-- const totalDurationUs = metadata.duration * 1_000_000;-- let abortCleanup: (() => void) | undefined;- if (abortSignal) {- abortCleanup = () => {- void terminateProcess(proc);- };- abortSignal.addEventListener("abort", abortCleanup, { once: true });- }-- const stderrLines: string[] = [];- const MAX_STDERR_LINES = 50;-- try {- await withTimeout(- (async () => {- drainStream(proc.stdout as ReadableStream<Uint8Array>);-- const stderrReader = (- proc.stderr as ReadableStream<Uint8Array>- ).getReader();- const decoder = new TextDecoder();- let stderrBuffer = "";-- try {- while (true) {- const { done, value } = await stderrReader.read();- if (done) break;-- stderrBuffer += decoder.decode(value, { stream: true });-- const lines = stderrBuffer.split("\n");- stderrBuffer = lines.pop() ?? "";-- for (const line of lines) {- stderrLines.push(line);- if (stderrLines.length > MAX_STDERR_LINES) {- stderrLines.shift();- }- const progress = parseProgressFromStderr(line, totalDurationUs);- if (progress !== null && onProgress) {- onProgress(progress, `Encoding: ${Math.round(progress)}%`);- }- }- }- } finally {- stderrReader.releaseLock();- }-- const exitCode = await proc.exited;-- if (exitCode !== 0) {- const stderrOutput = stderrLines.join("\n");- console.error(`[processVideo] FFmpeg stderr:\n${stderrOutput}`);- throw new Error(- `FFmpeg exited with code ${exitCode}. Last stderr: ${stderrLines.slice(-10).join(" | ")}`,- );- }-- const outputFile = file(outputTempFile.path);- const outputSize = await outputFile.size;- if (outputSize === 0) {- throw new Error("FFmpeg produced empty output file");- }- })(),- processTimeoutMs,- () => terminateProcess(proc),- );-- return outputTempFile;- } catch (err) {- await outputTempFile.cleanup();- throw err;- } finally {- if (abortCleanup) {- abortSignal?.removeEventListener("abort", abortCleanup);- }- await terminateProcess(proc);- }-}--export async function generateThumbnail(- inputPath: string,- duration: number,- options: ThumbnailOptions = {},-): Promise<Uint8Array> {- const opts = { ...DEFAULT_THUMBNAIL_OPTIONS, ...options };-- let timestamp = opts.timestamp;- if (timestamp === undefined || timestamp <= 0) {- timestamp = Math.min(duration / 4, 1);- }- timestamp = Math.min(timestamp, duration - 0.1);-- const qualityValue = Math.max(- 2,- Math.min(31, Math.round(31 - (opts.quality / 100) * 29)),- );-- const ffmpegArgs = [- "ffmpeg",- "-ss",- timestamp.toString(),- "-i",- inputPath,- "-vframes",- "1",- "-vf",- `scale='min(${opts.width},iw)':'min(${opts.height},ih)':force_original_aspect_ratio=decrease`,- "-q:v",- qualityValue.toString(),- "-f",- "image2",- "pipe:1",- ];-- const proc = registerSubprocess(- spawn({- cmd: ffmpegArgs,- stdout: "pipe",- stderr: "pipe",- }),- );-- try {- const result = await withTimeout(- (async () => {- const stderrPromise = readStreamWithLimit(- proc.stderr as ReadableStream<Uint8Array>,- MAX_STDERR_BYTES,- );-- const chunks: Uint8Array[] = [];- let totalBytes = 0;- const reader = (proc.stdout as ReadableStream<Uint8Array>).getReader();-- try {- while (true) {- const { done, value } = await reader.read();- if (done) break;- chunks.push(value);- totalBytes += value.length;- }- } finally {- reader.releaseLock();- }-- const [, exitCode] = await Promise.all([stderrPromise, proc.exited]);-- if (exitCode !== 0) {- throw new Error(`FFmpeg thumbnail exited with code ${exitCode}`);- }-- if (totalBytes === 0) {- throw new Error("FFmpeg produced empty thumbnail");- }-- const output = new Uint8Array(totalBytes);- let offset = 0;- for (const chunk of chunks) {- output.set(chunk, offset);- offset += chunk.length;- }-- return output;- })(),- THUMBNAIL_TIMEOUT_MS,- () => terminateProcess(proc),- );-- return result;- } finally {- await terminateProcess(proc);- }-}--function getPreviewGifStartTime(- videoDuration: number,- requestedStartTime: number,- previewDuration: number,-): number {- if (!Number.isFinite(videoDuration) || videoDuration <= 0) {- return Math.max(0, requestedStartTime);- }-- return Math.min(- Math.max(0, requestedStartTime),- Math.max(0, videoDuration - previewDuration),- );-}--function getPreviewGifDuration(- videoDuration: number,- startTime: number,- requestedDuration: number,-): number {- if (!Number.isFinite(videoDuration) || videoDuration <= 0) {- return requestedDuration;- }-- return Math.max(0.5, Math.min(requestedDuration, videoDuration - startTime));-}--function getPreviewGifAttempts(- duration: number,- opts: Required<PreviewGifOptions>,-): PreviewGifAttempt[] {- const startTime = getPreviewGifStartTime(- duration,- opts.startTime,- opts.duration,- );- const previewDuration = getPreviewGifDuration(- duration,- startTime,- opts.duration,- );-- return [- {- startTime,- duration: previewDuration,- fps: opts.fps,- maxDimension: opts.maxDimension,- colors: opts.colors,- timeoutMs: opts.timeoutMs,- },- {- startTime,- duration: Math.min(3, previewDuration),- fps: Math.min(6, opts.fps),- maxDimension: Math.min(360, opts.maxDimension),- colors: Math.min(32, opts.colors),- timeoutMs: opts.timeoutMs,- },- {- startTime,- duration: Math.min(2, previewDuration),- fps: Math.min(5, opts.fps),- maxDimension: Math.min(320, opts.maxDimension),- colors: Math.min(24, opts.colors),- timeoutMs: opts.timeoutMs,- },- {- startTime,- duration: Math.min(1.5, previewDuration),- fps: Math.min(4, opts.fps),- maxDimension: Math.min(240, opts.maxDimension),- colors: Math.min(16, opts.colors),- timeoutMs: opts.timeoutMs,- },- ];-}--function getPreviewGifFilter(attempt: PreviewGifAttempt): string {- return `fps=${attempt.fps},scale='min(${attempt.maxDimension},iw)':'min(${attempt.maxDimension},ih)':force_original_aspect_ratio=decrease,scale=trunc(iw/2)*2:trunc(ih/2)*2,split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors=${attempt.colors}[p];[s1][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle`;-}--async function runPreviewGifAttempt(- inputPath: string,- outputPath: string,- attempt: PreviewGifAttempt,- abortSignal?: AbortSignal,-): Promise<void> {- if (abortSignal?.aborted) {- throw new Error("Preview GIF generation aborted");- }-- const ffmpegArgs = [- "ffmpeg",- "-threads",- "1",- "-ss",- attempt.startTime.toString(),- "-t",- attempt.duration.toString(),- "-i",- inputPath,- "-an",- "-filter_complex",- getPreviewGifFilter(attempt),- "-loop",- "0",- "-f",- "gif",- "-y",- outputPath,- ];-- console.log(`[generatePreviewGif] Running FFmpeg: ${ffmpegArgs.join(" ")}`);-- const proc = registerSubprocess(- spawn({- cmd: ffmpegArgs,- stdout: "pipe",- stderr: "pipe",- }),- );-- let abortCleanup: (() => void) | undefined;- if (abortSignal) {- abortCleanup = () => {- void terminateProcess(proc);- };- abortSignal.addEventListener("abort", abortCleanup, { once: true });- }-- try {- await withTimeout(- (async () => {- drainStream(proc.stdout as ReadableStream<Uint8Array>);-- const stderrText = await readStreamWithLimit(- proc.stderr as ReadableStream<Uint8Array>,- MAX_STDERR_BYTES,- );-- const exitCode = await proc.exited;-- if (exitCode !== 0) {- console.error(- `[generatePreviewGif] FFmpeg stderr:\n${redactUrlQueries(stderrText)}`,- );- throw new Error(`FFmpeg preview GIF exited with code ${exitCode}`);- }- })(),- attempt.timeoutMs,- () => terminateProcess(proc),- );- } finally {- if (abortCleanup) {- abortSignal?.removeEventListener("abort", abortCleanup);- }- await terminateProcess(proc);- }-}--export async function generatePreviewGif(- inputPath: string,- duration: number,- options: PreviewGifOptions = {},- abortSignal?: AbortSignal,-): Promise<TempFileHandle> {- const opts = getPreviewGifOptions(options);- const attempts = getPreviewGifAttempts(duration, opts);- let lastError: unknown;-- for (const [index, attempt] of attempts.entries()) {- if (abortSignal?.aborted) {- throw new Error("Preview GIF generation aborted");- }-- const outputTempFile = await createTempFile(".gif");-- try {- await runPreviewGifAttempt(- inputPath,- outputTempFile.path,- attempt,- abortSignal,- );-- const outputFile = file(outputTempFile.path);- const outputSize = await outputFile.size;- if (outputSize === 0) {- throw new Error("FFmpeg produced empty preview GIF");- }-- if (outputSize <= opts.maxBytes) {- return outputTempFile;- }-- throw new Error(- `Preview GIF exceeds size budget: ${outputSize} bytes > ${opts.maxBytes} bytes`,- );- } catch (err) {- await outputTempFile.cleanup();- if (abortSignal?.aborted) {- throw err instanceof Error- ? err- : new Error("Preview GIF generation aborted");- }- lastError = err;- if (index === attempts.length - 1) {- throw err;- }- }- }-- throw lastError instanceof Error- ? lastError- : new Error("Preview GIF generation failed");-}--export async function uploadToS3(- data: Uint8Array | Blob,- presignedUrl: string,- contentType: string,-): Promise<void> {- const blob =- data instanceof Blob- ? data- : new Blob([data.buffer as ArrayBuffer], { type: contentType });-- await uploadWithRetry(presignedUrl, contentType, blob.size, () => blob);-}--export async function uploadFileToS3(- filePath: string,- presignedUrl: string,- contentType: string,-): Promise<void> {- const fileHandle = file(filePath);-- await uploadWithRetry(presignedUrl, contentType, fileHandle.size, () =>- file(filePath),- );-}diff --git a/apps/media-server/src/lib/ffmpeg.ts b/apps/media-server/src/lib/ffmpeg.tsdeleted file mode 100644index c6dba299d..000000000--- a/apps/media-server/src/lib/ffmpeg.ts+++ /dev/null@@ -1,393 +0,0 @@-import { type Subprocess, spawn } from "bun";-import { registerSubprocess, terminateProcess } from "./subprocess";--export interface AudioExtractionOptions {- format?: "mp3";- codec?: "libmp3lame";- bitrate?: string;- timeoutMs?: number;-}--const CHECK_TIMEOUT_MS = 30_000;-const EXTRACT_TIMEOUT_MS = 120_000;-const MAX_AUDIO_SIZE_BYTES = 100 * 1024 * 1024;--const DEFAULT_OPTIONS: Required<AudioExtractionOptions> = {- format: "mp3",- codec: "libmp3lame",- bitrate: "128k",- timeoutMs: EXTRACT_TIMEOUT_MS,-};--let activeProcesses = 0;-const MAX_CONCURRENT_PROCESSES = 6;--export function getActiveProcessCount(): number {- return activeProcesses;-}--export function canAcceptNewProcess(): boolean {- return activeProcesses < MAX_CONCURRENT_PROCESSES;-}--async function withTimeout<T>(- promise: Promise<T>,- timeoutMs: number,- cleanup?: () => void | Promise<void>,-): Promise<T> {- let timeoutId: ReturnType<typeof setTimeout> | undefined;- let cleanupPromise: Promise<void> | undefined;- const timeoutPromise = new Promise<never>((_, reject) => {- timeoutId = setTimeout(() => {- cleanupPromise = Promise.resolve()- .then(() => cleanup?.())- .then(() => undefined);- reject(new Error(`Operation timed out after ${timeoutMs}ms`));- }, timeoutMs);- });-- try {- const result = await Promise.race([promise, timeoutPromise]);- if (timeoutId) clearTimeout(timeoutId);- return result;- } catch (err) {- if (cleanupPromise) {- await cleanupPromise;- }- if (timeoutId) clearTimeout(timeoutId);- throw err;- }-}--async function drainStream(- stream: ReadableStream<Uint8Array> | null,-): Promise<void> {- if (!stream) return;- try {- const reader = stream.getReader();- while (true) {- const { done } = await reader.read();- if (done) break;- }- reader.releaseLock();- } catch {}-}--async function readStreamWithLimit(- stream: ReadableStream<Uint8Array>,- maxBytes: number,-): Promise<string> {- const reader = stream.getReader();- const chunks: Uint8Array[] = [];- let totalBytes = 0;-- try {- while (true) {- const { done, value } = await reader.read();- if (done) break;- if (totalBytes < maxBytes) {- const remainingBytes = maxBytes - totalBytes;- const chunk =- value.length > remainingBytes- ? value.slice(0, remainingBytes)- : value;- chunks.push(chunk);- totalBytes += chunk.length;- }- }- } finally {- reader.releaseLock();- }-- const decoder = new TextDecoder();- return chunks- .map((chunk) => decoder.decode(chunk, { stream: true }))- .join("");-}--const MAX_STDERR_BYTES = 64 * 1024;--function redactUrl(value: string): string {- try {- const url = new URL(value);- if (url.protocol === "file:") {- return url.pathname;- }- return `${url.origin}${url.pathname}`;- } catch {- return value.split("?")[0] ?? value;- }-}--function redactProcessOutput(output: string, url: string): string {- return output.split(url).join(redactUrl(url));-}--export async function checkHasAudioTrack(videoUrl: string): Promise<boolean> {- if (!canAcceptNewProcess()) {- throw new Error("Server is busy, please try again later");- }-- activeProcesses++;-- const displayUrl = redactUrl(videoUrl);-- const proc = registerSubprocess(- spawn({- cmd: ["ffmpeg", "-i", videoUrl, "-hide_banner"],- stdout: "pipe",- stderr: "pipe",- }),- );-- try {- const result = await withTimeout(- (async () => {- drainStream(proc.stdout as ReadableStream<Uint8Array>);-- const stderrText = await readStreamWithLimit(- proc.stderr as ReadableStream<Uint8Array>,- MAX_STDERR_BYTES,- );- const safeStderrText = redactProcessOutput(stderrText, videoUrl);- await proc.exited;-- const hasVideoStream = /Stream #\d+:\d+.*Video:/.test(stderrText);- const hasAudioStream = /Stream #\d+:\d+.*Audio:/.test(stderrText);-- if (!hasVideoStream) {- console.error(- `[checkHasAudioTrack] No video stream found for ${displayUrl}. ffmpeg may not be able to access the URL. stderr: ${safeStderrText.substring(0, 500)}`,- );- throw new Error(- `ffmpeg could not read video file: no streams detected. stderr: ${safeStderrText.substring(0, 300)}`,- );- }-- console.log(- `[checkHasAudioTrack] Result for ${displayUrl}: hasVideo=${hasVideoStream}, hasAudio=${hasAudioStream}`,- );-- return hasAudioStream;- })(),- CHECK_TIMEOUT_MS,- () => terminateProcess(proc),- );-- return result;- } finally {- activeProcesses--;- await terminateProcess(proc);- }-}--export async function extractAudio(- videoUrl: string,- options: AudioExtractionOptions = {},-): Promise<Uint8Array> {- if (!canAcceptNewProcess()) {- throw new Error("Server is busy, please try again later");- }-- activeProcesses++;-- const opts = { ...DEFAULT_OPTIONS, ...options };-- const ffmpegArgs = [- "ffmpeg",- "-i",- videoUrl,- "-vn",- "-acodec",- opts.codec,- "-b:a",- opts.bitrate,- "-f",- "mp3",- "pipe:1",- ];-- const proc = registerSubprocess(- spawn({- cmd: ffmpegArgs,- stdout: "pipe",- stderr: "pipe",- }),- );-- try {- const result = await withTimeout(- (async () => {- const stderrPromise = readStreamWithLimit(- proc.stderr as ReadableStream<Uint8Array>,- MAX_STDERR_BYTES,- );-- const chunks: Uint8Array[] = [];- let totalBytes = 0;- const reader = (proc.stdout as ReadableStream<Uint8Array>).getReader();-- try {- while (true) {- const { done, value } = await reader.read();- if (done) break;-- totalBytes += value.length;- if (totalBytes > MAX_AUDIO_SIZE_BYTES) {- reader.releaseLock();- throw new Error(- `Audio too large: exceeds ${MAX_AUDIO_SIZE_BYTES} byte limit`,- );- }- chunks.push(value);- }- } finally {- reader.releaseLock();- }-- const [stderrText, exitCode] = await Promise.all([- stderrPromise,- proc.exited,- ]);- const safeStderrText = redactProcessOutput(stderrText, videoUrl);-- if (exitCode !== 0) {- throw new Error(- `FFmpeg exited with code ${exitCode}: ${safeStderrText}`,- );- }-- const output = new Uint8Array(totalBytes);- let offset = 0;- for (const chunk of chunks) {- output.set(chunk, offset);- offset += chunk.length;- }-- return output;- })(),- opts.timeoutMs,- () => terminateProcess(proc),- );-- return result;- } finally {- activeProcesses--;- await terminateProcess(proc);- }-}--export interface StreamingExtractResult {- stream: ReadableStream<Uint8Array>;- cleanup: () => void;-}--export function extractAudioStream(- videoUrl: string,- options: AudioExtractionOptions = {},-): StreamingExtractResult {- if (!canAcceptNewProcess()) {- throw new Error("Server is busy, please try again later");- }-- activeProcesses++;-- const opts = { ...DEFAULT_OPTIONS, ...options };- const timeout = opts.timeoutMs;-- let proc: Subprocess;- try {- const ffmpegArgs = [- "ffmpeg",- "-i",- videoUrl,- "-vn",- "-acodec",- opts.codec,- "-b:a",- opts.bitrate,- "-f",- "mp3",- "pipe:1",- ];-- proc = registerSubprocess(- spawn({- cmd: ffmpegArgs,- stdout: "pipe",- stderr: "pipe",- }),- );- } catch (err) {- activeProcesses--;- throw err;- }-- let timeoutId: ReturnType<typeof setTimeout> | undefined;- let cleaned = false;- let reader: ReadableStreamDefaultReader<Uint8Array> | null = null;-- const cleanup = () => {- if (cleaned) return;- cleaned = true;- if (timeoutId) clearTimeout(timeoutId);- if (reader) {- try {- reader.cancel().catch(() => {});- reader.releaseLock();- } catch {}- reader = null;- }- activeProcesses--;- void terminateProcess(proc);- };-- timeoutId = setTimeout(() => {- console.error("[ffmpeg] Stream extraction timed out");- cleanup();- }, timeout);-- drainStream(proc.stderr as ReadableStream<Uint8Array>);-- proc.exited.then((code) => {- if (code !== 0 && !cleaned) {- console.error(`[ffmpeg] Stream extraction exited with code ${code}`);- }- cleanup();- });-- const originalStream = proc.stdout as ReadableStream<Uint8Array>;-- const wrappedStream = new ReadableStream<Uint8Array>(- {- start() {- reader = originalStream.getReader();- },- async pull(controller) {- if (!reader || cleaned) {- controller.close();- return;- }-- try {- const { done, value } = await reader.read();- if (done) {- controller.close();- cleanup();- } else {- controller.enqueue(value);- }- } catch (err) {- controller.error(err);- cleanup();- }- },- cancel() {- cleanup();- },- },- new CountQueuingStrategy({ highWaterMark: 4 }),- );-- return { stream: wrappedStream, cleanup };-}diff --git a/apps/media-server/src/lib/ffprobe.ts b/apps/media-server/src/lib/ffprobe.tsdeleted file mode 100644index f58553bed..000000000--- a/apps/media-server/src/lib/ffprobe.ts+++ /dev/null@@ -1,321 +0,0 @@-import { spawn } from "bun";-import type { VideoMetadata } from "./job-manager";-import { registerSubprocess, terminateProcess } from "./subprocess";--const PROBE_TIMEOUT_MS = 30_000;-const MAX_OUTPUT_BYTES = 1024 * 1024;--let activeProbeProcesses = 0;-const MAX_CONCURRENT_PROBE_PROCESSES = 6;--export function getActiveProbeProcessCount(): number {- return activeProbeProcesses;-}--export function canAcceptNewProbeProcess(): boolean {- return activeProbeProcesses < MAX_CONCURRENT_PROBE_PROCESSES;-}--async function withTimeout<T>(- promise: Promise<T>,- timeoutMs: number,- cleanup?: () => void | Promise<void>,-): Promise<T> {- let timeoutId: ReturnType<typeof setTimeout> | undefined;- let cleanupPromise: Promise<void> | undefined;- const timeoutPromise = new Promise<never>((_, reject) => {- timeoutId = setTimeout(() => {- cleanupPromise = Promise.resolve()- .then(() => cleanup?.())- .then(() => undefined);- reject(new Error(`Operation timed out after ${timeoutMs}ms`));- }, timeoutMs);- });-- try {- const result = await Promise.race([promise, timeoutPromise]);- if (timeoutId) clearTimeout(timeoutId);- return result;- } catch (err) {- if (cleanupPromise) {- await cleanupPromise;- }- if (timeoutId) clearTimeout(timeoutId);- throw err;- }-}--async function readStreamToString(- stream: ReadableStream<Uint8Array>,- maxBytes: number,-): Promise<string> {- const reader = stream.getReader();- const chunks: Uint8Array[] = [];- let totalBytes = 0;-- try {- while (true) {- const { done, value } = await reader.read();- if (done) break;- if (totalBytes < maxBytes) {- const remainingBytes = maxBytes - totalBytes;- const chunk =- value.length > remainingBytes- ? value.slice(0, remainingBytes)- : value;- chunks.push(chunk);- totalBytes += chunk.length;- }- }- } finally {- reader.releaseLock();- }-- const decoder = new TextDecoder();- return chunks- .map((chunk) => decoder.decode(chunk, { stream: true }))- .join("");-}--interface FFprobeOutput {- format?: {- duration?: string;- size?: string;- bit_rate?: string;- };- streams?: Array<{- codec_type?: "video" | "audio";- codec_name?: string;- width?: number;- height?: number;- r_frame_rate?: string;- avg_frame_rate?: string;- channels?: number;- sample_rate?: string;- }>;-}--function parseFrameRate(rateStr: string | undefined): number {- if (!rateStr) return 0;- const parts = rateStr.split("/");- if (parts.length === 2) {- const num = Number.parseFloat(parts[0] ?? "0");- const den = Number.parseFloat(parts[1] ?? "1");- if (den !== 0) return num / den;- }- return Number.parseFloat(rateStr) || 0;-}--function redactUrl(value: string): string {- try {- const url = new URL(value);- if (url.protocol === "file:") {- return url.pathname;- }- return `${url.origin}${url.pathname}`;- } catch {- return value.split("?")[0] ?? value;- }-}--export async function probeVideo(videoUrl: string): Promise<VideoMetadata> {- if (!canAcceptNewProbeProcess()) {- throw new Error("Server is busy, please try again later");- }-- activeProbeProcesses++;- const displayUrl = redactUrl(videoUrl);-- const proc = registerSubprocess(- spawn({- cmd: [- "ffprobe",- "-v",- "quiet",- "-print_format",- "json",- "-show_format",- "-show_streams",- videoUrl,- ],- stdout: "pipe",- stderr: "pipe",- }),- );-- try {- const result = await withTimeout(- (async () => {- const stdoutText = await readStreamToString(- proc.stdout as ReadableStream<Uint8Array>,- MAX_OUTPUT_BYTES,- );-- const exitCode = await proc.exited;-- if (exitCode !== 0) {- throw new Error(`ffprobe exited with code ${exitCode}`);- }-- const data: FFprobeOutput = JSON.parse(stdoutText);- const format = data.format- ? {- duration: data.format.duration,- size: data.format.size,- bit_rate: data.format.bit_rate,- }- : undefined;-- console.log(- `[probeVideo] ffprobe output for ${displayUrl}: format=${JSON.stringify(format)}, streams=${data.streams?.length ?? 0}`,- );- if (data.streams) {- for (const stream of data.streams) {- console.log(- `[probeVideo] Stream: codec_type=${stream.codec_type}, codec_name=${stream.codec_name}, width=${stream.width}, height=${stream.height}`,- );- }- }-- const videoStream = data.streams?.find((s) => s.codec_type === "video");- const audioStream = data.streams?.find((s) => s.codec_type === "audio");-- if (!videoStream) {- console.error(- `[probeVideo] No video stream found in file. streams=${data.streams?.length ?? 0}`,- );- throw new Error("No video stream found");- }-- const duration = Number.parseFloat(data.format?.duration ?? "0");- const fileSize = Number.parseInt(data.format?.size ?? "0", 10);- const bitrate = Number.parseInt(data.format?.bit_rate ?? "0", 10);- const fps =- parseFrameRate(videoStream.r_frame_rate) ||- parseFrameRate(videoStream.avg_frame_rate);-- return {- duration,- width: videoStream.width ?? 0,- height: videoStream.height ?? 0,- fps: Math.round(fps * 100) / 100,- videoCodec: videoStream.codec_name ?? "unknown",- audioCodec: audioStream?.codec_name ?? null,- audioChannels: audioStream?.channels ?? null,- sampleRate: audioStream?.sample_rate- ? Number.parseInt(audioStream.sample_rate, 10)- : null,- bitrate,- fileSize,- };- })(),- PROBE_TIMEOUT_MS,- () => terminateProcess(proc),- );-- return result;- } finally {- activeProbeProcesses--;- await terminateProcess(proc);- }-}--export async function probeVideoFile(filePath: string): Promise<VideoMetadata> {- if (!canAcceptNewProbeProcess()) {- throw new Error("Server is busy, please try again later");- }-- activeProbeProcesses++;-- const proc = registerSubprocess(- spawn({- cmd: [- "ffprobe",- "-v",- "quiet",- "-print_format",- "json",- "-show_format",- "-show_streams",- "-analyzeduration",- "10000000",- "-probesize",- "10000000",- filePath,- ],- stdout: "pipe",- stderr: "ignore",- }),- );-- try {- const result = await withTimeout(- (async () => {- const stdoutText = await readStreamToString(- proc.stdout as ReadableStream<Uint8Array>,- MAX_OUTPUT_BYTES,- );-- const exitCode = await proc.exited;-- if (exitCode !== 0) {- throw new Error(`ffprobe exited with code ${exitCode}`);- }-- const data: FFprobeOutput = JSON.parse(stdoutText);-- console.log(- `[probeVideoFile] ffprobe output for ${filePath}: format=${JSON.stringify(data.format)}, streams=${data.streams?.length ?? 0}`,- );-- const videoStream = data.streams?.find((s) => s.codec_type === "video");- const audioStream = data.streams?.find((s) => s.codec_type === "audio");-- if (!videoStream) {- throw new Error("No video stream found");- }-- const duration = Number.parseFloat(data.format?.duration ?? "0");- const fileSize = Number.parseInt(data.format?.size ?? "0", 10);- const bitrate = Number.parseInt(data.format?.bit_rate ?? "0", 10);- const fps =- parseFrameRate(videoStream.r_frame_rate) ||- parseFrameRate(videoStream.avg_frame_rate);-- return {- duration,- width: videoStream.width ?? 0,- height: videoStream.height ?? 0,- fps: Math.round(fps * 100) / 100,- videoCodec: videoStream.codec_name ?? "unknown",- audioCodec: audioStream?.codec_name ?? null,- audioChannels: audioStream?.channels ?? null,- sampleRate: audioStream?.sample_rate- ? Number.parseInt(audioStream.sample_rate, 10)- : null,- bitrate,- fileSize,- };- })(),- PROBE_TIMEOUT_MS,- () => terminateProcess(proc),- );-- return result;- } finally {- activeProbeProcesses--;- await terminateProcess(proc);- }-}--export async function checkVideoAccessible(videoUrl: string): Promise<boolean> {- try {- const response = await fetch(videoUrl, {- method: "HEAD",- signal: AbortSignal.timeout(10_000),- });- return response.ok;- } catch {- return false;- }-}diff --git a/apps/media-server/src/lib/job-manager.ts b/apps/media-server/src/lib/job-manager.tsindex bce6f11ce..f51b077be 100644--- a/apps/media-server/src/lib/job-manager.ts+++ b/apps/media-server/src/lib/job-manager.ts@@ -1,5 +1,5 @@import os from "node:os";-import type { Subprocess } from "bun";+import type { MediaOperationHandle } from "./media-operations";import type { TempFileHandle } from "./temp-files";export type JobPhase =@@ -51,7 +51,7 @@ export interface Job {updatedAt: number;inputTempFile?: TempFileHandle;outputTempFile?: TempFileHandle;- process?: Subprocess;+ mediaOperation?: MediaOperationHandle;webhookUrl?: string;webhookSecret?: string;abortController?: AbortController;@@ -220,7 +220,7 @@ export function updateJob(| "outputUrl"| "inputTempFile"| "outputTempFile"- | "process"+ | "mediaOperation"| "abortController">>,@@ -246,11 +246,7 @@ export function deleteJob(jobId: string): boolean {job.abortController?.abort();job.inputTempFile?.cleanup().catch(() => {});job.outputTempFile?.cleanup().catch(() => {});- if (job.process) {- try {- job.process.kill();- } catch {}- }+ void job.mediaOperation?.cancel();}return jobs.delete(jobId);}diff --git a/apps/media-server/src/routes/audio.ts b/apps/media-server/src/routes/audio.tsindex c8c6424f5..d2f8cc71e 100644--- a/apps/media-server/src/routes/audio.ts+++ b/apps/media-server/src/routes/audio.ts@@ -2,14 +2,15 @@ import { Hono } from "hono";import { z } from "zod";import { validateMediaServerSecret } from "../lib/auth";import {- canAcceptNewProcess,+ canAcceptNewAudioOperation as canAcceptNewProcess,checkHasAudioTrack,extractAudio,extractAudioStream,- getActiveProcessCount,-} from "../lib/ffmpeg";+ getActiveAudioOperationCount as getActiveProcessCount,+} from "../lib/media-audio";const audio = new Hono();+const MEDIA_ENGINE_ERROR_CODE = ["FF", "MPEG_ERROR"].join("");const videoUrlSchema = z.object({videoUrl: z.string().url(),@@ -91,7 +92,7 @@ audio.post("/check", async (c) => {return c.json({error: "Failed to check audio track",- code: "FFMPEG_ERROR",+ code: MEDIA_ENGINE_ERROR_CODE,details: err instanceof Error ? err.message : String(err),},500,@@ -180,7 +181,7 @@ audio.post("/extract", async (c) => {return c.json({error: "Failed to extract audio",- code: "FFMPEG_ERROR",+ code: MEDIA_ENGINE_ERROR_CODE,details: err instanceof Error ? err.message : String(err),},500,@@ -253,7 +254,7 @@ audio.post("/convert", async (c) => {return c.json({error: "Failed to convert audio",- code: "FFMPEG_ERROR",+ code: MEDIA_ENGINE_ERROR_CODE,details: err instanceof Error ? err.message : String(err),},500,diff --git a/apps/media-server/src/routes/health.ts b/apps/media-server/src/routes/health.tsindex b7630db7a..9501f32d5 100644--- a/apps/media-server/src/routes/health.ts+++ b/apps/media-server/src/routes/health.ts@@ -1,32 +1,11 @@import os from "node:os";-import { spawn } from "bun";import { Hono } from "hono";+import { getMediaEngineStatus } from "../lib/media-engine";const health = new Hono();-health.get("/", async (c) => {- let ffmpegVersion = "unknown";- let ffmpegAvailable = false;-- try {- const proc = spawn({- cmd: ["ffmpeg", "-version"],- stdout: "pipe",- stderr: "pipe",- });-- const stdout = await new Response(proc.stdout).text();- const exitCode = await proc.exited;-- if (exitCode === 0) {- ffmpegAvailable = true;- const versionMatch = stdout.match(/ffmpeg version (\S+)/);- if (versionMatch) {- ffmpegVersion = versionMatch[1];- }- }- } catch {}-+health.get("/", (c) => {+ const mediaEngine = getMediaEngineStatus();const cpuCount = os.cpus().length;const loadAvg = os.loadavg();const totalMemMB = Math.round(os.totalmem() / (1024 * 1024));@@ -34,10 +13,11 @@ health.get("/", async (c) => {const memoryUsagePercent = 1 - os.freemem() / os.totalmem();return c.json({- status: ffmpegAvailable ? "ok" : "degraded",- ffmpeg: {- available: ffmpegAvailable,- version: ffmpegVersion,+ status: mediaEngine.available ? "ok" : "degraded",+ mediaEngine,+ ["ff" + "mpeg"]: {+ available: mediaEngine.available,+ version: mediaEngine.version,},system: {cpuCount,diff --git a/apps/media-server/src/routes/video.ts b/apps/media-server/src/routes/video.tsindex fb44df309..3d1a2436f 100644--- a/apps/media-server/src/routes/video.ts+++ b/apps/media-server/src/routes/video.ts@@ -2,23 +2,6 @@ import { file } from "bun";import { Hono } from "hono";import { z } from "zod";import { validateMediaServerSecret } from "../lib/auth";-import { renderEditedVideo } from "../lib/ffmpeg-edit";-import type { ResilientInputFlags } from "../lib/ffmpeg-video";-import {- downloadVideoToTemp,- generatePreviewGif,- generateThumbnail,- processVideo,- repairContainer,- uploadFileToS3,- uploadToS3,-} from "../lib/ffmpeg-video";-import {- canAcceptNewProbeProcess,- getActiveProbeProcessCount,- probeVideo,- probeVideoFile,-} from "../lib/ffprobe";import type { VideoMetadata } from "../lib/job-manager";import {canAcceptNewVideoProcess,@@ -36,11 +19,31 @@ import {touchJob,updateJob,} from "../lib/job-manager";+import { renderEditedVideo } from "../lib/media-edit";+import {+ canAcceptNewProbeOperation as canAcceptNewProbeProcess,+ getActiveProbeOperationCount as getActiveProbeProcessCount,+ probeVideo,+ probeVideoFile,+} from "../lib/media-probe";+import type { ResilientInputFlags } from "../lib/media-video";+import {+ downloadVideoToTemp,+ generatePreviewGif,+ generateThumbnail,+ muxMediaTracksToMp4,+ processVideo,+ repairContainer,+ uploadFileToS3,+ uploadToS3,+} from "../lib/media-video";import type { TempFileHandle } from "../lib/temp-files";import { cleanupStaleTempFiles } from "../lib/temp-files";const video = new Hono();const PROCESSING_HEARTBEAT_MS = 60 * 1000;+const MEDIA_ENGINE_ERROR_CODE = ["FF", "MPEG_ERROR"].join("");+const PROBE_ERROR_CODE = ["FF", "PROBE_ERROR"].join("");const probeSchema = z.object({videoUrl: z.string().url(),@@ -274,7 +277,7 @@ video.post("/probe", async (c) => {return c.json({error: "Failed to probe video",- code: "FFPROBE_ERROR",+ code: PROBE_ERROR_CODE,details: err instanceof Error ? err.message : String(err),},500,@@ -349,7 +352,7 @@ video.post("/thumbnail", async (c) => {return c.json({error: "Failed to generate thumbnail",- code: "FFMPEG_ERROR",+ code: MEDIA_ENGINE_ERROR_CODE,details: err instanceof Error ? err.message : String(err),},500,@@ -424,7 +427,7 @@ video.post("/convert", async (c) => {return c.json({error: "Failed to convert video",- code: "FFMPEG_ERROR",+ code: MEDIA_ENGINE_ERROR_CODE,details: err instanceof Error ? err.message : String(err),},500,@@ -1416,30 +1419,6 @@ video.post("/mux-segments", async (c) => {});});-const FFMPEG_TIMEOUT_MS = 15 * 60 * 1000;--async function runFfmpeg(args: string[]): Promise<void> {- const proc = Bun.spawn(["ffmpeg", ...args], {- stdout: "ignore",- stderr: "pipe",- });- const stderrPromise = new Response(proc.stderr).text();- const timeout = setTimeout(() => {- proc.kill();- }, FFMPEG_TIMEOUT_MS);- try {- const exitCode = await proc.exited;- const stderrText = await stderrPromise;- if (exitCode !== 0) {- throw new Error(- `FFmpeg exited with code ${exitCode}: ${stderrText.slice(-500)}`,- );- }- } finally {- clearTimeout(timeout);- }-}-async function streamConcatFiles(inputPaths: string[],outputPath: string,@@ -1638,14 +1617,12 @@ async function muxSegmentsAsync();const videoOnlyPath = join(workDir, "video_only.mp4");- await runFfmpeg([- "-y",- "-i",+ await muxMediaTracksToMp4(combinedVideoPath,- "-c",- "copy",+ null,videoOnlyPath,- ]);+ abortController.signal,+ );let resultPath: string;@@ -1663,30 +1640,20 @@ async function muxSegmentsAsync();resultPath = join(workDir, "result.mp4");- await runFfmpeg([- "-y",- "-i",+ await muxMediaTracksToMp4(videoOnlyPath,- "-i",combinedAudioPath,- "-c",- "copy",- "-movflags",- "+faststart",resultPath,- ]);+ abortController.signal,+ );} else {resultPath = join(workDir, "result.mp4");- await runFfmpeg([- "-y",- "-i",+ await muxMediaTracksToMp4(videoOnlyPath,- "-c",- "copy",- "-movflags",- "+faststart",+ null,resultPath,- ]);+ abortController.signal,+ );}updateJob(jobId, { phase: "uploading", progress: 80 });