// A publish's media cut into HLS segments (RFC 8216 ยง3: each segment begins with a keyframe, so a player can start at // any one): a segment closes at the first video keyframe at or after the target duration from its start; audio follows // the video's cuts. A stream with no video is cut on its audio's time. Every timestamp is the publisher's (milliseconds) // plus the recording's offset, so a recording a publisher continues keeps its timeline. A change of encoder // configuration closes the segment under way and opens a new init. What a segment under way may hold is bounded: a // stream that sends no keyframe within the ceiling (no periodic IDR: intra-refresh, an endless GOP), or whose segment // passes its byte or frame ceiling (stalled timestamps), is refused (`LiveOverrun`), never held without end. Pure: bytes // in, segments out. import type { LiveAudio, LiveVideo } from './types.ts'; import { type AacConfig, type AvcConfig } from './flv.ts'; import { AUDIO_TRACK, type Fragment, initSegment, mediaSegment, VIDEO_TIMESCALE, VIDEO_TRACK } from './fmp4.ts'; type VideoSample = { dts: number; cts: number; key: boolean; data: Uint8Array }; type AudioSample = { dts: number; data: Uint8Array }; /** A segment closed: its bytes, its media start and duration (seconds), and, when it opens a new init, that init. */ export type Cut = { /** the segment's number in its recording */ sequence: number; bytes: Uint8Array; start: number; duration: number; init?: { bytes: Uint8Array; video?: LiveVideo; audio?: LiveAudio }; }; const AAC_FRAME = 1024; /** The longest a stream may go without a keyframe: ten target durations, at least 20 s, past OBS's automatic interval * of 250 frames (8.3 s at 30 fps, 10.4 s at 24). */ const MIN_KEYFRAME_CEILING_MS = 20_000; /** What one segment under way may hold: at a Twitch-like 8 Mbit/s, 20 s is 20 MB. */ const MAX_SEGMENT_BYTES = 64 * 1024 * 1024; const MAX_SEGMENT_FRAMES = 10_000; /** A stream the segmenter will not hold: its publish is ended with the reason (ingest.ts). */ export class LiveOverrun extends Error {} export class Segmenter { private avc?: AvcConfig; private aac?: AacConfig; private meta: Record = {}; private freshInit = true; private video: VideoSample[] = []; private audio: AudioSample[] = []; private start?: number; private keyed = false; private audioNext?: number; private lastVideoDuration = 33; private sequence = 0; /** what the segment under way holds, and since when video has come with no keyframe to start on */ private bytes = 0; private frames = 0; private unkeyedSince?: number; constructor(private readonly options: { targetMs: number; offsetMs: number; firstSequence: number }) { this.sequence = options.firstSequence; } /** The publisher's metadata (`onMetaData`): the size and rate a stream's SPS does not say, and whether video comes. */ metadata(meta: Record): void { this.meta = { ...this.meta, ...meta }; } videoConfig(config: AvcConfig): Cut[] { if (this.avc && same(this.avc.record, config.record)) return []; const out = this.flush(); this.avc = config; this.freshInit = true; this.keyed = false; this.unkeyedSince = undefined; return out; } audioConfig(config: AacConfig): Cut[] { if (this.aac && same(this.aac.asc, config.asc)) return []; const out = this.flush(); this.aac = config; this.freshInit = true; // A configuration boundary has no running video segment. Its first frame must be a new keyframe, and the // audio sample clock belongs to the new configuration (which may have a different sample rate). this.keyed = false; this.unkeyedSince = undefined; this.audioNext = undefined; return out; } /** A video frame at its decode time: the segment it closes, if it closes one. */ videoFrame(timestamp: number, key: boolean, cts: number, data: Uint8Array): Cut[] { if (!this.avc) return []; const dts = timestamp + this.options.offsetMs; const out: Cut[] = []; if (!this.keyed) { // a stream is played from a keyframe: what comes before the first is undecodable, and audio before it unheard if (!key) { this.unkeyedSince ??= dts; if (dts - this.unkeyedSince >= this.keyframeCeiling()) throw this.noKeyframe(); return []; } this.keyed = true; this.unkeyedSince = undefined; if (this.video.length || this.audioOnlyStarted()) out.push(...this.flush()); this.start = dts; this.audio = this.audio.filter((a) => a.dts >= dts); } else if (key && this.start !== undefined && dts - this.start >= this.options.targetMs) { const cut = this.cut(dts); if (cut) out.push(cut); this.start = dts; } this.within(dts, data.length, key); this.video.push({ dts, cts, key, data }); this.bytes += data.length; this.frames += 1; return out; } audioFrame(timestamp: number, data: Uint8Array): Cut[] { if (!this.aac || data.length === 0) return []; const dts = timestamp + this.options.offsetMs; if (this.expectsVideo()) { if (!this.keyed) return []; this.within(dts, data.length); this.audio.push({ dts, data }); this.bytes += data.length; this.frames += 1; return []; } // audio alone: cut on its own time const out: Cut[] = []; if (this.start === undefined) this.start = dts; else if (dts - this.start >= this.options.targetMs) { const cut = this.cut(dts); if (cut) out.push(cut); this.start = dts; } this.within(dts, data.length); this.audio.push({ dts, data }); this.bytes += data.length; this.frames += 1; return out; } /** The segment under way, closed (the publish's end, or a configuration change). */ flush(): Cut[] { const cut = this.cut(undefined); this.video = []; this.audio = []; this.start = undefined; this.bytes = 0; this.frames = 0; return cut ? [cut] : []; } private keyframeCeiling(): number { return Math.max(MIN_KEYFRAME_CEILING_MS, 10 * this.options.targetMs); } private noKeyframe(): LiveOverrun { return new LiveOverrun(`The stream sent no keyframe for ${Math.round(this.keyframeCeiling() / 1000)} s; send one at least every ${Math.round(this.options.targetMs / 1000)} s (the encoder's keyframe interval).`); } /** A frame the segment under way may still take, or the refusal past its ceilings. */ private within(dts: number, size: number, key = false): void { if (!key && this.start !== undefined && dts - this.start >= this.keyframeCeiling()) throw this.noKeyframe(); if (this.bytes + size > MAX_SEGMENT_BYTES || this.frames + 1 > MAX_SEGMENT_FRAMES) throw new LiveOverrun(`A segment passed ${MAX_SEGMENT_BYTES} bytes or ${MAX_SEGMENT_FRAMES} frames before a keyframe closed it.`); } private expectsVideo(): boolean { return this.avc !== undefined || this.meta.videocodecid !== undefined; } private audioOnlyStarted(): boolean { return !this.expectsVideo() && this.audio.length > 0; } private cut(at: number | undefined): Cut | undefined { const video = this.video; const audio = at === undefined ? this.audio : this.audio.filter((a) => a.dts < at); this.audio = at === undefined ? [] : this.audio.filter((a) => a.dts >= at); this.video = []; // what the next segment already holds: the audio past the cut this.bytes = this.audio.reduce((n, a) => n + a.data.length, 0); this.frames = this.audio.length; if (video.length === 0 && audio.length === 0) return undefined; const fragments: Fragment[] = []; let startMs: number; let durationMs: number; if (video.length) { const samples = video.map((s, i) => { const next = i + 1 < video.length ? video[i + 1]!.dts : at; const ms = next === undefined ? this.lastVideoDuration : Math.max(1, next - s.dts); if (next !== undefined) this.lastVideoDuration = ms; return { duration: Math.round(ms * 90), data: s.data, key: s.key, cts: Math.round(s.cts * 90) }; }); startMs = video[0]!.dts; durationMs = samples.reduce((n, s) => n + s.duration, 0) / 90; fragments.push({ track: VIDEO_TRACK, baseTime: Math.round(startMs * (VIDEO_TIMESCALE / 1000)), samples }); } else { startMs = audio[0]!.dts; durationMs = 0; } if (audio.length && this.aac) { const rate = this.aac.sampleRate; // a running sample clock, resynchronised to the publisher's timestamps when they drift past 100 ms (a gap) const expected = Math.round(audio[0]!.dts * rate / 1000); if (this.audioNext === undefined || Math.abs(this.audioNext - expected) > rate / 10) this.audioNext = expected; const baseTime = this.audioNext; this.audioNext += AAC_FRAME * audio.length; fragments.push({ track: AUDIO_TRACK, baseTime, samples: audio.map((a) => ({ duration: AAC_FRAME, data: a.data, key: true })) }); if (!video.length) durationMs = (AAC_FRAME * audio.length * 1000) / rate; } const sequence = this.sequence++; const cut: Cut = { sequence, bytes: mediaSegment(sequence + 1, fragments), start: startMs / 1000, duration: durationMs / 1000 }; if (this.freshInit) { this.freshInit = false; const video = this.avc ? { codec: this.avc.codec, width: this.avc.width || Number(this.meta.width) || 0, height: this.avc.height || Number(this.meta.height) || 0, ...(frameRate(this.meta) ? { frameRate: frameRate(this.meta)! } : {}) } : undefined; const audioInfo = this.aac ? { codec: this.aac.codec, sampleRate: this.aac.sampleRate, channels: this.aac.channels } : undefined; cut.init = { bytes: initSegment({ ...(this.avc ? { video: { ...this.avc, width: video!.width, height: video!.height } } : {}), ...(this.aac ? { audio: this.aac } : {}) }), ...(video ? { video } : {}), ...(audioInfo ? { audio: audioInfo } : {}), }; } return cut; } } function frameRate(meta: Record): number | undefined { const n = Number(meta.framerate ?? meta.fps); return Number.isFinite(n) && n > 0 ? n : undefined; } function same(a: Uint8Array, b: Uint8Array): boolean { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; return true; }