mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-25 23:49:28 +00:00
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:
@@ -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' },
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -190,6 +190,7 @@ describe('UploadService', () => {
|
||||
projectId: projectId,
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'off',
|
||||
sprite: true,
|
||||
poster: true,
|
||||
},
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<typeof updateTeamSettingsRequestSchema>
|
||||
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -85,6 +85,8 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
videoSpec,
|
||||
duration: metadata.duration,
|
||||
originalFps: metadata.frameRate,
|
||||
hardwareAcceleration: spec.hardwareAcceleration,
|
||||
sourceVideoBitrate: metadata.videoBitRate || metadata.bitRate,
|
||||
})
|
||||
|
||||
if (res === '180p') {
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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": "配置您在此团队的个人通知偏好。",
|
||||
|
||||
+5
@@ -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";
|
||||
|
||||
+5
@@ -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'
|
||||
|
||||
+16
@@ -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<Hardware_AccelerationInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Hardware_AccelerationInputs = {};
|
||||
@@ -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<Hardware_AccelerationInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_hardware_acceleration(inputs)
|
||||
return zh_hardware_acceleration(inputs)
|
||||
});
|
||||
+16
@@ -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<Hardware_Acceleration_AutoInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Hardware_Acceleration_AutoInputs = {};
|
||||
@@ -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<Hardware_Acceleration_AutoInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_hardware_acceleration_auto(inputs)
|
||||
return zh_hardware_acceleration_auto(inputs)
|
||||
});
|
||||
+16
@@ -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<Hardware_Acceleration_Auto_DescriptionInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Hardware_Acceleration_Auto_DescriptionInputs = {};
|
||||
@@ -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<Hardware_Acceleration_Auto_DescriptionInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
|
||||
});
|
||||
+16
@@ -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<Hardware_Acceleration_OffInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Hardware_Acceleration_OffInputs = {};
|
||||
@@ -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<Hardware_Acceleration_OffInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_hardware_acceleration_off(inputs)
|
||||
return zh_hardware_acceleration_off(inputs)
|
||||
});
|
||||
+16
@@ -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<Hardware_Acceleration_Off_DescriptionInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Hardware_Acceleration_Off_DescriptionInputs = {};
|
||||
@@ -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<Hardware_Acceleration_Off_DescriptionInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
|
||||
});
|
||||
@@ -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 (
|
||||
<div className="flex h-screen items-center justify-center">
|
||||
@@ -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 (
|
||||
<div className="h-full bg-background font-sans selection:bg-primary/20 transition-colors duration-300">
|
||||
<div className="flex flex-col md:flex-row h-full">
|
||||
@@ -667,6 +685,46 @@ function TeamSettingsPage() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Hardware Acceleration */}
|
||||
<div className="space-y-3 pt-6 border-t border-border">
|
||||
<h3 className="text-lg font-medium">{m.hardware_acceleration()}</h3>
|
||||
<div className="space-y-3">
|
||||
<div
|
||||
className={cn(
|
||||
'cursor-pointer rounded-lg border p-4 transition-all hover:border-primary',
|
||||
currentHardwareAcceleration === HardwareAcceleration.off
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border',
|
||||
)}
|
||||
onClick={() =>
|
||||
handleHardwareAccelerationChange(HardwareAcceleration.off)
|
||||
}
|
||||
>
|
||||
<div className="font-semibold">{m.hardware_acceleration_off()}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{m.hardware_acceleration_off_description()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'cursor-pointer rounded-lg border p-4 transition-all hover:border-primary',
|
||||
currentHardwareAcceleration === HardwareAcceleration.auto
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border',
|
||||
)}
|
||||
onClick={() =>
|
||||
handleHardwareAccelerationChange(HardwareAcceleration.auto)
|
||||
}
|
||||
>
|
||||
<div className="font-semibold">{m.hardware_acceleration_auto()}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{m.hardware_acceleration_auto_description()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user