feat(transcode): add 3D asset support and turntable viewer (#454)

* feat(transcode): add 3D asset support and turntable viewer

* perf(turntable): stream file via Bun.file and increase upload timeout

* feat(turntable): increase upload timeout to 15m to support 5GB uploads

* fix(webui): align 3D model viewer layout and full-width control bar with video viewer

* feat(webui): unify 3D viewer bottom bar and redesign cyclic ruler slider

- Place RulerSlider in single row with playback and zoom controls, centered with max 320px width
- Flank RulerSlider with minus and plus buttons to step angle by 15°
- Redesign RulerSlider with fixed center indicator and moving cyclic track with continuous 360° wrapping
- Render major ticks longer at 60° intervals without numeric text labels on track
- Display floating degree tooltip above center indicator only during dragging

* fix(webui): prevent RulerSlider from collapsing to 0px width in control bar

- Use flex layout with flex-1 on left and right clusters to preserve center cluster width
- Enforce min-w-[140px] and w-full on RulerSlider
- Fix tooltip positioning and remove outer overflow-hidden

* feat(webui): snap RulerSlider track directly to discrete 15° ticks during drag

* fix(webui): prevent ruler snap-back caused by floating point second truncation

- Use Math.round instead of Math.floor in secondToDegree to avoid 0.999996 dropping to previous frame
- Ensure final dragDegree is committed on pointer up

* fix(webui): fix arrow key frame rounding and duplicate event bubbling

- Use Math.round instead of Math.floor for keyboard arrow frame navigation in ModelViewer
- Add e.stopPropagation() to RulerSlider keyboard events to prevent duplicate bubbling to window listener

* feat(webui): redesign RulerSlider with encapsulated step buttons and capsule pill track

* feat(webui): make RulerSlider responsive on mobile and remove bottom bar reset button

* fix(webui): load 3d video directly without poster and invert drag rotation to counterclockwise

* fix(webui): fix 3d asset viewer frame seeking and drag jitter

* feat(transcode): show 3D asset poster preview immediately after render start

* fix(viewer): synchronize 3D turntable playback via frame callback to prevent skipped degrees

* fix(viewer): handle touchpad zoom gestures and prevent page zoom in 3D viewer

* fix(viewer): eliminate 3D model rotation jitter at 345 degrees

* fix(share): watermark 3D asset turntable video on share links

* fix(share): preserve video transcode resolution on watermarked share links

* fix(viewer): download original 3D model file instead of rendered turntable MP4
This commit is contained in:
Yiling-J
2026-10-11 21:32:28 +08:00
committed by GitHub
parent e894457275
commit 43a2eced75
68 changed files with 5548 additions and 59 deletions
@@ -0,0 +1,237 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import * as os from 'os'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { TurntableService } from './turntable'
describe('TurntableService', () => {
setupTestDbHooks()
const originalEnv = process.env
let tmpDir: string
let testFilePath: string
beforeEach(() => {
process.env = { ...originalEnv }
delete process.env.TURNTABLE_RENDERER_URL
delete process.env.TURNTABLE_RENDERER_BASIC_AUTH_USERNAME
delete process.env.TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD
delete process.env.TURNTABLE_RENDERER_USERNAME
delete process.env.TURNTABLE_RENDERER_PASSWORD
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'turntable-test-'))
testFilePath = path.join(tmpDir, 'model.glb')
fs.writeFileSync(testFilePath, 'fake glb content')
})
afterEach(() => {
process.env = originalEnv
fs.rmSync(tmpDir, { recursive: true, force: true })
vi.restoreAllMocks()
})
describe('resolveConfig', () => {
it('returns isEnv: false when neither env nor team settings are present', async () => {
const service = new TurntableService()
const config = await service.resolveConfig()
expect(config.url).toBeUndefined()
expect(config.isEnv).toBe(false)
})
it('resolves env configuration with highest priority', async () => {
process.env.TURNTABLE_RENDERER_URL = 'http://localhost:3000/'
process.env.TURNTABLE_RENDERER_BASIC_AUTH_USERNAME = 'admin'
process.env.TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD = 'secret'
const service = new TurntableService()
const config = await service.resolveConfig('any-team-id')
expect(config.url).toBe('http://localhost:3000')
expect(config.username).toBe('admin')
expect(config.password).toBe('secret')
expect(config.isEnv).toBe(true)
})
it('falls back to team DB settings when env is not set', async () => {
const team = await prisma.team.create({
data: {
name: 'Test Team 3D',
settings: {
turntable: {
url: 'http://custom-turntable:4000',
username: 'teamUser',
password: 'teamPassword',
},
},
},
})
const service = new TurntableService()
const config = await service.resolveConfig(team.id)
expect(config.url).toBe('http://custom-turntable:4000')
expect(config.username).toBe('teamUser')
expect(config.password).toBe('teamPassword')
expect(config.isEnv).toBe(false)
})
})
describe('isAvailable', () => {
it('returns false if URL is not configured', async () => {
const service = new TurntableService()
expect(await service.isAvailable()).toBe(false)
})
it('returns true when health check returns 200', async () => {
process.env.TURNTABLE_RENDERER_URL = 'http://turntable:3000'
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 200,
} as Response)
const service = new TurntableService()
expect(await service.isAvailable()).toBe(true)
})
it('returns false when health check fails or throws', async () => {
process.env.TURNTABLE_RENDERER_URL = 'http://turntable:3000'
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('Connection refused'))
const service = new TurntableService()
expect(await service.isAvailable()).toBe(false)
})
})
describe('testConnection', () => {
it('returns error when url is empty', async () => {
const service = new TurntableService()
const result = await service.testConnection({})
expect(result.ok).toBe(false)
expect(result.error).toBe('URL is required')
})
it('returns version information upon successful connection', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 200,
json: async () => ({ version: '0.1.0', blender: '5.2.2' }),
} as Response)
const service = new TurntableService()
const result = await service.testConnection({ url: 'http://localhost:3000' })
expect(result.ok).toBe(true)
expect(result.version).toBe('0.1.0')
expect(result.blender).toBe('5.2.2')
})
})
describe('uploadFile', () => {
it('posts file buffer to /v1/files and returns file info', async () => {
process.env.TURNTABLE_RENDERER_URL = 'http://turntable:3000'
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 201,
json: async () => ({ id: 'f_test123', name: 'model.glb', size: 100 }),
} as Response)
const service = new TurntableService()
const res = await service.uploadFile(testFilePath, 'model.glb')
expect(res.id).toBe('f_test123')
expect(fetchSpy).toHaveBeenCalledWith(
'http://turntable:3000/v1/files',
expect.objectContaining({
method: 'POST',
}),
)
})
})
describe('startRender & getTaskStatus & downloadFile & deleteTask', () => {
beforeEach(() => {
process.env.TURNTABLE_RENDERER_URL = 'http://turntable:3000'
})
it('startRender calls /v1/render and returns sync response', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 200,
json: async () => ({
taskId: 't_test456',
status: 'queued',
poster: {
fileId: 'f_poster',
size: 200,
contentType: 'image/png',
width: 1080,
height: 1080,
},
}),
} as Response)
const service = new TurntableService()
const res = await service.startRender('f_input')
expect(res.taskId).toBe('t_test456')
expect(res.poster.fileId).toBe('f_poster')
})
it('getTaskStatus queries /v1/render/tasks/:id', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 200,
json: async () => ({
taskId: 't_test456',
status: 'completed',
video: {
fileId: 'f_video',
size: 1000,
contentType: 'video/mp4',
width: 1080,
height: 1080,
},
}),
} as Response)
const service = new TurntableService()
const res = await service.getTaskStatus('t_test456')
expect(res.status).toBe('completed')
expect(res.video?.fileId).toBe('f_video')
})
it('downloadFile fetches /v1/files/:id and writes to destination', async () => {
const destPath = path.join(tmpDir, 'downloaded.mp4')
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 200,
arrayBuffer: async () => Buffer.from('video data').buffer,
} as Response)
const service = new TurntableService()
await service.downloadFile('f_video', destPath)
expect(fs.existsSync(destPath)).toBe(true)
expect(fs.readFileSync(destPath, 'utf8')).toBe('video data')
})
it('deleteTask calls DELETE /v1/render/tasks/:id and returns boolean', async () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 200,
} as Response)
const service = new TurntableService()
const deleted = await service.deleteTask('t_test456')
expect(deleted).toBe(true)
expect(fetchSpy).toHaveBeenCalledWith(
'http://turntable:3000/v1/render/tasks/t_test456',
expect.objectContaining({
method: 'DELETE',
}),
)
})
})
})
+437
View File
@@ -0,0 +1,437 @@
import * as fs from 'fs'
import { prisma } from '@shumai/db'
import type { TurntableSettingsResponse, UpdateTurntableSettingsRequest } from '@shumai/dtos'
import { logger } from '../logger'
export interface TurntableConfig {
url?: string
username?: string
password?: string
isEnv: boolean
}
export interface TurntablePosterOutput {
fileId: string
size: number
contentType: string
width: number
height: number
}
export interface TurntableRenderSyncResponse {
taskId: string
status: 'queued' | 'rendering'
positionInQueue?: number
metadata?: Record<string, unknown>
poster: TurntablePosterOutput
}
export interface TurntableVideoOutput {
fileId: string
size: number
contentType: string
width: number
height: number
}
export interface TurntableRenderStats {
width: number
height: number
frames: number
fps: number
durationSeconds: number
degreesPerFrame: number
startAngle: number
direction: string
includeEndFrame: boolean
engine: string
elapsedMs: number
}
export interface TurntableTaskResponse {
taskId: string
status: 'queued' | 'rendering' | 'completed' | 'failed'
positionInQueue?: number
createdAt: string
startedAt?: string
completedAt?: string
failedAt?: string
render?: TurntableRenderStats
video?: TurntableVideoOutput
error?: {
code: string
message: string
details?: Record<string, unknown>
}
}
export class TurntableService {
async resolveConfig(teamId?: string): Promise<TurntableConfig> {
const envUrl = process.env.TURNTABLE_RENDERER_URL?.trim()
const envUsername =
process.env.TURNTABLE_RENDERER_BASIC_AUTH_USERNAME?.trim() ||
process.env.TURNTABLE_RENDERER_USERNAME?.trim()
const envPassword =
process.env.TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD?.trim() ||
process.env.TURNTABLE_RENDERER_PASSWORD?.trim()
if (envUrl) {
return {
url: envUrl.replace(/\/+$/, ''),
username: envUsername || undefined,
password: envPassword || undefined,
isEnv: true,
}
}
if (teamId) {
try {
const team = await prisma.team.findUnique({
where: { id: teamId },
select: { settings: true },
})
const teamSettings = team?.settings as PrismaJson.Settings | null
const turntable = teamSettings?.turntable
if (turntable?.url?.trim()) {
return {
url: turntable.url.trim().replace(/\/+$/, ''),
username: turntable.username?.trim() || undefined,
password: turntable.password?.trim() || undefined,
isEnv: false,
}
}
} catch (err) {
logger.error({ err, teamId }, 'Failed to load team turntable settings')
}
}
return {
isEnv: false,
}
}
private getAuthHeader(config: TurntableConfig): string | undefined {
if (config.username && config.password) {
const credentials = Buffer.from(`${config.username}:${config.password}`).toString('base64')
return `Basic ${credentials}`
}
return undefined
}
async isAvailable(teamId?: string): Promise<boolean> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
return false
}
try {
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/health`, {
method: 'GET',
headers,
signal: AbortSignal.timeout(3000),
})
return response.ok
} catch {
return false
}
}
async getSettings(teamId: string): Promise<TurntableSettingsResponse> {
const config = await this.resolveConfig(teamId)
return {
url: config.url,
username: config.username,
hasPassword: Boolean(config.password),
isEnvConfigured: config.isEnv,
}
}
async updateSettings(
teamId: string,
req: UpdateTurntableSettingsRequest,
): Promise<TurntableSettingsResponse> {
const currentConfig = await this.resolveConfig(teamId)
if (currentConfig.isEnv) {
throw new Error(
'Turntable settings are configured via environment variables and cannot be edited',
)
}
const team = await prisma.team.findUnique({
where: { id: teamId },
select: { settings: true },
})
const settings = (team?.settings || {}) as PrismaJson.Settings
const prevTurntable = settings.turntable || {}
settings.turntable = {
url: req.url !== undefined ? req.url : prevTurntable.url,
username: req.username !== undefined ? req.username : prevTurntable.username,
password: req.password !== undefined ? req.password : prevTurntable.password,
}
await prisma.team.update({
where: { id: teamId },
data: { settings },
})
return this.getSettings(teamId)
}
async testConnection(
config?: {
url?: string
username?: string
password?: string
},
teamId?: string,
): Promise<{ ok: boolean; version?: string; blender?: string; error?: string }> {
let resolvedUrl = config?.url?.trim()
let resolvedUsername = config?.username?.trim()
let resolvedPassword = config?.password
if (teamId && (!resolvedUrl || resolvedPassword === undefined)) {
const savedConfig = await this.resolveConfig(teamId)
if (!resolvedUrl) {
resolvedUrl = savedConfig.url
}
if (!resolvedUsername && savedConfig.username) {
resolvedUsername = savedConfig.username
}
if (resolvedPassword === undefined) {
resolvedPassword = savedConfig.password
}
}
if (!resolvedUrl) {
return { ok: false, error: 'URL is required' }
}
const cleanUrl = resolvedUrl.replace(/\/+$/, '')
try {
const headers: Record<string, string> = {}
if (resolvedUsername && resolvedPassword) {
const credentials = Buffer.from(`${resolvedUsername}:${resolvedPassword}`).toString(
'base64',
)
headers['Authorization'] = `Basic ${credentials}`
}
const response = await fetch(`${cleanUrl}/version`, {
method: 'GET',
headers,
signal: AbortSignal.timeout(5000),
})
if (!response.ok) {
const errText = await response.text().catch(() => '')
return {
ok: false,
error: `Server returned status ${response.status}: ${errText || response.statusText}`,
}
}
const body = (await response.json()) as { version?: string; blender?: string }
return {
ok: true,
version: body.version,
blender: body.blender,
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
return { ok: false, error: message }
}
}
async uploadFile(
filePath: string,
filename: string,
teamId?: string,
): Promise<{ id: string; name: string; size: number }> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
throw new Error('Turntable renderer URL is not configured.')
}
const headers: Record<string, string> = {
'content-type': 'application/octet-stream',
'x-filename': encodeURIComponent(filename),
}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/v1/files`, {
method: 'POST',
headers,
body: Bun.file(filePath),
signal: AbortSignal.timeout(900000),
})
if (!response.ok) {
const errorText = await response.text().catch(() => '')
throw new Error(
`Turntable upload failed with status ${response.status}: ${errorText || response.statusText}`,
)
}
return (await response.json()) as { id: string; name: string; size: number }
}
async startRender(
fileId: string,
options: Record<string, unknown> = {},
teamId?: string,
): Promise<TurntableRenderSyncResponse> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
throw new Error('Turntable renderer URL is not configured.')
}
const headers: Record<string, string> = {
'content-type': 'application/json',
}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/v1/render`, {
method: 'POST',
headers,
body: JSON.stringify({
input: { fileId },
options,
}),
signal: AbortSignal.timeout(60000),
})
if (!response.ok) {
const errorText = await response.text().catch(() => '')
throw new Error(
`Turntable render request failed with status ${response.status}: ${errorText || response.statusText}`,
)
}
return (await response.json()) as TurntableRenderSyncResponse
}
async getTaskStatus(taskId: string, teamId?: string): Promise<TurntableTaskResponse> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
throw new Error('Turntable renderer URL is not configured.')
}
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/v1/render/tasks/${taskId}`, {
method: 'GET',
headers,
signal: AbortSignal.timeout(10000),
})
if (!response.ok) {
const errorText = await response.text().catch(() => '')
throw new Error(
`Failed to fetch task status (${response.status}): ${errorText || response.statusText}`,
)
}
return (await response.json()) as TurntableTaskResponse
}
async downloadFile(fileId: string, targetPath?: string, teamId?: string): Promise<Buffer> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
throw new Error('Turntable renderer URL is not configured.')
}
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/v1/files/${fileId}`, {
method: 'GET',
headers,
signal: AbortSignal.timeout(120000),
})
if (!response.ok) {
const errorText = await response.text().catch(() => '')
throw new Error(
`Failed to download file ${fileId} (${response.status}): ${errorText || response.statusText}`,
)
}
const arrayBuffer = await response.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
if (targetPath) {
fs.writeFileSync(targetPath, buffer)
}
return buffer
}
async deleteTask(taskId: string, teamId?: string): Promise<boolean> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
return false
}
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
try {
const response = await fetch(`${config.url}/v1/render/tasks/${taskId}`, {
method: 'DELETE',
headers,
signal: AbortSignal.timeout(10000),
})
return response.ok
} catch {
return false
}
}
async deleteFile(fileId: string, teamId?: string): Promise<boolean> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
return false
}
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
try {
const response = await fetch(`${config.url}/v1/files/${fileId}`, {
method: 'DELETE',
headers,
signal: AbortSignal.timeout(10000),
})
return response.ok
} catch {
return false
}
}
}
export const turntableService = new TurntableService()