mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 10:56:52 +00:00
Merge pull request #217 from shumaiOne/feat/psd-imagemagick-support
feat(transcode): add PSD support via ImageMagick and enforce sRGB conversion
This commit is contained in:
@@ -32,7 +32,7 @@ jobs:
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y ripgrep bubblewrap socat ffmpeg poppler-utils
|
||||
sudo apt-get install -y ripgrep bubblewrap socat ffmpeg poppler-utils imagemagick
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
@@ -157,7 +157,7 @@ jobs:
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y ripgrep bubblewrap socat ffmpeg poppler-utils
|
||||
sudo apt-get install -y ripgrep bubblewrap socat ffmpeg poppler-utils imagemagick
|
||||
|
||||
- name: Run Workflow E2E Tests
|
||||
run: bun run test:e2e:workflow
|
||||
|
||||
@@ -48,7 +48,7 @@ jobs:
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y ripgrep bubblewrap socat ffmpeg poppler-utils libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev fd-find
|
||||
sudo apt-get install -y ripgrep bubblewrap socat ffmpeg poppler-utils imagemagick libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev fd-find
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
|
||||
@@ -50,6 +50,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
bubblewrap \
|
||||
gosu \
|
||||
poppler-utils \
|
||||
imagemagick \
|
||||
fonts-noto-cjk \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
@@ -126,23 +126,24 @@ Shumai requires the following system packages on Linux:
|
||||
|
||||
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
|
||||
- **`poppler`** (`poppler-utils`) – Used for PDF page image extraction and PDF sprite preview generation (`pdftoppm`).
|
||||
- **`imagemagick`** – Used for PSD format transcoding and color profile conversion to sRGB.
|
||||
- **`bubblewrap`**, **`socat`**, and **`ripgrep`** – Required by the AI agent sandbox (`anthropic-experimental/sandbox-runtime`) for process isolation, networking, and workspace search.
|
||||
|
||||
Install all required packages with one command:
|
||||
|
||||
> Ubuntu/Debian
|
||||
```bash
|
||||
sudo apt install -y ffmpeg poppler-utils bubblewrap socat ripgrep
|
||||
sudo apt install -y ffmpeg poppler-utils imagemagick bubblewrap socat ripgrep
|
||||
```
|
||||
|
||||
> Fedora
|
||||
```bash
|
||||
sudo dnf install -y ffmpeg poppler-utils bubblewrap socat ripgrep
|
||||
sudo dnf install -y ffmpeg poppler-utils ImageMagick bubblewrap socat ripgrep
|
||||
```
|
||||
|
||||
> Arch Linux
|
||||
```bash
|
||||
sudo pacman -S --noconfirm ffmpeg poppler bubblewrap socat ripgrep
|
||||
sudo pacman -S --noconfirm ffmpeg poppler imagemagick bubblewrap socat ripgrep
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
@@ -164,12 +165,13 @@ Shumai requires:
|
||||
|
||||
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
|
||||
- **`poppler`** – Used for PDF page image extraction and PDF sprite preview generation (`pdftoppm`).
|
||||
- **`imagemagick`** – Used for PSD format transcoding and color profile conversion to sRGB.
|
||||
- **`ripgrep`** – Required by the AI agent sandbox (`anthropic-experimental/sandbox-runtime`).
|
||||
|
||||
Install the required packages with Homebrew:
|
||||
|
||||
```bash
|
||||
brew install ffmpeg poppler ripgrep
|
||||
brew install ffmpeg poppler imagemagick ripgrep
|
||||
```
|
||||
|
||||
---
|
||||
@@ -190,17 +192,18 @@ brew install ffmpeg poppler ripgrep
|
||||
Shumai requires:
|
||||
|
||||
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
|
||||
- **`imagemagick`** – Used for PSD format transcoding and color profile conversion to sRGB.
|
||||
|
||||
Install `ffmpeg` using your preferred package manager:
|
||||
Install required packages using your preferred package manager:
|
||||
|
||||
**winget**
|
||||
```powershell
|
||||
winget install Gyan.FFmpeg
|
||||
winget install Gyan.FFmpeg ImageMagick.ImageMagick
|
||||
```
|
||||
|
||||
**Chocolatey**
|
||||
```powershell
|
||||
choco install ffmpeg
|
||||
choco install ffmpeg imagemagick
|
||||
```
|
||||
|
||||
#### Step 4: Install Shumai globally
|
||||
|
||||
+10
-7
@@ -140,23 +140,24 @@ mkdir shumai && cd shumai
|
||||
|
||||
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
|
||||
- **`poppler`** (`poppler-utils`) —— 用于 PDF 页面图像提取和 PDF 雪碧图预览生成 (`pdftoppm`)。
|
||||
- **`imagemagick`** —— 用于 PSD 格式图像转码和 sRGB 色彩空间转换。
|
||||
- **`bubblewrap`**、**`socat`** 和 **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需,用于进程隔离、网络通信和工作区搜索。
|
||||
|
||||
可以使用以下命令一次性安装所有依赖:
|
||||
|
||||
> Ubuntu/Debian
|
||||
```bash
|
||||
sudo apt install -y ffmpeg poppler-utils bubblewrap socat ripgrep
|
||||
sudo apt install -y ffmpeg poppler-utils imagemagick bubblewrap socat ripgrep
|
||||
```
|
||||
|
||||
> Fedora
|
||||
```bash
|
||||
sudo dnf install -y ffmpeg poppler-utils bubblewrap socat ripgrep
|
||||
sudo dnf install -y ffmpeg poppler-utils ImageMagick bubblewrap socat ripgrep
|
||||
```
|
||||
|
||||
> Arch Linux
|
||||
```bash
|
||||
sudo pacman -S --noconfirm ffmpeg poppler bubblewrap socat ripgrep
|
||||
sudo pacman -S --noconfirm ffmpeg poppler imagemagick bubblewrap socat ripgrep
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
@@ -178,12 +179,13 @@ sudo pacman -S --noconfirm ffmpeg poppler bubblewrap socat ripgrep
|
||||
|
||||
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
|
||||
- **`poppler`** —— 用于 PDF 页面图像提取和 PDF 雪碧图预览生成 (`pdftoppm`)。
|
||||
- **`imagemagick`** —— 用于 PSD 格式图像转码和 sRGB 色彩空间转换。
|
||||
- **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需。
|
||||
|
||||
使用 Homebrew 安装所需依赖:
|
||||
|
||||
```bash
|
||||
brew install ffmpeg poppler ripgrep
|
||||
brew install ffmpeg poppler imagemagick ripgrep
|
||||
```
|
||||
|
||||
---
|
||||
@@ -204,17 +206,18 @@ brew install ffmpeg poppler ripgrep
|
||||
在 Windows 上运行 Shumai 需要:
|
||||
|
||||
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
|
||||
- **`imagemagick`** —— 用于 PSD 格式图像转码和 sRGB 色彩空间转换。
|
||||
|
||||
使用你偏好的包管理器安装 `ffmpeg`:
|
||||
使用你偏好的包管理器安装所需依赖:
|
||||
|
||||
**winget**
|
||||
```powershell
|
||||
winget install Gyan.FFmpeg
|
||||
winget install Gyan.FFmpeg ImageMagick.ImageMagick
|
||||
```
|
||||
|
||||
**Chocolatey**
|
||||
```powershell
|
||||
choco install ffmpeg
|
||||
choco install ffmpeg imagemagick
|
||||
```
|
||||
|
||||
#### 第四步:全局安装 Shumai
|
||||
|
||||
@@ -161,59 +161,59 @@ describe('AiUsageService', () => {
|
||||
// 3 days ago (within 7d, outside 24h)
|
||||
const threeDaysAgo = new Date(now.getTime() - 3 * 24 * 60 * 60 * 1000)
|
||||
|
||||
await aiUsageService.recordUsage({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
inputTokens: 100,
|
||||
outputTokens: 50,
|
||||
cacheReadTokens: 10,
|
||||
totalTokens: 150,
|
||||
cost: 0.001,
|
||||
timestamp: recent,
|
||||
})
|
||||
await aiUsageService.recordUsage({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
inputTokens: 100,
|
||||
outputTokens: 50,
|
||||
cacheReadTokens: 10,
|
||||
totalTokens: 150,
|
||||
cost: 0.001,
|
||||
timestamp: recent,
|
||||
})
|
||||
|
||||
await aiUsageService.recordUsage({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
inputTokens: 200,
|
||||
outputTokens: 100,
|
||||
cacheReadTokens: 20,
|
||||
totalTokens: 300,
|
||||
cost: 0.002,
|
||||
timestamp: twoHoursAgo,
|
||||
})
|
||||
await aiUsageService.recordUsage({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
inputTokens: 200,
|
||||
outputTokens: 100,
|
||||
cacheReadTokens: 20,
|
||||
totalTokens: 300,
|
||||
cost: 0.002,
|
||||
timestamp: twoHoursAgo,
|
||||
})
|
||||
|
||||
await aiUsageService.recordUsage({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
inputTokens: 400,
|
||||
outputTokens: 200,
|
||||
cacheReadTokens: 40,
|
||||
totalTokens: 600,
|
||||
cost: 0.004,
|
||||
timestamp: threeDaysAgo,
|
||||
})
|
||||
await aiUsageService.recordUsage({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
inputTokens: 400,
|
||||
outputTokens: 200,
|
||||
cacheReadTokens: 40,
|
||||
totalTokens: 600,
|
||||
cost: 0.004,
|
||||
timestamp: threeDaysAgo,
|
||||
})
|
||||
|
||||
// 1h timeframe should only include recent
|
||||
const stats1h = await aiUsageService.getTeamUsageStats({
|
||||
teamId: team.id,
|
||||
timeframe: '1h',
|
||||
})
|
||||
expect(stats1h.team?.inputTokens).toBe(100)
|
||||
// 1h timeframe should only include recent
|
||||
const stats1h = await aiUsageService.getTeamUsageStats({
|
||||
teamId: team.id,
|
||||
timeframe: '1h',
|
||||
})
|
||||
expect(stats1h.team?.inputTokens).toBe(100)
|
||||
|
||||
// 24h timeframe should include recent + 2 hours ago
|
||||
const stats24h = await aiUsageService.getTeamUsageStats({
|
||||
teamId: team.id,
|
||||
timeframe: '24h',
|
||||
})
|
||||
expect(stats24h.team?.inputTokens).toBe(300)
|
||||
// 24h timeframe should include recent + 2 hours ago
|
||||
const stats24h = await aiUsageService.getTeamUsageStats({
|
||||
teamId: team.id,
|
||||
timeframe: '24h',
|
||||
})
|
||||
expect(stats24h.team?.inputTokens).toBe(300)
|
||||
|
||||
// 7d timeframe should include all 3
|
||||
const stats7d = await aiUsageService.getTeamUsageStats({
|
||||
teamId: team.id,
|
||||
timeframe: '7d',
|
||||
})
|
||||
expect(stats7d.team?.inputTokens).toBe(700)
|
||||
// 7d timeframe should include all 3
|
||||
const stats7d = await aiUsageService.getTeamUsageStats({
|
||||
teamId: team.id,
|
||||
timeframe: '7d',
|
||||
})
|
||||
expect(stats7d.team?.inputTokens).toBe(700)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { transcodeService } from './transcode'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import * as path from 'path'
|
||||
import * as child_process from 'child_process'
|
||||
import { execFile } from 'child_process'
|
||||
import * as fs from 'fs'
|
||||
import { WorkflowTask } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
@@ -24,6 +25,7 @@ vi.mock('child_process', () => ({
|
||||
vi.mock('sharp', () => {
|
||||
const mockSharp = {
|
||||
resize: vi.fn().mockReturnThis(),
|
||||
toColorspace: vi.fn().mockReturnThis(),
|
||||
webp: vi.fn().mockReturnThis(),
|
||||
composite: vi.fn().mockReturnThis(),
|
||||
toBuffer: vi.fn().mockResolvedValue(Buffer.from('fake-webp-buffer')),
|
||||
@@ -182,17 +184,62 @@ describe('TranscodeService', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('should use sharp for image transcoding', async () => {
|
||||
it('should use sharp for image transcoding with sRGB conversion', async () => {
|
||||
const outputFile = path.join(tempDir, 'output.webp')
|
||||
await transcodeService.transcodeImage('input.png', outputFile, 480, 80)
|
||||
|
||||
expect(sharp).toHaveBeenCalledWith('input.png', { limitInputPixels: false })
|
||||
const mockSharp = vi.mocked(sharp).mock.results[0].value
|
||||
expect(mockSharp.toColorspace).toHaveBeenCalledWith('srgb')
|
||||
expect(mockSharp.resize).toHaveBeenCalledWith(480, 7680, expect.any(Object))
|
||||
expect(mockSharp.webp).toHaveBeenCalledWith({ quality: 80 })
|
||||
expect(mockSharp.toFile).toHaveBeenCalledWith(outputFile)
|
||||
})
|
||||
|
||||
it('should use ImageMagick for PSD image transcoding', async () => {
|
||||
const outputFile = path.join(tempDir, 'output_psd.webp')
|
||||
const psdBuffer = Buffer.from('8BPS-fake-psd-content')
|
||||
await transcodeService.transcodeImage(psdBuffer, outputFile, 480, 80)
|
||||
|
||||
expect(execFile).toHaveBeenCalledWith(
|
||||
'magick',
|
||||
expect.arrayContaining([
|
||||
'-colorspace',
|
||||
'sRGB',
|
||||
expect.stringContaining('[0]'),
|
||||
'-quality',
|
||||
'80',
|
||||
]),
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
|
||||
it('should get PSD image info using ImageMagick identify', async () => {
|
||||
const mockExecFile = vi.mocked(execFile)
|
||||
mockExecFile.mockImplementation((cmd: unknown, args: unknown, callback: unknown) => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
extra: string,
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (cmd === 'magick' && argsArr && argsArr[0] === 'identify') {
|
||||
cb(null, { stdout: '1920 1080\n', stderr: '' }, '')
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' }, '')
|
||||
}
|
||||
return {} as ReturnType<typeof execFile>
|
||||
})
|
||||
|
||||
const psdPath = path.join(tempDir, 'sample.psd')
|
||||
fs.writeFileSync(psdPath, '8BPS-sample')
|
||||
|
||||
const info = await transcodeService.getImageInfo(psdPath)
|
||||
expect(info.originalWidth).toBe(1920)
|
||||
expect(info.originalHeight).toBe(1080)
|
||||
expect(info.mimeType).toBe('psd')
|
||||
})
|
||||
|
||||
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
|
||||
@@ -215,6 +262,7 @@ describe('TranscodeService', () => {
|
||||
|
||||
expect(sharp).toHaveBeenCalledWith(inputBuffer, { limitInputPixels: false })
|
||||
const mockSharp = vi.mocked(sharp).mock.results[vi.mocked(sharp).mock.results.length - 1].value
|
||||
expect(mockSharp.toColorspace).toHaveBeenCalledWith('srgb')
|
||||
expect(mockSharp.resize).toHaveBeenCalledWith(480, 7680, expect.any(Object))
|
||||
expect(mockSharp.webp).toHaveBeenCalledWith({ quality: 80 })
|
||||
expect(mockSharp.toFile).toHaveBeenCalledWith(outputFile)
|
||||
|
||||
@@ -120,9 +120,69 @@ export interface ExtractVideoFramesParams {
|
||||
isImage: boolean
|
||||
}
|
||||
|
||||
export function isPsdInput(input: string | Buffer): boolean {
|
||||
if (typeof input === 'string') {
|
||||
if (input.toLowerCase().endsWith('.psd')) return true
|
||||
if (fs.existsSync(input)) {
|
||||
try {
|
||||
const fd = fs.openSync(input, 'r')
|
||||
const buf = Buffer.alloc(4)
|
||||
fs.readSync(fd, buf, 0, 4, 0)
|
||||
fs.closeSync(fd)
|
||||
return buf.toString('ascii') === '8BPS'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
return (
|
||||
input.length >= 4 &&
|
||||
input[0] === 0x38 &&
|
||||
input[1] === 0x42 &&
|
||||
input[2] === 0x50 &&
|
||||
input[3] === 0x53
|
||||
)
|
||||
}
|
||||
|
||||
export class TranscodeService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
|
||||
private async execImageMagick(args: string[]): Promise<{ stdout: string; stderr: string }> {
|
||||
try {
|
||||
return await execFileAsync('magick', args)
|
||||
} catch (err: unknown) {
|
||||
const code = (err as Record<string, unknown>)?.code
|
||||
if (code === 'ENOENT') {
|
||||
return await execFileAsync('convert', args)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
private async execImageMagickIdentify(
|
||||
filePath: string,
|
||||
): Promise<{ width: number; height: number }> {
|
||||
const fileArg = `${filePath}[0]`
|
||||
let stdout: string
|
||||
try {
|
||||
const res = await execFileAsync('magick', ['identify', '-format', '%w %h', fileArg])
|
||||
stdout = res.stdout
|
||||
} catch (err: unknown) {
|
||||
const code = (err as Record<string, unknown>)?.code
|
||||
if (code === 'ENOENT') {
|
||||
const res = await execFileAsync('identify', ['-format', '%w %h', fileArg])
|
||||
stdout = res.stdout
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
const parts = stdout.trim().split(/\s+/)
|
||||
const width = parseInt(parts[0], 10) || 0
|
||||
const height = parseInt(parts[1], 10) || 0
|
||||
return { width, height }
|
||||
}
|
||||
|
||||
private resolveCodecName(stream: {
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
codec_name?: string
|
||||
@@ -222,6 +282,8 @@ export class TranscodeService {
|
||||
|
||||
async getImageInfo(inputFile: string): Promise<MediaMetadata> {
|
||||
let input: string | Buffer = inputFile
|
||||
let tempDirToCleanup: string | null = null
|
||||
|
||||
if (inputFile.startsWith('http')) {
|
||||
const resp = await fetch(inputFile)
|
||||
if (!resp.ok) {
|
||||
@@ -230,6 +292,38 @@ export class TranscodeService {
|
||||
input = Buffer.from(await resp.arrayBuffer())
|
||||
}
|
||||
|
||||
if (isPsdInput(input)) {
|
||||
let psdPath: string
|
||||
if (typeof input === 'string') {
|
||||
psdPath = input
|
||||
} else {
|
||||
tempDirToCleanup = this.createTempDir('psd-info-')
|
||||
psdPath = path.join(tempDirToCleanup, 'input.psd')
|
||||
fs.writeFileSync(psdPath, input)
|
||||
}
|
||||
|
||||
try {
|
||||
const { width, height } = await this.execImageMagickIdentify(psdPath)
|
||||
return {
|
||||
originalWidth: width,
|
||||
originalHeight: height,
|
||||
duration: 0,
|
||||
bitRate: 0,
|
||||
frameRate: 0,
|
||||
totalFrames: 0,
|
||||
startTimecode: undefined,
|
||||
hasAudio: false,
|
||||
mimeType: 'psd',
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('ImageMagick identify failed for PSD, falling back to sharp:', err)
|
||||
} finally {
|
||||
if (tempDirToCleanup) {
|
||||
this.removeDir(tempDirToCleanup)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const metadata = await sharp(input, { limitInputPixels: false }).metadata()
|
||||
return {
|
||||
originalWidth: metadata.width || 0,
|
||||
@@ -309,13 +403,48 @@ export class TranscodeService {
|
||||
input = Buffer.from(await resp.arrayBuffer())
|
||||
}
|
||||
|
||||
const sharpInstance = sharp(input, { limitInputPixels: false })
|
||||
|
||||
const WEBP_MAX_DIMENSION = 7680
|
||||
const targetW = width > 0 ? Math.min(width, WEBP_MAX_DIMENSION) : WEBP_MAX_DIMENSION
|
||||
const targetH = height && height > 0 ? Math.min(height, WEBP_MAX_DIMENSION) : WEBP_MAX_DIMENSION
|
||||
|
||||
sharpInstance.resize(targetW, targetH, {
|
||||
if (isPsdInput(input)) {
|
||||
let psdPath: string
|
||||
let tempDirToCleanup: string | null = null
|
||||
if (typeof input === 'string') {
|
||||
psdPath = input
|
||||
} else {
|
||||
tempDirToCleanup = this.createTempDir('psd-transcode-')
|
||||
psdPath = path.join(tempDirToCleanup, 'input.psd')
|
||||
fs.writeFileSync(psdPath, input)
|
||||
}
|
||||
|
||||
try {
|
||||
const resizeGeometry =
|
||||
targetH < WEBP_MAX_DIMENSION
|
||||
? `${targetW}x${targetH}>`
|
||||
: `${targetW}x${WEBP_MAX_DIMENSION}>`
|
||||
|
||||
await this.execImageMagick([
|
||||
`${psdPath}[0]`,
|
||||
'-colorspace',
|
||||
'sRGB',
|
||||
'-resize',
|
||||
resizeGeometry,
|
||||
'-quality',
|
||||
quality.toString(),
|
||||
outputFile,
|
||||
])
|
||||
return
|
||||
} finally {
|
||||
if (tempDirToCleanup) {
|
||||
this.removeDir(tempDirToCleanup)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const sharpInstance = sharp(input, { limitInputPixels: false })
|
||||
|
||||
sharpInstance.toColorspace('srgb').resize(targetW, targetH, {
|
||||
withoutEnlargement: true,
|
||||
fit: 'inside',
|
||||
})
|
||||
@@ -430,6 +559,7 @@ export class TranscodeService {
|
||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...spriteArgs])
|
||||
|
||||
await sharp(firstPagePath, { limitInputPixels: false })
|
||||
.toColorspace('srgb')
|
||||
.resize(480, null, { withoutEnlargement: true, fit: 'inside' })
|
||||
.webp({ quality: 75 })
|
||||
.toFile(outputPoster)
|
||||
@@ -926,6 +1056,7 @@ export class TranscodeService {
|
||||
const webpName = `${stem}-page-${pageNum}-${ulid()}.webp`
|
||||
|
||||
let webpBuffer = await sharp(localPngPath, { limitInputPixels: false })
|
||||
.toColorspace('srgb')
|
||||
.resize(1920, 1080, { fit: 'inside', withoutEnlargement: false })
|
||||
.webp({ quality: 85 })
|
||||
.toBuffer()
|
||||
@@ -973,6 +1104,7 @@ export class TranscodeService {
|
||||
const svgStr = renderAnnotationsToSvg(width, height, annotations)
|
||||
return await sharp(imageBuffer, { limitInputPixels: false })
|
||||
.composite([{ input: Buffer.from(svgStr), top: 0, left: 0 }])
|
||||
.toColorspace('srgb')
|
||||
.resize(16383, 16383, { fit: 'inside', withoutEnlargement: true })
|
||||
.webp({ quality: 85 })
|
||||
.toBuffer()
|
||||
|
||||
@@ -27,6 +27,11 @@ describe('detectSupportedMimeType', () => {
|
||||
expect(detectSupportedMimeType(buffer)).toBe('image/webp')
|
||||
})
|
||||
|
||||
it('should detect PSD', () => {
|
||||
const buffer = new Uint8Array([0x38, 0x42, 0x50, 0x53, 0x00, 0x01])
|
||||
expect(detectSupportedMimeType(buffer)).toBe('image/vnd.adobe.photoshop')
|
||||
})
|
||||
|
||||
it('should detect MP4', () => {
|
||||
const buffer = new Uint8Array([
|
||||
0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d,
|
||||
@@ -44,6 +49,8 @@ describe('getProxyType', () => {
|
||||
it('should detect image proxyType', () => {
|
||||
expect(getProxyType('image/png', 'test.png')).toBe('image')
|
||||
expect(getProxyType('image/jpeg', 'photo.jpg')).toBe('image')
|
||||
expect(getProxyType('image/vnd.adobe.photoshop', 'design.psd')).toBe('image')
|
||||
expect(getProxyType(null, 'design.psd')).toBe('image')
|
||||
})
|
||||
|
||||
it('should detect video proxyType', () => {
|
||||
|
||||
@@ -7,7 +7,7 @@ export function getProxyType(
|
||||
const lowerMediaType = mediaType?.toLowerCase() || ''
|
||||
const lowerFilename = filename?.toLowerCase() || ''
|
||||
|
||||
if (lowerMediaType.startsWith('image/')) return 'image'
|
||||
if (lowerMediaType.startsWith('image/') || lowerFilename.endsWith('.psd')) return 'image'
|
||||
if (lowerMediaType.startsWith('video/')) return 'video'
|
||||
if (lowerMediaType.startsWith('audio/')) return 'audio'
|
||||
|
||||
@@ -32,6 +32,9 @@ export function getProxyType(
|
||||
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
||||
|
||||
export function detectSupportedMimeType(buffer: Uint8Array): string | null {
|
||||
if (startsWithAscii(buffer, 0, '8BPS')) {
|
||||
return 'image/vnd.adobe.photoshop'
|
||||
}
|
||||
if (startsWith(buffer, [0xff, 0xd8, 0xff])) {
|
||||
return buffer[3] === 0xf7 ? null : 'image/jpeg'
|
||||
}
|
||||
|
||||
Binary file not shown.
@@ -224,6 +224,87 @@ describe.each(['local', 'temporal'] as const)(
|
||||
expect(mediaInfo.thumbnail).toBeDefined()
|
||||
}, 50000)
|
||||
|
||||
it('should run transcodeMedia workflow for a PSD image asset successfully', async () => {
|
||||
// 1. Seed Database
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'E2E PSD Transcode Team' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'E2E PSD Transcode Project', teamId: team.id },
|
||||
})
|
||||
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: {
|
||||
key: 'projects/e2e/test.psd',
|
||||
},
|
||||
})
|
||||
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.psd',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
mediaType: 'image/vnd.adobe.photoshop',
|
||||
projectId: project.id,
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
|
||||
// 2. Seed S3 Storage from fixture test.psd
|
||||
const psdPath = path.join(fixturesDir, 'test.psd')
|
||||
const psdBuffer = fs.readFileSync(psdPath)
|
||||
await s3Service.putObject(
|
||||
'shumai-e2e-test-bucket-transcode',
|
||||
'projects/e2e/test.psd',
|
||||
psdBuffer,
|
||||
psdBuffer.length,
|
||||
'image/vnd.adobe.photoshop',
|
||||
)
|
||||
|
||||
// 3. Create Workflow Task
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'transcode_image',
|
||||
status: 'pending',
|
||||
assetId: asset.id,
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
transcode: {
|
||||
thumbnail: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// 4. Wait for workflow to complete
|
||||
console.log(
|
||||
`Submitted E2E PSD Image Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||
)
|
||||
const completedTask = await workflowService.executeWait(task, 45000)
|
||||
|
||||
// 5. Verification
|
||||
expect(completedTask.status).toBe('completed')
|
||||
|
||||
const updatedAsset = await prisma.asset.findUnique({
|
||||
where: { id: asset.id },
|
||||
})
|
||||
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
||||
|
||||
const mediaInfo = updatedAsset?.media as unknown as {
|
||||
proxyType: string
|
||||
imageTranscodes: unknown[]
|
||||
thumbnail: unknown
|
||||
}
|
||||
expect(mediaInfo).toBeDefined()
|
||||
expect(mediaInfo.proxyType).toBe('image')
|
||||
expect(mediaInfo.imageTranscodes).toBeDefined()
|
||||
expect(mediaInfo.imageTranscodes.length).toBeGreaterThan(0)
|
||||
expect(mediaInfo.thumbnail).toBeDefined()
|
||||
}, 50000)
|
||||
|
||||
it('should run transcodeMedia workflow for an audio asset successfully', async () => {
|
||||
// 1. Seed Database
|
||||
const team = await prisma.team.create({
|
||||
|
||||
@@ -469,6 +469,21 @@ describe('Transcode Activities', () => {
|
||||
).rejects.toThrowError(/Image transcoding failed/)
|
||||
})
|
||||
|
||||
it('should throw non-retryable ApplicationFailure when transcodeImageActivity fails with ImageMagick error', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
vi.mocked(transcodeService.transcodeImage).mockRejectedValue(
|
||||
new Error('imagemagick convert failed'),
|
||||
)
|
||||
|
||||
await expect(
|
||||
transcodeImageActivity({
|
||||
assetKey: 'i.psd',
|
||||
filePath: '/tmp/i.psd',
|
||||
imageSpec: { width: 800, height: 600, quality: 90, format: 'webp' },
|
||||
}),
|
||||
).rejects.toThrowError(/Image transcoding failed/)
|
||||
})
|
||||
|
||||
it('should throw non-retryable ApplicationFailure when generateSpriteActivity fails with error', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
vi.mocked(transcodeService.generateSprite).mockRejectedValue(new Error('FFmpeg failed'))
|
||||
|
||||
@@ -389,6 +389,9 @@ export async function transcodeImageActivity(
|
||||
code === 'ENOENT' ||
|
||||
lowerMsg.includes('enoent') ||
|
||||
lowerMsg.includes('sharp') ||
|
||||
lowerMsg.includes('imagemagick') ||
|
||||
lowerMsg.includes('magick') ||
|
||||
lowerMsg.includes('convert') ||
|
||||
lowerMsg.includes('spawn') ||
|
||||
lowerMsg.includes('format')
|
||||
) {
|
||||
|
||||
Reference in New Issue
Block a user