From 59742dde78132e031dd4c0053372189efc0176aa Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Fri, 25 Sep 2026 15:06:15 +0800 Subject: [PATCH] feat(transcode): optimize video sprite generation with seek pool and compositing (#427) * feat(transcode): optimize video sprite generation with seek pool and compositing * fix(transcode): handle abort signal during and after sharp compositing --- CHANGELOG.md | 2 + packages/core/src/transcode/transcode.test.ts | 185 ++++++++++++++- packages/core/src/transcode/transcode.ts | 215 ++++++++++++++++++ 3 files changed, 398 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e087a7c..ab72e9f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Changed +- **transcode**: Optimize video sprite generation for large and long videos using a concurrent fast-seek pool and image compositing, avoiding full-video decoding while preserving instant single-pass generation for short clips + ## [0.4.8] - 2026-09-24 ### Added diff --git a/packages/core/src/transcode/transcode.test.ts b/packages/core/src/transcode/transcode.test.ts index 59598ed0..259bb297 100644 --- a/packages/core/src/transcode/transcode.test.ts +++ b/packages/core/src/transcode/transcode.test.ts @@ -2222,7 +2222,7 @@ describe('TranscodeService', () => { expect(executedArgs).toContain('smpte2084') }) - it('generateSprite uses split=2 filterComplex for HDR inputs', async () => { + it('generateSprite uses split=2 filterComplex for small and short HDR inputs (single-pass)', async () => { let executedArgs: string[] = [] ;( child_process.execFile as unknown as { @@ -2244,9 +2244,11 @@ describe('TranscodeService', () => { return {} }) + const inputPath = path.join(tempDir, 'short.mp4') + fs.writeFileSync(inputPath, 'dummy short video content') const spritePath = path.join(tempDir, 'sprite.webp') const posterPath = path.join(tempDir, 'poster.webp') - await transcodeService.generateSprite('input.mp4', spritePath, posterPath, 100, undefined, { + await transcodeService.generateSprite(inputPath, spritePath, posterPath, 20, undefined, { isHdr: true, hdrType: 'pq', colorTransfer: 'smpte2084', @@ -2260,7 +2262,7 @@ describe('TranscodeService', () => { expect(filterStr).toContain('[v_thumb]scale=') }) - it('generateSprite uses split=2 filterComplex for SDR inputs', async () => { + it('generateSprite uses split=2 filterComplex for small and short SDR inputs (single-pass)', async () => { let executedArgs: string[] = [] ;( child_process.execFile as unknown as { @@ -2278,9 +2280,11 @@ describe('TranscodeService', () => { return {} }) + const inputPath = path.join(tempDir, 'short.mp4') + fs.writeFileSync(inputPath, 'dummy short video content') const spritePath = path.join(tempDir, 'sprite.webp') const posterPath = path.join(tempDir, 'poster.webp') - await transcodeService.generateSprite('input.mp4', spritePath, posterPath, 100) + await transcodeService.generateSprite(inputPath, spritePath, posterPath, 20) const filterIdx = executedArgs.indexOf('-filter_complex') expect(filterIdx).toBeGreaterThan(-1) @@ -2289,5 +2293,178 @@ describe('TranscodeService', () => { expect(filterStr).toContain('[v_sprite]fps=') expect(filterStr).toContain('[v_thumb]scale=') }) + + it('generateSprite uses seek-pool for long inputs (>30s) and generates sprite and poster', async () => { + const dummyWebp = await sharp({ + create: { width: 300, height: 168, channels: 3, background: { r: 50, g: 50, b: 50 } }, + }) + .webp() + .toBuffer() + + const executedCommands: string[][] = [] + ;( + child_process.execFile as unknown as { + mockImplementation: ( + fn: ( + file: string, + args: string[], + cb: (err: Error | null, res: { stdout: string; stderr: string }) => void, + ) => unknown, + ) => void + } + ).mockImplementation((_file, args, cb) => { + if (args.includes('-filters')) { + cb(null, { stdout: ' ... zscale ... \n ... tonemap ... ', stderr: '' }) + return {} + } + executedCommands.push(args) + const outPath = args[args.length - 1] + if (outPath && outPath.endsWith('.webp')) { + fs.writeFileSync(outPath, dummyWebp) + } + cb(null, { stdout: '', stderr: '' }) + return {} + }) + + const inputPath = path.join(tempDir, 'long.mp4') + fs.writeFileSync(inputPath, 'dummy long video content') + const spritePath = path.join(tempDir, 'sprite_pool.webp') + const posterPath = path.join(tempDir, 'poster_pool.webp') + + await transcodeService.generateSprite(inputPath, spritePath, posterPath, 120, undefined, { + isHdr: true, + hdrType: 'pq', + colorTransfer: 'smpte2084', + }) + + // Poster was extracted at t=0 + const posterCmd = executedCommands.find((cmd) => cmd[cmd.length - 1] === posterPath) + expect(posterCmd).toBeDefined() + expect(posterCmd).toContain('-ss') + expect(posterCmd).toContain('0') + expect(fs.existsSync(posterPath)).toBe(true) + + // 100 seek calls were performed for frames + const frameCmds = executedCommands.filter((cmd) => cmd[cmd.length - 1].includes('frame_')) + expect(frameCmds.length).toBe(100) + // Check pre-scaling before tonemap filter + expect(frameCmds[0].some((arg) => arg.includes('scale=300:-2'))).toBe(true) + + // Sprite file was generated by Sharp + expect(fs.existsSync(spritePath)).toBe(true) + expect( + vi.mocked(sharp).mock.calls.some((call) => { + const create = (call[0] as { create?: { width: number; height: number } })?.create + return create?.width === 8000 && create?.height === 6000 + }), + ).toBe(true) + }) + + it('generateSprite seek-pool resiliently handles frame failure and abort signal', async () => { + const dummyWebp = await sharp({ + create: { width: 300, height: 168, channels: 3, background: { r: 10, g: 20, b: 30 } }, + }) + .webp() + .toBuffer() + + ;( + child_process.execFile as unknown as { + mockImplementation: ( + fn: ( + file: string, + args: string[], + cb: (err: Error | null, res: { stdout: string; stderr: string }) => void, + ) => unknown, + ) => void + } + ).mockImplementation((_file, args, cb) => { + const outPath = args[args.length - 1] + // Simulate failure on frame 50 + if (outPath && outPath.includes('frame_050')) { + cb(new Error('Simulated frame decode error'), { stdout: '', stderr: 'error' }) + return {} + } + if (outPath && outPath.endsWith('.webp')) { + fs.writeFileSync(outPath, dummyWebp) + } + cb(null, { stdout: '', stderr: '' }) + return {} + }) + + const inputPath = path.join(tempDir, 'long_fail.mp4') + fs.writeFileSync(inputPath, 'dummy video') + const spritePath = path.join(tempDir, 'sprite_resilient.webp') + const posterPath = path.join(tempDir, 'poster_resilient.webp') + + // Should not throw even with frame_050 failure + await transcodeService.generateSprite(inputPath, spritePath, posterPath, 60) + expect(fs.existsSync(spritePath)).toBe(true) + + // Test abort signal + const controller = new AbortController() + controller.abort() + await expect( + transcodeService.generateSprite(inputPath, spritePath, posterPath, 60, controller.signal), + ).rejects.toThrow('Sprite generation cancelled') + }) + + it('generateSprite rejects with cancellation error if aborted while Sharp toFile is pending', async () => { + const dummyWebp = await sharp({ + create: { width: 300, height: 168, channels: 3, background: { r: 10, g: 20, b: 30 } }, + }) + .webp() + .toBuffer() + + const controller = new AbortController() + + ;( + child_process.execFile as unknown as { + mockImplementation: ( + fn: ( + file: string, + args: string[], + optOrCb: unknown, + maybeCb?: (err: Error | null, res: { stdout: string; stderr: string }) => void, + ) => unknown, + ) => void + } + ).mockImplementation((_file, args, optOrCb, maybeCb) => { + const cb = (typeof optOrCb === 'function' ? optOrCb : maybeCb) as ( + err: Error | null, + res: { stdout: string; stderr: string }, + ) => void + const outPath = args[args.length - 1] + if (outPath && outPath.endsWith('.webp')) { + fs.writeFileSync(outPath, dummyWebp) + } + cb(null, { stdout: '', stderr: '' }) + return {} + }) + + // Hook into Sharp toFile: trigger abort while toFile is pending + const mockSharpInstance = vi.mocked(sharp()) + mockSharpInstance.toFile.mockImplementationOnce(async (filePath: string) => { + controller.abort() + fs.writeFileSync(filePath, 'fake-webp-data') + return { + format: 'webp', + size: 14, + width: 3000, + height: 1680, + channels: 4, + premultiplied: false, + hasAlpha: false, + } + }) + + const inputPath = path.join(tempDir, 'cancel_during_sharp.mp4') + fs.writeFileSync(inputPath, 'dummy video') + const spritePath = path.join(tempDir, 'sprite_cancel.webp') + const posterPath = path.join(tempDir, 'poster_cancel.webp') + + await expect( + transcodeService.generateSprite(inputPath, spritePath, posterPath, 60, controller.signal), + ).rejects.toThrow('Sprite generation cancelled') + }) }) }) diff --git a/packages/core/src/transcode/transcode.ts b/packages/core/src/transcode/transcode.ts index 3a20d6d5..038bce62 100644 --- a/packages/core/src/transcode/transcode.ts +++ b/packages/core/src/transcode/transcode.ts @@ -957,6 +957,44 @@ export class TranscodeService { duration: number, signal?: AbortSignal, hdrOptions?: { isHdr?: boolean; hdrType?: HdrType; colorTransfer?: string }, + ): Promise { + let fileSize = Infinity + try { + const stats = await fs.promises.stat(inputFile) + fileSize = stats.size + } catch { + // If stat fails (e.g. mocked in unit tests), fileSize remains Infinity + } + + const isSmallAndShort = fileSize <= 50 * 1024 * 1024 && duration <= 30 + if (isSmallAndShort) { + await this.generateSpriteSinglePass( + inputFile, + outputSprite, + outputPoster, + duration, + signal, + hdrOptions, + ) + } else { + await this.generateSpriteSeekPool( + inputFile, + outputSprite, + outputPoster, + duration, + signal, + hdrOptions, + ) + } + } + + private async generateSpriteSinglePass( + inputFile: string, + outputSprite: string, + outputPoster: string, + duration: number, + signal?: AbortSignal, + hdrOptions?: { isHdr?: boolean; hdrType?: HdrType; colorTransfer?: string }, ): Promise { const spriteFps = 100 / duration let filterComplex: string @@ -1006,6 +1044,183 @@ export class TranscodeService { } } + private async generateSpriteSeekPool( + inputFile: string, + outputSprite: string, + outputPoster: string, + duration: number, + signal?: AbortSignal, + hdrOptions?: { isHdr?: boolean; hdrType?: HdrType; colorTransfer?: string }, + ): Promise { + if (signal?.aborted) { + throw new Error('Sprite generation cancelled') + } + + // 1. Generate poster at t=0 matching the existing poster filter dimensions + let vfPoster = 'scale=-2:300:force_original_aspect_ratio=decrease' + let tonemapFilterChain = '' + if (hdrOptions?.isHdr) { + const availableFilters = await this.getAvailableFilters() + tonemapFilterChain = buildSdrToneMapFilterChain({ + hdrType: hdrOptions.hdrType, + colorTransfer: hdrOptions.colorTransfer, + availableFilters, + }) + vfPoster = `${tonemapFilterChain},scale=-2:300:force_original_aspect_ratio=decrease` + } + + const posterArgs = [ + '-ss', + '0', + '-i', + inputFile, + '-vframes', + '1', + '-vf', + vfPoster, + '-c:v', + 'libwebp', + '-q:v', + '75', + outputPoster, + ] + if (signal) { + await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...posterArgs], { signal }) + } else { + await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...posterArgs]) + } + + // 2. Extract 100 frames across duration using 4-worker concurrency pool + const tmpDir = this.createTempDir('sprite-pool-') + try { + const numFrames = 100 + const tileX = 10 + const tileY = 10 + const timestamps = Array.from({ length: numFrames }, (_, i) => { + const rawTs = (i / (numFrames - 1)) * duration + return Math.min(rawTs, Math.max(0, duration - 0.1)) + }) + + // For sprite tiles: scale to width 300 first, then apply HDR tonemapping if needed + const vfSprite = tonemapFilterChain ? `scale=300:-2,${tonemapFilterChain}` : 'scale=300:-2' + + const concurrency = 4 + const frameFiles: string[] = new Array(numFrames).fill('') + let nextIdx = 0 + + const worker = async () => { + while (true) { + if (signal?.aborted) { + throw new Error('Sprite generation cancelled') + } + const idx = nextIdx++ + if (idx >= timestamps.length) break + + const ts = timestamps[idx] + const framePath = path.join(tmpDir, `frame_${idx.toString().padStart(3, '0')}.webp`) + const args = [ + '-ss', + ts.toFixed(3), + '-i', + inputFile, + '-vframes', + '1', + '-vf', + vfSprite, + '-c:v', + 'libwebp', + '-q:v', + '75', + framePath, + ] + + try { + if (signal) { + await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], { signal }) + } else { + await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args]) + } + if (fs.existsSync(framePath) && fs.statSync(framePath).size > 0) { + frameFiles[idx] = framePath + } + } catch (err) { + if (signal?.aborted) throw err + // If frame extraction fails, keep empty for resilient fallback + } + } + } + + await Promise.all(Array.from({ length: concurrency }, () => worker())) + + // Resilient fallback: ensure all 100 frames exist by filling any failed frame with adjacent frame + let lastValid = frameFiles.find((f) => f && fs.existsSync(f)) + if (!lastValid) { + throw new Error(`Failed to extract any frames from ${inputFile}`) + } + for (let i = 0; i < numFrames; i++) { + if (!frameFiles[i] || !fs.existsSync(frameFiles[i])) { + const fallbackFile = path.join(tmpDir, `frame_${i.toString().padStart(3, '0')}.webp`) + fs.copyFileSync(lastValid, fallbackFile) + frameFiles[i] = fallbackFile + } else { + lastValid = frameFiles[i] + } + } + + // 3. Composite 100 tiles into 10x10 sprite sheet with Sharp + if (signal?.aborted) { + throw new Error('Sprite generation cancelled') + } + + const firstMeta = await sharp(frameFiles[0]).metadata() + const frameW = firstMeta.width || 300 + const frameH = firstMeta.height || 168 + + const composites = frameFiles.map((file, i) => ({ + input: file, + left: (i % tileX) * frameW, + top: Math.floor(i / tileX) * frameH, + })) + + const toFilePromise = sharp({ + create: { + width: frameW * tileX, + height: frameH * tileY, + channels: 4, + background: { r: 0, g: 0, b: 0, alpha: 1 }, + }, + }) + .composite(composites) + .webp({ quality: 75 }) + .toFile(outputSprite) + + if (signal) { + await Promise.race([ + toFilePromise, + new Promise((_, reject) => { + if (signal.aborted) { + reject(new Error('Sprite generation cancelled')) + return + } + signal.addEventListener( + 'abort', + () => reject(new Error('Sprite generation cancelled')), + { once: true }, + ) + }), + ]) + } else { + await toFilePromise + } + + if (signal?.aborted) { + throw new Error('Sprite generation cancelled') + } + } finally { + this.removeDir(tmpDir) + } + } + async generatePdfSprite( inputFile: string, outputSprite: string,