UNPKG

m3u8stream

Version:

Reads segments from a m3u8 or dash playlist into a consumable stream.

614 lines • 27.8 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const stream_1 = require("stream"); const sax_1 = __importDefault(require("sax")); const parse_time_1 = require("./parse-time"); const parser_1 = require("./parser"); const isAbsolute = (url) => /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url); const resolveRelativeURI = (base, target) => { const origin = 'http://relative.invalid'; const absoluteBase = base.startsWith('/'); const href = new URL(target, `${origin}/${base.replace(/^\/+/, '')}`).href; const resolved = href.slice(origin.length); return absoluteBase || target.startsWith('/') ? resolved : resolved.replace(/^\//, ''); }; const resolveURI = (bases, target) => { const parts = [...bases.filter((s) => !!s), target]; let lastAbsIdx = -1; for (let i = 0; i < parts.length; i++) { if (isAbsolute(parts[i])) { lastAbsIdx = i; } } if (lastAbsIdx !== -1) { let current = parts[lastAbsIdx]; for (let i = lastAbsIdx + 1; i < parts.length; i++) { current = new URL(parts[i], current).href; } return current; } let result = parts[0] || ''; for (let i = 1; i < parts.length; i++) { result = resolveRelativeURI(result, parts[i]); } return result; }; const parseByteRange = (rangeStr) => { if (!rangeStr) { return null; } const [start, end] = rangeStr.split('-').map((n) => parseInt(n, 10)); if (isNaN(start) || isNaN(end)) { return null; } return { start, end }; }; const parseOptionalInt = (value) => { if (value === undefined) { return undefined; } const parsed = parseInt(value, 10); return isNaN(parsed) ? undefined : parsed; }; const mergeDefined = (base, next) => { const result = Object.assign({}, base); for (const key of Object.keys(next)) { if ((0, parser_1.isSet)(next[key])) { result[key] = next[key]; } } return result; }; /** * A wrapper around sax that emits segments. */ class DashMPDParser extends stream_1.Writable { constructor(targetID) { super(); this._chunks = []; this._targetFilter = targetID; } _write(chunk, encoding, callback) { this._chunks.push(chunk); callback(); } _final(callback) { const xml = Buffer.concat(this._chunks).toString('utf8'); this._parseMPD(xml, callback); } _extractVariants(xml, callback) { const variants = []; let currentAdaptation = {}; let isStatic = true; const periods = []; const variantParser = sax_1.default.parser(false, { lowercase: true }); variantParser.onerror = (err) => { this.destroy(err); callback(err); }; variantParser.onopentag = (node) => { if (node.name === 'mpd') { isStatic = node.attributes.type !== 'dynamic'; } else if (node.name === 'period') { const duration = (0, parse_time_1.durationStr)(node.attributes.duration || ''); let start = (0, parse_time_1.durationStr)(node.attributes.start || ''); if (!node.attributes.start && periods.length) { const previous = periods[periods.length - 1]; start = previous.start + previous.duration; } periods.push({ start, duration }); } else if (node.name === 'adaptationset') { currentAdaptation = node.attributes; } else if (node.name === 'representation') { const id = node.attributes.id; if (!variants.some((v) => v.id === id)) { const widthStr = node.attributes.width || currentAdaptation.width; const heightStr = node.attributes.height || currentAdaptation.height; const bwStr = node.attributes.bandwidth || currentAdaptation.bandwidth; const codecs = (node.attributes.codecs || currentAdaptation.codecs); const mimeType = (node.attributes.mimetype || currentAdaptation.mimetype); const contentType = (node.attributes.contenttype || currentAdaptation.contenttype || (mimeType ? mimeType.split('/')[0] : undefined)); const frStr = (node.attributes.framerate || node.attributes.maxframerate || currentAdaptation.framerate || currentAdaptation.maxframerate); const width = widthStr ? parseInt(widthStr, 10) : undefined; const height = heightStr ? parseInt(heightStr, 10) : undefined; const bandwidth = bwStr ? parseInt(bwStr, 10) : undefined; let frameRate; if (frStr) { if (frStr.includes('/')) { const [n, d] = frStr.split('/').map(Number); frameRate = n / d; } else { frameRate = parseFloat(frStr); } } variants.push({ id, index: variants.length, bandwidth: isNaN(bandwidth) ? undefined : bandwidth, width: isNaN(width) ? undefined : width, height: isNaN(height) ? undefined : height, resolution: width && height && !isNaN(width) && !isNaN(height) ? `${width}x${height}` : undefined, codecs, frameRate: isNaN(frameRate) ? undefined : frameRate, contentType, }); } } }; variantParser.onclosetag = (name) => { if (name === 'adaptationset') { currentAdaptation = {}; } }; variantParser.write(xml).close(); if (this.destroyed) { return null; } return { variants, isStatic, periods }; } _parseMPD(xml, callback) { const extracted = this._extractVariants(xml, callback); if (!extracted) { return; } const { variants, isStatic, periods } = extracted; let ended = false; const chosen = (0, parser_1.selectVariant)(variants, this._targetFilter); if (!chosen) { if (isStatic) { this.emit('endlist'); } const filterDesc = typeof this._targetFilter === 'function' ? `${this._targetFilter}` : this._targetFilter; this.destroy(new Error(`Representation '${filterDesc}' not found`)); callback(); return; } const targetID = chosen.id; let lastTag = null; let treeLevel = 0; let isTarget = false; let availabilityStartTime; let mpdDuration = 0; let timeShiftBufferDepth = 0; let periodStart = 0; let periodDuration = 0; let periodDurationExplicit = 0; let periodIndex = -1; const baseURLs = []; const templates = []; const timelines = []; const segmentLists = []; const segmentBases = []; const initializations = []; const resetLevel = (level) => { baseURLs[level] = ''; templates[level] = undefined; timelines[level] = undefined; segmentLists[level] = undefined; segmentBases[level] = undefined; initializations[level] = undefined; }; const getTemplate = (level) => { let result; for (let i = 1; i <= level; i++) { const template = templates[i]; if (template) { result = mergeDefined(result, template); } } return result; }; const getList = (level) => { let result; for (let i = 1; i <= level; i++) { const list = segmentLists[i]; if (list) { result = mergeDefined(result, list); if (list.segmentURLs.length) { result.segmentURLs = list.segmentURLs; } } } return result; }; const getBase = (level) => { let result; for (let i = 1; i <= level; i++) { const base = segmentBases[i]; if (base) { result = mergeDefined(result, base); } } return result; }; const getInitialization = (level) => { for (let i = level; i >= 1; i--) { if (initializations[i]) { return initializations[i]; } } return undefined; }; const hasDirectMedia = (level) => !!baseURLs[level] && !baseURLs[level].endsWith('/'); const getTimeline = (level) => { var _a; for (let i = level; i >= 1; i--) { if ((_a = timelines[i]) === null || _a === void 0 ? void 0 : _a.length) { return timelines[i]; } } return undefined; }; const templateValue = (str, number, time) => { const context = { RepresentationID: targetID, Bandwidth: chosen.bandwidth, Number: number, Time: time, }; return str.replace(/\$(?:(\w+)(?:%0(\d+)d)?)?\$/g, (m, key, width) => { if (!key) { return '$'; } const val = `${context[key]}`; return width ? val.padStart(parseInt(width, 10), '0') : val; }); }; const expandTimeline = (entries, timescale, presentationTimeOffset) => { var _a; const segments = []; let segTime = 0; for (let i = 0; i < entries.length; i++) { const entry = entries[i]; const duration = entry.duration; if (!duration || duration <= 0) { continue; } let count; const start = (_a = entry.time) !== null && _a !== void 0 ? _a : segTime; if (entry.repeat === -1) { const next = entries[i + 1]; let endUnits; const nextTime = next === null || next === void 0 ? void 0 : next.time; if ((0, parser_1.isSet)(nextTime)) { endUnits = nextTime; } else if (periodDuration) { endUnits = (periodDuration * timescale) / 1000 + presentationTimeOffset; } count = endUnits === undefined ? 1 : Math.max(1, Math.ceil((endUnits - start) / duration)); } else { count = (entry.repeat === undefined || isNaN(entry.repeat) ? 0 : entry.repeat) + 1; } segTime = start; for (let n = 0; n < count; n++) { segments.push({ time: segTime, duration: (duration / timescale) * 1000, }); segTime += duration; } } return segments; }; const getDurationTemplateRange = (segmentDuration, maxCount) => { if (isStatic) { return { first: 0, count: maxCount }; } const elapsed = typeof availabilityStartTime === 'number' ? Date.now() - availabilityStartTime - periodStart : 0; if (elapsed <= 0) { return { first: 0, count: Math.max(maxCount, 1) }; } const window = timeShiftBufferDepth || elapsed; const first = Math.max(0, Math.floor(Math.max(0, elapsed - window) / segmentDuration)); const last = Math.floor(elapsed / segmentDuration) - 1; let count = Math.max(0, last - first + 1); if (maxCount) { count = Math.min(count, Math.max(0, maxCount - first)); } return { first, count }; }; const emitInit = (level, seq, templateInitialization) => { const initialization = getInitialization(level); const url = templateInitialization ? resolveURI(baseURLs.slice(0, level + 1), templateValue(templateInitialization, seq)) : resolveURI(baseURLs.slice(0, level + 1), (initialization === null || initialization === void 0 ? void 0 : initialization.sourceURL) || ''); if (!templateInitialization && !initialization) { return; } this.emit('item', Object.assign({ url, seq, init: true, duration: 0 }, ((initialization === null || initialization === void 0 ? void 0 : initialization.range) ? { range: initialization.range } : {}))); }; const emitSegments = (level) => { var _a, _b, _c, _d, _e, _f, _g, _h; const bases = baseURLs.slice(0, level + 1); const template = getTemplate(level); const list = getList(level); const base = getBase(level); const mediaURL = (target) => resolveURI(bases, target); if (template === null || template === void 0 ? void 0 : template.media) { const timescale = (_a = template.timescale) !== null && _a !== void 0 ? _a : 1; const startNumber = (_b = template.startNumber) !== null && _b !== void 0 ? _b : 1; let number = startNumber; emitInit(level, number, template.initialization); const entries = getTimeline(level); if (entries === null || entries === void 0 ? void 0 : entries.length) { const segments = expandTimeline(entries, timescale, (_c = template.presentationTimeOffset) !== null && _c !== void 0 ? _c : 0); for (const segment of segments) { this.emit('item', { url: mediaURL(templateValue(template.media, number, segment.time)), seq: isStatic ? number : segment.time, duration: segment.duration, }); number++; } } else if (template.duration) { const segmentDuration = (template.duration / timescale) * 1000; const maxCount = periodDuration ? Math.ceil(periodDuration / segmentDuration) : 0; const { first, count } = getDurationTemplateRange(segmentDuration, maxCount); let seq = startNumber + first; for (let n = 0; n < count; n++) { this.emit('item', { url: mediaURL(templateValue(template.media, seq, undefined)), seq: seq++, duration: segmentDuration, }); } } return; } if (list === null || list === void 0 ? void 0 : list.segmentURLs.length) { const timescale = (_d = list.timescale) !== null && _d !== void 0 ? _d : 1; let seq = (_e = list.startNumber) !== null && _e !== void 0 ? _e : 1; emitInit(level, seq); const entries = getTimeline(level); const segments = entries ? expandTimeline(entries, timescale, (_f = list.presentationTimeOffset) !== null && _f !== void 0 ? _f : 0) : []; list.segmentURLs.forEach((segmentURL, index) => { var _a, _b; const duration = (_b = (_a = segments[index]) === null || _a === void 0 ? void 0 : _a.duration) !== null && _b !== void 0 ? _b : (list.duration ? (list.duration / timescale) * 1000 : 0); this.emit('item', Object.assign({ url: mediaURL(segmentURL.media || ''), seq: seq++, duration }, (segmentURL.mediaRange ? { range: segmentURL.mediaRange } : {}))); }); return; } if (base) { const initialization = getInitialization(level); let seq = 1; emitInit(level, seq); let start; if (base.indexRange) { start = base.indexRange.end + 1; } else if (((_g = base.representationIndex) === null || _g === void 0 ? void 0 : _g.range) && !base.representationIndex.sourceURL) { start = base.representationIndex.range.end + 1; } else if ((initialization === null || initialization === void 0 ? void 0 : initialization.range) && !initialization.sourceURL) { start = initialization.range.end + 1; } const url = mediaURL(''); if (url) { this.emit('item', Object.assign({ url, seq: seq++, duration: base.duration ? (base.duration / ((_h = base.timescale) !== null && _h !== void 0 ? _h : 1)) * 1000 : periodDuration }, ((0, parser_1.isSet)(start) ? { range: { start } } : {}))); } return; } if (baseURLs[level]) { const url = mediaURL(''); if (url) { this.emit('item', { url, seq: 1, duration: periodDuration, }); } } }; const onEnd = () => { ended = true; if (isStatic) { this.emit('endlist'); } this.emit('end'); }; const segmentParser = sax_1.default.parser(false, { lowercase: true }); segmentParser.onopentag = (node) => { var _a, _b, _c; switch (node.name) { case 'mpd': availabilityStartTime = node.attributes.availabilitystarttime ? new Date(node.attributes.availabilitystarttime).getTime() : undefined; mpdDuration = (0, parse_time_1.durationStr)(node.attributes.mediapresentationduration); timeShiftBufferDepth = (0, parse_time_1.durationStr)(node.attributes.timeshiftbufferdepth); if (node.attributes.minimumupdateperiod) { this.emit('targetduration', (0, parse_time_1.durationStr)(node.attributes.minimumupdateperiod)); } break; case 'period': { treeLevel = 1; resetLevel(treeLevel); baseURLs.length = treeLevel; periodIndex++; const periodInfo = periods[periodIndex]; periodStart = periodInfo.start; periodDurationExplicit = periodInfo.duration; const nextPeriodStart = (_a = periods[periodIndex + 1]) === null || _a === void 0 ? void 0 : _a.start; const inferredDuration = periodDurationExplicit || (nextPeriodStart !== null && nextPeriodStart !== void 0 ? nextPeriodStart : periodStart) - periodStart; periodDuration = inferredDuration || (mpdDuration ? Math.max(0, mpdDuration - periodStart) : 0); break; } case 'adaptationset': treeLevel++; resetLevel(treeLevel); baseURLs.length = treeLevel; break; case 'representation': treeLevel++; resetLevel(treeLevel); baseURLs.length = treeLevel; isTarget = `${node.attributes.id}` === `${targetID}`; break; case 'baseurl': lastTag = 'baseurl'; break; case 'segmenttemplate': templates[treeLevel] = { initialization: node.attributes.initialization, media: node.attributes.media, timescale: parseOptionalInt(node.attributes.timescale), startNumber: parseOptionalInt(node.attributes.startnumber), duration: parseOptionalInt(node.attributes.duration), presentationTimeOffset: parseOptionalInt(node.attributes.presentationtimeoffset), }; break; case 'segmentlist': segmentLists[treeLevel] = { timescale: parseOptionalInt(node.attributes.timescale), duration: parseOptionalInt(node.attributes.duration), startNumber: parseOptionalInt(node.attributes.startnumber), presentationTimeOffset: parseOptionalInt(node.attributes.presentationtimeoffset), segmentURLs: [], }; break; case 'segmentbase': { const indexRange = parseByteRange(node.attributes.indexrange); segmentBases[treeLevel] = Object.assign({ timescale: parseOptionalInt(node.attributes.timescale), duration: parseOptionalInt(node.attributes.duration), presentationTimeOffset: parseOptionalInt(node.attributes.presentationtimeoffset) }, (indexRange ? { indexRange } : {})); break; } case 'representationindex': { const current = segmentBases[treeLevel]; if (current) { const range = parseByteRange(node.attributes.range); current.representationIndex = Object.assign({ sourceURL: node.attributes.sourceurl }, (range ? { range } : {})); } break; } case 'segmenttimeline': lastTag = 'segmenttimeline'; break; case 's': { if (!timelines[treeLevel]) { timelines[treeLevel] = []; } timelines[treeLevel].push({ duration: parseOptionalInt(node.attributes.d), repeat: parseOptionalInt(node.attributes.r), time: parseOptionalInt(node.attributes.t), }); break; } case 'initialization': { const range = parseByteRange(node.attributes.range); initializations[treeLevel] = Object.assign({ sourceURL: node.attributes.sourceurl }, (range ? { range } : {})); break; } case 'segmenturl': { (_b = segmentLists[treeLevel]) === null || _b === void 0 ? void 0 : _b.segmentURLs.push({ media: node.attributes.media, mediaRange: (_c = parseByteRange(node.attributes.mediarange)) !== null && _c !== void 0 ? _c : undefined, }); break; } } }; segmentParser.onclosetag = (tagName) => { var _a, _b, _c; if (tagName === 'representation') { if (isTarget) { const template = getTemplate(treeLevel); const list = getList(treeLevel); const base = getBase(treeLevel); const initialization = getInitialization(treeLevel); const externalOnly = !!((_a = base === null || base === void 0 ? void 0 : base.representationIndex) === null || _a === void 0 ? void 0 : _a.sourceURL) && !base.indexRange && !base.duration && !initialization; const directMedia = hasDirectMedia(treeLevel) && !(template === null || template === void 0 ? void 0 : template.media) && !(list === null || list === void 0 ? void 0 : list.segmentURLs.length) && !base; const hasContent = !!(template === null || template === void 0 ? void 0 : template.media) || !!(list === null || list === void 0 ? void 0 : list.segmentURLs.length) || (!!base && !externalOnly) || directMedia; if (hasContent) { const config = (template === null || template === void 0 ? void 0 : template.media) ? template : (list === null || list === void 0 ? void 0 : list.segmentURLs.length) ? list : base; const timescale = (_b = config === null || config === void 0 ? void 0 : config.timescale) !== null && _b !== void 0 ? _b : 1; const presentationTimeOffset = (_c = config === null || config === void 0 ? void 0 : config.presentationTimeOffset) !== null && _c !== void 0 ? _c : 0; this.emit('starttime', (availabilityStartTime !== null && availabilityStartTime !== void 0 ? availabilityStartTime : 0) + periodStart - (presentationTimeOffset / timescale) * 1000); emitSegments(treeLevel); } } isTarget = false; resetLevel(treeLevel); baseURLs.length = treeLevel; treeLevel--; } else if (tagName === 'adaptationset' || tagName === 'period') { resetLevel(treeLevel); baseURLs.length = treeLevel; treeLevel--; } }; segmentParser.ontext = (text) => { if (lastTag === 'baseurl') { baseURLs[treeLevel] = text.trim(); lastTag = null; } }; segmentParser.write(xml).close(); if (!ended) { onEnd(); } callback(); } } exports.default = DashMPDParser; //# sourceMappingURL=dash-mpd-parser.js.map