From b35c824a27b5c37faf5688fa55c3c023b7b95ccc Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Tue, 8 Sep 2026 10:17:15 +0800 Subject: [PATCH] feat(transcode): optimize video operations using ffmpeg http range requests (#393) * feat(transcode): optimize video operations using ffmpeg http range requests * fix(transcode): preserve non-retryable errors and ensure mapConcurrent settles on rejection --- packages/agent/src/activities/ai.test.ts | 42 ++++- packages/agent/src/activities/ai.ts | 82 +++++----- .../src/workflows/agent-autofill.test.ts | 26 +--- .../agent/src/workflows/agent-autofill.ts | 20 +-- .../src/workflows/agent-embedding.test.ts | 16 +- .../agent/src/workflows/agent-embedding.ts | 22 +-- packages/core/src/s3/s3.test.ts | 20 +++ packages/core/src/s3/s3.ts | 13 ++ packages/core/src/transcode/transcode.test.ts | 36 +++++ packages/core/src/transcode/transcode.ts | 65 +++++--- packages/core/src/utils/async.test.ts | 81 ++++++++++ packages/core/src/utils/async.ts | 42 +++++ .../src/activities/transcode.test.ts | 144 ++++++++++++++++++ .../transcode/src/activities/transcode.ts | 111 +++++++++++++- .../src/workflows/transcode-video.test.ts | 76 +++++++++ .../src/workflows/transcode-video.ts | 30 +++- 16 files changed, 675 insertions(+), 151 deletions(-) create mode 100644 packages/core/src/utils/async.test.ts create mode 100644 packages/core/src/utils/async.ts diff --git a/packages/agent/src/activities/ai.test.ts b/packages/agent/src/activities/ai.test.ts index 05edd389..0490c036 100644 --- a/packages/agent/src/activities/ai.test.ts +++ b/packages/agent/src/activities/ai.test.ts @@ -37,12 +37,15 @@ vi.mock('@shumai/core/src/s3/s3', () => ({ headObject: vi.fn(), listObjects: vi.fn(), downloadToFile: vi.fn(), + resolveInput: vi.fn().mockImplementation(async (_bucket, key) => `https://mock-storage/${key}`), }, })) vi.mock('@shumai/core/src/transcode/transcode', () => ({ transcodeService: { extractVideoFrames: vi.fn(), + createTempDir: vi.fn().mockReturnValue('/tmp'), + removeDir: vi.fn(), }, })) @@ -123,8 +126,12 @@ describe('AI Activities Unit Tests', () => { ) }) - it('should stream video to tmp file via downloadToFile in generateEmbeddingActivity', async () => { - vi.mocked(s3Service.downloadToFile).mockResolvedValue() + it('should resolve video input via resolveInput and avoid downloadToFile in generateEmbeddingActivity', async () => { + vi.mocked(s3Service.downloadToFile).mockClear() + vi.mocked(s3Service.resolveInput).mockClear() + vi.mocked(s3Service.resolveInput).mockResolvedValue( + 'https://mock-storage/files/asset-123/video.mp4', + ) const res = await generateEmbeddingActivity({ teamId: 't1', @@ -140,11 +147,8 @@ describe('AI Activities Unit Tests', () => { }, }) - expect(s3Service.downloadToFile).toHaveBeenCalledWith( - 'shumai', - 'files/asset-123/video.mp4', - expect.stringContaining('video-'), - ) + expect(s3Service.resolveInput).toHaveBeenCalledWith('shumai', 'files/asset-123/video.mp4') + expect(s3Service.downloadToFile).not.toHaveBeenCalled() expect(s3Service.getObject).not.toHaveBeenCalledWith('shumai', 'files/asset-123/video.mp4') expect(res.embeddings.length).toBeGreaterThan(0) }) @@ -218,6 +222,30 @@ describe('AI Activities Unit Tests', () => { 'image/webp', ) }) + + it('should resolveInput from s3Service when filePath is not provided', async () => { + vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not Found')) + vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-storage/project/video.mp4') + vi.mocked(transcodeService.extractVideoFrames).mockResolvedValue(['/tmp/out1.webp']) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.mocked(s3Service.putObject).mockResolvedValue({} as any) + + const res = await extractAiMetadataActivity({ + assetKey: 'project/video.mp4', + type: 'autofill', + isImage: false, + }) + + expect(res).toEqual(['project/ai_metadata/out1.webp']) + expect(s3Service.resolveInput).toHaveBeenCalledWith('shumai', 'project/video.mp4') + expect(transcodeService.extractVideoFrames).toHaveBeenCalledWith({ + inputFile: 'https://mock-storage/project/video.mp4', + outputDir: expect.any(String), + numFrames: 30, + frameHeight: 720, + isImage: false, + }) + }) }) }) diff --git a/packages/agent/src/activities/ai.ts b/packages/agent/src/activities/ai.ts index 0983abb0..d6ad6f52 100644 --- a/packages/agent/src/activities/ai.ts +++ b/packages/agent/src/activities/ai.ts @@ -9,6 +9,7 @@ import { promisify } from 'util' import { ApplicationFailure } from '@temporalio/activity' import { prisma } from '@shumai/db' import { getProxyType } from '@shumai/core/src/utils/mime' +import { ulid } from 'ulid' const execFileAsync = promisify(execFile) @@ -115,41 +116,44 @@ export async function generateEmbeddingActivity(params: GenerateEmbeddingParams) const embVec = await generateMultimodalEmbedding(ai, data, asset.mediaType) results.push({ embedding: embVec }) } else if (isVideo) { - const tmpFile = path.join(os.tmpdir(), `video-${Date.now()}.mp4`) - await s3Service.downloadToFile(bucket, key, tmpFile) + const inputSource = await s3Service.resolveInput(bucket, key) + const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://') - try { - const { stdout } = await execFileAsync('ffprobe', [ - '-v', - 'error', - '-show_entries', - 'format=duration', - '-of', - 'default=noprint_wrappers=1:nokey=1', - tmpFile, - ]) - const duration = parseFloat(stdout.trim()) - if (isNaN(duration)) { - throw ApplicationFailure.create({ - message: 'failed to parse video duration', - nonRetryable: true, - }) - } + const { stdout } = await execFileAsync('ffprobe', [ + '-v', + 'error', + '-show_entries', + 'format=duration', + '-of', + 'default=noprint_wrappers=1:nokey=1', + inputSource, + ]) + const duration = parseFloat(stdout.trim()) + if (isNaN(duration)) { + throw ApplicationFailure.create({ + message: 'failed to parse video duration', + nonRetryable: true, + }) + } - const chunkSize = 60.0 - for (let start = 0.0; start < duration; start += chunkSize) { - let end = start + chunkSize - if (end > duration) end = duration + const chunkSize = 60.0 + for (let start = 0.0; start < duration; start += chunkSize) { + let end = start + chunkSize + if (end > duration) end = duration - const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}.mp4`) + const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}-${ulid()}.mp4`) + try { await execFileAsync('ffmpeg', [ '-y', '-loglevel', 'warning', - '-i', - tmpFile, + ...(isRemote + ? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5'] + : []), '-ss', start.toString(), + '-i', + inputSource, '-t', (end - start).toString(), '-c', @@ -158,7 +162,6 @@ export async function generateEmbeddingActivity(params: GenerateEmbeddingParams) ]) const chunkData = fs.readFileSync(chunkTmp) - fs.unlinkSync(chunkTmp) try { const embVec = await generateMultimodalEmbedding(ai, chunkData, 'video/mp4') @@ -169,10 +172,10 @@ export async function generateEmbeddingActivity(params: GenerateEmbeddingParams) `failed to generate video embedding for chunk ${start}-${end}: ${e.message}`, ) } - } - } finally { - if (fs.existsSync(tmpFile)) { - fs.unlinkSync(tmpFile) + } finally { + if (fs.existsSync(chunkTmp)) { + fs.unlinkSync(chunkTmp) + } } } } @@ -235,7 +238,7 @@ export async function generateTextEmbeddingActivity(params: GenerateTextEmbeddin export interface ExtractAiMetadataParams { assetKey: string - filePath: string + filePath?: string type: 'autofill' isImage: boolean } @@ -248,7 +251,12 @@ export async function extractAiMetadataActivity( const aiDir = path.join(assetDir, 'ai_metadata') const generatedFiles: string[] = [] - const tmpDir = path.dirname(params.filePath) + let tmpDir = params.filePath ? path.dirname(params.filePath) : '' + let cleanupTmp = false + if (!tmpDir) { + tmpDir = transcodeService.createTempDir('ai-meta-') + cleanupTmp = true + } try { if (params.type === 'autofill') { @@ -261,8 +269,10 @@ export async function extractAiMetadataActivity( // Not found } + const inputSource = params.filePath || (await s3Service.resolveInput(bucket, params.assetKey)) + const files = await transcodeService.extractVideoFrames({ - inputFile: params.filePath, + inputFile: inputSource, outputDir: tmpDir, numFrames: 30, frameHeight: 720, @@ -278,7 +288,9 @@ export async function extractAiMetadataActivity( } } } finally { - // Files are in tmpDir which will be cleaned up by cleanupTmpDirActivity + if (cleanupTmp && tmpDir) { + transcodeService.removeDir(tmpDir) + } } return generatedFiles diff --git a/packages/agent/src/workflows/agent-autofill.test.ts b/packages/agent/src/workflows/agent-autofill.test.ts index 7fb9aeb4..27dab08e 100644 --- a/packages/agent/src/workflows/agent-autofill.test.ts +++ b/packages/agent/src/workflows/agent-autofill.test.ts @@ -129,13 +129,9 @@ describe('Agent Autofill Workflow', () => { agentId: 'agent-1', }) - // Verify download, extraction and fields fetched - expect(mockActivities.downloadMediaToTmpActivity).toHaveBeenCalledWith({ - assetKey: 'asset-key', - }) + // Verify extraction and fields fetched expect(mockActivities.extractAiMetadataActivity).toHaveBeenCalledWith({ assetKey: 'asset-key', - filePath: '/tmp/test.png', type: 'autofill', isImage: true, }) @@ -186,11 +182,6 @@ describe('Agent Autofill Workflow', () => { sessionId: 'session-123', }) - // Verify cleanup was called - expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({ - tmpDir: '/tmp/test-dir', - }) - // Verify completed task status expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ taskId: task.id, @@ -219,11 +210,6 @@ describe('Agent Autofill Workflow', () => { expect(mockActivities.autofillAiActivity).not.toHaveBeenCalled() expect(mockActivities.updateAssetMetadataActivity).not.toHaveBeenCalled() - // Verify cleanup still runs - expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({ - tmpDir: '/tmp/test-dir', - }) - expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ taskId: task.id, status: 'completed', @@ -251,11 +237,6 @@ describe('Agent Autofill Workflow', () => { expect(mockActivities.autofillAiActivity).not.toHaveBeenCalled() expect(mockActivities.updateAssetMetadataActivity).not.toHaveBeenCalled() - // Verify cleanup still runs - expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({ - tmpDir: '/tmp/test-dir', - }) - expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ taskId: task.id, status: 'completed', @@ -287,11 +268,6 @@ describe('Agent Autofill Workflow', () => { status: 'failed', output: { error: 'DB failure' }, }) - - // Verify cleanup still runs in finally block - expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({ - tmpDir: '/tmp/test-dir', - }) }) it('should fail with non-retryable ApplicationFailure for unsupported audio files', async () => { diff --git a/packages/agent/src/workflows/agent-autofill.ts b/packages/agent/src/workflows/agent-autofill.ts index 58a9a8d9..672e89a5 100644 --- a/packages/agent/src/workflows/agent-autofill.ts +++ b/packages/agent/src/workflows/agent-autofill.ts @@ -22,13 +22,10 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise { updateCommentActivity, getTranscodeWorkerQueueActivity, getAgentWorkerQueueActivity, - downloadMediaToTmpActivity, - cleanupTmpDirActivity, } = getActivities() let placeholderCommentId: string | undefined - let tmpDir: string | undefined - let transcodeWorkerQueue = '' + let transcodeWorkerQueue: string let agentWorkerQueue = '' try { @@ -78,15 +75,8 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise { }) } - const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, { - assetKey: key, - }) - const { filePath } = download - tmpDir = download.tmpDir - const generatedFiles = await executeActivity(transcodeWorkerQueue, extractAiMetadataActivity, { assetKey: key, - filePath, type: 'autofill', isImage, }) @@ -211,14 +201,6 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise { }) } throw err - } finally { - if (tmpDir && transcodeWorkerQueue) { - try { - await executeActivity(transcodeWorkerQueue, cleanupTmpDirActivity, { tmpDir }) - } catch (cleanupErr) { - console.error('Failed to cleanup tmp dir:', cleanupErr) - } - } } } diff --git a/packages/agent/src/workflows/agent-embedding.test.ts b/packages/agent/src/workflows/agent-embedding.test.ts index 375473ac..2d0b2a84 100644 --- a/packages/agent/src/workflows/agent-embedding.test.ts +++ b/packages/agent/src/workflows/agent-embedding.test.ts @@ -242,29 +242,26 @@ describe('Agent Embedding Workflow', () => { await agentEmbeddingMedia(task) - // Verify video transcode queue discovery & download + // Verify video transcode queue discovery expect(mockActivities.getTranscodeWorkerQueueActivity).toHaveBeenCalled() - expect(mockActivities.downloadMediaToTmpActivity).toHaveBeenCalledWith({ - assetKey: 'test-transcoded.mp4', - }) // Verify video chunk slicing activity called 3 times on transcode queue expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(3) expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(1, { assetId: 'a1', - filePath: '/tmp/test.mp4', + assetKey: 'test-transcoded.mp4', startTime: 0, endTime: 60, }) expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(2, { assetId: 'a1', - filePath: '/tmp/test.mp4', + assetKey: 'test-transcoded.mp4', startTime: 55, endTime: 115, }) expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(3, { assetId: 'a1', - filePath: '/tmp/test.mp4', + assetKey: 'test-transcoded.mp4', startTime: 110, endTime: 150, }) @@ -290,11 +287,6 @@ describe('Agent Embedding Workflow', () => { key: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4', }) - // Verify temp directory cleanup on transcode queue - expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({ - tmpDir: '/tmp/test-dir', - }) - // Verify usage update (3 chunks * 3 tokens = 9) expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({ taskId: task.id, diff --git a/packages/agent/src/workflows/agent-embedding.ts b/packages/agent/src/workflows/agent-embedding.ts index 54739c25..ab365ab7 100644 --- a/packages/agent/src/workflows/agent-embedding.ts +++ b/packages/agent/src/workflows/agent-embedding.ts @@ -25,16 +25,13 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise { updateCommentActivity, getAgentWorkerQueueActivity, getTranscodeWorkerQueueActivity, - downloadMediaToTmpActivity, - cleanupTmpDirActivity, transcodeVideoChunkActivity, deleteS3ObjectActivity, } = getActivities() let placeholderCommentId: string | undefined let agentWorkerQueue = '' - let transcodeWorkerQueue = '' - let tmpDir: string | undefined + let transcodeWorkerQueue: string try { // 0. Discover queues @@ -132,13 +129,6 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise { usage.outputTokens += result.usage.outputTokens || 0 } } else if (isVideo) { - // 1. Download full video to transcode worker temp space - const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, { - assetKey: embeddingKey, - }) - const { filePath } = download - tmpDir = download.tmpDir - // Get video duration // eslint-disable-next-line @typescript-eslint/no-explicit-any const duration = (asset.media as any)?.duration || 0 @@ -155,7 +145,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise { // Step A: Slice chunk on transcode worker and upload to S3 const chunkRes = await executeActivity(transcodeWorkerQueue, transcodeVideoChunkActivity, { assetId: asset.id, - filePath, + assetKey: embeddingKey, startTime: start, endTime: end, }) @@ -249,14 +239,6 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise { }) } throw err - } finally { - if (tmpDir && transcodeWorkerQueue) { - try { - await executeActivity(transcodeWorkerQueue, cleanupTmpDirActivity, { tmpDir }) - } catch (cleanupErr) { - console.error('Failed to cleanup transcode worker tmp dir:', cleanupErr) - } - } } } diff --git a/packages/core/src/s3/s3.test.ts b/packages/core/src/s3/s3.test.ts index fd4f74eb..aa07762c 100644 --- a/packages/core/src/s3/s3.test.ts +++ b/packages/core/src/s3/s3.test.ts @@ -345,6 +345,15 @@ describe('S3Service implementations', () => { ).rejects.toThrow('Abort multipart upload requires uploadId') }) + it('should resolveInput using presign GET in S3StorageService', async () => { + const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket') + const presignSpy = vi.spyOn(s3, 'presign').mockResolvedValue('https://presigned.s3.url') + + const input = await s3.resolveInput('test-bucket', 'video.mp4') + expect(input).toBe('https://presigned.s3.url') + expect(presignSpy).toHaveBeenCalledWith('test-bucket', 'video.mp4', 'GET') + }) + it('should stream in uploadFileToKey', async () => { const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket') s3SendSpy.mockClear() @@ -587,6 +596,17 @@ describe('S3Service implementations', () => { it('should throw an error for unsupported presign methods', async () => { await expect(localS3.presign('b', 'k', 'POST')).rejects.toThrow() }) + + it('should resolveInput to local file path if file exists on disk', async () => { + await localS3.putObject('my-bucket', 'video.mp4', 'dummy content', 13) + const input = await localS3.resolveInput('my-bucket', 'video.mp4') + expect(input).toBe(path.join(TEST_BASE_PATH, 'my-bucket', 'video.mp4')) + }) + + it('should resolveInput to presigned URL if file does not exist on disk', async () => { + const input = await localS3.resolveInput('my-bucket', 'nonexistent.mp4') + expect(input).toBe('http://localhost:3000/files/my-bucket/nonexistent.mp4') + }) }) describe('s3Service initialization', () => { diff --git a/packages/core/src/s3/s3.ts b/packages/core/src/s3/s3.ts index c90cf885..0a756cb8 100644 --- a/packages/core/src/s3/s3.ts +++ b/packages/core/src/s3/s3.ts @@ -118,6 +118,7 @@ export interface S3Service { request: S3SignRequest, ) => Promise<{ url: string }> abortMultipartUpload: (bucket: string, key: string, uploadId: string) => Promise + resolveInput: (bucket: string, key: string) => Promise } export class S3StorageService implements S3Service { @@ -459,6 +460,10 @@ export class S3StorageService implements S3Service { }), ) } + + async resolveInput(bucket: string, key: string): Promise { + return this.presign(bucket, key, 'GET') + } } export class LocalStorageService implements S3Service { @@ -717,6 +722,14 @@ export class LocalStorageService implements S3Service { ): Promise { await this.deleteObject(bucket, key) } + + async resolveInput(bucket: string, key: string): Promise { + const filePath = this.getFilePath(bucket, key) + if (fs.existsSync(filePath)) { + return filePath + } + return this.presign(bucket, key, 'GET') + } } export function getStorageBackend(): 's3' | 'local' { diff --git a/packages/core/src/transcode/transcode.test.ts b/packages/core/src/transcode/transcode.test.ts index 8244a6e9..0cd329e4 100644 --- a/packages/core/src/transcode/transcode.test.ts +++ b/packages/core/src/transcode/transcode.test.ts @@ -21,6 +21,7 @@ vi.mock('@shumai/core/src/s3/s3', () => ({ s3Service: { downloadToFile: vi.fn(), putObject: vi.fn(), + resolveInput: vi.fn().mockImplementation(async (_bucket, key) => `http://mock-storage/${key}`), }, })) @@ -940,6 +941,41 @@ describe('TranscodeService', () => { overlaySpy.mockRestore() }) + it('should use resolveInput and avoid downloadToFile when taking screenshots', async () => { + vi.mocked(s3Service.downloadToFile).mockClear() + vi.mocked(s3Service.resolveInput).mockClear() + vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-r2.com/video.mp4') + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ;(child_process.execFile as any).mockImplementation( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (file: string, args: string[], cb: any) => { + if (file === 'ffmpeg') { + const outPath = args[args.length - 1] + fs.writeFileSync(outPath, 'fake-webp-image') + } + cb(null, { stdout: '', stderr: '' }) + }, + ) + + const results = await transcodeService.takeScreenshots({ + assetKey: 'test/video.mp4', + assetId: 'asset-123', + start: 0, + end: 10, + count: 5, + }) + + expect(results).toHaveLength(5) + expect(s3Service.resolveInput).toHaveBeenCalledWith('shumai', 'test/video.mp4') + expect(s3Service.downloadToFile).not.toHaveBeenCalled() + expect(child_process.execFile).toHaveBeenCalledWith( + 'ffmpeg', + expect.arrayContaining(['-i', 'https://mock-r2.com/video.mp4', '-reconnect', '1']), + expect.any(Function), + ) + }) + it('should generate PDF from text file including CJK characters', async () => { const txtFile = path.join(tempDir, 'test.txt') const pdfFile = path.join(tempDir, 'output.pdf') diff --git a/packages/core/src/transcode/transcode.ts b/packages/core/src/transcode/transcode.ts index 701f6f60..bbba272d 100644 --- a/packages/core/src/transcode/transcode.ts +++ b/packages/core/src/transcode/transcode.ts @@ -1,5 +1,6 @@ import { s3Service } from '@shumai/core/src/s3/s3' import { stemFromKey } from '@shumai/core/src/utils/filename' +import { mapConcurrent } from '../utils/async' import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db' import '@shumai/db/src/prisma-json-types' import { execFile } from 'child_process' @@ -1108,21 +1109,36 @@ export class TranscodeService { } const meta = await this.getVideoInfo(params.inputFile) - const fps = params.numFrames / meta.duration - const outputPattern = path.join(params.outputDir, '%d.webp') + const isRemote = + params.inputFile.startsWith('http://') || params.inputFile.startsWith('https://') - const args = [ - '-i', - params.inputFile, - '-vf', - `fps=${fps},scale=-2:${params.frameHeight}`, - '-c:v', - 'libwebp', - '-q:v', - '80', - outputPattern, - ] - await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args]) + const duration = meta.duration > 0 ? meta.duration : 1 + const numFrames = Math.max(1, params.numFrames) + const step = duration / numFrames + const timestamps = Array.from({ length: numFrames }, (_, i) => i * step) + + await mapConcurrent(timestamps, 10, async (t, idx) => { + const outputFile = path.join(params.outputDir, `${idx + 1}.webp`) + const args = [ + ...(isRemote + ? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5'] + : []), + '-ss', + t.toFixed(4), + '-i', + params.inputFile, + '-vframes', + '1', + '-vf', + `scale=-2:${params.frameHeight}`, + '-c:v', + 'libwebp', + '-q:v', + '80', + outputFile, + ] + await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args]) + }) const files = fs.readdirSync(params.outputDir) return files @@ -1186,11 +1202,11 @@ export class TranscodeService { }): Promise> { const bucket = process.env.S3_BUCKET || 'shumai' const tmpDir = this.createTempDir('screenshot-') - const videoPath = path.join(tmpDir, path.basename(params.assetKey)) try { - // 1. Download video - await s3Service.downloadToFile(bucket, params.assetKey, videoPath) + // 1. Resolve input source (presigned GET URL for S3/R2, local file path for local storage) + const inputSource = await s3Service.resolveInput(bucket, params.assetKey) + const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://') // 2. Generate timestamps let timestamps: number[] = [] @@ -1221,18 +1237,19 @@ export class TranscodeService { } } - const results: Array<{ key: string; timestamp: number }> = [] - - // 4. Extract each screenshot - for (const t of timestamps) { + // 4. Extract screenshots concurrently with a limit of 10 parallel processes + const results = await mapConcurrent(timestamps, 10, async (t) => { const outName = `shot-${t.toFixed(4)}-${ulid()}.webp` const localShotPath = path.join(tmpDir, outName) const args = [ + ...(isRemote + ? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5'] + : []), '-ss', t.toFixed(4), '-i', - videoPath, + inputSource, '-vframes', '1', '-vf', @@ -1262,8 +1279,8 @@ export class TranscodeService { const fileBuffer = fs.readFileSync(localShotPath) await s3Service.putObject(bucket, s3Key, fileBuffer, fileBuffer.length, 'image/webp') - results.push({ key: s3Key, timestamp: t }) - } + return { key: s3Key, timestamp: t } + }) return results } finally { diff --git a/packages/core/src/utils/async.test.ts b/packages/core/src/utils/async.test.ts new file mode 100644 index 00000000..3afc56ff --- /dev/null +++ b/packages/core/src/utils/async.test.ts @@ -0,0 +1,81 @@ +import { describe, it, expect } from 'vitest' +import { mapConcurrent } from './async' + +describe('mapConcurrent', () => { + it('should process items and preserve original ordering', async () => { + const items = [10, 20, 30, 40, 50] + const results = await mapConcurrent(items, 2, async (item, idx) => { + return item * 2 + idx + }) + + expect(results).toEqual([20, 41, 62, 83, 104]) + }) + + it('should respect concurrency limits', async () => { + let running = 0 + let maxRunning = 0 + const items = Array.from({ length: 20 }, (_, i) => i) + + const results = await mapConcurrent(items, 4, async (item) => { + running++ + maxRunning = Math.max(maxRunning, running) + await new Promise((resolve) => setTimeout(resolve, 10)) + running-- + return item * 2 + }) + + expect(results).toHaveLength(20) + expect(maxRunning).toBeLessThanOrEqual(4) + expect(maxRunning).toBeGreaterThan(1) + }) + + it('should handle empty input array', async () => { + const results = await mapConcurrent([], 5, async () => 1) + expect(results).toEqual([]) + }) + + it('should wait for all in-flight tasks to settle and not start queued tasks on error', async () => { + let task1Settled = false + let task2Started = false + + const items = [0, 1, 2] + // concurrency 2: items 0 and 1 start immediately. Item 2 is queued. + await expect( + mapConcurrent(items, 2, async (item) => { + if (item === 0) { + await new Promise((resolve) => setTimeout(resolve, 10)) + throw new Error('Task 0 failed') + } + if (item === 1) { + await new Promise((resolve) => setTimeout(resolve, 30)) + task1Settled = true + return 'ok-1' + } + task2Started = true + return 'ok-2' + }), + ).rejects.toThrow('Task 0 failed') + + expect(task1Settled).toBe(true) + expect(task2Started).toBe(false) + }) + + it('should rethrow the first encountered error when multiple concurrent workers fail', async () => { + let task1Settled = false + + const items = [0, 1] + await expect( + mapConcurrent(items, 2, async (item) => { + if (item === 0) { + await new Promise((resolve) => setTimeout(resolve, 10)) + throw new Error('First error') + } + await new Promise((resolve) => setTimeout(resolve, 30)) + task1Settled = true + throw new Error('Second error') + }), + ).rejects.toThrow('First error') + + expect(task1Settled).toBe(true) + }) +}) diff --git a/packages/core/src/utils/async.ts b/packages/core/src/utils/async.ts new file mode 100644 index 00000000..20d1ebba --- /dev/null +++ b/packages/core/src/utils/async.ts @@ -0,0 +1,42 @@ +/** + * Maps an array of items with an async mapping function subject to a concurrency limit. + * Results are returned in the same order as the input items array. + */ +export async function mapConcurrent( + items: T[], + limit: number, + fn: (item: T, index: number) => Promise, +): Promise { + if (items.length === 0) { + return [] + } + + const concurrency = Math.max(1, Math.min(limit, items.length)) + const results: TResult[] = new Array(items.length) + let nextIndex = 0 + let firstError: unknown = null + let hasError = false + + const workers = Array.from({ length: concurrency }, async () => { + while (!hasError && nextIndex < items.length) { + const idx = nextIndex++ + try { + results[idx] = await fn(items[idx], idx) + } catch (err) { + if (!hasError) { + hasError = true + firstError = err + } + break + } + } + }) + + await Promise.all(workers) + + if (hasError) { + throw firstError + } + + return results +} diff --git a/packages/transcode/src/activities/transcode.test.ts b/packages/transcode/src/activities/transcode.test.ts index dc2a7171..1eeb5bf7 100644 --- a/packages/transcode/src/activities/transcode.test.ts +++ b/packages/transcode/src/activities/transcode.test.ts @@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg' import { transcodeService } from '@shumai/core/src/transcode/transcode' import * as child_process from 'child_process' +import * as fs from 'fs' vi.mock('child_process', () => ({ execFile: vi.fn(), @@ -20,6 +21,7 @@ import { updateAssetMediaActivity, downloadMediaToTmpActivity, transcodeImageActivity, + extractPosterActivity, generateSpriteActivity, generatePdfProxyActivity, transcodeVideoChunkActivity, @@ -35,6 +37,7 @@ vi.mock('@shumai/core/src/s3/s3', () => ({ presign: vi.fn(), downloadToFile: vi.fn(), deleteObject: vi.fn(), + resolveInput: vi.fn().mockImplementation(async (_bucket, key) => `https://mock-url/${key}`), }, })) @@ -848,6 +851,147 @@ describe('Transcode Activities', () => { expect(res.chunkKey).toMatch(/^files\/asset-abc\/tmp-embedding-chunks\/chunk-10-25-.*\.mp4$/) }) + it('should transcode video chunk using assetKey directly via resolveInput', async () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ;(child_process.execFile as any).mockImplementation( + ( + file: string, + args: string[], + cb: (err: Error | null, result: { stdout: string; stderr: string }) => void, + ) => { + cb(null, { stdout: '', stderr: '' }) + }, + ) + vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-r2.com/video.mp4') + + const res = await transcodeVideoChunkActivity({ + assetId: 'asset-abc', + assetKey: 'video.mp4', + startTime: 10, + endTime: 25, + }) + + expect(s3Service.resolveInput).toHaveBeenCalledWith('shumai', 'video.mp4') + expect(child_process.execFile).toHaveBeenCalledWith( + 'ffmpeg', + expect.arrayContaining([ + '-ss', + '10', + '-i', + 'https://mock-r2.com/video.mp4', + '-reconnect', + '1', + ]), + expect.any(Function), + ) + expect(res.chunkKey).toMatch(/^files\/asset-abc\/tmp-embedding-chunks\/chunk-10-25-.*\.mp4$/) + }) + + it('should throw non-retryable ApplicationFailure when neither filePath nor assetKey is provided', async () => { + expect.assertions(2) + try { + await transcodeVideoChunkActivity({ + assetId: 'asset-abc', + startTime: 0, + endTime: 10, + }) + } catch (err: unknown) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect((err as any).nonRetryable).toBe(true) + expect((err as Error).message).toContain( + 'Neither filePath nor assetKey was provided for video chunk transcoding', + ) + } + }) + + it('should throw retryable ApplicationFailure when ffmpeg fails', async () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ;(child_process.execFile as any).mockImplementation( + ( + _file: string, + _args: string[], + cb: (err: Error | null, result: { stdout: string; stderr: string }) => void, + ) => { + cb(new Error('ffmpeg segmentation fault'), { stdout: '', stderr: '' }) + }, + ) + + expect.assertions(2) + try { + await transcodeVideoChunkActivity({ + assetId: 'asset-abc', + filePath: '/tmp/test.mp4', + startTime: 0, + endTime: 10, + }) + } catch (err: unknown) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect((err as any).nonRetryable).toBe(false) + expect((err as Error).message).toContain('Failed to transcode video chunk') + } + }) + + it('should return existing poster if already present in S3', async () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.mocked(s3Service.headObject).mockResolvedValue({} as any) + + const res = await extractPosterActivity({ + assetKey: 'video.mp4', + posterSpec: { key: 'poster.webp' }, + }) + + expect(res.poster.key).toBe('poster.webp') + expect(child_process.execFile).not.toHaveBeenCalled() + }) + + it('should extract poster upfront at t=0 and upload to S3', async () => { + vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found')) + vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-r2.com/video.mp4') + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ;(child_process.execFile as any).mockImplementation( + ( + file: string, + args: string[], + cb: (err: Error | null, result: { stdout: string; stderr: string }) => void, + ) => { + if (file === 'ffmpeg') { + const outPath = args[args.length - 1] + fs.writeFileSync(outPath, 'fake-poster-bytes') + } + cb(null, { stdout: '', stderr: '' }) + }, + ) + + const res = await extractPosterActivity({ + assetKey: 'video.mp4', + posterSpec: { key: 'files/asset-1/poster.webp' }, + }) + + expect(res.poster.key).toBe('files/asset-1/poster.webp') + expect(s3Service.resolveInput).toHaveBeenCalledWith('shumai', 'video.mp4') + expect(child_process.execFile).toHaveBeenCalledWith( + 'ffmpeg', + expect.arrayContaining([ + '-ss', + '0', + '-i', + 'https://mock-r2.com/video.mp4', + '-vframes', + '1', + '-c:v', + 'libwebp', + ]), + expect.any(Function), + ) + expect(s3Service.putObject).toHaveBeenCalledWith( + 'shumai', + 'files/asset-1/poster.webp', + expect.any(Buffer), + expect.any(Number), + 'image/webp', + ) + }) + it('should delete S3 object successfully', async () => { await deleteS3ObjectActivity({ key: 'files/test-key.mp4' }) expect(s3Service.deleteObject).toHaveBeenCalledWith('shumai', 'files/test-key.mp4') diff --git a/packages/transcode/src/activities/transcode.ts b/packages/transcode/src/activities/transcode.ts index 6fb23ed3..335b9942 100644 --- a/packages/transcode/src/activities/transcode.ts +++ b/packages/transcode/src/activities/transcode.ts @@ -712,6 +712,81 @@ export async function takeScreenshotsActivity(params: { } } +export interface ExtractPosterActivityParams { + assetKey: string + posterSpec: PrismaJson.PosterInfo +} + +export async function extractPosterActivity( + params: ExtractPosterActivityParams, +): Promise<{ poster: PrismaJson.PosterInfo }> { + const bucket = process.env.S3_BUCKET || 'shumai' + try { + await s3Service.headObject(bucket, params.posterSpec.key) + return { poster: params.posterSpec } + } catch { + // Not found, proceed to extract + } + + const tmpDir = transcodeService.createTempDir('poster-') + const posterFile = path.join(tmpDir, 'poster.webp') + + try { + const inputSource = await s3Service.resolveInput(bucket, params.assetKey) + const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://') + + const args = [ + ...(isRemote + ? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5'] + : []), + '-ss', + '0', + '-i', + inputSource, + '-vframes', + '1', + '-vf', + 'scale=-2:300:force_original_aspect_ratio=decrease', + '-c:v', + 'libwebp', + '-q:v', + '75', + posterFile, + ] + await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args]) + + const posterBuffer = fs.readFileSync(posterFile) + await s3Service.putObject( + bucket, + params.posterSpec.key, + posterBuffer, + posterBuffer.length, + 'image/webp', + ) + + return { poster: params.posterSpec } + } catch (err) { + const { code, message } = getErrorDetails(err) + const lowerMsg = message.toLowerCase() + if ( + code === 'ENOENT' || + lowerMsg.includes('enoent') || + lowerMsg.includes('nosuchkey') || + lowerMsg.includes('ffmpeg') || + lowerMsg.includes('sharp') + ) { + throw ApplicationFailure.create({ + message: `Poster extraction failed: ${message}`, + nonRetryable: true, + cause: err instanceof Error ? err : undefined, + }) + } + throw err + } finally { + transcodeService.removeDir(tmpDir) + } +} + export async function overlayAnnotationsActivity(params: { assetKey: string assetId: string @@ -920,7 +995,8 @@ export async function createAutofillTaskIfEnabledActivity( export interface TranscodeVideoChunkParams { assetId: string - filePath: string + assetKey?: string + filePath?: string startTime: number endTime: number } @@ -928,17 +1004,40 @@ export interface TranscodeVideoChunkParams { export async function transcodeVideoChunkActivity( params: TranscodeVideoChunkParams, ): Promise<{ chunkKey: string }> { - const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}.mp4`) + if (!params.filePath && !params.assetKey) { + throw ApplicationFailure.create({ + message: 'Neither filePath nor assetKey was provided for video chunk transcoding', + nonRetryable: true, + }) + } + + const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}-${ulid()}.mp4`) try { + const bucket = process.env.S3_BUCKET || 'shumai' + const inputSource = + params.filePath || + (params.assetKey ? await s3Service.resolveInput(bucket, params.assetKey) : '') + if (!inputSource) { + throw ApplicationFailure.create({ + message: 'Neither filePath nor assetKey was provided for video chunk transcoding', + nonRetryable: true, + }) + } + const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://') + // Slice video segment using ffmpeg, force 1fps and remove audio for gemini-embedding-2 optimization + // Note: -ss placed before -i for fast input seeking via demuxer Range requests await execFileAsync('ffmpeg', [ '-y', '-loglevel', 'warning', - '-i', - params.filePath, + ...(isRemote + ? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5'] + : []), '-ss', params.startTime.toString(), + '-i', + inputSource, '-t', (params.endTime - params.startTime).toString(), '-vf', @@ -956,13 +1055,15 @@ export async function transcodeVideoChunkActivity( const chunkData = fs.readFileSync(chunkTmp) // Upload to S3 - const bucket = process.env.S3_BUCKET || 'shumai' const key = `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}-${ulid()}.mp4` await s3Service.putObject(bucket, key, chunkData, chunkData.length, 'video/mp4') return { chunkKey: key } } catch (err) { + if (err instanceof ApplicationFailure) { + throw err + } throw ApplicationFailure.create({ message: `Failed to transcode video chunk for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`, nonRetryable: false, diff --git a/packages/transcode/src/workflows/transcode-video.test.ts b/packages/transcode/src/workflows/transcode-video.test.ts index 237c858d..423f5d1c 100644 --- a/packages/transcode/src/workflows/transcode-video.test.ts +++ b/packages/transcode/src/workflows/transcode-video.test.ts @@ -44,6 +44,9 @@ describe('transcodeVideoWorkflow', () => { createAutofillTaskIfEnabledActivity: Object.assign(vi.fn(), { _activityName: 'createAutofillTaskIfEnabledActivity', }), + extractPosterActivity: Object.assign(vi.fn(), { + _activityName: 'extractPosterActivity', + }), } beforeEach(() => { @@ -66,6 +69,9 @@ describe('transcodeVideoWorkflow', () => { filePath: '/tmp/video.mp4', tmpDir: '/tmp', }) + mockActivities.extractPosterActivity.mockResolvedValue({ + poster: { key: 'files/asset-1/poster.webp', width: 1920, height: 1080 }, + }) }) it('should process video transcode successfully', async () => { @@ -318,4 +324,74 @@ describe('transcodeVideoWorkflow', () => { status: WorkflowTaskStatus.completed, }) }) + + it('should extract poster upfront when spec.poster is true', async () => { + const task: WorkflowTask = { + id: 'task-poster', + assetId: 'asset-poster', + type: WorkflowTaskType.transcode_video, + status: WorkflowTaskStatus.pending, + sessionId: null, + output: null, + payload: { + projectId: 'proj-1', + transcode: { + poster: true, + videoStrategy: 'best_match', + }, + }, + createdAt: new Date(), + updatedAt: new Date(), + heartbeat: null, + teamId: 'team-1', + projectId: 'proj-1', + uid: 'task-uid-poster', + model: null, + inputTokens: 0, + outputTokens: 0, + } + + mockActivities.getAssetActivity.mockResolvedValue({ + id: 'asset-poster', + storageKey: { key: 'files/asset-poster/video.mp4' }, + mediaType: 'video/mp4', + }) + + mockActivities.getMediaInfoActivity.mockResolvedValue({ + proxyType: 'video', + metadata: { + originalWidth: 1920, + originalHeight: 1080, + duration: 10, + frameRate: 30, + totalFrames: 300, + startTimecode: '00:00:00:00', + bitRate: 1000, + hasAudio: false, + format: {}, + }, + videoTranscodes: [], + imageTranscodes: [], + }) + + mockActivities.extractPosterActivity.mockResolvedValue({ + poster: { key: 'files/asset-poster/poster.webp', width: 1920, height: 1080 }, + }) + + await transcodeVideoWorkflow(task) + + expect(mockActivities.extractPosterActivity).toHaveBeenCalledWith({ + assetKey: 'files/asset-poster/video.mp4', + posterSpec: { + key: 'files/asset-poster/poster.webp', + }, + }) + + expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith({ + assetId: 'asset-poster', + mediaInfo: expect.objectContaining({ + poster: { key: 'files/asset-poster/poster.webp', width: 1920, height: 1080 }, + }), + }) + }) }) diff --git a/packages/transcode/src/workflows/transcode-video.ts b/packages/transcode/src/workflows/transcode-video.ts index d96bf0c9..52c002dd 100644 --- a/packages/transcode/src/workflows/transcode-video.ts +++ b/packages/transcode/src/workflows/transcode-video.ts @@ -23,6 +23,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise transcodeVideoActivity, transcodeAudioActivity, transcodeImageActivity, + extractPosterActivity, generateSpriteActivity, updateAssetMediaActivity, downloadMediaToTmpActivity, @@ -58,6 +59,23 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise codec: '', } + if (spec.poster) { + const lastSlashIndex = key.lastIndexOf('/') + const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex) + const posterSpec: PrismaJson.PosterInfo = { + key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp', + } + const posterResult = await executeActivity(workerQueue, extractPosterActivity, { + assetKey: key, + posterSpec, + }) + mediaInfo.poster = posterResult.poster + await executeActivity(workerQueue, updateAssetMediaActivity, { + assetId: asset.id, + mediaInfo, + }) + } + const metadata = mediaInfo.metadata if (mediaInfo.proxyType === 'video' && metadata) { @@ -115,7 +133,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise mediaInfo.thumbnail = thumbTranscode } - if (spec.sprite || spec.poster) { + if (spec.sprite || (spec.poster && !mediaInfo.poster)) { const lastSlashIndex = key.lastIndexOf('/') const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex) @@ -125,7 +143,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise tileX: 10, tileY: 10, } - const posterSpec: PrismaJson.PosterInfo = { + const posterSpec: PrismaJson.PosterInfo = mediaInfo.poster || { key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp', } @@ -136,8 +154,12 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise posterSpec, mediaInfo, }) - mediaInfo.sprite = spriteResult.sprite - mediaInfo.poster = spriteResult.poster + if (spec.sprite) { + mediaInfo.sprite = spriteResult.sprite + } + if (!mediaInfo.poster) { + mediaInfo.poster = spriteResult.poster + } } await executeActivity(workerQueue, updateAssetMediaActivity, {