Files
order_site/apps/backend/src/services/file-storage/video-metadata.ts
T

192 lines
6.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 视频时长解析(不依赖 ffprobe)。
*
* 验收视频由前端 Canvas + MediaRecorder 重编码后上传,服务端仍要做一次兜底校验:
* 时长超过配置上限直接拒绝,避免"前端改了参数/绕过页面"后上传超长视频。
*
* 覆盖两种交付格式:
* - MP4:moov/mvhd 里的 timescale + duration(最可靠);
* - WebM:Segment/Info 下的 TimecodeScale + Duration。
* MediaRecorder 生成的 WebM 在部分浏览器里不写 Duration(值为 0 或缺失),
* 此时返回 null,由调用方回退到客户端上报的时长 + 体积上限。
*/
export function readVideoDurationSeconds(data: Buffer, contentType: string): number | null {
const normalized = String(contentType || '')
.trim()
.toLowerCase()
try {
if (normalized === 'video/mp4') return readMp4DurationSeconds(data)
if (normalized === 'video/webm') return readWebmDurationSeconds(data)
} catch {
// 损坏/截断的文件按"时长未知"处理,交给调用方决定。
}
return null
}
type Mp4Box = { payloadStart: number; payloadEnd: number }
function readMp4DurationSeconds(data: Buffer): number | null {
const moov = findMp4Box(data, 0, data.length, 'moov')
if (!moov) return null
const mvhd = findMp4Box(data, moov.payloadStart, moov.payloadEnd, 'mvhd')
if (!mvhd) return null
const payload = mvhd.payloadStart
const version = data[payload]
let timescale = 0
let duration = 0
if (version === 1) {
if (payload + 32 > mvhd.payloadEnd) return null
timescale = data.readUInt32BE(payload + 4 + 8 + 8)
duration = Number(data.readBigUInt64BE(payload + 4 + 8 + 8 + 4))
} else {
if (payload + 20 > mvhd.payloadEnd) return null
timescale = data.readUInt32BE(payload + 4 + 4 + 4)
duration = data.readUInt32BE(payload + 4 + 4 + 4 + 4)
}
if (!timescale || !Number.isFinite(duration) || duration <= 0) return null
const seconds = duration / timescale
return Number.isFinite(seconds) && seconds > 0 ? seconds : null
}
function findMp4Box(data: Buffer, start: number, end: number, type: string): Mp4Box | null {
let offset = start
while (offset + 8 <= end) {
let size = data.readUInt32BE(offset)
const boxType = data.toString('ascii', offset + 4, offset + 8)
let headerSize = 8
if (size === 1) {
if (offset + 16 > end) return null
size = Number(data.readBigUInt64BE(offset + 8))
headerSize = 16
} else if (size === 0) {
size = end - offset
}
if (size < headerSize || offset + size > end) return null
if (boxType === type) {
return { payloadStart: offset + headerSize, payloadEnd: offset + size }
}
offset += size
}
return null
}
const EBML_ID_SEGMENT = 0x18538067
const EBML_ID_INFO = 0x1549a966
const EBML_ID_TIMECODE_SCALE = 0x2ad7b1
const EBML_ID_DURATION = 0x4489
const DEFAULT_TIMECODE_SCALE_NS = 1_000_000
type EbmlElement = { payloadStart: number; payloadEnd: number }
function readWebmDurationSeconds(data: Buffer): number | null {
const segment = findEbmlChild(data, 0, data.length, EBML_ID_SEGMENT)
if (!segment) return null
const info = findEbmlChild(data, segment.payloadStart, segment.payloadEnd, EBML_ID_INFO)
if (!info) return null
const durationElement = findEbmlChild(data, info.payloadStart, info.payloadEnd, EBML_ID_DURATION)
if (!durationElement) return null
const durationValue = readEbmlFloat(data, durationElement)
if (!Number.isFinite(durationValue) || durationValue <= 0) return null
const scaleElement = findEbmlChild(
data,
info.payloadStart,
info.payloadEnd,
EBML_ID_TIMECODE_SCALE,
)
const scaleNs = scaleElement
? readEbmlUint(data, scaleElement) || DEFAULT_TIMECODE_SCALE_NS
: DEFAULT_TIMECODE_SCALE_NS
// Duration 的单位是 TimecodeScale(纳秒),换算成秒。
const seconds = (durationValue * scaleNs) / 1_000_000_000
return Number.isFinite(seconds) && seconds > 0 ? seconds : null
}
function findEbmlChild(
data: Buffer,
start: number,
end: number,
targetId: number,
): EbmlElement | null {
let offset = start
while (offset < end) {
const idInfo = readEbmlId(data, offset, end)
if (!idInfo) return null
const sizeInfo = readEbmlSize(data, idInfo.next, end)
if (!sizeInfo) return null
const payloadStart = sizeInfo.next
const payloadEnd = sizeInfo.unknown ? end : Math.min(end, payloadStart + sizeInfo.size)
if (idInfo.id === targetId) return { payloadStart, payloadEnd }
if (payloadEnd <= payloadStart) return null
offset = payloadEnd
}
return null
}
function readEbmlId(
data: Buffer,
offset: number,
end: number,
): { id: number; next: number } | null {
if (offset >= end) return null
const first = data[offset] as number
let length = 0
for (let index = 0; index < 4; index += 1) {
if (first & (0x80 >> index)) {
length = index + 1
break
}
}
if (!length || offset + length > end) return null
let id = 0
for (let index = 0; index < length; index += 1) {
id = id * 256 + (data[offset + index] as number)
}
return { id, next: offset + length }
}
function readEbmlSize(
data: Buffer,
offset: number,
end: number,
): { size: number; next: number; unknown: boolean } | null {
if (offset >= end) return null
const first = data[offset] as number
let length = 0
for (let index = 0; index < 8; index += 1) {
if (first & (0x80 >> index)) {
length = index + 1
break
}
}
if (!length || offset + length > end) return null
const mask = 0xff >> length
let value = first & mask
let unknown = value === mask
for (let index = 1; index < length; index += 1) {
const byte = data[offset + index] as number
if (byte !== 0xff) unknown = false
value = value * 256 + byte
}
return { size: value, next: offset + length, unknown }
}
function readEbmlFloat(data: Buffer, element: EbmlElement): number {
const size = element.payloadEnd - element.payloadStart
if (size === 4) return data.readFloatBE(element.payloadStart)
if (size === 8) return data.readDoubleBE(element.payloadStart)
return Number.NaN
}
function readEbmlUint(data: Buffer, element: EbmlElement): number {
const size = element.payloadEnd - element.payloadStart
if (size <= 0 || size > 6) return 0
let value = 0
for (let index = 0; index < size; index += 1) {
value = value * 256 + (data[element.payloadStart + index] as number)
}
return value
}