refactor(monorepo): decouple and split background workflow workers into packages

Splits monolithic workflow workers into four decoupled workspaces under the Bun workspaces monorepo:
- @shumai/workflow-core containing the core execution engine and utilities.
- @shumai/agent containing agent-specific logic, workflows, and activities.
- @shumai/transcode containing transcoding workflows, transcoder, and transcode activities.
- @shumai/worker-db containing database activities.

Introduces a dynamic workflow and activity registration pattern on LocalExecutor to eliminate circular dependencies. Updates worker bootstrapping and test suites to cleanly leverage generic workspace modules.
This commit is contained in:
yiling
2026-06-01 23:29:11 +08:00
parent cb80822637
commit e3f4fa219e
66 changed files with 421 additions and 150 deletions
@@ -0,0 +1,135 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { getMediaInfoActivity, transcodeVideoActivity, updateAssetMediaActivity } from './transcode'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '../transcode'
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
getObject: vi.fn(),
putObject: vi.fn(),
headObject: vi.fn(),
presign: vi.fn(),
},
}))
vi.mock('../transcode', () => ({
transcodeService: {
getVideoInfo: vi.fn(),
getImageInfo: vi.fn(),
transcodeVideo: vi.fn(),
createTempDir: vi.fn().mockReturnValue('/tmp'),
removeDir: vi.fn(),
},
}))
vi.mock('fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('fs')>()
return {
...actual,
readFileSync: vi.fn().mockReturnValue(Buffer.from('fake data')),
}
})
describe('Transcode Activities', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('should call getVideoInfo for video assets', async () => {
const asset = await prisma.asset.create({
data: { name: 'v.mp4', type: 'file', status: 'uploaded' },
})
vi.mocked(transcodeService.getVideoInfo).mockResolvedValue({
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
bitRate: 1000,
frameRate: 30,
hasAudio: true,
videoCodec: 'Advanced Video Coding',
audioCodec: 'MPEG-4 Audio',
audioChannels: 2,
audioSampleRate: 48000,
audioBitDepth: 16,
mimeType: 'video/mp4',
})
const result = await getMediaInfoActivity({
assetId: asset.id,
filePath: '/tmp/v.mp4',
mediaType: 'video/mp4',
})
expect(transcodeService.getVideoInfo).toHaveBeenCalledWith('/tmp/v.mp4')
expect(result.duration).toBe(10)
expect(result.metadata?.originalWidth).toBe(1920)
expect(result.metadata?.videoCodec).toBe('Advanced Video Coding')
expect(result.metadata?.audioCodec).toBe('MPEG-4 Audio')
expect(result.metadata?.audioChannels).toBe(2)
expect(result.metadata?.audioSampleRate).toBe(48000)
expect(result.metadata?.audioBitDepth).toBe(16)
})
it('should call getImageInfo for image assets', async () => {
const asset = await prisma.asset.create({
data: { name: 'i.png', type: 'file', status: 'uploaded' },
})
vi.mocked(transcodeService.getImageInfo).mockResolvedValue({
originalWidth: 800,
originalHeight: 600,
duration: 0,
bitRate: 0,
frameRate: 0,
hasAudio: false,
mimeType: 'image/png',
})
const result = await getMediaInfoActivity({
assetId: asset.id,
filePath: '/tmp/i.png',
mediaType: 'image/png',
})
expect(transcodeService.getImageInfo).toHaveBeenCalledWith('/tmp/i.png')
expect(result.metadata?.originalWidth).toBe(800)
expect(result.metadata?.duration).toBe(0)
})
it('should update asset media field', async () => {
const asset = await prisma.asset.create({
data: {
name: 'v.mp4',
storageKey: { create: { key: 'v.mp4' } },
status: 'uploaded',
type: 'file',
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mediaInfo: any = { duration: 123 }
await updateAssetMediaActivity({ assetId: asset.id, mediaInfo })
const updated = await prisma.asset.findUnique({ where: { id: asset.id } })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((updated?.media as any).duration).toBe(123)
expect(s3Service.putObject).toHaveBeenCalled()
})
it('should call transcodeService.transcodeVideo', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
await transcodeVideoActivity({
assetKey: 'v.mp4',
filePath: '/tmp/v.mp4',
videoSpec: { resolution: '720p', width: 1280, height: 720 },
duration: 10,
originalFps: 30,
})
expect(transcodeService.transcodeVideo).toHaveBeenCalled()
})
})
@@ -0,0 +1,299 @@
import { prisma } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '../transcode'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { ApplicationFailure } from '@temporalio/activity'
import * as path from 'path'
import * as fs from 'fs'
export interface GetMediaInfoActivityParams {
assetId: string
assetKey: string
mediaType: string
}
export async function getMediaInfoActivity(params: {
filePath: string
assetId: string
mediaType: string
}): Promise<PrismaJson.MediaInfo> {
const isVideo = params.mediaType.startsWith('video/')
const isImage = params.mediaType.startsWith('image/')
const mediaInfo: PrismaJson.MediaInfo = {
duration: 0,
filesize: 0,
fps: 0,
frames: 0,
imageTranscodes: [],
videoTranscodes: [],
videoPreview: { width: 0, height: 0 },
finishedAt: new Date().toISOString(),
metadata: null,
mimeType: params.mediaType,
original: {
key: '', // Will be filled by caller or updated later
downloadUrl: '',
filesizeInBytes: 0,
codec: '',
},
}
if (isVideo) {
const info = await transcodeService.getVideoInfo(params.filePath)
mediaInfo.duration = info.duration
mediaInfo.fps = info.frameRate
mediaInfo.metadata = {
originalWidth: info.originalWidth,
originalHeight: info.originalHeight,
duration: info.duration,
bitRate: info.bitRate,
frameRate: info.frameRate,
hasAudio: info.hasAudio,
videoCodec: info.videoCodec,
audioCodec: info.audioCodec,
audioChannels: info.audioChannels,
audioSampleRate: info.audioSampleRate,
audioBitDepth: info.audioBitDepth,
format: {},
}
const metadataUpdates: { key: string; value: string | number }[] = [
{ key: 'resolution_width', value: info.originalWidth },
{ key: 'resolution_height', value: info.originalHeight },
{ key: 'duration', value: info.duration },
{ key: 'bitRate', value: info.bitRate / 1000 },
{ key: 'frame_rate', value: info.frameRate },
]
if (info.videoCodec) metadataUpdates.push({ key: 'video_codec', value: info.videoCodec })
if (info.audioCodec) metadataUpdates.push({ key: 'audio_codec', value: info.audioCodec })
if (info.audioChannels !== undefined)
metadataUpdates.push({ key: 'audio_channels', value: info.audioChannels })
if (info.audioSampleRate !== undefined)
metadataUpdates.push({ key: 'audio_sample_rate', value: info.audioSampleRate })
if (info.audioBitDepth !== undefined)
metadataUpdates.push({ key: 'audio_bit_depth', value: info.audioBitDepth })
await metadataService.updateAssetMetadata(params.assetId, metadataUpdates, true)
} else if (isImage) {
const info = await transcodeService.getImageInfo(params.filePath)
mediaInfo.metadata = {
originalWidth: info.originalWidth,
originalHeight: info.originalHeight,
duration: 0,
bitRate: 0,
frameRate: 0,
hasAudio: false,
format: {},
}
await metadataService.updateAssetMetadata(
params.assetId,
[
{ key: 'resolution_width', value: info.originalWidth },
{ key: 'resolution_height', value: info.originalHeight },
],
true,
)
}
return mediaInfo
}
export interface VideoActivityParams {
assetKey: string
filePath: string
videoSpec: PrismaJson.VideoTranscode
duration: number
originalFps: number
}
export async function transcodeVideoActivity(
params: VideoActivityParams,
): Promise<PrismaJson.VideoTranscode> {
const bucket = process.env.S3_BUCKET || 'shumai'
const key = path.join(path.dirname(params.assetKey), `video-${params.videoSpec.height}p.mp4`)
try {
await s3Service.headObject(bucket, key)
return { ...params.videoSpec, key }
} catch {
// Not found
}
const tmpDir = path.dirname(params.filePath)
const outputFile = path.join(tmpDir, `video-${params.videoSpec.height}p.mp4`)
try {
let targetFps = 0
let disableAudio = false
if (params.videoSpec.resolution === '180p') {
disableAudio = true
targetFps = 24.0
if (params.originalFps > 0 && params.originalFps < 24.0) {
targetFps = params.originalFps
}
if (params.duration * targetFps > 1600) {
targetFps = 1600 / params.duration
}
}
await transcodeService.transcodeVideo({
inputFile: params.filePath,
outputFile,
width: params.videoSpec.width,
height: params.videoSpec.height,
frameRate: targetFps || undefined,
disableAudio,
})
const buffer = fs.readFileSync(outputFile)
await s3Service.putObject(bucket, key, buffer, buffer.length, 'video/mp4')
return { ...params.videoSpec, key }
} finally {
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile)
}
}
export interface ImageActivityParams {
assetKey: string
filePath: string
imageSpec: PrismaJson.ImageTranscode
}
export async function transcodeImageActivity(
params: ImageActivityParams,
): Promise<PrismaJson.ImageTranscode> {
const bucket = process.env.S3_BUCKET || 'shumai'
const key = path.join(path.dirname(params.assetKey), `image-${params.imageSpec.width}p.webp`)
try {
await s3Service.headObject(bucket, key)
return { ...params.imageSpec, key }
} catch {
// Not found
}
const tmpDir = path.dirname(params.filePath)
const outputFile = path.join(tmpDir, `image-${params.imageSpec.width}p.webp`)
try {
await transcodeService.transcodeImage(
params.filePath,
outputFile,
params.imageSpec.width,
params.imageSpec.quality,
)
const buffer = fs.readFileSync(outputFile)
await s3Service.putObject(bucket, key, buffer, buffer.length, 'image/webp')
return { ...params.imageSpec, key }
} finally {
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile)
}
}
export interface GenerateSpriteActivityParams {
assetKey: string
filePath: string
mediaInfo: PrismaJson.MediaInfo
spriteSpec: PrismaJson.SpriteInfo
posterSpec: PrismaJson.PosterInfo
}
export async function generateSpriteActivity(params: GenerateSpriteActivityParams) {
const bucket = process.env.S3_BUCKET || 'shumai'
try {
await s3Service.headObject(bucket, params.spriteSpec.key)
await s3Service.headObject(bucket, params.posterSpec.key)
return { sprite: params.spriteSpec, poster: params.posterSpec }
} catch {
// Not found
}
const tmpDir = path.dirname(params.filePath)
const spriteFile = path.join(tmpDir, 'sprite.webp')
const posterFile = path.join(tmpDir, 'poster.webp')
try {
await transcodeService.generateSprite(
params.filePath,
spriteFile,
posterFile,
params.mediaInfo.duration,
)
const spriteBuffer = fs.readFileSync(spriteFile)
await s3Service.putObject(
bucket,
params.spriteSpec.key,
spriteBuffer,
spriteBuffer.length,
'image/webp',
)
const posterBuffer = fs.readFileSync(posterFile)
await s3Service.putObject(
bucket,
params.posterSpec.key,
posterBuffer,
posterBuffer.length,
'image/webp',
)
return { sprite: params.spriteSpec, poster: params.posterSpec }
} finally {
if (fs.existsSync(spriteFile)) fs.unlinkSync(spriteFile)
if (fs.existsSync(posterFile)) fs.unlinkSync(posterFile)
}
}
export async function downloadMediaToTmpActivity(params: {
assetKey: string
}): Promise<{ filePath: string; tmpDir: string }> {
const bucket = process.env.S3_BUCKET || 'shumai'
const tmpDir = transcodeService.createTempDir('transcode-')
const filePath = path.join(tmpDir, path.basename(params.assetKey))
if (!fs.existsSync(tmpDir)) {
fs.mkdirSync(tmpDir, { recursive: true })
}
await s3Service.downloadToFile(bucket, params.assetKey, filePath)
return { filePath, tmpDir }
}
export async function cleanupTmpDirActivity(params: { tmpDir: string }): Promise<void> {
transcodeService.removeDir(params.tmpDir)
}
export interface UpdateAssetMediaActivityParams {
assetId: string
mediaInfo: PrismaJson.MediaInfo
}
export async function updateAssetMediaActivity(params: UpdateAssetMediaActivityParams) {
const bucket = process.env.S3_BUCKET || 'shumai'
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
include: { storageKey: true },
})
const key = asset?.storageKey?.key
if (!asset || !key) {
throw ApplicationFailure.create({
message: 'Asset not found or has no key',
nonRetryable: true,
})
}
const infoKey = path.join(path.dirname(key), 'info.json')
const buffer = Buffer.from(JSON.stringify(params.mediaInfo))
await s3Service.putObject(bucket, infoKey, buffer, buffer.length, 'application/json')
await prisma.asset.update({
where: { id: params.assetId },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data: { media: params.mediaInfo as any },
})
}
+14
View File
@@ -0,0 +1,14 @@
import { registerWorkflow, registerActivities } from '@shumai/workflow-core'
import { WorkflowTaskType } from '@shumai/db'
import { transcodeMedia } from './workflows/transcode'
import * as transcodeActivities from './activities/transcode'
export function initTranscodeWorkflows() {
registerWorkflow(WorkflowTaskType.transcode, transcodeMedia)
registerActivities(transcodeActivities)
}
export * from './transcoder'
export * from './transcode'
export * from './workflows/transcode'
export * from './activities/transcode'
+230
View File
@@ -0,0 +1,230 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { transcodeService } from './transcode'
import * as path from 'path'
import * as child_process from 'child_process'
import { WorkflowTask } from '@shumai/db'
import sharp from 'sharp'
// Mock child_process
vi.mock('child_process', () => ({
exec: vi.fn(),
}))
// Mock sharp
vi.mock('sharp', () => {
const mockSharp = {
resize: vi.fn().mockReturnThis(),
webp: vi.fn().mockReturnThis(),
toFile: vi.fn().mockResolvedValue({}),
metadata: vi.fn().mockResolvedValue({ width: 800, height: 600, format: 'png' }),
}
const sharpFunc = vi.fn(() => mockSharp)
return {
default: sharpFunc,
}
})
describe('TranscodeService', () => {
let tempDir: string
beforeEach(() => {
tempDir = transcodeService.createTempDir('transcode-test-')
vi.clearAllMocks()
})
afterEach(() => {
transcodeService.removeDir(tempDir)
})
it('should parse video info correctly from ffprobe output', async () => {
/* eslint-disable @typescript-eslint/naming-convention */
const mockOutput = JSON.stringify({
format: { duration: '10.5', bit_rate: '128000' },
streams: [
{
codec_type: 'video',
codec_name: 'h264',
width: 1920,
height: 1080,
r_frame_rate: '30/1',
tags: {
mime_codec_string: 'avc1.4d401e',
},
},
{
codec_type: 'audio',
codec_name: 'aac',
channels: 2,
sample_rate: '48000',
bits_per_raw_sample: '16',
tags: {
mime_codec_string: 'mp4a.40.2',
},
},
],
})
/* eslint-enable @typescript-eslint/naming-convention */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.exec as any).mockImplementation((cmd: string, cb: any) => {
cb(null, { stdout: mockOutput, stderr: '' })
})
const info = await transcodeService.getVideoInfo('test.mp4')
expect(info.originalWidth).toBe(1920)
expect(info.originalHeight).toBe(1080)
expect(info.duration).toBe(10.5)
expect(info.frameRate).toBe(30)
expect(info.hasAudio).toBe(true)
expect(info.videoCodec).toBe('Advanced Video Coding')
expect(info.audioCodec).toBe('MPEG-4 Audio')
expect(info.audioChannels).toBe(2)
expect(info.audioSampleRate).toBe(48000)
expect(info.audioBitDepth).toBe(16)
expect(child_process.exec).toHaveBeenCalledWith(
expect.stringContaining('ffprobe'),
expect.any(Function),
)
})
it('should get image info using sharp', async () => {
const mockMetadata = {
width: 800,
height: 600,
format: 'png',
}
const mockSharp = vi.mocked(sharp())
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockSharp.metadata.mockResolvedValue(mockMetadata as any)
const info = await transcodeService.getImageInfo('test.png')
expect(info.originalWidth).toBe(800)
expect(info.originalHeight).toBe(600)
expect(info.mimeType).toBe('png')
expect(info.duration).toBe(0)
expect(sharp).toHaveBeenCalledWith('test.png')
})
it('should construct correct ffmpeg arguments for video transcoding', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.exec as any).mockImplementation((cmd: string, cb: any) => {
cb(null, { stdout: '', stderr: '' })
})
const outputFile = path.join(tempDir, 'output.mp4')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
frameRate: 24,
disableAudio: true,
})
expect(child_process.exec).toHaveBeenCalledWith(
expect.stringContaining('scale=w=1280:h=720'),
expect.any(Function),
)
expect(child_process.exec).toHaveBeenCalledWith(
expect.stringContaining('fps=24'),
expect.any(Function),
)
// Should NOT have audio maps if disabled
expect(child_process.exec).not.toHaveBeenCalledWith(
expect.stringContaining('-map 0:a?'),
expect.any(Function),
)
})
it('should use sharp for image transcoding', async () => {
const outputFile = path.join(tempDir, 'output.webp')
await transcodeService.transcodeImage('input.png', outputFile, 480, 80)
expect(sharp).toHaveBeenCalledWith('input.png')
const mockSharp = vi.mocked(sharp).mock.results[0].value
expect(mockSharp.resize).toHaveBeenCalledWith(480, null, expect.any(Object))
expect(mockSharp.webp).toHaveBeenCalledWith({ quality: 80 })
expect(mockSharp.toFile).toHaveBeenCalledWith(outputFile)
})
it('should fetch image if input is a URL', async () => {
const mockBuffer = Buffer.from('fake-image-data')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(global as any).fetch = vi.fn().mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(mockBuffer),
})
const outputFile = path.join(tempDir, 'output.webp')
await transcodeService.transcodeImage('http://example.com/image.png', outputFile, 480, 80)
expect(global.fetch).toHaveBeenCalledWith('http://example.com/image.png')
expect(sharp).toHaveBeenCalledWith(expect.any(Buffer))
})
it('should use transcodeImage in extractVideoFrames for images', async () => {
const transcodeImageSpy = vi.spyOn(transcodeService, 'transcodeImage').mockResolvedValue()
const result = await transcodeService.extractVideoFrames({
inputFile: 'input.png',
outputDir: tempDir,
numFrames: 1,
frameHeight: 720,
isImage: true,
})
expect(transcodeImageSpy).toHaveBeenCalledWith(
'input.png',
expect.stringContaining('1.webp'),
-1,
80,
720,
)
expect(result).toHaveLength(1)
expect(result[0]).toContain('1.webp')
})
it('should use ffmpeg with libwebp in extractVideoFrames for videos', async () => {
vi.spyOn(transcodeService, 'getVideoInfo').mockResolvedValue({
duration: 10,
originalWidth: 1920,
originalHeight: 1080,
bitRate: 1000,
frameRate: 30,
hasAudio: true,
mimeType: 'video/mp4',
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.exec as any).mockImplementation((cmd: string, cb: any) => {
cb(null, { stdout: '', stderr: '' })
})
await transcodeService.extractVideoFrames({
inputFile: 'input.mp4',
outputDir: tempDir,
numFrames: 10,
frameHeight: 720,
isImage: false,
})
expect(child_process.exec).toHaveBeenCalledWith(
expect.stringContaining('-c:v libwebp'),
expect.any(Function),
)
})
it('should create transcode tasks correctly', async () => {
const task = (await transcodeService.createVideoTranscodeTask('asset-123', 'proj-123', {
videoStrategy: 'best_match',
thumbnail: true,
})) as WorkflowTask
expect(task.assetId).toBe('asset-123')
expect(task.type).toBe('transcode')
expect(task.status).toBe('pending')
expect(task.payload?.projectId).toBe('proj-123')
expect(task.payload?.transcode?.videoStrategy).toBe('best_match')
})
})
+434
View File
@@ -0,0 +1,434 @@
import { prisma } from '@shumai/db'
import { WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import { exec } from 'child_process'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import sharp from 'sharp'
import { promisify } from 'util'
const execAsync = promisify(exec)
const dataFormatNames: Record<string, string> = {
// additional codecs
apch: 'Apple ProRes 422 High Quality',
apcn: 'Apple ProRes 422 Standard Definition',
apcs: 'Apple ProRes 422 LT',
apco: 'Apple ProRes 422 Proxy',
ap4h: 'Apple ProRes 4444',
jpeg: 'JPEG Image',
// codecs from https://mp4ra.org/
'3gvo': '3GPP Video Orientation',
a3d1: 'Multiview Video Coding',
a3d2: 'Multiview Video Coding',
a3d3: 'Multiview Video Coding',
a3d4: 'Multiview Video Coding',
a3ds: 'Auro-Cx 3D audio',
'ac-3': 'AC-3 audio',
'ac-4': 'AC-4 audio',
alac: 'Apple lossless audio codec',
alaw: 'a-Law',
av01: 'AV1 video',
avc1: 'Advanced Video Coding',
avc2: 'Advanced Video Coding',
avc3: 'Advanced Video Coding',
avc4: 'Advanced Video Coding',
avcp: 'Advanced Video Coding Parameters',
dra1: 'DRA Audio',
drac: 'Dirac Video Coder',
'dts-': 'Dependent base layer for DTS layered audio',
'dts+': 'Enhancement layer for DTS layered audio',
dtsc: 'DTS Coherent Acoustics audio',
dtse: 'DTS Express low bit rate audio, also known as DTS LBR',
dtsh: 'DTS-HD High Resolution Audio',
dtsl: 'DTS-HD Master Audio',
dtsx: 'DTS:X',
dvav: 'AVC-based “Dolby Vision”',
dvhe: 'HEVC-based “Dolby Vision”',
'ec-3': 'Enhanced AC-3 audio',
enca: 'Encrypted/Protected audio',
encf: 'Encrypted/Protected font',
encm: 'Encrypted/Protected metadata stream',
encs: 'Encrypted Systems stream',
enct: 'Encrypted Text',
encv: 'Encrypted/protected video',
fdp: 'File delivery hints',
fLaC: 'Fres Lossless Audio Codec',
g719: 'ITU-T Recommendation G.719 (2008)',
g726: 'ITU-T Recommendation G.726 (1990)',
hev1: 'High Efficiency Video Coding',
hvc1: 'High Efficiency Video Coding',
hvt1: 'High Efficiency Video Coding',
ixse: 'DVB Track Level Index Track',
lhe1: 'Layered High Efficiency Video Coding',
lht1: 'Layered High Efficiency Video Coding',
lhv1: 'Layered High Efficiency Video Coding',
m2ts: 'MPEG-2 transport stream for DMB',
m4ae: 'MPEG-4 Audio Enhancement MP4v1/2',
mett: 'Text timed metadata that is not XML',
metx: 'XML timed metadata',
mha1: 'MPEG-H Audio (single stream, uncapsulated)',
mha2: 'MPEG-H Audio (multi-stream, unencapsulated)',
mhm1: 'MPEG-H Audio (single stream, MHAS encapsulated)',
mhm2: 'MPEG-H Audio (multi-stream, MHAS encapsulated)',
mjp2: 'Motion JPEG 2000',
mlix: 'DVB Movie level index track',
mlpa: 'MLP Audio',
mp4a: 'MPEG-4 Audio',
mp4s: 'MPEG-4 Systems',
mp4v: 'MPEG-4 Visual',
mvc1: 'Multiview coding',
mvc2: 'Multiview coding',
mvc3: 'Multiview coding',
mvc4: 'Multiview coding',
mvd1: 'Multiview coding',
mvd2: 'Multiview coding',
mvd3: 'Multiview coding',
mvd4: 'Multiview coding',
oksd: 'OMA Keys',
// eslint-disable-next-line @typescript-eslint/naming-convention
Opus: 'Opus audio coding',
pm2t: 'Protected MPEG-2 Transport',
prtp: 'Protected RTP Reception',
raw: 'Uncompressed audio',
resv: 'Restricted Video',
rm2t: 'MPEG-2 Transport Reception',
rrtp: 'RTP reception',
rsrp: 'SRTP Reception',
rtmd: 'Real Time Metadata Sample Entry(XAVC Format)',
rtp: 'RTP Hints',
s263: 'ITU H.263 video (3GPP format)',
samr: 'Narrowband AMR voice',
sawb: 'Wideband AMR voice',
sawp: 'Extended AMR-WB (AMR-WB+)',
sevc: 'EVRC Voice',
sm2t: 'MPEG-2 Transport Server',
sqcp: '13K Voice',
srtp: 'SRTP Hints',
ssmv: 'SMV Voice',
STGS: 'Subtitle Sample Entry (HMMP)',
stpp: 'Subtitles (Timed Text)',
svc1: 'Scalable Video Coding',
svc2: 'Scalable Video Coding',
svcM: 'SVC Metadata',
tc64: '64 bit timecode samples',
tmcd: '32 bit timecode samples',
twos: 'Uncompressed 16-bit audio',
tx3g: 'Timed Text stream',
ulaw: 'Samples have been compressed using uLaw 2:1.',
unid: 'Dynamic Range Control (DRC) data',
urim: 'Binary timed metadata identified by URI',
'vc-1': 'SMPTE VC-1',
vp08: 'VP8 video',
vp09: 'VP9 video',
wvtt: 'WebVTT',
}
export interface MediaMetadata {
originalWidth: number
originalHeight: number
duration: number
bitRate: number
frameRate: number
hasAudio: boolean
videoCodec?: string
audioCodec?: string
audioChannels?: number
audioSampleRate?: number
audioBitDepth?: number
mimeType: string
}
export interface TranscodeVideoParams {
inputFile: string
outputFile: string
width: number
height: number
frameRate?: number
disableAudio?: boolean
}
export interface ExtractVideoFramesParams {
inputFile: string
outputDir: string
numFrames: number
frameHeight: number
isImage: boolean
}
export class TranscodeService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
private resolveCodecName(stream: {
/* eslint-disable @typescript-eslint/naming-convention */
codec_name?: string
mime_codec_string?: string
tags?: { mime_codec_string?: string }
/* eslint-enable @typescript-eslint/naming-convention */
}): string | undefined {
const mimeCodec = stream.mime_codec_string || stream.tags?.mime_codec_string
if (mimeCodec && typeof mimeCodec === 'string') {
const shortCodec = mimeCodec.split('.')[0]
if (dataFormatNames[shortCodec]) {
return dataFormatNames[shortCodec]
}
}
return stream.codec_name
}
private safeParseInt(value: string | number | undefined): number | undefined {
if (value === undefined || value === null) return undefined
const parsed = typeof value === 'string' ? parseInt(value, 10) : value
return Number.isFinite(parsed) ? (parsed as number) : undefined
}
async getVideoInfo(inputFile: string): Promise<MediaMetadata> {
const { stdout } = await execAsync(
`ffprobe -v quiet -print_format json -show_format -show_streams "${inputFile}"`,
)
const info = JSON.parse(stdout)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const videoStream = info.streams.find((s: any) => s.codec_type === 'video')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const audioStream = info.streams.find((s: any) => s.codec_type === 'audio')
if (!videoStream) {
throw new Error('No video stream found')
}
const frameRateParts = videoStream.r_frame_rate.split('/')
const frameRate = parseFloat(frameRateParts[0]) / parseFloat(frameRateParts[1])
return {
originalWidth: videoStream.width,
originalHeight: videoStream.height,
duration: parseFloat(info.format.duration),
bitRate: parseFloat(info.format.bit_rate),
frameRate,
hasAudio: !!audioStream,
videoCodec: this.resolveCodecName(videoStream),
audioCodec: audioStream ? this.resolveCodecName(audioStream) : undefined,
audioChannels: audioStream?.channels,
audioSampleRate: this.safeParseInt(audioStream?.sample_rate),
audioBitDepth:
this.safeParseInt(audioStream?.bits_per_raw_sample) ??
this.safeParseInt(audioStream?.bits_per_sample),
mimeType: '',
}
}
async getImageInfo(inputFile: string): Promise<MediaMetadata> {
let input: string | Buffer = inputFile
if (inputFile.startsWith('http')) {
const resp = await fetch(inputFile)
if (!resp.ok) {
throw new Error(`Failed to fetch image from ${inputFile}: ${resp.statusText}`)
}
input = Buffer.from(await resp.arrayBuffer())
}
const metadata = await sharp(input).metadata()
return {
originalWidth: metadata.width || 0,
originalHeight: metadata.height || 0,
duration: 0,
bitRate: 0,
frameRate: 0,
hasAudio: false,
mimeType: metadata.format || '',
}
}
async transcodeVideo(params: TranscodeVideoParams): Promise<void> {
let filterComplex = `[0:v]scale=w=${params.width}:h=${params.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'`
if (params.frameRate) {
filterComplex += `,fps=${params.frameRate}`
}
filterComplex += '[vout]'
const args = [
'-i',
`"${params.inputFile}"`,
'-filter_complex',
`"${filterComplex}"`,
'-map',
'[vout]',
]
if (!params.disableAudio) {
args.push('-map', '0:a?')
}
args.push('-c:v', 'libx264', '-preset', 'fast', '-crf', '23')
if (!params.disableAudio) {
args.push('-c:a', 'aac', '-b:a', '128k')
}
args.push('-movflags', '+faststart', '-max_muxing_queue_size', '1024', `"${params.outputFile}"`)
await execAsync(`ffmpeg -y ${args.join(' ')}`)
}
async transcodeImage(
inputFile: string,
outputFile: string,
width: number,
quality: number,
height: number | null = null,
): Promise<void> {
let input: string | Buffer = inputFile
if (inputFile.startsWith('http')) {
const resp = await fetch(inputFile)
if (!resp.ok) {
throw new Error(`Failed to fetch image from ${inputFile}: ${resp.statusText}`)
}
input = Buffer.from(await resp.arrayBuffer())
}
const sharpInstance = sharp(input)
const w = width > 0 ? width : null
const h = height && height > 0 ? height : null
if (w || h) {
sharpInstance.resize(w, h, {
withoutEnlargement: true,
fit: 'inside',
})
}
await sharpInstance.webp({ quality }).toFile(outputFile)
}
async generateSprite(
inputFile: string,
outputSprite: string,
outputPoster: string,
duration: number,
): Promise<void> {
const spriteFps = 100 / duration
const filterComplex = `[0:v]fps=${spriteFps},scale=w=480:h=-2,tile=10x10[sprite_out];[0:v]scale=-2:720:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
const args = [
'-i',
`"${inputFile}"`,
'-filter_complex',
`"${filterComplex}"`,
'-map',
'[sprite_out]',
'-frames:v',
'1',
'-c:v',
'libwebp',
'-q:v',
'75',
`"${outputSprite}"`,
'-map',
'[thumb_out]',
'-c:v',
'libwebp',
'-q:v',
'75',
'-frames:v',
'1',
'-max_muxing_queue_size',
'1024',
`"${outputPoster}"`,
]
await execAsync(`ffmpeg -y ${args.join(' ')}`)
}
async extractAudio(inputFile: string, outputFile: string, bitrate: string): Promise<void> {
const args = [
'-i',
`"${inputFile}"`,
'-vn',
'-acodec',
'libmp3lame',
'-b:a',
bitrate,
`"${outputFile}"`,
]
await execAsync(`ffmpeg -y ${args.join(' ')}`)
}
async extractVideoFrames(params: ExtractVideoFramesParams): Promise<string[]> {
if (params.isImage) {
const outputFile = path.join(params.outputDir, '1.webp')
await this.transcodeImage(params.inputFile, outputFile, -1, 80, params.frameHeight)
return [outputFile]
}
const meta = await this.getVideoInfo(params.inputFile)
const fps = params.numFrames / meta.duration
const outputPattern = path.join(params.outputDir, '%d.webp')
const args = [
'-i',
`"${params.inputFile}"`,
'-vf',
`fps=${fps},scale=-2:${params.frameHeight}`,
'-c:v',
'libwebp',
'-q:v',
'80',
`"${outputPattern}"`,
]
await execAsync(`ffmpeg -y ${args.join(' ')}`)
const files = fs.readdirSync(params.outputDir)
return files
.filter((f) => f.endsWith('.webp'))
.sort((a, b) => {
const na = parseInt(path.basename(a, '.webp'))
const nb = parseInt(path.basename(b, '.webp'))
return na - nb
})
.map((f) => path.join(params.outputDir, f))
}
createTempDir(prefix: string): string {
return fs.mkdtempSync(path.join(os.tmpdir(), prefix))
}
removeDir(dir: string): void {
fs.rmSync(dir, { recursive: true, force: true })
}
// --- Task Creation Helpers ---
async createVideoTranscodeTask(assetId: string, projectId: string, spec: PrismaJson.TaskSpec) {
return this.prismaClient.workflowTask.create({
data: {
assetId,
projectId,
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
payload: {
projectId,
transcode: spec,
},
},
})
}
async createImageTranscodeTask(assetId: string, projectId: string, spec: PrismaJson.TaskSpec) {
return this.prismaClient.workflowTask.create({
data: {
assetId,
projectId,
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
payload: {
projectId,
transcode: spec,
},
},
})
}
}
export const transcodeService = new TranscodeService()
+84
View File
@@ -0,0 +1,84 @@
import { prisma } from '@shumai/db'
import { WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
type TransactionClient = Omit<
typeof prisma,
'$connect' | '$disconnect' | '$on' | '$transaction' | '$use' | '$extends'
>
export class VideoTranscoder {
private spec: PrismaJson.TaskSpec = {}
constructor(
private readonly db: TransactionClient,
private readonly assetId: string,
private readonly teamId: string,
private readonly projectId: string,
) {}
setStrategy(strategy: PrismaJson.VideoTranscodeStrategy): this {
this.spec.videoStrategy = strategy
return this
}
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,
status: WorkflowTaskStatus.pending,
payload: {
projectId: this.projectId,
transcode: this.spec,
},
},
})
return task.id
}
}
export class ImageTranscoder {
private spec: PrismaJson.TaskSpec = {}
constructor(
private readonly db: TransactionClient,
private readonly assetId: string,
private readonly teamId: string,
private readonly projectId: string,
) {}
withThumbnail(): this {
this.spec.thumbnail = 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,
status: WorkflowTaskStatus.pending,
payload: {
projectId: this.projectId,
transcode: this.spec,
},
},
})
return task.id
}
}
@@ -0,0 +1,237 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { transcodeMedia } from './transcode'
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('Transcode Workflow', () => {
const mockActivities = {
updateTaskStatusActivity: Object.assign(vi.fn(), {
_activityName: 'updateTaskStatusActivity',
}),
updateAssetStatusActivity: Object.assign(vi.fn(), {
_activityName: 'updateAssetStatusActivity',
}),
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
getMediaInfoActivity: Object.assign(vi.fn(), { _activityName: 'getMediaInfoActivity' }),
transcodeVideoActivity: Object.assign(vi.fn(), { _activityName: 'transcodeVideoActivity' }),
transcodeImageActivity: Object.assign(vi.fn(), { _activityName: 'transcodeImageActivity' }),
generateSpriteActivity: Object.assign(vi.fn(), { _activityName: 'generateSpriteActivity' }),
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' }),
}
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/video.mp4',
tmpDir: '/tmp',
})
})
it('should process video transcode successfully', async () => {
const task: WorkflowTask = {
id: 'task-1',
assetId: 'asset-1',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
output: null,
payload: {
projectId: 'proj-1',
transcode: {
videoStrategy: 'best_match',
thumbnail: true,
},
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-1',
storageKey: { key: 'video.mp4' },
mediaType: 'video/mp4',
})
mockActivities.getMediaInfoActivity.mockResolvedValue({
mimeType: 'video/mp4',
metadata: { originalWidth: 1920, originalHeight: 1080, duration: 10, frameRate: 30 },
videoTranscodes: [],
imageTranscodes: [],
})
mockActivities.transcodeVideoActivity.mockResolvedValue({
key: 'v.mp4',
width: 1920,
height: 1080,
})
mockActivities.transcodeImageActivity.mockResolvedValue({
key: 't.webp',
width: 480,
height: 270,
})
await transcodeMedia(task)
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
assetId: 'asset-1',
status: AssetStatus.processing,
})
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith({
assetId: 'asset-1',
mediaInfo: expect.objectContaining({
thumbnail: expect.objectContaining({
key: 't.webp',
}),
}),
})
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
assetId: 'asset-1',
status: AssetStatus.processed,
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-1',
status: WorkflowTaskStatus.completed,
})
})
it('should process image transcode and thumbnail successfully', async () => {
const task: WorkflowTask = {
id: 'task-image',
assetId: 'asset-image',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
output: null,
payload: {
projectId: 'proj-1',
transcode: {
thumbnail: true,
},
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-image',
storageKey: { key: 'image.jpg' },
mediaType: 'image/jpeg',
})
mockActivities.getMediaInfoActivity.mockResolvedValue({
mimeType: 'image/jpeg',
metadata: { originalWidth: 1000, originalHeight: 1000 },
videoTranscodes: [],
imageTranscodes: [],
})
mockActivities.transcodeImageActivity.mockResolvedValue({
key: 't.webp',
width: 480,
height: 480,
format: 'webp',
})
await transcodeMedia(task)
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
assetId: 'asset-image',
status: AssetStatus.processing,
})
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith({
assetId: 'asset-image',
mediaInfo: expect.objectContaining({
thumbnail: expect.objectContaining({
key: 't.webp',
width: 480,
height: 480,
}),
}),
})
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
assetId: 'asset-image',
status: AssetStatus.processed,
})
})
it('should handle failures and update task status with error', async () => {
const task: WorkflowTask = {
id: 'task-fail',
assetId: 'asset-1',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
output: null,
payload: {
projectId: 'proj-1',
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockRejectedValue(new Error('FFmpeg failed'))
await expect(transcodeMedia(task)).rejects.toThrow('FFmpeg failed')
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-fail',
status: WorkflowTaskStatus.failed,
output: { error: 'FFmpeg failed' },
})
})
})
@@ -0,0 +1,313 @@
import type { WorkflowTask } from '@shumai/db'
import { ApplicationFailure } from '@temporalio/workflow'
import {
getActivities,
executeActivity,
TaskQueueDb,
TaskQueueTranscode,
} from '@shumai/workflow-core'
export async function transcodeMedia(task: WorkflowTask): Promise<void> {
const {
updateTaskStatusActivity,
updateAssetStatusActivity,
getAssetActivity,
getMediaInfoActivity,
transcodeVideoActivity,
transcodeImageActivity,
generateSpriteActivity,
updateAssetMediaActivity,
getTranscodeWorkerQueueActivity,
downloadMediaToTmpActivity,
cleanupTmpDirActivity,
} = getActivities()
let tmpDir: string | undefined
let workerQueue = ''
try {
// 1. Update status to processing
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
await executeActivity(TaskQueueDb, updateAssetStatusActivity, {
assetId: task.assetId,
status: 'processing',
})
// 2. Get Asset
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
const key = asset?.storageKey?.key
if (!asset || !key) {
throw ApplicationFailure.create({
message: 'Asset not found or has no key',
nonRetryable: true,
})
}
// 3. Get Worker-Specific Queue for Transcode
workerQueue = await executeActivity(TaskQueueTranscode, getTranscodeWorkerQueueActivity)
// 4. Download Media to Tmp
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
assetKey: key,
})
const { filePath } = download
tmpDir = download.tmpDir
// 5. Get Media Info
const spec = task.payload?.transcode || {}
const mediaInfo = await executeActivity(workerQueue, getMediaInfoActivity, {
filePath,
assetId: asset.id,
mediaType: asset.mediaType || '',
})
mediaInfo.original = {
key,
downloadUrl: '',
filesizeInBytes: 0,
codec: '',
}
const mimeType = mediaInfo.mimeType
const metadata = mediaInfo.metadata
// 6. Video Transcoding
if (mimeType.startsWith('video/') && metadata) {
const videoResolutions = getTargetVideoResolutions(
spec.videoStrategy || 'best_match',
metadata.originalWidth,
metadata.originalHeight,
)
for (const res of videoResolutions) {
const [width, height] = resolutionToDimensions(
res,
metadata.originalWidth,
metadata.originalHeight,
)
const videoSpec: PrismaJson.VideoTranscode = {
resolution: res,
width,
height,
}
const videoTranscode = await executeActivity(workerQueue, transcodeVideoActivity, {
assetKey: key,
filePath,
videoSpec,
duration: metadata.duration,
originalFps: metadata.frameRate,
})
if (res === '180p') {
mediaInfo.videoPreview = videoTranscode
} else {
mediaInfo.videoTranscodes.push(videoTranscode)
}
}
// Always keep raw
mediaInfo.videoTranscodes.push({
key: mediaInfo.original?.key,
width: metadata.originalWidth,
height: metadata.originalHeight,
isRaw: true,
})
}
// 7. Image Transcoding
const isImage = mimeType.startsWith('image/')
const isPsd = isMimePsd(mimeType)
if ((isImage || isPsd) && metadata) {
const imageSpec: PrismaJson.ImageTranscode = {
width: metadata.originalWidth,
height: metadata.originalHeight,
quality: 90,
format: 'webp',
}
const imageTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
assetKey: key,
filePath,
imageSpec,
})
mediaInfo.imageTranscodes.push(imageTranscode)
}
// 9. System: Thumbnail
if (spec.thumbnail) {
const thumbTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
assetKey: key,
filePath,
imageSpec: { width: 480, height: 0, quality: 80, format: 'webp' },
})
mediaInfo.thumbnail = thumbTranscode
}
// 10. System: Sprite/Poster (Video only usually)
if (spec.sprite || spec.poster) {
const lastSlashIndex = key.lastIndexOf('/')
const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex)
const spriteSpec: PrismaJson.SpriteInfo = {
key: assetDir ? `${assetDir}/sprite.webp` : 'sprite.webp',
frames: 100,
tileX: 10,
tileY: 10,
}
const posterSpec: PrismaJson.PosterInfo = {
key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp',
}
const spriteResult = await executeActivity(workerQueue, generateSpriteActivity, {
assetKey: key,
filePath,
spriteSpec,
posterSpec,
mediaInfo,
})
mediaInfo.sprite = spriteResult.sprite
mediaInfo.poster = spriteResult.poster
}
// 11. Update Asset Media and Status
await executeActivity(TaskQueueDb, updateAssetMediaActivity, {
assetId: asset.id,
mediaInfo,
})
await executeActivity(TaskQueueDb, updateAssetStatusActivity, {
assetId: asset.id,
status: 'processed',
})
// 12. Update Task Status
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
} catch (err) {
console.error(`TranscodeMedia failed for task ${task.id}:`, err)
// Update status to failed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
throw err
} finally {
if (tmpDir && workerQueue) {
try {
await executeActivity(workerQueue, cleanupTmpDirActivity, { tmpDir })
} catch (cleanupErr) {
console.error('Failed to cleanup tmp dir:', cleanupErr)
}
}
}
}
function isMimePsd(mimeType: string): boolean {
switch (mimeType) {
case 'image/vnd.adobe.photoshop':
case 'image/x-photoshop':
case 'application/x-photoshop':
case 'image/psd':
return true
}
return false
}
const RESOLUTION_LONG_SIDES: Record<string, number> = {
'2160p': 3840,
'1080p': 1920,
'720p': 1280,
'540p': 960,
'360p': 640,
'180p': 320,
}
function resolutionToDimensions(
resolution: string,
originalWidth: number,
originalHeight: number,
): [number, number] {
const targetLongSide = RESOLUTION_LONG_SIDES[resolution]
if (!targetLongSide) return [0, 0]
let width = 0
let height = 0
if (originalWidth >= originalHeight) {
// Landscape or square: width is the long side
width = targetLongSide
height = Math.round(width * (originalHeight / originalWidth))
} else {
// Portrait: height is the long side
height = targetLongSide
width = Math.round(height * (originalWidth / originalHeight))
}
// Ensure even dimensions for H.264
if (width % 2 !== 0) width++
if (height % 2 !== 0) height++
return [width, height]
}
const TARGET_RESOLUTIONS = [
{ name: '2160p', longSide: 3840 },
{ name: '1080p', longSide: 1920 },
{ name: '720p', longSide: 1280 },
{ name: '540p', longSide: 960 },
{ name: '360p', longSide: 640 },
]
function getBestMatchResolution(
originalWidth: number,
originalHeight: number,
): { name: string; longSide: number } {
const rawLongSide = Math.max(originalWidth, originalHeight)
const lower = TARGET_RESOLUTIONS.filter((r) => r.longSide <= rawLongSide)
if (lower.length > 0) {
lower.sort((a, b) => b.longSide - a.longSide)
return lower[0]
}
return TARGET_RESOLUTIONS[TARGET_RESOLUTIONS.length - 1] // 360p (longSide 640)
}
function getTargetVideoResolutions(
strategy: PrismaJson.VideoTranscodeStrategy,
originalWidth: number,
originalHeight: number,
): string[] {
const resolutions = ['180p']
// Normalize legacy strategies for backward compatibility
let normalizedStrategy: string = strategy
const stratStr = strategy as string
if (stratStr === 'single' || stratStr === 'disable') {
normalizedStrategy = 'best_match'
} else if (stratStr === 'full') {
normalizedStrategy = 'all'
}
const bestMatch = getBestMatchResolution(originalWidth, originalHeight)
if (normalizedStrategy === 'best_match') {
resolutions.push(bestMatch.name)
} else if (normalizedStrategy === 'all') {
const bestMatchIndex = TARGET_RESOLUTIONS.findIndex((r) => r.name === bestMatch.name)
if (bestMatchIndex !== -1) {
for (let i = bestMatchIndex; i < TARGET_RESOLUTIONS.length; i++) {
resolutions.push(TARGET_RESOLUTIONS[i].name)
}
}
}
return resolutions
}
export const transcodeWorkflow = transcodeMedia