feat(transcode): add hardware-accelerated video transcoding support (#352)

* feat(transcode): add hardware-accelerated video transcoding support

* feat(transcode): use encoder quality modes and source-capped maxrate for video transcode

* fix(transcode): scale max bitrate for downsampled preview framerates

* fix(transcode): propagate videoBitRate in getMediaInfoActivity and update auto description
This commit is contained in:
Yiling-J
2026-08-26 16:28:14 +08:00
committed by GitHub
parent 7b1428bf51
commit 8f55ba1d37
29 changed files with 1272 additions and 11 deletions
+626 -1
View File
@@ -1,5 +1,13 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { transcodeService, calculatePreviewDimensions } from './transcode'
import {
transcodeService,
calculatePreviewDimensions,
getPlatformEncoderCandidates,
getDefaultBitrate,
getDefaultBitrateBps,
calculateMaxBitrate,
H264_ENCODER_CONFIGS,
} from './transcode'
import { s3Service } from '@shumai/core/src/s3/s3'
import * as path from 'path'
import * as child_process from 'child_process'
@@ -109,6 +117,118 @@ describe('TranscodeService', () => {
)
})
it('should extract videoBitRate from stream bit_rate or tags or fallback correctly', async () => {
/* eslint-disable @typescript-eslint/naming-convention */
// 1. Direct video stream bit_rate
const output1 = JSON.stringify({
format: { duration: '10', bit_rate: '2000000' },
streams: [
{ codec_type: 'video', width: 1920, height: 1080, bit_rate: '1800000' },
{ codec_type: 'audio', bit_rate: '128000' },
],
})
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: output1, stderr: '' })
}
return {} as ReturnType<typeof child_process.execFile>
},
)
const info1 = await transcodeService.getVideoInfo('test1.mp4')
expect(info1.videoBitRate).toBe(1800000)
// 2. Stream BPS tag
const output2 = JSON.stringify({
format: { duration: '10', bit_rate: '2000000' },
streams: [
{ codec_type: 'video', width: 1920, height: 1080, tags: { BPS: '1500000' } },
{ codec_type: 'audio', bit_rate: '128000' },
],
})
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: output2, stderr: '' })
}
return {} as ReturnType<typeof child_process.execFile>
},
)
const info2 = await transcodeService.getVideoInfo('test2.mp4')
expect(info2.videoBitRate).toBe(1500000)
// 3. Stream NUMBER_OF_BYTES tag
const output3 = JSON.stringify({
format: { duration: '10', bit_rate: '2000000' },
streams: [
{ codec_type: 'video', width: 1920, height: 1080, tags: { NUMBER_OF_BYTES: '1000000' } },
{ codec_type: 'audio', bit_rate: '128000' },
],
})
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: output3, stderr: '' })
}
return {} as ReturnType<typeof child_process.execFile>
},
)
const info3 = await transcodeService.getVideoInfo('test3.mp4')
expect(info3.videoBitRate).toBe(800000) // (1,000,000 * 8) / 10 = 800,000
// 4. Fallback totalBitrate - audioBitrate
const output4 = JSON.stringify({
format: { duration: '10', bit_rate: '1000000' },
streams: [
{ codec_type: 'video', width: 1920, height: 1080 },
{ codec_type: 'audio', bit_rate: '128000' },
],
})
/* eslint-enable @typescript-eslint/naming-convention */
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: output4, stderr: '' })
}
return {} as ReturnType<typeof child_process.execFile>
},
)
const info4 = await transcodeService.getVideoInfo('test4.mp4')
expect(info4.videoBitRate).toBe(872000) // 1,000,000 - 128,000 = 872,000
})
it('should get image info using sharp', async () => {
const mockMetadata = {
width: 800,
@@ -897,4 +1017,509 @@ describe('TranscodeService', () => {
})
})
})
describe('Hardware Acceleration & Encoder Resolution', () => {
beforeEach(() => {
transcodeService.clearEncodersCache()
})
afterEach(() => {
vi.restoreAllMocks()
})
it('should return platform candidates correctly', () => {
expect(getPlatformEncoderCandidates('darwin')).toEqual([
'h264_videotoolbox',
'h264_nvenc',
'h264_qsv',
'h264_amf',
])
expect(getPlatformEncoderCandidates('win32')).toEqual(['h264_nvenc', 'h264_qsv', 'h264_amf'])
expect(getPlatformEncoderCandidates('linux')).toEqual(['h264_nvenc', 'h264_qsv', 'h264_amf'])
})
it('should calculate default bitrates by resolution height and width correctly', () => {
expect(getDefaultBitrateBps(2160, 3840)).toBe(12_000_000)
expect(getDefaultBitrate(2160, 3840)).toBe('12000k')
expect(getDefaultBitrate(1080, 1920)).toBe('4500k')
expect(getDefaultBitrate(720, 1280)).toBe('2500k')
expect(getDefaultBitrate(540, 960)).toBe('1200k')
expect(getDefaultBitrate(360, 640)).toBe('800k')
expect(getDefaultBitrate(180, 320)).toBe('100k')
expect(getDefaultBitrate(100, 100)).toBe('100k')
})
it('calculateMaxBitrate should cap bitrate based on sourceVideoBitrate, ceiling, and targetFps', () => {
// Default without source bitrate
expect(calculateMaxBitrate(720, 1280)).toEqual({
maxrate: '2500k',
bufsize: '5000k',
})
// With low source bitrate (600k * 1.2 = 720k)
expect(calculateMaxBitrate(720, 1280, 600_000)).toEqual({
maxrate: '720k',
bufsize: '1440k',
})
// With high source bitrate (3000k * 1.2 = 3600k, capped at 2500k)
expect(calculateMaxBitrate(720, 1280, 3_000_000)).toEqual({
maxrate: '2500k',
bufsize: '5000k',
})
// With downsampled targetFps (180p preview @ 0.78 fps: 100k * (0.78/24) = 3.25k -> capped at min 50k)
expect(calculateMaxBitrate(180, 320, 600_000, 0.78)).toEqual({
maxrate: '50k',
bufsize: '100k',
})
// With downsampled targetFps string (180p preview @ 24 fps)
expect(calculateMaxBitrate(180, 320, 600_000, 24)).toEqual({
maxrate: '100k',
bufsize: '200k',
})
// With extremely low source bitrate without targetFps (50k * 1.2 = 60k, minimum floor 100k)
expect(calculateMaxBitrate(720, 1280, 50_000)).toEqual({
maxrate: '100k',
bufsize: '200k',
})
})
it('selectH264Encoder should return libx264 when hardwareAcceleration is off', async () => {
const encoder = await transcodeService.selectH264Encoder('off')
expect(encoder).toEqual(H264_ENCODER_CONFIGS.libx264)
expect(child_process.execFile).not.toHaveBeenCalledWith(
'ffmpeg',
['-encoders'],
expect.any(Function),
)
})
it('selectH264Encoder should select h264_videotoolbox on darwin when available', async () => {
const mockEncodersOutput = `
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
V....D h264_videotoolbox VideoToolbox 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>
},
)
const encoder = await transcodeService.selectH264Encoder('auto', 'darwin')
expect(encoder.name).toBe('h264_videotoolbox')
expect(encoder.presetArgs).toEqual(['-q:v', '74'])
})
it('selectH264Encoder should select h264_nvenc on linux when available', 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
V....D h264_qsv Intel Quick Sync Video H.264
`
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_nvenc')
expect(encoder.presetArgs).toEqual([
'-preset',
'p4',
'-rc:v',
'vbr',
'-cq:v',
'26',
'-b:v',
'0',
])
})
it('selectH264Encoder should select h264_qsv on linux when nvenc is not 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
`
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_qsv')
expect(encoder.presetArgs).toEqual(['-preset', 'fast', '-global_quality', '26'])
})
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
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>
},
)
const encoder = await transcodeService.selectH264Encoder('auto', 'win32')
expect(encoder.name).toBe('h264_amf')
expect(encoder.presetArgs).toEqual([
'-quality',
'balanced',
'-rc',
'qvbr',
'-qvbr_quality_level',
'26',
])
})
it('selectH264Encoder should fallback to libx264 when no hw encoder is in ffmpeg build', async () => {
const mockEncodersOutput = `
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
`
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('libx264')
expect(encoder.presetArgs).toEqual(['-preset', 'fast', '-crf', '26'])
})
it('transcodeVideo with hardwareAcceleration off should use libx264, preset fast, crf 26, maxrate, and yuv420p', async () => {
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_off.mp4')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
hardwareAcceleration: 'off',
sourceVideoBitrate: 600_000,
})
expect(child_process.execFile).toHaveBeenCalledWith(
'ffmpeg',
expect.arrayContaining([
'-c:v',
'libx264',
'-preset',
'fast',
'-crf',
'26',
'-maxrate',
'720k',
'-bufsize',
'1440k',
'-pix_fmt',
'yuv420p',
]),
expect.any(Function),
)
})
it('transcodeVideo with hardwareAcceleration auto and videotoolbox should use -q:v 74 and -maxrate', async () => {
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
H264_ENCODER_CONFIGS.h264_videotoolbox,
)
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_vt.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([
'-c:v',
'h264_videotoolbox',
'-q:v',
'74',
'-maxrate',
'720k',
'-bufsize',
'1440k',
'-pix_fmt',
'yuv420p',
]),
expect.any(Function),
)
})
it('transcodeVideo with hardwareAcceleration auto and nvenc should use -preset p4, -rc:v vbr, -cq:v 26, -b:v 0, and -maxrate', async () => {
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
H264_ENCODER_CONFIGS.h264_nvenc,
)
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_nvenc.mp4')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1920,
height: 1080,
hardwareAcceleration: 'auto',
sourceVideoBitrate: 1_000_000,
})
expect(child_process.execFile).toHaveBeenCalledWith(
'ffmpeg',
expect.arrayContaining([
'-c:v',
'h264_nvenc',
'-preset',
'p4',
'-rc:v',
'vbr',
'-cq:v',
'26',
'-b:v',
'0',
'-maxrate',
'1200k',
'-bufsize',
'2400k',
'-pix_fmt',
'yuv420p',
]),
expect.any(Function),
)
})
it('transcodeVideo with hardwareAcceleration auto and amf should use -quality balanced, -rc qvbr, -qvbr_quality_level 26, and -maxrate', async () => {
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
H264_ENCODER_CONFIGS.h264_amf,
)
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_amf.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([
'-c:v',
'h264_amf',
'-quality',
'balanced',
'-rc',
'qvbr',
'-qvbr_quality_level',
'26',
'-maxrate',
'720k',
'-bufsize',
'1440k',
'-pix_fmt',
'yuv420p',
]),
expect.any(Function),
)
})
it('transcodeVideo with explicit videoBitrate should use -b:v directly', async () => {
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_explicit.mp4')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
hardwareAcceleration: 'off',
videoBitrate: '1500k',
})
expect(child_process.execFile).toHaveBeenCalledWith(
'ffmpeg',
expect.arrayContaining([
'-c:v',
'libx264',
'-preset',
'fast',
'-crf',
'26',
'-b:v',
'1500k',
'-pix_fmt',
'yuv420p',
]),
expect.any(Function),
)
expect(child_process.execFile).not.toHaveBeenCalledWith(
'ffmpeg',
expect.arrayContaining(['-maxrate']),
expect.any(Function),
)
})
})
})
+201 -1
View File
@@ -91,6 +91,7 @@ export interface MediaMetadata {
originalHeight: number
duration: number
bitRate: number
videoBitRate?: number
frameRate: number
totalFrames: number
startTimecode?: string
@@ -111,6 +112,113 @@ export interface TranscodeVideoParams {
frameRate?: number | string
disableAudio?: boolean
overlayFile?: string
hardwareAcceleration?: 'off' | 'auto'
videoBitrate?: string
sourceVideoBitrate?: number
}
export interface EncoderConfig {
name: string
presetArgs: string[]
}
export const H264_ENCODER_CONFIGS: Record<string, EncoderConfig> = {
h264_nvenc: {
name: 'h264_nvenc',
presetArgs: ['-preset', 'p4', '-rc:v', 'vbr', '-cq:v', '26', '-b:v', '0'],
},
h264_qsv: {
name: 'h264_qsv',
presetArgs: ['-preset', 'fast', '-global_quality', '26'],
},
h264_amf: {
name: 'h264_amf',
presetArgs: ['-quality', 'balanced', '-rc', 'qvbr', '-qvbr_quality_level', '26'],
},
h264_videotoolbox: {
name: 'h264_videotoolbox',
presetArgs: ['-q:v', '74'],
},
libx264: {
name: 'libx264',
presetArgs: ['-preset', 'fast', '-crf', '26'],
},
}
export function getPlatformEncoderCandidates(
platform: NodeJS.Platform = process.platform,
): string[] {
switch (platform) {
case 'darwin':
return ['h264_videotoolbox', 'h264_nvenc', 'h264_qsv', 'h264_amf']
case 'win32':
return ['h264_nvenc', 'h264_qsv', 'h264_amf']
case 'linux':
default:
return ['h264_nvenc', 'h264_qsv', 'h264_amf']
}
}
export function getDefaultBitrateBps(height: number, width?: number): number {
const longSide = Math.max(width || 0, height)
const shortSide = Math.min(width || height, height)
const effectiveHeight = shortSide > 0 ? shortSide : height
if (effectiveHeight >= 2160 || longSide >= 3840) return 12_000_000
if (effectiveHeight >= 1080 || longSide >= 1920) return 4_500_000
if (effectiveHeight >= 720 || longSide >= 1280) return 2_500_000
if (effectiveHeight >= 540 || longSide >= 960) return 1_200_000
if (effectiveHeight >= 360 || longSide >= 640) return 800_000
return 100_000
}
export function getDefaultBitrate(height: number, width?: number): string {
const bps = getDefaultBitrateBps(height, width)
return `${Math.round(bps / 1000)}k`
}
export function calculateMaxBitrate(
targetHeight: number,
targetWidth?: number,
sourceVideoBitrate?: number,
targetFps?: number | string,
): { maxrate: string; bufsize: string } {
let configuredMaxBps = getDefaultBitrateBps(targetHeight, targetWidth)
// If frame rate is downsampled (e.g. 180p preview with < 24 fps), scale the bitrate ceiling proportionally
if (targetFps) {
let parsedFps: number | undefined
if (typeof targetFps === 'number') {
parsedFps = targetFps
} else {
const parts = targetFps.split('/')
if (parts.length === 2) {
parsedFps = parseFloat(parts[0]) / parseFloat(parts[1])
} else {
parsedFps = parseFloat(targetFps)
}
}
if (Number.isFinite(parsedFps) && parsedFps > 0 && parsedFps < 24) {
const fpsRatio = Math.max(0.1, parsedFps / 24)
configuredMaxBps = Math.max(50_000, Math.round(configuredMaxBps * fpsRatio))
}
}
let effectiveMaxBps =
sourceVideoBitrate && sourceVideoBitrate > 0
? Math.min(configuredMaxBps, Math.round(sourceVideoBitrate * 1.2))
: configuredMaxBps
const minFloor = targetFps ? 50_000 : 100_000
effectiveMaxBps = Math.max(minFloor, effectiveMaxBps)
const maxrateKbps = Math.max(50, Math.round(effectiveMaxBps / 1000))
const bufsizeKbps = maxrateKbps * 2
return {
maxrate: `${maxrateKbps}k`,
bufsize: `${bufsizeKbps}k`,
}
}
export interface ExtractVideoFramesParams {
@@ -295,11 +403,38 @@ export class TranscodeService {
}
const startTimecode = videoStream.tags?.timecode || info.format?.tags?.timecode
let videoBitRate: number | undefined
if (videoStream.bit_rate && parseInt(videoStream.bit_rate, 10) > 0) {
videoBitRate = parseInt(videoStream.bit_rate, 10)
} else {
const bpsTag = videoStream.tags?.BPS || videoStream.tags?.['BPS-eng']
if (bpsTag && parseInt(bpsTag, 10) > 0) {
videoBitRate = parseInt(bpsTag, 10)
} else {
const bytesTag =
videoStream.tags?.NUMBER_OF_BYTES || videoStream.tags?.['NUMBER_OF_BYTES-eng']
if (bytesTag && duration > 0) {
videoBitRate = Math.round((parseInt(bytesTag, 10) * 8) / duration)
} else {
const totalBitrate = parseFloat(info.format.bit_rate)
if (Number.isFinite(totalBitrate) && totalBitrate > 0) {
const audioBitrate = audioStream?.bit_rate
? parseFloat(audioStream.bit_rate)
: audioStream
? 128_000
: 0
videoBitRate = Math.max(100_000, Math.round(totalBitrate - audioBitrate))
}
}
}
}
return {
originalWidth: videoStream.width,
originalHeight: videoStream.height,
duration,
bitRate: parseFloat(info.format.bit_rate),
videoBitRate,
frameRate: fps || 30,
totalFrames: totalFrames || 0,
startTimecode,
@@ -373,6 +508,53 @@ export class TranscodeService {
}
}
private availableEncodersCache: Set<string> | null = null
clearEncodersCache(): void {
this.availableEncodersCache = null
}
async getAvailableEncoders(): Promise<Set<string>> {
if (this.availableEncodersCache) {
return this.availableEncodersCache
}
try {
const { stdout } = await execFileAsync('ffmpeg', ['-encoders'])
const encoders = new Set<string>()
const lines = stdout.split('\n')
for (const line of lines) {
const match = line.match(/^\s*[A-Z.]{6}\s+([a-zA-Z0-9_-]+)/)
if (match) {
encoders.add(match[1])
}
}
this.availableEncodersCache = encoders
return encoders
} catch (err) {
console.warn('Failed to probe ffmpeg encoders:', err)
return new Set<string>()
}
}
async selectH264Encoder(
hardwareAcceleration?: 'off' | 'auto',
platform: NodeJS.Platform = process.platform,
): Promise<EncoderConfig> {
if (hardwareAcceleration !== 'auto') {
return H264_ENCODER_CONFIGS.libx264
}
const available = await this.getAvailableEncoders()
const candidates = getPlatformEncoderCandidates(platform)
for (const enc of candidates) {
if (available.has(enc) && H264_ENCODER_CONFIGS[enc]) {
return H264_ENCODER_CONFIGS[enc]
}
}
return H264_ENCODER_CONFIGS.libx264
}
async transcodeVideo(params: TranscodeVideoParams): Promise<void> {
let filterComplex: string
const args: string[] = ['-i', params.inputFile]
@@ -420,7 +602,25 @@ export class TranscodeService {
args.push('-map', '0:a?')
}
args.push('-c:v', 'libx264', '-preset', 'fast', '-crf', '26')
const encoder = await this.selectH264Encoder(params.hardwareAcceleration)
args.push('-c:v', encoder.name)
if (encoder.presetArgs.length > 0) {
args.push(...encoder.presetArgs)
}
if (params.videoBitrate) {
args.push('-b:v', params.videoBitrate)
} else {
const { maxrate, bufsize } = calculateMaxBitrate(
params.height,
params.width,
params.sourceVideoBitrate,
params.frameRate,
)
args.push('-maxrate', maxrate, '-bufsize', bufsize)
}
args.push('-pix_fmt', 'yuv420p')
if (!params.disableAudio) {
args.push('-c:a', 'aac', '-b:a', '128k')