/*! * Copyright (c) 2026-present, Vanilagy and contributors * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ import { TrackType } from './output'; import { MediaCodec } from './codec'; import { DurationMetadataRequestOptions } from './demuxer'; import { Input } from './input'; import { InputAudioTrack, InputAudioTrackBacking, InputTrack, InputTrackBacking, InputVideoTrack, InputVideoTrackBacking, } from './input-track'; import { PacketRetrievalOptions } from './media-sink'; import { arrayCount, assert, MaybePromise, roundIfAlmostInteger, roundToDivisor } from './misc'; import { EncodedPacket } from './packet'; export type SegmentedInputMetadata = { name: string | null; bitrate: number | null; // doc block: this refers to the _peak_ bitrate averageBitrate: number | null; codecs: MediaCodec[]; codecStrings: string[]; resolution: { width: number; height: number } | null; frameRate: number | null; isKeyFrameOnly: boolean; }; export type AssociatedGroup = { id: string; type: 'video' | 'audio' | 'subtitles' | 'closed-captions'; }; export type Segment = { timestamp: number; duration: number; /** * The Unix time (in seconds) corresponding to this segment's start timestamp, or null if unknown. This is computed * whenever the source provides wall-clock information (e.g. HLS program date time), even if the segment timestamps * themselves are not shifted into Unix time space. */ unixEpochTimestamp: number | null; discontinuityNumber: number; initSegment: Segment | null; }; export type SegmentRetrievalOptions = { skipLiveWait?: boolean; }; export type SegmentedInputTrackDeclaration = { type: TrackType; }; export abstract class SegmentedInput { input: Input; path: string; trackDeclarations: SegmentedInputTrackDeclaration[] | null; nextInputCacheAge = 0; inputCache: { segment: Segment; input: Input; age: number; }[] = []; trackBackingsPromise: Promise | null = null; firstSegment: Segment | null = null; hasOnlyKeyPackets = false; // Roughly maps local segment timestamps onto actual packet timestamps learnedSegmentTimestampOffset: number | null = null; segmentMediaOffsets = new WeakMap>(); constructor(input: Input, path: string, trackDeclarations: SegmentedInputTrackDeclaration[] | null) { this.input = input; this.path = path; this.trackDeclarations = trackDeclarations; } abstract getFirstSegment(options: SegmentRetrievalOptions): Promise; abstract getSegmentAt(timestamp: number, options: SegmentRetrievalOptions): Promise; abstract getNextSegment(segment: Segment, options: SegmentRetrievalOptions): Promise; abstract getPreviousSegment(segment: Segment, options: SegmentRetrievalOptions): Promise; abstract getInputForSegment(segment: Segment): Input; abstract getLiveRefreshInterval(): Promise; abstract getMediaOffsetForDiscontinuity(discontinuityNumber: number): Promise; abstract getFirstSegmentTimestampOffset(): Promise; abstract getRawTimestampOffset(input: Input): Promise; // Needed to make things like MP3/ADTS work abstract getTimestampWrapPeriod(): number; async getDurationFromMetadata(options: DurationMetadataRequestOptions) { const lastSegment = await this.getSegmentAt(Infinity, { skipLiveWait: options.skipLiveWait, }); if (!lastSegment) { return null; } return (lastSegment.timestamp + await this.getFirstSegmentTimestampOffset()) + lastSegment.duration; } async getUnixTimeForTimestamp(timestamp: number): Promise { // Past the live edge, the last known segment's mapping extrapolates just as precisely, so no need to wait let segment = await this.getSegmentAt(timestamp, { skipLiveWait: true }); segment ??= await this.getFirstSegment({}); if (!segment || segment.unixEpochTimestamp === null) { return null; } const elapsed = timestamp - (segment.timestamp + await this.getFirstSegmentTimestampOffset()); return segment.unixEpochTimestamp + elapsed; } async getTrackBackings(): Promise { return this.trackBackingsPromise ??= (async () => { const backings: InputTrackBacking[] = []; if (this.trackDeclarations) { for (const decl of this.trackDeclarations) { if (decl.type === 'video') { const number = arrayCount(backings, x => x.getType() === 'video') + 1; backings.push( new SegmentedInputInputVideoTrackBacking(this, decl, number), ); } else if (decl.type === 'audio') { const number = arrayCount(backings, x => x.getType() === 'audio') + 1; backings.push( new SegmentedInputInputAudioTrackBacking(this, decl, number), ); } } } else { // There are no declarations, we must determine the tracks from the first segment this.firstSegment = await this.getFirstSegment({}); if (!this.firstSegment) { return []; } const input = this.getInputForSegment(this.firstSegment.initSegment ?? this.firstSegment); const inputTracks = await input.getTracks(); for (const track of inputTracks) { if (track.type === 'video') { const number = arrayCount(backings, x => x.getType() === 'video') + 1; backings.push( new SegmentedInputInputVideoTrackBacking(this, { type: 'video' }, number), ); } else if (track.type === 'audio') { const number = arrayCount(backings, x => x.getType() === 'audio') + 1; backings.push( new SegmentedInputInputAudioTrackBacking(this, { type: 'audio' }, number), ); } } } return backings; })(); } getMediaOffset(segment: Segment, input: Input) { let promise = this.segmentMediaOffsets.get(segment); if (promise) { return promise; } promise = (async () => { const rawTimestampOffset = await this.getRawTimestampOffset(input); if (rawTimestampOffset === null) { // Without media timestamps, all we can do is place the media at the segment's timestamp return segment.timestamp; } let mediaOffset = rawTimestampOffset + await this.getMediaOffsetForDiscontinuity(segment.discontinuityNumber); const period = this.getTimestampWrapPeriod(); if (period < Infinity) { // Media timestamps wrap around periodically (that's how MPEG-TS timestamps work). To make the entire // timeline continuous and monotonic (even for live streams that go on forever), we do a simple trick: // shift the media timestamps by multiples of the period length so that the first timestamp is closest // to the segment's timestamp (which DOES rise monotonically). This even works correctly for // non-wrapping formats like fMP4 because for them it's just a noop (or a constant shift for all media). const firstTimestamp = await getReferenceFirstTimestamp(input); if (firstTimestamp !== null) { const mediaStart = firstTimestamp + mediaOffset; mediaOffset += period * Math.round((segment.timestamp - mediaStart) / period); } } return mediaOffset; })(); this.segmentMediaOffsets.set(segment, promise); return promise; } dispose() { for (const entry of this.inputCache) { entry.input.dispose(); } this.inputCache.length = 0; } } export const getReferenceFirstTimestamp = async (input: Input) => { // Prefer video over audio const tracks = await input.getTracks(); const orderedTracks = [ ...tracks.filter(x => x.type === 'video'), ...tracks.filter(x => x.type !== 'video'), ]; for (const track of orderedTracks) { const firstTimestamp = await track.getFirstTimestampOrNull(); if (firstTimestamp !== null) { return firstTimestamp; } } return null; }; type PacketInfo = { segment: Segment; track: InputTrack; sourcePacket: EncodedPacket; }; class SegmentedInputInputTrackBacking implements InputTrackBacking { segmentedInput: SegmentedInput; decl: SegmentedInputTrackDeclaration; number: number; packetInfos = new WeakMap(); hydrationPromise: Promise | null = null; metadataInputTrack: InputTrack | null = null; constructor(segmentedInput: SegmentedInput, decl: SegmentedInputTrackDeclaration, number: number) { this.segmentedInput = segmentedInput; this.decl = decl; this.number = number; } hydrate() { return this.hydrationPromise ??= (async () => { const firstSegment = await this.getFirstSegment(); let track: InputTrack | null = null; if (firstSegment.initSegment) { // The init segment holds all the metadata, so there's no need to fetch any actual media const inputTracks = await this.segmentedInput.getInputForSegment(firstSegment.initSegment).getTracks(); track = inputTracks.find(x => x.type === this.decl.type && x.number === this.number) ?? null; } else { // For playlists with sparse tracks (rare af!!), not every segment has every track, so we need to loop // to find the first segment that actually contains the track we want. let currentSegment: Segment | null = firstSegment; while (currentSegment) { const input = this.segmentedInput.getInputForSegment(currentSegment); const inputTracks = await input.getTracks(); track = inputTracks.find(x => x.type === this.decl.type && x.number === this.number) ?? null; if (track) { break; } currentSegment = await this.segmentedInput.getNextSegment(currentSegment, {}); } } if (!track) { throw new Error('No matching track found in underlying media data.'); } this.metadataInputTrack = track; })(); } getType(): TrackType { return this.decl.type; } getNumber(): number { return this.number; } /** If the backing track is already present, delegate synchronously; otherwise, hydrate first. */ delegate(fn: () => MaybePromise): MaybePromise { if (this.metadataInputTrack) { return fn(); } return this.hydrate().then(fn); } async getDecoderConfig() { return this.delegate(() => this.metadataInputTrack!._backing.getDecoderConfig()); } getHasOnlyKeyPackets() { return this.delegate(() => { return this.segmentedInput.hasOnlyKeyPackets || (this.metadataInputTrack!._backing.getHasOnlyKeyPackets?.() ?? null); }); } getPairingMask() { return 1n; } getCodec() { return this.delegate(() => this.metadataInputTrack!._backing.getCodec()); } getInternalCodecId() { return this.delegate(() => this.metadataInputTrack!._backing.getInternalCodecId()); } getDisposition() { return this.delegate(() => this.metadataInputTrack!._backing.getDisposition()); } getLanguageCode() { return this.delegate(() => this.metadataInputTrack!._backing.getLanguageCode()); } getName() { return this.delegate(() => this.metadataInputTrack!._backing.getName()); } getTimeResolution() { return this.delegate(() => this.metadataInputTrack!._backing.getTimeResolution()); } async isRelativeToUnixEpoch() { const firstSegment = await this.getFirstSegment(); return firstSegment.unixEpochTimestamp === firstSegment.timestamp; } getUnixTimeForTimestamp(timestamp: number) { return this.segmentedInput.getUnixTimeForTimestamp(timestamp); } getBitrate() { return this.delegate(() => this.metadataInputTrack!._backing.getBitrate()); } getAverageBitrate() { return this.delegate(() => this.metadataInputTrack!._backing.getAverageBitrate()); } getDurationFromMetadata(options: DurationMetadataRequestOptions): Promise { return this.segmentedInput.getDurationFromMetadata(options); } getLiveRefreshInterval(): Promise { return this.segmentedInput.getLiveRefreshInterval(); } async createAdjustedPacket(packet: EncodedPacket, segment: Segment, track: InputTrack) { assert(packet.sequenceNumber >= 0); const firstSegment = await this.getFirstSegment(); const mediaOffset = await this.segmentedInput.getMediaOffset(segment, track.input); // If we didn't do this then sequence numbers would exceed Number.MAX_SAFE_INTEGER for Unix-timestamped segments const segmentTimestampRelativeToFirst = segment.timestamp - firstSegment.timestamp; const modified = packet.clone({ timestamp: roundToDivisor( packet.timestamp + mediaOffset, await track.getTimeResolution(), ), // The 1e8 assumes a max of 100 MB per second, highly unlikely to be hit, so this should guarantee // monotonically increasing sequence numbers across segments. sequenceNumber: Math.floor(1e8 * segmentTimestampRelativeToFirst) + packet.sequenceNumber, }); this.packetInfos.set(modified, { segment, track, sourcePacket: packet, }); return modified; } async getFirstPacket(options: PacketRetrievalOptions): Promise { const firstSegment = await this.getFirstSegment(); // Kick this off early so it runs in parallel to loading our own media void this.segmentedInput.getMediaOffsetForDiscontinuity(firstSegment.discontinuityNumber).catch(() => {}); // Loop until we found a segment with a packet (segments may contain zero packets in rare cases) let currentSegment: Segment | null = firstSegment; while (currentSegment) { const input = this.segmentedInput.getInputForSegment(currentSegment); const tracks = await input.getTracks(); const track = tracks.find(t => t.type === this.decl.type && t.number === this.number); if (track) { const packet = await track._backing.getFirstPacket(options); if (packet) { return this.createAdjustedPacket(packet, currentSegment, track); } } currentSegment = await this.segmentedInput.getNextSegment(currentSegment, { skipLiveWait: options.skipLiveWait, }); } return null; } async getFirstSegment() { this.segmentedInput.firstSegment ??= await this.segmentedInput.getFirstSegment({}); if (!this.segmentedInput.firstSegment) { throw new Error('Missing first segment, can\'t retrieve track.'); } return this.segmentedInput.firstSegment; } getNextPacket(packet: EncodedPacket, options: PacketRetrievalOptions): Promise { return this._getNextInternal(packet, options, false); } getNextKeyPacket(packet: EncodedPacket, options: PacketRetrievalOptions): Promise { return this._getNextInternal(packet, options, true); } async _getNextInternal( packet: EncodedPacket, options: PacketRetrievalOptions, keyframesOnly: boolean, ): Promise { const info = this.packetInfos.get(packet); if (!info) { throw new Error('Packet was not created from this track.'); } const nextPacket = keyframesOnly ? await info.track._backing.getNextKeyPacket(info.sourcePacket, options) : await info.track._backing.getNextPacket(info.sourcePacket, options); if (nextPacket) { return this.createAdjustedPacket(nextPacket, info.segment, info.track); } let currentSegment: Segment | null = info.segment; while (true) { const nextSegment = await this.segmentedInput.getNextSegment(currentSegment, { skipLiveWait: options.skipLiveWait, }); if (!nextSegment) { return null; } const nextInput = this.segmentedInput.getInputForSegment(nextSegment); const nextTracks = await nextInput.getTracks(); const nextTrack = nextTracks.find(t => t.type === info.track.type && t.number === info.track.number); if (!nextTrack) { currentSegment = nextSegment; continue; } let packet = await nextTrack._backing.getFirstPacket(options); if (packet && keyframesOnly && packet.type !== 'key') { packet = await nextTrack._backing.getNextKeyPacket(packet, options); } if (!packet) { // Segments may contain zero packets for a track, so, move on currentSegment = nextSegment; continue; } return this.createAdjustedPacket(packet, nextSegment, nextTrack); } } getPacket(timestamp: number, options: PacketRetrievalOptions): Promise { return this._getPacketInternal(timestamp, options, false); } getKeyPacket(timestamp: number, options: PacketRetrievalOptions): Promise { return this._getPacketInternal(timestamp, options, true); } async _getPacketInternal( timestamp: number, options: PacketRetrievalOptions, keyframesOnly: boolean, ): Promise { let currentSegment = await this.segmentedInput.getSegmentAt(timestamp, { skipLiveWait: options.skipLiveWait, }); // The media may start before the first segment's timestamp currentSegment ??= await this.segmentedInput.getFirstSegment({}); if (!currentSegment) { return null; } // Kick this off early so it runs in parallel to loading our own media void this.segmentedInput.getMediaOffsetForDiscontinuity(currentSegment.discontinuityNumber).catch(() => {}); while (currentSegment) { const input = this.segmentedInput.getInputForSegment(currentSegment); const tracks = await input.getTracks(); const track = tracks.find(t => t.type === this.decl.type && t.number === this.number); if (!track) { // Search the previous segment currentSegment = await this.segmentedInput.getPreviousSegment(currentSegment, { skipLiveWait: options.skipLiveWait, }); continue; } const mediaOffset = await this.segmentedInput.getMediaOffset(currentSegment, input); // If we don't know the segment timestamp offset yet, learn it once from where this segment's media // actually lies. If the timestamp is more than a segment's duration away from the segment, the lookup was // way off, so redo it with the learned offset instead of walking there segment by segment. Note that it's // fine if the result is still off, because we follow it with a correction step that finds the correct // packet. const firstPacket = this.segmentedInput.learnedSegmentTimestampOffset === null ? await track._backing.getFirstPacket({ ...options, metadataOnly: true }) : null; if (firstPacket) { const segmentStart = firstPacket.timestamp + mediaOffset; this.segmentedInput.learnedSegmentTimestampOffset = segmentStart - currentSegment.timestamp; const distance = timestamp - segmentStart; if (distance < -currentSegment.duration || distance >= 2 * currentSegment.duration) { const segment = await this.segmentedInput.getSegmentAt(timestamp, { skipLiveWait: options.skipLiveWait, }); if (segment !== currentSegment) { currentSegment = segment; continue; } } } const offsetTimestamp = toSegmentTimestamp(timestamp, mediaOffset, await track.getTimeResolution()); const packet = keyframesOnly ? await track._backing.getKeyPacket(offsetTimestamp, options) : await track._backing.getPacket(offsetTimestamp, options); if (!packet) { // Search the previous segment currentSegment = await this.segmentedInput.getPreviousSegment(currentSegment, { skipLiveWait: options.skipLiveWait, }); continue; } // The playlist may claim the segment to be longer than its media actually is, in which case the timestamp // can lie in the next segment instead. That's only possible if it lies past this segment's media. const lastPacket = keyframesOnly ? await track._backing.getPacket(offsetTimestamp, { ...options, metadataOnly: true }) : packet; assert(lastPacket); if (offsetTimestamp >= lastPacket.timestamp + lastPacket.duration) { const nextSegment = await this.segmentedInput.getNextSegment(currentSegment, { skipLiveWait: options.skipLiveWait, }); if (nextSegment) { const nextInput = this.segmentedInput.getInputForSegment(nextSegment); const nextTracks = await nextInput.getTracks(); const nextTrack = nextTracks.find(t => t.type === this.decl.type && t.number === this.number); let nextPacket = nextTrack ? await nextTrack._backing.getFirstPacket({ ...options, metadataOnly: true }) : null; if (nextPacket && keyframesOnly && nextPacket.type !== 'key') { nextPacket = await nextTrack!._backing.getNextKeyPacket(nextPacket, { ...options, metadataOnly: true, }); } if (nextPacket) { const nextMediaOffset = await this.segmentedInput.getMediaOffset(nextSegment, nextInput); const nextOffsetTimestamp = toSegmentTimestamp( timestamp, nextMediaOffset, await nextTrack!.getTimeResolution(), ); if (nextPacket.timestamp <= nextOffsetTimestamp) { currentSegment = nextSegment; continue; } } } } return this.createAdjustedPacket(packet, currentSegment, track); } return null; } } const toSegmentTimestamp = (timestamp: number, mediaOffset: number, timeResolution: number) => { // Mirrors the rounding in createAdjustedPacket const tick = Math.floor(roundIfAlmostInteger(timeResolution * timestamp)); return (tick - Math.round(timeResolution * mediaOffset)) / timeResolution; }; class SegmentedInputInputVideoTrackBacking extends SegmentedInputInputTrackBacking implements InputVideoTrackBacking { declare metadataInputTrack: InputVideoTrack | null; override getType() { return 'video' as const; } override getCodec() { return this.delegate(() => this.metadataInputTrack!._backing.getCodec()); } getCodedWidth() { return this.delegate(() => this.metadataInputTrack!._backing.getCodedWidth()); } getCodedHeight() { return this.delegate(() => this.metadataInputTrack!._backing.getCodedHeight()); } getSquarePixelWidth() { return this.delegate(() => this.metadataInputTrack!._backing.getSquarePixelWidth()); } getSquarePixelHeight() { return this.delegate(() => this.metadataInputTrack!._backing.getSquarePixelHeight()); } getTransformationMatrix() { return this.delegate(() => this.metadataInputTrack!._backing.getTransformationMatrix()); } async getColorSpace(): Promise { return this.delegate(() => this.metadataInputTrack!._backing.getColorSpace()); } async canBeTransparent(): Promise { return this.delegate(() => this.metadataInputTrack!._backing.canBeTransparent()); } override async getDecoderConfig(): Promise { return this.delegate(() => this.metadataInputTrack!._backing.getDecoderConfig()); } } class SegmentedInputInputAudioTrackBacking extends SegmentedInputInputTrackBacking implements InputAudioTrackBacking { declare metadataInputTrack: InputAudioTrack; override getType() { return 'audio' as const; } override getCodec() { return this.delegate(() => this.metadataInputTrack._backing.getCodec()); } getNumberOfChannels() { return this.delegate(() => this.metadataInputTrack._backing.getNumberOfChannels()); } getSampleRate() { return this.delegate(() => this.metadataInputTrack._backing.getSampleRate()); } override async getDecoderConfig(): Promise { return this.delegate(() => this.metadataInputTrack._backing.getDecoderConfig()); } }