Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add Bun-based media server for audio extraction

Richie McIlroy84dfdf94f8dd
diff --git a/apps/media-server/Dockerfile b/apps/media-server/Dockerfile
new file mode 100644
index 000000000..a99ead35d
--- /dev/null
+++ b/apps/media-server/Dockerfile
@@ -0,0 +1,18 @@
+FROM oven/bun:1-alpine
+
+RUN apk add --no-cache ffmpeg
+
+WORKDIR /app
+
+COPY package.json ./
+RUN bun install --production
+
+COPY src ./src
+
+ENV PORT=3456
+EXPOSE 3456
+
+HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
+ CMD wget -qO- http://localhost:${PORT}/health || exit 1
+
+CMD ["bun", "run", "src/index.ts"]
diff --git a/apps/media-server/package.json b/apps/media-server/package.json
new file mode 100644
index 000000000..d55c70a81
--- /dev/null
+++ b/apps/media-server/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "@cap/media-server",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev:local": "bun --watch src/index.ts",
+ "start": "bun src/index.ts",
+ "build": "echo 'No build step needed for Bun'",
+ "test": "bun test",
+ "test:watch": "bun test --watch"
+ },
+ "dependencies": {
+ "hono": "^4.7.1",
+ "zod": "^3.24.2"
+ },
+ "devDependencies": {
+ "@types/bun": "latest"
+ }
+}
diff --git a/apps/media-server/railway.toml b/apps/media-server/railway.toml
new file mode 100644
index 000000000..4e9975f81
--- /dev/null
+++ b/apps/media-server/railway.toml
@@ -0,0 +1,8 @@
+[build]
+dockerfilePath = "Dockerfile"
+
+[deploy]
+healthcheckPath = "/health"
+healthcheckTimeout = 10
+restartPolicyType = "ON_FAILURE"
+restartPolicyMaxRetries = 3
diff --git a/apps/media-server/src/__tests__/index.test.ts b/apps/media-server/src/__tests__/index.test.ts
new file mode 100644
index 000000000..c87f4fc38
--- /dev/null
+++ b/apps/media-server/src/__tests__/index.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, test } from "bun:test";
+import app from "../app";
+
+describe("GET /", () => {
+ test("returns server metadata and endpoints", async () => {
+ const response = await app.fetch(new Request("http://localhost/"));
+
+ expect(response.status).toBe(200);
+ const data = await response.json();
+ expect(data).toEqual({
+ name: "@cap/media-server",
+ version: "1.0.0",
+ endpoints: ["/health", "/audio/check", "/audio/extract"],
+ });
+ });
+});
+
+describe("unknown routes", () => {
+ test("returns 404 for unknown GET routes", async () => {
+ const response = await app.fetch(
+ new Request("http://localhost/unknown-route"),
+ );
+
+ expect(response.status).toBe(404);
+ });
+});
diff --git a/apps/media-server/src/__tests__/routes/audio.test.ts b/apps/media-server/src/__tests__/routes/audio.test.ts
new file mode 100644
index 000000000..9a212dd2c
--- /dev/null
+++ b/apps/media-server/src/__tests__/routes/audio.test.ts
@@ -0,0 +1,186 @@
+import { beforeEach, describe, expect, mock, test } from "bun:test";
+import app from "../../app";
+import * as ffmpeg from "../../lib/ffmpeg";
+
+describe("POST /audio/check", () => {
+ beforeEach(() => {
+ mock.restore();
+ });
+
+ test("returns 400 for missing videoUrl", async () => {
+ const response = await app.fetch(
+ new Request("http://localhost/audio/check", {
+ 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/audio/check", {
+ 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 hasAudio true when video has audio track", async () => {
+ mock.module("../../lib/ffmpeg", () => ({
+ checkHasAudioTrack: async () => true,
+ extractAudio: ffmpeg.extractAudio,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/audio/check", {
+ 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).toEqual({ hasAudio: true });
+ });
+
+ test("returns hasAudio false when video has no audio track", async () => {
+ mock.module("../../lib/ffmpeg", () => ({
+ checkHasAudioTrack: async () => false,
+ extractAudio: ffmpeg.extractAudio,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/audio/check", {
+ 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).toEqual({ hasAudio: false });
+ });
+});
+
+describe("POST /audio/extract", () => {
+ beforeEach(() => {
+ mock.restore();
+ });
+
+ test("returns 400 for missing videoUrl", async () => {
+ const response = await app.fetch(
+ new Request("http://localhost/audio/extract", {
+ 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/audio/extract", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl: "invalid-url" }),
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ const data = await response.json();
+ expect(data.code).toBe("INVALID_REQUEST");
+ });
+
+ test("returns 422 when video has no audio track", async () => {
+ mock.module("../../lib/ffmpeg", () => ({
+ checkHasAudioTrack: async () => false,
+ extractAudio: ffmpeg.extractAudio,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/audio/extract", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),
+ }),
+ );
+
+ expect(response.status).toBe(422);
+ const data = await response.json();
+ expect(data.code).toBe("NO_AUDIO_TRACK");
+ });
+
+ test("returns audio data when extraction succeeds", async () => {
+ const mockAudioData = new Uint8Array([0x00, 0x00, 0x00, 0x1c, 0x66, 0x74]);
+
+ mock.module("../../lib/ffmpeg", () => ({
+ checkHasAudioTrack: async () => true,
+ extractAudio: async () => mockAudioData,
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/audio/extract", {
+ 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("audio/mp4");
+ expect(response.headers.get("Content-Length")).toBe(
+ mockAudioData.length.toString(),
+ );
+
+ const buffer = await response.arrayBuffer();
+ expect(new Uint8Array(buffer)).toEqual(mockAudioData);
+ });
+
+ test("returns 500 when ffmpeg extraction fails", async () => {
+ mock.module("../../lib/ffmpeg", () => ({
+ checkHasAudioTrack: async () => true,
+ extractAudio: async () => {
+ throw new Error("FFmpeg failed");
+ },
+ }));
+
+ const { default: appWithMock } = await import("../../app");
+
+ const response = await appWithMock.fetch(
+ new Request("http://localhost/audio/extract", {
+ 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("FFMPEG_ERROR");
+ expect(data.details).toContain("FFmpeg failed");
+ });
+});
diff --git a/apps/media-server/src/__tests__/routes/health.test.ts b/apps/media-server/src/__tests__/routes/health.test.ts
new file mode 100644
index 000000000..e82a35156
--- /dev/null
+++ b/apps/media-server/src/__tests__/routes/health.test.ts
@@ -0,0 +1,12 @@
+import { describe, expect, test } from "bun:test";
+import app from "../../app";
+
+describe("GET /health", () => {
+ test("returns status ok", async () => {
+ const response = await app.fetch(new Request("http://localhost/health"));
+
+ expect(response.status).toBe(200);
+ const data = await response.json();
+ expect(data).toEqual({ status: "ok" });
+ });
+});
diff --git a/apps/media-server/src/app.ts b/apps/media-server/src/app.ts
new file mode 100644
index 000000000..7b97a4f55
--- /dev/null
+++ b/apps/media-server/src/app.ts
@@ -0,0 +1,21 @@
+import { Hono } from "hono";
+import { logger } from "hono/logger";
+import audio from "./routes/audio";
+import health from "./routes/health";
+
+const app = new Hono();
+
+app.use("*", logger());
+
+app.route("/health", health);
+app.route("/audio", audio);
+
+app.get("/", (c) => {
+ return c.json({
+ name: "@cap/media-server",
+ version: "1.0.0",
+ endpoints: ["/health", "/audio/check", "/audio/extract"],
+ });
+});
+
+export default app;
diff --git a/apps/media-server/src/index.ts b/apps/media-server/src/index.ts
new file mode 100644
index 000000000..3d3b4db2d
--- /dev/null
+++ b/apps/media-server/src/index.ts
@@ -0,0 +1,19 @@
+import app from "./app";
+
+const port = Number(process.env.PORT) || 3456;
+
+console.log(`[media-server] Starting on port ${port}`);
+
+const shutdown = () => {
+ console.log("[media-server] Shutting down...");
+ process.exit(0);
+};
+
+process.on("SIGINT", shutdown);
+process.on("SIGTERM", shutdown);
+process.on("SIGHUP", shutdown);
+
+export default {
+ port,
+ fetch: app.fetch,
+};
diff --git a/apps/media-server/src/lib/ffmpeg.ts b/apps/media-server/src/lib/ffmpeg.ts
new file mode 100644
index 000000000..ac612851a
--- /dev/null
+++ b/apps/media-server/src/lib/ffmpeg.ts
@@ -0,0 +1,116 @@
+import { spawn } from "bun";
+
+export interface AudioExtractionOptions {
+ format?: "m4a";
+ codec?: "aac";
+ bitrate?: string;
+}
+
+const DEFAULT_OPTIONS: Required<AudioExtractionOptions> = {
+ format: "m4a",
+ codec: "aac",
+ bitrate: "128k",
+};
+
+export async function checkHasAudioTrack(videoUrl: string): Promise<boolean> {
+ const proc = spawn({
+ cmd: ["ffmpeg", "-i", videoUrl, "-hide_banner"],
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+
+ const stderrText = await new Response(proc.stderr).text();
+ await proc.exited;
+
+ const hasAudio = /Stream #\d+:\d+.*Audio:/.test(stderrText);
+ console.log(`[ffmpeg] Video has audio track: ${hasAudio}`);
+ return hasAudio;
+}
+
+export async function extractAudio(
+ videoUrl: string,
+ options: AudioExtractionOptions = {},
+): Promise<Uint8Array> {
+ const opts = { ...DEFAULT_OPTIONS, ...options };
+
+ const ffmpegArgs = [
+ "ffmpeg",
+ "-i",
+ videoUrl,
+ "-vn",
+ "-acodec",
+ opts.codec,
+ "-b:a",
+ opts.bitrate,
+ "-f",
+ "ipod",
+ "-movflags",
+ "+frag_keyframe+empty_moov",
+ "-pipe:1",
+ ];
+
+ console.log(`[ffmpeg] Starting audio extraction: ${ffmpegArgs.join(" ")}`);
+
+ const proc = spawn({
+ cmd: ffmpegArgs,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+
+ const [stdout, stderrText, exitCode] = await Promise.all([
+ new Response(proc.stdout).arrayBuffer(),
+ new Response(proc.stderr).text(),
+ proc.exited,
+ ]);
+
+ if (exitCode !== 0) {
+ console.error(`[ffmpeg] Audio extraction failed:\n${stderrText}`);
+ throw new Error(`FFmpeg exited with code ${exitCode}`);
+ }
+
+ console.log(
+ `[ffmpeg] Audio extraction complete, size: ${stdout.byteLength} bytes`,
+ );
+ return new Uint8Array(stdout);
+}
+
+export async function extractAudioStream(
+ videoUrl: string,
+ options: AudioExtractionOptions = {},
+): Promise<ReadableStream<Uint8Array>> {
+ const opts = { ...DEFAULT_OPTIONS, ...options };
+
+ const ffmpegArgs = [
+ "ffmpeg",
+ "-i",
+ videoUrl,
+ "-vn",
+ "-acodec",
+ opts.codec,
+ "-b:a",
+ opts.bitrate,
+ "-f",
+ "ipod",
+ "-movflags",
+ "+frag_keyframe+empty_moov",
+ "-pipe:1",
+ ];
+
+ console.log(
+ `[ffmpeg] Starting audio extraction (stream): ${ffmpegArgs.join(" ")}`,
+ );
+
+ const proc = spawn({
+ cmd: ffmpegArgs,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+
+ proc.exited.then((code) => {
+ if (code !== 0) {
+ console.error(`[ffmpeg] Stream extraction failed with code ${code}`);
+ }
+ });
+
+ return proc.stdout as ReadableStream<Uint8Array>;
+}
diff --git a/apps/media-server/src/routes/audio.ts b/apps/media-server/src/routes/audio.ts
new file mode 100644
index 000000000..b8ef1ffd1
--- /dev/null
+++ b/apps/media-server/src/routes/audio.ts
@@ -0,0 +1,87 @@
+import { Hono } from "hono";
+import { z } from "zod";
+import { checkHasAudioTrack, extractAudio } from "../lib/ffmpeg";
+
+const audio = new Hono();
+
+const videoUrlSchema = z.object({
+ videoUrl: z.string().url(),
+});
+
+audio.post("/check", async (c) => {
+ const body = await c.req.json();
+ const result = videoUrlSchema.safeParse(body);
+
+ if (!result.success) {
+ return c.json(
+ {
+ error: "Invalid request",
+ code: "INVALID_REQUEST",
+ details: result.error.message,
+ },
+ 400,
+ );
+ }
+
+ try {
+ const hasAudio = await checkHasAudioTrack(result.data.videoUrl);
+ return c.json({ hasAudio });
+ } catch (err) {
+ console.error("[audio/check] Error:", err);
+ return c.json(
+ {
+ error: "Failed to check audio track",
+ code: "FFMPEG_ERROR",
+ details: err instanceof Error ? err.message : String(err),
+ },
+ 500,
+ );
+ }
+});
+
+audio.post("/extract", async (c) => {
+ const body = await c.req.json();
+ const result = videoUrlSchema.safeParse(body);
+
+ if (!result.success) {
+ return c.json(
+ {
+ error: "Invalid request",
+ code: "INVALID_REQUEST",
+ details: result.error.message,
+ },
+ 400,
+ );
+ }
+
+ try {
+ const hasAudio = await checkHasAudioTrack(result.data.videoUrl);
+ if (!hasAudio) {
+ return c.json(
+ { error: "Video has no audio track", code: "NO_AUDIO_TRACK" },
+ 422,
+ );
+ }
+
+ const audioData = await extractAudio(result.data.videoUrl);
+
+ return new Response(Buffer.from(audioData), {
+ headers: {
+ "Content-Type": "audio/mp4",
+ "Content-Length": audioData.length.toString(),
+ },
+ });
+ } catch (err) {
+ console.error("[audio/extract] Error:", err);
+ return c.json(
+ {
+ error: "Failed to extract audio",
+ code: "FFMPEG_ERROR",
+ details: err instanceof Error ? err.message : String(err),
+ },
+ 500,
+ );
+ }
+});
+
+export default audio;
diff --git a/apps/media-server/src/routes/health.ts b/apps/media-server/src/routes/health.ts
new file mode 100644
index 000000000..1fbd83e89
--- /dev/null
+++ b/apps/media-server/src/routes/health.ts
@@ -0,0 +1,9 @@
+import { Hono } from "hono";
+
+const health = new Hono();
+
+health.get("/", (c) => {
+ return c.json({ status: "ok" });
+});
+
+export default health;
diff --git a/apps/media-server/tsconfig.json b/apps/media-server/tsconfig.json
new file mode 100644
index 000000000..66ec091b3
--- /dev/null
+++ b/apps/media-server/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "skipLibCheck": true,
+ "noEmit": true,
+ "esModuleInterop": true,
+ "allowSyntheticDefaultImports": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "types": ["bun-types"]
+ },
+ "include": ["src/**/*.ts"]
+}
diff --git a/apps/web/__tests__/unit/media-client.test.ts b/apps/web/__tests__/unit/media-client.test.ts
new file mode 100644
index 000000000..a459fd3bd
--- /dev/null
+++ b/apps/web/__tests__/unit/media-client.test.ts
@@ -0,0 +1,189 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ checkHasAudioTrackViaMediaServer,
+ extractAudioViaMediaServer,
+ isMediaServerConfigured,
+} from "@/lib/media-client";
+
+vi.mock("@cap/env", () => ({
+ serverEnv: vi.fn(),
+}));
+
+const mockFetch = vi.fn();
+global.fetch = mockFetch;
+
+describe("media-client", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe("isMediaServerConfigured", () => {
+ it("returns true when MEDIA_SERVER_URL is set", async () => {
+ const { serverEnv } = await import("@cap/env");
+ vi.mocked(serverEnv).mockReturnValue({
+ MEDIA_SERVER_URL: "http://localhost:3456",
+ } as ReturnType<typeof serverEnv>);
+
+ expect(isMediaServerConfigured()).toBe(true);
+ });
+
+ it("returns false when MEDIA_SERVER_URL is not set", async () => {
+ const { serverEnv } = await import("@cap/env");
+ vi.mocked(serverEnv).mockReturnValue({
+ MEDIA_SERVER_URL: undefined,
+ } as unknown as ReturnType<typeof serverEnv>);
+
+ expect(isMediaServerConfigured()).toBe(false);
+ });
+
+ it("returns false when MEDIA_SERVER_URL is empty string", async () => {
+ const { serverEnv } = await import("@cap/env");
+ vi.mocked(serverEnv).mockReturnValue({
+ MEDIA_SERVER_URL: "",
+ } as unknown as ReturnType<typeof serverEnv>);
+
+ expect(isMediaServerConfigured()).toBe(false);
+ });
+ });
+
+ describe("checkHasAudioTrackViaMediaServer", () => {
+ beforeEach(async () => {
+ const { serverEnv } = await import("@cap/env");
+ vi.mocked(serverEnv).mockReturnValue({
+ MEDIA_SERVER_URL: "http://localhost:3456",
+ } as ReturnType<typeof serverEnv>);
+ });
+
+ it("throws error when MEDIA_SERVER_URL is not configured", async () => {
+ const { serverEnv } = await import("@cap/env");
+ vi.mocked(serverEnv).mockReturnValue({
+ MEDIA_SERVER_URL: undefined,
+ } as unknown as ReturnType<typeof serverEnv>);
+
+ await expect(
+ checkHasAudioTrackViaMediaServer("https://example.com/video.mp4"),
+ ).rejects.toThrow("MEDIA_SERVER_URL is not configured");
+ });
+
+ it("returns true when video has audio track", async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ hasAudio: true }),
+ });
+
+ const result = await checkHasAudioTrackViaMediaServer(
+ "https://example.com/video.mp4",
+ );
+
+ expect(result).toBe(true);
+ expect(mockFetch).toHaveBeenCalledWith(
+ "http://localhost:3456/audio/check",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),
+ },
+ );
+ });
+
+ it("returns false when video has no audio track", async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ hasAudio: false }),
+ });
+
+ const result = await checkHasAudioTrackViaMediaServer(
+ "https://example.com/video.mp4",
+ );
+
+ expect(result).toBe(false);
+ });
+
+ it("throws error when media server returns error", async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: false,
+ json: async () => ({
+ error: "FFMPEG_ERROR",
+ code: "FFMPEG_ERROR",
+ details: "FFmpeg process failed",
+ }),
+ });
+
+ await expect(
+ checkHasAudioTrackViaMediaServer("https://example.com/video.mp4"),
+ ).rejects.toThrow("FFMPEG_ERROR");
+ });
+ });
+
+ describe("extractAudioViaMediaServer", () => {
+ beforeEach(async () => {
+ const { serverEnv } = await import("@cap/env");
+ vi.mocked(serverEnv).mockReturnValue({
+ MEDIA_SERVER_URL: "http://localhost:3456",
+ } as ReturnType<typeof serverEnv>);
+ });
+
+ it("throws error when MEDIA_SERVER_URL is not configured", async () => {
+ const { serverEnv } = await import("@cap/env");
+ vi.mocked(serverEnv).mockReturnValue({
+ MEDIA_SERVER_URL: undefined,
+ } as unknown as ReturnType<typeof serverEnv>);
+
+ await expect(
+ extractAudioViaMediaServer("https://example.com/video.mp4"),
+ ).rejects.toThrow("MEDIA_SERVER_URL is not configured");
+ });
+
+ it("returns audio buffer when extraction succeeds", async () => {
+ const mockAudioData = new Uint8Array([0x00, 0x00, 0x00, 0x1c, 0x66]);
+ mockFetch.mockResolvedValueOnce({
+ ok: true,
+ arrayBuffer: async () => mockAudioData.buffer,
+ });
+
+ const result = await extractAudioViaMediaServer(
+ "https://example.com/video.mp4",
+ );
+
+ expect(result).toBeInstanceOf(Buffer);
+ expect(result.length).toBe(mockAudioData.length);
+ expect(mockFetch).toHaveBeenCalledWith(
+ "http://localhost:3456/audio/extract",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),
+ },
+ );
+ });
+
+ it("throws NO_AUDIO_TRACK error when video has no audio", async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: false,
+ json: async () => ({
+ error: "Video has no audio track",
+ code: "NO_AUDIO_TRACK",
+ }),
+ });
+
+ await expect(
+ extractAudioViaMediaServer("https://example.com/video.mp4"),
+ ).rejects.toThrow("NO_AUDIO_TRACK");
+ });
+
+ it("throws error when extraction fails", async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: false,
+ json: async () => ({
+ error: "Failed to extract audio",
+ code: "FFMPEG_ERROR",
+ details: "FFmpeg process exited with code 1",
+ }),
+ });
+
+ await expect(
+ extractAudioViaMediaServer("https://example.com/video.mp4"),
+ ).rejects.toThrow("Failed to extract audio");
+ });
+ });
+});
diff --git a/apps/web/lib/media-client.ts b/apps/web/lib/media-client.ts
new file mode 100644
index 000000000..a036c2cc8
--- /dev/null
+++ b/apps/web/lib/media-client.ts
@@ -0,0 +1,63 @@
+import { serverEnv } from "@cap/env";
+
+interface MediaServerError {
+ error: string;
+ code: string;
+ details?: string;
+}
+
+export function isMediaServerConfigured(): boolean {
+ return !!serverEnv().MEDIA_SERVER_URL;
+}
+
+export async function checkHasAudioTrackViaMediaServer(
+ videoUrl: string,
+): Promise<boolean> {
+ const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;
+ if (!mediaServerUrl) {
+ throw new Error("MEDIA_SERVER_URL is not configured");
+ }
+
+ const response = await fetch(`${mediaServerUrl}/audio/check`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl }),
+ });
+
+ if (!response.ok) {
+ const errorData = (await response.json()) as MediaServerError;
+ console.error("[media-client] Audio check failed:", errorData);
+ throw new Error(errorData.error || "Audio check failed");
+ }
+
+ const data = (await response.json()) as { hasAudio: boolean };
+ return data.hasAudio;
+}
+
+export async function extractAudioViaMediaServer(
+ videoUrl: string,
+): Promise<Buffer> {
+ const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;
+ if (!mediaServerUrl) {
+ throw new Error("MEDIA_SERVER_URL is not configured");
+ }
+
+ const response = await fetch(`${mediaServerUrl}/audio/extract`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl }),
+ });
+
+ if (!response.ok) {
+ const errorData = (await response.json()) as MediaServerError;
+ console.error("[media-client] Audio extraction failed:", errorData);
+
+ if (errorData.code === "NO_AUDIO_TRACK") {
+ throw new Error("NO_AUDIO_TRACK");
+ }
+ throw new Error(errorData.error || "Audio extraction failed");
+ }
+
+ const arrayBuffer = await response.arrayBuffer();
+ return Buffer.from(arrayBuffer);
+}
diff --git a/apps/web/workflows/transcribe.ts b/apps/web/workflows/transcribe.ts
index 72d120578..c8f781f0a 100644
--- a/apps/web/workflows/transcribe.ts
+++ b/apps/web/workflows/transcribe.ts
@@ -10,6 +10,11 @@ import { Option } from "effect";
import { FatalError } from "workflow";
import { generateAiMetadata } from "@/actions/videos/generate-ai-metadata";
import { checkHasAudioTrack, extractAudioFromUrl } from "@/lib/audio-extract";
+import {
+ checkHasAudioTrackViaMediaServer,
+ extractAudioViaMediaServer,
+ isMediaServerConfigured,
+} from "@/lib/media-client";
import { runPromise } from "@/lib/server";
import { type DeepgramResult, formatToWebVTT } from "@/lib/transcribe-utils";
@@ -151,34 +156,54 @@ async function extractAudio(
throw new Error("Video file not accessible");
}
- const hasAudio = await checkHasAudioTrack(videoUrl);
- if (!hasAudio) {
- console.log("[transcribe-workflow] Video has no audio track");
- return null;
- }
+ const useMediaServer = isMediaServerConfigured();
+ console.log(
+ `[transcribe-workflow] Using ${useMediaServer ? "media server" : "local FFmpeg"} for audio extraction`,
+ );
- console.log("[transcribe-workflow] Extracting audio from video");
- const result = await extractAudioFromUrl(videoUrl);
+ let hasAudio: boolean;
+ let audioBuffer: Buffer;
+
+ if (useMediaServer) {
+ hasAudio = await checkHasAudioTrackViaMediaServer(videoUrl);
+ if (!hasAudio) {
+ console.log("[transcribe-workflow] Video has no audio track");
+ return null;
+ }
+
+ console.log("[transcribe-workflow] Extracting audio via media server");
+ audioBuffer = await extractAudioViaMediaServer(videoUrl);
+ } else {
+ hasAudio = await checkHasAudioTrack(videoUrl);
+ if (!hasAudio) {
+ console.log("[transcribe-workflow] Video has no audio track");
+ return null;
+ }
+
+ console.log("[transcribe-workflow] Extracting audio from video");
+ const result = await extractAudioFromUrl(videoUrl);
+
+ try {
+ audioBuffer = await fs.readFile(result.filePath);
+ } finally {
+ await result.cleanup();
+ }
+ }
- try {
- const audioBuffer = await fs.readFile(result.filePath);
- const audioKey = `${userId}/${videoId}/audio-temp.m4a`;
+ const audioKey = `${userId}/${videoId}/audio-temp.m4a`;
- await bucket
- .putObject(audioKey, audioBuffer, {
- contentType: result.mimeType,
- })
- .pipe(runPromise);
+ await bucket
+ .putObject(audioKey, audioBuffer, {
+ contentType: "audio/mp4",
+ })
+ .pipe(runPromise);
- const audioSignedUrl = await bucket
- .getSignedObjectUrl(audioKey)
- .pipe(runPromise);
+ const audioSignedUrl = await bucket
+ .getSignedObjectUrl(audioKey)
+ .pipe(runPromise);
- console.log("[transcribe-workflow] Audio uploaded to S3");
- return audioSignedUrl;
- } finally {
- await result.cleanup();
- }
+ console.log("[transcribe-workflow] Audio uploaded to S3");
+ return audioSignedUrl;
}
async function transcribeWithDeepgram(audioUrl: string): Promise<string> {
diff --git a/docker-compose.template.yml b/docker-compose.template.yml
index 95b5cfef5..437a3b1d0 100644
--- a/docker-compose.template.yml
+++ b/docker-compose.template.yml
@@ -23,6 +23,7 @@ services:
CAP_AWS_REGION: us-east-1
S3_PUBLIC_ENDPOINT: http://localhost:3902
S3_INTERNAL_ENDPOINT: http://minio:3902
+ MEDIA_SERVER_URL: http://cap-media-server:3456
ports:
- 3000:3000
@@ -45,6 +46,15 @@ services:
volumes:
- ps-mysql:/var/lib/mysql
+ cap-media-server:
+ container_name: cap-media-server
+ image: ghcr.io/capsoftware/cap-media-server:latest
+ restart: unless-stopped
+ environment:
+ PORT: 3456
+ ports:
+ - "3456:3456"
+
# Local S3 Strorage
minio:
container_name: cap-minio-storage
diff --git a/packages/env/server.ts b/packages/env/server.ts
index f32a6f09e..353ea9c97 100644
--- a/packages/env/server.ts
+++ b/packages/env/server.ts
@@ -114,6 +114,12 @@ function createServerEnv() {
DUB_API_KEY: z.string().optional(),
INTERCOM_SECRET: z.string().optional(),
+ /// Media Server
+ MEDIA_SERVER_URL: z
+ .string()
+ .optional()
+ .describe("URL of the media server for FFmpeg processing"),
+
/// Ignore
NODE_ENV: z.string(),
WORKFLOWS_RPC_URL: z.string().optional(),
diff --git a/packages/local-docker/docker-compose.yml b/packages/local-docker/docker-compose.yml
index fe095e118..eab47d09a 100644
--- a/packages/local-docker/docker-compose.yml
+++ b/packages/local-docker/docker-compose.yml
@@ -20,6 +20,17 @@ services:
volumes:
- ps-mysql:/var/lib/mysql
+ cap-media-server:
+ container_name: cap-media-server-dev
+ build:
+ context: ../../apps/media-server
+ dockerfile: Dockerfile
+ restart: unless-stopped
+ environment:
+ PORT: 3456
+ ports:
+ - "3456:3456"
+
# Local S3 Strorage
minio:
container_name: minio-storage
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 488f75a6f..55731b0b5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -118,7 +118,7 @@ importers:
version: 0.14.10([email protected])
'@solidjs/start':
specifier: ^1.1.3
'@tanstack/solid-query':
specifier: ^5.51.21
version: 5.75.4([email protected])
@@ -208,7 +208,7 @@ importers:
version: 9.0.1
vinxi:
specifier: ^0.5.6
webcodecs:
specifier: ^0.1.0
version: 0.1.0
@@ -302,6 +302,19 @@ importers:
specifier: ^3.109.1
version: 3.114.8(@cloudflare/[email protected])
+ apps/media-server:
+ dependencies:
+ hono:
+ specifier: ^4.7.1
+ version: 4.7.8
+ zod:
+ specifier: ^3.24.2
+ version: 3.25.76
+ devDependencies:
+ '@types/bun':
+ specifier: latest
+ version: 1.3.5
+
apps/storybook:
dependencies:
'@cap/ui-solid':
@@ -457,7 +470,7 @@ importers:
version: 0.0.14
'@kubiks/otel-drizzle':
specifier: ^2.1.0
- version: 2.1.0(@opentelemetry/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected]))
+ version: 2.1.0(@opentelemetry/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])([email protected]))
'@mux/mux-node':
specifier: ^8.5.1
version: 8.8.0([email protected])
@@ -592,7 +605,7 @@ importers:
version: 16.5.0
drizzle-orm:
specifier: 0.44.6
- version: 0.44.6(@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])
+ version: 0.44.6(@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])([email protected])
dub:
specifier: ^0.64.0
version: 0.64.0(@modelcontextprotocol/[email protected])([email protected])
@@ -950,7 +963,7 @@ importers:
'@kubiks/otel-drizzle':
specifier: ^2.1.0
- version: 2.1.0(@opentelemetry/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected]))
+ version: 2.1.0(@opentelemetry/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])([email protected]))
'@mattrax/mysql-planetscale':
specifier: ^0.0.3
version: 0.0.3
@@ -971,7 +984,7 @@ importers:
version: 1.0.5([email protected])
drizzle-orm:
specifier: 0.44.6
- version: 0.44.6(@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])
+ version: 0.44.6(@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])([email protected])
dub:
specifier: ^0.64.0
version: 0.64.0(@modelcontextprotocol/[email protected])([email protected])
@@ -1337,7 +1350,7 @@ importers:
version: 3.1.0(@aws-sdk/[email protected])
drizzle-orm:
specifier: 0.44.6
- version: 0.44.6(@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])
+ version: 0.44.6(@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])([email protected])
effect:
specifier: ^3.18.4
version: 3.18.4
@@ -7459,6 +7472,9 @@ packages:
resolution: {integrity: sha512-SQFof9H+LXeWNz8wDe7oN5zu7ket0qwMu5vZubW4GCJ8Kkeh6nBWUz87+KTz/G3Kqsrp0j/W253XJb3KMEeg3w==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-RnygCqNrd3srIPEWBd5LFeUYG7plCoH2Yw9WaZGyNmdTEei+gWaHqydbaIRkIkcbXwhBT94q78QljxN0Sk838w==}
+
resolution: {integrity: sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==}
@@ -8699,6 +8715,9 @@ packages:
resolution: {integrity: sha512-bkXY9WsVpY7CvMhKSR6pZilZu9Ln5WDrKVBUXf2S443etkmEO4V58heTecXcUIsNsi4Rx8JUO4NfX1IcQl4deg==}
engines: {node: '>=18.20'}
+ resolution: {integrity: sha512-inmAYe2PFLs0SUbFOWSVD24sg1jFlMPxOjOSSCYqUgn4Hsc3rDc7dFvfVYjFPNHtov6kgUeulV4SxbuIV/stPw==}
+
resolution: {integrity: sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==}
engines: {node: '>=18'}
@@ -18532,7 +18551,7 @@ snapshots:
dependencies:
- '@emnapi/runtime': 1.5.0
+ '@emnapi/runtime': 1.7.1
optional: true
@@ -18690,10 +18709,10 @@ snapshots:
'@solid-primitives/utils': 6.3.1([email protected])
solid-js: 1.9.6
dependencies:
'@opentelemetry/api': 1.9.0
- drizzle-orm: 0.44.6(@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])
+ drizzle-orm: 0.44.6(@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])([email protected])
'@logdna/[email protected]': {}
@@ -21956,11 +21975,11 @@ snapshots:
dependencies:
solid-js: 1.9.6
dependencies:
'@tanstack/server-functions-plugin': 1.119.2(@types/[email protected])([email protected])([email protected])([email protected])
defu: 6.1.4
error-stack-parser: 2.1.4
html-to-image: 1.11.13
@@ -21971,7 +21990,7 @@ snapshots:
source-map-js: 1.2.1
terracotta: 1.0.6([email protected])
tinyglobby: 0.2.13
transitivePeerDependencies:
- '@testing-library/jest-dom'
@@ -22767,6 +22786,10 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ bun-types: 1.3.5
+
dependencies:
'@types/http-cache-semantics': 4.0.4
@@ -23357,7 +23380,7 @@ snapshots:
untun: 0.1.3
uqr: 0.1.2
dependencies:
'@babel/parser': 7.27.2
acorn: 8.14.1
@@ -23368,18 +23391,18 @@ snapshots:
magicast: 0.2.11
recast: 0.23.11
tslib: 2.8.1
dependencies:
acorn: 8.14.1
acorn-loose: 8.5.0
acorn-typescript: 1.4.13([email protected])
astring: 1.9.0
magicast: 0.2.11
recast: 0.23.11
'@virtual-grid/[email protected]': {}
@@ -24490,6 +24513,10 @@ snapshots:
+ dependencies:
+ '@types/node': 20.19.21
+
dependencies:
run-applescript: 7.1.0
@@ -25081,9 +25108,9 @@ snapshots:
optionalDependencies:
- drizzle-orm: 0.44.6(@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])
+ drizzle-orm: 0.44.6(@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])([email protected])
mysql2: 3.15.2
@@ -25361,11 +25388,12 @@ snapshots:
transitivePeerDependencies:
- supports-color
optionalDependencies:
'@cloudflare/workers-types': 4.20250507.0
'@opentelemetry/api': 1.9.0
'@planetscale/database': 1.19.0
+ bun-types: 1.3.5
mysql2: 3.15.2
@@ -28682,7 +28710,7 @@ snapshots:
cors: 2.8.5
dependencies:
'@cloudflare/kv-asset-handler': 0.4.0
'@netlify/functions': 3.1.5([email protected])([email protected])
@@ -28704,7 +28732,7 @@ snapshots:
cookie-es: 2.0.0
croner: 9.0.0
crossws: 0.3.5
defu: 6.1.4
destr: 2.0.5
dot-prop: 9.0.0
@@ -28750,7 +28778,7 @@ snapshots:
unenv: 2.0.0-rc.15
unimport: 5.0.1
unplugin-utils: 0.2.4
untyped: 2.0.0
unwasm: 0.3.9
youch: 4.1.0-beta.7
@@ -31837,7 +31865,7 @@ snapshots:
'@unrs/resolver-binding-win32-ia32-msvc': 1.7.2
'@unrs/resolver-binding-win32-x64-msvc': 1.7.2
dependencies:
anymatch: 3.1.3
chokidar: 4.0.3
@@ -31849,7 +31877,7 @@ snapshots:
ufo: 1.6.1
optionalDependencies:
'@planetscale/database': 1.19.0
ioredis: 5.6.1
@@ -32008,7 +32036,7 @@ snapshots:
d3-time: 3.1.0
d3-timer: 3.0.1
dependencies:
'@babel/core': 7.27.1
'@babel/plugin-syntax-jsx': 7.27.1(@babel/[email protected])
@@ -32030,7 +32058,7 @@ snapshots:
hookable: 5.5.3
http-proxy: 1.18.1
micromatch: 4.0.8
node-fetch-native: 1.6.6
path-to-regexp: 6.3.0
pathe: 1.1.2
@@ -32041,7 +32069,7 @@ snapshots:
ufo: 1.6.1
unctx: 2.4.1
unenv: 1.10.0
zod: 3.25.76
transitivePeerDependencies:
diff --git a/scripts/env-cli.js b/scripts/env-cli.js
index 49c6a7169..36ad0f4b8 100644
--- a/scripts/env-cli.js
+++ b/scripts/env-cli.js
@@ -59,6 +59,7 @@ async function main() {
envs.WEB_URL = "http://localhost:3000";
envs.NEXTAUTH_URL = envs.WEB_URL;
envs.WORKFLOWS_RPC_SECRET = crypto.randomBytes(32).toString("base64");
+ envs.MEDIA_SERVER_URL = "http://localhost:3456";
if (!allEnvs.NEXTAUTH_SECRET) {
allEnvs.NEXTAUTH_SECRET = crypto.randomBytes(32).toString("base64");