Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add resilient container repair and processing

Richie McIlroy7cf3f948f861
diff --git a/apps/media-server/bun.lock b/apps/media-server/bun.lock
new file mode 100644
index 000000000..51e241452
--- /dev/null
+++ b/apps/media-server/bun.lock
@@ -0,0 +1,29 @@
+{
+ "lockfileVersion": 1,
+ "configVersion": 1,
+ "workspaces": {
+ "": {
+ "name": "@cap/media-server",
+ "dependencies": {
+ "hono": "^4.7.1",
+ "zod": "^3.24.2",
+ },
+ "devDependencies": {
+ "@types/bun": "latest",
+ },
+ },
+ },
+ "packages": {
+ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.10" } }, "sha512-0+rlrUrOrTSskibryHbvQkDOWRJwJZqZlxrUs1u4oOoTln8+WIXBPmAuCF35SWB2z4Zl3E84Nl/D0P7803nigQ=="],
+
+ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-9wLpoeWuBlcbBpOY3XmzSTG3oscB6xjBEEtn+pYXTfhyXhIxC5FsBer2KTopBlvKEiW9l13po9fq+SJY/5lkhw=="],
+
+ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-tcpfCCl6XWo6nCVnpcVrxQ+9AYN1iqMIzgrSKYMB/fjLtV2eyAVEg7AxQJuCq/26R6HpKWykQXuSOq/21RYcbg=="],
+
+ "hono": ["[email protected]", "", {}, "sha512-3qq+FUBtlTHhtYxbxheZgY8NIFnkkC/MR8u5TTsr7YZ3wixryQ3cCwn3iZbg8p8B88iDBBAYSfZDS75t8MN7Vg=="],
+
+ "undici-types": ["[email protected]", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
+
+ "zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
+ }
+}
diff --git a/apps/media-server/src/lib/ffmpeg-video.ts b/apps/media-server/src/lib/ffmpeg-video.ts
index 8df346688..31e8d9b9c 100644
--- a/apps/media-server/src/lib/ffmpeg-video.ts
+++ b/apps/media-server/src/lib/ffmpeg-video.ts
@@ -216,12 +216,126 @@ export async function downloadVideoToTemp(
}
}
+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 = spawn({
+ cmd: ffmpegArgs,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+
+ let abortCleanup: (() => void) | undefined;
+ if (abortSignal) {
+ abortCleanup = () => {
+ killProcess(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${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,
+ () => killProcess(proc),
+ );
+
+ return repairedFile;
+ } catch (err) {
+ await repairedFile.cleanup();
+ throw err;
+ } finally {
+ if (abortCleanup) {
+ abortSignal?.removeEventListener("abort", abortCleanup);
+ }
+ killProcess(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 [];
+}
+
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),
@@ -235,7 +349,21 @@ export async function processVideo(
: needsVideoTranscode(metadata, opts);
const audioTranscode = remuxOnly ? false : needsAudioTranscode(metadata);
- const ffmpegArgs: string[] = ["ffmpeg", "-threads", "2", "-i", inputPath];
+ const extraInputArgs = resilientFlags
+ ? buildExtraInputFlags(resilientFlags)
+ : [];
+ const extraOutputArgs = resilientFlags
+ ? buildExtraOutputFlags(resilientFlags)
+ : [];
+
+ const ffmpegArgs: string[] = [
+ "ffmpeg",
+ "-threads",
+ "2",
+ ...extraInputArgs,
+ "-i",
+ inputPath,
+ ];
if (videoTranscode) {
ffmpegArgs.push(
@@ -265,6 +393,7 @@ export async function processVideo(
ffmpegArgs.push(
"-movflags",
"+faststart",
+ ...extraOutputArgs,
"-progress",
"pipe:2",
"-y",
diff --git a/apps/media-server/src/lib/ffprobe.ts b/apps/media-server/src/lib/ffprobe.ts
index 5cde045d8..e592d94e5 100644
--- a/apps/media-server/src/lib/ffprobe.ts
+++ b/apps/media-server/src/lib/ffprobe.ts
@@ -190,6 +190,92 @@ export async function probeVideo(videoUrl: string): Promise<VideoMetadata> {
}
}
+export async function probeVideoFile(filePath: string): Promise<VideoMetadata> {
+ if (!canAcceptNewProbeProcess()) {
+ throw new Error("Server is busy, please try again later");
+ }
+
+ activeProbeProcesses++;
+
+ const proc = 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,
+ () => killProcess(proc),
+ );
+
+ return result;
+ } finally {
+ activeProbeProcesses--;
+ killProcess(proc);
+ }
+}
+
export async function checkVideoAccessible(videoUrl: string): Promise<boolean> {
try {
const response = await fetch(videoUrl, {
diff --git a/apps/media-server/src/routes/video.ts b/apps/media-server/src/routes/video.ts
index fc2d99d80..e14e76fe7 100644
--- a/apps/media-server/src/routes/video.ts
+++ b/apps/media-server/src/routes/video.ts
@@ -1,9 +1,11 @@
import { Hono } from "hono";
import { z } from "zod";
+import type { ResilientInputFlags } from "../lib/ffmpeg-video";
import {
downloadVideoToTemp,
generateThumbnail,
processVideo,
+ repairContainer,
uploadFileToS3,
uploadToS3,
} from "../lib/ffmpeg-video";
@@ -11,7 +13,9 @@ import {
canAcceptNewProbeProcess,
getActiveProbeProcessCount,
probeVideo,
+ probeVideoFile,
} from "../lib/ffprobe";
+import type { VideoMetadata } from "../lib/job-manager";
import {
canAcceptNewVideoProcess,
createJob,
@@ -26,6 +30,7 @@ import {
sendWebhook,
updateJob,
} from "../lib/job-manager";
+import type { TempFileHandle } from "../lib/temp-files";
import { cleanupStaleTempFiles } from "../lib/temp-files";
const video = new Hono();
@@ -270,6 +275,194 @@ video.post("/process", async (c) => {
});
});
+function isWebmInput(extension: string | undefined): boolean {
+ if (!extension) return false;
+ const normalized = extension.toLowerCase().replace(/^\./, "");
+ return normalized === "webm";
+}
+
+function needsContainerRepair(metadata: VideoMetadata): boolean {
+ return (
+ metadata.duration <= 0 || metadata.width === 0 || metadata.height === 0
+ );
+}
+
+const RESILIENT_FLAGS: ResilientInputFlags = {
+ errDetectIgnoreErr: true,
+ genPts: true,
+ discardCorrupt: true,
+ maxMuxingQueueSize: 1024,
+};
+
+async function probeWithRepairFallback(
+ inputPath: string,
+ isWebm: boolean,
+ abortSignal: AbortSignal,
+): Promise<{ metadata: VideoMetadata; repairedFile: TempFileHandle | null }> {
+ let probeError: unknown = null;
+ let metadata: VideoMetadata | null = null;
+
+ try {
+ metadata = await probeVideoFile(inputPath);
+ } catch (err) {
+ probeError = err;
+ console.warn(
+ `[probeWithRepairFallback] Initial probe failed: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+
+ if (metadata && !needsContainerRepair(metadata)) {
+ return { metadata, repairedFile: null };
+ }
+
+ if (!isWebm) {
+ if (probeError) throw probeError;
+ if (metadata) return { metadata, repairedFile: null };
+ throw new Error("Probe returned no metadata");
+ }
+
+ console.log(
+ `[probeWithRepairFallback] Attempting container repair (probe ${probeError ? "failed" : `returned duration=${metadata?.duration}`})`,
+ );
+
+ const repairedFile = await repairContainer(inputPath, abortSignal);
+
+ try {
+ const repairedMetadata = await probeVideoFile(repairedFile.path);
+
+ if (repairedMetadata.duration <= 0 && metadata && metadata.duration > 0) {
+ console.log(
+ "[probeWithRepairFallback] Repaired file has worse duration; using original metadata with repaired file",
+ );
+ return { metadata, repairedFile };
+ }
+
+ console.log(
+ `[probeWithRepairFallback] Repair successful: duration=${repairedMetadata.duration}, ${repairedMetadata.width}x${repairedMetadata.height}`,
+ );
+ return { metadata: repairedMetadata, repairedFile };
+ } catch (reProbeErr) {
+ console.error(
+ `[probeWithRepairFallback] Re-probe after repair also failed: ${reProbeErr instanceof Error ? reProbeErr.message : String(reProbeErr)}`,
+ );
+ await repairedFile.cleanup();
+
+ if (metadata) {
+ return { metadata, repairedFile: null };
+ }
+
+ throw probeError ?? reProbeErr;
+ }
+}
+
+async function processWithResilientRetry(
+ inputPath: string,
+ originalInputPath: string,
+ metadata: VideoMetadata,
+ options: z.infer<typeof processSchema>,
+ isWebm: boolean,
+ jobId: string,
+ abortSignal: AbortSignal,
+): Promise<{
+ outputFile: TempFileHandle;
+ lastResortRepairFile: TempFileHandle | null;
+}> {
+ const processOptions = {
+ maxWidth: options.maxWidth,
+ maxHeight: options.maxHeight,
+ crf: options.crf,
+ preset: options.preset,
+ remuxOnly: options.remuxOnly,
+ };
+
+ const onProgress = (progress: number, message: string) => {
+ const scaledProgress = 10 + progress * 0.7;
+ updateJob(jobId, { progress: scaledProgress, message });
+ const currentJob = getJob(jobId);
+ if (currentJob) {
+ sendWebhook(currentJob);
+ }
+ };
+
+ try {
+ const outputFile = await processVideo(
+ inputPath,
+ metadata,
+ processOptions,
+ onProgress,
+ abortSignal,
+ );
+ return { outputFile, lastResortRepairFile: null };
+ } catch (firstError) {
+ if (!isWebm) throw firstError;
+
+ console.warn(
+ `[processWithResilientRetry] First transcode attempt failed: ${firstError instanceof Error ? firstError.message : String(firstError)}`,
+ );
+
+ updateJob(jobId, {
+ progress: 10,
+ message: "Retrying with error recovery...",
+ });
+
+ try {
+ const outputFile = await processVideo(
+ inputPath,
+ metadata,
+ processOptions,
+ onProgress,
+ abortSignal,
+ RESILIENT_FLAGS,
+ );
+ return { outputFile, lastResortRepairFile: null };
+ } catch (retryError) {
+ console.warn(
+ `[processWithResilientRetry] Resilient retry also failed: ${retryError instanceof Error ? retryError.message : String(retryError)}`,
+ );
+ }
+
+ console.log(
+ "[processWithResilientRetry] Attempting last-resort container repair and transcode...",
+ );
+
+ updateJob(jobId, {
+ progress: 10,
+ message: "Attempting full repair...",
+ });
+
+ let lastResortRepairFile: TempFileHandle | null = null;
+ try {
+ lastResortRepairFile = await repairContainer(
+ originalInputPath,
+ abortSignal,
+ );
+
+ let repairedMetadata: VideoMetadata;
+ try {
+ repairedMetadata = await probeVideoFile(lastResortRepairFile.path);
+ } catch {
+ repairedMetadata = metadata;
+ }
+
+ const outputFile = await processVideo(
+ lastResortRepairFile.path,
+ repairedMetadata,
+ processOptions,
+ onProgress,
+ abortSignal,
+ RESILIENT_FLAGS,
+ );
+ return { outputFile, lastResortRepairFile };
+ } catch (lastResortError) {
+ console.error(
+ `[processWithResilientRetry] Last-resort repair+transcode failed: ${lastResortError instanceof Error ? lastResortError.message : String(lastResortError)}`,
+ );
+ await lastResortRepairFile?.cleanup();
+ throw lastResortError;
+ }
+ }
+}
+
async function processVideoAsync(
jobId: string,
videoUrl: string,
@@ -286,6 +479,9 @@ async function processVideoAsync(
const abortController = new AbortController();
updateJob(jobId, { abortController });
+ let repairedTempFile: TempFileHandle | null = null;
+ let lastResortRepairFile: TempFileHandle | null = null;
+
try {
updateJob(jobId, {
phase: "downloading",
@@ -301,6 +497,8 @@ async function processVideoAsync(
);
updateJob(jobId, { inputTempFile });
+ const isWebm = isWebmInput(options.inputExtension);
+
updateJob(jobId, {
phase: "probing",
progress: 5,
@@ -308,33 +506,38 @@ async function processVideoAsync(
});
await sendWebhook(job);
- const metadata = await probeVideo(inputTempFile.path);
+ const { metadata, repairedFile } = await probeWithRepairFallback(
+ inputTempFile.path,
+ isWebm,
+ abortController.signal,
+ );
+ repairedTempFile = repairedFile;
updateJob(jobId, { metadata });
+ const processingInputPath = repairedFile
+ ? repairedFile.path
+ : inputTempFile.path;
+
updateJob(jobId, {
phase: "processing",
progress: 10,
- message: "Processing video...",
+ message: repairedFile
+ ? "Processing repaired video..."
+ : "Processing video...",
});
await sendWebhook(job);
- const outputTempFile = await processVideo(
- inputTempFile.path,
- metadata,
- {
- maxWidth: options.maxWidth,
- maxHeight: options.maxHeight,
- crf: options.crf,
- preset: options.preset,
- remuxOnly: options.remuxOnly,
- },
- (progress, message) => {
- const scaledProgress = 10 + progress * 0.7;
- updateJob(jobId, { progress: scaledProgress, message });
- sendWebhook(getJob(jobId)!);
- },
- abortController.signal,
- );
+ const { outputFile: outputTempFile, lastResortRepairFile: lrrf } =
+ await processWithResilientRetry(
+ processingInputPath,
+ inputTempFile.path,
+ metadata,
+ options,
+ isWebm,
+ jobId,
+ abortController.signal,
+ );
+ lastResortRepairFile = lrrf;
updateJob(jobId, { outputTempFile });
updateJob(jobId, {
@@ -370,6 +573,8 @@ async function processVideoAsync(
await inputTempFile.cleanup();
await outputTempFile.cleanup();
+ await repairedTempFile?.cleanup();
+ await lastResortRepairFile?.cleanup();
setTimeout(() => deleteJob(jobId), 5 * 60 * 1000);
} catch (err) {
@@ -390,6 +595,8 @@ async function processVideoAsync(
await currentJob.inputTempFile?.cleanup();
await currentJob.outputTempFile?.cleanup();
}
+ await repairedTempFile?.cleanup();
+ await lastResortRepairFile?.cleanup();
} finally {
decrementActiveVideoProcesses();
}
diff --git a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/useWebRecorder.ts b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/useWebRecorder.ts
index aa1e0cc35..4775d7d58 100644
--- a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/useWebRecorder.ts
+++ b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/useWebRecorder.ts
@@ -1178,10 +1178,6 @@ export const useWebRecorder = ({
createdVideoId = creationResult.id;
- if (pipeline.mode === "streaming-webm" && creationResult.shareUrl) {
- openShareUrl(creationResult.shareUrl);
- }
-
updatePhase("uploading");
setUploadStatus({
status: "uploadingVideo",