mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 03:14:11 +00:00
feat(transcode): add PSD support via ImageMagick and enforce sRGB conversion
This commit is contained in:
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user