From c9d0b476cd62ad394738a39e0dfaa887e2c52172 Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Mon, 28 Sep 2026 16:45:28 +0800 Subject: [PATCH] feat(transcode): fallback to software encoding when hardware transcode fails (#433) --- CHANGELOG.md | 1 + docs/configuration/hardware-transcoding.mdx | 2 +- packages/core/src/transcode/transcode.test.ts | 179 +++++++++++++++++- packages/core/src/transcode/transcode.ts | 55 +++++- 4 files changed, 228 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 556e235f..dcace07e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/configuration/hardware-transcoding.mdx b/docs/configuration/hardware-transcoding.mdx index 8d984e3f..d4426c65 100644 --- a/docs/configuration/hardware-transcoding.mdx +++ b/docs/configuration/hardware-transcoding.mdx @@ -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. --- diff --git a/packages/core/src/transcode/transcode.test.ts b/packages/core/src/transcode/transcode.test.ts index befacf86..aba48e06 100644 --- a/packages/core/src/transcode/transcode.test.ts +++ b/packages/core/src/transcode/transcode.test.ts @@ -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 => { + 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 + }, + ) + + 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 => { + 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 }, ) - 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 => { + 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 + }, + ) + + 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 => { + 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 + }, + ) + + 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 () => { diff --git a/packages/core/src/transcode/transcode.ts b/packages/core/src/transcode/transcode.ts index 10d59156..dd09c75f 100644 --- a/packages/core/src/transcode/transcode.ts +++ b/packages/core/src/transcode/transcode.ts @@ -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 + 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 { + 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 { 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