diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bc9c3fe..be0e66c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Changed +- **transcode**: Speed up VA-API hardware transcoding (Intel and AMD GPUs) by also decoding and resizing video on the GPU, making 4K proxies and HLS renditions roughly 3–5× faster on Intel integrated graphics. Videos the GPU cannot decode (such as HEVC on older Intel chips), rotated phone videos, watermarked shares and HDR sources automatically keep using the previous method, and a GPU attempt that stalls is stopped and retried. Set `SHUMAI_HW_DECODE=false` to turn it off + ## [0.5.0] - 2026-10-02 ### Added diff --git a/docs/configuration/hardware-transcoding.mdx b/docs/configuration/hardware-transcoding.mdx index d4426c65..75e41fef 100644 --- a/docs/configuration/hardware-transcoding.mdx +++ b/docs/configuration/hardware-transcoding.mdx @@ -55,6 +55,20 @@ Shumai includes a built-in usability probe that tests hardware encoders at start You should see `card0` and `renderD128` (or similar). 2. Shumai's Docker image automatically adjusts group permissions on container startup so the non-root application user can access host `/dev/dri` devices without permission errors. +#### GPU decoding + +With VA-API, Shumai decodes and resizes video on the GPU as well as encoding it, so frames never leave GPU memory. This is much faster than decoding on the CPU, especially for 4K sources on integrated graphics. (Other backends currently decode on the CPU and encode on the GPU.) + +Some videos automatically use CPU decoding with GPU encoding instead: + +- Codecs your GPU cannot decode, such as HEVC or 10-bit video on older Intel chips. Shumai tries the GPU first and retries on the CPU within a second. +- Rotated videos, such as portrait phone recordings, so they keep the correct orientation. +- Watermarked share links and HDR sources. + +If a GPU-decode attempt stops making progress for 2 minutes (some driver bugs make ffmpeg hang instead of failing), Shumai stops it and retries on the CPU. Change the limit with `SHUMAI_HW_DECODE_STALL_TIMEOUT` (in seconds). + +To always decode on the CPU, set `SHUMAI_HW_DECODE=false` on the `shumai` service. + ### WSL2 (Windows) - Ensure you are running Windows 11 with WSL2 and have installed the appropriate GPU drivers on the Windows host. diff --git a/packages/core/src/transcode/transcode.test.ts b/packages/core/src/transcode/transcode.test.ts index 875f2c0a..aac6d992 100644 --- a/packages/core/src/transcode/transcode.test.ts +++ b/packages/core/src/transcode/transcode.test.ts @@ -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 => { + const n = vi.mocked(execFile).mock.calls.length + onCall(n, callbackOf(optionsOrCallback, maybeCallback), optionsOrCallback) + return {} as ReturnType + }, + ) + + 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 => { + ;(callback as FfmpegCallback)(null, { stdout: JSON.stringify(json), stderr: '' }) + return {} as ReturnType + }, + ) + + /* 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']) diff --git a/packages/core/src/transcode/transcode.ts b/packages/core/src/transcode/transcode.ts index 03bd1895..e31f6955 100644 --- a/packages/core/src/transcode/transcode.ts +++ b/packages/core/src/transcode/transcode.ts @@ -194,6 +194,8 @@ export interface TranscodeVideoParams { sourceColorTransfer?: string sourceColorPrimaries?: string sourceColorSpace?: string + /** Source rotation in degrees from MediaMetadata; probed when omitted. */ + sourceRotation?: number streamIndex?: number audioStreamIndex?: number } @@ -218,6 +220,8 @@ export interface TranscodeHlsRenditionParams { sourceColorPrimaries?: string sourceColorSpace?: string segmentDuration?: number + /** Source rotation in degrees from MediaMetadata; probed when omitted. */ + sourceRotation?: number streamIndex?: number audioStreamIndex?: number } @@ -254,6 +258,35 @@ export const H264_ENCODER_CONFIGS: Record = { }, } +/** + * How an encoder can also decode and scale on its own device, so frames stay in + * GPU memory instead of being decoded and scaled on the CPU and uploaded. + * Only backends verified on real hardware are listed; others (e.g. h264_nvenc + * with `-hwaccel cuda` + `scale_cuda`, h264_qsv, RKMPP) can be added the same way. + */ +export interface HardwareDecodeConfig { + /** Input options placed before `-i` (after any `-init_hw_device`). */ + inputArgs: string[] + /** Output options placed after the filter graph. */ + outputArgs: string[] + /** GPU filter fitting the frame within width x height with even dimensions. */ + scaleFilter: (width: number, height: number) => string +} + +export const HW_DECODE_CONFIGS: Partial> = { + h264_vaapi: { + inputArgs: ['-hwaccel', 'vaapi', '-hwaccel_device', 'accel', '-hwaccel_output_format', 'vaapi'], + // If the decoder reinitializes mid-stream with a different coded size + // (e.g. 1080 -> 1088), ffmpeg would otherwise auto-insert a software + // scaler, which cannot take GPU frames, and fail. + outputArgs: ['-noautoscale'], + // Output range is left as-is (matching the software path): on i965, + // out_range only retags the stream without converting levels. + scaleFilter: (width, height) => + `scale_vaapi=w=${width}:h=${height}:force_original_aspect_ratio=decrease:force_divisible_by=2:format=nv12:mode=hq`, + }, +} + export function getPlatformEncoderCandidates( platform: NodeJS.Platform = process.platform, ): string[] { @@ -293,6 +326,43 @@ export function getVaapiDevice(driDir = '/dev/dri'): string | null { return null } +/** + * Whether hardware encoders with a {@link HW_DECODE_CONFIGS} entry also decode + * and scale on the GPU. Enabled by default; set SHUMAI_HW_DECODE=false to disable. + */ +export function isHwDecodeEnabled(): boolean { + const value = process.env.SHUMAI_HW_DECODE?.trim().toLowerCase() + return value !== 'false' && value !== '0' && value !== 'off' +} + +/** + * A GPU-decode attempt whose output stops growing for this long is killed and + * retried with software decode, since some driver failures hang ffmpeg instead + * of exiting. Override with SHUMAI_HW_DECODE_STALL_TIMEOUT (seconds). + */ +export function getHwDecodeStallTimeoutMs(): number { + const seconds = parseFloat(process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT ?? '') + return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : 120_000 +} + +function getPathSize(target: string): number { + try { + const stat = fs.statSync(target) + if (!stat.isDirectory()) { + return stat.size + } + return fs + .readdirSync(target) + .reduce((total, entry) => total + getPathSize(path.join(target, entry)), 0) + } catch { + return 0 + } +} + +function normalizeRotation(rotation: number): number { + return ((Math.round(rotation) % 360) + 360) % 360 +} + export function parseBitrateKbps(bitrate: string | number): number { if (typeof bitrate === 'number') { return Math.round(bitrate / 1000) @@ -1009,6 +1079,31 @@ export class TranscodeService { async transcodeVideo(params: TranscodeVideoParams): Promise { const encoder = await this.selectH264Encoder(params.hardwareAcceleration) + if (await this.canUseHwDecode(params, encoder)) { + try { + await this.executeFfmpegVideoTranscode(params, encoder, { hwDecode: true }) + 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 decode failed; retrying with software decode and hardware encode', + ) + + this.removeFileIfExists(params.outputFile) + } + } + if (encoder.name !== 'libx264') { try { await this.executeFfmpegVideoTranscode(params, encoder) @@ -1030,13 +1125,7 @@ export class TranscodeService { 'Hardware video transcoding failed; falling back to software transcode (libx264)', ) - if (fs.existsSync(params.outputFile)) { - try { - fs.unlinkSync(params.outputFile) - } catch { - // ignore unlink errors - } - } + this.removeFileIfExists(params.outputFile) await this.executeFfmpegVideoTranscode(params, H264_ENCODER_CONFIGS.libx264) return @@ -1046,9 +1135,211 @@ export class TranscodeService { await this.executeFfmpegVideoTranscode(params, encoder) } + /** + * GPU decode + scale is attempted only for plain proxies: watermark overlays, + * HDR sources and rotated sources keep the software decode path. (ffmpeg + * cannot auto-insert its rotation filter on GPU frames, so a rotated phone + * clip would otherwise come out sideways rather than fail.) Sources the GPU + * cannot decode (e.g. HEVC/10-bit on older Intel iGPUs) fail fast and are + * retried with software decode by the caller. + */ + private async canUseHwDecode( + params: Pick< + TranscodeVideoParams, + | 'inputFile' + | 'streamIndex' + | 'overlayFile' + | 'sourceIsHdr' + | 'sourceHdrType' + | 'sourceRotation' + >, + encoder: EncoderConfig, + ): Promise { + if (!HW_DECODE_CONFIGS[encoder.name] || !isHwDecodeEnabled()) { + return false + } + if (params.overlayFile) { + return false + } + const isSourceHdr = + params.sourceIsHdr || + params.sourceHdrType === 'pq' || + params.sourceHdrType === 'hlg' || + params.sourceHdrType === 'dovi_p5' + if (isSourceHdr) { + return false + } + const rotation = + params.sourceRotation !== undefined + ? normalizeRotation(params.sourceRotation) + : await this.getVideoRotation(params.inputFile, params.streamIndex) + return rotation === 0 + } + + /** + * Rotation of the source video stream in degrees (0, 90, 180 or 270), from + * the display matrix or the legacy `rotate` tag. Returns null if it cannot be + * determined. + */ + async getVideoRotation(inputFile: string, streamIndex?: number): Promise { + try { + const { stdout } = await execFileAsync('ffprobe', [ + '-v', + 'error', + '-select_streams', + streamIndex !== undefined ? String(streamIndex) : 'V:0', + '-show_entries', + 'stream_side_data=rotation:stream_tags=rotate', + '-of', + 'json', + inputFile, + ]) + const stream = JSON.parse(stdout)?.streams?.[0] + if (!stream) { + return null + } + let rotation = 0 + const sideData = Array.isArray(stream.side_data_list) ? stream.side_data_list : [] + const matrix = sideData.find((d: { rotation?: unknown }) => typeof d.rotation === 'number') + if (matrix) { + rotation = matrix.rotation + } else if (stream.tags?.rotate !== undefined) { + rotation = parseFloat(stream.tags.rotate) || 0 + } + return normalizeRotation(rotation) + } catch (err) { + logger.debug({ err, inputFile }, 'Failed to probe video rotation') + return null + } + } + + private removeFileIfExists(filePath: string): void { + if (fs.existsSync(filePath)) { + try { + fs.unlinkSync(filePath) + } catch { + // ignore unlink errors + } + } + } + + /** + * Inputs, video filter graph and `-map [vout]`, shared by the MP4 and HLS + * paths: GPU decode + GPU scale when `hwDecodeConfig` is set, otherwise + * software decode + scale (+ upload for VAAPI encode). + */ + private buildVideoInputArgs( + params: Pick< + TranscodeVideoParams, + 'inputFile' | 'overlayFile' | 'streamIndex' | 'width' | 'height' + >, + options: { + isVaapi: boolean + vaapiDevice?: string + hwDecodeConfig?: HardwareDecodeConfig + frameRate?: number | string + }, + ): string[] { + const { isVaapi, vaapiDevice, hwDecodeConfig, frameRate } = options + const args: string[] = [] + + if (isVaapi && vaapiDevice) { + args.push('-init_hw_device', `vaapi=accel:${vaapiDevice}`, '-filter_hw_device', 'accel') + } + if (hwDecodeConfig) { + args.push(...hwDecodeConfig.inputArgs) + } + + args.push('-i', params.inputFile) + const baseScale = hwDecodeConfig + ? hwDecodeConfig.scaleFilter(params.width, params.height) + : `scale=w=${params.width}:h=${params.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'` + + const vPad = params.streamIndex !== undefined ? `0:${params.streamIndex}` : '0:V' + + let filterComplex: string + if (params.overlayFile) { + args.push('-i', params.overlayFile) + filterComplex = `[${vPad}]scale=${params.width}:${params.height}[vscaled];[vscaled][1:v]overlay=0:0` + } else { + filterComplex = `[${vPad}]${baseScale}` + } + + if (frameRate) { + filterComplex += `,fps=${frameRate}` + } + if (isVaapi && !hwDecodeConfig) { + filterComplex += ',format=nv12,hwupload=extra_hw_frames=64' + } + filterComplex += '[vout]' + + args.push('-filter_complex', filterComplex, '-map', '[vout]') + if (hwDecodeConfig) { + args.push(...hwDecodeConfig.outputArgs) + } + return args + } + + /** + * Runs ffmpeg. With `stallWatchPath`, ffmpeg is killed (SIGKILL; hung VAAPI + * processes have been seen to ignore SIGTERM) if that output file/directory + * stops growing for {@link getHwDecodeStallTimeoutMs}, and the call rejects + * with a regular error so the caller can fall back. + */ + private async runFfmpeg( + args: string[], + options: { signal?: AbortSignal; stallWatchPath?: string } = {}, + ): Promise { + const ffmpegArgs = ['-y', '-loglevel', 'warning', ...args] + + if (!options.stallWatchPath) { + if (options.signal) { + await execFileAsync('ffmpeg', ffmpegArgs, { signal: options.signal }) + } else { + await execFileAsync('ffmpeg', ffmpegArgs) + } + return + } + + const stallTimeoutMs = getHwDecodeStallTimeoutMs() + const stall = new AbortController() + const signal = options.signal ? AbortSignal.any([options.signal, stall.signal]) : stall.signal + const watchPath = options.stallWatchPath + let lastSize = -1 + let lastProgressAt = Date.now() + const timer = setInterval( + () => { + const size = getPathSize(watchPath) + if (size !== lastSize) { + lastSize = size + lastProgressAt = Date.now() + } else if (Date.now() - lastProgressAt >= stallTimeoutMs) { + stall.abort() + } + }, + Math.min(5000, stallTimeoutMs), + ) + timer.unref?.() + + try { + await execFileAsync('ffmpeg', ffmpegArgs, { signal, killSignal: 'SIGKILL' }) + } catch (err) { + if (stall.signal.aborted && !options.signal?.aborted) { + throw new Error( + `ffmpeg made no progress for ${Math.round(stallTimeoutMs / 1000)}s and was killed`, + { cause: err }, + ) + } + throw err + } finally { + clearInterval(timer) + } + } + private async executeFfmpegVideoTranscode( params: TranscodeVideoParams, encoder: EncoderConfig, + options: { hwDecode?: boolean } = {}, ): Promise { const isSourceHdr = params.sourceIsHdr || @@ -1059,6 +1350,11 @@ export class TranscodeService { const isVaapi = encoder.name === 'h264_vaapi' const vaapiDevice = isVaapi ? (this.getVaapiDevice() ?? '/dev/dri/renderD128') : undefined + const hwDecodeConfig = + options.hwDecode && !params.overlayFile && (!isVaapi || vaapiDevice) + ? HW_DECODE_CONFIGS[encoder.name] + : undefined + const hwDecode = Boolean(hwDecodeConfig) logger.info( { @@ -1067,38 +1363,17 @@ export class TranscodeService { inputFile: params.inputFile, outputFile: params.outputFile, vaapiDevice, + hwDecode, }, 'Starting video transcoding', ) - let filterComplex: string - const args: string[] = [] - - if (isVaapi && vaapiDevice) { - args.push('-init_hw_device', `vaapi=accel:${vaapiDevice}`, '-filter_hw_device', 'accel') - } - - args.push('-i', params.inputFile) - const baseScale = `scale=w=${params.width}:h=${params.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'` - - const vPad = params.streamIndex !== undefined ? `0:${params.streamIndex}` : '0:V' - - if (params.overlayFile) { - args.push('-i', params.overlayFile) - filterComplex = `[${vPad}]scale=${params.width}:${params.height}[vscaled];[vscaled][1:v]overlay=0:0` - } else { - filterComplex = `[${vPad}]${baseScale}` - } - - if (params.frameRate) { - filterComplex += `,fps=${params.frameRate}` - } - if (isVaapi) { - filterComplex += ',format=nv12,hwupload=extra_hw_frames=64' - } - filterComplex += '[vout]' - - args.push('-filter_complex', filterComplex, '-map', '[vout]') + const args = this.buildVideoInputArgs(params, { + isVaapi, + vaapiDevice, + hwDecodeConfig, + frameRate: params.frameRate, + }) if (params.frameRate) { let calculatedFps: number @@ -1210,18 +1485,40 @@ export class TranscodeService { args.push('-movflags', '+faststart', '-max_muxing_queue_size', '1024', params.outputFile) - if (params.signal) { - await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], { - signal: params.signal, - }) - } else { - await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args]) - } + await this.runFfmpeg(args, { + signal: params.signal, + stallWatchPath: hwDecode ? params.outputFile : undefined, + }) } async transcodeHlsRendition(params: TranscodeHlsRenditionParams): Promise { const encoder = await this.selectH264Encoder(params.hardwareAcceleration) + if (await this.canUseHwDecode(params, encoder)) { + try { + await this.executeFfmpegHlsTranscode(params, encoder, { hwDecode: true }) + return + } catch (err) { + if (this.isAbortError(err, params.signal)) { + throw err + } + + logger.warn( + { + err, + encoder: encoder.name, + inputFile: params.inputFile, + outputDir: params.outputDir, + width: params.width, + height: params.height, + }, + 'Hardware decode failed for HLS; retrying with software decode and hardware encode', + ) + + this.removeDirIfExists(params.outputDir) + } + } + if (encoder.name !== 'libx264') { try { await this.executeFfmpegHlsTranscode(params, encoder) @@ -1243,13 +1540,7 @@ export class TranscodeService { 'Hardware HLS transcoding failed; falling back to software transcode (libx264)', ) - if (fs.existsSync(params.outputDir)) { - try { - fs.rmSync(params.outputDir, { recursive: true, force: true }) - } catch { - // ignore unlink errors - } - } + this.removeDirIfExists(params.outputDir) await this.executeFfmpegHlsTranscode(params, H264_ENCODER_CONFIGS.libx264) return @@ -1259,9 +1550,20 @@ export class TranscodeService { await this.executeFfmpegHlsTranscode(params, encoder) } + private removeDirIfExists(dirPath: string): void { + if (fs.existsSync(dirPath)) { + try { + fs.rmSync(dirPath, { recursive: true, force: true }) + } catch { + // ignore unlink errors + } + } + } + private async executeFfmpegHlsTranscode( params: TranscodeHlsRenditionParams, encoder: EncoderConfig, + options: { hwDecode?: boolean } = {}, ): Promise { fs.mkdirSync(params.outputDir, { recursive: true }) @@ -1274,6 +1576,11 @@ export class TranscodeService { const isVaapi = encoder.name === 'h264_vaapi' const vaapiDevice = isVaapi ? (this.getVaapiDevice() ?? '/dev/dri/renderD128') : undefined + const hwDecodeConfig = + options.hwDecode && !params.overlayFile && (!isVaapi || vaapiDevice) + ? HW_DECODE_CONFIGS[encoder.name] + : undefined + const hwDecode = Boolean(hwDecodeConfig) const segmentDuration = params.segmentDuration || 4 let calculatedFps = 30 @@ -1304,37 +1611,17 @@ export class TranscodeService { height: params.height, segmentDuration, gopSize, + hwDecode, }, 'Starting HLS rendition transcoding', ) - let filterComplex: string - const args: string[] = [] - - if (isVaapi && vaapiDevice) { - args.push('-init_hw_device', `vaapi=accel:${vaapiDevice}`, '-filter_hw_device', 'accel') - } - - args.push('-i', params.inputFile) - const baseScale = `scale=w=${params.width}:h=${params.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'` - - const vPad = params.streamIndex !== undefined ? `0:${params.streamIndex}` : '0:V' - - if (params.overlayFile) { - args.push('-i', params.overlayFile) - filterComplex = `[${vPad}]scale=${params.width}:${params.height}[vscaled];[vscaled][1:v]overlay=0:0` - } else { - filterComplex = `[${vPad}]${baseScale}` - } - - filterComplex += `,fps=${calculatedFps}` - - if (isVaapi) { - filterComplex += ',format=nv12,hwupload=extra_hw_frames=64' - } - filterComplex += '[vout]' - - args.push('-filter_complex', filterComplex, '-map', '[vout]') + const args = this.buildVideoInputArgs(params, { + isVaapi, + vaapiDevice, + hwDecodeConfig, + frameRate: calculatedFps, + }) if (!params.disableAudio) { const aMap = params.audioStreamIndex !== undefined ? `0:${params.audioStreamIndex}` : '0:a:0?' @@ -1508,13 +1795,10 @@ export class TranscodeService { playlistFile, ) - if (params.signal) { - await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], { - signal: params.signal, - }) - } else { - await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args]) - } + await this.runFfmpeg(args, { + signal: params.signal, + stallWatchPath: hwDecode ? params.outputDir : undefined, + }) } async transcodeImage( diff --git a/packages/transcode/src/activities/transcode.ts b/packages/transcode/src/activities/transcode.ts index 50b3f551..191814be 100644 --- a/packages/transcode/src/activities/transcode.ts +++ b/packages/transcode/src/activities/transcode.ts @@ -334,6 +334,7 @@ export interface VideoActivityParams { sourceColorTransfer?: string sourceColorPrimaries?: string sourceColorSpace?: string + sourceRotation?: number streamIndex?: number audioStreamIndex?: number } @@ -397,6 +398,7 @@ export async function transcodeVideoActivity( sourceColorTransfer: params.sourceColorTransfer, sourceColorPrimaries: params.sourceColorPrimaries, sourceColorSpace: params.sourceColorSpace, + sourceRotation: params.sourceRotation, streamIndex: params.streamIndex, audioStreamIndex: params.audioStreamIndex, }) @@ -464,6 +466,7 @@ export interface HlsActivityParams { sourceColorTransfer?: string sourceColorPrimaries?: string sourceColorSpace?: string + sourceRotation?: number streamIndex?: number audioStreamIndex?: number } @@ -532,6 +535,7 @@ export async function transcodeHlsActivity(params: HlsActivityParams): Promise

sourceColorTransfer: metadata.colorTransfer, sourceColorPrimaries: metadata.colorPrimaries, sourceColorSpace: metadata.colorSpace, + sourceRotation: metadata.rotation ?? 0, streamIndex: metadata.videoStreamIndex, audioStreamIndex: metadata.audioStreamIndex, }) @@ -197,6 +198,8 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise sourceColorTransfer: metadata.colorTransfer, sourceColorPrimaries: metadata.colorPrimaries, sourceColorSpace: metadata.colorSpace, + // rotation is undefined when the probed source has none + sourceRotation: metadata.rotation ?? 0, streamIndex: metadata.videoStreamIndex, audioStreamIndex: metadata.audioStreamIndex, }) @@ -227,6 +230,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise sourceColorTransfer: metadata.colorTransfer, sourceColorPrimaries: metadata.colorPrimaries, sourceColorSpace: metadata.colorSpace, + sourceRotation: metadata.rotation ?? 0, streamIndex: metadata.videoStreamIndex, audioStreamIndex: metadata.audioStreamIndex, })