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,
@@ -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 },
}),
})
})
})
@@ -23,6 +23,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
transcodeVideoActivity,
transcodeAudioActivity,
transcodeImageActivity,
extractPosterActivity,
generateSpriteActivity,
updateAssetMediaActivity,
downloadMediaToTmpActivity,
@@ -58,6 +59,23 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
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<void>
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<void>
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<void>
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, {