mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 04:14:30 +00:00
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:
@@ -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', () => {
|
||||
|
||||
@@ -118,6 +118,7 @@ export interface S3Service {
|
||||
request: S3SignRequest,
|
||||
) => Promise<{ url: string }>
|
||||
abortMultipartUpload: (bucket: string, key: string, uploadId: string) => Promise<void>
|
||||
resolveInput: (bucket: string, key: string) => Promise<string>
|
||||
}
|
||||
|
||||
export class S3StorageService implements S3Service {
|
||||
@@ -459,6 +460,10 @@ export class S3StorageService implements S3Service {
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async resolveInput(bucket: string, key: string): Promise<string> {
|
||||
return this.presign(bucket, key, 'GET')
|
||||
}
|
||||
}
|
||||
|
||||
export class LocalStorageService implements S3Service {
|
||||
@@ -717,6 +722,14 @@ export class LocalStorageService implements S3Service {
|
||||
): Promise<void> {
|
||||
await this.deleteObject(bucket, key)
|
||||
}
|
||||
|
||||
async resolveInput(bucket: string, key: string): Promise<string> {
|
||||
const filePath = this.getFilePath(bucket, key)
|
||||
if (fs.existsSync(filePath)) {
|
||||
return filePath
|
||||
}
|
||||
return this.presign(bucket, key, 'GET')
|
||||
}
|
||||
}
|
||||
|
||||
export function getStorageBackend(): 's3' | 'local' {
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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<Array<{ key: string; timestamp: number }>> {
|
||||
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 {
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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<T, TResult>(
|
||||
items: T[],
|
||||
limit: number,
|
||||
fn: (item: T, index: number) => Promise<TResult>,
|
||||
): Promise<TResult[]> {
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user