mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 02:58:19 +00:00
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:
@@ -0,0 +1,327 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
render3dModelActivity,
|
||||
start3dRenderActivity,
|
||||
waitFor3dVideoRenderActivity,
|
||||
generate3dSpriteActivity,
|
||||
} from './transcode'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { transcodeService } from '@shumai/core/src/transcode/transcode'
|
||||
import * as fs from 'fs'
|
||||
|
||||
vi.mock('@shumai/core/src/turntable/turntable', () => ({
|
||||
turntableService: {
|
||||
uploadFile: vi.fn(),
|
||||
startRender: vi.fn(),
|
||||
getTaskStatus: vi.fn(),
|
||||
downloadFile: vi.fn(),
|
||||
deleteTask: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
putObject: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/transcode/transcode', () => ({
|
||||
transcodeService: {
|
||||
convertImageToWebp: vi.fn(),
|
||||
generate3dSprite: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/asset/asset', () => ({
|
||||
assetService: {
|
||||
isAssetPurging: vi.fn().mockResolvedValue(false),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('fs')>()
|
||||
return {
|
||||
...actual,
|
||||
readFileSync: vi.fn(),
|
||||
writeFileSync: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('3D Transcode Activities', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(fs.readFileSync).mockReturnValue(Buffer.from('mock-bytes'))
|
||||
vi.mocked(transcodeService.convertImageToWebp).mockResolvedValue(Buffer.from('webp-bytes'))
|
||||
vi.mocked(transcodeService.generate3dSprite).mockResolvedValue()
|
||||
vi.mocked(s3Service.putObject).mockResolvedValue({} as never)
|
||||
vi.mocked(turntableService.deleteTask).mockResolvedValue(true)
|
||||
})
|
||||
|
||||
describe('start3dRenderActivity', () => {
|
||||
it('uploads file, starts render, immediately downloads and uploads poster to S3', async () => {
|
||||
vi.mocked(turntableService.uploadFile).mockResolvedValue({
|
||||
id: 'f_input',
|
||||
name: 'model.glb',
|
||||
size: 1024,
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.startRender).mockResolvedValue({
|
||||
taskId: 'task_render_1',
|
||||
status: 'queued',
|
||||
poster: {
|
||||
fileId: 'f_poster',
|
||||
contentType: 'image/png',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
size: 5000,
|
||||
},
|
||||
metadata: { format: 'glb', vertices: 120 },
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.downloadFile).mockResolvedValue(Buffer.from('poster-raw-data'))
|
||||
|
||||
const res = await start3dRenderActivity({
|
||||
taskId: 'wf-task-1',
|
||||
teamId: 'team-1',
|
||||
assetId: 'asset-1',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
filePath: '/tmp/model.glb',
|
||||
filename: 'model.glb',
|
||||
targetPosterKey: 'files/asset-1/poster.webp',
|
||||
})
|
||||
|
||||
expect(turntableService.uploadFile).toHaveBeenCalledWith(
|
||||
'/tmp/model.glb',
|
||||
'model.glb',
|
||||
'team-1',
|
||||
)
|
||||
expect(turntableService.startRender).toHaveBeenCalledWith('f_input', {}, 'team-1')
|
||||
expect(turntableService.downloadFile).toHaveBeenCalledWith('f_poster', undefined, 'team-1')
|
||||
expect(transcodeService.convertImageToWebp).toHaveBeenCalledWith(
|
||||
Buffer.from('poster-raw-data'),
|
||||
)
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/asset-1/poster.webp',
|
||||
Buffer.from('webp-bytes'),
|
||||
Buffer.from('webp-bytes').length,
|
||||
'image/webp',
|
||||
)
|
||||
|
||||
expect(res.renderTaskId).toBe('task_render_1')
|
||||
expect(res.posterFilePath).toBe('/tmp/poster.webp')
|
||||
expect(res.posterWidth).toBe(1080)
|
||||
expect(res.posterHeight).toBe(1080)
|
||||
expect(res.modelMetadata).toEqual({ format: 'glb', vertices: 120 })
|
||||
})
|
||||
|
||||
it('throws ApplicationFailure when poster file ID is missing', async () => {
|
||||
vi.mocked(turntableService.uploadFile).mockResolvedValue({
|
||||
id: 'f_input',
|
||||
name: 'model.glb',
|
||||
size: 1024,
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.startRender).mockResolvedValue({
|
||||
taskId: 'task_render_1',
|
||||
status: 'queued',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
poster: undefined as any,
|
||||
})
|
||||
|
||||
await expect(
|
||||
start3dRenderActivity({
|
||||
taskId: 'wf-task-1',
|
||||
teamId: 'team-1',
|
||||
assetId: 'asset-1',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
filePath: '/tmp/model.glb',
|
||||
filename: 'model.glb',
|
||||
targetPosterKey: 'files/asset-1/poster.webp',
|
||||
}),
|
||||
).rejects.toThrow('Poster file ID missing from turntable render result')
|
||||
|
||||
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_1', 'team-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('waitFor3dVideoRenderActivity', () => {
|
||||
it('polls until complete, downloads video, uploads to S3, and cleans up task', async () => {
|
||||
vi.mocked(turntableService.getTaskStatus).mockResolvedValue({
|
||||
taskId: 'task_render_1',
|
||||
status: 'completed',
|
||||
createdAt: new Date().toISOString(),
|
||||
video: {
|
||||
fileId: 'f_video',
|
||||
contentType: 'video/mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
size: 1000,
|
||||
},
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.downloadFile).mockResolvedValue(Buffer.from('video-data'))
|
||||
|
||||
const res = await waitFor3dVideoRenderActivity({
|
||||
taskId: 'wf-task-1',
|
||||
teamId: 'team-1',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
renderTaskId: 'task_render_1',
|
||||
targetVideoKey: 'files/asset-1/turntable.mp4',
|
||||
tmpDir: '/tmp',
|
||||
})
|
||||
|
||||
expect(turntableService.getTaskStatus).toHaveBeenCalledWith('task_render_1', 'team-1')
|
||||
expect(turntableService.downloadFile).toHaveBeenCalledWith(
|
||||
'f_video',
|
||||
'/tmp/turntable.mp4',
|
||||
'team-1',
|
||||
)
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/asset-1/turntable.mp4',
|
||||
Buffer.from('video-data'),
|
||||
Buffer.from('video-data').length,
|
||||
'video/mp4',
|
||||
)
|
||||
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_1', 'team-1')
|
||||
expect(res.videoFilePath).toBe('/tmp/turntable.mp4')
|
||||
})
|
||||
|
||||
it('throws ApplicationFailure when render fails on turntable-renderer', async () => {
|
||||
vi.mocked(turntableService.getTaskStatus).mockResolvedValue({
|
||||
taskId: 'task_render_2',
|
||||
status: 'failed',
|
||||
createdAt: new Date().toISOString(),
|
||||
error: {
|
||||
code: 'render_failed',
|
||||
message: 'Blender failed to import model',
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
waitFor3dVideoRenderActivity({
|
||||
taskId: 'wf-task-2',
|
||||
teamId: 'team-1',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
renderTaskId: 'task_render_2',
|
||||
targetVideoKey: 'files/asset-1/turntable.mp4',
|
||||
tmpDir: '/tmp',
|
||||
}),
|
||||
).rejects.toThrow('Blender failed to import model')
|
||||
|
||||
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_2', 'team-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('render3dModelActivity (legacy wrapper)', () => {
|
||||
it('uploads file, starts render, polls until complete, and uploads to S3', async () => {
|
||||
vi.mocked(turntableService.uploadFile).mockResolvedValue({
|
||||
id: 'f_input',
|
||||
name: 'model.glb',
|
||||
size: 1024,
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.startRender).mockResolvedValue({
|
||||
taskId: 'task_render_1',
|
||||
status: 'queued',
|
||||
poster: {
|
||||
fileId: 'f_poster',
|
||||
contentType: 'image/png',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
size: 5000,
|
||||
},
|
||||
metadata: { format: 'glb', vertices: 120 },
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.getTaskStatus).mockResolvedValue({
|
||||
taskId: 'task_render_1',
|
||||
status: 'completed',
|
||||
createdAt: new Date().toISOString(),
|
||||
video: {
|
||||
fileId: 'f_video',
|
||||
contentType: 'video/mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
size: 1000,
|
||||
},
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.downloadFile).mockResolvedValue(Buffer.from('downloaded-data'))
|
||||
|
||||
const res = await render3dModelActivity({
|
||||
taskId: 'wf-task-1',
|
||||
teamId: 'team-1',
|
||||
assetId: 'asset-1',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
filePath: '/tmp/model.glb',
|
||||
filename: 'model.glb',
|
||||
targetVideoKey: 'files/asset-1/turntable.mp4',
|
||||
targetPosterKey: 'files/asset-1/poster.webp',
|
||||
})
|
||||
|
||||
expect(turntableService.uploadFile).toHaveBeenCalledWith(
|
||||
'/tmp/model.glb',
|
||||
'model.glb',
|
||||
'team-1',
|
||||
)
|
||||
expect(turntableService.startRender).toHaveBeenCalledWith('f_input', {}, 'team-1')
|
||||
expect(turntableService.getTaskStatus).toHaveBeenCalledWith('task_render_1', 'team-1')
|
||||
expect(turntableService.downloadFile).toHaveBeenCalledWith(
|
||||
'f_video',
|
||||
'/tmp/turntable.mp4',
|
||||
'team-1',
|
||||
)
|
||||
expect(turntableService.downloadFile).toHaveBeenCalledWith('f_poster', undefined, 'team-1')
|
||||
expect(transcodeService.convertImageToWebp).toHaveBeenCalledWith(expect.any(Buffer))
|
||||
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/asset-1/turntable.mp4',
|
||||
expect.any(Buffer),
|
||||
expect.any(Number),
|
||||
'video/mp4',
|
||||
)
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/asset-1/poster.webp',
|
||||
expect.any(Buffer),
|
||||
expect.any(Number),
|
||||
'image/webp',
|
||||
)
|
||||
|
||||
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_1', 'team-1')
|
||||
expect(res.modelMetadata).toEqual({ format: 'glb', vertices: 120 })
|
||||
expect(res.videoFilePath).toBe('/tmp/turntable.mp4')
|
||||
expect(res.posterFilePath).toBe('/tmp/poster.webp')
|
||||
})
|
||||
})
|
||||
|
||||
describe('generate3dSpriteActivity', () => {
|
||||
it('generates 3d sprite sheet and uploads to S3', async () => {
|
||||
const res = await generate3dSpriteActivity({
|
||||
taskId: 'wf-task-3',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
videoFilePath: '/tmp/turntable.mp4',
|
||||
spriteKey: 'files/asset-1/sprite.webp',
|
||||
})
|
||||
|
||||
expect(transcodeService.generate3dSprite).toHaveBeenCalledWith(
|
||||
'/tmp/turntable.mp4',
|
||||
'/tmp/sprite.webp',
|
||||
undefined,
|
||||
)
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/asset-1/sprite.webp',
|
||||
expect.any(Buffer),
|
||||
expect.any(Number),
|
||||
'image/webp',
|
||||
)
|
||||
expect(res.spriteKey).toBe('files/asset-1/sprite.webp')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { getDerivedArtifactDirectory, stemFromKey } from '@shumai/core/src/utils/filename'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { parseCsvContent } from '@shumai/core/src/transcode/transcode'
|
||||
import { resolutionToDimensions } from '../workflows/transcode-utils'
|
||||
import {
|
||||
@@ -1551,3 +1552,316 @@ export async function deleteS3ObjectActivity(params: { key: string }): Promise<v
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
await s3Service.deleteObject(bucket, params.key)
|
||||
}
|
||||
|
||||
export interface Render3dModelActivityParams {
|
||||
taskId: string
|
||||
teamId: string
|
||||
assetId: string
|
||||
assetKey: string
|
||||
filePath: string
|
||||
filename: string
|
||||
targetVideoKey: string
|
||||
targetPosterKey: string
|
||||
}
|
||||
|
||||
export interface Render3dModelActivityResult {
|
||||
videoFilePath: string
|
||||
posterFilePath: string
|
||||
modelMetadata?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface Start3dRenderActivityParams {
|
||||
taskId: string
|
||||
teamId: string
|
||||
assetId: string
|
||||
assetKey: string
|
||||
filePath: string
|
||||
filename: string
|
||||
targetPosterKey: string
|
||||
}
|
||||
|
||||
export interface Start3dRenderActivityResult {
|
||||
renderTaskId: string
|
||||
posterFilePath: string
|
||||
posterWidth?: number
|
||||
posterHeight?: number
|
||||
modelMetadata?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export async function start3dRenderActivity(
|
||||
params: Start3dRenderActivityParams,
|
||||
): Promise<Start3dRenderActivityResult> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Render cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
const posterFilePath = path.join(tmpDir, 'poster.webp')
|
||||
|
||||
let fileId: string | undefined
|
||||
let renderTaskId: string | undefined
|
||||
|
||||
try {
|
||||
const uploadResult = await turntableService.uploadFile(
|
||||
params.filePath,
|
||||
params.filename,
|
||||
params.teamId,
|
||||
)
|
||||
fileId = uploadResult.id
|
||||
|
||||
if (signal?.aborted) {
|
||||
await turntableService.deleteFile(fileId, params.teamId).catch(() => {})
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Render cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const startResult = await turntableService.startRender(fileId, {}, params.teamId)
|
||||
renderTaskId = startResult.taskId
|
||||
|
||||
const posterFileId = startResult.poster?.fileId
|
||||
if (!posterFileId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Poster file ID missing from turntable render result',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const posterBuffer = await turntableService.downloadFile(posterFileId, undefined, params.teamId)
|
||||
const posterWebpBuffer = await transcodeService.convertImageToWebp(posterBuffer)
|
||||
fs.writeFileSync(posterFilePath, posterWebpBuffer)
|
||||
|
||||
await ensureAssetNotPurging(params.assetKey)
|
||||
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
params.targetPosterKey,
|
||||
posterWebpBuffer,
|
||||
posterWebpBuffer.length,
|
||||
'image/webp',
|
||||
)
|
||||
|
||||
return {
|
||||
renderTaskId,
|
||||
posterFilePath,
|
||||
posterWidth: startResult.poster?.width,
|
||||
posterHeight: startResult.poster?.height,
|
||||
modelMetadata: (startResult.metadata as Record<string, unknown>) || {},
|
||||
}
|
||||
} catch (err) {
|
||||
if (renderTaskId) {
|
||||
await turntableService.deleteTask(renderTaskId, params.teamId).catch(() => {})
|
||||
} else if (fileId) {
|
||||
await turntableService.deleteFile(fileId, params.teamId).catch(() => {})
|
||||
}
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
}
|
||||
const errMsg = err instanceof Error ? err.message : String(err)
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to start 3D render: ${errMsg}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export interface WaitFor3dVideoRenderActivityParams {
|
||||
taskId: string
|
||||
teamId: string
|
||||
assetKey: string
|
||||
renderTaskId: string
|
||||
targetVideoKey: string
|
||||
tmpDir: string
|
||||
}
|
||||
|
||||
export interface WaitFor3dVideoRenderActivityResult {
|
||||
videoFilePath: string
|
||||
}
|
||||
|
||||
export async function waitFor3dVideoRenderActivity(
|
||||
params: WaitFor3dVideoRenderActivityParams,
|
||||
): Promise<WaitFor3dVideoRenderActivityResult> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
await turntableService.deleteTask(params.renderTaskId, params.teamId).catch(() => {})
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Render cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const videoFilePath = path.join(params.tmpDir, 'turntable.mp4')
|
||||
|
||||
try {
|
||||
let finishedStatus: 'completed' | 'failed' | null = null
|
||||
let taskRecord: Awaited<ReturnType<typeof turntableService.getTaskStatus>> | null = null
|
||||
|
||||
for (let i = 0; i < 360; i++) {
|
||||
if (signal?.aborted) {
|
||||
await turntableService.deleteTask(params.renderTaskId, params.teamId).catch(() => {})
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Render cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
if (i > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 5000))
|
||||
}
|
||||
|
||||
taskRecord = await turntableService.getTaskStatus(params.renderTaskId, params.teamId)
|
||||
if (taskRecord.status === 'completed') {
|
||||
finishedStatus = 'completed'
|
||||
break
|
||||
}
|
||||
if (taskRecord.status === 'failed') {
|
||||
finishedStatus = 'failed'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (finishedStatus !== 'completed' || !taskRecord) {
|
||||
const errMsg =
|
||||
finishedStatus === 'failed'
|
||||
? taskRecord?.error?.message || '3D render failed on turntable server'
|
||||
: '3D render timed out on turntable server'
|
||||
throw ApplicationFailure.create({
|
||||
message: errMsg,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const videoFileId = taskRecord.video?.fileId
|
||||
if (!videoFileId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Video file ID missing from turntable render result',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const videoBuffer = await turntableService.downloadFile(
|
||||
videoFileId,
|
||||
videoFilePath,
|
||||
params.teamId,
|
||||
)
|
||||
|
||||
await ensureAssetNotPurging(params.assetKey)
|
||||
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
params.targetVideoKey,
|
||||
videoBuffer,
|
||||
videoBuffer.length,
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
await turntableService.deleteTask(params.renderTaskId, params.teamId).catch((err) => {
|
||||
logger.warn(
|
||||
{ err, taskId: params.renderTaskId },
|
||||
'Failed to delete turntable task after completion',
|
||||
)
|
||||
})
|
||||
|
||||
return {
|
||||
videoFilePath,
|
||||
}
|
||||
} catch (err) {
|
||||
await turntableService.deleteTask(params.renderTaskId, params.teamId).catch(() => {})
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
}
|
||||
const errMsg = err instanceof Error ? err.message : String(err)
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to render 3D model video: ${errMsg}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Legacy monolithic 3D render activity. Prefer using `start3dRenderActivity` and `waitFor3dVideoRenderActivity`.
|
||||
*/
|
||||
export async function render3dModelActivity(
|
||||
params: Render3dModelActivityParams,
|
||||
): Promise<Render3dModelActivityResult> {
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
const startResult = await start3dRenderActivity({
|
||||
taskId: params.taskId,
|
||||
teamId: params.teamId,
|
||||
assetId: params.assetId,
|
||||
assetKey: params.assetKey,
|
||||
filePath: params.filePath,
|
||||
filename: params.filename,
|
||||
targetPosterKey: params.targetPosterKey,
|
||||
})
|
||||
|
||||
const videoResult = await waitFor3dVideoRenderActivity({
|
||||
taskId: params.taskId,
|
||||
teamId: params.teamId,
|
||||
assetKey: params.assetKey,
|
||||
renderTaskId: startResult.renderTaskId,
|
||||
targetVideoKey: params.targetVideoKey,
|
||||
tmpDir,
|
||||
})
|
||||
|
||||
return {
|
||||
videoFilePath: videoResult.videoFilePath,
|
||||
posterFilePath: startResult.posterFilePath,
|
||||
modelMetadata: startResult.modelMetadata,
|
||||
}
|
||||
}
|
||||
|
||||
export interface Generate3dSpriteActivityParams {
|
||||
taskId: string
|
||||
assetKey: string
|
||||
videoFilePath: string
|
||||
spriteKey: string
|
||||
}
|
||||
|
||||
export async function generate3dSpriteActivity(
|
||||
params: Generate3dSpriteActivityParams,
|
||||
): Promise<{ spriteKey: string }> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Sprite generation cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const tmpDir = path.dirname(params.videoFilePath)
|
||||
const spriteFilePath = path.join(tmpDir, 'sprite.webp')
|
||||
|
||||
try {
|
||||
await transcodeService.generate3dSprite(params.videoFilePath, spriteFilePath, signal)
|
||||
const spriteBuffer = fs.readFileSync(spriteFilePath)
|
||||
|
||||
await ensureAssetNotPurging(params.assetKey)
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
params.spriteKey,
|
||||
spriteBuffer,
|
||||
spriteBuffer.length,
|
||||
'image/webp',
|
||||
)
|
||||
|
||||
return { spriteKey: params.spriteKey }
|
||||
} catch (err) {
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
}
|
||||
const errMsg = err instanceof Error ? err.message : String(err)
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to generate 3D sprite: ${errMsg}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -618,6 +618,125 @@ describe('Watermark Activities', () => {
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('produces a watermarked mp4 proxy from the turntable video for a 3d asset', async () => {
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/asset-3d/robot.glb' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'robot.glb',
|
||||
type: 'file',
|
||||
mediaType: 'model/gltf-binary',
|
||||
status: 'processed',
|
||||
storageKeyId: storageKey.id,
|
||||
media: {
|
||||
duration: 4,
|
||||
filesize: 100,
|
||||
frames: 24,
|
||||
proxyType: '3d',
|
||||
videoTranscodes: [
|
||||
{
|
||||
key: 'files/asset-3d/turntable.mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
},
|
||||
],
|
||||
videoPreview: {
|
||||
key: 'files/asset-3d/turntable.mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
},
|
||||
poster: { key: 'files/asset-3d/poster.webp' },
|
||||
sprite: { key: 'files/asset-3d/sprite.webp', frames: 100, tileX: 10, tileY: 10 },
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalWidth: 1080,
|
||||
originalHeight: 1080,
|
||||
duration: 4,
|
||||
bitRate: 0,
|
||||
frameRate: 6,
|
||||
totalFrames: 24,
|
||||
startTimecode: '00:00:00:00',
|
||||
hasAudio: false,
|
||||
format: {},
|
||||
},
|
||||
original: {
|
||||
key: 'files/asset-3d/robot.glb',
|
||||
filesizeInBytes: 100,
|
||||
codec: '',
|
||||
},
|
||||
} as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
const config = await seedConfig()
|
||||
|
||||
vi.mocked(transcodeService.getVideoInfo).mockResolvedValue({
|
||||
originalWidth: 1080,
|
||||
originalHeight: 1080,
|
||||
duration: 4,
|
||||
bitRate: 2000,
|
||||
frameRate: 6,
|
||||
totalFrames: 24,
|
||||
startTimecode: '00:00:00:00',
|
||||
hasAudio: false,
|
||||
mimeType: 'video/mp4',
|
||||
})
|
||||
vi.mocked(s3Service.putObject).mockResolvedValue(undefined as never)
|
||||
|
||||
const stem = 'robot'
|
||||
const configId = config.id
|
||||
const outFilePath = path.join('/tmp', `${stem}-watermark-${configId}-1080p.mp4`)
|
||||
fs.writeFileSync(outFilePath, Buffer.from('fake 3d watermarked turntable mp4'))
|
||||
|
||||
const media = await transcodeWatermarkMediaActivity({
|
||||
assetId: asset.id,
|
||||
watermarkConfigId: config.id,
|
||||
})
|
||||
|
||||
expect(media.proxyType).toBe('3d')
|
||||
expect(media.videoTranscodes?.length).toBeGreaterThan(0)
|
||||
expect(media.videoTranscodes?.[0].key).toContain('watermark-')
|
||||
expect(media.videoPreview?.key).toBe(media.videoTranscodes?.[0].key)
|
||||
expect(media.poster?.key).toBe('files/asset-3d/poster.webp')
|
||||
expect(media.sprite?.key).toBe('files/asset-3d/sprite.webp')
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
bucket,
|
||||
'files/asset-3d/turntable.mp4',
|
||||
expect.any(String),
|
||||
)
|
||||
|
||||
fs.rmSync(outFilePath, { force: true })
|
||||
})
|
||||
|
||||
it('throws non-retryable ApplicationFailure when 3d asset has no turntable video transcode', async () => {
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/asset-3d/robot.glb' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'robot.glb',
|
||||
type: 'file',
|
||||
mediaType: 'model/gltf-binary',
|
||||
status: 'processing',
|
||||
storageKeyId: storageKey.id,
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
videoTranscodes: [],
|
||||
} as unknown as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
const config = await seedConfig()
|
||||
|
||||
await expect(
|
||||
transcodeWatermarkMediaActivity({
|
||||
assetId: asset.id,
|
||||
watermarkConfigId: config.id,
|
||||
}),
|
||||
).rejects.toThrow('Turntable video transcode not found for 3D asset')
|
||||
})
|
||||
})
|
||||
|
||||
describe('completeWatermarkFileActivity', () => {
|
||||
|
||||
@@ -163,17 +163,39 @@ export async function transcodeWatermarkMediaActivity(
|
||||
const stem = stemFromKey(assetKey)
|
||||
|
||||
const tmpDir = transcodeService.createTempDir('watermark-')
|
||||
const rawFilePath = path.join(tmpDir, path.basename(assetKey))
|
||||
|
||||
try {
|
||||
await s3Service.downloadToFile(bucket, assetKey, rawFilePath)
|
||||
|
||||
const is3d = (asset.media as PrismaJson.MediaInfo | null)?.proxyType === '3d'
|
||||
const isVideo =
|
||||
asset.mediaType?.startsWith('video/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'video'
|
||||
!is3d &&
|
||||
(asset.mediaType?.startsWith('video/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'video')
|
||||
const isImage =
|
||||
asset.mediaType?.startsWith('image/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'image'
|
||||
!is3d &&
|
||||
(asset.mediaType?.startsWith('image/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'image')
|
||||
|
||||
if (!isVideo && !isImage && !is3d) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Asset ${params.assetId} is neither video nor image`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const inputKey = is3d
|
||||
? (asset.media as PrismaJson.MediaInfo | null)?.videoTranscodes?.[0]?.key ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.videoPreview?.key
|
||||
: assetKey
|
||||
|
||||
if (is3d && !inputKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Turntable video transcode not found for 3D asset ${params.assetId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const rawFilePath = path.join(tmpDir, path.basename(inputKey!))
|
||||
await s3Service.downloadToFile(bucket, inputKey!, rawFilePath)
|
||||
|
||||
let originalWidth = 1920
|
||||
let originalHeight = 1080
|
||||
@@ -192,7 +214,7 @@ export async function transcodeWatermarkMediaActivity(
|
||||
let hdrType: PrismaJson.HdrType | undefined
|
||||
let dvProfile: number | undefined
|
||||
|
||||
if (isVideo) {
|
||||
if (isVideo || is3d) {
|
||||
const info = await transcodeService.getVideoInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
originalHeight = info.originalHeight
|
||||
@@ -214,11 +236,6 @@ export async function transcodeWatermarkMediaActivity(
|
||||
const info = await transcodeService.getImageInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
originalHeight = info.originalHeight
|
||||
} else {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Asset ${params.assetId} is neither video nor image`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Process image blocks if any
|
||||
@@ -260,9 +277,11 @@ export async function transcodeWatermarkMediaActivity(
|
||||
duration,
|
||||
filesize: 0,
|
||||
frames: totalFrames,
|
||||
proxyType: isVideo ? 'video' : 'image',
|
||||
proxyType: is3d ? '3d' : isVideo ? 'video' : 'image',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
poster: originalMedia?.poster,
|
||||
sprite: originalMedia?.sprite,
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalWidth,
|
||||
@@ -280,7 +299,7 @@ export async function transcodeWatermarkMediaActivity(
|
||||
isHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
hdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
dvProfile: dvProfile ?? originalMedia?.metadata?.dvProfile,
|
||||
format: {},
|
||||
format: originalMedia?.metadata?.format ?? {},
|
||||
},
|
||||
original: {
|
||||
key: assetKey,
|
||||
@@ -333,7 +352,7 @@ export async function transcodeWatermarkMediaActivity(
|
||||
})
|
||||
}
|
||||
mediaInfo.filesize = totalSize
|
||||
} else if (isVideo) {
|
||||
} else if (isVideo || is3d) {
|
||||
const originalTranscodes = originalMedia?.videoTranscodes || []
|
||||
let totalSize = 0
|
||||
|
||||
@@ -395,6 +414,15 @@ export async function transcodeWatermarkMediaActivity(
|
||||
})
|
||||
}
|
||||
|
||||
if (is3d && mediaInfo.videoTranscodes.length > 0) {
|
||||
mediaInfo.videoPreview = {
|
||||
key: mediaInfo.videoTranscodes[0].key,
|
||||
width: mediaInfo.videoTranscodes[0].width,
|
||||
height: mediaInfo.videoTranscodes[0].height,
|
||||
resolution: mediaInfo.videoTranscodes[0].resolution,
|
||||
}
|
||||
}
|
||||
|
||||
if (originalMedia?.isHls && originalMedia?.hls?.resolutions?.length) {
|
||||
const hlsWatermarkDirKey = path.posix.join(
|
||||
path.posix.dirname(assetKey),
|
||||
|
||||
@@ -9,6 +9,7 @@ import { renderPdfPagesWorkflow } from './workflows/render-pdf-pages'
|
||||
import { takeVideoScreenshotsWorkflow } from './workflows/take-video-screenshots'
|
||||
import { overlayImageAnnotationWorkflow } from './workflows/overlay-image-annotation'
|
||||
import { transcodeWatermarkWorkflow } from './workflows/transcode-watermark'
|
||||
import { transcode3dWorkflow } from './workflows/transcode-3d'
|
||||
import { transcodeMedia } from './workflows/transcode'
|
||||
|
||||
export function initTranscodeWorkflows() {
|
||||
@@ -16,6 +17,7 @@ export function initTranscodeWorkflows() {
|
||||
registerWorkflow(WorkflowTaskType.transcode_video, transcodeVideoWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_image, transcodeImageWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_pdf, transcodePdfWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_3d, transcode3dWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_pdf_pages, renderPdfPagesWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_screenshot, takeVideoScreenshotsWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_image_annotation, overlayImageAnnotationWorkflow)
|
||||
@@ -26,6 +28,7 @@ export function initTranscodeWorkflows() {
|
||||
|
||||
export * from './transcoder'
|
||||
export * from './workflows/transcode'
|
||||
export * from './workflows/transcode-3d'
|
||||
export * from './workflows/transcode-watermark'
|
||||
export * from './activities/transcode'
|
||||
export * from './activities/watermark'
|
||||
|
||||
@@ -151,3 +151,41 @@ export class PdfTranscoder {
|
||||
return task.id
|
||||
}
|
||||
}
|
||||
|
||||
export class ModelTranscoder {
|
||||
private spec: PrismaJson.TaskSpec = {}
|
||||
|
||||
constructor(
|
||||
private readonly db: TransactionClient,
|
||||
private readonly assetId: string,
|
||||
private readonly teamId: string,
|
||||
private readonly projectId: string,
|
||||
) {}
|
||||
|
||||
withSprite(): this {
|
||||
this.spec.sprite = true
|
||||
return this
|
||||
}
|
||||
|
||||
withPoster(): this {
|
||||
this.spec.poster = true
|
||||
return this
|
||||
}
|
||||
|
||||
async submit(): Promise<string> {
|
||||
const task = await this.db.workflowTask.create({
|
||||
data: {
|
||||
assetId: this.assetId,
|
||||
teamId: this.teamId,
|
||||
projectId: this.projectId,
|
||||
type: WorkflowTaskType.transcode_3d,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
payload: {
|
||||
projectId: this.projectId,
|
||||
transcode: this.spec,
|
||||
},
|
||||
},
|
||||
})
|
||||
return task.id
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcode3dWorkflow } from './transcode-3d'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('transcode3dWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
updateAssetStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
render3dModelActivity: Object.assign(vi.fn(), { _activityName: 'render3dModelActivity' }),
|
||||
start3dRenderActivity: Object.assign(vi.fn(), { _activityName: 'start3dRenderActivity' }),
|
||||
waitFor3dVideoRenderActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'waitFor3dVideoRenderActivity',
|
||||
}),
|
||||
generate3dSpriteActivity: Object.assign(vi.fn(), { _activityName: 'generate3dSpriteActivity' }),
|
||||
updateAssetMediaActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMediaActivity',
|
||||
}),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createEmbeddingTaskIfEnabledActivity',
|
||||
}),
|
||||
createAutofillTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createAutofillTaskIfEnabledActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/model.glb',
|
||||
tmpDir: '/tmp',
|
||||
})
|
||||
})
|
||||
|
||||
it('should process 3D model transcode successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-3d',
|
||||
assetId: 'asset-3d',
|
||||
type: WorkflowTaskType.transcode_3d,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
transcode: {
|
||||
sprite: true,
|
||||
poster: true,
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-3d',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-3d',
|
||||
name: 'robot.glb',
|
||||
storageKey: { key: 'files/asset-3d/robot.glb' },
|
||||
mediaType: 'model/gltf-binary',
|
||||
sizeByte: BigInt(1024),
|
||||
})
|
||||
|
||||
mockActivities.start3dRenderActivity.mockResolvedValue({
|
||||
renderTaskId: 'task_render_1',
|
||||
posterFilePath: '/tmp/poster.webp',
|
||||
posterWidth: 1080,
|
||||
posterHeight: 1080,
|
||||
modelMetadata: { format: 'glb' },
|
||||
})
|
||||
|
||||
mockActivities.waitFor3dVideoRenderActivity.mockResolvedValue({
|
||||
videoFilePath: '/tmp/turntable.mp4',
|
||||
})
|
||||
|
||||
mockActivities.generate3dSpriteActivity.mockResolvedValue({
|
||||
spriteKey: 'files/asset-3d/sprite.webp',
|
||||
})
|
||||
|
||||
await transcode3dWorkflow(task)
|
||||
|
||||
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-3d',
|
||||
status: AssetStatus.processing,
|
||||
})
|
||||
|
||||
expect(mockActivities.start3dRenderActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-3d',
|
||||
teamId: 'team-1',
|
||||
assetId: 'asset-3d',
|
||||
assetKey: 'files/asset-3d/robot.glb',
|
||||
filePath: '/tmp/model.glb',
|
||||
filename: 'robot.glb',
|
||||
targetPosterKey: 'files/asset-3d/poster.webp',
|
||||
})
|
||||
|
||||
// Verify initial updateAssetMediaActivity with poster was called before waitFor3dVideoRenderActivity
|
||||
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'asset-3d',
|
||||
mediaInfo: expect.objectContaining({
|
||||
proxyType: '3d',
|
||||
poster: { key: 'files/asset-3d/poster.webp' },
|
||||
metadata: expect.objectContaining({
|
||||
format: { format: 'glb' },
|
||||
originalHeight: 1080,
|
||||
originalWidth: 1080,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
const firstMediaUpdateOrder =
|
||||
mockActivities.updateAssetMediaActivity.mock.invocationCallOrder[0]
|
||||
const waitVideoOrder = mockActivities.waitFor3dVideoRenderActivity.mock.invocationCallOrder[0]
|
||||
expect(firstMediaUpdateOrder).toBeLessThan(waitVideoOrder)
|
||||
|
||||
expect(mockActivities.waitFor3dVideoRenderActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-3d',
|
||||
teamId: 'team-1',
|
||||
assetKey: 'files/asset-3d/robot.glb',
|
||||
renderTaskId: 'task_render_1',
|
||||
targetVideoKey: 'files/asset-3d/turntable.mp4',
|
||||
tmpDir: '/tmp',
|
||||
})
|
||||
|
||||
expect(mockActivities.generate3dSpriteActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-3d',
|
||||
assetKey: 'files/asset-3d/robot.glb',
|
||||
videoFilePath: '/tmp/turntable.mp4',
|
||||
spriteKey: 'files/asset-3d/sprite.webp',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'asset-3d',
|
||||
mediaInfo: expect.objectContaining({
|
||||
proxyType: '3d',
|
||||
duration: 4,
|
||||
frames: 24,
|
||||
poster: { key: 'files/asset-3d/poster.webp' },
|
||||
sprite: expect.objectContaining({ key: 'files/asset-3d/sprite.webp' }),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-3d',
|
||||
status: AssetStatus.processed,
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
taskId: 'task-3d',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
}),
|
||||
)
|
||||
|
||||
expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({
|
||||
tmpDir: '/tmp',
|
||||
})
|
||||
})
|
||||
|
||||
it('should fail task when render activity fails', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-3d-fail',
|
||||
assetId: 'asset-3d-fail',
|
||||
type: WorkflowTaskType.transcode_3d,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-3d-fail',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-3d-fail',
|
||||
name: 'corrupt.glb',
|
||||
storageKey: { key: 'files/corrupt.glb' },
|
||||
mediaType: 'model/gltf-binary',
|
||||
sizeByte: BigInt(512),
|
||||
})
|
||||
|
||||
mockActivities.start3dRenderActivity.mockRejectedValue(new Error('Renderer crashed'))
|
||||
|
||||
await expect(transcode3dWorkflow(task)).rejects.toThrow('Renderer crashed')
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
taskId: 'task-3d-fail',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
}),
|
||||
)
|
||||
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'asset-3d-fail',
|
||||
status: AssetStatus.failed,
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities } from '@shumai/workflow-core'
|
||||
import {
|
||||
getWorkerQueueAndStartTask,
|
||||
fetchAssetWithKey,
|
||||
completeTask,
|
||||
failTask,
|
||||
cleanupTmpDir,
|
||||
} from './common'
|
||||
|
||||
export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let tmpDir: string | undefined
|
||||
let workerQueue = ''
|
||||
let mediaProcessed = false
|
||||
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
|
||||
const {
|
||||
updateAssetStatusActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
start3dRenderActivity,
|
||||
waitFor3dVideoRenderActivity,
|
||||
generate3dSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} = getActivities()
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
assetId: task.assetId,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
|
||||
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
||||
assetKey: key,
|
||||
})
|
||||
const currentFilePath = download.filePath
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
const lastSlashIndex = key.lastIndexOf('/')
|
||||
const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex)
|
||||
const videoKey = assetDir ? `${assetDir}/turntable.mp4` : 'turntable.mp4'
|
||||
const posterKey = assetDir ? `${assetDir}/poster.webp` : 'poster.webp'
|
||||
const spriteKey = assetDir ? `${assetDir}/sprite.webp` : 'sprite.webp'
|
||||
|
||||
const renderStart = await executeActivity(workerQueue, start3dRenderActivity, {
|
||||
taskId: task.id,
|
||||
teamId: task.teamId,
|
||||
assetId: asset.id,
|
||||
assetKey: key,
|
||||
filePath: currentFilePath,
|
||||
filename: asset.name || 'model.glb',
|
||||
targetPosterKey: posterKey,
|
||||
})
|
||||
|
||||
const posterWidth = renderStart.posterWidth || 1080
|
||||
const posterHeight = renderStart.posterHeight || 1080
|
||||
|
||||
const mediaInfo: PrismaJson.MediaInfo = {
|
||||
duration: 4,
|
||||
filesize: 0,
|
||||
frames: 24,
|
||||
proxyType: '3d',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
poster: {
|
||||
key: posterKey,
|
||||
},
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalHeight: posterHeight,
|
||||
originalWidth: posterWidth,
|
||||
hasAudio: false,
|
||||
duration: 4,
|
||||
bitRate: 0,
|
||||
frameRate: 6,
|
||||
totalFrames: 24,
|
||||
startTimecode: '00:00:00:00',
|
||||
format: renderStart.modelMetadata ?? {},
|
||||
},
|
||||
original: {
|
||||
key,
|
||||
filesizeInBytes: Number(asset.sizeByte || 0),
|
||||
codec: '',
|
||||
},
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
const renderVideo = await executeActivity(workerQueue, waitFor3dVideoRenderActivity, {
|
||||
taskId: task.id,
|
||||
teamId: task.teamId,
|
||||
assetKey: key,
|
||||
renderTaskId: renderStart.renderTaskId,
|
||||
targetVideoKey: videoKey,
|
||||
tmpDir,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, generate3dSpriteActivity, {
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
videoFilePath: renderVideo.videoFilePath,
|
||||
spriteKey,
|
||||
})
|
||||
|
||||
mediaInfo.sprite = {
|
||||
key: spriteKey,
|
||||
frames: 100,
|
||||
tileX: 10,
|
||||
tileY: 10,
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
mediaInfo.videoTranscodes = [
|
||||
{
|
||||
key: videoKey,
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
},
|
||||
]
|
||||
mediaInfo.videoPreview = {
|
||||
key: videoKey,
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
}
|
||||
mediaInfo.finishedAt = new Date().toISOString()
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
assetId: asset.id,
|
||||
status: 'processed',
|
||||
})
|
||||
mediaProcessed = true
|
||||
|
||||
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, createAutofillTaskIfEnabledActivity, {
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id)
|
||||
} catch (err) {
|
||||
console.error(`transcode3dWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
throw err
|
||||
} finally {
|
||||
await cleanupTmpDir(workerQueue, tmpDir)
|
||||
}
|
||||
}
|
||||
@@ -47,5 +47,6 @@ export * from './render-pdf-pages'
|
||||
export * from './take-video-screenshots'
|
||||
export * from './overlay-image-annotation'
|
||||
export * from './transcode-watermark'
|
||||
export * from './transcode-3d'
|
||||
export * from './common'
|
||||
export * from './transcode-utils'
|
||||
|
||||
Reference in New Issue
Block a user