fix(transcode): avoid selecting attached picture streams for video transcoding (#443)

* fix(transcode): avoid selecting attached picture streams for video transcoding

Filter out attached picture streams (disposition.attached_pic) during video probing and stream selection, matching Immich's default and bitrate selection strategy. Forward explicit primary video and audio stream indices to FFmpeg pipelines to prevent picking embedded cover art or thumbnail streams.

* fix(transcode): skip poster and sprite generation for audio-only assets and add multi-stream e2e tests

* test(workflow): scope pixel format to h264 stream and use yuvj420p for mjpeg cover art
This commit is contained in:
Yiling-J
2026-10-02 13:51:17 +08:00
committed by GitHub
parent 206763e966
commit 3564d4d164
10 changed files with 1346 additions and 73 deletions
@@ -217,6 +217,86 @@ describe('Transcode Activities', () => {
)
})
it('should downgrade proxyType to audio when getVideoInfo throws No video stream found but audio exists', async () => {
const asset = await prisma.asset.create({
data: { name: 'audio-with-art.mp4', type: 'file', status: 'uploaded' },
})
vi.mocked(transcodeService.getVideoInfo).mockRejectedValueOnce(
new Error('No video stream found'),
)
vi.mocked(transcodeService.getAudioInfo).mockResolvedValueOnce({
originalWidth: 0,
originalHeight: 0,
duration: 42,
bitRate: 192000,
frameRate: 0,
totalFrames: 0,
hasAudio: true,
audioCodec: 'aac',
audioChannels: 2,
audioSampleRate: 44100,
audioBitDepth: 16,
audioStreamIndex: 0,
mimeType: 'audio/mp4',
})
const result = await getMediaInfoActivity({
assetId: asset.id,
filePath: '/tmp/audio-with-art.mp4',
proxyType: 'video',
mediaType: 'video/mp4',
})
expect(transcodeService.getVideoInfo).toHaveBeenCalledWith('/tmp/audio-with-art.mp4')
expect(transcodeService.getAudioInfo).toHaveBeenCalledWith('/tmp/audio-with-art.mp4')
expect(result.proxyType).toBe('audio')
expect(result.duration).toBe(42)
expect(result.metadata?.hasAudio).toBe(true)
expect(result.metadata?.audioStreamIndex).toBe(0)
expect(result.metadata?.videoStreamIndex).toBeUndefined()
expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith(
asset.id,
expect.arrayContaining([
{ key: 'file_type', value: 'audio' },
{ key: 'proxy_type', value: 'audio' },
{ key: 'duration', value: 42 },
]),
true,
)
})
it('should populate videoStreamIndex and audioStreamIndex in mediaInfo.metadata', async () => {
const asset = await prisma.asset.create({
data: { name: 'dual-stream.mp4', type: 'file', status: 'uploaded' },
})
vi.mocked(transcodeService.getVideoInfo).mockResolvedValueOnce({
originalWidth: 1920,
originalHeight: 1080,
duration: 15,
bitRate: 2000000,
frameRate: 30,
totalFrames: 450,
hasAudio: true,
videoCodec: 'h264',
audioCodec: 'aac',
videoStreamIndex: 1,
audioStreamIndex: 2,
mimeType: 'video/mp4',
})
const result = await getMediaInfoActivity({
assetId: asset.id,
filePath: '/tmp/dual-stream.mp4',
proxyType: 'video',
mediaType: 'video/mp4',
})
expect(result.metadata?.videoStreamIndex).toBe(1)
expect(result.metadata?.audioStreamIndex).toBe(2)
})
it('should call getImageInfo and set file_type to image', async () => {
const asset = await prisma.asset.create({
data: { name: 'i.png', type: 'file', status: 'uploaded' },
@@ -703,6 +783,28 @@ describe('Transcode Activities', () => {
)
})
it('transcodeVideoActivity forwards streamIndex and audioStreamIndex to transcodeService', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
await transcodeVideoActivity({
assetKey: 'v.mp4',
filePath: '/tmp/v.mp4',
videoSpec: { resolution: '720p', width: 1280, height: 720 },
duration: 10,
originalFps: 30,
streamIndex: 2,
audioStreamIndex: 1,
})
expect(transcodeService.transcodeVideo).toHaveBeenCalledWith(
expect.objectContaining({
inputFile: '/tmp/v.mp4',
streamIndex: 2,
audioStreamIndex: 1,
}),
)
})
it('transcodeVideoActivity appends -hdr.mp4 suffix and forwards HDR metadata', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
@@ -946,6 +1048,44 @@ describe('Transcode Activities', () => {
hdrType: 'pq',
colorTransfer: 'smpte2084',
},
undefined,
)
})
it('generateSpriteActivity forwards videoStreamIndex to transcodeService.generateSprite', async () => {
vi.mocked(transcodeService.generateSprite).mockImplementation(
async (_in, spriteOut, posterOut) => {
const fs = await import('fs')
fs.writeFileSync(spriteOut, 'fake-sprite')
fs.writeFileSync(posterOut, 'fake-poster')
},
)
await generateSpriteActivity({
assetKey: 'files/asset-1/video.mp4',
filePath: '/tmp/video.mp4',
mediaInfo: {
duration: 10,
metadata: {
videoStreamIndex: 1,
},
} as unknown as PrismaJson.MediaInfo,
spriteSpec: { key: 'files/asset-1/sprite.webp', frames: 100, tileX: 10, tileY: 10 },
posterSpec: { key: 'files/asset-1/poster.webp' },
})
expect(transcodeService.generateSprite).toHaveBeenCalledWith(
'/tmp/video.mp4',
expect.any(String),
expect.any(String),
10,
undefined,
{
isHdr: undefined,
hdrType: undefined,
colorTransfer: undefined,
},
1,
)
})
+119 -47
View File
@@ -130,54 +130,110 @@ export async function getMediaInfoActivity(params: {
}
if (isVideo) {
const info = await transcodeService.getVideoInfo(params.filePath)
mediaInfo.duration = info.duration
mediaInfo.frames = info.totalFrames
mediaInfo.metadata = {
originalWidth: info.originalWidth,
originalHeight: info.originalHeight,
duration: info.duration,
bitRate: info.bitRate,
videoBitRate: info.videoBitRate,
frameRate: info.frameRate,
totalFrames: info.totalFrames,
startTimecode: info.startTimecode || '00:00:00:00',
hasAudio: info.hasAudio,
videoCodec: info.videoCodec,
audioCodec: info.audioCodec,
audioChannels: info.audioChannels,
audioSampleRate: info.audioSampleRate,
audioBitDepth: info.audioBitDepth,
colorTransfer: info.colorTransfer,
colorPrimaries: info.colorPrimaries,
colorSpace: info.colorSpace,
isHdr: info.isHdr,
hdrType: info.hdrType,
dvProfile: info.dvProfile,
rotation: info.rotation,
format: {},
let isDowngradedToAudio = false
let videoInfo: Awaited<ReturnType<typeof transcodeService.getVideoInfo>> | null = null
try {
videoInfo = await transcodeService.getVideoInfo(params.filePath)
} catch (err) {
if (err instanceof Error && err.message.includes('No video stream found')) {
try {
const audioInfo = await transcodeService.getAudioInfo(params.filePath)
isDowngradedToAudio = true
mediaInfo.proxyType = 'audio'
mediaInfo.duration = audioInfo.duration
mediaInfo.metadata = {
originalWidth: 0,
originalHeight: 0,
duration: audioInfo.duration,
bitRate: audioInfo.bitRate,
frameRate: 0,
totalFrames: 0,
startTimecode: '00:00:00:00',
hasAudio: true,
videoCodec: undefined,
audioCodec: audioInfo.audioCodec,
audioChannels: audioInfo.audioChannels,
audioSampleRate: audioInfo.audioSampleRate,
audioBitDepth: audioInfo.audioBitDepth,
audioStreamIndex: audioInfo.audioStreamIndex,
format: {},
}
const ftIdx = metadataUpdates.findIndex((u) => u.key === 'file_type')
if (ftIdx !== -1) metadataUpdates[ftIdx].value = 'audio'
const ptIdx = metadataUpdates.findIndex((u) => u.key === 'proxy_type')
if (ptIdx !== -1) metadataUpdates[ptIdx].value = 'audio'
metadataUpdates.push(
{ key: 'duration', value: audioInfo.duration },
{ key: 'bitRate', value: audioInfo.bitRate / 1000 },
)
if (audioInfo.audioCodec)
metadataUpdates.push({ key: 'audio_codec', value: audioInfo.audioCodec })
if (audioInfo.audioChannels !== undefined)
metadataUpdates.push({ key: 'audio_channels', value: audioInfo.audioChannels })
if (audioInfo.audioSampleRate !== undefined)
metadataUpdates.push({ key: 'audio_sample_rate', value: audioInfo.audioSampleRate })
if (audioInfo.audioBitDepth !== undefined)
metadataUpdates.push({ key: 'audio_bit_depth', value: audioInfo.audioBitDepth })
} catch {
throw err
}
} else {
throw err
}
}
if (!isDowngradedToAudio && videoInfo) {
const info = videoInfo
mediaInfo.duration = info.duration
mediaInfo.frames = info.totalFrames
mediaInfo.metadata = {
originalWidth: info.originalWidth,
originalHeight: info.originalHeight,
duration: info.duration,
bitRate: info.bitRate,
videoBitRate: info.videoBitRate,
frameRate: info.frameRate,
totalFrames: info.totalFrames,
startTimecode: info.startTimecode || '00:00:00:00',
hasAudio: info.hasAudio,
videoCodec: info.videoCodec,
audioCodec: info.audioCodec,
audioChannels: info.audioChannels,
audioSampleRate: info.audioSampleRate,
audioBitDepth: info.audioBitDepth,
colorTransfer: info.colorTransfer,
colorPrimaries: info.colorPrimaries,
colorSpace: info.colorSpace,
isHdr: info.isHdr,
hdrType: info.hdrType,
dvProfile: info.dvProfile,
rotation: info.rotation,
videoStreamIndex: info.videoStreamIndex,
audioStreamIndex: info.audioStreamIndex,
format: {},
}
metadataUpdates.push(
{ key: 'resolution_width', value: info.originalWidth },
{ key: 'resolution_height', value: info.originalHeight },
{ key: 'duration', value: info.duration },
{ key: 'bitRate', value: info.bitRate / 1000 },
{ key: 'frame_rate', value: info.frameRate },
)
if (info.rotation !== undefined)
metadataUpdates.push({ key: 'rotation', value: info.rotation })
if (info.isHdr !== undefined)
metadataUpdates.push({ key: 'is_hdr', value: info.isHdr ? 1 : 0 })
if (info.colorTransfer)
metadataUpdates.push({ key: 'color_transfer', value: info.colorTransfer })
if (info.videoCodec) metadataUpdates.push({ key: 'video_codec', value: info.videoCodec })
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 })
}
metadataUpdates.push(
{ key: 'resolution_width', value: info.originalWidth },
{ key: 'resolution_height', value: info.originalHeight },
{ key: 'duration', value: info.duration },
{ key: 'bitRate', value: info.bitRate / 1000 },
{ key: 'frame_rate', value: info.frameRate },
)
if (info.rotation !== undefined)
metadataUpdates.push({ key: 'rotation', value: info.rotation })
if (info.isHdr !== undefined)
metadataUpdates.push({ key: 'is_hdr', value: info.isHdr ? 1 : 0 })
if (info.colorTransfer)
metadataUpdates.push({ key: 'color_transfer', value: info.colorTransfer })
if (info.videoCodec) metadataUpdates.push({ key: 'video_codec', value: info.videoCodec })
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 (isAudio) {
const info = await transcodeService.getAudioInfo(params.filePath)
mediaInfo.duration = info.duration
@@ -195,6 +251,7 @@ export async function getMediaInfoActivity(params: {
audioChannels: info.audioChannels,
audioSampleRate: info.audioSampleRate,
audioBitDepth: info.audioBitDepth,
audioStreamIndex: info.audioStreamIndex,
format: {},
}
metadataUpdates.push(
@@ -277,6 +334,8 @@ export interface VideoActivityParams {
sourceColorTransfer?: string
sourceColorPrimaries?: string
sourceColorSpace?: string
streamIndex?: number
audioStreamIndex?: number
}
export async function transcodeVideoActivity(
@@ -338,6 +397,8 @@ export async function transcodeVideoActivity(
sourceColorTransfer: params.sourceColorTransfer,
sourceColorPrimaries: params.sourceColorPrimaries,
sourceColorSpace: params.sourceColorSpace,
streamIndex: params.streamIndex,
audioStreamIndex: params.audioStreamIndex,
})
const stat = fs.statSync(outputFile)
@@ -403,6 +464,8 @@ export interface HlsActivityParams {
sourceColorTransfer?: string
sourceColorPrimaries?: string
sourceColorSpace?: string
streamIndex?: number
audioStreamIndex?: number
}
export async function transcodeHlsActivity(params: HlsActivityParams): Promise<PrismaJson.HlsInfo> {
@@ -469,6 +532,8 @@ export async function transcodeHlsActivity(params: HlsActivityParams): Promise<P
sourceColorTransfer: params.sourceColorTransfer,
sourceColorPrimaries: params.sourceColorPrimaries,
sourceColorSpace: params.sourceColorSpace,
streamIndex: params.streamIndex,
audioStreamIndex: params.audioStreamIndex,
})
renditionSpecs.push({
@@ -572,6 +637,7 @@ export interface AudioActivityParams {
assetKey: string
filePath: string
threads?: number
audioStreamIndex?: number
}
export async function transcodeAudioActivity(
@@ -606,6 +672,7 @@ export async function transcodeAudioActivity(
bitrate: '128k',
threads: params.threads,
signal,
audioStreamIndex: params.audioStreamIndex,
})
const stat = fs.statSync(outputFile)
@@ -777,6 +844,7 @@ export async function generateSpriteActivity(params: GenerateSpriteActivityParam
hdrType: params.mediaInfo.metadata?.hdrType,
colorTransfer: params.mediaInfo.metadata?.colorTransfer,
},
params.mediaInfo.metadata?.videoStreamIndex,
)
}
@@ -1081,6 +1149,7 @@ export interface ExtractPosterActivityParams {
isHdr?: boolean
hdrType?: HdrType
colorTransfer?: string
streamIndex?: number
}
export async function extractPosterActivity(
@@ -1112,6 +1181,7 @@ export async function extractPosterActivity(
hdrType: params.hdrType,
colorTransfer: params.colorTransfer,
signal,
streamIndex: params.streamIndex,
})
const posterBuffer = fs.readFileSync(posterFile)
@@ -1428,6 +1498,8 @@ export async function transcodeVideoChunkActivity(
params.startTime.toString(),
'-i',
inputSource,
'-map',
'0:V:0',
'-t',
(params.endTime - params.startTime).toString(),
'-vf',
@@ -370,6 +370,8 @@ export async function transcodeWatermarkMediaActivity(
sourceColorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
sourceColorPrimaries: colorPrimaries ?? originalMedia?.metadata?.colorPrimaries,
sourceColorSpace: colorSpace ?? originalMedia?.metadata?.colorSpace,
streamIndex: originalMedia?.metadata?.videoStreamIndex,
audioStreamIndex: originalMedia?.metadata?.audioStreamIndex,
})
const stat = fs.statSync(outFilePath)
@@ -440,6 +442,8 @@ export async function transcodeWatermarkMediaActivity(
sourceColorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
sourceColorPrimaries: colorPrimaries ?? originalMedia?.metadata?.colorPrimaries,
sourceColorSpace: colorSpace ?? originalMedia?.metadata?.colorSpace,
streamIndex: originalMedia?.metadata?.videoStreamIndex,
audioStreamIndex: originalMedia?.metadata?.audioStreamIndex,
})
const targetBps = calculateEffectiveBitrateBps(
@@ -64,7 +64,9 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
codec: '',
}
if (spec.poster) {
const isVideo = mediaInfo.proxyType === 'video'
if (spec.poster && isVideo) {
const lastSlashIndex = key.lastIndexOf('/')
const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex)
const posterSpec: PrismaJson.PosterInfo = {
@@ -77,6 +79,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
isHdr: mediaInfo.metadata?.isHdr,
hdrType: mediaInfo.metadata?.hdrType,
colorTransfer: mediaInfo.metadata?.colorTransfer,
streamIndex: mediaInfo.metadata?.videoStreamIndex,
})
mediaInfo.poster = posterResult.poster
await executeActivity(workerQueue, updateAssetMediaActivity, {
@@ -87,7 +90,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
// Generate the sprite (and its poster fallback) before the expensive proxy transcodes so the
// file list can show a poster/sprite preview while the asset is still processing.
if (spec.sprite || (spec.poster && !mediaInfo.poster)) {
if ((spec.sprite || (spec.poster && !mediaInfo.poster)) && isVideo) {
const lastSlashIndex = key.lastIndexOf('/')
const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex)
@@ -124,7 +127,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
const metadata = mediaInfo.metadata
if (mediaInfo.proxyType === 'video' && metadata) {
if (isVideo && metadata) {
const videoResolutions = getTargetVideoResolutions(
spec.videoStrategy || 'best_match',
metadata.originalWidth,
@@ -163,6 +166,8 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
sourceColorTransfer: metadata.colorTransfer,
sourceColorPrimaries: metadata.colorPrimaries,
sourceColorSpace: metadata.colorSpace,
streamIndex: metadata.videoStreamIndex,
audioStreamIndex: metadata.audioStreamIndex,
})
mediaInfo.videoPreview = videoTranscode
@@ -191,6 +196,8 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
sourceColorTransfer: metadata.colorTransfer,
sourceColorPrimaries: metadata.colorPrimaries,
sourceColorSpace: metadata.colorSpace,
streamIndex: metadata.videoStreamIndex,
audioStreamIndex: metadata.audioStreamIndex,
})
mediaInfo.videoTranscodes.push(videoTranscode)
@@ -219,6 +226,8 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
sourceColorTransfer: metadata.colorTransfer,
sourceColorPrimaries: metadata.colorPrimaries,
sourceColorSpace: metadata.colorSpace,
streamIndex: metadata.videoStreamIndex,
audioStreamIndex: metadata.audioStreamIndex,
})
mediaInfo.isHls = true
mediaInfo.hls = hlsResult
@@ -233,11 +242,12 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
assetKey: key,
filePath,
threads: spec.threads,
audioStreamIndex: metadata.audioStreamIndex,
})
mediaInfo.videoTranscodes.push(audioTranscode)
}
if (spec.thumbnail) {
if (spec.thumbnail && isVideo) {
const thumbTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
assetKey: key,
filePath,