diff --git a/packages/agent/src/database-session-storage.test.ts b/packages/agent/src/database-session-storage.test.ts index 2b3a4fe2..eb98708e 100644 --- a/packages/agent/src/database-session-storage.test.ts +++ b/packages/agent/src/database-session-storage.test.ts @@ -2,7 +2,7 @@ import { prisma } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' import { s3Service } from '@shumai/core/src/s3/s3' import { type SessionTreeEntry } from '@earendil-works/pi-agent-core' -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi, afterEach } from 'vitest' import { DatabaseSessionStorage } from './database-session-storage' import { agentService } from '@shumai/core/src/agent/agent' import { createAgentSession } from './index' @@ -13,6 +13,10 @@ import * as screenshotModule from './tools/screenshot' describe('DatabaseSessionStorage', () => { setupTestDbHooks() + afterEach(() => { + vi.restoreAllMocks() + }) + const mockModelConfig: PrismaJson.ModelConfig = { reasoning: false, input: ['text'], @@ -392,7 +396,7 @@ describe('DatabaseSessionStorage', () => { expect(entries[2].id).toBe('01C') }) - it('should use the current comment ID for media tools in subsequent turns', async () => { + it('should use the current comment ID for media tools in subsequent turns (image)', async () => { const { agent, user, team } = await setupTestData() // Create a project and asset to satisfy FK constraints @@ -441,6 +445,58 @@ describe('DatabaseSessionStorage', () => { // 4. Assert that the tools were instantiated using the new comment ID, not the original one expect(createAnalyzeImageToolSpy).toHaveBeenCalledWith(asset.id, 'new-comment-456') + expect(createScreenshotToolSpy).not.toHaveBeenCalled() + }) + + it('should use the current comment ID for media tools in subsequent turns (video)', async () => { + const { agent, user, team } = await setupTestData() + + // Create a project and asset to satisfy FK constraints + const project = await prisma.project.create({ + data: { name: 'Test Project', teamId: team.id }, + }) + const asset = await prisma.asset.create({ + data: { + id: 'asset-456', + name: 'test.mp4', + type: 'file', + mediaType: 'video/mp4', + projectId: project.id, + status: 'uploaded', + }, + }) + + // 1. Create a session with an original comment ID and an asset ID using the storage class + const initialStorage = await DatabaseSessionStorage.create({ + agentId: agent.id, + userId: user.id, + cwd: '/test/cwd', + assetId: asset.id, + userCommentId: 'original-comment-123', + }) + const sessionId = initialStorage.sessionId + + // 2. Spy on media tools constructors + const createAnalyzeImageToolSpy = vi.spyOn(analyzeImageModule, 'createAnalyzeImageTool') + const createScreenshotToolSpy = vi.spyOn(screenshotModule, 'createScreenshotTool') + + // 3. Resume the session via createAgentSession with a NEW comment ID + await createAgentSession({ + teamId: 't1', + agentId: agent.id, + providerName: 'test-provider', + modelId: 'test-model', + systemPrompt: 'Test prompt', + teamSkills: [], + allowedDomains: [], + sessionId: sessionId, + userId: user.id, + userCommentId: 'new-comment-456', + providers: [], + }) + + // 4. Assert that the tools were instantiated using the new comment ID, not the original one expect(createScreenshotToolSpy).toHaveBeenCalledWith(asset.id, 'new-comment-456') + expect(createAnalyzeImageToolSpy).not.toHaveBeenCalled() }) }) diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index f4eb3686..6ae42d62 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -15,6 +15,7 @@ import { agentService } from '@shumai/core/src/agent/agent' import { DatabaseSessionStorage } from './database-session-storage' import { createAnalyzeImageTool } from './tools/analyze-image' import { createScreenshotTool } from './tools/screenshot' +import { getSimpleMediaType } from './workflows/agent-chat-prompt-builder' import { createCreateFileTool } from './tools/create-file' import { createCreateFolderTool } from './tools/create-folder' import { createCreateVersionTool } from './tools/create-version' @@ -212,10 +213,17 @@ export async function createAgentSession(params: CreateAgentSessionParams) { const mediaTools: AgentTool[] = [] if (assetId) { - mediaTools.push( - createAnalyzeImageTool(assetId, userCommentId), - createScreenshotTool(assetId, userCommentId), - ) + const asset = await prisma.asset.findUnique({ + where: { id: assetId }, + }) + if (asset?.mediaType) { + const type = getSimpleMediaType(asset.mediaType) + if (type === 'image') { + mediaTools.push(createAnalyzeImageTool(assetId, userCommentId)) + } else if (type === 'video') { + mediaTools.push(createScreenshotTool(assetId, userCommentId)) + } + } } const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, { diff --git a/packages/agent/src/workflows/agent-autofill.test.ts b/packages/agent/src/workflows/agent-autofill.test.ts index 2988298c..c4fb185f 100644 --- a/packages/agent/src/workflows/agent-autofill.test.ts +++ b/packages/agent/src/workflows/agent-autofill.test.ts @@ -283,4 +283,32 @@ describe('Agent Autofill Workflow', () => { tmpDir: '/tmp/test-dir', }) }) + + it('should fail with non-retryable ApplicationFailure for unsupported audio files', async () => { + mockActivities.getAssetActivity.mockResolvedValue({ + id: 'a1', + storageKey: { key: 'asset-key' }, + project: { id: 'p1', teamId: 't1' }, + mediaType: 'audio/mp3', + }) + + const task = await prisma.workflowTask.create({ + data: { + type: 'ai_metadata_autofill', + status: 'pending', + assetId: 'a1', + }, + }) + + await expect(agentAutofillMedia(task)).rejects.toThrow( + 'unsupported media type for autofill: audio/mp3', + ) + + // Verify task failed status + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'failed', + output: { error: 'unsupported media type for autofill: audio/mp3' }, + }) + }) }) diff --git a/packages/agent/src/workflows/agent-autofill.ts b/packages/agent/src/workflows/agent-autofill.ts index 340fa09f..84e620f8 100644 --- a/packages/agent/src/workflows/agent-autofill.ts +++ b/packages/agent/src/workflows/agent-autofill.ts @@ -65,6 +65,14 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise { // 2. Prepare Data (Images) const isImage = asset.mediaType?.startsWith('image/') || false + const isVideo = asset.mediaType?.startsWith('video/') || false + + if (!isImage && !isVideo) { + throw ApplicationFailure.create({ + message: `unsupported media type for autofill: ${asset.mediaType}`, + nonRetryable: true, + }) + } const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, { assetKey: key, diff --git a/packages/core/src/transcode/transcode.test.ts b/packages/core/src/transcode/transcode.test.ts index 61ea2639..2657068f 100644 --- a/packages/core/src/transcode/transcode.test.ts +++ b/packages/core/src/transcode/transcode.test.ts @@ -270,4 +270,81 @@ describe('TranscodeService', () => { expect(task.payload?.projectId).toBe('proj-123') expect(task.payload?.transcode?.videoStrategy).toBe('best_match') }) + + it('should parse audio info correctly from ffprobe output', async () => { + /* eslint-disable @typescript-eslint/naming-convention */ + const mockOutput = JSON.stringify({ + format: { duration: '120.4', bit_rate: '256000' }, + streams: [ + { + codec_type: 'audio', + codec_name: 'flac', + channels: 6, + sample_rate: '44100', + bits_per_sample: '24', + tags: { + mime_codec_string: 'fLaC', + }, + }, + ], + }) + /* eslint-enable @typescript-eslint/naming-convention */ + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ;(child_process.execFile as any).mockImplementation((file: string, args: string[], cb: any) => { + cb(null, { stdout: mockOutput, stderr: '' }) + }) + + const info = await transcodeService.getAudioInfo('test.flac') + + expect(info.originalWidth).toBe(0) + expect(info.originalHeight).toBe(0) + expect(info.duration).toBe(120.4) + expect(info.frameRate).toBe(0) + expect(info.hasAudio).toBe(true) + expect(info.videoCodec).toBeUndefined() + expect(info.audioCodec).toBe('Fres Lossless Audio Codec') + expect(info.audioChannels).toBe(6) + expect(info.audioSampleRate).toBe(44100) + expect(info.audioBitDepth).toBe(24) + + expect(child_process.execFile).toHaveBeenCalledWith( + 'ffprobe', + expect.any(Array), + expect.any(Function), + ) + }) + + it('should construct correct ffmpeg arguments for audio transcoding', async () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ;(child_process.execFile as any).mockImplementation((file: string, args: string[], cb: any) => { + cb(null, { stdout: '', stderr: '' }) + }) + + await transcodeService.transcodeAudio({ + inputFile: 'input.wav', + outputFile: 'output.mp4', + bitrate: '128k', + }) + + expect(child_process.execFile).toHaveBeenCalledWith( + 'ffmpeg', + [ + '-y', + '-loglevel', + 'warning', + '-i', + 'input.wav', + '-vn', + '-c:a', + 'aac', + '-b:a', + '128k', + '-ac', + '2', + 'output.mp4', + ], + expect.any(Function), + ) + }) }) diff --git a/packages/core/src/transcode/transcode.ts b/packages/core/src/transcode/transcode.ts index 97f92f0a..baba2a68 100644 --- a/packages/core/src/transcode/transcode.ts +++ b/packages/core/src/transcode/transcode.ts @@ -292,6 +292,67 @@ export class TranscodeService { await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args]) } + async getAudioInfo(inputFile: string): Promise { + const { stdout } = await execFileAsync('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 audioStream = info.streams.find((s: any) => s.codec_type === 'audio') + + if (!audioStream) { + throw new Error('No audio stream found') + } + + const duration = parseFloat(info.format.duration) + + return { + originalWidth: 0, + originalHeight: 0, + duration: isNaN(duration) ? 0 : duration, + bitRate: parseFloat(info.format.bit_rate) || 0, + frameRate: 0, + totalFrames: 0, + startTimecode: undefined, + hasAudio: true, + videoCodec: undefined, + audioCodec: this.resolveCodecName(audioStream), + 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 transcodeAudio(params: { + inputFile: string + outputFile: string + bitrate?: string + }): Promise { + const bitrate = params.bitrate || '128k' + const args = [ + '-i', + params.inputFile, + '-vn', + '-c:a', + 'aac', + '-b:a', + bitrate, + '-ac', + '2', + params.outputFile, + ] + await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args]) + } + async extractVideoFrames(params: ExtractVideoFramesParams): Promise { if (params.isImage) { const outputFile = path.join(params.outputDir, '1.webp') diff --git a/packages/core/src/upload/upload.test.ts b/packages/core/src/upload/upload.test.ts index 4fbece50..f3c0b6e1 100644 --- a/packages/core/src/upload/upload.test.ts +++ b/packages/core/src/upload/upload.test.ts @@ -388,4 +388,37 @@ describe('UploadService', () => { expect(result.data[0].id).toBe(task.id) expect(result.data[0].name).toBe('test-upload-task') }) + + it('should correct the mediaType for .wma files that browser incorrectly reports as video', async () => { + const req = { + parentId: parentId, + files: [ + { + name: 'song.wma', + id: '1', + size: 100, + type: 'file' as const, + mediaType: 'video/x-ms-wma', + children: [], + }, + { + name: 'other_song.WMA', + id: '2', + size: 200, + type: 'file' as const, + mediaType: 'video/x-ms-asf', + children: [], + }, + ], + } + + const resp = await uploadService.createUploadTask(userId, req) + expect(resp.taskId).toBeDefined() + + const song1 = await prisma.asset.findFirst({ where: { name: 'song.wma' } }) + expect(song1?.mediaType).toBe('audio/x-ms-wma') + + const song2 = await prisma.asset.findFirst({ where: { name: 'other_song.WMA' } }) + expect(song2?.mediaType).toBe('audio/x-ms-asf') + }) }) diff --git a/packages/core/src/upload/upload.ts b/packages/core/src/upload/upload.ts index 896493cf..84cd3972 100644 --- a/packages/core/src/upload/upload.ts +++ b/packages/core/src/upload/upload.ts @@ -134,13 +134,18 @@ export class UploadService { key = `files/${ulid()}/${sanitizeFilename(file.name)}` } + let mediaType = file.mediaType + if (mediaType && file.name.toLowerCase().endsWith('.wma') && mediaType.startsWith('video/')) { + mediaType = mediaType.replace(/^video\//, 'audio/') + } + const newAsset = await tx.asset.create({ data: { name: file.name, type: assetType, storageKey: key ? { create: { key } } : undefined, sortIndex: newSortIndex, - mediaType: file.mediaType, + mediaType: mediaType, status: assetType === AssetType.folder ? AssetStatus.uploaded : AssetStatus.uploading, sizeByte: file.size, creator: userId ? { connect: { id: userId } } : undefined, @@ -289,7 +294,11 @@ export class UploadService { }, }) - if (autofillAgent) { + const isVideo = asset.mediaType?.startsWith('video/') + const isImage = asset.mediaType?.startsWith('image/') + const isAudio = asset.mediaType?.startsWith('audio/') + + if (autofillAgent && (isVideo || isImage)) { await tx.workflowTask.create({ data: { assetId: asset.id, @@ -305,9 +314,7 @@ export class UploadService { }) } - const isVideo = asset.mediaType?.startsWith('video/') - const isImage = asset.mediaType?.startsWith('image/') - if (!isVideo && !isImage) { + if (!isVideo && !isImage && !isAudio) { await tx.asset.update({ where: { id: asset.id }, data: { status: AssetStatus.processed }, @@ -322,6 +329,9 @@ export class UploadService { .withSprite() .withPoster() .submit() + } else if (isAudio) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + await new VideoTranscoder(tx as any, asset.id, team.id, projectId).submit() } else if (isImage) { // eslint-disable-next-line @typescript-eslint/no-explicit-any await new ImageTranscoder(tx as any, asset.id, team.id, projectId).withThumbnail().submit() diff --git a/packages/transcode/src/activities/transcode.test.ts b/packages/transcode/src/activities/transcode.test.ts index 042d8d69..5bfb7305 100644 --- a/packages/transcode/src/activities/transcode.test.ts +++ b/packages/transcode/src/activities/transcode.test.ts @@ -14,6 +14,7 @@ import { overlayAnnotationsActivity, takeScreenshotsActivity, transcodeVideoActivity, + transcodeAudioActivity, updateAssetMediaActivity, downloadMediaToTmpActivity, transcodeImageActivity, @@ -36,8 +37,10 @@ vi.mock('@shumai/core/src/s3/s3', () => ({ vi.mock('@shumai/core/src/transcode/transcode', () => ({ transcodeService: { getVideoInfo: vi.fn(), + getAudioInfo: vi.fn(), getImageInfo: vi.fn(), transcodeVideo: vi.fn(), + transcodeAudio: vi.fn(), transcodeImage: vi.fn(), generateSprite: vi.fn(), createTempDir: vi.fn().mockReturnValue('/tmp'), @@ -143,20 +146,49 @@ describe('Transcode Activities', () => { ) }) - it('should set file_type to audio for audio files', async () => { + it('should set file_type to audio for audio files and extract audio metadata', async () => { const asset = await prisma.asset.create({ data: { name: 'a.mp3', type: 'file', status: 'uploaded' }, }) + vi.mocked(transcodeService.getAudioInfo).mockResolvedValue({ + originalWidth: 0, + originalHeight: 0, + duration: 45.5, + bitRate: 128000, + frameRate: 0, + totalFrames: 0, + hasAudio: true, + audioCodec: 'mp3', + audioChannels: 2, + audioSampleRate: 44100, + audioBitDepth: 16, + mimeType: 'audio/mpeg', + }) - await getMediaInfoActivity({ + const result = await getMediaInfoActivity({ assetId: asset.id, filePath: '/tmp/a.mp3', mediaType: 'audio/mpeg', }) + expect(transcodeService.getAudioInfo).toHaveBeenCalledWith('/tmp/a.mp3') + expect(result.duration).toBe(45.5) + expect(result.metadata?.duration).toBe(45.5) + expect(result.metadata?.audioCodec).toBe('mp3') + expect(result.metadata?.audioChannels).toBe(2) + expect(result.metadata?.audioSampleRate).toBe(44100) + expect(result.metadata?.audioBitDepth).toBe(16) + expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith( asset.id, - expect.arrayContaining([{ key: 'file_type', value: 'audio' }]), + expect.arrayContaining([ + { key: 'file_type', value: 'audio' }, + { key: 'duration', value: 45.5 }, + { key: 'audio_codec', value: 'mp3' }, + { key: 'audio_channels', value: 2 }, + { key: 'audio_sample_rate', value: 44100 }, + { key: 'audio_bit_depth', value: 16 }, + ]), true, ) }) @@ -437,5 +469,53 @@ describe('Transcode Activities', () => { await deleteS3ObjectActivity({ key: 'files/test-key.mp4' }) expect(s3Service.deleteObject).toHaveBeenCalledWith('shumai', 'files/test-key.mp4') }) + + it('should transcode audio file and upload proxy to S3', async () => { + vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found')) + vi.mocked(transcodeService.transcodeAudio).mockResolvedValue() + + const res = await transcodeAudioActivity({ + assetKey: 'files/proj-123/a.wav', + filePath: '/tmp/a.wav', + }) + + expect(transcodeService.transcodeAudio).toHaveBeenCalledWith({ + inputFile: '/tmp/a.wav', + outputFile: expect.stringContaining('a-audio-proxy.mp4'), + bitrate: '128k', + }) + + expect(s3Service.putObject).toHaveBeenCalledWith( + 'shumai', + 'files/proj-123/a-audio-proxy.mp4', + expect.any(Buffer), + expect.any(Number), + 'video/mp4', + ) + + expect(res).toEqual({ + width: 0, + height: 0, + key: 'files/proj-123/a-audio-proxy.mp4', + }) + }) + + it('should return existing audio transcode if already exists in S3', async () => { + vi.mocked(s3Service.headObject).mockResolvedValue( + {} as Awaited>, + ) + + const res = await transcodeAudioActivity({ + assetKey: 'files/proj-123/a.wav', + filePath: '/tmp/a.wav', + }) + + expect(transcodeService.transcodeAudio).not.toHaveBeenCalled() + expect(res).toEqual({ + width: 0, + height: 0, + key: 'files/proj-123/a-audio-proxy.mp4', + }) + }) }) }) diff --git a/packages/transcode/src/activities/transcode.ts b/packages/transcode/src/activities/transcode.ts index dc6e6477..d601fb71 100644 --- a/packages/transcode/src/activities/transcode.ts +++ b/packages/transcode/src/activities/transcode.ts @@ -116,6 +116,36 @@ export async function getMediaInfoActivity(params: { metadataUpdates.push({ key: 'audio_sample_rate', value: info.audioSampleRate }) if (info.audioBitDepth !== undefined) metadataUpdates.push({ key: 'audio_bit_depth', value: info.audioBitDepth }) + } else if (isAudio) { + const info = await transcodeService.getAudioInfo(params.filePath) + mediaInfo.duration = info.duration + mediaInfo.metadata = { + originalWidth: 0, + originalHeight: 0, + duration: info.duration, + bitRate: info.bitRate, + frameRate: 0, + totalFrames: 0, + startTimecode: '00:00:00:00', + hasAudio: true, + videoCodec: undefined, + audioCodec: info.audioCodec, + audioChannels: info.audioChannels, + audioSampleRate: info.audioSampleRate, + audioBitDepth: info.audioBitDepth, + format: {}, + } + metadataUpdates.push( + { key: 'duration', value: info.duration }, + { key: 'bitRate', value: info.bitRate / 1000 }, + ) + 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 }) } else if (isImage) { const info = await transcodeService.getImageInfo(params.filePath) mediaInfo.metadata = { @@ -230,6 +260,64 @@ export async function transcodeVideoActivity( } } +export interface AudioActivityParams { + assetKey: string + filePath: string +} + +export async function transcodeAudioActivity( + params: AudioActivityParams, +): Promise { + const bucket = process.env.S3_BUCKET || 'shumai' + const stem = stemFromKey(params.assetKey) + const key = path.posix.join(path.posix.dirname(params.assetKey), `${stem}-audio-proxy.mp4`) + + try { + await s3Service.headObject(bucket, key) + return { width: 0, height: 0, key } + } catch { + // Not found + } + + const tmpDir = path.dirname(params.filePath) + const outputFile = path.join(tmpDir, `${stem}-audio-proxy.mp4`) + + try { + await transcodeService.transcodeAudio({ + inputFile: params.filePath, + outputFile, + bitrate: '128k', + }) + + const buffer = fs.readFileSync(outputFile) + await s3Service.putObject(bucket, key, buffer, buffer.length, 'video/mp4') + + return { width: 0, height: 0, key } + } catch (err) { + const { code, message } = getErrorDetails(err) + const lowerMsg = message.toLowerCase() + + if ( + code === 'ENOENT' || + lowerMsg.includes('enoent') || + lowerMsg.includes('ffmpeg') || + lowerMsg.includes('ffprobe') || + lowerMsg.includes('spawn') || + lowerMsg.includes('format') || + lowerMsg.includes('no video stream found') + ) { + throw ApplicationFailure.create({ + message: `Audio transcoding failed: ${message}`, + nonRetryable: true, + cause: err instanceof Error ? err : undefined, + }) + } + throw err + } finally { + if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile) + } +} + export interface ImageActivityParams { assetKey: string filePath: string @@ -494,23 +582,25 @@ export interface CreateEmbeddingTaskIfEnabledParams { export async function createEmbeddingTaskIfEnabledActivity( params: CreateEmbeddingTaskIfEnabledParams, ): Promise { - let teamId = params.teamId - let projectId = params.projectId - - // Resolve teamId and projectId from asset if missing - if (!teamId || !projectId) { - const asset = await prisma.asset.findUnique({ - where: { id: params.assetId }, - include: { - project: true, - }, - }) - if (asset) { - projectId = projectId || asset.projectId - teamId = teamId || asset.project?.teamId || null - } + const asset = await prisma.asset.findUnique({ + where: { id: params.assetId }, + include: { + project: true, + }, + }) + if (!asset) { + return } + const isVideo = asset.mediaType?.startsWith('video/') + const isImage = asset.mediaType?.startsWith('image/') + if (!isVideo && !isImage) { + return + } + + const teamId = params.teamId || asset.project?.teamId || null + const projectId = params.projectId || asset.projectId + if (!teamId) { return } diff --git a/packages/transcode/src/workflows/transcode.test.ts b/packages/transcode/src/workflows/transcode.test.ts index c6517c7a..2ffd0300 100644 --- a/packages/transcode/src/workflows/transcode.test.ts +++ b/packages/transcode/src/workflows/transcode.test.ts @@ -25,6 +25,7 @@ describe('Transcode Workflow', () => { getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }), getMediaInfoActivity: Object.assign(vi.fn(), { _activityName: 'getMediaInfoActivity' }), transcodeVideoActivity: Object.assign(vi.fn(), { _activityName: 'transcodeVideoActivity' }), + transcodeAudioActivity: Object.assign(vi.fn(), { _activityName: 'transcodeAudioActivity' }), transcodeImageActivity: Object.assign(vi.fn(), { _activityName: 'transcodeImageActivity' }), generateSpriteActivity: Object.assign(vi.fn(), { _activityName: 'generateSpriteActivity' }), updateAssetMediaActivity: Object.assign(vi.fn(), { @@ -388,4 +389,87 @@ describe('Transcode Workflow', () => { output: { key: 'files/asset-image/annotations/ann1.webp' }, }) }) + + it('should run audio transcoding workflow successfully', async () => { + const task: WorkflowTask = { + id: 'task-audio', + assetId: 'asset-audio', + type: WorkflowTaskType.transcode, + status: WorkflowTaskStatus.pending, + output: null, + payload: { + projectId: 'proj-1', + transcode: {}, + }, + createdAt: new Date(), + updatedAt: new Date(), + heartbeat: null, + teamId: 'team-1', + projectId: 'proj-1', + uid: 'task-uid-2', + model: null, + inputTokens: 0, + outputTokens: 0, + } + + mockActivities.getAssetActivity.mockResolvedValue({ + id: 'asset-audio', + storageKey: { key: 'audio.wav' }, + mediaType: 'audio/wav', + }) + + mockActivities.getMediaInfoActivity.mockResolvedValue({ + mimeType: 'audio/wav', + metadata: { + originalWidth: 0, + originalHeight: 0, + duration: 30, + bitRate: 1411200, + frameRate: 0, + totalFrames: 0, + hasAudio: true, + audioCodec: 'pcm_s16le', + audioChannels: 2, + }, + original: { + key: 'audio.wav', + downloadUrl: '', + filesizeInBytes: 0, + codec: '', + }, + videoTranscodes: [], + }) + + mockActivities.transcodeAudioActivity.mockResolvedValue({ + width: 0, + height: 0, + key: 'files/asset-audio/audio-audio-proxy.mp4', + }) + + await transcodeMedia(task) + + expect(mockActivities.transcodeAudioActivity).toHaveBeenCalledWith({ + assetKey: 'audio.wav', + filePath: '/tmp/video.mp4', + }) + + expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith({ + assetId: 'asset-audio', + mediaInfo: expect.objectContaining({ + mimeType: 'audio/wav', + videoTranscodes: [ + { + width: 0, + height: 0, + key: 'files/asset-audio/audio-audio-proxy.mp4', + }, + ], + }), + }) + + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: 'task-audio', + status: WorkflowTaskStatus.completed, + }) + }) }) diff --git a/packages/transcode/src/workflows/transcode.ts b/packages/transcode/src/workflows/transcode.ts index d4944379..7be0ae6f 100644 --- a/packages/transcode/src/workflows/transcode.ts +++ b/packages/transcode/src/workflows/transcode.ts @@ -10,6 +10,7 @@ export async function transcodeMedia(task: WorkflowTask): Promise { getAssetActivity, getMediaInfoActivity, transcodeVideoActivity, + transcodeAudioActivity, transcodeImageActivity, generateSpriteActivity, updateAssetMediaActivity, @@ -181,6 +182,16 @@ export async function transcodeMedia(task: WorkflowTask): Promise { }) } + // 6.5 Audio Transcoding + const isAudio = mimeType.startsWith('audio/') + if (isAudio && metadata) { + const audioTranscode = await executeActivity(workerQueue, transcodeAudioActivity, { + assetKey: key, + filePath, + }) + mediaInfo.videoTranscodes.push(audioTranscode) + } + // 7. Image Transcoding const isImage = mimeType.startsWith('image/') const isPsd = isMimePsd(mimeType) diff --git a/packages/webui/components/breadcrumb-nav.tsx b/packages/webui/components/breadcrumb-nav.tsx index d3e3581a..0e487755 100644 --- a/packages/webui/components/breadcrumb-nav.tsx +++ b/packages/webui/components/breadcrumb-nav.tsx @@ -34,6 +34,7 @@ interface BreadcrumbNavProps { name?: string type: 'file' | 'folder' version?: number + mediaType?: string | null } isRootFolder: boolean displayStyle?: 'card' | 'list' @@ -135,8 +136,11 @@ export function BreadcrumbNav({ } } + const isAudio = currentAsset.mediaType?.startsWith('audio/') const hasVideoTranscodes = - downloadInfo?.videoTranscodes && downloadInfo.videoTranscodes.filter((t) => !t.isRaw).length > 0 + !isAudio && + downloadInfo?.videoTranscodes && + downloadInfo.videoTranscodes.filter((t) => !t.isRaw).length > 0 const breadcrumbs: { name: string; path?: string; id?: string; isMuted?: boolean }[] = isPublic ? [ diff --git a/packages/webui/components/file-browser/file-browser.tsx b/packages/webui/components/file-browser/file-browser.tsx index aa1857f4..2bfb9d62 100644 --- a/packages/webui/components/file-browser/file-browser.tsx +++ b/packages/webui/components/file-browser/file-browser.tsx @@ -513,7 +513,10 @@ export function FileBrowser({ fileCount: 0, type: 'file', status: hasUrl ? 'uploading' : 'error', - mediaType: f.file.type || null, + mediaType: + f.file.name.toLowerCase().endsWith('.wma') && f.file.type?.startsWith('video/') + ? f.file.type.replace(/^video\//, 'audio/') + : f.file.type || null, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), } @@ -846,13 +849,17 @@ export function FileBrowser({ } const fileWithId = { file, id: ulid() } fileWithIds.push(fileWithId) + let mediaType = file.type + if (fileName.toLowerCase().endsWith('.wma') && mediaType?.startsWith('video/')) { + mediaType = mediaType.replace(/^video\//, 'audio/') + } currentLevel.push({ name: fileName, size: file.size, type: 'file', id: fileWithId.id, children: [], - mediaType: file.type, + mediaType, }) } filesToUpload = fileWithIds diff --git a/packages/webui/components/file-browser/file-list-item.tsx b/packages/webui/components/file-browser/file-list-item.tsx index 7d87b807..1704b1f6 100644 --- a/packages/webui/components/file-browser/file-list-item.tsx +++ b/packages/webui/components/file-browser/file-list-item.tsx @@ -3,7 +3,7 @@ import { client } from '@/ui/api/client' import { useQuery } from '@tanstack/react-query' import { useDraggable } from '@dnd-kit/react' -import { File, Folder, MoreVertical } from 'lucide-react' +import { File, Folder, MoreVertical, AudioLines } from 'lucide-react' import React, { useEffect, useMemo, useRef, useState } from 'react' import { cn } from '@/ui/lib/utils' import type { DragState } from '../dnd-types' @@ -214,6 +214,9 @@ export function FileListItem({ alt="" className="w-full h-full object-cover" /> + ) : displayItem.preview?.mediaType?.startsWith('audio/') || + displayItem.mediaType?.startsWith('audio/') ? ( + ) : displayItem.type === 'folder' ? ( ) : ( diff --git a/packages/webui/components/file-browser/file-preview.tsx b/packages/webui/components/file-browser/file-preview.tsx index c7875cc3..362bc20a 100644 --- a/packages/webui/components/file-browser/file-preview.tsx +++ b/packages/webui/components/file-browser/file-preview.tsx @@ -1,4 +1,4 @@ -import { File, Folder } from 'lucide-react' +import { File, Folder, AudioLines } from 'lucide-react' import { SpriteScrubber } from '../sprite-scrubber' import { formatTime } from '../viewers/video/utils' @@ -21,9 +21,11 @@ interface FilePreviewProps { export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) => { const isVideo = item.preview?.mediaType?.startsWith('video/') + const isAudio = item.preview?.mediaType?.startsWith('audio/') + const hasDuration = isVideo || isAudio const duration = item.preview?.duration const durationOverlay = - showDuration && isVideo && typeof duration === 'number' && duration > 0 ? ( + showDuration && hasDuration && typeof duration === 'number' && duration > 0 ? ( {formatTime(duration)} @@ -63,6 +65,17 @@ export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) => ) } + if (isAudio) { + return ( + <> +
+ +
+ {durationOverlay} + + ) + } + // Assumption: folders in latestChildren have no media type. if (!item.type) { return ( diff --git a/packages/webui/components/file-viewer-left-sidebar.tsx b/packages/webui/components/file-viewer-left-sidebar.tsx index 70a41243..098648cf 100644 --- a/packages/webui/components/file-viewer-left-sidebar.tsx +++ b/packages/webui/components/file-viewer-left-sidebar.tsx @@ -2,7 +2,7 @@ import { client } from '@/ui/api/client' import { cn } from '@/ui/lib/utils' import type { AssetInfo, AssetInfoPaginatedList } from '@shumai/dtos' import { Link } from '@tanstack/react-router' -import { File, Loader2 } from 'lucide-react' +import { File, Loader2, AudioLines } from 'lucide-react' import type { FC } from 'react' import { useEffect, useRef, useState } from 'react' import { useInView } from 'react-intersection-observer' @@ -22,6 +22,16 @@ export const CarouselFilePreview = ({ item }: { item: AssetInfo }) => { ) } + const isAudio = + item.preview?.mediaType?.startsWith('audio/') || item.mediaType?.startsWith('audio/') + if (isAudio) { + return ( +
+ +
+ ) + } + return (
diff --git a/packages/webui/components/file-viewer.tsx b/packages/webui/components/file-viewer.tsx index df026049..c4ccec13 100644 --- a/packages/webui/components/file-viewer.tsx +++ b/packages/webui/components/file-viewer.tsx @@ -22,6 +22,7 @@ export function FileViewer({ return ( v.id === activeFileId)?.version ?? stackFileData.versionStack.versions.length) : undefined, + mediaType: viewingFileData?.mediaType || null, }, isRootFolder: currentFolderId === shareInfo.rootFolderId && !viewingFileId, isPublic: true, @@ -646,6 +647,10 @@ export function PublicShareManager({ mediaControllerRef.current?.pause() }} selectedCommentId={selectedCommentId} + hideAnnotationControl={(isCompareMode + ? compareActiveAsset + : currentSelectedItem + )?.mediaType?.startsWith('audio/')} />
diff --git a/packages/webui/components/viewers/video/compare-video-pane.tsx b/packages/webui/components/viewers/video/compare-video-pane.tsx index b63f4852..1c49d838 100644 --- a/packages/webui/components/viewers/video/compare-video-pane.tsx +++ b/packages/webui/components/viewers/video/compare-video-pane.tsx @@ -4,7 +4,7 @@ import { cn } from '@/ui/lib/utils' import { useAnnotationStore } from '@/ui/stores/annotation-store' import type { Annotation } from '@/ui/types' import type { AssetInfo } from '@shumai/dtos' -import { Play } from 'lucide-react' +import { Play, AudioLines } from 'lucide-react' import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react' import videojs from 'video.js' import type Player from 'video.js/dist/types/player' @@ -118,7 +118,8 @@ export const CompareVideoPane = forwardRef observer.disconnect() }, []) - const vidW = metadata?.originalWidth ?? 1920 - const vidH = metadata?.originalHeight ?? 1080 + const vidW = metadata?.originalWidth || 1920 + const vidH = metadata?.originalHeight || 1080 // Auto-fit zoom useEffect(() => { @@ -439,22 +440,34 @@ export const CompareVideoPane = forwardRef
- {videoHtmlEl && containerSize.width > 0 && ( - + {file.mediaType?.startsWith('audio/') ? ( +
+ +
+ ) : ( + videoHtmlEl && + containerSize.width > 0 && ( + + ) )} {!isPlaying && !isDrawing && ( diff --git a/packages/webui/components/viewers/video/index.tsx b/packages/webui/components/viewers/video/index.tsx index ee338712..11f0fbfd 100644 --- a/packages/webui/components/viewers/video/index.tsx +++ b/packages/webui/components/viewers/video/index.tsx @@ -5,7 +5,7 @@ import { CompareVideoPane } from './compare-video-pane' export const videoTypeDefinition: FileTypeDefinition = { id: 'video', name: 'Video', - match: (file) => !!file.mediaType?.startsWith('video/'), + match: (file) => !!file.mediaType?.startsWith('video/') || !!file.mediaType?.startsWith('audio/'), viewer: VideoViewer, comparePane: CompareVideoPane, commentsConfig: { diff --git a/packages/webui/components/viewers/video/use-frame-player.ts b/packages/webui/components/viewers/video/use-frame-player.ts index 5d063e03..c5735a0c 100644 --- a/packages/webui/components/viewers/video/use-frame-player.ts +++ b/packages/webui/components/viewers/video/use-frame-player.ts @@ -24,6 +24,7 @@ export function useFramePlayer( videoRef: React.RefObject, frameRate: number, totalFrames: number, + isAudio?: boolean, ): UseFramePlayerResult { const [currentFrame, setCurrentFrame] = useState(0) const isSeekingRef = useRef(false) @@ -113,7 +114,7 @@ export function useFramePlayer( const rVfcStalledAfterDelivery = hasDeliveredVfc && sinceLastVfc > stallThreshold const rVfcNeverDelivered = !hasDeliveredVfc && sinceLastVfc > INITIAL_VFC_GRACE_MS const useCurrentTimeFallback = - !rVfcSupported || rVfcStalledAfterDelivery || rVfcNeverDelivered + isAudio || !rVfcSupported || rVfcStalledAfterDelivery || rVfcNeverDelivered if (useCurrentTimeFallback) { const frame = Math.floor(video.currentTime * frameRate + 0.45) diff --git a/packages/webui/components/viewers/video/video-control-bar.tsx b/packages/webui/components/viewers/video/video-control-bar.tsx index ff05f3ea..12311310 100644 --- a/packages/webui/components/viewers/video/video-control-bar.tsx +++ b/packages/webui/components/viewers/video/video-control-bar.tsx @@ -113,6 +113,7 @@ export const VideoControlBar: React.FC = ({ // fullscreen). Compare keeps it in-flow. Colors stay theme-aware either way. const overlay = state.isFullScreen && floatOverlayInFullScreen + const isAudio = data.mediaType?.startsWith('audio/') const previewResolutions = resolutions.filter((r) => !r.isRaw) const startTimecode = data.media?.metadata?.startTimecode @@ -253,31 +254,33 @@ export const VideoControlBar: React.FC = ({ {/* Right Side: Zoom, Speed, Res, Download, Fullscreen */}
{/* Zoom Controls */} -
-
+ {!isAudio && ( +
+
+ + + {Math.round(zoom * 100)}% + + +
- - {Math.round(zoom * 100)}% - -
- -
+ )} {/* Playback Rate */} @@ -304,60 +307,73 @@ export const VideoControlBar: React.FC = ({ - {/* Resolution Selector */} - - - - + {/* Settings / Resolution */} + {!isAudio && previewResolutions.length > 0 && ( + + + + - - Quality - {previewResolutions.map((res) => ( - changeResolution(res)} - className={cn( - 'flex w-full items-center justify-between', - state.currentResolution === res.resolution - ? 'text-primary font-medium' - : 'text-foreground', - )} - > - {res.resolution} - - {res.width}x{res.height} - - - ))} - - + + Quality + {previewResolutions.map((res) => ( + changeResolution(res)} + className={cn( + 'flex w-full items-center justify-between', + state.currentResolution === res.resolution + ? 'text-primary font-medium' + : 'text-foreground', + )} + > + {res.resolution} + + {res.width}x{res.height} + + + ))} + + + )} {/* Download */} - - - - - - Download - {resolutions.map((res) => ( - handleDownload(res.key ?? '')} - className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground" - > - {res.resolution} - - {res.isRaw ? data.name?.split('.').pop()?.toUpperCase() || 'RAW' : 'MP4'} - - - ))} - - + {isAudio ? ( + + ) : ( + + + + + + Download + {resolutions.map((res) => ( + handleDownload(res.key ?? '')} + className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground" + > + {res.resolution} + + {res.isRaw ? data.name?.split('.').pop()?.toUpperCase() || 'RAW' : 'MP4'} + + + ))} + + + )} {/* Fullscreen */}
diff --git a/packages/webui/stores/top-nav.ts b/packages/webui/stores/top-nav.ts index e84af066..7dcae4d1 100644 --- a/packages/webui/stores/top-nav.ts +++ b/packages/webui/stores/top-nav.ts @@ -10,6 +10,7 @@ export interface TopNavProjectState { name?: string type: 'file' | 'folder' version?: number + mediaType?: string | null } isRootFolder: boolean fileId?: string