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
This commit is contained in:
Yiling-J
2026-09-08 10:17:15 +08:00
committed by GitHub
parent f62df9555a
commit b35c824a27
16 changed files with 675 additions and 151 deletions
@@ -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')
+106 -5
View File
@@ -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,