Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add video processing and thumbnail API with tests

Richie McIlroy21aa45a31a3b
diff --git a/apps/media-server/src/__tests__/index.test.ts b/apps/media-server/src/__tests__/index.test.ts
index 0eda76841..ad7cc1539 100644
--- a/apps/media-server/src/__tests__/index.test.ts
+++ b/apps/media-server/src/__tests__/index.test.ts
@@ -10,7 +10,18 @@ describe("GET /", () => {
expect(data).toEqual({
name: "@cap/media-server",
version: "1.0.0",
- endpoints: ["/health", "/audio/status", "/audio/check", "/audio/extract"],
+ endpoints: [
+ "/health",
+ "/audio/status",
+ "/audio/check",
+ "/audio/extract",
+ "/video/status",
+ "/video/probe",
+ "/video/thumbnail",
+ "/video/process",
+ "/video/process/:jobId/status",
+ "/video/process/:jobId/cancel",
+ ],
});
});
});
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
new file mode 100644
index 000000000..9cdb43a83
--- /dev/null
+++ b/apps/media-server/src/__tests__/lib/ffmpeg-video.integration.test.ts
@@ -0,0 +1,168 @@
+import { afterAll, describe, expect, test } from "bun:test";
+import { existsSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { generateThumbnail, processVideo } 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("processVideo integration tests", () => {
+ 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();
+ });
+});
diff --git a/apps/media-server/src/__tests__/lib/ffprobe.integration.test.ts b/apps/media-server/src/__tests__/lib/ffprobe.integration.test.ts
new file mode 100644
index 000000000..6bc6a186a
--- /dev/null
+++ b/apps/media-server/src/__tests__/lib/ffprobe.integration.test.ts
@@ -0,0 +1,95 @@
+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);
+ });
+});
diff --git a/apps/media-server/src/__tests__/routes/video.test.ts b/apps/media-server/src/__tests__/routes/video.test.ts
new file mode 100644
index 000000000..d563e5eba
--- /dev/null
+++ b/apps/media-server/src/__tests__/routes/video.test.ts
@@ -0,0 +1,595 @@
+import { beforeEach, describe, expect, mock, test } from "bun:test";
+import app from "../../app";
+import * as ffmpegVideo from "../../lib/ffmpeg-video";
+import * as ffprobe from "../../lib/ffprobe";
+import * as jobManager from "../../lib/job-manager";
+
+describe("GET /video/status", () => {
+ test("returns server status", async () => {
+ const response = await app.fetch(
+ new Request("http://localhost/video/status", {
+ method: "GET",
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ const data = await response.json();
+ expect(data).toHaveProperty("activeVideoProcesses");
+ expect(data).toHaveProperty("activeProbeProcesses");
+ expect(data).toHaveProperty("canAcceptNewVideoProcess");
+ expect(data).toHaveProperty("canAcceptNewProbeProcess");
+ expect(data).toHaveProperty("jobCount");
+ expect(data).toHaveProperty("jobs");
+ expect(Array.isArray(data.jobs)).toBe(true);
+ });
+});
+
+describe("POST /video/probe", () => {
+ beforeEach(() => {
+ mock.restore();
+ });
+
+ test("returns 400 for missing videoUrl", async () => {
+ const response = await app.fetch(
+ new Request("http://localhost/video/probe", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({}),
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ const data = await response.json();
+ expect(data.code).toBe("INVALID_REQUEST");
+ });
+
+ test("returns 400 for invalid URL format", async () => {
+ const response = await app.fetch(
+ new Request("http://localhost/video/probe", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl: "not-a-valid-url" }),
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ const data = await response.json();
+ expect(data.code).toBe("INVALID_REQUEST");
+ });
+
+ test("returns metadata when probe succeeds", async () => {
+ const mockMetadata = {
+ duration: 10.5,
+ width: 1920,
+ height: 1080,
+ fps: 30,
+ videoCodec: "h264",
+ audioCodec: "aac",
+ audioChannels: 2,
+ sampleRate: 48000,
+ bitrate: 5000000,
+ fileSize: 6553600,
+ };
+
+ mock.module("../../lib/ffprobe", () => ({
+ probeVideo: async () => mockMetadata,
+ canAcceptNewProbeProcess: ffprobe.canAcceptNewProbeProcess,
+ getActiveProbeProcessCount: ffprobe.getActiveProbeProcessCount,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/video/probe", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ const data = await response.json();
+ expect(data.metadata).toEqual(mockMetadata);
+ });
+
+ test("returns 503 when server is busy", async () => {
+ mock.module("../../lib/ffprobe", () => ({
+ probeVideo: async () => {
+ throw new Error("Server is busy, please try again later");
+ },
+ canAcceptNewProbeProcess: ffprobe.canAcceptNewProbeProcess,
+ getActiveProbeProcessCount: ffprobe.getActiveProbeProcessCount,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/video/probe", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),
+ }),
+ );
+
+ expect(response.status).toBe(503);
+ const data = await response.json();
+ expect(data.code).toBe("SERVER_BUSY");
+ });
+
+ test("returns 504 when probe times out", async () => {
+ mock.module("../../lib/ffprobe", () => ({
+ probeVideo: async () => {
+ throw new Error("Operation timed out after 30000ms");
+ },
+ canAcceptNewProbeProcess: ffprobe.canAcceptNewProbeProcess,
+ getActiveProbeProcessCount: ffprobe.getActiveProbeProcessCount,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/video/probe", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),
+ }),
+ );
+
+ expect(response.status).toBe(504);
+ const data = await response.json();
+ expect(data.code).toBe("TIMEOUT");
+ });
+
+ test("returns 500 when ffprobe fails", async () => {
+ mock.module("../../lib/ffprobe", () => ({
+ probeVideo: async () => {
+ throw new Error("ffprobe failed: no such file");
+ },
+ canAcceptNewProbeProcess: ffprobe.canAcceptNewProbeProcess,
+ getActiveProbeProcessCount: ffprobe.getActiveProbeProcessCount,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/video/probe", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),
+ }),
+ );
+
+ expect(response.status).toBe(500);
+ const data = await response.json();
+ expect(data.code).toBe("FFPROBE_ERROR");
+ expect(data.details).toContain("ffprobe failed");
+ });
+});
+
+describe("POST /video/thumbnail", () => {
+ beforeEach(() => {
+ mock.restore();
+ });
+
+ test("returns 400 for missing videoUrl", async () => {
+ const response = await app.fetch(
+ new Request("http://localhost/video/thumbnail", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({}),
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ const data = await response.json();
+ expect(data.code).toBe("INVALID_REQUEST");
+ });
+
+ test("returns 400 for invalid URL format", async () => {
+ const response = await app.fetch(
+ new Request("http://localhost/video/thumbnail", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl: "not-a-url" }),
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ const data = await response.json();
+ expect(data.code).toBe("INVALID_REQUEST");
+ });
+
+ test("returns thumbnail image when generation succeeds", async () => {
+ const mockThumbnailData = new Uint8Array([
+ 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46,
+ ]);
+ const mockMetadata = {
+ duration: 10.5,
+ width: 1920,
+ height: 1080,
+ fps: 30,
+ videoCodec: "h264",
+ audioCodec: null,
+ audioChannels: null,
+ sampleRate: null,
+ bitrate: 5000000,
+ fileSize: 6553600,
+ };
+
+ mock.module("../../lib/ffprobe", () => ({
+ probeVideo: async () => mockMetadata,
+ canAcceptNewProbeProcess: ffprobe.canAcceptNewProbeProcess,
+ getActiveProbeProcessCount: ffprobe.getActiveProbeProcessCount,
+ }));
+
+ mock.module("../../lib/ffmpeg-video", () => ({
+ generateThumbnail: async () => mockThumbnailData,
+ downloadVideoToTemp: ffmpegVideo.downloadVideoToTemp,
+ processVideo: ffmpegVideo.processVideo,
+ uploadToS3: ffmpegVideo.uploadToS3,
+ uploadFileToS3: ffmpegVideo.uploadFileToS3,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/video/thumbnail", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("Content-Type")).toBe("image/jpeg");
+ expect(response.headers.get("Content-Length")).toBe(
+ mockThumbnailData.length.toString(),
+ );
+
+ const buffer = await response.arrayBuffer();
+ expect(new Uint8Array(buffer)).toEqual(mockThumbnailData);
+ });
+});
+
+describe("POST /video/process", () => {
+ beforeEach(() => {
+ mock.restore();
+ });
+
+ test("returns 400 for missing required fields", async () => {
+ const response = await app.fetch(
+ new Request("http://localhost/video/process", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({}),
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ const data = await response.json();
+ expect(data.code).toBe("INVALID_REQUEST");
+ });
+
+ test("returns 400 for missing videoUrl", async () => {
+ const response = await app.fetch(
+ new Request("http://localhost/video/process", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ videoId: "test-id",
+ userId: "user-id",
+ outputPresignedUrl: "https://s3.example.com/output",
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ const data = await response.json();
+ expect(data.code).toBe("INVALID_REQUEST");
+ });
+
+ test("returns 400 for invalid outputPresignedUrl", async () => {
+ const response = await app.fetch(
+ new Request("http://localhost/video/process", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ videoId: "test-id",
+ userId: "user-id",
+ videoUrl: "https://example.com/video.mp4",
+ outputPresignedUrl: "not-a-url",
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ const data = await response.json();
+ expect(data.code).toBe("INVALID_REQUEST");
+ });
+
+ test("returns 503 when server is busy", async () => {
+ mock.module("../../lib/job-manager", () => ({
+ canAcceptNewVideoProcess: () => false,
+ getActiveVideoProcessCount: jobManager.getActiveVideoProcessCount,
+ getAllJobs: jobManager.getAllJobs,
+ generateJobId: jobManager.generateJobId,
+ createJob: jobManager.createJob,
+ incrementActiveVideoProcesses: jobManager.incrementActiveVideoProcesses,
+ decrementActiveVideoProcesses: jobManager.decrementActiveVideoProcesses,
+ getJob: jobManager.getJob,
+ updateJob: jobManager.updateJob,
+ deleteJob: jobManager.deleteJob,
+ sendWebhook: jobManager.sendWebhook,
+ getJobProgress: jobManager.getJobProgress,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/video/process", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ videoId: "test-id",
+ userId: "user-id",
+ videoUrl: "https://example.com/video.mp4",
+ outputPresignedUrl: "https://s3.example.com/output",
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(503);
+ const data = await response.json();
+ expect(data.code).toBe("SERVER_BUSY");
+ });
+
+ test("returns jobId when process starts successfully", async () => {
+ mock.module("../../lib/job-manager", () => ({
+ canAcceptNewVideoProcess: () => true,
+ getActiveVideoProcessCount: () => 0,
+ getAllJobs: () => [],
+ generateJobId: () => "test-job-id",
+ createJob: () => ({
+ jobId: "test-job-id",
+ videoId: "test-id",
+ userId: "user-id",
+ phase: "queued",
+ progress: 0,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ }),
+ incrementActiveVideoProcesses: () => {},
+ decrementActiveVideoProcesses: () => {},
+ getJob: () => null,
+ updateJob: () => null,
+ deleteJob: () => {},
+ sendWebhook: async () => {},
+ getJobProgress: jobManager.getJobProgress,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/video/process", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ videoId: "test-id",
+ userId: "user-id",
+ videoUrl: "https://example.com/video.mp4",
+ outputPresignedUrl: "https://s3.example.com/output",
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ const data = await response.json();
+ expect(data.jobId).toBe("test-job-id");
+ expect(data.status).toBe("queued");
+ });
+});
+
+describe("GET /video/process/:jobId/status", () => {
+ beforeEach(() => {
+ mock.restore();
+ });
+
+ test("returns 404 for non-existent job", async () => {
+ const response = await app.fetch(
+ new Request("http://localhost/video/process/nonexistent-job/status", {
+ method: "GET",
+ }),
+ );
+
+ expect(response.status).toBe(404);
+ const data = await response.json();
+ expect(data.code).toBe("NOT_FOUND");
+ });
+
+ test("returns job progress when job exists", async () => {
+ mock.module("../../lib/job-manager", () => ({
+ canAcceptNewVideoProcess: () => true,
+ getActiveVideoProcessCount: () => 0,
+ getAllJobs: () => [],
+ generateJobId: () => "test-job-id",
+ createJob: jobManager.createJob,
+ incrementActiveVideoProcesses: () => {},
+ decrementActiveVideoProcesses: () => {},
+ getJob: () => ({
+ jobId: "test-job-id",
+ videoId: "test-video",
+ userId: "test-user",
+ phase: "processing",
+ progress: 50,
+ message: "Processing video...",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ }),
+ updateJob: () => null,
+ deleteJob: () => {},
+ sendWebhook: async () => {},
+ getJobProgress: (job: any) => ({
+ phase: job.phase,
+ progress: job.progress,
+ message: job.message,
+ }),
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/video/process/test-job-id/status", {
+ method: "GET",
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ const data = await response.json();
+ expect(data.phase).toBe("processing");
+ expect(data.progress).toBe(50);
+ });
+});
+
+describe("POST /video/process/:jobId/cancel", () => {
+ beforeEach(() => {
+ mock.restore();
+ });
+
+ test("returns 404 for non-existent job", async () => {
+ mock.module("../../lib/job-manager", () => ({
+ canAcceptNewVideoProcess: () => true,
+ getActiveVideoProcessCount: () => 0,
+ getAllJobs: () => [],
+ generateJobId: () => "test-job-id",
+ createJob: jobManager.createJob,
+ incrementActiveVideoProcesses: () => {},
+ decrementActiveVideoProcesses: () => {},
+ getJob: () => null,
+ updateJob: () => null,
+ deleteJob: () => {},
+ sendWebhook: async () => {},
+ getJobProgress: jobManager.getJobProgress,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/video/process/nonexistent-job/cancel", {
+ method: "POST",
+ }),
+ );
+
+ expect(response.status).toBe(404);
+ const data = await response.json();
+ expect(data.code).toBe("NOT_FOUND");
+ });
+
+ test("returns 400 when trying to cancel completed job", async () => {
+ mock.module("../../lib/job-manager", () => ({
+ canAcceptNewVideoProcess: () => true,
+ getActiveVideoProcessCount: () => 0,
+ getAllJobs: () => [],
+ generateJobId: () => "test-job-id",
+ createJob: jobManager.createJob,
+ incrementActiveVideoProcesses: () => {},
+ decrementActiveVideoProcesses: () => {},
+ getJob: () => ({
+ jobId: "test-job-id",
+ videoId: "test-video",
+ userId: "test-user",
+ phase: "complete",
+ progress: 100,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ }),
+ updateJob: () => null,
+ deleteJob: () => {},
+ sendWebhook: async () => {},
+ getJobProgress: jobManager.getJobProgress,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/video/process/test-job-id/cancel", {
+ method: "POST",
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ const data = await response.json();
+ expect(data.code).toBe("INVALID_STATE");
+ expect(data.currentPhase).toBe("complete");
+ });
+
+ test("successfully cancels running job", async () => {
+ const abortController = new AbortController();
+ let abortCalled = false;
+
+ mock.module("../../lib/job-manager", () => ({
+ canAcceptNewVideoProcess: () => true,
+ getActiveVideoProcessCount: () => 0,
+ getAllJobs: () => [],
+ generateJobId: () => "test-job-id",
+ createJob: jobManager.createJob,
+ incrementActiveVideoProcesses: () => {},
+ decrementActiveVideoProcesses: () => {},
+ getJob: () => ({
+ jobId: "test-job-id",
+ videoId: "test-video",
+ userId: "test-user",
+ phase: "processing",
+ progress: 50,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ abortController: {
+ abort: () => {
+ abortCalled = true;
+ },
+ },
+ }),
+ updateJob: () => null,
+ deleteJob: () => {},
+ sendWebhook: async () => {},
+ getJobProgress: jobManager.getJobProgress,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/video/process/test-job-id/cancel", {
+ method: "POST",
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ const data = await response.json();
+ expect(data.success).toBe(true);
+ expect(abortCalled).toBe(true);
+ });
+});
+
+describe("POST /video/cleanup", () => {
+ beforeEach(() => {
+ mock.restore();
+ });
+
+ test("returns cleanup result", async () => {
+ mock.module("../../lib/temp-files", () => ({
+ cleanupStaleTempFiles: async () => 5,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/video/cleanup", {
+ method: "POST",
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ const data = await response.json();
+ expect(data.success).toBe(true);
+ expect(data.cleanedFiles).toBe(5);
+ });
+});
diff --git a/apps/media-server/src/app.ts b/apps/media-server/src/app.ts
index dc29e3c4e..5f6e4d9c2 100644
--- a/apps/media-server/src/app.ts
+++ b/apps/media-server/src/app.ts
@@ -2,6 +2,7 @@ import { Hono } from "hono";
import { logger } from "hono/logger";
import audio from "./routes/audio";
import health from "./routes/health";
+import video from "./routes/video";
const app = new Hono();
@@ -9,12 +10,24 @@ app.use("*", logger());
app.route("/health", health);
app.route("/audio", audio);
+app.route("/video", video);
app.get("/", (c) => {
return c.json({
name: "@cap/media-server",
version: "1.0.0",
- endpoints: ["/health", "/audio/status", "/audio/check", "/audio/extract"],
+ endpoints: [
+ "/health",
+ "/audio/status",
+ "/audio/check",
+ "/audio/extract",
+ "/video/status",
+ "/video/probe",
+ "/video/thumbnail",
+ "/video/process",
+ "/video/process/:jobId/status",
+ "/video/process/:jobId/cancel",
+ ],
});
});
diff --git a/apps/media-server/src/lib/ffmpeg-video.ts b/apps/media-server/src/lib/ffmpeg-video.ts
new file mode 100644
index 000000000..e8c0db9a3
--- /dev/null
+++ b/apps/media-server/src/lib/ffmpeg-video.ts
@@ -0,0 +1,457 @@
+import { file, type Subprocess, spawn } from "bun";
+import type { VideoMetadata } from "./job-manager";
+import { createTempFile, type TempFileHandle } from "./temp-files";
+
+const PROCESS_TIMEOUT_MS = 30 * 60 * 1000;
+const THUMBNAIL_TIMEOUT_MS = 60_000;
+const DOWNLOAD_TIMEOUT_MS = 10 * 60 * 1000;
+const MAX_STDERR_BYTES = 64 * 1024;
+
+export interface VideoProcessingOptions {
+ maxWidth?: number;
+ maxHeight?: number;
+ videoBitrate?: string;
+ audioBitrate?: string;
+ crf?: number;
+ preset?: "ultrafast" | "fast" | "medium" | "slow";
+}
+
+const DEFAULT_OPTIONS: Required<VideoProcessingOptions> = {
+ maxWidth: 1920,
+ maxHeight: 1080,
+ videoBitrate: "5M",
+ audioBitrate: "128k",
+ crf: 23,
+ preset: "medium",
+};
+
+export interface ThumbnailOptions {
+ timestamp?: number;
+ width?: number;
+ height?: number;
+ quality?: number;
+}
+
+const DEFAULT_THUMBNAIL_OPTIONS: Required<ThumbnailOptions> = {
+ timestamp: 1,
+ width: 1280,
+ height: 720,
+ quality: 85,
+};
+
+function killProcess(proc: Subprocess): void {
+ try {
+ proc.kill();
+ } catch {}
+}
+
+async function withTimeout<T>(
+ promise: Promise<T>,
+ timeoutMs: number,
+ cleanup?: () => void,
+): Promise<T> {
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
+ const timeoutPromise = new Promise<never>((_, reject) => {
+ timeoutId = setTimeout(() => {
+ cleanup?.();
+ reject(new Error(`Operation timed out after ${timeoutMs}ms`));
+ }, timeoutMs);
+ });
+
+ try {
+ const result = await Promise.race([promise, timeoutPromise]);
+ if (timeoutId) clearTimeout(timeoutId);
+ return result;
+ } catch (err) {
+ if (timeoutId) clearTimeout(timeoutId);
+ throw err;
+ }
+}
+
+async function drainStream(
+ stream: ReadableStream<Uint8Array> | null,
+): Promise<void> {
+ if (!stream) return;
+ try {
+ const reader = stream.getReader();
+ while (true) {
+ const { done } = await reader.read();
+ if (done) break;
+ }
+ reader.releaseLock();
+ } catch {}
+}
+
+async function readStreamWithLimit(
+ stream: ReadableStream<Uint8Array>,
+ maxBytes: number,
+): Promise<string> {
+ const reader = stream.getReader();
+ const chunks: Uint8Array[] = [];
+ let totalBytes = 0;
+
+ try {
+ while (totalBytes < maxBytes) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ totalBytes += value.length;
+ }
+ } finally {
+ reader.releaseLock();
+ }
+
+ const decoder = new TextDecoder();
+ return chunks
+ .map((chunk) => decoder.decode(chunk, { stream: true }))
+ .join("");
+}
+
+export type ProgressCallback = (progress: number, message: string) => void;
+
+function parseProgressFromStderr(
+ stderrLine: string,
+ totalDurationUs: number,
+): number | null {
+ const match = stderrLine.match(/out_time_us=(\d+)/);
+ if (!match) return null;
+ const currentUs = Number.parseInt(match[1] ?? "0", 10);
+ return Math.min(100, (currentUs / totalDurationUs) * 100);
+}
+
+function needsVideoTranscode(
+ metadata: VideoMetadata,
+ options: VideoProcessingOptions,
+): boolean {
+ const maxWidth = options.maxWidth ?? DEFAULT_OPTIONS.maxWidth;
+ const maxHeight = options.maxHeight ?? DEFAULT_OPTIONS.maxHeight;
+
+ const needsResize = metadata.width > maxWidth || metadata.height > maxHeight;
+ const needsCodecChange = metadata.videoCodec !== "h264";
+
+ return needsResize || needsCodecChange;
+}
+
+function needsAudioTranscode(metadata: VideoMetadata): boolean {
+ if (!metadata.audioCodec) return false;
+ return metadata.audioCodec !== "aac";
+}
+
+export async function downloadVideoToTemp(
+ videoUrl: string,
+ abortSignal?: AbortSignal,
+): Promise<TempFileHandle> {
+ const tempFile = await createTempFile(".mp4");
+
+ console.log(
+ `[downloadVideoToTemp] Downloading from URL: ${videoUrl.substring(0, 100)}...`,
+ );
+
+ try {
+ const response = await fetch(videoUrl, {
+ signal: abortSignal ?? AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),
+ });
+
+ console.log(
+ `[downloadVideoToTemp] Response status: ${response.status}, content-type: ${response.headers.get("content-type")}, content-length: ${response.headers.get("content-length")}`,
+ );
+
+ if (!response.ok) {
+ const errorBody = await response.text().catch(() => "");
+ console.error(
+ `[downloadVideoToTemp] Error response body: ${errorBody.substring(0, 500)}`,
+ );
+ throw new Error(
+ `Failed to download video: ${response.status} ${response.statusText}`,
+ );
+ }
+
+ if (!response.body) {
+ throw new Error("No response body");
+ }
+
+ await Bun.write(tempFile.path, response.body);
+
+ const fileHandle = file(tempFile.path);
+ const fileSize = fileHandle.size;
+ console.log(
+ `[downloadVideoToTemp] Downloaded file size: ${fileSize} bytes to ${tempFile.path}`,
+ );
+
+ if (fileSize < 1000) {
+ const content = await fileHandle.text();
+ console.error(
+ `[downloadVideoToTemp] Small file content: ${content.substring(0, 500)}`,
+ );
+ }
+
+ return tempFile;
+ } catch (err) {
+ console.error(`[downloadVideoToTemp] Download failed:`, err);
+ await tempFile.cleanup();
+ throw err;
+ }
+}
+
+export async function processVideo(
+ inputPath: string,
+ metadata: VideoMetadata,
+ options: VideoProcessingOptions = {},
+ onProgress?: ProgressCallback,
+ abortSignal?: AbortSignal,
+): Promise<TempFileHandle> {
+ const opts = { ...DEFAULT_OPTIONS, ...options };
+ const outputTempFile = await createTempFile(".mp4");
+
+ const videoTranscode = needsVideoTranscode(metadata, opts);
+ const audioTranscode = needsAudioTranscode(metadata);
+
+ const ffmpegArgs: string[] = ["ffmpeg", "-i", inputPath];
+
+ if (videoTranscode) {
+ ffmpegArgs.push(
+ "-c:v",
+ "libx264",
+ "-preset",
+ opts.preset,
+ "-crf",
+ opts.crf.toString(),
+ "-vf",
+ `scale='min(${opts.maxWidth},iw)':'min(${opts.maxHeight},ih)':force_original_aspect_ratio=decrease`,
+ );
+ } else {
+ ffmpegArgs.push("-c:v", "copy");
+ }
+
+ if (metadata.audioCodec) {
+ if (audioTranscode) {
+ ffmpegArgs.push("-c:a", "aac", "-b:a", opts.audioBitrate);
+ } else {
+ ffmpegArgs.push("-c:a", "copy");
+ }
+ } else {
+ ffmpegArgs.push("-an");
+ }
+
+ ffmpegArgs.push(
+ "-movflags",
+ "+faststart",
+ "-progress",
+ "pipe:2",
+ "-y",
+ outputTempFile.path,
+ );
+
+ const proc = spawn({
+ cmd: ffmpegArgs,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+
+ const totalDurationUs = metadata.duration * 1_000_000;
+
+ 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 stderrReader = (
+ proc.stderr as ReadableStream<Uint8Array>
+ ).getReader();
+ const decoder = new TextDecoder();
+ let stderrBuffer = "";
+
+ try {
+ while (true) {
+ const { done, value } = await stderrReader.read();
+ if (done) break;
+
+ stderrBuffer += decoder.decode(value, { stream: true });
+
+ const lines = stderrBuffer.split("\n");
+ stderrBuffer = lines.pop() ?? "";
+
+ for (const line of lines) {
+ const progress = parseProgressFromStderr(line, totalDurationUs);
+ if (progress !== null && onProgress) {
+ onProgress(progress, `Encoding: ${Math.round(progress)}%`);
+ }
+ }
+ }
+ } finally {
+ stderrReader.releaseLock();
+ }
+
+ const exitCode = await proc.exited;
+
+ if (exitCode !== 0) {
+ throw new Error(`FFmpeg exited with code ${exitCode}`);
+ }
+
+ const outputFile = file(outputTempFile.path);
+ const outputSize = await outputFile.size;
+ if (outputSize === 0) {
+ throw new Error("FFmpeg produced empty output file");
+ }
+ })(),
+ PROCESS_TIMEOUT_MS,
+ () => killProcess(proc),
+ );
+
+ return outputTempFile;
+ } catch (err) {
+ await outputTempFile.cleanup();
+ throw err;
+ } finally {
+ if (abortCleanup) {
+ abortSignal?.removeEventListener("abort", abortCleanup);
+ }
+ killProcess(proc);
+ }
+}
+
+export async function generateThumbnail(
+ inputPath: string,
+ duration: number,
+ options: ThumbnailOptions = {},
+): Promise<Uint8Array> {
+ const opts = { ...DEFAULT_THUMBNAIL_OPTIONS, ...options };
+
+ let timestamp = opts.timestamp;
+ if (timestamp === undefined || timestamp <= 0) {
+ timestamp = Math.min(duration / 4, 1);
+ }
+ timestamp = Math.min(timestamp, duration - 0.1);
+
+ const qualityValue = Math.max(
+ 2,
+ Math.min(31, Math.round(31 - (opts.quality / 100) * 29)),
+ );
+
+ const ffmpegArgs = [
+ "ffmpeg",
+ "-ss",
+ timestamp.toString(),
+ "-i",
+ inputPath,
+ "-vframes",
+ "1",
+ "-vf",
+ `scale='min(${opts.width},iw)':'min(${opts.height},ih)':force_original_aspect_ratio=decrease`,
+ "-q:v",
+ qualityValue.toString(),
+ "-f",
+ "image2",
+ "pipe:1",
+ ];
+
+ const proc = spawn({
+ cmd: ffmpegArgs,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+
+ try {
+ const result = await withTimeout(
+ (async () => {
+ const stderrPromise = readStreamWithLimit(
+ proc.stderr as ReadableStream<Uint8Array>,
+ MAX_STDERR_BYTES,
+ );
+
+ const chunks: Uint8Array[] = [];
+ let totalBytes = 0;
+ const reader = (proc.stdout as ReadableStream<Uint8Array>).getReader();
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ totalBytes += value.length;
+ }
+ } finally {
+ reader.releaseLock();
+ }
+
+ const [, exitCode] = await Promise.all([stderrPromise, proc.exited]);
+
+ if (exitCode !== 0) {
+ throw new Error(`FFmpeg thumbnail exited with code ${exitCode}`);
+ }
+
+ if (totalBytes === 0) {
+ throw new Error("FFmpeg produced empty thumbnail");
+ }
+
+ const output = new Uint8Array(totalBytes);
+ let offset = 0;
+ for (const chunk of chunks) {
+ output.set(chunk, offset);
+ offset += chunk.length;
+ }
+
+ return output;
+ })(),
+ THUMBNAIL_TIMEOUT_MS,
+ () => killProcess(proc),
+ );
+
+ return result;
+ } finally {
+ killProcess(proc);
+ }
+}
+
+export async function uploadToS3(
+ data: Uint8Array | Blob | ReadableStream<Uint8Array>,
+ presignedUrl: string,
+ contentType: string,
+): Promise<void> {
+ const response = await fetch(presignedUrl, {
+ method: "PUT",
+ headers: {
+ "Content-Type": contentType,
+ },
+ body: data,
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ `Failed to upload to S3: ${response.status} ${response.statusText}`,
+ );
+ }
+}
+
+export async function uploadFileToS3(
+ filePath: string,
+ presignedUrl: string,
+ contentType: string,
+): Promise<void> {
+ const fileHandle = file(filePath);
+ const stream = fileHandle.stream();
+
+ const response = await fetch(presignedUrl, {
+ method: "PUT",
+ headers: {
+ "Content-Type": contentType,
+ "Content-Length": fileHandle.size.toString(),
+ },
+ body: stream,
+ duplex: "half",
+ } as RequestInit);
+
+ if (!response.ok) {
+ throw new Error(
+ `Failed to upload file to S3: ${response.status} ${response.statusText}`,
+ );
+ }
+}
diff --git a/apps/media-server/src/lib/ffprobe.ts b/apps/media-server/src/lib/ffprobe.ts
new file mode 100644
index 000000000..5cde045d8
--- /dev/null
+++ b/apps/media-server/src/lib/ffprobe.ts
@@ -0,0 +1,203 @@
+import { type Subprocess, spawn } from "bun";
+import type { VideoMetadata } from "./job-manager";
+
+const PROBE_TIMEOUT_MS = 30_000;
+const MAX_OUTPUT_BYTES = 1024 * 1024;
+
+let activeProbeProcesses = 0;
+const MAX_CONCURRENT_PROBE_PROCESSES = 6;
+
+export function getActiveProbeProcessCount(): number {
+ return activeProbeProcesses;
+}
+
+export function canAcceptNewProbeProcess(): boolean {
+ return activeProbeProcesses < MAX_CONCURRENT_PROBE_PROCESSES;
+}
+
+function killProcess(proc: Subprocess): void {
+ try {
+ proc.kill();
+ } catch {}
+}
+
+async function withTimeout<T>(
+ promise: Promise<T>,
+ timeoutMs: number,
+ cleanup?: () => void,
+): Promise<T> {
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
+ const timeoutPromise = new Promise<never>((_, reject) => {
+ timeoutId = setTimeout(() => {
+ cleanup?.();
+ reject(new Error(`Operation timed out after ${timeoutMs}ms`));
+ }, timeoutMs);
+ });
+
+ try {
+ const result = await Promise.race([promise, timeoutPromise]);
+ if (timeoutId) clearTimeout(timeoutId);
+ return result;
+ } catch (err) {
+ if (timeoutId) clearTimeout(timeoutId);
+ throw err;
+ }
+}
+
+async function readStreamToString(
+ stream: ReadableStream<Uint8Array>,
+ maxBytes: number,
+): Promise<string> {
+ const reader = stream.getReader();
+ const chunks: Uint8Array[] = [];
+ let totalBytes = 0;
+
+ try {
+ while (totalBytes < maxBytes) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ totalBytes += value.length;
+ }
+ } finally {
+ reader.releaseLock();
+ }
+
+ const decoder = new TextDecoder();
+ return chunks
+ .map((chunk) => decoder.decode(chunk, { stream: true }))
+ .join("");
+}
+
+interface FFprobeOutput {
+ format?: {
+ duration?: string;
+ size?: string;
+ bit_rate?: string;
+ };
+ streams?: Array<{
+ codec_type?: "video" | "audio";
+ codec_name?: string;
+ width?: number;
+ height?: number;
+ r_frame_rate?: string;
+ avg_frame_rate?: string;
+ channels?: number;
+ sample_rate?: string;
+ }>;
+}
+
+function parseFrameRate(rateStr: string | undefined): number {
+ if (!rateStr) return 0;
+ const parts = rateStr.split("/");
+ if (parts.length === 2) {
+ const num = Number.parseFloat(parts[0] ?? "0");
+ const den = Number.parseFloat(parts[1] ?? "1");
+ if (den !== 0) return num / den;
+ }
+ return Number.parseFloat(rateStr) || 0;
+}
+
+export async function probeVideo(videoUrl: 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",
+ videoUrl,
+ ],
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+
+ try {
+ const result = await withTimeout(
+ (async () => {
+ const stdoutText = await readStreamToString(
+ proc.stdout as ReadableStream<Uint8Array>,
+ MAX_OUTPUT_BYTES,
+ );
+
+ const exitCode = await proc.exited;
+
+ if (exitCode !== 0) {
+ throw new Error(`ffprobe exited with code ${exitCode}`);
+ }
+
+ const data: FFprobeOutput = JSON.parse(stdoutText);
+
+ console.log(
+ `[probeVideo] ffprobe output for ${videoUrl.substring(0, 80)}...: format=${JSON.stringify(data.format)}, streams=${data.streams?.length ?? 0}`,
+ );
+ if (data.streams) {
+ for (const stream of data.streams) {
+ console.log(
+ `[probeVideo] Stream: codec_type=${stream.codec_type}, codec_name=${stream.codec_name}, width=${stream.width}, height=${stream.height}`,
+ );
+ }
+ }
+
+ const videoStream = data.streams?.find((s) => s.codec_type === "video");
+ const audioStream = data.streams?.find((s) => s.codec_type === "audio");
+
+ if (!videoStream) {
+ console.error(
+ `[probeVideo] No video stream found in file. Raw output: ${stdoutText.substring(0, 500)}`,
+ );
+ 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, {
+ method: "HEAD",
+ signal: AbortSignal.timeout(10_000),
+ });
+ return response.ok;
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/media-server/src/lib/job-manager.ts b/apps/media-server/src/lib/job-manager.ts
new file mode 100644
index 000000000..d95ac0dc9
--- /dev/null
+++ b/apps/media-server/src/lib/job-manager.ts
@@ -0,0 +1,208 @@
+import type { Subprocess } from "bun";
+import type { TempFileHandle } from "./temp-files";
+
+export type JobPhase =
+ | "queued"
+ | "downloading"
+ | "probing"
+ | "processing"
+ | "uploading"
+ | "generating_thumbnail"
+ | "complete"
+ | "error"
+ | "cancelled";
+
+export interface JobProgress {
+ jobId: string;
+ videoId: string;
+ phase: JobPhase;
+ progress: number;
+ message?: string;
+ error?: string;
+ metadata?: VideoMetadata;
+ outputUrl?: string;
+}
+
+export interface VideoMetadata {
+ duration: number;
+ width: number;
+ height: number;
+ fps: number;
+ videoCodec: string;
+ audioCodec: string | null;
+ audioChannels: number | null;
+ sampleRate: number | null;
+ bitrate: number;
+ fileSize: number;
+}
+
+export interface Job {
+ jobId: string;
+ videoId: string;
+ userId: string;
+ phase: JobPhase;
+ progress: number;
+ message?: string;
+ error?: string;
+ metadata?: VideoMetadata;
+ outputUrl?: string;
+ createdAt: number;
+ updatedAt: number;
+ inputTempFile?: TempFileHandle;
+ outputTempFile?: TempFileHandle;
+ process?: Subprocess;
+ webhookUrl?: string;
+ abortController?: AbortController;
+}
+
+const jobs = new Map<string, Job>();
+const JOB_TTL_MS = 60 * 60 * 1000;
+
+let activeVideoProcesses = 0;
+const MAX_CONCURRENT_VIDEO_PROCESSES = 3;
+
+export function getActiveVideoProcessCount(): number {
+ return activeVideoProcesses;
+}
+
+export function canAcceptNewVideoProcess(): boolean {
+ return activeVideoProcesses < MAX_CONCURRENT_VIDEO_PROCESSES;
+}
+
+export function incrementActiveVideoProcesses(): void {
+ activeVideoProcesses++;
+}
+
+export function decrementActiveVideoProcesses(): void {
+ if (activeVideoProcesses > 0) {
+ activeVideoProcesses--;
+ }
+}
+
+export function generateJobId(): string {
+ return `job_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
+}
+
+export function createJob(
+ jobId: string,
+ videoId: string,
+ userId: string,
+ webhookUrl?: string,
+): Job {
+ const now = Date.now();
+ const job: Job = {
+ jobId,
+ videoId,
+ userId,
+ phase: "queued",
+ progress: 0,
+ createdAt: now,
+ updatedAt: now,
+ webhookUrl,
+ };
+ jobs.set(jobId, job);
+ return job;
+}
+
+export function getJob(jobId: string): Job | undefined {
+ return jobs.get(jobId);
+}
+
+export function updateJob(
+ jobId: string,
+ updates: Partial<
+ Pick<
+ Job,
+ | "phase"
+ | "progress"
+ | "message"
+ | "error"
+ | "metadata"
+ | "outputUrl"
+ | "inputTempFile"
+ | "outputTempFile"
+ | "process"
+ | "abortController"
+ >
+ >,
+): Job | undefined {
+ const job = jobs.get(jobId);
+ if (!job) return undefined;
+
+ Object.assign(job, updates, { updatedAt: Date.now() });
+ return job;
+}
+
+export function deleteJob(jobId: string): boolean {
+ const job = jobs.get(jobId);
+ if (job) {
+ job.inputTempFile?.cleanup().catch(() => {});
+ job.outputTempFile?.cleanup().catch(() => {});
+ if (job.process) {
+ try {
+ job.process.kill();
+ } catch {}
+ }
+ }
+ return jobs.delete(jobId);
+}
+
+export function getAllJobs(): Job[] {
+ return Array.from(jobs.values());
+}
+
+export function cleanupExpiredJobs(): number {
+ const now = Date.now();
+ let cleaned = 0;
+
+ for (const [jobId, job] of jobs) {
+ if (now - job.updatedAt > JOB_TTL_MS) {
+ deleteJob(jobId);
+ cleaned++;
+ }
+ }
+
+ return cleaned;
+}
+
+export function getJobProgress(job: Job): JobProgress {
+ return {
+ jobId: job.jobId,
+ videoId: job.videoId,
+ phase: job.phase,
+ progress: job.progress,
+ message: job.message,
+ error: job.error,
+ metadata: job.metadata,
+ outputUrl: job.outputUrl,
+ };
+}
+
+export async function sendWebhook(job: Job): Promise<void> {
+ if (!job.webhookUrl) return;
+
+ const payload = getJobProgress(job);
+
+ try {
+ await fetch(job.webhookUrl, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ });
+ } catch (err) {
+ console.error(
+ `[job-manager] Failed to send webhook for job ${job.jobId}:`,
+ err,
+ );
+ }
+}
+
+setInterval(
+ () => {
+ const cleaned = cleanupExpiredJobs();
+ if (cleaned > 0) {
+ console.log(`[job-manager] Cleaned up ${cleaned} expired jobs`);
+ }
+ },
+ 5 * 60 * 1000,
+);
diff --git a/apps/media-server/src/lib/temp-files.ts b/apps/media-server/src/lib/temp-files.ts
new file mode 100644
index 000000000..5141ad6c4
--- /dev/null
+++ b/apps/media-server/src/lib/temp-files.ts
@@ -0,0 +1,61 @@
+import { randomUUID } from "node:crypto";
+import { mkdir, readdir, rm, stat, unlink } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const TEMP_DIR = join(tmpdir(), "cap-media-server");
+const STALE_FILE_AGE_MS = 60 * 60 * 1000;
+
+export interface TempFileHandle {
+ path: string;
+ cleanup: () => Promise<void>;
+}
+
+export async function ensureTempDir(): Promise<void> {
+ await mkdir(TEMP_DIR, { recursive: true });
+}
+
+export async function createTempFile(
+ extension: string,
+): Promise<TempFileHandle> {
+ await ensureTempDir();
+ const filename = `${randomUUID()}${extension.startsWith(".") ? extension : `.${extension}`}`;
+ const path = join(TEMP_DIR, filename);
+
+ return {
+ path,
+ cleanup: async () => {
+ try {
+ await unlink(path);
+ } catch {}
+ },
+ };
+}
+
+export async function cleanupStaleTempFiles(): Promise<number> {
+ try {
+ await ensureTempDir();
+ const files = await readdir(TEMP_DIR);
+ const now = Date.now();
+ let cleaned = 0;
+
+ for (const file of files) {
+ const filePath = join(TEMP_DIR, file);
+ try {
+ const fileStat = await stat(filePath);
+ if (now - fileStat.mtimeMs > STALE_FILE_AGE_MS) {
+ await rm(filePath, { force: true });
+ cleaned++;
+ }
+ } catch {}
+ }
+
+ return cleaned;
+ } catch {
+ return 0;
+ }
+}
+
+export function getTempDir(): string {
+ return TEMP_DIR;
+}
diff --git a/apps/media-server/src/routes/video.ts b/apps/media-server/src/routes/video.ts
new file mode 100644
index 000000000..543545181
--- /dev/null
+++ b/apps/media-server/src/routes/video.ts
@@ -0,0 +1,523 @@
+import { Hono } from "hono";
+import { z } from "zod";
+import {
+ downloadVideoToTemp,
+ generateThumbnail,
+ processVideo,
+ uploadFileToS3,
+ uploadToS3,
+} from "../lib/ffmpeg-video";
+import {
+ canAcceptNewProbeProcess,
+ getActiveProbeProcessCount,
+ probeVideo,
+} from "../lib/ffprobe";
+import {
+ canAcceptNewVideoProcess,
+ createJob,
+ decrementActiveVideoProcesses,
+ deleteJob,
+ generateJobId,
+ getActiveVideoProcessCount,
+ getAllJobs,
+ getJob,
+ getJobProgress,
+ incrementActiveVideoProcesses,
+ sendWebhook,
+ updateJob,
+} from "../lib/job-manager";
+import { cleanupStaleTempFiles } from "../lib/temp-files";
+
+const video = new Hono();
+
+const probeSchema = z.object({
+ videoUrl: z.string().url(),
+});
+
+const thumbnailSchema = z.object({
+ videoUrl: z.string().url(),
+ timestamp: z.number().optional(),
+ width: z.number().max(2000).optional(),
+ height: z.number().max(2000).optional(),
+ quality: z.number().min(1).max(100).optional(),
+});
+
+const processSchema = z.object({
+ videoId: z.string(),
+ userId: z.string(),
+ videoUrl: z.string().url(),
+ outputPresignedUrl: z.string().url(),
+ thumbnailPresignedUrl: z.string().url().optional(),
+ webhookUrl: z.string().url().optional(),
+ maxWidth: z.number().max(4096).optional(),
+ maxHeight: z.number().max(4096).optional(),
+ crf: z.number().min(0).max(51).optional(),
+ preset: z.enum(["ultrafast", "fast", "medium", "slow"]).optional(),
+});
+
+function isBusyError(err: unknown): boolean {
+ return err instanceof Error && err.message.includes("Server is busy");
+}
+
+function isTimeoutError(err: unknown): boolean {
+ return err instanceof Error && err.message.includes("timed out");
+}
+
+video.get("/status", (c) => {
+ const jobs = getAllJobs();
+ return c.json({
+ activeVideoProcesses: getActiveVideoProcessCount(),
+ activeProbeProcesses: getActiveProbeProcessCount(),
+ canAcceptNewVideoProcess: canAcceptNewVideoProcess(),
+ canAcceptNewProbeProcess: canAcceptNewProbeProcess(),
+ jobCount: jobs.length,
+ jobs: jobs.map((j) => ({
+ jobId: j.jobId,
+ videoId: j.videoId,
+ phase: j.phase,
+ progress: j.progress,
+ createdAt: j.createdAt,
+ updatedAt: j.updatedAt,
+ })),
+ });
+});
+
+video.post("/probe", async (c) => {
+ const body = await c.req.json();
+ const result = probeSchema.safeParse(body);
+
+ if (!result.success) {
+ return c.json(
+ {
+ error: "Invalid request",
+ code: "INVALID_REQUEST",
+ details: result.error.message,
+ },
+ 400,
+ );
+ }
+
+ try {
+ const metadata = await probeVideo(result.data.videoUrl);
+ return c.json({ metadata });
+ } catch (err) {
+ console.error("[video/probe] Error:", err);
+
+ if (isBusyError(err)) {
+ return c.json(
+ {
+ error: "Server is busy",
+ code: "SERVER_BUSY",
+ details: "Too many concurrent requests, please retry later",
+ },
+ 503,
+ );
+ }
+
+ if (isTimeoutError(err)) {
+ return c.json(
+ {
+ error: "Request timed out",
+ code: "TIMEOUT",
+ details: err instanceof Error ? err.message : String(err),
+ },
+ 504,
+ );
+ }
+
+ return c.json(
+ {
+ error: "Failed to probe video",
+ code: "FFPROBE_ERROR",
+ details: err instanceof Error ? err.message : String(err),
+ },
+ 500,
+ );
+ }
+});
+
+video.post("/thumbnail", async (c) => {
+ const body = await c.req.json();
+ const result = thumbnailSchema.safeParse(body);
+
+ if (!result.success) {
+ return c.json(
+ {
+ error: "Invalid request",
+ code: "INVALID_REQUEST",
+ details: result.error.message,
+ },
+ 400,
+ );
+ }
+
+ try {
+ const metadata = await probeVideo(result.data.videoUrl);
+
+ const thumbnailData = await generateThumbnail(
+ result.data.videoUrl,
+ metadata.duration,
+ {
+ timestamp: result.data.timestamp,
+ width: result.data.width,
+ height: result.data.height,
+ quality: result.data.quality,
+ },
+ );
+
+ return new Response(thumbnailData, {
+ headers: {
+ "Content-Type": "image/jpeg",
+ "Content-Length": thumbnailData.length.toString(),
+ },
+ });
+ } catch (err) {
+ console.error("[video/thumbnail] Error:", err);
+
+ if (isBusyError(err)) {
+ return c.json(
+ {
+ error: "Server is busy",
+ code: "SERVER_BUSY",
+ details: "Too many concurrent requests, please retry later",
+ },
+ 503,
+ );
+ }
+
+ if (isTimeoutError(err)) {
+ return c.json(
+ {
+ error: "Request timed out",
+ code: "TIMEOUT",
+ details: err instanceof Error ? err.message : String(err),
+ },
+ 504,
+ );
+ }
+
+ return c.json(
+ {
+ error: "Failed to generate thumbnail",
+ code: "FFMPEG_ERROR",
+ details: err instanceof Error ? err.message : String(err),
+ },
+ 500,
+ );
+ }
+});
+
+video.post("/process", async (c) => {
+ const body = await c.req.json();
+ const result = processSchema.safeParse(body);
+
+ if (!result.success) {
+ return c.json(
+ {
+ error: "Invalid request",
+ code: "INVALID_REQUEST",
+ details: result.error.message,
+ },
+ 400,
+ );
+ }
+
+ if (!canAcceptNewVideoProcess()) {
+ return c.json(
+ {
+ error: "Server is busy",
+ code: "SERVER_BUSY",
+ details:
+ "Too many concurrent video processing jobs, please retry later",
+ },
+ 503,
+ );
+ }
+
+ const {
+ videoId,
+ userId,
+ videoUrl,
+ outputPresignedUrl,
+ thumbnailPresignedUrl,
+ webhookUrl,
+ } = result.data;
+
+ const jobId = generateJobId();
+ const job = createJob(jobId, videoId, userId, webhookUrl);
+
+ incrementActiveVideoProcesses();
+
+ processVideoAsync(
+ job.jobId,
+ videoUrl,
+ outputPresignedUrl,
+ thumbnailPresignedUrl,
+ result.data,
+ ).catch((err) => {
+ console.error(
+ `[video/process] Async processing error for job ${jobId}:`,
+ err,
+ );
+ });
+
+ return c.json({
+ jobId,
+ status: "queued",
+ message: "Video processing started",
+ });
+});
+
+async function processVideoAsync(
+ jobId: string,
+ videoUrl: string,
+ outputPresignedUrl: string,
+ thumbnailPresignedUrl: string | undefined,
+ options: z.infer<typeof processSchema>,
+): Promise<void> {
+ const job = getJob(jobId);
+ if (!job) {
+ decrementActiveVideoProcesses();
+ return;
+ }
+
+ const abortController = new AbortController();
+ updateJob(jobId, { abortController });
+
+ try {
+ updateJob(jobId, {
+ phase: "downloading",
+ progress: 0,
+ message: "Downloading video...",
+ });
+ await sendWebhook(job);
+
+ const inputTempFile = await downloadVideoToTemp(
+ videoUrl,
+ abortController.signal,
+ );
+ updateJob(jobId, { inputTempFile });
+
+ updateJob(jobId, {
+ phase: "probing",
+ progress: 5,
+ message: "Analyzing video...",
+ });
+ await sendWebhook(job);
+
+ const metadata = await probeVideo(inputTempFile.path);
+ updateJob(jobId, { metadata });
+
+ updateJob(jobId, {
+ phase: "processing",
+ progress: 10,
+ message: "Processing video...",
+ });
+ await sendWebhook(job);
+
+ const outputTempFile = await processVideo(
+ inputTempFile.path,
+ metadata,
+ {
+ maxWidth: options.maxWidth,
+ maxHeight: options.maxHeight,
+ crf: options.crf,
+ preset: options.preset,
+ },
+ (progress, message) => {
+ const scaledProgress = 10 + progress * 0.7;
+ updateJob(jobId, { progress: scaledProgress, message });
+ sendWebhook(getJob(jobId)!);
+ },
+ abortController.signal,
+ );
+ updateJob(jobId, { outputTempFile });
+
+ updateJob(jobId, {
+ phase: "uploading",
+ progress: 80,
+ message: "Uploading processed video...",
+ });
+ await sendWebhook(job);
+
+ await uploadFileToS3(outputTempFile.path, outputPresignedUrl, "video/mp4");
+
+ if (thumbnailPresignedUrl) {
+ updateJob(jobId, {
+ phase: "generating_thumbnail",
+ progress: 90,
+ message: "Generating thumbnail...",
+ });
+ await sendWebhook(job);
+
+ const thumbnailData = await generateThumbnail(
+ outputTempFile.path,
+ metadata.duration,
+ );
+ await uploadToS3(thumbnailData, thumbnailPresignedUrl, "image/jpeg");
+ }
+
+ updateJob(jobId, {
+ phase: "complete",
+ progress: 100,
+ message: "Processing complete",
+ });
+ await sendWebhook(getJob(jobId)!);
+
+ await inputTempFile.cleanup();
+ await outputTempFile.cleanup();
+
+ setTimeout(() => deleteJob(jobId), 5 * 60 * 1000);
+ } catch (err) {
+ console.error(`[video/process] Error processing job ${jobId}:`, err);
+
+ const updatedJob = updateJob(jobId, {
+ phase: "error",
+ error: err instanceof Error ? err.message : String(err),
+ message: "Processing failed",
+ });
+
+ if (updatedJob) {
+ await sendWebhook(updatedJob);
+ }
+
+ const currentJob = getJob(jobId);
+ if (currentJob) {
+ await currentJob.inputTempFile?.cleanup();
+ await currentJob.outputTempFile?.cleanup();
+ }
+ } finally {
+ decrementActiveVideoProcesses();
+ }
+}
+
+video.get("/process/:jobId/status", async (c) => {
+ const jobId = c.req.param("jobId");
+ const job = getJob(jobId);
+
+ if (!job) {
+ return c.json(
+ {
+ error: "Job not found",
+ code: "NOT_FOUND",
+ },
+ 404,
+ );
+ }
+
+ const accept = c.req.header("Accept");
+
+ if (accept?.includes("text/event-stream")) {
+ const stream = new ReadableStream({
+ start(controller) {
+ const encoder = new TextEncoder();
+
+ const sendUpdate = () => {
+ const currentJob = getJob(jobId);
+ if (!currentJob) {
+ controller.enqueue(
+ encoder.encode(
+ `data: ${JSON.stringify({ error: "Job not found" })}\n\n`,
+ ),
+ );
+ controller.close();
+ return false;
+ }
+
+ const progress = getJobProgress(currentJob);
+ controller.enqueue(
+ encoder.encode(`data: ${JSON.stringify(progress)}\n\n`),
+ );
+
+ if (
+ currentJob.phase === "complete" ||
+ currentJob.phase === "error" ||
+ currentJob.phase === "cancelled"
+ ) {
+ controller.close();
+ return false;
+ }
+
+ return true;
+ };
+
+ sendUpdate();
+
+ const interval = setInterval(() => {
+ if (!sendUpdate()) {
+ clearInterval(interval);
+ }
+ }, 1000);
+
+ c.req.raw.signal.addEventListener("abort", () => {
+ clearInterval(interval);
+ controller.close();
+ });
+ },
+ });
+
+ return new Response(stream, {
+ headers: {
+ "Content-Type": "text/event-stream",
+ "Cache-Control": "no-cache",
+ Connection: "keep-alive",
+ },
+ });
+ }
+
+ return c.json(getJobProgress(job));
+});
+
+video.post("/process/:jobId/cancel", async (c) => {
+ const jobId = c.req.param("jobId");
+ const job = getJob(jobId);
+
+ if (!job) {
+ return c.json(
+ {
+ error: "Job not found",
+ code: "NOT_FOUND",
+ },
+ 404,
+ );
+ }
+
+ if (
+ job.phase === "complete" ||
+ job.phase === "error" ||
+ job.phase === "cancelled"
+ ) {
+ return c.json(
+ {
+ error: "Job already finished",
+ code: "INVALID_STATE",
+ currentPhase: job.phase,
+ },
+ 400,
+ );
+ }
+
+ job.abortController?.abort();
+
+ updateJob(jobId, {
+ phase: "cancelled",
+ message: "Processing cancelled by user",
+ });
+
+ await sendWebhook(getJob(jobId)!);
+
+ return c.json({
+ success: true,
+ message: "Job cancelled",
+ });
+});
+
+video.post("/cleanup", async (c) => {
+ const cleaned = await cleanupStaleTempFiles();
+ return c.json({
+ success: true,
+ cleanedFiles: cleaned,
+ });
+});
+
+export default video;