initial commit

This commit is contained in:
yiling
2026-05-19 16:05:09 +08:00
commit 9cad96210c
370 changed files with 131609 additions and 0 deletions
+125
View File
@@ -0,0 +1,125 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { getMediaInfoActivity, transcodeVideoActivity, updateAssetMediaActivity } from './transcode'
import { s3Service } from '@/services/s3/s3'
import { transcodeService } from '@/transcode/transcode'
vi.mock('@/services/s3/s3', () => ({
s3Service: {
getObject: vi.fn(),
putObject: vi.fn(),
headObject: vi.fn(),
presign: vi.fn(),
},
}))
vi.mock('@/transcode/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,
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)
})
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',
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()
})
})
+268
View File
@@ -0,0 +1,268 @@
import { prisma } from '@/db'
import { s3Service } from '@/services/s3/s3'
import { transcodeService } from '@/transcode/transcode'
import { metadataService } from '@/services/metadata/metadata'
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,
format: {},
}
await metadataService.updateAssetMetadata(params.assetId, [
{ 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 },
])
} 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 },
])
}
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 } })
if (!asset || !asset.key) throw new Error('Asset not found')
const infoKey = path.join(path.dirname(asset.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 },
})
}
+214
View File
@@ -0,0 +1,214 @@
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 '@/generated/prisma/client'
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',
width: 1920,
height: 1080,
r_frame_rate: '30/1',
},
{
codec_type: 'audio',
},
],
})
/* 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(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', {
videoStrategy: 'single',
thumbnail: true,
})) as WorkflowTask
expect(task.assetId).toBe('asset-123')
expect(task.type).toBe('transcode')
expect(task.status).toBe('pending')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((task.payload as any).videoStrategy).toBe('single')
})
})
+277
View File
@@ -0,0 +1,277 @@
import { exec } from 'child_process'
import { promisify } from 'util'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import sharp from 'sharp'
import { prisma } from '@/db'
import { WorkflowTaskType, WorkflowTaskStatus } from '@/generated/prisma/client'
import '@/prisma-json-types'
const execAsync = promisify(exec)
export interface MediaMetadata {
originalWidth: number
originalHeight: number
duration: number
bitRate: number
frameRate: number
hasAudio: boolean
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) {}
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,
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('-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, spec: PrismaJson.TaskSpec) {
return this.prismaClient.workflowTask.create({
data: {
assetId,
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload: spec as any,
},
})
}
async createImageTranscodeTask(assetId: string, spec: PrismaJson.TaskSpec) {
return this.prismaClient.workflowTask.create({
data: {
assetId,
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload: spec as any,
},
})
}
}
export const transcodeService = new TranscodeService()
+83
View File
@@ -0,0 +1,83 @@
import { prisma } from '@/db'
import { WorkflowTaskType, WorkflowTaskStatus } from '@/generated/prisma/client'
import '@/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: 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,
) {}
setStrategy(strategy: PrismaJson.ImageTranscodeStrategy): this {
this.spec.imageStrategy = strategy
return this
}
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: this.spec,
},
})
return task.id
}
}
+163
View File
@@ -0,0 +1,163 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { transcodeMedia } from './transcode'
import {
WorkflowTask,
WorkflowTaskStatus,
WorkflowTaskType,
AssetStatus,
} from '@/generated/prisma/client'
import * as workflowUtils from '@/workflow/workflow-utils'
vi.mock('@/workflow/workflow-utils', 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: {
videoStrategy: 'single',
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',
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).toHaveBeenCalled()
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
assetId: 'asset-1',
status: AssetStatus.processed,
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-1',
status: WorkflowTaskStatus.completed,
})
})
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: {},
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' },
})
})
})
+341
View File
@@ -0,0 +1,341 @@
import type { WorkflowTask } from '@/generated/prisma/client'
import {
getActivities,
executeActivity,
TaskQueueDb,
TaskQueueTranscode,
} from '@/workflow/workflow-utils'
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: string | undefined
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)
if (!asset || !asset.key) throw new Error('Asset not found')
// 3. Get Worker-Specific Queue for Transcode
workerQueue = await executeActivity(TaskQueueTranscode, getTranscodeWorkerQueueActivity)
// 4. Download Media to Tmp
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
assetKey: asset.key,
})
const { filePath } = download
tmpDir = download.tmpDir
// 5. Get Media Info
const spec = task.payload as PrismaJson.TaskSpec
const mediaInfo = await executeActivity(workerQueue, getMediaInfoActivity, {
filePath,
assetId: asset.id,
mediaType: asset.mediaType || '',
})
mediaInfo.original = {
key: asset.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 || 'disable',
metadata.originalHeight,
)
for (const res of videoResolutions) {
const [width, height] = resolutionToDimensions(
res,
metadata.originalWidth,
metadata.originalHeight,
)
if (width > metadata.originalWidth) continue
const videoSpec: PrismaJson.VideoTranscode = {
resolution: res,
width,
height,
}
const videoTranscode = await executeActivity(workerQueue, transcodeVideoActivity, {
assetKey: asset.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) {
if (metadata) {
const imageSpecs = getTargetImageResolutions(
spec.imageStrategy || 'disable',
metadata.originalWidth,
)
for (const imageSpec of imageSpecs) {
if (imageSpec.width > metadata.originalWidth) continue
const imageTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
assetKey: asset.key,
filePath,
imageSpec,
})
mediaInfo.imageTranscodes.push(imageTranscode)
}
}
}
// 8. PSD / Raw fallback
if (mediaInfo.imageTranscodes.length === 0 && isPsd && metadata) {
const imageSpec: PrismaJson.ImageTranscode = {
width: metadata.originalWidth,
height: metadata.originalHeight,
quality: 90,
format: 'webp',
}
const imageTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
assetKey: asset.key,
filePath,
imageSpec,
})
imageTranscode.isRaw = true
mediaInfo.imageTranscodes.push(imageTranscode)
} else if (isImage && metadata) {
// Always keep raw for image
mediaInfo.imageTranscodes.push({
key: mediaInfo.original?.key,
width: metadata.originalWidth,
height: metadata.originalHeight,
format: mimeType,
isRaw: true,
quality: 100,
})
}
// 9. System: Thumbnail
if (spec.thumbnail) {
const thumbTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
assetKey: asset.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 = asset.key.lastIndexOf('/')
const assetDir = lastSlashIndex === -1 ? '' : asset.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: asset.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
}
function resolutionToDimensions(
resolution: string,
originalWidth: number,
originalHeight: number,
): [number, number] {
const aspectRatio = originalWidth / originalHeight
let height = 0
switch (resolution) {
case '2160p':
height = 2160
break
case '1440p':
height = 1440
break
case '1080p':
height = 1080
break
case '720p':
height = 720
break
case '480p':
height = 480
break
case '360p':
height = 360
break
case '180p':
height = 180
break
default:
return [0, 0]
}
let width = Math.round(height * aspectRatio)
// Ensure even dimensions
if (width % 2 !== 0) width++
if (height % 2 !== 0) height++
return [width, height]
}
function getTargetVideoResolutions(
strategy: PrismaJson.VideoTranscodeStrategy,
originalHeight: number,
): string[] {
const resolutions = ['180p']
if (strategy === 'disable') return resolutions
const targets = [2160, 1440, 1080, 720, 480]
const targetMap: Record<number, string> = {
'2160': '2160p',
'1440': '1440p',
'1080': '1080p',
'720': '720p',
'480': '480p',
}
const validTargets = targets.filter((t) => t <= originalHeight)
if (strategy === 'single') {
if (validTargets.length > 0) {
resolutions.push(targetMap[validTargets[0]])
}
} else if (strategy === 'full') {
for (const t of validTargets) {
resolutions.push(targetMap[t])
}
}
return resolutions
}
function getTargetImageResolutions(
strategy: PrismaJson.ImageTranscodeStrategy,
originalWidth: number,
): PrismaJson.ImageTranscode[] {
if (strategy === 'disable') return []
const targets = [
{ width: 1920, quality: 80, format: 'webp' },
{ width: 1280, quality: 80, format: 'webp' },
{ width: 854, quality: 80, format: 'webp' },
]
if (strategy === 'single') {
const valid = targets.filter((t) => t.width <= originalWidth)
if (valid.length > 0) {
return [{ ...valid[0], height: 0 }]
}
}
return []
}
export const transcodeWorkflow = transcodeMedia