mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 20:34:28 +00:00
feat(transcode): add HLS live streaming support (#436)
* feat(transcode): add HLS live streaming support * fix(hls): resolve version stacks for public HLS and add workflow E2E test
This commit is contained in:
@@ -16,6 +16,7 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
presign: vi.fn().mockResolvedValue('http://mock-s3-url'),
|
||||
putObject: vi.fn().mockResolvedValue(undefined),
|
||||
getObject: vi.fn().mockResolvedValue({ buffer: Buffer.from('') }),
|
||||
deleteObject: vi.fn().mockResolvedValue(1),
|
||||
deletePrefix: vi.fn().mockResolvedValue(1),
|
||||
copyObject: vi.fn().mockResolvedValue(undefined),
|
||||
@@ -5251,4 +5252,111 @@ describe('AssetService — natural sort by name', () => {
|
||||
expect(restored?.status).toBe(AssetStatus.processed)
|
||||
})
|
||||
})
|
||||
|
||||
describe('HLS playlists', () => {
|
||||
const setupHlsAssets = async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'hls-team-' + Date.now() } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'hls-proj-' + Date.now(), teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'root',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.processed,
|
||||
},
|
||||
})
|
||||
return { team, project, rootFolder }
|
||||
}
|
||||
|
||||
it('getHlsMasterPlaylist throws 404 if asset is not HLS', async () => {
|
||||
const { project, rootFolder } = await setupHlsAssets()
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'regular.mp4',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
status: AssetStatus.processed,
|
||||
media: {
|
||||
isHls: false,
|
||||
} as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(assetService.getHlsMasterPlaylist({ assetId: file.id })).rejects.toThrow(
|
||||
'HLS playlist not found',
|
||||
)
|
||||
})
|
||||
|
||||
it('getHlsMasterPlaylist returns playlist string when asset is HLS', async () => {
|
||||
const { project, rootFolder } = await setupHlsAssets()
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'hls-video.mp4',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
status: AssetStatus.processed,
|
||||
media: {
|
||||
isHls: true,
|
||||
hls: {
|
||||
key: 'files/asset/hls/master.m3u8',
|
||||
resolutions: [
|
||||
{ resolution: '1080p', width: 1920, height: 1080 },
|
||||
{ resolution: '720p', width: 1280, height: 720 },
|
||||
],
|
||||
},
|
||||
} as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
|
||||
const masterContent = '#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=4628000\n1080p/index.m3u8\n'
|
||||
vi.mocked(s3Service.getObject).mockResolvedValueOnce({
|
||||
buffer: Buffer.from(masterContent),
|
||||
} as unknown as Awaited<ReturnType<typeof s3Service.getObject>>)
|
||||
|
||||
const res = await assetService.getHlsMasterPlaylist({ assetId: file.id })
|
||||
expect(res).toBe(masterContent)
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'files/asset/hls/master.m3u8',
|
||||
)
|
||||
})
|
||||
|
||||
it('getHlsVariantPlaylist fetches and rewrites segment URLs', async () => {
|
||||
const { project, rootFolder } = await setupHlsAssets()
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'hls-video.mp4',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
status: AssetStatus.processed,
|
||||
media: {
|
||||
isHls: true,
|
||||
hls: {
|
||||
key: 'files/asset/hls/master.m3u8',
|
||||
resolutions: [{ resolution: '1080p', width: 1920, height: 1080 }],
|
||||
},
|
||||
} as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
|
||||
const sampleVariant = '#EXTM3U\n#EXT-X-MAP:URI="init.mp4"\nsegment_000.m4s\n'
|
||||
vi.mocked(s3Service.getObject).mockResolvedValueOnce({
|
||||
buffer: Buffer.from(sampleVariant),
|
||||
} as unknown as Awaited<ReturnType<typeof s3Service.getObject>>)
|
||||
vi.mocked(s3Service.presign).mockResolvedValue('http://mock-s3-url')
|
||||
|
||||
const variant = await assetService.getHlsVariantPlaylist({
|
||||
assetId: file.id,
|
||||
resolution: '1080p',
|
||||
})
|
||||
expect(variant).toBeDefined()
|
||||
expect(variant).toContain('#EXT-X-MAP:URI="http://mock-s3-url"')
|
||||
expect(variant).toContain('http://mock-s3-url')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -57,6 +57,7 @@ import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import path from 'path'
|
||||
import { stemFromKey } from '@shumai/core/src/utils/filename'
|
||||
import { rewriteM3u8WithPresignedUrls } from '@shumai/core/src/transcode/transcode'
|
||||
|
||||
export const assetInclude = {
|
||||
creator: true,
|
||||
@@ -2386,6 +2387,9 @@ export class AssetService {
|
||||
'GET',
|
||||
)
|
||||
}
|
||||
if (media && media.isHls && media.hls?.key) {
|
||||
media.hls.url = `/api/files/${latestVersion.id}/m3u8/master.m3u8`
|
||||
}
|
||||
|
||||
const key = latestVersion.storageKey?.key
|
||||
if (key) {
|
||||
@@ -3196,6 +3200,95 @@ export class AssetService {
|
||||
req,
|
||||
)
|
||||
}
|
||||
|
||||
async getHlsMasterPlaylist(params: {
|
||||
assetId: string
|
||||
watermarkConfigId?: string | null
|
||||
}): Promise<string> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const targetAssetId = await this.resolveLatestVersionId(params.assetId)
|
||||
|
||||
if (params.watermarkConfigId) {
|
||||
const wf = await this.prismaClient.watermarkFile.findUnique({
|
||||
where: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
assetId_watermarkConfigId: {
|
||||
assetId: targetAssetId,
|
||||
watermarkConfigId: params.watermarkConfigId,
|
||||
},
|
||||
},
|
||||
})
|
||||
const media = wf?.media as PrismaJson.MediaInfo | null
|
||||
if (!media?.isHls || !media.hls?.key) {
|
||||
throw new HTTPException(404, { message: 'HLS playlist not found' })
|
||||
}
|
||||
const obj = await s3Service.getObject(bucket, media.hls.key)
|
||||
return obj.buffer.toString('utf-8')
|
||||
}
|
||||
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: targetAssetId },
|
||||
})
|
||||
if (!asset) {
|
||||
throw new HTTPException(404, { message: 'Asset not found' })
|
||||
}
|
||||
const media = asset.media as PrismaJson.MediaInfo | null
|
||||
if (!media?.isHls || !media.hls?.key) {
|
||||
throw new HTTPException(404, { message: 'HLS playlist not found' })
|
||||
}
|
||||
const obj = await s3Service.getObject(bucket, media.hls.key)
|
||||
return obj.buffer.toString('utf-8')
|
||||
}
|
||||
|
||||
async getHlsVariantPlaylist(params: {
|
||||
assetId: string
|
||||
resolution: string
|
||||
watermarkConfigId?: string | null
|
||||
}): Promise<string> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
if (!/^\d+p$/.test(params.resolution)) {
|
||||
throw new HTTPException(400, { message: 'Invalid resolution format' })
|
||||
}
|
||||
|
||||
const targetAssetId = await this.resolveLatestVersionId(params.assetId)
|
||||
let media: PrismaJson.MediaInfo | null
|
||||
|
||||
if (params.watermarkConfigId) {
|
||||
const wf = await this.prismaClient.watermarkFile.findUnique({
|
||||
where: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
assetId_watermarkConfigId: {
|
||||
assetId: targetAssetId,
|
||||
watermarkConfigId: params.watermarkConfigId,
|
||||
},
|
||||
},
|
||||
})
|
||||
media = (wf?.media as PrismaJson.MediaInfo | null) ?? null
|
||||
} else {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: targetAssetId },
|
||||
})
|
||||
if (!asset) {
|
||||
throw new HTTPException(404, { message: 'Asset not found' })
|
||||
}
|
||||
media = (asset.media as PrismaJson.MediaInfo | null) ?? null
|
||||
}
|
||||
|
||||
if (!media?.isHls || !media.hls?.key) {
|
||||
throw new HTTPException(404, { message: 'HLS playlist not found' })
|
||||
}
|
||||
|
||||
const matchedRes = media.hls.resolutions?.find((r) => r.resolution === params.resolution)
|
||||
const variantKey =
|
||||
matchedRes?.key ||
|
||||
path.posix.join(path.posix.dirname(media.hls.key), params.resolution, 'index.m3u8')
|
||||
|
||||
const obj = await s3Service.getObject(bucket, variantKey)
|
||||
const rawM3u8 = obj.buffer.toString('utf-8')
|
||||
const s3Prefix = path.posix.dirname(variantKey)
|
||||
|
||||
return await rewriteM3u8WithPresignedUrls(rawM3u8, s3Prefix, bucket)
|
||||
}
|
||||
}
|
||||
|
||||
export const assetService = new AssetService()
|
||||
|
||||
@@ -371,6 +371,8 @@ describe('TeamService', () => {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'off',
|
||||
threads: 0,
|
||||
hlsEnabled: false,
|
||||
hlsResolutions: ['480p', '720p', '1080p'],
|
||||
},
|
||||
appearance: { hideAgent: false },
|
||||
})
|
||||
@@ -385,6 +387,8 @@ describe('TeamService', () => {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'off',
|
||||
threads: 0,
|
||||
hlsEnabled: false,
|
||||
hlsResolutions: ['480p', '720p', '1080p'],
|
||||
},
|
||||
appearance: { hideAgent: false },
|
||||
})
|
||||
@@ -392,6 +396,12 @@ describe('TeamService', () => {
|
||||
await teamService.updateSettings(team.id, 'transcode.videoStrategy', 'all')
|
||||
await teamService.updateSettings(team.id, 'transcode.hardwareAcceleration', 'auto')
|
||||
await teamService.updateSettings(team.id, 'transcode.threads', 4)
|
||||
await teamService.updateSettings(team.id, 'transcode.hlsEnabled', true)
|
||||
await teamService.updateSettings(team.id, 'transcode.hlsResolutions', [
|
||||
'720p',
|
||||
'1080p',
|
||||
'2160p',
|
||||
])
|
||||
await teamService.updateSettings(team.id, 'appearance.hideAgent', true)
|
||||
|
||||
const finalSettings = await teamService.getSettings(team.id)
|
||||
@@ -401,6 +411,8 @@ describe('TeamService', () => {
|
||||
videoStrategy: 'all',
|
||||
hardwareAcceleration: 'auto',
|
||||
threads: 4,
|
||||
hlsEnabled: true,
|
||||
hlsResolutions: ['720p', '1080p', '2160p'],
|
||||
},
|
||||
appearance: { hideAgent: true },
|
||||
semanticSearchEnabled: false,
|
||||
|
||||
@@ -314,6 +314,15 @@ export class TeamService {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'off',
|
||||
threads: 0,
|
||||
hlsEnabled: false,
|
||||
hlsResolutions: ['480p', '720p', '1080p'],
|
||||
}
|
||||
} else {
|
||||
if (settings.transcode.hlsEnabled === undefined) {
|
||||
settings.transcode.hlsEnabled = false
|
||||
}
|
||||
if (!settings.transcode.hlsResolutions) {
|
||||
settings.transcode.hlsResolutions = ['480p', '720p', '1080p']
|
||||
}
|
||||
}
|
||||
|
||||
@@ -354,6 +363,20 @@ export class TeamService {
|
||||
}
|
||||
settings.transcode.threads = Number(value)
|
||||
delete settings['transcode.threads']
|
||||
} else if (key === 'transcode.hlsEnabled') {
|
||||
if (!settings.transcode) {
|
||||
settings.transcode = {}
|
||||
}
|
||||
settings.transcode.hlsEnabled = Boolean(value)
|
||||
delete settings['transcode.hlsEnabled']
|
||||
} else if (key === 'transcode.hlsResolutions') {
|
||||
if (!settings.transcode) {
|
||||
settings.transcode = {}
|
||||
}
|
||||
settings.transcode.hlsResolutions = value as NonNullable<
|
||||
TeamSettingsResponse['transcode']
|
||||
>['hlsResolutions']
|
||||
delete settings['transcode.hlsResolutions']
|
||||
} else if (key === 'appearance.hideAgent') {
|
||||
if (!settings.appearance) {
|
||||
settings.appearance = {}
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
buildSdrToneMapFilterChain,
|
||||
getVaapiDevice,
|
||||
parseBitrateKbps,
|
||||
buildHlsMasterPlaylist,
|
||||
rewriteM3u8WithPresignedUrls,
|
||||
} from './transcode'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
@@ -27,6 +29,9 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
downloadToFile: vi.fn(),
|
||||
putObject: vi.fn(),
|
||||
resolveInput: vi.fn().mockImplementation(async (_bucket, key) => `http://mock-storage/${key}`),
|
||||
presign: vi
|
||||
.fn()
|
||||
.mockImplementation(async (_bucket, key) => `https://presigned.example.com/${key}`),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -3376,4 +3381,106 @@ describe('TranscodeService', () => {
|
||||
).rejects.toThrow('Poster generation cancelled')
|
||||
})
|
||||
})
|
||||
|
||||
describe('HLS utilities', () => {
|
||||
it('builds master playlist correctly with bandwidth and codecs', () => {
|
||||
const playlist = buildHlsMasterPlaylist([
|
||||
{ resolution: '1080p', width: 1920, height: 1080, bitrateBps: 4_500_000, isHdr: false },
|
||||
{ resolution: '720p', width: 1280, height: 720, bitrateBps: 2_500_000, isHdr: false },
|
||||
{ resolution: '480p', width: 854, height: 480, bitrateBps: 1_200_000, isHdr: false },
|
||||
])
|
||||
|
||||
expect(playlist).toContain('#EXTM3U')
|
||||
expect(playlist).toContain('#EXT-X-VERSION:7')
|
||||
expect(playlist).toContain('#EXT-X-INDEPENDENT-SEGMENTS')
|
||||
expect(playlist).toContain('RESOLUTION=1920x1080')
|
||||
expect(playlist).toContain('BANDWIDTH=4628000')
|
||||
expect(playlist).toContain('1080p/index.m3u8')
|
||||
expect(playlist).toContain('RESOLUTION=1280x720')
|
||||
expect(playlist).toContain('720p/index.m3u8')
|
||||
expect(playlist).toContain('RESOLUTION=854x480')
|
||||
expect(playlist).toContain('480p/index.m3u8')
|
||||
})
|
||||
|
||||
it('builds master playlist with HDR codec when isHdr is true', () => {
|
||||
const playlist = buildHlsMasterPlaylist([
|
||||
{ resolution: '1080p', width: 1920, height: 1080, bitrateBps: 4_500_000, isHdr: true },
|
||||
])
|
||||
expect(playlist).toContain('CODECS="avc1.640028,mp4a.40.2"')
|
||||
})
|
||||
|
||||
it('rewrites variant m3u8 playlist with presigned S3 URLs', async () => {
|
||||
const sampleM3u8 = [
|
||||
'#EXTM3U',
|
||||
'#EXT-X-VERSION:7',
|
||||
'#EXT-X-TARGETDURATION:4',
|
||||
'#EXT-X-MEDIA-SEQUENCE:0',
|
||||
'#EXT-X-PLAYLIST-TYPE:VOD',
|
||||
'#EXT-X-MAP:URI="init.mp4"',
|
||||
'#EXTINF:4.000000,',
|
||||
'segment_000.m4s',
|
||||
'#EXTINF:4.000000,',
|
||||
'segment_001.m4s',
|
||||
'#EXT-X-ENDLIST',
|
||||
].join('\n')
|
||||
|
||||
const rewritten = await rewriteM3u8WithPresignedUrls(
|
||||
sampleM3u8,
|
||||
'files/asset1/hls/1080p',
|
||||
'shumai',
|
||||
)
|
||||
|
||||
expect(rewritten).toContain(
|
||||
'#EXT-X-MAP:URI="https://presigned.example.com/files/asset1/hls/1080p/init.mp4"',
|
||||
)
|
||||
expect(rewritten).toContain(
|
||||
'https://presigned.example.com/files/asset1/hls/1080p/segment_000.m4s',
|
||||
)
|
||||
expect(rewritten).toContain(
|
||||
'https://presigned.example.com/files/asset1/hls/1080p/segment_001.m4s',
|
||||
)
|
||||
expect(rewritten).toContain('#EXTINF:4.000000,')
|
||||
expect(rewritten).toContain('#EXT-X-ENDLIST')
|
||||
})
|
||||
|
||||
it('executes transcodeHlsRendition with correct fMP4 CMAF parameters', async () => {
|
||||
let executedArgs: string[] = []
|
||||
// child_process.execFile mock signature
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(child_process.execFile as any).mockImplementation(
|
||||
(
|
||||
_file: string,
|
||||
args: string[],
|
||||
cb: (err: unknown, result: { stdout: string; stderr: string }) => void,
|
||||
) => {
|
||||
executedArgs = args
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
},
|
||||
)
|
||||
|
||||
const outputDir = path.join(tempDir, 'hls_output')
|
||||
fs.mkdirSync(outputDir, { recursive: true })
|
||||
|
||||
await transcodeService.transcodeHlsRendition({
|
||||
inputFile: 'input.mp4',
|
||||
outputDir,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
frameRate: 30,
|
||||
hardwareAcceleration: 'off',
|
||||
threads: 4,
|
||||
})
|
||||
|
||||
expect(executedArgs).toContain('-f')
|
||||
expect(executedArgs).toContain('hls')
|
||||
expect(executedArgs).toContain('-hls_segment_type')
|
||||
expect(executedArgs).toContain('fmp4')
|
||||
expect(executedArgs).toContain('-hls_fmp4_init_filename')
|
||||
expect(executedArgs).toContain('init.mp4')
|
||||
expect(executedArgs).toContain('-flags')
|
||||
expect(executedArgs).toContain('+cgop')
|
||||
expect(executedArgs).toContain('-threads')
|
||||
expect(executedArgs).toContain('4')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -146,6 +146,28 @@ export interface TranscodeVideoParams {
|
||||
sourceColorSpace?: string
|
||||
}
|
||||
|
||||
export interface TranscodeHlsRenditionParams {
|
||||
inputFile: string
|
||||
outputDir: string
|
||||
width: number
|
||||
height: number
|
||||
frameRate?: number | string
|
||||
disableAudio?: boolean
|
||||
overlayFile?: string
|
||||
hardwareAcceleration?: 'off' | 'auto'
|
||||
videoBitrate?: string
|
||||
sourceVideoBitrate?: number
|
||||
threads?: number
|
||||
signal?: AbortSignal
|
||||
hdr?: boolean
|
||||
sourceIsHdr?: boolean
|
||||
sourceHdrType?: HdrType
|
||||
sourceColorTransfer?: string
|
||||
sourceColorPrimaries?: string
|
||||
sourceColorSpace?: string
|
||||
segmentDuration?: number
|
||||
}
|
||||
|
||||
export interface EncoderConfig {
|
||||
name: string
|
||||
presetArgs: string[]
|
||||
@@ -241,9 +263,11 @@ export function getDefaultBitrateBps(height: number, width?: number): number {
|
||||
const effectiveHeight = shortSide > 0 ? shortSide : height
|
||||
|
||||
if (effectiveHeight >= 2160 || longSide >= 3840) return 12_000_000
|
||||
if (effectiveHeight >= 1440 || longSide >= 2560) return 8_000_000
|
||||
if (effectiveHeight >= 1080 || longSide >= 1920) return 4_500_000
|
||||
if (effectiveHeight >= 720 || longSide >= 1280) return 2_500_000
|
||||
if (effectiveHeight >= 540 || longSide >= 960) return 1_200_000
|
||||
if (effectiveHeight >= 480 || longSide >= 854) return 1_400_000
|
||||
if (effectiveHeight >= 360 || longSide >= 640) return 800_000
|
||||
return 100_000
|
||||
}
|
||||
@@ -1131,6 +1155,301 @@ export class TranscodeService {
|
||||
}
|
||||
}
|
||||
|
||||
async transcodeHlsRendition(params: TranscodeHlsRenditionParams): Promise<void> {
|
||||
const encoder = await this.selectH264Encoder(params.hardwareAcceleration)
|
||||
|
||||
if (encoder.name !== 'libx264') {
|
||||
try {
|
||||
await this.executeFfmpegHlsTranscode(params, encoder)
|
||||
return
|
||||
} catch (err) {
|
||||
if (this.isAbortError(err, params.signal)) {
|
||||
throw err
|
||||
}
|
||||
|
||||
logger.warn(
|
||||
{
|
||||
err,
|
||||
encoder: encoder.name,
|
||||
inputFile: params.inputFile,
|
||||
outputDir: params.outputDir,
|
||||
width: params.width,
|
||||
height: params.height,
|
||||
},
|
||||
'Hardware HLS transcoding failed; falling back to software transcode (libx264)',
|
||||
)
|
||||
|
||||
if (fs.existsSync(params.outputDir)) {
|
||||
try {
|
||||
fs.rmSync(params.outputDir, { recursive: true, force: true })
|
||||
} catch {
|
||||
// ignore unlink errors
|
||||
}
|
||||
}
|
||||
|
||||
await this.executeFfmpegHlsTranscode(params, H264_ENCODER_CONFIGS.libx264)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
await this.executeFfmpegHlsTranscode(params, encoder)
|
||||
}
|
||||
|
||||
private async executeFfmpegHlsTranscode(
|
||||
params: TranscodeHlsRenditionParams,
|
||||
encoder: EncoderConfig,
|
||||
): Promise<void> {
|
||||
fs.mkdirSync(params.outputDir, { recursive: true })
|
||||
|
||||
const isSourceHdr =
|
||||
params.sourceIsHdr ||
|
||||
params.sourceHdrType === 'pq' ||
|
||||
params.sourceHdrType === 'hlg' ||
|
||||
params.sourceHdrType === 'dovi_p5'
|
||||
const isHdrOutput = Boolean(params.hdr)
|
||||
|
||||
const isVaapi = encoder.name === 'h264_vaapi'
|
||||
const vaapiDevice = isVaapi ? (this.getVaapiDevice() ?? '/dev/dri/renderD128') : undefined
|
||||
|
||||
const segmentDuration = params.segmentDuration || 4
|
||||
let calculatedFps = 30
|
||||
if (params.frameRate) {
|
||||
if (typeof params.frameRate === 'number') {
|
||||
calculatedFps = params.frameRate
|
||||
} else {
|
||||
const parts = params.frameRate.split('/')
|
||||
if (parts.length === 2) {
|
||||
calculatedFps = parseFloat(parts[0]) / parseFloat(parts[1])
|
||||
} else {
|
||||
calculatedFps = parseFloat(params.frameRate)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!Number.isFinite(calculatedFps) || calculatedFps <= 0) {
|
||||
calculatedFps = 30
|
||||
}
|
||||
const gopSize = Math.max(1, Math.round(calculatedFps * segmentDuration))
|
||||
|
||||
logger.info(
|
||||
{
|
||||
encoder: encoder.name,
|
||||
hardwareAcceleration: params.hardwareAcceleration ?? 'off',
|
||||
inputFile: params.inputFile,
|
||||
outputDir: params.outputDir,
|
||||
width: params.width,
|
||||
height: params.height,
|
||||
segmentDuration,
|
||||
gopSize,
|
||||
},
|
||||
'Starting HLS rendition transcoding',
|
||||
)
|
||||
|
||||
let filterComplex: string
|
||||
const args: string[] = []
|
||||
|
||||
if (isVaapi && vaapiDevice) {
|
||||
args.push('-init_hw_device', `vaapi=accel:${vaapiDevice}`, '-filter_hw_device', 'accel')
|
||||
}
|
||||
|
||||
args.push('-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]${baseScale}`
|
||||
}
|
||||
|
||||
filterComplex += `,fps=${calculatedFps}`
|
||||
|
||||
if (isVaapi) {
|
||||
filterComplex += ',format=nv12,hwupload=extra_hw_frames=64'
|
||||
}
|
||||
filterComplex += '[vout]'
|
||||
|
||||
args.push('-filter_complex', filterComplex, '-map', '[vout]')
|
||||
|
||||
if (!params.disableAudio) {
|
||||
args.push('-map', '0:a?')
|
||||
}
|
||||
|
||||
args.push('-c:v', encoder.name)
|
||||
if (encoder.presetArgs.length > 0) {
|
||||
args.push(...encoder.presetArgs)
|
||||
}
|
||||
|
||||
if (encoder.name === 'h264_videotoolbox') {
|
||||
if (params.videoBitrate) {
|
||||
args.push('-b:v', params.videoBitrate)
|
||||
} else {
|
||||
const targetBps = calculateEffectiveBitrateBps(
|
||||
params.height,
|
||||
params.width,
|
||||
params.sourceVideoBitrate,
|
||||
calculatedFps,
|
||||
)
|
||||
const targetKbps = Math.max(50, Math.round(targetBps / 1000))
|
||||
args.push('-b:v', `${targetKbps}k`)
|
||||
}
|
||||
} else if (isVaapi) {
|
||||
let maxKbps: number
|
||||
if (params.videoBitrate) {
|
||||
maxKbps = parseBitrateKbps(params.videoBitrate)
|
||||
} else {
|
||||
const { maxrate } = calculateMaxBitrate(
|
||||
params.height,
|
||||
params.width,
|
||||
params.sourceVideoBitrate,
|
||||
calculatedFps,
|
||||
)
|
||||
maxKbps = parseInt(maxrate, 10)
|
||||
}
|
||||
const targetKbps = Math.max(25, Math.ceil(maxKbps / 1.45))
|
||||
const minKbps = Math.max(10, Math.round(targetKbps / 2))
|
||||
args.push(
|
||||
'-rc_mode',
|
||||
'3',
|
||||
'-b:v',
|
||||
`${targetKbps}k`,
|
||||
'-minrate',
|
||||
`${minKbps}k`,
|
||||
'-maxrate',
|
||||
`${maxKbps}k`,
|
||||
)
|
||||
} else if (encoder.name === 'h264_qsv') {
|
||||
let maxKbps: number
|
||||
if (params.videoBitrate) {
|
||||
maxKbps = parseBitrateKbps(params.videoBitrate)
|
||||
} else {
|
||||
const { maxrate } = calculateMaxBitrate(
|
||||
params.height,
|
||||
params.width,
|
||||
params.sourceVideoBitrate,
|
||||
calculatedFps,
|
||||
)
|
||||
maxKbps = parseInt(maxrate, 10)
|
||||
}
|
||||
const targetKbps = Math.max(25, Math.ceil(maxKbps / 1.45))
|
||||
args.push('-b:v', `${targetKbps}k`, '-maxrate', `${maxKbps}k`)
|
||||
} else if (encoder.name === 'h264_nvenc') {
|
||||
let maxrateStr: string
|
||||
let bufsizeStr: string
|
||||
if (params.videoBitrate) {
|
||||
const kbps = parseBitrateKbps(params.videoBitrate)
|
||||
maxrateStr = `${kbps}k`
|
||||
bufsizeStr = `${kbps * 2}k`
|
||||
} else {
|
||||
const res = calculateMaxBitrate(
|
||||
params.height,
|
||||
params.width,
|
||||
params.sourceVideoBitrate,
|
||||
calculatedFps,
|
||||
)
|
||||
maxrateStr = res.maxrate
|
||||
bufsizeStr = res.bufsize
|
||||
}
|
||||
args.push(
|
||||
'-rc',
|
||||
'vbr',
|
||||
'-cq',
|
||||
'23',
|
||||
'-maxrate',
|
||||
maxrateStr,
|
||||
'-bufsize',
|
||||
bufsizeStr,
|
||||
'-spatial-aq',
|
||||
'1',
|
||||
'-temporal-aq',
|
||||
'1',
|
||||
)
|
||||
} else {
|
||||
let maxrateStr: string
|
||||
let bufsizeStr: string
|
||||
if (params.videoBitrate) {
|
||||
const kbps = parseBitrateKbps(params.videoBitrate)
|
||||
maxrateStr = `${kbps}k`
|
||||
bufsizeStr = `${kbps * 2}k`
|
||||
} else {
|
||||
const res = calculateMaxBitrate(
|
||||
params.height,
|
||||
params.width,
|
||||
params.sourceVideoBitrate,
|
||||
calculatedFps,
|
||||
)
|
||||
maxrateStr = res.maxrate
|
||||
bufsizeStr = res.bufsize
|
||||
}
|
||||
args.push('-crf', '23', '-maxrate', maxrateStr, '-bufsize', bufsizeStr)
|
||||
}
|
||||
|
||||
if (!isVaapi) {
|
||||
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`)
|
||||
}
|
||||
}
|
||||
|
||||
args.push(
|
||||
'-r',
|
||||
calculatedFps.toString(),
|
||||
'-g',
|
||||
gopSize.toString(),
|
||||
'-keyint_min',
|
||||
gopSize.toString(),
|
||||
'-sc_threshold',
|
||||
'0',
|
||||
'-flags',
|
||||
'+cgop',
|
||||
'-force_key_frames',
|
||||
`expr:gte(t,n_forced*${segmentDuration})`,
|
||||
)
|
||||
|
||||
if (!params.disableAudio) {
|
||||
args.push('-c:a', 'aac', '-b:a', '128k')
|
||||
}
|
||||
|
||||
if (params.threads && params.threads > 0) {
|
||||
args.push('-threads', params.threads.toString())
|
||||
}
|
||||
|
||||
const initFilename = 'init.mp4'
|
||||
const segmentPattern = path.join(params.outputDir, 'segment_%03d.m4s')
|
||||
const playlistFile = path.join(params.outputDir, 'index.m3u8')
|
||||
|
||||
args.push(
|
||||
'-f',
|
||||
'hls',
|
||||
'-hls_time',
|
||||
segmentDuration.toString(),
|
||||
'-hls_playlist_type',
|
||||
'vod',
|
||||
'-hls_segment_type',
|
||||
'fmp4',
|
||||
'-hls_fmp4_init_filename',
|
||||
initFilename,
|
||||
'-hls_segment_filename',
|
||||
segmentPattern,
|
||||
'-max_muxing_queue_size',
|
||||
'1024',
|
||||
playlistFile,
|
||||
)
|
||||
|
||||
if (params.signal) {
|
||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], {
|
||||
signal: params.signal,
|
||||
})
|
||||
} else {
|
||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
||||
}
|
||||
}
|
||||
|
||||
async transcodeImage(
|
||||
inputFile: string | Buffer,
|
||||
outputFile: string,
|
||||
@@ -2385,3 +2704,60 @@ function renderAnnotationsToSvg(
|
||||
}
|
||||
|
||||
export const transcodeService = new TranscodeService()
|
||||
|
||||
export function buildHlsMasterPlaylist(
|
||||
renditions: Array<{
|
||||
resolution: string
|
||||
width: number
|
||||
height: number
|
||||
bitrateBps: number
|
||||
isHdr?: boolean
|
||||
}>,
|
||||
): string {
|
||||
let content = '#EXTM3U\n#EXT-X-VERSION:7\n#EXT-X-INDEPENDENT-SEGMENTS\n'
|
||||
for (const r of renditions) {
|
||||
const bandwidth = r.bitrateBps + 128_000
|
||||
const codecs = r.isHdr ? 'avc1.640028,mp4a.40.2' : 'avc1.64001f,mp4a.40.2'
|
||||
content += `#EXT-X-STREAM-INF:BANDWIDTH=${bandwidth},AVERAGE-BANDWIDTH=${bandwidth},RESOLUTION=${r.width}x${r.height},CODECS="${codecs}"\n`
|
||||
content += `${r.resolution}/index.m3u8\n`
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
export async function rewriteM3u8WithPresignedUrls(
|
||||
m3u8Content: string,
|
||||
s3Prefix: string,
|
||||
bucket: string,
|
||||
): Promise<string> {
|
||||
const lines = m3u8Content.split(/\r?\n/)
|
||||
const rewrittenLines: string[] = []
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed) {
|
||||
rewrittenLines.push(line)
|
||||
continue
|
||||
}
|
||||
|
||||
const mapMatch = trimmed.match(/^#EXT-X-MAP:URI="([^"]+)"(.*)$/)
|
||||
if (mapMatch) {
|
||||
const initRelPath = mapMatch[1]
|
||||
const extra = mapMatch[2] || ''
|
||||
const initKey = path.posix.join(s3Prefix, initRelPath)
|
||||
const presignedUrl = await s3Service.presign(bucket, initKey, 'GET')
|
||||
rewrittenLines.push(`#EXT-X-MAP:URI="${presignedUrl}"${extra}`)
|
||||
continue
|
||||
}
|
||||
|
||||
if (trimmed.endsWith('.m4s') || trimmed.endsWith('.mp4') || trimmed.endsWith('.ts')) {
|
||||
const segmentKey = path.posix.join(s3Prefix, trimmed)
|
||||
const presignedUrl = await s3Service.presign(bucket, segmentKey, 'GET')
|
||||
rewrittenLines.push(presignedUrl)
|
||||
continue
|
||||
}
|
||||
|
||||
rewrittenLines.push(line)
|
||||
}
|
||||
|
||||
return rewrittenLines.join('\n')
|
||||
}
|
||||
|
||||
@@ -198,6 +198,7 @@ describe('UploadService', () => {
|
||||
threads: 0,
|
||||
sprite: true,
|
||||
poster: true,
|
||||
hlsEnabled: false,
|
||||
},
|
||||
})
|
||||
})
|
||||
@@ -249,6 +250,7 @@ describe('UploadService', () => {
|
||||
threads: 12,
|
||||
sprite: true,
|
||||
poster: true,
|
||||
hlsEnabled: false,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
@@ -335,11 +335,14 @@ export class UploadService {
|
||||
if (isVideo) {
|
||||
const strategy = settings?.transcode?.videoStrategy || 'best_match'
|
||||
const hardwareAcceleration = settings?.transcode?.hardwareAcceleration || 'off'
|
||||
const hlsEnabled = settings?.transcode?.hlsEnabled ?? false
|
||||
const hlsResolutions = settings?.transcode?.hlsResolutions
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await new VideoTranscoder(tx as any, asset.id, team.id, projectId)
|
||||
.setStrategy(strategy)
|
||||
.setHardwareAcceleration(hardwareAcceleration)
|
||||
.setThreads(threads)
|
||||
.setHls(hlsEnabled, hlsResolutions)
|
||||
.withSprite()
|
||||
.withPoster()
|
||||
.submit()
|
||||
|
||||
@@ -323,7 +323,7 @@ export class WatermarkService {
|
||||
if (isVideo || isImage) {
|
||||
mediaAssetIds.push(asset.id)
|
||||
}
|
||||
} else if (asset.type === 'folder') {
|
||||
} else if (asset.type === 'folder' || asset.type === 'version_stack') {
|
||||
folderIds.push(asset.id)
|
||||
} else if (asset.type === 'symlink' && asset.targetId) {
|
||||
// Resolve nested symlinks (e.g. folders that contain their own symlinks)
|
||||
|
||||
Reference in New Issue
Block a user