mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 22:59:25 +00:00
feat(transcode): add HDR video proxy support and playback (#424)
* feat(transcode): add HDR output proxy support * fix(transcode): auto-detect MoltenVK Vulkan ICD on macOS for libplacebo filters * fix(transcode): split filter in generateSprite to ensure poster uses tone-mapped stream * docs(changelog): update docs/changelog.mdx and ignore in prettier * fix(transcode): respect video rotation metadata to preserve display aspect ratio * fix(webui): render native video with hardware EDR acceleration instead of 2D canvas * fix(webui): show HDR label on mobile video control bar * fix(share): preserve hdr flag on watermarked video transcodes * fix(webui): differentiate HDR download options in video player * fix(transcode): handle Dolby Vision Profile 5 via standard HDR pipeline without libplacebo * fix(transcode): prepend setparams filter to prevent zscale colorspace path error for DV P5 * refactor(transcode): simplify HDR proxies to always produce HDR without SDR setting
This commit is contained in:
@@ -7,6 +7,7 @@ import {
|
||||
getDefaultBitrateBps,
|
||||
calculateMaxBitrate,
|
||||
H264_ENCODER_CONFIGS,
|
||||
buildSdrToneMapFilterChain,
|
||||
} from './transcode'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import * as path from 'path'
|
||||
@@ -1813,4 +1814,477 @@ describe('TranscodeService', () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('HDR detection, tone mapping, and transcoding', () => {
|
||||
it('buildSdrToneMapFilterChain constructs zscale + tonemap filter chain for PQ and HLG', () => {
|
||||
const available = new Set(['zscale', 'tonemap'])
|
||||
const pqChain = buildSdrToneMapFilterChain({
|
||||
hdrType: 'pq',
|
||||
availableFilters: available,
|
||||
})
|
||||
expect(pqChain).toContain(
|
||||
'setparams=color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc',
|
||||
)
|
||||
expect(pqChain).toContain('zscale=tin=smpte2084:pin=bt2020:min=bt2020nc')
|
||||
expect(pqChain).toContain('tonemap=tonemap=hable:desat=0:peak=100')
|
||||
expect(pqChain).toContain('format=yuv420p')
|
||||
|
||||
const hlgChain = buildSdrToneMapFilterChain({
|
||||
hdrType: 'hlg',
|
||||
availableFilters: available,
|
||||
})
|
||||
expect(hlgChain).toContain(
|
||||
'setparams=color_primaries=bt2020:color_trc=arib-std-b67:colorspace=bt2020nc',
|
||||
)
|
||||
expect(hlgChain).toContain('zscale=tin=arib-std-b67:pin=bt2020:min=bt2020nc')
|
||||
expect(hlgChain).toContain('tonemap=tonemap=hable')
|
||||
})
|
||||
|
||||
it('buildSdrToneMapFilterChain throws error if zscale or tonemap is missing for PQ/HLG', () => {
|
||||
expect(() =>
|
||||
buildSdrToneMapFilterChain({
|
||||
hdrType: 'pq',
|
||||
availableFilters: new Set(['zscale']),
|
||||
}),
|
||||
).toThrow(/zscale and tonemap filters are required for HDR tone mapping/)
|
||||
|
||||
expect(() =>
|
||||
buildSdrToneMapFilterChain({
|
||||
hdrType: 'hlg',
|
||||
availableFilters: new Set(['tonemap']),
|
||||
}),
|
||||
).toThrow(/zscale and tonemap filters are required for HDR tone mapping/)
|
||||
})
|
||||
|
||||
it('buildSdrToneMapFilterChain constructs zscale + tonemap filter chain for Dolby Vision Profile 5', () => {
|
||||
const chain = buildSdrToneMapFilterChain({
|
||||
hdrType: 'dovi_p5',
|
||||
availableFilters: new Set(['zscale', 'tonemap']),
|
||||
})
|
||||
expect(chain).toContain(
|
||||
'setparams=color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc',
|
||||
)
|
||||
expect(chain).toContain('tin=smpte2084')
|
||||
expect(chain).toContain('tonemap=tonemap=hable')
|
||||
expect(chain).toContain('m=bt709')
|
||||
})
|
||||
|
||||
it('buildSdrToneMapFilterChain throws error if zscale or tonemap is missing for Dolby Vision Profile 5', () => {
|
||||
expect(() =>
|
||||
buildSdrToneMapFilterChain({
|
||||
hdrType: 'dovi_p5',
|
||||
availableFilters: new Set(['tonemap']),
|
||||
}),
|
||||
).toThrow(/zscale and tonemap filters are required for HDR tone mapping/)
|
||||
})
|
||||
|
||||
const mockExecFileStdout = (mockOutput: string) => {
|
||||
;(
|
||||
child_process.execFile as unknown as {
|
||||
mockImplementation: (
|
||||
fn: (
|
||||
file: string,
|
||||
args: string[],
|
||||
cb: (err: Error | null, res: { stdout: string; stderr: string }) => void,
|
||||
) => unknown,
|
||||
) => void
|
||||
}
|
||||
).mockImplementation((_file, _args, cb) => {
|
||||
cb(null, { stdout: mockOutput, stderr: '' })
|
||||
})
|
||||
}
|
||||
|
||||
it('getVideoInfo detects PQ HDR from smpte2084 color_transfer', async () => {
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const mockOutput = JSON.stringify({
|
||||
format: { duration: '10.0', bit_rate: '20000000' },
|
||||
streams: [
|
||||
{
|
||||
codec_type: 'video',
|
||||
codec_name: 'hevc',
|
||||
width: 3840,
|
||||
height: 2160,
|
||||
r_frame_rate: '24/1',
|
||||
color_transfer: 'smpte2084',
|
||||
color_primaries: 'bt2020',
|
||||
color_space: 'bt2020nc',
|
||||
bits_per_raw_sample: '10',
|
||||
},
|
||||
],
|
||||
})
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
mockExecFileStdout(mockOutput)
|
||||
|
||||
const info = await transcodeService.getVideoInfo('hdr-pq.mp4')
|
||||
expect(info.isHdr).toBe(true)
|
||||
expect(info.hdrType).toBe('pq')
|
||||
expect(info.colorTransfer).toBe('smpte2084')
|
||||
})
|
||||
|
||||
it('getVideoInfo detects HLG HDR from arib-std-b67 color_transfer', async () => {
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const mockOutput = JSON.stringify({
|
||||
format: { duration: '10.0', bit_rate: '20000000' },
|
||||
streams: [
|
||||
{
|
||||
codec_type: 'video',
|
||||
codec_name: 'hevc',
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
r_frame_rate: '30/1',
|
||||
color_transfer: 'arib-std-b67',
|
||||
color_primaries: 'bt2020',
|
||||
color_space: 'bt2020nc',
|
||||
},
|
||||
],
|
||||
})
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
mockExecFileStdout(mockOutput)
|
||||
|
||||
const info = await transcodeService.getVideoInfo('hdr-hlg.mp4')
|
||||
expect(info.isHdr).toBe(true)
|
||||
expect(info.hdrType).toBe('hlg')
|
||||
expect(info.colorTransfer).toBe('arib-std-b67')
|
||||
})
|
||||
|
||||
it('getVideoInfo treats 10-bit Rec.709 with BT.709 transfer as SDR', async () => {
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const mockOutput = JSON.stringify({
|
||||
format: { duration: '10.0', bit_rate: '20000000' },
|
||||
streams: [
|
||||
{
|
||||
codec_type: 'video',
|
||||
codec_name: 'h264',
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
r_frame_rate: '24/1',
|
||||
color_transfer: 'bt709',
|
||||
color_primaries: 'bt709',
|
||||
color_space: 'bt709',
|
||||
bits_per_raw_sample: '10',
|
||||
},
|
||||
],
|
||||
})
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
mockExecFileStdout(mockOutput)
|
||||
|
||||
const info = await transcodeService.getVideoInfo('10bit-sdr.mp4')
|
||||
expect(info.isHdr).toBe(false)
|
||||
expect(info.hdrType).toBe('sdr')
|
||||
})
|
||||
|
||||
it('getVideoInfo detects Dolby Vision Profile 5 via side data', async () => {
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const mockOutput = JSON.stringify({
|
||||
format: { duration: '10.0', bit_rate: '25000000' },
|
||||
streams: [
|
||||
{
|
||||
codec_type: 'video',
|
||||
codec_name: 'hevc',
|
||||
width: 3840,
|
||||
height: 2160,
|
||||
r_frame_rate: '24/1',
|
||||
side_data_list: [
|
||||
{
|
||||
side_data_type: 'DOVI configuration record',
|
||||
dv_profile: 5,
|
||||
dv_level: 6,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
mockExecFileStdout(mockOutput)
|
||||
|
||||
const info = await transcodeService.getVideoInfo('dovi-p5.mp4')
|
||||
expect(info.isHdr).toBe(true)
|
||||
expect(info.hdrType).toBe('dovi_p5')
|
||||
expect(info.dvProfile).toBe(5)
|
||||
})
|
||||
|
||||
it('getVideoInfo treats Dolby Vision Profile 8 with BT.709 transfer as SDR', async () => {
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const mockOutput = JSON.stringify({
|
||||
format: { duration: '10.0', bit_rate: '25000000' },
|
||||
streams: [
|
||||
{
|
||||
codec_type: 'video',
|
||||
codec_name: 'hevc',
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
r_frame_rate: '24/1',
|
||||
color_transfer: 'bt709',
|
||||
color_primaries: 'bt709',
|
||||
color_space: 'bt709',
|
||||
side_data_list: [
|
||||
{
|
||||
side_data_type: 'DOVI configuration record',
|
||||
dv_profile: 8,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
mockExecFileStdout(mockOutput)
|
||||
|
||||
const info = await transcodeService.getVideoInfo('dovi-p8-sdr.mp4')
|
||||
expect(info.isHdr).toBe(false)
|
||||
expect(info.hdrType).toBe('sdr')
|
||||
expect(info.dvProfile).toBe(8)
|
||||
})
|
||||
|
||||
it('getVideoInfo swaps width and height when Display Matrix side data has rotation -90', async () => {
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const mockOutput = JSON.stringify({
|
||||
format: { duration: '10.0', bit_rate: '20000000' },
|
||||
streams: [
|
||||
{
|
||||
codec_type: 'video',
|
||||
codec_name: 'hevc',
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
r_frame_rate: '30/1',
|
||||
side_data_list: [
|
||||
{
|
||||
side_data_type: 'Display Matrix',
|
||||
rotation: -90,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
mockExecFileStdout(mockOutput)
|
||||
|
||||
const info = await transcodeService.getVideoInfo('vertical-display-matrix.mp4')
|
||||
expect(info.originalWidth).toBe(1080)
|
||||
expect(info.originalHeight).toBe(1920)
|
||||
expect(info.rotation).toBe(-90)
|
||||
})
|
||||
|
||||
it('getVideoInfo swaps width and height when tags.rotate is 90 or 270', async () => {
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const mockOutput = JSON.stringify({
|
||||
format: { duration: '10.0', bit_rate: '20000000' },
|
||||
streams: [
|
||||
{
|
||||
codec_type: 'video',
|
||||
codec_name: 'h264',
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
r_frame_rate: '30/1',
|
||||
tags: {
|
||||
rotate: '90',
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
mockExecFileStdout(mockOutput)
|
||||
|
||||
const info = await transcodeService.getVideoInfo('vertical-tag.mp4')
|
||||
expect(info.originalWidth).toBe(1080)
|
||||
expect(info.originalHeight).toBe(1920)
|
||||
expect(info.rotation).toBe(90)
|
||||
})
|
||||
|
||||
it('getVideoInfo preserves width and height when rotation is 180 degrees', async () => {
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const mockOutput = JSON.stringify({
|
||||
format: { duration: '10.0', bit_rate: '20000000' },
|
||||
streams: [
|
||||
{
|
||||
codec_type: 'video',
|
||||
codec_name: 'h264',
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
r_frame_rate: '30/1',
|
||||
tags: {
|
||||
rotate: '180',
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
mockExecFileStdout(mockOutput)
|
||||
|
||||
const info = await transcodeService.getVideoInfo('upside-down.mp4')
|
||||
expect(info.originalWidth).toBe(1920)
|
||||
expect(info.originalHeight).toBe(1080)
|
||||
expect(info.rotation).toBe(180)
|
||||
})
|
||||
|
||||
it('transcodeVideo preserves HDR parameters and tags when hdr is true', async () => {
|
||||
let executedArgs: string[] = []
|
||||
;(
|
||||
child_process.execFile as unknown as {
|
||||
mockImplementation: (
|
||||
fn: (
|
||||
file: string,
|
||||
args: string[],
|
||||
cb: (err: Error | null, res: { stdout: string; stderr: string }) => void,
|
||||
) => unknown,
|
||||
) => void
|
||||
}
|
||||
).mockImplementation((_file, args, cb) => {
|
||||
if (args.includes('-filters')) {
|
||||
cb(null, { stdout: ' ... zscale ... \n ... tonemap ... ', stderr: '' })
|
||||
return {}
|
||||
}
|
||||
if (args.includes('-encoders')) {
|
||||
cb(null, { stdout: ' V..... libx264 ', stderr: '' })
|
||||
return {}
|
||||
}
|
||||
executedArgs = args
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
return {}
|
||||
})
|
||||
|
||||
const outputFile = path.join(tempDir, 'hdr_output.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'hdr_input.mp4',
|
||||
outputFile,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
hdr: true,
|
||||
sourceIsHdr: true,
|
||||
sourceHdrType: 'pq',
|
||||
sourceColorTransfer: 'smpte2084',
|
||||
})
|
||||
|
||||
expect(executedArgs).toContain('-color_primaries')
|
||||
expect(executedArgs).toContain('bt2020')
|
||||
expect(executedArgs).toContain('-color_trc')
|
||||
expect(executedArgs).toContain('smpte2084')
|
||||
expect(executedArgs).toContain('-colorspace')
|
||||
expect(executedArgs).toContain('bt2020nc')
|
||||
expect(executedArgs).toContain('-x264-params')
|
||||
expect(executedArgs).toContain('colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc')
|
||||
})
|
||||
|
||||
it('transcodeVideo transcodes Dolby Vision Profile 5 to HDR proxy without libplacebo', async () => {
|
||||
let executedArgs: string[] = []
|
||||
;(
|
||||
child_process.execFile as unknown as {
|
||||
mockImplementation: (
|
||||
fn: (
|
||||
file: string,
|
||||
args: string[],
|
||||
cb: (err: Error | null, res: { stdout: string; stderr: string }) => void,
|
||||
) => unknown,
|
||||
) => void
|
||||
}
|
||||
).mockImplementation((_file, args, cb) => {
|
||||
if (args.includes('-filters')) {
|
||||
cb(null, { stdout: ' ... zscale ... \n ... tonemap ... ', stderr: '' })
|
||||
return {}
|
||||
}
|
||||
if (args.includes('-encoders')) {
|
||||
cb(null, { stdout: ' V..... libx264 ', stderr: '' })
|
||||
return {}
|
||||
}
|
||||
executedArgs = args
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
return {}
|
||||
})
|
||||
|
||||
const outputFile = path.join(tempDir, 'dovi_p5_hdr.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'dovi_p5_input.mp4',
|
||||
outputFile,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
hdr: true,
|
||||
sourceIsHdr: true,
|
||||
sourceHdrType: 'dovi_p5',
|
||||
})
|
||||
|
||||
const filterIdx = executedArgs.indexOf('-filter_complex')
|
||||
expect(filterIdx).toBeGreaterThan(-1)
|
||||
const filterComplex = executedArgs[filterIdx + 1]
|
||||
expect(filterComplex).not.toContain('libplacebo')
|
||||
expect(executedArgs).toContain('-color_primaries')
|
||||
expect(executedArgs).toContain('bt2020')
|
||||
expect(executedArgs).toContain('-color_trc')
|
||||
expect(executedArgs).toContain('smpte2084')
|
||||
})
|
||||
|
||||
it('generateSprite uses split=2 filterComplex for HDR inputs', async () => {
|
||||
let executedArgs: string[] = []
|
||||
;(
|
||||
child_process.execFile as unknown as {
|
||||
mockImplementation: (
|
||||
fn: (
|
||||
file: string,
|
||||
args: string[],
|
||||
cb: (err: Error | null, res: { stdout: string; stderr: string }) => void,
|
||||
) => unknown,
|
||||
) => void
|
||||
}
|
||||
).mockImplementation((_file, args, cb) => {
|
||||
if (args.includes('-filters')) {
|
||||
cb(null, { stdout: ' ... zscale ... \n ... tonemap ... ', stderr: '' })
|
||||
return {}
|
||||
}
|
||||
executedArgs = args
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
return {}
|
||||
})
|
||||
|
||||
const spritePath = path.join(tempDir, 'sprite.webp')
|
||||
const posterPath = path.join(tempDir, 'poster.webp')
|
||||
await transcodeService.generateSprite('input.mp4', spritePath, posterPath, 100, undefined, {
|
||||
isHdr: true,
|
||||
hdrType: 'pq',
|
||||
colorTransfer: 'smpte2084',
|
||||
})
|
||||
|
||||
const filterIdx = executedArgs.indexOf('-filter_complex')
|
||||
expect(filterIdx).toBeGreaterThan(-1)
|
||||
const filterStr = executedArgs[filterIdx + 1]
|
||||
expect(filterStr).toContain('split=2[v_sprite][v_thumb]')
|
||||
expect(filterStr).toContain('[v_sprite]fps=')
|
||||
expect(filterStr).toContain('[v_thumb]scale=')
|
||||
})
|
||||
|
||||
it('generateSprite uses split=2 filterComplex for SDR inputs', async () => {
|
||||
let executedArgs: string[] = []
|
||||
;(
|
||||
child_process.execFile as unknown as {
|
||||
mockImplementation: (
|
||||
fn: (
|
||||
file: string,
|
||||
args: string[],
|
||||
cb: (err: Error | null, res: { stdout: string; stderr: string }) => void,
|
||||
) => unknown,
|
||||
) => void
|
||||
}
|
||||
).mockImplementation((_file, args, cb) => {
|
||||
executedArgs = args
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
return {}
|
||||
})
|
||||
|
||||
const spritePath = path.join(tempDir, 'sprite.webp')
|
||||
const posterPath = path.join(tempDir, 'poster.webp')
|
||||
await transcodeService.generateSprite('input.mp4', spritePath, posterPath, 100)
|
||||
|
||||
const filterIdx = executedArgs.indexOf('-filter_complex')
|
||||
expect(filterIdx).toBeGreaterThan(-1)
|
||||
const filterStr = executedArgs[filterIdx + 1]
|
||||
expect(filterStr).toContain('[0:v]split=2[v_sprite][v_thumb]')
|
||||
expect(filterStr).toContain('[v_sprite]fps=')
|
||||
expect(filterStr).toContain('[v_thumb]scale=')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -87,6 +87,8 @@ export function parseCsvContent(content: string): string[][] {
|
||||
}
|
||||
}
|
||||
|
||||
export type HdrType = 'pq' | 'hlg' | 'dovi_p5' | 'dovi_p8' | 'sdr'
|
||||
|
||||
export interface MediaMetadata {
|
||||
originalWidth: number
|
||||
originalHeight: number
|
||||
@@ -103,6 +105,14 @@ export interface MediaMetadata {
|
||||
audioSampleRate?: number
|
||||
audioBitDepth?: number
|
||||
mimeType: string
|
||||
colorTransfer?: string
|
||||
colorPrimaries?: string
|
||||
colorSpace?: string
|
||||
isHdr?: boolean
|
||||
hdrType?: HdrType
|
||||
dvProfile?: number
|
||||
dvCompatibilityId?: number
|
||||
rotation?: number
|
||||
}
|
||||
|
||||
export interface TranscodeVideoParams {
|
||||
@@ -118,6 +128,12 @@ export interface TranscodeVideoParams {
|
||||
sourceVideoBitrate?: number
|
||||
threads?: number
|
||||
signal?: AbortSignal
|
||||
hdr?: boolean
|
||||
sourceIsHdr?: boolean
|
||||
sourceHdrType?: HdrType
|
||||
sourceColorTransfer?: string
|
||||
sourceColorPrimaries?: string
|
||||
sourceColorSpace?: string
|
||||
}
|
||||
|
||||
export interface EncoderConfig {
|
||||
@@ -224,6 +240,24 @@ export function calculateMaxBitrate(
|
||||
}
|
||||
}
|
||||
|
||||
export function buildSdrToneMapFilterChain(options: {
|
||||
hdrType?: HdrType
|
||||
availableFilters?: Set<string>
|
||||
colorTransfer?: string
|
||||
}): string {
|
||||
if (options.availableFilters) {
|
||||
if (!options.availableFilters.has('zscale') || !options.availableFilters.has('tonemap')) {
|
||||
throw new Error('zscale and tonemap filters are required for HDR tone mapping')
|
||||
}
|
||||
}
|
||||
|
||||
const tin =
|
||||
options.hdrType === 'hlg' || options.colorTransfer === 'arib-std-b67'
|
||||
? 'arib-std-b67'
|
||||
: 'smpte2084'
|
||||
return `setparams=color_primaries=bt2020:color_trc=${tin}:colorspace=bt2020nc,zscale=tin=${tin}:pin=bt2020:min=bt2020nc:t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0:peak=100,zscale=t=bt709:m=bt709:out_range=full,format=yuv420p`
|
||||
}
|
||||
|
||||
export interface ExtractVideoFramesParams {
|
||||
inputFile: string
|
||||
outputDir: string
|
||||
@@ -432,9 +466,101 @@ export class TranscodeService {
|
||||
}
|
||||
}
|
||||
|
||||
const colorTransfer =
|
||||
typeof videoStream.color_transfer === 'string'
|
||||
? videoStream.color_transfer.toLowerCase()
|
||||
: undefined
|
||||
const colorPrimaries =
|
||||
typeof videoStream.color_primaries === 'string'
|
||||
? videoStream.color_primaries.toLowerCase()
|
||||
: undefined
|
||||
const colorSpace =
|
||||
typeof videoStream.color_space === 'string'
|
||||
? videoStream.color_space.toLowerCase()
|
||||
: undefined
|
||||
|
||||
let dvProfile: number | undefined
|
||||
let dvCompatibilityId: number | undefined
|
||||
|
||||
if (Array.isArray(videoStream.side_data_list)) {
|
||||
const dovi = videoStream.side_data_list.find(
|
||||
(sd: unknown): sd is Record<string, unknown> =>
|
||||
typeof (sd as Record<string, unknown>)?.side_data_type === 'string' &&
|
||||
String((sd as Record<string, unknown>).side_data_type)
|
||||
.toLowerCase()
|
||||
.includes('dovi'),
|
||||
)
|
||||
if (dovi) {
|
||||
dvProfile = this.safeParseInt(dovi.dv_profile)
|
||||
dvCompatibilityId = this.safeParseInt(dovi.dv_bl_signal_compatibility_id)
|
||||
}
|
||||
}
|
||||
|
||||
let isHdr: boolean
|
||||
let hdrType: HdrType
|
||||
|
||||
if (dvProfile === 5) {
|
||||
isHdr = true
|
||||
hdrType = 'dovi_p5'
|
||||
} else if (dvProfile !== undefined) {
|
||||
if (colorTransfer === 'smpte2084') {
|
||||
isHdr = true
|
||||
hdrType = 'pq'
|
||||
} else if (colorTransfer === 'arib-std-b67') {
|
||||
isHdr = true
|
||||
hdrType = 'hlg'
|
||||
} else {
|
||||
isHdr = false
|
||||
hdrType = 'sdr'
|
||||
}
|
||||
} else {
|
||||
if (colorTransfer === 'smpte2084') {
|
||||
isHdr = true
|
||||
hdrType = 'pq'
|
||||
} else if (colorTransfer === 'arib-std-b67') {
|
||||
isHdr = true
|
||||
hdrType = 'hlg'
|
||||
} else {
|
||||
isHdr = false
|
||||
hdrType = 'sdr'
|
||||
}
|
||||
}
|
||||
|
||||
let rotation = 0
|
||||
|
||||
if (Array.isArray(videoStream.side_data_list)) {
|
||||
const displayMatrix = videoStream.side_data_list.find(
|
||||
(sd: unknown): sd is Record<string, unknown> =>
|
||||
typeof (sd as Record<string, unknown>)?.side_data_type === 'string' &&
|
||||
String((sd as Record<string, unknown>).side_data_type).toLowerCase() === 'display matrix',
|
||||
)
|
||||
if (displayMatrix && typeof displayMatrix.rotation === 'number') {
|
||||
rotation = displayMatrix.rotation
|
||||
}
|
||||
}
|
||||
|
||||
if (!rotation) {
|
||||
const rotateTag = videoStream.tags?.rotate || info.format?.tags?.rotate
|
||||
if (rotateTag) {
|
||||
const parsed = parseFloat(rotateTag)
|
||||
if (Number.isFinite(parsed)) {
|
||||
rotation = parsed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const normalizedRotation = ((Math.round(rotation) % 360) + 360) % 360
|
||||
const isRotatedVertical = normalizedRotation === 90 || normalizedRotation === 270
|
||||
|
||||
const rawWidth = typeof videoStream.width === 'number' ? videoStream.width : 0
|
||||
const rawHeight = typeof videoStream.height === 'number' ? videoStream.height : 0
|
||||
const originalWidth = isRotatedVertical ? rawHeight : rawWidth
|
||||
const originalHeight = isRotatedVertical ? rawWidth : rawHeight
|
||||
|
||||
return {
|
||||
originalWidth: videoStream.width,
|
||||
originalHeight: videoStream.height,
|
||||
originalWidth,
|
||||
originalHeight,
|
||||
rotation: rotation || undefined,
|
||||
duration,
|
||||
bitRate: parseFloat(info.format.bit_rate),
|
||||
videoBitRate,
|
||||
@@ -450,6 +576,13 @@ export class TranscodeService {
|
||||
this.safeParseInt(audioStream?.bits_per_raw_sample) ??
|
||||
this.safeParseInt(audioStream?.bits_per_sample),
|
||||
mimeType: '',
|
||||
colorTransfer,
|
||||
colorPrimaries,
|
||||
colorSpace,
|
||||
isHdr,
|
||||
hdrType,
|
||||
dvProfile,
|
||||
dvCompatibilityId,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -539,6 +672,34 @@ export class TranscodeService {
|
||||
}
|
||||
}
|
||||
|
||||
private availableFiltersCache: Set<string> | null = null
|
||||
|
||||
clearFiltersCache(): void {
|
||||
this.availableFiltersCache = null
|
||||
}
|
||||
|
||||
async getAvailableFilters(): Promise<Set<string>> {
|
||||
if (this.availableFiltersCache) {
|
||||
return this.availableFiltersCache
|
||||
}
|
||||
try {
|
||||
const { stdout } = await execFileAsync('ffmpeg', ['-filters'])
|
||||
const filters = new Set<string>()
|
||||
const lines = stdout.split('\n')
|
||||
for (const line of lines) {
|
||||
const match = line.match(/^\s*[A-Z.]{2,4}\s+([a-zA-Z0-9_-]+)/)
|
||||
if (match) {
|
||||
filters.add(match[1])
|
||||
}
|
||||
}
|
||||
this.availableFiltersCache = filters
|
||||
return filters
|
||||
} catch (err) {
|
||||
console.warn('Failed to probe ffmpeg filters:', err)
|
||||
return new Set<string>()
|
||||
}
|
||||
}
|
||||
|
||||
async selectH264Encoder(
|
||||
hardwareAcceleration?: 'off' | 'auto',
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
@@ -559,14 +720,22 @@ export class TranscodeService {
|
||||
}
|
||||
|
||||
async transcodeVideo(params: TranscodeVideoParams): Promise<void> {
|
||||
const isSourceHdr =
|
||||
params.sourceIsHdr ||
|
||||
params.sourceHdrType === 'pq' ||
|
||||
params.sourceHdrType === 'hlg' ||
|
||||
params.sourceHdrType === 'dovi_p5'
|
||||
const isHdrOutput = Boolean(params.hdr)
|
||||
|
||||
let filterComplex: string
|
||||
const args: string[] = ['-i', params.inputFile]
|
||||
const baseScale = `scale=w=${params.width}:h=${params.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'`
|
||||
|
||||
if (params.overlayFile) {
|
||||
args.push('-i', params.overlayFile)
|
||||
filterComplex = `[0:v]scale=${params.width}:${params.height}[vscaled];[vscaled][1:v]overlay=0:0`
|
||||
} else {
|
||||
filterComplex = `[0:v]scale=w=${params.width}:h=${params.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'`
|
||||
filterComplex = `[0:v]${baseScale}`
|
||||
}
|
||||
|
||||
if (params.frameRate) {
|
||||
@@ -625,6 +794,15 @@ export class TranscodeService {
|
||||
|
||||
args.push('-pix_fmt', 'yuv420p')
|
||||
|
||||
if (isSourceHdr && isHdrOutput) {
|
||||
const isHlg = params.sourceHdrType === 'hlg' || params.sourceColorTransfer === 'arib-std-b67'
|
||||
const trc = isHlg ? 'arib-std-b67' : 'smpte2084'
|
||||
args.push('-color_primaries', 'bt2020', '-color_trc', trc, '-colorspace', 'bt2020nc')
|
||||
if (encoder.name === 'libx264') {
|
||||
args.push('-x264-params', `colorprim=bt2020:transfer=${trc}:colormatrix=bt2020nc`)
|
||||
}
|
||||
}
|
||||
|
||||
if (!params.disableAudio) {
|
||||
args.push('-c:a', 'aac', '-b:a', '128k')
|
||||
}
|
||||
@@ -749,9 +927,22 @@ export class TranscodeService {
|
||||
outputPoster: string,
|
||||
duration: number,
|
||||
signal?: AbortSignal,
|
||||
hdrOptions?: { isHdr?: boolean; hdrType?: HdrType; colorTransfer?: string },
|
||||
): Promise<void> {
|
||||
const spriteFps = 100 / duration
|
||||
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]`
|
||||
let filterComplex: string
|
||||
|
||||
if (hdrOptions?.isHdr) {
|
||||
const availableFilters = await this.getAvailableFilters()
|
||||
const tonemap = buildSdrToneMapFilterChain({
|
||||
hdrType: hdrOptions.hdrType,
|
||||
colorTransfer: hdrOptions.colorTransfer,
|
||||
availableFilters,
|
||||
})
|
||||
filterComplex = `[0:v]${tonemap},split=2[v_sprite][v_thumb];[v_sprite]fps=${spriteFps},scale=w=300:h=-2,tile=10x10[sprite_out];[v_thumb]scale=-2:300:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
|
||||
} else {
|
||||
filterComplex = `[0:v]split=2[v_sprite][v_thumb];[v_sprite]fps=${spriteFps},scale=w=300:h=-2,tile=10x10[sprite_out];[v_thumb]scale=-2:300:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
|
||||
}
|
||||
|
||||
const args = [
|
||||
'-i',
|
||||
|
||||
Reference in New Issue
Block a user