From 8f55ba1d3740b107f172163a29ee281ed93e78c6 Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Wed, 26 Aug 2026 16:28:14 +0800 Subject: [PATCH] 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 --- packages/api/src/team.test.ts | 15 + packages/core/src/team/team.test.ts | 3 +- packages/core/src/team/team.ts | 8 +- packages/core/src/transcode/transcode.test.ts | 627 +++++++++++++++++- packages/core/src/transcode/transcode.ts | 202 +++++- packages/core/src/upload/upload.test.ts | 1 + packages/core/src/upload/upload.ts | 2 + packages/db/src/prisma-json-types.ts | 4 + packages/dtos/src/team.ts | 10 + .../src/activities/transcode.test.ts | 12 +- .../transcode/src/activities/transcode.ts | 5 + packages/transcode/src/transcoder.ts | 7 + .../src/workflows/transcode-video.test.ts | 80 ++- .../src/workflows/transcode-video.ts | 2 + packages/webui/messages/en.json | 5 + packages/webui/messages/zh.json | 5 + packages/webui/paraglide/messages/_index.d.ts | 5 + packages/webui/paraglide/messages/_index.js | 5 + .../messages/hardware_acceleration.d.ts | 16 + .../messages/hardware_acceleration.js | 29 + .../messages/hardware_acceleration_auto.d.ts | 16 + .../messages/hardware_acceleration_auto.js | 29 + ...ardware_acceleration_auto_description.d.ts | 16 + .../hardware_acceleration_auto_description.js | 29 + .../messages/hardware_acceleration_off.d.ts | 16 + .../messages/hardware_acceleration_off.js | 29 + ...hardware_acceleration_off_description.d.ts | 16 + .../hardware_acceleration_off_description.js | 29 + .../routes/teams/$teamId/settings.lazy.tsx | 60 +- 29 files changed, 1272 insertions(+), 11 deletions(-) create mode 100644 packages/webui/paraglide/messages/hardware_acceleration.d.ts create mode 100644 packages/webui/paraglide/messages/hardware_acceleration.js create mode 100644 packages/webui/paraglide/messages/hardware_acceleration_auto.d.ts create mode 100644 packages/webui/paraglide/messages/hardware_acceleration_auto.js create mode 100644 packages/webui/paraglide/messages/hardware_acceleration_auto_description.d.ts create mode 100644 packages/webui/paraglide/messages/hardware_acceleration_auto_description.js create mode 100644 packages/webui/paraglide/messages/hardware_acceleration_off.d.ts create mode 100644 packages/webui/paraglide/messages/hardware_acceleration_off.js create mode 100644 packages/webui/paraglide/messages/hardware_acceleration_off_description.d.ts create mode 100644 packages/webui/paraglide/messages/hardware_acceleration_off_description.js diff --git a/packages/api/src/team.test.ts b/packages/api/src/team.test.ts index e864bff7..da6fef78 100644 --- a/packages/api/src/team.test.ts +++ b/packages/api/src/team.test.ts @@ -245,6 +245,21 @@ describe('team api', () => { expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'transcode.videoStrategy', 'all') }) + it('PATCH /teams/:teamId/settings updates transcode.hardwareAcceleration', async () => { + mockUpdateSettings.mockResolvedValue({ transcode: { hardwareAcceleration: 'auto' } }) + + const res = await app.request('/teams/t1/settings', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ key: 'transcode.hardwareAcceleration', value: 'auto' }), + }) + + expect(res.status).toBe(200) + const data = await res.json() + expect(data.transcode.hardwareAcceleration).toBe('auto') + expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'transcode.hardwareAcceleration', 'auto') + }) + it('GET /teams/:teamId/user-metadata returns all metadata for the user in the team', async () => { mockListUserMetadata.mockResolvedValue([ { key: 'key1', value: 'value1' }, diff --git a/packages/core/src/team/team.test.ts b/packages/core/src/team/team.test.ts index 5412de49..528518a3 100644 --- a/packages/core/src/team/team.test.ts +++ b/packages/core/src/team/team.test.ts @@ -371,11 +371,12 @@ describe('TeamService', () => { expect(newSettings).toEqual({ theme: 'dark', semanticSearchEnabled: false }) await teamService.updateSettings(team.id, 'transcode.videoStrategy', 'all') + await teamService.updateSettings(team.id, 'transcode.hardwareAcceleration', 'auto') const finalSettings = await teamService.getSettings(team.id) expect(finalSettings).toEqual({ theme: 'dark', - transcode: { videoStrategy: 'all' }, + transcode: { videoStrategy: 'all', hardwareAcceleration: 'auto' }, semanticSearchEnabled: false, }) }) diff --git a/packages/core/src/team/team.ts b/packages/core/src/team/team.ts index 41b86660..c7a6d2bb 100644 --- a/packages/core/src/team/team.ts +++ b/packages/core/src/team/team.ts @@ -31,7 +31,7 @@ export class TeamService { data: { name: 'Default Team', settings: { - transcode: { videoStrategy: 'best_match' }, + transcode: { videoStrategy: 'best_match', hardwareAcceleration: 'off' }, }, sandbox: { create: {} }, }, @@ -318,6 +318,12 @@ export class TeamService { } settings.transcode.videoStrategy = value delete settings['transcode.videoStrategy'] + } else if (key === 'transcode.hardwareAcceleration') { + if (!settings.transcode) { + settings.transcode = {} + } + settings.transcode.hardwareAcceleration = value + delete settings['transcode.hardwareAcceleration'] } else { settings[key] = value } diff --git a/packages/core/src/transcode/transcode.test.ts b/packages/core/src/transcode/transcode.test.ts index 293277c3..8244a6e9 100644 --- a/packages/core/src/transcode/transcode.test.ts +++ b/packages/core/src/transcode/transcode.test.ts @@ -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 => { + 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 + }, + ) + 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 => { + 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 + }, + ) + 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 => { + 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 + }, + ) + 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 => { + 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 + }, + ) + 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 => { + 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 + }, + ) + + 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 => { + 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 + }, + ) + + 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 => { + 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 + }, + ) + + 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 => { + 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 + }, + ) + + 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 => { + 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 + }, + ) + + 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 => { + const cb = callback as ( + err: Error | null, + result: { stdout: string; stderr: string }, + ) => void + if (typeof cb === 'function') { + cb(null, { stdout: '', stderr: '' }) + } + return {} as ReturnType + }, + ) + + 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 => { + const cb = callback as ( + err: Error | null, + result: { stdout: string; stderr: string }, + ) => void + if (typeof cb === 'function') { + cb(null, { stdout: '', stderr: '' }) + } + return {} as ReturnType + }, + ) + + 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 => { + const cb = callback as ( + err: Error | null, + result: { stdout: string; stderr: string }, + ) => void + if (typeof cb === 'function') { + cb(null, { stdout: '', stderr: '' }) + } + return {} as ReturnType + }, + ) + + 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 => { + const cb = callback as ( + err: Error | null, + result: { stdout: string; stderr: string }, + ) => void + if (typeof cb === 'function') { + cb(null, { stdout: '', stderr: '' }) + } + return {} as ReturnType + }, + ) + + 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 => { + const cb = callback as ( + err: Error | null, + result: { stdout: string; stderr: string }, + ) => void + if (typeof cb === 'function') { + cb(null, { stdout: '', stderr: '' }) + } + return {} as ReturnType + }, + ) + + 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), + ) + }) + }) }) diff --git a/packages/core/src/transcode/transcode.ts b/packages/core/src/transcode/transcode.ts index 56906350..7e4026f2 100644 --- a/packages/core/src/transcode/transcode.ts +++ b/packages/core/src/transcode/transcode.ts @@ -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 = { + 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 | null = null + + clearEncodersCache(): void { + this.availableEncodersCache = null + } + + async getAvailableEncoders(): Promise> { + if (this.availableEncodersCache) { + return this.availableEncodersCache + } + try { + const { stdout } = await execFileAsync('ffmpeg', ['-encoders']) + const encoders = new Set() + 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() + } + } + + async selectH264Encoder( + hardwareAcceleration?: 'off' | 'auto', + platform: NodeJS.Platform = process.platform, + ): Promise { + 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 { 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') diff --git a/packages/core/src/upload/upload.test.ts b/packages/core/src/upload/upload.test.ts index a3426d14..e2660d34 100644 --- a/packages/core/src/upload/upload.test.ts +++ b/packages/core/src/upload/upload.test.ts @@ -190,6 +190,7 @@ describe('UploadService', () => { projectId: projectId, transcode: { videoStrategy: 'best_match', + hardwareAcceleration: 'off', sprite: true, poster: true, }, diff --git a/packages/core/src/upload/upload.ts b/packages/core/src/upload/upload.ts index 28f19906..d0e3c6dd 100644 --- a/packages/core/src/upload/upload.ts +++ b/packages/core/src/upload/upload.ts @@ -303,9 +303,11 @@ export class UploadService { const settings = team.settings as PrismaJson.Settings | null if (isVideo) { const strategy = settings?.transcode?.videoStrategy || 'best_match' + const hardwareAcceleration = settings?.transcode?.hardwareAcceleration || 'off' // eslint-disable-next-line @typescript-eslint/no-explicit-any await new VideoTranscoder(tx as any, asset.id, team.id, projectId) .setStrategy(strategy) + .setHardwareAcceleration(hardwareAcceleration) .withSprite() .withPoster() .submit() diff --git a/packages/db/src/prisma-json-types.ts b/packages/db/src/prisma-json-types.ts index dcf45650..440ff2c4 100644 --- a/packages/db/src/prisma-json-types.ts +++ b/packages/db/src/prisma-json-types.ts @@ -46,6 +46,7 @@ declare global { // Team Settings // ---------------------------------------------------------------------- export type VideoTranscodeStrategy = 'best_match' | 'all' + export type HardwareAcceleration = 'off' | 'auto' // ---------------------------------------------------------------------- // Collection Filter @@ -54,6 +55,7 @@ declare global { export interface TranscodeSettings { videoStrategy: VideoTranscodeStrategy + hardwareAcceleration?: HardwareAcceleration } export interface Settings { @@ -103,6 +105,7 @@ declare global { hasAudio: boolean duration: number bitRate: number + videoBitRate?: number frameRate: number totalFrames: number startTimecode: string @@ -290,6 +293,7 @@ declare global { export interface TaskSpec { videoStrategy?: VideoTranscodeStrategy + hardwareAcceleration?: HardwareAcceleration thumbnail?: boolean sprite?: boolean poster?: boolean diff --git a/packages/dtos/src/team.ts b/packages/dtos/src/team.ts index e8d00537..e70b4d1c 100644 --- a/packages/dtos/src/team.ts +++ b/packages/dtos/src/team.ts @@ -74,11 +74,21 @@ export const VideoTranscodeStrategy = { export type VideoTranscodeStrategy = (typeof VideoTranscodeStrategy)[keyof typeof VideoTranscodeStrategy] +export const HardwareAcceleration = { + off: 'off', + auto: 'auto', +} as const +export type HardwareAcceleration = (typeof HardwareAcceleration)[keyof typeof HardwareAcceleration] + export const updateTeamSettingsRequestSchema = z.union([ z.object({ key: z.literal('transcode.videoStrategy'), value: z.nativeEnum(VideoTranscodeStrategy), }), + z.object({ + key: z.literal('transcode.hardwareAcceleration'), + value: z.nativeEnum(HardwareAcceleration), + }), ]) export type UpdateTeamSettingsRequest = z.infer diff --git a/packages/transcode/src/activities/transcode.test.ts b/packages/transcode/src/activities/transcode.test.ts index 9f643c0b..dc2a7171 100644 --- a/packages/transcode/src/activities/transcode.test.ts +++ b/packages/transcode/src/activities/transcode.test.ts @@ -172,6 +172,7 @@ describe('Transcode Activities', () => { originalHeight: 1080, duration: 10, bitRate: 1000, + videoBitRate: 850000, frameRate: 30, totalFrames: 300, hasAudio: true, @@ -193,6 +194,7 @@ describe('Transcode Activities', () => { expect(transcodeService.getVideoInfo).toHaveBeenCalledWith('/tmp/v.mp4') expect(result.duration).toBe(10) expect(result.metadata?.originalWidth).toBe(1920) + expect(result.metadata?.videoBitRate).toBe(850000) expect(result.metadata?.videoCodec).toBe('Advanced Video Coding') expect(result.metadata?.audioCodec).toBe('MPEG-4 Audio') expect(result.metadata?.audioChannels).toBe(2) @@ -590,9 +592,17 @@ describe('Transcode Activities', () => { videoSpec: { resolution: '720p', width: 1280, height: 720 }, duration: 10, originalFps: 30, + hardwareAcceleration: 'auto', + sourceVideoBitrate: 600_000, }) - expect(transcodeService.transcodeVideo).toHaveBeenCalled() + expect(transcodeService.transcodeVideo).toHaveBeenCalledWith( + expect.objectContaining({ + inputFile: '/tmp/v.mp4', + hardwareAcceleration: 'auto', + sourceVideoBitrate: 600_000, + }), + ) }) it('should call transcodeService.takeScreenshots', async () => { diff --git a/packages/transcode/src/activities/transcode.ts b/packages/transcode/src/activities/transcode.ts index f5ac3113..6fb23ed3 100644 --- a/packages/transcode/src/activities/transcode.ts +++ b/packages/transcode/src/activities/transcode.ts @@ -104,6 +104,7 @@ export async function getMediaInfoActivity(params: { originalHeight: info.originalHeight, duration: info.duration, bitRate: info.bitRate, + videoBitRate: info.videoBitRate, frameRate: info.frameRate, totalFrames: info.totalFrames, startTimecode: info.startTimecode || '00:00:00:00', @@ -220,6 +221,8 @@ export interface VideoActivityParams { videoSpec: PrismaJson.VideoTranscode duration: number originalFps: number + hardwareAcceleration?: PrismaJson.HardwareAcceleration + sourceVideoBitrate?: number } export async function transcodeVideoActivity( @@ -262,6 +265,8 @@ export async function transcodeVideoActivity( height: params.videoSpec.height, frameRate: targetFps || undefined, disableAudio, + hardwareAcceleration: params.hardwareAcceleration, + sourceVideoBitrate: params.sourceVideoBitrate, }) const stat = fs.statSync(outputFile) diff --git a/packages/transcode/src/transcoder.ts b/packages/transcode/src/transcoder.ts index c9475e5a..234c5367 100644 --- a/packages/transcode/src/transcoder.ts +++ b/packages/transcode/src/transcoder.ts @@ -22,6 +22,13 @@ export class VideoTranscoder { return this } + setHardwareAcceleration(hardwareAcceleration?: PrismaJson.HardwareAcceleration): this { + if (hardwareAcceleration) { + this.spec.hardwareAcceleration = hardwareAcceleration + } + return this + } + withSprite(): this { this.spec.sprite = true return this diff --git a/packages/transcode/src/workflows/transcode-video.test.ts b/packages/transcode/src/workflows/transcode-video.test.ts index 3043e7a6..237c858d 100644 --- a/packages/transcode/src/workflows/transcode-video.test.ts +++ b/packages/transcode/src/workflows/transcode-video.test.ts @@ -154,11 +154,13 @@ describe('transcodeVideoWorkflow', () => { projectId: 'proj-1', }) - expect(mockActivities.createAutofillTaskIfEnabledActivity).toHaveBeenCalledWith({ - assetId: 'asset-1', - teamId: 'team-1', - projectId: 'proj-1', - }) + expect(mockActivities.transcodeVideoActivity).toHaveBeenCalledWith( + expect.objectContaining({ + assetKey: 'video.mp4', + filePath: '/tmp/video.mp4', + hardwareAcceleration: undefined, + }), + ) expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ taskId: 'task-1', @@ -166,6 +168,74 @@ describe('transcodeVideoWorkflow', () => { }) }) + it('should forward hardwareAcceleration to transcodeVideoActivity when specified', async () => { + const task: WorkflowTask = { + id: 'task-hw', + assetId: 'asset-hw', + type: WorkflowTaskType.transcode_video, + status: WorkflowTaskStatus.pending, + sessionId: null, + output: null, + payload: { + projectId: 'proj-1', + transcode: { + videoStrategy: 'best_match', + hardwareAcceleration: 'auto', + }, + }, + createdAt: new Date(), + updatedAt: new Date(), + heartbeat: null, + teamId: 'team-1', + projectId: 'proj-1', + uid: 'task-uid-hw', + model: null, + inputTokens: 0, + outputTokens: 0, + } + + mockActivities.getAssetActivity.mockResolvedValue({ + id: 'asset-hw', + storageKey: { key: 'video.mp4' }, + mediaType: 'video/mp4', + }) + + mockActivities.getMediaInfoActivity.mockResolvedValue({ + proxyType: 'video', + metadata: { + originalWidth: 1920, + originalHeight: 1080, + duration: 10, + frameRate: 30, + totalFrames: 300, + startTimecode: '00:00:00:00', + bitRate: 1000, + videoBitRate: 850000, + hasAudio: false, + format: {}, + }, + videoTranscodes: [], + imageTranscodes: [], + }) + + mockActivities.transcodeVideoActivity.mockResolvedValue({ + key: 'v.mp4', + width: 1920, + height: 1080, + }) + + await transcodeVideoWorkflow(task) + + expect(mockActivities.transcodeVideoActivity).toHaveBeenCalledWith( + expect.objectContaining({ + assetKey: 'video.mp4', + filePath: '/tmp/video.mp4', + hardwareAcceleration: 'auto', + sourceVideoBitrate: 850000, + }), + ) + }) + it('should run audio transcoding workflow successfully', async () => { const task: WorkflowTask = { id: 'task-audio', diff --git a/packages/transcode/src/workflows/transcode-video.ts b/packages/transcode/src/workflows/transcode-video.ts index 0c2e7d99..d96bf0c9 100644 --- a/packages/transcode/src/workflows/transcode-video.ts +++ b/packages/transcode/src/workflows/transcode-video.ts @@ -85,6 +85,8 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise videoSpec, duration: metadata.duration, originalFps: metadata.frameRate, + hardwareAcceleration: spec.hardwareAcceleration, + sourceVideoBitrate: metadata.videoBitRate || metadata.bitRate, }) if (res === '180p') { diff --git a/packages/webui/messages/en.json b/packages/webui/messages/en.json index ecf757b8..9aca7115 100644 --- a/packages/webui/messages/en.json +++ b/packages/webui/messages/en.json @@ -254,6 +254,11 @@ "best_match_description": "Generates a single optimal resolution matching the source quality.", "all_resolutions": "All resolutions", "all_resolutions_description": "Generates all supported resolutions up to the source quality.", + "hardware_acceleration": "Hardware Acceleration", + "hardware_acceleration_off": "Disabled (Software)", + "hardware_acceleration_off_description": "Uses software libx264 encoder with constant rate factor (CRF).", + "hardware_acceleration_auto": "Auto Detect", + "hardware_acceleration_auto_description": "Automatically probes and uses GPU/Hardware acceleration (NVENC, QSV, AMF, VideoToolbox). If hardware acceleration is unsupported on the host, video transcoding may fail.", "notification_settings": "Notification Settings", "notifications_description": "Configure your personal notification preferences for this team.", diff --git a/packages/webui/messages/zh.json b/packages/webui/messages/zh.json index 84edc933..b1deffab 100644 --- a/packages/webui/messages/zh.json +++ b/packages/webui/messages/zh.json @@ -254,6 +254,11 @@ "best_match_description": "生成与源质量匹配的单一最优分辨率。", "all_resolutions": "所有分辨率", "all_resolutions_description": "生成不超过源质量的所有支持分辨率。", + "hardware_acceleration": "硬件加速", + "hardware_acceleration_off": "已禁用 (软件编码)", + "hardware_acceleration_off_description": "使用 CPU 的 libx264 软件编码器及 CRF 恒定画质模式。", + "hardware_acceleration_auto": "自动检测", + "hardware_acceleration_auto_description": "自动检测并使用 GPU/硬件加速(NVENC、QSV、AMF、VideoToolbox)。若宿主硬件不支持加速,视频转码可能会失败。", "notification_settings": "通知设置", "notifications_description": "配置您在此团队的个人通知偏好。", diff --git a/packages/webui/paraglide/messages/_index.d.ts b/packages/webui/paraglide/messages/_index.d.ts index 9f57f7ed..b2356e5c 100644 --- a/packages/webui/paraglide/messages/_index.d.ts +++ b/packages/webui/paraglide/messages/_index.d.ts @@ -241,6 +241,11 @@ export * from "./best_match.js"; export * from "./best_match_description.js"; export * from "./all_resolutions.js"; export * from "./all_resolutions_description.js"; +export * from "./hardware_acceleration.js"; +export * from "./hardware_acceleration_off.js"; +export * from "./hardware_acceleration_off_description.js"; +export * from "./hardware_acceleration_auto.js"; +export * from "./hardware_acceleration_auto_description.js"; export * from "./notification_settings.js"; export * from "./notifications_description.js"; export * from "./notification_settings_updated.js"; diff --git a/packages/webui/paraglide/messages/_index.js b/packages/webui/paraglide/messages/_index.js index e6c9fd42..3ee30564 100644 --- a/packages/webui/paraglide/messages/_index.js +++ b/packages/webui/paraglide/messages/_index.js @@ -243,6 +243,11 @@ export * from './best_match.js' export * from './best_match_description.js' export * from './all_resolutions.js' export * from './all_resolutions_description.js' +export * from './hardware_acceleration.js' +export * from './hardware_acceleration_off.js' +export * from './hardware_acceleration_off_description.js' +export * from './hardware_acceleration_auto.js' +export * from './hardware_acceleration_auto_description.js' export * from './notification_settings.js' export * from './notifications_description.js' export * from './notification_settings_updated.js' diff --git a/packages/webui/paraglide/messages/hardware_acceleration.d.ts b/packages/webui/paraglide/messages/hardware_acceleration.d.ts new file mode 100644 index 00000000..a45700e6 --- /dev/null +++ b/packages/webui/paraglide/messages/hardware_acceleration.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Hardware Acceleration" | +* +* @param {Hardware_AccelerationInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const hardware_acceleration: ((inputs?: Hardware_AccelerationInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Hardware_AccelerationInputs = {}; diff --git a/packages/webui/paraglide/messages/hardware_acceleration.js b/packages/webui/paraglide/messages/hardware_acceleration.js new file mode 100644 index 00000000..0924345e --- /dev/null +++ b/packages/webui/paraglide/messages/hardware_acceleration.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Hardware_AccelerationInputs */ + +const en_hardware_acceleration = /** @type {(inputs: Hardware_AccelerationInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Hardware Acceleration`) +}; + +const zh_hardware_acceleration = /** @type {(inputs: Hardware_AccelerationInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`硬件加速`) +}; + +/** +* | output | +* | --- | +* | "Hardware Acceleration" | +* +* @param {Hardware_AccelerationInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const hardware_acceleration = /** @type {((inputs?: Hardware_AccelerationInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_hardware_acceleration(inputs) + return zh_hardware_acceleration(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/hardware_acceleration_auto.d.ts b/packages/webui/paraglide/messages/hardware_acceleration_auto.d.ts new file mode 100644 index 00000000..1e4b0fd6 --- /dev/null +++ b/packages/webui/paraglide/messages/hardware_acceleration_auto.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Auto Detect" | +* +* @param {Hardware_Acceleration_AutoInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const hardware_acceleration_auto: ((inputs?: Hardware_Acceleration_AutoInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Hardware_Acceleration_AutoInputs = {}; diff --git a/packages/webui/paraglide/messages/hardware_acceleration_auto.js b/packages/webui/paraglide/messages/hardware_acceleration_auto.js new file mode 100644 index 00000000..60853190 --- /dev/null +++ b/packages/webui/paraglide/messages/hardware_acceleration_auto.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Hardware_Acceleration_AutoInputs */ + +const en_hardware_acceleration_auto = /** @type {(inputs: Hardware_Acceleration_AutoInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Auto Detect`) +}; + +const zh_hardware_acceleration_auto = /** @type {(inputs: Hardware_Acceleration_AutoInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`自动检测`) +}; + +/** +* | output | +* | --- | +* | "Auto Detect" | +* +* @param {Hardware_Acceleration_AutoInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const hardware_acceleration_auto = /** @type {((inputs?: Hardware_Acceleration_AutoInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_hardware_acceleration_auto(inputs) + return zh_hardware_acceleration_auto(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/hardware_acceleration_auto_description.d.ts b/packages/webui/paraglide/messages/hardware_acceleration_auto_description.d.ts new file mode 100644 index 00000000..690bf802 --- /dev/null +++ b/packages/webui/paraglide/messages/hardware_acceleration_auto_description.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Automatically probes and uses GPU/Hardware acceleration (NVENC, QSV, AMF, VideoToolbox). If hardware acceleration is unsupported on the host, video transcodi..." | +* +* @param {Hardware_Acceleration_Auto_DescriptionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const hardware_acceleration_auto_description: ((inputs?: Hardware_Acceleration_Auto_DescriptionInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Hardware_Acceleration_Auto_DescriptionInputs = {}; diff --git a/packages/webui/paraglide/messages/hardware_acceleration_auto_description.js b/packages/webui/paraglide/messages/hardware_acceleration_auto_description.js new file mode 100644 index 00000000..5f0c09f3 --- /dev/null +++ b/packages/webui/paraglide/messages/hardware_acceleration_auto_description.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Hardware_Acceleration_Auto_DescriptionInputs */ + +const en_hardware_acceleration_auto_description = /** @type {(inputs: Hardware_Acceleration_Auto_DescriptionInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Automatically probes and uses GPU/Hardware acceleration (NVENC, QSV, AMF, VideoToolbox). If hardware acceleration is unsupported on the host, video transcoding may fail.`) +}; + +const zh_hardware_acceleration_auto_description = /** @type {(inputs: Hardware_Acceleration_Auto_DescriptionInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`自动检测并使用 GPU/硬件加速(NVENC、QSV、AMF、VideoToolbox)。若宿主硬件不支持加速,视频转码可能会失败。`) +}; + +/** +* | output | +* | --- | +* | "Automatically probes and uses GPU/Hardware acceleration (NVENC, QSV, AMF, VideoToolbox). If hardware acceleration is unsupported on the host, video transcodi..." | +* +* @param {Hardware_Acceleration_Auto_DescriptionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const hardware_acceleration_auto_description = /** @type {((inputs?: Hardware_Acceleration_Auto_DescriptionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_hardware_acceleration_auto_description(inputs) + return zh_hardware_acceleration_auto_description(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/hardware_acceleration_off.d.ts b/packages/webui/paraglide/messages/hardware_acceleration_off.d.ts new file mode 100644 index 00000000..0316e084 --- /dev/null +++ b/packages/webui/paraglide/messages/hardware_acceleration_off.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Disabled (Software)" | +* +* @param {Hardware_Acceleration_OffInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const hardware_acceleration_off: ((inputs?: Hardware_Acceleration_OffInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Hardware_Acceleration_OffInputs = {}; diff --git a/packages/webui/paraglide/messages/hardware_acceleration_off.js b/packages/webui/paraglide/messages/hardware_acceleration_off.js new file mode 100644 index 00000000..07f40e2e --- /dev/null +++ b/packages/webui/paraglide/messages/hardware_acceleration_off.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Hardware_Acceleration_OffInputs */ + +const en_hardware_acceleration_off = /** @type {(inputs: Hardware_Acceleration_OffInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Disabled (Software)`) +}; + +const zh_hardware_acceleration_off = /** @type {(inputs: Hardware_Acceleration_OffInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`已禁用 (软件编码)`) +}; + +/** +* | output | +* | --- | +* | "Disabled (Software)" | +* +* @param {Hardware_Acceleration_OffInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const hardware_acceleration_off = /** @type {((inputs?: Hardware_Acceleration_OffInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_hardware_acceleration_off(inputs) + return zh_hardware_acceleration_off(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/hardware_acceleration_off_description.d.ts b/packages/webui/paraglide/messages/hardware_acceleration_off_description.d.ts new file mode 100644 index 00000000..6520ab95 --- /dev/null +++ b/packages/webui/paraglide/messages/hardware_acceleration_off_description.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Uses software libx264 encoder with constant rate factor (CRF)." | +* +* @param {Hardware_Acceleration_Off_DescriptionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const hardware_acceleration_off_description: ((inputs?: Hardware_Acceleration_Off_DescriptionInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Hardware_Acceleration_Off_DescriptionInputs = {}; diff --git a/packages/webui/paraglide/messages/hardware_acceleration_off_description.js b/packages/webui/paraglide/messages/hardware_acceleration_off_description.js new file mode 100644 index 00000000..4ba87484 --- /dev/null +++ b/packages/webui/paraglide/messages/hardware_acceleration_off_description.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Hardware_Acceleration_Off_DescriptionInputs */ + +const en_hardware_acceleration_off_description = /** @type {(inputs: Hardware_Acceleration_Off_DescriptionInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Uses software libx264 encoder with constant rate factor (CRF).`) +}; + +const zh_hardware_acceleration_off_description = /** @type {(inputs: Hardware_Acceleration_Off_DescriptionInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`使用 CPU 的 libx264 软件编码器及 CRF 恒定画质模式。`) +}; + +/** +* | output | +* | --- | +* | "Uses software libx264 encoder with constant rate factor (CRF)." | +* +* @param {Hardware_Acceleration_Off_DescriptionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const hardware_acceleration_off_description = /** @type {((inputs?: Hardware_Acceleration_Off_DescriptionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_hardware_acceleration_off_description(inputs) + return zh_hardware_acceleration_off_description(inputs) +}); \ No newline at end of file diff --git a/packages/webui/routes/teams/$teamId/settings.lazy.tsx b/packages/webui/routes/teams/$teamId/settings.lazy.tsx index d198e3d6..e0bbe212 100644 --- a/packages/webui/routes/teams/$teamId/settings.lazy.tsx +++ b/packages/webui/routes/teams/$teamId/settings.lazy.tsx @@ -1,5 +1,9 @@ import { createLazyFileRoute } from '@tanstack/react-router' -import { VideoTranscodeStrategy, UpdateTeamSettingsRequest } from '@shumai/dtos' +import { + VideoTranscodeStrategy, + HardwareAcceleration, + UpdateTeamSettingsRequest, +} from '@shumai/dtos' import { client } from '@/ui/api/client' import { AgentsSettings } from '@/ui/components/settings/AgentsSettings' import { ProvidersSettings } from '@/ui/components/settings/ProvidersSettings' @@ -244,6 +248,16 @@ function TeamSettingsPage() { }) } + const handleHardwareAccelerationChange = (value: HardwareAcceleration) => { + updateSettings({ + teamId, + data: { + key: 'transcode.hardwareAcceleration', + value: value, + }, + }) + } + if (isSettingsLoading || isMeLoading) { return (
@@ -265,6 +279,10 @@ function TeamSettingsPage() { currentVideoStrategy = VideoTranscodeStrategy.all } + const currentHardwareAcceleration = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (settings as any)?.transcode?.hardwareAcceleration || HardwareAcceleration.off + return (
@@ -667,6 +685,46 @@ function TeamSettingsPage() {
+ + {/* Hardware Acceleration */} +
+

{m.hardware_acceleration()}

+
+
+ handleHardwareAccelerationChange(HardwareAcceleration.off) + } + > +
{m.hardware_acceleration_off()}
+
+ {m.hardware_acceleration_off_description()} +
+
+ +
+ handleHardwareAccelerationChange(HardwareAcceleration.auto) + } + > +
{m.hardware_acceleration_auto()}
+
+ {m.hardware_acceleration_auto_description()} +
+
+
+