p2p-media-loader-dashjs 5.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"p2p-media-loader-dashjs.iife.js","names":["window","window","isObject","window"],"sources":["../../../node_modules/.pnpm/global@4.4.0/node_modules/global/window.js","../../../node_modules/.pnpm/@videojs+vhs-utils@4.1.2/node_modules/@videojs/vhs-utils/es/resolve-url.js","../../../node_modules/.pnpm/@videojs+vhs-utils@4.1.2/node_modules/@videojs/vhs-utils/es/media-groups.js","../../../node_modules/.pnpm/@videojs+vhs-utils@4.1.2/node_modules/@videojs/vhs-utils/es/decode-b64-to-uint8-array.js","../../p2p-media-loader-core/src/manifest/shims/dom-parser.ts","../../../node_modules/.pnpm/mpd-parser@1.4.0/node_modules/mpd-parser/dist/mpd-parser.es.js","../../p2p-media-loader-core/src/manifest/shims/object-values.ts","../../../node_modules/.pnpm/@videojs+vhs-utils@4.1.2/node_modules/@videojs/vhs-utils/es/codecs.js","../../p2p-media-loader-core/src/manifest/properties.ts","../../p2p-media-loader-core/src/manifest/url-key.ts","../../p2p-media-loader-core/src/manifest/dash.ts","../../p2p-media-loader-core/src/types.ts","../../p2p-media-loader-core/src/utils/abort-controller.ts","../../p2p-media-loader-core/src/http-loader.ts","../../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js","../../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js","../../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js","../../p2p-media-loader-core/src/p2p/commands/types.ts","../../p2p-media-loader-core/src/utils/utils.ts","../../p2p-media-loader-core/src/p2p/commands/binary-serialization.ts","../../p2p-media-loader-core/src/p2p/commands/binary-command-creator.ts","../../p2p-media-loader-core/src/p2p/commands/commands.ts","../../p2p-media-loader-core/src/p2p/commands/index.ts","../../p2p-media-loader-core/src/webtorrent/utils.ts","../../p2p-media-loader-core/src/webtorrent/data-channel-sender.ts","../../p2p-media-loader-core/src/p2p/peer-protocol.ts","../../p2p-media-loader-core/src/bandwidth-calculator.ts","../../p2p-media-loader-core/src/p2p/peer.ts","../../p2p-media-loader-core/src/utils/event-target.ts","../../p2p-media-loader-core/src/webtorrent/webtorrent-client/webrtc-utils.ts","../../p2p-media-loader-core/src/webtorrent/webtorrent-client/index.ts","../../p2p-media-loader-core/src/webtorrent/webtorrent-manager/index.ts","../../p2p-media-loader-core/src/utils/stream.ts","../../p2p-media-loader-core/src/p2p/loader.ts","../../p2p-media-loader-core/src/utils/logger.ts","../../p2p-media-loader-core/src/p2p/loaders-container.ts","../../p2p-media-loader-core/src/requests/request.ts","../../p2p-media-loader-core/src/requests/request-container.ts","../../p2p-media-loader-core/src/requests/engine-request.ts","../../p2p-media-loader-core/src/utils/queue.ts","../../p2p-media-loader-core/src/utils/election.ts","../../p2p-media-loader-core/src/playback-tracker.ts","../../p2p-media-loader-core/src/hybrid-loader.ts","../../p2p-media-loader-core/src/utils/hash.ts","../../p2p-media-loader-core/src/stream-identity.ts","../../p2p-media-loader-core/src/manifest/mp4-sidx.ts","../../p2p-media-loader-core/src/manifest/registry.ts","../../p2p-media-loader-core/src/segment-storage/utils.ts","../../p2p-media-loader-core/src/segment-storage/segment-memory-storage.ts","../../p2p-media-loader-core/src/utils/version.ts","../../p2p-media-loader-core/src/utils/peer.ts","../../p2p-media-loader-core/src/webtorrent/websocket-client/index.ts","../../p2p-media-loader-core/src/webtorrent/webtorrent-socket-pool/index.ts","../../p2p-media-loader-core/src/core.ts","../../p2p-media-loader-core/src/playback.ts","../../p2p-media-loader-core/src/live-delay.ts","../src/types.ts","../src/loader.ts","../src/engine.ts"],"sourcesContent":["var win;\n\nif (typeof window !== \"undefined\") {\n win = window;\n} else if (typeof global !== \"undefined\") {\n win = global;\n} else if (typeof self !== \"undefined\"){\n win = self;\n} else {\n win = {};\n}\n\nmodule.exports = win;\n","import window from 'global/window';\nvar DEFAULT_LOCATION = 'https://example.com';\n\nvar resolveUrl = function resolveUrl(baseUrl, relativeUrl) {\n // return early if we don't need to resolve\n if (/^[a-z]+:/i.test(relativeUrl)) {\n return relativeUrl;\n } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location\n\n\n if (/^data:/.test(baseUrl)) {\n baseUrl = window.location && window.location.href || '';\n }\n\n var protocolLess = /^\\/\\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)\n // and if baseUrl isn't an absolute url\n\n var removeLocation = !window.location && !/\\/\\//i.test(baseUrl); // if the base URL is relative then combine with the current location\n\n baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION);\n var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol\n // and if we're location-less, remove the location\n // otherwise, return the url unmodified\n\n if (removeLocation) {\n return newUrl.href.slice(DEFAULT_LOCATION.length);\n } else if (protocolLess) {\n return newUrl.href.slice(newUrl.protocol.length);\n }\n\n return newUrl.href;\n};\n\nexport default resolveUrl;","/**\n * Loops through all supported media groups in master and calls the provided\n * callback for each group\n *\n * @param {Object} master\n * The parsed master manifest object\n * @param {string[]} groups\n * The media groups to call the callback for\n * @param {Function} callback\n * Callback to call for each media group\n */\nexport var forEachMediaGroup = function forEachMediaGroup(master, groups, callback) {\n groups.forEach(function (mediaType) {\n for (var groupKey in master.mediaGroups[mediaType]) {\n for (var labelKey in master.mediaGroups[mediaType][groupKey]) {\n var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];\n callback(mediaProperties, mediaType, groupKey, labelKey);\n }\n }\n });\n};","import window from 'global/window';\n\nvar atob = function atob(s) {\n return window.atob ? window.atob(s) : Buffer.from(s, 'base64').toString('binary');\n};\n\nexport default function decodeB64ToUint8Array(b64Text) {\n var decodedString = atob(b64Text);\n var array = new Uint8Array(decodedString.length);\n\n for (var i = 0; i < decodedString.length; i++) {\n array[i] = decodedString.charCodeAt(i);\n }\n\n return array;\n}","/**\n * Stands in for `@xmldom/xmldom` in browser bundles. mpd-parser imports a\n * full XML parser so it can run in Node; every browser and WebView already has\n * one. Substituting the platform implementation removes ~70 KB minified from\n * the DASH bundle. Node test runs are not aliased and keep the real package.\n * See specs/packaging.md.\n *\n * `window`, not `globalThis`: the IIFE builds serve Chromium 49-era devices,\n * and `globalThis` only arrived in Chromium 71.\n */\nexport const { DOMParser } = window;\n","/*! @name mpd-parser @version 1.4.0 @license Apache-2.0 */\nimport resolveUrl from '@videojs/vhs-utils/es/resolve-url';\nimport window from 'global/window';\nimport { forEachMediaGroup } from '@videojs/vhs-utils/es/media-groups';\nimport decodeB64ToUint8Array from '@videojs/vhs-utils/es/decode-b64-to-uint8-array';\nimport { DOMParser } from '@xmldom/xmldom';\n\nvar version = \"1.4.0\";\n\nconst isObject = obj => {\n return !!obj && typeof obj === 'object';\n};\n\nconst merge = (...objects) => {\n return objects.reduce((result, source) => {\n if (typeof source !== 'object') {\n return result;\n }\n\n Object.keys(source).forEach(key => {\n if (Array.isArray(result[key]) && Array.isArray(source[key])) {\n result[key] = result[key].concat(source[key]);\n } else if (isObject(result[key]) && isObject(source[key])) {\n result[key] = merge(result[key], source[key]);\n } else {\n result[key] = source[key];\n }\n });\n return result;\n }, {});\n};\nconst values = o => Object.keys(o).map(k => o[k]);\n\nconst range = (start, end) => {\n const result = [];\n\n for (let i = start; i < end; i++) {\n result.push(i);\n }\n\n return result;\n};\nconst flatten = lists => lists.reduce((x, y) => x.concat(y), []);\nconst from = list => {\n if (!list.length) {\n return [];\n }\n\n const result = [];\n\n for (let i = 0; i < list.length; i++) {\n result.push(list[i]);\n }\n\n return result;\n};\nconst findIndexes = (l, key) => l.reduce((a, e, i) => {\n if (e[key]) {\n a.push(i);\n }\n\n return a;\n}, []);\n/**\n * Returns a union of the included lists provided each element can be identified by a key.\n *\n * @param {Array} list - list of lists to get the union of\n * @param {Function} keyFunction - the function to use as a key for each element\n *\n * @return {Array} the union of the arrays\n */\n\nconst union = (lists, keyFunction) => {\n return values(lists.reduce((acc, list) => {\n list.forEach(el => {\n acc[keyFunction(el)] = el;\n });\n return acc;\n }, {}));\n};\n\nvar errors = {\n INVALID_NUMBER_OF_PERIOD: 'INVALID_NUMBER_OF_PERIOD',\n INVALID_NUMBER_OF_CONTENT_STEERING: 'INVALID_NUMBER_OF_CONTENT_STEERING',\n DASH_EMPTY_MANIFEST: 'DASH_EMPTY_MANIFEST',\n DASH_INVALID_XML: 'DASH_INVALID_XML',\n NO_BASE_URL: 'NO_BASE_URL',\n MISSING_SEGMENT_INFORMATION: 'MISSING_SEGMENT_INFORMATION',\n SEGMENT_TIME_UNSPECIFIED: 'SEGMENT_TIME_UNSPECIFIED',\n UNSUPPORTED_UTC_TIMING_SCHEME: 'UNSUPPORTED_UTC_TIMING_SCHEME'\n};\n\n/**\n * @typedef {Object} SingleUri\n * @property {string} uri - relative location of segment\n * @property {string} resolvedUri - resolved location of segment\n * @property {Object} byterange - Object containing information on how to make byte range\n * requests following byte-range-spec per RFC2616.\n * @property {String} byterange.length - length of range request\n * @property {String} byterange.offset - byte offset of range request\n *\n * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1\n */\n\n/**\n * Converts a URLType node (5.3.9.2.3 Table 13) to a segment object\n * that conforms to how m3u8-parser is structured\n *\n * @see https://github.com/videojs/m3u8-parser\n *\n * @param {string} baseUrl - baseUrl provided by <BaseUrl> nodes\n * @param {string} source - source url for segment\n * @param {string} range - optional range used for range calls,\n * follows RFC 2616, Clause 14.35.1\n * @return {SingleUri} full segment information transformed into a format similar\n * to m3u8-parser\n */\n\nconst urlTypeToSegment = ({\n baseUrl = '',\n source = '',\n range = '',\n indexRange = ''\n}) => {\n const segment = {\n uri: source,\n resolvedUri: resolveUrl(baseUrl || '', source)\n };\n\n if (range || indexRange) {\n const rangeStr = range ? range : indexRange;\n const ranges = rangeStr.split('-'); // default to parsing this as a BigInt if possible\n\n let startRange = window.BigInt ? window.BigInt(ranges[0]) : parseInt(ranges[0], 10);\n let endRange = window.BigInt ? window.BigInt(ranges[1]) : parseInt(ranges[1], 10); // convert back to a number if less than MAX_SAFE_INTEGER\n\n if (startRange < Number.MAX_SAFE_INTEGER && typeof startRange === 'bigint') {\n startRange = Number(startRange);\n }\n\n if (endRange < Number.MAX_SAFE_INTEGER && typeof endRange === 'bigint') {\n endRange = Number(endRange);\n }\n\n let length;\n\n if (typeof endRange === 'bigint' || typeof startRange === 'bigint') {\n length = window.BigInt(endRange) - window.BigInt(startRange) + window.BigInt(1);\n } else {\n length = endRange - startRange + 1;\n }\n\n if (typeof length === 'bigint' && length < Number.MAX_SAFE_INTEGER) {\n length = Number(length);\n } // byterange should be inclusive according to\n // RFC 2616, Clause 14.35.1\n\n\n segment.byterange = {\n length,\n offset: startRange\n };\n }\n\n return segment;\n};\nconst byteRangeToString = byterange => {\n // `endRange` is one less than `offset + length` because the HTTP range\n // header uses inclusive ranges\n let endRange;\n\n if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {\n endRange = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);\n } else {\n endRange = byterange.offset + byterange.length - 1;\n }\n\n return `${byterange.offset}-${endRange}`;\n};\n\n/**\n * parse the end number attribue that can be a string\n * number, or undefined.\n *\n * @param {string|number|undefined} endNumber\n * The end number attribute.\n *\n * @return {number|null}\n * The result of parsing the end number.\n */\n\nconst parseEndNumber = endNumber => {\n if (endNumber && typeof endNumber !== 'number') {\n endNumber = parseInt(endNumber, 10);\n }\n\n if (isNaN(endNumber)) {\n return null;\n }\n\n return endNumber;\n};\n/**\n * Functions for calculating the range of available segments in static and dynamic\n * manifests.\n */\n\n\nconst segmentRange = {\n /**\n * Returns the entire range of available segments for a static MPD\n *\n * @param {Object} attributes\n * Inheritied MPD attributes\n * @return {{ start: number, end: number }}\n * The start and end numbers for available segments\n */\n static(attributes) {\n const {\n duration,\n timescale = 1,\n sourceDuration,\n periodDuration\n } = attributes;\n const endNumber = parseEndNumber(attributes.endNumber);\n const segmentDuration = duration / timescale;\n\n if (typeof endNumber === 'number') {\n return {\n start: 0,\n end: endNumber\n };\n }\n\n if (typeof periodDuration === 'number') {\n return {\n start: 0,\n end: periodDuration / segmentDuration\n };\n }\n\n return {\n start: 0,\n end: sourceDuration / segmentDuration\n };\n },\n\n /**\n * Returns the current live window range of available segments for a dynamic MPD\n *\n * @param {Object} attributes\n * Inheritied MPD attributes\n * @return {{ start: number, end: number }}\n * The start and end numbers for available segments\n */\n dynamic(attributes) {\n const {\n NOW,\n clientOffset,\n availabilityStartTime,\n timescale = 1,\n duration,\n periodStart = 0,\n minimumUpdatePeriod = 0,\n timeShiftBufferDepth = Infinity\n } = attributes;\n const endNumber = parseEndNumber(attributes.endNumber); // clientOffset is passed in at the top level of mpd-parser and is an offset calculated\n // after retrieving UTC server time.\n\n const now = (NOW + clientOffset) / 1000; // WC stands for Wall Clock.\n // Convert the period start time to EPOCH.\n\n const periodStartWC = availabilityStartTime + periodStart; // Period end in EPOCH is manifest's retrieval time + time until next update.\n\n const periodEndWC = now + minimumUpdatePeriod;\n const periodDuration = periodEndWC - periodStartWC;\n const segmentCount = Math.ceil(periodDuration * timescale / duration);\n const availableStart = Math.floor((now - periodStartWC - timeShiftBufferDepth) * timescale / duration);\n const availableEnd = Math.floor((now - periodStartWC) * timescale / duration);\n return {\n start: Math.max(0, availableStart),\n end: typeof endNumber === 'number' ? endNumber : Math.min(segmentCount, availableEnd)\n };\n }\n\n};\n/**\n * Maps a range of numbers to objects with information needed to build the corresponding\n * segment list\n *\n * @name toSegmentsCallback\n * @function\n * @param {number} number\n * Number of the segment\n * @param {number} index\n * Index of the number in the range list\n * @return {{ number: Number, duration: Number, timeline: Number, time: Number }}\n * Object with segment timing and duration info\n */\n\n/**\n * Returns a callback for Array.prototype.map for mapping a range of numbers to\n * information needed to build the segment list.\n *\n * @param {Object} attributes\n * Inherited MPD attributes\n * @return {toSegmentsCallback}\n * Callback map function\n */\n\nconst toSegments = attributes => number => {\n const {\n duration,\n timescale = 1,\n periodStart,\n startNumber = 1\n } = attributes;\n return {\n number: startNumber + number,\n duration: duration / timescale,\n timeline: periodStart,\n time: number * duration\n };\n};\n/**\n * Returns a list of objects containing segment timing and duration info used for\n * building the list of segments. This uses the @duration attribute specified\n * in the MPD manifest to derive the range of segments.\n *\n * @param {Object} attributes\n * Inherited MPD attributes\n * @return {{number: number, duration: number, time: number, timeline: number}[]}\n * List of Objects with segment timing and duration info\n */\n\nconst parseByDuration = attributes => {\n const {\n type,\n duration,\n timescale = 1,\n periodDuration,\n sourceDuration\n } = attributes;\n const {\n start,\n end\n } = segmentRange[type](attributes);\n const segments = range(start, end).map(toSegments(attributes));\n\n if (type === 'static') {\n const index = segments.length - 1; // section is either a period or the full source\n\n const sectionDuration = typeof periodDuration === 'number' ? periodDuration : sourceDuration; // final segment may be less than full segment duration\n\n segments[index].duration = sectionDuration - duration / timescale * index;\n }\n\n return segments;\n};\n\n/**\n * Translates SegmentBase into a set of segments.\n * (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each\n * node should be translated into segment.\n *\n * @param {Object} attributes\n * Object containing all inherited attributes from parent elements with attribute\n * names as keys\n * @return {Object.<Array>} list of segments\n */\n\nconst segmentsFromBase = attributes => {\n const {\n baseUrl,\n initialization = {},\n sourceDuration,\n indexRange = '',\n periodStart,\n presentationTime,\n number = 0,\n duration\n } = attributes; // base url is required for SegmentBase to work, per spec (Section 5.3.9.2.1)\n\n if (!baseUrl) {\n throw new Error(errors.NO_BASE_URL);\n }\n\n const initSegment = urlTypeToSegment({\n baseUrl,\n source: initialization.sourceURL,\n range: initialization.range\n });\n const segment = urlTypeToSegment({\n baseUrl,\n source: baseUrl,\n indexRange\n });\n segment.map = initSegment; // If there is a duration, use it, otherwise use the given duration of the source\n // (since SegmentBase is only for one total segment)\n\n if (duration) {\n const segmentTimeInfo = parseByDuration(attributes);\n\n if (segmentTimeInfo.length) {\n segment.duration = segmentTimeInfo[0].duration;\n segment.timeline = segmentTimeInfo[0].timeline;\n }\n } else if (sourceDuration) {\n segment.duration = sourceDuration;\n segment.timeline = periodStart;\n } // If presentation time is provided, these segments are being generated by SIDX\n // references, and should use the time provided. For the general case of SegmentBase,\n // there should only be one segment in the period, so its presentation time is the same\n // as its period start.\n\n\n segment.presentationTime = presentationTime || periodStart;\n segment.number = number;\n return [segment];\n};\n/**\n * Given a playlist, a sidx box, and a baseUrl, update the segment list of the playlist\n * according to the sidx information given.\n *\n * playlist.sidx has metadadata about the sidx where-as the sidx param\n * is the parsed sidx box itself.\n *\n * @param {Object} playlist the playlist to update the sidx information for\n * @param {Object} sidx the parsed sidx box\n * @return {Object} the playlist object with the updated sidx information\n */\n\nconst addSidxSegmentsToPlaylist$1 = (playlist, sidx, baseUrl) => {\n // Retain init segment information\n const initSegment = playlist.sidx.map ? playlist.sidx.map : null; // Retain source duration from initial main manifest parsing\n\n const sourceDuration = playlist.sidx.duration; // Retain source timeline\n\n const timeline = playlist.timeline || 0;\n const sidxByteRange = playlist.sidx.byterange;\n const sidxEnd = sidxByteRange.offset + sidxByteRange.length; // Retain timescale of the parsed sidx\n\n const timescale = sidx.timescale; // referenceType 1 refers to other sidx boxes\n\n const mediaReferences = sidx.references.filter(r => r.referenceType !== 1);\n const segments = [];\n const type = playlist.endList ? 'static' : 'dynamic';\n const periodStart = playlist.sidx.timeline;\n let presentationTime = periodStart;\n let number = playlist.mediaSequence || 0; // firstOffset is the offset from the end of the sidx box\n\n let startIndex; // eslint-disable-next-line\n\n if (typeof sidx.firstOffset === 'bigint') {\n startIndex = window.BigInt(sidxEnd) + sidx.firstOffset;\n } else {\n startIndex = sidxEnd + sidx.firstOffset;\n }\n\n for (let i = 0; i < mediaReferences.length; i++) {\n const reference = sidx.references[i]; // size of the referenced (sub)segment\n\n const size = reference.referencedSize; // duration of the referenced (sub)segment, in the timescale\n // this will be converted to seconds when generating segments\n\n const duration = reference.subsegmentDuration; // should be an inclusive range\n\n let endIndex; // eslint-disable-next-line\n\n if (typeof startIndex === 'bigint') {\n endIndex = startIndex + window.BigInt(size) - window.BigInt(1);\n } else {\n endIndex = startIndex + size - 1;\n }\n\n const indexRange = `${startIndex}-${endIndex}`;\n const attributes = {\n baseUrl,\n timescale,\n timeline,\n periodStart,\n presentationTime,\n number,\n duration,\n sourceDuration,\n indexRange,\n type\n };\n const segment = segmentsFromBase(attributes)[0];\n\n if (initSegment) {\n segment.map = initSegment;\n }\n\n segments.push(segment);\n\n if (typeof startIndex === 'bigint') {\n startIndex += window.BigInt(size);\n } else {\n startIndex += size;\n }\n\n presentationTime += duration / timescale;\n number++;\n }\n\n playlist.segments = segments;\n return playlist;\n};\n\nconst SUPPORTED_MEDIA_TYPES = ['AUDIO', 'SUBTITLES']; // allow one 60fps frame as leniency (arbitrarily chosen)\n\nconst TIME_FUDGE = 1 / 60;\n/**\n * Given a list of timelineStarts, combines, dedupes, and sorts them.\n *\n * @param {TimelineStart[]} timelineStarts - list of timeline starts\n *\n * @return {TimelineStart[]} the combined and deduped timeline starts\n */\n\nconst getUniqueTimelineStarts = timelineStarts => {\n return union(timelineStarts, ({\n timeline\n }) => timeline).sort((a, b) => a.timeline > b.timeline ? 1 : -1);\n};\n/**\n * Finds the playlist with the matching NAME attribute.\n *\n * @param {Array} playlists - playlists to search through\n * @param {string} name - the NAME attribute to search for\n *\n * @return {Object|null} the matching playlist object, or null\n */\n\nconst findPlaylistWithName = (playlists, name) => {\n for (let i = 0; i < playlists.length; i++) {\n if (playlists[i].attributes.NAME === name) {\n return playlists[i];\n }\n }\n\n return null;\n};\n/**\n * Gets a flattened array of media group playlists.\n *\n * @param {Object} manifest - the main manifest object\n *\n * @return {Array} the media group playlists\n */\n\nconst getMediaGroupPlaylists = manifest => {\n let mediaGroupPlaylists = [];\n forEachMediaGroup(manifest, SUPPORTED_MEDIA_TYPES, (properties, type, group, label) => {\n mediaGroupPlaylists = mediaGroupPlaylists.concat(properties.playlists || []);\n });\n return mediaGroupPlaylists;\n};\n/**\n * Updates the playlist's media sequence numbers.\n *\n * @param {Object} config - options object\n * @param {Object} config.playlist - the playlist to update\n * @param {number} config.mediaSequence - the mediaSequence number to start with\n */\n\nconst updateMediaSequenceForPlaylist = ({\n playlist,\n mediaSequence\n}) => {\n playlist.mediaSequence = mediaSequence;\n playlist.segments.forEach((segment, index) => {\n segment.number = playlist.mediaSequence + index;\n });\n};\n/**\n * Updates the media and discontinuity sequence numbers of newPlaylists given oldPlaylists\n * and a complete list of timeline starts.\n *\n * If no matching playlist is found, only the discontinuity sequence number of the playlist\n * will be updated.\n *\n * Since early available timelines are not supported, at least one segment must be present.\n *\n * @param {Object} config - options object\n * @param {Object[]} oldPlaylists - the old playlists to use as a reference\n * @param {Object[]} newPlaylists - the new playlists to update\n * @param {Object} timelineStarts - all timelineStarts seen in the stream to this point\n */\n\nconst updateSequenceNumbers = ({\n oldPlaylists,\n newPlaylists,\n timelineStarts\n}) => {\n newPlaylists.forEach(playlist => {\n playlist.discontinuitySequence = timelineStarts.findIndex(function ({\n timeline\n }) {\n return timeline === playlist.timeline;\n }); // Playlists NAMEs come from DASH Representation IDs, which are mandatory\n // (see ISO_23009-1-2012 5.3.5.2).\n //\n // If the same Representation existed in a prior Period, it will retain the same NAME.\n\n const oldPlaylist = findPlaylistWithName(oldPlaylists, playlist.attributes.NAME);\n\n if (!oldPlaylist) {\n // Since this is a new playlist, the media sequence values can start from 0 without\n // consequence.\n return;\n } // TODO better support for live SIDX\n //\n // As of this writing, mpd-parser does not support multiperiod SIDX (in live or VOD).\n // This is evident by a playlist only having a single SIDX reference. In a multiperiod\n // playlist there would need to be multiple SIDX references. In addition, live SIDX is\n // not supported when the SIDX properties change on refreshes.\n //\n // In the future, if support needs to be added, the merging logic here can be called\n // after SIDX references are resolved. For now, exit early to prevent exceptions being\n // thrown due to undefined references.\n\n\n if (playlist.sidx) {\n return;\n } // Since we don't yet support early available timelines, we don't need to support\n // playlists with no segments.\n\n\n const firstNewSegment = playlist.segments[0];\n const oldMatchingSegmentIndex = oldPlaylist.segments.findIndex(function (oldSegment) {\n return Math.abs(oldSegment.presentationTime - firstNewSegment.presentationTime) < TIME_FUDGE;\n }); // No matching segment from the old playlist means the entire playlist was refreshed.\n // In this case the media sequence should account for this update, and the new segments\n // should be marked as discontinuous from the prior content, since the last prior\n // timeline was removed.\n\n if (oldMatchingSegmentIndex === -1) {\n updateMediaSequenceForPlaylist({\n playlist,\n mediaSequence: oldPlaylist.mediaSequence + oldPlaylist.segments.length\n });\n playlist.segments[0].discontinuity = true;\n playlist.discontinuityStarts.unshift(0); // No matching segment does not necessarily mean there's missing content.\n //\n // If the new playlist's timeline is the same as the last seen segment's timeline,\n // then a discontinuity can be added to identify that there's potentially missing\n // content. If there's no missing content, the discontinuity should still be rather\n // harmless. It's possible that if segment durations are accurate enough, that the\n // existence of a gap can be determined using the presentation times and durations,\n // but if the segment timing info is off, it may introduce more problems than simply\n // adding the discontinuity.\n //\n // If the new playlist's timeline is different from the last seen segment's timeline,\n // then a discontinuity can be added to identify that this is the first seen segment\n // of a new timeline. However, the logic at the start of this function that\n // determined the disconinuity sequence by timeline index is now off by one (the\n // discontinuity of the newest timeline hasn't yet fallen off the manifest...since\n // we added it), so the disconinuity sequence must be decremented.\n //\n // A period may also have a duration of zero, so the case of no segments is handled\n // here even though we don't yet support early available periods.\n\n if (!oldPlaylist.segments.length && playlist.timeline > oldPlaylist.timeline || oldPlaylist.segments.length && playlist.timeline > oldPlaylist.segments[oldPlaylist.segments.length - 1].timeline) {\n playlist.discontinuitySequence--;\n }\n\n return;\n } // If the first segment matched with a prior segment on a discontinuity (it's matching\n // on the first segment of a period), then the discontinuitySequence shouldn't be the\n // timeline's matching one, but instead should be the one prior, and the first segment\n // of the new manifest should be marked with a discontinuity.\n //\n // The reason for this special case is that discontinuity sequence shows how many\n // discontinuities have fallen off of the playlist, and discontinuities are marked on\n // the first segment of a new \"timeline.\" Because of this, while DASH will retain that\n // Period while the \"timeline\" exists, HLS keeps track of it via the discontinuity\n // sequence, and that first segment is an indicator, but can be removed before that\n // timeline is gone.\n\n\n const oldMatchingSegment = oldPlaylist.segments[oldMatchingSegmentIndex];\n\n if (oldMatchingSegment.discontinuity && !firstNewSegment.discontinuity) {\n firstNewSegment.discontinuity = true;\n playlist.discontinuityStarts.unshift(0);\n playlist.discontinuitySequence--;\n }\n\n updateMediaSequenceForPlaylist({\n playlist,\n mediaSequence: oldPlaylist.segments[oldMatchingSegmentIndex].number\n });\n });\n};\n/**\n * Given an old parsed manifest object and a new parsed manifest object, updates the\n * sequence and timing values within the new manifest to ensure that it lines up with the\n * old.\n *\n * @param {Array} oldManifest - the old main manifest object\n * @param {Array} newManifest - the new main manifest object\n *\n * @return {Object} the updated new manifest object\n */\n\nconst positionManifestOnTimeline = ({\n oldManifest,\n newManifest\n}) => {\n // Starting from v4.1.2 of the IOP, section 4.4.3.3 states:\n //\n // \"MPD@availabilityStartTime and Period@start shall not be changed over MPD updates.\"\n //\n // This was added from https://github.com/Dash-Industry-Forum/DASH-IF-IOP/issues/160\n //\n // Because of this change, and the difficulty of supporting periods with changing start\n // times, periods with changing start times are not supported. This makes the logic much\n // simpler, since periods with the same start time can be considerred the same period\n // across refreshes.\n //\n // To give an example as to the difficulty of handling periods where the start time may\n // change, if a single period manifest is refreshed with another manifest with a single\n // period, and both the start and end times are increased, then the only way to determine\n // if it's a new period or an old one that has changed is to look through the segments of\n // each playlist and determine the presentation time bounds to find a match. In addition,\n // if the period start changed to exceed the old period end, then there would be no\n // match, and it would not be possible to determine whether the refreshed period is a new\n // one or the old one.\n const oldPlaylists = oldManifest.playlists.concat(getMediaGroupPlaylists(oldManifest));\n const newPlaylists = newManifest.playlists.concat(getMediaGroupPlaylists(newManifest)); // Save all seen timelineStarts to the new manifest. Although this potentially means that\n // there's a \"memory leak\" in that it will never stop growing, in reality, only a couple\n // of properties are saved for each seen Period. Even long running live streams won't\n // generate too many Periods, unless the stream is watched for decades. In the future,\n // this can be optimized by mapping to discontinuity sequence numbers for each timeline,\n // but it may not become an issue, and the additional info can be useful for debugging.\n\n newManifest.timelineStarts = getUniqueTimelineStarts([oldManifest.timelineStarts, newManifest.timelineStarts]);\n updateSequenceNumbers({\n oldPlaylists,\n newPlaylists,\n timelineStarts: newManifest.timelineStarts\n });\n return newManifest;\n};\n\nconst generateSidxKey = sidx => sidx && sidx.uri + '-' + byteRangeToString(sidx.byterange);\n\nconst mergeDiscontiguousPlaylists = playlists => {\n // Break out playlists into groups based on their baseUrl\n const playlistsByBaseUrl = playlists.reduce(function (acc, cur) {\n if (!acc[cur.attributes.baseUrl]) {\n acc[cur.attributes.baseUrl] = [];\n }\n\n acc[cur.attributes.baseUrl].push(cur);\n return acc;\n }, {});\n let allPlaylists = [];\n Object.values(playlistsByBaseUrl).forEach(playlistGroup => {\n const mergedPlaylists = values(playlistGroup.reduce((acc, playlist) => {\n // assuming playlist IDs are the same across periods\n // TODO: handle multiperiod where representation sets are not the same\n // across periods\n const name = playlist.attributes.id + (playlist.attributes.lang || '');\n\n if (!acc[name]) {\n // First Period\n acc[name] = playlist;\n acc[name].attributes.timelineStarts = [];\n } else {\n // Subsequent Periods\n if (playlist.segments) {\n // first segment of subsequent periods signal a discontinuity\n if (playlist.segments[0]) {\n playlist.segments[0].discontinuity = true;\n }\n\n acc[name].segments.push(...playlist.segments);\n } // bubble up contentProtection, this assumes all DRM content\n // has the same contentProtection\n\n\n if (playlist.attributes.contentProtection) {\n acc[name].attributes.contentProtection = playlist.attributes.contentProtection;\n }\n }\n\n acc[name].attributes.timelineStarts.push({\n // Although they represent the same number, it's important to have both to make it\n // compatible with HLS potentially having a similar attribute.\n start: playlist.attributes.periodStart,\n timeline: playlist.attributes.periodStart\n });\n return acc;\n }, {}));\n allPlaylists = allPlaylists.concat(mergedPlaylists);\n });\n return allPlaylists.map(playlist => {\n playlist.discontinuityStarts = findIndexes(playlist.segments || [], 'discontinuity');\n return playlist;\n });\n};\n\nconst addSidxSegmentsToPlaylist = (playlist, sidxMapping) => {\n const sidxKey = generateSidxKey(playlist.sidx);\n const sidxMatch = sidxKey && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx;\n\n if (sidxMatch) {\n addSidxSegmentsToPlaylist$1(playlist, sidxMatch, playlist.sidx.resolvedUri);\n }\n\n return playlist;\n};\nconst addSidxSegmentsToPlaylists = (playlists, sidxMapping = {}) => {\n if (!Object.keys(sidxMapping).length) {\n return playlists;\n }\n\n for (const i in playlists) {\n playlists[i] = addSidxSegmentsToPlaylist(playlists[i], sidxMapping);\n }\n\n return playlists;\n};\nconst formatAudioPlaylist = ({\n attributes,\n segments,\n sidx,\n mediaSequence,\n discontinuitySequence,\n discontinuityStarts\n}, isAudioOnly) => {\n const playlist = {\n attributes: {\n NAME: attributes.id,\n BANDWIDTH: attributes.bandwidth,\n CODECS: attributes.codecs,\n ['PROGRAM-ID']: 1\n },\n uri: '',\n endList: attributes.type === 'static',\n timeline: attributes.periodStart,\n resolvedUri: attributes.baseUrl || '',\n targetDuration: attributes.duration,\n discontinuitySequence,\n discontinuityStarts,\n timelineStarts: attributes.timelineStarts,\n mediaSequence,\n segments\n };\n\n if (attributes.contentProtection) {\n playlist.contentProtection = attributes.contentProtection;\n }\n\n if (attributes.serviceLocation) {\n playlist.attributes.serviceLocation = attributes.serviceLocation;\n }\n\n if (sidx) {\n playlist.sidx = sidx;\n }\n\n if (isAudioOnly) {\n playlist.attributes.AUDIO = 'audio';\n playlist.attributes.SUBTITLES = 'subs';\n }\n\n return playlist;\n};\nconst formatVttPlaylist = ({\n attributes,\n segments,\n mediaSequence,\n discontinuityStarts,\n discontinuitySequence\n}) => {\n if (typeof segments === 'undefined') {\n // vtt tracks may use single file in BaseURL\n segments = [{\n uri: attributes.baseUrl,\n timeline: attributes.periodStart,\n resolvedUri: attributes.baseUrl || '',\n duration: attributes.sourceDuration,\n number: 0\n }]; // targetDuration should be the same duration as the only segment\n\n attributes.duration = attributes.sourceDuration;\n }\n\n const m3u8Attributes = {\n NAME: attributes.id,\n BANDWIDTH: attributes.bandwidth,\n ['PROGRAM-ID']: 1\n };\n\n if (attributes.codecs) {\n m3u8Attributes.CODECS = attributes.codecs;\n }\n\n const vttPlaylist = {\n attributes: m3u8Attributes,\n uri: '',\n endList: attributes.type === 'static',\n timeline: attributes.periodStart,\n resolvedUri: attributes.baseUrl || '',\n targetDuration: attributes.duration,\n timelineStarts: attributes.timelineStarts,\n discontinuityStarts,\n discontinuitySequence,\n mediaSequence,\n segments\n };\n\n if (attributes.serviceLocation) {\n vttPlaylist.attributes.serviceLocation = attributes.serviceLocation;\n }\n\n return vttPlaylist;\n};\nconst organizeAudioPlaylists = (playlists, sidxMapping = {}, isAudioOnly = false) => {\n let mainPlaylist;\n const formattedPlaylists = playlists.reduce((a, playlist) => {\n const role = playlist.attributes.role && playlist.attributes.role.value || '';\n const language = playlist.attributes.lang || '';\n let label = playlist.attributes.label || 'main';\n\n if (language && !playlist.attributes.label) {\n const roleLabel = role ? ` (${role})` : '';\n label = `${playlist.attributes.lang}${roleLabel}`;\n }\n\n if (!a[label]) {\n a[label] = {\n language,\n autoselect: true,\n default: role === 'main',\n playlists: [],\n uri: ''\n };\n }\n\n const formatted = addSidxSegmentsToPlaylist(formatAudioPlaylist(playlist, isAudioOnly), sidxMapping);\n a[label].playlists.push(formatted);\n\n if (typeof mainPlaylist === 'undefined' && role === 'main') {\n mainPlaylist = playlist;\n mainPlaylist.default = true;\n }\n\n return a;\n }, {}); // if no playlists have role \"main\", mark the first as main\n\n if (!mainPlaylist) {\n const firstLabel = Object.keys(formattedPlaylists)[0];\n formattedPlaylists[firstLabel].default = true;\n }\n\n return formattedPlaylists;\n};\nconst organizeVttPlaylists = (playlists, sidxMapping = {}) => {\n return playlists.reduce((a, playlist) => {\n const label = playlist.attributes.label || playlist.attributes.lang || 'text';\n const language = playlist.attributes.lang || 'und';\n\n if (!a[label]) {\n a[label] = {\n language,\n default: false,\n autoselect: false,\n playlists: [],\n uri: ''\n };\n }\n\n a[label].playlists.push(addSidxSegmentsToPlaylist(formatVttPlaylist(playlist), sidxMapping));\n return a;\n }, {});\n};\n\nconst organizeCaptionServices = captionServices => captionServices.reduce((svcObj, svc) => {\n if (!svc) {\n return svcObj;\n }\n\n svc.forEach(service => {\n const {\n channel,\n language\n } = service;\n svcObj[language] = {\n autoselect: false,\n default: false,\n instreamId: channel,\n language\n };\n\n if (service.hasOwnProperty('aspectRatio')) {\n svcObj[language].aspectRatio = service.aspectRatio;\n }\n\n if (service.hasOwnProperty('easyReader')) {\n svcObj[language].easyReader = service.easyReader;\n }\n\n if (service.hasOwnProperty('3D')) {\n svcObj[language]['3D'] = service['3D'];\n }\n });\n return svcObj;\n}, {});\n\nconst formatVideoPlaylist = ({\n attributes,\n segments,\n sidx,\n discontinuityStarts\n}) => {\n const playlist = {\n attributes: {\n NAME: attributes.id,\n AUDIO: 'audio',\n SUBTITLES: 'subs',\n RESOLUTION: {\n width: attributes.width,\n height: attributes.height\n },\n CODECS: attributes.codecs,\n BANDWIDTH: attributes.bandwidth,\n ['PROGRAM-ID']: 1\n },\n uri: '',\n endList: attributes.type === 'static',\n timeline: attributes.periodStart,\n resolvedUri: attributes.baseUrl || '',\n targetDuration: attributes.duration,\n discontinuityStarts,\n timelineStarts: attributes.timelineStarts,\n segments\n };\n\n if (attributes.frameRate) {\n playlist.attributes['FRAME-RATE'] = attributes.frameRate;\n } // qualityRanking is inversely related to quality (higher value = lower quality)\n // so SCORE is calculated as 1/(qualityRanking+1) (higher SCORE = higher quality)\n // The +1 ensures we avoid division by zero when qualityRanking is 0\n\n\n if (attributes.qualityRanking !== undefined) {\n playlist.attributes.SCORE = 1 / (attributes.qualityRanking + 1);\n }\n\n if (attributes.contentProtection) {\n playlist.contentProtection = attributes.contentProtection;\n }\n\n if (attributes.serviceLocation) {\n playlist.attributes.serviceLocation = attributes.serviceLocation;\n }\n\n if (sidx) {\n playlist.sidx = sidx;\n }\n\n return playlist;\n};\n\nconst videoOnly = ({\n attributes\n}) => attributes.mimeType === 'video/mp4' || attributes.mimeType === 'video/webm' || attributes.contentType === 'video';\n\nconst audioOnly = ({\n attributes\n}) => attributes.mimeType === 'audio/mp4' || attributes.mimeType === 'audio/webm' || attributes.contentType === 'audio';\n\nconst vttOnly = ({\n attributes\n}) => attributes.mimeType === 'text/vtt' || attributes.contentType === 'text';\n/**\n * Contains start and timeline properties denoting a timeline start. For DASH, these will\n * be the same number.\n *\n * @typedef {Object} TimelineStart\n * @property {number} start - the start time of the timeline\n * @property {number} timeline - the timeline number\n */\n\n/**\n * Adds appropriate media and discontinuity sequence values to the segments and playlists.\n *\n * Throughout mpd-parser, the `number` attribute is used in relation to `startNumber`, a\n * DASH specific attribute used in constructing segment URI's from templates. However, from\n * an HLS perspective, the `number` attribute on a segment would be its `mediaSequence`\n * value, which should start at the original media sequence value (or 0) and increment by 1\n * for each segment thereafter. Since DASH's `startNumber` values are independent per\n * period, it doesn't make sense to use it for `number`. Instead, assume everything starts\n * from a 0 mediaSequence value and increment from there.\n *\n * Note that VHS currently doesn't use the `number` property, but it can be helpful for\n * debugging and making sense of the manifest.\n *\n * For live playlists, to account for values increasing in manifests when periods are\n * removed on refreshes, merging logic should be used to update the numbers to their\n * appropriate values (to ensure they're sequential and increasing).\n *\n * @param {Object[]} playlists - the playlists to update\n * @param {TimelineStart[]} timelineStarts - the timeline starts for the manifest\n */\n\n\nconst addMediaSequenceValues = (playlists, timelineStarts) => {\n // increment all segments sequentially\n playlists.forEach(playlist => {\n playlist.mediaSequence = 0;\n playlist.discontinuitySequence = timelineStarts.findIndex(function ({\n timeline\n }) {\n return timeline === playlist.timeline;\n });\n\n if (!playlist.segments) {\n return;\n }\n\n playlist.segments.forEach((segment, index) => {\n segment.number = index;\n });\n });\n};\n/**\n * Given a media group object, flattens all playlists within the media group into a single\n * array.\n *\n * @param {Object} mediaGroupObject - the media group object\n *\n * @return {Object[]}\n * The media group playlists\n */\n\nconst flattenMediaGroupPlaylists = mediaGroupObject => {\n if (!mediaGroupObject) {\n return [];\n }\n\n return Object.keys(mediaGroupObject).reduce((acc, label) => {\n const labelContents = mediaGroupObject[label];\n return acc.concat(labelContents.playlists);\n }, []);\n};\nconst toM3u8 = ({\n dashPlaylists,\n locations,\n contentSteering,\n sidxMapping = {},\n previousManifest,\n eventStream\n}) => {\n if (!dashPlaylists.length) {\n return {};\n } // grab all main manifest attributes\n\n\n const {\n sourceDuration: duration,\n type,\n suggestedPresentationDelay,\n minimumUpdatePeriod\n } = dashPlaylists[0].attributes;\n const videoPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(videoOnly)).map(formatVideoPlaylist);\n const audioPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(audioOnly));\n const vttPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(vttOnly));\n const captions = dashPlaylists.map(playlist => playlist.attributes.captionServices).filter(Boolean);\n const manifest = {\n allowCache: true,\n discontinuityStarts: [],\n segments: [],\n endList: true,\n mediaGroups: {\n AUDIO: {},\n VIDEO: {},\n ['CLOSED-CAPTIONS']: {},\n SUBTITLES: {}\n },\n uri: '',\n duration,\n playlists: addSidxSegmentsToPlaylists(videoPlaylists, sidxMapping)\n };\n\n if (minimumUpdatePeriod >= 0) {\n manifest.minimumUpdatePeriod = minimumUpdatePeriod * 1000;\n }\n\n if (locations) {\n manifest.locations = locations;\n }\n\n if (contentSteering) {\n manifest.contentSteering = contentSteering;\n }\n\n if (type === 'dynamic') {\n manifest.suggestedPresentationDelay = suggestedPresentationDelay;\n }\n\n if (eventStream && eventStream.length > 0) {\n manifest.eventStream = eventStream;\n }\n\n const isAudioOnly = manifest.playlists.length === 0;\n const organizedAudioGroup = audioPlaylists.length ? organizeAudioPlaylists(audioPlaylists, sidxMapping, isAudioOnly) : null;\n const organizedVttGroup = vttPlaylists.length ? organizeVttPlaylists(vttPlaylists, sidxMapping) : null;\n const formattedPlaylists = videoPlaylists.concat(flattenMediaGroupPlaylists(organizedAudioGroup), flattenMediaGroupPlaylists(organizedVttGroup));\n const playlistTimelineStarts = formattedPlaylists.map(({\n timelineStarts\n }) => timelineStarts);\n manifest.timelineStarts = getUniqueTimelineStarts(playlistTimelineStarts);\n addMediaSequenceValues(formattedPlaylists, manifest.timelineStarts);\n\n if (organizedAudioGroup) {\n manifest.mediaGroups.AUDIO.audio = organizedAudioGroup;\n }\n\n if (organizedVttGroup) {\n manifest.mediaGroups.SUBTITLES.subs = organizedVttGroup;\n }\n\n if (captions.length) {\n manifest.mediaGroups['CLOSED-CAPTIONS'].cc = organizeCaptionServices(captions);\n }\n\n if (previousManifest) {\n return positionManifestOnTimeline({\n oldManifest: previousManifest,\n newManifest: manifest\n });\n }\n\n return manifest;\n};\n\n/**\n * Calculates the R (repetition) value for a live stream (for the final segment\n * in a manifest where the r value is negative 1)\n *\n * @param {Object} attributes\n * Object containing all inherited attributes from parent elements with attribute\n * names as keys\n * @param {number} time\n * current time (typically the total time up until the final segment)\n * @param {number} duration\n * duration property for the given <S />\n *\n * @return {number}\n * R value to reach the end of the given period\n */\nconst getLiveRValue = (attributes, time, duration) => {\n const {\n NOW,\n clientOffset,\n availabilityStartTime,\n timescale = 1,\n periodStart = 0,\n minimumUpdatePeriod = 0\n } = attributes;\n const now = (NOW + clientOffset) / 1000;\n const periodStartWC = availabilityStartTime + periodStart;\n const periodEndWC = now + minimumUpdatePeriod;\n const periodDuration = periodEndWC - periodStartWC;\n return Math.ceil((periodDuration * timescale - time) / duration);\n};\n/**\n * Uses information provided by SegmentTemplate.SegmentTimeline to determine segment\n * timing and duration\n *\n * @param {Object} attributes\n * Object containing all inherited attributes from parent elements with attribute\n * names as keys\n * @param {Object[]} segmentTimeline\n * List of objects representing the attributes of each S element contained within\n *\n * @return {{number: number, duration: number, time: number, timeline: number}[]}\n * List of Objects with segment timing and duration info\n */\n\n\nconst parseByTimeline = (attributes, segmentTimeline) => {\n const {\n type,\n minimumUpdatePeriod = 0,\n media = '',\n sourceDuration,\n timescale = 1,\n startNumber = 1,\n periodStart: timeline\n } = attributes;\n const segments = [];\n let time = -1;\n\n for (let sIndex = 0; sIndex < segmentTimeline.length; sIndex++) {\n const S = segmentTimeline[sIndex];\n const duration = S.d;\n const repeat = S.r || 0;\n const segmentTime = S.t || 0;\n\n if (time < 0) {\n // first segment\n time = segmentTime;\n }\n\n if (segmentTime && segmentTime > time) {\n // discontinuity\n // TODO: How to handle this type of discontinuity\n // timeline++ here would treat it like HLS discontuity and content would\n // get appended without gap\n // E.G.\n // <S t=\"0\" d=\"1\" />\n // <S d=\"1\" />\n // <S d=\"1\" />\n // <S t=\"5\" d=\"1\" />\n // would have $Time$ values of [0, 1, 2, 5]\n // should this be appened at time positions [0, 1, 2, 3],(#EXT-X-DISCONTINUITY)\n // or [0, 1, 2, gap, gap, 5]? (#EXT-X-GAP)\n // does the value of sourceDuration consider this when calculating arbitrary\n // negative @r repeat value?\n // E.G. Same elements as above with this added at the end\n // <S d=\"1\" r=\"-1\" />\n // with a sourceDuration of 10\n // Would the 2 gaps be included in the time duration calculations resulting in\n // 8 segments with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9] or 10 segments\n // with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9, 10, 11] ?\n time = segmentTime;\n }\n\n let count;\n\n if (repeat < 0) {\n const nextS = sIndex + 1;\n\n if (nextS === segmentTimeline.length) {\n // last segment\n if (type === 'dynamic' && minimumUpdatePeriod > 0 && media.indexOf('$Number$') > 0) {\n count = getLiveRValue(attributes, time, duration);\n } else {\n // TODO: This may be incorrect depending on conclusion of TODO above\n count = (sourceDuration * timescale - time) / duration;\n }\n } else {\n count = (segmentTimeline[nextS].t - time) / duration;\n }\n } else {\n count = repeat + 1;\n }\n\n const end = startNumber + segments.length + count;\n let number = startNumber + segments.length;\n\n while (number < end) {\n segments.push({\n number,\n duration: duration / timescale,\n time,\n timeline\n });\n time += duration;\n number++;\n }\n }\n\n return segments;\n};\n\nconst identifierPattern = /\\$([A-z]*)(?:(%0)([0-9]+)d)?\\$/g;\n/**\n * Replaces template identifiers with corresponding values. To be used as the callback\n * for String.prototype.replace\n *\n * @name replaceCallback\n * @function\n * @param {string} match\n * Entire match of identifier\n * @param {string} identifier\n * Name of matched identifier\n * @param {string} format\n * Format tag string. Its presence indicates that padding is expected\n * @param {string} width\n * Desired length of the replaced value. Values less than this width shall be left\n * zero padded\n * @return {string}\n * Replacement for the matched identifier\n */\n\n/**\n * Returns a function to be used as a callback for String.prototype.replace to replace\n * template identifiers\n *\n * @param {Obect} values\n * Object containing values that shall be used to replace known identifiers\n * @param {number} values.RepresentationID\n * Value of the Representation@id attribute\n * @param {number} values.Number\n * Number of the corresponding segment\n * @param {number} values.Bandwidth\n * Value of the Representation@bandwidth attribute.\n * @param {number} values.Time\n * Timestamp value of the corresponding segment\n * @return {replaceCallback}\n * Callback to be used with String.prototype.replace to replace identifiers\n */\n\nconst identifierReplacement = values => (match, identifier, format, width) => {\n if (match === '$$') {\n // escape sequence\n return '$';\n }\n\n if (typeof values[identifier] === 'undefined') {\n return match;\n }\n\n const value = '' + values[identifier];\n\n if (identifier === 'RepresentationID') {\n // Format tag shall not be present with RepresentationID\n return value;\n }\n\n if (!format) {\n width = 1;\n } else {\n width = parseInt(width, 10);\n }\n\n if (value.length >= width) {\n return value;\n }\n\n return `${new Array(width - value.length + 1).join('0')}${value}`;\n};\n/**\n * Constructs a segment url from a template string\n *\n * @param {string} url\n * Template string to construct url from\n * @param {Obect} values\n * Object containing values that shall be used to replace known identifiers\n * @param {number} values.RepresentationID\n * Value of the Representation@id attribute\n * @param {number} values.Number\n * Number of the corresponding segment\n * @param {number} values.Bandwidth\n * Value of the Representation@bandwidth attribute.\n * @param {number} values.Time\n * Timestamp value of the corresponding segment\n * @return {string}\n * Segment url with identifiers replaced\n */\n\nconst constructTemplateUrl = (url, values) => url.replace(identifierPattern, identifierReplacement(values));\n/**\n * Generates a list of objects containing timing and duration information about each\n * segment needed to generate segment uris and the complete segment object\n *\n * @param {Object} attributes\n * Object containing all inherited attributes from parent elements with attribute\n * names as keys\n * @param {Object[]|undefined} segmentTimeline\n * List of objects representing the attributes of each S element contained within\n * the SegmentTimeline element\n * @return {{number: number, duration: number, time: number, timeline: number}[]}\n * List of Objects with segment timing and duration info\n */\n\nconst parseTemplateInfo = (attributes, segmentTimeline) => {\n if (!attributes.duration && !segmentTimeline) {\n // if neither @duration or SegmentTimeline are present, then there shall be exactly\n // one media segment\n return [{\n number: attributes.startNumber || 1,\n duration: attributes.sourceDuration,\n time: 0,\n timeline: attributes.periodStart\n }];\n }\n\n if (attributes.duration) {\n return parseByDuration(attributes);\n }\n\n return parseByTimeline(attributes, segmentTimeline);\n};\n/**\n * Generates a list of segments using information provided by the SegmentTemplate element\n *\n * @param {Object} attributes\n * Object containing all inherited attributes from parent elements with attribute\n * names as keys\n * @param {Object[]|undefined} segmentTimeline\n * List of objects representing the attributes of each S element contained within\n * the SegmentTimeline element\n * @return {Object[]}\n * List of segment objects\n */\n\nconst segmentsFromTemplate = (attributes, segmentTimeline) => {\n const templateValues = {\n RepresentationID: attributes.id,\n Bandwidth: attributes.bandwidth || 0\n };\n const {\n initialization = {\n sourceURL: '',\n range: ''\n }\n } = attributes;\n const mapSegment = urlTypeToSegment({\n baseUrl: attributes.baseUrl,\n source: constructTemplateUrl(initialization.sourceURL, templateValues),\n range: initialization.range\n });\n const segments = parseTemplateInfo(attributes, segmentTimeline);\n return segments.map(segment => {\n templateValues.Number = segment.number;\n templateValues.Time = segment.time;\n const uri = constructTemplateUrl(attributes.media || '', templateValues); // See DASH spec section 5.3.9.2.2\n // - if timescale isn't present on any level, default to 1.\n\n const timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0\n\n const presentationTimeOffset = attributes.presentationTimeOffset || 0;\n const presentationTime = // Even if the @t attribute is not specified for the segment, segment.time is\n // calculated in mpd-parser prior to this, so it's assumed to be available.\n attributes.periodStart + (segment.time - presentationTimeOffset) / timescale;\n const map = {\n uri,\n timeline: segment.timeline,\n duration: segment.duration,\n resolvedUri: resolveUrl(attributes.baseUrl || '', uri),\n map: mapSegment,\n number: segment.number,\n presentationTime\n };\n return map;\n });\n};\n\n/**\n * Converts a <SegmentUrl> (of type URLType from the DASH spec 5.3.9.2 Table 14)\n * to an object that matches the output of a segment in videojs/mpd-parser\n *\n * @param {Object} attributes\n * Object containing all inherited attributes from parent elements with attribute\n * names as keys\n * @param {Object} segmentUrl\n * <SegmentURL> node to translate into a segment object\n * @return {Object} translated segment object\n */\n\nconst SegmentURLToSegmentObject = (attributes, segmentUrl) => {\n const {\n baseUrl,\n initialization = {}\n } = attributes;\n const initSegment = urlTypeToSegment({\n baseUrl,\n source: initialization.sourceURL,\n range: initialization.range\n });\n const segment = urlTypeToSegment({\n baseUrl,\n source: segmentUrl.media,\n range: segmentUrl.mediaRange\n });\n segment.map = initSegment;\n return segment;\n};\n/**\n * Generates a list of segments using information provided by the SegmentList element\n * SegmentList (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each\n * node should be translated into segment.\n *\n * @param {Object} attributes\n * Object containing all inherited attributes from parent elements with attribute\n * names as keys\n * @param {Object[]|undefined} segmentTimeline\n * List of objects representing the attributes of each S element contained within\n * the SegmentTimeline element\n * @return {Object.<Array>} list of segments\n */\n\n\nconst segmentsFromList = (attributes, segmentTimeline) => {\n const {\n duration,\n segmentUrls = [],\n periodStart\n } = attributes; // Per spec (5.3.9.2.1) no way to determine segment duration OR\n // if both SegmentTimeline and @duration are defined, it is outside of spec.\n\n if (!duration && !segmentTimeline || duration && segmentTimeline) {\n throw new Error(errors.SEGMENT_TIME_UNSPECIFIED);\n }\n\n const segmentUrlMap = segmentUrls.map(segmentUrlObject => SegmentURLToSegmentObject(attributes, segmentUrlObject));\n let segmentTimeInfo;\n\n if (duration) {\n segmentTimeInfo = parseByDuration(attributes);\n }\n\n if (segmentTimeline) {\n segmentTimeInfo = parseByTimeline(attributes, segmentTimeline);\n }\n\n const segments = segmentTimeInfo.map((segmentTime, index) => {\n if (segmentUrlMap[index]) {\n const segment = segmentUrlMap[index]; // See DASH spec section 5.3.9.2.2\n // - if timescale isn't present on any level, default to 1.\n\n const timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0\n\n const presentationTimeOffset = attributes.presentationTimeOffset || 0;\n segment.timeline = segmentTime.timeline;\n segment.duration = segmentTime.duration;\n segment.number = segmentTime.number;\n segment.presentationTime = periodStart + (segmentTime.time - presentationTimeOffset) / timescale;\n return segment;\n } // Since we're mapping we should get rid of any blank segments (in case\n // the given SegmentTimeline is handling for more elements than we have\n // SegmentURLs for).\n\n }).filter(segment => segment);\n return segments;\n};\n\nconst generateSegments = ({\n attributes,\n segmentInfo\n}) => {\n let segmentAttributes;\n let segmentsFn;\n\n if (segmentInfo.template) {\n segmentsFn = segmentsFromTemplate;\n segmentAttributes = merge(attributes, segmentInfo.template);\n } else if (segmentInfo.base) {\n segmentsFn = segmentsFromBase;\n segmentAttributes = merge(attributes, segmentInfo.base);\n } else if (segmentInfo.list) {\n segmentsFn = segmentsFromList;\n segmentAttributes = merge(attributes, segmentInfo.list);\n }\n\n const segmentsInfo = {\n attributes\n };\n\n if (!segmentsFn) {\n return segmentsInfo;\n }\n\n const segments = segmentsFn(segmentAttributes, segmentInfo.segmentTimeline); // The @duration attribute will be used to determin the playlist's targetDuration which\n // must be in seconds. Since we've generated the segment list, we no longer need\n // @duration to be in @timescale units, so we can convert it here.\n\n if (segmentAttributes.duration) {\n const {\n duration,\n timescale = 1\n } = segmentAttributes;\n segmentAttributes.duration = duration / timescale;\n } else if (segments.length) {\n // if there is no @duration attribute, use the largest segment duration as\n // as target duration\n segmentAttributes.duration = segments.reduce((max, segment) => {\n return Math.max(max, Math.ceil(segment.duration));\n }, 0);\n } else {\n segmentAttributes.duration = 0;\n }\n\n segmentsInfo.attributes = segmentAttributes;\n segmentsInfo.segments = segments; // This is a sidx box without actual segment information\n\n if (segmentInfo.base && segmentAttributes.indexRange) {\n segmentsInfo.sidx = segments[0];\n segmentsInfo.segments = [];\n }\n\n return segmentsInfo;\n};\nconst toPlaylists = representations => representations.map(generateSegments);\n\nconst findChildren = (element, name) => from(element.childNodes).filter(({\n tagName\n}) => tagName === name);\nconst getContent = element => element.textContent.trim();\n\n/**\n * Converts the provided string that may contain a division operation to a number.\n *\n * @param {string} value - the provided string value\n *\n * @return {number} the parsed string value\n */\nconst parseDivisionValue = value => {\n return parseFloat(value.split('/').reduce((prev, current) => prev / current));\n};\n\nconst parseDuration = str => {\n const SECONDS_IN_YEAR = 365 * 24 * 60 * 60;\n const SECONDS_IN_MONTH = 30 * 24 * 60 * 60;\n const SECONDS_IN_DAY = 24 * 60 * 60;\n const SECONDS_IN_HOUR = 60 * 60;\n const SECONDS_IN_MIN = 60; // P10Y10M10DT10H10M10.1S\n\n const durationRegex = /P(?:(\\d*)Y)?(?:(\\d*)M)?(?:(\\d*)D)?(?:T(?:(\\d*)H)?(?:(\\d*)M)?(?:([\\d.]*)S)?)?/;\n const match = durationRegex.exec(str);\n\n if (!match) {\n return 0;\n }\n\n const [year, month, day, hour, minute, second] = match.slice(1);\n return parseFloat(year || 0) * SECONDS_IN_YEAR + parseFloat(month || 0) * SECONDS_IN_MONTH + parseFloat(day || 0) * SECONDS_IN_DAY + parseFloat(hour || 0) * SECONDS_IN_HOUR + parseFloat(minute || 0) * SECONDS_IN_MIN + parseFloat(second || 0);\n};\nconst parseDate = str => {\n // Date format without timezone according to ISO 8601\n // YYY-MM-DDThh:mm:ss.ssssss\n const dateRegex = /^\\d+-\\d+-\\d+T\\d+:\\d+:\\d+(\\.\\d+)?$/; // If the date string does not specifiy a timezone, we must specifiy UTC. This is\n // expressed by ending with 'Z'\n\n if (dateRegex.test(str)) {\n str += 'Z';\n }\n\n return Date.parse(str);\n};\n\nconst parsers = {\n /**\n * Specifies the duration of the entire Media Presentation. Format is a duration string\n * as specified in ISO 8601\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The duration in seconds\n */\n mediaPresentationDuration(value) {\n return parseDuration(value);\n },\n\n /**\n * Specifies the Segment availability start time for all Segments referred to in this\n * MPD. For a dynamic manifest, it specifies the anchor for the earliest availability\n * time. Format is a date string as specified in ISO 8601\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The date as seconds from unix epoch\n */\n availabilityStartTime(value) {\n return parseDate(value) / 1000;\n },\n\n /**\n * Specifies the smallest period between potential changes to the MPD. Format is a\n * duration string as specified in ISO 8601\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The duration in seconds\n */\n minimumUpdatePeriod(value) {\n return parseDuration(value);\n },\n\n /**\n * Specifies the suggested presentation delay. Format is a\n * duration string as specified in ISO 8601\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The duration in seconds\n */\n suggestedPresentationDelay(value) {\n return parseDuration(value);\n },\n\n /**\n * specifices the type of mpd. Can be either \"static\" or \"dynamic\"\n *\n * @param {string} value\n * value of attribute as a string\n *\n * @return {string}\n * The type as a string\n */\n type(value) {\n return value;\n },\n\n /**\n * Specifies the duration of the smallest time shifting buffer for any Representation\n * in the MPD. Format is a duration string as specified in ISO 8601\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The duration in seconds\n */\n timeShiftBufferDepth(value) {\n return parseDuration(value);\n },\n\n /**\n * Specifies the PeriodStart time of the Period relative to the availabilityStarttime.\n * Format is a duration string as specified in ISO 8601\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The duration in seconds\n */\n start(value) {\n return parseDuration(value);\n },\n\n /**\n * Specifies the width of the visual presentation\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The parsed width\n */\n width(value) {\n return parseInt(value, 10);\n },\n\n /**\n * Specifies the height of the visual presentation\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The parsed height\n */\n height(value) {\n return parseInt(value, 10);\n },\n\n /**\n * Specifies the bitrate of the representation\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The parsed bandwidth\n */\n bandwidth(value) {\n return parseInt(value, 10);\n },\n\n /**\n * Specifies the frame rate of the representation\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The parsed frame rate\n */\n frameRate(value) {\n return parseDivisionValue(value);\n },\n\n /**\n * Specifies the number of the first Media Segment in this Representation in the Period\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The parsed number\n */\n startNumber(value) {\n return parseInt(value, 10);\n },\n\n /**\n * Specifies the timescale in units per seconds\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The parsed timescale\n */\n timescale(value) {\n return parseInt(value, 10);\n },\n\n /**\n * Specifies the presentationTimeOffset.\n *\n * @param {string} value\n * value of the attribute as a string\n *\n * @return {number}\n * The parsed presentationTimeOffset\n */\n presentationTimeOffset(value) {\n return parseInt(value, 10);\n },\n\n /**\n * Specifies the constant approximate Segment duration\n * NOTE: The <Period> element also contains an @duration attribute. This duration\n * specifies the duration of the Period. This attribute is currently not\n * supported by the rest of the parser, however we still check for it to prevent\n * errors.\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The parsed duration\n */\n duration(value) {\n const parsedValue = parseInt(value, 10);\n\n if (isNaN(parsedValue)) {\n return parseDuration(value);\n }\n\n return parsedValue;\n },\n\n /**\n * Specifies the Segment duration, in units of the value of the @timescale.\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The parsed duration\n */\n d(value) {\n return parseInt(value, 10);\n },\n\n /**\n * Specifies the MPD start time, in @timescale units, the first Segment in the series\n * starts relative to the beginning of the Period\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The parsed time\n */\n t(value) {\n return parseInt(value, 10);\n },\n\n /**\n * Specifies the repeat count of the number of following contiguous Segments with the\n * same duration expressed by the value of @d\n *\n * @param {string} value\n * value of attribute as a string\n * @return {number}\n * The parsed number\n */\n r(value) {\n return parseInt(value, 10);\n },\n\n /**\n * Specifies the presentationTime.\n *\n * @param {string} value\n * value of the attribute as a string\n *\n * @return {number}\n * The parsed presentationTime\n */\n presentationTime(value) {\n return parseInt(value, 10);\n },\n\n /**\n * Specifies the quality ranking of the representation relative to others in the same\n * adaptation set. This is inversely related to quality - higher values represent\n * lower quality content (e.g., 1 = highest quality, 10 = lowest quality).\n *\n * @param {string} value\n * value of the attribute as a string\n *\n * @return {number}\n * The parsed qualityRanking\n */\n qualityRanking(value) {\n return parseInt(value, 10);\n },\n\n /**\n * Alias for qualityRanking to handle lowercase attribute names from HTML DOM.\n *\n * @param {string} value\n * value of the attribute as a string\n *\n * @return {number}\n * The parsed qualityRanking\n */\n qualityranking(value) {\n return parseInt(value, 10);\n },\n\n /**\n * Default parser for all other attributes. Acts as a no-op and just returns the value\n * as a string\n *\n * @param {string} value\n * value of attribute as a string\n * @return {string}\n * Unparsed value\n */\n DEFAULT(value) {\n return value;\n }\n\n};\n/**\n * Maps lowercase attribute names to their camelCase equivalents for internal use.\n * HTML DOM converts attributes to lowercase, but we want to maintain camelCase\n * naming conventions in the parsed output. XML parsers like xmldom preserve\n * the original casing.\n */\n\nconst attributeNameMap = {\n qualityranking: 'qualityRanking'\n};\n/**\n * Gets all the attributes and values of the provided node, parses attributes with known\n * types, and returns an object with attribute names mapped to values.\n *\n * @param {Node} el\n * The node to parse attributes from\n * @return {Object}\n * Object with all attributes of el parsed\n */\n\nconst parseAttributes = el => {\n if (!(el && el.attributes)) {\n return {};\n }\n\n return from(el.attributes).reduce((a, e) => {\n const parseFn = parsers[e.name] || parsers.DEFAULT;\n const attributeName = attributeNameMap[e.name] || e.name;\n a[attributeName] = parseFn(e.value);\n return a;\n }, {});\n};\n\nconst keySystemsMap = {\n 'urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b': 'org.w3.clearkey',\n 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed': 'com.widevine.alpha',\n 'urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95': 'com.microsoft.playready',\n 'urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb': 'com.adobe.primetime',\n // ISO_IEC 23009-1_2022 5.8.5.2.2 The mp4 Protection Scheme\n 'urn:mpeg:dash:mp4protection:2011': 'mp4protection'\n};\n/**\n * Builds a list of urls that is the product of the reference urls and BaseURL values\n *\n * @param {Object[]} references\n * List of objects containing the reference URL as well as its attributes\n * @param {Node[]} baseUrlElements\n * List of BaseURL nodes from the mpd\n * @return {Object[]}\n * List of objects with resolved urls and attributes\n */\n\nconst buildBaseUrls = (references, baseUrlElements) => {\n if (!baseUrlElements.length) {\n return references;\n }\n\n return flatten(references.map(function (reference) {\n return baseUrlElements.map(function (baseUrlElement) {\n const initialBaseUrl = getContent(baseUrlElement);\n const resolvedBaseUrl = resolveUrl(reference.baseUrl, initialBaseUrl);\n const finalBaseUrl = merge(parseAttributes(baseUrlElement), {\n baseUrl: resolvedBaseUrl\n }); // If the URL is resolved, we want to get the serviceLocation from the reference\n // assuming there is no serviceLocation on the initialBaseUrl\n\n if (resolvedBaseUrl !== initialBaseUrl && !finalBaseUrl.serviceLocation && reference.serviceLocation) {\n finalBaseUrl.serviceLocation = reference.serviceLocation;\n }\n\n return finalBaseUrl;\n });\n }));\n};\n/**\n * Contains all Segment information for its containing AdaptationSet\n *\n * @typedef {Object} SegmentInformation\n * @property {Object|undefined} template\n * Contains the attributes for the SegmentTemplate node\n * @property {Object[]|undefined} segmentTimeline\n * Contains a list of atrributes for each S node within the SegmentTimeline node\n * @property {Object|undefined} list\n * Contains the attributes for the SegmentList node\n * @property {Object|undefined} base\n * Contains the attributes for the SegmentBase node\n */\n\n/**\n * Returns all available Segment information contained within the AdaptationSet node\n *\n * @param {Node} adaptationSet\n * The AdaptationSet node to get Segment information from\n * @return {SegmentInformation}\n * The Segment information contained within the provided AdaptationSet\n */\n\nconst getSegmentInformation = adaptationSet => {\n const segmentTemplate = findChildren(adaptationSet, 'SegmentTemplate')[0];\n const segmentList = findChildren(adaptationSet, 'SegmentList')[0];\n const segmentUrls = segmentList && findChildren(segmentList, 'SegmentURL').map(s => merge({\n tag: 'SegmentURL'\n }, parseAttributes(s)));\n const segmentBase = findChildren(adaptationSet, 'SegmentBase')[0];\n const segmentTimelineParentNode = segmentList || segmentTemplate;\n const segmentTimeline = segmentTimelineParentNode && findChildren(segmentTimelineParentNode, 'SegmentTimeline')[0];\n const segmentInitializationParentNode = segmentList || segmentBase || segmentTemplate;\n const segmentInitialization = segmentInitializationParentNode && findChildren(segmentInitializationParentNode, 'Initialization')[0]; // SegmentTemplate is handled slightly differently, since it can have both\n // @initialization and an <Initialization> node. @initialization can be templated,\n // while the node can have a url and range specified. If the <SegmentTemplate> has\n // both @initialization and an <Initialization> subelement we opt to override with\n // the node, as this interaction is not defined in the spec.\n\n const template = segmentTemplate && parseAttributes(segmentTemplate);\n\n if (template && segmentInitialization) {\n template.initialization = segmentInitialization && parseAttributes(segmentInitialization);\n } else if (template && template.initialization) {\n // If it is @initialization we convert it to an object since this is the format that\n // later functions will rely on for the initialization segment. This is only valid\n // for <SegmentTemplate>\n template.initialization = {\n sourceURL: template.initialization\n };\n }\n\n const segmentInfo = {\n template,\n segmentTimeline: segmentTimeline && findChildren(segmentTimeline, 'S').map(s => parseAttributes(s)),\n list: segmentList && merge(parseAttributes(segmentList), {\n segmentUrls,\n initialization: parseAttributes(segmentInitialization)\n }),\n base: segmentBase && merge(parseAttributes(segmentBase), {\n initialization: parseAttributes(segmentInitialization)\n })\n };\n Object.keys(segmentInfo).forEach(key => {\n if (!segmentInfo[key]) {\n delete segmentInfo[key];\n }\n });\n return segmentInfo;\n};\n/**\n * Contains Segment information and attributes needed to construct a Playlist object\n * from a Representation\n *\n * @typedef {Object} RepresentationInformation\n * @property {SegmentInformation} segmentInfo\n * Segment information for this Representation\n * @property {Object} attributes\n * Inherited attributes for this Representation\n */\n\n/**\n * Maps a Representation node to an object containing Segment information and attributes\n *\n * @name inheritBaseUrlsCallback\n * @function\n * @param {Node} representation\n * Representation node from the mpd\n * @return {RepresentationInformation}\n * Representation information needed to construct a Playlist object\n */\n\n/**\n * Returns a callback for Array.prototype.map for mapping Representation nodes to\n * Segment information and attributes using inherited BaseURL nodes.\n *\n * @param {Object} adaptationSetAttributes\n * Contains attributes inherited by the AdaptationSet\n * @param {Object[]} adaptationSetBaseUrls\n * List of objects containing resolved base URLs and attributes\n * inherited by the AdaptationSet\n * @param {SegmentInformation} adaptationSetSegmentInfo\n * Contains Segment information for the AdaptationSet\n * @return {inheritBaseUrlsCallback}\n * Callback map function\n */\n\nconst inheritBaseUrls = (adaptationSetAttributes, adaptationSetBaseUrls, adaptationSetSegmentInfo) => representation => {\n const repBaseUrlElements = findChildren(representation, 'BaseURL');\n const repBaseUrls = buildBaseUrls(adaptationSetBaseUrls, repBaseUrlElements);\n const attributes = merge(adaptationSetAttributes, parseAttributes(representation));\n const representationSegmentInfo = getSegmentInformation(representation);\n return repBaseUrls.map(baseUrl => {\n return {\n segmentInfo: merge(adaptationSetSegmentInfo, representationSegmentInfo),\n attributes: merge(attributes, baseUrl)\n };\n });\n};\n/**\n * Tranforms a series of content protection nodes to\n * an object containing pssh data by key system\n *\n * @param {Node[]} contentProtectionNodes\n * Content protection nodes\n * @return {Object}\n * Object containing pssh data by key system\n */\n\nconst generateKeySystemInformation = contentProtectionNodes => {\n return contentProtectionNodes.reduce((acc, node) => {\n const attributes = parseAttributes(node); // Although it could be argued that according to the UUID RFC spec the UUID string (a-f chars) should be generated\n // as a lowercase string it also mentions it should be treated as case-insensitive on input. Since the key system\n // UUIDs in the keySystemsMap are hardcoded as lowercase in the codebase there isn't any reason not to do\n // .toLowerCase() on the input UUID string from the manifest (at least I could not think of one).\n\n if (attributes.schemeIdUri) {\n attributes.schemeIdUri = attributes.schemeIdUri.toLowerCase();\n }\n\n const keySystem = keySystemsMap[attributes.schemeIdUri];\n\n if (keySystem) {\n acc[keySystem] = {\n attributes\n };\n const psshNode = findChildren(node, 'cenc:pssh')[0];\n\n if (psshNode) {\n const pssh = getContent(psshNode);\n acc[keySystem].pssh = pssh && decodeB64ToUint8Array(pssh);\n }\n }\n\n return acc;\n }, {});\n}; // defined in ANSI_SCTE 214-1 2016\n\n\nconst parseCaptionServiceMetadata = service => {\n // 608 captions\n if (service.schemeIdUri === 'urn:scte:dash:cc:cea-608:2015') {\n const values = typeof service.value !== 'string' ? [] : service.value.split(';');\n return values.map(value => {\n let channel;\n let language; // default language to value\n\n language = value;\n\n if (/^CC\\d=/.test(value)) {\n [channel, language] = value.split('=');\n } else if (/^CC\\d$/.test(value)) {\n channel = value;\n }\n\n return {\n channel,\n language\n };\n });\n } else if (service.schemeIdUri === 'urn:scte:dash:cc:cea-708:2015') {\n const values = typeof service.value !== 'string' ? [] : service.value.split(';');\n return values.map(value => {\n const flags = {\n // service or channel number 1-63\n 'channel': undefined,\n // language is a 3ALPHA per ISO 639.2/B\n // field is required\n 'language': undefined,\n // BIT 1/0 or ?\n // default value is 1, meaning 16:9 aspect ratio, 0 is 4:3, ? is unknown\n 'aspectRatio': 1,\n // BIT 1/0\n // easy reader flag indicated the text is tailed to the needs of beginning readers\n // default 0, or off\n 'easyReader': 0,\n // BIT 1/0\n // If 3d metadata is present (CEA-708.1) then 1\n // default 0\n '3D': 0\n };\n\n if (/=/.test(value)) {\n const [channel, opts = ''] = value.split('=');\n flags.channel = channel;\n flags.language = value;\n opts.split(',').forEach(opt => {\n const [name, val] = opt.split(':');\n\n if (name === 'lang') {\n flags.language = val; // er for easyReadery\n } else if (name === 'er') {\n flags.easyReader = Number(val); // war for wide aspect ratio\n } else if (name === 'war') {\n flags.aspectRatio = Number(val);\n } else if (name === '3D') {\n flags['3D'] = Number(val);\n }\n });\n } else {\n flags.language = value;\n }\n\n if (flags.channel) {\n flags.channel = 'SERVICE' + flags.channel;\n }\n\n return flags;\n });\n }\n};\n/**\n * A map callback that will parse all event stream data for a collection of periods\n * DASH ISO_IEC_23009 5.10.2.2\n * https://dashif-documents.azurewebsites.net/Events/master/event.html#mpd-event-timing\n *\n * @param {PeriodInformation} period object containing necessary period information\n * @return a collection of parsed eventstream event objects\n */\n\nconst toEventStream = period => {\n // get and flatten all EventStreams tags and parse attributes and children\n return flatten(findChildren(period.node, 'EventStream').map(eventStream => {\n const eventStreamAttributes = parseAttributes(eventStream);\n const schemeIdUri = eventStreamAttributes.schemeIdUri; // find all Events per EventStream tag and map to return objects\n\n return findChildren(eventStream, 'Event').map(event => {\n const eventAttributes = parseAttributes(event);\n const presentationTime = eventAttributes.presentationTime || 0;\n const timescale = eventStreamAttributes.timescale || 1;\n const duration = eventAttributes.duration || 0;\n const start = presentationTime / timescale + period.attributes.start;\n return {\n schemeIdUri,\n value: eventStreamAttributes.value,\n id: eventAttributes.id,\n start,\n end: start + duration / timescale,\n messageData: getContent(event) || eventAttributes.messageData,\n contentEncoding: eventStreamAttributes.contentEncoding,\n presentationTimeOffset: eventStreamAttributes.presentationTimeOffset || 0\n };\n });\n }));\n};\n/**\n * Maps an AdaptationSet node to a list of Representation information objects\n *\n * @name toRepresentationsCallback\n * @function\n * @param {Node} adaptationSet\n * AdaptationSet node from the mpd\n * @return {RepresentationInformation[]}\n * List of objects containing Representaion information\n */\n\n/**\n * Returns a callback for Array.prototype.map for mapping AdaptationSet nodes to a list of\n * Representation information objects\n *\n * @param {Object} periodAttributes\n * Contains attributes inherited by the Period\n * @param {Object[]} periodBaseUrls\n * Contains list of objects with resolved base urls and attributes\n * inherited by the Period\n * @param {string[]} periodSegmentInfo\n * Contains Segment Information at the period level\n * @return {toRepresentationsCallback}\n * Callback map function\n */\n\nconst toRepresentations = (periodAttributes, periodBaseUrls, periodSegmentInfo) => adaptationSet => {\n const adaptationSetAttributes = parseAttributes(adaptationSet);\n const adaptationSetBaseUrls = buildBaseUrls(periodBaseUrls, findChildren(adaptationSet, 'BaseURL'));\n const role = findChildren(adaptationSet, 'Role')[0];\n const roleAttributes = {\n role: parseAttributes(role)\n };\n let attrs = merge(periodAttributes, adaptationSetAttributes, roleAttributes);\n const accessibility = findChildren(adaptationSet, 'Accessibility')[0];\n const captionServices = parseCaptionServiceMetadata(parseAttributes(accessibility));\n\n if (captionServices) {\n attrs = merge(attrs, {\n captionServices\n });\n }\n\n const label = findChildren(adaptationSet, 'Label')[0];\n\n if (label && label.childNodes.length) {\n const labelVal = label.childNodes[0].nodeValue.trim();\n attrs = merge(attrs, {\n label: labelVal\n });\n }\n\n const contentProtection = generateKeySystemInformation(findChildren(adaptationSet, 'ContentProtection'));\n\n if (Object.keys(contentProtection).length) {\n attrs = merge(attrs, {\n contentProtection\n });\n }\n\n const segmentInfo = getSegmentInformation(adaptationSet);\n const representations = findChildren(adaptationSet, 'Representation');\n const adaptationSetSegmentInfo = merge(periodSegmentInfo, segmentInfo);\n return flatten(representations.map(inheritBaseUrls(attrs, adaptationSetBaseUrls, adaptationSetSegmentInfo)));\n};\n/**\n * Contains all period information for mapping nodes onto adaptation sets.\n *\n * @typedef {Object} PeriodInformation\n * @property {Node} period.node\n * Period node from the mpd\n * @property {Object} period.attributes\n * Parsed period attributes from node plus any added\n */\n\n/**\n * Maps a PeriodInformation object to a list of Representation information objects for all\n * AdaptationSet nodes contained within the Period.\n *\n * @name toAdaptationSetsCallback\n * @function\n * @param {PeriodInformation} period\n * Period object containing necessary period information\n * @param {number} periodStart\n * Start time of the Period within the mpd\n * @return {RepresentationInformation[]}\n * List of objects containing Representaion information\n */\n\n/**\n * Returns a callback for Array.prototype.map for mapping Period nodes to a list of\n * Representation information objects\n *\n * @param {Object} mpdAttributes\n * Contains attributes inherited by the mpd\n * @param {Object[]} mpdBaseUrls\n * Contains list of objects with resolved base urls and attributes\n * inherited by the mpd\n * @return {toAdaptationSetsCallback}\n * Callback map function\n */\n\nconst toAdaptationSets = (mpdAttributes, mpdBaseUrls) => (period, index) => {\n const periodBaseUrls = buildBaseUrls(mpdBaseUrls, findChildren(period.node, 'BaseURL'));\n const periodAttributes = merge(mpdAttributes, {\n periodStart: period.attributes.start\n });\n\n if (typeof period.attributes.duration === 'number') {\n periodAttributes.periodDuration = period.attributes.duration;\n }\n\n const adaptationSets = findChildren(period.node, 'AdaptationSet');\n const periodSegmentInfo = getSegmentInformation(period.node);\n return flatten(adaptationSets.map(toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo)));\n};\n/**\n * Tranforms an array of content steering nodes into an object\n * containing CDN content steering information from the MPD manifest.\n *\n * For more information on the DASH spec for Content Steering parsing, see:\n * https://dashif.org/docs/DASH-IF-CTS-00XX-Content-Steering-Community-Review.pdf\n *\n * @param {Node[]} contentSteeringNodes\n * Content steering nodes\n * @param {Function} eventHandler\n * The event handler passed into the parser options to handle warnings\n * @return {Object}\n * Object containing content steering data\n */\n\nconst generateContentSteeringInformation = (contentSteeringNodes, eventHandler) => {\n // If there are more than one ContentSteering tags, throw an error\n if (contentSteeringNodes.length > 1) {\n eventHandler({\n type: 'warn',\n message: 'The MPD manifest should contain no more than one ContentSteering tag'\n });\n } // Return a null value if there are no ContentSteering tags\n\n\n if (!contentSteeringNodes.length) {\n return null;\n }\n\n const infoFromContentSteeringTag = merge({\n serverURL: getContent(contentSteeringNodes[0])\n }, parseAttributes(contentSteeringNodes[0])); // Converts `queryBeforeStart` to a boolean, as well as setting the default value\n // to `false` if it doesn't exist\n\n infoFromContentSteeringTag.queryBeforeStart = infoFromContentSteeringTag.queryBeforeStart === 'true';\n return infoFromContentSteeringTag;\n};\n/**\n * Gets Period@start property for a given period.\n *\n * @param {Object} options\n * Options object\n * @param {Object} options.attributes\n * Period attributes\n * @param {Object} [options.priorPeriodAttributes]\n * Prior period attributes (if prior period is available)\n * @param {string} options.mpdType\n * The MPD@type these periods came from\n * @return {number|null}\n * The period start, or null if it's an early available period or error\n */\n\nconst getPeriodStart = ({\n attributes,\n priorPeriodAttributes,\n mpdType\n}) => {\n // Summary of period start time calculation from DASH spec section 5.3.2.1\n //\n // A period's start is the first period's start + time elapsed after playing all\n // prior periods to this one. Periods continue one after the other in time (without\n // gaps) until the end of the presentation.\n //\n // The value of Period@start should be:\n // 1. if Period@start is present: value of Period@start\n // 2. if previous period exists and it has @duration: previous Period@start +\n // previous Period@duration\n // 3. if this is first period and MPD@type is 'static': 0\n // 4. in all other cases, consider the period an \"early available period\" (note: not\n // currently supported)\n // (1)\n if (typeof attributes.start === 'number') {\n return attributes.start;\n } // (2)\n\n\n if (priorPeriodAttributes && typeof priorPeriodAttributes.start === 'number' && typeof priorPeriodAttributes.duration === 'number') {\n return priorPeriodAttributes.start + priorPeriodAttributes.duration;\n } // (3)\n\n\n if (!priorPeriodAttributes && mpdType === 'static') {\n return 0;\n } // (4)\n // There is currently no logic for calculating the Period@start value if there is\n // no Period@start or prior Period@start and Period@duration available. This is not made\n // explicit by the DASH interop guidelines or the DASH spec, however, since there's\n // nothing about any other resolution strategies, it's implied. Thus, this case should\n // be considered an early available period, or error, and null should suffice for both\n // of those cases.\n\n\n return null;\n};\n/**\n * Traverses the mpd xml tree to generate a list of Representation information objects\n * that have inherited attributes from parent nodes\n *\n * @param {Node} mpd\n * The root node of the mpd\n * @param {Object} options\n * Available options for inheritAttributes\n * @param {string} options.manifestUri\n * The uri source of the mpd\n * @param {number} options.NOW\n * Current time per DASH IOP. Default is current time in ms since epoch\n * @param {number} options.clientOffset\n * Client time difference from NOW (in milliseconds)\n * @return {RepresentationInformation[]}\n * List of objects containing Representation information\n */\n\nconst inheritAttributes = (mpd, options = {}) => {\n const {\n manifestUri = '',\n NOW = Date.now(),\n clientOffset = 0,\n // TODO: For now, we are expecting an eventHandler callback function\n // to be passed into the mpd parser as an option.\n // In the future, we should enable stream parsing by using the Stream class from vhs-utils.\n // This will support new features including a standardized event handler.\n // See the m3u8 parser for examples of how stream parsing is currently used for HLS parsing.\n // https://github.com/videojs/vhs-utils/blob/88d6e10c631e57a5af02c5a62bc7376cd456b4f5/src/stream.js#L9\n eventHandler = function () {}\n } = options;\n const periodNodes = findChildren(mpd, 'Period');\n\n if (!periodNodes.length) {\n throw new Error(errors.INVALID_NUMBER_OF_PERIOD);\n }\n\n const locations = findChildren(mpd, 'Location');\n const mpdAttributes = parseAttributes(mpd);\n const mpdBaseUrls = buildBaseUrls([{\n baseUrl: manifestUri\n }], findChildren(mpd, 'BaseURL'));\n const contentSteeringNodes = findChildren(mpd, 'ContentSteering'); // See DASH spec section 5.3.1.2, Semantics of MPD element. Default type to 'static'.\n\n mpdAttributes.type = mpdAttributes.type || 'static';\n mpdAttributes.sourceDuration = mpdAttributes.mediaPresentationDuration || 0;\n mpdAttributes.NOW = NOW;\n mpdAttributes.clientOffset = clientOffset;\n\n if (locations.length) {\n mpdAttributes.locations = locations.map(getContent);\n }\n\n const periods = []; // Since toAdaptationSets acts on individual periods right now, the simplest approach to\n // adding properties that require looking at prior periods is to parse attributes and add\n // missing ones before toAdaptationSets is called. If more such properties are added, it\n // may be better to refactor toAdaptationSets.\n\n periodNodes.forEach((node, index) => {\n const attributes = parseAttributes(node); // Use the last modified prior period, as it may contain added information necessary\n // for this period.\n\n const priorPeriod = periods[index - 1];\n attributes.start = getPeriodStart({\n attributes,\n priorPeriodAttributes: priorPeriod ? priorPeriod.attributes : null,\n mpdType: mpdAttributes.type\n });\n periods.push({\n node,\n attributes\n });\n });\n return {\n locations: mpdAttributes.locations,\n contentSteeringInfo: generateContentSteeringInformation(contentSteeringNodes, eventHandler),\n // TODO: There are occurences where this `representationInfo` array contains undesired\n // duplicates. This generally occurs when there are multiple BaseURL nodes that are\n // direct children of the MPD node. When we attempt to resolve URLs from a combination of the\n // parent BaseURL and a child BaseURL, and the value does not resolve,\n // we end up returning the child BaseURL multiple times.\n // We need to determine a way to remove these duplicates in a safe way.\n // See: https://github.com/videojs/mpd-parser/pull/17#discussion_r162750527\n representationInfo: flatten(periods.map(toAdaptationSets(mpdAttributes, mpdBaseUrls))),\n eventStream: flatten(periods.map(toEventStream))\n };\n};\n\nconst stringToMpdXml = manifestString => {\n if (manifestString === '') {\n throw new Error(errors.DASH_EMPTY_MANIFEST);\n }\n\n const parser = new DOMParser();\n let xml;\n let mpd;\n\n try {\n xml = parser.parseFromString(manifestString, 'application/xml');\n mpd = xml && xml.documentElement.tagName === 'MPD' ? xml.documentElement : null;\n } catch (e) {// ie 11 throws on invalid xml\n }\n\n if (!mpd || mpd && mpd.getElementsByTagName('parsererror').length > 0) {\n throw new Error(errors.DASH_INVALID_XML);\n }\n\n return mpd;\n};\n\n/**\n * Parses the manifest for a UTCTiming node, returning the nodes attributes if found\n *\n * @param {string} mpd\n * XML string of the MPD manifest\n * @return {Object|null}\n * Attributes of UTCTiming node specified in the manifest. Null if none found\n */\n\nconst parseUTCTimingScheme = mpd => {\n const UTCTimingNode = findChildren(mpd, 'UTCTiming')[0];\n\n if (!UTCTimingNode) {\n return null;\n }\n\n const attributes = parseAttributes(UTCTimingNode);\n\n switch (attributes.schemeIdUri) {\n case 'urn:mpeg:dash:utc:http-head:2014':\n case 'urn:mpeg:dash:utc:http-head:2012':\n attributes.method = 'HEAD';\n break;\n\n case 'urn:mpeg:dash:utc:http-xsdate:2014':\n case 'urn:mpeg:dash:utc:http-iso:2014':\n case 'urn:mpeg:dash:utc:http-xsdate:2012':\n case 'urn:mpeg:dash:utc:http-iso:2012':\n attributes.method = 'GET';\n break;\n\n case 'urn:mpeg:dash:utc:direct:2014':\n case 'urn:mpeg:dash:utc:direct:2012':\n attributes.method = 'DIRECT';\n attributes.value = Date.parse(attributes.value);\n break;\n\n case 'urn:mpeg:dash:utc:http-ntp:2014':\n case 'urn:mpeg:dash:utc:ntp:2014':\n case 'urn:mpeg:dash:utc:sntp:2014':\n default:\n throw new Error(errors.UNSUPPORTED_UTC_TIMING_SCHEME);\n }\n\n return attributes;\n};\n\nconst VERSION = version;\n/*\n * Given a DASH manifest string and options, parses the DASH manifest into an object in the\n * form outputed by m3u8-parser and accepted by videojs/http-streaming.\n *\n * For live DASH manifests, if `previousManifest` is provided in options, then the newly\n * parsed DASH manifest will have its media sequence and discontinuity sequence values\n * updated to reflect its position relative to the prior manifest.\n *\n * @param {string} manifestString - the DASH manifest as a string\n * @param {options} [options] - any options\n *\n * @return {Object} the manifest object\n */\n\nconst parse = (manifestString, options = {}) => {\n const parsedManifestInfo = inheritAttributes(stringToMpdXml(manifestString), options);\n const playlists = toPlaylists(parsedManifestInfo.representationInfo);\n return toM3u8({\n dashPlaylists: playlists,\n locations: parsedManifestInfo.locations,\n contentSteering: parsedManifestInfo.contentSteeringInfo,\n sidxMapping: options.sidxMapping,\n previousManifest: options.previousManifest,\n eventStream: parsedManifestInfo.eventStream\n });\n};\n/**\n * Parses the manifest for a UTCTiming node, returning the nodes attributes if found\n *\n * @param {string} manifestString\n * XML string of the MPD manifest\n * @return {Object|null}\n * Attributes of UTCTiming node specified in the manifest. Null if none found\n */\n\n\nconst parseUTCTiming = manifestString => parseUTCTimingScheme(stringToMpdXml(manifestString));\n\nexport { VERSION, addSidxSegmentsToPlaylist$1 as addSidxSegmentsToPlaylist, generateSidxKey, inheritAttributes, parse, parseUTCTiming, stringToMpdXml, toM3u8, toPlaylists };\n","/**\n * mpd-parser's build calls `Object.values` once, an ES2017 builtin that\n * Chromium gained in 54, while the IIFE builds serve Chromium 49-era devices.\n *\n * Installed by an explicit call from the DASH tokenizer rather than by a bare\n * side-effect import: this package declares `sideEffects: false`, which lets a\n * consumer's bundler drop an import that exports nothing. A call inside a\n * module the consumer uses cannot be dropped. HLS bundles never carry it.\n *\n * Shaka Player's compiled build installs the same builtin through Closure's\n * `$jscomp.polyfill` runtime at script load, so on a page with Shaka this\n * shim finds it present and does nothing. It is kept for deployments without\n * Shaka — a custom integration playing DASH, or the standalone core in a\n * WebView — and because another library's load order is not ours to rely on.\n */\nexport function ensureObjectValues(): void {\n const target = Object as ObjectConstructor & {\n values?: (source: object) => unknown[];\n };\n if (typeof target.values === \"function\") return;\n target.values = (source: object) =>\n Object.keys(source).map((key) => (source as Record<string, unknown>)[key]);\n}\n","import window from 'global/window';\nvar regexs = {\n // to determine mime types\n mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,\n webm: /^(vp0?[89]|av0?1|opus|vorbis)/,\n ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,\n // to determine if a codec is audio or video\n video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,\n audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,\n text: /^(stpp.ttml.im1t)/,\n // mux.js support regex\n muxerVideo: /^(avc0?1)/,\n muxerAudio: /^(mp4a)/,\n // match nothing as muxer does not support text right now.\n // there cannot never be a character before the start of a string\n // so this matches nothing.\n muxerText: /a^/\n};\nvar mediaTypes = ['video', 'audio', 'text'];\nvar upperMediaTypes = ['Video', 'Audio', 'Text'];\n/**\n * Replace the old apple-style `avc1.<dd>.<dd>` codec string with the standard\n * `avc1.<hhhhhh>`\n *\n * @param {string} codec\n * Codec string to translate\n * @return {string}\n * The translated codec string\n */\n\nexport var translateLegacyCodec = function translateLegacyCodec(codec) {\n if (!codec) {\n return codec;\n }\n\n return codec.replace(/avc1\\.(\\d+)\\.(\\d+)/i, function (orig, profile, avcLevel) {\n var profileHex = ('00' + Number(profile).toString(16)).slice(-2);\n var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);\n return 'avc1.' + profileHex + '00' + avcLevelHex;\n });\n};\n/**\n * Replace the old apple-style `avc1.<dd>.<dd>` codec strings with the standard\n * `avc1.<hhhhhh>`\n *\n * @param {string[]} codecs\n * An array of codec strings to translate\n * @return {string[]}\n * The translated array of codec strings\n */\n\nexport var translateLegacyCodecs = function translateLegacyCodecs(codecs) {\n return codecs.map(translateLegacyCodec);\n};\n/**\n * Replace codecs in the codec string with the old apple-style `avc1.<dd>.<dd>` to the\n * standard `avc1.<hhhhhh>`.\n *\n * @param {string} codecString\n * The codec string\n * @return {string}\n * The codec string with old apple-style codecs replaced\n *\n * @private\n */\n\nexport var mapLegacyAvcCodecs = function mapLegacyAvcCodecs(codecString) {\n return codecString.replace(/avc1\\.(\\d+)\\.(\\d+)/i, function (match) {\n return translateLegacyCodecs([match])[0];\n });\n};\n/**\n * @typedef {Object} ParsedCodecInfo\n * @property {number} codecCount\n * Number of codecs parsed\n * @property {string} [videoCodec]\n * Parsed video codec (if found)\n * @property {string} [videoObjectTypeIndicator]\n * Video object type indicator (if found)\n * @property {string|null} audioProfile\n * Audio profile\n */\n\n/**\n * Parses a codec string to retrieve the number of codecs specified, the video codec and\n * object type indicator, and the audio profile.\n *\n * @param {string} [codecString]\n * The codec string to parse\n * @return {ParsedCodecInfo}\n * Parsed codec info\n */\n\nexport var parseCodecs = function parseCodecs(codecString) {\n if (codecString === void 0) {\n codecString = '';\n }\n\n var codecs = codecString.split(',');\n var result = [];\n codecs.forEach(function (codec) {\n codec = codec.trim();\n var codecType;\n mediaTypes.forEach(function (name) {\n var match = regexs[name].exec(codec.toLowerCase());\n\n if (!match || match.length <= 1) {\n return;\n }\n\n codecType = name; // maintain codec case\n\n var type = codec.substring(0, match[1].length);\n var details = codec.replace(type, '');\n result.push({\n type: type,\n details: details,\n mediaType: name\n });\n });\n\n if (!codecType) {\n result.push({\n type: codec,\n details: '',\n mediaType: 'unknown'\n });\n }\n });\n return result;\n};\n/**\n * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is\n * a default alternate audio playlist for the provided audio group.\n *\n * @param {Object} master\n * The master playlist\n * @param {string} audioGroupId\n * ID of the audio group for which to find the default codec info\n * @return {ParsedCodecInfo}\n * Parsed codec info\n */\n\nexport var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {\n if (!master.mediaGroups.AUDIO || !audioGroupId) {\n return null;\n }\n\n var audioGroup = master.mediaGroups.AUDIO[audioGroupId];\n\n if (!audioGroup) {\n return null;\n }\n\n for (var name in audioGroup) {\n var audioType = audioGroup[name];\n\n if (audioType.default && audioType.playlists) {\n // codec should be the same for all playlists within the audio type\n return parseCodecs(audioType.playlists[0].attributes.CODECS);\n }\n }\n\n return null;\n};\nexport var isVideoCodec = function isVideoCodec(codec) {\n if (codec === void 0) {\n codec = '';\n }\n\n return regexs.video.test(codec.trim().toLowerCase());\n};\nexport var isAudioCodec = function isAudioCodec(codec) {\n if (codec === void 0) {\n codec = '';\n }\n\n return regexs.audio.test(codec.trim().toLowerCase());\n};\nexport var isTextCodec = function isTextCodec(codec) {\n if (codec === void 0) {\n codec = '';\n }\n\n return regexs.text.test(codec.trim().toLowerCase());\n};\nexport var getMimeForCodec = function getMimeForCodec(codecString) {\n if (!codecString || typeof codecString !== 'string') {\n return;\n }\n\n var codecs = codecString.toLowerCase().split(',').map(function (c) {\n return translateLegacyCodec(c.trim());\n }); // default to video type\n\n var type = 'video'; // only change to audio type if the only codec we have is\n // audio\n\n if (codecs.length === 1 && isAudioCodec(codecs[0])) {\n type = 'audio';\n } else if (codecs.length === 1 && isTextCodec(codecs[0])) {\n // text uses application/<container> for now\n type = 'application';\n } // default the container to mp4\n\n\n var container = 'mp4'; // every codec must be able to go into the container\n // for that container to be the correct one\n\n if (codecs.every(function (c) {\n return regexs.mp4.test(c);\n })) {\n container = 'mp4';\n } else if (codecs.every(function (c) {\n return regexs.webm.test(c);\n })) {\n container = 'webm';\n } else if (codecs.every(function (c) {\n return regexs.ogg.test(c);\n })) {\n container = 'ogg';\n }\n\n return type + \"/\" + container + \";codecs=\\\"\" + codecString + \"\\\"\";\n};\n/**\n * Tests whether the codec is supported by MediaSource. Optionally also tests ManagedMediaSource.\n *\n * @param {string} codecString\n * Codec to test\n * @param {boolean} [withMMS]\n * Whether to check if ManagedMediaSource supports it\n * @return {boolean}\n * Codec is supported\n */\n\nexport var browserSupportsCodec = function browserSupportsCodec(codecString, withMMS) {\n if (codecString === void 0) {\n codecString = '';\n }\n\n if (withMMS === void 0) {\n withMMS = false;\n }\n\n return window.MediaSource && window.MediaSource.isTypeSupported && window.MediaSource.isTypeSupported(getMimeForCodec(codecString)) || withMMS && window.ManagedMediaSource && window.ManagedMediaSource.isTypeSupported && window.ManagedMediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;\n};\nexport var muxerSupportsCodec = function muxerSupportsCodec(codecString) {\n if (codecString === void 0) {\n codecString = '';\n }\n\n return codecString.toLowerCase().split(',').every(function (codec) {\n codec = codec.trim(); // any match is supported.\n\n for (var i = 0; i < upperMediaTypes.length; i++) {\n var type = upperMediaTypes[i];\n\n if (regexs[\"muxer\" + type].test(codec)) {\n return true;\n }\n }\n\n return false;\n });\n};\nexport var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';\nexport var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';","// Ambient typings for untyped packages must travel with the modules that\n// import them, so other packages compiling these sources see them too.\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// <reference path=\"./vendor-types.d.ts\" />\nimport { parseCodecs } from \"@videojs/vhs-utils/es/codecs.js\";\nimport type { StreamProperties } from \"../types.js\";\n\n/**\n * Stream properties from manifest attributes. These feed `identityHash`\n * unnormalized, so what is read here is what every peer hashes; the golden\n * vectors in the core tests pin the results.\n */\n\nexport type VideoAttributes = {\n bandwidth?: number;\n codecs?: string;\n width?: number;\n height?: number;\n frameRate?: number | string;\n videoRange?: string;\n};\n\nexport type AudioAttributes = {\n codecs?: string;\n language?: string;\n channels?: string | number;\n name?: string;\n};\n\nfunction codecsOfType(\n codecs: string | undefined,\n mediaType: \"video\" | \"audio\",\n): string | undefined {\n if (!codecs) return undefined;\n const matching = parseCodecs(codecs)\n .filter((c) => c.mediaType === mediaType)\n .map((c) => `${c.type}${c.details}`);\n return matching.length ? matching.join(\",\") : undefined;\n}\n\n/** The video codecs out of a mixed `CODECS` list; audio and text are dropped. */\nfunction videoCodecs(codecs: string | undefined): string | undefined {\n return codecsOfType(codecs, \"video\");\n}\n\n/** The audio codecs out of a mixed `CODECS` list. */\nexport function audioCodecs(codecs: string | undefined): string | undefined {\n return codecsOfType(codecs, \"audio\");\n}\n\n/**\n * A variant with no bandwidth carries no trustworthy metadata; every other\n * property is blanked so such variants hash identically everywhere.\n */\nexport function videoStreamProperties(a: VideoAttributes): StreamProperties {\n const bitrate = a.bandwidth ?? 0;\n const isMissingMetadata = bitrate === 0;\n return {\n bitrate,\n codecs: isMissingMetadata ? undefined : videoCodecs(a.codecs),\n width: isMissingMetadata ? undefined : a.width,\n height: isMissingMetadata ? undefined : a.height,\n frameRate: isMissingMetadata ? undefined : a.frameRate,\n videoRange: isMissingMetadata ? undefined : a.videoRange,\n };\n}\n\n/** An alternate audio rendition; bitrate is 0 by convention across players. */\nexport function audioStreamProperties(a: AudioAttributes): StreamProperties {\n return {\n bitrate: 0,\n codecs: a.codecs,\n language: a.language,\n channels: a.channels,\n name: a.name,\n };\n}\n","import type { ByteRange } from \"../types.js\";\n\n/**\n * Registry keys. A segment is looked up by the URL the player will request\n * plus its byte range, so a key must be built identically from a manifest and\n * from an intercepted request. See specs/manifest-registry.md.\n */\n\n/**\n * Query parameters that vary per request without changing what is fetched.\n * Only these are removed from keys: stripping anything else risks collapsing\n * two distinct segments onto one key, which would serve wrong bytes.\n */\nconst PER_REQUEST_QUERY_PARAMS: ReadonlySet<string> = new Set([\"CMCD\"]);\n\n/** Resolves a manifest URI against the document that declared it. */\nexport function resolveUrl(uri: string, baseUrl: string): string {\n try {\n return new URL(uri, baseUrl).toString();\n } catch {\n return uri;\n }\n}\n\n/**\n * Removes per-request telemetry parameters and nothing else. Signed URLs keep\n * their tokens, so a normalized URL is still fetchable — but the core never\n * fetches a normalized URL; it fetches what the player asked for.\n */\nexport function normalizeUrl(url: string): string {\n const query = url.indexOf(\"?\");\n if (query === -1) return url;\n\n const params = new URLSearchParams(url.slice(query + 1));\n let changed = false;\n for (const name of PER_REQUEST_QUERY_PARAMS) {\n if (params.has(name)) {\n params.delete(name);\n changed = true;\n }\n }\n if (!changed) return url;\n\n const rest = params.toString();\n return rest ? `${url.slice(0, query)}?${rest}` : url.slice(0, query);\n}\n\n/** `url|start-end` with an inclusive end, matching the engines' runtime IDs. */\nexport function segmentKey(url: string, byteRange?: ByteRange): string {\n const normalized = normalizeUrl(url);\n if (!byteRange) return normalized;\n return `${normalized}|${byteRange.start}-${byteRange.end}`;\n}\n\n/** m3u8 `{ offset, length }` → inclusive `[start, end]`. */\nexport function byteRangeFromOffsetLength(range?: {\n offset: number;\n length: number;\n}): ByteRange | undefined {\n if (!range || range.length <= 0) return undefined;\n return { start: range.offset, end: range.offset + range.length - 1 };\n}\n\n/** `Range: bytes=a-b` → inclusive `[a, b]`; open-ended ranges are not keys. */\nexport function byteRangeFromRangeHeader(\n header: string | undefined,\n): ByteRange | undefined {\n if (!header) return undefined;\n const match = /^\\s*bytes=(\\d+)-(\\d+)\\s*$/i.exec(header);\n if (!match) return undefined;\n const start = Number(match[1]);\n const end = Number(match[2]);\n return start <= end ? { start, end } : undefined;\n}\n\n/** Half-open `[start, end)` from a player → inclusive `[start, end - 1]`. */\nexport function byteRangeFromHalfOpen(\n start: number | undefined,\n end: number | undefined,\n): ByteRange | undefined {\n if (start === undefined || end === undefined || end <= start) {\n return undefined;\n }\n return { start, end: end - 1 };\n}\n","// Ambient typings for untyped packages must travel with the modules that\n// import them, so other packages compiling these sources see them too.\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// <reference path=\"./vendor-types.d.ts\" />\nimport { parse, stringToMpdXml, type MpdPlaylist } from \"mpd-parser\";\nimport { ensureObjectValues } from \"./shims/object-values.js\";\nimport type {\n ManifestParser,\n ParsedSegment,\n ParsedStream,\n SegmentIndexSource,\n} from \"./types.js\";\nimport { audioStreamProperties, videoStreamProperties } from \"./properties.js\";\nimport { byteRangeFromOffsetLength } from \"./url-key.js\";\nimport type { StreamProperties, StreamType } from \"../types.js\";\n\n// Supplies a builtin mpd-parser assumes; must run before the first parse.\nensureObjectValues();\n\n/**\n * DASH tokenizer over mpd-parser. Produces `ParsedManifest`; interprets\n * nothing. An MPD declares streams and segments in one document, so every\n * stream here may carry segments — or, for `SegmentBase`, an external index.\n */\nexport const dashManifestParser: ManifestParser = {\n protocol: \"dash\",\n\n canParse(text) {\n return /<MPD[\\s>]/.test(text.slice(0, 2048));\n },\n\n parse(text, url) {\n const manifest = parse(text, { manifestUri: url });\n // `type=\"dynamic\"` is authoritative for live, and reading the attribute\n // directly survives changes in how the tokenizer summarises it.\n const isLive = /<MPD[^>]*\\btype\\s*=\\s*[\"']dynamic[\"']/.test(\n text.slice(0, 4096),\n );\n\n // mpd-parser drops AudioChannelConfiguration; read it from the MPD itself.\n const channelsByRepresentation = scanAudioChannels(text);\n\n const streams: ParsedStream[] = [];\n for (const playlist of manifest.playlists) {\n streams.push(toStream(playlist, \"main\", isLive, videoProperties));\n }\n const groups = manifest.mediaGroups.AUDIO ?? {};\n for (const groupId of Object.keys(groups)) {\n const renditions = groups[groupId];\n for (const label of Object.keys(renditions)) {\n const rendition = renditions[label];\n for (const playlist of rendition.playlists) {\n streams.push(\n toStream(playlist, \"secondary\", isLive, (a) =>\n audioStreamProperties({\n codecs: a.CODECS,\n language: rendition.language,\n channels: a.NAME\n ? channelsByRepresentation.get(a.NAME)\n : undefined,\n // The Representation id is the one stable, manifest-given name\n // of an audio rendition; a label is optional and a parser may\n // synthesise one from language and role.\n name: a.NAME,\n }),\n ),\n );\n }\n }\n }\n\n return { protocol: \"dash\", url, streams };\n },\n};\n\nfunction videoProperties(a: MpdPlaylist[\"attributes\"]): StreamProperties {\n return videoStreamProperties({\n bandwidth: a.BANDWIDTH,\n codecs: a.CODECS,\n width: a.RESOLUTION?.width,\n height: a.RESOLUTION?.height,\n frameRate: a[\"FRAME-RATE\"],\n });\n}\n\nfunction toStream(\n playlist: MpdPlaylist,\n type: StreamType,\n isLive: boolean,\n properties: (a: MpdPlaylist[\"attributes\"]) => StreamProperties,\n): ParsedStream {\n const { sidx } = playlist;\n const indexSource: SegmentIndexSource = sidx\n ? {\n kind: \"external\",\n url: sidx.resolvedUri,\n byteRange: byteRangeFromOffsetLength(sidx.byterange) ?? {\n start: 0,\n end: 0,\n },\n periodStart: sidx.timeline ?? 0,\n }\n : { kind: \"manifest\" };\n\n const segments: ParsedSegment[] = playlist.segments.map((s) => ({\n url: s.resolvedUri,\n byteRange: byteRangeFromOffsetLength(s.byterange),\n duration: s.duration,\n sequence: s.number,\n presentationTime: s.presentationTime,\n }));\n\n // A SegmentBase representation lists no segments; its init segment hangs\n // off the index reference instead.\n const map = playlist.segments[0]?.map ?? sidx?.map;\n\n return {\n // The representation id is the only stable per-stream name an MPD offers.\n key: playlist.attributes.NAME ?? playlist.resolvedUri,\n type,\n properties: properties(playlist.attributes),\n segments,\n initSegment: map\n ? {\n url: map.resolvedUri,\n byteRange: byteRangeFromOffsetLength(map.byterange),\n }\n : undefined,\n indexSource,\n isLive,\n };\n}\n\n/**\n * Channel count per audio Representation id, from `AudioChannelConfiguration`\n * on the Representation or, failing that, its AdaptationSet. Only the MPEG\n * scheme (`urn:mpeg:dash:23003:3:audio_channel_configuration:2011`), whose\n * value is a plain count, is read; vendor schemes encode channel masks and are\n * left undefined rather than guessed.\n */\nfunction scanAudioChannels(text: string): Map<string, number> {\n const result = new Map<string, number>();\n // mpd-parser's own DOM step, so the core has no XML dependency of its own:\n // in Node it resolves xmldom transitively, in browser bundles the alias in\n // vite.common.config.ts hands it the platform DOMParser.\n let doc: Document;\n try {\n doc = stringToMpdXml(text);\n } catch {\n return result;\n }\n\n // Array.from: DOM collections are not iterable under the ES2015 lib target.\n for (const set of Array.from(doc.getElementsByTagName(\"AdaptationSet\"))) {\n const setChannels = channelCountOf(set);\n for (const representation of Array.from(\n set.getElementsByTagName(\"Representation\"),\n )) {\n const id = representation.getAttribute(\"id\");\n const channels = channelCountOf(representation) ?? setChannels;\n if (id && channels !== undefined) result.set(id, channels);\n }\n }\n return result;\n}\n\nconst MPEG_CHANNEL_SCHEME = \"23003:3:audio_channel_configuration\";\n\nfunction channelCountOf(element: Element): number | undefined {\n for (const child of Array.from(element.childNodes)) {\n if (\n child.nodeType !== 1 ||\n (child as Element).localName !== \"AudioChannelConfiguration\"\n ) {\n continue;\n }\n const config = child as Element;\n if (\n !(config.getAttribute(\"schemeIdUri\") ?? \"\").includes(MPEG_CHANNEL_SCHEME)\n ) {\n continue;\n }\n const value = Number(config.getAttribute(\"value\"));\n if (Number.isInteger(value) && value > 0) return value;\n }\n return undefined;\n}\n","import { SegmentStorage } from \"./segment-storage/index.js\";\nimport type { ManifestParser } from \"./manifest/types.js\";\n\n/** Represents the types of streams available, either primary (main) or secondary. */\nexport type StreamType = \"main\" | \"secondary\";\n\n/** Represents a range of bytes, used for specifying a segment of data to download. */\nexport type ByteRange = {\n /** The starting byte index of the range. */\n readonly start: number;\n /** The ending byte index of the range. */\n readonly end: number;\n};\n\n/** Describes a media segment with its unique identifiers, location, and timing information. */\nexport type Segment = {\n /**\n * The registry key: the segment's absolute URL, with telemetry query\n * parameters (`CMCD`) removed, followed by `|start-end` when a byte range\n * applies. Local to this process, never on the wire.\n */\n readonly runtimeId: string;\n\n /**\n * The segment's identity within its stream, as sent to peers: the media\n * sequence number for HLS, the presentation time in 100 ms units for\n * MPEG-DASH. See specs/segment-identity.md.\n */\n readonly externalId: number;\n\n /** The URL from which the segment can be downloaded. */\n readonly url: string;\n\n /** An optional property specifying the range of bytes that represent the segment. */\n readonly byteRange?: ByteRange;\n\n /**\n * Start of the segment, in seconds, on the stream's manifest timeline.\n *\n * The timeline is whatever the manifest provides — wall-clock time from\n * `EXT-X-PROGRAM-DATE-TIME`, presentation time for DASH (which counts from\n * the MPD's availability start, often 1970 for live), or a zero-based\n * anchor on the media sequence when HLS carries no date tags. Its zero\n * point is arbitrary: only differences between values of the same stream\n * carry meaning. Never compare it with the media element's `currentTime`.\n * See specs/manifest-registry.md, \"Timeline stability\".\n */\n readonly startTime: number;\n\n /** End of the segment, in seconds, on the same timeline as `startTime`. */\n readonly endTime: number;\n};\n\n/**\n * Raw stream properties as the core read them from the manifest's variant or\n * rendition metadata. They define the stream's identity: streams with equal\n * properties are the same stream to every peer. `bitrate` counts only where\n * the manifest needs it to tell two same-type streams apart (see\n * specs/segment-identity.md).\n */\nexport type StreamProperties = {\n bitrate?: number | null;\n codecs?: string | null;\n width?: number | null;\n height?: number | null;\n language?: string | null;\n channels?: string | number | null;\n name?: string | null;\n frameRate?: number | string | null;\n videoRange?: string | null;\n};\n\n/** Represents a media stream with various defining characteristics. */\nexport type Stream = {\n /**\n * The manifest-derived stream key: the media playlist URL for HLS, the\n * Representation id for DASH. Local to this process, never on the wire.\n */\n readonly runtimeId: string;\n\n /** Stream type. */\n readonly type: StreamType;\n\n /** Raw stream properties as the core read them from the manifest. */\n readonly properties: Readonly<StreamProperties>;\n\n /**\n * The swarm ID the stream was registered with: the configured `swarmId`\n * or, if not set, the first manifest's response URL with its query string\n * discarded. Resolved once at registration.\n */\n readonly swarmId: string;\n\n /**\n * Stream identity hash derived from the stream properties as read from the\n * manifest. The same for all peers regardless of the player in use.\n */\n readonly identityHash: string;\n\n /**\n * The pre-hash string that defines which P2P swarm the stream belongs to.\n * By default `${peerProtocolVersion}-${swarmId}-${type}-${identityHash}`;\n * a custom `streamSwarmIdBuilder` may override it. Computed once at registration.\n */\n readonly streamSwarmId: string;\n\n /**\n * The infohash announced to trackers for the stream's swarm:\n * a 20-character ASCII string derived from the stream swarm ID.\n * Computed once at registration.\n */\n readonly infoHash: string;\n};\n\n/** Represents a defined Core configuration with specific settings for the main and secondary streams. */\nexport type DefinedCoreConfig = CommonCoreConfig & {\n /** Configuration for the main stream. */\n mainStream: StreamConfig;\n /** Configuration for the secondary stream. */\n secondaryStream: StreamConfig;\n};\n\n/** Represents a set of properties that can be dynamically modified at runtime. */\nexport type DynamicStreamProperties =\n | \"highDemandTimeWindow\"\n | \"httpDownloadInitialTimeoutMs\"\n | \"httpDownloadTimeWindow\"\n | \"p2pDownloadTimeWindow\"\n | \"simultaneousHttpDownloads\"\n | \"simultaneousP2PDownloads\"\n | \"webRtcMaxMessageSize\"\n | \"p2pNotReceivingBytesTimeoutMs\"\n | \"p2pInactiveLoaderDestroyTimeoutMs\"\n | \"httpNotReceivingBytesTimeoutMs\"\n | \"httpErrorRetries\"\n | \"p2pErrorRetries\"\n | \"validateP2PSegment\"\n | \"validateHTTPSegment\"\n | \"httpRequestSetup\"\n | \"isP2PDisabled\"\n | \"isP2PUploadDisabled\"\n | \"p2pMaxPeers\"\n | \"p2pChurnMaxPeersMultiplier\"\n | \"p2pChurnCleanupIntervalMs\"\n | \"p2pChurnGracePeriodMs\"\n | \"webRtcOffersCount\"\n | \"webRtcOfferTimeoutMs\"\n | \"webRtcIceGatheringTimeoutMs\"\n | \"webRtcConnectionTimeoutMs\"\n | \"rtcConfig\";\n\n/**\n * Represents a dynamically modifiable configuration, allowing updates to selected CoreConfig properties at runtime.\n *\n * Note that `swarmId` and `streamSwarmIdBuilder` cannot be changed at runtime:\n * stream identity is derived from them once, when a stream is registered.\n *\n * @example\n * ```typescript\n * const dynamicConfig: DynamicCoreConfig = {\n * core: {\n * cachedSegmentsCount: 200,\n * },\n * mainStream: {\n * highDemandTimeWindow: 20,\n * p2pDownloadTimeWindow: 6000,\n * },\n * secondaryStream: {\n * highDemandTimeWindow: 10,\n * p2pDownloadTimeWindow: 3000,\n * }\n * };\n * ```\n */\nexport type DynamicCoreConfig = Partial<\n Pick<CoreConfig, DynamicStreamProperties>\n> &\n Partial<CommonCoreConfig> & {\n /** Optional dynamic configuration for the main stream. */\n mainStream?: DynamicStreamConfig;\n /** Optional dynamic configuration for the secondary stream. */\n secondaryStream?: DynamicStreamConfig;\n };\n\n/** Represents a partial configuration for a stream with dynamic properties. */\nexport type DynamicStreamConfig = Partial<\n Pick<StreamConfig, DynamicStreamProperties>\n>;\n\n/** Represents the configuration for the Core functionality that is common to all streams. */\nexport type CommonCoreConfig = {\n /**\n * Defines the memory storage limit for media segments (in MiB).\n *\n * @default\n * ```typescript\n * segmentMemoryStorageLimit: undefined\n * ```\n *\n * - When `undefined`, the default limit is determined based on the device type and browser:\n * - Desktop: 4096 MiB\n * - Android: 2048 MiB\n * - iOS: 1024 MiB\n * - Android WebView: 1024 MiB\n * - iOS WebView: 1024 MiB\n *\n */\n segmentMemoryStorageLimit: number | undefined;\n\n /**\n * An optional custom storage factory for the segment storage. Called once,\n * on the first segment request; `isLive` is derived from the manifests\n * processed so far (see specs/manifest-registry.md, \"Live detection\").\n *\n * @default\n * ```typescript\n * customSegmentStorageFactory: undefined\n * ```\n */\n customSegmentStorageFactory?: (isLive: boolean) => SegmentStorage;\n\n /**\n * The prefix to use for the WebTorrent client version during tracker communications.\n *\n * @default\n * ```typescript\n * trackerClientVersionPrefix: `-PM${formattedPackageVersion}-`\n * ```\n */\n trackerClientVersionPrefix: string;\n};\n\n/**\n * Represents a set of configuration parameters that can be used to override or extend the\n * default configuration settings for a specific stream (main or secondary).\n *\n * @example Configuration for basic video stream\n *\n * ```typescript\n * const config: CoreConfig = {\n * highDemandTimeWindow: 15,\n * httpDownloadTimeWindow: 3000,\n * p2pDownloadTimeWindow: 6000,\n * swarmId: \"custom swarm ID for video stream\",\n * }\n * ```\n *\n * @example Configuration for advanced video stream\n *\n * ```typescript\n * const config: CoreConfig = {\n * // Configuration for both streams\n * highDemandTimeWindow: 20,\n * httpDownloadTimeWindow: 3000,\n * p2pDownloadTimeWindow: 6000,\n * mainStream: {\n * // Optional configuration for the main stream\n * swarmId: \"custom swarm ID for video stream\",\n * },\n * secondaryStream: {\n * // Optional configuration for the secondary stream\n * swarmId: \"custom swarm ID for audio stream\",\n * },\n * }\n * ```\n */\nexport type CoreConfig = Partial<StreamConfig> &\n Partial<CommonCoreConfig> & {\n /** Optional configuration for the main stream. */\n mainStream?: Partial<StreamConfig>;\n /** Optional configuration for the secondary stream. */\n secondaryStream?: Partial<StreamConfig>;\n /**\n * Manifest parsers the core may use, selected statically by the\n * integration so a bundle carries only the protocols it plays:\n *\n * ```ts\n * import { hlsManifestParser } from \"p2p-media-loader-core/hls\";\n * new Core({ manifestParsers: [hlsManifestParser] });\n * ```\n *\n * Not part of the merged configuration returned by `getConfig()`.\n * See specs/packaging.md.\n */\n manifestParsers?: readonly ManifestParser[];\n };\n\n/** Configuration options for the Core functionality, including network and processing parameters. */\nexport type StreamConfig = {\n /**\n * Controls whether peer-to-peer uploading is disabled for the stream.\n * If `true`, the stream will only download segments and will not upload to other peers.\n *\n * @default\n * ```typescript\n * isP2PUploadDisabled: false\n * ```\n */\n isP2PUploadDisabled: boolean;\n /**\n * Controls whether all peer-to-peer functionality is disabled for the stream.\n *\n * @default\n * ```typescript\n * isP2PDisabled: false\n * ```\n */\n isP2PDisabled: boolean;\n /**\n * Defines the duration of the time window (in seconds) during which segments are preemptively loaded to ensure smooth playback.\n * This window prioritizes the fetching of media segments that will be played imminently.\n *\n * @default\n * ```typescript\n * highDemandTimeWindow: 15\n * ```\n */\n highDemandTimeWindow: number;\n\n /**\n * Defines the time window (in seconds) for HTTP segment downloads. This property specifies the duration\n * over which media segments are preemptively fetched using HTTP requests.\n *\n * To achieve a higher P2P ratio, it is recommended to set `httpDownloadTimeWindow` lower than `p2pDownloadTimeWindow`.\n *\n * NOTE: This setting only takes effect if there is at least one peer connection, and the connected peer\n * does not have the requested segments available to share via P2P.\n *\n * @default\n * ```typescript\n * httpDownloadTimeWindow: 3000\n * ```\n */\n httpDownloadTimeWindow: number;\n\n /**\n * The delay (in milliseconds) before falling back to HTTP for the very first segments.\n * This allows the tracker time to discover peers when playback first begins.\n * A higher value provides a better opportunity to download initial segments via P2P, thereby improving the overall P2P ratio.\n * However, setting this value too high can increase playback startup time or stall playback if peers are not immediately available.\n * If set to `0`, the HTTP fallback will occur immediately.\n *\n * @default\n * ```typescript\n * httpDownloadInitialTimeoutMs: 0\n * ```\n */\n httpDownloadInitialTimeoutMs: number;\n\n /**\n * Defines the time window (in seconds) dedicated to preemptively fetching media segments via Peer-to-Peer (P2P) downloads.\n * This duration determines how much content is downloaded in advance via P2P connections to ensure smooth playback and reduce reliance on HTTP downloads.\n *\n * To achieve a higher P2P ratio, it is recommended to set this time window higher than `httpDownloadTimeWindow` to maximize P2P usage.\n *\n * @default\n * ```typescript\n * p2pDownloadTimeWindow: 6000\n * ```\n */\n p2pDownloadTimeWindow: number;\n\n /**\n * The maximum number of simultaneous HTTP downloads allowed.\n *\n * @default\n * ```typescript\n * simultaneousHttpDownloads: 2\n * ```\n */\n simultaneousHttpDownloads: number;\n\n /**\n * The maximum number of simultaneous P2P downloads allowed.\n *\n * @default\n * ```typescript\n * simultaneousP2PDownloads: 3\n * ```\n */\n simultaneousP2PDownloads: number;\n\n /**\n * The maximum message size for WebRTC communications, in bytes.\n *\n * @default\n * ```typescript\n * webRtcMaxMessageSize: 64 * 1024 - 1\n * ```\n */\n webRtcMaxMessageSize: number;\n\n /**\n * The timeout duration (in milliseconds) for not receiving bytes from a P2P connection.\n *\n * @default\n * ```typescript\n * p2pNotReceivingBytesTimeoutMs: 2000\n * ```\n */\n p2pNotReceivingBytesTimeoutMs: number;\n\n /**\n * The timeout duration (in milliseconds) before destroying the P2P loader if it remains inactive.\n *\n * @default\n * ```typescript\n * p2pInactiveLoaderDestroyTimeoutMs: 30 * 1000\n * ```\n */\n p2pInactiveLoaderDestroyTimeoutMs: number;\n\n /**\n * The timeout duration (in milliseconds) for not receiving bytes from an HTTP download.\n *\n * @default\n * ```typescript\n * httpNotReceivingBytesTimeoutMs: 3000\n * ```\n */\n httpNotReceivingBytesTimeoutMs: number;\n\n /**\n * The number of retries allowed following an HTTP error.\n *\n * @default\n * ```typescript\n * httpErrorRetries: 3\n * ```\n */\n httpErrorRetries: number;\n\n /**\n * The number of retries allowed following a P2P error.\n *\n * @default\n * ```typescript\n * p2pErrorRetries: 3\n * ```\n */\n p2pErrorRetries: number;\n\n /**\n * A list of URLs to the WebTorrent trackers used for announcing and discovering peers (i.e., WebRTC signaling).\n *\n * WARNING: In the Safari browser, only the first tracker will be utilized. Safari has known issues with multiple trackers,\n * which can lead to problems sending SDP messages during WebRTC signaling.\n *\n * @default\n * The default trackers used are:\n * ```typescript\n * [\n * \"wss://tracker.webtorrent.dev\",\n * \"wss://tracker.openwebtorrent.com\",\n * ]\n * ```\n */\n announceTrackers: string[];\n\n /**\n * The configuration for the RTC layer, utilized during WebRTC communication.\n * This configuration specifies the STUN/TURN servers used by WebRTC to establish connections through NATs and firewalls.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/RTCConfiguration\n *\n * @default\n * ```json\n * {\n * \"rtcConfig\": {\n * \"iceServers\": [\n * { \"urls\": \"stun:stun.l.google.com:19302\" },\n * { \"urls\": \"stun:global.stun.twilio.com:3478\" }\n * ]\n * }\n * }\n * ```\n */\n rtcConfig: RTCConfiguration;\n\n /**\n * An optional unique identifier for the swarm, used to isolate peer pools by media stream.\n * If left undefined, the first manifest's response URL — after redirects,\n * with its query string discarded — names the swarm. Set it when that URL\n * differs between viewers of the same content, for example a redirect to a\n * per-viewer edge host or a token in the path (see specs/segment-identity.md).\n *\n * This property cannot be changed at runtime: stream identity is derived\n * from it once, when a stream is registered.\n *\n * @default\n * ```typescript\n * swarmId: undefined\n * ```\n */\n swarmId?: string;\n\n /**\n * An optional function that builds a custom stream swarm ID.\n * The stream swarm ID is hashed into the infohash announced to trackers\n * (`infoHash = computeInfoHash(streamSwarmId)`), so it fully defines which\n * swarm the stream's peers join.\n *\n * Use it to make infohashes predictable on a server: build the ID from\n * values the server knows (e.g. swarm ID, stream type, resolution), then\n * compute the same infohash server-side with `computeInfoHash` from\n * `p2p-media-loader-core/server` — for example, to allowlist the hashes\n * on a private tracker.\n *\n * The function must be deterministic and identical across all peers of the\n * swarm, and every distinct stream must map to a distinct ID: peers whose\n * streams resolve to the same infohash exchange segments with each other, and\n * registering two different streams with the same ID fails the registration\n * (reported via the `onStreamRegistrationError` event). Include enough\n * properties to guarantee uniqueness — resolution alone collides on ladders\n * with several bitrates at the same resolution. If in doubt, incorporate the\n * `identityHash` from the context (reproduce it server-side with\n * `computeStreamIdentityHash`).\n *\n * Called once per stream at registration. This property cannot be changed\n * at runtime.\n *\n * @param context - The stream identity data the ID may be built from,\n * including the ready-made `defaultStreamSwarmId`.\n * @returns The stream swarm ID, or `undefined` to use the default\n * derivation (`` `${peerProtocolVersion}-${swarmId}-${streamType}-${identityHash}` ``,\n * provided as `context.defaultStreamSwarmId`).\n *\n * @default\n * ```typescript\n * streamSwarmIdBuilder: undefined\n * ```\n *\n * @example\n * ```typescript\n * // Include bitrate: resolution alone collides on multi-bitrate ladders.\n * streamSwarmIdBuilder: ({ swarmId, streamType, properties }) =>\n * `my-app-${swarmId}-${streamType}-${properties.height ?? 0}-${properties.bitrate ?? 0}`,\n * ```\n */\n streamSwarmIdBuilder?: (\n context: StreamSwarmIdBuilderContext,\n ) => string | undefined;\n\n /**\n * An optional function to validate a P2P segment before fully integrating it into the playback buffer.\n * @param url The URL of the segment to validate.\n * @param byteRange The optional byte range of the segment.\n * @param data The downloaded segment data.\n * @returns A promise that resolves to a boolean indicating whether the segment is valid.\n *\n * @default\n * ```typescript\n * validateP2PSegment: undefined\n * ```\n */\n validateP2PSegment?: (\n url: string,\n byteRange: ByteRange | undefined,\n data: ArrayBuffer,\n ) => Promise<boolean>;\n\n /**\n * An optional function to validate an HTTP segment before fully integrating it into the playback buffer.\n * @param url The URL of the segment to validate.\n * @param byteRange The optional byte range of the segment.\n * @param data The downloaded segment data.\n * @returns A promise that resolves to a boolean indicating whether the segment is valid.\n *\n * @default\n * ```typescript\n * validateHTTPSegment: undefined\n * ```\n */\n validateHTTPSegment?: (\n url: string,\n byteRange: ByteRange | undefined,\n data: ArrayBuffer,\n ) => Promise<boolean>;\n\n /**\n * An optional function to customize the setup of HTTP requests for segment downloads.\n * @param segmentUrl The URL of the segment.\n * @param segmentByteRange The range of bytes requested for the segment.\n * @param requestAbortSignal An abort signal to cancel the request if needed (will be `undefined` if `AbortController` is not supported by the browser).\n * @param requestByteRange An additional byte range for partial requests, if required.\n * @returns A promise that resolves to the configured request, or `undefined` if no customization is necessary.\n *\n * @default\n * ```typescript\n * httpRequestSetup: undefined\n * ```\n */\n httpRequestSetup?: (\n segmentUrl: string,\n segmentByteRange: ByteRange | undefined,\n requestAbortSignal: AbortSignal | undefined,\n requestByteRange: { start: number; end?: number } | undefined,\n ) => Promise<Request | undefined | null>;\n\n /**\n * The maximum number of active peer-to-peer connections for the stream.\n * If this limit is reached, the client will stop accepting new incoming offers\n * and cease requesting new peers from the tracker until the connection count drops.\n *\n * @default\n * ```typescript\n * p2pMaxPeers: 50\n * ```\n */\n p2pMaxPeers: number;\n\n /**\n * The multiplier applied to `p2pMaxPeers` to determine the hard limit for accepting incoming connections.\n * To keep the P2P swarm healthy and well-mixed, incoming connection offers are accepted up to this hard limit,\n * and a background cleanup process will periodically prune the worst-performing peers if the total count exceeds `p2pMaxPeers`.\n *\n * @default\n * ```typescript\n * p2pChurnMaxPeersMultiplier: 1.5\n * ```\n */\n p2pChurnMaxPeersMultiplier: number;\n\n /**\n * The interval (in milliseconds) at which the background churning process evaluates and prunes the worst-performing\n * peers if the total connection count exceeds `p2pMaxPeers`.\n *\n * @default\n * ```typescript\n * p2pChurnCleanupIntervalMs: 30000\n * ```\n */\n p2pChurnCleanupIntervalMs: number;\n\n /**\n * The duration (in milliseconds) of the grace period granted to new peers.\n * During this time, newly connected peers are protected from being dropped by the churning logic,\n * allowing them time to establish connections and prove their bandwidth.\n *\n * @default\n * ```typescript\n * p2pChurnGracePeriodMs: 15000\n * ```\n */\n p2pChurnGracePeriodMs: number;\n\n /**\n * The number of WebRTC offers to generate and send to the tracker per announce request.\n * This controls how aggressively the client attempts to discover new peers.\n *\n * @default\n * ```typescript\n * webRtcOffersCount: 5\n * ```\n */\n webRtcOffersCount: number;\n\n /**\n * The duration (in milliseconds) to keep a pending WebRTC offer alive while waiting for an answer from a remote peer.\n *\n * @default\n * ```typescript\n * webRtcOfferTimeoutMs: 50000\n * ```\n */\n webRtcOfferTimeoutMs: number;\n\n /**\n * The maximum duration (in milliseconds) to wait for ICE candidates to gather before sending an offer.\n *\n * @default\n * ```typescript\n * webRtcIceGatheringTimeoutMs: 5000\n * ```\n */\n webRtcIceGatheringTimeoutMs: number;\n\n /**\n * The maximum duration (in milliseconds) to wait for the actual RTCDataChannel to open after signaling has completed.\n *\n * @default\n * ```typescript\n * webRtcConnectionTimeoutMs: 15000\n * ```\n */\n webRtcConnectionTimeoutMs: number;\n};\n\n/** The stream identity data passed to a custom `streamSwarmIdBuilder`. */\nexport type StreamSwarmIdBuilderContext = {\n /**\n * The swarm ID of the stream: the configured `swarmId` or, if unset, the\n * first manifest's response URL with its query string discarded.\n */\n swarmId: string;\n\n /**\n * The stream key (`Stream.runtimeId`): the media playlist URL for HLS, the\n * Representation id for DASH. A playlist URL may differ from peer to peer\n * (CDN host, signed path) — avoid using it in the ID.\n */\n runtimeId: string;\n\n /** Stream type. */\n streamType: StreamType;\n\n /** Raw stream properties from the manifest. */\n properties: Readonly<StreamProperties>;\n\n /** Stream identity hash derived from the manifest's stream properties. The same for all peers. */\n identityHash: string;\n\n /**\n * The stream swarm ID the default derivation would produce:\n * `${peerProtocolVersion}-${swarmId}-${streamType}-${identityHash}`.\n * Useful as a base for custom IDs, e.g. `` `${tenant}-${defaultStreamSwarmId}` ``.\n */\n defaultStreamSwarmId: string;\n\n /** Version of the peer swarm protocol used in the default stream swarm ID derivation. */\n peerProtocolVersion: string;\n};\n\n/**\n * Specifies the source of a download within a media streaming context.\n *\n * \"http\" - Indicates that the segment was downloaded using the HTTP protocol.\n *\n * \"p2p\"- Indicates that the segment was downloaded through a peer-to-peer network.\n */\nexport type DownloadSource = \"http\" | \"p2p\";\n\n/** Fields common to all segment event payloads. */\nexport type SegmentEventDetails = {\n /** The segment that the event is about. */\n segment: Segment;\n\n /** The source of the download. */\n downloadSource: DownloadSource;\n\n /** The peer ID, if the segment is downloaded from a peer. */\n peerId: string | undefined;\n\n /** The info hash of the swarm that the segment belongs to. */\n infoHash: string;\n\n /** The type of stream that the segment is associated with. */\n streamType: StreamType;\n};\n\n/** Represents details about a segment event. */\nexport type SegmentStartDetails = SegmentEventDetails;\n\n/** Represents details about a segment error event. */\nexport type SegmentErrorDetails = SegmentEventDetails & {\n /** The error that occurred during the segment download. */\n error: RequestError;\n};\n\n/** Represents details about a segment abort event. */\nexport type SegmentAbortDetails = Omit<\n SegmentEventDetails,\n \"downloadSource\"\n> & {\n /** The source of the download, if it was determined before the abort. */\n downloadSource: DownloadSource | undefined;\n};\n\n/** Represents the details about a loaded segment. */\nexport type SegmentLoadDetails = SegmentEventDetails & {\n /** The length of the segment in bytes. */\n bytesLength: number;\n};\n\n/** Represents the details of a peer in a peer-to-peer network. */\nexport type PeerDetails = {\n /** The unique identifier for a peer in the network. */\n peerId: string;\n /** The info hash of the swarm that the peer is part of. */\n infoHash: string;\n /** The type of stream that the peer is connected to. */\n streamType: StreamType;\n /** The tracker URL that the peer was discovered from. */\n trackerUrl: string;\n};\n\n/** Represents the types of errors that can occur during a peer connection. */\nexport type PeerErrorType =\n | \"transport-error\"\n | \"protocol-violation\"\n | \"bytes-length-mismatch\"\n | \"validation-failed\"\n | \"timeout\"\n | \"connection-lost\";\n\n/**\n * Base class for all errors and warnings emitted by the library, carrying a\n * machine-readable `type` discriminator. Use `instanceof TypedError` to catch\n * any library error regardless of its specific class.\n */\nexport abstract class TypedError<T extends string> extends Error {\n readonly cause?: unknown;\n\n constructor(\n readonly type: T,\n message?: string,\n cause?: unknown,\n ) {\n super(message);\n // Explicit assignment for ES6 compatibility (ErrorOptions with cause is ES2022)\n this.cause = cause;\n }\n}\n\n/** Represents an error that occurred during a peer connection. */\nexport class PeerError extends TypedError<PeerErrorType> {\n readonly name = \"PeerError\";\n}\n\n/** Represents the details of a peer error event. */\nexport type PeerErrorDetails = PeerDetails & {\n /** The error that occurred during the peer-to-peer connection. */\n error: PeerError;\n};\n\n/** Represents the types of warnings that can occur during a peer connection. */\nexport type PeerWarningType = \"timeout-strike\";\n\n/** Represents a warning that occurred during a peer connection. */\nexport class PeerWarning extends TypedError<PeerWarningType> {\n readonly name = \"PeerWarning\";\n}\n\n/** Represents the details of a peer warning event. */\nexport type PeerWarningDetails = PeerDetails & {\n /** The warning that occurred during the peer-to-peer connection. */\n warning: PeerWarning;\n};\n\n/** Fields common to all tracker event payloads. */\nexport type TrackerEventDetails = {\n /** The tracker URL. */\n trackerUrl: string;\n /** The info hash of the swarm that the tracker is for. */\n infoHash: string;\n /** The type of stream that the tracker is for. */\n streamType: StreamType;\n};\n\n/** Represents the details of a tracker error event. */\nexport type TrackerErrorDetails = TrackerEventDetails & {\n /** The error that occurred during the tracker request. */\n error: TrackerError;\n};\n\n/** Represents the details of a tracker warning event. */\nexport type TrackerWarningDetails = TrackerEventDetails & {\n /** The warning that occurred during the tracker request. */\n warning: TrackerWarning;\n};\n\n/** Represents the types of errors that can occur during the tracker request process. */\nexport type TrackerErrorType =\n \"announce-failed\" | \"parse-error\" | \"tracker-response\" | \"signaling-failed\";\n\n/** Represents an error that occurred during a tracker request. */\nexport class TrackerError extends TypedError<TrackerErrorType> {\n readonly name = \"TrackerError\";\n}\n\n/** Represents the types of warnings that can occur during the tracker request process. */\nexport type TrackerWarningType = \"tracker-response\" | \"offer-failed\";\n\n/** Represents a warning that occurred during a tracker request. */\nexport class TrackerWarning extends TypedError<TrackerWarningType> {\n readonly name = \"TrackerWarning\";\n}\n\n/** Represents the types of errors that can occur during the peer connection process. */\nexport type PeerConnectErrorType = \"connection-failed\";\n\n/** Represents an error that occurred while establishing a peer connection. */\nexport class PeerConnectError extends TypedError<PeerConnectErrorType> {\n readonly name = \"PeerConnectError\";\n}\n\n/** Represents the details of a peer connection error event. */\nexport type PeerConnectErrorDetails = PeerDetails & {\n /** The error that occurred during the peer-to-peer connection. */\n error: PeerConnectError;\n};\n\n/** Represents the details of a stream registration failure. */\nexport type StreamRegistrationErrorDetails = {\n /** Key of the stream that failed to register (see `Stream.runtimeId`). */\n runtimeId: string;\n\n /** Stream type. */\n streamType: StreamType;\n\n /** Raw stream properties the core read from the manifest. */\n properties: Readonly<StreamProperties>;\n\n /** The error that caused the registration to fail. */\n error: Error;\n};\n\n/** Represents the details about a registered stream. */\nexport type StreamAddedDetails = {\n /**\n * The registered stream with its computed identity.\n *\n * A snapshot taken at registration, detached from the core's internal\n * stream state. The identity fields never change after registration, so\n * the snapshot stays accurate for the stream's lifetime.\n */\n stream: Stream;\n};\n\n/**\n * What a processed manifest described, for each stream it listed segments\n * for. A master playlist lists none and yields no entries; a media playlist\n * yields one; an MPD yields one per Representation.\n */\nexport type ProcessedStream = {\n /** The stream key (see `Stream.runtimeId`). */\n readonly key: string;\n readonly type: StreamType;\n readonly isLive: boolean;\n /** Start of the earliest listed segment on the stream's manifest timeline. */\n readonly start: number;\n /** End of the latest listed segment on the same timeline. */\n readonly end: number;\n readonly segmentCount: number;\n};\n\n/** The outcome of `Core.processManifest` for a manifest a parser accepted. */\nexport type ProcessedManifest = {\n readonly streams: readonly ProcessedStream[];\n};\n\n/**\n * A segment request the registry could not resolve. See\n * specs/manifest-registry.md, \"Divergence between core and the player\".\n */\nexport type SegmentRegistryMissDetails = {\n /** The URL the player requested. */\n url: string;\n\n /** The byte range the player requested, if any. */\n byteRange?: ByteRange;\n};\n\n/**\n * The CoreEventMap defines a comprehensive suite of event handlers crucial for monitoring and controlling the lifecycle\n * of segment downloading and uploading processes.\n */\nexport type CoreEventMap = {\n /**\n * Invoked when a stream is registered in the Core, once per stream.\n * The stream carries its computed identity, including the infohash\n * announced to trackers for its swarm.\n *\n * @param params - Contains the registered stream.\n */\n onStreamAdded: (params: StreamAddedDetails) => void;\n\n /**\n * Invoked when a stream fails to register in the Core: a custom\n * `streamSwarmIdBuilder` returned an invalid or colliding stream swarm ID.\n * The stream stays unknown to the core — its segments load through the\n * player's default path without P2P; other streams are unaffected.\n *\n * Subscribe to surface `streamSwarmIdBuilder` misconfigurations: without a\n * listener the failure is only visible in debug logs.\n *\n * @param params - Contains the failed registration and the error.\n */\n onStreamRegistrationError: (params: StreamRegistrationErrorDetails) => void;\n\n /**\n * Invoked when the player requests a segment the registry does not know.\n * The request falls back to the player's own loader and plays without P2P;\n * this event makes the disagreement between the core's manifest parse and\n * the player's observable rather than silent. Initialization segments are\n * recognised and never reported.\n *\n * @param params - The URL and byte range that missed.\n */\n onSegmentRegistryMiss: (params: SegmentRegistryMissDetails) => void;\n\n /**\n * Invoked when a segment is fully downloaded and available for use.\n *\n * @param params - Contains information about the loaded segment.\n */\n onSegmentLoaded: (params: SegmentLoadDetails) => void;\n\n /**\n * Triggered when an error occurs during the download of a segment.\n *\n * @param params - Contains information about the errored segment.\n */\n onSegmentError: (params: SegmentErrorDetails) => void;\n\n /**\n * Called if the download of a segment is aborted before completion.\n *\n * @param params - Contains information about the aborted segment.\n */\n onSegmentAbort: (params: SegmentAbortDetails) => void;\n\n /**\n * Fired at the beginning of a segment download process.\n *\n * @param params - Provides details about the segment being downloaded.\n */\n onSegmentStart: (params: SegmentStartDetails) => void;\n\n /**\n * Occurs when a new peer-to-peer connection is established.\n *\n * @param params - Contains details about the peer that the event is about.\n */\n onPeerConnect: (params: PeerDetails) => void;\n\n /**\n * Triggered when an error occurs while establishing a peer-to-peer connection.\n *\n * @param params - Contains details about the connection error and the peer.\n */\n onPeerConnectError: (params: PeerConnectErrorDetails) => void;\n\n /**\n * Triggered when an existing peer-to-peer connection is closed.\n *\n * @param params - Contains details about the peer that the event is about.\n */\n onPeerClose: (params: PeerDetails) => void;\n\n /**\n * Triggered when an error occurs during a peer-to-peer connection.\n *\n * @param params - Contains details about the error and the peer that the event is about.\n */\n onPeerError: (params: PeerErrorDetails) => void;\n\n /**\n * Called when a warning occurs during a peer-to-peer connection.\n *\n * @param params - Contains information about the peer warning.\n */\n onPeerWarning: (params: PeerWarningDetails) => void;\n\n // Positional parameters instead of an object to avoid allocation on every\n // chunk — this is a high-frequency event and allocations increase GC pressure.\n /**\n * Invoked after a chunk of data from a segment has been successfully downloaded.\n *\n * @param bytesLength - The size of the downloaded chunk in bytes.\n * @param downloadSource - The source of the download.\n * @param peerId - The peer ID of the peer that the event is about, if applicable.\n * @param streamType - The type of stream that the chunk belongs to.\n * @param infoHash - The info hash of the swarm that the chunk belongs to.\n */\n onChunkDownloaded: (\n bytesLength: number,\n downloadSource: DownloadSource,\n peerId: string | undefined,\n streamType: StreamType,\n infoHash: string,\n ) => void;\n\n // Positional parameters instead of an object to avoid allocation on every\n // chunk — this is a high-frequency event and allocations increase GC pressure.\n /**\n * Called when a chunk of data has been successfully uploaded to a peer.\n *\n * @param bytesLength - The length of the segment in bytes.\n * @param peerId - The peer ID, if the segment was downloaded from a peer\n * @param streamType - The type of stream that the chunk belongs to.\n * @param infoHash - The info hash of the swarm that the chunk belongs to.\n */\n onChunkUploaded: (\n bytesLength: number,\n peerId: string,\n streamType: StreamType,\n infoHash: string,\n ) => void;\n\n /**\n * Called when an error occurs during the tracker request process.\n *\n * @param params - Contains information about the tracker error.\n */\n onTrackerError: (params: TrackerErrorDetails) => void;\n\n /**\n * Called when a warning occurs during the tracker request process.\n *\n * @param params - Contains information about the tracker warning.\n */\n onTrackerWarning: (params: TrackerWarningDetails) => void;\n};\n\n/** Defines the types of errors that can occur during a request abortion process. */\nexport type RequestAbortErrorType = \"abort\" | \"bytes-receiving-timeout\";\n\n/** Defines the types of errors specific to HTTP requests. */\nexport type HttpRequestErrorType =\n | \"http-error\"\n | \"http-bytes-mismatch\"\n | \"http-unexpected-status-code\"\n | \"http-segment-validation-failed\";\n\n/** Defines the types of errors specific to peer-to-peer requests. */\nexport type PeerRequestErrorType =\n \"peer-segment-absent\" | \"peer-closed\" | \"p2p-segment-validation-failed\";\n\n/** Enumerates all possible request error types, including HTTP and peer-related errors. */\nexport type RequestErrorType =\n RequestAbortErrorType | PeerRequestErrorType | HttpRequestErrorType;\n\n/**\n * Represents an error that can occur during the request process, with a timestamp for when the error occurred.\n * @template T - The specific type of request error.\n */\nexport class RequestError<\n T extends RequestErrorType = RequestErrorType,\n> extends TypedError<T> {\n readonly name = \"RequestError\";\n\n /** Error timestamp. */\n readonly timestamp: number;\n\n /**\n * Constructs a new RequestError.\n * @param type - The specific error type.\n * @param message - Optional message describing the error.\n * @param cause - Optional underlying cause of the error.\n */\n constructor(type: T, message?: string, cause?: unknown) {\n super(type, message, cause);\n this.timestamp = performance.now();\n }\n}\n\n/** Represents the response from a segment request, including the data and measured bandwidth. */\nexport type SegmentResponse = {\n /**\n * Segment data as an ArrayBuffer.\n *\n * The caller's own copy, never the buffer the core keeps in segment storage\n * for P2P upload. It may be modified, and transferred to a worker the way\n * players transmux — doing so detaches it here and leaves what peers are\n * served untouched.\n */\n data: ArrayBuffer;\n\n /** Measured bandwidth for the segment download, in bytes per second. */\n bandwidth: number;\n};\n\n/** Custom error class for errors that occur during core network requests. */\nexport class CoreRequestError extends TypedError<\"failed\" | \"aborted\"> {\n readonly name = \"CoreRequestError\";\n}\n","class AbortSignalPolyfill {\n aborted = false;\n readonly #listeners = new Set<(event?: unknown) => void>();\n\n addEventListener(_type: \"abort\", listener: (event?: unknown) => void) {\n this.#listeners.add(listener);\n }\n\n removeEventListener(_type: \"abort\", listener: (event?: unknown) => void) {\n this.#listeners.delete(listener);\n }\n\n dispatchEvent(_type: \"abort\") {\n this.aborted = true;\n for (const listener of this.#listeners) {\n try {\n listener();\n } catch {\n // Swallow listener errors\n }\n }\n this.#listeners.clear();\n }\n}\n\nclass AbortControllerPolyfill {\n readonly signal = new AbortSignalPolyfill();\n\n abort() {\n this.signal.dispatchEvent(\"abort\");\n }\n}\n\nexport const isAbortControllerSupported =\n typeof AbortController !== \"undefined\";\n\nexport const SafeAbortController = isAbortControllerSupported\n ? AbortController\n : AbortControllerPolyfill;\n","import {\n CoreConfig,\n CoreEventMap,\n RequestError,\n HttpRequestErrorType,\n} from \"./types.js\";\nimport {\n Request as SegmentRequest,\n RequestControls,\n} from \"./requests/request.js\";\nimport { EventTarget } from \"./utils/event-target.js\";\nimport {\n SafeAbortController,\n isAbortControllerSupported,\n} from \"./utils/abort-controller.js\";\n\ntype HttpConfig = Pick<\n CoreConfig,\n \"httpNotReceivingBytesTimeoutMs\" | \"httpRequestSetup\" | \"validateHTTPSegment\"\n>;\n\nexport class HttpRequestExecutor {\n private readonly abortController = new SafeAbortController();\n private expectedBytesLength?: number;\n private requestByteRange?: { start: number; end?: number };\n private readonly onChunkDownloaded: CoreEventMap[\"onChunkDownloaded\"];\n\n private isAborted(): boolean {\n return this.abortController.signal.aborted;\n }\n\n constructor(\n private readonly request: SegmentRequest,\n private readonly httpConfig: HttpConfig,\n eventTarget: EventTarget<CoreEventMap>,\n ) {\n this.onChunkDownloaded =\n eventTarget.getEventDispatcher(\"onChunkDownloaded\");\n\n const { byteRange } = this.request.segment;\n if (byteRange) this.requestByteRange = { ...byteRange };\n }\n\n execute() {\n const startControls = {\n onAbort: () => this.abortController.abort(),\n notReceivingBytesTimeoutMs:\n this.httpConfig.httpNotReceivingBytesTimeoutMs,\n };\n\n const completed = this.request.tryCompleteByLoadedBytes(\n { downloadSource: \"http\" },\n startControls,\n this.httpConfig.validateHTTPSegment,\n \"http-segment-validation-failed\",\n );\n\n if (completed) return;\n\n if (this.request.loadedBytes !== 0) {\n this.requestByteRange = this.requestByteRange ?? { start: 0 };\n this.requestByteRange.start =\n this.requestByteRange.start + this.request.loadedBytes;\n }\n if (this.request.totalBytes) {\n this.expectedBytesLength =\n this.request.totalBytes - this.request.loadedBytes;\n }\n\n const requestControls = this.request.start(\n { downloadSource: \"http\" },\n startControls,\n );\n void this.fetch(requestControls);\n }\n\n private async fetch(requestControls: RequestControls) {\n const { segment } = this.request;\n let activeReader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\n if (this.isAborted()) {\n return;\n }\n\n const onAbort = () => {\n try {\n activeReader?.cancel().catch(() => {\n // Swallow stream cancel errors\n });\n } catch {\n // Swallow stream cancel errors\n }\n };\n\n this.abortController.signal.addEventListener(\"abort\", onAbort);\n\n const abortSignal = isAbortControllerSupported\n ? (this.abortController.signal as AbortSignal)\n : undefined;\n\n try {\n let request = await this.httpConfig.httpRequestSetup?.(\n segment.url,\n segment.byteRange,\n abortSignal,\n this.requestByteRange,\n );\n\n if (this.isAborted()) {\n throw new DOMException(\"Request aborted\", \"AbortError\");\n }\n\n if (!request) {\n // Use default empty Headers constructor and set fields individually for compatibility\n // with older browsers (e.g. Chrome < 47) that do not support passing an object parameter.\n const headers = new Headers();\n if (this.requestByteRange) {\n headers.set(\n \"Range\",\n `bytes=${this.requestByteRange.start}-${\n this.requestByteRange.end ?? \"\"\n }`,\n );\n }\n\n const requestOptions: RequestInit = { headers };\n if (abortSignal) {\n requestOptions.signal = abortSignal;\n }\n\n request = new Request(segment.url, requestOptions);\n }\n\n if (this.isAborted()) {\n throw new DOMException(\n \"Request aborted before request fetch\",\n \"AbortError\",\n );\n }\n\n const response = await window.fetch(request);\n\n if (this.isAborted()) {\n throw new DOMException(\"Request aborted\", \"AbortError\");\n }\n\n this.handleResponseHeaders(response);\n\n requestControls.firstBytesReceived();\n\n if (!response.body || typeof response.body.getReader !== \"function\") {\n // Fallback for older browsers (e.g. Chrome < 43) that do not support ReadableStream\n // or response.body.getReader. Reads the entire segment into an ArrayBuffer instead.\n const arrayBuffer = await response.arrayBuffer();\n if (this.isAborted()) {\n throw new DOMException(\"Request aborted\", \"AbortError\");\n }\n const value = new Uint8Array(arrayBuffer);\n requestControls.addLoadedChunk(value);\n this.onChunkDownloaded(\n value.byteLength,\n \"http\",\n undefined,\n segment.stream.type,\n this.request.infoHash,\n );\n } else {\n const reader = response.body.getReader();\n activeReader = reader;\n\n for (;;) {\n if (this.isAborted()) {\n throw new DOMException(\"Request aborted\", \"AbortError\");\n }\n const { done, value } = await reader.read();\n if (done) break;\n if (this.isAborted()) {\n throw new DOMException(\"Request aborted\", \"AbortError\");\n }\n requestControls.addLoadedChunk(value);\n this.onChunkDownloaded(\n value.byteLength,\n \"http\",\n undefined,\n segment.stream.type,\n this.request.infoHash,\n );\n }\n }\n\n if (this.isAborted()) {\n throw new DOMException(\"Request aborted\", \"AbortError\");\n }\n\n // If the HTTP connection drops gracefully but prematurely, fetch yields done: true\n // without throwing an error. We must verify that we received the full segment.\n // If truncated, we throw without clearing loaded bytes to allow the next\n // download attempt to resume from the current offset using HTTP Range requests.\n if (\n this.request.totalBytes !== undefined &&\n this.request.loadedBytes !== this.request.totalBytes\n ) {\n throw new RequestError(\n \"http-bytes-mismatch\",\n `HTTP response truncated: received ${this.request.loadedBytes} of ${this.request.totalBytes} bytes`,\n );\n }\n\n // A 200 with no body is not a segment. Nothing downstream would notice:\n // it would be stored, announced, seeded to peers and appended by the\n // player, which is a stall or a rendition exclusion rather than an error.\n // Failing the attempt leaves the retry rules to deal with it.\n if (this.request.loadedBytes === 0) {\n this.request.clearLoadedBytes();\n throw new RequestError<\"http-bytes-mismatch\">(\n \"http-bytes-mismatch\",\n \"HTTP response carried no bytes\",\n );\n }\n\n const isValid = await this.request.validateData(\n this.httpConfig.validateHTTPSegment,\n );\n\n if (this.isAborted()) {\n throw new DOMException(\"Request aborted\", \"AbortError\");\n }\n\n if (!isValid) {\n this.request.clearLoadedBytes();\n throw new RequestError<\"http-segment-validation-failed\">(\n \"http-segment-validation-failed\",\n );\n }\n\n requestControls.completeOnSuccess();\n } catch (error) {\n this.handleError(error, requestControls);\n } finally {\n this.abortController.signal.removeEventListener(\"abort\", onAbort);\n }\n }\n\n private handleResponseHeaders(response: Response) {\n if (!response.ok) {\n if (response.status === 406 || response.status === 416) {\n this.request.clearLoadedBytes();\n throw new RequestError<\"http-bytes-mismatch\">(\n \"http-bytes-mismatch\",\n response.statusText,\n );\n } else {\n throw new RequestError<\"http-error\">(\"http-error\", response.statusText);\n }\n }\n\n const { requestByteRange } = this;\n if (requestByteRange) {\n if (response.status === 200) {\n if (this.request.segment.byteRange) {\n throw new RequestError(\"http-unexpected-status-code\");\n } else {\n this.request.clearLoadedBytes();\n }\n } else {\n if (response.status !== 206) {\n throw new RequestError(\n \"http-unexpected-status-code\",\n response.statusText,\n );\n }\n const contentLengthHeader = response.headers.get(\"Content-Length\");\n if (\n contentLengthHeader &&\n this.expectedBytesLength !== undefined &&\n this.expectedBytesLength !== +contentLengthHeader\n ) {\n this.request.clearLoadedBytes();\n throw new RequestError(\"http-bytes-mismatch\", response.statusText);\n }\n\n const contentRangeHeader = response.headers.get(\"Content-Range\");\n const contentRange = contentRangeHeader\n ? parseContentRangeHeader(contentRangeHeader)\n : undefined;\n if (contentRange) {\n const { from, to } = contentRange;\n const responseExpectedBytesLength =\n to !== undefined && from !== undefined ? to - from + 1 : undefined;\n\n if (\n (responseExpectedBytesLength !== undefined &&\n this.expectedBytesLength !== responseExpectedBytesLength) ||\n (from !== undefined && requestByteRange.start !== from) ||\n (to !== undefined &&\n requestByteRange.end !== undefined &&\n requestByteRange.end !== to)\n ) {\n this.request.clearLoadedBytes();\n throw new RequestError(\"http-bytes-mismatch\", response.statusText);\n }\n }\n }\n }\n\n if (response.status === 200 && this.request.totalBytes === undefined) {\n const contentLengthHeader = response.headers.get(\"Content-Length\");\n if (contentLengthHeader) this.request.setTotalBytes(+contentLengthHeader);\n }\n }\n\n private handleError(error: unknown, requestControls: RequestControls) {\n // Abort-initiated errors: the Request already transitioned its own\n // status via cancel/abortOnTimeout, nothing to do here.\n if (this.isAborted()) return;\n\n if (error instanceof Error) {\n const httpLoaderError =\n error instanceof RequestError\n ? (error as RequestError<HttpRequestErrorType>)\n : new RequestError(\"http-error\", error.message);\n\n requestControls.failWithError(httpLoaderError);\n }\n }\n}\n\nconst rangeHeaderRegex = /^bytes (?:(?:(\\d+)|)-(?:(\\d+)|)|\\*)\\/(?:(\\d+)|\\*)$/;\n\nfunction parseContentRangeHeader(headerValue: string) {\n const match = rangeHeaderRegex.exec(headerValue.trim());\n if (!match) return;\n\n const [, from, to, total] = match;\n return {\n from: from ? parseInt(from) : undefined,\n to: to ? parseInt(to) : undefined,\n total: total ? parseInt(total) : undefined,\n };\n}\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","type BasePeerCommand<T extends PeerCommandType = PeerCommandType> = {\n c: T;\n};\n\nexport const enum PeerCommandType {\n SegmentsAnnouncement,\n SegmentRequest,\n SegmentData,\n SegmentDataSendingCompleted,\n SegmentAbsent,\n CancelSegmentRequest,\n}\n\nexport type PeerSegmentCommand = BasePeerCommand<\n | PeerCommandType.SegmentAbsent\n | PeerCommandType.CancelSegmentRequest\n | PeerCommandType.SegmentDataSendingCompleted\n> & {\n i: number; // segment id\n r: number; // request id\n};\n\nexport type PeerRequestSegmentCommand =\n BasePeerCommand<PeerCommandType.SegmentRequest> & {\n i: number; // segment id\n r: number; // request id\n b?: number; // byte from\n };\n\nexport type PeerSegmentAnnouncementCommand =\n BasePeerCommand<PeerCommandType.SegmentsAnnouncement> & {\n l?: number[]; // loaded segments\n p?: number[]; // segments loading by http\n };\n\nexport type PeerSendSegmentCommand =\n BasePeerCommand<PeerCommandType.SegmentData> & {\n i: number; // segment id\n r: number; // request id\n s: number; // size in bytes\n };\n\nexport type PeerCommand =\n | PeerSegmentCommand\n | PeerRequestSegmentCommand\n | PeerSegmentAnnouncementCommand\n | PeerSendSegmentCommand;\n","import { CommonCoreConfig, CoreConfig, StreamConfig } from \"../types.js\";\n\nexport function getPromiseWithResolvers<T = void>() {\n let resolve: (value: T) => void;\n let reject: (reason?: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n return {\n promise,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n resolve: resolve!,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n reject: reject!,\n };\n}\n\nexport function queueMicrotask(fn: () => void): void {\n void Promise.resolve().then(fn);\n}\n\nexport function joinChunks(chunks: Uint8Array[], totalBytes?: number) {\n totalBytes ??= chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n\n const buffer = new Uint8Array(totalBytes);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return buffer;\n}\n\nexport function getRandomItem<T>(items: T[]): T {\n return items[Math.floor(Math.random() * items.length)];\n}\n\nexport function getWeightedRandomItem<T>(\n items: T[],\n weightAccessor: (item: T) => number,\n): T {\n if (items.length === 0) throw new Error(\"Cannot get item from empty array\");\n if (items.length === 1) return items[0];\n\n let totalWeight = 0;\n const weights = items.map((item) => {\n const weight = weightAccessor(item);\n totalWeight += weight;\n return weight;\n });\n\n let randomWeight = Math.random() * totalWeight;\n for (let i = 0; i < items.length; i++) {\n randomWeight -= weights[i];\n if (randomWeight <= 0) return items[i];\n }\n\n return items[items.length - 1];\n}\n\nexport function utf8ToUintArray(utf8String: string): Uint8Array {\n return new TextEncoder().encode(utf8String);\n}\n\nexport function* arrayBackwards<T>(arr: T[]) {\n for (let i = arr.length - 1; i >= 0; i--) {\n yield arr[i];\n }\n}\n\nfunction isObject(item: unknown): item is Record<string, unknown> {\n return !!item && typeof item === \"object\" && !Array.isArray(item);\n}\n\nfunction isArray(item: unknown): item is unknown[] {\n return Array.isArray(item);\n}\n\nexport function filterUndefinedProps<T extends object>(obj: T): Partial<T> {\n function filter(obj: unknown): unknown {\n if (isObject(obj)) {\n const result: Record<string, unknown> = {};\n Object.keys(obj).forEach((key) => {\n if (obj[key] !== undefined) {\n const value = filter(obj[key]);\n if (value !== undefined) {\n result[key] = value;\n }\n }\n });\n return result;\n } else {\n return obj;\n }\n }\n\n return filter(obj) as Partial<T>;\n}\n\nexport function deepCopy<T>(item: T): T {\n if (isArray(item)) {\n return item.map((element) => deepCopy(element)) as T;\n } else if (isObject(item)) {\n const copy = {} as Record<string, unknown>;\n for (const key of Object.keys(item)) {\n copy[key] = deepCopy(item[key]);\n }\n return copy as T;\n } else {\n return item;\n }\n}\n\ntype RecursivePartial<T> = {\n [P in keyof T]?: T[P] extends object ? RecursivePartial<T[P]> : T[P];\n};\n\nexport function overrideConfig<T>(\n target: T,\n updates: RecursivePartial<T> | null,\n defaults: RecursivePartial<T> = {},\n): T {\n if (\n typeof target !== \"object\" ||\n target === null ||\n typeof updates !== \"object\" ||\n updates === null\n ) {\n return target;\n }\n\n (Object.keys(updates) as (keyof T)[]).forEach((key) => {\n const keyStr = typeof key === \"symbol\" ? key.toString() : String(key);\n if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") {\n throw new Error(`Attempt to modify restricted property '${keyStr}'`);\n }\n\n const updateValue = updates[key];\n const defaultValue = defaults[key];\n\n if (key in target) {\n if (updateValue === undefined) {\n target[key] =\n defaultValue === undefined\n ? (undefined as (T & object)[keyof T])\n : (defaultValue as (T & object)[keyof T]);\n } else {\n target[key] = updateValue as (T & object)[keyof T];\n }\n }\n });\n\n return target;\n}\n\ntype MergeConfigsToTypeOptions = {\n defaultConfig: StreamConfig | CommonCoreConfig | CoreConfig;\n baseConfig?: Partial<CoreConfig>;\n specificStreamConfig?: Partial<StreamConfig>;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters\nexport function mergeAndFilterConfig<T>(options: MergeConfigsToTypeOptions) {\n const { defaultConfig, baseConfig = {}, specificStreamConfig = {} } = options;\n\n const mergedConfig = deepCopy({\n ...defaultConfig,\n ...baseConfig,\n ...specificStreamConfig,\n });\n\n const keysOfT = Object.keys(defaultConfig) as (keyof T)[];\n const filteredConfig: Partial<T> = {};\n\n keysOfT.forEach((key) => {\n if (key in mergedConfig) {\n filteredConfig[key] = mergedConfig[\n key as keyof typeof mergedConfig\n ] as T[keyof T];\n }\n });\n\n return filteredConfig as T;\n}\n","import { joinChunks } from \"../../utils/utils.js\";\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder(\"utf8\");\n\n// restricted up to 16 item types (4 bits to type definition)\nexport const enum SerializedItem {\n Min = -1,\n Int,\n SimilarIntArray,\n String,\n Max,\n}\n\nexport function getRequiredBytesForInt(num: number): number {\n if (num === 0) return 1;\n const necessaryBits = Math.floor(Math.log2(Math.abs(num))) + 2;\n return Math.ceil(necessaryBits / 8);\n}\n\nfunction intToBytes(num: number): Uint8Array {\n const isNegative = num < 0;\n const bytesAmountNumber = getRequiredBytesForInt(num);\n const bytes = new Uint8Array(bytesAmountNumber);\n\n num = Math.abs(num);\n for (let i = 0; i < bytesAmountNumber; i++) {\n const shift = 8 * (bytesAmountNumber - 1 - i);\n const byte = Math.floor(num / Math.pow(2, shift)) & 0xff;\n bytes[i] = byte;\n }\n\n if (isNegative) bytes[0] = bytes[0] | 0b10000000;\n return bytes;\n}\n\nfunction bytesToInt(bytes: Uint8Array): number {\n const byteLength = bytes.length;\n const getNumberPart = (byte: number, i: number): number => {\n const shift = 8 * (byteLength - 1 - i);\n return byte * Math.pow(2, shift);\n };\n\n // ignore first bit of first byte as it is sign bit\n let number = getNumberPart(bytes[0] & 0b01111111, 0);\n for (let i = 1; i < byteLength; i++) {\n number += getNumberPart(bytes[i], i);\n }\n if ((bytes[0] & 0b10000000) >> 7 !== 0) number = -number;\n\n return number;\n}\n\nexport function serializeInt(num: number): Uint8Array {\n const numBytes = intToBytes(num);\n const numberMetadata = (SerializedItem.Int << 4) | numBytes.length;\n return new Uint8Array([numberMetadata, ...numBytes]);\n}\n\nexport function deserializeInt(bytes: Uint8Array) {\n if (bytes.length === 0) throw new Error(\"Buffer is too short\");\n const metadata = bytes[0];\n const code: SerializedItem = metadata >> 4;\n if (code !== SerializedItem.Int) {\n throw new Error(\n \"Trying to deserialize integer with invalid serialized item code\",\n );\n }\n const numberBytesLength = metadata & 0b1111;\n if (numberBytesLength === 0) {\n throw new Error(\"Invalid integer: zero byte length\");\n }\n if (numberBytesLength > 7) {\n throw new Error(\"Invalid integer: byte length exceeds safe integer limit\");\n }\n const start = 1;\n const end = start + numberBytesLength;\n if (bytes.length < end) {\n throw new Error(\"Buffer is too short\");\n }\n return {\n number: bytesToInt(bytes.subarray(start, end)),\n byteLength: numberBytesLength + 1,\n };\n}\n\nexport function serializeUniqueSimilarIntArray(numbers: number[]) {\n const commonPartNumbersMap = new Map<number, ResizableUint8Array>();\n\n for (const number of numbers) {\n const diffByte = number & 0xff;\n const common = number - diffByte;\n const bytes = commonPartNumbersMap.get(common) ?? new ResizableUint8Array();\n if (!bytes.length) commonPartNumbersMap.set(common, bytes);\n bytes.push(diffByte);\n }\n\n const result = new ResizableUint8Array();\n result.push([SerializedItem.SimilarIntArray << 4, commonPartNumbersMap.size]);\n\n for (const [commonPart, binaryArray] of commonPartNumbersMap) {\n const { length } = binaryArray;\n const commonPartWithLength = commonPart + (length & 0xff);\n binaryArray.unshift(serializeInt(commonPartWithLength));\n result.push(binaryArray.getBuffer());\n }\n\n return result.getBuffer();\n}\n\nexport function deserializeUniqueSimilarIntArray(bytes: Uint8Array) {\n if (bytes.length < 2) throw new Error(\"Buffer is too short\");\n const [codeByte, commonPartArraysAmount] = bytes;\n const code: SerializedItem = codeByte >> 4;\n if (code !== SerializedItem.SimilarIntArray) {\n throw new Error(\n \"Trying to deserialize similar int array with invalid serialized item code\",\n );\n }\n\n let offset = 2;\n const originalIntArr: number[] = [];\n for (let i = 0; i < commonPartArraysAmount; i++) {\n const { number: commonPartWithLength, byteLength } = deserializeInt(\n bytes.subarray(offset),\n );\n offset += byteLength;\n const arrayLength = commonPartWithLength & 0xff;\n const actualLength = arrayLength === 0 ? 256 : arrayLength;\n const commonPart = commonPartWithLength - arrayLength;\n\n if (offset + actualLength > bytes.length) {\n throw new Error(\"Malformed similar int array: buffer too short\");\n }\n for (let j = 0; j < actualLength; j++) {\n const diffPart = bytes[offset];\n originalIntArr.push(commonPart + diffPart);\n offset++;\n }\n }\n\n return { numbers: originalIntArr, byteLength: offset };\n}\n\nexport function serializeString(string: string) {\n const encoded = textEncoder.encode(string);\n const { length } = encoded;\n if (length > 4095) {\n throw new Error(\"String exceeds maximum length of 4095 bytes\");\n }\n\n const bytes = new ResizableUint8Array();\n bytes.push([\n (SerializedItem.String << 4) | ((length >> 8) & 0x0f),\n length & 0xff,\n ]);\n bytes.push(encoded);\n return bytes.getBuffer();\n}\n\nexport function deserializeString(bytes: Uint8Array) {\n if (bytes.length < 2) throw new Error(\"Buffer is too short\");\n const [codeByte, lengthByte] = bytes;\n const code: SerializedItem = codeByte >> 4;\n if (code !== SerializedItem.String) {\n throw new Error(\n \"Trying to deserialize bytes (sting) with invalid serialized item code.\",\n );\n }\n const length = ((codeByte & 0x0f) << 8) | lengthByte;\n if (bytes.length < length + 2) {\n throw new Error(\"Malformed string: buffer too short\");\n }\n const stringBytes = bytes.subarray(2, length + 2);\n const string = textDecoder.decode(stringBytes);\n return { string, byteLength: length + 2 };\n}\n\nexport class ResizableUint8Array {\n #bytes: Uint8Array[] = [];\n #length = 0;\n\n push(bytes: Uint8Array | number | number[]) {\n this.#addBytes(bytes, \"end\");\n }\n\n unshift(bytes: Uint8Array | number | number[]) {\n this.#addBytes(bytes, \"start\");\n }\n\n #addBytes(bytes: Uint8Array | number | number[], position: \"start\" | \"end\") {\n let bytesToAdd: Uint8Array;\n if (bytes instanceof Uint8Array) {\n bytesToAdd = bytes;\n } else if (Array.isArray(bytes)) {\n bytesToAdd = new Uint8Array(bytes);\n } else {\n bytesToAdd = new Uint8Array([bytes]);\n }\n this.#length += bytesToAdd.length;\n this.#bytes[position === \"start\" ? \"unshift\" : \"push\"](bytesToAdd);\n }\n\n getBytesChunks(): readonly Uint8Array[] {\n return this.#bytes;\n }\n\n getBuffer(): Uint8Array {\n return joinChunks(this.#bytes, this.#length);\n }\n\n get length() {\n return this.#length;\n }\n}\n","import * as Serialization from \"./binary-serialization.js\";\nimport {\n PeerCommandType,\n PeerCommand,\n PeerSegmentCommand,\n PeerRequestSegmentCommand,\n PeerSegmentAnnouncementCommand,\n PeerSendSegmentCommand,\n} from \"./types.js\";\n\nconst FRAME_PART_LENGTH = 4;\nconst commandFrameStart = stringToUtf8CodesBuffer(\"cstr\", FRAME_PART_LENGTH);\nconst commandFrameEnd = stringToUtf8CodesBuffer(\"cend\", FRAME_PART_LENGTH);\nconst commandDivFrameStart = stringToUtf8CodesBuffer(\"dstr\", FRAME_PART_LENGTH);\nconst commandDivFrameEnd = stringToUtf8CodesBuffer(\"dend\", FRAME_PART_LENGTH);\nconst startFrames = [commandFrameStart, commandDivFrameStart];\nconst endFrames = [commandFrameEnd, commandDivFrameEnd];\nconst commandFramesLength = commandFrameStart.length + commandFrameEnd.length;\n\nexport function isCommandChunk(buffer: Uint8Array) {\n if (buffer.length < commandFramesLength) return false;\n const { length } = commandFrameStart;\n const bufferEndingToCompare = buffer.subarray(-length);\n return (\n startFrames.some((frame) =>\n areBuffersEqual(buffer, frame, FRAME_PART_LENGTH),\n ) &&\n endFrames.some((frame) =>\n areBuffersEqual(bufferEndingToCompare, frame, FRAME_PART_LENGTH),\n )\n );\n}\n\nfunction isFirstCommandChunk(buffer: Uint8Array) {\n if (buffer.length < commandFramesLength) return false;\n return areBuffersEqual(buffer, commandFrameStart, FRAME_PART_LENGTH);\n}\n\nfunction isLastCommandChunk(buffer: Uint8Array) {\n if (buffer.length < commandFramesLength) return false;\n return areBuffersEqual(\n buffer.subarray(-FRAME_PART_LENGTH),\n commandFrameEnd,\n FRAME_PART_LENGTH,\n );\n}\n\nclass BinaryCommandJoiningError extends Error {\n constructor(readonly type: \"incomplete-joining\" | \"no-first-chunk\") {\n super();\n }\n}\n\nexport class BinaryCommandChunksJoiner {\n readonly #chunks = new Serialization.ResizableUint8Array();\n #status: \"joining\" | \"completed\" = \"joining\";\n readonly #onComplete: (commandBuffer: Uint8Array) => void;\n\n constructor(onComplete: (commandBuffer: Uint8Array) => void) {\n this.#onComplete = onComplete;\n }\n\n addCommandChunk(chunk: Uint8Array) {\n if (this.#status === \"completed\") return;\n\n const isFirstChunk = isFirstCommandChunk(chunk);\n if (!this.#chunks.length && !isFirstChunk) {\n throw new BinaryCommandJoiningError(\"no-first-chunk\");\n }\n if (this.#chunks.length && isFirstChunk) {\n throw new BinaryCommandJoiningError(\"incomplete-joining\");\n }\n this.#chunks.push(this.#unframeCommandChunk(chunk));\n\n if (!isLastCommandChunk(chunk)) return;\n this.#status = \"completed\";\n this.#onComplete(this.#chunks.getBuffer());\n }\n\n #unframeCommandChunk(chunk: Uint8Array) {\n if (chunk.length < commandFramesLength) {\n throw new Error(\"Command chunk is too short to unframe\");\n }\n return chunk.subarray(FRAME_PART_LENGTH, chunk.length - FRAME_PART_LENGTH);\n }\n}\n\nexport class BinaryCommandCreator {\n readonly #bytes = new Serialization.ResizableUint8Array();\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments\n #resultBuffers: Uint8Array<ArrayBuffer>[] = [];\n #status: \"creating\" | \"completed\" = \"creating\";\n readonly #maxChunkLength: number;\n\n constructor(commandType: PeerCommandType, maxChunkLength: number) {\n this.#maxChunkLength = maxChunkLength;\n this.#bytes.push(commandType);\n }\n\n addInteger(name: string, value: number) {\n this.#bytes.push(name.charCodeAt(0));\n const bytes = Serialization.serializeInt(value);\n this.#bytes.push(bytes);\n }\n\n addUniqueSimilarIntArr(name: string, arr: number[]) {\n this.#bytes.push(name.charCodeAt(0));\n const bytes = Serialization.serializeUniqueSimilarIntArray(arr);\n this.#bytes.push(bytes);\n }\n\n addString(name: string, string: string) {\n this.#bytes.push(name.charCodeAt(0));\n const bytes = Serialization.serializeString(string);\n this.#bytes.push(bytes);\n }\n\n complete() {\n if (!this.#bytes.length) throw new Error(\"Buffer is empty\");\n if (this.#status === \"completed\") return;\n this.#status = \"completed\";\n\n const unframedBuffer = this.#bytes.getBuffer();\n if (unframedBuffer.length + commandFramesLength <= this.#maxChunkLength) {\n this.#resultBuffers.push(\n frameBuffer(unframedBuffer, commandFrameStart, commandFrameEnd),\n );\n return;\n }\n\n let chunksCount = Math.ceil(unframedBuffer.length / this.#maxChunkLength);\n if (\n Math.ceil(unframedBuffer.length / chunksCount) + commandFramesLength >\n this.#maxChunkLength\n ) {\n chunksCount++;\n }\n\n for (const [i, chunk] of splitBufferToEqualChunks(\n unframedBuffer,\n chunksCount,\n )) {\n if (i === 0) {\n this.#resultBuffers.push(\n frameBuffer(chunk, commandFrameStart, commandDivFrameEnd),\n );\n } else if (i === chunksCount - 1) {\n this.#resultBuffers.push(\n frameBuffer(chunk, commandDivFrameStart, commandFrameEnd),\n );\n } else {\n this.#resultBuffers.push(\n frameBuffer(chunk, commandDivFrameStart, commandDivFrameEnd),\n );\n }\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments\n getResultBuffers(): Uint8Array<ArrayBuffer>[] {\n if (this.#status === \"creating\" || !this.#resultBuffers.length) {\n throw new Error(\"Command is not complete.\");\n }\n return this.#resultBuffers;\n }\n}\n\nexport function deserializeCommand(bytes: Uint8Array): PeerCommand {\n const [commandCode] = bytes;\n const deserializedCommand: Record<string, unknown> = {\n c: commandCode,\n };\n\n let offset = 1;\n while (offset < bytes.length) {\n if (offset + 1 >= bytes.length) {\n throw new Error(\"Malformed command buffer: truncated name/type header\");\n }\n const name = String.fromCharCode(bytes[offset]);\n offset++;\n const dataType = getDataTypeFromByte(bytes[offset]);\n\n switch (dataType) {\n case Serialization.SerializedItem.Int:\n {\n const { number, byteLength } = Serialization.deserializeInt(\n bytes.subarray(offset),\n );\n deserializedCommand[name] = number;\n offset += byteLength;\n }\n break;\n case Serialization.SerializedItem.SimilarIntArray:\n {\n const { numbers, byteLength } =\n Serialization.deserializeUniqueSimilarIntArray(\n bytes.subarray(offset),\n );\n deserializedCommand[name] = numbers;\n offset += byteLength;\n }\n break;\n case Serialization.SerializedItem.String:\n {\n const { string, byteLength } = Serialization.deserializeString(\n bytes.subarray(offset),\n );\n deserializedCommand[name] = string;\n offset += byteLength;\n }\n break;\n }\n }\n return validateCommand(deserializedCommand);\n}\n\nfunction getDataTypeFromByte(byte: number): Serialization.SerializedItem {\n const typeCode: Serialization.SerializedItem = byte >> 4;\n if (\n typeCode <= Serialization.SerializedItem.Min ||\n typeCode >= Serialization.SerializedItem.Max\n ) {\n throw new Error(\"Not existing type\");\n }\n\n return typeCode;\n}\n\nfunction stringToUtf8CodesBuffer(string: string, length?: number): Uint8Array {\n if (length && string.length !== length) {\n throw new Error(\"Wrong string length\");\n }\n const buffer = new Uint8Array(length ?? string.length);\n for (let i = 0; i < string.length; i++) buffer[i] = string.charCodeAt(i);\n return buffer;\n}\n\nfunction* splitBufferToEqualChunks(\n buffer: Uint8Array,\n chunksCount: number,\n): Generator<[number, Uint8Array], void> {\n const chunkLength = Math.ceil(buffer.length / chunksCount);\n for (let i = 0; i < chunksCount; i++) {\n yield [i, buffer.subarray(i * chunkLength, (i + 1) * chunkLength)];\n }\n}\n\nfunction frameBuffer(\n buffer: Uint8Array,\n frameStart: Uint8Array,\n frameEnd: Uint8Array,\n) {\n const result = new Uint8Array(\n buffer.length + frameStart.length + frameEnd.length,\n );\n result.set(frameStart);\n result.set(buffer, frameStart.length);\n result.set(frameEnd, frameStart.length + buffer.length);\n\n return result;\n}\n\nfunction areBuffersEqual(\n buffer1: Uint8Array,\n buffer2: Uint8Array,\n length: number,\n) {\n for (let i = 0; i < length; i++) {\n if (buffer1[i] !== buffer2[i]) return false;\n }\n return true;\n}\n\nfunction validateCommand(command: Record<string, unknown>): PeerCommand {\n switch (command.c) {\n case PeerCommandType.SegmentsAnnouncement:\n return command as unknown as PeerSegmentAnnouncementCommand;\n\n case PeerCommandType.SegmentRequest:\n assertNumberFields(command, \"i\", \"r\");\n return command as unknown as PeerRequestSegmentCommand;\n\n case PeerCommandType.SegmentData:\n assertNumberFields(command, \"i\", \"r\", \"s\");\n return command as unknown as PeerSendSegmentCommand;\n\n case PeerCommandType.SegmentAbsent:\n case PeerCommandType.CancelSegmentRequest:\n case PeerCommandType.SegmentDataSendingCompleted:\n assertNumberFields(command, \"i\", \"r\");\n return command as unknown as PeerSegmentCommand;\n\n default:\n throw new Error(`Unknown peer command type: ${String(command.c)}`);\n }\n}\n\nfunction assertNumberFields(\n obj: Record<string, unknown>,\n ...fields: string[]\n): void {\n for (const field of fields) {\n if (typeof obj[field] !== \"number\") {\n throw new Error(\n `Expected number field \"${field}\", got ${typeof obj[field]}`,\n );\n }\n }\n}\n","import { BinaryCommandCreator } from \"./binary-command-creator.js\";\nimport {\n PeerSegmentCommand,\n PeerSendSegmentCommand,\n PeerSegmentAnnouncementCommand,\n PeerRequestSegmentCommand,\n PeerCommand,\n PeerCommandType,\n} from \"./types.js\";\n\nfunction serializeSegmentAnnouncementCommand(\n command: PeerSegmentAnnouncementCommand,\n maxChunkSize: number,\n) {\n const { c: commandCode, p: loadingByHttp, l: loaded } = command;\n const creator = new BinaryCommandCreator(commandCode, maxChunkSize);\n if (loaded?.length) creator.addUniqueSimilarIntArr(\"l\", loaded);\n if (loadingByHttp?.length) {\n creator.addUniqueSimilarIntArr(\"p\", loadingByHttp);\n }\n creator.complete();\n return creator.getResultBuffers();\n}\n\nfunction serializePeerSegmentCommand(\n command: PeerSegmentCommand,\n maxChunkSize: number,\n) {\n const creator = new BinaryCommandCreator(command.c, maxChunkSize);\n creator.addInteger(\"i\", command.i);\n creator.addInteger(\"r\", command.r);\n creator.complete();\n return creator.getResultBuffers();\n}\n\nfunction serializePeerSendSegmentCommand(\n command: PeerSendSegmentCommand,\n maxChunkSize: number,\n) {\n const creator = new BinaryCommandCreator(command.c, maxChunkSize);\n creator.addInteger(\"i\", command.i);\n creator.addInteger(\"s\", command.s);\n creator.addInteger(\"r\", command.r);\n creator.complete();\n return creator.getResultBuffers();\n}\n\nfunction serializePeerSegmentRequestCommand(\n command: PeerRequestSegmentCommand,\n maxChunkSize: number,\n) {\n const creator = new BinaryCommandCreator(command.c, maxChunkSize);\n creator.addInteger(\"i\", command.i);\n creator.addInteger(\"r\", command.r);\n if (command.b) creator.addInteger(\"b\", command.b);\n creator.complete();\n return creator.getResultBuffers();\n}\n\nexport function serializePeerCommand(\n command: PeerCommand,\n maxChunkSize: number,\n) {\n switch (command.c) {\n case PeerCommandType.CancelSegmentRequest:\n case PeerCommandType.SegmentAbsent:\n case PeerCommandType.SegmentDataSendingCompleted:\n return serializePeerSegmentCommand(command, maxChunkSize);\n case PeerCommandType.SegmentRequest:\n return serializePeerSegmentRequestCommand(command, maxChunkSize);\n case PeerCommandType.SegmentsAnnouncement:\n return serializeSegmentAnnouncementCommand(command, maxChunkSize);\n case PeerCommandType.SegmentData:\n return serializePeerSendSegmentCommand(command, maxChunkSize);\n }\n}\n","export * from \"./types.js\";\nexport { serializePeerCommand } from \"./commands.js\";\nexport {\n deserializeCommand,\n isCommandChunk,\n BinaryCommandChunksJoiner,\n} from \"./binary-command-creator.js\";\n","function getRTCError(event: Event, fallbackMessage = \"RTC error\"): Error {\n const errorEvent = event as { error?: unknown };\n if (errorEvent.error instanceof Error) {\n return errorEvent.error;\n }\n const msg =\n (errorEvent.error as { message?: string } | undefined)?.message ??\n fallbackMessage;\n return new Error(msg);\n}\n\nexport function getRTCErrorMessage(\n event: Event,\n fallbackMessage = \"RTC error\",\n): string {\n return getRTCError(event, fallbackMessage).message;\n}\n\nexport function isTerminalConnectionState(\n state: RTCIceConnectionState,\n): boolean {\n // \"disconnected\" is technically a transient ICE state that can recover,\n // but for live video streaming we treat it as terminal: dropping the peer\n // immediately and reconnecting via the tracker is faster than waiting for\n // a stale connection to potentially recover.\n\n return state === \"failed\" || state === \"closed\" || state === \"disconnected\";\n}\n","import { getPromiseWithResolvers } from \"../utils/utils.js\";\nimport { getRTCErrorMessage } from \"./utils.js\";\n\nconst MAX_BUFFERED_AMOUNT = 64 * 1024; // 64 KB, matching simple-peer\n\nexport class DataChannelSender {\n #currentSendContext?: { cancel: () => void };\n\n constructor(\n private readonly channel: RTCDataChannel,\n private readonly maxMessageSize: number,\n ) {}\n\n async sendData(\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments\n data: ArrayBuffer | ArrayBufferView<ArrayBuffer>,\n onChunkSent?: (chunkSize: number) => void,\n ): Promise<void> {\n if (this.#currentSendContext) {\n throw new Error(\"Already sending data\");\n }\n if (this.channel.readyState !== \"open\") {\n throw new Error(\"Data channel is not open\");\n }\n\n this.channel.bufferedAmountLowThreshold = MAX_BUFFERED_AMOUNT;\n\n const { promise, resolve, reject } = getPromiseWithResolvers();\n\n let offset = 0;\n let isSettled = false;\n\n const cleanup = (): boolean => {\n if (isSettled) return false;\n isSettled = true;\n this.#currentSendContext = undefined;\n this.channel.removeEventListener(\"bufferedamountlow\", sendChunks);\n this.channel.removeEventListener(\"closing\", onClose);\n this.channel.removeEventListener(\"close\", onClose);\n this.channel.removeEventListener(\"error\", onError);\n return true;\n };\n\n this.#currentSendContext = {\n cancel: () => {\n if (cleanup()) reject(new Error(\"Send cancelled\"));\n },\n };\n\n const onClose = () => {\n if (cleanup()) reject(new Error(\"Data channel closed\"));\n };\n\n const onError = (event: Event) => {\n if (!cleanup()) return;\n\n const message = getRTCErrorMessage(event, \"Unknown error\");\n reject(new Error(`Data channel error: ${message}`));\n };\n\n const buffer = ArrayBuffer.isView(data) ? data.buffer : data;\n const byteOffset = ArrayBuffer.isView(data) ? data.byteOffset : 0;\n\n const sendChunks = () => {\n if (isSettled) return;\n if (this.channel.readyState !== \"open\") {\n if (cleanup()) {\n reject(\n new Error(\n `Data channel not open (state: ${this.channel.readyState})`,\n ),\n );\n }\n return;\n }\n\n try {\n while (offset < data.byteLength) {\n if (this.channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {\n return;\n }\n\n const bytesToSend = Math.min(\n this.maxMessageSize,\n data.byteLength - offset,\n );\n const chunk = new Uint8Array(\n buffer,\n byteOffset + offset,\n bytesToSend,\n );\n\n this.channel.send(chunk);\n offset += bytesToSend;\n onChunkSent?.(bytesToSend);\n // The callback may have called cancel(), which settles the promise.\n if (!this.#currentSendContext) return;\n }\n } catch (error) {\n if (cleanup()) {\n reject(error instanceof Error ? error : new Error(String(error)));\n }\n return;\n }\n\n if (cleanup()) resolve();\n };\n\n this.channel.addEventListener(\"bufferedamountlow\", sendChunks);\n this.channel.addEventListener(\"closing\", onClose);\n this.channel.addEventListener(\"close\", onClose);\n this.channel.addEventListener(\"error\", onError);\n\n // Start sending\n sendChunks();\n\n return promise;\n }\n\n cancel(): void {\n this.#currentSendContext?.cancel();\n }\n}\n","import debug from \"debug\";\nimport { CoreEventMap, StreamConfig, StreamType } from \"../types.js\";\nimport * as Command from \"./commands/index.js\";\nimport { EventTarget } from \"../utils/event-target.js\";\nimport { DataChannelSender } from \"../webtorrent/data-channel-sender.js\";\n\nexport type PeerConfig = Pick<\n StreamConfig,\n | \"p2pNotReceivingBytesTimeoutMs\"\n | \"webRtcMaxMessageSize\"\n | \"p2pErrorRetries\"\n | \"validateP2PSegment\"\n> & { streamType: StreamType; infoHash: string };\n\nexport type PeerProtocolEventHandlers = {\n onCommandReceived: (command: Command.PeerCommand) => void;\n onSegmentChunkReceived: (data: Uint8Array) => void;\n onProtocolError: (error: unknown) => void;\n};\n\nconst logger = debug(\"p2pml-core:peer-protocol\");\n\nexport class PeerProtocol {\n #commandChunks?: Command.BinaryCommandChunksJoiner;\n #dataChannelSender: DataChannelSender;\n #uploadingRequestId?: number;\n readonly #onChunkDownloaded: CoreEventMap[\"onChunkDownloaded\"];\n readonly #onChunkUploaded: CoreEventMap[\"onChunkUploaded\"];\n readonly #channel: RTCDataChannel;\n readonly #peerConfig: PeerConfig;\n readonly #eventHandlers: PeerProtocolEventHandlers;\n readonly #peerId: string;\n\n constructor(\n channel: RTCDataChannel,\n peerConfig: PeerConfig,\n eventHandlers: PeerProtocolEventHandlers,\n eventTarget: EventTarget<CoreEventMap>,\n peerId: string,\n ) {\n this.#channel = channel;\n this.#peerConfig = peerConfig;\n this.#eventHandlers = eventHandlers;\n this.#peerId = peerId;\n\n this.#dataChannelSender = new DataChannelSender(\n channel,\n peerConfig.webRtcMaxMessageSize,\n );\n this.#onChunkDownloaded =\n eventTarget.getEventDispatcher(\"onChunkDownloaded\");\n this.#onChunkUploaded = eventTarget.getEventDispatcher(\"onChunkUploaded\");\n\n if (channel.binaryType !== \"arraybuffer\") {\n throw new Error(\n `Expected binaryType \"arraybuffer\", got \"${channel.binaryType}\"`,\n );\n }\n channel.addEventListener(\"message\", this.#onMessageReceived);\n }\n\n #onMessageReceived = (event: MessageEvent) => {\n try {\n // WebRTC data channel assumed to have binaryType = \"arraybuffer\"\n const data = new Uint8Array(event.data as ArrayBuffer);\n if (Command.isCommandChunk(data)) {\n this.#receivingCommandBytes(data);\n } else {\n this.#eventHandlers.onSegmentChunkReceived(data);\n this.#onChunkDownloaded(\n data.byteLength,\n \"p2p\",\n this.#peerId,\n this.#peerConfig.streamType,\n this.#peerConfig.infoHash,\n );\n }\n } catch (err) {\n logger(\"error handling data channel message: %O\", err);\n this.#eventHandlers.onProtocolError(err);\n }\n };\n\n sendCommand(command: Command.PeerCommand) {\n if (this.#channel.readyState !== \"open\") {\n throw new Error(\n `cannot send command ${command.c} (channel state: ${this.#channel.readyState})`,\n );\n }\n\n const binaryCommandBuffers = Command.serializePeerCommand(\n command,\n this.#peerConfig.webRtcMaxMessageSize,\n );\n for (const buffer of binaryCommandBuffers) {\n this.#channel.send(buffer);\n }\n }\n\n stopUploadingSegmentData() {\n this.#dataChannelSender.cancel();\n this.#uploadingRequestId = undefined;\n }\n\n getUploadingRequestId() {\n return this.#uploadingRequestId;\n }\n\n async splitSegmentDataToChunksAndUploadAsync(\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments\n data: ArrayBuffer | ArrayBufferView<ArrayBuffer>,\n requestId: number,\n ) {\n if (this.#uploadingRequestId !== undefined) {\n throw new Error(`Some segment data is already uploading.`);\n }\n\n this.#uploadingRequestId = requestId;\n\n try {\n await this.#dataChannelSender.sendData(data, (chunkSize) => {\n this.#onChunkUploaded(\n chunkSize,\n this.#peerId,\n this.#peerConfig.streamType,\n this.#peerConfig.infoHash,\n );\n });\n } finally {\n if (this.#uploadingRequestId === requestId) {\n this.#uploadingRequestId = undefined;\n }\n }\n }\n\n #receivingCommandBytes(buffer: Uint8Array) {\n this.#commandChunks ??= new Command.BinaryCommandChunksJoiner(\n (commandBuffer) => {\n this.#commandChunks = undefined;\n // Peers are expected to be the same version; a deserialization\n // failure indicates a protocol-violating or buggy peer.\n let command: Command.PeerCommand;\n try {\n command = Command.deserializeCommand(commandBuffer);\n } catch (err) {\n logger(\"error deserializing command: %O\", err);\n // This synchronously triggers Peer.destroy() -> channel.close()\n // from inside the onmessage handler, preventing further chunks from being processed.\n this.#eventHandlers.onProtocolError(err);\n return;\n }\n this.#eventHandlers.onCommandReceived(command);\n },\n );\n try {\n this.#commandChunks.addCommandChunk(buffer);\n } catch (err) {\n // Malformed chunk framing — same rationale as above.\n logger(\"error receiving command chunks: %O\", err);\n this.#commandChunks = undefined;\n // Triggers synchronous teardown inside the onmessage loop\n this.#eventHandlers.onProtocolError(err);\n }\n }\n\n destroy() {\n this.#channel.removeEventListener(\"message\", this.#onMessageReceived);\n this.#dataChannelSender.cancel();\n this.#commandChunks = undefined;\n this.#uploadingRequestId = undefined;\n }\n}\n","// Minimum time denominator in ms to prevent division by zero for instantaneous\n// downloads (e.g., from cache), maintaining a high bandwidth estimate so the\n// ABR doesn't downshift.\nconst MIN_TIME_DIFF_MS = 1;\n\nexport class BandwidthCalculator {\n private loadingsCount = 0;\n private readonly bytes: number[] = [];\n private readonly loadingOnlyTimestamps: number[] = [];\n private readonly timestamps: number[] = [];\n private noLoadingsTime = 0;\n private loadingsStoppedAt = 0;\n\n constructor(private readonly clearThresholdMs = 20000) {}\n\n addBytes(bytesLength: number, now = performance.now()) {\n this.bytes.push(bytesLength);\n this.loadingOnlyTimestamps.push(now - this.noLoadingsTime);\n this.timestamps.push(now);\n }\n\n startLoading(now = performance.now()) {\n this.clearStale();\n if (this.loadingsCount === 0 && this.loadingsStoppedAt !== 0) {\n this.noLoadingsTime += now - this.loadingsStoppedAt;\n }\n this.loadingsCount++;\n }\n\n stopLoading(now = performance.now()) {\n if (this.loadingsCount > 0) {\n this.loadingsCount--;\n if (this.loadingsCount === 0) this.loadingsStoppedAt = now;\n }\n }\n\n getBandwidthLoadingOnly(\n seconds: number,\n ignoreThresholdTimestamp = Number.NEGATIVE_INFINITY,\n ) {\n if (!this.loadingOnlyTimestamps.length) return 0;\n const milliseconds = seconds * 1000;\n const lastItemTimestamp =\n this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length - 1];\n let lastCountedTimestamp = lastItemTimestamp;\n const threshold = lastItemTimestamp - milliseconds;\n let totalBytes = 0;\n\n for (let i = this.bytes.length - 1; i >= 0; i--) {\n const timestamp = this.loadingOnlyTimestamps[i];\n if (\n timestamp < threshold ||\n this.timestamps[i] < ignoreThresholdTimestamp\n ) {\n break;\n }\n lastCountedTimestamp = timestamp;\n totalBytes += this.bytes[i];\n }\n\n const timeDiff = Math.max(\n lastItemTimestamp - lastCountedTimestamp,\n MIN_TIME_DIFF_MS,\n );\n return (totalBytes * 8000) / timeDiff;\n }\n\n getBandwidth(\n seconds: number,\n ignoreThresholdTimestamp = Number.NEGATIVE_INFINITY,\n now = performance.now(),\n ) {\n if (!this.timestamps.length) return 0;\n const milliseconds = seconds * 1000;\n const threshold = now - milliseconds;\n let lastCountedTimestamp = now;\n let totalBytes = 0;\n\n for (let i = this.bytes.length - 1; i >= 0; i--) {\n const timestamp = this.timestamps[i];\n if (timestamp < threshold || timestamp < ignoreThresholdTimestamp) break;\n lastCountedTimestamp = timestamp;\n totalBytes += this.bytes[i];\n }\n\n const timeDiff = Math.max(now - lastCountedTimestamp, MIN_TIME_DIFF_MS);\n return (totalBytes * 8000) / timeDiff;\n }\n\n clearStale() {\n if (!this.loadingOnlyTimestamps.length) return;\n const threshold =\n this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length - 1] -\n this.clearThresholdMs;\n\n let samplesToRemove = 0;\n for (const timestamp of this.loadingOnlyTimestamps) {\n if (timestamp > threshold) break;\n samplesToRemove++;\n }\n\n this.bytes.splice(0, samplesToRemove);\n this.loadingOnlyTimestamps.splice(0, samplesToRemove);\n this.timestamps.splice(0, samplesToRemove);\n }\n\n clear() {\n this.bytes.length = 0;\n this.loadingOnlyTimestamps.length = 0;\n this.timestamps.length = 0;\n this.loadingsCount = 0;\n this.noLoadingsTime = 0;\n this.loadingsStoppedAt = 0;\n }\n}\n","import debug from \"debug\";\nimport { Request, RequestControls } from \"../requests/request.js\";\nimport {\n CoreEventMap,\n PeerRequestErrorType,\n RequestError,\n PeerError,\n PeerErrorType,\n PeerWarning,\n} from \"../types.js\";\nimport { SegmentWithStream } from \"../internal-types.js\";\nimport * as Command from \"./commands/index.js\";\nimport { PeerProtocol, PeerConfig } from \"./peer-protocol.js\";\nimport { EventTarget } from \"../utils/event-target.js\";\nimport { BandwidthCalculator } from \"../bandwidth-calculator.js\";\nconst { PeerCommandType } = Command;\ntype PeerEventHandlers = {\n onSegmentRequested: (\n peer: Peer,\n segmentId: number,\n requestId: number,\n byteFrom?: number,\n ) => void;\n onSegmentsAnnouncement: () => void;\n onWarning: (warning: PeerWarning) => void;\n};\n\nexport class Peer {\n readonly #peerProtocol;\n #downloadingContext?: {\n request: Request;\n controls: RequestControls;\n isSegmentDataCommandReceived: boolean;\n requestId: number;\n };\n #loadedSegments = new Set<number>();\n #httpLoadingSegments = new Set<number>();\n #consecutiveTimeouts = 0;\n readonly #bandwidthCalculator = new BandwidthCalculator();\n #cachedDownloadBandwidth = { value: 0, timestamp: 0 };\n #logger = debug(\"p2pml-core:peer\");\n #nextRequestId = 0;\n #latestRequestedUploadRequestId?: number;\n #isDestroyed = false;\n readonly connectedAt = performance.now();\n\n readonly #closeConnection: (error?: PeerError) => void;\n readonly #eventHandlers: PeerEventHandlers;\n readonly #peerConfig: PeerConfig;\n\n get isDestroyed() {\n return this.#isDestroyed;\n }\n\n constructor(\n public readonly id: string,\n readonly channel: RTCDataChannel,\n closeConnection: (error?: PeerError) => void,\n eventHandlers: PeerEventHandlers,\n peerConfig: PeerConfig,\n readonly eventTarget: EventTarget<CoreEventMap>,\n ) {\n this.#closeConnection = closeConnection;\n this.#eventHandlers = eventHandlers;\n this.#peerConfig = peerConfig;\n\n this.#peerProtocol = new PeerProtocol(\n channel,\n peerConfig,\n {\n onSegmentChunkReceived: this.#onSegmentChunkReceived,\n onCommandReceived: (command) =>\n void this.#onCommandReceived(command).catch((error: unknown) => {\n this.#logger(\"error processing command %O: %O\", command, error);\n this.destroy(\n false,\n new PeerError(\n \"protocol-violation\",\n error instanceof Error\n ? error.message\n : \"Error processing command\",\n error,\n ),\n );\n }),\n onProtocolError: (error) => {\n this.destroy(\n false,\n new PeerError(\n \"protocol-violation\",\n error instanceof Error ? error.message : \"Protocol error\",\n error,\n ),\n );\n },\n },\n eventTarget,\n id,\n );\n }\n\n get downloadingSegment(): SegmentWithStream | undefined {\n return this.#downloadingContext?.request.segment;\n }\n\n get isUploadingSegment(): boolean {\n return this.#peerProtocol.getUploadingRequestId() !== undefined;\n }\n\n getDownloadBandwidth(): number {\n const now = performance.now();\n // Cache the array iteration math for 1000ms to preserve O(1) hot path efficiency during rapid queue segment evaluations\n if (now - this.#cachedDownloadBandwidth.timestamp > 1000) {\n // Uses a 15-second tracking window to calculate a moving average of the peer's throughput speed\n this.#cachedDownloadBandwidth.value =\n this.#bandwidthCalculator.getBandwidthLoadingOnly(15);\n this.#cachedDownloadBandwidth.timestamp = now;\n }\n return this.#cachedDownloadBandwidth.value;\n }\n\n getSegmentStatus(\n segment: SegmentWithStream,\n ): \"loaded\" | \"http-loading\" | undefined {\n const { externalId } = segment;\n if (this.#loadedSegments.has(externalId)) return \"loaded\";\n if (this.#httpLoadingSegments.has(externalId)) return \"http-loading\";\n }\n\n #onCommandReceived = async (command: Command.PeerCommand) => {\n switch (command.c) {\n case PeerCommandType.SegmentsAnnouncement:\n this.#loadedSegments = new Set(command.l);\n this.#httpLoadingSegments = new Set(command.p);\n this.#eventHandlers.onSegmentsAnnouncement();\n break;\n\n case PeerCommandType.SegmentRequest:\n this.#latestRequestedUploadRequestId = command.r;\n this.#peerProtocol.stopUploadingSegmentData();\n this.#eventHandlers.onSegmentRequested(\n this,\n command.i,\n command.r,\n command.b,\n );\n break;\n\n case PeerCommandType.SegmentData:\n {\n if (!this.#downloadingContext) break;\n if (this.#downloadingContext.isSegmentDataCommandReceived) break;\n\n const { request, controls, requestId } = this.#downloadingContext;\n if (\n request.segment.externalId !== command.i ||\n requestId !== command.r\n ) {\n break;\n }\n\n // A peer answering with a segment of no bytes at all. Accepting it\n // would store an empty segment, announce it, and pass it on: one\n // peer's defect becomes the swarm's. A peer that has nothing to\n // send says so with SegmentAbsent. Zero is only meaningful as the\n // remainder of a resumed transfer, where the bytes are already here.\n if (command.s === 0 && request.loadedBytes === 0) {\n this.#destroyOnPeerError(\n \"bytes-length-mismatch\",\n \"Peer sent a segment of zero length\",\n );\n break;\n }\n\n this.#downloadingContext.isSegmentDataCommandReceived = true;\n controls.firstBytesReceived();\n\n if (request.totalBytes === undefined) {\n request.setTotalBytes(request.loadedBytes + command.s);\n } else if (request.totalBytes - request.loadedBytes !== command.s) {\n this.#destroyOnPeerError(\n \"bytes-length-mismatch\",\n \"Peer response bytes length mismatch\",\n );\n }\n }\n break;\n\n case PeerCommandType.SegmentDataSendingCompleted: {\n const downloadingContext = this.#downloadingContext;\n\n if (!downloadingContext?.isSegmentDataCommandReceived) return;\n\n const { request, controls, requestId } = downloadingContext;\n\n const isWrongSegment =\n request.segment.externalId !== command.i || requestId !== command.r;\n\n if (isWrongSegment) {\n this.#destroyOnPeerError(\n \"protocol-violation\",\n \"Peer protocol violation\",\n );\n return;\n }\n\n const isWrongBytes = request.loadedBytes !== request.totalBytes;\n\n if (isWrongBytes) {\n this.#destroyOnPeerError(\n \"bytes-length-mismatch\",\n \"Peer response bytes length mismatch\",\n );\n return;\n }\n\n const isValid = await request.validateData(\n this.#peerConfig.validateP2PSegment,\n );\n\n if (this.#isDestroyed) return;\n if (this.#downloadingContext !== downloadingContext) return;\n\n if (!isValid) {\n this.#destroyOnPeerError(\n \"validation-failed\",\n \"P2P segment validation failed\",\n );\n return;\n }\n\n this.#consecutiveTimeouts = 0;\n controls.completeOnSuccess();\n this.#bandwidthCalculator.stopLoading();\n this.#downloadingContext = undefined;\n break;\n }\n\n case PeerCommandType.SegmentAbsent:\n this.#loadedSegments.delete(command.i);\n if (\n this.#downloadingContext?.request.segment.externalId === command.i &&\n this.#downloadingContext.requestId === command.r\n ) {\n this.#cancelSegmentDownloading(\"peer-segment-absent\");\n }\n break;\n\n case PeerCommandType.CancelSegmentRequest: {\n if (this.#latestRequestedUploadRequestId === command.r) {\n this.#latestRequestedUploadRequestId = undefined;\n }\n const uploadingRequestId = this.#peerProtocol.getUploadingRequestId();\n\n if (uploadingRequestId !== command.r) break;\n\n this.#peerProtocol.stopUploadingSegmentData();\n break;\n }\n }\n };\n\n #onSegmentChunkReceived = (chunk: Uint8Array) => {\n if (!this.#downloadingContext?.isSegmentDataCommandReceived) return;\n\n const { request, controls } = this.#downloadingContext;\n\n const isOverflow =\n request.totalBytes !== undefined &&\n request.loadedBytes + chunk.byteLength > request.totalBytes;\n\n if (isOverflow) {\n this.#destroyOnPeerError(\n \"bytes-length-mismatch\",\n \"Peer response bytes length mismatch\",\n );\n return;\n }\n\n this.#bandwidthCalculator.addBytes(chunk.byteLength);\n this.#cachedDownloadBandwidth.timestamp = 0; // invalidate cache\n controls.addLoadedChunk(chunk);\n };\n\n downloadSegment(segmentRequest: Request) {\n if (this.#isDestroyed) return;\n if (this.#downloadingContext) {\n throw new Error(\"Some segment already is downloading\");\n }\n\n const completed = segmentRequest.tryCompleteByLoadedBytes(\n { downloadSource: \"p2p\", peerId: this.id },\n {\n notReceivingBytesTimeoutMs:\n this.#peerConfig.p2pNotReceivingBytesTimeoutMs,\n onAbort: () => void 0,\n },\n this.#peerConfig.validateP2PSegment,\n \"p2p-segment-validation-failed\",\n );\n\n if (completed) return;\n\n this.#bandwidthCalculator.startLoading();\n this.#nextRequestId = (this.#nextRequestId + 1) % 1000000000;\n this.#downloadingContext = {\n request: segmentRequest,\n requestId: this.#nextRequestId,\n isSegmentDataCommandReceived: false,\n controls: segmentRequest.start(\n { downloadSource: \"p2p\", peerId: this.id },\n {\n notReceivingBytesTimeoutMs:\n this.#peerConfig.p2pNotReceivingBytesTimeoutMs,\n onAbort: (error) => {\n // Note: This callback is exclusively triggered by Engine-initiated\n // cancellations (e.g., user seeks) or timeouts. It is mutually exclusive\n // from peer-initiated failures, which are handled by #cancelSegmentDownloading.\n if (\n !this.#downloadingContext ||\n this.#downloadingContext.request !== segmentRequest\n ) {\n return;\n }\n const { request, requestId } = this.#downloadingContext;\n this.#sendCancelSegmentRequestCommand(request.segment, requestId);\n this.#bandwidthCalculator.stopLoading();\n if (error.type !== \"abort\") {\n this.#bandwidthCalculator.clear();\n this.#cachedDownloadBandwidth.timestamp = 0;\n this.#logger(`cleared bandwidth history due to ${error.type}`);\n }\n this.#downloadingContext = undefined;\n\n if (error.type === \"bytes-receiving-timeout\") {\n this.#consecutiveTimeouts++;\n }\n\n if (this.#consecutiveTimeouts >= this.#peerConfig.p2pErrorRetries) {\n this.destroy(\n false,\n new PeerError(\"timeout\", \"Too many timeout errors\"),\n );\n } else if (error.type === \"bytes-receiving-timeout\") {\n this.#eventHandlers.onWarning(\n new PeerWarning(\n \"timeout-strike\",\n `Timeout strike ${this.#consecutiveTimeouts}/${this.#peerConfig.p2pErrorRetries}`,\n ),\n );\n }\n },\n },\n ),\n };\n const command: Command.PeerRequestSegmentCommand = {\n c: PeerCommandType.SegmentRequest,\n r: this.#downloadingContext.requestId,\n i: segmentRequest.segment.externalId,\n };\n if (segmentRequest.loadedBytes) command.b = segmentRequest.loadedBytes;\n if (!this.#sendCommand(command)) {\n this.#cancelSegmentDownloading(\"peer-closed\");\n }\n }\n\n async uploadSegmentData(\n segment: SegmentWithStream,\n requestId: number,\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments\n data: ArrayBuffer | ArrayBufferView<ArrayBuffer>,\n ) {\n if (this.#isDestroyed) return;\n\n if (requestId !== this.#latestRequestedUploadRequestId) {\n this.#logger(\n `discarding obsolete upload request ${requestId} for segment ${segment.externalId}`,\n );\n return;\n }\n\n const { externalId } = segment;\n this.#logger(\n `send segment ${segment.externalId} to ${this.id} (byteLength: ${data.byteLength})`,\n );\n const command: Command.PeerSendSegmentCommand = {\n c: PeerCommandType.SegmentData,\n i: externalId,\n r: requestId,\n s: data.byteLength,\n };\n if (!this.#sendCommand(command)) return;\n try {\n await this.#peerProtocol.splitSegmentDataToChunksAndUploadAsync(\n data,\n requestId,\n );\n if (\n this.isDestroyed ||\n requestId !== this.#latestRequestedUploadRequestId\n ) {\n return;\n }\n this.#sendSegmentDataSendingCompletedCommand(segment, requestId);\n this.#logger(`segment ${externalId} has been sent to ${this.id}`);\n } catch (error) {\n this.#logger(`cancel segment uploading ${externalId}: %O`, error);\n }\n }\n\n #destroyOnPeerError(type: PeerErrorType, message: string) {\n this.#downloadingContext?.request.clearLoadedBytes();\n const error = new PeerError(type, message);\n this.#cancelSegmentDownloading(\"peer-closed\", error);\n this.destroy(false, error);\n }\n\n #cancelSegmentDownloading(type: PeerRequestErrorType, cause?: PeerError) {\n if (!this.#downloadingContext) return;\n const { request, controls } = this.#downloadingContext;\n const { segment } = request;\n this.#logger(`cancel segment request ${segment.externalId} (${type})`);\n const error = new RequestError(type, undefined, cause);\n\n // Note: failWithError DOES NOT trigger the onAbort callback above.\n // We must manually clean up the peer's downloading context and bandwidth state.\n controls.failWithError(error);\n this.#bandwidthCalculator.stopLoading();\n\n if (type !== \"peer-segment-absent\") {\n this.#bandwidthCalculator.clear();\n this.#cachedDownloadBandwidth.timestamp = 0;\n this.#logger(`cleared bandwidth history due to ${error.type}`);\n }\n\n this.#downloadingContext = undefined;\n }\n\n sendSegmentsAnnouncementCommand(\n loadedSegmentsIds: number[],\n httpLoadingSegmentsIds: number[],\n ) {\n const command: Command.PeerSegmentAnnouncementCommand = {\n c: PeerCommandType.SegmentsAnnouncement,\n p: httpLoadingSegmentsIds,\n l: loadedSegmentsIds,\n };\n void this.#sendCommand(command);\n }\n\n sendSegmentAbsentCommand(segmentExternalId: number, requestId: number) {\n void this.#sendCommand({\n c: PeerCommandType.SegmentAbsent,\n i: segmentExternalId,\n r: requestId,\n });\n }\n\n #sendCancelSegmentRequestCommand(\n segment: SegmentWithStream,\n requestId: number,\n ) {\n void this.#sendCommand({\n c: PeerCommandType.CancelSegmentRequest,\n i: segment.externalId,\n r: requestId,\n });\n }\n\n #sendSegmentDataSendingCompletedCommand(\n segment: SegmentWithStream,\n requestId: number,\n ) {\n void this.#sendCommand({\n c: PeerCommandType.SegmentDataSendingCompleted,\n r: requestId,\n i: segment.externalId,\n });\n }\n\n destroy(isConnectionClosed = false, error?: PeerError) {\n if (this.#isDestroyed) return;\n this.#isDestroyed = true;\n\n this.#cancelSegmentDownloading(\"peer-closed\", error);\n this.#peerProtocol.destroy();\n\n if (!isConnectionClosed) {\n this.#closeConnection(error);\n }\n this.#logger(`peer closed ${this.id}`);\n }\n\n #sendCommand(command: Command.PeerCommand): boolean {\n if (this.#isDestroyed) return false;\n try {\n this.#peerProtocol.sendCommand(command);\n return true;\n } catch (error) {\n this.#logger(\"error sending command %d: %O\", command.c, error);\n return false;\n }\n }\n}\n","export class EventTarget<\n EventTypesMap extends Record<\n string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (a1?: any, a2?: any, a3?: any, a4?: any, a5?: any) => unknown\n >,\n> {\n private events = new Map<\n keyof EventTypesMap,\n EventTypesMap[keyof EventTypesMap][]\n >();\n\n // We use hardcoded positional arguments (a1, a2, etc.) instead of TypeScript rest parameters\n // (...args) to avoid hidden array allocations during high-frequency event dispatching.\n // This ensures zero heap allocation for critical path events like onChunkDownloaded.\n //\n // IMPORTANT: Maximum supported arity is 5. If an event handler ever needs more than\n // 5 parameters, add additional positional arguments (a6, a7, ...) here AND in\n // getEventDispatcher below.\n public dispatchEvent<K extends keyof EventTypesMap>(\n eventName: K,\n ...args: Parameters<EventTypesMap[K]>\n ): void;\n public dispatchEvent<K extends keyof EventTypesMap>(\n eventName: K,\n a1?: unknown,\n a2?: unknown,\n a3?: unknown,\n a4?: unknown,\n a5?: unknown,\n ) {\n const listeners = this.events.get(eventName);\n if (!listeners) return;\n for (const listener of listeners) {\n try {\n listener(a1, a2, a3, a4, a5);\n } catch {\n // Swallow user-land errors to protect internal invariants\n }\n }\n }\n\n public getEventDispatcher<K extends keyof EventTypesMap>(\n eventName: K,\n ): (...args: Parameters<EventTypesMap[K]>) => void;\n public getEventDispatcher<K extends keyof EventTypesMap>(eventName: K) {\n return (\n a1?: unknown,\n a2?: unknown,\n a3?: unknown,\n a4?: unknown,\n a5?: unknown,\n ) => {\n const listeners = this.events.get(eventName);\n if (!listeners) return;\n for (const listener of listeners) {\n try {\n listener(a1, a2, a3, a4, a5);\n } catch {\n // Swallow user-land errors to protect internal invariants\n }\n }\n };\n }\n\n public addEventListener<K extends keyof EventTypesMap>(\n eventName: K,\n listener: EventTypesMap[K],\n ) {\n const listeners = this.events.get(eventName);\n if (!listeners) {\n this.events.set(eventName, [listener]);\n } else {\n // Copy-on-write: we MUST create a new array here instead of mutating (e.g. push()).\n // dispatchEvent/getEventDispatcher iterate the array directly (no snapshot copy)\n // for zero-allocation dispatch. Creating a new array ensures any in-progress\n // iteration sees a stable reference and is not affected by concurrent additions.\n this.events.set(eventName, [...listeners, listener]);\n }\n }\n\n public removeEventListener<K extends keyof EventTypesMap>(\n eventName: K,\n listener: EventTypesMap[K],\n ) {\n const listeners = this.events.get(eventName);\n if (!listeners) return;\n\n const index = listeners.indexOf(listener);\n if (index === -1) return;\n\n if (listeners.length === 1) {\n this.events.delete(eventName);\n return;\n }\n\n // Copy-on-write: manually slice and splice to avoid closure allocation\n // and maintain stable references for in-progress iterations.\n const newListeners = listeners.slice();\n newListeners.splice(index, 1);\n this.events.set(eventName, newListeners);\n }\n\n public clear(): void {\n this.events.clear();\n }\n}\n","interface LegacyBrowserWindow extends Window {\n RTCPeerConnection?: typeof RTCPeerConnection;\n webkitRTCPeerConnection?: typeof RTCPeerConnection;\n mozRTCPeerConnection?: typeof RTCPeerConnection;\n RTCSessionDescription?: typeof RTCSessionDescription;\n webkitRTCSessionDescription?: typeof RTCSessionDescription;\n mozRTCSessionDescription?: typeof RTCSessionDescription;\n}\n\n// Since this library runs exclusively in the browser window context, we target\n// the global 'window' directly. We use a fallback to an empty object for SSR/testing environments.\nconst win = (typeof window !== \"undefined\"\n ? window\n : {}) as unknown as LegacyBrowserWindow;\n\nexport const PeerConnection = (win.RTCPeerConnection ??\n win.webkitRTCPeerConnection ??\n win.mozRTCPeerConnection) as unknown as typeof RTCPeerConnection;\n\nexport const SessionDescription = (win.RTCSessionDescription ??\n win.webkitRTCSessionDescription ??\n win.mozRTCSessionDescription) as unknown as typeof RTCSessionDescription;\n\ntype LegacyRTCPeerConnection = Omit<\n RTCPeerConnection,\n | \"createOffer\"\n | \"createAnswer\"\n | \"setLocalDescription\"\n | \"setRemoteDescription\"\n> & {\n createOffer(\n successCallback: (offer: RTCSessionDescriptionInit) => void,\n failureCallback: (error: Error) => void,\n options?: RTCOfferOptions,\n ): void;\n createAnswer(\n successCallback: (answer: RTCSessionDescriptionInit) => void,\n failureCallback: (error: Error) => void,\n options?: RTCAnswerOptions,\n ): void;\n setLocalDescription(\n description: RTCSessionDescriptionInit,\n successCallback: () => void,\n failureCallback: (error: Error) => void,\n ): void;\n setRemoteDescription(\n description: RTCSessionDescriptionInit,\n successCallback: () => void,\n failureCallback: (error: Error) => void,\n ): void;\n};\n\n/**\n * Detects whether the current browser environment natively supports Promise-based WebRTC APIs\n * (specifically pc.createOffer and pc.createAnswer).\n *\n * For example:\n * - Chrome < 50: Callback-only for all WebRTC APIs.\n * - Chrome 50: Promise support for setLocalDescription/setRemoteDescription, but callback-only for createOffer/createAnswer.\n * - Chrome 51+: Promise support for all WebRTC APIs.\n *\n * Probing this statically once at startup prevents the need to repeatedly execute throw/catch blocks\n * during runtime connection negotiations, avoiding unnecessary exception-handling overhead.\n */\nconst supportsPromiseWebRTC = (() => {\n // Guard for SSR/test environments where no WebRTC APIs exist\n if (\n !win.RTCPeerConnection &&\n !win.webkitRTCPeerConnection &&\n !win.mozRTCPeerConnection\n ) {\n return false;\n }\n let pc: RTCPeerConnection | undefined;\n try {\n pc = new PeerConnection();\n const p = pc.createOffer();\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof p?.then === \"function\") {\n p.catch(() => {\n /* suppress unhandled rejection from probe */\n });\n return true;\n }\n } catch {\n // Fallback to legacy callback-based APIs\n } finally {\n try {\n pc?.close();\n } catch {\n // ignore\n }\n }\n return false;\n})();\n\n/**\n * Safe, backward-compatible wrapper for RTCPeerConnection.createOffer.\n *\n * Falls back to legacy callback-based signature on older engines (like Chrome 50 and below)\n * while leveraging native Promises on modern browsers, avoiding runtime throwing or exception latency.\n */\nexport function safeCreateOffer(\n pc: RTCPeerConnection,\n options?: RTCOfferOptions,\n): Promise<RTCSessionDescriptionInit> {\n if (supportsPromiseWebRTC) {\n return pc.createOffer(options);\n }\n return new Promise((resolve, reject) => {\n try {\n (pc as LegacyRTCPeerConnection).createOffer(resolve, reject, options);\n } catch (err: unknown) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(err);\n }\n });\n}\n\n/**\n * Safe, backward-compatible wrapper for RTCPeerConnection.createAnswer.\n *\n * Falls back to legacy callback-based signature on older engines (like Chrome 50 and below)\n * while leveraging native Promises on modern browsers, avoiding runtime throwing or exception latency.\n */\nexport function safeCreateAnswer(\n pc: RTCPeerConnection,\n options?: RTCAnswerOptions,\n): Promise<RTCSessionDescriptionInit> {\n if (supportsPromiseWebRTC) {\n return pc.createAnswer(options);\n }\n return new Promise((resolve, reject) => {\n try {\n (pc as LegacyRTCPeerConnection).createAnswer(resolve, reject, options);\n } catch (err: unknown) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(err);\n }\n });\n}\n\n/**\n * Safe, backward-compatible wrapper for RTCPeerConnection.setLocalDescription.\n *\n * Falls back to legacy callback-based signature on older engines (like Chrome < 50)\n * while leveraging native Promises on modern browsers.\n */\nexport function safeSetLocalDescription(\n pc: RTCPeerConnection,\n description: RTCSessionDescriptionInit,\n): Promise<void> {\n if (supportsPromiseWebRTC) {\n return pc.setLocalDescription(description);\n }\n return new Promise((resolve, reject) => {\n try {\n (pc as LegacyRTCPeerConnection).setLocalDescription(\n description,\n resolve,\n reject,\n );\n } catch (err: unknown) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(err);\n }\n });\n}\n\n/**\n * Safe, backward-compatible wrapper for RTCPeerConnection.setRemoteDescription.\n *\n * Falls back to legacy callback-based signature on older engines (like Chrome < 50)\n * while leveraging native Promises on modern browsers.\n */\nexport function safeSetRemoteDescription(\n pc: RTCPeerConnection,\n description: RTCSessionDescriptionInit,\n): Promise<void> {\n if (supportsPromiseWebRTC) {\n return pc.setRemoteDescription(description);\n }\n return new Promise((resolve, reject) => {\n try {\n (pc as LegacyRTCPeerConnection).setRemoteDescription(\n description,\n resolve,\n reject,\n );\n } catch (err: unknown) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(err);\n }\n });\n}\n","import { EventTarget } from \"../../utils/event-target.js\";\nimport { getPromiseWithResolvers } from \"../../utils/utils.js\";\nimport { isTerminalConnectionState } from \"../utils.js\";\nimport { WebSocketClient } from \"../websocket-client/index.js\";\nimport { TrackerError, TrackerWarning, PeerConnectError } from \"../../types.js\";\nimport { SafeAbortController } from \"../../utils/abort-controller.js\";\n\nimport {\n PeerConnection,\n SessionDescription,\n safeCreateOffer,\n safeCreateAnswer,\n safeSetLocalDescription,\n safeSetRemoteDescription,\n} from \"./webrtc-utils.js\";\n\nexport type WebTorrentClientEventMap = {\n peerConnected: (event: {\n peerId: string;\n connection: RTCPeerConnection;\n channel: RTCDataChannel;\n }) => void;\n peerConnectFailed: (event: {\n peerId: string;\n error: PeerConnectError;\n }) => void;\n warning: (warning: TrackerWarning) => void;\n error: (error: TrackerError) => void;\n};\n\nconst WEBTORRENT_DEFAULT_OFFER_TIMEOUT = 50000;\nconst WEBTORRENT_DEFAULT_CONNECTION_TIMEOUT = 15000;\nconst WEBTORRENT_DEFAULT_OFFERS_COUNT = 5;\nconst WEBTORRENT_DEFAULT_ICE_GATHERING_TIMEOUT = 5000;\n\nexport interface WebTorrentClientConfig {\n wsClient: WebSocketClient;\n infoHash: string;\n peerId: string;\n rtcConfig?: () => RTCConfiguration | undefined;\n channelConfig?: RTCDataChannelInit;\n offerTimeout?: () => number;\n offersCount?: () => number;\n iceGatheringTimeout?: () => number;\n connectionTimeout?: () => number;\n claimPeer?: (peerId: string) => boolean;\n shouldGenerateOffers?: () => boolean;\n}\n\ntype PendingOffer = {\n connection: RTCPeerConnection;\n channel: RTCDataChannel;\n timeoutId: ReturnType<typeof setTimeout>;\n};\n\ntype IncomingOffer = {\n sdp: RTCSessionDescriptionInit;\n peerId: string;\n offerId: string;\n};\n\ntype IncomingAnswer = {\n sdp: RTCSessionDescriptionInit;\n peerId: string;\n offerId: string;\n};\n\nfunction generateOfferId(): string {\n // Generate a safe 20-character alphanumeric string\n let id = \"\";\n const chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n for (let i = 0; i < 20; i++) {\n id += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n return id;\n}\n\nconst VALID_SDP_TYPES = new Set([\"offer\", \"answer\", \"pranswer\", \"rollback\"]);\n\nfunction isSessionDescriptionInit(\n value: unknown,\n): value is RTCSessionDescriptionInit {\n if (typeof value !== \"object\" || value === null) return false;\n const obj = value as Record<string, unknown>;\n return (\n typeof obj.type === \"string\" &&\n VALID_SDP_TYPES.has(obj.type) &&\n typeof obj.sdp === \"string\"\n );\n}\n\nexport class WebTorrentClient {\n static readonly #DEFAULT_ANNOUNCE_INTERVAL_SECONDS = 120;\n static readonly #MIN_ANNOUNCE_INTERVAL_SECONDS = 20;\n\n readonly #config: Required<\n Omit<WebTorrentClientConfig, \"rtcConfig\" | \"channelConfig\" | \"wsClient\">\n > & {\n rtcConfig?: () => RTCConfiguration | undefined;\n channelConfig?: RTCDataChannelInit;\n };\n\n readonly #wsClient: WebSocketClient;\n readonly #eventTarget = new EventTarget<WebTorrentClientEventMap>();\n readonly #pendingOffers = new Map<string, PendingOffer>();\n readonly #negotiatingConnections = new Set<RTCPeerConnection>();\n readonly #destroyAbortController = new SafeAbortController();\n\n #announceTimeoutId: ReturnType<typeof setTimeout> | null = null;\n #announceIntervalSeconds: number | null = null;\n #scheduleAnnounceRunId = 0;\n #activeAnnouncePromise: Promise<void> | null = null;\n #nextAnnounceEvent: \"started\" | undefined = undefined;\n #trackerId: string | null = null;\n #started = false;\n\n #isDestroyed(): boolean {\n return this.#destroyAbortController.signal.aborted;\n }\n\n #throwIfDestroyed(): void {\n if (this.#destroyAbortController.signal.aborted) {\n throw new Error(\"Client destroyed\");\n }\n }\n\n constructor(config: WebTorrentClientConfig) {\n this.#config = {\n infoHash: config.infoHash,\n peerId: config.peerId,\n rtcConfig: config.rtcConfig,\n channelConfig: config.channelConfig,\n offerTimeout:\n config.offerTimeout ?? (() => WEBTORRENT_DEFAULT_OFFER_TIMEOUT),\n offersCount:\n config.offersCount ?? (() => WEBTORRENT_DEFAULT_OFFERS_COUNT),\n iceGatheringTimeout:\n config.iceGatheringTimeout ??\n (() => WEBTORRENT_DEFAULT_ICE_GATHERING_TIMEOUT),\n connectionTimeout:\n config.connectionTimeout ??\n (() => WEBTORRENT_DEFAULT_CONNECTION_TIMEOUT),\n claimPeer: config.claimPeer ?? (() => true),\n shouldGenerateOffers: config.shouldGenerateOffers ?? (() => true),\n };\n\n this.#wsClient = config.wsClient;\n }\n\n public addEventListener<K extends keyof WebTorrentClientEventMap>(\n eventName: K,\n listener: WebTorrentClientEventMap[K],\n ): void {\n this.#eventTarget.addEventListener(eventName, listener);\n }\n\n public removeEventListener<K extends keyof WebTorrentClientEventMap>(\n eventName: K,\n listener: WebTorrentClientEventMap[K],\n ): void {\n this.#eventTarget.removeEventListener(eventName, listener);\n }\n\n public start(): void {\n if (this.#isDestroyed() || this.#started) return;\n this.#started = true;\n\n this.#wsClient.addEventListener(\"connected\", this.#onWsConnected);\n this.#wsClient.addEventListener(\"disconnected\", this.#onWsDisconnected);\n this.#wsClient.addEventListener(\"message\", this.#onWsMessage);\n\n if (this.#wsClient.state === \"connected\") {\n this.#onWsConnected();\n }\n }\n\n public destroy(): void {\n if (this.#isDestroyed()) return;\n this.#destroyAbortController.abort();\n this.#clearAnnounceTimeout();\n\n this.#sendStopped();\n\n this.#cleanupPendingOffers();\n this.#cleanupNegotiatingConnections();\n\n if (this.#started) {\n this.#wsClient.removeEventListener(\"connected\", this.#onWsConnected);\n this.#wsClient.removeEventListener(\n \"disconnected\",\n this.#onWsDisconnected,\n );\n this.#wsClient.removeEventListener(\"message\", this.#onWsMessage);\n }\n\n this.#eventTarget.clear();\n }\n\n #onWsConnected = (): void => {\n // Setup a fallback interval in case the tracker doesn't provide one\n this.#scheduleAnnounce(WebTorrentClient.#DEFAULT_ANNOUNCE_INTERVAL_SECONDS);\n\n // Send the initial announce event\n this.#announce(\"started\").catch((err: unknown) => {\n if (this.#isDestroyed()) return;\n\n this.#eventTarget.dispatchEvent(\n \"error\",\n new TrackerError(\n \"announce-failed\",\n `Initial announce failed: ${err instanceof Error ? err.message : String(err)}`,\n err,\n ),\n );\n });\n };\n\n #onWsDisconnected = (): void => {\n this.#clearAnnounceTimeout();\n this.#announceIntervalSeconds = null;\n };\n\n #onWsMessage = (data: ArrayBuffer | string): void => {\n if (this.#isDestroyed()) return;\n\n let msg: unknown;\n\n try {\n const text =\n typeof data === \"string\" ? data : new TextDecoder().decode(data);\n msg = JSON.parse(text) as unknown;\n } catch (err: unknown) {\n this.#eventTarget.dispatchEvent(\n \"error\",\n new TrackerError(\n \"parse-error\",\n `Failed to parse tracker message: ${err instanceof Error ? err.message : String(err)}`,\n err,\n ),\n );\n return;\n }\n\n if (typeof msg !== \"object\" || msg === null || Array.isArray(msg)) return;\n const dataObject = msg as Record<string, unknown>;\n\n // Ignore messages for a different torrent (possible on shared WebSocket connections)\n const infoHash = dataObject.info_hash;\n if (typeof infoHash === \"string\" && infoHash !== this.#config.infoHash) {\n return;\n }\n\n const warningMessage = dataObject[\"warning message\"];\n if (typeof warningMessage === \"string\") {\n this.#eventTarget.dispatchEvent(\n \"warning\",\n new TrackerWarning(\"tracker-response\", warningMessage),\n );\n }\n\n const failureReason = dataObject[\"failure reason\"];\n if (typeof failureReason === \"string\") {\n this.#eventTarget.dispatchEvent(\n \"error\",\n new TrackerError(\"tracker-response\", failureReason),\n );\n return;\n }\n\n const { interval } = dataObject;\n if (typeof interval === \"number\" && interval > 0) {\n // Defend against trackers asking for extremely frequent announces\n const safeInterval = Math.max(\n WebTorrentClient.#MIN_ANNOUNCE_INTERVAL_SECONDS,\n interval,\n );\n if (this.#announceIntervalSeconds !== safeInterval) {\n this.#scheduleAnnounce(safeInterval);\n }\n }\n\n // The WebTorrent tracker protocol specifies \"tracker id\" (with a space) in the\n // response, but expects it to be echoed back as \"trackerid\" (no space) in\n // subsequent announce requests. We store it here and send it back later.\n const trackerId = dataObject[\"tracker id\"];\n if (typeof trackerId === \"string\") {\n this.#trackerId = trackerId;\n }\n\n // Ignore offers/answers from ourselves\n const peerId = dataObject.peer_id;\n if (typeof peerId === \"string\" && peerId === this.#config.peerId) {\n return;\n }\n\n // Both offer and answer messages require peer_id and offer_id\n const offerId = dataObject.offer_id;\n if (typeof peerId !== \"string\" || typeof offerId !== \"string\") return;\n\n if (isSessionDescriptionInit(dataObject.offer)) {\n this.#handleIncomingOffer({\n sdp: dataObject.offer,\n peerId,\n offerId,\n }).catch((err: unknown) => {\n if (this.#isDestroyed()) return;\n this.#eventTarget.dispatchEvent(\n \"error\",\n new TrackerError(\n \"signaling-failed\",\n `Failed to handle offer: ${err instanceof Error ? err.message : String(err)}`,\n err,\n ),\n );\n });\n } else if (isSessionDescriptionInit(dataObject.answer)) {\n this.#handleIncomingAnswer({\n sdp: dataObject.answer,\n peerId,\n offerId,\n }).catch((err: unknown) => {\n if (this.#isDestroyed()) return;\n this.#eventTarget.dispatchEvent(\n \"error\",\n new TrackerError(\n \"signaling-failed\",\n `Failed to handle answer: ${err instanceof Error ? err.message : String(err)}`,\n err,\n ),\n );\n });\n }\n };\n\n #scheduleAnnounce(intervalSeconds: number): void {\n this.#clearAnnounceTimeout();\n this.#announceIntervalSeconds = intervalSeconds;\n\n const runId = ++this.#scheduleAnnounceRunId;\n\n const run = async () => {\n try {\n await this.#announce();\n } catch (err: unknown) {\n if (this.#isDestroyed()) return;\n this.#eventTarget.dispatchEvent(\n \"error\",\n new TrackerError(\n \"announce-failed\",\n `Announce failed: ${err instanceof Error ? err.message : String(err)}`,\n err,\n ),\n );\n }\n\n if (\n !this.#isDestroyed() &&\n this.#announceIntervalSeconds !== null &&\n this.#scheduleAnnounceRunId === runId\n ) {\n this.#announceTimeoutId = setTimeout(\n run,\n this.#announceIntervalSeconds * 1000,\n );\n }\n };\n\n this.#announceTimeoutId = setTimeout(run, intervalSeconds * 1000);\n }\n\n #clearAnnounceTimeout(): void {\n if (this.#announceTimeoutId !== null) {\n clearTimeout(this.#announceTimeoutId);\n this.#announceTimeoutId = null;\n }\n }\n\n async #announce(event?: \"started\"): Promise<void> {\n if (this.#isDestroyed() || this.#wsClient.state !== \"connected\") return;\n\n if (event) {\n this.#nextAnnounceEvent = event;\n }\n\n if (this.#activeAnnouncePromise) {\n return this.#activeAnnouncePromise;\n }\n\n const promise = (async () => {\n const shouldGenerateOffers = this.#config.shouldGenerateOffers();\n const offersCount = shouldGenerateOffers ? this.#config.offersCount() : 0;\n\n // Generate offers in parallel to avoid sequential ICE gathering latency.\n // Each #createOffer() internally catches its own errors and returns\n // undefined on failure, so Promise.all() will never reject here.\n // We avoid Promise.allSettled() for older browser compatibility.\n const results = await Promise.all(\n Array.from({ length: offersCount }, () => this.#createOffer()),\n );\n\n if (this.#isDestroyed()) {\n for (const result of results) {\n if (result) {\n this.#cleanupPendingOffer(result.offer_id);\n }\n }\n return;\n }\n\n const offers: {\n offer: { type: string; sdp: string };\n offer_id: string;\n }[] = [];\n\n for (const result of results) {\n if (result) {\n offers.push(result);\n }\n }\n\n const currentEvent = this.#nextAnnounceEvent;\n this.#nextAnnounceEvent = undefined;\n\n const payload = this.#buildAnnouncePayload({\n numwant: offers.length,\n offers,\n event: currentEvent,\n });\n\n if (this.#wsClient.state !== \"connected\") {\n for (const offer of offers) {\n this.#cleanupPendingOffer(offer.offer_id);\n }\n return;\n }\n\n try {\n this.#wsClient.send(JSON.stringify(payload));\n } catch (err: unknown) {\n for (const offer of offers) {\n this.#cleanupPendingOffer(offer.offer_id);\n }\n throw err;\n }\n })();\n\n this.#activeAnnouncePromise = promise;\n\n try {\n await promise;\n } finally {\n if (this.#activeAnnouncePromise === promise) {\n this.#activeAnnouncePromise = null;\n }\n }\n }\n\n async #createOffer(): Promise<\n | {\n offer: { type: string; sdp: string };\n offer_id: string;\n }\n | undefined\n > {\n if (this.#isDestroyed()) return undefined;\n\n let pc: RTCPeerConnection | undefined;\n try {\n pc = new PeerConnection(this.#config.rtcConfig?.());\n this.#negotiatingConnections.add(pc);\n\n const channel = pc.createDataChannel(\n \"webtorrent\",\n this.#config.channelConfig,\n );\n\n const offer = await safeCreateOffer(pc);\n this.#throwIfDestroyed();\n\n await safeSetLocalDescription(pc, offer);\n this.#throwIfDestroyed();\n\n await this.#waitForIceGathering(pc);\n this.#throwIfDestroyed();\n\n const sdp = pc.localDescription;\n if (!sdp?.sdp) {\n pc.close();\n return undefined;\n }\n\n const offerId = generateOfferId();\n\n this.#pendingOffers.set(offerId, {\n connection: pc,\n channel,\n timeoutId: setTimeout(() => {\n this.#cleanupPendingOffer(offerId);\n }, this.#config.offerTimeout()),\n });\n\n return {\n offer: { type: sdp.type, sdp: sdp.sdp },\n offer_id: offerId,\n };\n } catch (err: unknown) {\n pc?.close();\n if (!this.#isDestroyed()) {\n this.#eventTarget.dispatchEvent(\n \"warning\",\n new TrackerWarning(\n \"offer-failed\",\n `Failed to create offer: ${err instanceof Error ? err.message : String(err)}`,\n err,\n ),\n );\n }\n } finally {\n if (pc) {\n this.#negotiatingConnections.delete(pc);\n }\n }\n\n return undefined;\n }\n\n #sendStopped(): void {\n if (this.#wsClient.state !== \"connected\") return;\n\n const payload = this.#buildAnnouncePayload({\n numwant: 0,\n offers: [],\n event: \"stopped\",\n });\n\n try {\n this.#wsClient.send(JSON.stringify(payload));\n } catch {\n // Best-effort \"stopped\" notification\n }\n }\n\n #buildAnnouncePayload({\n numwant,\n offers,\n event,\n }: {\n numwant: number;\n offers: { offer: { type: string; sdp: string }; offer_id: string }[];\n event?: string;\n }): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n action: \"announce\",\n info_hash: this.#config.infoHash,\n peer_id: this.#config.peerId,\n numwant,\n uploaded: 0,\n downloaded: 0,\n offers,\n };\n\n if (event) {\n payload.event = event;\n }\n\n if (this.#trackerId) {\n payload.trackerid = this.#trackerId;\n }\n\n return payload;\n }\n\n async #handleIncomingOffer({\n sdp: offerSdp,\n peerId: remotePeerId,\n offerId: remoteOfferId,\n }: IncomingOffer): Promise<void> {\n if (this.#isDestroyed()) return;\n\n if (!this.#config.claimPeer(remotePeerId)) {\n return; // Reject offer silently\n }\n\n let pc: RTCPeerConnection | undefined;\n try {\n pc = new PeerConnection(this.#config.rtcConfig?.());\n this.#negotiatingConnections.add(pc);\n\n await safeSetRemoteDescription(pc, new SessionDescription(offerSdp));\n this.#throwIfDestroyed();\n\n const answer = await safeCreateAnswer(pc);\n this.#throwIfDestroyed();\n\n await safeSetLocalDescription(pc, answer);\n this.#throwIfDestroyed();\n\n await this.#waitForIceGathering(pc);\n this.#throwIfDestroyed();\n\n const sdp = pc.localDescription;\n if (!sdp) {\n throw new Error(\"Failed to get local description after ICE gathering\");\n }\n\n const payload = {\n action: \"announce\",\n info_hash: this.#config.infoHash,\n peer_id: this.#config.peerId,\n to_peer_id: remotePeerId,\n offer_id: remoteOfferId,\n answer: { type: sdp.type, sdp: sdp.sdp },\n };\n\n this.#wsClient.send(JSON.stringify(payload));\n\n const channel = await this.#waitForConnection(pc);\n this.#throwIfDestroyed();\n\n this.#eventTarget.dispatchEvent(\"peerConnected\", {\n peerId: remotePeerId,\n connection: pc,\n channel,\n });\n } catch (err: unknown) {\n pc?.close();\n // Always dispatch peerConnectFailed so the Manager can release the peer\n // from #connectingPeers. Safe to call after destroy: event target is\n // already cleared, making the dispatch a no-op.\n this.#eventTarget.dispatchEvent(\"peerConnectFailed\", {\n peerId: remotePeerId,\n error: new PeerConnectError(\n \"connection-failed\",\n err instanceof Error ? err.message : String(err),\n err,\n ),\n });\n } finally {\n if (pc) this.#negotiatingConnections.delete(pc);\n }\n }\n\n async #handleIncomingAnswer({\n sdp: answerSdp,\n peerId: remotePeerId,\n offerId: ourOfferId,\n }: IncomingAnswer): Promise<void> {\n if (this.#isDestroyed()) return;\n\n const pending = this.#pendingOffers.get(ourOfferId);\n if (!pending) return; // Offer expired or invalid\n\n // Stop tracking it as pending\n this.#pendingOffers.delete(ourOfferId);\n clearTimeout(pending.timeoutId);\n\n if (!this.#config.claimPeer(remotePeerId)) {\n pending.connection.close();\n return; // Reject answer silently\n }\n\n this.#negotiatingConnections.add(pending.connection);\n\n try {\n await safeSetRemoteDescription(\n pending.connection,\n new SessionDescription(answerSdp),\n );\n this.#throwIfDestroyed();\n\n const channel = await this.#waitForConnection(\n pending.connection,\n pending.channel,\n );\n this.#throwIfDestroyed();\n\n this.#eventTarget.dispatchEvent(\"peerConnected\", {\n peerId: remotePeerId,\n connection: pending.connection,\n channel,\n });\n } catch (err: unknown) {\n pending.connection.close();\n // Always dispatch peerConnectFailed so the Manager can release the peer\n // from #connectingPeers. Safe to call after destroy: event target is\n // already cleared, making the dispatch a no-op.\n this.#eventTarget.dispatchEvent(\"peerConnectFailed\", {\n peerId: remotePeerId,\n error: new PeerConnectError(\n \"connection-failed\",\n err instanceof Error ? err.message : String(err),\n err,\n ),\n });\n } finally {\n this.#negotiatingConnections.delete(pending.connection);\n }\n }\n\n #waitForIceGathering(pc: RTCPeerConnection): Promise<void> {\n return new Promise((resolve, reject) => {\n if (pc.iceGatheringState === \"complete\") {\n resolve();\n return;\n }\n if (pc.signalingState === \"closed\") {\n reject(new Error(\"RTCPeerConnection closed\"));\n return;\n }\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined = undefined;\n\n const cleanup = () => {\n clearTimeout(timeoutId);\n pc.removeEventListener(\"icegatheringstatechange\", onGatheringChange);\n pc.removeEventListener(\"icecandidate\", onIceCandidate);\n pc.removeEventListener(\"signalingstatechange\", onSignalingChange);\n this.#destroyAbortController.signal.removeEventListener(\n \"abort\",\n onAbort,\n );\n };\n\n const onGatheringChange = () => {\n if (pc.iceGatheringState === \"complete\") {\n cleanup();\n resolve();\n }\n };\n\n // A null candidate also signals gathering completion in some browsers\n // more reliably than icegatheringstatechange.\n const onIceCandidate = (event: RTCPeerConnectionIceEvent) => {\n if (event.candidate === null) {\n cleanup();\n resolve();\n }\n };\n\n const onSignalingChange = () => {\n if (pc.signalingState === \"closed\") {\n cleanup();\n reject(new Error(\"RTCPeerConnection closed\"));\n }\n };\n\n const onAbort = () => {\n cleanup();\n reject(new Error(\"ICE gathering aborted due to teardown\"));\n };\n\n if (this.#destroyAbortController.signal.aborted) {\n onAbort();\n return;\n }\n\n timeoutId = setTimeout(() => {\n cleanup();\n resolve(); // Use whatever candidates we have gathered so far\n }, this.#config.iceGatheringTimeout());\n\n pc.addEventListener(\"icegatheringstatechange\", onGatheringChange);\n pc.addEventListener(\"icecandidate\", onIceCandidate);\n pc.addEventListener(\"signalingstatechange\", onSignalingChange);\n this.#destroyAbortController.signal.addEventListener(\"abort\", onAbort);\n });\n }\n\n #waitForConnection(\n pc: RTCPeerConnection,\n channel?: RTCDataChannel,\n ): Promise<RTCDataChannel> {\n const { promise, resolve, reject } =\n getPromiseWithResolvers<RTCDataChannel>();\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined = undefined;\n let boundChannel: RTCDataChannel | undefined = channel;\n\n const rejectIfTerminalState = () => {\n if (isTerminalConnectionState(pc.iceConnectionState)) {\n cleanup();\n reject(new Error(`ICE connection ${pc.iceConnectionState}`));\n return true;\n }\n return false;\n };\n\n const onChannelOpen = () => {\n cleanup();\n if (boundChannel) {\n resolve(boundChannel);\n } else {\n reject(new Error(\"Data channel missing on open\"));\n }\n };\n\n const onChannelError = () => {\n cleanup();\n reject(new Error(\"Data channel error\"));\n };\n\n const onChannelClose = () => {\n cleanup();\n reject(new Error(\"Data channel closed prematurely\"));\n };\n\n const bindDataChannel = (dc: RTCDataChannel) => {\n boundChannel = dc;\n if (dc.readyState === \"open\") {\n onChannelOpen();\n } else if (dc.readyState === \"closed\" || dc.readyState === \"closing\") {\n onChannelClose();\n } else {\n dc.addEventListener(\"open\", onChannelOpen);\n dc.addEventListener(\"error\", onChannelError);\n dc.addEventListener(\"close\", onChannelClose);\n dc.addEventListener(\"closing\", onChannelClose);\n }\n };\n\n const onDataChannel = (event: RTCDataChannelEvent) => {\n if (!boundChannel) {\n bindDataChannel(event.channel);\n }\n };\n\n const onAbort = () => {\n cleanup();\n reject(new Error(\"Connection aborted due to teardown\"));\n };\n\n const cleanup = () => {\n clearTimeout(timeoutId);\n pc.removeEventListener(\"iceconnectionstatechange\", rejectIfTerminalState);\n pc.removeEventListener(\"datachannel\", onDataChannel);\n\n if (boundChannel) {\n boundChannel.removeEventListener(\"open\", onChannelOpen);\n boundChannel.removeEventListener(\"error\", onChannelError);\n boundChannel.removeEventListener(\"close\", onChannelClose);\n boundChannel.removeEventListener(\"closing\", onChannelClose);\n }\n this.#destroyAbortController.signal.removeEventListener(\"abort\", onAbort);\n };\n\n if (this.#destroyAbortController.signal.aborted) {\n onAbort();\n return promise;\n }\n\n if (rejectIfTerminalState()) return promise;\n\n timeoutId = setTimeout(() => {\n cleanup();\n reject(new Error(\"Data channel open timeout\"));\n }, this.#config.connectionTimeout());\n\n pc.addEventListener(\"iceconnectionstatechange\", rejectIfTerminalState);\n this.#destroyAbortController.signal.addEventListener(\"abort\", onAbort);\n\n if (boundChannel) {\n bindDataChannel(boundChannel);\n } else {\n pc.addEventListener(\"datachannel\", onDataChannel);\n }\n\n return promise;\n }\n\n #cleanupPendingOffer(offerId: string, pending?: PendingOffer): void {\n const entry = pending ?? this.#pendingOffers.get(offerId);\n if (entry) {\n clearTimeout(entry.timeoutId);\n entry.connection.close();\n this.#pendingOffers.delete(offerId);\n }\n }\n\n #cleanupPendingOffers(): void {\n for (const [offerId, pending] of this.#pendingOffers) {\n this.#cleanupPendingOffer(offerId, pending);\n }\n }\n\n #cleanupNegotiatingConnections(): void {\n for (const pc of this.#negotiatingConnections) {\n pc.close();\n }\n this.#negotiatingConnections.clear();\n }\n}\n","import {\n PeerError,\n TrackerError,\n TrackerWarning,\n PeerConnectError,\n} from \"../../types.js\";\nimport { EventTarget } from \"../../utils/event-target.js\";\nimport { getRTCErrorMessage, isTerminalConnectionState } from \"../utils.js\";\nimport { WebTorrentClient } from \"../webtorrent-client/index.js\";\nimport { WebTorrentSocketPool } from \"../webtorrent-socket-pool/index.js\";\n\nexport interface WebTorrentManagerConfig {\n infoHash: string;\n peerId: string;\n trackerUrls: string[];\n rtcConfig?: () => RTCConfiguration | undefined;\n channelConfig?: RTCDataChannelInit;\n socketPool: WebTorrentSocketPool;\n offersCount?: () => number;\n offerTimeout?: () => number;\n iceGatheringTimeout?: () => number;\n connectionTimeout?: () => number;\n maxPeers?: () => number;\n maxPeersMultiplier?: () => number;\n}\n\nexport type WebTorrentManagerEventMap = {\n peerConnected: (event: {\n peerId: string;\n connection: RTCPeerConnection;\n channel: RTCDataChannel;\n trackerUrl: string;\n close: (error?: PeerError) => void;\n }) => void;\n peerDisconnected: (\n event: {\n peerId: string;\n trackerUrl: string;\n } & (\n | { error: PeerError; disconnectReason?: never }\n | { error?: never; disconnectReason: string }\n ),\n ) => void;\n peerConnectFailed: (event: {\n peerId: string;\n trackerUrl: string;\n error: PeerConnectError;\n }) => void;\n warning: (event: { trackerUrl: string; warning: TrackerWarning }) => void;\n error: (event: { trackerUrl: string; error: TrackerError }) => void;\n};\n\ntype ConnectedPeer = {\n connection: RTCPeerConnection;\n channel: RTCDataChannel;\n trackerUrl: string;\n cleanup: () => void;\n};\n\nconst WEBTORRENT_DEFAULT_MAX_PEERS = 50;\nconst WEBTORRENT_DEFAULT_MAX_PEERS_MULTIPLIER = 1.5;\n\ntype ResolvedConfig = Required<\n Pick<WebTorrentManagerConfig, \"maxPeers\" | \"maxPeersMultiplier\">\n> &\n WebTorrentManagerConfig;\n\nexport class WebTorrentManager {\n readonly #config: ResolvedConfig;\n readonly #eventTarget = new EventTarget<WebTorrentManagerEventMap>();\n\n readonly #connectingPeers = new Set<string>();\n readonly #connectedPeers = new Map<string, ConnectedPeer>();\n\n readonly #clients = new Set<{\n client: WebTorrentClient;\n releaseSocket: () => void;\n cleanupListeners: () => void;\n }>();\n\n #destroyed = false;\n #started = false;\n\n #claimPeer = (remotePeerId: string): boolean => {\n if (this.#destroyed) return false;\n\n if (\n this.#connectingPeers.has(remotePeerId) ||\n this.#connectedPeers.has(remotePeerId)\n ) {\n return false;\n }\n\n // claimPeer is used to passively ACCEPT incoming connections.\n // We accept peers up to the hard limit (maxPeers * multiplier) to allow new\n // peers to join the swarm and be evaluated by the background peer churning process.\n const hardLimit = Math.floor(\n this.#config.maxPeers() *\n Math.max(1.0, this.#config.maxPeersMultiplier()),\n );\n if (this.#connectingPeers.size + this.#connectedPeers.size >= hardLimit) {\n return false;\n }\n\n this.#connectingPeers.add(remotePeerId);\n return true;\n };\n\n constructor(config: WebTorrentManagerConfig) {\n this.#config = {\n ...config,\n maxPeers: config.maxPeers ?? (() => WEBTORRENT_DEFAULT_MAX_PEERS),\n maxPeersMultiplier:\n config.maxPeersMultiplier ??\n (() => WEBTORRENT_DEFAULT_MAX_PEERS_MULTIPLIER),\n };\n }\n\n public addEventListener<K extends keyof WebTorrentManagerEventMap>(\n eventName: K,\n listener: WebTorrentManagerEventMap[K],\n ): void {\n this.#eventTarget.addEventListener(eventName, listener);\n }\n\n public removeEventListener<K extends keyof WebTorrentManagerEventMap>(\n eventName: K,\n listener: WebTorrentManagerEventMap[K],\n ): void {\n this.#eventTarget.removeEventListener(eventName, listener);\n }\n\n public start(): void {\n if (this.#destroyed || this.#started) return;\n this.#started = true;\n\n try {\n for (const url of this.#config.trackerUrls) {\n const { client: wsClient, release } =\n this.#config.socketPool.acquire(url);\n\n let addedToClients = false;\n try {\n const client = new WebTorrentClient({\n infoHash: this.#config.infoHash,\n peerId: this.#config.peerId,\n wsClient,\n rtcConfig: this.#config.rtcConfig,\n channelConfig: this.#config.channelConfig,\n claimPeer: this.#claimPeer,\n offersCount: this.#config.offersCount,\n offerTimeout: this.#config.offerTimeout,\n iceGatheringTimeout: this.#config.iceGatheringTimeout,\n connectionTimeout: this.#config.connectionTimeout,\n // shouldGenerateOffers is used to proactively INITIATE connections.\n // We stop actively hunting for peers once we hit the soft limit (maxPeers).\n // This prevents artificial hyper-churn where a stable swarm constantly\n // cycles connections to reach the hard limit unnecessarily.\n shouldGenerateOffers: () =>\n this.#connectingPeers.size + this.#connectedPeers.size <\n this.#config.maxPeers(),\n });\n\n const onPeerConnected = (event: {\n peerId: string;\n connection: RTCPeerConnection;\n channel: RTCDataChannel;\n }) => {\n this.#connectingPeers.delete(event.peerId);\n this.#addConnectedPeer(\n event.peerId,\n event.connection,\n event.channel,\n url,\n );\n };\n\n const onPeerConnectFailed = (event: {\n peerId: string;\n error: PeerConnectError;\n }) => {\n if (this.#connectingPeers.has(event.peerId)) {\n this.#connectingPeers.delete(event.peerId);\n this.#eventTarget.dispatchEvent(\"peerConnectFailed\", {\n peerId: event.peerId,\n trackerUrl: url,\n error: event.error,\n });\n }\n };\n\n const onWarning = (warning: TrackerWarning) => {\n this.#eventTarget.dispatchEvent(\"warning\", {\n trackerUrl: url,\n warning,\n });\n };\n\n const onError = (error: TrackerError) => {\n this.#eventTarget.dispatchEvent(\"error\", {\n trackerUrl: url,\n error,\n });\n };\n\n client.addEventListener(\"peerConnected\", onPeerConnected);\n client.addEventListener(\"peerConnectFailed\", onPeerConnectFailed);\n client.addEventListener(\"warning\", onWarning);\n client.addEventListener(\"error\", onError);\n\n const cleanupListeners = () => {\n client.removeEventListener(\"peerConnected\", onPeerConnected);\n client.removeEventListener(\n \"peerConnectFailed\",\n onPeerConnectFailed,\n );\n client.removeEventListener(\"warning\", onWarning);\n client.removeEventListener(\"error\", onError);\n };\n\n this.#clients.add({\n client,\n releaseSocket: release,\n cleanupListeners,\n });\n addedToClients = true;\n\n client.start();\n } catch (error) {\n if (!addedToClients) {\n release();\n }\n throw error;\n }\n }\n } catch (error) {\n this.destroy();\n throw error;\n }\n }\n\n public destroy(): void {\n if (this.#destroyed) return;\n this.#destroyed = true;\n\n // Remove our listeners BEFORE destroying the client. This ensures that\n // if client.destroy() synchronously dispatches events,\n // they won't reach this already-destroyed manager.\n for (const { client, releaseSocket, cleanupListeners } of this.#clients) {\n cleanupListeners();\n client.destroy();\n releaseSocket();\n }\n this.#clients.clear();\n\n this.#connectingPeers.clear();\n\n const connectedSnapshot = [...this.#connectedPeers.entries()];\n this.#connectedPeers.clear();\n\n for (const [peerId, peer] of connectedSnapshot) {\n peer.cleanup();\n try {\n peer.channel.close();\n } catch {\n // ignore\n }\n try {\n peer.connection.close();\n } catch {\n // ignore\n }\n this.#eventTarget.dispatchEvent(\"peerDisconnected\", {\n peerId,\n trackerUrl: peer.trackerUrl,\n disconnectReason: \"Manager destroyed\",\n });\n }\n\n this.#eventTarget.clear();\n }\n\n #closePeer(\n peerId: string,\n cause:\n | { error: PeerError; disconnectReason?: never }\n | { error?: never; disconnectReason: string },\n ): void {\n if (this.#destroyed) return;\n\n const connected = this.#connectedPeers.get(peerId);\n if (!connected) return;\n\n // Synchronously extract from map first to prevent re-entrant double-fire\n // if close() synchronously triggers event listeners.\n this.#connectedPeers.delete(peerId);\n\n connected.cleanup();\n try {\n connected.channel.close();\n } catch {\n // ignore\n }\n try {\n connected.connection.close();\n } catch {\n // ignore\n }\n this.#eventTarget.dispatchEvent(\"peerDisconnected\", {\n peerId,\n trackerUrl: connected.trackerUrl,\n ...cause,\n });\n }\n\n #addConnectedPeer(\n peerId: string,\n connection: RTCPeerConnection,\n channel: RTCDataChannel,\n trackerUrl: string,\n ): void {\n if (isTerminalConnectionState(connection.iceConnectionState)) {\n try {\n connection.close();\n } catch {\n // ignore\n }\n this.#eventTarget.dispatchEvent(\"peerConnectFailed\", {\n peerId,\n trackerUrl,\n error: new PeerConnectError(\n \"connection-failed\",\n \"Connection failed during promotion\",\n ),\n });\n return;\n }\n\n const onDisconnect = (\n cause:\n | { error: PeerError; disconnectReason?: never }\n | { error?: never; disconnectReason: string },\n ) => this.#closePeer(peerId, cause);\n\n const onIceConnectionStateChange = () => {\n if (isTerminalConnectionState(connection.iceConnectionState)) {\n onDisconnect({\n error: new PeerError(\n \"connection-lost\",\n `ICE connection state became ${connection.iceConnectionState}`,\n ),\n });\n }\n };\n\n const onChannelClose = () =>\n onDisconnect({ disconnectReason: \"Data channel closed\" });\n const onChannelClosing = () =>\n onDisconnect({ disconnectReason: \"Data channel closing\" });\n const onChannelError = (event: Event) => {\n const msg = getRTCErrorMessage(event, \"Data channel error\");\n onDisconnect({\n error: new PeerError(\"transport-error\", `Data channel error: ${msg}`),\n });\n };\n\n // Indirection so that cleanup() can null out the reference. Without this,\n // the close() closure exposed in the peerConnected event would capture\n // `this` permanently, preventing GC of the manager after destruction.\n let closeRef: ((error?: PeerError) => void) | null = (error) =>\n this.#closePeer(\n peerId,\n error ? { error } : { disconnectReason: \"Closed by consumer\" },\n );\n\n const cleanup = () => {\n closeRef = null;\n connection.removeEventListener(\n \"iceconnectionstatechange\",\n onIceConnectionStateChange,\n );\n channel.removeEventListener(\"close\", onChannelClose);\n channel.removeEventListener(\"closing\", onChannelClosing);\n channel.removeEventListener(\"error\", onChannelError);\n };\n\n this.#connectedPeers.set(peerId, {\n connection,\n channel,\n trackerUrl,\n cleanup,\n });\n\n connection.addEventListener(\n \"iceconnectionstatechange\",\n onIceConnectionStateChange,\n );\n channel.addEventListener(\"close\", onChannelClose);\n channel.addEventListener(\"closing\", onChannelClosing);\n channel.addEventListener(\"error\", onChannelError);\n\n this.#eventTarget.dispatchEvent(\"peerConnected\", {\n peerId,\n connection,\n channel,\n trackerUrl,\n close: (error?: PeerError) => closeRef?.(error),\n });\n }\n}\n","import { StreamConfig } from \"../types.js\";\nimport {\n Playback,\n SegmentWithStream,\n StreamWithSegments,\n} from \"../internal-types.js\";\nimport { P2PLoader } from \"../p2p/loader.js\";\n\nexport type SegmentPlaybackStatuses = {\n isHighDemand: boolean;\n isHttpDownloadable: boolean;\n isP2PDownloadable: boolean;\n};\n\nexport type PlaybackTimeWindowsConfig = Pick<\n StreamConfig,\n \"highDemandTimeWindow\" | \"httpDownloadTimeWindow\" | \"p2pDownloadTimeWindow\"\n>;\n\nexport function getSegmentFromStreamsMap(\n streams: Map<string, StreamWithSegments>,\n segmentRuntimeId: string,\n): SegmentWithStream | undefined {\n for (const stream of streams.values()) {\n const segment = stream.segments.get(segmentRuntimeId);\n if (segment) return segment;\n }\n}\n\nexport function getSegmentFromStreamByExternalId(\n stream: StreamWithSegments,\n segmentExternalId: number,\n): SegmentWithStream | undefined {\n for (const segment of stream.segments.values()) {\n if (segment.externalId === segmentExternalId) return segment;\n }\n}\n\nfunction calculateTimeWindows(\n timeWindowsConfig: PlaybackTimeWindowsConfig,\n availableMemoryInPercent: number,\n) {\n const {\n highDemandTimeWindow,\n httpDownloadTimeWindow,\n p2pDownloadTimeWindow,\n } = timeWindowsConfig;\n\n const result = {\n highDemandTimeWindow,\n httpDownloadTimeWindow,\n p2pDownloadTimeWindow,\n };\n\n if (availableMemoryInPercent <= 5) {\n result.httpDownloadTimeWindow = 0;\n result.p2pDownloadTimeWindow = 0;\n } else if (availableMemoryInPercent <= 10) {\n result.p2pDownloadTimeWindow = result.httpDownloadTimeWindow;\n }\n\n return result;\n}\n\nexport function getSegmentPlaybackStatuses(\n segment: SegmentWithStream,\n playback: Playback,\n timeWindowsConfig: PlaybackTimeWindowsConfig,\n currentP2PLoader: P2PLoader,\n availableMemoryPercent: number,\n): SegmentPlaybackStatuses {\n const {\n highDemandTimeWindow,\n httpDownloadTimeWindow,\n p2pDownloadTimeWindow,\n } = calculateTimeWindows(timeWindowsConfig, availableMemoryPercent);\n\n return {\n isHighDemand: isSegmentInTimeWindow(\n segment,\n playback,\n highDemandTimeWindow,\n ),\n isHttpDownloadable: isSegmentInTimeWindow(\n segment,\n playback,\n httpDownloadTimeWindow,\n ),\n isP2PDownloadable:\n isSegmentInTimeWindow(segment, playback, p2pDownloadTimeWindow) &&\n currentP2PLoader.isSegmentLoadingOrLoadedBySomeone(segment),\n };\n}\n\n/**\n * Seconds from the playhead to a segment's edges, positive ahead.\n *\n * The buffer edge sits exactly `bufferAhead` in front of the playhead, so\n * subtracting it converts manifest time into distance from the playhead. Both\n * terms are differences — a manifest-space delta and a player-space duration —\n * so the offset between the two timelines cancels and never has to be known.\n */\nexport function getDistanceFromPlayhead(\n segment: Pick<SegmentWithStream, \"startTime\" | \"endTime\">,\n playback: Pick<Playback, \"bufferEdge\" | \"bufferAhead\">,\n): { start: number; end: number } {\n const { bufferEdge, bufferAhead } = playback;\n return {\n start: segment.startTime - bufferEdge + bufferAhead,\n end: segment.endTime - bufferEdge + bufferAhead,\n };\n}\n\nexport function isSegmentInTimeWindow(\n segment: Pick<SegmentWithStream, \"startTime\" | \"endTime\">,\n playback: Pick<Playback, \"bufferEdge\" | \"bufferAhead\" | \"rate\">,\n timeWindowLength: number,\n): boolean {\n const { start, end } = getDistanceFromPlayhead(segment, playback);\n const rightMargin = timeWindowLength * playback.rate;\n return !(rightMargin < start || 0 > end);\n}\n","import { Peer } from \"./peer.js\";\nimport { CoreEventMap, PeerError, StreamConfig } from \"../types.js\";\nimport { SegmentWithStream, StreamWithSegments } from \"../internal-types.js\";\nimport { RequestsContainer } from \"../requests/request-container.js\";\nimport { WebTorrentManager } from \"../webtorrent/webtorrent-manager/index.js\";\nimport { WebTorrentSocketPool } from \"../webtorrent/webtorrent-socket-pool/index.js\";\nimport * as StreamUtils from \"../utils/stream.js\";\nimport * as Utils from \"../utils/utils.js\";\nimport { EventTarget } from \"../utils/event-target.js\";\nimport { SegmentStorage } from \"../segment-storage/index.js\";\nimport debug from \"debug\";\n\nexport type EventTargetMap = Record<`onStorageUpdated-${string}`, () => void> &\n CoreEventMap;\n\nconst MIN_CHURN_CLEANUP_INTERVAL_MS = 1000;\n\nexport class P2PLoader {\n readonly #webtorrentManager: WebTorrentManager;\n readonly #peersMap = new Map<string, Peer>();\n #isAnnounceMicrotaskCreated = false;\n readonly #webtorrentManagerLogger = debug(\"p2pml-core:webtorrent-manager\");\n readonly #churnLogger = debug(\"p2pml-core:churn-cleanup\");\n\n readonly #stream: StreamWithSegments;\n readonly #requests: RequestsContainer;\n readonly #segmentStorage: SegmentStorage;\n readonly #config: StreamConfig;\n readonly #webTorrentSocketPool: WebTorrentSocketPool;\n readonly #eventTarget: EventTarget<EventTargetMap>;\n readonly #onSegmentAnnouncement: () => void;\n #churnCleanupTimeoutId?: ReturnType<typeof setTimeout>;\n\n readonly #onPeerConnect: CoreEventMap[\"onPeerConnect\"];\n readonly #onPeerConnectError: CoreEventMap[\"onPeerConnectError\"];\n readonly #onPeerClose: CoreEventMap[\"onPeerClose\"];\n readonly #onPeerError: CoreEventMap[\"onPeerError\"];\n readonly #onPeerWarning: CoreEventMap[\"onPeerWarning\"];\n readonly #onTrackerWarning: CoreEventMap[\"onTrackerWarning\"];\n readonly #onTrackerError: CoreEventMap[\"onTrackerError\"];\n\n constructor(\n stream: StreamWithSegments,\n requests: RequestsContainer,\n segmentStorage: SegmentStorage,\n config: StreamConfig,\n webTorrentSocketPool: WebTorrentSocketPool,\n eventTarget: EventTarget<EventTargetMap>,\n peerId: string,\n onSegmentAnnouncement: () => void,\n ) {\n this.#stream = stream;\n this.#requests = requests;\n this.#segmentStorage = segmentStorage;\n this.#config = config;\n this.#webTorrentSocketPool = webTorrentSocketPool;\n this.#eventTarget = eventTarget;\n this.#onSegmentAnnouncement = onSegmentAnnouncement;\n\n this.#onPeerConnect = eventTarget.getEventDispatcher(\"onPeerConnect\");\n this.#onPeerConnectError =\n eventTarget.getEventDispatcher(\"onPeerConnectError\");\n this.#onPeerClose = eventTarget.getEventDispatcher(\"onPeerClose\");\n this.#onPeerError = eventTarget.getEventDispatcher(\"onPeerError\");\n this.#onPeerWarning = eventTarget.getEventDispatcher(\"onPeerWarning\");\n this.#onTrackerWarning = eventTarget.getEventDispatcher(\"onTrackerWarning\");\n this.#onTrackerError = eventTarget.getEventDispatcher(\"onTrackerError\");\n\n this.#webtorrentManager = new WebTorrentManager({\n infoHash: this.#stream.infoHash,\n peerId,\n trackerUrls: this.#config.announceTrackers,\n rtcConfig: () => this.#config.rtcConfig,\n socketPool: this.#webTorrentSocketPool,\n maxPeers: () => this.#config.p2pMaxPeers,\n maxPeersMultiplier: () => this.#config.p2pChurnMaxPeersMultiplier,\n offersCount: () => this.#config.webRtcOffersCount,\n offerTimeout: () => this.#config.webRtcOfferTimeoutMs,\n iceGatheringTimeout: () => this.#config.webRtcIceGatheringTimeoutMs,\n connectionTimeout: () => this.#config.webRtcConnectionTimeoutMs,\n });\n\n this.#webtorrentManager.addEventListener(\n \"peerConnected\",\n this.#onPeerConnectedWebTorrent,\n );\n\n this.#webtorrentManager.addEventListener(\n \"peerDisconnected\",\n this.#onPeerDisconnectedWebTorrent,\n );\n\n this.#webtorrentManager.addEventListener(\"peerConnectFailed\", (event) => {\n this.#webtorrentManagerLogger(\n `Peer connection failed (${event.peerId}) from tracker ${event.trackerUrl}:`,\n event.error,\n );\n this.#onPeerConnectError({\n peerId: event.peerId,\n infoHash: this.#stream.infoHash,\n streamType: this.#stream.type,\n trackerUrl: event.trackerUrl,\n error: event.error,\n });\n });\n\n this.#webtorrentManager.addEventListener(\"warning\", (event) => {\n this.#webtorrentManagerLogger(\n `Tracker warning (${event.trackerUrl}):`,\n event.warning,\n );\n this.#onTrackerWarning({\n trackerUrl: event.trackerUrl,\n infoHash: this.#stream.infoHash,\n streamType: this.#stream.type,\n warning: event.warning,\n });\n });\n\n this.#webtorrentManager.addEventListener(\"error\", (event) => {\n this.#webtorrentManagerLogger(\n `Tracker error (${event.trackerUrl}):`,\n event.error,\n );\n this.#onTrackerError({\n trackerUrl: event.trackerUrl,\n infoHash: this.#stream.infoHash,\n streamType: this.#stream.type,\n error: event.error,\n });\n });\n\n this.#eventTarget.addEventListener(\n `onStorageUpdated-${this.#stream.streamSwarmId}`,\n this.broadcastAnnouncement,\n );\n\n this.#webtorrentManager.start();\n\n this.#churnCleanupTimeoutId = setTimeout(\n this.#churnCleanup,\n Math.max(\n MIN_CHURN_CLEANUP_INTERVAL_MS,\n this.#config.p2pChurnCleanupIntervalMs,\n ),\n );\n }\n\n #churnCleanup = () => {\n // Schedule the next run dynamically based on the current config value, enforcing a minimum safe interval\n this.#churnCleanupTimeoutId = setTimeout(\n this.#churnCleanup,\n Math.max(\n MIN_CHURN_CLEANUP_INTERVAL_MS,\n this.#config.p2pChurnCleanupIntervalMs,\n ),\n );\n\n const excessPeersCount = this.#peersMap.size - this.#config.p2pMaxPeers;\n if (excessPeersCount <= 0) return;\n\n const eligiblePeers: Peer[] = [];\n const now = performance.now();\n\n for (const peer of this.#peersMap.values()) {\n // Don't drop peers that are actively downloading or uploading to avoid interrupting streams\n if (peer.downloadingSegment || peer.isUploadingSegment) continue;\n\n // Give new peers a grace period to establish connections and prove their bandwidth\n if (now - peer.connectedAt < this.#config.p2pChurnGracePeriodMs) {\n continue;\n }\n\n eligiblePeers.push(peer);\n }\n\n if (eligiblePeers.length === 0) return;\n\n eligiblePeers.sort((a, b) => {\n return (\n a.getDownloadBandwidth() - b.getDownloadBandwidth() ||\n a.connectedAt - b.connectedAt\n );\n });\n\n const peersToDrop = eligiblePeers.slice(0, excessPeersCount);\n\n this.#churnLogger(\n `Background churn cleanup: dropping ${peersToDrop.length} excess peers ` +\n `(total: ${this.#peersMap.size}, target: ${this.#config.p2pMaxPeers}, eligible: ${eligiblePeers.length})`,\n );\n\n for (const peer of peersToDrop) {\n this.#churnLogger(\n `dropping excess peer ${peer.id} with bandwidth ${peer.getDownloadBandwidth()}`,\n );\n peer.destroy();\n }\n };\n\n downloadSegment(segment: SegmentWithStream) {\n const peersWithSegment: Peer[] = [];\n for (const peer of this.#peersMap.values()) {\n if (\n !peer.downloadingSegment &&\n peer.getSegmentStatus(segment) === \"loaded\"\n ) {\n peersWithSegment.push(peer);\n }\n }\n\n if (peersWithSegment.length === 0) return;\n\n const selectedPeer = selectPeerForDownload(peersWithSegment);\n\n const request = this.#requests.getOrCreateRequest(segment);\n selectedPeer.downloadSegment(request);\n }\n\n isSegmentLoadingOrLoadedBySomeone(segment: SegmentWithStream): boolean {\n for (const peer of this.#peersMap.values()) {\n if (peer.getSegmentStatus(segment)) return true;\n }\n return false;\n }\n\n isSegmentLoadedBySomeone(segment: SegmentWithStream): boolean {\n for (const peer of this.#peersMap.values()) {\n if (peer.getSegmentStatus(segment) === \"loaded\") return true;\n }\n return false;\n }\n\n get connectedPeerIds(): IterableIterator<string> {\n return this.#peersMap.keys();\n }\n\n get connectedPeerCount() {\n return this.#peersMap.size;\n }\n\n *peers() {\n for (const peer of this.#peersMap.values()) {\n yield peer;\n }\n }\n\n #getSegmentsAnnouncement() {\n const loaded: number[] = this.#segmentStorage.getStoredSegmentIds(\n this.#stream.swarmId,\n this.#stream.streamSwarmId,\n );\n const httpLoading: number[] = [];\n\n for (const request of this.#requests.httpRequests()) {\n const segment = this.#stream.segments.get(request.segment.runtimeId);\n if (!segment) continue;\n\n httpLoading.push(segment.externalId);\n }\n return { loaded, httpLoading };\n }\n\n #onPeerConnectedWebTorrent = (event: {\n peerId: string;\n channel: RTCDataChannel;\n trackerUrl: string;\n close: (error?: PeerError) => void;\n }) => {\n this.#webtorrentManagerLogger(`peerConnected: peerId=${event.peerId}`);\n if (this.#peersMap.has(event.peerId)) {\n event.close();\n return;\n }\n\n const peer = new Peer(\n event.peerId,\n event.channel,\n event.close,\n {\n onSegmentRequested: (peer, segmentExternalId, requestId, byteFrom) => {\n this.#onSegmentRequested(\n peer,\n segmentExternalId,\n requestId,\n byteFrom,\n ).catch((error: unknown) => {\n this.#webtorrentManagerLogger(\n `Error in onSegmentRequested ${segmentExternalId} for peer ${peer.id}:`,\n error,\n );\n });\n },\n onSegmentsAnnouncement: this.#onSegmentAnnouncement,\n onWarning: (warning) => {\n this.#onPeerWarning({\n peerId: peer.id,\n infoHash: this.#stream.infoHash,\n streamType: this.#stream.type,\n trackerUrl: event.trackerUrl,\n warning,\n });\n },\n },\n {\n p2pNotReceivingBytesTimeoutMs:\n this.#config.p2pNotReceivingBytesTimeoutMs,\n webRtcMaxMessageSize: this.#config.webRtcMaxMessageSize,\n p2pErrorRetries: this.#config.p2pErrorRetries,\n validateP2PSegment: this.#config.validateP2PSegment,\n streamType: this.#stream.type,\n infoHash: this.#stream.infoHash,\n },\n this.#eventTarget,\n );\n this.#peersMap.set(event.peerId, peer);\n\n this.#onPeerConnect({\n peerId: event.peerId,\n infoHash: this.#stream.infoHash,\n streamType: this.#stream.type,\n trackerUrl: event.trackerUrl,\n });\n\n if (this.#config.isP2PUploadDisabled) return;\n\n const { httpLoading, loaded } = this.#getSegmentsAnnouncement();\n peer.sendSegmentsAnnouncementCommand(loaded, httpLoading);\n };\n\n #onPeerDisconnectedWebTorrent = (\n event: {\n peerId: string;\n trackerUrl: string;\n } & (\n | { error: PeerError; disconnectReason?: never }\n | { error?: never; disconnectReason: string }\n ),\n ) => {\n this.#webtorrentManagerLogger(\n \"peerDisconnected: peerId=%s error=%s reason=%s\",\n event.peerId,\n event.error?.message,\n event.disconnectReason,\n );\n\n const peer = this.#peersMap.get(event.peerId);\n if (!peer) return;\n\n this.#peersMap.delete(event.peerId);\n peer.destroy(true);\n\n if (event.error) {\n this.#onPeerError({\n peerId: event.peerId,\n infoHash: this.#stream.infoHash,\n streamType: this.#stream.type,\n trackerUrl: event.trackerUrl,\n error: event.error,\n });\n }\n\n this.#onPeerClose({\n peerId: peer.id,\n infoHash: this.#stream.infoHash,\n streamType: this.#stream.type,\n trackerUrl: event.trackerUrl,\n });\n };\n\n broadcastAnnouncement = (sendEmptyAnnouncement = false) => {\n if (sendEmptyAnnouncement) {\n this.#sendSegmentsAnnouncement(sendEmptyAnnouncement);\n return;\n }\n\n if (this.#isAnnounceMicrotaskCreated || this.#config.isP2PUploadDisabled) {\n return;\n }\n\n this.#sendSegmentsAnnouncement();\n };\n\n #sendSegmentsAnnouncement = (sendEmptyAnnouncement = false) => {\n this.#isAnnounceMicrotaskCreated = true;\n\n Utils.queueMicrotask(() => {\n const { loaded = [], httpLoading = [] } = sendEmptyAnnouncement\n ? {}\n : this.#getSegmentsAnnouncement();\n\n for (const peer of this.#peersMap.values()) {\n peer.sendSegmentsAnnouncementCommand(loaded, httpLoading);\n }\n this.#isAnnounceMicrotaskCreated = false;\n });\n };\n\n #onSegmentRequested = async (\n peer: Peer,\n segmentExternalId: number,\n requestId: number,\n byteFrom?: number,\n ) => {\n const segment = StreamUtils.getSegmentFromStreamByExternalId(\n this.#stream,\n segmentExternalId,\n );\n if (!segment) return;\n if (this.#config.isP2PUploadDisabled) {\n peer.sendSegmentAbsentCommand(segmentExternalId, requestId);\n return;\n }\n\n let segmentData: ArrayBuffer | undefined;\n try {\n segmentData = await this.#segmentStorage.getSegmentData(\n this.#stream.swarmId,\n this.#stream.streamSwarmId,\n segment.externalId,\n );\n } catch (error) {\n this.#webtorrentManagerLogger(\n `Storage error for segment ${segmentExternalId} requested by peer ${peer.id}:`,\n error,\n );\n }\n\n const peerClosedWhileAwait = !this.#peersMap.has(peer.id);\n if (peerClosedWhileAwait) return;\n\n if (!segmentData || segmentData.byteLength === 0) {\n if (segmentData) {\n // Storage handed back a segment with no bytes. Core owns what it\n // stores and never lets a consumer touch it, so this can only be a\n // storage implementation that does not — most likely one whose buffer\n // was detached by a player transmuxing it. Say the segment is absent\n // rather than pass the defect on, and say so loudly: silently seeding\n // nothing looks exactly like having no peers.\n this.#webtorrentManagerLogger(\n `refusing to upload empty segment ${segmentExternalId} to peer ${peer.id}: segment storage returned no bytes`,\n );\n }\n peer.sendSegmentAbsentCommand(segmentExternalId, requestId);\n return;\n }\n await peer.uploadSegmentData(\n segment,\n requestId,\n byteFrom !== undefined\n ? new Uint8Array(segmentData).subarray(byteFrom)\n : segmentData,\n );\n };\n\n destroy() {\n clearTimeout(this.#churnCleanupTimeoutId);\n this.#churnCleanupTimeoutId = undefined;\n\n this.#eventTarget.removeEventListener(\n `onStorageUpdated-${this.#stream.streamSwarmId}`,\n this.broadcastAnnouncement,\n );\n\n // webtorrentManager.destroy() internally clears its event target and dispatches\n // synchronous \"peerDisconnected\" events for active peers. These events trigger\n // our #onPeerDisconnectedWebTorrent handler, which destroys peer wrappers and\n // removes them from #peersMap. We destroy webtorrentManager first to prevent\n // redundant WebRTC connection closing calls during the manual peer cleanup loop.\n this.#webtorrentManager.destroy();\n\n for (const peer of this.#peersMap.values()) {\n peer.destroy();\n }\n this.#peersMap.clear();\n }\n}\n\nfunction selectPeerForDownload(peersWithSegment: Peer[]): Peer {\n if (peersWithSegment.length === 1) {\n return peersWithSegment[0];\n }\n\n let maxSpeed = 0;\n for (const peer of peersWithSegment) {\n const speed = peer.getDownloadBandwidth();\n if (speed > maxSpeed) maxSpeed = speed;\n }\n\n if (maxSpeed > 0) {\n const baseSpeed = Math.max(1, maxSpeed * 0.1);\n let unprovenPeersCount = 0;\n let provenPeersWeight = 0;\n\n for (const peer of peersWithSegment) {\n if (peer.getDownloadBandwidth() <= baseSpeed) {\n unprovenPeersCount++;\n } else {\n provenPeersWeight += peer.getDownloadBandwidth();\n }\n }\n\n let adjustedBaseSpeed = baseSpeed;\n if (\n unprovenPeersCount > 0 &&\n provenPeersWeight > 0 &&\n unprovenPeersCount * baseSpeed > provenPeersWeight\n ) {\n adjustedBaseSpeed = provenPeersWeight / unprovenPeersCount;\n }\n\n return Utils.getWeightedRandomItem(peersWithSegment, (peer) =>\n Math.max(peer.getDownloadBandwidth(), adjustedBaseSpeed),\n );\n } else {\n return Utils.getRandomItem(peersWithSegment);\n }\n}\n","import { Stream } from \"../types.js\";\nimport { SegmentWithStream } from \"../internal-types.js\";\n\nexport function getStreamString(stream: Stream) {\n return `${stream.type}-${stream.identityHash}`;\n}\n\nexport function getSegmentString(segment: SegmentWithStream) {\n const { externalId } = segment;\n return `(${getStreamString(segment.stream)} | ${externalId})`;\n}\n","import { P2PLoader } from \"./loader.js\";\nimport debug from \"debug\";\nimport {\n CoreEventMap,\n Stream,\n StreamConfig,\n SegmentStorage,\n} from \"../index.js\";\nimport { StreamWithSegments } from \"../internal-types.js\";\nimport { RequestsContainer } from \"../requests/request-container.js\";\nimport * as LoggerUtils from \"../utils/logger.js\";\nimport { EventTarget } from \"../utils/event-target.js\";\nimport { WebTorrentSocketPool } from \"../webtorrent/webtorrent-socket-pool/index.js\";\n\ntype P2PLoaderContainerItem = {\n stream: Stream;\n loader: P2PLoader;\n destroyTimeoutId?: number;\n loggerInfo: string;\n};\n\nexport class P2PLoadersContainer {\n readonly #loaders = new Map<string, P2PLoaderContainerItem>();\n #currentLoaderItem: P2PLoaderContainerItem;\n readonly #logger = debug(\"p2pml-core:p2p-loaders-container\");\n readonly #requests: RequestsContainer;\n readonly #segmentStorage: SegmentStorage;\n readonly #config: StreamConfig;\n readonly #webTorrentSocketPool: WebTorrentSocketPool;\n readonly #eventTarget: EventTarget<CoreEventMap>;\n readonly #peerId: string;\n readonly #onSegmentAnnouncement: () => void;\n\n constructor(\n stream: StreamWithSegments,\n requests: RequestsContainer,\n segmentStorage: SegmentStorage,\n config: StreamConfig,\n webTorrentSocketPool: WebTorrentSocketPool,\n eventTarget: EventTarget<CoreEventMap>,\n peerId: string,\n onSegmentAnnouncement: () => void,\n ) {\n this.#requests = requests;\n this.#segmentStorage = segmentStorage;\n this.#config = config;\n this.#webTorrentSocketPool = webTorrentSocketPool;\n this.#eventTarget = eventTarget;\n this.#peerId = peerId;\n this.#onSegmentAnnouncement = onSegmentAnnouncement;\n\n this.#currentLoaderItem = this.#findOrCreateLoaderForStream(stream);\n this.#logger(\n `set current p2p loader: ${LoggerUtils.getStreamString(stream)}`,\n );\n }\n\n #createLoader(stream: StreamWithSegments): P2PLoaderContainerItem {\n if (this.#loaders.has(stream.runtimeId)) {\n throw new Error(\"Loader for this stream already exists\");\n }\n const loader = new P2PLoader(\n stream,\n this.#requests,\n this.#segmentStorage,\n this.#config,\n this.#webTorrentSocketPool,\n this.#eventTarget,\n this.#peerId,\n () => {\n if (this.#currentLoaderItem.loader === loader) {\n this.#onSegmentAnnouncement();\n }\n },\n );\n const loggerInfo = LoggerUtils.getStreamString(stream);\n this.#logger(`created new loader: ${loggerInfo}`);\n return {\n loader,\n stream,\n loggerInfo,\n };\n }\n\n #findOrCreateLoaderForStream(stream: StreamWithSegments) {\n const loaderItem = this.#loaders.get(stream.runtimeId);\n if (loaderItem) {\n clearTimeout(loaderItem.destroyTimeoutId);\n loaderItem.destroyTimeoutId = undefined;\n return loaderItem;\n } else {\n const loader = this.#createLoader(stream);\n this.#loaders.set(stream.runtimeId, loader);\n return loader;\n }\n }\n\n changeCurrentLoader(stream: StreamWithSegments) {\n const currentStream = this.#currentLoaderItem.stream;\n const ids = this.#segmentStorage.getStoredSegmentIds(\n currentStream.swarmId,\n currentStream.streamSwarmId,\n );\n if (!ids.length) this.#destroyAndRemoveLoader(this.#currentLoaderItem);\n else this.#setLoaderDestroyTimeout(this.#currentLoaderItem);\n\n this.#currentLoaderItem = this.#findOrCreateLoaderForStream(stream);\n\n this.#logger(\n `change current p2p loader: ${LoggerUtils.getStreamString(stream)}`,\n );\n }\n\n #setLoaderDestroyTimeout(item: P2PLoaderContainerItem) {\n item.destroyTimeoutId = window.setTimeout(\n () => this.#destroyAndRemoveLoader(item),\n this.#config.p2pInactiveLoaderDestroyTimeoutMs,\n );\n }\n\n #destroyAndRemoveLoader(item: P2PLoaderContainerItem) {\n item.loader.destroy();\n this.#loaders.delete(item.stream.runtimeId);\n this.#logger(`destroy p2p loader: `, item.loggerInfo);\n }\n\n get currentLoader() {\n return this.#currentLoaderItem.loader;\n }\n\n destroy() {\n for (const { loader, destroyTimeoutId } of this.#loaders.values()) {\n loader.destroy();\n clearTimeout(destroyTimeoutId);\n }\n this.#loaders.clear();\n }\n}\n","import debug from \"debug\";\nimport {\n BandwidthCalculators,\n Playback,\n SegmentWithStream,\n} from \"../internal-types.js\";\nimport {\n CoreEventMap,\n RequestError,\n RequestAbortErrorType,\n RequestErrorType,\n Segment,\n} from \"../types.js\";\nimport * as StreamUtils from \"../utils/stream.js\";\nimport * as Utils from \"../utils/utils.js\";\nimport { EventTarget } from \"../utils/event-target.js\";\n\nexport type LoadProgress = {\n startTimestamp: number;\n lastLoadedChunkTimestamp?: number;\n startFromByte?: number;\n loadedBytes: number;\n};\n\ntype HttpRequestAttempt = {\n downloadSource: \"http\";\n error?: RequestError;\n};\n\ntype P2PRequestAttempt = {\n downloadSource: \"p2p\";\n peerId: string;\n error?: RequestError;\n};\n\nexport type RequestAttempt = HttpRequestAttempt | P2PRequestAttempt;\n\nexport type RequestControls = Readonly<{\n firstBytesReceived: Request[\"firstBytesReceived\"];\n addLoadedChunk: Request[\"addLoadedChunk\"];\n completeOnSuccess: Request[\"completeOnSuccess\"];\n failWithError: Request[\"failWithError\"];\n}>;\n\ntype OmitEncapsulated<T extends RequestAttempt> = Omit<\n T,\n \"error\" | \"errorTimestamp\"\n>;\ntype StartRequestParameters =\n OmitEncapsulated<HttpRequestAttempt> | OmitEncapsulated<P2PRequestAttempt>;\n\nexport type RequestStatus =\n \"not-started\" | \"loading\" | \"succeed\" | \"failed\" | \"aborted\";\n\nfunction mapSegmentWithStreamToSegment(segment: SegmentWithStream): Segment {\n return {\n runtimeId: segment.runtimeId,\n externalId: segment.externalId,\n url: segment.url,\n byteRange: segment.byteRange && { ...segment.byteRange },\n startTime: segment.startTime,\n endTime: segment.endTime,\n };\n}\n\nexport class Request {\n private currentAttempt?: RequestAttempt;\n private _failedAttempts = new FailedRequestAttempts();\n private finalData?: ArrayBuffer;\n private bytes: Uint8Array[] = [];\n private _loadedBytes = 0;\n private _totalBytes?: number;\n private _status: RequestStatus = \"not-started\";\n private progress?: LoadProgress;\n private notReceivingBytesTimeout: Timeout;\n private _onAbortCallback?: (\n error: RequestError<RequestAbortErrorType>,\n ) => void;\n private notReceivingBytesTimeoutMs?: number;\n private readonly _logger: debug.Debugger;\n private _isHandledByProcessQueue = false;\n private readonly onSegmentError: CoreEventMap[\"onSegmentError\"];\n private readonly onSegmentAbort: CoreEventMap[\"onSegmentAbort\"];\n private readonly onSegmentStart: CoreEventMap[\"onSegmentStart\"];\n private readonly onSegmentLoaded: CoreEventMap[\"onSegmentLoaded\"];\n\n constructor(\n readonly segment: SegmentWithStream,\n private readonly requestProcessQueueCallback: () => void,\n private readonly bandwidthCalculators: BandwidthCalculators,\n private readonly playback: Playback,\n private readonly playbackConfig: StreamUtils.PlaybackTimeWindowsConfig,\n eventTarget: EventTarget<CoreEventMap>,\n readonly infoHash: string,\n ) {\n this.onSegmentError = eventTarget.getEventDispatcher(\"onSegmentError\");\n this.onSegmentAbort = eventTarget.getEventDispatcher(\"onSegmentAbort\");\n this.onSegmentStart = eventTarget.getEventDispatcher(\"onSegmentStart\");\n this.onSegmentLoaded = eventTarget.getEventDispatcher(\"onSegmentLoaded\");\n\n const { byteRange } = this.segment;\n if (byteRange) {\n const { end, start } = byteRange;\n this._totalBytes = end - start + 1;\n }\n this.notReceivingBytesTimeout = new Timeout(this.abortOnTimeout);\n\n const { type } = this.segment.stream;\n this._logger = debug(`p2pml-core:request-${type}`);\n }\n\n clearLoadedBytes() {\n this._loadedBytes = 0;\n this.bytes = [];\n this._totalBytes = undefined;\n this.finalData = undefined;\n }\n\n get status() {\n return this._status;\n }\n\n private setStatus(status: RequestStatus) {\n this._status = status;\n this._isHandledByProcessQueue = false;\n }\n\n get downloadSource() {\n return this.currentAttempt?.downloadSource;\n }\n\n get loadedBytes() {\n return this._loadedBytes;\n }\n\n get totalBytes(): number | undefined {\n return this._totalBytes;\n }\n\n get data(): ArrayBuffer {\n this.finalData ??= Utils.joinChunks(this.bytes).buffer;\n return this.finalData;\n }\n\n get failedAttempts() {\n return this._failedAttempts;\n }\n\n get isHandledByProcessQueue() {\n return this._isHandledByProcessQueue;\n }\n\n markHandledByProcessQueue() {\n this._isHandledByProcessQueue = true;\n }\n\n setTotalBytes(value: number) {\n if (this._totalBytes !== undefined) {\n throw new Error(\"Request total bytes value is already set\");\n }\n this._totalBytes = value;\n }\n\n /**\n * Checks if all bytes are already loaded and, if so, starts, validates,\n * and completes the request without making a network request.\n *\n * Handles three cases:\n * - loadedBytes === totalBytes: start → validate → complete (returns true)\n * - loadedBytes > totalBytes: corrupted state → clearLoadedBytes (returns false)\n * - otherwise: no-op (returns false)\n *\n * The request is started synchronously so that processQueue sees\n * it as \"loading\" immediately. Validation runs as fire-and-forget.\n *\n * @returns true if the request was started and is being handled,\n * false if caller should proceed with a normal download.\n */\n tryCompleteByLoadedBytes(\n requestData: StartRequestParameters,\n controls: {\n notReceivingBytesTimeoutMs?: number;\n onAbort: (errorType: RequestError<RequestAbortErrorType>) => void;\n },\n validate:\n | ((\n url: string,\n byteRange: Segment[\"byteRange\"],\n data: ArrayBuffer,\n ) => Promise<boolean>)\n | undefined,\n validationErrorType: RequestErrorType,\n ): boolean {\n if (!this._totalBytes) return false;\n\n if (this._loadedBytes > this._totalBytes) {\n this.logger(\n `${requestData.downloadSource} ${this.segment.externalId} loaded bytes overflow: ${this._loadedBytes} > ${this._totalBytes}, clearing`,\n );\n this.clearLoadedBytes();\n return false;\n }\n\n if (this._loadedBytes !== this._totalBytes) return false;\n\n // Start synchronously so the request is immediately in \"loading\" status.\n const requestControls = this.start(requestData, controls);\n\n // No network bytes will arrive in this path, so disable the timeout\n // to prevent it from aborting the request during async validation.\n this.notReceivingBytesTimeout.clear();\n\n if (validate) {\n void this.validateAndComplete(\n requestData.downloadSource,\n requestControls,\n validate,\n validationErrorType,\n );\n } else {\n requestControls.completeOnSuccess();\n }\n\n return true;\n }\n\n async validateData(\n validate?: (\n url: string,\n byteRange: Segment[\"byteRange\"],\n data: ArrayBuffer,\n ) => Promise<boolean>,\n ): Promise<boolean> {\n if (!validate) return true;\n try {\n return await validate(\n this.segment.url,\n this.segment.byteRange,\n this.data,\n );\n } catch (err) {\n this.logger(`validation threw an error: ${String(err)}`);\n return false;\n }\n }\n\n private async validateAndComplete(\n downloadSource: \"http\" | \"p2p\",\n requestControls: RequestControls,\n validate: (\n url: string,\n byteRange: Segment[\"byteRange\"],\n data: ArrayBuffer,\n ) => Promise<boolean>,\n validationErrorType: RequestErrorType,\n ) {\n const isValid = await this.validateData(validate);\n\n // Request may have been aborted by processQueue while validation ran.\n if (this._status !== \"loading\") return;\n\n if (!isValid) {\n this.logger(\n `${downloadSource} ${this.segment.externalId} validation failed for already-loaded bytes, clearing`,\n );\n this.clearLoadedBytes();\n requestControls.failWithError(new RequestError(validationErrorType));\n return;\n }\n\n this.logger(\n `${downloadSource} ${this.segment.externalId} validation passed for already-loaded bytes`,\n );\n requestControls.completeOnSuccess();\n }\n\n start(\n requestData: StartRequestParameters,\n controls: {\n notReceivingBytesTimeoutMs?: number;\n onAbort: (errorType: RequestError<RequestAbortErrorType>) => void;\n },\n ): RequestControls {\n if (this._status === \"succeed\") {\n throw new Error(\n `Request ${this.segment.externalId} has been already succeed.`,\n );\n }\n if (this._status === \"loading\") {\n throw new Error(\n `Request ${this.segment.externalId} has been already started.`,\n );\n }\n\n this.setStatus(\"loading\");\n this.currentAttempt = { ...requestData };\n this.progress = {\n startFromByte: this._loadedBytes,\n loadedBytes: 0,\n startTimestamp: performance.now(),\n };\n this.manageBandwidthCalculatorsState(\"start\");\n\n const { notReceivingBytesTimeoutMs } = controls;\n this._onAbortCallback = controls.onAbort;\n this.notReceivingBytesTimeoutMs = notReceivingBytesTimeoutMs;\n\n if (notReceivingBytesTimeoutMs !== undefined) {\n this.notReceivingBytesTimeout.start(notReceivingBytesTimeoutMs);\n }\n\n this.logger(\n `${requestData.downloadSource} ${this.segment.externalId} started`,\n );\n\n this.onSegmentStart({\n segment: mapSegmentWithStreamToSegment(this.segment),\n downloadSource: requestData.downloadSource,\n peerId:\n requestData.downloadSource === \"p2p\" ? requestData.peerId : undefined,\n infoHash: this.infoHash,\n streamType: this.segment.stream.type,\n });\n\n return {\n firstBytesReceived: this.firstBytesReceived,\n addLoadedChunk: this.addLoadedChunk,\n completeOnSuccess: this.completeOnSuccess,\n failWithError: this.failWithError,\n };\n }\n\n cancel() {\n this.throwErrorIfNotLoadingStatus();\n this.setStatus(\"aborted\");\n this.logger(\n `${this.currentAttempt?.downloadSource} ${this.segment.externalId} aborted`,\n );\n this._onAbortCallback?.(new RequestError(\"abort\"));\n this.onSegmentAbort({\n segment: mapSegmentWithStreamToSegment(this.segment),\n downloadSource: this.currentAttempt?.downloadSource,\n peerId:\n this.currentAttempt?.downloadSource === \"p2p\"\n ? this.currentAttempt.peerId\n : undefined,\n infoHash: this.infoHash,\n streamType: this.segment.stream.type,\n });\n this._onAbortCallback = undefined;\n this.manageBandwidthCalculatorsState(\"stop\");\n this.notReceivingBytesTimeout.clear();\n }\n\n private abortOnTimeout = () => {\n this.throwErrorIfNotLoadingStatus();\n if (\n !this.currentAttempt ||\n !this.progress ||\n this.notReceivingBytesTimeoutMs === undefined\n ) {\n return;\n }\n\n const now = performance.now();\n const lastActive =\n this.progress.lastLoadedChunkTimestamp ?? this.progress.startTimestamp;\n const msSinceLastActive = now - lastActive;\n\n if (msSinceLastActive < this.notReceivingBytesTimeoutMs) {\n // False alarm! The stream is still downloading. Reschedule the timer.\n this.notReceivingBytesTimeout.restart(\n this.notReceivingBytesTimeoutMs - msSinceLastActive,\n );\n return;\n }\n\n const error = new RequestError(\"bytes-receiving-timeout\");\n this._onAbortCallback?.(error);\n this.handleFailure(error);\n };\n\n private failWithError = (error: RequestError) => {\n this.throwErrorIfNotLoadingStatus();\n if (!this.currentAttempt) return;\n\n this.handleFailure(error);\n };\n\n private handleFailure = (error: RequestError) => {\n if (!this.currentAttempt) return;\n\n this.setStatus(\"failed\");\n this.logger(\n `${this.downloadSource} ${this.segment.externalId} failed ${error.type}`,\n );\n this._failedAttempts.add({\n ...this.currentAttempt,\n error,\n });\n this.onSegmentError({\n segment: mapSegmentWithStreamToSegment(this.segment),\n error,\n downloadSource: this.currentAttempt.downloadSource,\n peerId:\n this.currentAttempt.downloadSource === \"p2p\"\n ? this.currentAttempt.peerId\n : undefined,\n infoHash: this.infoHash,\n streamType: this.segment.stream.type,\n });\n this.notReceivingBytesTimeout.clear();\n this.manageBandwidthCalculatorsState(\"stop\");\n this.requestProcessQueueCallback();\n };\n\n private completeOnSuccess = () => {\n this.throwErrorIfNotLoadingStatus();\n if (!this.currentAttempt) return;\n\n this.manageBandwidthCalculatorsState(\"stop\");\n this.notReceivingBytesTimeout.clear();\n this.setStatus(\"succeed\");\n this._totalBytes = this._loadedBytes;\n this.onSegmentLoaded({\n segment: mapSegmentWithStreamToSegment(this.segment),\n bytesLength: this.data.byteLength,\n downloadSource: this.currentAttempt.downloadSource,\n peerId:\n this.currentAttempt.downloadSource === \"p2p\"\n ? this.currentAttempt.peerId\n : undefined,\n infoHash: this.infoHash,\n streamType: this.segment.stream.type,\n });\n\n this.logger(\n `${this.currentAttempt.downloadSource} ${this.segment.externalId} succeed`,\n );\n this.requestProcessQueueCallback();\n };\n\n private addLoadedChunk = (chunk: Uint8Array) => {\n this.throwErrorIfNotLoadingStatus();\n if (!this.currentAttempt || !this.progress) return;\n\n const { byteLength } = chunk;\n const { all: allBC, http: httpBC } = this.bandwidthCalculators;\n allBC.addBytes(byteLength);\n if (this.currentAttempt.downloadSource === \"http\") {\n httpBC.addBytes(byteLength);\n }\n\n this.bytes.push(chunk);\n this.progress.lastLoadedChunkTimestamp = performance.now();\n this.progress.loadedBytes += byteLength;\n this._loadedBytes += byteLength;\n };\n\n private firstBytesReceived = () => {\n this.throwErrorIfNotLoadingStatus();\n };\n\n private throwErrorIfNotLoadingStatus() {\n if (this._status !== \"loading\") {\n throw new Error(`Request has been already ${this.status}.`);\n }\n }\n\n private logger(message: string) {\n this._logger.color =\n this.currentAttempt?.downloadSource === \"http\" ? \"green\" : \"red\";\n this._logger(message);\n this._logger.color = \"\";\n }\n\n private manageBandwidthCalculatorsState(state: \"start\" | \"stop\") {\n const { all, http } = this.bandwidthCalculators;\n const method = state === \"start\" ? \"startLoading\" : \"stopLoading\";\n if (this.currentAttempt?.downloadSource === \"http\") http[method]();\n all[method]();\n }\n}\n\nclass FailedRequestAttempts {\n private attempts: Required<RequestAttempt>[] = [];\n\n add(attempt: Required<RequestAttempt>) {\n this.attempts.push(attempt);\n }\n\n get httpAttemptsCount() {\n return this.attempts.reduce(\n (sum, attempt) => (attempt.downloadSource === \"http\" ? sum + 1 : sum),\n 0,\n );\n }\n\n get p2pAttemptsCount() {\n return this.attempts.reduce(\n (sum, attempt) => (attempt.downloadSource === \"p2p\" ? sum + 1 : sum),\n 0,\n );\n }\n\n get lastAttempt(): Readonly<Required<RequestAttempt>> | undefined {\n return this.attempts[this.attempts.length - 1];\n }\n\n clear() {\n this.attempts = [];\n }\n}\n\nexport class Timeout {\n private timeoutId?: number;\n private ms?: number;\n\n constructor(private readonly action: () => void) {}\n\n start(ms: number) {\n if (this.timeoutId) {\n throw new Error(\"Timeout is already started.\");\n }\n this.ms = ms;\n this.timeoutId = window.setTimeout(this.action, this.ms);\n }\n\n restart(ms?: number) {\n this.clear();\n if (ms !== undefined) this.ms = ms;\n if (this.ms === undefined) return;\n this.timeoutId = window.setTimeout(this.action, this.ms);\n }\n\n clear() {\n clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n }\n}\n","import {\n Playback,\n BandwidthCalculators,\n SegmentWithStream,\n} from \"../internal-types.js\";\nimport { CoreEventMap, StreamConfig } from \"../types.js\";\nimport { EventTarget } from \"../utils/event-target.js\";\nimport { Request } from \"./request.js\";\n\nexport class RequestsContainer {\n private readonly requests = new Map<SegmentWithStream, Request>();\n\n constructor(\n private readonly requestProcessQueueCallback: () => void,\n private readonly bandwidthCalculators: BandwidthCalculators,\n private readonly playback: Playback,\n private readonly config: StreamConfig,\n private readonly eventTarget: EventTarget<CoreEventMap>,\n ) {}\n\n get executingHttpCount() {\n let count = 0;\n for (const request of this.httpRequests()) {\n if (request.status === \"loading\") count++;\n }\n return count;\n }\n\n get executingP2PCount() {\n let count = 0;\n for (const request of this.p2pRequests()) {\n if (request.status === \"loading\") count++;\n }\n return count;\n }\n\n get(segment: SegmentWithStream) {\n return this.requests.get(segment);\n }\n\n getOrCreateRequest(segment: SegmentWithStream) {\n let request = this.requests.get(segment);\n if (!request) {\n request = new Request(\n segment,\n this.requestProcessQueueCallback,\n this.bandwidthCalculators,\n this.playback,\n this.config,\n this.eventTarget,\n segment.stream.infoHash,\n );\n this.requests.set(segment, request);\n }\n return request;\n }\n\n remove(request: Request) {\n this.requests.delete(request.segment);\n }\n\n items() {\n return this.requests.values();\n }\n\n *httpRequests(): Generator<Request, void> {\n for (const request of this.requests.values()) {\n if (request.downloadSource === \"http\") yield request;\n }\n }\n\n *p2pRequests(): Generator<Request, void> {\n for (const request of this.requests.values()) {\n if (request.downloadSource === \"p2p\") yield request;\n }\n }\n\n destroy() {\n for (const request of this.requests.values()) {\n if (request.status !== \"loading\") continue;\n request.cancel();\n }\n this.requests.clear();\n }\n}\n","import { CoreRequestError } from \"../types.js\";\nimport { EngineCallbacks, SegmentWithStream } from \"../internal-types.js\";\n\nexport class EngineRequest {\n private _status: \"pending\" | \"succeed\" | \"failed\" | \"aborted\" = \"pending\";\n private _shouldBeStartedImmediately = false;\n\n constructor(\n readonly segment: SegmentWithStream,\n readonly engineCallbacks: EngineCallbacks,\n ) {}\n\n get status() {\n return this._status;\n }\n\n get shouldBeStartedImmediately() {\n return this._shouldBeStartedImmediately;\n }\n\n /**\n * Hands the segment to the player as a copy — the one place bytes leave the\n * core, and therefore the one place the copy belongs.\n *\n * What the core keeps in storage is what it seeds to peers, and players\n * transfer the buffer they are given to a transmuxing worker, which detaches\n * it: `byteLength` becomes 0 and the bytes are gone. hls.js and video.js's\n * VHS both do it. A detached buffer in storage is uploaded to peers as an\n * empty segment and served to the player itself as one, so the stream keeps\n * playing while the swarm quietly circulates nothing.\n *\n * Copying here rather than in each adapter means no integration can get it\n * wrong, and nothing else copies: a prefetched segment the player never asks\n * for is never copied at all.\n */\n resolve(data: ArrayBuffer, bandwidth: number) {\n if (this._status !== \"pending\") return;\n this._status = \"succeed\";\n this.engineCallbacks.onSuccess({ data: data.slice(0), bandwidth });\n }\n\n reject() {\n if (this._status !== \"pending\") return;\n this._status = \"failed\";\n this.engineCallbacks.onError(new CoreRequestError(\"failed\"));\n }\n\n abort() {\n if (this._status !== \"pending\") return;\n this._status = \"aborted\";\n this.engineCallbacks.onError(new CoreRequestError(\"aborted\"));\n }\n\n markAsShouldBeStartedImmediately() {\n this._shouldBeStartedImmediately = true;\n }\n}\n","import {\n Playback,\n SegmentWithStream,\n StreamWithSegments,\n} from \"../internal-types.js\";\nimport { P2PLoader } from \"../p2p/loader.js\";\nimport {\n getSegmentPlaybackStatuses,\n SegmentPlaybackStatuses,\n PlaybackTimeWindowsConfig,\n} from \"./stream.js\";\n\nexport type QueueItem = {\n segment: SegmentWithStream;\n statuses: SegmentPlaybackStatuses;\n};\n\nexport function* generateQueue(\n lastRequestedSegment: Readonly<SegmentWithStream>,\n playback: Readonly<Playback>,\n playbackConfig: PlaybackTimeWindowsConfig,\n currentP2PLoader: P2PLoader,\n availablePercentMemory: number,\n): Generator<QueueItem, void> {\n const { runtimeId, stream } = lastRequestedSegment;\n\n const requestedSegment =\n stream.segments.get(runtimeId) ?? reanchor(stream, lastRequestedSegment);\n if (!requestedSegment) return;\n\n const queueSegments = stream.segments.values();\n\n let first: SegmentWithStream;\n\n do {\n const next = queueSegments.next();\n if (next.done) return; // should never happen\n first = next.value;\n } while (first !== requestedSegment);\n\n const firstStatuses = getSegmentPlaybackStatuses(\n first,\n playback,\n playbackConfig,\n currentP2PLoader,\n availablePercentMemory,\n );\n if (isNotActualStatuses(firstStatuses)) {\n const next = queueSegments.next();\n\n // for cases when engine requests segment that is a little bit\n // earlier than current playhead position\n // it could happen when playhead position is significantly changed by user\n if (next.done) return;\n\n const second = next.value;\n\n const secondStatuses = getSegmentPlaybackStatuses(\n second,\n playback,\n playbackConfig,\n currentP2PLoader,\n availablePercentMemory,\n );\n\n if (isNotActualStatuses(secondStatuses)) return;\n firstStatuses.isHighDemand = true;\n yield { segment: first, statuses: firstStatuses };\n yield { segment: second, statuses: secondStatuses };\n } else {\n yield { segment: first, statuses: firstStatuses };\n }\n\n for (const segment of queueSegments) {\n const statuses = getSegmentPlaybackStatuses(\n segment,\n playback,\n playbackConfig,\n currentP2PLoader,\n availablePercentMemory,\n );\n if (isNotActualStatuses(statuses)) break;\n yield { segment, statuses };\n }\n}\n\n/**\n * Where to resume when a live window has rolled past the segment the player\n * last asked for: the oldest segment the window still holds that is not behind\n * it.\n *\n * The anchor ages out whenever the player loads without core for a while — a\n * request the registry could not resolve went to the player's own loader (see\n * specs/manifest-registry.md, \"Divergence between core and the player\"), or the\n * player simply stopped fetching with a full buffer. Losing the anchor must not\n * stop the queue: a peer that holds the window is still worth something to the\n * swarm, and prefetching keeps the segments the player will want next within\n * reach. Where the player actually is stays unknown until it requests again, so\n * this resumes from the earliest position it can possibly have, never from the\n * live edge.\n */\nfunction reanchor(\n stream: StreamWithSegments,\n lastRequestedSegment: Readonly<SegmentWithStream>,\n): SegmentWithStream | undefined {\n for (const segment of stream.segments.values()) {\n if (segment.startTime >= lastRequestedSegment.startTime) return segment;\n }\n}\n\nfunction isNotActualStatuses(statuses: SegmentPlaybackStatuses) {\n const { isHighDemand, isHttpDownloadable, isP2PDownloadable } = statuses;\n return !isHighDemand && !isHttpDownloadable && !isP2PDownloadable;\n}\n","/**\n * Which peer fetches a segment over HTTP so that the others can take it over\n * P2P. See specs/prefetch.md.\n *\n * Every peer scores itself and each connected neighbour for the segment with\n * the same hash; the peer with the lowest score in its own neighbourhood is\n * the owner and fetches. Two connected peers can never both be owners, a\n * non-owner always has a neighbour with a lower score to take the segment\n * from once that neighbour holds it, and because the segment id is part of\n * the score, ownership rotates from segment to segment. The same scores rank\n * the non-owners as backups, in the order they step in should the owner\n * fail to deliver in time.\n */\n\n/**\n * 32-bit string hash: FNV-1a with a final avalanche, so that inputs differing\n * in a few characters — peer ids share a prefix, segment ids are sequential —\n * still spread evenly. Dependency-free and the same on every peer.\n */\nexport function hash32(input: string): number {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n hash ^= hash >>> 16;\n hash = Math.imul(hash, 0x85ebca6b);\n hash ^= hash >>> 13;\n hash = Math.imul(hash, 0xc2b2ae35);\n hash ^= hash >>> 16;\n return hash >>> 0;\n}\n\nfunction scoreForSegment(peerId: string, externalId: number): number {\n return hash32(`${peerId}|${externalId}`);\n}\n\n/**\n * How many of `peerIds` outscore `ownPeerId` for the segment, i.e. this\n * peer's place in the line of fetchers: 0 is the owner, 1 the first backup,\n * and so on. Ties, which a 32-bit hash makes vanishingly rare, go to the\n * lexically smaller peer id so that both sides still agree.\n */\nexport function rankForSegment(\n ownPeerId: string,\n peerIds: Iterable<string>,\n externalId: number,\n): number {\n const ownScore = scoreForSegment(ownPeerId, externalId);\n let rank = 0;\n for (const peerId of peerIds) {\n const score = scoreForSegment(peerId, externalId);\n if (score < ownScore || (score === ownScore && peerId < ownPeerId)) {\n rank++;\n }\n }\n return rank;\n}\n\n/** True when `ownPeerId` has the lowest score for the segment. */\nexport function isHttpOwner(\n ownPeerId: string,\n peerIds: Iterable<string>,\n externalId: number,\n): boolean {\n return rankForSegment(ownPeerId, peerIds, externalId) === 0;\n}\n\n/**\n * Time a backup allows for the owner's announcement to arrive before it\n * counts the owner as absent. Covers a playlist refresh's worth of skew\n * between peers seeing the segment plus the announcement's own latency.\n */\nconst ANNOUNCEMENT_ALLOWANCE_SECONDS = 0.5;\n\n/**\n * Whether a peer should fetch a segment over HTTP now.\n *\n * The owner always should. A backup should only when waiting any longer\n * would risk the fetch landing inside the player's high-demand window: it\n * steps in once the time left until then falls to a multiple of the fetch\n * time it expects. The multiple shrinks with rank — the first backup at\n * twice the fetch time, the second at one and a half, and so on towards\n * once — so backups act in order, each only when the one before it has not.\n */\nexport function shouldFetchNow(params: {\n rank: number;\n secondsToHighDemand: number;\n estimatedFetchSeconds: number;\n}): boolean {\n const { rank, secondsToHighDemand, estimatedFetchSeconds } = params;\n if (rank === 0) return true;\n const factor = 1 + 1 / rank;\n return (\n secondsToHighDemand <=\n estimatedFetchSeconds * factor + ANNOUNCEMENT_ALLOWANCE_SECONDS\n );\n}\n","import type { Playback, SegmentWithStream } from \"./internal-types.js\";\nimport type { PlaybackState } from \"./playback.js\";\n\n/**\n * Turns whatever the environment can tell us into the single `Playback` value\n * the request queue consumes. See specs/playback-contract.md.\n *\n * Two sources, one output:\n * - \"reported\": an integration pushes `PlaybackState` (a media element, or a\n * native shim behind a proxy);\n * - \"inferred\": nobody reports, so it is derived from the request pattern the\n * core already observes.\n *\n * Inference is a fallback inside the core, not a second contract. An\n * integration's only job is to report if it can and stay silent if it cannot.\n */\n\ntype SegmentLike = Pick<\n SegmentWithStream,\n \"externalId\" | \"startTime\" | \"endTime\"\n>;\n\nexport type PlaybackTrackerConfig = {\n /**\n * A reported state older than this is stale; fall back to inference. A\n * paused report (rate 0) is exempt: nothing moves while paused, and the\n * one thing that can change — the buffer growing — fires a media event\n * that reports again.\n */\n reportStaleAfterMs: number;\n /** Starting guess for the player's buffer target, learned from there. */\n initialBufferTarget: number;\n /** Hard ceiling on the inferred estimate. */\n maxBufferTarget: number;\n /**\n * Inferred estimates are scaled down before use. Underestimating the buffer\n * costs P2P ratio; overestimating it stalls the viewer. Bias toward the\n * cheaper failure.\n */\n inferredSafetyFactor: number;\n /** Idle longer than `segmentDuration * this` means the buffer was full. */\n idleFullBufferRatio: number;\n};\n\nconst DEFAULT_PLAYBACK_TRACKER_CONFIG: PlaybackTrackerConfig = {\n reportStaleAfterMs: 2000,\n initialBufferTarget: 30,\n maxBufferTarget: 120,\n inferredSafetyFactor: 0.7,\n idleFullBufferRatio: 0.5,\n};\n\nexport class PlaybackTracker {\n private readonly config: PlaybackTrackerConfig;\n private readonly now: () => number;\n\n private reported?: { state: PlaybackState; at: number };\n\n /**\n * Manifest time at which the player's buffer currently ends: the anchor's\n * `startTime` while the anchor is in flight, its `endTime` once delivered.\n * Kept explicit rather than derived, because the right value depends on\n * delivery state and the request path and the storage path read it at\n * different moments.\n */\n private bufferEdge: number;\n private anchor: SegmentLike;\n private lastDeliveryEndedAt = 0;\n\n // Inference anchor: the buffer held `atBuffer` seconds when the wall clock\n // read `atMs` and `atDelivered` seconds of media had been handed over.\n private atMs: number;\n private atBuffer = 0;\n private atDelivered = 0;\n private delivered = 0;\n private bufferTarget: number;\n\n constructor(\n initialSegment: SegmentLike,\n config: Partial<PlaybackTrackerConfig> = {},\n now: () => number = () => performance.now(),\n ) {\n this.config = { ...DEFAULT_PLAYBACK_TRACKER_CONFIG, ...config };\n this.now = now;\n this.bufferTarget = this.config.initialBufferTarget;\n this.anchor = initialSegment;\n this.bufferEdge = initialSegment.startTime;\n this.atMs = this.now();\n }\n\n /** Integration push: media events in a browser, or a native bridge. */\n report(state: PlaybackState): void {\n this.reported = {\n state: { bufferAhead: Math.max(0, state.bufferAhead), rate: state.rate },\n at: this.now(),\n };\n }\n\n /**\n * The player asked for a segment. In flight, its buffer ends where that\n * segment begins; that is precisely why it is being requested.\n *\n * Also the seek detector: a request that is not the successor of the previous\n * one means the player jumped, and a jump means its buffer was discarded.\n * Returns whether a seek was detected so the caller can react.\n */\n onSegmentRequested(segment: SegmentLike): boolean {\n const now = this.now();\n const previous = this.anchor;\n this.anchor = segment;\n this.bufferEdge = segment.startTime;\n\n // Continuity is judged on the timeline, not on `externalId`: HLS ids step\n // by one, DASH ids by the segment's length in 100 ms units. A retry of the\n // same segment is not a jump either.\n const isSuccessor =\n segment.externalId === previous.externalId ||\n continues(previous, segment);\n\n if (!isSuccessor) {\n this.reanchor(now, 0);\n return true;\n }\n\n // A sequential request arriving after an idle gap: the player was not\n // fetching because it had nowhere to put the data. Its buffer was at target.\n const idle = (now - this.lastDeliveryEndedAt) / 1000;\n const duration = segment.endTime - segment.startTime;\n if (\n this.lastDeliveryEndedAt > 0 &&\n duration > 0 &&\n idle > duration * this.config.idleFullBufferRatio\n ) {\n this.learnBufferTarget(this.rawInferredBufferAhead(now));\n this.reanchor(now, this.bufferTarget);\n }\n return false;\n }\n\n /** A segment's bytes reached the player: the buffer now extends through it. */\n onSegmentDelivered(segment: SegmentLike): void {\n this.delivered += Math.max(0, segment.endTime - segment.startTime);\n this.lastDeliveryEndedAt = this.now();\n // Never let an out-of-order completion drag the edge backwards.\n this.bufferEdge = Math.max(this.bufferEdge, segment.endTime);\n }\n\n /** The value the queue reads. */\n getPlayback(): Playback {\n const now = this.now();\n const { reported } = this;\n\n const fresh =\n reported &&\n (reported.state.rate === 0 ||\n now - reported.at <= this.config.reportStaleAfterMs);\n if (reported && fresh) {\n return {\n bufferEdge: this.bufferEdge,\n bufferAhead: reported.state.bufferAhead,\n rate: reported.state.rate,\n source: \"reported\",\n };\n }\n\n return {\n bufferEdge: this.bufferEdge,\n bufferAhead:\n this.rawInferredBufferAhead(now) * this.config.inferredSafetyFactor,\n // Rate is the one genuinely ambiguous input when inferring. Assuming 1\n // is safe: it decays the estimate, which only ever makes the core more\n // eager to use HTTP, and the core acts only when a request arrives, so\n // a paused player costs nothing.\n rate: 1,\n source: \"inferred\",\n };\n }\n\n private rawInferredBufferAhead(now: number): number {\n const elapsed = (now - this.atMs) / 1000;\n const produced = this.delivered - this.atDelivered;\n return clamp(this.atBuffer + produced - elapsed, 0, this.bufferTarget);\n }\n\n private reanchor(now: number, bufferAhead: number): void {\n this.atMs = now;\n this.atBuffer = bufferAhead;\n this.atDelivered = this.delivered;\n }\n\n private learnBufferTarget(observed: number): void {\n if (observed <= 0) return;\n // EWMA toward what the player actually holds before it idles.\n const next = this.bufferTarget * 0.8 + observed * 0.2;\n this.bufferTarget = clamp(next, 1, this.config.maxBufferTarget);\n }\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value));\n}\n\n/**\n * Whether `next` starts where `previous` ends, within half the shorter of the\n * two durations — enough to absorb timeline rounding, not enough to hide a\n * skipped segment.\n */\nfunction continues(previous: SegmentLike, next: SegmentLike): boolean {\n const tolerance =\n Math.min(\n previous.endTime - previous.startTime,\n next.endTime - next.startTime,\n ) / 2;\n return Math.abs(next.startTime - previous.endTime) <= tolerance;\n}\n","import { HttpRequestExecutor } from \"./http-loader.js\";\nimport { CoreEventMap, DownloadSource, StreamConfig } from \"./types.js\";\nimport {\n Playback,\n BandwidthCalculators,\n EngineCallbacks,\n StreamDetails,\n SegmentWithStream,\n StreamWithSegments,\n} from \"./internal-types.js\";\nimport { P2PLoadersContainer } from \"./p2p/loaders-container.js\";\nimport { RequestsContainer } from \"./requests/request-container.js\";\nimport { EngineRequest } from \"./requests/engine-request.js\";\nimport * as QueueUtils from \"./utils/queue.js\";\nimport * as LoggerUtils from \"./utils/logger.js\";\nimport * as Utils from \"./utils/utils.js\";\nimport * as ElectionUtils from \"./utils/election.js\";\nimport { getDistanceFromPlayhead } from \"./utils/stream.js\";\nimport debug from \"debug\";\nimport { QueueItem } from \"./utils/queue.js\";\nimport { EventTarget } from \"./utils/event-target.js\";\nimport { SegmentStorage } from \"./segment-storage/index.js\";\nimport { WebTorrentSocketPool } from \"./webtorrent/webtorrent-socket-pool/index.js\";\nimport { PlaybackTracker } from \"./playback-tracker.js\";\nimport type { PlaybackState } from \"./playback.js\";\n\nconst FAILED_ATTEMPTS_CLEAR_INTERVAL = 60000;\nconst PEER_UPDATE_LATENCY = 1000;\n/** Weight of the newest sample in the running estimate of a stream's segment size. */\nconst SEGMENT_BYTES_EWMA_ALPHA = 0.3;\n\nexport class HybridLoader {\n private readonly requests: RequestsContainer;\n private engineRequest?: EngineRequest;\n private readonly p2pLoaders: P2PLoadersContainer;\n private readonly playback: Playback;\n private readonly playbackTracker: PlaybackTracker;\n private readonly logger: debug.Debugger;\n // Diagnostic only. While segment times still come from the player, the\n // estimate below must match media.currentTime; the engines log that value in\n // the same namespace. Enable with localStorage.debug = \"p2pml:playback-oracle\".\n private readonly oracleLogger = debug(\"p2pml:playback-oracle\");\n private levelChangedTimestamp?: number;\n private lastQueueProcessingTimeStamp?: number;\n private randomHttpDownloadTimeout?: number;\n /** Running estimate of segment size per stream, from segments already loaded. */\n private readonly segmentBytesByStream = new Map<string, number>();\n private initialHttpDelayTimeoutId?: number;\n private isProcessQueueMicrotaskCreated = false;\n private readonly createdAt = performance.now();\n\n constructor(\n private lastRequestedSegment: Readonly<SegmentWithStream>,\n private readonly streamDetails: Required<Readonly<StreamDetails>>,\n private readonly config: StreamConfig,\n private readonly bandwidthCalculators: BandwidthCalculators,\n private readonly segmentStorage: SegmentStorage,\n private readonly webTorrentSocketPool: WebTorrentSocketPool,\n private readonly eventTarget: EventTarget<CoreEventMap>,\n private readonly peerId: string,\n ) {\n const activeStream = this.lastRequestedSegment.stream;\n this.playbackTracker = new PlaybackTracker(this.lastRequestedSegment);\n // Shared by reference with the requests container; kept current by\n // syncPlayback() rather than replaced.\n this.playback = this.playbackTracker.getPlayback();\n this.requests = new RequestsContainer(\n this.requestProcessQueueMicrotask,\n this.bandwidthCalculators,\n this.playback,\n this.config,\n this.eventTarget,\n );\n\n this.p2pLoaders = new P2PLoadersContainer(\n this.lastRequestedSegment.stream,\n this.requests,\n this.segmentStorage,\n this.config,\n this.webTorrentSocketPool,\n this.eventTarget,\n this.peerId,\n this.requestProcessQueueMicrotask,\n );\n\n this.logger = debug(`p2pml-core:hybrid-loader-${activeStream.type}`);\n this.logger.color = \"coral\";\n\n this.setIntervalLoading();\n }\n\n private setIntervalLoading() {\n const peersCount = this.p2pLoaders.currentLoader.connectedPeerCount;\n const randomTimeout =\n Math.random() * PEER_UPDATE_LATENCY * peersCount + PEER_UPDATE_LATENCY;\n this.randomHttpDownloadTimeout = window.setTimeout(() => {\n // Deadlines pass without any queue event, so re-check on a timer too.\n this.prefetchThroughHttp();\n this.setIntervalLoading();\n }, randomTimeout);\n }\n\n // api method for engines\n async loadSegment(\n segment: Readonly<SegmentWithStream>,\n callbacks: EngineCallbacks,\n ) {\n this.logger(`requests: ${LoggerUtils.getSegmentString(segment)}`);\n const { stream } = segment;\n if (stream !== this.lastRequestedSegment.stream) {\n this.logger(`stream changed to ${LoggerUtils.getStreamString(stream)}`);\n this.p2pLoaders.changeCurrentLoader(stream);\n // The active rendition follows from the requested segment; bandwidth\n // measured before the switch says nothing about the new one.\n this.levelChangedTimestamp = performance.now();\n }\n this.lastRequestedSegment = segment;\n const isSeek = this.playbackTracker.onSegmentRequested(segment);\n this.syncPlayback();\n if (isSeek) this.logger(\"seek detected: buffer edge re-anchored\");\n\n this.segmentStorage.onSegmentRequested(\n stream.swarmId,\n stream.streamSwarmId,\n segment.externalId,\n segment.startTime,\n segment.endTime,\n stream.type,\n this.streamDetails.isLive,\n );\n const engineRequest = new EngineRequest(segment, callbacks);\n // After a seek the player has nothing buffered at the new position; do not\n // wait for peers before starting this request.\n if (isSeek) engineRequest.markAsShouldBeStartedImmediately();\n\n try {\n const hasSegment = this.segmentStorage.hasSegment(\n stream.swarmId,\n stream.streamSwarmId,\n segment.externalId,\n );\n\n if (hasSegment) {\n const data = await this.segmentStorage.getSegmentData(\n stream.swarmId,\n stream.streamSwarmId,\n segment.externalId,\n );\n // Byte length as well as presence: a stored segment that reads back\n // empty is a storage that let its buffer be detached, and serving it\n // would hand the player nothing while looking like a hit. Load it\n // again instead — at once, because the queue still counts the segment\n // as held and would leave this request waiting on nothing — and say so\n // loudly enough to be found.\n if (data?.byteLength === 0) {\n this.logger(\n `storage returned an empty segment for ${LoggerUtils.getSegmentString(segment)}; loading it again`,\n );\n engineRequest.markAsShouldBeStartedImmediately();\n }\n\n if (data && data.byteLength > 0) {\n const { queueDownloadRatio } = this.generateQueue();\n engineRequest.resolve(data, this.getBandwidth(queueDownloadRatio));\n this.playbackTracker.onSegmentDelivered(segment);\n this.syncPlayback();\n return;\n }\n }\n\n this.engineRequest?.abort();\n this.engineRequest = engineRequest;\n\n // If the engine explicitly requests a segment that previously failed during\n // background pre-fetching, clear its error history so it can be retried.\n const request = this.requests.get(segment);\n if (request?.status === \"failed\") {\n request.failedAttempts.clear();\n }\n } catch (error) {\n this.logger(\n `request failed for ${LoggerUtils.getSegmentString(segment)} in ${LoggerUtils.getStreamString(stream)}`,\n error,\n );\n engineRequest.reject();\n } finally {\n this.requestProcessQueueMicrotask();\n }\n }\n\n private requestProcessQueueMicrotask = (force = true) => {\n const now = performance.now();\n if (\n (!force &&\n this.lastQueueProcessingTimeStamp !== undefined &&\n now - this.lastQueueProcessingTimeStamp <= 1000) ||\n this.isProcessQueueMicrotaskCreated\n ) {\n return;\n }\n\n this.isProcessQueueMicrotaskCreated = true;\n Utils.queueMicrotask(() => {\n try {\n this.processQueue();\n this.lastQueueProcessingTimeStamp = now;\n } finally {\n this.isProcessQueueMicrotaskCreated = false;\n }\n });\n };\n\n private processRequests(\n queueSegmentIds: Set<string>,\n queueDownloadRatio: number,\n ) {\n const { stream } = this.lastRequestedSegment;\n const { httpErrorRetries } = this.config;\n const now = performance.now();\n for (const request of this.requests.items()) {\n const {\n downloadSource: type,\n status,\n segment,\n isHandledByProcessQueue,\n } = request;\n const engineRequest =\n this.engineRequest?.segment === segment\n ? this.engineRequest\n : undefined;\n\n switch (status) {\n case \"loading\":\n if (!queueSegmentIds.has(segment.runtimeId) && !engineRequest) {\n request.cancel();\n this.requests.remove(request);\n }\n break;\n\n case \"succeed\": {\n if (!type) break;\n if (type === \"http\") {\n this.p2pLoaders.currentLoader.broadcastAnnouncement();\n }\n if (engineRequest) {\n engineRequest.resolve(\n request.data,\n this.getBandwidth(queueDownloadRatio),\n );\n this.engineRequest = undefined;\n // The buffer edge tracks what the player holds. Only an engine\n // request delivers to the player; a background prefetch fills the\n // store and leaves the player's buffer where it was.\n this.playbackTracker.onSegmentDelivered(segment);\n this.syncPlayback();\n }\n this.requests.remove(request);\n this.noteSegmentBytes(segment, request.data.byteLength);\n\n this.logger(\n `succeed: ${LoggerUtils.getSegmentString(segment)} (byteLength: ${request.data.byteLength})`,\n );\n\n void this.segmentStorage.storeSegment(\n stream.swarmId,\n stream.streamSwarmId,\n segment.externalId,\n request.data,\n segment.startTime,\n segment.endTime,\n segment.stream.type,\n this.streamDetails.isLive,\n );\n break;\n }\n\n case \"failed\":\n if (type === \"http\" && !isHandledByProcessQueue) {\n this.p2pLoaders.currentLoader.broadcastAnnouncement();\n }\n if (\n !engineRequest &&\n !stream.segments.has(request.segment.runtimeId)\n ) {\n this.requests.remove(request);\n }\n if (\n request.failedAttempts.httpAttemptsCount >= httpErrorRetries &&\n engineRequest\n ) {\n this.engineRequest = undefined;\n engineRequest.reject();\n }\n break;\n\n case \"not-started\":\n this.requests.remove(request);\n break;\n\n case \"aborted\":\n this.requests.remove(request);\n break;\n }\n\n request.markHandledByProcessQueue();\n const { lastAttempt } = request.failedAttempts;\n if (\n lastAttempt &&\n now - lastAttempt.error.timestamp > FAILED_ATTEMPTS_CLEAR_INTERVAL\n ) {\n request.failedAttempts.clear();\n }\n }\n }\n\n private processQueue() {\n const { queue, queueSegmentIds, queueDownloadRatio } = this.generateQueue();\n this.processRequests(queueSegmentIds, queueDownloadRatio);\n\n const {\n simultaneousHttpDownloads,\n simultaneousP2PDownloads,\n httpErrorRetries,\n httpDownloadInitialTimeoutMs,\n } = this.config;\n\n const timeSinceStart = performance.now() - this.createdAt;\n const isInitialHttpWait =\n httpDownloadInitialTimeoutMs > 0 &&\n timeSinceStart < httpDownloadInitialTimeoutMs;\n\n if (isInitialHttpWait) {\n this.initialHttpDelayTimeoutId ??= window.setTimeout(() => {\n this.initialHttpDelayTimeoutId = undefined;\n this.requestProcessQueueMicrotask();\n }, httpDownloadInitialTimeoutMs - timeSinceStart);\n }\n\n const { engineRequest } = this;\n if (engineRequest) {\n const { segment } = engineRequest;\n const request = this.requests.get(segment);\n\n const shouldStartLoadImmediatelyEngineRequest =\n engineRequest.shouldBeStartedImmediately &&\n engineRequest.status === \"pending\" &&\n (!request ||\n request.status === \"not-started\" ||\n request.status === \"failed\" ||\n request.status === \"aborted\");\n\n if (shouldStartLoadImmediatelyEngineRequest) {\n // Don't abort requests when processing engine request\n // to avoid race condition with aborts in the requests queue\n\n const canLoadThroughHttp =\n !isInitialHttpWait &&\n (request?.failedAttempts.httpAttemptsCount ?? 0) < httpErrorRetries &&\n this.requests.executingHttpCount < simultaneousHttpDownloads;\n\n if (canLoadThroughHttp) {\n this.loadThroughHttp(segment);\n } else {\n const canLoadThroughP2P =\n this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(segment) &&\n this.requests.executingP2PCount < simultaneousP2PDownloads;\n\n if (canLoadThroughP2P) {\n this.loadThroughP2P(segment);\n }\n }\n }\n }\n\n for (const item of queue) {\n const { statuses, segment } = item;\n const request = this.requests.get(segment);\n\n if (request?.status === \"succeed\") continue;\n\n if (statuses.isHighDemand) {\n const canLoadThroughHttp =\n !isInitialHttpWait &&\n (request?.failedAttempts.httpAttemptsCount ?? 0) < httpErrorRetries;\n\n if (request?.status === \"loading\") {\n // High-demand request is loading\n\n const shouldSwitchFromP2PToHttp =\n canLoadThroughHttp &&\n request.downloadSource === \"p2p\" &&\n (this.requests.executingHttpCount < simultaneousHttpDownloads ||\n this.abortLastLoadingInQueueAfterItem(queue, segment, \"http\"));\n\n if (shouldSwitchFromP2PToHttp) {\n request.cancel();\n this.loadThroughHttp(segment);\n }\n\n continue;\n }\n\n // High-demand request is not loading\n\n const shouldLoadThroughHttp =\n canLoadThroughHttp &&\n (this.requests.executingHttpCount < simultaneousHttpDownloads ||\n this.abortLastLoadingInQueueAfterItem(queue, segment, \"http\"));\n\n if (shouldLoadThroughHttp) {\n this.loadThroughHttp(segment);\n continue;\n }\n\n const canLoadThroughP2P =\n this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(segment) &&\n (this.requests.executingP2PCount < simultaneousP2PDownloads ||\n this.abortLastLoadingInQueueAfterItem(queue, segment, \"p2p\"));\n\n if (canLoadThroughP2P) {\n this.loadThroughP2P(segment);\n }\n } else {\n // Regular requests load via P2P; HTTP prefetching is the owner's job,\n // decided below.\n\n const canLoadThroughP2P =\n statuses.isP2PDownloadable &&\n request?.status !== \"loading\" &&\n this.requests.executingP2PCount < simultaneousP2PDownloads;\n\n if (canLoadThroughP2P) {\n this.loadThroughP2P(segment);\n }\n }\n }\n\n // A queue pass runs on every playlist refresh, so the owner of a segment\n // that just appeared fetches it now rather than on the next timer tick.\n if (!isInitialHttpWait) this.prefetchThroughHttp();\n }\n\n // api method for engines\n abortSegmentRequest(segmentRuntimeId: string) {\n if (this.engineRequest?.segment.runtimeId !== segmentRuntimeId) return;\n this.engineRequest.abort();\n this.logger(\n \"abort: \",\n LoggerUtils.getSegmentString(this.engineRequest.segment),\n );\n this.engineRequest = undefined;\n this.requestProcessQueueMicrotask();\n }\n\n private loadThroughHttp(segment: SegmentWithStream) {\n const request = this.requests.getOrCreateRequest(segment);\n const executor = new HttpRequestExecutor(\n request,\n this.config,\n this.eventTarget,\n );\n executor.execute();\n this.p2pLoaders.currentLoader.broadcastAnnouncement();\n }\n\n private loadThroughP2P(segment: SegmentWithStream) {\n this.p2pLoaders.currentLoader.downloadSegment(segment);\n }\n\n /**\n * HTTP prefetching of segments nobody has yet. Each candidate has one\n * elected owner among the connected peers (see specs/prefetch.md); the\n * owner fetches at once, everyone else waits for its announcement and\n * takes the segment over P2P. The others are ranked as backups by the same\n * scores, and a backup steps in only when waiting any longer would risk\n * the fetch landing inside the player's high-demand window — judged from\n * the time left until then and the fetch time this peer expects.\n */\n private prefetchThroughHttp() {\n const { httpDownloadInitialTimeoutMs } = this.config;\n const isInitialHttpWait =\n httpDownloadInitialTimeoutMs > 0 &&\n performance.now() - this.createdAt < httpDownloadInitialTimeoutMs;\n\n if (isInitialHttpWait) return;\n\n const availableStorageCapacityPercent =\n this.getAvailableStorageCapacityPercent();\n if (availableStorageCapacityPercent <= 10) return;\n\n const {\n simultaneousHttpDownloads,\n httpErrorRetries,\n highDemandTimeWindow,\n } = this.config;\n const p2pLoader = this.p2pLoaders.currentLoader;\n if (!p2pLoader.connectedPeerCount) return;\n\n this.syncPlayback();\n const peerIds = Array.from(p2pLoader.connectedPeerIds);\n\n for (const { segment, statuses } of QueueUtils.generateQueue(\n this.lastRequestedSegment,\n this.playback,\n this.config,\n p2pLoader,\n availableStorageCapacityPercent,\n )) {\n if (this.requests.executingHttpCount >= simultaneousHttpDownloads) break;\n if (\n !statuses.isHttpDownloadable ||\n statuses.isP2PDownloadable ||\n this.segmentStorage.hasSegment(\n segment.stream.swarmId,\n segment.stream.streamSwarmId,\n segment.externalId,\n )\n ) {\n continue;\n }\n const request = this.requests.get(segment);\n if (\n request &&\n (request.status === \"loading\" ||\n request.status === \"succeed\" ||\n request.failedAttempts.httpAttemptsCount >= httpErrorRetries)\n ) {\n continue;\n }\n\n const rank = ElectionUtils.rankForSegment(\n this.peerId,\n peerIds,\n segment.externalId,\n );\n const secondsToHighDemand =\n getDistanceFromPlayhead(segment, this.playback).start -\n highDemandTimeWindow * this.playback.rate;\n const estimatedFetchSeconds = this.estimateFetchSeconds(segment);\n\n if (\n ElectionUtils.shouldFetchNow({\n rank,\n secondsToHighDemand,\n estimatedFetchSeconds,\n })\n ) {\n this.logger(\n `prefetch ${LoggerUtils.getSegmentString(segment)} as ${rank === 0 ? \"owner\" : `backup #${rank}`}`,\n );\n this.loadThroughHttp(segment);\n }\n }\n }\n\n /**\n * Expected wall-clock seconds to fetch the segment over HTTP: its size,\n * estimated from segments of the same stream already loaded or else from\n * the stream's bitrate, over the throughput HTTP transfers have achieved.\n * With no transfer measured yet the link is assumed to run at the stream's\n * bitrate, which errs on the side of stepping in early.\n */\n private estimateFetchSeconds(segment: SegmentWithStream): number {\n const { stream } = segment;\n const duration = Math.max(0, segment.endTime - segment.startTime);\n const bitrate = stream.properties.bitrate ?? 0;\n\n const bytes =\n this.segmentBytesByStream.get(stream.runtimeId) ??\n (bitrate * duration) / 8;\n if (bytes <= 0) return duration;\n\n const { http } = this.bandwidthCalculators;\n const measured = Math.max(\n http.getBandwidthLoadingOnly(10),\n http.getBandwidthLoadingOnly(30),\n );\n const bandwidth = measured > 0 ? measured : bitrate;\n if (bandwidth <= 0) return duration;\n\n return (bytes * 8) / bandwidth;\n }\n\n private noteSegmentBytes(segment: SegmentWithStream, bytes: number) {\n if (bytes <= 0) return;\n const key = segment.stream.runtimeId;\n const previous = this.segmentBytesByStream.get(key);\n this.segmentBytesByStream.set(\n key,\n previous === undefined\n ? bytes\n : previous + SEGMENT_BYTES_EWMA_ALPHA * (bytes - previous),\n );\n }\n\n private abortLastLoadingInQueueAfterItem(\n queue: QueueUtils.QueueItem[],\n segment: SegmentWithStream,\n downloadSource: DownloadSource,\n ): boolean {\n for (const { segment: itemSegment } of Utils.arrayBackwards(queue)) {\n if (itemSegment === segment) break;\n const request = this.requests.get(itemSegment);\n if (\n request?.downloadSource === downloadSource &&\n request.status === \"loading\"\n ) {\n request.cancel();\n return true;\n }\n }\n return false;\n }\n\n private getAvailableStorageCapacityPercent(): number {\n const { totalCapacity, usedCapacity } = this.segmentStorage.getUsage();\n return 100 - (usedCapacity / totalCapacity) * 100;\n }\n\n private generateQueue() {\n this.syncPlayback();\n const queue: QueueItem[] = [];\n const queueSegmentIds = new Set<string>();\n let maxPossibleLength = 0;\n let alreadyLoadedCount = 0;\n\n const availableStorageCapacityPercent =\n this.getAvailableStorageCapacityPercent();\n for (const item of QueueUtils.generateQueue(\n this.lastRequestedSegment,\n this.playback,\n this.config,\n this.p2pLoaders.currentLoader,\n availableStorageCapacityPercent,\n )) {\n maxPossibleLength++;\n const { segment } = item;\n\n if (\n this.segmentStorage.hasSegment(\n segment.stream.swarmId,\n segment.stream.streamSwarmId,\n segment.externalId,\n ) ||\n this.requests.get(segment)?.status === \"succeed\"\n ) {\n alreadyLoadedCount++;\n continue;\n }\n queue.push(item);\n queueSegmentIds.add(segment.runtimeId);\n }\n\n return {\n queue,\n queueSegmentIds,\n maxPossibleLength,\n alreadyLoadedCount,\n queueDownloadRatio:\n maxPossibleLength !== 0 ? alreadyLoadedCount / maxPossibleLength : 0,\n };\n }\n\n private getBandwidth(queueDownloadRatio: number) {\n const { http, all } = this.bandwidthCalculators;\n const activeLevelBitrate =\n this.lastRequestedSegment.stream.properties.bitrate ?? 0;\n if (activeLevelBitrate === 0) {\n return all.getBandwidthLoadingOnly(3);\n }\n\n const bandwidth = Math.max(\n all.getBandwidth(30, this.levelChangedTimestamp),\n all.getBandwidth(60, this.levelChangedTimestamp),\n all.getBandwidth(90, this.levelChangedTimestamp),\n );\n\n if (queueDownloadRatio >= 0.8 || bandwidth >= activeLevelBitrate * 0.9) {\n return Math.max(\n all.getBandwidthLoadingOnly(1),\n all.getBandwidthLoadingOnly(3),\n all.getBandwidthLoadingOnly(5),\n );\n }\n\n const httpRealBandwidth = Math.max(\n http.getBandwidthLoadingOnly(1),\n http.getBandwidthLoadingOnly(3),\n http.getBandwidthLoadingOnly(5),\n );\n\n return Math.max(bandwidth, httpRealBandwidth);\n }\n\n sendBroadcastAnnouncement(sendEmptySegmentsAnnouncement = false) {\n this.p2pLoaders.currentLoader.broadcastAnnouncement(\n sendEmptySegmentsAnnouncement,\n );\n }\n\n updatePlayback(state: PlaybackState) {\n this.playbackTracker.report(state);\n const changed = this.syncPlayback();\n if (!changed) return;\n\n if (this.oracleLogger.enabled) {\n const { bufferEdge, bufferAhead, source } = this.playback;\n this.oracleLogger(\n `${this.lastRequestedSegment.stream.type} playhead≈${(bufferEdge - bufferAhead).toFixed(3)} (${source})`,\n );\n }\n\n // The store compares this position against the segment times it was given,\n // which are manifest time — so the position must be manifest time too.\n const { bufferEdge, bufferAhead, rate } = this.playback;\n this.segmentStorage.onPlaybackUpdated(bufferEdge - bufferAhead, rate);\n this.requestProcessQueueMicrotask(false);\n }\n\n /**\n * Copies the tracker's current view into the shared `playback` object.\n * Returns whether anything changed.\n *\n * A paused player reports rate 0. Window sizing keeps the last non-zero\n * rate instead, so prefetching continues while paused and the buffer is\n * ready on resume — the behaviour the absolute-position code had.\n */\n private syncPlayback(): boolean {\n const next = this.playbackTracker.getPlayback();\n const rate = next.rate === 0 ? this.playback.rate : next.rate;\n const changed =\n this.playback.bufferEdge !== next.bufferEdge ||\n this.playback.bufferAhead !== next.bufferAhead ||\n this.playback.rate !== rate ||\n this.playback.source !== next.source;\n this.playback.bufferEdge = next.bufferEdge;\n this.playback.bufferAhead = next.bufferAhead;\n this.playback.rate = rate;\n this.playback.source = next.source;\n return changed;\n }\n\n updateStream(stream: StreamWithSegments) {\n if (stream !== this.lastRequestedSegment.stream) return;\n this.logger(`update stream: ${LoggerUtils.getStreamString(stream)}`);\n this.requestProcessQueueMicrotask();\n }\n\n destroy() {\n clearTimeout(this.randomHttpDownloadTimeout);\n clearTimeout(this.initialHttpDelayTimeoutId);\n this.engineRequest?.abort();\n this.requests.destroy();\n this.p2pLoaders.destroy();\n }\n}\n","import { utf8ToUintArray } from \"./utils.js\";\n\nexport function sha1(str: string): string {\n const bytes = utf8ToUintArray(str);\n const words: number[] = [];\n const msgLen = bytes.length * 8;\n\n for (let i = 0; i < bytes.length; i++) {\n words[i >> 2] |= (bytes[i] & 0xff) << (24 - (i % 4) * 8);\n }\n words[msgLen >> 5] |= 0x80 << (24 - (msgLen % 32));\n words[(((msgLen + 64) >> 9) << 4) + 15] = msgLen;\n\n let h0 = 0x67452301;\n let h1 = 0xefcdab89;\n let h2 = 0x98badcfe;\n let h3 = 0x10325476;\n let h4 = 0xc3d2e1f0;\n\n const w: number[] = [];\n for (let i = 0; i < words.length; i += 16) {\n const a = h0,\n b = h1,\n c = h2,\n d = h3,\n e = h4;\n for (let j = 0; j < 80; j++) {\n if (j < 16) {\n w[j] = words[i + j] | 0;\n } else {\n const n = w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16];\n w[j] = (n << 1) | (n >>> 31);\n }\n let f: number;\n if (j < 20) {\n f = ((h1 & h2) | (~h1 & h3)) + 0x5a827999;\n } else if (j < 40) {\n f = (h1 ^ h2 ^ h3) + 0x6ed9eba1;\n } else if (j < 60) {\n f = ((h1 & h2) | (h1 & h3) | (h2 & h3)) - 0x70e44324;\n } else {\n f = (h1 ^ h2 ^ h3) - 0x359d3e2a;\n }\n\n const t = (((h0 << 5) | (h0 >>> 27)) + h4 + (w[j] >>> 0) + f) | 0;\n h4 = h3;\n h3 = h2;\n h2 = (h1 << 30) | (h1 >>> 2);\n h1 = h0;\n h0 = t;\n }\n h0 = (h0 + a) | 0;\n h1 = (h1 + b) | 0;\n h2 = (h2 + c) | 0;\n h3 = (h3 + d) | 0;\n h4 = (h4 + e) | 0;\n }\n\n let bin = \"\";\n const wordsOut = [h0, h1, h2, h3, h4];\n for (let i = 0; i < 20; i++) {\n const shift = 24 - (i % 4) * 8;\n const word = wordsOut[i >> 2];\n bin += String.fromCharCode((word >>> shift) & 0xff);\n }\n return bin;\n}\n","import type { StreamProperties, StreamType } from \"./types.js\";\nimport { sha1 } from \"./utils/hash.js\";\n\n/**\n * Version of the peer swarm protocol. Included in every stream swarm ID, so peers\n * with incompatible protocols never join the same swarm.\n *\n * Changing the identity derivation in any way requires bumping this version.\n */\nexport const PEER_PROTOCOL_VERSION = \"v3\";\n\n/**\n * Computes a stream's identity hash from the properties the core read from\n * the manifest. Every peer parses the same manifest with the same parser, so\n * the input is already identical everywhere and nothing is normalized: the\n * fields are joined as given. `null`, `undefined` and `\"\"` hash alike, and so\n * do a missing `bitrate` and 0.\n *\n * `bitrate` belongs in the input only when the manifest needs it to tell the\n * stream apart from another of the same type — see {@link identityProperties},\n * which the core applies before hashing. A server reproducing a client's hash\n * must make the same choice.\n *\n * Environment-agnostic: usable in Node.js 16+ as well as in the browser.\n */\nexport function computeStreamIdentityHash(\n properties: StreamProperties,\n): string {\n const field = (value: string | number | null | undefined) =>\n value === undefined || value === null ? \"\" : String(value);\n const str = [\n properties.bitrate ?? 0,\n field(properties.codecs),\n field(properties.width),\n field(properties.height),\n field(properties.language),\n field(properties.channels),\n field(properties.name),\n field(properties.frameRate),\n field(properties.videoRange),\n ].join(\"-\");\n return btoa(sha1(str));\n}\n\n/**\n * The properties that feed each stream's identity, given every stream one\n * manifest declares: the stream's own properties with `bitrate` dropped,\n * unless another stream of the same type in the manifest would then be\n * indistinguishable from it — a ladder with two rungs at one resolution.\n *\n * Bandwidth is the one attribute an origin may recompute on every request:\n * some live packagers publish the encoder's current rate, so two viewers who\n * fetched the master seconds apart would read different `BANDWIDTH` for the\n * same rendition and, were it hashed, never meet. It is therefore left out of\n * identity wherever the rest of the properties already tell the streams apart.\n * The decision depends only on the manifest, so every peer makes the same one.\n */\nexport function identityProperties(\n streams: readonly { type: StreamType; properties: StreamProperties }[],\n): StreamProperties[] {\n const withoutBitrate = streams.map((s): StreamProperties => ({\n ...s.properties,\n bitrate: undefined,\n }));\n const occurrences = new Map<string, number>();\n const keys = streams.map((s, i) => {\n const key = `${s.type}|${computeStreamIdentityHash(withoutBitrate[i])}`;\n occurrences.set(key, (occurrences.get(key) ?? 0) + 1);\n return key;\n });\n return streams.map((s, i) =>\n (occurrences.get(keys[i]) ?? 0) > 1 ? s.properties : withoutBitrate[i],\n );\n}\n\n/**\n * Builds the default stream swarm ID from its components. The stream swarm ID is the\n * pre-hash string that defines which P2P swarm a stream belongs to;\n * its hash is the infohash announced to trackers (see {@link computeInfoHash}).\n */\nexport function buildStreamSwarmId(\n swarmId: string,\n streamType: StreamType,\n identityHash: string,\n): string {\n return `${PEER_PROTOCOL_VERSION}-${swarmId}-${streamType}-${identityHash}`;\n}\n\n/**\n * Computes the default stream swarm ID for a stream from its raw properties.\n *\n * This is the derivation a client with no `streamSwarmIdBuilder` configured uses.\n * Run it on a server (Node.js 16+) to predict a stream's swarm ID — and, via\n * {@link computeInfoHash}, the exact infohash the client announces to trackers.\n */\nexport function computeStreamSwarmId(options: {\n swarmId: string;\n streamType: StreamType;\n properties: StreamProperties;\n}): string {\n return buildStreamSwarmId(\n options.swarmId,\n options.streamType,\n computeStreamIdentityHash(options.properties),\n );\n}\n\n/**\n * Computes the infohash announced to trackers for the given stream swarm ID.\n *\n * A BitTorrent tracker `infoHash` MUST be exactly 20 bytes.\n * We take 15 bytes of the binary SHA-1 and encode it to Base64.\n * This produces exactly a 20-character ASCII string (no padding).\n * Note: this is a 20-byte ASCII representation, not a standard\n * 20-byte binary SHA-1 infoHash.\n *\n * This function is environment-agnostic: use it on a server (Node.js 16+) to\n * compute the infohashes to allowlist on a private tracker.\n */\nexport function computeInfoHash(streamSwarmId: string): string {\n return btoa(sha1(streamSwarmId).slice(0, 15));\n}\n","import type { ByteRange } from \"../types.js\";\n\n/**\n * The `sidx` box of an ISO BMFF file: a DASH `SegmentBase` stream's segment\n * index. See specs/manifest-registry.md, \"Resolving an external index\".\n */\ntype SidxReference = {\n /** 0 references media; 1 references another `sidx` box (not followed). */\n readonly referenceType: 0 | 1;\n readonly referencedSize: number;\n /** In the box's timescale. */\n readonly subsegmentDuration: number;\n};\n\nexport type SidxBox = {\n /** Where the box starts in the parsed data, and its size in bytes. */\n readonly boxOffset: number;\n readonly boxSize: number;\n readonly timescale: number;\n readonly earliestPresentationTime: number;\n /** Bytes from the end of the box to the first referenced subsegment. */\n readonly firstOffset: number;\n readonly references: readonly SidxReference[];\n};\n\nconst MAX_SAFE_HIGH_WORD = 0x1fffff; // 2^53 / 2^32\n\n/**\n * Finds and parses the `sidx` box in a response. The response may be wider\n * than the index alone — a player often fetches initialization and index\n * together — so the box is located by walking the box structure, never assumed\n * to sit at the start. Returns `undefined` for truncated data, for values\n * beyond the safe integer range, and when there is no `sidx` box at all.\n */\nexport function parseSidx(\n data: ArrayBuffer | ArrayBufferView,\n): SidxBox | undefined {\n const view =\n data instanceof ArrayBuffer\n ? new DataView(data)\n : new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n let offset = 0;\n while (offset + 8 <= view.byteLength) {\n let size = view.getUint32(offset);\n const type = String.fromCharCode(\n view.getUint8(offset + 4),\n view.getUint8(offset + 5),\n view.getUint8(offset + 6),\n view.getUint8(offset + 7),\n );\n let headerSize = 8;\n if (size === 1) {\n const large = readUint64(view, offset + 8);\n if (large === undefined) return undefined;\n size = large;\n headerSize = 16;\n } else if (size === 0) {\n size = view.byteLength - offset;\n }\n if (size < headerSize) return undefined;\n if (type === \"sidx\") {\n const payload = parseSidxPayload(\n view,\n offset + headerSize,\n Math.min(offset + size, view.byteLength),\n );\n return payload && { boxOffset: offset, boxSize: size, ...payload };\n }\n offset += size;\n }\n return undefined;\n}\n\nfunction parseSidxPayload(\n view: DataView,\n start: number,\n end: number,\n): Omit<SidxBox, \"boxOffset\" | \"boxSize\"> | undefined {\n // version(1) flags(3) reference_ID(4) timescale(4)\n if (start + 12 > end) return undefined;\n const version = view.getUint8(start);\n const timescale = view.getUint32(start + 8);\n let pos = start + 12;\n\n let earliestPresentationTime: number | undefined;\n let firstOffset: number | undefined;\n if (version === 0) {\n if (pos + 8 > end) return undefined;\n earliestPresentationTime = view.getUint32(pos);\n firstOffset = view.getUint32(pos + 4);\n pos += 8;\n } else {\n earliestPresentationTime = readUint64(view, pos);\n firstOffset = readUint64(view, pos + 8);\n pos += 16;\n if (earliestPresentationTime === undefined || firstOffset === undefined) {\n return undefined;\n }\n }\n\n // reserved(2) reference_count(2)\n if (pos + 4 > end) return undefined;\n const referenceCount = view.getUint16(pos + 2);\n pos += 4;\n\n if (timescale === 0) return undefined;\n\n const references: SidxReference[] = [];\n for (let i = 0; i < referenceCount; i++) {\n if (pos + 12 > end) return undefined;\n const word = view.getUint32(pos);\n references.push({\n referenceType: word >>> 31 === 1 ? 1 : 0,\n referencedSize: word & 0x7fffffff,\n subsegmentDuration: view.getUint32(pos + 4),\n });\n pos += 12;\n }\n\n return { timescale, earliestPresentationTime, firstOffset, references };\n}\n\nfunction readUint64(view: DataView, pos: number): number | undefined {\n if (pos + 8 > view.byteLength) return undefined;\n const high = view.getUint32(pos);\n if (high > MAX_SAFE_HIGH_WORD) return undefined;\n return high * 0x100000000 + view.getUint32(pos + 4);\n}\n\n/** Whether the requested range covers the index range entirely. */\nexport function rangeCovers(\n requested: ByteRange | undefined,\n index: ByteRange,\n): boolean {\n if (!requested) return true;\n return requested.start <= index.start && requested.end >= index.end;\n}\n","import type { ByteRange, StreamProperties, StreamType } from \"../types.js\";\nimport type {\n ParsedManifest,\n ParsedSegment,\n ParsedStream,\n SegmentIndexSource,\n} from \"./types.js\";\nimport {\n computeStreamIdentityHash,\n identityProperties,\n} from \"../stream-identity.js\";\nimport { normalizeUrl, segmentKey } from \"./url-key.js\";\nimport { rangeCovers, type SidxBox } from \"./mp4-sidx.js\";\n\n/**\n * The manifest-derived registry: every stream and segment the core knows,\n * as read from the manifests the player fetched. See\n * specs/manifest-registry.md.\n *\n * Everything here is interpretation, and interpretation belongs to the core:\n * canonical identity, the stable timeline, live detection.\n */\n\ntype RegistrySegment = {\n readonly key: string;\n readonly url: string;\n readonly byteRange?: ByteRange;\n /** Canonical identity: HLS media sequence; DASH presentation time in 100 ms units. */\n readonly externalId: number;\n readonly startTime: number;\n readonly endTime: number;\n};\n\nexport type RegistryStream = {\n readonly key: string;\n readonly type: StreamType;\n readonly properties: StreamProperties;\n readonly identityHash: string;\n readonly indexSource: SegmentIndexSource;\n readonly initSegment?: { url: string; byteRange?: ByteRange };\n readonly isLive?: boolean;\n readonly segments: ReadonlyMap<string, RegistrySegment>;\n};\n\ntype MutableStream = Omit<RegistryStream, \"segments\"> & {\n segments: Map<string, RegistrySegment>;\n /** HLS without PDT: start time of every sequence number laid out so far. */\n timeline: Map<number, number>;\n};\n\n/** One per stream the manifest listed segments for, changed or not. */\nexport type RegistryUpdate = {\n readonly streamKey: string;\n readonly type: StreamType;\n readonly isLive: boolean;\n /** Bounds of the listed segments on the stream's manifest timeline. */\n readonly start: number;\n readonly end: number;\n readonly segmentCount: number;\n readonly added: number;\n readonly removed: number;\n};\n\nexport class ManifestRegistry {\n private readonly streams = new Map<string, MutableStream>();\n\n getStreams(): readonly RegistryStream[] {\n return Array.from(this.streams.values());\n }\n\n getStream(key: string): RegistryStream | undefined {\n return this.streams.get(key);\n }\n\n /**\n * Applies one parsed manifest. Idempotent: re-applying an unchanged\n * manifest changes nothing and reports no updates.\n */\n apply(manifest: ParsedManifest): RegistryUpdate[] {\n const updates: RegistryUpdate[] = [];\n // Bitrate enters a stream's identity only where this manifest needs it to\n // tell same-type streams apart; see specs/segment-identity.md.\n const identity = identityProperties(manifest.streams);\n\n for (const [i, parsed] of manifest.streams.entries()) {\n const stream = this.upsertStream(parsed, manifest, identity[i]);\n if (!parsed.segments) continue;\n\n updates.push(\n this.applySegments(stream, parsed.segments, manifest.protocol),\n );\n }\n\n return updates;\n }\n\n /** Streams whose external index a request for this URL and range would fetch. */\n streamsAwaitingIndex(\n url: string,\n byteRange: ByteRange | undefined,\n ): RegistryStream[] {\n const wanted = normalizeUrl(url);\n const result: RegistryStream[] = [];\n for (const stream of this.streams.values()) {\n const source = stream.indexSource;\n if (source.kind !== \"external\") continue;\n if (normalizeUrl(source.url) !== wanted) continue;\n if (!rangeCovers(byteRange, source.byteRange)) continue;\n result.push(stream);\n }\n return result;\n }\n\n /**\n * Lays a stream's segments out from its `sidx` box the way ISO BMFF defines\n * it, which is the layout the player requests: the first subsegment starts\n * `firstOffset` bytes after the end of the `sidx` box itself — not after the\n * declared index range, which may hold further boxes — and the rest follow\n * each other. Presentation time accumulates from the period start in the\n * box's timescale. References to further index boxes are not followed.\n */\n resolveExternalIndex(\n url: string,\n byteRange: ByteRange | undefined,\n sidx: SidxBox,\n ): RegistryUpdate[] {\n const updates: RegistryUpdate[] = [];\n for (const stream of this.streamsAwaitingIndex(url, byteRange)) {\n const source = stream.indexSource;\n if (source.kind !== \"external\") continue;\n\n const segments: ParsedSegment[] = [];\n // The box was found at `boxOffset` within a response that began at the\n // requested range's start, so this is its position in the file.\n const boxEnd = (byteRange?.start ?? 0) + sidx.boxOffset + sidx.boxSize;\n let start = boxEnd + sidx.firstOffset;\n let presentationTime = source.periodStart;\n for (const reference of sidx.references) {\n if (reference.referenceType === 1) continue;\n const duration = reference.subsegmentDuration / sidx.timescale;\n segments.push({\n url: source.url,\n byteRange: { start, end: start + reference.referencedSize - 1 },\n duration,\n sequence: segments.length,\n presentationTime,\n });\n start += reference.referencedSize;\n presentationTime += duration;\n }\n\n const mutable = this.streams.get(stream.key);\n if (!mutable) continue;\n updates.push(this.applySegments(mutable, segments, \"dash\"));\n }\n return updates;\n }\n\n private upsertStream(\n parsed: ParsedStream,\n manifest: ParsedManifest,\n identityInput: StreamProperties,\n ): MutableStream {\n const key = this.resolveStreamKey(parsed, manifest);\n const existing = this.streams.get(key);\n\n // A media playlist says nothing about the stream's identity; only the\n // master does. Keep whatever the master registered.\n const carriesIdentity = !parsed.segments || !existing;\n\n const stream: MutableStream = {\n key,\n type: existing?.type ?? parsed.type,\n properties: carriesIdentity ? parsed.properties : existing.properties,\n identityHash: carriesIdentity\n ? computeStreamIdentityHash(identityInput)\n : existing.identityHash,\n indexSource: parsed.indexSource,\n initSegment: parsed.initSegment ?? existing?.initSegment,\n isLive: parsed.isLive ?? existing?.isLive,\n segments: existing?.segments ?? new Map<string, RegistrySegment>(),\n timeline: existing?.timeline ?? new Map<number, number>(),\n };\n this.streams.set(key, stream);\n return stream;\n }\n\n /**\n * An HLS media playlist is matched to the stream its master declared by\n * URL, tolerating a differing query string (signed tokens rotate). No match\n * means a media playlist loaded directly, which is a single anonymous stream.\n */\n private resolveStreamKey(\n parsed: ParsedStream,\n manifest: ParsedManifest,\n ): string {\n if (this.streams.has(parsed.key)) return parsed.key;\n if (manifest.protocol !== \"hls\" || !parsed.segments) return parsed.key;\n\n const wanted = stripQuery(normalizeUrl(parsed.key));\n for (const key of this.streams.keys()) {\n if (stripQuery(normalizeUrl(key)) === wanted) return key;\n }\n return parsed.key;\n }\n\n private applySegments(\n stream: MutableStream,\n segments: readonly ParsedSegment[] = [],\n protocol: ParsedManifest[\"protocol\"],\n ): RegistryUpdate {\n const next = new Map<string, RegistrySegment>();\n const times = this.layoutTimeline(stream, segments, protocol);\n\n segments.forEach((s, i) => {\n const key = segmentKey(s.url, s.byteRange);\n const startTime = times[i];\n next.set(key, {\n key,\n url: s.url,\n byteRange: s.byteRange,\n externalId: externalIdOf(s, protocol),\n startTime,\n endTime: startTime + s.duration,\n });\n });\n\n let added = 0;\n let removed = 0;\n for (const key of stream.segments.keys()) {\n if (!next.has(key)) {\n stream.segments.delete(key);\n removed++;\n }\n }\n for (const [key, segment] of next) {\n if (!stream.segments.has(key)) added++;\n stream.segments.set(key, segment);\n }\n\n let start = Infinity;\n let end = -Infinity;\n for (const segment of next.values()) {\n start = Math.min(start, segment.startTime);\n end = Math.max(end, segment.endTime);\n }\n return {\n streamKey: stream.key,\n type: stream.type,\n isLive: stream.isLive === true,\n start: next.size ? start : 0,\n end: next.size ? end : 0,\n segmentCount: next.size,\n added,\n removed,\n };\n }\n\n /**\n * Start times that mean the same thing across refreshes.\n *\n * - DASH: presentation time, already stable.\n * - HLS with `EXT-X-PROGRAM-DATE-TIME`: the tokenizer extrapolates it to\n * every segment; wall-clock seconds are the timeline.\n * - HLS without it: anchor on media sequence. Lay out from a sequence\n * number already placed; if none overlaps, continue from the last known\n * end, or start at zero. The zero point never leaves the core.\n */\n private layoutTimeline(\n stream: MutableStream,\n segments: readonly ParsedSegment[],\n protocol: ParsedManifest[\"protocol\"],\n ): number[] {\n if (protocol === \"dash\") {\n return segments.map((s) => s.presentationTime ?? 0);\n }\n if (segments.every((s) => s.programDateTime !== undefined)) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return segments.map((s) => s.programDateTime! / 1000);\n }\n\n const { timeline } = stream;\n const anchorIndex = segments.findIndex((s) => timeline.has(s.sequence));\n const times = new Array<number>(segments.length);\n\n if (anchorIndex === -1) {\n let start = 0;\n if (timeline.size) {\n const lastSequence = Math.max(...timeline.keys());\n start =\n (timeline.get(lastSequence) ?? 0) +\n (this.durationOf(stream, lastSequence) ?? 0);\n }\n for (let i = 0; i < segments.length; i++) {\n times[i] = start;\n start += segments[i].duration;\n }\n } else {\n times[anchorIndex] = timeline.get(segments[anchorIndex].sequence) ?? 0;\n for (let i = anchorIndex + 1; i < segments.length; i++) {\n times[i] = times[i - 1] + segments[i - 1].duration;\n }\n for (let i = anchorIndex - 1; i >= 0; i--) {\n times[i] = times[i + 1] - segments[i].duration;\n }\n }\n\n segments.forEach((s, i) => timeline.set(s.sequence, times[i]));\n // Sequence numbers that slid out of the window are never revisited.\n if (timeline.size > segments.length * 4) {\n const keep = new Set(segments.map((s) => s.sequence));\n for (const sequence of timeline.keys()) {\n if (!keep.has(sequence)) timeline.delete(sequence);\n }\n }\n return times;\n }\n\n private durationOf(\n stream: MutableStream,\n sequence: number,\n ): number | undefined {\n for (const segment of stream.segments.values()) {\n if (segment.externalId === sequence) {\n return segment.endTime - segment.startTime;\n }\n }\n return undefined;\n }\n}\n\nfunction externalIdOf(\n s: ParsedSegment,\n protocol: ParsedManifest[\"protocol\"],\n): number {\n // See specs/segment-identity.md: HLS media sequence is canonical; a DASH\n // segment number is not available in every addressing mode, so DASH uses\n // presentation time in 100 ms units — fine enough to separate any real\n // segments, coarse enough to keep peer announcements compact.\n return protocol === \"dash\"\n ? Math.round((s.presentationTime ?? 0) * 10)\n : s.sequence;\n}\n\nfunction stripQuery(url: string): string {\n const i = url.indexOf(\"?\");\n return i === -1 ? url : url.slice(0, i);\n}\n","export const getStorageItemId = (streamId: string, segmentId: number) =>\n `${streamId}|${segmentId}`;\n\nexport const isAndroid = (userAgent: string) => /Android/i.test(userAgent);\n\nexport const isIPadOrIPhone = (userAgent: string) =>\n /iPad|iPhone/i.test(userAgent);\n\nexport const isAndroidWebview = (userAgent: string) =>\n /Android/i.test(userAgent) &&\n (/; wv\\)/i.test(userAgent) || !/Chrome|Firefox/i.test(userAgent));\n","import { CommonCoreConfig, StreamConfig, StreamType } from \"../types.js\";\nimport debug from \"debug\";\nimport { SegmentStorage } from \"./index.js\";\nimport {\n isAndroid,\n isIPadOrIPhone,\n isAndroidWebview,\n getStorageItemId,\n} from \"./utils.js\";\n\ntype SegmentDataItem = {\n segmentId: number;\n streamSwarmId: string;\n data: ArrayBuffer;\n startTime: number;\n endTime: number;\n streamType: StreamType;\n};\n\ntype Playback = {\n position: number;\n rate: number;\n};\n\ntype LastRequestedSegmentInfo = {\n streamSwarmId: string;\n segmentId: number;\n startTime: number;\n endTime: number;\n swarmId: string;\n streamType: StreamType;\n isLiveStream: boolean;\n};\n\nconst BYTES_PER_MiB = 1048576;\n\nexport class SegmentMemoryStorage implements SegmentStorage {\n private readonly userAgent = navigator.userAgent;\n private segmentMemoryStorageLimit = 4 * 1024;\n private currentStorageUsage = 0;\n\n private cache = new Map<string, SegmentDataItem>();\n private readonly logger: debug.Debugger;\n private coreConfig?: CommonCoreConfig;\n private mainStreamConfig?: StreamConfig;\n private secondaryStreamConfig?: StreamConfig;\n private currentPlayback?: Playback;\n private lastRequestedSegment?: LastRequestedSegmentInfo;\n private segmentChangeCallback?: (streamSwarmId: string) => void;\n\n constructor() {\n this.logger = debug(\"p2pml-core:segment-memory-storage\");\n this.logger.color = \"RebeccaPurple\";\n }\n\n // eslint-disable-next-line @typescript-eslint/require-await\n async initialize(\n coreConfig: CommonCoreConfig,\n mainStreamConfig: StreamConfig,\n secondaryStreamConfig: StreamConfig,\n ) {\n this.coreConfig = coreConfig;\n this.mainStreamConfig = mainStreamConfig;\n this.secondaryStreamConfig = secondaryStreamConfig;\n\n this.setMemoryStorageLimit();\n this.logger(\"initialized\");\n }\n\n onPlaybackUpdated(position: number, rate: number) {\n this.currentPlayback = { position, rate };\n }\n\n onSegmentRequested(\n swarmId: string,\n streamSwarmId: string,\n segmentId: number,\n startTime: number,\n endTime: number,\n streamType: StreamType,\n isLiveStream: boolean,\n ): void {\n this.lastRequestedSegment = {\n streamSwarmId,\n segmentId,\n startTime,\n endTime,\n swarmId,\n streamType,\n isLiveStream,\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/require-await\n async storeSegment(\n _swarmId: string,\n streamSwarmId: string,\n segmentId: number,\n data: ArrayBuffer,\n startTime: number,\n endTime: number,\n streamType: StreamType,\n isLiveStream: boolean,\n ) {\n this.clear(isLiveStream, data.byteLength);\n\n const storageId = getStorageItemId(streamSwarmId, segmentId);\n this.cache.set(storageId, {\n data,\n segmentId,\n streamSwarmId,\n startTime,\n endTime,\n streamType,\n });\n this.increaseStorageUsage(data.byteLength);\n\n this.logger(`add segment: ${segmentId} to ${streamSwarmId}`);\n\n if (!this.segmentChangeCallback) {\n throw new Error(\"dispatchStorageUpdatedEvent is not set\");\n }\n\n this.segmentChangeCallback(streamSwarmId);\n }\n\n // eslint-disable-next-line @typescript-eslint/require-await\n async getSegmentData(\n _swarmId: string,\n streamSwarmId: string,\n segmentId: number,\n ) {\n const segmentStorageId = getStorageItemId(streamSwarmId, segmentId);\n const dataItem = this.cache.get(segmentStorageId);\n\n if (dataItem === undefined) return undefined;\n\n return dataItem.data;\n }\n\n getUsage() {\n if (!this.lastRequestedSegment || !this.currentPlayback) {\n return {\n totalCapacity: this.segmentMemoryStorageLimit,\n usedCapacity: this.currentStorageUsage,\n };\n }\n const playbackPosition = this.currentPlayback.position;\n\n let calculatedUsedCapacity = 0;\n for (const { endTime, data } of this.cache.values()) {\n if (playbackPosition > endTime) continue;\n\n calculatedUsedCapacity += data.byteLength;\n }\n\n return {\n totalCapacity: this.segmentMemoryStorageLimit,\n usedCapacity: calculatedUsedCapacity / BYTES_PER_MiB,\n };\n }\n\n hasSegment(_swarmId: string, streamSwarmId: string, externalId: number) {\n const segmentStorageId = getStorageItemId(streamSwarmId, externalId);\n const segment = this.cache.get(segmentStorageId);\n\n return segment !== undefined;\n }\n\n getStoredSegmentIds(_swarmId: string, streamSwarmId: string) {\n const externalIds: number[] = [];\n\n for (const {\n segmentId,\n streamSwarmId: streamCacheId,\n } of this.cache.values()) {\n if (streamCacheId !== streamSwarmId) continue;\n externalIds.push(segmentId);\n }\n\n return externalIds;\n }\n\n private clear(isLiveStream: boolean, newSegmentSize: number) {\n if (\n !this.currentPlayback ||\n !this.mainStreamConfig ||\n !this.secondaryStreamConfig ||\n !this.coreConfig\n ) {\n return;\n }\n\n const isMemoryLimitReached = this.isMemoryLimitReached(newSegmentSize);\n\n if (!isMemoryLimitReached && !isLiveStream) return;\n\n const affectedStreams = new Set<string>();\n const sortedCache = Array.from(this.cache.values()).sort(\n (a, b) => a.startTime - b.startTime,\n );\n\n for (const segmentData of sortedCache) {\n const { streamSwarmId, segmentId, data } = segmentData;\n const storageId = getStorageItemId(streamSwarmId, segmentId);\n\n const shouldRemove = this.shouldRemoveSegment(\n segmentData,\n isLiveStream,\n this.currentPlayback.position,\n );\n\n if (!shouldRemove) continue;\n\n this.cache.delete(storageId);\n affectedStreams.add(streamSwarmId);\n this.decreaseStorageUsage(data.byteLength);\n\n this.logger(`Removed segment ${segmentId} from stream ${streamSwarmId}`);\n\n if (!this.isMemoryLimitReached(newSegmentSize) && !isLiveStream) break;\n }\n\n this.sendUpdatesToAffectedStreams(affectedStreams);\n }\n\n private isMemoryLimitReached(segmentByteLength: number) {\n return (\n this.currentStorageUsage + segmentByteLength / BYTES_PER_MiB >\n this.segmentMemoryStorageLimit\n );\n }\n\n setSegmentChangeCallback(\n callback: ((streamSwarmId: string) => void) | undefined,\n ) {\n this.segmentChangeCallback = callback;\n }\n\n private sendUpdatesToAffectedStreams(affectedStreams: Set<string>) {\n if (affectedStreams.size === 0) return;\n\n affectedStreams.forEach((stream) => {\n if (!this.segmentChangeCallback) {\n throw new Error(\"dispatchStorageUpdatedEvent is not set\");\n }\n\n this.segmentChangeCallback(stream);\n });\n }\n\n private shouldRemoveSegment(\n segmentData: SegmentDataItem,\n isLiveStream: boolean,\n currentPlaybackPosition: number,\n ): boolean {\n const { endTime, streamType } = segmentData;\n const highDemandTimeWindow = this.getStreamTimeWindow(\n streamType,\n \"highDemandTimeWindow\",\n );\n\n if (currentPlaybackPosition <= endTime) return false;\n\n if (isLiveStream) {\n return currentPlaybackPosition > highDemandTimeWindow + endTime;\n }\n\n return true;\n }\n\n private increaseStorageUsage(segmentByteLength: number) {\n this.currentStorageUsage += segmentByteLength / BYTES_PER_MiB;\n }\n\n private decreaseStorageUsage(segmentByteLength: number) {\n this.currentStorageUsage -= segmentByteLength / BYTES_PER_MiB;\n }\n\n private setMemoryStorageLimit() {\n if (this.coreConfig?.segmentMemoryStorageLimit) {\n this.segmentMemoryStorageLimit =\n this.coreConfig.segmentMemoryStorageLimit;\n return;\n }\n\n if (isAndroidWebview(this.userAgent) || isIPadOrIPhone(this.userAgent)) {\n this.segmentMemoryStorageLimit = 1024;\n } else if (isAndroid(this.userAgent)) {\n this.segmentMemoryStorageLimit = 2 * 1024;\n }\n }\n\n private getStreamTimeWindow(\n streamType: string,\n configKey: \"highDemandTimeWindow\" | \"httpDownloadTimeWindow\",\n ): number {\n const config =\n streamType === \"main\"\n ? this.mainStreamConfig\n : this.secondaryStreamConfig;\n\n return config?.[configKey] ?? 0;\n }\n\n public destroy() {\n this.cache.clear();\n this.segmentChangeCallback = undefined;\n }\n}\n","export const PACKAGE_VERSION = \"5.0.0-alpha.1\";\n","import { PACKAGE_VERSION } from \"./version.js\";\n\nexport const TRACKER_CLIENT_VERSION_PREFIX = `-PM${formatVersion(PACKAGE_VERSION)}-`;\n\nconst HASH_SYMBOLS =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\nconst PEER_ID_LENGTH = 20;\n\nexport function generatePeerId(trackerClientVersionPrefix: string): string {\n const trackerClientId = [trackerClientVersionPrefix];\n const randomCharsCount = PEER_ID_LENGTH - trackerClientVersionPrefix.length;\n\n for (let i = 0; i < randomCharsCount; i++) {\n trackerClientId.push(\n HASH_SYMBOLS[Math.floor(Math.random() * HASH_SYMBOLS.length)],\n );\n }\n\n return trackerClientId.join(\"\");\n}\n\nfunction formatVersion(versionString: string) {\n const splittedVersion = versionString.split(\".\");\n\n const v0 = `00${splittedVersion[0]}`.slice(-2);\n const v1 = `00${splittedVersion[1]}`.slice(-2);\n return `${v0}${v1}`;\n}\n","import { EventTarget } from \"../../utils/event-target.js\";\n\nexport type WebSocketClientEventMap = {\n connected: () => void;\n disconnected: () => void;\n reconnecting: () => void;\n error: (error: Event) => void;\n message: (data: ArrayBuffer | string) => void;\n};\n\nexport type WebSocketClientState =\n \"connecting\" | \"connected\" | \"reconnecting\" | \"disconnected\" | \"disposed\";\n\nexport interface WebSocketClientConfig {\n url: string;\n initialDelay?: number;\n maxDelay?: number;\n jitterMultiplier?: number;\n}\n\nexport class WebSocketClient {\n readonly #config: Required<WebSocketClientConfig>;\n\n #state: WebSocketClientState = \"disconnected\";\n #ws: WebSocket | null = null;\n #backoffCount = 0;\n #reconnectTimeoutId: ReturnType<typeof setTimeout> | null = null;\n\n readonly #eventTarget = new EventTarget<WebSocketClientEventMap>();\n\n constructor(config: WebSocketClientConfig) {\n const initialDelay = Math.max(100, config.initialDelay ?? 1000);\n\n this.#config = {\n url: config.url,\n initialDelay,\n // Ensure maxDelay is never less than initialDelay\n maxDelay: Math.max(initialDelay, config.maxDelay ?? 30000),\n jitterMultiplier: Math.max(0, config.jitterMultiplier ?? 0.2),\n };\n }\n\n public get state(): WebSocketClientState {\n return this.#state;\n }\n\n public addEventListener<K extends keyof WebSocketClientEventMap>(\n eventName: K,\n listener: WebSocketClientEventMap[K],\n ): void {\n this.#eventTarget.addEventListener(eventName, listener);\n }\n\n public removeEventListener<K extends keyof WebSocketClientEventMap>(\n eventName: K,\n listener: WebSocketClientEventMap[K],\n ): void {\n this.#eventTarget.removeEventListener(eventName, listener);\n }\n\n public connect(): void {\n if (\n this.#state === \"connected\" ||\n this.#state === \"connecting\" ||\n this.#state === \"disposed\"\n ) {\n return;\n }\n\n this.#state = \"connecting\";\n this.#clearReconnectTimeout();\n\n try {\n this.#ws = new WebSocket(this.#config.url);\n this.#ws.binaryType = \"arraybuffer\";\n\n this.#ws.onopen = this.#onOpen;\n this.#ws.onclose = this.#onClose;\n this.#ws.onerror = this.#onError;\n this.#ws.onmessage = this.#onMessage;\n } catch (error) {\n this.#state = \"disconnected\";\n const errorEvent = new ErrorEvent(\"error\", {\n message:\n error instanceof Error\n ? error.message\n : \"Unknown WebSocket creation error\",\n error,\n });\n this.#eventTarget.dispatchEvent(\"error\", errorEvent);\n }\n }\n\n public send(\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments\n data: string | ArrayBuffer | Blob | ArrayBufferView<ArrayBuffer>,\n ): void {\n if (this.#state !== \"connected\" || !this.#ws) {\n throw new Error(\"WebSocketClient: Cannot send data when not connected\");\n }\n this.#ws.send(data);\n }\n\n public dispose(): void {\n this.#state = \"disposed\";\n this.#clearReconnectTimeout();\n\n if (this.#ws) {\n this.#ws.onopen = null;\n this.#ws.onclose = null;\n this.#ws.onerror = null;\n this.#ws.onmessage = null;\n this.#ws.close();\n this.#ws = null;\n }\n this.#eventTarget.clear();\n }\n\n #onOpen = (): void => {\n if (this.#state === \"disposed\") return;\n this.#state = \"connected\";\n this.#backoffCount = 0;\n this.#eventTarget.dispatchEvent(\"connected\");\n };\n\n #onClose = (): void => {\n if (this.#state === \"disposed\") return;\n if (this.#ws) {\n this.#ws.onopen = null;\n this.#ws.onclose = null;\n this.#ws.onerror = null;\n this.#ws.onmessage = null;\n this.#ws = null;\n }\n this.#scheduleReconnect();\n this.#eventTarget.dispatchEvent(\"disconnected\");\n };\n\n #onError = (event: Event): void => {\n if (this.#state === \"disposed\") return;\n this.#eventTarget.dispatchEvent(\"error\", event);\n };\n\n #onMessage = (event: MessageEvent<ArrayBuffer | string>): void => {\n if (this.#state === \"disposed\") return;\n this.#eventTarget.dispatchEvent(\"message\", event.data);\n };\n\n #scheduleReconnect(): void {\n if (this.#state === \"disposed\") return;\n\n this.#state = \"reconnecting\";\n\n const baseDelay = Math.min(\n this.#config.initialDelay * Math.pow(2, this.#backoffCount),\n this.#config.maxDelay,\n );\n\n const jitter = baseDelay * this.#config.jitterMultiplier;\n const randomJitter = Math.random() * 2 * jitter - jitter;\n const delay = Math.max(0, baseDelay + randomJitter);\n\n if (baseDelay < this.#config.maxDelay) {\n this.#backoffCount++;\n }\n\n this.#reconnectTimeoutId = setTimeout(() => {\n if (this.#state !== \"disposed\") {\n this.connect();\n }\n }, delay);\n\n this.#eventTarget.dispatchEvent(\"reconnecting\");\n }\n\n #clearReconnectTimeout(): void {\n if (this.#reconnectTimeoutId !== null) {\n clearTimeout(this.#reconnectTimeoutId);\n this.#reconnectTimeoutId = null;\n }\n }\n}\n","import { WebSocketClient } from \"../websocket-client/index.js\";\nimport { EventTarget } from \"../../utils/event-target.js\";\n\nexport type WebTorrentSocketPoolEventMap = {\n error: (error: Event, url: string) => void;\n};\n\ntype PoolEntry = {\n client: WebSocketClient;\n refCount: number;\n};\n\nexport class WebTorrentSocketPool {\n readonly #sockets = new Map<string, PoolEntry>();\n readonly #eventTarget = new EventTarget<WebTorrentSocketPoolEventMap>();\n\n public addEventListener<K extends keyof WebTorrentSocketPoolEventMap>(\n eventName: K,\n listener: WebTorrentSocketPoolEventMap[K],\n ): void {\n this.#eventTarget.addEventListener(eventName, listener);\n }\n\n public removeEventListener<K extends keyof WebTorrentSocketPoolEventMap>(\n eventName: K,\n listener: WebTorrentSocketPoolEventMap[K],\n ): void {\n this.#eventTarget.removeEventListener(eventName, listener);\n }\n\n public acquire(url: string): {\n client: WebSocketClient;\n release: () => void;\n } {\n let entry = this.#sockets.get(url);\n\n if (!entry) {\n const client = new WebSocketClient({ url });\n client.addEventListener(\"error\", (error) => {\n this.#eventTarget.dispatchEvent(\"error\", error, url);\n });\n client.connect();\n entry = { client, refCount: 0 };\n this.#sockets.set(url, entry);\n }\n\n entry.refCount++;\n\n let isReleased = false;\n\n return {\n client: entry.client,\n release: () => {\n if (isReleased) return;\n isReleased = true;\n\n entry.refCount--;\n\n if (entry.refCount <= 0) {\n if (entry.refCount < 0) {\n // eslint-disable-next-line no-console\n console.error(\n `[WebTorrentSocketPool] Negative refCount detected for ${url}`,\n );\n }\n const currentEntry = this.#sockets.get(url);\n if (currentEntry === entry) {\n this.#sockets.delete(url);\n }\n entry.client.dispose();\n }\n },\n };\n }\n\n public destroy(): void {\n this.#eventTarget.clear();\n const entries = Array.from(this.#sockets.values());\n this.#sockets.clear();\n for (const entry of entries) {\n try {\n entry.client.dispose();\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\n \"[WebTorrentSocketPool] Failed to dispose WebSocketClient:\",\n error,\n );\n }\n }\n }\n}\n","import { HybridLoader } from \"./hybrid-loader.js\";\nimport type { PlaybackState } from \"./playback.js\";\nimport type { ManifestParser, ManifestProtocol } from \"./manifest/types.js\";\nimport {\n ManifestRegistry,\n type RegistryStream,\n type RegistryUpdate,\n} from \"./manifest/registry.js\";\nimport { segmentKey } from \"./manifest/url-key.js\";\nimport { parseSidx } from \"./manifest/mp4-sidx.js\";\nimport debug from \"debug\";\nimport {\n Stream,\n ByteRange,\n CoreConfig,\n CoreEventMap,\n CoreRequestError,\n DynamicCoreConfig,\n CommonCoreConfig,\n StreamConfig,\n DefinedCoreConfig,\n SegmentResponse,\n StreamProperties,\n StreamType,\n DynamicStreamConfig,\n ProcessedManifest,\n} from \"./types.js\";\nimport {\n BandwidthCalculators,\n EngineCallbacks,\n StreamDetails,\n StreamWithSegments,\n SegmentWithStream,\n} from \"./internal-types.js\";\nimport * as StreamUtils from \"./utils/stream.js\";\nimport {\n buildStreamSwarmId,\n computeInfoHash,\n PEER_PROTOCOL_VERSION,\n} from \"./stream-identity.js\";\nimport { BandwidthCalculator } from \"./bandwidth-calculator.js\";\nimport { SegmentMemoryStorage } from \"./segment-storage/segment-memory-storage.js\";\nimport { EventTarget } from \"./utils/event-target.js\";\nimport {\n overrideConfig,\n mergeAndFilterConfig,\n deepCopy,\n filterUndefinedProps,\n} from \"./utils/utils.js\";\nimport { TRACKER_CLIENT_VERSION_PREFIX, generatePeerId } from \"./utils/peer.js\";\nimport { SegmentStorage } from \"./segment-storage/index.js\";\nimport { WebTorrentSocketPool } from \"./webtorrent/webtorrent-socket-pool/index.js\";\n\n/** Core class for managing media streams loading via P2P. */\nexport class Core {\n /** Default configuration for common core settings. */\n static readonly DEFAULT_COMMON_CORE_CONFIG: CommonCoreConfig = {\n segmentMemoryStorageLimit: undefined,\n customSegmentStorageFactory: undefined,\n trackerClientVersionPrefix: TRACKER_CLIENT_VERSION_PREFIX,\n };\n\n /** Default configuration for stream settings. */\n static readonly DEFAULT_STREAM_CONFIG: StreamConfig = {\n isP2PUploadDisabled: false,\n isP2PDisabled: false,\n simultaneousHttpDownloads: 2,\n simultaneousP2PDownloads: 3,\n highDemandTimeWindow: 15,\n httpDownloadInitialTimeoutMs: 0,\n httpDownloadTimeWindow: 3000,\n p2pDownloadTimeWindow: 6000,\n webRtcMaxMessageSize: 64 * 1024 - 1,\n p2pNotReceivingBytesTimeoutMs: 2000,\n p2pInactiveLoaderDestroyTimeoutMs: 30 * 1000,\n httpNotReceivingBytesTimeoutMs: 3000,\n httpErrorRetries: 3,\n p2pErrorRetries: 3,\n announceTrackers: [\n \"wss://tracker.webtorrent.dev\",\n \"wss://tracker.openwebtorrent.com\",\n ],\n rtcConfig: {\n iceServers: [\n { urls: \"stun:stun.l.google.com:19302\" },\n { urls: \"stun:global.stun.twilio.com:3478\" },\n ],\n },\n validateP2PSegment: undefined,\n validateHTTPSegment: undefined,\n httpRequestSetup: undefined,\n swarmId: undefined,\n streamSwarmIdBuilder: undefined,\n p2pMaxPeers: 50,\n p2pChurnMaxPeersMultiplier: 1.5,\n p2pChurnCleanupIntervalMs: 30000,\n p2pChurnGracePeriodMs: 15000,\n webRtcOffersCount: 5,\n webRtcOfferTimeoutMs: 50000,\n webRtcIceGatheringTimeoutMs: 5000,\n webRtcConnectionTimeoutMs: 15000,\n };\n\n private readonly eventTarget = new EventTarget<CoreEventMap>();\n private manifestResponseUrl?: string;\n /** Registered streams, keyed by the manifest-derived stream key. */\n private readonly streams = new Map<string, StreamWithSegments>();\n /** Stream keys whose registration failed; reported once, then left alone. */\n private readonly failedStreamKeys = new Set<string>();\n /**\n * Initialization segments, recognised so a request for one is passed\n * through knowingly rather than counted as a registry miss. Never shared.\n * See specs/manifest-registry.md, \"Initialization segments\".\n */\n private readonly initSegmentKeys = new Set<string>();\n private mainStreamConfig: StreamConfig;\n private secondaryStreamConfig: StreamConfig;\n private commonCoreConfig: CommonCoreConfig;\n private readonly bandwidthCalculators: BandwidthCalculators = {\n all: new BandwidthCalculator(),\n http: new BandwidthCalculator(),\n };\n private segmentStorage?: SegmentStorage;\n private readonly webTorrentSocketPool = new WebTorrentSocketPool();\n private readonly logger = debug(\"p2pml-core:core\");\n private readonly socketPoolLogger = debug(\n \"p2pml-core:webtorrent-socket-pool\",\n );\n private readonly peerId: string;\n private mainStreamLoader?: HybridLoader;\n private secondaryStreamLoader?: HybridLoader;\n private streamDetails: StreamDetails = { isLive: false };\n private storageInitPromise?: Promise<void>;\n private readonly manifestParsers: readonly ManifestParser[];\n private manifestRegistry = new ManifestRegistry();\n private readonly manifestLogger = debug(\"p2pml-core:manifest\");\n private readonly registryMissLogger = debug(\"p2pml-core:registry-miss\");\n\n /**\n * Constructs a new Core instance with optional initial configuration.\n *\n * @param config - Optional partial configuration to override default settings.\n *\n * @example\n * // Create a Core instance with custom configuration for HTTP and P2P downloads.\n * const core = new Core({\n * simultaneousHttpDownloads: 5,\n * simultaneousP2PDownloads: 5,\n * httpErrorRetries: 5,\n * p2pErrorRetries: 5\n * });\n *\n * @example\n * // Create a Core instance using the default configuration.\n * const core = new Core();\n */\n constructor(config?: Partial<CoreConfig>) {\n const filteredConfig = filterUndefinedProps(config ?? {});\n\n this.commonCoreConfig = mergeAndFilterConfig<CommonCoreConfig>({\n defaultConfig: Core.DEFAULT_COMMON_CORE_CONFIG,\n baseConfig: filteredConfig,\n });\n\n this.mainStreamConfig = mergeAndFilterConfig<StreamConfig>({\n defaultConfig: Core.DEFAULT_STREAM_CONFIG,\n baseConfig: filteredConfig,\n specificStreamConfig: filteredConfig.mainStream,\n });\n\n this.secondaryStreamConfig = mergeAndFilterConfig<StreamConfig>({\n defaultConfig: Core.DEFAULT_STREAM_CONFIG,\n baseConfig: filteredConfig,\n specificStreamConfig: filteredConfig.secondaryStream,\n });\n\n this.peerId = generatePeerId(\n this.commonCoreConfig.trackerClientVersionPrefix,\n );\n\n // Parsers are capabilities, not tunables: kept as given, outside the\n // merged config, so they are never deep-copied or surfaced by getConfig().\n this.manifestParsers = config?.manifestParsers ?? [];\n\n this.webTorrentSocketPool.addEventListener(\"error\", (error, url) => {\n this.socketPoolLogger(`WebSocket error for tracker url ${url}:`, error);\n });\n }\n\n /**\n * Retrieves the current configuration for the core instance, ensuring immutability.\n *\n * @returns A deep readonly version of the core configuration.\n */\n getConfig(): DefinedCoreConfig {\n return {\n ...deepCopy(this.commonCoreConfig),\n mainStream: deepCopy(this.mainStreamConfig),\n secondaryStream: deepCopy(this.secondaryStreamConfig),\n };\n }\n\n /**\n * Applies a set of dynamic configuration updates to the core, merging with the existing configuration.\n *\n * @param dynamicConfig - A set of configuration changes to apply.\n *\n * @example\n * // Example of dynamically updating the download time windows and timeout settings.\n * const dynamicConfig = {\n * httpDownloadTimeWindow: 60, // Set HTTP download time window to 60 seconds\n * p2pDownloadTimeWindow: 60, // Set P2P download time window to 60 seconds\n * httpNotReceivingBytesTimeoutMs: 1500, // Set HTTP timeout to 1500 milliseconds\n * p2pNotReceivingBytesTimeoutMs: 1500 // Set P2P timeout to 1500 milliseconds\n * };\n * core.applyDynamicConfig(dynamicConfig);\n */\n applyDynamicConfig(dynamicConfig: DynamicCoreConfig) {\n const { mainStream, secondaryStream } = dynamicConfig;\n\n const mainStreamConfigCopy = deepCopy(this.mainStreamConfig);\n const secondaryStreamConfigCopy = deepCopy(this.secondaryStreamConfig);\n\n this.overrideAllConfigs(dynamicConfig, mainStream, secondaryStream);\n\n this.processSpecificDynamicConfigParams(\n mainStreamConfigCopy,\n dynamicConfig,\n \"main\",\n );\n this.processSpecificDynamicConfigParams(\n secondaryStreamConfigCopy,\n dynamicConfig,\n \"secondary\",\n );\n }\n\n private processSpecificDynamicConfigParams(\n prevConfig: StreamConfig,\n updatedConfig: DynamicCoreConfig,\n streamType: StreamType,\n ) {\n const isP2PDisabled = this.getUpdatedStreamProperty(\n \"isP2PDisabled\",\n updatedConfig,\n streamType,\n );\n\n if (isP2PDisabled && prevConfig.isP2PDisabled !== isP2PDisabled) {\n this.destroyStreamLoader(streamType);\n }\n\n const isP2PUploadDisabled = this.getUpdatedStreamProperty(\n \"isP2PUploadDisabled\",\n updatedConfig,\n streamType,\n );\n\n if (\n isP2PUploadDisabled !== undefined &&\n prevConfig.isP2PUploadDisabled !== isP2PUploadDisabled\n ) {\n const streamLoader =\n streamType === \"main\"\n ? this.mainStreamLoader\n : this.secondaryStreamLoader;\n\n streamLoader?.sendBroadcastAnnouncement(isP2PUploadDisabled);\n }\n }\n\n private getUpdatedStreamProperty<K extends keyof DynamicStreamConfig>(\n propertyName: K,\n updatedConfig: DynamicCoreConfig,\n streamType: StreamType,\n ): DynamicStreamConfig[K] | undefined {\n const updatedStreamConfig =\n streamType === \"main\"\n ? updatedConfig.mainStream\n : updatedConfig.secondaryStream;\n\n return updatedStreamConfig?.[propertyName] ?? updatedConfig[propertyName];\n }\n\n /**\n * Adds an event listener for the specified event type on the core event target.\n *\n * @param eventName - The name of the event to listen for.\n * @param listener - The callback function to invoke when the event is fired.\n */\n addEventListener<K extends keyof CoreEventMap>(\n eventName: K,\n listener: CoreEventMap[K],\n ) {\n this.eventTarget.addEventListener(eventName, listener);\n }\n\n /**\n * Removes an event listener for the specified event type on the core event target.\n *\n * @param eventName - The name of the event to listen for.\n * @param listener - The callback function to be removed.\n */\n removeEventListener<K extends keyof CoreEventMap>(\n eventName: K,\n listener: CoreEventMap[K],\n ) {\n this.eventTarget.removeEventListener(eventName, listener);\n }\n\n /**\n * Names the swarm explicitly, in place of the first manifest's response URL.\n *\n * By default the swarm ID is the URL of the first manifest handed to\n * `processManifest`, with its entire query string discarded. An integration\n * that knows a better name — one shared by every viewer regardless of CDN\n * or redirect — may set it here before the first manifest arrives, or\n * configure `swarmId` instead. See specs/segment-identity.md.\n *\n * @param url - The full URL to the manifest response.\n */\n setManifestResponseUrl(url: string): void {\n this.manifestResponseUrl = stripQuery(url);\n }\n\n /**\n * Parses a manifest the player has fetched and brings the registry up to\n * date: streams are registered with their identity, their segments are\n * added and removed by URL key, and the live state is derived. This is the\n * only way streams and segments enter the core. See\n * specs/manifest-registry.md.\n *\n * Never throws. A manifest with no matching parser is ignored, and a parse\n * failure leaves the registry as it was — a transient bad response must not\n * empty a working segment list. Idempotent: re-processing an unchanged\n * manifest changes nothing and emits no events.\n *\n * @returns What the manifest described — each stream it listed segments\n * for, with the bounds of those segments on the manifest timeline — so an\n * adapter can size its player's live window from the same parse; or\n * `undefined` when the manifest was ignored or failed to parse.\n */\n processManifest(manifest: {\n url: string;\n /** Text, or the raw bytes a player's networking layer delivers. */\n data: string | ArrayBuffer | ArrayBufferView;\n protocol?: ManifestProtocol;\n }): ProcessedManifest | undefined {\n const text =\n typeof manifest.data === \"string\"\n ? manifest.data\n : new TextDecoder().decode(manifest.data);\n\n const parser = manifest.protocol\n ? this.manifestParsers.find((p) => p.protocol === manifest.protocol)\n : this.manifestParsers.find((p) => p.canParse(text));\n if (!parser) {\n this.manifestLogger(\"no parser for manifest %s\", manifest.url);\n return undefined;\n }\n\n let updates;\n try {\n updates = this.manifestRegistry.apply(parser.parse(text, manifest.url));\n } catch (error) {\n this.manifestLogger(\"failed to parse %s: %O\", manifest.url, error);\n return undefined;\n }\n\n // The first manifest names the swarm unless the integration already did.\n this.manifestResponseUrl ??= stripQuery(manifest.url);\n\n this.syncStreamsFromRegistry();\n\n this.logRegistryUpdates(manifest.url, updates);\n return summarize(updates);\n }\n\n /**\n * Resolves a stream's external segment index — the `sidx` box of a DASH\n * `SegmentBase` representation — from the bytes the player fetched for it.\n * The stream, registered from the MPD without segments, gains them here.\n * See specs/manifest-registry.md, \"Resolving an external index\".\n *\n * Never throws. Data with no parsable `sidx` box, or for which no stream is\n * waiting, changes nothing.\n *\n * @param index.url - The media file the index was read from.\n * @param index.byteRange - The range that was fetched, if the request had one.\n * @param index.data - The response body, which may be wider than the index.\n * @returns The streams that gained segments, or `undefined` when none did.\n */\n processSegmentIndex(index: {\n url: string;\n byteRange?: ByteRange;\n data: ArrayBuffer | ArrayBufferView;\n }): ProcessedManifest | undefined {\n const sidx = parseSidx(index.data);\n if (!sidx) {\n this.manifestLogger(\n \"no sidx box in the index fetched from %s\",\n index.url,\n );\n return undefined;\n }\n\n const updates = this.manifestRegistry.resolveExternalIndex(\n index.url,\n index.byteRange,\n sidx,\n );\n if (!updates.length) {\n this.manifestLogger(\"no stream awaits an index at %s\", index.url);\n return undefined;\n }\n\n this.syncStreamsFromRegistry();\n this.logRegistryUpdates(index.url, updates);\n return summarize(updates);\n }\n\n /**\n * Whether a request is for a registered stream's external segment index —\n * the `sidx` range of a DASH `SegmentBase` representation. Such a request\n * is not a media segment: the adapter lets the player load it and hands the\n * response to `processSegmentIndex`.\n *\n * @param url - The URL the player is about to request.\n * @param byteRange - Its byte range, if any; a range covering the index counts.\n */\n isSegmentIndex(url: string, byteRange?: ByteRange): boolean {\n return (\n this.manifestRegistry.streamsAwaitingIndex(url, byteRange).length > 0\n );\n }\n\n private logRegistryUpdates(url: string, updates: RegistryUpdate[]): void {\n if (!this.manifestLogger.enabled) return;\n const changed = updates.filter((u) => u.added || u.removed);\n this.manifestLogger(\n \"%s — %d streams registered, %s\",\n url,\n this.streams.size,\n changed.length\n ? changed\n .map((u) => `${u.streamKey}: +${u.added} -${u.removed}`)\n .join(\", \")\n : \"no segment changes\",\n );\n }\n\n /**\n * Makes the registered streams mirror the manifest registry: registers\n * streams the registry has and the core does not, and diffs every stream's\n * segments by URL key. A stream whose registration failed is skipped.\n */\n private syncStreamsFromRegistry(): void {\n let isLive = false;\n for (const registryStream of this.manifestRegistry.getStreams()) {\n isLive ||= registryStream.isLive === true;\n\n if (registryStream.initSegment) {\n const { url, byteRange } = registryStream.initSegment;\n this.initSegmentKeys.add(segmentKey(url, byteRange));\n }\n\n let stream = this.streams.get(registryStream.key);\n if (!stream) {\n if (this.failedStreamKeys.has(registryStream.key)) continue;\n stream = this.registerStream(registryStream);\n if (!stream) continue;\n }\n this.syncSegments(stream, registryStream);\n }\n this.streamDetails.isLive = isLive;\n }\n\n private syncSegments(\n stream: StreamWithSegments,\n registryStream: RegistryStream,\n ): void {\n let changed = false;\n for (const key of stream.segments.keys()) {\n if (!registryStream.segments.has(key)) {\n stream.segments.delete(key);\n changed = true;\n }\n }\n for (const [key, segment] of registryStream.segments) {\n if (stream.segments.has(key)) continue;\n stream.segments.set(key, {\n runtimeId: key,\n externalId: segment.externalId,\n url: segment.url,\n byteRange: segment.byteRange,\n startTime: segment.startTime,\n endTime: segment.endTime,\n stream,\n });\n changed = true;\n }\n if (!changed) return;\n this.mainStreamLoader?.updateStream(stream);\n this.secondaryStreamLoader?.updateStream(stream);\n }\n\n /**\n * Whether a segment request resolves against the registry.\n *\n * @param url - The URL the player is about to request.\n * @param byteRange - Its byte range, when the segment is a range of a file.\n * @returns `true` if the registry knows the segment, otherwise `false`.\n */\n hasSegment(url: string, byteRange?: ByteRange): boolean {\n return !!StreamUtils.getSegmentFromStreamsMap(\n this.streams,\n segmentKey(url, byteRange),\n );\n }\n\n /**\n * Retrieves a registered stream by its key, if it exists.\n *\n * @param streamRuntimeId - The stream key: the media playlist URL for HLS,\n * the Representation id for DASH.\n * @returns A detached snapshot of the registered stream with its computed\n * identity, or `undefined` if not found. The identity fields never change\n * after registration, so the snapshot stays accurate for the stream's lifetime.\n */\n getStream(streamRuntimeId: string): Stream | undefined {\n const stream = this.streams.get(streamRuntimeId);\n return stream && this.toStreamSnapshot(stream);\n }\n\n /**\n * Retrieves all currently registered streams with their computed identities,\n * including the infohashes announced to trackers. Unlike the `onStreamAdded`\n * event, this reflects the full set at any moment, so late subscribers can\n * catch up on streams registered before they attached.\n *\n * @returns Detached snapshots of the registered streams, in registration order.\n */\n getStreams(): Stream[] {\n return Array.from(this.streams.values(), (stream) =>\n this.toStreamSnapshot(stream),\n );\n }\n\n /**\n * Builds a detached snapshot of a registered stream: its identity and\n * integration-specific fields without the internal segments registry.\n * Everything the core hands out — event payloads and getters — is a\n * snapshot, so consumers can never reach or retain core state.\n */\n private toStreamSnapshot(stream: StreamWithSegments): Stream {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { segments, ...snapshot } = stream;\n return snapshot;\n }\n\n /**\n * Registers a stream the manifest registry produced, computing its identity\n * (`swarmId`, `identityHash`, `streamSwarmId`, `infoHash`) exactly once.\n *\n * Never throws: a stream that fails to register (an invalid or colliding\n * custom stream swarm ID) stays unknown to the core — its segments load\n * through the player's default path without P2P — and the failure is\n * reported once via the `onStreamRegistrationError` event.\n */\n private registerStream(\n registryStream: RegistryStream,\n ): StreamWithSegments | undefined {\n const properties = Object.freeze({ ...registryStream.properties });\n try {\n return this.addStream(registryStream, properties);\n } catch (error) {\n this.failedStreamKeys.add(registryStream.key);\n this.logger(\n \"failed to register stream %s: %O\",\n registryStream.key,\n error,\n );\n this.eventTarget.dispatchEvent(\"onStreamRegistrationError\", {\n runtimeId: registryStream.key,\n streamType: registryStream.type,\n properties,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n return undefined;\n }\n }\n\n private addStream(\n stream: RegistryStream,\n properties: Readonly<StreamProperties>,\n ): StreamWithSegments {\n const config =\n stream.type === \"main\"\n ? this.mainStreamConfig\n : this.secondaryStreamConfig;\n\n const swarmId = config.swarmId ?? this.manifestResponseUrl;\n if (swarmId === undefined) {\n throw new Error(\n \"Failed to register stream: no swarmId is configured and no manifest has named the swarm.\",\n );\n }\n\n // Computed by the registry from the whole manifest: bitrate is part of it\n // only where the manifest needs it to tell same-type streams apart.\n const { identityHash } = stream;\n\n let streamSwarmId = buildStreamSwarmId(swarmId, stream.type, identityHash);\n if (config.streamSwarmIdBuilder) {\n const customStreamSwarmId = config.streamSwarmIdBuilder({\n swarmId,\n runtimeId: stream.key,\n streamType: stream.type,\n properties,\n identityHash,\n defaultStreamSwarmId: streamSwarmId,\n peerProtocolVersion: PEER_PROTOCOL_VERSION,\n });\n\n if (customStreamSwarmId !== undefined) {\n if (\n typeof customStreamSwarmId !== \"string\" ||\n customStreamSwarmId === \"\"\n ) {\n throw new Error(\n \"streamSwarmIdBuilder must return a non-empty string or undefined\",\n );\n }\n streamSwarmId = customStreamSwarmId;\n }\n }\n\n for (const registered of this.streams.values()) {\n if (registered.streamSwarmId !== streamSwarmId) continue;\n // Sharing a stream swarm ID is only legitimate for streams with the same\n // default identity (e.g. the same rendition served from multiple CDNs).\n // A stream's identity is the whole (swarmId, type, identityHash) tuple —\n // identityHash alone excludes type and swarmId, so comparing it is not\n // enough. If any part differs, a custom builder has merged distinct\n // streams into one swarm and peers would exchange wrong-stream segments.\n if (\n registered.swarmId !== swarmId ||\n registered.type !== stream.type ||\n registered.identityHash !== identityHash\n ) {\n throw new Error(\n `streamSwarmIdBuilder produced the same stream swarm ID (\"${streamSwarmId}\") for streams with different identities. Peers of these streams would exchange segments of the wrong stream.`,\n );\n }\n }\n\n const registeredStream: StreamWithSegments = {\n runtimeId: stream.key,\n type: stream.type,\n properties,\n swarmId,\n identityHash,\n streamSwarmId,\n infoHash: computeInfoHash(streamSwarmId),\n segments: new Map<string, SegmentWithStream>(),\n };\n\n this.streams.set(stream.key, registeredStream);\n\n this.eventTarget.dispatchEvent(\"onStreamAdded\", {\n stream: this.toStreamSnapshot(registeredStream),\n });\n return registeredStream;\n }\n\n /**\n * Loads a segment the player requested, from a peer, from the segment\n * store, or over HTTP. Initializes segment storage if it has not been\n * initialized yet.\n *\n * @param url - The URL the player is requesting.\n * @param options.byteRange - Its byte range, when the segment is a range of a file.\n * @param options.signal - Aborts the request. Environments without\n * `AbortController` may call `abortSegmentLoading` instead.\n * @returns The segment bytes and the bandwidth they were fetched at.\n * @throws {CoreRequestError} `\"aborted\"` when cancelled, `\"failed\"` when\n * every source failed.\n * @throws {Error} If the segment is not in the registry; check\n * `isSegmentLoadable` first.\n */\n async loadSegment(\n url: string,\n options: { byteRange?: ByteRange; signal?: AbortSignal } = {},\n ): Promise<SegmentResponse> {\n const key = segmentKey(url, options.byteRange);\n const { signal } = options;\n if (signal?.aborted) throw new CoreRequestError(\"aborted\");\n\n await this.initializeSegmentStorage();\n if (signal?.aborted) throw new CoreRequestError(\"aborted\");\n\n const segment = this.identifySegment(key);\n const loader = this.getStreamHybridLoader(segment);\n\n return new Promise<SegmentResponse>((resolve, reject) => {\n const callbacks: EngineCallbacks = {\n onSuccess: (response) => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(response);\n },\n onError: (error) => {\n signal?.removeEventListener(\"abort\", onAbort);\n reject(error);\n },\n };\n const onAbort = () => loader.abortSegmentRequest(key);\n signal?.addEventListener(\"abort\", onAbort);\n void loader.loadSegment(segment, callbacks);\n });\n }\n\n /**\n * Aborts a pending `loadSegment` request. The request's promise rejects\n * with a `CoreRequestError` of type `\"aborted\"`.\n *\n * @param url - The URL the request was made with.\n * @param byteRange - The byte range the request was made with, if any.\n */\n abortSegmentLoading(url: string, byteRange?: ByteRange): void {\n const key = segmentKey(url, byteRange);\n this.mainStreamLoader?.abortSegmentRequest(key);\n this.secondaryStreamLoader?.abortSegmentRequest(key);\n }\n\n /**\n * Reports the player's playback state to the stream loaders.\n *\n * Only the buffer ahead of the playhead and the rate are needed — never the\n * absolute position. See `getPlaybackStateFromMediaElement` for the browser\n * case, and specs/playback-contract.md for why.\n *\n * @param state - The current playback state.\n */\n updatePlayback(state: PlaybackState): void {\n this.mainStreamLoader?.updatePlayback(state);\n this.secondaryStreamLoader?.updatePlayback(state);\n }\n\n /**\n * Whether the core will serve a request for this segment: it is in the\n * registry and P2P is enabled for its stream type. This is the check an\n * adapter makes before routing a request through `loadSegment`; a `false`\n * means \"use the player's own loader\".\n *\n * A request for a URL the registry does not know is reported through the\n * `onSegmentRegistryMiss` event, so a disagreement between the core's parse\n * and the player's is observable. Initialization segments are recognised\n * and passed through without a report; they are never shared.\n *\n * @param url - The URL the player is about to request.\n * @param byteRange - Its byte range, when the segment is a range of a file.\n */\n isSegmentLoadable(url: string, byteRange?: ByteRange): boolean {\n const key = segmentKey(url, byteRange);\n const segment = StreamUtils.getSegmentFromStreamsMap(this.streams, key);\n if (!segment) {\n // Initialization segments and external indexes are recognised and\n // passed through knowingly; only an unknown URL is a miss.\n if (\n !this.initSegmentKeys.has(key) &&\n !this.isSegmentIndex(url, byteRange)\n ) {\n // Logged as well as dispatched: a miss makes the segment load without\n // P2P and leaves no other trace, so without this a stream that stops\n // sharing looks the same as one with no peers.\n this.registryMissLogger(\"%s\", key);\n this.eventTarget.dispatchEvent(\"onSegmentRegistryMiss\", {\n url,\n byteRange,\n });\n }\n return false;\n }\n\n const config =\n segment.stream.type === \"main\"\n ? this.mainStreamConfig\n : this.secondaryStreamConfig;\n return !config.isP2PDisabled;\n }\n\n /**\n * Cleans up resources used by the Core instance, including destroying any active stream loaders\n * and clearing stored segments.\n *\n * Event listeners deliberately survive: the player integrations reuse one\n * Core instance across media sources, destroying it between loads, and\n * subscriptions (e.g. `onStreamAdded`, `onPeerConnect`) are expected to\n * keep working after the next source loads. Use `removeEventListener` to\n * unsubscribe explicitly.\n */\n destroy(): void {\n this.manifestRegistry = new ManifestRegistry();\n this.streams.clear();\n this.failedStreamKeys.clear();\n this.initSegmentKeys.clear();\n this.mainStreamLoader?.destroy();\n this.secondaryStreamLoader?.destroy();\n this.segmentStorage?.setSegmentChangeCallback(undefined);\n this.segmentStorage?.destroy();\n this.mainStreamLoader = undefined;\n this.secondaryStreamLoader = undefined;\n this.segmentStorage = undefined;\n this.manifestResponseUrl = undefined;\n this.streamDetails = { isLive: false };\n this.storageInitPromise = undefined;\n this.webTorrentSocketPool.destroy();\n }\n\n private async initializeSegmentStorage() {\n if (this.segmentStorage) return;\n if (this.storageInitPromise) return this.storageInitPromise;\n\n this.storageInitPromise = (async () => {\n const { isLive } = this.streamDetails;\n const createCustomStorage =\n this.commonCoreConfig.customSegmentStorageFactory;\n\n if (createCustomStorage && typeof createCustomStorage !== \"function\") {\n throw new Error(\"Storage configuration is invalid\");\n }\n\n const segmentStorage = createCustomStorage\n ? createCustomStorage(isLive)\n : new SegmentMemoryStorage();\n\n try {\n await segmentStorage.initialize(\n this.commonCoreConfig,\n this.mainStreamConfig,\n this.secondaryStreamConfig,\n );\n } catch (error) {\n segmentStorage.destroy();\n throw error;\n }\n\n if (!this.storageInitPromise) {\n segmentStorage.setSegmentChangeCallback(undefined);\n segmentStorage.destroy();\n return;\n }\n\n segmentStorage.setSegmentChangeCallback((streamSwarmId: string) => {\n (\n this.eventTarget as unknown as EventTarget<\n CoreEventMap & Record<`onStorageUpdated-${string}`, () => void>\n >\n ).dispatchEvent(`onStorageUpdated-${streamSwarmId}`);\n });\n\n this.segmentStorage = segmentStorage;\n })();\n\n try {\n await this.storageInitPromise;\n } finally {\n this.storageInitPromise = undefined;\n }\n }\n\n private identifySegment(key: string): SegmentWithStream {\n const segment = StreamUtils.getSegmentFromStreamsMap(this.streams, key);\n if (!segment) {\n throw new Error(`Segment is not in the registry: ${key}`);\n }\n return segment;\n }\n\n private overrideAllConfigs(\n dynamicConfig: DynamicCoreConfig,\n mainStream?: Partial<StreamConfig>,\n secondaryStream?: Partial<StreamConfig>,\n ) {\n // Stream identity is derived from these properties once, at stream\n // registration; changing them at runtime would silently desynchronize\n // the announced swarms from the registered streams.\n const sanitizedDynamicConfig = this.stripStaticOnlyProps(dynamicConfig);\n const sanitizedMainStream =\n mainStream && this.stripStaticOnlyProps(mainStream);\n const sanitizedSecondaryStream =\n secondaryStream && this.stripStaticOnlyProps(secondaryStream);\n\n overrideConfig(this.commonCoreConfig, sanitizedDynamicConfig);\n overrideConfig(this.mainStreamConfig, sanitizedDynamicConfig);\n overrideConfig(this.secondaryStreamConfig, sanitizedDynamicConfig);\n\n if (sanitizedMainStream) {\n overrideConfig(this.mainStreamConfig, sanitizedMainStream);\n }\n\n if (sanitizedSecondaryStream) {\n overrideConfig(this.secondaryStreamConfig, sanitizedSecondaryStream);\n }\n }\n\n private stripStaticOnlyProps<T extends object>(\n config: T,\n ): Omit<T, \"swarmId\" | \"streamSwarmIdBuilder\"> {\n if (!(\"swarmId\" in config) && !(\"streamSwarmIdBuilder\" in config)) {\n return config;\n }\n\n // TypeScript excludes these properties from DynamicCoreConfig, but\n // plain-JS callers can still pass them — signal instead of silently\n // ignoring the update.\n this.logger(\n \"swarmId and streamSwarmIdBuilder cannot be changed at runtime; ignoring them in the dynamic configuration update\",\n );\n\n const sanitized = { ...config } as T & {\n swarmId?: unknown;\n streamSwarmIdBuilder?: unknown;\n };\n delete sanitized.swarmId;\n delete sanitized.streamSwarmIdBuilder;\n return sanitized;\n }\n\n private destroyStreamLoader(streamType: StreamType) {\n if (streamType === \"main\") {\n this.mainStreamLoader?.destroy();\n this.mainStreamLoader = undefined;\n } else {\n this.secondaryStreamLoader?.destroy();\n this.secondaryStreamLoader = undefined;\n }\n }\n\n private getStreamHybridLoader(segment: SegmentWithStream) {\n if (segment.stream.type === \"main\") {\n this.mainStreamLoader ??= this.createNewHybridLoader(segment);\n return this.mainStreamLoader;\n } else {\n this.secondaryStreamLoader ??= this.createNewHybridLoader(segment);\n return this.secondaryStreamLoader;\n }\n }\n\n private createNewHybridLoader(segment: SegmentWithStream) {\n if (!this.segmentStorage) {\n throw new Error(\"Segment storage is not initialized\");\n }\n\n const streamConfig =\n segment.stream.type === \"main\"\n ? this.mainStreamConfig\n : this.secondaryStreamConfig;\n\n return new HybridLoader(\n segment,\n this.streamDetails,\n streamConfig,\n this.bandwidthCalculators,\n this.segmentStorage,\n this.webTorrentSocketPool,\n this.eventTarget,\n this.peerId,\n );\n }\n}\n\nfunction stripQuery(url: string): string {\n return url.split(\"?\")[0];\n}\n\nfunction summarize(updates: readonly RegistryUpdate[]): ProcessedManifest {\n return {\n streams: updates.map((u) => ({\n key: u.streamKey,\n type: u.type,\n isLive: u.isLive,\n start: u.start,\n end: u.end,\n segmentCount: u.segmentCount,\n })),\n };\n}\n","/**\n * The playback contract: everything the core needs to know about where the\n * player is and how urgently it needs what it just asked for.\n *\n * Deliberately not player-shaped. It is the intersection of what a media\n * element, ExoPlayer and AVPlayer can all answer, so adding a player never\n * means widening it. See specs/playback-contract.md.\n */\n\n/** A buffered interval, in seconds on the player's own timeline. */\nexport type TimeRange = {\n readonly start: number;\n readonly end: number;\n};\n\n/**\n * Playback state as reported by a player integration.\n *\n * There is no playhead position here, and that is the point. Where the player\n * is in the stream is already known from the last requested segment, in\n * manifest time; `bufferAhead` is a duration, so it is invariant under the\n * offset between the player's timeline and the manifest's. Never reporting an\n * absolute position is what lets a manifest-derived registry and any player\n * share one timebase with no calibration step.\n */\nexport type PlaybackState = {\n /**\n * Seconds of contiguous media buffered ahead of the playhead. Zero when the\n * playhead sits in a gap: an unbuffered playhead is maximum urgency.\n */\n readonly bufferAhead: number;\n\n /** Effective playback rate; 0 while paused. */\n readonly rate: number;\n};\n\n/**\n * Seconds buffered ahead of `currentTime`, taken from the range that contains\n * it.\n *\n * The containing range is the one that matters, not the last one: after a seek\n * across a gap the buffer is a set of disjoint islands, and the final island\n * may describe media the playhead is nowhere near.\n */\nexport function getBufferAhead(\n ranges: readonly TimeRange[],\n currentTime: number,\n): number {\n for (const { start, end } of ranges) {\n if (start <= currentTime && currentTime <= end) {\n return Math.max(0, end - currentTime);\n }\n }\n return 0;\n}\n\n/** Reads the contract straight off a media element. */\nexport function getPlaybackStateFromMediaElement(\n media: Pick<\n HTMLMediaElement,\n \"currentTime\" | \"playbackRate\" | \"paused\" | \"buffered\"\n >,\n): PlaybackState {\n const { buffered, currentTime } = media;\n const ranges: TimeRange[] = [];\n for (let i = 0; i < buffered.length; i++) {\n ranges.push({ start: buffered.start(i), end: buffered.end(i) });\n }\n\n return {\n bufferAhead: getBufferAhead(ranges, currentTime),\n rate: media.paused ? 0 : media.playbackRate,\n };\n}\n","import type { ProcessedManifest } from \"./types.js\";\n\n/**\n * Where the player sits in a live window. Mirrors the hls.js adapter: as deep\n * as the window allows, one segment inside the tail, never more than a\n * minute behind the edge. Its own out-of-window handling covers a playhead\n * that drifts past the tail.\n *\n * A delay alone does not leave the window ahead of the buffer free for peers\n * to exchange: what the player fetches is a forward buffer ahead of the\n * playhead, and a player whose buffering goal is as wide as the window fetches\n * at the live edge however far behind it plays. An adapter that applies this\n * delay holds that buffer down too. Shared by the Shaka and dash.js adapters;\n * see specs/player-adapters.md.\n */\nconst MAX_LIVE_LATENCY = 60;\nconst LIVE_TAIL_MARGIN_SEGMENTS = 1;\n\nexport type LiveDelay = {\n /** Seconds behind the live edge to place the playhead. */\n readonly delay: number;\n /** Average segment length of the stream the delay was derived from. */\n readonly segment: number;\n};\n\n/**\n * The presentation delay a processed manifest calls for, or `undefined` when\n * it described no live stream with segments. Among the streams the manifest\n * listed, the widest live main stream decides; on an MPD every\n * Representation shares one window, and on HLS one media playlist arrives at\n * a time.\n */\nexport function liveDelayFor(\n manifest: ProcessedManifest,\n): LiveDelay | undefined {\n let best: LiveDelay | undefined;\n for (const stream of manifest.streams) {\n if (!stream.isLive || stream.type !== \"main\" || stream.segmentCount === 0) {\n continue;\n }\n const window = stream.end - stream.start;\n if (!(window > 0)) continue;\n const segment = window / stream.segmentCount;\n const delay = Math.max(\n segment,\n Math.min(window - LIVE_TAIL_MARGIN_SEGMENTS * segment, MAX_LIVE_LATENCY),\n );\n if (!best || delay > best.delay) best = { delay, segment };\n }\n return best;\n}\n","/**\n * The slice of dash.js's request plumbing the adapter touches, typed\n * structurally. dash.js's own declarations for these live in\n * `@svta/cml-request`, a transitive dependency this package cannot import\n * directly, and the adapter needs only a handful of fields.\n */\n\n/** `HTTPRequest.*_TYPE` values a request carries in `customData.request.type`. */\nexport const REQUEST_TYPE = {\n MPD: \"MPD\",\n INIT_SEGMENT: \"InitializationSegment\",\n MEDIA_SEGMENT: \"MediaSegment\",\n INDEX_SEGMENT: \"IndexSegment\",\n} as const;\n\n/** What `_onprogress` in dash.js's HTTPLoader reads off a progress event. */\nexport type ProgressEventLike = {\n lengthComputable: boolean;\n loaded: number;\n total: number;\n /** Trace duration in ms; dash.js uses it instead of the wall clock when set. */\n time?: number;\n};\n\n/** The dash.js `FragmentRequest` (or `TextRequest`) behind a network request. */\ntype FragmentRequestLike = {\n type?: string | null;\n url?: string | null;\n range?: string | null;\n mediaType?: string | null;\n};\n\n/** Callbacks and state dash.js's HTTPLoader hangs on a request. */\ntype RequestCustomData = {\n request?: FragmentRequestLike;\n onloadend?: () => void;\n onprogress?: (event: ProgressEventLike) => void;\n onabort?: () => void;\n ontimeout?: (event: unknown) => void;\n abort?: () => void;\n};\n\n/** `CommonMediaRequest` as HTTPLoader builds it. */\nexport type CommonMediaRequestLike = {\n url: string;\n method?: string;\n responseType?: string;\n headers?: Record<string, string | undefined>;\n customData?: RequestCustomData;\n};\n\n/** `CommonMediaResponse` as HTTPLoader expects the loader to fill it. */\nexport type CommonMediaResponseLike = {\n url?: string;\n status: number;\n statusText?: string;\n headers?: Record<string, string> | null;\n data?: unknown;\n};\n\n/** The instance dash.js's own `XHRLoader` factory produces. */\nexport type XhrLoaderLike = {\n load(\n request: CommonMediaRequestLike,\n response: CommonMediaResponseLike,\n ): boolean;\n abort(): void;\n};\n\n/**\n * What `FactoryMaker` binds as `this` when it applies an `override`\n * extension: the real instance is `parent`.\n */\nexport type FactoryMakerThis = {\n context: object;\n factory: unknown;\n parent: XhrLoaderLike;\n};\n","import {\n Core,\n CoreRequestError,\n ProcessedManifest,\n byteRangeFromRangeHeader,\n debug,\n} from \"p2p-media-loader-core\";\nimport {\n CommonMediaRequestLike,\n CommonMediaResponseLike,\n FactoryMakerThis,\n REQUEST_TYPE,\n XhrLoaderLike,\n} from \"./types.js\";\n\nexport type LoaderHooks = {\n /** Called with what the core read from each MPD, before dash.js parses it. */\n onManifestProcessed?: (manifest: ProcessedManifest) => void;\n};\n\nconst SEGMENT_TYPES: ReadonlySet<string> = new Set([\n REQUEST_TYPE.INIT_SEGMENT,\n REQUEST_TYPE.MEDIA_SEGMENT,\n REQUEST_TYPE.INDEX_SEGMENT,\n]);\n\n/**\n * The `XHRLoader` replacement, in the shape dash.js's `FactoryMaker` applies\n * it: a plain function it calls with `this.parent` set to the real loader,\n * whose `load` and `abort` the returned object overrides. Registered per\n * player through `player.extend(\"XHRLoader\", extension, true)`.\n *\n * Every request dash.js makes over HTTP passes through here — MPD, init,\n * media and index segments, licences — and is told apart by the type of the\n * `FragmentRequest` behind it. See specs/player-adapters.md, \"dash.js\".\n */\nexport function createXhrLoaderExtension(core: Core, hooks: LoaderHooks = {}) {\n return function xhrLoaderExtension(this: FactoryMakerThis): XhrLoaderLike {\n // FactoryMaker copies the returned `load` and `abort` onto the parent\n // instance itself, so `this.parent.load` would point back here once the\n // override is applied. Keep dash.js's own methods before that happens.\n const { parent } = this;\n const original: XhrLoaderLike = {\n load: parent.load.bind(parent),\n abort: parent.abort.bind(parent),\n };\n const router = new RequestRouter(core, original, hooks);\n return {\n load: (request, response) => router.load(request, response),\n abort: () => router.abort(),\n };\n };\n}\n\nclass RequestRouter {\n private readonly logger = debug(\"p2pml-dashjs:loader\");\n /** Aborts the request served by the core most recently, if still in flight. */\n private abortCurrent?: () => void;\n\n constructor(\n private readonly core: Core,\n private readonly parent: XhrLoaderLike,\n private readonly hooks: LoaderHooks,\n ) {}\n\n load(\n request: CommonMediaRequestLike,\n response: CommonMediaResponseLike,\n ): boolean {\n const type = request.customData?.request?.type ?? undefined;\n const { url } = request;\n const byteRange = byteRangeFromRangeHeader(\n request.headers?.Range ?? request.headers?.range,\n );\n\n // Every MPD dash.js fetches — first load and each refresh — reaches the\n // core before dash.js parses the same bytes.\n if (type === REQUEST_TYPE.MPD) {\n return this.passThroughAndObserve(request, response, (data) => {\n if (typeof data !== \"string\" && !isBinary(data)) return;\n // The response URL, when the loader filled it in, follows redirects.\n const responseUrl = response.url;\n const processed = this.core.processManifest({\n url:\n responseUrl !== undefined && responseUrl !== \"\" ? responseUrl : url,\n data,\n });\n if (processed) this.hooks.onManifestProcessed?.(processed);\n });\n }\n\n if (type !== undefined && SEGMENT_TYPES.has(type)) {\n // A SegmentBase stream's index: dash.js loads it, the core reads the\n // segment list from the same bytes. Recognition, not lookup.\n if (this.core.isSegmentIndex(url, byteRange)) {\n return this.passThroughAndObserve(request, response, (data) => {\n if (!isBinary(data)) return;\n this.core.processSegmentIndex({ url, byteRange, data });\n });\n }\n\n // Whitelist by lookup: a segment the registry knows on a stream with\n // P2P enabled is served by the core; initialization segments and\n // anything the registry does not know load through dash.js itself.\n if (\n type === REQUEST_TYPE.MEDIA_SEGMENT &&\n this.core.isSegmentLoadable(url, byteRange)\n ) {\n this.serve(request, response, byteRange);\n return true;\n }\n }\n\n // Licences, certificates, steering, XLink, init segments: untouched.\n return this.parent.load(request, response);\n }\n\n abort() {\n this.abortCurrent?.();\n this.parent.abort();\n }\n\n private passThroughAndObserve(\n request: CommonMediaRequestLike,\n response: CommonMediaResponseLike,\n observe: (data: unknown) => void,\n ): boolean {\n request.customData ??= {};\n const { customData } = request;\n const original = customData.onloadend;\n // dash.js's XHRLoader copies `onloadend` onto the XHR at `load`, so the\n // wrap has to be in place before the parent runs.\n customData.onloadend = () => {\n try {\n if (response.status >= 200 && response.status <= 299) {\n observe(response.data);\n }\n } catch (error) {\n this.logger(\"failed to process %s: %O\", request.url, error);\n }\n original?.();\n };\n return this.parent.load(request, response);\n }\n\n private serve(\n request: CommonMediaRequestLike,\n response: CommonMediaResponseLike,\n byteRange: ReturnType<typeof byteRangeFromRangeHeader>,\n ) {\n const { url } = request;\n request.customData ??= {};\n const { customData } = request;\n let settled = false;\n\n const abort = () => {\n if (settled) return;\n this.core.abortSegmentLoading(url, byteRange);\n };\n customData.abort = abort;\n this.abortCurrent = abort;\n\n this.core\n .loadSegment(url, { byteRange })\n .then(({ data, bandwidth }) => {\n settled = true;\n response.url = url;\n response.status = 200;\n response.statusText = \"OK\";\n response.headers = {};\n response.data = data;\n\n // dash.js measures throughput from progress traces, dropping the\n // first (it carries the latency) and summing the rest. Two events\n // give it one download trace whose duration is the core's bandwidth\n // hint — wall-clock time says nothing about the network for a segment\n // that came from a peer or from storage. Never 0 ms.\n const total = data.byteLength;\n customData.onprogress?.({\n lengthComputable: true,\n loaded: 0,\n total,\n time: 1,\n });\n customData.onprogress?.({\n lengthComputable: true,\n loaded: total,\n total,\n time: loadingTimeMs(bandwidth, total),\n });\n customData.onloadend?.();\n })\n .catch((error: unknown) => {\n settled = true;\n if (error instanceof CoreRequestError && error.type === \"aborted\") {\n customData.onabort?.();\n return;\n }\n // A non-2xx status is what dash.js's HTTPLoader retries on; the\n // failure is reported as one rather than thrown into dash.js.\n response.url = url;\n response.status = 0;\n response.statusText =\n error instanceof Error ? error.message : String(error);\n response.data = undefined;\n this.logger(\"core failed to load %s: %O\", url, error);\n customData.onloadend?.();\n });\n }\n}\n\nfunction isBinary(data: unknown): data is ArrayBuffer | ArrayBufferView {\n return data instanceof ArrayBuffer || ArrayBuffer.isView(data);\n}\n\n/** Download time in ms for the core's bandwidth hint; see the Shaka adapter. */\nfunction loadingTimeMs(bandwidth: number, bytes: number): number {\n if (bandwidth <= 0) return 1;\n return Math.max(1, Math.round((bytes * 8 * 1000) / bandwidth));\n}\n","import type { MediaPlayerClass, MediaPlayerEvents } from \"dashjs\";\nimport { dashManifestParser } from \"p2p-media-loader-core/dash\";\nimport {\n Core,\n CoreConfig,\n CoreEventMap,\n DefinedCoreConfig,\n DynamicCoreConfig,\n ProcessedManifest,\n debug,\n getPlaybackStateFromMediaElement,\n liveDelayFor,\n type LiveDelay,\n} from \"p2p-media-loader-core\";\nimport { createXhrLoaderExtension } from \"./loader.js\";\n\n/** A type for specifying dynamic configuration options that can be changed at runtime for the P2P engine's core. */\nexport type DynamicDashJsP2PEngineConfig = {\n /** Dynamic core config */\n core?: DynamicCoreConfig;\n};\n\n/** Represents the complete configuration for the `DashJsP2PEngine`. */\nexport type DashJsP2PEngineConfig = {\n /** Complete core configuration settings. */\n core: DefinedCoreConfig;\n};\n\n/** Allows for partial configuration settings for the `DashJsP2PEngine`. */\nexport type PartialDashJsP2PEngineConfig = {\n /** Partial core config */\n core?: Partial<CoreConfig>;\n};\n\n/**\n * Live delay until the first live manifest says how wide the window is; from\n * then on the delay follows the window (see the core's liveDelayFor). Only\n * applied when the integrator left dash.js's own default in place.\n */\nconst INITIAL_LIVE_EDGE_DELAY = 25;\n\n/** Least forward buffer to leave the player, whatever the windows work out to. */\nconst MIN_BUFFER_SEGMENTS = 2;\n/** Segments left between the player's forward buffer and the live edge. */\nconst LIVE_EDGE_MARGIN_SEGMENTS = 1;\n\nconst STREAM_INITIALIZED: MediaPlayerEvents[\"STREAM_INITIALIZED\"] =\n \"streamInitialized\";\nconst STREAM_TEARDOWN_COMPLETE: MediaPlayerEvents[\"STREAM_TEARDOWN_COMPLETE\"] =\n \"streamTeardownComplete\";\n\n// Every event after which the buffer ahead of the playhead or the rate may\n// have changed. `progress` covers buffer growth without playhead movement.\nconst PLAYBACK_EVENTS = [\n \"timeupdate\",\n \"progress\",\n \"seeking\",\n \"seeked\",\n \"ratechange\",\n \"play\",\n \"pause\",\n \"waiting\",\n] as const;\n\n/**\n * Represents a Peer-to-Peer (P2P) engine designed to enhance media streaming efficiency.\n * This class integrates P2P technologies into dash.js, enabling the distribution of media segments via a peer network\n * alongside traditional HTTP fetching. This reduces server bandwidth costs and improves scalability by sharing the load\n * across multiple clients.\n *\n * The engine has three responsibilities (see specs/player-adapters.md): it\n * hands every MPD dash.js fetches to the core, routes segment requests\n * through the core, and reports playback state from the media element. dash.js's\n * own manifest parsing runs untouched; the core parses the same bytes itself.\n *\n * @example\n * const player = dashjs.MediaPlayer().create();\n * const engine = new DashJsP2PEngine({\n * core: {\n * swarmId: \"example-swarm-id\",\n * announceTrackers: [\"wss://personal.tracker.com\"],\n * },\n * });\n * engine.bindPlayer(player); // before initialize()\n * player.initialize(videoElement, manifestUrl, true);\n */\nexport class DashJsP2PEngine {\n private player?: MediaPlayerClass;\n private media?: HTMLMediaElement;\n private readonly core: Core;\n /** False when the integrator configured a live delay themselves. */\n private managesLiveDelay = false;\n private readonly debug = debug(\"p2pml-dashjs:engine\");\n\n /**\n * Constructs an instance of `DashJsP2PEngine`.\n *\n * @param config An optional configuration for customizing the P2P engine's behavior.\n */\n constructor(config?: PartialDashJsP2PEngineConfig) {\n this.core = new Core({\n ...config?.core,\n // dash.js plays DASH only, so its bundle carries the DASH parser only.\n manifestParsers: config?.core?.manifestParsers ?? [dashManifestParser],\n });\n }\n\n /**\n * Hooks the engine into a dash.js player. Call before `player.initialize()`:\n * the engine replaces the player's `XHRLoader` through `player.extend`,\n * which dash.js resolves when it first loads.\n *\n * @param player The dash.js `MediaPlayer` instance.\n */\n bindPlayer(player: MediaPlayerClass) {\n if (this.player === player) return;\n if (this.player) this.destroy();\n this.player = player;\n\n const liveDelay = player.getSettings().streaming?.delay?.liveDelay;\n this.managesLiveDelay = liveDelay === undefined || Number.isNaN(liveDelay);\n if (this.managesLiveDelay) {\n player.updateSettings({\n streaming: {\n delay: {\n liveDelay: INITIAL_LIVE_EDGE_DELAY,\n // A server's suggestion places the player near the edge, where\n // there is nothing to share.\n useSuggestedPresentationDelay: false,\n },\n },\n });\n }\n\n player.extend(\n \"XHRLoader\",\n createXhrLoaderExtension(this.core, {\n onManifestProcessed: this.applyLivePlacement,\n }),\n true,\n );\n\n player.on(STREAM_INITIALIZED, this.handleStreamInitialized);\n player.on(STREAM_TEARDOWN_COMPLETE, this.handleStreamTeardown);\n this.registerMediaElement();\n }\n\n /**\n * Applies dynamic configuration updates to the P2P engine.\n *\n * @param dynamicConfig The configuration changes to apply.\n */\n applyDynamicConfig(dynamicConfig: DynamicDashJsP2PEngineConfig) {\n if (dynamicConfig.core) this.core.applyDynamicConfig(dynamicConfig.core);\n }\n\n /**\n * Retrieves the current configuration of the `DashJsP2PEngine`.\n *\n * @returns The configuration as a readonly object.\n */\n getConfig(): DashJsP2PEngineConfig {\n return { core: this.core.getConfig() };\n }\n\n /**\n * Adds an event listener for the specified event.\n * @param eventName The name of the event to listen for.\n * @param listener The callback function to be invoked when the event is triggered.\n *\n * @example\n * engine.addEventListener('onSegmentLoaded', (details) => {\n * console.log('Segment Loaded:', details);\n * });\n */\n addEventListener<K extends keyof CoreEventMap>(\n eventName: K,\n listener: CoreEventMap[K],\n ) {\n this.core.addEventListener(eventName, listener);\n }\n\n /**\n * Removes an event listener for the specified event.\n * @param eventName The name of the event.\n * @param listener The callback function that was previously added.\n */\n removeEventListener<K extends keyof CoreEventMap>(\n eventName: K,\n listener: CoreEventMap[K],\n ) {\n this.core.removeEventListener(eventName, listener);\n }\n\n /**\n * Places the player in the live window from the window the core just\n * parsed: how far behind the edge it plays, and how far ahead of the\n * playhead it may fetch. The MPD reaches the core before dash.js parses the\n * same bytes, so both are in place when dash.js computes its live position.\n * Re-applied only when the window changes by at least half a segment.\n */\n private applyLivePlacement = (manifest: ProcessedManifest) => {\n if (!this.player || !this.managesLiveDelay) return;\n const target = liveDelayFor(manifest);\n if (!target) return;\n\n const current = this.player.getSettings().streaming?.delay?.liveDelay;\n if (\n current !== undefined &&\n !Number.isNaN(current) &&\n Math.abs(current - target.delay) < target.segment / 2\n ) {\n return;\n }\n\n const buffer = this.forwardBufferSettings(target);\n this.debug(\n `Setting liveDelay to ${target.delay}, forward buffer to ${buffer.bufferTimeDefault}`,\n );\n this.player.updateSettings({\n streaming: { delay: { liveDelay: target.delay }, buffer },\n });\n };\n\n /**\n * How far ahead of the playhead dash.js may fetch: the high-demand window,\n * never closer to the live edge than a segment, never less than a couple of\n * segments. The segments beyond it are the core's to prefetch, and they are\n * the ones peers exchange.\n *\n * Left alone, dash.js buffers `bufferTimeAtTopQualityLongForm` — a minute,\n * since a dynamic stream is long-form by its duration — which on a live\n * stream is the whole window. Its playhead then sits a live delay behind the\n * edge while its *fetch* position rides the edge itself, where the registry\n * cannot yet know the segment: core learns of one only when dash.js refreshes\n * the MPD, and dash.js derives availability from its own synced clock. Every\n * such request misses the registry and falls through to dash.js's own loader,\n * so the stream plays perfectly with no P2P at all.\n *\n * Settings the integrator already holds below this are left alone; the value\n * is a ceiling, not a target.\n */\n private forwardBufferSettings(target: LiveDelay) {\n const { mainStream, secondaryStream } = this.core.getConfig();\n const highDemandTimeWindow = Math.max(\n mainStream.highDemandTimeWindow,\n secondaryStream.highDemandTimeWindow,\n );\n const bufferTime = Math.max(\n target.segment * MIN_BUFFER_SEGMENTS,\n Math.min(\n highDemandTimeWindow,\n target.delay - target.segment * LIVE_EDGE_MARGIN_SEGMENTS,\n ),\n );\n\n const current = this.player?.getSettings().streaming?.buffer;\n const lower = (setting: number | undefined) =>\n setting === undefined || Number.isNaN(setting) || setting > bufferTime\n ? bufferTime\n : setting;\n\n return {\n bufferTimeDefault: lower(current?.bufferTimeDefault),\n bufferTimeAtTopQuality: lower(current?.bufferTimeAtTopQuality),\n bufferTimeAtTopQualityLongForm: lower(\n current?.bufferTimeAtTopQualityLongForm,\n ),\n };\n }\n\n private handleStreamInitialized = () => {\n this.registerMediaElement();\n };\n\n private handleStreamTeardown = () => {\n this.core.destroy();\n this.unregisterMediaElement();\n };\n\n private registerMediaElement() {\n let media: HTMLMediaElement | undefined;\n try {\n // Throws until a view is attached.\n media = this.player?.getVideoElement();\n } catch {\n return;\n }\n if (!media || media === this.media) return;\n this.unregisterMediaElement();\n this.media = media;\n for (const event of PLAYBACK_EVENTS) {\n media.addEventListener(event, this.handlePlaybackUpdate);\n }\n }\n\n private unregisterMediaElement() {\n const { media } = this;\n if (!media) return;\n for (const event of PLAYBACK_EVENTS) {\n media.removeEventListener(event, this.handlePlaybackUpdate);\n }\n this.media = undefined;\n }\n\n private handlePlaybackUpdate = (event: Event) => {\n const media = event.target as HTMLMediaElement;\n this.core.updatePlayback(getPlaybackStateFromMediaElement(media));\n };\n\n /** Cleans up and releases all resources, and unregisters all event handlers. */\n destroy() {\n this.core.destroy();\n this.unregisterMediaElement();\n if (this.player) {\n this.player.off(STREAM_INITIALIZED, this.handleStreamInitialized);\n this.player.off(STREAM_TEARDOWN_COMPLETE, this.handleStreamTeardown);\n }\n this.player = undefined;\n }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