feat(transcode): fallback to software encoding when hardware transcode fails (#433)

This commit is contained in:
Yiling-J
2026-09-28 16:45:28 +08:00
committed by GitHub
parent bf5ac566b6
commit c9d0b476cd
4 changed files with 228 additions and 9 deletions
+1
View File
@@ -10,6 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- **notification**: You can now receive notifications via email, with batched digest emails and configurable team-level SMTP settings
- **transcode**: Add VA-API hardware acceleration support for Linux hosts and Docker environments with Intel and AMD GPUs, featuring automatic DRI render node discovery, variable bitrate control, and structured transcoding observability logs
- **transcode**: Add automatic fallback to software transcoding (libx264) when hardware-accelerated video encoding encounters GPU resolution constraints or runtime driver errors
- **docker**: Add modular hardware-accelerated transcoding presets matching Immich's compose configuration via `hwaccel.transcoding.yaml` with support for NVENC, QuickSync, RKMPP, and VA-API
### Fixed
+1 -1
View File
@@ -7,7 +7,7 @@ High-resolution camera recordings, phone videos, and animation media files requi
Hardware-accelerated transcoding allows you to offload video encoding to a dedicated or integrated GPU, dramatically speeding up processing and freeing host CPU cores for other services.
Shumai includes a built-in usability probe that tests hardware encoders at runtime. If GPU drivers or device nodes are unavailable, Shumai automatically falls back to software encoding without failing user tasks.
Shumai includes a built-in usability probe that tests hardware encoders at startup, alongside automatic runtime fallback during video processing. If GPU drivers or device nodes are unavailable, or if a hardware encoder encounters hardware limits (such as resolution or dimension constraints on certain GPUs) or runtime driver errors, Shumai seamlessly falls back to software encoding (`libx264`) without failing user tasks.
---
+172 -7
View File
@@ -2108,11 +2108,81 @@ describe('TranscodeService', () => {
expect(callArgs).toContain('1552k')
})
it('transcodeVideo should throw immediately when ffmpeg fails during hardware transcoding', async () => {
it('transcodeVideo should fall back to libx264 software encoding when hardware transcoding fails', async () => {
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
H264_ENCODER_CONFIGS.h264_vaapi,
)
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue('/dev/dri/renderD128')
const warnSpy = vi.spyOn(logger, 'warn')
let callCount = 0
vi.mocked(execFile).mockImplementation(
(
_cmd: unknown,
_args: unknown,
callback: unknown,
): ReturnType<typeof child_process.execFile> => {
callCount++
const cb = callback as (
err: Error | null,
result: { stdout: string; stderr: string },
) => void
if (typeof cb === 'function') {
if (callCount === 1) {
cb(
new Error(
'Hardware does not support encoding at size 1088x1920 (constraints: width 128-2560 height 128-1440)',
),
{
stdout: '',
stderr: 'VAAPI error',
},
)
} else {
cb(null, { stdout: '', stderr: '' })
}
}
return {} as ReturnType<typeof child_process.execFile>
},
)
const outputFile = path.join(tempDir, 'out_vaapi_fallback.mp4')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1088,
height: 1920,
hardwareAcceleration: 'auto',
})
expect(callCount).toBe(2)
const firstCallArgs = vi.mocked(child_process.execFile).mock.calls[0][1] as string[]
const secondCallArgs = vi.mocked(child_process.execFile).mock.calls[1][1] as string[]
expect(firstCallArgs).toContain('h264_vaapi')
expect(secondCallArgs).toContain('libx264')
expect(secondCallArgs).toContain('-pix_fmt')
expect(secondCallArgs).toContain('yuv420p')
expect(warnSpy).toHaveBeenCalledWith(
expect.objectContaining({
encoder: 'h264_vaapi',
inputFile: 'input.mp4',
outputFile,
}),
'Hardware video transcoding failed; falling back to software transcode (libx264)',
)
})
it('transcodeVideo should clean up partial output file before falling back to software transcode', async () => {
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
H264_ENCODER_CONFIGS.h264_vaapi,
)
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue('/dev/dri/renderD128')
const outputFile = path.join(tempDir, 'out_vaapi_partial.mp4')
let callCount = 0
let existedBeforeFallback = false
vi.mocked(execFile).mockImplementation(
(
@@ -2120,21 +2190,70 @@ describe('TranscodeService', () => {
_args: unknown,
callback: unknown,
): ReturnType<typeof child_process.execFile> => {
callCount++
const cb = callback as (
err: Error | null,
result: { stdout: string; stderr: string },
) => void
if (typeof cb === 'function') {
cb(new Error('VAAPI driver error: failed to allocate surface'), {
stdout: '',
stderr: 'driver error',
})
if (callCount === 1) {
// Simulate ffmpeg creating a partial output file before failing
fs.writeFileSync(outputFile, 'partial video data')
cb(new Error('VAAPI encode failed'), { stdout: '', stderr: 'encode failed' })
} else {
existedBeforeFallback = fs.existsSync(outputFile)
cb(null, { stdout: '', stderr: '' })
}
}
return {} as ReturnType<typeof child_process.execFile>
},
)
const outputFile = path.join(tempDir, 'out_vaapi_fail.mp4')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1088,
height: 1920,
hardwareAcceleration: 'auto',
})
expect(callCount).toBe(2)
expect(existedBeforeFallback).toBe(false)
})
it('transcodeVideo should rethrow software transcode error if fallback also fails', async () => {
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
H264_ENCODER_CONFIGS.h264_vaapi,
)
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue('/dev/dri/renderD128')
let callCount = 0
vi.mocked(execFile).mockImplementation(
(
_cmd: unknown,
_args: unknown,
callback: unknown,
): ReturnType<typeof child_process.execFile> => {
callCount++
const cb = callback as (
err: Error | null,
result: { stdout: string; stderr: string },
) => void
if (typeof cb === 'function') {
if (callCount === 1) {
cb(new Error('VAAPI driver error'), { stdout: '', stderr: 'driver error' })
} else {
cb(new Error('x264 failed: corrupted frame'), {
stdout: '',
stderr: 'x264 error',
})
}
}
return {} as ReturnType<typeof child_process.execFile>
},
)
const outputFile = path.join(tempDir, 'out_vaapi_both_fail.mp4')
await expect(
transcodeService.transcodeVideo({
inputFile: 'input.mp4',
@@ -2143,7 +2262,53 @@ describe('TranscodeService', () => {
height: 720,
hardwareAcceleration: 'auto',
}),
).rejects.toThrow('VAAPI driver error: failed to allocate surface')
).rejects.toThrow('x264 failed: corrupted frame')
expect(callCount).toBe(2)
})
it('transcodeVideo should not fall back to software encoding when transcode was aborted', async () => {
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
H264_ENCODER_CONFIGS.h264_vaapi,
)
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue('/dev/dri/renderD128')
const abortController = new AbortController()
let callCount = 0
vi.mocked(execFile).mockImplementation(
(
_cmd: unknown,
_args: unknown,
optionsOrCallback: unknown,
maybeCallback?: unknown,
): ReturnType<typeof child_process.execFile> => {
callCount++
const cb = (
typeof optionsOrCallback === 'function' ? optionsOrCallback : maybeCallback
) as (err: Error | null, result: { stdout: string; stderr: string }) => void
if (typeof cb === 'function') {
abortController.abort()
const abortErr = new Error('The operation was aborted')
abortErr.name = 'AbortError'
cb(abortErr, { stdout: '', stderr: '' })
}
return {} as ReturnType<typeof child_process.execFile>
},
)
const outputFile = path.join(tempDir, 'out_vaapi_abort.mp4')
await expect(
transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
signal: abortController.signal,
}),
).rejects.toThrow('The operation was aborted')
expect(callCount).toBe(1)
})
it('transcodeVideo with threads > 0 should pass -threads to ffmpeg', async () => {
+54 -1
View File
@@ -866,7 +866,61 @@ export class TranscodeService {
return H264_ENCODER_CONFIGS.libx264
}
private isAbortError(err: unknown, signal?: AbortSignal): boolean {
if (signal?.aborted) return true
if (err && typeof err === 'object') {
const r = err as Record<string, unknown>
if (r.name === 'AbortError' || r.code === 'ABORT_ERR') return true
const msg = typeof r.message === 'string' ? r.message.toLowerCase() : ''
if (msg.includes('abort')) return true
}
return false
}
async transcodeVideo(params: TranscodeVideoParams): Promise<void> {
const encoder = await this.selectH264Encoder(params.hardwareAcceleration)
if (encoder.name !== 'libx264') {
try {
await this.executeFfmpegVideoTranscode(params, encoder)
return
} catch (err) {
if (this.isAbortError(err, params.signal)) {
throw err
}
logger.warn(
{
err,
encoder: encoder.name,
inputFile: params.inputFile,
outputFile: params.outputFile,
width: params.width,
height: params.height,
},
'Hardware video transcoding failed; falling back to software transcode (libx264)',
)
if (fs.existsSync(params.outputFile)) {
try {
fs.unlinkSync(params.outputFile)
} catch {
// ignore unlink errors
}
}
await this.executeFfmpegVideoTranscode(params, H264_ENCODER_CONFIGS.libx264)
return
}
}
await this.executeFfmpegVideoTranscode(params, encoder)
}
private async executeFfmpegVideoTranscode(
params: TranscodeVideoParams,
encoder: EncoderConfig,
): Promise<void> {
const isSourceHdr =
params.sourceIsHdr ||
params.sourceHdrType === 'pq' ||
@@ -874,7 +928,6 @@ export class TranscodeService {
params.sourceHdrType === 'dovi_p5'
const isHdrOutput = Boolean(params.hdr)
const encoder = await this.selectH264Encoder(params.hardwareAcceleration)
const isVaapi = encoder.name === 'h264_vaapi'
const vaapiDevice = isVaapi ? (this.getVaapiDevice() ?? '/dev/dri/renderD128') : undefined