feat(settings): add FFmpeg threads setting for media processing (#415)

* feat(settings): add FFmpeg threads setting for media processing

* style(settings): add bottom padding to media processing page
This commit is contained in:
Yiling-J
2026-09-18 13:30:33 +08:00
committed by GitHub
parent 3a509537fd
commit a91d8c4521
20 changed files with 355 additions and 17 deletions
+1
View File
@@ -10,6 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- **changelog**: Introduce Keep a Changelog support, historical release summaries, and automated release notes extraction
- **release**: Automatically populate GitHub release bodies from CHANGELOG.md and promote unreleased notes during version bumps
- **settings**: Add FFmpeg threads slider to team media processing settings
## [0.4.6] - 2026-09-17
+38
View File
@@ -260,6 +260,44 @@ describe('team api', () => {
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'transcode.hardwareAcceleration', 'auto')
})
it('PATCH /teams/:teamId/settings updates transcode.threads', async () => {
mockUpdateSettings.mockResolvedValue({ transcode: { threads: 8 } })
const res = await app.request('/teams/t1/settings', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'transcode.threads', value: 8 }),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.transcode.threads).toBe(8)
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'transcode.threads', 8)
})
it('PATCH /teams/:teamId/settings rejects invalid transcode.threads', async () => {
const resNegative = await app.request('/teams/t1/settings', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'transcode.threads', value: -1 }),
})
expect(resNegative.status).toBe(400)
const resTooLarge = await app.request('/teams/t1/settings', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'transcode.threads', value: 33 }),
})
expect(resTooLarge.status).toBe(400)
const resFloat = await app.request('/teams/t1/settings', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'transcode.threads', value: 4.5 }),
})
expect(resFloat.status).toBe(400)
})
it('PATCH /teams/:teamId/settings updates appearance.hideAgent', async () => {
mockUpdateSettings.mockResolvedValue({ appearance: { hideAgent: true } })
+4 -1
View File
@@ -2,6 +2,7 @@ import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { teamService } from '@shumai/core/src/team/team'
import { describe, expect, it } from 'vitest'
import type { TeamSettingsResponse } from '@shumai/dtos'
describe('TeamService', () => {
setupTestDbHooks()
@@ -10,6 +11,7 @@ describe('TeamService', () => {
const team = await teamService.ensureDefaultTeam()
expect(team).toBeDefined()
expect(team.name).toBe('Default Team')
expect((team.settings as TeamSettingsResponse | null)?.transcode?.threads).toBe(0)
})
it('should create team', async () => {
@@ -376,12 +378,13 @@ describe('TeamService', () => {
await teamService.updateSettings(team.id, 'transcode.videoStrategy', 'all')
await teamService.updateSettings(team.id, 'transcode.hardwareAcceleration', 'auto')
await teamService.updateSettings(team.id, 'transcode.threads', 4)
await teamService.updateSettings(team.id, 'appearance.hideAgent', true)
const finalSettings = await teamService.getSettings(team.id)
expect(finalSettings).toEqual({
theme: 'dark',
transcode: { videoStrategy: 'all', hardwareAcceleration: 'auto' },
transcode: { videoStrategy: 'all', hardwareAcceleration: 'auto', threads: 4 },
appearance: { hideAgent: true },
semanticSearchEnabled: false,
})
+7 -1
View File
@@ -33,7 +33,7 @@ export class TeamService {
data: {
name: 'Default Team',
settings: {
transcode: { videoStrategy: 'best_match', hardwareAcceleration: 'off' },
transcode: { videoStrategy: 'best_match', hardwareAcceleration: 'off', threads: 0 },
},
sandbox: { create: {} },
},
@@ -332,6 +332,12 @@ export class TeamService {
TeamSettingsResponse['transcode']
>['hardwareAcceleration']
delete settings['transcode.hardwareAcceleration']
} else if (key === 'transcode.threads') {
if (!settings.transcode) {
settings.transcode = {}
}
settings.transcode.threads = Number(value)
delete settings['transcode.threads']
} else if (key === 'appearance.hideAgent') {
if (!settings.appearance) {
settings.appearance = {}
@@ -614,6 +614,76 @@ describe('TranscodeService', () => {
)
})
it('transcodeAudio should pass -threads when threads > 0', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.execFile as any).mockImplementation((file: string, args: string[], cb: any) => {
cb(null, { stdout: '', stderr: '' })
})
await transcodeService.transcodeAudio({
inputFile: 'input.wav',
outputFile: 'output.mp4',
bitrate: '128k',
threads: 4,
})
expect(child_process.execFile).toHaveBeenCalledWith(
'ffmpeg',
[
'-y',
'-loglevel',
'warning',
'-i',
'input.wav',
'-vn',
'-c:a',
'aac',
'-b:a',
'128k',
'-ac',
'2',
'-threads',
'4',
'output.mp4',
],
expect.any(Function),
)
})
it('transcodeAudio should omit -threads when threads is 0', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.execFile as any).mockImplementation((file: string, args: string[], cb: any) => {
cb(null, { stdout: '', stderr: '' })
})
await transcodeService.transcodeAudio({
inputFile: 'input.wav',
outputFile: 'output.mp4',
bitrate: '128k',
threads: 0,
})
expect(child_process.execFile).toHaveBeenCalledWith(
'ffmpeg',
[
'-y',
'-loglevel',
'warning',
'-i',
'input.wav',
'-vn',
'-c:a',
'aac',
'-b:a',
'128k',
'-ac',
'2',
'output.mp4',
],
expect.any(Function),
)
})
it('should generate PDF sprite sheet and poster using pdftoppm, ffmpeg, and sharp', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.execFile as any).mockImplementation(
@@ -1638,5 +1708,73 @@ describe('TranscodeService', () => {
expect.any(Function),
)
})
it('transcodeVideo with threads > 0 should pass -threads to ffmpeg', 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_threads.mp4')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
threads: 6,
})
expect(child_process.execFile).toHaveBeenCalledWith(
'ffmpeg',
expect.arrayContaining(['-threads', '6']),
expect.any(Function),
)
})
it('transcodeVideo with threads 0 or undefined should omit -threads', 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_threads_0.mp4')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
threads: 0,
})
expect(child_process.execFile).not.toHaveBeenCalledWith(
'ffmpeg',
expect.arrayContaining(['-threads']),
expect.any(Function),
)
})
})
})
+11 -12
View File
@@ -116,6 +116,7 @@ export interface TranscodeVideoParams {
hardwareAcceleration?: 'off' | 'auto'
videoBitrate?: string
sourceVideoBitrate?: number
threads?: number
}
export interface EncoderConfig {
@@ -627,6 +628,10 @@ export class TranscodeService {
args.push('-c:a', 'aac', '-b:a', '128k')
}
if (params.threads && params.threads > 0) {
args.push('-threads', params.threads.toString())
}
args.push('-movflags', '+faststart', '-max_muxing_queue_size', '1024', params.outputFile)
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
@@ -1084,20 +1089,14 @@ export class TranscodeService {
inputFile: string
outputFile: string
bitrate?: string
threads?: number
}): Promise<void> {
const bitrate = params.bitrate || '128k'
const args = [
'-i',
params.inputFile,
'-vn',
'-c:a',
'aac',
'-b:a',
bitrate,
'-ac',
'2',
params.outputFile,
]
const args = ['-i', params.inputFile, '-vn', '-c:a', 'aac', '-b:a', bitrate, '-ac', '2']
if (params.threads && params.threads > 0) {
args.push('-threads', params.threads.toString())
}
args.push(params.outputFile)
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
}
+52
View File
@@ -195,6 +195,58 @@ describe('UploadService', () => {
transcode: {
videoStrategy: 'best_match',
hardwareAcceleration: 'off',
threads: 0,
sprite: true,
poster: true,
},
})
})
it('should pass custom transcode.threads from team settings to transcode task', async () => {
await prisma.team.update({
where: { id: teamId },
data: {
settings: {
transcode: {
videoStrategy: 'all',
hardwareAcceleration: 'auto',
threads: 12,
},
},
},
})
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
})
const asset = await prisma.asset.create({
data: {
name: 'video-custom-threads.mp4',
type: AssetType.file,
project: { connect: { id: projectId } },
parent: { connect: { id: parentId } },
status: AssetStatus.uploading,
storageKey: {
connectOrCreate: {
where: { key: 'test-key-threads' },
create: { key: 'test-key-threads' },
},
},
},
})
await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
const workflowTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_video },
})
expect(workflowTask).toBeDefined()
expect(workflowTask?.payload).toEqual({
projectId: projectId,
transcode: {
videoStrategy: 'all',
hardwareAcceleration: 'auto',
threads: 12,
sprite: true,
poster: true,
},
+5 -1
View File
@@ -331,6 +331,7 @@ export class UploadService {
})
} else {
const settings = team.settings as PrismaJson.Settings | null
const threads = settings?.transcode?.threads ?? 0
if (isVideo) {
const strategy = settings?.transcode?.videoStrategy || 'best_match'
const hardwareAcceleration = settings?.transcode?.hardwareAcceleration || 'off'
@@ -338,12 +339,15 @@ export class UploadService {
await new VideoTranscoder(tx as any, asset.id, team.id, projectId)
.setStrategy(strategy)
.setHardwareAcceleration(hardwareAcceleration)
.setThreads(threads)
.withSprite()
.withPoster()
.submit()
} else if (isAudio) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new VideoTranscoder(tx as any, asset.id, team.id, projectId).submit()
await new VideoTranscoder(tx as any, asset.id, team.id, projectId)
.setThreads(threads)
.submit()
} else if (isImage) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new ImageTranscoder(tx as any, asset.id, team.id, projectId).withThumbnail().submit()
+2
View File
@@ -59,6 +59,7 @@ declare global {
export interface TranscodeSettings {
videoStrategy: VideoTranscodeStrategy
hardwareAcceleration?: HardwareAcceleration
threads?: number
}
export interface MediaProviderConfig {
@@ -314,6 +315,7 @@ declare global {
export interface TaskSpec {
videoStrategy?: VideoTranscodeStrategy
hardwareAcceleration?: HardwareAcceleration
threads?: number
thumbnail?: boolean
sprite?: boolean
poster?: boolean
+5
View File
@@ -89,6 +89,10 @@ export const updateTeamSettingsRequestSchema = z.union([
key: z.literal('transcode.hardwareAcceleration'),
value: z.nativeEnum(HardwareAcceleration),
}),
z.object({
key: z.literal('transcode.threads'),
value: z.number().int().min(0).max(32),
}),
z.object({
key: z.literal('appearance.hideAgent'),
value: z.boolean(),
@@ -104,6 +108,7 @@ export interface TeamSettingsResponse {
transcode?: {
videoStrategy?: VideoTranscodeStrategy
hardwareAcceleration?: HardwareAcceleration
threads?: number
}
appearance?: TeamAppearanceSettings
semanticSearchEnabled?: boolean
@@ -606,6 +606,7 @@ describe('Transcode Activities', () => {
originalFps: 30,
hardwareAcceleration: 'auto',
sourceVideoBitrate: 600_000,
threads: 8,
})
expect(transcodeService.transcodeVideo).toHaveBeenCalledWith(
@@ -613,6 +614,7 @@ describe('Transcode Activities', () => {
inputFile: '/tmp/v.mp4',
hardwareAcceleration: 'auto',
sourceVideoBitrate: 600_000,
threads: 8,
}),
)
})
@@ -1013,12 +1015,14 @@ describe('Transcode Activities', () => {
const res = await transcodeAudioActivity({
assetKey: 'files/proj-123/a.wav',
filePath: '/tmp/a.wav',
threads: 4,
})
expect(transcodeService.transcodeAudio).toHaveBeenCalledWith({
inputFile: '/tmp/a.wav',
outputFile: expect.stringContaining('a-audio-proxy.mp4'),
bitrate: '128k',
threads: 4,
})
expect(s3Service.putObject).toHaveBeenCalledWith(
@@ -223,6 +223,7 @@ export interface VideoActivityParams {
originalFps: number
hardwareAcceleration?: PrismaJson.HardwareAcceleration
sourceVideoBitrate?: number
threads?: number
}
export async function transcodeVideoActivity(
@@ -267,6 +268,7 @@ export async function transcodeVideoActivity(
disableAudio,
hardwareAcceleration: params.hardwareAcceleration,
sourceVideoBitrate: params.sourceVideoBitrate,
threads: params.threads,
})
const stat = fs.statSync(outputFile)
@@ -302,6 +304,7 @@ export async function transcodeVideoActivity(
export interface AudioActivityParams {
assetKey: string
filePath: string
threads?: number
}
export async function transcodeAudioActivity(
@@ -326,6 +329,7 @@ export async function transcodeAudioActivity(
inputFile: params.filePath,
outputFile,
bitrate: '128k',
threads: params.threads,
})
const stat = fs.statSync(outputFile)
@@ -352,6 +352,7 @@ describe('Watermark Activities', () => {
transcode: {
videoStrategy: 'best_match',
hardwareAcceleration: 'auto',
threads: 6,
},
},
},
@@ -398,6 +399,7 @@ describe('Watermark Activities', () => {
hardwareAcceleration: 'auto',
sourceVideoBitrate: 1800000,
disableAudio: true,
threads: 6,
}),
)
@@ -150,6 +150,7 @@ export async function transcodeWatermarkMediaActivity(
const teamSettings = asset.project?.team?.settings as PrismaJson.Settings | null
const hardwareAcceleration = teamSettings?.transcode?.hardwareAcceleration ?? 'off'
const threads = teamSettings?.transcode?.threads ?? 0
// The config column is declared as PrismaJson.WatermarkConfigSpec, which is
// structurally identical to the DTO type, so no cast is required.
@@ -338,6 +339,7 @@ export async function transcodeWatermarkMediaActivity(
overlayFile: overlayPngPath,
hardwareAcceleration,
sourceVideoBitrate,
threads,
})
const stat = fs.statSync(outFilePath)
+7
View File
@@ -29,6 +29,13 @@ export class VideoTranscoder {
return this
}
setThreads(threads?: number): this {
if (threads !== undefined) {
this.spec.threads = threads
}
return this
}
withSprite(): this {
this.spec.sprite = true
return this
@@ -187,6 +187,7 @@ describe('transcodeVideoWorkflow', () => {
transcode: {
videoStrategy: 'best_match',
hardwareAcceleration: 'auto',
threads: 8,
},
},
createdAt: new Date(),
@@ -238,6 +239,7 @@ describe('transcodeVideoWorkflow', () => {
filePath: '/tmp/video.mp4',
hardwareAcceleration: 'auto',
sourceVideoBitrate: 850000,
threads: 8,
}),
)
})
@@ -252,7 +254,9 @@ describe('transcodeVideoWorkflow', () => {
output: null,
payload: {
projectId: 'proj-1',
transcode: {},
transcode: {
threads: 4,
},
},
createdAt: new Date(),
updatedAt: new Date(),
@@ -303,6 +307,7 @@ describe('transcodeVideoWorkflow', () => {
expect(mockActivities.transcodeAudioActivity).toHaveBeenCalledWith({
assetKey: 'audio.wav',
filePath: '/tmp/video.mp4',
threads: 4,
})
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith({
@@ -105,6 +105,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
originalFps: metadata.frameRate,
hardwareAcceleration: spec.hardwareAcceleration,
sourceVideoBitrate: metadata.videoBitRate || metadata.bitRate,
threads: spec.threads,
})
if (res === '180p') {
@@ -120,6 +121,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
const audioTranscode = await executeActivity(workerQueue, transcodeAudioActivity, {
assetKey: key,
filePath,
threads: spec.threads,
})
mediaInfo.videoTranscodes.push(audioTranscode)
}
+4
View File
@@ -260,6 +260,10 @@
"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.",
"ffmpeg_threads": "FFmpeg Threads",
"ffmpeg_threads_description": "Maximum number of CPU threads used by FFmpeg during transcoding. Set to 0 for Auto.",
"threads_auto": "Auto",
"threads_count": "{count} threads",
"notification_settings": "Notification Settings",
"notifications_description": "Configure your personal notification preferences for this team.",
+4
View File
@@ -260,6 +260,10 @@
"hardware_acceleration_off_description": "使用 CPU 的 libx264 软件编码器及 CRF 恒定画质模式。",
"hardware_acceleration_auto": "自动检测",
"hardware_acceleration_auto_description": "自动检测并使用 GPU/硬件加速(NVENC、QSV、AMF、VideoToolbox)。若宿主硬件不支持加速,视频转码可能会失败。",
"ffmpeg_threads": "FFmpeg 线程数",
"ffmpeg_threads_description": "FFmpeg 转码时使用的最大 CPU 线程数。设置为 0 表示自动。",
"threads_auto": "自动",
"threads_count": "{count} 线程",
"notification_settings": "通知设置",
"notifications_description": "配置您在此团队的个人通知偏好。",
@@ -3,6 +3,7 @@ import {
VideoTranscodeStrategy,
HardwareAcceleration,
UpdateTeamSettingsRequest,
TeamSettingsResponse,
} from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { AgentsSettings } from '@/ui/components/settings/AgentsSettings'
@@ -16,6 +17,7 @@ import { QuotasSettings } from '@/ui/components/settings/QuotasSettings'
import { AppearanceSettings } from '@/ui/components/settings/AppearanceSettings'
import { ImageVideoGenerationSettings } from '@/ui/components/settings/ImageVideoGenerationSettings'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
import { Slider } from '@/ui/components/ui/slider'
import { cn } from '@/ui/lib/utils'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
@@ -309,6 +311,23 @@ function TeamSettingsPage() {
})
}
const [localThreads, setLocalThreads] = useState<number | null>(null)
const serverThreads = (settings as TeamSettingsResponse | undefined)?.transcode?.threads ?? 0
useEffect(() => {
setLocalThreads(null)
}, [serverThreads])
const handleThreadsChange = (value: number) => {
updateSettings({
teamId,
data: {
key: 'transcode.threads',
value,
},
})
}
if (isSettingsLoading || isMeLoading) {
return (
<div className="flex h-screen items-center justify-center">
@@ -334,6 +353,8 @@ function TeamSettingsPage() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(settings as any)?.transcode?.hardwareAcceleration || HardwareAcceleration.off
const currentThreads = localThreads ?? serverThreads
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">
@@ -725,7 +746,7 @@ function TeamSettingsPage() {
)}
{activeTab === 'transcode' && (
<div className="h-full overflow-y-auto pr-1">
<div className="h-full overflow-y-auto pr-1 pb-8">
<Card>
<CardHeader>
<CardTitle>{m.transcode_settings()}</CardTitle>
@@ -812,6 +833,41 @@ function TeamSettingsPage() {
</div>
</div>
</div>
{/* FFmpeg Threads */}
<div className="space-y-4 pt-6 border-t border-border">
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-medium">{m.ffmpeg_threads()}</h3>
<p className="text-sm text-muted-foreground">
{m.ffmpeg_threads_description()}
</p>
</div>
<span className="font-mono text-sm font-semibold px-2.5 py-1 rounded bg-muted text-foreground border border-border">
{currentThreads === 0
? m.threads_auto()
: m.threads_count({ count: currentThreads })}
</span>
</div>
<div className="pt-2 px-1">
<Slider
value={[currentThreads]}
min={0}
max={32}
step={1}
onValueChange={([val]) => setLocalThreads(val)}
onValueCommit={([val]) => {
setLocalThreads(val)
handleThreadsChange(val)
}}
/>
<div className="flex justify-between text-xs text-muted-foreground mt-2">
<span>{m.threads_auto()} (0)</span>
<span>16</span>
<span>32</span>
</div>
</div>
</div>
</CardContent>
</Card>
</div>