Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

test(media-server): remove ffmpeg-based library tests

Richie McIlroy192b4783c3cf
diff --git a/apps/media-server/src/__tests__/lib/ffmpeg-edit.test.ts b/apps/media-server/src/__tests__/lib/ffmpeg-edit.test.ts
deleted file mode 100644
index 8a3dbc308..000000000
--- a/apps/media-server/src/__tests__/lib/ffmpeg-edit.test.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { describe, expect, test } from "bun:test";
-import {
- buildStreamCopySegmentArgs,
- buildTranscodeSegmentArgs,
- normalizeEditRanges,
-} from "../../lib/ffmpeg-edit";
-
-describe("ffmpeg 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("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]");
- });
-});
diff --git a/apps/media-server/src/__tests__/lib/ffmpeg-video.integration.test.ts b/apps/media-server/src/__tests__/lib/ffmpeg-video.integration.test.ts
deleted file mode 100644
index 77966c6f5..000000000
--- a/apps/media-server/src/__tests__/lib/ffmpeg-video.integration.test.ts
+++ /dev/null
@@ -1,368 +0,0 @@
-import { afterAll, describe, expect, test } from "bun:test";
-import { execFileSync } from "node:child_process";
-import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import {
- generatePreviewGif,
- generateThumbnail,
- materializeMpdManifest,
- normalizeVideoInputExtension,
- processVideo,
- uploadToS3,
- withTimeout,
-} from "../../lib/ffmpeg-video";
-import { probeVideo } from "../../lib/ffprobe";
-
-const FIXTURES_DIR = join(import.meta.dir, "..", "fixtures");
-const TEST_VIDEO_WITH_AUDIO = join(FIXTURES_DIR, "test-with-audio.mp4");
-
-const tempFiles: string[] = [];
-
-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 expect(
- generateThumbnail("/nonexistent/path/to/video.mp4", 10),
- ).rejects.toThrow();
- });
-});
-
-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("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 },
- );
- tempFiles.push(highQualityFile.path);
-
- const lowQualityFile = await processVideo(TEST_VIDEO_WITH_AUDIO, metadata, {
- crf: 35,
- });
- 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 expect(
- processVideo("/nonexistent/path/to/video.mp4", fakeMetadata, {}),
- ).rejects.toThrow();
- });
-
- test("processes raw webm input into a valid mp4 output", async () => {
- const rawWebmPath = join(
- FIXTURES_DIR,
- `generated-${Date.now()}-${Math.random().toString(36).slice(2)}.webm`,
- );
- tempFiles.push(rawWebmPath);
-
- execFileSync("ffmpeg", [
- "-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();
- }, 120000);
-});
diff --git a/apps/media-server/src/__tests__/lib/ffmpeg.integration.test.ts b/apps/media-server/src/__tests__/lib/ffmpeg.integration.test.ts
deleted file mode 100644
index 9b440801e..000000000
--- a/apps/media-server/src/__tests__/lib/ffmpeg.integration.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { describe, expect, test } from "bun:test";
-import { join } from "node:path";
-import { checkHasAudioTrack, extractAudio } from "../../lib/ffmpeg";
-
-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")}`;
-
-describe("ffmpeg 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);
- expect(audioData.length).toBeGreaterThan(0);
-
- const hasId3Tag =
- audioData[0] === 0x49 && audioData[1] === 0x44 && audioData[2] === 0x33;
- const hasMpegSync =
- audioData[0] === 0xff && (audioData[1] & 0xe0) === 0xe0;
- expect(hasId3Tag || hasMpegSync).toBe(true);
- });
-
- test("throws error for video without audio track", async () => {
- await expect(extractAudio(TEST_VIDEO_NO_AUDIO)).rejects.toThrow();
- });
- });
-});
diff --git a/apps/media-server/src/__tests__/lib/ffprobe.integration.test.ts b/apps/media-server/src/__tests__/lib/ffprobe.integration.test.ts
deleted file mode 100644
index 6bc6a186a..000000000
--- a/apps/media-server/src/__tests__/lib/ffprobe.integration.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { describe, expect, test } from "bun:test";
-import { join } from "node:path";
-import { checkVideoAccessible, probeVideo } from "../../lib/ffprobe";
-
-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")}`;
-
-describe("ffprobe 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 expect(
- probeVideo("file:///nonexistent/path/to/video.mp4"),
- ).rejects.toThrow();
- });
-
- test("throws error for invalid URL", async () => {
- await expect(
- probeVideo(
- "https://invalid-domain-that-does-not-exist.example/video.mp4",
- ),
- ).rejects.toThrow();
- });
- });
-
- 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("ffprobe 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);
- });
-});