mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 22:59:25 +00:00
feat(transcode): add VA-API hardware acceleration support (#430)
* feat(transcode): add VA-API hardware acceleration support * fix(docker): switch to jellyfin-ffmpeg 8.1.2-5 for VA-API support * fix(transcode): probe hardware encoder usability to skip uninitialized drivers * ci(release): add workflow_dispatch trigger with custom tag input * fix(transcode): use 256x256 frame dimension for encoder usability probe * feat(docker): add hwaccel transcoding compose presets matching immich * docs: add hardware transcoding documentation and quickstart references * feat(transcode): prioritize h264_vaapi before h264_qsv on Linux * fix(docker): extend device permission loop to rkmpp and wsl accelerator nodes
This commit is contained in:
@@ -8,7 +8,10 @@ import {
|
||||
calculateMaxBitrate,
|
||||
H264_ENCODER_CONFIGS,
|
||||
buildSdrToneMapFilterChain,
|
||||
getVaapiDevice,
|
||||
parseBitrateKbps,
|
||||
} from './transcode'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import * as path from 'path'
|
||||
import * as child_process from 'child_process'
|
||||
@@ -1223,7 +1226,57 @@ describe('TranscodeService', () => {
|
||||
'h264_amf',
|
||||
])
|
||||
expect(getPlatformEncoderCandidates('win32')).toEqual(['h264_nvenc', 'h264_qsv', 'h264_amf'])
|
||||
expect(getPlatformEncoderCandidates('linux')).toEqual(['h264_nvenc', 'h264_qsv', 'h264_amf'])
|
||||
expect(getPlatformEncoderCandidates('linux')).toEqual([
|
||||
'h264_nvenc',
|
||||
'h264_vaapi',
|
||||
'h264_qsv',
|
||||
'h264_amf',
|
||||
])
|
||||
})
|
||||
|
||||
it('getVaapiDevice should return device from SHUMAI_VAAPI_DEVICE or VAAPI_DEVICE env var', () => {
|
||||
const origShumai = process.env.SHUMAI_VAAPI_DEVICE
|
||||
const origVaapi = process.env.VAAPI_DEVICE
|
||||
try {
|
||||
process.env.SHUMAI_VAAPI_DEVICE = '/dev/dri/custom1'
|
||||
expect(getVaapiDevice()).toBe('/dev/dri/custom1')
|
||||
delete process.env.SHUMAI_VAAPI_DEVICE
|
||||
|
||||
process.env.VAAPI_DEVICE = '/dev/dri/custom2'
|
||||
expect(getVaapiDevice()).toBe('/dev/dri/custom2')
|
||||
} finally {
|
||||
if (origShumai) process.env.SHUMAI_VAAPI_DEVICE = origShumai
|
||||
else delete process.env.SHUMAI_VAAPI_DEVICE
|
||||
if (origVaapi) process.env.VAAPI_DEVICE = origVaapi
|
||||
else delete process.env.VAAPI_DEVICE
|
||||
}
|
||||
})
|
||||
|
||||
it('getVaapiDevice should pick highest index render node from driDir', () => {
|
||||
const fakeDriDir = path.join(tempDir, 'fake-dri')
|
||||
fs.mkdirSync(fakeDriDir, { recursive: true })
|
||||
fs.writeFileSync(path.join(fakeDriDir, 'card0'), '')
|
||||
fs.writeFileSync(path.join(fakeDriDir, 'renderD128'), '')
|
||||
fs.writeFileSync(path.join(fakeDriDir, 'renderD129'), '')
|
||||
|
||||
expect(getVaapiDevice(fakeDriDir)).toBe(path.join(fakeDriDir, 'renderD129'))
|
||||
})
|
||||
|
||||
it('getVaapiDevice should return null if driDir does not exist or has no render/card devices', () => {
|
||||
expect(getVaapiDevice(path.join(tempDir, 'non-existent'))).toBeNull()
|
||||
|
||||
const emptyDir = path.join(tempDir, 'empty-dri')
|
||||
fs.mkdirSync(emptyDir, { recursive: true })
|
||||
expect(getVaapiDevice(emptyDir)).toBeNull()
|
||||
})
|
||||
|
||||
it('parseBitrateKbps should parse number and various string bitrate units', () => {
|
||||
expect(parseBitrateKbps(2_500_000)).toBe(2500)
|
||||
expect(parseBitrateKbps('4500k')).toBe(4500)
|
||||
expect(parseBitrateKbps('4500kbps')).toBe(4500)
|
||||
expect(parseBitrateKbps('12M')).toBe(12000)
|
||||
expect(parseBitrateKbps('1.5Mbps')).toBe(1500)
|
||||
expect(parseBitrateKbps('invalid')).toBe(2500)
|
||||
})
|
||||
|
||||
it('should calculate default bitrates by resolution height and width correctly', () => {
|
||||
@@ -1385,6 +1438,38 @@ describe('TranscodeService', () => {
|
||||
expect(encoder.presetArgs).toEqual(['-preset', 'fast', '-global_quality', '26'])
|
||||
})
|
||||
|
||||
it('selectH264Encoder should select h264_vaapi before h264_qsv on linux when both are available', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
V....D h264_qsv Intel Quick Sync Video H.264
|
||||
V....D h264_vaapi H.264/AVC (VAAPI)
|
||||
`
|
||||
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue('/dev/dri/renderD128')
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'linux')
|
||||
expect(encoder.name).toBe('h264_vaapi')
|
||||
expect(encoder.presetArgs).toEqual(['-compression_level', '4'])
|
||||
})
|
||||
|
||||
it('selectH264Encoder should select h264_amf on win32 when available', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
@@ -1451,6 +1536,197 @@ describe('TranscodeService', () => {
|
||||
expect(encoder.presetArgs).toEqual(['-preset', 'fast', '-crf', '23', '-bf', '0'])
|
||||
})
|
||||
|
||||
it('selectH264Encoder should select h264_vaapi on linux when available and dri device exists', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
V....D h264_vaapi H.264/AVC (VAAPI)
|
||||
V....D h264_amf AMD AMF H.264 Encoder
|
||||
`
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue('/dev/dri/renderD128')
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'linux')
|
||||
expect(encoder.name).toBe('h264_vaapi')
|
||||
expect(encoder.presetArgs).toEqual(['-compression_level', '4'])
|
||||
})
|
||||
|
||||
it('selectH264Encoder should skip h264_vaapi on linux when vaapi device is not found', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
V....D h264_vaapi H.264/AVC (VAAPI)
|
||||
V....D h264_amf AMD AMF H.264 Encoder
|
||||
`
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue(null)
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'linux')
|
||||
expect(encoder.name).toBe('h264_amf')
|
||||
})
|
||||
|
||||
it('selectH264Encoder should skip h264_nvenc and fallback to libx264 when nvenc fails usability probe', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
V....D h264_nvenc NVIDIA NVENC H.264 encoder
|
||||
`
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result?: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (argsArr && argsArr.includes('h264_nvenc')) {
|
||||
cb(new Error('Cannot load libcuda.so.1'))
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'linux')
|
||||
expect(encoder.name).toBe('libx264')
|
||||
})
|
||||
|
||||
it('isEncoderUsable should return true and cache result when probe succeeds', async () => {
|
||||
const execFileMock = vi
|
||||
.mocked(execFile)
|
||||
.mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result?: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const result1 = await transcodeService.isEncoderUsable('h264_nvenc')
|
||||
expect(result1).toBe(true)
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
// Subsequent call should hit cache and not call execFile again
|
||||
const result2 = await transcodeService.isEncoderUsable('h264_nvenc')
|
||||
expect(result2).toBe(true)
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('isEncoderUsable should return false and cache result when probe fails', async () => {
|
||||
const execFileMock = vi
|
||||
.mocked(execFile)
|
||||
.mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result?: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(new Error('Driver init failed'))
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const result1 = await transcodeService.isEncoderUsable('h264_qsv')
|
||||
expect(result1).toBe(false)
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
// Cached call
|
||||
const result2 = await transcodeService.isEncoderUsable('h264_qsv')
|
||||
expect(result2).toBe(false)
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('isEncoderUsable should return false for h264_vaapi when getVaapiDevice returns null without running ffmpeg', async () => {
|
||||
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue(null)
|
||||
const execFileMock = vi.mocked(execFile)
|
||||
|
||||
const result = await transcodeService.isEncoderUsable('h264_vaapi')
|
||||
expect(result).toBe(false)
|
||||
expect(execFileMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('isEncoderUsable should probe vaapi with hw device options when vaapi device exists', async () => {
|
||||
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue('/dev/dri/renderD128')
|
||||
let probeArgs: string[] = []
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
probeArgs = (args as string[]) || []
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result?: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const result = await transcodeService.isEncoderUsable('h264_vaapi')
|
||||
expect(result).toBe(true)
|
||||
expect(probeArgs).toContain('-init_hw_device')
|
||||
expect(probeArgs).toContain('vaapi=accel:/dev/dri/renderD128')
|
||||
expect(probeArgs).toContain('h264_vaapi')
|
||||
})
|
||||
|
||||
it('transcodeVideo with hardwareAcceleration off should use libx264, preset fast, crf 23, -bf 0, maxrate, and yuv420p', async () => {
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
@@ -1713,6 +1989,163 @@ describe('TranscodeService', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('transcodeVideo with hardwareAcceleration auto and vaapi should use init_hw_device, hwupload, rc_mode 3, and omit pix_fmt yuv420p', async () => {
|
||||
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
|
||||
H264_ENCODER_CONFIGS.h264_vaapi,
|
||||
)
|
||||
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue('/dev/dri/renderD128')
|
||||
const loggerSpy = vi.spyOn(logger, 'info')
|
||||
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const outputFile = path.join(tempDir, 'out_vaapi.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 600_000,
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining([
|
||||
'-init_hw_device',
|
||||
'vaapi=accel:/dev/dri/renderD128',
|
||||
'-filter_hw_device',
|
||||
'accel',
|
||||
'-c:v',
|
||||
'h264_vaapi',
|
||||
'-compression_level',
|
||||
'4',
|
||||
'-rc_mode',
|
||||
'3',
|
||||
'-b:v',
|
||||
'497k',
|
||||
'-maxrate',
|
||||
'720k',
|
||||
'-minrate',
|
||||
'249k',
|
||||
]),
|
||||
expect.any(Function),
|
||||
)
|
||||
|
||||
const callArgs = vi.mocked(child_process.execFile).mock.calls[0][1] as string[]
|
||||
expect(callArgs).not.toContain('-pix_fmt')
|
||||
expect(callArgs).not.toContain('yuv420p')
|
||||
|
||||
const filterComplexIdx = callArgs.indexOf('-filter_complex')
|
||||
expect(filterComplexIdx).toBeGreaterThan(-1)
|
||||
expect(callArgs[filterComplexIdx + 1]).toContain('format=nv12,hwupload=extra_hw_frames=64')
|
||||
|
||||
expect(loggerSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
encoder: 'h264_vaapi',
|
||||
hardwareAcceleration: 'auto',
|
||||
vaapiDevice: '/dev/dri/renderD128',
|
||||
}),
|
||||
'Starting video transcoding',
|
||||
)
|
||||
})
|
||||
|
||||
it('transcodeVideo with explicit videoBitrate and vaapi calculates VBR distribution correctly', async () => {
|
||||
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
|
||||
H264_ENCODER_CONFIGS.h264_vaapi,
|
||||
)
|
||||
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue('/dev/dri/renderD128')
|
||||
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const outputFile = path.join(tempDir, 'out_vaapi_custom.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
hardwareAcceleration: 'auto',
|
||||
videoBitrate: '4500k',
|
||||
})
|
||||
|
||||
const callArgs = vi.mocked(child_process.execFile).mock.calls[0][1] as string[]
|
||||
expect(callArgs).toContain('-rc_mode')
|
||||
expect(callArgs).toContain('3')
|
||||
expect(callArgs).toContain('-b:v')
|
||||
expect(callArgs).toContain('3104k')
|
||||
expect(callArgs).toContain('-maxrate')
|
||||
expect(callArgs).toContain('4500k')
|
||||
expect(callArgs).toContain('-minrate')
|
||||
expect(callArgs).toContain('1552k')
|
||||
})
|
||||
|
||||
it('transcodeVideo should throw immediately when ffmpeg fails during hardware transcoding', async () => {
|
||||
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
|
||||
H264_ENCODER_CONFIGS.h264_vaapi,
|
||||
)
|
||||
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue('/dev/dri/renderD128')
|
||||
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
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',
|
||||
})
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const outputFile = path.join(tempDir, 'out_vaapi_fail.mp4')
|
||||
await expect(
|
||||
transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
hardwareAcceleration: 'auto',
|
||||
}),
|
||||
).rejects.toThrow('VAAPI driver error: failed to allocate surface')
|
||||
})
|
||||
|
||||
it('transcodeVideo with threads > 0 should pass -threads to ffmpeg', async () => {
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
|
||||
@@ -13,6 +13,7 @@ import { ulid } from 'ulid'
|
||||
import { promisify } from 'util'
|
||||
import { mapConcurrent } from '../utils/async'
|
||||
import { dataFormatNames } from './dataFormatNames'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
@@ -157,6 +158,10 @@ export const H264_ENCODER_CONFIGS: Record<string, EncoderConfig> = {
|
||||
name: 'h264_qsv',
|
||||
presetArgs: ['-preset', 'fast', '-global_quality', '26'],
|
||||
},
|
||||
h264_vaapi: {
|
||||
name: 'h264_vaapi',
|
||||
presetArgs: ['-compression_level', '4'],
|
||||
},
|
||||
h264_amf: {
|
||||
name: 'h264_amf',
|
||||
presetArgs: ['-quality', 'balanced', '-rc', 'qvbr', '-qvbr_quality_level', '26'],
|
||||
@@ -181,10 +186,53 @@ export function getPlatformEncoderCandidates(
|
||||
return ['h264_nvenc', 'h264_qsv', 'h264_amf']
|
||||
case 'linux':
|
||||
default:
|
||||
return ['h264_nvenc', 'h264_qsv', 'h264_amf']
|
||||
return ['h264_nvenc', 'h264_vaapi', 'h264_qsv', 'h264_amf']
|
||||
}
|
||||
}
|
||||
|
||||
export function getVaapiDevice(driDir = '/dev/dri'): string | null {
|
||||
const envDevice = process.env.SHUMAI_VAAPI_DEVICE || process.env.VAAPI_DEVICE
|
||||
if (envDevice) {
|
||||
return envDevice
|
||||
}
|
||||
|
||||
try {
|
||||
if (!fs.existsSync(driDir)) {
|
||||
return null
|
||||
}
|
||||
const entries = fs.readdirSync(driDir)
|
||||
const renderNodes = entries
|
||||
.filter((entry) => entry.startsWith('renderD') || entry.startsWith('card'))
|
||||
.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))
|
||||
|
||||
if (renderNodes.length > 0) {
|
||||
return path.join(driDir, renderNodes[0])
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function parseBitrateKbps(bitrate: string | number): number {
|
||||
if (typeof bitrate === 'number') {
|
||||
return Math.round(bitrate / 1000)
|
||||
}
|
||||
const clean = bitrate.trim().toLowerCase()
|
||||
if (clean.endsWith('m') || clean.endsWith('mbps')) {
|
||||
return Math.round(parseFloat(clean) * 1000)
|
||||
}
|
||||
if (clean.endsWith('k') || clean.endsWith('kbps')) {
|
||||
return Math.round(parseFloat(clean))
|
||||
}
|
||||
const num = parseFloat(clean)
|
||||
if (Number.isFinite(num)) {
|
||||
return num > 100_000 ? Math.round(num / 1000) : Math.round(num)
|
||||
}
|
||||
return 2500
|
||||
}
|
||||
|
||||
export function getDefaultBitrateBps(height: number, width?: number): number {
|
||||
const longSide = Math.max(width || 0, height)
|
||||
const shortSide = Math.min(width || height, height)
|
||||
@@ -666,9 +714,11 @@ export class TranscodeService {
|
||||
}
|
||||
|
||||
private availableEncodersCache: Set<string> | null = null
|
||||
private usableEncodersCache: Map<string, boolean> = new Map()
|
||||
|
||||
clearEncodersCache(): void {
|
||||
this.availableEncodersCache = null
|
||||
this.usableEncodersCache.clear()
|
||||
}
|
||||
|
||||
async getAvailableEncoders(): Promise<Set<string>> {
|
||||
@@ -721,6 +771,78 @@ export class TranscodeService {
|
||||
}
|
||||
}
|
||||
|
||||
getVaapiDevice(driDir = '/dev/dri'): string | null {
|
||||
return getVaapiDevice(driDir)
|
||||
}
|
||||
|
||||
async isEncoderUsable(encoder: string): Promise<boolean> {
|
||||
const cached = this.usableEncodersCache.get(encoder)
|
||||
if (cached !== undefined) {
|
||||
return cached
|
||||
}
|
||||
|
||||
if (encoder === 'h264_vaapi') {
|
||||
const vaapiDevice = this.getVaapiDevice()
|
||||
if (!vaapiDevice) {
|
||||
this.usableEncodersCache.set(encoder, false)
|
||||
return false
|
||||
}
|
||||
try {
|
||||
await execFileAsync('ffmpeg', [
|
||||
'-loglevel',
|
||||
'error',
|
||||
'-init_hw_device',
|
||||
`vaapi=accel:${vaapiDevice}`,
|
||||
'-filter_hw_device',
|
||||
'accel',
|
||||
'-f',
|
||||
'lavfi',
|
||||
'-i',
|
||||
'color=c=black:s=256x256:d=0.04',
|
||||
'-vf',
|
||||
'format=nv12,hwupload',
|
||||
'-frames:v',
|
||||
'1',
|
||||
'-c:v',
|
||||
'h264_vaapi',
|
||||
'-f',
|
||||
'null',
|
||||
'-',
|
||||
])
|
||||
this.usableEncodersCache.set(encoder, true)
|
||||
return true
|
||||
} catch (err) {
|
||||
logger.debug({ encoder, err }, 'Encoder failed usability probe')
|
||||
this.usableEncodersCache.set(encoder, false)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await execFileAsync('ffmpeg', [
|
||||
'-loglevel',
|
||||
'error',
|
||||
'-f',
|
||||
'lavfi',
|
||||
'-i',
|
||||
'color=c=black:s=256x256:d=0.04',
|
||||
'-frames:v',
|
||||
'1',
|
||||
'-c:v',
|
||||
encoder,
|
||||
'-f',
|
||||
'null',
|
||||
'-',
|
||||
])
|
||||
this.usableEncodersCache.set(encoder, true)
|
||||
return true
|
||||
} catch (err) {
|
||||
logger.debug({ encoder, err }, 'Encoder failed usability probe')
|
||||
this.usableEncodersCache.set(encoder, false)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async selectH264Encoder(
|
||||
hardwareAcceleration?: 'off' | 'auto',
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
@@ -733,6 +855,10 @@ export class TranscodeService {
|
||||
const candidates = getPlatformEncoderCandidates(platform)
|
||||
for (const enc of candidates) {
|
||||
if (available.has(enc) && H264_ENCODER_CONFIGS[enc]) {
|
||||
const usable = await this.isEncoderUsable(enc)
|
||||
if (!usable) {
|
||||
continue
|
||||
}
|
||||
return H264_ENCODER_CONFIGS[enc]
|
||||
}
|
||||
}
|
||||
@@ -748,8 +874,29 @@ 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
|
||||
|
||||
logger.info(
|
||||
{
|
||||
encoder: encoder.name,
|
||||
hardwareAcceleration: params.hardwareAcceleration ?? 'off',
|
||||
inputFile: params.inputFile,
|
||||
outputFile: params.outputFile,
|
||||
vaapiDevice,
|
||||
},
|
||||
'Starting video transcoding',
|
||||
)
|
||||
|
||||
let filterComplex: string
|
||||
const args: string[] = ['-i', params.inputFile]
|
||||
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'`
|
||||
|
||||
if (params.overlayFile) {
|
||||
@@ -762,6 +909,9 @@ export class TranscodeService {
|
||||
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]')
|
||||
@@ -795,7 +945,6 @@ export class TranscodeService {
|
||||
args.push('-map', '0:a?')
|
||||
}
|
||||
|
||||
const encoder = await this.selectH264Encoder(params.hardwareAcceleration)
|
||||
args.push('-c:v', encoder.name)
|
||||
if (encoder.presetArgs.length > 0) {
|
||||
args.push(...encoder.presetArgs)
|
||||
@@ -814,6 +963,31 @@ export class TranscodeService {
|
||||
const targetKbps = Math.max(50, Math.round(targetBps / 1000))
|
||||
args.push('-b:v', `${targetKbps}k`)
|
||||
}
|
||||
} else if (isVaapi) {
|
||||
let maxKbps: number
|
||||
if (params.videoBitrate) {
|
||||
maxKbps = parseBitrateKbps(params.videoBitrate)
|
||||
} else {
|
||||
const { maxrate } = calculateMaxBitrate(
|
||||
params.height,
|
||||
params.width,
|
||||
params.sourceVideoBitrate,
|
||||
params.frameRate,
|
||||
)
|
||||
maxKbps = parseInt(maxrate, 10)
|
||||
}
|
||||
const targetKbps = Math.max(25, Math.ceil(maxKbps / 1.45))
|
||||
const minKbps = Math.max(10, Math.round(targetKbps / 2))
|
||||
args.push(
|
||||
'-rc_mode',
|
||||
'3',
|
||||
'-b:v',
|
||||
`${targetKbps}k`,
|
||||
'-maxrate',
|
||||
`${maxKbps}k`,
|
||||
'-minrate',
|
||||
`${minKbps}k`,
|
||||
)
|
||||
} else {
|
||||
if (params.videoBitrate) {
|
||||
args.push('-b:v', params.videoBitrate)
|
||||
@@ -828,7 +1002,9 @@ export class TranscodeService {
|
||||
}
|
||||
}
|
||||
|
||||
args.push('-pix_fmt', 'yuv420p')
|
||||
if (!isVaapi) {
|
||||
args.push('-pix_fmt', 'yuv420p')
|
||||
}
|
||||
|
||||
if (isSourceHdr && isHdrOutput) {
|
||||
const isHlg = params.sourceHdrType === 'hlg' || params.sourceColorTransfer === 'arib-std-b67'
|
||||
|
||||
Reference in New Issue
Block a user