feat(transcode): decode and scale on the GPU for hardware transcodes (VA-API) (#449)

* feat(transcode): decode and scale on the GPU for VA-API transcodes

When the selected encoder is h264_vaapi, decode with -hwaccel vaapi and
scale with scale_vaapi so frames stay in GPU memory, instead of decoding
and scaling on the CPU and hwupload-ing before the encoder. On a Haswell
iGPU this makes 4K proxy/HLS renditions 3-5x faster.

Fallback order: GPU decode + VA-API encode -> software decode + VA-API
encode (previous behavior) -> libx264. Watermark overlays, HDR sources
and rotated sources skip GPU decode: ffmpeg cannot auto-insert its
rotation filter on hardware frames, so rotated input would otherwise come
out sideways instead of failing. SHUMAI_VAAPI_HW_DECODE=false disables it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(transcode): document VA-API GPU decoding and SHUMAI_VAAPI_HW_DECODE

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(transcode): generic hardware decode config, stall watchdog, reuse probed rotation

Follow-ups from comparing with Immich and Jellyfin:

- Replace the VA-API-specific helpers with a per-encoder HW_DECODE_CONFIGS
  table (input args, output args, GPU scale filter) and build the MP4 and
  HLS input/filter graph in one shared method so the paths cannot drift.
  Only h264_vaapi has an entry; other backends can be added once tested on
  real hardware. The opt-out is now SHUMAI_HW_DECODE=false.
- Kill a GPU-decode attempt with SIGKILL when its output stops growing for
  SHUMAI_HW_DECODE_STALL_TIMEOUT (default 120s) and fall back, since some
  VA-API driver failures hang ffmpeg instead of exiting (immich#31933).
- Add -noautoscale on the GPU-decode path so a mid-stream decoder reinit
  (e.g. 1080 -> 1088) cannot auto-insert a software scaler into the GPU
  graph (jellyfin#17133).
- Pass the rotation already probed into MediaMetadata through the workflow
  and activities as sourceRotation; ffprobe only runs when it is missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cameron Harris
2026-10-05 12:00:01 +08:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 9a640632aa
commit dd57fb9ed2
6 changed files with 881 additions and 83 deletions
@@ -7,6 +7,9 @@ import {
getDefaultBitrateBps,
calculateMaxBitrate,
H264_ENCODER_CONFIGS,
isHwDecodeEnabled,
getHwDecodeStallTimeoutMs,
HW_DECODE_CONFIGS,
buildSdrToneMapFilterChain,
getVaapiDevice,
parseBitrateKbps,
@@ -1370,12 +1373,20 @@ describe('TranscodeService', () => {
})
describe('Hardware Acceleration & Encoder Resolution', () => {
let origHwDecode: string | undefined
beforeEach(() => {
transcodeService.clearEncodersCache()
// These tests cover the software-decode VAAPI path; the GPU decode path
// (on by default) is covered in 'Hardware decode' below.
origHwDecode = process.env.SHUMAI_HW_DECODE
process.env.SHUMAI_HW_DECODE = 'false'
})
afterEach(() => {
vi.restoreAllMocks()
if (origHwDecode === undefined) delete process.env.SHUMAI_HW_DECODE
else process.env.SHUMAI_HW_DECODE = origHwDecode
})
it('should return platform candidates correctly', () => {
@@ -2576,6 +2587,485 @@ describe('TranscodeService', () => {
})
})
describe('Hardware decode', () => {
let origHwDecode: string | undefined
let origStall: string | undefined
type FfmpegCallback = (err: Error | null, result: { stdout: string; stderr: string }) => void
// execFile is called as (cmd, args, cb) or (cmd, args, options, cb); the
// GPU-decode attempt always passes options (signal + SIGKILL watchdog).
const callbackOf = (optionsOrCallback: unknown, maybeCallback?: unknown) =>
(typeof optionsOrCallback === 'function'
? optionsOrCallback
: maybeCallback) as FfmpegCallback
const mockFfmpeg = (onCall: (n: number, cb: FfmpegCallback, options: unknown) => void) =>
vi
.mocked(execFile)
.mockImplementation(
(
_cmd: unknown,
_args: unknown,
optionsOrCallback: unknown,
maybeCallback?: unknown,
): ReturnType<typeof child_process.execFile> => {
const n = vi.mocked(execFile).mock.calls.length
onCall(n, callbackOf(optionsOrCallback, maybeCallback), optionsOrCallback)
return {} as ReturnType<typeof child_process.execFile>
},
)
const failOn =
(...failing: number[]) =>
(n: number, cb: FfmpegCallback) =>
failing.includes(n)
? cb(new Error(`ffmpeg failed on call ${n}`), { stdout: '', stderr: '' })
: cb(null, { stdout: '', stderr: '' })
const calls = () => vi.mocked(child_process.execFile).mock.calls.map((c) => c[1] as string[])
const filterOf = (args: string[]) => args[args.indexOf('-filter_complex') + 1]
const vaapiScale = (w: number, h: number) => HW_DECODE_CONFIGS.h264_vaapi!.scaleFilter(w, h)
beforeEach(() => {
transcodeService.clearEncodersCache()
origHwDecode = process.env.SHUMAI_HW_DECODE
origStall = process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT
delete process.env.SHUMAI_HW_DECODE
delete process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
H264_ENCODER_CONFIGS.h264_vaapi,
)
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue('/dev/dri/renderD128')
vi.spyOn(transcodeService, 'getVideoRotation').mockResolvedValue(0)
})
afterEach(() => {
vi.restoreAllMocks()
if (origHwDecode === undefined) delete process.env.SHUMAI_HW_DECODE
else process.env.SHUMAI_HW_DECODE = origHwDecode
if (origStall === undefined) delete process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT
else process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT = origStall
})
it('isHwDecodeEnabled should default to true and honor false/0/off', () => {
expect(isHwDecodeEnabled()).toBe(true)
for (const value of ['false', '0', 'off', ' FALSE ']) {
process.env.SHUMAI_HW_DECODE = value
expect(isHwDecodeEnabled()).toBe(false)
}
process.env.SHUMAI_HW_DECODE = 'true'
expect(isHwDecodeEnabled()).toBe(true)
})
it('getHwDecodeStallTimeoutMs should default to 120s and honor SHUMAI_HW_DECODE_STALL_TIMEOUT', () => {
expect(getHwDecodeStallTimeoutMs()).toBe(120_000)
process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT = '30'
expect(getHwDecodeStallTimeoutMs()).toBe(30_000)
process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT = 'nope'
expect(getHwDecodeStallTimeoutMs()).toBe(120_000)
})
it('only h264_vaapi should have a hardware decode config for now', () => {
expect(Object.keys(HW_DECODE_CONFIGS)).toEqual(['h264_vaapi'])
expect(vaapiScale(1920, 1080)).toBe(
'scale_vaapi=w=1920:h=1080:force_original_aspect_ratio=decrease:force_divisible_by=2:format=nv12:mode=hq',
)
})
it('transcodeVideo should decode and scale on the GPU by default with vaapi', async () => {
mockFfmpeg(failOn())
const loggerSpy = vi.spyOn(logger, 'info')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, 'out_hwdec.mp4'),
width: 1280,
height: 720,
frameRate: 24,
hardwareAcceleration: 'auto',
sourceVideoBitrate: 600_000,
sourceRotation: 0,
})
expect(calls()).toHaveLength(1)
const args = calls()[0]
expect(args).toEqual(
expect.arrayContaining([
'-init_hw_device',
'vaapi=accel:/dev/dri/renderD128',
'-hwaccel',
'vaapi',
'-hwaccel_device',
'accel',
'-hwaccel_output_format',
'vaapi',
'-noautoscale',
'-c:v',
'h264_vaapi',
'-rc_mode',
'3',
]),
)
// hwaccel options must precede the input; -noautoscale is an output option
expect(args.indexOf('-hwaccel')).toBeLessThan(args.indexOf('-i'))
expect(args.indexOf('-noautoscale')).toBeGreaterThan(args.indexOf('-filter_complex'))
expect(filterOf(args)).toBe(`[0:V]${vaapiScale(1280, 720)},fps=24[vout]`)
expect(filterOf(args)).not.toContain('hwupload')
expect(args).not.toContain('-pix_fmt')
// the GPU attempt runs under the stall watchdog
expect(vi.mocked(child_process.execFile).mock.calls[0][2]).toEqual(
expect.objectContaining({ killSignal: 'SIGKILL', signal: expect.any(AbortSignal) }),
)
expect(loggerSpy).toHaveBeenCalledWith(
expect.objectContaining({ encoder: 'h264_vaapi', hwDecode: true }),
'Starting video transcoding',
)
})
it('transcodeVideo should use the provided sourceRotation instead of probing', async () => {
mockFfmpeg(failOn())
await transcodeService.transcodeVideo({
inputFile: 'portrait.mov',
outputFile: path.join(tempDir, 'out_hwdec_rotation_param.mp4'),
width: 1080,
height: 1920,
hardwareAcceleration: 'auto',
sourceRotation: -90,
})
expect(transcodeService.getVideoRotation).not.toHaveBeenCalled()
expect(calls()[0]).not.toContain('-hwaccel')
expect(filterOf(calls()[0])).toContain('hwupload')
})
it('transcodeVideo should probe rotation when sourceRotation is not provided', async () => {
vi.mocked(transcodeService.getVideoRotation).mockResolvedValue(90)
mockFfmpeg(failOn())
await transcodeService.transcodeVideo({
inputFile: 'portrait.mov',
outputFile: path.join(tempDir, 'out_hwdec_rotated.mp4'),
width: 1080,
height: 1920,
hardwareAcceleration: 'auto',
})
expect(transcodeService.getVideoRotation).toHaveBeenCalledWith('portrait.mov', undefined)
expect(calls()).toHaveLength(1)
expect(calls()[0]).not.toContain('-hwaccel')
expect(filterOf(calls()[0])).toContain('hwupload')
})
it('transcodeVideo should retry with software decode + hardware encode when GPU decode fails', async () => {
const outputFile = path.join(tempDir, 'out_hwdec_retry.mp4')
mockFfmpeg(failOn(1))
const warnSpy = vi.spyOn(logger, 'warn')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(calls()).toHaveLength(2)
expect(calls()[0]).toContain('-hwaccel')
expect(calls()[1]).not.toContain('-hwaccel')
expect(calls()[1]).not.toContain('-noautoscale')
expect(calls()[1]).toContain('h264_vaapi')
expect(filterOf(calls()[1])).toContain('format=nv12,hwupload=extra_hw_frames=64')
expect(warnSpy).toHaveBeenCalledWith(
expect.objectContaining({ encoder: 'h264_vaapi', outputFile }),
'Hardware decode failed; retrying with software decode and hardware encode',
)
})
it('transcodeVideo should kill a stalled GPU decode attempt and fall back', async () => {
process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT = '0.05'
const outputFile = path.join(tempDir, 'out_hwdec_stall.mp4')
const warnSpy = vi.spyOn(logger, 'warn')
let killSignal: unknown
mockFfmpeg((n, cb, options) => {
if (n === 1) {
// simulate a hung ffmpeg: never exits on its own, only when killed
const opts = options as { signal: AbortSignal; killSignal: string }
killSignal = opts.killSignal
opts.signal.addEventListener('abort', () => {
const err = new Error('The operation was aborted')
err.name = 'AbortError'
cb(err, { stdout: '', stderr: '' })
})
} else {
cb(null, { stdout: '', stderr: '' })
}
})
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(killSignal).toBe('SIGKILL')
expect(calls()).toHaveLength(2)
expect(calls()[1]).not.toContain('-hwaccel')
expect(warnSpy).toHaveBeenCalledWith(
expect.objectContaining({
err: expect.objectContaining({ message: expect.stringContaining('made no progress') }),
}),
'Hardware decode failed; retrying with software decode and hardware encode',
)
})
it('transcodeVideo should fall back to libx264 when GPU decode and vaapi encode both fail', async () => {
const outputFile = path.join(tempDir, 'out_hwdec_x264.mp4')
let existedBeforeRetry = true
mockFfmpeg((n, cb) => {
if (n === 1) {
fs.writeFileSync(outputFile, 'partial video data')
cb(new Error('hw decode failed'), { stdout: '', stderr: '' })
} else if (n === 2) {
existedBeforeRetry = fs.existsSync(outputFile)
cb(new Error('vaapi encode failed'), { stdout: '', stderr: '' })
} else {
cb(null, { stdout: '', stderr: '' })
}
})
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(calls()).toHaveLength(3)
expect(existedBeforeRetry).toBe(false)
expect(calls()[0]).toContain('-hwaccel')
expect(calls()[1]).toContain('h264_vaapi')
expect(calls()[1]).not.toContain('-hwaccel')
expect(calls()[2]).toContain('libx264')
})
it('transcodeVideo should not retry when the GPU decode attempt was aborted by the caller', async () => {
const abortController = new AbortController()
mockFfmpeg((_n, cb) => {
abortController.abort()
const abortErr = new Error('The operation was aborted')
abortErr.name = 'AbortError'
cb(abortErr, { stdout: '', stderr: '' })
})
await expect(
transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, 'out_hwdec_abort.mp4'),
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
signal: abortController.signal,
}),
).rejects.toThrow('aborted')
expect(vi.mocked(child_process.execFile)).toHaveBeenCalledTimes(1)
})
it('transcodeVideo should keep software decode for watermark overlays', async () => {
mockFfmpeg(failOn())
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, 'out_hwdec_overlay.mp4'),
width: 1280,
height: 720,
overlayFile: 'overlay.png',
hardwareAcceleration: 'auto',
})
expect(calls()).toHaveLength(1)
expect(calls()[0]).not.toContain('-hwaccel')
expect(filterOf(calls()[0])).toContain('overlay=0:0')
expect(filterOf(calls()[0])).toContain('hwupload')
})
it('transcodeVideo should keep software decode for HDR sources', async () => {
mockFfmpeg(failOn())
await transcodeService.transcodeVideo({
inputFile: 'input.mov',
outputFile: path.join(tempDir, 'out_hwdec_hdr.mp4'),
width: 1920,
height: 1080,
sourceHdrType: 'pq',
hardwareAcceleration: 'auto',
})
expect(calls()[0]).not.toContain('-hwaccel')
expect(filterOf(calls()[0])).toContain('hwupload')
})
it('transcodeVideo should keep software decode when SHUMAI_HW_DECODE=false', async () => {
process.env.SHUMAI_HW_DECODE = 'false'
mockFfmpeg(failOn())
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, 'out_hwdec_disabled.mp4'),
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(calls()[0]).not.toContain('-hwaccel')
expect(filterOf(calls()[0])).toContain('hwupload')
})
it('transcodeVideo should not use GPU decode for encoders without a hardware decode config', async () => {
for (const encoder of ['libx264', 'h264_nvenc', 'h264_qsv'] as const) {
vi.mocked(child_process.execFile).mockClear()
vi.mocked(transcodeService.selectH264Encoder).mockResolvedValue(
H264_ENCODER_CONFIGS[encoder],
)
mockFfmpeg(failOn())
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, `out_hwdec_${encoder}.mp4`),
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(calls()).toHaveLength(1)
expect(calls()[0]).not.toContain('-hwaccel')
expect(calls()[0]).toContain(encoder)
}
})
it('transcodeHlsRendition should decode and scale on the GPU by default with vaapi', async () => {
mockFfmpeg(failOn())
const loggerSpy = vi.spyOn(logger, 'info')
await transcodeService.transcodeHlsRendition({
inputFile: 'input.mp4',
outputDir: path.join(tempDir, 'hls_hwdec'),
width: 1920,
height: 1080,
frameRate: 24,
hardwareAcceleration: 'auto',
sourceRotation: 0,
})
expect(calls()).toHaveLength(1)
const args = calls()[0]
expect(args).toEqual(
expect.arrayContaining([
'-hwaccel',
'vaapi',
'-hwaccel_output_format',
'vaapi',
'-noautoscale',
'-f',
'hls',
]),
)
expect(args.indexOf('-hwaccel')).toBeLessThan(args.indexOf('-i'))
expect(filterOf(args)).toBe(`[0:V]${vaapiScale(1920, 1080)},fps=24[vout]`)
expect(transcodeService.getVideoRotation).not.toHaveBeenCalled()
expect(loggerSpy).toHaveBeenCalledWith(
expect.objectContaining({ encoder: 'h264_vaapi', hwDecode: true }),
'Starting HLS rendition transcoding',
)
})
it('transcodeHlsRendition should keep software decode when rotation cannot be determined', async () => {
vi.mocked(transcodeService.getVideoRotation).mockResolvedValue(null)
mockFfmpeg(failOn())
await transcodeService.transcodeHlsRendition({
inputFile: 'input.mp4',
outputDir: path.join(tempDir, 'hls_hwdec_unknown_rotation'),
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(calls()[0]).not.toContain('-hwaccel')
})
it('transcodeHlsRendition should retry with software decode, then libx264, cleaning the output dir', async () => {
const outputDir = path.join(tempDir, 'hls_hwdec_fallback')
let dirExistedBeforeRetry = true
mockFfmpeg((n, cb) => {
if (n === 1) {
fs.writeFileSync(path.join(outputDir, 'segment_000.m4s'), 'partial')
cb(new Error('hw decode failed'), { stdout: '', stderr: '' })
} else if (n === 2) {
dirExistedBeforeRetry = fs.existsSync(path.join(outputDir, 'segment_000.m4s'))
cb(new Error('vaapi encode failed'), { stdout: '', stderr: '' })
} else {
cb(null, { stdout: '', stderr: '' })
}
})
await transcodeService.transcodeHlsRendition({
inputFile: 'input.mp4',
outputDir,
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(calls()).toHaveLength(3)
expect(dirExistedBeforeRetry).toBe(false)
expect(calls()[0]).toContain('-hwaccel')
expect(calls()[1]).not.toContain('-hwaccel')
expect(filterOf(calls()[1])).toContain('hwupload')
expect(calls()[2]).toContain('libx264')
})
it('getVideoRotation should read the display matrix, the rotate tag, and normalize', async () => {
vi.mocked(transcodeService.getVideoRotation).mockRestore()
const probe = (json: unknown) =>
vi
.mocked(execFile)
.mockImplementationOnce(
(
_cmd: unknown,
_args: unknown,
callback: unknown,
): ReturnType<typeof child_process.execFile> => {
;(callback as FfmpegCallback)(null, { stdout: JSON.stringify(json), stderr: '' })
return {} as ReturnType<typeof child_process.execFile>
},
)
/* eslint-disable @typescript-eslint/naming-convention */
probe({
streams: [{ side_data_list: [{ side_data_type: 'Display Matrix', rotation: -90 }] }],
})
/* eslint-enable @typescript-eslint/naming-convention */
expect(await transcodeService.getVideoRotation('a.mov')).toBe(270)
probe({ streams: [{ tags: { rotate: '180' } }] })
expect(await transcodeService.getVideoRotation('b.mp4')).toBe(180)
probe({ streams: [{}] })
expect(await transcodeService.getVideoRotation('c.mp4', 2)).toBe(0)
expect(vi.mocked(child_process.execFile).mock.calls.at(-1)?.[1]).toEqual(
expect.arrayContaining(['-select_streams', '2']),
)
probe({ streams: [] })
expect(await transcodeService.getVideoRotation('d.mp4')).toBeNull()
})
})
describe('HDR detection, tone mapping, and transcoding', () => {
it('buildSdrToneMapFilterChain constructs zscale + tonemap filter chain for PQ and HLG', () => {
const available = new Set(['zscale', 'tonemap'])