Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(web): remove ffmpeg from segment transcription - binary absent in prod
Richie McIlroyd0edd3d4f1da
diff --git a/apps/web/__tests__/e2e/live-transcribe-local-e2e.test.ts b/apps/web/__tests__/e2e/live-transcribe-local-e2e.test.tsindex 4c521b950..2e52d76b9 100644--- a/apps/web/__tests__/e2e/live-transcribe-local-e2e.test.ts+++ b/apps/web/__tests__/e2e/live-transcribe-local-e2e.test.ts@@ -22,7 +22,6 @@ import { AssemblyAI } from "assemblyai";import { Either, Schema } from "effect";import { describe, expect, it } from "vitest";import { getAssemblyAITranscriptionOptions } from "@/lib/assemblyai";-import { extractAudioFromUrl } from "@/lib/audio-extract";import {createEditTranscript,editTranscriptWordsToCaptionVtt,@@ -35,7 +34,10 @@ import {planNextLiveChunk,} from "@/lib/live-transcribe-core";import { planSegmentsAudioExtraction } from "@/lib/segments-audio";-import { downloadConcatenatedSegments } from "@/lib/segments-audio-download";+import {+ downloadConcatenatedSegments,+ downloadConcatenatedSegmentsToBuffer,+} from "@/lib/segments-audio-download";const enabled =process.env.CAP_TRANSCRIBE_E2E === "1" &&@@ -70,15 +72,6 @@ const presign = (client: S3Client, key: string) =>expiresIn: 3600,});-async function extractMp3(concatPath: string): Promise<Buffer> {- const extracted = await extractAudioFromUrl(concatPath);- try {- return await fs.readFile(extracted.filePath);- } finally {- await extracted.cleanup();- }-}-async function transcribeBuffer(audio: Buffer,language: Parameters<typeof getAssemblyAITranscriptionOptions>[0],@@ -139,15 +132,17 @@ describe.skipIf(!enabled)("segments transcription local e2e", () => {`[e2e] concatenated ${plan.entries.length} segments: ${bytes} bytes, expected ~${Math.round(plan.totalDurationMs / 1000)}s audio`,);- const mp3 = await extractMp3(concatPath);- expect(mp3.length).toBeGreaterThan(10_000);+ // The raw fMP4 concat goes to AssemblyAI directly — the production+ // path has no transcode step and no ffmpeg.+ const fmp4 = await fs.readFile(concatPath);+ expect(fmp4.length).toBeGreaterThan(10_000);- const full = await transcribeBuffer(mp3, "auto");+ const full = await transcribeBuffer(fmp4, "auto");const audioDurationMs = (full.audio_duration ?? 0) * 1000;// ffmpeg-decoded duration must match the manifest's segment sum- expect(- Math.abs(audioDurationMs - plan.totalDurationMs),- ).toBeLessThan(3000);+ expect(Math.abs(audioDurationMs - plan.totalDurationMs)).toBeLessThan(+ 3000,+ );const edit = createEditTranscript(full, plan.totalDurationMs);const vtt = editTranscriptWordsToCaptionVtt(edit.words);@@ -160,9 +155,8 @@ describe.skipIf(!enabled)("segments transcription local e2e", () => {const artifactChunks: string[] = [];let artifact = createEmptyLiveTranscript(new Date().toISOString());let lastIndex = LIVE_TRANSCRIPT_NO_SEGMENTS;- let language: Parameters<- typeof getAssemblyAITranscriptionOptions- >[0] = "auto";+ let language: Parameters<typeof getAssemblyAITranscriptionOptions>[0] =+ "auto";for (let i = 0; i < 20; i++) {const decision = planNextLiveChunk({@@ -185,11 +179,10 @@ describe.skipIf(!enabled)("segments transcription local e2e", () => {),),]);- const chunkPath = join(tmpdir(), `e2e-chunk-${randomUUID()}.mp4`);- try {- await downloadConcatenatedSegments(chunkUrls, chunkPath);- const chunkMp3 = await extractMp3(chunkPath);- const chunkTranscript = await transcribeBuffer(chunkMp3, language);+ {+ const chunkFmp4 =+ await downloadConcatenatedSegmentsToBuffer(chunkUrls);+ const chunkTranscript = await transcribeBuffer(chunkFmp4, language);const words = offsetChunkWords(chunkTranscript.words,@@ -217,8 +210,6 @@ describe.skipIf(!enabled)("segments transcription local e2e", () => {console.log(`[e2e] CHUNK ${artifactChunks.length}: segments ..${lastIndex}, +${words.length} words @ ${decision.startMs}ms`,);- } finally {- await fs.unlink(chunkPath).catch(() => {});}}diff --git a/apps/web/lib/segments-audio-download.ts b/apps/web/lib/segments-audio-download.tsindex ec3c19996..3103e6515 100644--- a/apps/web/lib/segments-audio-download.ts+++ b/apps/web/lib/segments-audio-download.ts@@ -7,14 +7,65 @@ import { createWriteStream } from "node:fs";*//**- * Sized so concat fMP4 + extracted mp3 both fit a 512MB serverless /tmp with- * headroom (~2h of 192kbps AAC). Beyond it the caller gets a clean- * "unavailable" and defers to the post-mux path instead of ENOSPC/OOM.+ * Sized to fit a 512MB serverless /tmp (and memory) with plenty of headroom+ * (~2h of 192kbps AAC). Beyond it the caller gets a clean "unavailable" and+ * defers to the post-mux path instead of ENOSPC/OOM.*/const MAX_SEGMENTS_AUDIO_BYTES = 192 * 1024 * 1024;const DEFAULT_DOWNLOAD_CONCURRENCY = 8;+/**+ * Download objects and byte-concatenate them, in order, into one Buffer. An+ * fMP4 init segment followed by its fragments concatenates into a valid+ * fragmented MP4 that AssemblyAI ingests directly — no transcode step, no+ * ffmpeg binary (which is not available in the serverless runtime). Only for+ * bounded inputs like live chunks; use the file variant for whole recordings.+ */+export async function downloadConcatenatedSegmentsToBuffer(+ urls: string[],+ options: {+ concurrency?: number;+ maxBytes?: number;+ fetchImpl?: typeof fetch;+ } = {},+): Promise<Buffer> {+ const concurrency = Math.max(+ 1,+ options.concurrency ?? DEFAULT_DOWNLOAD_CONCURRENCY,+ );+ const maxBytes = options.maxBytes ?? MAX_SEGMENTS_AUDIO_BYTES;+ const fetchImpl = options.fetchImpl ?? fetch;++ const buffers: Buffer[] = [];+ let totalBytes = 0;++ for (let start = 0; start < urls.length; start += concurrency) {+ const batch = urls.slice(start, start + concurrency);+ const batchBuffers = await Promise.all(+ batch.map(async (url, offset) => {+ const response = await fetchImpl(url);+ if (!response.ok) {+ throw new Error(+ `Segment ${start + offset} not accessible: ${response.status}`,+ );+ }+ return Buffer.from(await response.arrayBuffer());+ }),+ );++ for (const buffer of batchBuffers) {+ totalBytes += buffer.length;+ if (totalBytes > maxBytes) {+ throw new Error(`Segment audio exceeds ${maxBytes} bytes`);+ }+ buffers.push(buffer);+ }+ }++ return Buffer.concat(buffers);+}+/*** Download objects and byte-concatenate them, in order, into `outputPath`.* An fMP4 init segment followed by its fragments concatenates into a validdiff --git a/apps/web/workflows/live-transcribe.ts b/apps/web/workflows/live-transcribe.tsindex 1fb55caa0..bc185e06f 100644--- a/apps/web/workflows/live-transcribe.ts+++ b/apps/web/workflows/live-transcribe.ts@@ -1,7 +1,3 @@-import { randomUUID } from "node:crypto";-import { promises as fs } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";import { db } from "@cap/database";import { organizations, users, videoEdits, videos } from "@cap/database/schema";import { serverEnv } from "@cap/env";@@ -21,7 +17,6 @@ import {ASSEMBLYAI_SUPPORTED_LANGUAGES,getAssemblyAITranscriptionOptions,} from "@/lib/assemblyai";-import { extractAudioFromUrl } from "@/lib/audio-extract";import {getEditTranscriptObjectKey,serializeEditTranscript,@@ -36,13 +31,13 @@ import {isNoSpokenAudioError,LIVE_TRANSCRIBE,LIVE_TRANSCRIPT_NO_SEGMENTS,- liveTranscriptToEditTranscript,type LiveTranscriptState,+ liveTranscriptToEditTranscript,offsetChunkWords,parseLiveTranscript,planNextLiveChunk,} from "@/lib/live-transcribe-core";-import { downloadConcatenatedSegments } from "@/lib/segments-audio-download";+import { downloadConcatenatedSegmentsToBuffer } from "@/lib/segments-audio-download";import { transcribeVideo } from "@/lib/transcribe";import { decodeStorageVideo } from "@/lib/video-storage";import { runWorkflowPromise } from "@/lib/workflow-runtime";@@ -421,19 +416,11 @@ async function processNextLiveChunk(options: {),]);- const concatPath = join(tmpdir(), `live-chunk-${randomUUID()}.mp4`);- let audioBuffer: Buffer;- try {- await downloadConcatenatedSegments(segmentUrls, concatPath);- const extracted = await extractAudioFromUrl(concatPath);- try {- audioBuffer = await fs.readFile(extracted.filePath);- } finally {- await extracted.cleanup();- }- } finally {- await fs.unlink(concatPath).catch(() => {});- }+ // init + fragments concatenate into a valid fragmented MP4 that+ // AssemblyAI ingests directly (verified: full files, mid-stream chunks+ // with chunk-relative timestamps, and real desktop uploads). No local+ // ffmpeg — the binary doesn't exist in the serverless runtime.+ const audioBuffer = await downloadConcatenatedSegmentsToBuffer(segmentUrls);const client = new AssemblyAI({apiKey: serverEnv().ASSEMBLY_API_KEY as string,diff --git a/apps/web/workflows/transcribe.ts b/apps/web/workflows/transcribe.tsindex 1452d7d9e..356f54f6c 100644--- a/apps/web/workflows/transcribe.ts+++ b/apps/web/workflows/transcribe.ts@@ -38,13 +38,13 @@ import {} from "@/lib/edit-transcript";import { encryptEditTranscriptObject } from "@/lib/edit-transcript-storage";import { startAiGeneration } from "@/lib/generate-ai";+import { getLiveTranscriptObjectKey } from "@/lib/live-transcribe-core";import {checkHasAudioTrackViaMediaServer,extractAudioViaMediaServer,isMediaServerConfigured,probeVideoViaMediaServer,} from "@/lib/media-client";-import { getLiveTranscriptObjectKey } from "@/lib/live-transcribe-core";import { planSegmentsAudioExtraction } from "@/lib/segments-audio";import { downloadConcatenatedSegments } from "@/lib/segments-audio-download";import { decodeStorageVideo } from "@/lib/video-storage";@@ -718,18 +718,17 @@ async function extractAudioFromSegmentsImpl(`[transcribe] Assembled ${plan.entries.length} audio segments (${totalBytes} bytes) for ${videoId}`,);- const result = await extractAudioFromUrl(concatPath);- let audioBuffer: Buffer;- try {- audioBuffer = await fs.readFile(result.filePath);- } finally {- await result.cleanup();- }+ // The concatenated init + fragments form a valid fragmented MP4 that+ // AssemblyAI ingests directly — no transcode, and no ffmpeg binary+ // (which is not available in the serverless runtime). The temp object+ // keeps the same key regardless of container so cleanupTempAudio's+ // contract is untouched.+ const audioBuffer = await fs.readFile(concatPath);const audioKey = `${userId}/${videoId}/${tempAudioFilename}`;await bucket.putObject(audioKey, audioBuffer, {- contentType: "audio/mpeg",+ contentType: "audio/mp4",}).pipe(runWorkflowPromise);