Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: preserve playback through media processing failures
Richie McIlroye3a23fdc69a1
diff --git a/.github/workflows/recording-reliability.yml b/.github/workflows/recording-reliability.ymlindex 4d0039ea7..9196e58fb 100644--- a/.github/workflows/recording-reliability.yml+++ b/.github/workflows/recording-reliability.yml@@ -44,4 +44,7 @@ jobs:__tests__/unit/desktop-recording-*.test.ts \__tests__/unit/desktop-segments-*.test.ts \__tests__/unit/finalize-desktop-recording.test.ts \- __tests__/unit/media-server-progress.test.ts+ __tests__/unit/media-server-progress.test.ts \+ __tests__/unit/media-processing-budget.test.ts \+ __tests__/unit/playback-source.test.ts \+ __tests__/unit/upload-progress-playback.test.tsdiff --git a/apps/media-server/src/__tests__/lib/media-routes-real-world.integration.test.ts b/apps/media-server/src/__tests__/lib/media-routes-real-world.integration.test.tsindex d38226c64..af4042022 100644--- a/apps/media-server/src/__tests__/lib/media-routes-real-world.integration.test.ts+++ b/apps/media-server/src/__tests__/lib/media-routes-real-world.integration.test.ts@@ -19,6 +19,7 @@ import type appType from "../../app";import * as containerCpu from "../../lib/container-cpu";import * as containerMemory from "../../lib/container-memory";import type { Job, JobProgress } from "../../lib/job-manager";+import { withTimeout } from "../../lib/media-common";import { probeVideoFile } from "../../lib/media-probe";import * as mediaVideo from "../../lib/media-video";import * as recordingVerification from "../../lib/recording-verification";@@ -40,6 +41,9 @@ let baseUrl = "";let tempDir = "";const uploadedArtifacts = new Map<string, Uint8Array>();+const uploadFailures = new Map<string, number>();+const uploadRequests: string[] = [];+const fixtureReads: string[] = [];const recordingSources = new Map<string, Uint8Array>();const sourceReads: {path: string;@@ -364,6 +368,7 @@ beforeAll(async () => {: null;if (fixturePath) {+ if (request.method === "GET") fixtureReads.push(url.pathname);const fixture = Bun.file(fixturePath);const headers = {"Content-Type": "video/mp4",@@ -408,6 +413,11 @@ beforeAll(async () => {}if (request.method === "PUT" && url.pathname.startsWith("/uploads/")) {+ uploadRequests.push(url.pathname);+ const failureStatus = uploadFailures.get(url.pathname);+ if (failureStatus) {+ return new Response("Storage unavailable", { status: failureStatus });+ }uploadConditions.push(request.headers.get("if-none-match"));if (request.headers.get("if-none-match") === "*" &&@@ -451,6 +461,9 @@ beforeEach(() => {pressure: 0.0625,});uploadedArtifacts.clear();+ uploadFailures.clear();+ uploadRequests.length = 0;+ fixtureReads.length = 0;transientFixtureFailures = 0;permanentFixtureFailures = 0;slowFixtureCancellations = 0;@@ -950,6 +963,128 @@ describe("media routes real-world integration tests", () => {}}, 90000);+ test.each([403, 503])(+ "keeps a playable processed video when thumbnail storage returns %s",+ async (status) => {+ uploadFailures.set("/uploads/optional-thumbnail.jpg", status);+ const response = await app.fetch(+ mediaPostRequest("/video/process", {+ videoId: "optional-thumbnail",+ userId: "real-process-user",+ videoUrl: fixtureUrl(),+ outputPresignedUrl: uploadUrl("optional-thumbnail.mp4"),+ thumbnailPresignedUrl: uploadUrl("optional-thumbnail.jpg"),+ inputExtension: ".mp4",+ }),+ );+ expect(response.status).toBe(200);+ const { jobId } = (await response.json()) as { jobId: string };+ try {+ const job = await waitForTerminalJob(jobId);+ expect(job.phase).toBe("complete");+ expect(job.error).toBeUndefined();+ expect(fixtureReads).toEqual(["/fixtures/test-with-audio.mp4"]);+ expect(uploadRequests.filter((path) => path.endsWith(".mp4"))).toEqual([+ "/uploads/optional-thumbnail.mp4",+ ]);+ expect(+ uploadRequests.filter((path) => path.endsWith(".jpg")),+ ).toHaveLength(status === 403 ? 1 : 5);+ const output = join(tempDir, `optional-thumbnail-${status}.mp4`);+ await writeFile(+ output,+ uploadedBytes("/uploads/optional-thumbnail.mp4"),+ );+ execFileSync("ffmpeg", [+ "-v",+ "error",+ "-xerror",+ "-i",+ output,+ "-f",+ "null",+ "-",+ ]);+ const metadata = await probeVideoFile(output);+ expect(metadata.videoCodec).toBe("h264");+ expect(metadata.audioCodec).toBe("aac");+ } finally {+ deleteJob(jobId);+ }+ },+ 30_000,+ );++ test("still fails processing when the video output cannot be uploaded", async () => {+ uploadFailures.set("/uploads/failed-output.mp4", 403);+ const response = await app.fetch(+ mediaPostRequest("/video/process", {+ videoId: "failed-output",+ userId: "real-process-user",+ videoUrl: fixtureUrl(),+ outputPresignedUrl: uploadUrl("failed-output.mp4"),+ thumbnailPresignedUrl: uploadUrl("failed-output.jpg"),+ inputExtension: ".mp4",+ }),+ );+ expect(response.status).toBe(200);+ const { jobId } = (await response.json()) as { jobId: string };+ try {+ const job = await waitForTerminalJob(jobId);+ expect(job.phase).toBe("error");+ expect(job.error).toContain("403");+ expect(uploadRequests).toEqual(["/uploads/failed-output.mp4"]);+ expect(uploadedArtifacts.size).toBe(0);+ } finally {+ deleteJob(jobId);+ }+ }, 30_000);++ test("does not complete a cancelled job during thumbnail upload", async () => {+ let started: (() => void) | undefined;+ const ready = new Promise<void>((resolve) => {+ started = resolve;+ });+ const upload = spyOn(mediaVideo, "uploadToS3").mockImplementation(+ async (_data, _url, _contentType, signal) => {+ if (!signal) throw new Error("Missing thumbnail upload signal");+ await new Promise<void>((_resolve, reject) => {+ signal.addEventListener("abort", () => reject(signal.reason), {+ once: true,+ });+ started?.();+ });+ },+ );+ let jobId: string | undefined;+ try {+ const response = await app.fetch(+ mediaPostRequest("/video/process", {+ videoId: "cancelled-thumbnail",+ userId: "real-process-user",+ videoUrl: fixtureUrl(),+ outputPresignedUrl: uploadUrl("cancelled-thumbnail.mp4"),+ thumbnailPresignedUrl: uploadUrl("cancelled-thumbnail.jpg"),+ inputExtension: ".mp4",+ }),+ );+ expect(response.status).toBe(200);+ jobId = ((await response.json()) as { jobId: string }).jobId;+ await withTimeout(ready, 10_000);+ getJob(jobId)?.abortController?.abort(new Error("Worker cancelled"));+ const job = await waitForTerminalJob(jobId);+ expect(job.phase).toBe("error");+ expect(job.error).toBe("Worker cancelled");+ expect(upload).toHaveBeenCalledTimes(1);+ } finally {+ if (jobId) {+ getJob(jobId)?.abortController?.abort();+ deleteJob(jobId);+ }+ upload.mockRestore();+ }+ }, 15_000);+test("retries transient segment downloads and completes a real mux job", async () => {const response = await app.fetch(mediaPostRequest("/video/mux-segments", {diff --git a/apps/media-server/src/__tests__/lib/media-video.integration.test.ts b/apps/media-server/src/__tests__/lib/media-video.integration.test.tsindex d8f4f798b..1b02af4b3 100644--- a/apps/media-server/src/__tests__/lib/media-video.integration.test.ts+++ b/apps/media-server/src/__tests__/lib/media-video.integration.test.ts@@ -302,6 +302,33 @@ describe("recording upload cancellation", () => {});describe("generateThumbnail integration tests", () => {+ test("uses the first frame when a sparse video has no frame after the thumbnail seek", async () => {+ const directory = mkdtempSync(join(tmpdir(), "cap-sparse-thumbnail-"));+ const input = join(directory, "single-frame.mp4");+ try {+ execFileSync("ffmpeg", [+ "-v",+ "error",+ "-f",+ "lavfi",+ "-i",+ "color=c=blue:s=160x120:r=1/2",+ "-frames:v",+ "1",+ "-c:v",+ "libx264",+ "-pix_fmt",+ "yuv420p",+ input,+ ]);+ const thumbnail = await generateThumbnail(input, 2);+ expect(thumbnail.length).toBeGreaterThan(0);+ expect([...thumbnail.subarray(0, 2)]).toEqual([0xff, 0xd8]);+ } finally {+ rmSync(directory, { recursive: true, force: true });+ }+ });+test("joins an in-flight thumbnail decoder when its worker is cancelled", async () => {let ready: (() => void) | undefined;const started = new Promise<void>((resolve) => {diff --git a/apps/media-server/src/lib/media-video.ts b/apps/media-server/src/lib/media-video.tsindex d6737224e..c418d1a84 100644--- a/apps/media-server/src/lib/media-video.ts+++ b/apps/media-server/src/lib/media-video.ts@@ -1,12 +1,13 @@import { createHash, randomUUID } from "node:crypto";import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises";-import { join } from "node:path";+import { isAbsolute, join } from "node:path";import { setTimeout as sleep } from "node:timers/promises";import { type BunFile, file, spawn } from "bun";import { uploadDriveResumable } from "./drive-resumable-upload";import type { VideoMetadata } from "./job-manager";import {DOWNLOAD_TIMEOUT_MS,+ normalizeLocalPath,PROCESS_TIMEOUT_MS,type ProgressCallback,UPLOAD_TIMEOUT_MS,@@ -1670,6 +1671,8 @@ function getThumbnailTimestamp(return Math.min(Math.max(0, timestamp), Math.max(0, duration - 0.1));}+class EmptyThumbnailError extends Error {}+export async function generateThumbnail(inputPath: string,duration: number,@@ -1679,12 +1682,53 @@ export async function generateThumbnail(abortSignal?.throwIfAborted();const opts = { ...DEFAULT_THUMBNAIL_OPTIONS, ...options };const timestamp = getThumbnailTimestamp(duration, opts.timestamp);+ const deadline = performance.now() + THUMBNAIL_TIMEOUT_MS;+ try {+ return await generateThumbnailFrame(+ inputPath,+ opts,+ timestamp,+ THUMBNAIL_TIMEOUT_MS,+ abortSignal,+ );+ } catch (error) {+ abortSignal?.throwIfAborted();+ const remainingMs = deadline - performance.now();+ if (+ !(error instanceof EmptyThumbnailError) ||+ !isAbsolute(normalizeLocalPath(inputPath)) ||+ timestamp <= 0 ||+ remainingMs <= 0+ ) {+ throw error;+ }+ return await generateThumbnailFrame(+ inputPath,+ opts,+ 0,+ remainingMs,+ abortSignal,+ true,+ );+ }+}++async function generateThumbnailFrame(+ inputPath: string,+ opts: Required<ThumbnailOptions>,+ timestamp: number,+ timeoutMs: number,+ abortSignal?: AbortSignal,+ localOnly = false,+): Promise<Uint8Array> {+ abortSignal?.throwIfAborted();const qualityValue = Math.max(2,Math.min(31, Math.round(31 - (opts.quality / 100) * 29)),);const ffmpegArgs = ["ffmpeg",+ ...(localOnly ? ["-protocol_whitelist", "file,pipe"] : []),"-ss",timestamp.toString(),"-i",@@ -1746,12 +1790,16 @@ export async function generateThumbnail(]);abortSignal?.throwIfAborted();+ if (totalBytes === 0) {+ throw new EmptyThumbnailError(+ exitCode === 0+ ? "FFmpeg produced empty thumbnail"+ : `FFmpeg thumbnail exited with code ${exitCode}`,+ );+ }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;@@ -1762,7 +1810,7 @@ export async function generateThumbnail(return output;})(),- THUMBNAIL_TIMEOUT_MS,+ timeoutMs,stop,);} catch (error) {diff --git a/apps/media-server/src/routes/video.ts b/apps/media-server/src/routes/video.tsindex 334b3d27b..854d5fc99 100644--- a/apps/media-server/src/routes/video.ts+++ b/apps/media-server/src/routes/video.ts@@ -1352,7 +1352,12 @@ async function processVideoAsync(});await sendWebhook(job);- await uploadFileToS3(outputTempFile.path, outputPresignedUrl, "video/mp4");+ await uploadFileToS3(+ outputTempFile.path,+ outputPresignedUrl,+ "video/mp4",+ abortController.signal,+ );if (thumbnailPresignedUrl || previewGifPresignedUrl) {updateJob(jobId, {@@ -1367,8 +1372,23 @@ async function processVideoAsync(const thumbnailData = await generateThumbnail(outputTempFile.path,metadata.duration,+ {},+ abortController.signal,);- await uploadToS3(thumbnailData, thumbnailPresignedUrl, "image/jpeg");+ try {+ await uploadToS3(+ thumbnailData,+ thumbnailPresignedUrl,+ "image/jpeg",+ abortController.signal,+ );+ } catch (error) {+ abortController.signal.throwIfAborted();+ console.warn(+ `[video/process] Thumbnail upload failed for ${jobId}:`,+ error,+ );+ }}await generateAndUploadPreviewGif(diff --git a/apps/web/__tests__/unit/playback-source.test.ts b/apps/web/__tests__/unit/playback-source.test.tsindex 2191ae1a6..86736b64c 100644--- a/apps/web/__tests__/unit/playback-source.test.ts+++ b/apps/web/__tests__/unit/playback-source.test.ts@@ -101,6 +101,73 @@ describe("canPlayRawContentType", () => {});describe("resolvePlaybackSource", () => {+ it.each([200, 206, 404])(+ "closes the probe body after reading HTTP %s headers",+ async (status) => {+ const cancel = vi.fn();+ const fetchImpl = vi+ .fn<typeof fetch>()+ .mockResolvedValue(+ new Response(new ReadableStream({ cancel }), { status }),+ );+ const result = await resolvePlaybackSource({+ videoSrc: "/api/playlist?videoType=mp4",+ fetchImpl,+ });+ expect(cancel).toHaveBeenCalledTimes(1);+ expect(fetchImpl).toHaveBeenCalledTimes(1);+ if (status === 404) expect(result).toBeNull();+ else expect(result?.type).toBe("mp4");+ },+ );++ it("keeps a playable source when closing its probe body fails", async () => {+ const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(+ new Response(+ new ReadableStream({+ cancel: () => Promise.reject(new Error("Connection closed")),+ }),+ { status: 206 },+ ),+ );+ const result = await resolvePlaybackSource({+ videoSrc: "https://v.cap.so/result.mp4",+ fetchImpl,+ });+ expect(result?.type).toBe("mp4");+ expect(fetchImpl).toHaveBeenCalledTimes(1);+ });++ it("closes both probes while retaining the raw preview content type", async () => {+ const cancelMp4 = vi.fn();+ const cancelRaw = vi.fn();+ const canPlayType = vi.fn().mockReturnValue("probably");+ const fetchImpl = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(+ new Response(new ReadableStream({ cancel: cancelMp4 }), {+ status: 404,+ }),+ )+ .mockResolvedValueOnce(+ new Response(new ReadableStream({ cancel: cancelRaw }), {+ status: 206,+ headers: { "Content-Type": "video/webm;codecs=vp9,opus" },+ }),+ );+ const result = await resolvePlaybackSource({+ videoSrc: "/api/playlist?videoType=mp4",+ rawFallbackSrc: "/api/playlist?videoType=raw-preview",+ fetchImpl,+ createVideoElement: () => ({ canPlayType }),+ });+ expect(result?.type).toBe("raw");+ expect(cancelMp4).toHaveBeenCalledTimes(1);+ expect(cancelRaw).toHaveBeenCalledTimes(1);+ expect(canPlayType).toHaveBeenCalledWith("video/webm;codecs=vp9,opus");+ expect(fetchImpl).toHaveBeenCalledTimes(2);+ });+it("returns the MP4 source immediately when it is available", async () => {const fetchImpl = vi.fn<typeof fetch>().mockResolvedValueOnce(createResponse("https://bucket.s3.amazonaws.com/result.mp4", {@@ -208,6 +275,38 @@ describe("resolvePlaybackSource", () => {});});+ it.each([206, 404])(+ "rechecks the processed MP4 once when a preferred raw upload is gone (HTTP %s)",+ async (status) => {+ const fetchImpl = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(+ createResponse("/raw-upload.webm", { status: 404 }),+ )+ .mockResolvedValueOnce(+ createResponse("https://v.cap.so/result.mp4", {+ status,+ redirected: true,+ }),+ );+ const result = await resolvePlaybackSource({+ videoSrc: "/api/playlist?videoType=mp4",+ rawFallbackSrc: "/api/playlist?videoType=raw-preview",+ preferredSource: "raw",+ fetchImpl,+ now: () => 275,+ });+ expect(fetchImpl).toHaveBeenCalledTimes(2);+ expect(fetchImpl).toHaveBeenNthCalledWith(+ 2,+ "/api/playlist?videoType=mp4&_t=275",+ { headers: { range: "bytes=0-0" } },+ );+ if (status === 206) expect(result?.type).toBe("mp4");+ else expect(result).toBeNull();+ },+ );+it("rejects raw webm previews when the browser cannot play them", async () => {const fetchImpl = vi.fn<typeof fetch>()diff --git a/apps/web/app/s/[videoId]/_components/playback-source.ts b/apps/web/app/s/[videoId]/_components/playback-source.tsindex d02c1bb61..96a858b76 100644--- a/apps/web/app/s/[videoId]/_components/playback-source.ts+++ b/apps/web/app/s/[videoId]/_components/playback-source.ts@@ -64,6 +64,7 @@ async function probePlaybackSource(const response = await fetchImpl(requestUrl, {headers: { range: "bytes=0-0" },});+ void response.body?.cancel().catch(() => {});if (!isPlayableProbeResponse(response)) {return {@@ -166,7 +167,8 @@ export async function resolvePlaybackSource({};if (preferredSource === "raw") {- return await resolveRaw();+ const rawSource = await resolveRaw();+ if (rawSource) return rawSource;}const mp4Result = await probePlaybackSource(videoSrc, fetchImpl, now);@@ -189,5 +191,5 @@ export async function resolvePlaybackSource({};}- return await resolveRaw();+ return preferredSource === "raw" ? null : await resolveRaw();}