feat(transcode): add multi-resolution strategy with configurable ladders and fallback (#438)

* feat(transcode): add multi-resolution strategy with configurable ladders and fallback

* feat(settings): show toast on settings update and add manual verification plan to PR template

* fix(webui): preserve video resolution and fix 480p label in download dropdowns

* fix(webui): display standard short-side resolution for vertical videos in seekbar

* fix(webui): fix portrait transcode resolution labeling and serialize settings toggles
This commit is contained in:
Yiling-J
2026-10-01 13:27:50 +08:00
committed by GitHub
parent a84da8678e
commit e007054f47
35 changed files with 1260 additions and 123 deletions
@@ -300,6 +300,7 @@ function FileViewPage() {
key: t.key,
width: t.width,
height: t.height,
resolution: t.resolution,
hdr: t.hdr,
})),
},
@@ -1,6 +1,8 @@
import { createLazyFileRoute } from '@tanstack/react-router'
import {
VideoTranscodeStrategy,
VideoResolutionLadder,
DEFAULT_VIDEO_RESOLUTIONS,
HardwareAcceleration,
UpdateTeamSettingsRequest,
TeamSettingsResponse,
@@ -97,7 +99,7 @@ function getTabFromHash(): SettingsTab {
: 'general'
}
function TeamSettingsPage() {
export function TeamSettingsPage() {
const { teamId } = Route.useParams()
const queryClient = useQueryClient()
const [activeTab, setActiveTabState] = useState<SettingsTab>(getTabFromHash)
@@ -297,6 +299,10 @@ function TeamSettingsPage() {
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
toast.success(m.settings_updated())
},
onError: () => {
toast.error(m.failed_update_settings())
},
})
@@ -310,6 +316,102 @@ function TeamSettingsPage() {
})
}
const pendingVideoResolutionsRef = useRef<VideoResolutionLadder[] | null>(null)
const [optimisticVideoResolutions, setOptimisticVideoResolutions] = useState<
VideoResolutionLadder[] | null
>(null)
const videoResolutionsQueueRef = useRef<Promise<void>>(Promise.resolve())
const isVideoResolutionsUpdatingRef = useRef<boolean>(false)
const pendingHlsResolutionsRef = useRef<HlsResolutionLadder[] | null>(null)
const [optimisticHlsResolutions, setOptimisticHlsResolutions] = useState<
HlsResolutionLadder[] | null
>(null)
const hlsResolutionsQueueRef = useRef<Promise<void>>(Promise.resolve())
const isHlsResolutionsUpdatingRef = useRef<boolean>(false)
useEffect(() => {
if (!isVideoResolutionsUpdatingRef.current) {
pendingVideoResolutionsRef.current = null
setOptimisticVideoResolutions(null)
}
}, [settings])
useEffect(() => {
if (!isHlsResolutionsUpdatingRef.current) {
pendingHlsResolutionsRef.current = null
setOptimisticHlsResolutions(null)
}
}, [settings])
const handleVideoLadderToggle = (ladder: VideoResolutionLadder) => {
const current =
pendingVideoResolutionsRef.current ??
optimisticVideoResolutions ??
(settings as TeamSettingsResponse | undefined)?.transcode?.videoResolutions ??
DEFAULT_VIDEO_RESOLUTIONS
const updated = current.includes(ladder)
? current.filter((l) => l !== ladder)
: [...current, ladder]
if (updated.length === 0) return
pendingVideoResolutionsRef.current = updated
setOptimisticVideoResolutions(updated)
queryClient.setQueryData(
['teams', teamId, 'settings'],
(old: TeamSettingsResponse | undefined) => {
if (!old) return old
return {
...old,
transcode: {
...old.transcode,
videoResolutions: updated,
},
}
},
)
isVideoResolutionsUpdatingRef.current = true
videoResolutionsQueueRef.current = videoResolutionsQueueRef.current
.then(async () => {
const target = pendingVideoResolutionsRef.current
if (!target) return
const res = await client.api.teams[':teamId'].settings.$patch({
param: { teamId },
json: {
key: 'transcode.videoResolutions',
value: target,
},
})
if (!res.ok) throw new Error('Failed to update settings')
await res.json()
if (pendingVideoResolutionsRef.current === target) {
pendingVideoResolutionsRef.current = null
isVideoResolutionsUpdatingRef.current = false
setOptimisticVideoResolutions(null)
await queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
toast.success(m.settings_updated())
}
})
.catch((err) => {
console.error(err)
pendingVideoResolutionsRef.current = null
isVideoResolutionsUpdatingRef.current = false
setOptimisticVideoResolutions(null)
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
toast.error(m.failed_update_settings())
})
}
const handleHardwareAccelerationChange = (value: HardwareAcceleration) => {
updateSettings({
teamId,
@@ -349,6 +451,8 @@ function TeamSettingsPage() {
const handleHlsLadderToggle = (ladder: HlsResolutionLadder) => {
const current =
pendingHlsResolutionsRef.current ??
optimisticHlsResolutions ??
(settings as TeamSettingsResponse | undefined)?.transcode?.hlsResolutions ??
DEFAULT_HLS_RESOLUTIONS
const updated = current.includes(ladder)
@@ -357,13 +461,60 @@ function TeamSettingsPage() {
if (updated.length === 0) return
updateSettings({
teamId,
data: {
key: 'transcode.hlsResolutions',
value: updated,
pendingHlsResolutionsRef.current = updated
setOptimisticHlsResolutions(updated)
queryClient.setQueryData(
['teams', teamId, 'settings'],
(old: TeamSettingsResponse | undefined) => {
if (!old) return old
return {
...old,
transcode: {
...old.transcode,
hlsResolutions: updated,
},
}
},
})
)
isHlsResolutionsUpdatingRef.current = true
hlsResolutionsQueueRef.current = hlsResolutionsQueueRef.current
.then(async () => {
const target = pendingHlsResolutionsRef.current
if (!target) return
const res = await client.api.teams[':teamId'].settings.$patch({
param: { teamId },
json: {
key: 'transcode.hlsResolutions',
value: target,
},
})
if (!res.ok) throw new Error('Failed to update settings')
await res.json()
if (pendingHlsResolutionsRef.current === target) {
pendingHlsResolutionsRef.current = null
isHlsResolutionsUpdatingRef.current = false
setOptimisticHlsResolutions(null)
await queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
toast.success(m.settings_updated())
}
})
.catch((err) => {
console.error(err)
pendingHlsResolutionsRef.current = null
isHlsResolutionsUpdatingRef.current = false
setOptimisticHlsResolutions(null)
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
toast.error(m.failed_update_settings())
})
}
if (isSettingsLoading || isMeLoading) {
@@ -383,10 +534,20 @@ function TeamSettingsPage() {
(settings as any)?.transcode?.videoStrategy || VideoTranscodeStrategy.best_match
if (currentVideoStrategy === 'single' || currentVideoStrategy === 'disable') {
currentVideoStrategy = VideoTranscodeStrategy.best_match
} else if (currentVideoStrategy === 'full') {
currentVideoStrategy = VideoTranscodeStrategy.all
} else if (
currentVideoStrategy === 'full' ||
currentVideoStrategy === 'all' ||
currentVideoStrategy === 'multi'
) {
currentVideoStrategy = VideoTranscodeStrategy.multi
}
const currentVideoResolutions: VideoResolutionLadder[] =
optimisticVideoResolutions ??
(settings as TeamSettingsResponse | undefined)?.transcode?.videoResolutions ??
DEFAULT_VIDEO_RESOLUTIONS
const ALL_VIDEO_LADDERS: VideoResolutionLadder[] = ['480p', '720p', '1080p', '1440p', '2160p']
const currentHardwareAcceleration =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(settings as any)?.transcode?.hardwareAcceleration || HardwareAcceleration.off
@@ -395,6 +556,7 @@ function TeamSettingsPage() {
const currentHlsEnabled =
(settings as TeamSettingsResponse | undefined)?.transcode?.hlsEnabled ?? false
const currentHlsResolutions: HlsResolutionLadder[] =
optimisticHlsResolutions ??
(settings as TeamSettingsResponse | undefined)?.transcode?.hlsResolutions ??
DEFAULT_HLS_RESOLUTIONS
const ALL_HLS_LADDERS: HlsResolutionLadder[] = ['480p', '720p', '1080p', '1440p', '2160p']
@@ -842,17 +1004,47 @@ function TeamSettingsPage() {
<div
className={cn(
'cursor-pointer rounded-lg border p-4 transition-all hover:border-primary',
currentVideoStrategy === VideoTranscodeStrategy.all
currentVideoStrategy === VideoTranscodeStrategy.multi
? 'border-primary bg-primary/5'
: 'border-border',
)}
onClick={() => handleVideoStrategyChange(VideoTranscodeStrategy.all)}
onClick={() => handleVideoStrategyChange(VideoTranscodeStrategy.multi)}
>
<div className="font-semibold">{m.all_resolutions()}</div>
<div className="font-semibold">{m.multi_resolutions()}</div>
<div className="text-sm text-muted-foreground">
{m.all_resolutions_description()}
{m.multi_resolutions_description()}
</div>
</div>
{currentVideoStrategy === VideoTranscodeStrategy.multi && (
<div className="space-y-3 pt-2 pl-1">
<div className="space-y-1">
<h4 className="text-sm font-medium">
{m.video_resolution_ladders()}
</h4>
<p className="text-xs text-muted-foreground">
{m.video_resolution_ladders_description()}
</p>
</div>
<div className="flex flex-wrap gap-4 pt-1">
{ALL_VIDEO_LADDERS.map((ladder) => {
const checked = currentVideoResolutions.includes(ladder)
return (
<label
key={ladder}
className="flex items-center space-x-2 cursor-pointer text-sm"
>
<Checkbox
checked={checked}
onCheckedChange={() => handleVideoLadderToggle(ladder)}
/>
<span>{ladder}</span>
</label>
)
})}
</div>
</div>
)}
</div>
</div>
@@ -0,0 +1,241 @@
// @vitest-environment happy-dom
import { cleanup, render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { TeamSettingsPage } from './settings.lazy'
import { toast } from 'sonner'
import { VideoTranscodeStrategy } from '@shumai/dtos'
interface PatchSettingsArgs {
param: { teamId: string }
json: { key: string; value: string[] }
}
const mockGetSettings = vi.fn()
const mockPatchSettings = vi.fn()
const mockGetMe = vi.fn()
vi.mock('@tanstack/react-router', () => ({
createLazyFileRoute: () => (opts: Record<string, unknown>) => ({
...opts,
useParams: () => ({ teamId: 'team-1' }),
}),
useNavigate: () => vi.fn(),
Link: ({ children, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement>) => (
<a {...props}>{children}</a>
),
}))
vi.mock('@/ui/api/client', () => ({
client: {
api: {
teams: {
':teamId': {
settings: {
$get: () => mockGetSettings(),
$patch: (args: unknown) => mockPatchSettings(args),
},
me: {
$get: () => mockGetMe(),
$patch: vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }),
},
},
},
},
},
}))
vi.mock('sonner', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}))
describe('TeamSettingsPage Transcode Settings', () => {
let queryClient: QueryClient
beforeEach(() => {
vi.clearAllMocks()
window.location.hash = '#transcode'
queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
mockGetMe.mockResolvedValue({
ok: true,
json: async () => ({
id: 'user-1',
name: 'Owner',
role: 'owner',
}),
})
mockGetSettings.mockResolvedValue({
ok: true,
json: async () => ({
transcode: {
videoStrategy: VideoTranscodeStrategy.multi,
videoResolutions: ['480p', '720p', '1080p', '1440p', '2160p'],
hardwareAcceleration: 'off',
threads: 0,
hlsEnabled: true,
hlsResolutions: ['480p', '720p', '1080p', '1440p', '2160p'],
},
}),
})
})
afterEach(() => {
cleanup()
})
it('keeps pending selections optimistically and serializes consecutive toggles without submitting stale arrays', async () => {
let resolveFirstPatch!: (value: unknown) => void
const firstPatchPromise = new Promise((resolve) => {
resolveFirstPatch = resolve
})
const patchCalls: PatchSettingsArgs[] = []
mockPatchSettings.mockImplementation(async (args: PatchSettingsArgs) => {
patchCalls.push(args)
if (patchCalls.length === 1) {
await firstPatchPromise
}
return {
ok: true,
json: async () => ({
transcode: {
videoResolutions: args.json.value,
},
}),
}
})
render(
<QueryClientProvider client={queryClient}>
<TeamSettingsPage />
</QueryClientProvider>,
)
// Wait for settings to load
await waitFor(() => {
expect(screen.getAllByText('480p').length).toBeGreaterThan(0)
expect(screen.getAllByText('720p').length).toBeGreaterThan(0)
})
const label480p = screen.getAllByText('480p')[0].closest('label')
const checkbox480p = label480p?.querySelector('button[role="checkbox"]') as HTMLElement
expect(checkbox480p).toBeDefined()
expect(checkbox480p.getAttribute('aria-checked')).toBe('true')
const label720p = screen.getAllByText('720p')[0].closest('label')
const checkbox720p = label720p?.querySelector('button[role="checkbox"]') as HTMLElement
expect(checkbox720p).toBeDefined()
expect(checkbox720p.getAttribute('aria-checked')).toBe('true')
// Click 480p to uncheck it
act(() => {
fireEvent.click(checkbox480p)
})
// Optimistically 480p should be unchecked immediately
expect(checkbox480p.getAttribute('aria-checked')).toBe('false')
// Wait for the first PATCH request to be in-flight
await waitFor(() => {
expect(patchCalls.length).toBe(1)
})
expect(patchCalls[0].json.value).toEqual(['720p', '1080p', '1440p', '2160p'])
// Rapid consecutive click: Click 720p to uncheck it WHILE first patch is in-flight
act(() => {
fireEvent.click(checkbox720p)
})
// Optimistically 720p should also be unchecked immediately
expect(checkbox720p.getAttribute('aria-checked')).toBe('false')
// Resolve first patch so the queue advances to the second queued update
await act(async () => {
resolveFirstPatch({
ok: true,
json: async () => ({
transcode: {
videoResolutions: ['720p', '1080p', '1440p', '2160p'],
},
}),
})
})
// Wait for the second queued patch to complete
await waitFor(() => {
expect(patchCalls.length).toBe(2)
})
// The second patch MUST NOT submit stale array with 480p present!
// It must contain neither 480p nor 720p
expect(patchCalls[1].json.value).toEqual(['1080p', '1440p', '2160p'])
expect(patchCalls[1].json.value.includes('480p')).toBe(false)
expect(patchCalls[1].json.value.includes('720p')).toBe(false)
// Verify toast notification on success
expect(toast.success).toHaveBeenCalled()
})
it('coalesces rapid consecutive toggles before network dispatch into a single PATCH', async () => {
const patchCalls: PatchSettingsArgs[] = []
mockPatchSettings.mockImplementation(async (args: PatchSettingsArgs) => {
patchCalls.push(args)
return {
ok: true,
json: async () => ({
transcode: {
videoResolutions: args.json.value,
},
}),
}
})
render(
<QueryClientProvider client={queryClient}>
<TeamSettingsPage />
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getAllByText('480p').length).toBeGreaterThan(0)
})
const label480p = screen.getAllByText('480p')[0].closest('label')
const checkbox480p = label480p?.querySelector('button[role="checkbox"]') as HTMLElement
const label720p = screen.getAllByText('720p')[0].closest('label')
const checkbox720p = label720p?.querySelector('button[role="checkbox"]') as HTMLElement
// Rapid synchronous clicks in the same event tick
act(() => {
fireEvent.click(checkbox480p)
fireEvent.click(checkbox720p)
})
// Both reflect optimistically
expect(checkbox480p.getAttribute('aria-checked')).toBe('false')
expect(checkbox720p.getAttribute('aria-checked')).toBe('false')
// Wait for the coalesced PATCH to complete
await waitFor(() => {
expect(patchCalls.length).toBeGreaterThanOrEqual(1)
})
// The submitted payload must reflect both toggles
const lastPatch = patchCalls[patchCalls.length - 1]
expect(lastPatch.json.value).toEqual(['1080p', '1440p', '2160p'])
})
})