feat(transcode): smart poster frame selection and decoupled generation (#428)

* feat(transcode): smart poster frame selection and decoupled generation

* fix(transcode): detect MPEG-TS extension from URL pathname for signed remote sources
This commit is contained in:
Yiling-J
2026-09-25 16:37:16 +08:00
committed by GitHub
parent 59742dde78
commit 941bf0fd1b
5 changed files with 361 additions and 186 deletions
+1
View File
@@ -12,6 +12,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Changed
- **transcode**: Improve video poster selection using intelligent scene detection and color variance filtering to automatically skip black frames, fade-ins, and blank intros in favor of representative video content
- **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
+229 -19
View File
@@ -2222,8 +2222,8 @@ describe('TranscodeService', () => {
expect(executedArgs).toContain('smpte2084')
})
it('generateSprite uses split=2 filterComplex for small and short HDR inputs (single-pass)', async () => {
let executedArgs: string[] = []
it('generateSprite extracts smart poster and generates sprite grid for small and short HDR inputs (single-pass)', async () => {
const executedCommands: string[][] = []
;(
child_process.execFile as unknown as {
mockImplementation: (
@@ -2239,7 +2239,7 @@ describe('TranscodeService', () => {
cb(null, { stdout: ' ... zscale ... \n ... tonemap ... ', stderr: '' })
return {}
}
executedArgs = args
executedCommands.push(args)
cb(null, { stdout: '', stderr: '' })
return {}
})
@@ -2254,16 +2254,29 @@ describe('TranscodeService', () => {
colorTransfer: 'smpte2084',
})
const filterIdx = executedArgs.indexOf('-filter_complex')
// Poster command
const posterCmd = executedCommands.find((cmd) => cmd[cmd.length - 1] === posterPath)
expect(posterCmd).toBeDefined()
expect(posterCmd).toContain('-skip_frame')
expect(posterCmd).toContain('nointra')
const posterVf = posterCmd![posterCmd!.indexOf('-vf') + 1]
expect(posterVf).toContain('thumbnail=12')
expect(posterVf).toContain('reverse')
expect(posterVf).toContain('scale=-2:300')
// Sprite command
const spriteCmd = executedCommands.find((cmd) => cmd[cmd.length - 1] === spritePath)
expect(spriteCmd).toBeDefined()
const filterIdx = spriteCmd!.indexOf('-filter_complex')
expect(filterIdx).toBeGreaterThan(-1)
const filterStr = executedArgs[filterIdx + 1]
expect(filterStr).toContain('split=2[v_sprite][v_thumb]')
expect(filterStr).toContain('[v_sprite]fps=')
expect(filterStr).toContain('[v_thumb]scale=')
const filterStr = spriteCmd![filterIdx + 1]
expect(filterStr).toContain('fps=')
expect(filterStr).toContain('scale=w=300:h=-2')
expect(filterStr).toContain('tile=10x10[sprite_out]')
})
it('generateSprite uses split=2 filterComplex for small and short SDR inputs (single-pass)', async () => {
let executedArgs: string[] = []
it('generateSprite extracts smart poster and generates sprite grid for small and short SDR inputs (single-pass)', async () => {
const executedCommands: string[][] = []
;(
child_process.execFile as unknown as {
mockImplementation: (
@@ -2275,7 +2288,7 @@ describe('TranscodeService', () => {
) => void
}
).mockImplementation((_file, args, cb) => {
executedArgs = args
executedCommands.push(args)
cb(null, { stdout: '', stderr: '' })
return {}
})
@@ -2286,12 +2299,23 @@ describe('TranscodeService', () => {
const posterPath = path.join(tempDir, 'poster.webp')
await transcodeService.generateSprite(inputPath, spritePath, posterPath, 20)
const filterIdx = executedArgs.indexOf('-filter_complex')
// Poster command
const posterCmd = executedCommands.find((cmd) => cmd[cmd.length - 1] === posterPath)
expect(posterCmd).toBeDefined()
expect(posterCmd).toContain('-skip_frame')
expect(posterCmd).toContain('nointra')
const posterVf = posterCmd![posterCmd!.indexOf('-vf') + 1]
expect(posterVf).toContain('thumbnail=12')
expect(posterVf).toContain('reverse')
// Sprite command
const spriteCmd = executedCommands.find((cmd) => cmd[cmd.length - 1] === spritePath)
expect(spriteCmd).toBeDefined()
const filterIdx = spriteCmd!.indexOf('-filter_complex')
expect(filterIdx).toBeGreaterThan(-1)
const filterStr = executedArgs[filterIdx + 1]
expect(filterStr).toContain('[0:v]split=2[v_sprite][v_thumb]')
expect(filterStr).toContain('[v_sprite]fps=')
expect(filterStr).toContain('[v_thumb]scale=')
const filterStr = spriteCmd![filterIdx + 1]
expect(filterStr).toContain('[0:v]fps=')
expect(filterStr).toContain('scale=w=300:h=-2,tile=10x10[sprite_out]')
})
it('generateSprite uses seek-pool for long inputs (>30s) and generates sprite and poster', async () => {
@@ -2337,11 +2361,15 @@ describe('TranscodeService', () => {
colorTransfer: 'smpte2084',
})
// Poster was extracted at t=0
// Poster was extracted with smart poster filter
const posterCmd = executedCommands.find((cmd) => cmd[cmd.length - 1] === posterPath)
expect(posterCmd).toBeDefined()
expect(posterCmd).toContain('-ss')
expect(posterCmd).toContain('0')
expect(posterCmd).toContain('-skip_frame')
expect(posterCmd).toContain('nointra')
const posterVf = posterCmd![posterCmd!.indexOf('-vf') + 1]
expect(posterVf).toContain('thumbnail=12')
expect(posterVf).toContain('reverse')
expect(posterVf).toContain('scale=-2:300')
expect(fs.existsSync(posterPath)).toBe(true)
// 100 seek calls were performed for frames
@@ -2467,4 +2495,186 @@ describe('TranscodeService', () => {
).rejects.toThrow('Sprite generation cancelled')
})
})
describe('generatePoster', () => {
it('generates poster with fast intra skipping and intelligent filter graph', async () => {
let executedArgs: 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) => {
executedArgs = args
cb(null, { stdout: '', stderr: '' })
return {}
})
const inputPath = path.join(tempDir, 'sample.mp4')
const outputPath = path.join(tempDir, 'poster.webp')
await transcodeService.generatePoster(inputPath, outputPath)
expect(executedArgs).toContain('-skip_frame')
expect(executedArgs).toContain('nointra')
expect(executedArgs).toContain('-frames:v')
expect(executedArgs).toContain('1')
expect(executedArgs).toContain('-update')
expect(executedArgs).toContain('1')
expect(executedArgs).toContain('-c:v')
expect(executedArgs).toContain('libwebp')
const vfIndex = executedArgs.indexOf('-vf')
expect(vfIndex).toBeGreaterThan(-1)
const vf = executedArgs[vfIndex + 1]
expect(vf).toContain('fps=12:start_time=0:eof_action=pass:round=down')
expect(vf).toContain('thumbnail=12')
expect(vf).toContain(
'select=gt(scene\\,0.1)-eq(prev_selected_n\\,n)+isnan(prev_selected_n)+gt(n\\,20)',
)
expect(vf).toContain('trim=end_frame=2')
expect(vf).toContain('reverse')
expect(vf).toContain('scale=-2:300:force_original_aspect_ratio=decrease')
})
it('omits -skip_frame nointra for MPEG-TS files (.ts / .m2ts / .mts)', async () => {
let executedArgs: 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) => {
executedArgs = args
cb(null, { stdout: '', stderr: '' })
return {}
})
const inputPath = path.join(tempDir, 'stream.m2ts')
const outputPath = path.join(tempDir, 'poster.webp')
await transcodeService.generatePoster(inputPath, outputPath)
expect(executedArgs).not.toContain('-skip_frame')
expect(executedArgs).not.toContain('nointra')
expect(executedArgs).toContain('-i')
expect(executedArgs).toContain(inputPath)
})
it('omits -skip_frame nointra for signed remote MPEG-TS URLs with query parameters', async () => {
let executedArgs: 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) => {
executedArgs = args
cb(null, { stdout: '', stderr: '' })
return {}
})
const signedUrl =
'https://storage.example.com/videos/stream.ts?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Signature=abcdef123'
const outputPath = path.join(tempDir, 'poster.webp')
await transcodeService.generatePoster(signedUrl, outputPath)
expect(executedArgs).not.toContain('-skip_frame')
expect(executedArgs).not.toContain('nointra')
expect(executedArgs).toContain('-reconnect')
expect(executedArgs).toContain('-i')
expect(executedArgs).toContain(signedUrl)
})
it('adds reconnect options for remote input sources', async () => {
let executedArgs: 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) => {
executedArgs = args
cb(null, { stdout: '', stderr: '' })
return {}
})
const inputUrl = 'https://example.com/video.mp4'
const outputPath = path.join(tempDir, 'poster.webp')
await transcodeService.generatePoster(inputUrl, outputPath)
expect(executedArgs).toContain('-reconnect')
expect(executedArgs).toContain('1')
expect(executedArgs).toContain('-reconnect_streamed')
expect(executedArgs).toContain('-reconnect_delay_max')
})
it('applies HDR tone mapping filter when isHdr is true', async () => {
let executedArgs: 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 {}
}
executedArgs = args
cb(null, { stdout: '', stderr: '' })
return {}
})
const inputPath = path.join(tempDir, 'hdr.mp4')
const outputPath = path.join(tempDir, 'poster.webp')
await transcodeService.generatePoster(inputPath, outputPath, {
isHdr: true,
hdrType: 'pq',
colorTransfer: 'smpte2084',
})
const vfIndex = executedArgs.indexOf('-vf')
expect(vfIndex).toBeGreaterThan(-1)
const vf = executedArgs[vfIndex + 1]
expect(vf).toContain('zscale=tin=smpte2084')
expect(vf).toContain('tonemap=tonemap=hable')
expect(vf).toContain('scale=-2:300')
})
it('rejects with cancellation error if aborted before or during execution', async () => {
const controller = new AbortController()
controller.abort()
const inputPath = path.join(tempDir, 'aborted.mp4')
const outputPath = path.join(tempDir, 'poster.webp')
await expect(
transcodeService.generatePoster(inputPath, outputPath, { signal: controller.signal }),
).rejects.toThrow('Poster generation cancelled')
})
})
})
+91 -56
View File
@@ -89,6 +89,13 @@ export function parseCsvContent(content: string): string[][] {
export type HdrType = 'pq' | 'hlg' | 'dovi_p5' | 'dovi_p8' | 'sdr'
export interface GeneratePosterOptions {
isHdr?: boolean
hdrType?: HdrType
colorTransfer?: string
signal?: AbortSignal
}
export interface MediaMetadata {
originalWidth: number
originalHeight: number
@@ -950,6 +957,77 @@ export class TranscodeService {
await sharpInstance.webp({ quality }).toFile(outputFile)
}
async generatePoster(
inputFile: string,
outputPoster: string,
options: GeneratePosterOptions = {},
): Promise<void> {
const { isHdr, hdrType, colorTransfer, signal } = options
if (signal?.aborted) {
throw new Error('Poster generation cancelled')
}
const isRemote = inputFile.startsWith('http://') || inputFile.startsWith('https://')
let pathname = inputFile
if (isRemote) {
try {
pathname = new URL(inputFile).pathname
} catch {
pathname = inputFile.split('?')[0].split('#')[0]
}
}
const ext = path.extname(pathname).toLowerCase()
const isMpegTs = ext === '.ts' || ext === '.m2ts' || ext === '.mts'
const filters: string[] = [
'fps=12:start_time=0:eof_action=pass:round=down',
'thumbnail=12',
String.raw`select=gt(scene\,0.1)-eq(prev_selected_n\,n)+isnan(prev_selected_n)+gt(n\,20)`,
'trim=end_frame=2',
'reverse',
]
if (isHdr) {
const availableFilters = await this.getAvailableFilters()
const tonemap = buildSdrToneMapFilterChain({
hdrType,
colorTransfer,
availableFilters,
})
filters.push(tonemap)
}
filters.push('scale=-2:300:force_original_aspect_ratio=decrease')
const args = [
...(isRemote
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
: []),
...(isMpegTs ? [] : ['-skip_frame', 'nointra']),
'-i',
inputFile,
'-vf',
filters.join(','),
'-fps_mode',
'vfr',
'-frames:v',
'1',
'-update',
'1',
'-c:v',
'libwebp',
'-q:v',
'75',
outputPoster,
]
if (signal) {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], { signal })
} else {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
}
}
async generateSprite(
inputFile: string,
outputSprite: string,
@@ -958,6 +1036,14 @@ export class TranscodeService {
signal?: AbortSignal,
hdrOptions?: { isHdr?: boolean; hdrType?: HdrType; colorTransfer?: string },
): Promise<void> {
if (signal?.aborted) {
throw new Error('Sprite generation cancelled')
}
// 1. Generate poster first (fast, smart frame selection)
await this.generatePoster(inputFile, outputPoster, { ...hdrOptions, signal })
// 2. Generate sprite
let fileSize = Infinity
try {
const stats = await fs.promises.stat(inputFile)
@@ -968,30 +1054,15 @@ export class TranscodeService {
const isSmallAndShort = fileSize <= 50 * 1024 * 1024 && duration <= 30
if (isSmallAndShort) {
await this.generateSpriteSinglePass(
inputFile,
outputSprite,
outputPoster,
duration,
signal,
hdrOptions,
)
await this.generateSpriteSinglePass(inputFile, outputSprite, duration, signal, hdrOptions)
} else {
await this.generateSpriteSeekPool(
inputFile,
outputSprite,
outputPoster,
duration,
signal,
hdrOptions,
)
await this.generateSpriteSeekPool(inputFile, outputSprite, duration, signal, hdrOptions)
}
}
private async generateSpriteSinglePass(
inputFile: string,
outputSprite: string,
outputPoster: string,
duration: number,
signal?: AbortSignal,
hdrOptions?: { isHdr?: boolean; hdrType?: HdrType; colorTransfer?: string },
@@ -1006,9 +1077,9 @@ export class TranscodeService {
colorTransfer: hdrOptions.colorTransfer,
availableFilters,
})
filterComplex = `[0:v]${tonemap},split=2[v_sprite][v_thumb];[v_sprite]fps=${spriteFps},scale=w=300:h=-2,tile=10x10[sprite_out];[v_thumb]scale=-2:300:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
filterComplex = `[0:v]${tonemap},fps=${spriteFps},scale=w=300:h=-2,tile=10x10[sprite_out]`
} else {
filterComplex = `[0:v]split=2[v_sprite][v_thumb];[v_sprite]fps=${spriteFps},scale=w=300:h=-2,tile=10x10[sprite_out];[v_thumb]scale=-2:300:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
filterComplex = `[0:v]fps=${spriteFps},scale=w=300:h=-2,tile=10x10[sprite_out]`
}
const args = [
@@ -1025,17 +1096,6 @@ export class TranscodeService {
'-q:v',
'75',
outputSprite,
'-map',
'[thumb_out]',
'-c:v',
'libwebp',
'-q:v',
'75',
'-frames:v',
'1',
'-max_muxing_queue_size',
'1024',
outputPoster,
]
if (signal) {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], { signal })
@@ -1047,7 +1107,6 @@ export class TranscodeService {
private async generateSpriteSeekPool(
inputFile: string,
outputSprite: string,
outputPoster: string,
duration: number,
signal?: AbortSignal,
hdrOptions?: { isHdr?: boolean; hdrType?: HdrType; colorTransfer?: string },
@@ -1056,8 +1115,6 @@ export class TranscodeService {
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()
@@ -1066,31 +1123,9 @@ export class TranscodeService {
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
// Extract 100 frames across duration using 4-worker concurrency pool
const tmpDir = this.createTempDir('sprite-pool-')
try {
const numFrames = 100
@@ -63,6 +63,7 @@ vi.mock('@shumai/core/src/transcode/transcode', async (importOriginal) => {
transcodeAudio: vi.fn(),
transcodeImage: vi.fn(),
generateSprite: vi.fn(),
generatePoster: vi.fn(),
generatePdfSprite: vi.fn().mockResolvedValue({
pageCount: 10,
originalWidth: 800,
@@ -1127,22 +1128,12 @@ describe('Transcode Activities', () => {
expect(child_process.execFile).not.toHaveBeenCalled()
})
it('should extract poster upfront at t=0 and upload to S3', async () => {
it('should extract poster upfront 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[], optionsOrCb: unknown, maybeCb?: unknown) => {
const cb = typeof optionsOrCb === 'function' ? optionsOrCb : maybeCb
if (file === 'ffmpeg') {
const outPath = args[args.length - 1]
fs.writeFileSync(outPath, 'fake-poster-bytes')
}
if (typeof cb === 'function') {
cb(null, { stdout: '', stderr: '' })
}
},
)
vi.mocked(transcodeService.generatePoster).mockImplementation(async (_in, posterOut) => {
fs.writeFileSync(posterOut, Buffer.from('fake-poster-bytes'))
})
const res = await extractPosterActivity({
assetKey: 'video.mp4',
@@ -1151,20 +1142,15 @@ describe('Transcode Activities', () => {
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.objectContaining({ signal: undefined }),
expect.any(Function),
expect(transcodeService.generatePoster).toHaveBeenCalledWith(
'https://mock-r2.com/video.mp4',
expect.stringContaining('poster.webp'),
{
isHdr: undefined,
hdrType: undefined,
colorTransfer: undefined,
signal: undefined,
},
)
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
@@ -1178,21 +1164,9 @@ describe('Transcode Activities', () => {
it('extractPosterActivity applies tone mapping filter when isHdr is true', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-r2.com/video.mp4')
let ffmpegArgs: string[] = []
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.execFile as any).mockImplementation(
(file: string, args: string[], optionsOrCb: unknown, maybeCb?: unknown) => {
const cb = typeof optionsOrCb === 'function' ? optionsOrCb : maybeCb
if (file === 'ffmpeg') {
ffmpegArgs = args
const outPath = args[args.length - 1]
fs.writeFileSync(outPath, 'fake-poster-bytes')
}
if (typeof cb === 'function') {
cb(null, { stdout: '', stderr: '' })
}
},
)
vi.mocked(transcodeService.generatePoster).mockImplementation(async (_in, posterOut) => {
fs.writeFileSync(posterOut, Buffer.from('fake-poster-bytes'))
})
await extractPosterActivity({
assetKey: 'video.mp4',
@@ -1202,12 +1176,16 @@ describe('Transcode Activities', () => {
colorTransfer: 'smpte2084',
})
const vfIndex = ffmpegArgs.indexOf('-vf')
expect(vfIndex).toBeGreaterThan(-1)
const vfArg = ffmpegArgs[vfIndex + 1]
expect(vfArg).toContain('zscale=tin=smpte2084')
expect(vfArg).toContain('tonemap=tonemap=hable')
expect(vfArg).toContain('scale=-2:300')
expect(transcodeService.generatePoster).toHaveBeenCalledWith(
'https://mock-r2.com/video.mp4',
expect.stringContaining('poster.webp'),
{
isHdr: true,
hdrType: 'pq',
colorTransfer: 'smpte2084',
signal: undefined,
},
)
})
it('should throw non-retryable ApplicationFailure when poster extraction is cancelled with aborted signal', async () => {
@@ -1232,19 +1210,10 @@ describe('Transcode Activities', () => {
vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-r2.com/video.mp4')
const controller = new AbortController()
const abortErr = new Error('The operation was aborted')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.execFile as any).mockImplementation(
(_file: string, _args: string[], optionsOrCb: unknown, maybeCb?: unknown) => {
const cb = typeof optionsOrCb === 'function' ? optionsOrCb : maybeCb
controller.abort()
const abortErr = new Error('The operation was aborted')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(abortErr as any).code = 'ABORT_ERR'
if (typeof cb === 'function') {
cb(abortErr, { stdout: '', stderr: '' })
}
},
)
;(abortErr as any).code = 'ABORT_ERR'
vi.mocked(transcodeService.generatePoster).mockRejectedValue(abortErr)
await expect(
extractPosterActivity({
@@ -1273,19 +1242,9 @@ describe('Transcode Activities', () => {
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.execFile as any).mockImplementation(
(file: string, args: string[], optionsOrCb: unknown, maybeCb?: unknown) => {
const cb = typeof optionsOrCb === 'function' ? optionsOrCb : maybeCb
if (file === 'ffmpeg') {
const outPath = args[args.length - 1]
fs.writeFileSync(outPath, 'fake-poster-bytes')
}
if (typeof cb === 'function') {
cb(null, { stdout: '', stderr: '' })
}
},
)
vi.mocked(transcodeService.generatePoster).mockImplementation(async (_in, posterOut) => {
fs.writeFileSync(posterOut, Buffer.from('fake-poster-bytes'))
})
await expect(
extractPosterActivity({
+7 -37
View File
@@ -1,10 +1,6 @@
import { AssetStatus, prisma, WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import {
transcodeService,
buildSdrToneMapFilterChain,
type HdrType,
} from '@shumai/core/src/transcode/transcode'
import { transcodeService, type HdrType } from '@shumai/core/src/transcode/transcode'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { getDerivedArtifactDirectory, stemFromKey } from '@shumai/core/src/utils/filename'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
@@ -924,38 +920,12 @@ export async function extractPosterActivity(
try {
const inputSource = await s3Service.resolveInput(bucket, params.assetKey)
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
let vf = 'scale=-2:300:force_original_aspect_ratio=decrease'
if (params.isHdr) {
const availableFilters = await transcodeService.getAvailableFilters()
const tonemap = buildSdrToneMapFilterChain({
hdrType: params.hdrType,
colorTransfer: params.colorTransfer,
availableFilters,
})
vf = `${tonemap},scale=-2:300:force_original_aspect_ratio=decrease`
}
const args = [
...(isRemote
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
: []),
'-ss',
'0',
'-i',
inputSource,
'-vframes',
'1',
'-vf',
vf,
'-c:v',
'libwebp',
'-q:v',
'75',
posterFile,
]
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], { signal })
await transcodeService.generatePoster(inputSource, posterFile, {
isHdr: params.isHdr,
hdrType: params.hdrType,
colorTransfer: params.colorTransfer,
signal,
})
const posterBuffer = fs.readFileSync(posterFile)
await ensureAssetNotPurging(params.assetKey)