mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 03:38:21 +00:00
feat(transcode): update preview thumbnail resolution to 300p with max length constraint (#281)
* feat(transcode): update preview thumbnail resolution to 300p with max length constraint * fix(transcode): address code review feedback on preview thumbnail transcoding
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { transcodeService } from './transcode'
|
||||
import { transcodeService, calculatePreviewDimensions } from './transcode'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import * as path from 'path'
|
||||
import * as child_process from 'child_process'
|
||||
@@ -185,18 +185,100 @@ describe('TranscodeService', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('should use sharp for image transcoding with sRGB conversion', async () => {
|
||||
it('should use sharp for image transcoding with sRGB conversion (production 300p spec)', async () => {
|
||||
const outputFile = path.join(tempDir, 'output.webp')
|
||||
await transcodeService.transcodeImage('input.png', outputFile, 480, 80)
|
||||
await transcodeService.transcodeImage('input.png', outputFile, 300, 80, { isPreview: true })
|
||||
|
||||
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.resize).toHaveBeenCalledWith(400, 300, expect.any(Object))
|
||||
expect(mockSharp.webp).toHaveBeenCalledWith({ quality: 80 })
|
||||
expect(mockSharp.toFile).toHaveBeenCalledWith(outputFile)
|
||||
})
|
||||
|
||||
it('should support legacy 480 width fallback shim', async () => {
|
||||
const outputFile = path.join(tempDir, 'output_legacy.webp')
|
||||
await transcodeService.transcodeImage('input.png', outputFile, 480, 80)
|
||||
|
||||
const mockSharp = vi.mocked(sharp).mock.results[vi.mocked(sharp).mock.results.length - 1].value
|
||||
expect(mockSharp.resize).toHaveBeenCalledWith(400, 300, expect.any(Object))
|
||||
})
|
||||
|
||||
it('should handle preview and full-res proxy dimension calculations correctly', async () => {
|
||||
const outputFile = path.join(tempDir, 'out.webp')
|
||||
|
||||
// 16:9 source (1920x1080) in preview mode -> 533x300
|
||||
const mockSharp169 = {
|
||||
resize: vi.fn().mockReturnThis(),
|
||||
toColorspace: vi.fn().mockReturnThis(),
|
||||
webp: vi.fn().mockReturnThis(),
|
||||
toFile: vi.fn().mockResolvedValue({}),
|
||||
metadata: vi.fn().mockResolvedValue({ width: 1920, height: 1080 }),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(sharp).mockReturnValueOnce(mockSharp169 as any)
|
||||
await transcodeService.transcodeImage('169.png', outputFile, 300, 80, { isPreview: true })
|
||||
expect(mockSharp169.resize).toHaveBeenCalledWith(533, 300, expect.any(Object))
|
||||
|
||||
// Small image (200x150) in preview mode -> 200x150
|
||||
const mockSharpSmall = {
|
||||
resize: vi.fn().mockReturnThis(),
|
||||
toColorspace: vi.fn().mockReturnThis(),
|
||||
webp: vi.fn().mockReturnThis(),
|
||||
toFile: vi.fn().mockResolvedValue({}),
|
||||
metadata: vi.fn().mockResolvedValue({ width: 200, height: 150 }),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(sharp).mockReturnValueOnce(mockSharpSmall as any)
|
||||
await transcodeService.transcodeImage('small.png', outputFile, 300, 80, { isPreview: true })
|
||||
expect(mockSharpSmall.resize).toHaveBeenCalledWith(200, 150, expect.any(Object))
|
||||
|
||||
// 1:10 Tall screenshot (1000x10000) in preview mode -> 53x533
|
||||
const mockSharpTall = {
|
||||
resize: vi.fn().mockReturnThis(),
|
||||
toColorspace: vi.fn().mockReturnThis(),
|
||||
webp: vi.fn().mockReturnThis(),
|
||||
toFile: vi.fn().mockResolvedValue({}),
|
||||
metadata: vi.fn().mockResolvedValue({ width: 1000, height: 10000 }),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(sharp).mockReturnValueOnce(mockSharpTall as any)
|
||||
await transcodeService.transcodeImage('tall.png', outputFile, 300, 80, { isPreview: true })
|
||||
expect(mockSharpTall.resize).toHaveBeenCalledWith(53, 533, expect.any(Object))
|
||||
|
||||
// Square full-resolution proxy (10000x10000, isPreview: false) -> capped at WEBP_MAX_DIMENSION (7680)
|
||||
const mockSharpSquareProxy = {
|
||||
resize: vi.fn().mockReturnThis(),
|
||||
toColorspace: vi.fn().mockReturnThis(),
|
||||
webp: vi.fn().mockReturnThis(),
|
||||
toFile: vi.fn().mockResolvedValue({}),
|
||||
metadata: vi.fn().mockResolvedValue({ width: 10000, height: 10000 }),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(sharp).mockReturnValueOnce(mockSharpSquareProxy as any)
|
||||
await transcodeService.transcodeImage('square.png', outputFile, 10000, 90, {
|
||||
height: 10000,
|
||||
isPreview: false,
|
||||
})
|
||||
expect(mockSharpSquareProxy.resize).toHaveBeenCalledWith(7680, 7680, expect.any(Object))
|
||||
})
|
||||
|
||||
it('should calculate preview dimensions correctly for 300p (short side 300, max long side 533)', () => {
|
||||
// 16:9 Landscape
|
||||
expect(calculatePreviewDimensions(1920, 1080)).toEqual({ width: 533, height: 300 })
|
||||
// 9:16 Portrait
|
||||
expect(calculatePreviewDimensions(1080, 1920)).toEqual({ width: 300, height: 533 })
|
||||
// 1:1 Square
|
||||
expect(calculatePreviewDimensions(1000, 1000)).toEqual({ width: 300, height: 300 })
|
||||
// 21:9 Ultrawide
|
||||
expect(calculatePreviewDimensions(2560, 1080)).toEqual({ width: 533, height: 225 })
|
||||
// 1:10 Tall screenshot (capped at max long side = 533)
|
||||
expect(calculatePreviewDimensions(1000, 10000)).toEqual({ width: 53, height: 533 })
|
||||
// Small image (no enlargement)
|
||||
expect(calculatePreviewDimensions(200, 150)).toEqual({ width: 200, height: 150 })
|
||||
})
|
||||
|
||||
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')
|
||||
@@ -264,7 +346,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.resize).toHaveBeenCalledWith(400, 300, expect.any(Object))
|
||||
expect(mockSharp.webp).toHaveBeenCalledWith({ quality: 80 })
|
||||
expect(mockSharp.toFile).toHaveBeenCalledWith(outputFile)
|
||||
})
|
||||
@@ -451,7 +533,7 @@ describe('TranscodeService', () => {
|
||||
)
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining(['-filter_complex', 'scale=w=480:h=-2,tile=10x10']),
|
||||
expect.arrayContaining(['-filter_complex', 'scale=w=300:h=-2,tile=10x10']),
|
||||
expect.any(Function),
|
||||
)
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
|
||||
@@ -145,6 +145,40 @@ export function isPsdInput(input: string | Buffer): boolean {
|
||||
input[3] === 0x53
|
||||
)
|
||||
}
|
||||
export function calculatePreviewDimensions(
|
||||
origW: number,
|
||||
origH: number,
|
||||
targetShort = 300,
|
||||
maxLong = 533,
|
||||
): { width: number; height: number } {
|
||||
if (origW <= 0 || origH <= 0) {
|
||||
return { width: targetShort, height: targetShort }
|
||||
}
|
||||
|
||||
const origShort = Math.min(origW, origH)
|
||||
const origLong = Math.max(origW, origH)
|
||||
|
||||
if (origShort <= targetShort && origLong <= maxLong) {
|
||||
return { width: origW, height: origH }
|
||||
}
|
||||
|
||||
let scale = targetShort / origShort
|
||||
const scaledLong = Math.round(origLong * scale)
|
||||
|
||||
if (scaledLong > maxLong) {
|
||||
scale = maxLong / origLong
|
||||
}
|
||||
|
||||
const newW = Math.max(1, Math.round(origW * scale))
|
||||
const newH = Math.max(1, Math.round(origH * scale))
|
||||
|
||||
return { width: newW, height: newH }
|
||||
}
|
||||
|
||||
export interface TranscodeImageOptions {
|
||||
height?: number | null
|
||||
isPreview?: boolean
|
||||
}
|
||||
|
||||
export class TranscodeService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
@@ -402,8 +436,22 @@ export class TranscodeService {
|
||||
outputFile: string,
|
||||
width: number,
|
||||
quality: number,
|
||||
height: number | null = null,
|
||||
heightOrOptions: number | null | TranscodeImageOptions = null,
|
||||
): Promise<void> {
|
||||
const height =
|
||||
typeof heightOrOptions === 'object' && heightOrOptions !== null
|
||||
? (heightOrOptions.height ?? null)
|
||||
: heightOrOptions
|
||||
let isPreview =
|
||||
typeof heightOrOptions === 'object' && heightOrOptions !== null
|
||||
? (heightOrOptions.isPreview ?? false)
|
||||
: false
|
||||
|
||||
// Backward compatibility shim for legacy queued tasks or old call signatures passing width 480 or height 0
|
||||
if (width === 480 || height === 0) {
|
||||
isPreview = true
|
||||
}
|
||||
|
||||
let input: string | Buffer = inputFile
|
||||
if (typeof inputFile === 'string' && inputFile.startsWith('http')) {
|
||||
const resp = await fetch(inputFile)
|
||||
@@ -414,8 +462,30 @@ export class TranscodeService {
|
||||
}
|
||||
|
||||
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
|
||||
let targetW = width > 0 ? Math.min(width, WEBP_MAX_DIMENSION) : WEBP_MAX_DIMENSION
|
||||
let targetH = height && height > 0 ? Math.min(height, WEBP_MAX_DIMENSION) : WEBP_MAX_DIMENSION
|
||||
|
||||
const sharpInstance = sharp(input, { limitInputPixels: false })
|
||||
|
||||
if (isPreview) {
|
||||
try {
|
||||
const meta = await sharpInstance.metadata()
|
||||
if (meta.width && meta.height) {
|
||||
// Fallback shim: If legacy 480 caller passed width=480, map targetShort to 300
|
||||
const targetShort = width === 480 ? 300 : width
|
||||
const maxLong = Math.round((targetShort * 16) / 9)
|
||||
const dims = calculatePreviewDimensions(meta.width, meta.height, targetShort, maxLong)
|
||||
targetW = dims.width
|
||||
targetH = dims.height
|
||||
}
|
||||
} catch {
|
||||
// Fallback to targetW/targetH as calculated above
|
||||
}
|
||||
}
|
||||
|
||||
// WEBP_MAX_DIMENSION (7680) safety cap is ALWAYS enforced
|
||||
targetW = Math.min(targetW, WEBP_MAX_DIMENSION)
|
||||
targetH = Math.min(targetH, WEBP_MAX_DIMENSION)
|
||||
|
||||
if (isPsdInput(input)) {
|
||||
let psdPath: string
|
||||
@@ -452,8 +522,6 @@ export class TranscodeService {
|
||||
}
|
||||
}
|
||||
|
||||
const sharpInstance = sharp(input, { limitInputPixels: false })
|
||||
|
||||
sharpInstance.toColorspace('srgb').resize(targetW, targetH, {
|
||||
withoutEnlargement: true,
|
||||
fit: 'inside',
|
||||
@@ -469,7 +537,7 @@ export class TranscodeService {
|
||||
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:480:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
|
||||
const filterComplex = `[0:v]fps=${spriteFps},scale=w=300:h=-2,tile=10x10[sprite_out];[0:v]scale=-2:300:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
|
||||
|
||||
const args = [
|
||||
'-i',
|
||||
@@ -557,7 +625,7 @@ export class TranscodeService {
|
||||
'-i',
|
||||
path.join(tmpDir, 'frame_%d.png'),
|
||||
'-filter_complex',
|
||||
'scale=w=480:h=-2,tile=10x10',
|
||||
'scale=w=300:h=-2,tile=10x10',
|
||||
'-frames:v',
|
||||
'1',
|
||||
'-c:v',
|
||||
@@ -570,7 +638,7 @@ export class TranscodeService {
|
||||
|
||||
await sharp(firstPagePath, { limitInputPixels: false })
|
||||
.toColorspace('srgb')
|
||||
.resize(480, null, { withoutEnlargement: true, fit: 'inside' })
|
||||
.resize(300, 533, { withoutEnlargement: true, fit: 'inside' })
|
||||
.webp({ quality: 75 })
|
||||
.toFile(outputPoster)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user