Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Improve ffmpeg process and memory management

Richie McIlroy1deb22d7320e
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index f8b7353b0..ae17000c2 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -2,6 +2,7 @@ import { Select as KSelect } from "@kobalte/core/select";
import { ToggleButton as KToggleButton } from "@kobalte/core/toggle-button";
import { createElementBounds } from "@solid-primitives/bounds";
import { debounce } from "@solid-primitives/scheduled";
+import { Menu } from "@tauri-apps/api/menu";
import { cx } from "cva";
import { createEffect, createSignal, onMount, Show } from "solid-js";
@@ -17,6 +18,7 @@ import {
} from "./context";
import { preloadCropVideoFull } from "./cropVideoPreloader";
import { MaskOverlay } from "./MaskOverlay";
+import { PerformanceOverlay } from "./PerformanceOverlay";
import { TextOverlay } from "./TextOverlay";
import {
EditorButton,
@@ -442,10 +444,25 @@ const gridStyle = {
};
function PreviewCanvas() {
- const { latestFrame, canvasControls } = useEditorContext();
+ const { latestFrame, canvasControls, performanceMode, setPerformanceMode } =
+ useEditorContext();
const hasRenderedFrame = () => canvasControls()?.hasRenderedFrame() ?? false;
+ const handleContextMenu = async (e: MouseEvent) => {
+ e.preventDefault();
+ const menu = await Menu.new({
+ items: [
+ {
+ id: "performance-mode",
+ text: performanceMode() ? "✓ Performance Mode" : "Performance Mode",
+ action: () => setPerformanceMode(!performanceMode()),
+ },
+ ],
+ });
+ menu.popup();
+ };
+
const canvasInitializedRef = { current: false };
const [canvasRef, setCanvasRef] = createSignal<HTMLCanvasElement | null>(
null,
@@ -538,6 +555,7 @@ function PreviewCanvas() {
ref={setCanvasContainerRef}
class="relative flex-1 justify-center items-center"
style={{ contain: "layout style" }}
+ onContextMenu={handleContextMenu}
>
<div
class="flex overflow-hidden absolute inset-0 justify-center items-center h-full"
@@ -565,6 +583,7 @@ function PreviewCanvas() {
<Show when={hasFrame()}>
<MaskOverlay size={size()} />
<TextOverlay size={size()} />
+ <PerformanceOverlay size={size()} />
</Show>
</div>
</div>
diff --git a/apps/media-server/src/__tests__/lib/memory-leak.test.ts b/apps/media-server/src/__tests__/lib/memory-leak.test.ts
new file mode 100644
index 000000000..a159e5b84
--- /dev/null
+++ b/apps/media-server/src/__tests__/lib/memory-leak.test.ts
@@ -0,0 +1,298 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { join } from "node:path";
+import { spawn } from "bun";
+import {
+ checkHasAudioTrack,
+ extractAudio,
+ extractAudioStream,
+ getActiveProcessCount,
+} from "../../lib/ffmpeg";
+
+const FIXTURES_DIR = join(import.meta.dir, "..", "fixtures");
+const TEST_VIDEO_WITH_AUDIO = `file://${join(FIXTURES_DIR, "test-with-audio.mp4")}`;
+
+async function countFFmpegProcesses(): Promise<number> {
+ const proc = spawn({
+ cmd: ["pgrep", "-f", "ffmpeg"],
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const output = await new Response(proc.stdout).text();
+ await proc.exited;
+ return output.trim().split("\n").filter(Boolean).length;
+}
+
+async function getProcessMemoryMB(): Promise<number> {
+ return process.memoryUsage().heapUsed / 1024 / 1024;
+}
+
+async function waitForProcessCleanup(
+ expectedCount: number,
+ timeoutMs = 5000,
+): Promise<void> {
+ const startTime = Date.now();
+ while (Date.now() - startTime < timeoutMs) {
+ if (getActiveProcessCount() === expectedCount) return;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ throw new Error(
+ `Timeout waiting for process count to reach ${expectedCount}, got ${getActiveProcessCount()}`,
+ );
+}
+
+describe("memory and resource leak tests", () => {
+ let initialFFmpegCount: number;
+
+ beforeAll(async () => {
+ initialFFmpegCount = await countFFmpegProcesses();
+ });
+
+ afterAll(async () => {
+ await new Promise((r) => setTimeout(r, 1000));
+ });
+
+ describe("process cleanup", () => {
+ test("checkHasAudioTrack cleans up process after completion", async () => {
+ const beforeCount = getActiveProcessCount();
+
+ await checkHasAudioTrack(TEST_VIDEO_WITH_AUDIO);
+
+ await waitForProcessCleanup(beforeCount);
+ expect(getActiveProcessCount()).toBe(beforeCount);
+ });
+
+ test("extractAudio cleans up process after completion", async () => {
+ const beforeCount = getActiveProcessCount();
+
+ await extractAudio(TEST_VIDEO_WITH_AUDIO);
+
+ await waitForProcessCleanup(beforeCount);
+ expect(getActiveProcessCount()).toBe(beforeCount);
+ });
+
+ test("extractAudioStream cleans up after stream is fully consumed", async () => {
+ const beforeCount = getActiveProcessCount();
+
+ const { stream } = extractAudioStream(TEST_VIDEO_WITH_AUDIO);
+
+ const reader = stream.getReader();
+ while (true) {
+ const { done } = await reader.read();
+ if (done) break;
+ }
+ reader.releaseLock();
+
+ await waitForProcessCleanup(beforeCount);
+ expect(getActiveProcessCount()).toBe(beforeCount);
+ });
+
+ test("extractAudioStream cleans up when stream is cancelled", async () => {
+ const beforeCount = getActiveProcessCount();
+
+ const { stream, cleanup } = extractAudioStream(TEST_VIDEO_WITH_AUDIO);
+
+ const reader = stream.getReader();
+ await reader.read();
+ reader.releaseLock();
+
+ cleanup();
+
+ await waitForProcessCleanup(beforeCount);
+ expect(getActiveProcessCount()).toBe(beforeCount);
+ });
+
+ test("extractAudioStream cleans up via cancel() method", async () => {
+ const beforeCount = getActiveProcessCount();
+
+ const { stream } = extractAudioStream(TEST_VIDEO_WITH_AUDIO);
+
+ await stream.cancel();
+
+ await waitForProcessCleanup(beforeCount);
+ expect(getActiveProcessCount()).toBe(beforeCount);
+ });
+ });
+
+ describe("concurrent request handling", () => {
+ test("handles multiple concurrent checkHasAudioTrack calls", async () => {
+ const beforeCount = getActiveProcessCount();
+ const concurrency = 5;
+
+ const promises = Array.from({ length: concurrency }, () =>
+ checkHasAudioTrack(TEST_VIDEO_WITH_AUDIO),
+ );
+
+ const results = await Promise.all(promises);
+
+ expect(results.every((r) => r === true)).toBe(true);
+ await waitForProcessCleanup(beforeCount);
+ expect(getActiveProcessCount()).toBe(beforeCount);
+ });
+
+ test("handles multiple concurrent extractAudio calls", async () => {
+ const beforeCount = getActiveProcessCount();
+ const concurrency = 3;
+
+ const promises = Array.from({ length: concurrency }, () =>
+ extractAudio(TEST_VIDEO_WITH_AUDIO),
+ );
+
+ const results = await Promise.all(promises);
+
+ expect(results.every((r) => r instanceof Uint8Array)).toBe(true);
+ await waitForProcessCleanup(beforeCount);
+ expect(getActiveProcessCount()).toBe(beforeCount);
+ });
+
+ test("handles mixed concurrent operations", async () => {
+ const beforeCount = getActiveProcessCount();
+
+ const operations = [
+ checkHasAudioTrack(TEST_VIDEO_WITH_AUDIO),
+ extractAudio(TEST_VIDEO_WITH_AUDIO),
+ (async () => {
+ const { stream } = extractAudioStream(TEST_VIDEO_WITH_AUDIO);
+ const reader = stream.getReader();
+ while (true) {
+ const { done } = await reader.read();
+ if (done) break;
+ }
+ reader.releaseLock();
+ })(),
+ ];
+
+ await Promise.all(operations);
+
+ await waitForProcessCleanup(beforeCount);
+ expect(getActiveProcessCount()).toBe(beforeCount);
+ });
+ });
+
+ describe("memory stability", () => {
+ test("memory does not grow unbounded over repeated operations", async () => {
+ if (typeof Bun.gc !== "function") {
+ console.log("Skipping GC test - Bun.gc not available");
+ return;
+ }
+
+ Bun.gc(true);
+ await new Promise((r) => setTimeout(r, 100));
+ const initialMemory = await getProcessMemoryMB();
+
+ const iterations = 10;
+ for (let i = 0; i < iterations; i++) {
+ await checkHasAudioTrack(TEST_VIDEO_WITH_AUDIO);
+ await extractAudio(TEST_VIDEO_WITH_AUDIO);
+
+ const { stream } = extractAudioStream(TEST_VIDEO_WITH_AUDIO);
+ const reader = stream.getReader();
+ while (true) {
+ const { done } = await reader.read();
+ if (done) break;
+ }
+ reader.releaseLock();
+ }
+
+ Bun.gc(true);
+ await new Promise((r) => setTimeout(r, 100));
+ const finalMemory = await getProcessMemoryMB();
+
+ const memoryGrowth = finalMemory - initialMemory;
+ const maxAllowedGrowthMB = 50;
+
+ console.log(
+ `Memory: initial=${initialMemory.toFixed(2)}MB, final=${finalMemory.toFixed(2)}MB, growth=${memoryGrowth.toFixed(2)}MB`,
+ );
+
+ expect(memoryGrowth).toBeLessThan(maxAllowedGrowthMB);
+ });
+
+ test("active process count stays bounded under load", async () => {
+ const beforeCount = getActiveProcessCount();
+ const operations = 20;
+
+ const promises = Array.from({ length: operations }, async (_, i) => {
+ try {
+ if (i % 3 === 0) {
+ await checkHasAudioTrack(TEST_VIDEO_WITH_AUDIO);
+ } else if (i % 3 === 1) {
+ await extractAudio(TEST_VIDEO_WITH_AUDIO);
+ } else {
+ const { stream, cleanup } = extractAudioStream(
+ TEST_VIDEO_WITH_AUDIO,
+ );
+ const reader = stream.getReader();
+ const { done } = await reader.read();
+ if (!done) {
+ reader.releaseLock();
+ cleanup();
+ }
+ }
+ } catch {
+ // Server busy errors expected when hitting concurrency limit
+ }
+ });
+
+ await Promise.all(promises);
+
+ await waitForProcessCleanup(beforeCount, 10000);
+ expect(getActiveProcessCount()).toBe(beforeCount);
+ });
+ });
+
+ describe("no orphaned ffmpeg processes", () => {
+ test("ffmpeg process count returns to baseline after operations", async () => {
+ const baselineCount = await countFFmpegProcesses();
+
+ await checkHasAudioTrack(TEST_VIDEO_WITH_AUDIO);
+ await extractAudio(TEST_VIDEO_WITH_AUDIO);
+
+ const { stream, cleanup } = extractAudioStream(TEST_VIDEO_WITH_AUDIO);
+ await stream.cancel();
+ cleanup();
+
+ await new Promise((r) => setTimeout(r, 3000));
+
+ const finalCount = await countFFmpegProcesses();
+
+ const processGrowth = finalCount - baselineCount;
+ expect(processGrowth).toBeLessThanOrEqual(2);
+ });
+ });
+});
+
+describe("abort signal handling", () => {
+ test("stream cleanup is called when response is aborted", async () => {
+ let cleanupCalled = false;
+
+ const { stream, cleanup: originalCleanup } = extractAudioStream(
+ TEST_VIDEO_WITH_AUDIO,
+ );
+
+ const wrappedCleanup = () => {
+ cleanupCalled = true;
+ originalCleanup();
+ };
+
+ const controller = new AbortController();
+
+ setTimeout(() => controller.abort(), 50);
+
+ controller.signal.addEventListener("abort", () => {
+ wrappedCleanup();
+ });
+
+ try {
+ const reader = stream.getReader();
+ while (!controller.signal.aborted) {
+ const { done } = await reader.read();
+ if (done) break;
+ await new Promise((r) => setTimeout(r, 10));
+ }
+ reader.releaseLock();
+ } catch {}
+
+ await new Promise((r) => setTimeout(r, 100));
+ expect(cleanupCalled).toBe(true);
+ });
+});
diff --git a/apps/media-server/src/__tests__/routes/audio-memory.test.ts b/apps/media-server/src/__tests__/routes/audio-memory.test.ts
new file mode 100644
index 000000000..dffe75a89
--- /dev/null
+++ b/apps/media-server/src/__tests__/routes/audio-memory.test.ts
@@ -0,0 +1,196 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
+import { join } from "node:path";
+import { getActiveProcessCount } from "../../lib/ffmpeg";
+
+const FIXTURES_DIR = join(import.meta.dir, "..", "fixtures");
+const TEST_VIDEO_WITH_AUDIO = `file://${join(FIXTURES_DIR, "test-with-audio.mp4")}`;
+
+async function waitForProcessCleanup(
+ expectedCount: number,
+ timeoutMs = 5000,
+): Promise<void> {
+ const startTime = Date.now();
+ while (Date.now() - startTime < timeoutMs) {
+ if (getActiveProcessCount() === expectedCount) return;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ throw new Error(
+ `Timeout waiting for process count to reach ${expectedCount}, got ${getActiveProcessCount()}`,
+ );
+}
+
+async function getFreshApp() {
+ mock.restore();
+ const { default: freshApp } = await import("../../app");
+ return freshApp;
+}
+
+describe("audio routes memory management", () => {
+ let initialProcessCount: number;
+
+ beforeEach(() => {
+ mock.restore();
+ initialProcessCount = getActiveProcessCount();
+ });
+
+ afterEach(async () => {
+ await waitForProcessCleanup(initialProcessCount, 10000);
+ });
+
+ describe("POST /audio/check", () => {
+ test("cleans up after successful check", async () => {
+ const app = await getFreshApp();
+ const response = await app.fetch(
+ new Request("http://localhost/audio/check", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl: TEST_VIDEO_WITH_AUDIO }),
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ const data = await response.json();
+ expect(data.hasAudio).toBe(true);
+
+ await waitForProcessCleanup(initialProcessCount);
+ });
+
+ test("cleans up after multiple concurrent checks", async () => {
+ const app = await getFreshApp();
+ const requests = Array.from({ length: 5 }, () =>
+ app.fetch(
+ new Request("http://localhost/audio/check", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ videoUrl: TEST_VIDEO_WITH_AUDIO }),
+ }),
+ ),
+ );
+
+ const responses = await Promise.all(requests);
+
+ for (const response of responses) {
+ expect(response.status).toBe(200);
+ await response.json();
+ }
+
+ await waitForProcessCleanup(initialProcessCount);
+ });
+ });
+
+ describe("POST /audio/extract (streaming)", () => {
+ test("cleans up after stream is fully consumed", async () => {
+ const app = await getFreshApp();
+ const response = await app.fetch(
+ new Request("http://localhost/audio/extract", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ videoUrl: TEST_VIDEO_WITH_AUDIO,
+ stream: true,
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(200);
+
+ const reader = response.body!.getReader();
+ while (true) {
+ const { done } = await reader.read();
+ if (done) break;
+ }
+ reader.releaseLock();
+
+ await waitForProcessCleanup(initialProcessCount);
+ });
+
+ test("cleans up when stream is cancelled early", async () => {
+ const app = await getFreshApp();
+ const response = await app.fetch(
+ new Request("http://localhost/audio/extract", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ videoUrl: TEST_VIDEO_WITH_AUDIO,
+ stream: true,
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(200);
+
+ const reader = response.body!.getReader();
+ await reader.read();
+ await reader.cancel();
+
+ await waitForProcessCleanup(initialProcessCount);
+ });
+
+ test("cleans up when response body is not read at all", async () => {
+ const app = await getFreshApp();
+ const response = await app.fetch(
+ new Request("http://localhost/audio/extract", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ videoUrl: TEST_VIDEO_WITH_AUDIO,
+ stream: true,
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(200);
+
+ await response.body?.cancel();
+
+ await waitForProcessCleanup(initialProcessCount, 15000);
+ });
+
+ test("cleans up with multiple concurrent streaming requests", async () => {
+ const app = await getFreshApp();
+ const requests = Array.from({ length: 3 }, () =>
+ app.fetch(
+ new Request("http://localhost/audio/extract", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ videoUrl: TEST_VIDEO_WITH_AUDIO,
+ stream: true,
+ }),
+ }),
+ ),
+ );
+
+ const responses = await Promise.all(requests);
+
+ for (const response of responses) {
+ expect(response.status).toBe(200);
+ const reader = response.body!.getReader();
+ while (true) {
+ const { done } = await reader.read();
+ if (done) break;
+ }
+ reader.releaseLock();
+ }
+
+ await waitForProcessCleanup(initialProcessCount);
+ });
+ });
+
+ describe("status endpoint", () => {
+ test("reports accurate process count", async () => {
+ const app = await getFreshApp();
+ const response = await app.fetch(
+ new Request("http://localhost/audio/status", {
+ method: "GET",
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ const data = await response.json();
+ expect(typeof data.activeProcesses).toBe("number");
+ expect(typeof data.canAcceptNewProcess).toBe("boolean");
+ expect(data.activeProcesses).toBe(initialProcessCount);
+ });
+ });
+});
diff --git a/apps/media-server/src/lib/ffmpeg.ts b/apps/media-server/src/lib/ffmpeg.ts
index 7524251f1..ef9c3b6d1 100644
--- a/apps/media-server/src/lib/ffmpeg.ts
+++ b/apps/media-server/src/lib/ffmpeg.ts
@@ -56,6 +56,47 @@ async function withTimeout<T>(
}
}
+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("");
+}
+
+const MAX_STDERR_BYTES = 64 * 1024;
+
export async function checkHasAudioTrack(videoUrl: string): Promise<boolean> {
if (!canAcceptNewProcess()) {
throw new Error("Server is busy, please try again later");
@@ -72,7 +113,12 @@ export async function checkHasAudioTrack(videoUrl: string): Promise<boolean> {
try {
const result = await withTimeout(
(async () => {
- const stderrText = await new Response(proc.stderr).text();
+ drainStream(proc.stdout as ReadableStream<Uint8Array>);
+
+ const stderrText = await readStreamWithLimit(
+ proc.stderr as ReadableStream<Uint8Array>,
+ MAX_STDERR_BYTES,
+ );
await proc.exited;
return /Stream #\d+:\d+.*Audio:/.test(stderrText);
})(),
@@ -122,9 +168,35 @@ export async function extractAudio(
try {
const result = await withTimeout(
(async () => {
- const [stdout, stderrText, exitCode] = await Promise.all([
- new Response(proc.stdout).arrayBuffer(),
- new Response(proc.stderr).text(),
+ 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;
+
+ totalBytes += value.length;
+ if (totalBytes > MAX_AUDIO_SIZE_BYTES) {
+ reader.releaseLock();
+ throw new Error(
+ `Audio too large: exceeds ${MAX_AUDIO_SIZE_BYTES} byte limit`,
+ );
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+
+ const [stderrText, exitCode] = await Promise.all([
+ stderrPromise,
proc.exited,
]);
@@ -132,13 +204,14 @@ export async function extractAudio(
throw new Error(`FFmpeg exited with code ${exitCode}: ${stderrText}`);
}
- if (stdout.byteLength > MAX_AUDIO_SIZE_BYTES) {
- throw new Error(
- `Audio too large: ${stdout.byteLength} bytes exceeds ${MAX_AUDIO_SIZE_BYTES} byte limit`,
- );
+ const output = new Uint8Array(totalBytes);
+ let offset = 0;
+ for (const chunk of chunks) {
+ output.set(chunk, offset);
+ offset += chunk.length;
}
- return new Uint8Array(stdout);
+ return output;
})(),
EXTRACT_TIMEOUT_MS,
() => killProcess(proc),
@@ -190,11 +263,19 @@ export function extractAudioStream(
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let cleaned = false;
+ let reader: ReadableStreamDefaultReader<Uint8Array> | null = null;
const cleanup = () => {
if (cleaned) return;
cleaned = true;
if (timeoutId) clearTimeout(timeoutId);
+ if (reader) {
+ try {
+ reader.cancel().catch(() => {});
+ reader.releaseLock();
+ } catch {}
+ reader = null;
+ }
activeProcesses--;
killProcess(proc);
};
@@ -204,8 +285,10 @@ export function extractAudioStream(
cleanup();
}, EXTRACT_TIMEOUT_MS);
+ drainStream(proc.stderr as ReadableStream<Uint8Array>);
+
proc.exited.then((code) => {
- if (code !== 0) {
+ if (code !== 0 && !cleaned) {
console.error(`[ffmpeg] Stream extraction exited with code ${code}`);
}
cleanup();
@@ -213,27 +296,36 @@ export function extractAudioStream(
const originalStream = proc.stdout as ReadableStream<Uint8Array>;
- const wrappedStream = new ReadableStream<Uint8Array>({
- async start(controller) {
- const reader = originalStream.getReader();
- try {
- while (true) {
+ const wrappedStream = new ReadableStream<Uint8Array>(
+ {
+ start() {
+ reader = originalStream.getReader();
+ },
+ async pull(controller) {
+ if (!reader || cleaned) {
+ controller.close();
+ return;
+ }
+
+ try {
const { done, value } = await reader.read();
- if (done) break;
- controller.enqueue(value);
+ if (done) {
+ controller.close();
+ cleanup();
+ } else {
+ controller.enqueue(value);
+ }
+ } catch (err) {
+ controller.error(err);
+ cleanup();
}
- controller.close();
- } catch (err) {
- controller.error(err);
- } finally {
- reader.releaseLock();
+ },
+ cancel() {
cleanup();
- }
- },
- cancel() {
- cleanup();
+ },
},
- });
+ new CountQueuingStrategy({ highWaterMark: 4 }),
+ );
return { stream: wrappedStream, cleanup };
}
diff --git a/apps/media-server/src/routes/audio.ts b/apps/media-server/src/routes/audio.ts
index 39bd3ed8b..1a253b098 100644
--- a/apps/media-server/src/routes/audio.ts
+++ b/apps/media-server/src/routes/audio.ts
@@ -115,7 +115,12 @@ audio.post("/extract", async (c) => {
}
if (useStreaming) {
- const { stream } = extractAudioStream(videoUrl);
+ const { stream, cleanup } = extractAudioStream(videoUrl);
+
+ c.req.raw.signal.addEventListener("abort", () => {
+ cleanup();
+ });
+
return new Response(stream, {
headers: {
"Content-Type": "audio/mpeg",