Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

test(media-server): add mediabunny library integration tests

Richie McIlroy5c5e36b23ace
diff --git a/apps/media-server/src/__tests__/lib/media-audio.integration.test.ts b/apps/media-server/src/__tests__/lib/media-audio.integration.test.ts
new file mode 100644
index 000000000..4101df813
--- /dev/null
+++ b/apps/media-server/src/__tests__/lib/media-audio.integration.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, test } from "bun:test";
+import { join } from "node:path";
+import {
+ checkHasAudioTrack,
+ extractAudio,
+ extractAudioStream,
+ getActiveProcessCount,
+} from "../../lib/media-audio";
+
+const FIXTURES_DIR = join(import.meta.dir, "..", "fixtures");
+const TEST_VIDEO_WITH_AUDIO = `file://${join(FIXTURES_DIR, "test-with-audio.mp4")}`;
+const TEST_VIDEO_NO_AUDIO = `file://${join(FIXTURES_DIR, "test-no-audio.mp4")}`;
+
+async function readStream(stream: ReadableStream<Uint8Array>) {
+ const reader = stream.getReader();
+ const chunks: Uint8Array[] = [];
+ let totalBytes = 0;
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ totalBytes += value.length;
+ }
+ } finally {
+ reader.releaseLock();
+ }
+
+ const output = new Uint8Array(totalBytes);
+ let offset = 0;
+ for (const chunk of chunks) {
+ output.set(chunk, offset);
+ offset += chunk.length;
+ }
+
+ return output;
+}
+
+async function waitForAudioOperations(expectedCount: number) {
+ const startedAt = Date.now();
+ while (Date.now() - startedAt < 5000) {
+ if (getActiveProcessCount() === expectedCount) return;
+ await Bun.sleep(50);
+ }
+ throw new Error(
+ `Expected ${expectedCount} active audio operations, got ${getActiveProcessCount()}`,
+ );
+}
+
+function expectMp3(data: Uint8Array) {
+ expect(data.length).toBeGreaterThan(0);
+ const hasId3Tag = data[0] === 0x49 && data[1] === 0x44 && data[2] === 0x33;
+ const hasMpegSync = data[0] === 0xff && (data[1] & 0xe0) === 0xe0;
+ expect(hasId3Tag || hasMpegSync).toBe(true);
+}
+
+describe("mediaAudio integration tests", () => {
+ describe("checkHasAudioTrack", () => {
+ test("detects audio track in video with audio", async () => {
+ const hasAudio = await checkHasAudioTrack(TEST_VIDEO_WITH_AUDIO);
+ expect(hasAudio).toBe(true);
+ });
+
+ test("detects no audio track in video without audio", async () => {
+ const hasAudio = await checkHasAudioTrack(TEST_VIDEO_NO_AUDIO);
+ expect(hasAudio).toBe(false);
+ });
+ });
+
+ describe("extractAudio", () => {
+ test("extracts audio from video with audio track", async () => {
+ const audioData = await extractAudio(TEST_VIDEO_WITH_AUDIO);
+
+ expect(audioData).toBeInstanceOf(Uint8Array);
+ expectMp3(audioData);
+ });
+
+ test("throws error for video without audio track", async () => {
+ await expect(extractAudio(TEST_VIDEO_NO_AUDIO)).rejects.toThrow();
+ });
+ });
+
+ describe("extractAudioStream", () => {
+ test("streams real mp3 data and cleans up its operation", async () => {
+ const beforeCount = getActiveProcessCount();
+ const { stream } = extractAudioStream(TEST_VIDEO_WITH_AUDIO);
+
+ const audioData = await readStream(stream);
+
+ expectMp3(audioData);
+ await waitForAudioOperations(beforeCount);
+ });
+
+ test("cleans up when a real stream is cancelled", async () => {
+ const beforeCount = getActiveProcessCount();
+ const { stream } = extractAudioStream(TEST_VIDEO_WITH_AUDIO);
+
+ await stream.cancel();
+
+ await waitForAudioOperations(beforeCount);
+ });
+ });
+});
diff --git a/apps/media-server/src/__tests__/lib/media-edit.test.ts b/apps/media-server/src/__tests__/lib/media-edit.test.ts
new file mode 100644
index 000000000..a1836f5a7
--- /dev/null
+++ b/apps/media-server/src/__tests__/lib/media-edit.test.ts
@@ -0,0 +1,150 @@
+import { afterAll, describe, expect, test } from "bun:test";
+import { existsSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import {
+ buildStreamCopySegmentArgs,
+ buildTranscodeSegmentArgs,
+ normalizeEditRanges,
+ renderEditedVideo,
+} from "../../lib/media-edit";
+import { probeVideo } from "../../lib/media-probe";
+
+const FIXTURES_DIR = join(import.meta.dir, "..", "fixtures");
+const TEST_VIDEO_WITH_AUDIO = join(FIXTURES_DIR, "test-with-audio.mp4");
+const TEST_VIDEO_NO_AUDIO = join(FIXTURES_DIR, "test-no-audio.mp4");
+
+const tempFiles: string[] = [];
+
+afterAll(() => {
+ for (const file of tempFiles) {
+ if (existsSync(file)) {
+ rmSync(file);
+ }
+ }
+});
+
+describe("media edit helpers", () => {
+ test("normalizes edit ranges", () => {
+ expect(
+ normalizeEditRanges(
+ [
+ { start: 3, end: 5 },
+ { start: -1, end: 0.01 },
+ { start: 8, end: 12 },
+ ],
+ 10,
+ ),
+ ).toEqual([
+ { start: 3, end: 5 },
+ { start: 8, end: 10 },
+ ]);
+ });
+
+ test("merges ranges separated by tiny gaps", () => {
+ expect(
+ normalizeEditRanges(
+ [
+ { start: 0, end: 1 },
+ { start: 1.02, end: 2 },
+ { start: 3, end: 3.02 },
+ ],
+ 5,
+ ),
+ ).toEqual([{ start: 0, end: 2 }]);
+ });
+
+ test("builds stream-copy segment args", () => {
+ const args = buildStreamCopySegmentArgs(
+ "/input.mp4",
+ {
+ start: 1,
+ end: 3.25,
+ },
+ "/segment.mp4",
+ );
+
+ expect(args).toContain("copy");
+ expect(args).toContain("-avoid_negative_ts");
+ expect(args).toContain("2.250");
+ });
+
+ test("builds no-audio transcode args", () => {
+ const args = buildTranscodeSegmentArgs(
+ "/input.mp4",
+ { start: 0, end: 1 },
+ "/segment.mp4",
+ false,
+ );
+
+ expect(args).toContain("libx264");
+ expect(args).toContain(
+ "[0:v:0]fps=30,trim=start=0.000:end=1.000,setpts=PTS-STARTPTS[v]",
+ );
+ expect(args).toContain("-an");
+ expect(args).not.toContain("0:a:0?");
+ });
+
+ test("builds audio transcode args", () => {
+ const args = buildTranscodeSegmentArgs(
+ "/input.mp4",
+ { start: 0, end: 1 },
+ "/segment.mp4",
+ true,
+ );
+
+ expect(args).toContain("aac");
+ expect(args).toContain(
+ "[0:v:0]fps=30,trim=start=0.000:end=1.000,setpts=PTS-STARTPTS[v];[0:a:0]atrim=start=0.000:end=1.000,asetpts=PTS-STARTPTS[a]",
+ );
+ expect(args).toContain("[a]");
+ });
+});
+
+describe("renderEditedVideo integration tests", () => {
+ test("renders an edited mp4 with audio using the real ffmpeg path", async () => {
+ const metadata = await probeVideo(`file://${TEST_VIDEO_WITH_AUDIO}`);
+ const progressUpdates: number[] = [];
+
+ const editedFile = await renderEditedVideo({
+ inputPath: TEST_VIDEO_WITH_AUDIO,
+ keepRanges: [
+ { start: 0, end: 0.4 },
+ { start: 0.55, end: 0.95 },
+ ],
+ metadata,
+ onProgress: (progress) => {
+ progressUpdates.push(progress);
+ },
+ });
+ tempFiles.push(editedFile.path);
+
+ const outputMetadata = await probeVideo(`file://${editedFile.path}`);
+ expect(outputMetadata.videoCodec).toBe("h264");
+ expect(outputMetadata.audioCodec).toBe("aac");
+ expect(outputMetadata.duration).toBeGreaterThan(0.3);
+ expect(outputMetadata.duration).toBeLessThan(metadata.duration + 0.2);
+ expect(progressUpdates.length).toBeGreaterThan(0);
+ expect(progressUpdates.at(-1)).toBe(75);
+
+ await editedFile.cleanup();
+ }, 60000);
+
+ test("renders an edited mp4 without adding an audio track", async () => {
+ const metadata = await probeVideo(`file://${TEST_VIDEO_NO_AUDIO}`);
+
+ const editedFile = await renderEditedVideo({
+ inputPath: TEST_VIDEO_NO_AUDIO,
+ keepRanges: [{ start: 0, end: 0.6 }],
+ metadata,
+ });
+ tempFiles.push(editedFile.path);
+
+ const outputMetadata = await probeVideo(`file://${editedFile.path}`);
+ expect(outputMetadata.videoCodec).toBe("h264");
+ expect(outputMetadata.audioCodec).toBeNull();
+ expect(outputMetadata.duration).toBeGreaterThan(0.2);
+ expect(outputMetadata.duration).toBeLessThan(metadata.duration + 0.2);
+
+ await editedFile.cleanup();
+ }, 60000);
+});
diff --git a/apps/media-server/src/__tests__/lib/media-probe.integration.test.ts b/apps/media-server/src/__tests__/lib/media-probe.integration.test.ts
new file mode 100644
index 000000000..be25588d2
--- /dev/null
+++ b/apps/media-server/src/__tests__/lib/media-probe.integration.test.ts
@@ -0,0 +1,156 @@
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { checkVideoAccessible, probeVideo } from "../../lib/media-probe";
+
+const FIXTURES_DIR = join(import.meta.dir, "..", "fixtures");
+const TEST_VIDEO_WITH_AUDIO_PATH = join(FIXTURES_DIR, "test-with-audio.mp4");
+const TEST_VIDEO_WITH_AUDIO = `file://${join(FIXTURES_DIR, "test-with-audio.mp4")}`;
+const TEST_VIDEO_NO_AUDIO = `file://${join(FIXTURES_DIR, "test-no-audio.mp4")}`;
+
+async function expectRejected(promise: Promise<unknown>): Promise<void> {
+ let rejected = false;
+ try {
+ await promise;
+ } catch {
+ rejected = true;
+ }
+ expect(rejected).toBe(true);
+}
+
+describe("mediaProbe integration tests", () => {
+ describe("probeVideo", () => {
+ test("extracts metadata from video with audio", async () => {
+ const metadata = await probeVideo(TEST_VIDEO_WITH_AUDIO);
+
+ expect(metadata).toHaveProperty("duration");
+ expect(metadata).toHaveProperty("width");
+ expect(metadata).toHaveProperty("height");
+ expect(metadata).toHaveProperty("fps");
+ expect(metadata).toHaveProperty("videoCodec");
+ expect(metadata).toHaveProperty("audioCodec");
+ expect(metadata).toHaveProperty("audioChannels");
+ expect(metadata).toHaveProperty("sampleRate");
+ expect(metadata).toHaveProperty("bitrate");
+ expect(metadata).toHaveProperty("fileSize");
+
+ expect(metadata.duration).toBeGreaterThan(0);
+ expect(metadata.width).toBeGreaterThan(0);
+ expect(metadata.height).toBeGreaterThan(0);
+ expect(metadata.fps).toBeGreaterThan(0);
+ expect(metadata.videoCodec).toBeTruthy();
+ expect(metadata.audioCodec).not.toBeNull();
+ });
+
+ test("extracts metadata from video without audio", async () => {
+ const metadata = await probeVideo(TEST_VIDEO_NO_AUDIO);
+
+ expect(metadata.duration).toBeGreaterThan(0);
+ expect(metadata.width).toBeGreaterThan(0);
+ expect(metadata.height).toBeGreaterThan(0);
+ expect(metadata.fps).toBeGreaterThan(0);
+ expect(metadata.videoCodec).toBeTruthy();
+ expect(metadata.audioCodec).toBeNull();
+ expect(metadata.audioChannels).toBeNull();
+ expect(metadata.sampleRate).toBeNull();
+ });
+
+ test("throws error for non-existent video", async () => {
+ await expectRejected(probeVideo("file:///nonexistent/path/to/video.mp4"));
+ });
+
+ test("throws error for invalid URL", async () => {
+ await expectRejected(
+ probeVideo(
+ "https://invalid-domain-that-does-not-exist.example/video.mp4",
+ ),
+ );
+ });
+
+ test("probes media when HEAD is forbidden but GET is allowed", async () => {
+ const videoData = readFileSync(TEST_VIDEO_WITH_AUDIO_PATH);
+ const server = Bun.serve({
+ port: 0,
+ fetch(request) {
+ if (request.method === "HEAD") {
+ return new Response(null, { status: 403 });
+ }
+
+ const range = request.headers.get("range");
+ const match = range?.match(/^bytes=(\d+)-(\d*)$/);
+ if (match) {
+ const start = Number.parseInt(match[1] ?? "0", 10);
+ const end = match[2]
+ ? Number.parseInt(match[2], 10)
+ : videoData.length - 1;
+ const chunk = videoData.subarray(start, end + 1);
+
+ return new Response(chunk, {
+ status: 206,
+ headers: {
+ "Accept-Ranges": "bytes",
+ "Content-Length": chunk.length.toString(),
+ "Content-Range": `bytes ${start}-${end}/${videoData.length}`,
+ "Content-Type": "video/mp4",
+ },
+ });
+ }
+
+ return new Response(videoData, {
+ headers: {
+ "Accept-Ranges": "bytes",
+ "Content-Length": videoData.length.toString(),
+ "Content-Type": "video/mp4",
+ },
+ });
+ },
+ });
+
+ try {
+ const metadata = await probeVideo(
+ `${server.url}video.mp4?Policy=a&Signature=b`,
+ );
+
+ expect(metadata.duration).toBeGreaterThan(0);
+ expect(metadata.videoCodec).toBeTruthy();
+ } finally {
+ await server.stop(true);
+ }
+ });
+ });
+
+ describe("checkVideoAccessible", () => {
+ test("returns false for non-existent http URL", async () => {
+ const accessible = await checkVideoAccessible(
+ "https://invalid-domain-that-does-not-exist.example/video.mp4",
+ );
+ expect(accessible).toBe(false);
+ });
+ });
+});
+
+describe("mediaProbe metadata accuracy", () => {
+ test("returns correct frame rate format", async () => {
+ const metadata = await probeVideo(TEST_VIDEO_WITH_AUDIO);
+
+ expect(typeof metadata.fps).toBe("number");
+ expect(metadata.fps).toBeLessThanOrEqual(240);
+ expect(metadata.fps % 1).toBeLessThanOrEqual(0.01);
+ });
+
+ test("returns reasonable dimensions", async () => {
+ const metadata = await probeVideo(TEST_VIDEO_WITH_AUDIO);
+
+ expect(metadata.width).toBeLessThanOrEqual(4096);
+ expect(metadata.height).toBeLessThanOrEqual(4096);
+ expect(metadata.width).toBeGreaterThan(0);
+ expect(metadata.height).toBeGreaterThan(0);
+ });
+
+ test("duration matches expected range for test file", async () => {
+ const metadata = await probeVideo(TEST_VIDEO_WITH_AUDIO);
+
+ expect(metadata.duration).toBeGreaterThan(0);
+ expect(metadata.duration).toBeLessThan(3600);
+ });
+});
diff --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.ts
new file mode 100644
index 000000000..abd477b2b
--- /dev/null
+++ b/apps/media-server/src/__tests__/lib/media-routes-real-world.integration.test.ts
@@ -0,0 +1,327 @@
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ mock,
+ test,
+} from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import type appType from "../../app";
+import type { Job } from "../../lib/job-manager";
+import { probeVideoFile } from "../../lib/media-probe";
+
+const FIXTURES_DIR = join(import.meta.dir, "..", "fixtures");
+const TEST_VIDEO_WITH_AUDIO = join(FIXTURES_DIR, "test-with-audio.mp4");
+const TEST_VIDEO_NO_AUDIO = join(FIXTURES_DIR, "test-no-audio.mp4");
+const MEDIA_SERVER_SECRET = "test-secret";
+const AUTH_HEADERS = {
+ "Content-Type": "application/json",
+ "x-media-server-secret": MEDIA_SERVER_SECRET,
+};
+
+let app: typeof appType;
+let getJob: typeof import("../../lib/job-manager").getJob;
+let deleteJob: typeof import("../../lib/job-manager").deleteJob;
+let server: ReturnType<typeof Bun.serve>;
+let baseUrl = "";
+let tempDir = "";
+
+const uploadedArtifacts = new Map<string, Uint8Array>();
+
+function fileUrl(path: string) {
+ return pathToFileURL(path).toString();
+}
+
+function fixtureUrl(name = "test-with-audio.mp4") {
+ return `${baseUrl}/fixtures/${name}`;
+}
+
+function uploadUrl(name: string) {
+ return `${baseUrl}/uploads/${name}`;
+}
+
+function mediaPostRequest(path: string, body: unknown): Request {
+ return new Request(`http://localhost${path}`, {
+ method: "POST",
+ headers: AUTH_HEADERS,
+ body: JSON.stringify(body),
+ });
+}
+
+async function responseBytes(response: Response) {
+ return new Uint8Array(await response.arrayBuffer());
+}
+
+function expectJpeg(data: Uint8Array) {
+ expect(data.length).toBeGreaterThan(0);
+ expect(data[0]).toBe(0xff);
+ expect(data[1]).toBe(0xd8);
+}
+
+function expectMp3(data: Uint8Array) {
+ expect(data.length).toBeGreaterThan(0);
+ const hasId3Tag = data[0] === 0x49 && data[1] === 0x44 && data[2] === 0x33;
+ const hasMpegSync = data[0] === 0xff && (data[1] & 0xe0) === 0xe0;
+ expect(hasId3Tag || hasMpegSync).toBe(true);
+}
+
+function expectMp4(data: Uint8Array) {
+ expect(data.length).toBeGreaterThan(0);
+ expect(new TextDecoder().decode(data.slice(4, 8))).toBe("ftyp");
+}
+
+async function probeBytesAsMp4(data: Uint8Array, name: string) {
+ const path = join(tempDir, `${Date.now()}-${name}`);
+ await writeFile(path, data);
+ return await probeVideoFile(path);
+}
+
+async function waitForTerminalJob(jobId: string): Promise<Job> {
+ const startedAt = Date.now();
+ while (Date.now() - startedAt < 90000) {
+ const job = getJob(jobId);
+ if (!job) {
+ throw new Error(`Job ${jobId} disappeared`);
+ }
+ if (
+ job.phase === "complete" ||
+ job.phase === "error" ||
+ job.phase === "cancelled"
+ ) {
+ return job;
+ }
+ await Bun.sleep(100);
+ }
+
+ const job = getJob(jobId);
+ throw new Error(
+ `Timed out waiting for job ${jobId}; phase=${job?.phase ?? "missing"}`,
+ );
+}
+
+function uploadedBytes(pathname: string) {
+ const bytes = uploadedArtifacts.get(pathname);
+ if (!bytes) {
+ throw new Error(`Expected upload at ${pathname}`);
+ }
+ return bytes;
+}
+
+beforeAll(async () => {
+ mock.restore();
+ process.env.MEDIA_SERVER_WEBHOOK_SECRET = MEDIA_SERVER_SECRET;
+ process.env.MEDIA_SERVER_MAX_CONCURRENT_VIDEO_PROCESSES = "4";
+
+ const appModule = await import("../../app");
+ const jobManager = await import("../../lib/job-manager");
+ app = appModule.default;
+ getJob = jobManager.getJob;
+ deleteJob = jobManager.deleteJob;
+ tempDir = mkdtempSync(join(tmpdir(), "cap-real-world-routes-"));
+
+ server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ async fetch(request) {
+ const url = new URL(request.url);
+
+ if (request.method === "GET" || request.method === "HEAD") {
+ const fixturePath =
+ url.pathname === "/fixtures/test-no-audio.mp4"
+ ? TEST_VIDEO_NO_AUDIO
+ : url.pathname === "/fixtures/test-with-audio.mp4"
+ ? TEST_VIDEO_WITH_AUDIO
+ : null;
+
+ if (fixturePath) {
+ const fixture = Bun.file(fixturePath);
+ const headers = {
+ "Content-Type": "video/mp4",
+ "Content-Length": String(await fixture.size),
+ };
+ return request.method === "HEAD"
+ ? new Response(null, { headers })
+ : new Response(fixture, { headers });
+ }
+ }
+
+ if (request.method === "PUT" && url.pathname.startsWith("/uploads/")) {
+ uploadedArtifacts.set(
+ url.pathname,
+ new Uint8Array(await request.arrayBuffer()),
+ );
+ return new Response(null, { status: 200, statusText: "OK" });
+ }
+
+ return new Response("Not found", { status: 404 });
+ },
+ });
+ baseUrl = `http://127.0.0.1:${server.port}`;
+});
+
+beforeEach(() => {
+ mock.restore();
+ uploadedArtifacts.clear();
+});
+
+afterAll(() => {
+ server?.stop(true);
+ if (tempDir) {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+});
+
+describe("media routes real-world integration tests", () => {
+ test("checks real audio tracks through the route stack", async () => {
+ const withAudioResponse = await app.fetch(
+ mediaPostRequest("/audio/check", {
+ videoUrl: fileUrl(TEST_VIDEO_WITH_AUDIO),
+ }),
+ );
+ const noAudioResponse = await app.fetch(
+ mediaPostRequest("/audio/check", {
+ videoUrl: fileUrl(TEST_VIDEO_NO_AUDIO),
+ }),
+ );
+
+ expect(withAudioResponse.status).toBe(200);
+ expect(noAudioResponse.status).toBe(200);
+
+ const withAudio = (await withAudioResponse.json()) as { hasAudio: boolean };
+ const noAudio = (await noAudioResponse.json()) as { hasAudio: boolean };
+ expect(withAudio.hasAudio).toBe(true);
+ expect(noAudio.hasAudio).toBe(false);
+ });
+
+ test("extracts real audio through the non-streaming route", async () => {
+ const response = await app.fetch(
+ mediaPostRequest("/audio/extract", {
+ videoUrl: fileUrl(TEST_VIDEO_WITH_AUDIO),
+ stream: false,
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("Content-Type")).toBe("audio/mpeg");
+ expectMp3(await responseBytes(response));
+ });
+
+ test("probes and thumbnails a real video through the route stack", async () => {
+ const probeResponse = await app.fetch(
+ mediaPostRequest("/video/probe", {
+ videoUrl: fileUrl(TEST_VIDEO_WITH_AUDIO),
+ }),
+ );
+ expect(probeResponse.status).toBe(200);
+ const probeData = (await probeResponse.json()) as {
+ metadata: { videoCodec: string; audioCodec: string | null };
+ };
+ expect(probeData.metadata.videoCodec).toBe("h264");
+ expect(probeData.metadata.audioCodec).toBe("aac");
+
+ const thumbnailResponse = await app.fetch(
+ mediaPostRequest("/video/thumbnail", {
+ videoUrl: fileUrl(TEST_VIDEO_WITH_AUDIO),
+ timestamp: 0.2,
+ width: 160,
+ height: 120,
+ quality: 80,
+ }),
+ );
+ expect(thumbnailResponse.status).toBe(200);
+ expect(thumbnailResponse.headers.get("Content-Type")).toBe("image/jpeg");
+ expectJpeg(await responseBytes(thumbnailResponse));
+ });
+
+ test("converts a real downloaded video through the route stack", async () => {
+ const response = await app.fetch(
+ mediaPostRequest("/video/convert", {
+ videoUrl: fixtureUrl(),
+ inputExtension: ".mp4",
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("Content-Type")).toBe("video/mp4");
+ const bytes = await responseBytes(response);
+ expectMp4(bytes);
+
+ const metadata = await probeBytesAsMp4(bytes, "converted.mp4");
+ expect(metadata.videoCodec).toBe("h264");
+ expect(metadata.audioCodec).toBe("aac");
+ expect(metadata.duration).toBeGreaterThan(0);
+ }, 60000);
+
+ test("processes and uploads a real video job through the async route", async () => {
+ const response = await app.fetch(
+ mediaPostRequest("/video/process", {
+ videoId: "real-process-video",
+ userId: "real-process-user",
+ videoUrl: fixtureUrl(),
+ outputPresignedUrl: uploadUrl("process-output.mp4"),
+ inputExtension: ".mp4",
+ maxWidth: 160,
+ maxHeight: 120,
+ crf: 30,
+ preset: "ultrafast",
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ const data = (await response.json()) as { jobId: string };
+ const job = await waitForTerminalJob(data.jobId);
+ try {
+ expect(job.phase).toBe("complete");
+ expect(job.error).toBeUndefined();
+
+ const bytes = uploadedBytes("/uploads/process-output.mp4");
+ expectMp4(bytes);
+ const metadata = await probeBytesAsMp4(bytes, "process-output.mp4");
+ expect(metadata.videoCodec).toBe("h264");
+ expect(metadata.audioCodec).toBe("aac");
+ expect(metadata.width).toBeLessThanOrEqual(160);
+ expect(metadata.height).toBeLessThanOrEqual(120);
+ } finally {
+ deleteJob(data.jobId);
+ }
+ }, 90000);
+
+ test("edits and uploads a real video job through the async route", async () => {
+ const response = await app.fetch(
+ mediaPostRequest("/video/edit", {
+ videoId: "real-edit-video",
+ userId: "real-edit-user",
+ sourceUrl: fixtureUrl(),
+ outputPresignedUrl: uploadUrl("edit-output.mp4"),
+ keepRanges: [
+ { start: 0, end: 0.4 },
+ { start: 0.55, end: 0.95 },
+ ],
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ const data = (await response.json()) as { jobId: string };
+ const job = await waitForTerminalJob(data.jobId);
+ try {
+ expect(job.phase).toBe("complete");
+ expect(job.error).toBeUndefined();
+
+ const bytes = uploadedBytes("/uploads/edit-output.mp4");
+ expectMp4(bytes);
+ const metadata = await probeBytesAsMp4(bytes, "edit-output.mp4");
+ expect(metadata.videoCodec).toBe("h264");
+ expect(metadata.audioCodec).toBe("aac");
+ expect(metadata.duration).toBeGreaterThan(0.3);
+ expect(metadata.duration).toBeLessThan(1.2);
+ } finally {
+ deleteJob(data.jobId);
+ }
+ }, 90000);
+});
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.ts
new file mode 100644
index 000000000..30a0ff24d
--- /dev/null
+++ b/apps/media-server/src/__tests__/lib/media-video.integration.test.ts
@@ -0,0 +1,740 @@
+import { afterAll, describe, expect, test } from "bun:test";
+import { execFileSync } from "node:child_process";
+import {
+ existsSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ statSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { withTimeout } from "../../lib/media-common";
+import { probeVideo } from "../../lib/media-probe";
+import {
+ copyFileToMp4,
+ generatePreviewGif,
+ generateThumbnail,
+ materializeHlsPlaylist,
+ materializeMpdAsHlsPlaylist,
+ materializeMpdManifest,
+ materializeStreamingInput,
+ muxMediaTracksToMp4,
+ normalizeVideoInputExtension,
+ processVideo,
+ repairContainer,
+ uploadToS3,
+} from "../../lib/media-video";
+
+const FIXTURES_DIR = join(import.meta.dir, "..", "fixtures");
+const TEST_VIDEO_WITH_AUDIO = join(FIXTURES_DIR, "test-with-audio.mp4");
+
+const tempFiles: string[] = [];
+
+async function expectRejected(promise: Promise<unknown>): Promise<void> {
+ let rejected = false;
+ try {
+ await promise;
+ } catch {
+ rejected = true;
+ }
+ expect(rejected).toBe(true);
+}
+
+afterAll(() => {
+ for (const file of tempFiles) {
+ if (existsSync(file)) {
+ rmSync(file);
+ }
+ }
+});
+
+describe("generateThumbnail integration tests", () => {
+ test("generates JPEG thumbnail from video", async () => {
+ const metadata = await probeVideo(`file://${TEST_VIDEO_WITH_AUDIO}`);
+ const thumbnailData = await generateThumbnail(
+ TEST_VIDEO_WITH_AUDIO,
+ metadata.duration,
+ );
+
+ expect(thumbnailData).toBeInstanceOf(Uint8Array);
+ expect(thumbnailData.length).toBeGreaterThan(0);
+
+ expect(thumbnailData[0]).toBe(0xff);
+ expect(thumbnailData[1]).toBe(0xd8);
+ });
+
+ test("generates thumbnail at specific timestamp", async () => {
+ const metadata = await probeVideo(`file://${TEST_VIDEO_WITH_AUDIO}`);
+ const thumbnailData = await generateThumbnail(
+ TEST_VIDEO_WITH_AUDIO,
+ metadata.duration,
+ { timestamp: 0.1 },
+ );
+
+ expect(thumbnailData).toBeInstanceOf(Uint8Array);
+ expect(thumbnailData.length).toBeGreaterThan(0);
+ });
+
+ test("generates thumbnail with custom dimensions", async () => {
+ const metadata = await probeVideo(`file://${TEST_VIDEO_WITH_AUDIO}`);
+ const thumbnailData = await generateThumbnail(
+ TEST_VIDEO_WITH_AUDIO,
+ metadata.duration,
+ { width: 320, height: 180 },
+ );
+
+ expect(thumbnailData).toBeInstanceOf(Uint8Array);
+ expect(thumbnailData.length).toBeGreaterThan(0);
+ });
+
+ test("generates thumbnail with custom quality", async () => {
+ const metadata = await probeVideo(`file://${TEST_VIDEO_WITH_AUDIO}`);
+
+ const highQuality = await generateThumbnail(
+ TEST_VIDEO_WITH_AUDIO,
+ metadata.duration,
+ { quality: 95 },
+ );
+
+ const lowQuality = await generateThumbnail(
+ TEST_VIDEO_WITH_AUDIO,
+ metadata.duration,
+ { quality: 10 },
+ );
+
+ expect(highQuality.length).toBeGreaterThanOrEqual(lowQuality.length);
+ });
+
+ test("throws error for non-existent video", async () => {
+ await expectRejected(
+ generateThumbnail("/nonexistent/path/to/video.mp4", 10),
+ );
+ });
+});
+
+describe("generatePreviewGif integration tests", () => {
+ test("generates small GIF preview from video", async () => {
+ const metadata = await probeVideo(`file://${TEST_VIDEO_WITH_AUDIO}`);
+ const preview = await generatePreviewGif(
+ TEST_VIDEO_WITH_AUDIO,
+ metadata.duration,
+ { maxBytes: 100_000 },
+ );
+
+ try {
+ const previewData = readFileSync(preview.path);
+
+ expect(previewData.length).toBeGreaterThan(0);
+ expect(previewData.length).toBeLessThanOrEqual(100_000);
+ expect(previewData.subarray(0, 3).toString()).toBe("GIF");
+ } finally {
+ await preview.cleanup();
+ }
+ });
+
+ test("rejects GIF previews over the size budget", async () => {
+ const metadata = await probeVideo(`file://${TEST_VIDEO_WITH_AUDIO}`);
+
+ await expect(
+ generatePreviewGif(TEST_VIDEO_WITH_AUDIO, metadata.duration, {
+ maxBytes: 1,
+ }),
+ ).rejects.toThrow("Preview GIF exceeds size budget");
+ });
+
+ test("rejects before spawning when already aborted", async () => {
+ const controller = new AbortController();
+ controller.abort();
+
+ await expect(
+ generatePreviewGif(TEST_VIDEO_WITH_AUDIO, 10, {}, controller.signal),
+ ).rejects.toThrow("Preview GIF generation aborted");
+ });
+});
+
+describe("processVideo integration tests", () => {
+ test("retries transient S3 upload failures", async () => {
+ const originalFetch = globalThis.fetch;
+ let attempts = 0;
+
+ globalThis.fetch = (async () => {
+ attempts++;
+ if (attempts === 1) {
+ const error = new Error(
+ "The socket connection was closed unexpectedly.",
+ );
+ Object.assign(error, { code: "ECONNRESET" });
+ throw error;
+ }
+
+ return new Response(null, {
+ status: 200,
+ statusText: "OK",
+ });
+ }) as unknown as typeof fetch;
+
+ try {
+ await uploadToS3(
+ new Uint8Array([1, 2, 3, 4]),
+ "https://uploads.example/result.mp4",
+ "video/mp4",
+ );
+ expect(attempts).toBe(2);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
+ test("does not retry non-retryable S3 upload failures", async () => {
+ const originalFetch = globalThis.fetch;
+ let attempts = 0;
+
+ globalThis.fetch = (async () => {
+ attempts++;
+ return new Response(null, {
+ status: 403,
+ statusText: "Forbidden",
+ });
+ }) as unknown as typeof fetch;
+
+ try {
+ await expect(
+ uploadToS3(
+ new Uint8Array([1, 2, 3, 4]),
+ "https://uploads.example/result.mp4",
+ "video/mp4",
+ ),
+ ).rejects.toThrow("Storage upload failed: 403 Forbidden");
+ expect(attempts).toBe(1);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
+ test("escapes signed DASH manifest URLs in XML attributes", async () => {
+ const originalFetch = globalThis.fetch;
+ const manifestDir = mkdtempSync(join(tmpdir(), "cap-mpd-"));
+
+ globalThis.fetch = (async () =>
+ new Response(
+ '<MPD><Period><AdaptationSet><Representation><SegmentTemplate initialization="init.mp4" media="chunk-$Number$.m4s"/></Representation></AdaptationSet></Period></MPD>',
+ { status: 200, statusText: "OK" },
+ )) as unknown as typeof fetch;
+
+ try {
+ const path = await materializeMpdManifest(
+ "https://cdn.example/video/manifest.mpd?Policy=a&Signature=b&Key-Pair-Id=c",
+ manifestDir,
+ );
+ const content = readFileSync(path, "utf8");
+
+ expect(content).toContain(
+ "init.mp4?Policy=a&amp;Signature=b&amp;Key-Pair-Id=c",
+ );
+ expect(content).toContain(
+ "chunk-$Number$.m4s?Policy=a&amp;Signature=b&amp;Key-Pair-Id=c",
+ );
+ } finally {
+ globalThis.fetch = originalFetch;
+ rmSync(manifestDir, { recursive: true, force: true });
+ }
+ });
+
+ test("materializes signed DASH SegmentTemplate manifests as HLS", async () => {
+ const originalFetch = globalThis.fetch;
+ const manifestDir = mkdtempSync(join(tmpdir(), "cap-mpd-hls-"));
+
+ globalThis.fetch = (async () =>
+ new Response(
+ `<MPD mediaPresentationDuration="PT2S">
+ <Period>
+ <AdaptationSet contentType="video" mimeType="video/mp4" codecs="avc1.4d401f" width="640" height="360">
+ <Representation id="v1" bandwidth="800000">
+ <SegmentTemplate timescale="1000" duration="1000" initialization="video/init-$RepresentationID$.mp4" media="video/chunk-$Number%05d$.m4s" startNumber="3"/>
+ </Representation>
+ </AdaptationSet>
+ <AdaptationSet contentType="audio" mimeType="audio/mp4" codecs="mp4a.40.2">
+ <Representation id="a1" bandwidth="96000">
+ <SegmentTemplate timescale="48000" initialization="audio/init.mp4" media="audio/chunk-$Time$.m4s">
+ <SegmentTimeline><S t="0" d="48000" r="1"/></SegmentTimeline>
+ </SegmentTemplate>
+ </Representation>
+ </AdaptationSet>
+ </Period>
+ </MPD>`,
+ { status: 200, statusText: "OK" },
+ )) as unknown as typeof fetch;
+
+ try {
+ const masterPath = await materializeMpdAsHlsPlaylist(
+ "https://cdn.example/video/manifest.mpd?Policy=a&Signature=b",
+ manifestDir,
+ );
+ const master = readFileSync(masterPath, "utf8");
+ const mediaMatch = master.match(/#EXT-X-MEDIA:[^\n]+URI="([^"]+)"/);
+ const masterLines = master.split("\n");
+ const streamIndex = masterLines.findIndex((line) =>
+ line.startsWith("#EXT-X-STREAM-INF:"),
+ );
+ const videoPlaylistPath = masterLines[streamIndex + 1];
+
+ expect(mediaMatch?.[1]).toBeTruthy();
+ expect(videoPlaylistPath).toBeTruthy();
+ expect(master).toContain('CODECS="avc1.4d401f,mp4a.40.2"');
+
+ const videoPlaylist = readFileSync(videoPlaylistPath ?? "", "utf8");
+ const audioPlaylist = readFileSync(mediaMatch?.[1] ?? "", "utf8");
+
+ expect(videoPlaylist).toContain(
+ "https://cdn.example/video/video/init-v1.mp4?Policy=a&Signature=b",
+ );
+ expect(videoPlaylist).toContain(
+ "https://cdn.example/video/video/chunk-00003.m4s?Policy=a&Signature=b",
+ );
+ expect(videoPlaylist).toContain(
+ "https://cdn.example/video/video/chunk-00004.m4s?Policy=a&Signature=b",
+ );
+ expect(audioPlaylist).toContain(
+ "https://cdn.example/video/audio/chunk-0.m4s?Policy=a&Signature=b",
+ );
+ expect(audioPlaylist).toContain(
+ "https://cdn.example/video/audio/chunk-48000.m4s?Policy=a&Signature=b",
+ );
+ } finally {
+ globalThis.fetch = originalFetch;
+ rmSync(manifestDir, { recursive: true, force: true });
+ }
+ });
+
+ test("falls back to generic DASH manifest materialization for unsupported MPD shapes", async () => {
+ const originalFetch = globalThis.fetch;
+ const manifestDir = mkdtempSync(join(tmpdir(), "cap-mpd-fallback-"));
+ let requests = 0;
+
+ globalThis.fetch = (async () => {
+ requests++;
+ return new Response(
+ `<MPD>
+ <Period>
+ <AdaptationSet mimeType="video/mp4">
+ <Representation id="v1" bandwidth="800000">
+ <SegmentList>
+ <Initialization sourceURL="init.mp4"/>
+ <SegmentURL media="seg-1.m4s"/>
+ </SegmentList>
+ </Representation>
+ </AdaptationSet>
+ </Period>
+ </MPD>`,
+ { status: 200, statusText: "OK" },
+ );
+ }) as unknown as typeof fetch;
+
+ try {
+ const path = await materializeStreamingInput(
+ "https://cdn.example/video/manifest.mpd?Policy=a&Signature=b",
+ manifestDir,
+ );
+ const content = readFileSync(path, "utf8");
+
+ expect(path.endsWith(".mpd")).toBe(true);
+ expect(requests).toBe(2);
+ expect(content).toContain("seg-1.m4s?Policy=a&amp;Signature=b");
+ } finally {
+ globalThis.fetch = originalFetch;
+ rmSync(manifestDir, { recursive: true, force: true });
+ }
+ });
+
+ test("does not retry DASH materialization when the manifest fetch fails", async () => {
+ const originalFetch = globalThis.fetch;
+ const manifestDir = mkdtempSync(join(tmpdir(), "cap-mpd-fetch-fail-"));
+ let requests = 0;
+
+ globalThis.fetch = (async () => {
+ requests++;
+ return new Response("", { status: 403, statusText: "Forbidden" });
+ }) as unknown as typeof fetch;
+
+ try {
+ await expect(
+ materializeStreamingInput(
+ "https://cdn.example/video/manifest.mpd?Policy=a&Signature=b",
+ manifestDir,
+ ),
+ ).rejects.toThrow("Failed to fetch DASH manifest: 403 Forbidden");
+ expect(requests).toBe(1);
+ } finally {
+ globalThis.fetch = originalFetch;
+ rmSync(manifestDir, { recursive: true, force: true });
+ }
+ });
+
+ test("materializes signed HLS playlists with inherited query strings", async () => {
+ const originalFetch = globalThis.fetch;
+ const manifestDir = mkdtempSync(join(tmpdir(), "cap-hls-"));
+ const requestedUrls: string[] = [];
+
+ globalThis.fetch = (async (input: RequestInfo | URL) => {
+ const url = input instanceof Request ? input.url : input.toString();
+ requestedUrls.push(url);
+
+ if (url.includes("/master.m3u8")) {
+ return new Response(
+ [
+ "#EXTM3U",
+ "#EXT-X-STREAM-INF:BANDWIDTH=1000000",
+ "variant.m3u8",
+ ].join("\n"),
+ { status: 200, statusText: "OK" },
+ );
+ }
+
+ if (url.includes("/variant.m3u8")) {
+ return new Response(
+ [
+ "#EXTM3U",
+ "#EXT-X-TARGETDURATION:2",
+ '#EXT-X-MAP:URI="init.mp4"',
+ '#EXT-X-KEY:METHOD=AES-128,URI="key.bin"',
+ "#EXTINF:1,",
+ "segment-1.ts",
+ "#EXTINF:1,",
+ "segment-2.ts",
+ "#EXT-X-ENDLIST",
+ ].join("\n"),
+ { status: 200, statusText: "OK" },
+ );
+ }
+
+ return new Response("not found", {
+ status: 404,
+ statusText: "Not Found",
+ });
+ }) as unknown as typeof fetch;
+
+ try {
+ const masterPath = await materializeHlsPlaylist(
+ "https://cdn.example/video/master.m3u8?Policy=a&Signature=b",
+ manifestDir,
+ );
+ const master = readFileSync(masterPath, "utf8");
+ const variantPath = master
+ .split("\n")
+ .find((line) => line.startsWith(manifestDir));
+
+ expect(requestedUrls).toContain(
+ "https://cdn.example/video/variant.m3u8?Policy=a&Signature=b",
+ );
+ expect(variantPath).toBeTruthy();
+
+ const variant = readFileSync(variantPath ?? "", "utf8");
+ expect(variant).toContain(
+ 'URI="https://cdn.example/video/init.mp4?Policy=a&Signature=b"',
+ );
+ expect(variant).toContain(
+ 'URI="https://cdn.example/video/key.bin?Policy=a&Signature=b"',
+ );
+ expect(variant).toContain(
+ "https://cdn.example/video/segment-1.ts?Policy=a&Signature=b",
+ );
+ expect(variant).toContain(
+ "https://cdn.example/video/segment-2.ts?Policy=a&Signature=b",
+ );
+ } finally {
+ globalThis.fetch = originalFetch;
+ rmSync(manifestDir, { recursive: true, force: true });
+ }
+ });
+
+ test("waits for async cleanup before rejecting timed out work", async () => {
+ let resolveCleanup: (() => void) | undefined;
+ let settled = false;
+ const cleanupFinished = new Promise<void>((resolve) => {
+ resolveCleanup = resolve;
+ });
+
+ const timedOutWork = withTimeout(
+ new Promise<never>(() => {}),
+ 1,
+ async () => {
+ await cleanupFinished;
+ },
+ );
+
+ void timedOutWork.catch(() => {
+ settled = true;
+ });
+
+ await Bun.sleep(25);
+ expect(settled).toBe(false);
+
+ resolveCleanup?.();
+
+ await expect(timedOutWork).rejects.toThrow("Operation timed out after 1ms");
+ expect(settled).toBe(true);
+ });
+
+ test("normalizes input extensions", () => {
+ expect(normalizeVideoInputExtension(undefined)).toBe(".mp4");
+ expect(normalizeVideoInputExtension("webm")).toBe(".webm");
+ expect(normalizeVideoInputExtension(".MOV")).toBe(".mov");
+ });
+
+ test("processes video and produces valid output", async () => {
+ const metadata = await probeVideo(`file://${TEST_VIDEO_WITH_AUDIO}`);
+
+ let lastProgress = 0;
+ const progressUpdates: number[] = [];
+
+ const tempFile = await processVideo(
+ TEST_VIDEO_WITH_AUDIO,
+ metadata,
+ { maxWidth: 640, maxHeight: 360 },
+ (progress, _message) => {
+ expect(progress).toBeGreaterThanOrEqual(lastProgress);
+ progressUpdates.push(progress);
+ lastProgress = progress;
+ },
+ );
+
+ tempFiles.push(tempFile.path);
+
+ expect(existsSync(tempFile.path)).toBe(true);
+
+ const outputMetadata = await probeVideo(`file://${tempFile.path}`);
+ expect(outputMetadata.width).toBeLessThanOrEqual(640);
+ expect(outputMetadata.height).toBeLessThanOrEqual(360);
+ expect(outputMetadata.videoCodec).toBe("h264");
+
+ expect(progressUpdates.length).toBeGreaterThan(0);
+ expect(progressUpdates[progressUpdates.length - 1]).toBeGreaterThanOrEqual(
+ 50,
+ );
+
+ await tempFile.cleanup();
+ expect(existsSync(tempFile.path)).toBe(false);
+ }, 60000);
+
+ test("respects CRF setting", async () => {
+ const metadata = await probeVideo(`file://${TEST_VIDEO_WITH_AUDIO}`);
+
+ const highQualityFile = await processVideo(
+ TEST_VIDEO_WITH_AUDIO,
+ metadata,
+ { crf: 18, maxWidth: 160, maxHeight: 120 },
+ );
+ tempFiles.push(highQualityFile.path);
+
+ const lowQualityFile = await processVideo(TEST_VIDEO_WITH_AUDIO, metadata, {
+ crf: 35,
+ maxWidth: 160,
+ maxHeight: 120,
+ });
+ tempFiles.push(lowQualityFile.path);
+
+ const highQualityMetadata = await probeVideo(
+ `file://${highQualityFile.path}`,
+ );
+ const lowQualityMetadata = await probeVideo(
+ `file://${lowQualityFile.path}`,
+ );
+
+ expect(highQualityMetadata.bitrate).toBeGreaterThanOrEqual(
+ lowQualityMetadata.bitrate,
+ );
+
+ await highQualityFile.cleanup();
+ await lowQualityFile.cleanup();
+ }, 120000);
+
+ test("throws error for non-existent video", async () => {
+ const fakeMetadata = {
+ duration: 10,
+ width: 1920,
+ height: 1080,
+ fps: 30,
+ videoCodec: "h264",
+ audioCodec: null,
+ audioChannels: null,
+ sampleRate: null,
+ bitrate: 5000000,
+ fileSize: 0,
+ };
+
+ await expectRejected(
+ processVideo("/nonexistent/path/to/video.mp4", fakeMetadata, {}),
+ );
+ });
+
+ test("remuxes compatible mp4 input into a valid mp4 output", async () => {
+ const metadata = await probeVideo(`file://${TEST_VIDEO_WITH_AUDIO}`);
+ const tempFile = await processVideo(TEST_VIDEO_WITH_AUDIO, metadata, {
+ remuxOnly: true,
+ });
+ tempFiles.push(tempFile.path);
+
+ const outputMetadata = await probeVideo(`file://${tempFile.path}`);
+ expect(outputMetadata.videoCodec).toBe("h264");
+ expect(outputMetadata.audioCodec).toBe("aac");
+
+ await tempFile.cleanup();
+ }, 120000);
+
+ test("does not recompress compatible mp4 input when no transcode is needed", async () => {
+ const metadata = await probeVideo(`file://${TEST_VIDEO_WITH_AUDIO}`);
+ const sourceSize = statSync(TEST_VIDEO_WITH_AUDIO).size;
+ const tempFile = await processVideo(TEST_VIDEO_WITH_AUDIO, metadata, {
+ maxWidth: metadata.width,
+ maxHeight: metadata.height,
+ });
+ tempFiles.push(tempFile.path);
+
+ const outputSize = statSync(tempFile.path).size;
+ const outputMetadata = await probeVideo(`file://${tempFile.path}`);
+
+ expect(outputMetadata.videoCodec).toBe("h264");
+ expect(outputMetadata.audioCodec).toBe("aac");
+ expect(outputSize).toBeGreaterThan(Math.round(sourceSize * 0.75));
+
+ await tempFile.cleanup();
+ }, 120000);
+
+ test("transcodes raw webm input into a valid mp4 output", async () => {
+ const workDir = mkdtempSync(join(tmpdir(), "cap-webm-transcode-"));
+ try {
+ const rawWebmPath = join(workDir, "input.webm");
+
+ execFileSync("ffmpeg", [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-y",
+ "-i",
+ TEST_VIDEO_WITH_AUDIO,
+ "-c:v",
+ "libvpx-vp9",
+ "-c:a",
+ "libopus",
+ rawWebmPath,
+ ]);
+
+ const metadata = await probeVideo(`file://${rawWebmPath}`);
+ const tempFile = await processVideo(rawWebmPath, metadata, {});
+ tempFiles.push(tempFile.path);
+
+ const outputMetadata = await probeVideo(`file://${tempFile.path}`);
+ expect(outputMetadata.videoCodec).toBe("h264");
+ expect(outputMetadata.audioCodec).toBe("aac");
+
+ await tempFile.cleanup();
+ } finally {
+ rmSync(workDir, { recursive: true, force: true });
+ }
+ }, 120000);
+});
+
+describe("ffmpeg-backed media utilities integration tests", () => {
+ test("repairs a real mp4 container into a probeable file", async () => {
+ const repairedFile = await repairContainer(TEST_VIDEO_WITH_AUDIO);
+ tempFiles.push(repairedFile.path);
+
+ const metadata = await probeVideo(`file://${repairedFile.path}`);
+ expect(metadata.videoCodec).toBe("h264");
+ expect(metadata.audioCodec).toBe("aac");
+ expect(metadata.duration).toBeGreaterThan(0);
+
+ await repairedFile.cleanup();
+ }, 60000);
+
+ test("copies a real media file to mp4 through the production remux path", async () => {
+ const copiedFile = await copyFileToMp4(TEST_VIDEO_WITH_AUDIO);
+ tempFiles.push(copiedFile.path);
+
+ const metadata = await probeVideo(`file://${copiedFile.path}`);
+ expect(metadata.videoCodec).toBe("h264");
+ expect(metadata.audioCodec).toBe("aac");
+ expect(metadata.duration).toBeGreaterThan(0);
+
+ await copiedFile.cleanup();
+ }, 60000);
+
+ test("muxes real video and audio tracks into a valid mp4", async () => {
+ const workDir = mkdtempSync(join(tmpdir(), "cap-mux-"));
+ try {
+ const videoOnlyPath = join(workDir, "video-only.mp4");
+ const audioOnlyPath = join(workDir, "audio-only.m4a");
+ const outputPath = join(workDir, "muxed.mp4");
+
+ execFileSync("ffmpeg", [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-y",
+ "-i",
+ TEST_VIDEO_WITH_AUDIO,
+ "-map",
+ "0:v:0",
+ "-c",
+ "copy",
+ "-an",
+ videoOnlyPath,
+ ]);
+ execFileSync("ffmpeg", [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-y",
+ "-i",
+ TEST_VIDEO_WITH_AUDIO,
+ "-map",
+ "0:a:0",
+ "-c",
+ "copy",
+ audioOnlyPath,
+ ]);
+
+ await muxMediaTracksToMp4(videoOnlyPath, audioOnlyPath, outputPath);
+
+ const metadata = await probeVideo(`file://${outputPath}`);
+ expect(metadata.videoCodec).toBe("h264");
+ expect(metadata.audioCodec).toBe("aac");
+ expect(metadata.duration).toBeGreaterThan(0);
+ } finally {
+ rmSync(workDir, { recursive: true, force: true });
+ }
+ }, 60000);
+
+ test("muxes a real video-only track without creating an audio stream", async () => {
+ const workDir = mkdtempSync(join(tmpdir(), "cap-mux-video-only-"));
+ try {
+ const videoOnlyPath = join(workDir, "video-only.mp4");
+ const outputPath = join(workDir, "muxed-video-only.mp4");
+
+ execFileSync("ffmpeg", [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-y",
+ "-i",
+ TEST_VIDEO_WITH_AUDIO,
+ "-map",
+ "0:v:0",
+ "-c",
+ "copy",
+ "-an",
+ videoOnlyPath,
+ ]);
+
+ await muxMediaTracksToMp4(videoOnlyPath, null, outputPath);
+
+ const metadata = await probeVideo(`file://${outputPath}`);
+ expect(metadata.videoCodec).toBe("h264");
+ expect(metadata.audioCodec).toBeNull();
+ expect(metadata.duration).toBeGreaterThan(0);
+ } finally {
+ rmSync(workDir, { recursive: true, force: true });
+ }
+ }, 60000);
+});