feat(transcode): add initial camera RAW image support (#435)

- Add centralized RAW file extension set and detection helper for 23 common camera RAW formats
- Update getProxyType and EXTENSION_MIME_TYPES to route RAW formats into the image pipeline
- Add exiftool-vendored runtime dependency and mark as external in build-npm script
- Implement embedded JPEG extraction to temporary file with priority JpgFromRaw2 -> JpgFromRaw -> PreviewImage
- Read and apply EXIF orientation from RAW container to prevent rotation/mirroring issues
- Integrate into TranscodeService.getImageInfo and transcodeImage with proper temporary file cleanup
- Add hasUsablePreview guard in transcodeImageWorkflow to gracefully handle RAW files without embedded previews
- Add unit, service, workflow, and E2E tests for RAW processing
This commit is contained in:
Yiling-J
2026-09-29 21:09:27 +08:00
committed by GitHub
parent 11d21444cf
commit 5fe22ac52c
17 changed files with 999 additions and 62 deletions
@@ -0,0 +1,283 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import * as fs from 'fs'
import {
extractEmbeddedJpeg,
validateExtractedJpeg,
extractAndValidateRawPreview,
EXIF_ORIENTATION_TO_ROTATION,
} from './raw-extract'
// Mock exiftool-vendored
vi.mock('exiftool-vendored', () => ({
exiftool: {
extractBinaryTag: vi.fn(),
read: vi.fn(),
},
}))
// Mock sharp
vi.mock('sharp', () => {
const mockMetadata = vi.fn()
const mockSharp = vi.fn(() => ({
metadata: mockMetadata,
}))
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(mockSharp as any)._mockMetadata = mockMetadata
return { default: mockSharp }
})
import { exiftool } from 'exiftool-vendored'
import sharp from 'sharp'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mockMetadata = (sharp as any)._mockMetadata as ReturnType<typeof vi.fn>
const mockExtractBinaryTag = vi.mocked(exiftool.extractBinaryTag)
const mockRead = vi.mocked(exiftool.read)
describe('extractEmbeddedJpeg', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('extracts from JpgFromRaw2 first to a temporary file', async () => {
mockExtractBinaryTag.mockImplementationOnce(async (_tag, _src, dest) => {
fs.writeFileSync(dest, 'jpeg-data')
})
mockRead.mockResolvedValueOnce({ Orientation: 1 } as never)
const result = await extractEmbeddedJpeg('/path/to/photo.cr2')
expect(result).not.toBeNull()
expect(fs.existsSync(result!.previewPath)).toBe(true)
expect(result!.orientation).toBe(1)
expect(mockExtractBinaryTag).toHaveBeenCalledWith(
'JpgFromRaw2',
'/path/to/photo.cr2',
expect.stringContaining('preview-JpgFromRaw2'),
)
// Test cleanup
result!.cleanup()
expect(fs.existsSync(result!.previewPath)).toBe(false)
})
it('falls back to JpgFromRaw when JpgFromRaw2 fails', async () => {
mockExtractBinaryTag
.mockRejectedValueOnce(new Error('0 output files created'))
.mockImplementationOnce(async (_tag, _src, dest) => {
fs.writeFileSync(dest, 'jpeg-data')
})
mockRead.mockResolvedValueOnce({ Orientation: 6 } as never)
const result = await extractEmbeddedJpeg('/path/to/photo.nef')
expect(result).not.toBeNull()
expect(fs.existsSync(result!.previewPath)).toBe(true)
expect(result!.orientation).toBe(6)
expect(mockExtractBinaryTag).toHaveBeenCalledTimes(2)
expect(mockExtractBinaryTag).toHaveBeenNthCalledWith(
2,
'JpgFromRaw',
'/path/to/photo.nef',
expect.stringContaining('preview-JpgFromRaw'),
)
result!.cleanup()
expect(fs.existsSync(result!.previewPath)).toBe(false)
})
it('falls back to PreviewImage when JpgFromRaw2 and JpgFromRaw fail', async () => {
mockExtractBinaryTag
.mockRejectedValueOnce(new Error('0 output files created'))
.mockRejectedValueOnce(new Error('0 output files created'))
.mockImplementationOnce(async (_tag, _src, dest) => {
fs.writeFileSync(dest, 'preview-data')
})
mockRead.mockResolvedValueOnce({ Orientation: 3 } as never)
const result = await extractEmbeddedJpeg('/path/to/photo.arw')
expect(result).not.toBeNull()
expect(fs.existsSync(result!.previewPath)).toBe(true)
expect(result!.orientation).toBe(3)
expect(mockExtractBinaryTag).toHaveBeenCalledTimes(3)
expect(mockExtractBinaryTag).toHaveBeenNthCalledWith(
3,
'PreviewImage',
'/path/to/photo.arw',
expect.stringContaining('preview-PreviewImage'),
)
result!.cleanup()
expect(fs.existsSync(result!.previewPath)).toBe(false)
})
it('returns null and cleans up when all tags fail', async () => {
mockExtractBinaryTag
.mockRejectedValueOnce(new Error('0 output files created'))
.mockRejectedValueOnce(new Error('0 output files created'))
.mockRejectedValueOnce(new Error('0 output files created'))
const result = await extractEmbeddedJpeg('/path/to/photo.cr2')
expect(result).toBeNull()
expect(mockExtractBinaryTag).toHaveBeenCalledTimes(3)
})
it('returns undefined orientation when EXIF read fails', async () => {
mockExtractBinaryTag.mockImplementationOnce(async (_tag, _src, dest) => {
fs.writeFileSync(dest, 'jpeg-data')
})
mockRead.mockRejectedValueOnce(new Error('EXIF read failed'))
const result = await extractEmbeddedJpeg('/path/to/photo.cr2')
expect(result).not.toBeNull()
expect(result!.orientation).toBeUndefined()
result!.cleanup()
})
it('returns undefined orientation when orientation value is out of range', async () => {
mockExtractBinaryTag.mockImplementationOnce(async (_tag, _src, dest) => {
fs.writeFileSync(dest, 'jpeg-data')
})
mockRead.mockResolvedValueOnce({ Orientation: 9 } as never)
const result = await extractEmbeddedJpeg('/path/to/photo.cr2')
expect(result).not.toBeNull()
expect(result!.orientation).toBeUndefined()
result!.cleanup()
})
it('returns undefined orientation when orientation is not a number', async () => {
mockExtractBinaryTag.mockImplementationOnce(async (_tag, _src, dest) => {
fs.writeFileSync(dest, 'jpeg-data')
})
mockRead.mockResolvedValueOnce({ Orientation: 'Horizontal' } as never)
const result = await extractEmbeddedJpeg('/path/to/photo.cr2')
expect(result).not.toBeNull()
expect(result!.orientation).toBeUndefined()
result!.cleanup()
})
})
describe('validateExtractedJpeg', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns dimensions for a valid JPEG file', async () => {
mockMetadata.mockResolvedValueOnce({ width: 6000, height: 4000 })
const result = await validateExtractedJpeg('/tmp/valid-jpeg.jpg')
expect(result).toEqual({ width: 6000, height: 4000 })
})
it('returns null when metadata has zero width', async () => {
mockMetadata.mockResolvedValueOnce({ width: 0, height: 4000 })
const result = await validateExtractedJpeg('/tmp/bad-jpeg.jpg')
expect(result).toBeNull()
})
it('returns null when metadata has no dimensions', async () => {
mockMetadata.mockResolvedValueOnce({})
const result = await validateExtractedJpeg('/tmp/bad-jpeg.jpg')
expect(result).toBeNull()
})
it('returns null when sharp throws', async () => {
mockMetadata.mockRejectedValueOnce(new Error('Invalid image'))
const result = await validateExtractedJpeg('/tmp/corrupt-jpeg.jpg')
expect(result).toBeNull()
})
})
describe('extractAndValidateRawPreview', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns previewPath, dimensions, orientation, and cleanup for valid RAW', async () => {
mockExtractBinaryTag.mockImplementationOnce(async (_tag, _src, dest) => {
fs.writeFileSync(dest, 'jpeg-data')
})
mockRead.mockResolvedValueOnce({ Orientation: 6 } as never)
mockMetadata.mockResolvedValueOnce({ width: 4000, height: 3000 })
const result = await extractAndValidateRawPreview('/path/to/photo.cr2')
expect(result).not.toBeNull()
expect(fs.existsSync(result!.previewPath)).toBe(true)
expect(result!.width).toBe(4000)
expect(result!.height).toBe(3000)
expect(result!.orientation).toBe(6)
result!.cleanup()
expect(fs.existsSync(result!.previewPath)).toBe(false)
})
it('returns null when extraction fails', async () => {
mockExtractBinaryTag
.mockRejectedValueOnce(new Error('fail'))
.mockRejectedValueOnce(new Error('fail'))
.mockRejectedValueOnce(new Error('fail'))
const result = await extractAndValidateRawPreview('/path/to/photo.cr2')
expect(result).toBeNull()
})
it('returns null and cleans up when validation fails', async () => {
let createdPath = ''
mockExtractBinaryTag.mockImplementationOnce(async (_tag, _src, dest) => {
createdPath = dest
fs.writeFileSync(dest, 'bad-jpeg')
})
mockRead.mockResolvedValueOnce({ Orientation: 1 } as never)
mockMetadata.mockRejectedValueOnce(new Error('Not a valid image'))
const result = await extractAndValidateRawPreview('/path/to/photo.cr2')
expect(result).toBeNull()
expect(fs.existsSync(createdPath)).toBe(false)
})
})
describe('EXIF_ORIENTATION_TO_ROTATION', () => {
it('maps all 8 EXIF orientations', () => {
expect(Object.keys(EXIF_ORIENTATION_TO_ROTATION)).toHaveLength(8)
for (let i = 1; i <= 8; i++) {
expect(EXIF_ORIENTATION_TO_ROTATION[i]).toBeDefined()
}
})
it('has correct rotation for landscape (1)', () => {
expect(EXIF_ORIENTATION_TO_ROTATION[1]).toEqual({})
})
it('has correct rotation for 90° CW (6)', () => {
expect(EXIF_ORIENTATION_TO_ROTATION[6]).toEqual({ angle: 90 })
})
it('has correct rotation for 180° (3)', () => {
expect(EXIF_ORIENTATION_TO_ROTATION[3]).toEqual({ angle: 180 })
})
it('has correct rotation for 270° CW (8)', () => {
expect(EXIF_ORIENTATION_TO_ROTATION[8]).toEqual({ angle: 270 })
})
it('has correct rotation for mirror horizontal (2)', () => {
expect(EXIF_ORIENTATION_TO_ROTATION[2]).toEqual({ flop: true })
})
})
+153
View File
@@ -0,0 +1,153 @@
import { exiftool } from 'exiftool-vendored'
import sharp from 'sharp'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import { logger } from '@shumai/core/src/logger'
export interface RawExtractResult {
previewPath: string
cleanup: () => void
/** EXIF orientation from the RAW container (1–8), or undefined if absent. */
orientation?: number
}
/**
* Maps EXIF orientation values (1–8) to Sharp rotation operations.
* Follows the same mapping as Immich's ORIENTATION_TO_SHARP_ROTATION.
*/
export const EXIF_ORIENTATION_TO_ROTATION: Record<
number,
{ angle?: number; flip?: boolean; flop?: boolean }
> = {
1: {}, // Horizontal (normal)
2: { flop: true }, // Mirror horizontal
3: { angle: 180 }, // Rotate 180°
4: { angle: 180, flop: true }, // Mirror vertical
5: { angle: 270, flip: true }, // Mirror horizontal + rotate 270° CW
6: { angle: 90 }, // Rotate 90° CW
7: { angle: 90, flip: true }, // Mirror horizontal + rotate 90° CW
8: { angle: 270 }, // Rotate 270° CW
}
/**
* Attempt to extract an embedded JPEG preview from a camera RAW file to a temporary file.
*
* Tries tags in priority order (matching Immich, skipping PreviewJXL):
* 1. JpgFromRaw2 — secondary full-resolution JPEG (newer Sony/Canon/Nikon)
* 2. JpgFromRaw — primary full-size embedded JPEG
* 3. PreviewImage — smaller embedded preview fallback
*
* Also reads the EXIF orientation from the RAW container so callers can
* apply it to the extracted buffer/file (which often lacks its own orientation tag).
*
* Returns null if no usable embedded JPEG exists.
*/
export async function extractEmbeddedJpeg(
rawFilePath: string,
targetDir?: string,
): Promise<RawExtractResult | null> {
const tags = ['JpgFromRaw2', 'JpgFromRaw', 'PreviewImage'] as const
const ownTempDir = !targetDir
const workDir = targetDir ?? fs.mkdtempSync(path.join(os.tmpdir(), 'raw-extract-'))
const cleanup = () => {
try {
if (ownTempDir && fs.existsSync(workDir)) {
fs.rmSync(workDir, { recursive: true, force: true })
}
} catch (err) {
logger.warn({ workDir, err }, 'Failed to clean up raw extraction temporary directory')
}
}
for (const tag of tags) {
const candidatePath = path.join(workDir, `preview-${tag}-${Date.now()}.jpg`)
try {
await exiftool.extractBinaryTag(tag, rawFilePath, candidatePath)
if (fs.existsSync(candidatePath) && fs.statSync(candidatePath).size > 0) {
logger.debug({ tag, rawFilePath, candidatePath }, 'Extracted embedded JPEG from RAW')
// Read orientation from the RAW container's EXIF metadata.
// The extracted JPEG binary stream often does NOT carry its own
// orientation tag, so we must read it from the parent RAW file
// to avoid incorrectly-rotated previews.
let orientation: number | undefined
try {
const exif = await exiftool.read(rawFilePath)
const rawOrientation = exif.Orientation
if (typeof rawOrientation === 'number' && rawOrientation >= 1 && rawOrientation <= 8) {
orientation = rawOrientation
}
} catch {
logger.debug({ rawFilePath }, 'Could not read EXIF orientation from RAW container')
}
return { previewPath: candidatePath, cleanup, orientation }
}
} catch {
logger.debug({ tag, rawFilePath }, `Could not extract ${tag} from RAW file`)
try {
if (fs.existsSync(candidatePath)) {
fs.rmSync(candidatePath, { force: true })
}
} catch {
// ignore
}
}
}
cleanup()
logger.info({ rawFilePath }, 'No usable embedded JPEG found in RAW file')
return null
}
/**
* Validate that an extracted JPEG file is decodable.
* Returns dimensions if valid, null if corrupt/unusable.
*/
export async function validateExtractedJpeg(
filePath: string,
): Promise<{ width: number; height: number } | null> {
try {
const metadata = await sharp(filePath).metadata()
if (metadata.width && metadata.height && metadata.width > 0 && metadata.height > 0) {
return { width: metadata.width, height: metadata.height }
}
return null
} catch {
return null
}
}
/**
* Extract and validate an embedded JPEG from a RAW file to a temporary file.
* Returns a validated file path + dimensions + orientation + cleanup function, or null.
*/
export async function extractAndValidateRawPreview(
rawFilePath: string,
targetDir?: string,
): Promise<{
previewPath: string
cleanup: () => void
width: number
height: number
orientation?: number
} | null> {
const extracted = await extractEmbeddedJpeg(rawFilePath, targetDir)
if (!extracted) return null
const dims = await validateExtractedJpeg(extracted.previewPath)
if (!dims) {
logger.warn({ rawFilePath }, 'Extracted JPEG from RAW is not decodable, skipping preview')
extracted.cleanup()
return null
}
return {
previewPath: extracted.previewPath,
cleanup: extracted.cleanup,
orientation: extracted.orientation,
...dims,
}
}
@@ -20,6 +20,7 @@ import * as fs from 'fs'
import { WorkflowTask } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import sharp from 'sharp'
import * as rawExtract from './raw-extract'
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
@@ -40,6 +41,9 @@ vi.mock('sharp', () => {
resize: vi.fn().mockReturnThis(),
toColorspace: vi.fn().mockReturnThis(),
webp: vi.fn().mockReturnThis(),
rotate: vi.fn().mockReturnThis(),
flip: vi.fn().mockReturnThis(),
flop: vi.fn().mockReturnThis(),
composite: vi.fn().mockReturnThis(),
png: vi.fn().mockReturnThis(),
toBuffer: vi.fn().mockResolvedValue(Buffer.from('fake-webp-buffer')),
@@ -448,6 +452,103 @@ describe('TranscodeService', () => {
expect(info.mimeType).toBe('psd')
})
it('should extract embedded preview for RAW image in getImageInfo', async () => {
const rawPath = path.join(tempDir, 'photo.cr2')
const cleanupSpy = vi.fn()
vi.spyOn(rawExtract, 'extractAndValidateRawPreview').mockResolvedValueOnce({
previewPath: '/tmp/preview.jpg',
cleanup: cleanupSpy,
width: 6000,
height: 4000,
orientation: 1,
})
const info = await transcodeService.getImageInfo(rawPath)
expect(info.originalWidth).toBe(6000)
expect(info.originalHeight).toBe(4000)
expect(info.mimeType).toBe('jpeg')
expect(cleanupSpy).toHaveBeenCalled()
})
it('should swap dimensions in getImageInfo when RAW orientation is portrait (orientation 6)', async () => {
const rawPath = path.join(tempDir, 'portrait.dng')
const cleanupSpy = vi.fn()
vi.spyOn(rawExtract, 'extractAndValidateRawPreview').mockResolvedValueOnce({
previewPath: '/tmp/preview.jpg',
cleanup: cleanupSpy,
width: 6000,
height: 4000,
orientation: 6,
})
const info = await transcodeService.getImageInfo(rawPath)
expect(info.originalWidth).toBe(4000)
expect(info.originalHeight).toBe(6000)
expect(info.mimeType).toBe('jpeg')
expect(cleanupSpy).toHaveBeenCalled()
})
it('should return zero dimensions in getImageInfo when RAW has no usable preview', async () => {
const rawPath = path.join(tempDir, 'nopreview.arw')
vi.spyOn(rawExtract, 'extractAndValidateRawPreview').mockResolvedValueOnce(null)
const info = await transcodeService.getImageInfo(rawPath)
expect(info.originalWidth).toBe(0)
expect(info.originalHeight).toBe(0)
expect(info.mimeType).toBe('')
})
it('should transcode RAW image by extracting preview to temp file and feeding to sharp', async () => {
const rawPath = path.join(tempDir, 'sample.nef')
const outputFile = path.join(tempDir, 'output-raw.webp')
const cleanupSpy = vi.fn()
vi.spyOn(rawExtract, 'extractAndValidateRawPreview').mockResolvedValueOnce({
previewPath: '/tmp/extracted-raw.jpg',
cleanup: cleanupSpy,
width: 3000,
height: 2000,
orientation: 1,
})
await transcodeService.transcodeImage(rawPath, outputFile, 1920, 85)
expect(sharp).toHaveBeenCalledWith('/tmp/extracted-raw.jpg', { limitInputPixels: false })
const mockSharp = vi.mocked(sharp).mock.results[vi.mocked(sharp).mock.results.length - 1].value
expect(mockSharp.toColorspace).toHaveBeenCalledWith('srgb')
expect(mockSharp.webp).toHaveBeenCalledWith({ quality: 85 })
expect(mockSharp.toFile).toHaveBeenCalledWith(outputFile)
expect(cleanupSpy).toHaveBeenCalled()
})
it('should apply orientation rotation when transcoding RAW image', async () => {
const rawPath = path.join(tempDir, 'rotated.cr3')
const outputFile = path.join(tempDir, 'output-rotated.webp')
const cleanupSpy = vi.fn()
vi.spyOn(rawExtract, 'extractAndValidateRawPreview').mockResolvedValueOnce({
previewPath: '/tmp/extracted-rotated.jpg',
cleanup: cleanupSpy,
width: 4000,
height: 3000,
orientation: 6, // 90° CW
})
await transcodeService.transcodeImage(rawPath, outputFile, 1920, 85)
const mockSharp = vi.mocked(sharp).mock.results[vi.mocked(sharp).mock.results.length - 1].value
expect(mockSharp.rotate).toHaveBeenCalledWith(90)
expect(cleanupSpy).toHaveBeenCalled()
})
it('should throw error when transcoding RAW without usable preview', async () => {
const rawPath = path.join(tempDir, 'corrupt.raf')
const outputFile = path.join(tempDir, 'output-fail.webp')
vi.spyOn(rawExtract, 'extractAndValidateRawPreview').mockResolvedValueOnce(null)
await expect(transcodeService.transcodeImage(rawPath, outputFile, 1920, 85)).rejects.toThrow(
'Cannot generate preview for RAW file',
)
})
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
+136 -59
View File
@@ -12,7 +12,9 @@ import sharp from 'sharp'
import { ulid } from 'ulid'
import { promisify } from 'util'
import { mapConcurrent } from '../utils/async'
import { isRawImage } from '../utils/raw'
import { dataFormatNames } from './dataFormatNames'
import { extractAndValidateRawPreview, EXIF_ORIENTATION_TO_ROTATION } from './raw-extract'
import { logger } from '@shumai/core/src/logger'
const execFileAsync = promisify(execFile)
@@ -699,6 +701,48 @@ export class TranscodeService {
}
}
// RAW branch — extract embedded JPEG for metadata
if (typeof input === 'string' && isRawImage(input)) {
const extracted = await extractAndValidateRawPreview(input)
if (extracted) {
try {
const isSwapped =
extracted.orientation !== undefined &&
extracted.orientation >= 5 &&
extracted.orientation <= 8
const originalWidth = isSwapped ? extracted.height : extracted.width
const originalHeight = isSwapped ? extracted.width : extracted.height
return {
originalWidth,
originalHeight,
duration: 0,
bitRate: 0,
frameRate: 0,
totalFrames: 0,
startTimecode: undefined,
hasAudio: false,
mimeType: 'jpeg',
}
} finally {
extracted.cleanup()
}
}
// No extractable preview — return zero dimensions
// The workflow will still mark the asset as processed
return {
originalWidth: 0,
originalHeight: 0,
duration: 0,
bitRate: 0,
frameRate: 0,
totalFrames: 0,
startTimecode: undefined,
hasAudio: false,
mimeType: '',
}
}
const metadata = await sharp(input, { limitInputPixels: false }).metadata()
return {
originalWidth: metadata.width || 0,
@@ -1117,73 +1161,106 @@ export class TranscodeService {
input = Buffer.from(await resp.arrayBuffer())
}
const WEBP_MAX_DIMENSION = 7680
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
// RAW branch — extract embedded JPEG to temporary file + orientation, then treat as normal image
let rawOrientation: number | undefined
let rawCleanup: (() => void) | null = null
if (typeof input === 'string' && isRawImage(input)) {
const extracted = await extractAndValidateRawPreview(input)
if (!extracted) {
throw new Error(`Cannot generate preview for RAW file: no usable embedded JPEG in ${input}`)
}
input = extracted.previewPath
rawOrientation = extracted.orientation
rawCleanup = extracted.cleanup
}
// WEBP_MAX_DIMENSION (7680) safety cap is ALWAYS enforced
targetW = Math.min(targetW, WEBP_MAX_DIMENSION)
targetH = Math.min(targetH, WEBP_MAX_DIMENSION)
try {
const WEBP_MAX_DIMENSION = 7680
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
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)
}
const sharpInstance = sharp(input, { limitInputPixels: false })
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)
if (isPreview) {
try {
const meta = await sharpInstance.metadata()
if (meta.width && meta.height) {
const isSwapped =
rawOrientation !== undefined && rawOrientation >= 5 && rawOrientation <= 8
const srcW = isSwapped ? meta.height : meta.width
const srcH = isSwapped ? 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(srcW, srcH, 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
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)
}
}
}
// Apply EXIF orientation from the RAW container to the extracted buffer.
// The buffer itself often lacks orientation EXIF, so Sharp won't auto-rotate.
// For non-RAW images, Sharp auto-rotates from the image's own EXIF.
if (rawOrientation && EXIF_ORIENTATION_TO_ROTATION[rawOrientation]) {
const { angle, flip, flop } = EXIF_ORIENTATION_TO_ROTATION[rawOrientation]
if (angle) sharpInstance.rotate(angle)
if (flip) sharpInstance.flip()
if (flop) sharpInstance.flop()
}
sharpInstance.toColorspace('srgb').resize(targetW, targetH, {
withoutEnlargement: true,
fit: 'inside',
})
await sharpInstance.webp({ quality }).toFile(outputFile)
} finally {
if (rawCleanup) {
rawCleanup()
}
}
sharpInstance.toColorspace('srgb').resize(targetW, targetH, {
withoutEnlargement: true,
fit: 'inside',
})
await sharpInstance.webp({ quality }).toFile(outputFile)
}
async generatePoster(
+24
View File
@@ -15,6 +15,30 @@ const EXTENSION_MIME_TYPES: Record<string, string> = {
'.txt': 'text/plain',
'.md': 'text/markdown',
'.markdown': 'text/markdown',
// Camera RAW formats
'.3fr': 'image/x-hasselblad-3fr',
'.arw': 'image/x-sony-arw',
'.cr2': 'image/x-canon-cr2',
'.cr3': 'image/x-canon-cr3',
'.crw': 'image/x-canon-crw',
'.dcr': 'image/x-kodak-dcr',
'.dng': 'image/x-adobe-dng',
'.erf': 'image/x-epson-erf',
'.fff': 'image/x-hasselblad-fff',
'.iiq': 'image/x-phaseone-iiq',
'.kdc': 'image/x-kodak-kdc',
'.nef': 'image/x-nikon-nef',
'.nrw': 'image/x-nikon-nrw',
'.orf': 'image/x-olympus-orf',
'.pef': 'image/x-pentax-pef',
'.raf': 'image/x-fuji-raf',
'.raw': 'image/x-panasonic-raw',
'.rw2': 'image/x-panasonic-rw2',
'.rwl': 'image/x-leica-rwl',
'.sr2': 'image/x-sony-sr2',
'.srf': 'image/x-sony-srf',
'.srw': 'image/x-samsung-srw',
'.x3f': 'image/x-sigma-x3f',
}
/**
+14
View File
@@ -92,6 +92,20 @@ describe('getProxyType', () => {
expect(getProxyType(null, 'design.psd')).toBe('image')
})
it('should detect image proxyType for RAW camera files', () => {
// RAW files typically upload with application/octet-stream or null mediaType
expect(getProxyType('application/octet-stream', 'photo.cr2')).toBe('image')
expect(getProxyType('application/octet-stream', 'photo.arw')).toBe('image')
expect(getProxyType(null, 'photo.dng')).toBe('image')
expect(getProxyType(null, 'photo.nef')).toBe('image')
expect(getProxyType(null, 'photo.raf')).toBe('image')
expect(getProxyType(null, 'photo.cr3')).toBe('image')
expect(getProxyType(null, 'photo.rw2')).toBe('image')
// Case-insensitive
expect(getProxyType(null, 'PHOTO.ARW')).toBe('image')
expect(getProxyType(null, 'Photo.DNG')).toBe('image')
})
it('should detect video proxyType', () => {
expect(getProxyType('video/mp4', 'clip.mp4')).toBe('video')
})
+8 -1
View File
@@ -1,3 +1,5 @@
import { isRawImage } from './raw'
export type ProxyType = 'image' | 'video' | 'audio' | 'pdf'
export function isOfficeDocument(mediaType?: string | null, filename?: string | null): boolean {
@@ -73,7 +75,12 @@ export function getProxyType(
const lowerMediaType = mediaType?.toLowerCase() || ''
const lowerFilename = filename?.toLowerCase() || ''
if (lowerMediaType.startsWith('image/') || lowerFilename.endsWith('.psd')) return 'image'
if (
lowerMediaType.startsWith('image/') ||
lowerFilename.endsWith('.psd') ||
isRawImage(lowerFilename)
)
return 'image'
if (lowerMediaType.startsWith('video/')) return 'video'
if (lowerMediaType.startsWith('audio/')) return 'audio'
+68
View File
@@ -0,0 +1,68 @@
import { describe, it, expect } from 'vitest'
import { isRawImage } from './raw'
describe('isRawImage', () => {
it('recognizes common RAW extensions (lowercase)', () => {
expect(isRawImage('photo.cr2')).toBe(true)
expect(isRawImage('photo.arw')).toBe(true)
expect(isRawImage('photo.dng')).toBe(true)
expect(isRawImage('photo.nef')).toBe(true)
expect(isRawImage('photo.raf')).toBe(true)
expect(isRawImage('photo.rw2')).toBe(true)
expect(isRawImage('photo.orf')).toBe(true)
expect(isRawImage('photo.pef')).toBe(true)
expect(isRawImage('photo.cr3')).toBe(true)
expect(isRawImage('photo.x3f')).toBe(true)
expect(isRawImage('photo.raw')).toBe(true)
expect(isRawImage('photo.3fr')).toBe(true)
expect(isRawImage('photo.iiq')).toBe(true)
expect(isRawImage('photo.kdc')).toBe(true)
expect(isRawImage('photo.dcr')).toBe(true)
expect(isRawImage('photo.erf')).toBe(true)
expect(isRawImage('photo.fff')).toBe(true)
expect(isRawImage('photo.crw')).toBe(true)
expect(isRawImage('photo.nrw')).toBe(true)
expect(isRawImage('photo.rwl')).toBe(true)
expect(isRawImage('photo.sr2')).toBe(true)
expect(isRawImage('photo.srf')).toBe(true)
expect(isRawImage('photo.srw')).toBe(true)
})
it('recognizes RAW extensions case-insensitively', () => {
expect(isRawImage('photo.CR2')).toBe(true)
expect(isRawImage('IMG_1234.ARW')).toBe(true)
expect(isRawImage('test.DNG')).toBe(true)
expect(isRawImage('photo.Nef')).toBe(true)
})
it('rejects non-RAW image files', () => {
expect(isRawImage('photo.jpg')).toBe(false)
expect(isRawImage('photo.png')).toBe(false)
expect(isRawImage('photo.webp')).toBe(false)
expect(isRawImage('photo.gif')).toBe(false)
expect(isRawImage('photo.svg')).toBe(false)
})
it('rejects non-image files', () => {
expect(isRawImage('design.psd')).toBe(false)
expect(isRawImage('video.mp4')).toBe(false)
expect(isRawImage('doc.pdf')).toBe(false)
expect(isRawImage('readme.txt')).toBe(false)
})
it('rejects files without extensions', () => {
expect(isRawImage('photo')).toBe(false)
expect(isRawImage('rawfile')).toBe(false)
})
it('handles filenames with multiple dots', () => {
expect(isRawImage('my.photo.cr2')).toBe(true)
expect(isRawImage('backup.2024.dng')).toBe(true)
expect(isRawImage('my.photo.jpg')).toBe(false)
})
it('handles paths with directories', () => {
expect(isRawImage('/home/user/photos/photo.cr2')).toBe(true)
expect(isRawImage('C:\\Users\\photos\\photo.arw')).toBe(true)
})
})
+37
View File
@@ -0,0 +1,37 @@
/**
* Centralized set of recognized camera RAW file extensions.
* Used only for routing files into the ExifTool extraction path.
*/
const RAW_EXTENSIONS: ReadonlySet<string> = new Set([
'.3fr',
'.arw',
'.cr2',
'.cr3',
'.crw',
'.dcr',
'.dng',
'.erf',
'.fff',
'.iiq',
'.kdc',
'.nef',
'.nrw',
'.orf',
'.pef',
'.raf',
'.raw',
'.rw2',
'.rwl',
'.sr2',
'.srf',
'.srw',
'.x3f',
])
/** Check whether a filename has a recognized camera RAW extension. */
export function isRawImage(filename: string): boolean {
const dotIndex = filename.lastIndexOf('.')
if (dotIndex === -1) return false
const ext = filename.slice(dotIndex).toLowerCase()
return RAW_EXTENSIONS.has(ext)
}