UNPKG

p2p-media-loader-hlsjs

Version:
2 lines 109 kB
this.p2pml=this.p2pml||{},this.p2pml.hlsjs=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),c=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},l=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},u=(e,r,i)=>(i=e==null?{}:t(a(e)),l(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e));function d(e,t){return t?`${e}|${t.start}-${t.end}`:e}function f(e,t){if(e!==void 0&&t!==void 0&&e<=t)return{start:e,end:t}}function p(e){"@babel/helpers - typeof";return p=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},p(e)}function m(e,t){if(p(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(p(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ee(e){var t=m(e,`string`);return p(t)==`symbol`?t:t+``}function h(e,t,n){return(t=ee(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var te=class extends Error{constructor(e,t,n){super(t),h(this,`type`,void 0),h(this,`cause`,void 0),this.type=e,this.cause=n}},ne=class extends te{constructor(...e){super(...e),h(this,`name`,`PeerError`)}},re=class extends te{constructor(...e){super(...e),h(this,`name`,`PeerWarning`)}},ie=class extends te{constructor(...e){super(...e),h(this,`name`,`TrackerError`)}},ae=class extends te{constructor(...e){super(...e),h(this,`name`,`TrackerWarning`)}},oe=class extends te{constructor(...e){super(...e),h(this,`name`,`PeerConnectError`)}},g=class extends te{constructor(e,t,n){super(e,t,n),h(this,`name`,`RequestError`),h(this,`timestamp`,void 0),this.timestamp=performance.now()}},se=class extends te{constructor(...e){super(...e),h(this,`name`,`CoreRequestError`)}};function ce(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function _(e,t,n){ce(e,t),t.set(e,n)}function v(e,t,n){if(typeof e==`function`?e===t:e.has(t))return arguments.length<3?t:n;throw TypeError(`Private element is not present on this object`)}function y(e,t){return e.get(v(e,t))}var le=new WeakMap,ue=class{constructor(){h(this,`aborted`,!1),_(this,le,new Set)}addEventListener(e,t){y(le,this).add(t)}removeEventListener(e,t){y(le,this).delete(t)}dispatchEvent(e){this.aborted=!0;for(let e of y(le,this))try{e()}catch(e){}y(le,this).clear()}},de=class{constructor(){h(this,`signal`,new ue)}abort(){this.signal.dispatchEvent(`abort`)}},fe=typeof AbortController<`u`,pe=fe?AbortController:de;function me(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function b(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?me(Object(n),!0).forEach(function(t){h(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):me(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function he(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function x(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var a=e.apply(t,n);function o(e){he(a,r,i,o,s,`next`,e)}function s(e){he(a,r,i,o,s,`throw`,e)}o(void 0)})}}var ge=class{isAborted(){return this.abortController.signal.aborted}constructor(e,t,n){h(this,`request`,void 0),h(this,`httpConfig`,void 0),h(this,`abortController`,new pe),h(this,`expectedBytesLength`,void 0),h(this,`requestByteRange`,void 0),h(this,`onChunkDownloaded`,void 0),this.request=e,this.httpConfig=t,this.onChunkDownloaded=n.getEventDispatcher(`onChunkDownloaded`);let{byteRange:r}=this.request.segment;r&&(this.requestByteRange=b({},r))}execute(){let e={onAbort:()=>this.abortController.abort(),notReceivingBytesTimeoutMs:this.httpConfig.httpNotReceivingBytesTimeoutMs};if(this.request.tryCompleteByLoadedBytes({downloadSource:`http`},e,this.httpConfig.validateHTTPSegment,`http-segment-validation-failed`))return;if(this.request.loadedBytes!==0){var t;this.requestByteRange=(t=this.requestByteRange)==null?{start:0}:t,this.requestByteRange.start=this.requestByteRange.start+this.request.loadedBytes}this.request.totalBytes&&(this.expectedBytesLength=this.request.totalBytes-this.request.loadedBytes);let n=this.request.start({downloadSource:`http`},e);this.fetch(n)}fetch(e){var t=this;return x(function*(){let{segment:n}=t.request,r;if(t.isAborted())return;let i=()=>{try{r==null||r.cancel().catch(()=>{})}catch(e){}};t.abortController.signal.addEventListener(`abort`,i);let a=fe?t.abortController.signal:void 0;try{var o,s;let i=yield(o=(s=t.httpConfig).httpRequestSetup)==null?void 0:o.call(s,n.url,n.byteRange,a,t.requestByteRange);if(t.isAborted())throw new DOMException(`Request aborted`,`AbortError`);if(!i){let e=new Headers;if(t.requestByteRange){var c;e.set(`Range`,`bytes=${t.requestByteRange.start}-${(c=t.requestByteRange.end)==null?``:c}`)}let r={headers:e};a&&(r.signal=a),i=new Request(n.url,r)}if(t.isAborted())throw new DOMException(`Request aborted before request fetch`,`AbortError`);let l=yield window.fetch(i);if(t.isAborted())throw new DOMException(`Request aborted`,`AbortError`);if(t.handleResponseHeaders(l),e.firstBytesReceived(),!l.body||typeof l.body.getReader!=`function`){let r=yield l.arrayBuffer();if(t.isAborted())throw new DOMException(`Request aborted`,`AbortError`);let i=new Uint8Array(r);e.addLoadedChunk(i),t.onChunkDownloaded(i.byteLength,`http`,void 0,n.stream.type,t.request.infoHash)}else{let i=l.body.getReader();for(r=i;;){if(t.isAborted())throw new DOMException(`Request aborted`,`AbortError`);let{done:r,value:a}=yield i.read();if(r)break;if(t.isAborted())throw new DOMException(`Request aborted`,`AbortError`);e.addLoadedChunk(a),t.onChunkDownloaded(a.byteLength,`http`,void 0,n.stream.type,t.request.infoHash)}}if(t.isAborted())throw new DOMException(`Request aborted`,`AbortError`);if(t.request.totalBytes!==void 0&&t.request.loadedBytes!==t.request.totalBytes)throw new g(`http-bytes-mismatch`,`HTTP response truncated: received ${t.request.loadedBytes} of ${t.request.totalBytes} bytes`);let u=yield t.request.validateData(t.httpConfig.validateHTTPSegment);if(t.isAborted())throw new DOMException(`Request aborted`,`AbortError`);if(!u)throw t.request.clearLoadedBytes(),new g(`http-segment-validation-failed`);e.completeOnSuccess()}catch(n){t.handleError(n,e)}finally{t.abortController.signal.removeEventListener(`abort`,i)}})()}handleResponseHeaders(e){if(!e.ok)throw e.status===406||e.status===416?(this.request.clearLoadedBytes(),new g(`http-bytes-mismatch`,e.statusText)):new g(`http-error`,e.statusText);let{requestByteRange:t}=this;if(t)if(e.status===200){if(this.request.segment.byteRange)throw new g(`http-unexpected-status-code`);this.request.clearLoadedBytes()}else{if(e.status!==206)throw new g(`http-unexpected-status-code`,e.statusText);let n=e.headers.get(`Content-Length`);if(n&&this.expectedBytesLength!==void 0&&this.expectedBytesLength!==+n)throw this.request.clearLoadedBytes(),new g(`http-bytes-mismatch`,e.statusText);let r=e.headers.get(`Content-Range`),i=r?ve(r):void 0;if(i){let{from:n,to:r}=i,a=r!==void 0&&n!==void 0?r-n+1:void 0;if(a!==void 0&&this.expectedBytesLength!==a||n!==void 0&&t.start!==n||r!==void 0&&t.end!==void 0&&t.end!==r)throw this.request.clearLoadedBytes(),new g(`http-bytes-mismatch`,e.statusText)}}if(e.status===200&&this.request.totalBytes===void 0){let t=e.headers.get(`Content-Length`);t&&this.request.setTotalBytes(+t)}}handleError(e,t){if(!this.isAborted()&&e instanceof Error){let n=e instanceof g?e:new g(`http-error`,e.message);t.failWithError(n)}}},_e=/^bytes (?:(?:(\d+)|)-(?:(\d+)|)|\*)\/(?:(\d+)|\*)$/;function ve(e){let t=_e.exec(e.trim());if(!t)return;let[,n,r,i]=t;return{from:n?parseInt(n):void 0,to:r?parseInt(r):void 0,total:i?parseInt(i):void 0}}var ye=s(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t=t||{};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),be=s(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=ye(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),S=u(s(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch(e){}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch(e){}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch(e){}}t.exports=be()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}}))(),1),C=function(e){return e[e.SegmentsAnnouncement=0]=`SegmentsAnnouncement`,e[e.SegmentRequest=1]=`SegmentRequest`,e[e.SegmentData=2]=`SegmentData`,e[e.SegmentDataSendingCompleted=3]=`SegmentDataSendingCompleted`,e[e.SegmentAbsent=4]=`SegmentAbsent`,e[e.CancelSegmentRequest=5]=`CancelSegmentRequest`,e}({});function xe(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}function Se(e){Promise.resolve().then(e)}function Ce(e,t){t!=null||(t=e.reduce((e,t)=>e+t.byteLength,0));let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;return n}function we(e){return e[Math.floor(Math.random()*e.length)]}function Te(e,t){if(e.length===0)throw Error(`Cannot get item from empty array`);if(e.length===1)return e[0];let n=0,r=e.map(e=>{let r=t(e);return n+=r,r}),i=Math.random()*n;for(let t=0;t<e.length;t++)if(i-=r[t],i<=0)return e[t];return e[e.length-1]}function Ee(e){return new TextEncoder().encode(e)}function*De(e){for(let t=e.length-1;t>=0;t--)yield e[t]}function Oe(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ke(e){return Array.isArray(e)}function Ae(e){function t(e){if(Oe(e)){let n={};return Object.keys(e).forEach(r=>{if(e[r]!==void 0){let i=t(e[r]);i!==void 0&&(n[r]=i)}}),n}else return e}return t(e)}function je(e){if(ke(e))return e.map(e=>je(e));if(Oe(e)){let t={};for(let n of Object.keys(e))t[n]=je(e[n]);return t}else return e}function Me(e){for(let t=e.length-1;t>0;t--){let n=Math.floor(Math.random()*(t+1));[e[t],e[n]]=[e[n],e[t]]}return e}function Ne(e,t,n={}){return typeof e!=`object`||!e||typeof t!=`object`||!t||Object.keys(t).forEach(r=>{let i=typeof r==`symbol`?r.toString():String(r);if(r===`__proto__`||r===`constructor`||r===`prototype`)throw Error(`Attempt to modify restricted property '${i}'`);let a=t[r],o=n[r];r in e&&(a===void 0?e[r]=o===void 0?void 0:o:e[r]=a)}),e}function Pe(e){let{defaultConfig:t,baseConfig:n={},specificStreamConfig:r={}}=e,i=je(b(b(b({},t),n),r)),a=Object.keys(t),o={};return a.forEach(e=>{e in i&&(o[e]=i[e])}),o}function w(e,t){ce(e,t),t.add(e)}function T(e,t,n){return e.set(v(e,t),n),n}var Fe=new TextEncoder,Ie=new TextDecoder(`utf8`),Le=function(e){return e[e.Min=-1]=`Min`,e[e.Int=0]=`Int`,e[e.SimilarIntArray=1]=`SimilarIntArray`,e[e.String=2]=`String`,e[e.Max=3]=`Max`,e}({});function Re(e){if(e===0)return 1;let t=Math.floor(Math.log2(Math.abs(e)))+2;return Math.ceil(t/8)}function ze(e){let t=e<0,n=Re(e),r=new Uint8Array(n);e=Math.abs(e);for(let t=0;t<n;t++){let i=8*(n-1-t);r[t]=Math.floor(e/Math.pow(2,i))&255}return t&&(r[0]|=128),r}function Be(e){let t=e.length,n=(e,n)=>{let r=8*(t-1-n);return e*Math.pow(2,r)},r=n(e[0]&127,0);for(let i=1;i<t;i++)r+=n(e[i],i);return(e[0]&128)>>7&&(r=-r),r}function Ve(e){let t=ze(e),n=0|t.length;return new Uint8Array([n,...t])}function He(e){if(e.length===0)throw Error(`Buffer is too short`);let t=e[0];if(t>>4)throw Error(`Trying to deserialize integer with invalid serialized item code`);let n=t&15;if(n===0)throw Error(`Invalid integer: zero byte length`);if(n>7)throw Error(`Invalid integer: byte length exceeds safe integer limit`);let r=1+n;if(e.length<r)throw Error(`Buffer is too short`);return{number:Be(e.subarray(1,r)),byteLength:n+1}}function Ue(e){let t=new Map;for(let r of e){var n;let e=r&255,i=r-e,a=(n=t.get(i))==null?new Xe:n;a.length||t.set(i,a),a.push(e)}let r=new Xe;r.push([16,t.size]);for(let[e,n]of t){let{length:t}=n,i=e+(t&255);n.unshift(Ve(i)),r.push(n.getBuffer())}return r.getBuffer()}function We(e){if(e.length<2)throw Error(`Buffer is too short`);let[t,n]=e;if(t>>4!=1)throw Error(`Trying to deserialize similar int array with invalid serialized item code`);let r=2,i=[];for(let t=0;t<n;t++){let{number:t,byteLength:n}=He(e.subarray(r));r+=n;let a=t&255,o=a===0?256:a,s=t-a;if(r+o>e.length)throw Error(`Malformed similar int array: buffer too short`);for(let t=0;t<o;t++){let t=e[r];i.push(s+t),r++}}return{numbers:i,byteLength:r}}function Ge(e){let t=Fe.encode(e),{length:n}=t;if(n>4095)throw Error(`String exceeds maximum length of 4095 bytes`);let r=new Xe;return r.push([32|n>>8&15,n&255]),r.push(t),r.getBuffer()}function Ke(e){if(e.length<2)throw Error(`Buffer is too short`);let[t,n]=e;if(t>>4!=2)throw Error(`Trying to deserialize bytes (sting) with invalid serialized item code.`);let r=(t&15)<<8|n;if(e.length<r+2)throw Error(`Malformed string: buffer too short`);let i=e.subarray(2,r+2);return{string:Ie.decode(i),byteLength:r+2}}var qe=new WeakMap,Je=new WeakMap,Ye=new WeakSet,Xe=class{constructor(){w(this,Ye),_(this,qe,[]),_(this,Je,0)}push(e){v(Ye,this,Ze).call(this,e,`end`)}unshift(e){v(Ye,this,Ze).call(this,e,`start`)}getBytesChunks(){return y(qe,this)}getBuffer(){return Ce(y(qe,this),y(Je,this))}get length(){return y(Je,this)}};function Ze(e,t){let n;n=e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):new Uint8Array([e]),T(Je,this,y(Je,this)+n.length),y(qe,this)[t===`start`?`unshift`:`push`](n)}var E=4,Qe=xt(`cstr`,E),$e=xt(`cend`,E),et=xt(`dstr`,E),tt=xt(`dend`,E),nt=[Qe,et],rt=[$e,tt],it=Qe.length+$e.length;function at(e){if(e.length<it)return!1;let{length:t}=Qe,n=e.subarray(-t);return nt.some(t=>wt(e,t,E))&&rt.some(e=>wt(n,e,E))}function ot(e){return e.length<it?!1:wt(e,Qe,E)}function st(e){return e.length<it?!1:wt(e.subarray(-4),$e,E)}var ct=class extends Error{constructor(e){super(),h(this,`type`,void 0),this.type=e}},lt=new WeakMap,ut=new WeakMap,dt=new WeakMap,ft=new WeakSet,pt=class{constructor(e){w(this,ft),_(this,lt,new Xe),_(this,ut,`joining`),_(this,dt,void 0),T(dt,this,e)}addCommandChunk(e){if(y(ut,this)===`completed`)return;let t=ot(e);if(!y(lt,this).length&&!t)throw new ct(`no-first-chunk`);if(y(lt,this).length&&t)throw new ct(`incomplete-joining`);y(lt,this).push(v(ft,this,mt).call(this,e)),st(e)&&(T(ut,this,`completed`),y(dt,this).call(this,y(lt,this).getBuffer()))}};function mt(e){if(e.length<it)throw Error(`Command chunk is too short to unframe`);return e.subarray(E,e.length-E)}var D=new WeakMap,ht=new WeakMap,gt=new WeakMap,_t=new WeakMap,vt=class{constructor(e,t){_(this,D,new Xe),_(this,ht,[]),_(this,gt,`creating`),_(this,_t,void 0),T(_t,this,t),y(D,this).push(e)}addInteger(e,t){y(D,this).push(e.charCodeAt(0));let n=Ve(t);y(D,this).push(n)}addUniqueSimilarIntArr(e,t){y(D,this).push(e.charCodeAt(0));let n=Ue(t);y(D,this).push(n)}addString(e,t){y(D,this).push(e.charCodeAt(0));let n=Ge(t);y(D,this).push(n)}complete(){if(!y(D,this).length)throw Error(`Buffer is empty`);if(y(gt,this)===`completed`)return;T(gt,this,`completed`);let e=y(D,this).getBuffer();if(e.length+it<=y(_t,this)){y(ht,this).push(Ct(e,Qe,$e));return}let t=Math.ceil(e.length/y(_t,this));Math.ceil(e.length/t)+it>y(_t,this)&&t++;for(let[n,r]of St(e,t))n===0?y(ht,this).push(Ct(r,Qe,tt)):n===t-1?y(ht,this).push(Ct(r,et,$e)):y(ht,this).push(Ct(r,et,tt))}getResultBuffers(){if(y(gt,this)===`creating`||!y(ht,this).length)throw Error(`Command is not complete.`);return y(ht,this)}};function yt(e){let[t]=e,n={c:t},r=1;for(;r<e.length;){if(r+1>=e.length)throw Error(`Malformed command buffer: truncated name/type header`);let t=String.fromCharCode(e[r]);switch(r++,bt(e[r])){case Le.Int:{let{number:i,byteLength:a}=He(e.subarray(r));n[t]=i,r+=a}break;case Le.SimilarIntArray:{let{numbers:i,byteLength:a}=We(e.subarray(r));n[t]=i,r+=a}break;case Le.String:{let{string:i,byteLength:a}=Ke(e.subarray(r));n[t]=i,r+=a}break}}return Tt(n)}function bt(e){let t=e>>4;if(t<=Le.Min||t>=Le.Max)throw Error(`Not existing type`);return t}function xt(e,t){if(t&&e.length!==t)throw Error(`Wrong string length`);let n=new Uint8Array(t==null?e.length:t);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}function*St(e,t){let n=Math.ceil(e.length/t);for(let r=0;r<t;r++)yield[r,e.subarray(r*n,(r+1)*n)]}function Ct(e,t,n){let r=new Uint8Array(e.length+t.length+n.length);return r.set(t),r.set(e,t.length),r.set(n,t.length+e.length),r}function wt(e,t,n){for(let r=0;r<n;r++)if(e[r]!==t[r])return!1;return!0}function Tt(e){switch(e.c){case C.SegmentsAnnouncement:return e;case C.SegmentRequest:return Et(e,`i`,`r`),e;case C.SegmentData:return Et(e,`i`,`r`,`s`),e;case C.SegmentAbsent:case C.CancelSegmentRequest:case C.SegmentDataSendingCompleted:return Et(e,`i`,`r`),e;default:throw Error(`Unknown peer command type: ${String(e.c)}`)}}function Et(e,...t){for(let n of t)if(typeof e[n]!=`number`)throw Error(`Expected number field "${n}", got ${typeof e[n]}`)}function Dt(e,t){let{c:n,p:r,l:i}=e,a=new vt(n,t);return i!=null&&i.length&&a.addUniqueSimilarIntArr(`l`,i),r!=null&&r.length&&a.addUniqueSimilarIntArr(`p`,r),a.complete(),a.getResultBuffers()}function Ot(e,t){let n=new vt(e.c,t);return n.addInteger(`i`,e.i),n.addInteger(`r`,e.r),n.complete(),n.getResultBuffers()}function kt(e,t){let n=new vt(e.c,t);return n.addInteger(`i`,e.i),n.addInteger(`s`,e.s),n.addInteger(`r`,e.r),n.complete(),n.getResultBuffers()}function At(e,t){let n=new vt(e.c,t);return n.addInteger(`i`,e.i),n.addInteger(`r`,e.r),e.b&&n.addInteger(`b`,e.b),n.complete(),n.getResultBuffers()}function jt(e,t){switch(e.c){case C.CancelSegmentRequest:case C.SegmentAbsent:case C.SegmentDataSendingCompleted:return Ot(e,t);case C.SegmentRequest:return At(e,t);case C.SegmentsAnnouncement:return Dt(e,t);case C.SegmentData:return kt(e,t)}}var Mt=c({BinaryCommandChunksJoiner:()=>pt,BinaryCommandJoiningError:()=>ct,PeerCommandType:()=>C,deserializeCommand:()=>yt,isCommandChunk:()=>at,serializePeerCommand:()=>jt});function Nt(e,t=`RTC error`){var n,r;let i=e;if(i.error instanceof Error)return i.error;let a=(n=(r=i.error)==null?void 0:r.message)==null?t:n;return Error(a)}function Pt(e,t=`RTC error`){return Nt(e,t).message}function Ft(e){return e===`failed`||e===`closed`||e===`disconnected`}var It=64*1024,Lt=new WeakMap,Rt=class{constructor(e,t){h(this,`channel`,void 0),h(this,`maxMessageSize`,void 0),_(this,Lt,void 0),this.channel=e,this.maxMessageSize=t}sendData(e,t){var n=this;return x(function*(){if(y(Lt,n))throw Error(`Already sending data`);if(n.channel.readyState!==`open`)throw Error(`Data channel is not open`);n.channel.bufferedAmountLowThreshold=It;let{promise:r,resolve:i,reject:a}=xe(),o=0,s=!1,c=()=>s?!1:(s=!0,T(Lt,n,void 0),n.channel.removeEventListener(`bufferedamountlow`,p),n.channel.removeEventListener(`closing`,l),n.channel.removeEventListener(`close`,l),n.channel.removeEventListener(`error`,u),!0);T(Lt,n,{cancel:()=>{c()&&a(Error(`Send cancelled`))}});let l=()=>{c()&&a(Error(`Data channel closed`))},u=e=>{if(!c())return;let t=Pt(e,`Unknown error`);a(Error(`Data channel error: ${t}`))},d=ArrayBuffer.isView(e)?e.buffer:e,f=ArrayBuffer.isView(e)?e.byteOffset:0,p=()=>{if(!s){if(n.channel.readyState!==`open`){c()&&a(Error(`Data channel not open (state: ${n.channel.readyState})`));return}try{for(;o<e.byteLength;){if(n.channel.bufferedAmount>It)return;let r=Math.min(n.maxMessageSize,e.byteLength-o),i=new Uint8Array(d,f+o,r);if(n.channel.send(i),o+=r,t==null||t(r),!y(Lt,n))return}}catch(e){c()&&a(e instanceof Error?e:Error(String(e)));return}c()&&i()}};return n.channel.addEventListener(`bufferedamountlow`,p),n.channel.addEventListener(`closing`,l),n.channel.addEventListener(`close`,l),n.channel.addEventListener(`error`,u),p(),r})()}cancel(){var e;(e=y(Lt,this))==null||e.cancel()}},zt=(0,S.default)(`p2pml-core:peer-protocol`),Bt=new WeakMap,Vt=new WeakMap,Ht=new WeakMap,Ut=new WeakMap,Wt=new WeakMap,Gt=new WeakMap,Kt=new WeakMap,qt=new WeakMap,Jt=new WeakMap,Yt=new WeakMap,Xt=new WeakSet,Zt=class{constructor(e,t,n,r,i){if(w(this,Xt),_(this,Bt,void 0),_(this,Vt,void 0),_(this,Ht,void 0),_(this,Ut,void 0),_(this,Wt,void 0),_(this,Gt,void 0),_(this,Kt,void 0),_(this,qt,void 0),_(this,Jt,void 0),_(this,Yt,e=>{try{let t=new Uint8Array(e.data);at(t)?v(Xt,this,Qt).call(this,t):(y(qt,this).onSegmentChunkReceived(t),y(Ut,this).call(this,t.byteLength,`p2p`,y(Jt,this),y(Kt,this).streamType,y(Kt,this).infoHash))}catch(e){zt(`error handling data channel message: %O`,e),y(qt,this).onProtocolError(e)}}),T(Gt,this,e),T(Kt,this,t),T(qt,this,n),T(Jt,this,i),T(Vt,this,new Rt(e,t.webRtcMaxMessageSize)),T(Ut,this,r.getEventDispatcher(`onChunkDownloaded`)),T(Wt,this,r.getEventDispatcher(`onChunkUploaded`)),e.binaryType!==`arraybuffer`)throw Error(`Expected binaryType "arraybuffer", got "${e.binaryType}"`);e.addEventListener(`message`,y(Yt,this))}sendCommand(e){if(y(Gt,this).readyState!==`open`)throw Error(`cannot send command ${e.c} (channel state: ${y(Gt,this).readyState})`);let t=jt(e,y(Kt,this).webRtcMaxMessageSize);for(let e of t)y(Gt,this).send(e)}stopUploadingSegmentData(){y(Vt,this).cancel(),T(Ht,this,void 0)}getUploadingRequestId(){return y(Ht,this)}splitSegmentDataToChunksAndUploadAsync(e,t){var n=this;return x(function*(){if(y(Ht,n)!==void 0)throw Error(`Some segment data is already uploading.`);T(Ht,n,t);try{yield y(Vt,n).sendData(e,e=>{y(Wt,n).call(n,e,y(Jt,n),y(Kt,n).streamType,y(Kt,n).infoHash)})}finally{y(Ht,n)===t&&T(Ht,n,void 0)}})()}destroy(){y(Gt,this).removeEventListener(`message`,y(Yt,this)),y(Vt,this).cancel(),T(Bt,this,void 0),T(Ht,this,void 0)}};function Qt(e){y(Bt,this)!=null||T(Bt,this,new pt(e=>{T(Bt,this,void 0);let t;try{t=yt(e)}catch(e){zt(`error deserializing command: %O`,e),y(qt,this).onProtocolError(e);return}y(qt,this).onCommandReceived(t)}));try{y(Bt,this).addCommandChunk(e)}catch(e){zt(`error receiving command chunks: %O`,e),T(Bt,this,void 0),y(qt,this).onProtocolError(e)}}var $t=1,en=class{constructor(e=2e4){h(this,`clearThresholdMs`,void 0),h(this,`loadingsCount`,0),h(this,`bytes`,[]),h(this,`loadingOnlyTimestamps`,[]),h(this,`timestamps`,[]),h(this,`noLoadingsTime`,0),h(this,`loadingsStoppedAt`,0),this.clearThresholdMs=e}addBytes(e,t=performance.now()){this.bytes.push(e),this.loadingOnlyTimestamps.push(t-this.noLoadingsTime),this.timestamps.push(t)}startLoading(e=performance.now()){this.clearStale(),this.loadingsCount===0&&this.loadingsStoppedAt!==0&&(this.noLoadingsTime+=e-this.loadingsStoppedAt),this.loadingsCount++}stopLoading(e=performance.now()){this.loadingsCount>0&&(this.loadingsCount--,this.loadingsCount===0&&(this.loadingsStoppedAt=e))}getBandwidthLoadingOnly(e,t=-1/0){if(!this.loadingOnlyTimestamps.length)return 0;let n=e*1e3,r=this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length-1],i=r,a=r-n,o=0;for(let e=this.bytes.length-1;e>=0;e--){let n=this.loadingOnlyTimestamps[e];if(n<a||this.timestamps[e]<t)break;i=n,o+=this.bytes[e]}let s=Math.max(r-i,$t);return o*8e3/s}getBandwidth(e,t=-1/0,n=performance.now()){if(!this.timestamps.length)return 0;let r=n-e*1e3,i=n,a=0;for(let e=this.bytes.length-1;e>=0;e--){let n=this.timestamps[e];if(n<r||n<t)break;i=n,a+=this.bytes[e]}let o=Math.max(n-i,$t);return a*8e3/o}clearStale(){if(!this.loadingOnlyTimestamps.length)return;let e=this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length-1]-this.clearThresholdMs,t=0;for(let n of this.loadingOnlyTimestamps){if(n>e)break;t++}this.bytes.splice(0,t),this.loadingOnlyTimestamps.splice(0,t),this.timestamps.splice(0,t)}clear(){this.bytes.length=0,this.loadingOnlyTimestamps.length=0,this.timestamps.length=0,this.loadingsCount=0,this.noLoadingsTime=0,this.loadingsStoppedAt=0}},{PeerCommandType:O}=Mt,k=new WeakMap,A=new WeakMap,tn=new WeakMap,nn=new WeakMap,rn=new WeakMap,an=new WeakMap,on=new WeakMap,j=new WeakMap,sn=new WeakMap,cn=new WeakMap,ln=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,pn=new WeakMap,mn=new WeakMap,M=new WeakSet,hn=class{get isDestroyed(){return y(ln,this)}constructor(e,t,n,r,i,a){var o=this;w(this,M),h(this,`id`,void 0),h(this,`channel`,void 0),h(this,`eventTarget`,void 0),_(this,k,void 0),_(this,A,void 0),_(this,tn,new Set),_(this,nn,new Set),_(this,rn,0),_(this,an,new en),_(this,on,{value:0,timestamp:0}),_(this,j,(0,S.default)(`p2pml-core:peer`)),_(this,sn,0),_(this,cn,void 0),_(this,ln,!1),h(this,`connectedAt`,performance.now()),_(this,un,void 0),_(this,dn,void 0),_(this,fn,void 0),_(this,pn,function(){var e=x(function*(e){switch(e.c){case O.SegmentsAnnouncement:T(tn,o,new Set(e.l)),T(nn,o,new Set(e.p)),y(dn,o).onSegmentsAnnouncement();break;case O.SegmentRequest:T(cn,o,e.r),y(k,o).stopUploadingSegmentData(),y(dn,o).onSegmentRequested(o,e.i,e.r,e.b);break;case O.SegmentData:{if(!y(A,o)||y(A,o).isSegmentDataCommandReceived)break;let{request:t,controls:n,requestId:r}=y(A,o);if(t.segment.externalId!==e.i||r!==e.r)break;y(A,o).isSegmentDataCommandReceived=!0,n.firstBytesReceived(),t.totalBytes===void 0?t.setTotalBytes(t.loadedBytes+e.s):t.totalBytes-t.loadedBytes!==e.s&&v(M,o,gn).call(o,`bytes-length-mismatch`,`Peer response bytes length mismatch`)}break;case O.SegmentDataSendingCompleted:{let t=y(A,o);if(!(t!=null&&t.isSegmentDataCommandReceived))return;let{request:n,controls:r,requestId:i}=t;if(n.segment.externalId!==e.i||i!==e.r){v(M,o,gn).call(o,`protocol-violation`,`Peer protocol violation`);return}if(n.loadedBytes!==n.totalBytes){v(M,o,gn).call(o,`bytes-length-mismatch`,`Peer response bytes length mismatch`);return}let a=yield n.validateData(y(fn,o).validateP2PSegment);if(y(ln,o)||y(A,o)!==t)return;if(!a){v(M,o,gn).call(o,`validation-failed`,`P2P segment validation failed`);return}T(rn,o,0),r.completeOnSuccess(),y(an,o).stopLoading(),T(A,o,void 0);break}case O.SegmentAbsent:var t;y(tn,o).delete(e.i),((t=y(A,o))==null?void 0:t.request.segment.externalId)===e.i&&y(A,o).requestId===e.r&&v(M,o,_n).call(o,`peer-segment-absent`);break;case O.CancelSegmentRequest:if(y(cn,o)===e.r&&T(cn,o,void 0),y(k,o).getUploadingRequestId()!==e.r)break;y(k,o).stopUploadingSegmentData();break}});return function(t){return e.apply(this,arguments)}}()),_(this,mn,e=>{var t;if(!((t=y(A,this))!=null&&t.isSegmentDataCommandReceived))return;let{request:n,controls:r}=y(A,this);if(n.totalBytes!==void 0&&n.loadedBytes+e.byteLength>n.totalBytes){v(M,this,gn).call(this,`bytes-length-mismatch`,`Peer response bytes length mismatch`);return}y(an,this).addBytes(e.byteLength),y(on,this).timestamp=0,r.addLoadedChunk(e)}),this.id=e,this.channel=t,this.eventTarget=a,T(un,this,n),T(dn,this,r),T(fn,this,i),T(k,this,new Zt(t,i,{onSegmentChunkReceived:y(mn,this),onCommandReceived:e=>void y(pn,this).call(this,e).catch(t=>{y(j,this).call(this,`error processing command %O: %O`,e,t),this.destroy(!1,new ne(`protocol-violation`,t instanceof Error?t.message:`Error processing command`,t))}),onProtocolError:e=>{this.destroy(!1,new ne(`protocol-violation`,e instanceof Error?e.message:`Protocol error`,e))}},a,e))}get downloadingSegment(){var e;return(e=y(A,this))==null?void 0:e.request.segment}get isUploadingSegment(){return y(k,this).getUploadingRequestId()!==void 0}getDownloadBandwidth(){let e=performance.now();return e-y(on,this).timestamp>1e3&&(y(on,this).value=y(an,this).getBandwidthLoadingOnly(15),y(on,this).timestamp=e),y(on,this).value}getSegmentStatus(e){let{externalId:t}=e;if(y(tn,this).has(t))return`loaded`;if(y(nn,this).has(t))return`http-loading`}downloadSegment(e){if(y(ln,this))return;if(y(A,this))throw Error(`Some segment already is downloading`);if(e.tryCompleteByLoadedBytes({downloadSource:`p2p`,peerId:this.id},{notReceivingBytesTimeoutMs:y(fn,this).p2pNotReceivingBytesTimeoutMs,onAbort:()=>void 0},y(fn,this).validateP2PSegment,`p2p-segment-validation-failed`))return;y(an,this).startLoading(),T(sn,this,(y(sn,this)+1)%1e9),T(A,this,{request:e,requestId:y(sn,this),isSegmentDataCommandReceived:!1,controls:e.start({downloadSource:`p2p`,peerId:this.id},{notReceivingBytesTimeoutMs:y(fn,this).p2pNotReceivingBytesTimeoutMs,onAbort:t=>{if(!y(A,this)||y(A,this).request!==e)return;let{request:n,requestId:r}=y(A,this);if(v(M,this,vn).call(this,n.segment,r),y(an,this).stopLoading(),t.type!==`abort`&&(y(an,this).clear(),y(on,this).timestamp=0,y(j,this).call(this,`cleared bandwidth history due to ${t.type}`)),T(A,this,void 0),t.type===`bytes-receiving-timeout`){var i;T(rn,this,(i=y(rn,this),i++,i))}y(rn,this)>=y(fn,this).p2pErrorRetries?this.destroy(!1,new ne(`timeout`,`Too many timeout errors`)):t.type===`bytes-receiving-timeout`&&y(dn,this).onWarning(new re(`timeout-strike`,`Timeout strike ${y(rn,this)}/${y(fn,this).p2pErrorRetries}`))}})});let t={c:O.SegmentRequest,r:y(A,this).requestId,i:e.segment.externalId};e.loadedBytes&&(t.b=e.loadedBytes),v(M,this,bn).call(this,t)||v(M,this,_n).call(this,`peer-closed`)}uploadSegmentData(e,t,n){var r=this;return x(function*(){if(y(ln,r))return;if(t!==y(cn,r)){y(j,r).call(r,`discarding obsolete upload request ${t} for segment ${e.externalId}`);return}let{externalId:i}=e;y(j,r).call(r,`send segment ${e.externalId} to ${r.id} (byteLength: ${n.byteLength})`);let a={c:O.SegmentData,i,r:t,s:n.byteLength};if(v(M,r,bn).call(r,a))try{if(yield y(k,r).splitSegmentDataToChunksAndUploadAsync(n,t),r.isDestroyed||t!==y(cn,r))return;v(M,r,yn).call(r,e,t),y(j,r).call(r,`segment ${i} has been sent to ${r.id}`)}catch(e){y(j,r).call(r,`cancel segment uploading ${i}: %O`,e)}})()}sendSegmentsAnnouncementCommand(e,t){let n={c:O.SegmentsAnnouncement,p:t,l:e};v(M,this,bn).call(this,n)}sendSegmentAbsentCommand(e,t){v(M,this,bn).call(this,{c:O.SegmentAbsent,i:e,r:t})}destroy(e=!1,t){y(ln,this)||(T(ln,this,!0),v(M,this,_n).call(this,`peer-closed`,t),y(k,this).destroy(),e||y(un,this).call(this,t),y(j,this).call(this,`peer closed ${this.id}`))}};function gn(e,t){var n;(n=y(A,this))==null||n.request.clearLoadedBytes();let r=new ne(e,t);v(M,this,_n).call(this,`peer-closed`,r),this.destroy(!1,r)}function _n(e,t){if(!y(A,this))return;let{request:n,controls:r}=y(A,this),{segment:i}=n;y(j,this).call(this,`cancel segment request ${i.externalId} (${e})`);let a=new g(e,void 0,t);r.failWithError(a),y(an,this).stopLoading(),e!==`peer-segment-absent`&&(y(an,this).clear(),y(on,this).timestamp=0,y(j,this).call(this,`cleared bandwidth history due to ${a.type}`)),T(A,this,void 0)}function vn(e,t){v(M,this,bn).call(this,{c:O.CancelSegmentRequest,i:e.externalId,r:t})}function yn(e,t){v(M,this,bn).call(this,{c:O.SegmentDataSendingCompleted,r:t,i:e.externalId})}function bn(e){if(y(ln,this))return!1;try{return y(k,this).sendCommand(e),!0}catch(t){return y(j,this).call(this,`error sending command %d: %O`,e.c,t),!1}}var xn=class{constructor(){h(this,`events`,new Map)}dispatchEvent(e,t,n,r,i,a){let o=this.events.get(e);if(o)for(let e of o)try{e(t,n,r,i,a)}catch(e){}}getEventDispatcher(e){return(t,n,r,i,a)=>{let o=this.events.get(e);if(o)for(let e of o)try{e(t,n,r,i,a)}catch(e){}}}addEventListener(e,t){let n=this.events.get(e);n?this.events.set(e,[...n,t]):this.events.set(e,[t])}removeEventListener(e,t){let n=this.events.get(e);if(!n)return;let r=n.indexOf(t);if(r===-1)return;if(n.length===1){this.events.delete(e);return}let i=n.slice();i.splice(r,1),this.events.set(e,i)}clear(){this.events.clear()}},Sn,Cn,wn,Tn,N=typeof window<`u`?window:{},En=(Sn=(Cn=N.RTCPeerConnection)==null?N.webkitRTCPeerConnection:Cn)==null?N.mozRTCPeerConnection:Sn,Dn=(wn=(Tn=N.RTCSessionDescription)==null?N.webkitRTCSessionDescription:Tn)==null?N.mozRTCSessionDescription:wn,On=(()=>{if(!N.RTCPeerConnection&&!N.webkitRTCPeerConnection&&!N.mozRTCPeerConnection)return!1;let e;try{e=new En;let t=e.createOffer();if(typeof(t==null?void 0:t.then)==`function`)return t.catch(()=>{}),!0}catch(e){}finally{try{e==null||e.close()}catch(e){}}return!1})();function kn(e,t){return On?e.createOffer(t):new Promise((n,r)=>{try{e.createOffer(n,r,t)}catch(e){r(e)}})}function An(e,t){return On?e.createAnswer(t):new Promise((n,r)=>{try{e.createAnswer(n,r,t)}catch(e){r(e)}})}function jn(e,t){return On?e.setLocalDescription(t):new Promise((n,r)=>{try{e.setLocalDescription(t,n,r)}catch(e){r(e)}})}function Mn(e,t){return On?e.setRemoteDescription(t):new Promise((n,r)=>{try{e.setRemoteDescription(t,n,r)}catch(e){r(e)}})}var Nn=5e4,Pn=15e3,Fn=5,In=5e3;function Ln(){let e=``;for(let t=0;t<20;t++)e+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*62));return e}var Rn=new Set([`offer`,`answer`,`pranswer`,`rollback`]);function zn(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.type==`string`&&Rn.has(t.type)&&typeof t.sdp==`string`}var P=new WeakMap,F=new WeakMap,I=new WeakMap,Bn=new WeakMap,L=new WeakMap,R=new WeakMap,Vn=new WeakMap,Hn=new WeakMap,Un=new WeakMap,Wn=new WeakMap,Gn=new WeakMap,Kn=new WeakMap,qn=new WeakMap,z=new WeakSet,Jn=new WeakMap,Yn=new WeakMap,Xn=new WeakMap,Zn=class{constructor(e){var t,n,r,i,a,o;w(this,z),_(this,P,void 0),_(this,F,void 0),_(this,I,new xn),_(this,Bn,new Map),_(this,L,new Set),_(this,R,new pe),_(this,Vn,null),_(this,Hn,null),_(this,Un,0),_(this,Wn,null),_(this,Gn,void 0),_(this,Kn,null),_(this,qn,!1),_(this,Jn,()=>{v(z,this,Qn).call(this,dr._),v(z,this,er).call(this,`started`).catch(e=>{v(z,this,B).call(this)||y(I,this).dispatchEvent(`error`,new ie(`announce-failed`,`Initial announce failed: ${e instanceof Error?e.message:String(e)}`,e))})}),_(this,Yn,()=>{v(z,this,$n).call(this),T(Hn,this,null)}),_(this,Xn,e=>{if(v(z,this,B).call(this))return;let t;try{let n=typeof e==`string`?e:new TextDecoder().decode(e);t=JSON.parse(n)}catch(e){y(I,this).dispatchEvent(`error`,new ie(`parse-error`,`Failed to parse tracker message: ${e instanceof Error?e.message:String(e)}`,e));return}if(typeof t!=`object`||!t||Array.isArray(t))return;let n=t,r=n.info_hash;if(typeof r==`string`&&r!==y(P,this).infoHash)return;let i=n[`warning message`];typeof i==`string`&&y(I,this).dispatchEvent(`warning`,new ae(`tracker-response`,i));let a=n[`failure reason`];if(typeof a==`string`){y(I,this).dispatchEvent(`error`,new ie(`tracker-response`,a));return}let{interval:o}=n;if(typeof o==`number`&&o>0){let e=Math.max(fr._,o);y(Hn,this)!==e&&v(z,this,Qn).call(this,e)}let s=n[`tracker id`];typeof s==`string`&&T(Kn,this,s);let c=n.peer_id;if(typeof c==`string`&&c===y(P,this).peerId)return;let l=n.offer_id;typeof c!=`string`||typeof l!=`string`||(zn(n.offer)?v(z,this,ir).call(this,{sdp:n.offer,peerId:c,offerId:l}).catch(e=>{v(z,this,B).call(this)||y(I,this).dispatchEvent(`error`,new ie(`signaling-failed`,`Failed to handle offer: ${e instanceof Error?e.message:String(e)}`,e))}):zn(n.answer)&&v(z,this,ar).call(this,{sdp:n.answer,peerId:c,offerId:l}).catch(e=>{v(z,this,B).call(this)||y(I,this).dispatchEvent(`error`,new ie(`signaling-failed`,`Failed to handle answer: ${e instanceof Error?e.message:String(e)}`,e))}))}),T(P,this,{infoHash:e.infoHash,peerId:e.peerId,rtcConfig:e.rtcConfig,channelConfig:e.channelConfig,offerTimeout:(t=e.offerTimeout)==null?(()=>Nn):t,offersCount:(n=e.offersCount)==null?(()=>Fn):n,iceGatheringTimeout:(r=e.iceGatheringTimeout)==null?(()=>In):r,connectionTimeout:(i=e.connectionTimeout)==null?(()=>Pn):i,claimPeer:(a=e.claimPeer)==null?(()=>!0):a,shouldGenerateOffers:(o=e.shouldGenerateOffers)==null?(()=>!0):o}),T(F,this,e.wsClient)}addEventListener(e,t){y(I,this).addEventListener(e,t)}removeEventListener(e,t){y(I,this).removeEventListener(e,t)}start(){v(z,this,B).call(this)||y(qn,this)||(T(qn,this,!0),y(F,this).addEventListener(`connected`,y(Jn,this)),y(F,this).addEventListener(`disconnected`,y(Yn,this)),y(F,this).addEventListener(`message`,y(Xn,this)),y(F,this).state===`connected`&&y(Jn,this).call(this))}destroy(){v(z,this,B).call(this)||(y(R,this).abort(),v(z,this,$n).call(this),v(z,this,nr).call(this),v(z,this,lr).call(this),v(z,this,ur).call(this),y(qn,this)&&(y(F,this).removeEventListener(`connected`,y(Jn,this)),y(F,this).removeEventListener(`disconnected`,y(Yn,this)),y(F,this).removeEventListener(`message`,y(Xn,this))),y(I,this).clear())}};function B(){return y(R,this).signal.aborted}function V(){if(y(R,this).signal.aborted)throw Error(`Client destroyed`)}function Qn(e){var t=this,n;v(z,this,$n).call(this),T(Hn,this,e);let r=T(Un,this,(n=y(Un,this),++n)),i=function(){var e=x(function*(){try{yield v(z,t,er).call(t)}catch(e){if(v(z,t,B).call(t))return;y(I,t).dispatchEvent(`error`,new ie(`announce-failed`,`Announce failed: ${e instanceof Error?e.message:String(e)}`,e))}!v(z,t,B).call(t)&&y(Hn,t)!==null&&y(Un,t)===r&&T(Vn,t,setTimeout(i,y(Hn,t)*1e3))});return function(){return e.apply(this,arguments)}}();T(Vn,this,setTimeout(i,e*1e3))}function $n(){y(Vn,this)!==null&&(clearTimeout(y(Vn,this)),T(Vn,this,null))}function er(e){var t=this;return x(function*(){if(v(z,t,B).call(t)||y(F,t).state!==`connected`)return;if(e&&T(Gn,t,e),y(Wn,t))return y(Wn,t);let n=x(function*(){let e=y(P,t).shouldGenerateOffers()?y(P,t).offersCount():0,n=yield Promise.all(Array.from({length:e},()=>v(z,t,tr).call(t)));if(v(z,t,B).call(t)){for(let e of n)e&&v(z,t,cr).call(t,e.offer_id);return}let r=[];for(let e of n)e&&r.push(e);let i=y(Gn,t);T(Gn,t,void 0);let a=v(z,t,rr).call(t,{numwant:r.length,offers:r,event:i});if(y(F,t).state!==`connected`){for(let e of r)v(z,t,cr).call(t,e.offer_id);return}try{y(F,t).send(JSON.stringify(a))}catch(e){for(let e of r)v(z,t,cr).call(t,e.offer_id);throw e}})();T(Wn,t,n);try{yield n}finally{y(Wn,t)===n&&T(Wn,t,null)}})()}function tr(){var e=this;return x(function*(){if(v(z,e,B).call(e))return;let t;try{var n,r;t=new En((n=(r=y(P,e)).rtcConfig)==null?void 0:n.call(r)),y(L,e).add(t);let i=t.createDataChannel(`webtorrent`,y(P,e).channelConfig),a=yield kn(t);v(z,e,V).call(e),yield jn(t,a),v(z,e,V).call(e),yield v(z,e,or).call(e,t),v(z,e,V).call(e);let o=t.localDescription;if(!(o!=null&&o.sdp)){t.close();return}let s=Ln();return y(Bn,e).set(s,{connection:t,channel:i,timeoutId:setTimeout(()=>{v(z,e,cr).call(e,s)},y(P,e).offerTimeout())}),{offer:{type:o.type,sdp:o.sdp},offer_id:s}}catch(n){t==null||t.close(),v(z,e,B).call(e)||y(I,e).dispatchEvent(`warning`,new ae(`offer-failed`,`Failed to create offer: ${n instanceof Error?n.message:String(n)}`,n))}finally{t&&y(L,e).delete(t)}})()}function nr(){if(y(F,this).state!==`connected`)return;let e=v(z,this,rr).call(this,{numwant:0,offers:[],event:`stopped`});try{y(F,this).send(JSON.stringify(e))}catch(e){}}function rr({numwant:e,offers:t,event:n}){let r={action:`announce`,info_hash:y(P,this).infoHash,peer_id:y(P,this).peerId,numwant:e,uploaded:0,downloaded:0,offers:t};return n&&(r.event=n),y(Kn,this)&&(r.trackerid=y(Kn,this)),r}function ir({sdp:e,peerId:t,offerId:n}){var r=this;return x(function*(){if(v(z,r,B).call(r)||!y(P,r).claimPeer(t))return;let i;try{var a,o;i=new En((a=(o=y(P,r)).rtcConfig)==null?void 0:a.call(o)),y(L,r).add(i),yield Mn(i,new Dn(e)),v(z,r,V).call(r);let s=yield An(i);v(z,r,V).call(r),yield jn(i,s),v(z,r,V).call(r),yield v(z,r,or).call(r,i),v(z,r,V).call(r);let c=i.localDescription;if(!c)throw Error(`Failed to get local description after ICE gathering`);let l={action:`announce`,info_hash:y(P,r).infoHash,peer_id:y(P,r).peerId,to_peer_id:t,offer_id:n,answer:{type:c.type,sdp:c.sdp}};y(F,r).send(JSON.stringify(l));let u=yield v(z,r,sr).call(r,i);v(z,r,V).call(r),y(I,r).dispatchEvent(`peerConnected`,{peerId:t,connection:i,channel:u})}catch(e){i==null||i.close(),y(I,r).dispatchEvent(`peerConnectFailed`,{peerId:t,error:new oe(`connection-failed`,e instanceof Error?e.message:String(e),e)})}finally{i&&y(L,r).delete(i)}})()}function ar({sdp:e,peerId:t,offerId:n}){var r=this;return x(function*(){if(v(z,r,B).call(r))return;let i=y(Bn,r).get(n);if(i){if(y(Bn,r).delete(n),clearTimeout(i.timeoutId),!y(P,r).claimPeer(t)){i.connection.close();return}y(L,r).add(i.connection);try{yield Mn(i.connection,new Dn(e)),v(z,r,V).call(r);let n=yield v(z,r,sr).call(r,i.connection,i.channel);v(z,r,V).call(r),y(I,r).dispatchEvent(`peerConnected`,{peerId:t,connection:i.connection,channel:n})}catch(e){i.connection.close(),y(I,r).dispatchEvent(`peerConnectFailed`,{peerId:t,error:new oe(`connection-failed`,e instanceof Error?e.message:String(e),e)})}finally{y(L,r).delete(i.connection)}}})()}function or(e){return new Promise((t,n)=>{if(e.iceGatheringState===`complete`){t();return}if(e.signalingState===`closed`){n(Error(`RTCPeerConnection closed`));return}let r,i=()=>{clearTimeout(r),e.removeEventListener(`icegatheringstatechange`,a),e.removeEventListener(`icecandidate`,o),e.removeEventListener(`signalingstatechange`,s),y(R,this).signal.removeEventListener(`abort`,c)},a=()=>{e.iceGatheringState===`complete`&&(i(),t())},o=e=>{e.candidate===null&&(i(),t())},s=()=>{e.signalingState===`closed`&&(i(),n(Error(`RTCPeerConnection closed`)))},c=()=>{i(),n(Error(`ICE gathering aborted due to teardown`))};if(y(R,this).signal.aborted){c();return}r=setTimeout(()=>{i(),t()},y(P,this).iceGatheringTimeout()),e.addEventListener(`icegatheringstatechange`,a),e.addEventListener(`icecandidate`,o),e.addEventListener(`signalingstatechange`,s),y(R,this).signal.addEventListener(`abort`,c)})}function sr(e,t){let{promise:n,resolve:r,reject:i}=xe(),a,o=t,s=()=>Ft(e.iceConnectionState)?(m(),i(Error(`ICE connection ${e.iceConnectionState}`)),!0):!1,c=()=>{m(),o?r(o):i(Error(`Data channel missing on open`))},l=()=>{m(),i(Error(`Data channel error`))},u=()=>{m(),i(Error(`Data channel closed prematurely`))},d=e=>{o=e,e.readyState===`open`?c():e.readyState===`closed`||e.readyState===`closing`?u():(e.addEventListener(`open`,c),e.addEventListener(`error`,l),e.addEventListener(`close`,u),e.addEventListener(`closing`,u))},f=e=>{o||d(e.channel)},p=()=>{m(),i(Error(`Connection aborted due to teardown`))},m=()=>{clearTimeout(a),e.removeEventListener(`iceconnectionstatechange`,s),e.removeEventListener(`datachannel`,f),o&&(o.removeEventListener(`open`,c),o.removeEventListener(`error`,l),o.removeEventListener(`close`,u),o.removeEventListener(`closing`,u)),y(R,this).signal.removeEventListener(`abort`,p)};return y(R,this).signal.aborted?(p(),n):s()?n:(a=setTimeout(()=>{m(),i(Error(`Data channel open timeout`))},y(P,this).connectionTimeout()),e.addEventListener(`iceconnectionstatechange`,s),y(R,this).signal.addEventListener(`abort`,p),o?d(o):e.addEventListener(`datachannel`,f),n)}function cr(e,t){let n=t==null?y(Bn,this).get(e):t;n&&(clearTimeout(n.timeoutId),n.connection.close(),y(Bn,this).delete(e))}function lr(){for(let[e,t]of y(Bn,this))v(z,this,cr).call(this,e,t)}function ur(){for(let e of y(L,this))e.close();y(L,this).clear()}var dr={_:120},fr={_:20},pr=50,mr=1.5,H=new WeakMap,U=new WeakMap,W=new WeakMap,G=new WeakMap,hr=new WeakMap,gr=new WeakMap,_r=new WeakMap,vr=new WeakMap,yr=new WeakSet,br=class{constructor(e){var t,n;w(this,yr),_(this,H,void 0),_(this,U,new xn),_(this,W,new Set),_(this,G,new Map),_(this,hr,new Set),_(this,gr,!1),_(this,_r,!1),_(this,vr,e=>{if(y(gr,this)||y(W,this).has(e)||y(G,this).has(e))return!1;let t=Math.floor(y(H,this).maxPeers()*Math.max(1,y(H,this).maxPeersMultiplier()));return y(W,this).size+y(G,this).size>=t?!1:(y(W,this).add(e),!0)}),T(H,this,b(b({},e),{},{maxPeers:(t=e.maxPeers)==null?(()=>pr):t,maxPeersMultiplier:(n=e.maxPeersMultiplier)==null?(()=>mr):n}))}addEventListener(e,t){y(U,this).addEventListener(e,t)}removeEventListener(e,t){y(U,this).removeEventListener(e,t)}start(){if(!(y(gr,this)||y(_r,this))){T(_r,this,!0);try{for(let e of y(H,this).trackerUrls){let{client:t,release:n}=y(H,this).socketPool.acquire(e),r=!1;try{let i=new Zn({infoHash:y(H,this).infoHash,peerId:y(H,this).peerId,wsClient:t,rtcConfig:y(H,this).rtcConfig,channelConfig:y(H,this).channelConfig,claimPeer:y(vr,this),offersCount:y(H,this).offersCount,offerTimeout:y(H,this).offerTimeout,iceGatheringTimeout:y(H,this).iceGatheringTimeout,connectionTimeout:y(H,this).connectionTimeout,shouldGenerateOffers:()=>y(W,this).size+y(G,this).size<y(H,this).maxPeers()}),a=t=>{y(W,this).delete(t.peerId),v(yr,this,Sr).call(this,t.peerId,t.connection,t.channel,e)},o=t=>{y(W,this).has(t.peerId)&&(y(W,this).delete(t.peerId),y(U,this).dispatchEvent(`peerConnectFailed`,{peerId:t.peerId,trackerUrl:e,error:t.error}))},s=t=>{y(U,this).dispatchEvent(`warning`,{trackerUrl:e,warning:t})},c=t=>{y(U,this).dispatchEvent(`error`,{trackerUrl:e,error:t})};i.addEventListener(`peerConnected`,a),i.addEventListener(`peerConnectFailed`,o),i.addEventListener(`warning`,s),i.addEventListener(`error`,c),y(hr,this).add({client:i,releaseSocket:n,cleanupListeners:()=>{i.removeEventListener(`peerConnected`,a),i.removeEventListener(`peerConnectFailed`,o),i.removeEventListener(`warning`,s),i.removeEventListener(`error`,c)}}),r=!0,i.start()}catch(e){throw r||n(),e}}}catch(e){throw this.destroy(),e}}}destroy(){if(y(gr,this))return;T(gr,this,!0);for(let{client:e,releaseSocket:t,cleanupListeners:n}of y(hr,this))n(),e.destroy(),t();y(hr,this).clear(),y(W,this).clear();let e=[...y(G,this).entries()];y(G,this).clear();for(let[t,n]of e){n.cleanup();try{n.channel.close()}catch(e){}try{n.connection.close()}catch(e){}y(U,this).dispatchEvent(`peerDisconnected`,{peerId:t,trackerUrl:n.trackerUrl,disconnectReason:`Manager destroyed`})}y(U,this).clear()}};function xr(e,t){if(y(gr,this))return;let n=y(G,this).get(e);if(n){y(G,this).delete(e),n.cleanup();try{n.channel.close()}catch(e){}try{n.connection.close()}catch(e){}y(U,this).dispatchEvent(`peerDisconnected`,b({peerId:e,trackerUrl:n.trackerUrl},t))}}function Sr(e,t,n,r){if(Ft(t.iceConnectionState)){try{t.close()}catch(e){}y(U,this).dispatchEvent(`peerConnectFailed`,{peerId:e,trackerUrl:r,error:new oe(`connection-failed`,`Connection failed during promotion`)});return}let i=t=>v(yr,this,xr).call(this,e,t),a=()=>{Ft(t.iceConnectionState)&&i({error:new ne(`connection-lost`,`ICE connection state became ${t.iceConnectionState}`)})},o=()=>i({disconnectReason:`Data channel closed`}),s=()=>i({disconnectReason:`Data channel closing`}),c=e=>{i({error:new ne(`transport-error`,`Data channel error: ${Pt(e,`Data channel error`)}`)})},l=t=>v(yr,this,xr).call(this,e,t?{error:t}:{disconnectReason:`Closed by consumer`});y(G,this).set(e,{connection:t,channel:n,trackerUrl:r,cleanup:()=>{l=null,t.removeEventListener(`iceconnectionstatechange`,a),n.removeEventListener(`close`,o),n.removeEventListener(`closing`,s),n.removeEventListener(`error`,c)}}),t.addEventListener(`iceconnectionstatechange`,a),n.addEventListener(`close`,o),n.addEventListener(`closing`,s),n.addEventListener(`error`,c),y(U,this).dispatchEvent(`peerConnected`,{peerId:e,connection:t,channel:n,trackerUrl:r,close:e=>l==null?void 0:l(e)})}function Cr(e){let t=Ee(e),n=[],r=t.length*8;for(let e=0;e<t.length;e++)n[e>>2]|=(t[e]&255)<<24-e%4*8;n[r>>5]|=128<<24-r%32,n[(r+64>>9<<4)+15]=r;let i=1732584193,a=4023233417,o=2562383102,s=271733878,c=3285377520,l=[];for(let e=0;e<n.length;e+=16){let t=i,r=a,u=o,d=s,f=c;for(let t=0;t<80;t++){if(t<16)l[t]=n[e+t]|0;else{let e=l[t-3]^l[t-8]^l[t-14]^l[t-16];l[t]=e<<1|e>>>31}let r;r=t<20?(a&o|~a&s)+1518500249:t<40?(a^o^s)+1859775393:t<60?(a&o|a&s|o&s)-1894007588:(a^o^s)-899497514;let u=(i<<5|i>>>27)+c+(l[t]>>>0)+r|0;c=s,s=o,o=a<<30|a>>>2,a=i,i=u}i=i+t|0,a=a+r|0,o=o+u|0,s=s+d|0,c=c+f|0}let u=``,d=[i,a,o,s,c];for(let e=0;e<20;e++){let t=24-e%4*8,n=d[e>>2];u+=String.fromCharCode(n>>>t&255)}return u}var wr=`v2`;function Tr({bitrate:e,codecs:t,width:n,height:r,language:i,channels:a,name:o,frameRate:s,videoRange:c}){let l=t?t.split(`,`).map(e=>{e=e.trim().toLowerCase();let t=e.split(`.`);if(t.length===3&&(t[0]===`avc1`||t[0]===`avc`)){let n=parseInt(t[1],10),r=parseInt(t[2],10);if(!isNaN(n)&&!isNaN(r)&&t[1]===n.toString()&&t[2]===r.toString()){let i=`00${n.toString(16)}`.slice(-2),a=`00${r.toString(16)}`.slice(-2);e=`${t[0]}.${i}00${a}`}}return e}).sort().join(`,`):``,u=i&&i!==`und`?i.slice(0,2).toLowerCase():``,d=a?a.toString().split(`/`)[0]:``,f=o?o.toLowerCase().trim():``,p=s&&!isNaN(Number(s))?Number(s).toString():``,m=c?c.toUpperCase().trim():``,ee=`${e==null?0:e}-${l}-${n==null?``:n}-${r==null?``:r}-${u}-${d}-${f}-${p}-${m}`;return btoa(Cr(ee))}function Er(e,t){return`${wr}-${e}-${kr(t)}`}function Dr(e,t){for(let n of e.values()){let e=n.segments.get(t);if(e)return e}}function Or(e,t){for(let n of e.segments.values())if(n.externalId===t)return n}function kr(e){return`${e.type}-${e.index}`}function Ar(e){let{segments:t}=e,n=0,{size:r}=t;if(r===0)return 0;for(let e of t.values()){let t=e.endTime-e.startTime;n+=t}return n/r}function jr(e,t){let{highDemandTimeWindow:n,httpDownloadTimeWindow:r,p2pDownloadTimeWindow:i}=e,a={highDemandTimeWindow:n,httpDownloadTimeWindow:r,p2pDownloadTimeWindow:i};return t<=5?(a.httpDownloadTimeWindow=0,a.p2pDownloadTimeWindow=0):t<=10&&(a.p2pDownloadTimeWindow=a.httpDownloadTimeWindow),a}function Mr(e,t,n,r,i){let{highDemandTimeWindow:a,httpDownloadTimeWindow:o,p2pDownloadTimeWindow:s}=jr(n,i);return{isHighDemand:Nr(e,t,a),isHttpDownloadable:Nr(e,t,o),isP2PDownloadable:Nr(e,t,s)&&r.isSegmentLoadingOrLoadedBySomeone(e)}}function Nr(e,t,n){let{startTime:r,endTime:i}=e,{position:a,rate:o}=t;return!(a+n*o<r||a>i)}var Pr=`-PM${zr(`3.0.1`)}-`,Fr=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`,Ir=20;function Lr(e){return btoa(Cr(e).slice(0,15))}function Rr(e){let t=[e],n=Ir-e.length;for(let e=0;e<n;e++)t.push(Fr[Math.floor(Math.random()*62)]);return t.join(``)}function zr(e){let t=e.split(`.`);return`${`00${t[0]}`.slice(-2)}${`00${t[1]}`.slice(-2)}`}var Br=1e3,K=new WeakMap,q=new WeakMap,Vr=new WeakMap,Hr=new WeakMap,Ur=new WeakMap,Wr=new WeakMap,Gr=new WeakMap,J=new WeakMap,Kr=new WeakMap,Y=new WeakMap,qr=new WeakMap,Jr=new WeakMap,X=new WeakMap,Yr=new WeakMap,Xr=new WeakMap,Zr=new WeakMap,Qr=new WeakMap,$r=new WeakMap,ei=new WeakMap,ti=new WeakMap,ni=new WeakMap,ri=new WeakMap,ii=new WeakMap,ai=new WeakMap,oi=new WeakMap,si=new WeakSet,ci=new WeakMap,li=new WeakMap,ui=new WeakMap,di=new WeakMap,fi=class{constructor(e,t,n,r,i,a,o,s,c){var l=this,u;w(this,si),_(this,K,void 0),_(this,q,new Map),_(this,Vr,void 0),_(this,Hr,void 0),_(this,Ur,!1),_(this,Wr,(0,S.default)(`p2pml-core:webtorrent-manager`)),_(this,Gr,(0,S.default)(`p2pml-core:churn-cleanup`)),_(this,J,void 0),_(this,Kr,void 0),_(this,Y,void 0),_(this,qr,void 0),_(this,Jr,void 0),_(this,X,void 0),_(this,Yr,void 0),_(this,Xr,void 0),_(this,Zr,void 0),_(this,Qr,void 0),_(this,$r,void 0),_(this,ei,void 0),_(this,ti,void 0),_(this,ni,void 0),_(this,ri,void 0),_(this,ii,void 0),_(this,ai,void 0),_(this,oi,()=>{T(Qr,this,setTimeout(y(oi,this),Math.max(Br,y(X,this).p2pChurnCleanupIntervalMs)));let e=y(q,this).size-y(X,this).p2pMaxPeers;if(e<=0)return;let t=[],n=performance.now();for(let e of y(q,this).values())e.downloadingSegment||e.isUploadingSegment||n-e.connectedAt<y(X,this).p2pChurnGracePeriodMs||t.push(e);if(t.length===0)return;t.sort((e,t)=>e.getDownloadBandwidth()-t.getDownloadBandwidth()||e.connectedAt-t.connectedAt);let r=t.slice(0,e);y(Gr,this).call(this,`Background churn cleanup: dropping ${r.length} excess peers (total: ${y(q,this).size}, target: ${y(X,this).p2pMaxPeers}, eligible: ${t.length})`);for(let e of r)y(Gr,this).call(this,`dropping excess peer ${e.id} with bandwidth ${e.getDownloadBandwidth()}`),e.destroy()}),_(this,ci,e=>{if(y(Wr,this).call(this,`peerConnected: peerId=${e.peerId}`),y(q,this).has(e.peerId)){e.close();return}let t=new hn(e.peerId,e.channel,e.close,{onSegmentRequested:(e,t,n,r)=>{y(di,this).call(this,e,t,n,r).catch(n=>{y(Wr,this).call(this,`Error in onSegmentRequested ${t} for peer ${e.id}:`,n)})},onSegmentsAnnouncement:y(Zr,this),onWarning:e=>{y(ri,this).call(this,{peerId:t.id,infoHash:y(J,this),streamType:y(Y,this).type,warning:e})}},{p2pNotReceivingBytesTimeoutMs:y(X,this).p2pNotReceivingBytesTimeoutMs,webRtcMaxMessageSize:y(X,this).webRtcMaxMessageSize,p2pErrorRetries:y(X,this).p2pErrorRetries,validateP2PSegment:y(X,this).validateP2PSegment,streamType:y(Y,this).type,infoHash:y(J,this)},y(Xr,this));if(y(q,this).set(e.peerId,t),y($r,this).call(this,{peerId:e.peerId,infoHash:y(J,this),streamType:y(Y,this).type}),y(X,this).isP2PUploadDisabled)return;let{httpLoading:n,loaded:r}=v(si,this,pi).call(this);t.sendSegmentsAnnouncementCommand(r,n)}),_(this,li,e=>{var t;y(Wr,this).call(this,`peerDisconnected: peerId=%s error=%s reason=%s`,e.peerId,(t=e.error)==null?void 0:t.message,e.disconnectReason);let n=y(q,this).get(e.peerId);n&&(y(q,this).delete(e.peerId),n.destroy(!0),e.error&&y(ni,this).call(this,{peerId:e.peerId,infoHash:y(J,this),streamType:y(Y,this).type,error:e.error}),y(ti,this).call(this,{peerId:n.id,infoHash:y(J,this),streamType:y(Y,this).type}))}),h(this,`broadcastAnnouncement`,(e=!1)=>{if(e){y(ui,this).call(this,e);return}y(Ur,this)||y(X,this).isP2PUploadDisabled||y(ui,this).call(this)}),_(this,ui,(e=!1)=>{T(Ur,this,!0),Se(()=>{let{loaded:t=[],httpLoading:n=[]}=e?{}:v(si,this,pi).call(this);for(let e of y(q,this).values())e.sendSegmentsAnnouncementCommand(t,n);T(Ur,this,!1)})}),_(this,di,function(){var e=x(function*(e,t,n,r){let i=Or(y(Y,l),t);if(!i)return;if(y(X,l).isP2PUploadDisabled){e.sendSegmentAbsentCommand(t,n);return}let a;try{a=yield y(Jr,l).getSegmentData(y(Vr,l),y(Hr,l),i.externalId)}catch(n){y(Wr,l).call(l,`Storage error for segment ${t} requested by peer ${e.id}:`,n)}if(y(q,l).has(e.id)){if(!a){e.sendSegmentAbsentCommand(t,n);return}yield e.uploadSegmentData(i,n,r===void 0?a:new Uint8Array(a).subarray(r))}});return function(t,n,r,i){return e.apply(this,arguments)}}()),T(Kr,this,e),T(Y,this,t),T(qr,this,n),T(Jr,this,r),T(X,this,i),T(Yr,this,a),T(Xr,this,o),T(Zr,this,c),T($r,this,o.getEventDispatcher(`onPeerConnect`)),T(ei,this,o.getEventDispatcher(`onPeerConnectError`)),T(ti,this,o.getEventDispatcher(`onPeerClose`)),T(ni,this,o.getEventDispatcher(`onPeerError`)),T(ri,this,o.getEventDispatcher(`onPeerWarning`)),T(ii,this,o.getEventDispatcher(`onTrackerWarning`)),T(ai,this,o.getEventDispatcher(`onTrackerError`)),T(Vr,this,(u=y(X,this).swarmId)==null?y(Kr,this):u),T(Hr,this,Er(y(Vr,this),y(Y,this)));let d=Lr(y(Hr,this));T(J,this,d),T(K,this,new br({infoHash:d,peerId:s,trackerUrls:y(X,this).announceTrackers,rtcConfig:()=>y(X,this).rtcConfig,socketPool:y(Yr,this),maxPeers:()=>y(X,this).p2pMaxPeers,maxPeersMultiplier:()=>y(X,this).p2pChurnMaxPeersMultiplier,offersCount:()=>y(X,this).webRtcOffersCount,offerTimeout:()=>y(X,this).webRtcOfferTimeoutMs,iceGatheringTimeout:()=>y(X,this).webRtcIceGatheringTimeoutMs,connectionTimeout:()=>y(X,this).webRtcConnectionTimeoutMs})),y(K,this).addEventListener(`peerConnected`,y(ci,this)),y(K,this).addEventListener(`peerDisconnected`,y(li,this)),y(K,this).addEventListener(`peerConnectFailed`,e=>{y(Wr,this).call(this,`Peer connection failed (${e.peerId}) from tracker ${e.trackerUrl}:`,e.error),y(ei,this).call(this,{peerId:e.peerId,infoHash:y(J,this),streamType:y(Y,this).type,trackerUrl:e.trackerUrl,error:e.error})}),y(K,this).addEventListener(`warning`,e=>{y(Wr,this).call(this,`Tracker warning (${e.trackerUrl}):`,e.warning),y(ii,this).call(this,{trackerUrl:e.trackerUrl,infoHash:y(J,this),streamType:y(Y,this).type,warning:e.warning})}),y(K,this).addEventListener(`error`,e=>{y(Wr,this).call(this,`Tracker error (${e.trackerUrl}):`,e.error),y(ai,this).call(this,{trackerUrl:e.trackerUrl,infoHash:y(J,this),streamType:y(Y,this).type,error:e.error})}),y(Xr,this).addEventListener(`onStorageUpdated-${y(Hr,this)}`,this.broadcastAnnouncement),y(K,this).start(),T(Qr,this,setTimeout(y(oi,this),Math.max(Br,y(X,this).p2pChurnCleanupIntervalMs)))}downloadSegment(e){let t=[];for(let n of y(q,this).values())!n.downloadingSegment&&n.getSegmentStatus(e)===`loaded`&&t.push(n);if(t.length===0)return;let n=mi(t),r=y(qr,this).getOrCreateRequest(e);n.downloadSegment(r)}isSegmentLoadingOrLoadedBySomeone(e){for(let t of y(q,this).values())if(t.getSegmentStatus(e))return!0;return!1}isSegmentLoadedBySomeone(e){for(let t of y(q,this).values())if(t.getSegmentStatus(e)===`loaded`)return!0;return!1}get connectedPeerCount(){return y(q,this).size}*peers(){for(let e of y(q,this).values())yield e}destroy(){clearTimeout(y(Qr,this)),T(Qr,this,void 0),y(Xr,this).removeEventListener(`onStorageUpdated-${y(Hr,this)}`,this.broadcastAnnouncement),y(K,this).destroy();for(let e of y(q,this).values())e.destroy();y(q,this).clear()}};function pi(){let e=y(Jr,this).getStoredSegmentIds(y(Vr,this),y(Hr,this)),t=[];for(let e of y(qr,this).httpRequests()){let n=y(Y,this).segments.get(e.segment.runtimeId);n&&t.push(n.externalId)}return{loaded:e,httpLoading:t}}function mi(e){if(e.length===1)return e[0];let t=0;for(let n of e){let e=n.getDownloadBandwidth();e>t&&(t=e)}if(t>0){let n=Math.max(1,t*.1),r=0,i=0;for(let t of e)t.getDownloadBandwidth()<=n?r++:i+=t.getDownloadBandwidth();let a=n;return r>0&&i>0&&r*n>i&&(a=i/r),Te(e,e=>Math.max(e.getDownloadBandwidth(),a))}else return we(e)}function hi(e){return`${e.type}-${e.index}`}function gi(e){let{externalId:t}=e;return`(${hi(e.stream)} | ${t})`}var _i=new WeakMap,vi=new WeakMap,yi=new WeakMap,bi=new WeakMap,xi=new WeakMap,Si=new WeakMap,Ci=new WeakMap,wi=new WeakMap,Ti=new WeakMap,Ei=new WeakMap,Di=new WeakMap,Oi=new WeakSet,ki=class{constructor(e,t,n,r,i,a,o,s,c){w(this,Oi),_(this,_i,new Map),_(this,vi,void 0),_(this,yi,(0,S.default)(`p2pml-core:p2p-loaders-container`)),_(this,bi,void 0),_(this,xi,void 0),_(this,Si,void 0),_(this,Ci,void 0),_(this,wi,void 0),_(this,Ti,void 0),_(this,Ei,void 0),_(this,Di,void 0),T(bi,this,e),T(xi,this,n),T(Si,this,r),T(Ci,this,i),T(wi,this,a),T(Ti,this,o),T(Ei,this,s),T(Di,this,c),T(vi,this,v(Oi,this,ji).call(this,t)),y(yi,this).call(this,`set current p2p loader: ${hi(t)}`)}changeCurrentLoader(e){var t;let n=(t=y(Ci,this).swarmId)==null?y(bi,this):t,r=Er(n,y(vi,this).stream);y(Si,this).getStoredSegmentIds(n,r).length?v(Oi,this,Mi).call(this,y(vi,this)):v(Oi,this,Ni).call(this,y(vi,this)),T(vi,this,v(Oi,this,ji).call(this,e)),y(yi,this).call(this,`change current p2p loader: ${hi(e)}`)}get currentLoader(){return y(vi,this).loader}destroy(){for(let{loader:e,destroyTimeoutId:t}of y(_i,this).values())e.destroy(),clearTimeout(t);y(_i,this).clear()}};function Ai(e){if(y(_i,this).has(e.runtimeId))throw Error(`Loader for this stream already exists`);let t=new fi(y(bi,this),e,y(xi,this),y(Si,this),y(Ci,this),y(wi,this),y(Ti,this),y(Ei,this),()=>{y(vi,this).loader===t&&y(Di,this).call(this)}),n=hi(e);return y(yi,this).call(this,`created new loader: ${n}`),{loader:t,stream:e,loggerInfo:n}}function ji(e){let t=y(_i,this).get(e.runtimeId);if(t)return clearTimeout(t.destroyTimeoutId),t.destroyTimeoutId=void 0,t;{let t=v(Oi,this,Ai).call(this,e);return y(_i,this).set(e.runtimeId,t),t}}function Mi(e){e.destroyTimeoutId=window.setTimeout(()=>v(Oi,this,Ni).call(this,e),y(Ci,this).p2pInactiveLoaderDestroyTimeoutMs)}function Ni(e){e.loader.destroy(),y(_i,this).delete(e.stream.runtimeId),y(yi,this).call(this,`destroy p2p loader: `,e.loggerInfo)}function Pi(e){return{runtimeId:e.runtimeId,externalId:e.externalId,url:e.url,byteRange:e.byteRange,startTime:e.startTime,endTime:e.endTime}}var Fi=class{constructor(e,t,n,r,i,a,o){h(this,`segment`,void 0),h(this,`requestProcessQueueCallback`,void 0),h(this,`bandwidthCalculators`,void 0),h(this,`playback`,void 0),h(this,`playbackConfig`,void 0),h(this,`infoHash`,void 0),h(this,`currentAttempt`,void 0),h(this,`_failedAttempts`,new Ii),h(this,`finalData`,void 0),h(this,`bytes`,[]),h(this,`_loadedBytes`,0),h(this,`_totalBytes`,void 0),h(this,`_status`,`not-started`),h(this,`progress`,void 0),h(this,`notReceivingBytesTimeout`,void 0),h(this,`_onAbortCallback`,void 0),h(this,`notReceivingBytesTimeoutMs`,void 0),h(this,`_logger`,void 0),h(this,`_isHandledByProcessQueue`,!1),h(this,`onSegmentError`,void 0),h(this,`onSegmentAbort`,void 0),h(this,`onSegmentStart`,void 0),h(this,`onSegmentLoaded`,void 0),h(this,`abortOnTimeout`,()=>{var e,t;if(this.throwErrorIfNotLoadingStatus(),!this.currentAttempt||!this.progress||this.notReceivingBytesTimeoutMs===void 0)return;let n=performance.now()-((e=this.progress.lastLoadedChunkTimestamp)==null?this.progress.startTimestamp:e);if(n<this.notReceivingBytesTimeoutMs){this.notReceivingBytesTimeout.restart(this.notReceivingBytesTimeoutMs-n);return}let r=new g(`bytes-receiving-timeout`);(t=this._onAbortCallback)==null||t.call(this,r),this.handleFailure(r)}),h(this,`failWithError`,e=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&this.handleFailure(e)}),h(this,`handleFailure`,e=>{this.currentAttempt&&(this.setStatus(`failed`),this.logger(`${this.downloadSource} ${this.segment.externalId} failed ${e.type}`),this._failedAttempts.add(b(b({},this.currentAttempt),{},{error:e})),this.onSegmentError({segment:Pi(this.segment),error:e,downloadSource:this.currentAttempt.downloadSource,peerId:this.currentAttempt.downloadSource===`p2p`?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this.notReceivingBytesTimeout.clear(),this.manageBandwidthCalculatorsState(`stop`),this.requestProcessQueueCallback())}),h(this,`completeOnSuccess`,()=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&(this.manageBandwidthCalculatorsState(`stop`),this.notReceivingBytesTimeout.clear(),this.setStatus(`succeed`),this._totalBytes=this._loadedBytes,this.onSegmentLoaded({segmentUrl:this.segment.url,segment:Pi(this.segment),bytesLength:this.data.byteLength,downloadSource:this.currentAttempt.downloadSource,peerId:this.currentAttempt.downloadSource===`p2p`?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this.logger(`${this.currentAttempt.downloadSource} ${this.segment.externalId} succeed`),this.requestProcessQueueCallback())}),h(this,`addLoadedChunk`,e=>{if(this.throwErrorIfNotLoadingStatus(),!this.currentAttempt||!this.progress)return;let{byteLength:t}=e,{all:n,http:r}=this.bandwidthCalculators;n.addBytes(t),this.currentAttempt.downloadSource===`http`&&r.addBytes(t),this.bytes.push(e),this.progress.lastLoadedChunkTimestamp=performance.now(),this.progress.loadedBytes+=t,this._loadedBytes+=t}),h(this,`firstBytesReceived`,()=>{this.throwErrorIfNotLoadingStatus()}),this.segment=e,this.requestProcessQueueCallback=t,this.bandwidthCalculators=n,this.playback=r,this.playbackConfig=i,this.infoHash=o,this.onSegmentError=a.getEventDispatcher(`onSegmentError`),this.onSegmentAbort=a.getEventDispatcher(`onSegmentAbort`),this.onSegmentStart=a.getEventDispatcher(`onSegmentStart`),this.onSegmentLoaded=a.getEventDispatcher(`onSegmentLoaded`);let{byteRange:s}=this.segment;if(s){let{end:e,start:t}=s;this._totalBytes=e-t+1}this.notReceivingBytesTimeout=new Li(this.abortOnTimeout);let{type:c}=this.segment.stream;this._logger=(0,S.default)(`p2pml-core:request-${c}`)}clearLoadedBytes(){this._loadedBytes=0,this.bytes=[],this._totalBytes=void 0,this.finalData=void 0}get status(){return this._status}setStatus(e){this._status=e,this._isHandledByProcessQueue=!1}get downloadSource(){var e;return(e=this.currentAttempt)==null?void 0:e.downloadSource}get loadedBytes(){return this._loadedBytes}get totalBytes(){return this._totalBytes}get data(){return this.finalData!=null||(this.finalData=Ce(this.bytes).buffer),this.finalData}get failedAttempts(){return this._failedAttempts}get isHandledByProcessQueue(){return this._isHandledByProcessQueue}markHandledByProcessQueue(){this._isHandledByProcessQueue=!0}setTotalBytes(e){if(this._totalBytes!==void 0)throw Error(`Request total bytes value is already set`);this._totalBytes=e}tryCompleteByLoadedBytes(e,t,n,r){if(!this._totalBytes)return!1;if(this._loadedBytes>this._totalBytes)return this.logger(`${e.downloadSource} ${this.segment.externalId} loaded bytes overflow: ${this._loadedBytes} > ${this._totalBytes}, clearing`),this.clearLoadedBytes(),!1;if(this._loadedBytes!==this._totalBytes)return!1;let i=this.start(e,t);return this.notReceivingBytesTimeout.clear(),n?this.validateAndComplete(e.downloadSource,i,n,r):i.completeOnSuccess(),!0}validateData(e){var t=this;return x(function*(){if(!e)return!0;try{return yield e(t.segment.url,t.segment.byteRange,t.data)}catch(e){return t.logger(`validation threw an error: ${String(e)}`),!1}})()}validateAndComplete(e,t,n,r){var i=this;return x(function*(){let a=yield i.validateData(n);if(i._status===`loading`){if(!a){i.logger(`${e} ${i.segment.externalId} validation failed for already-loaded bytes, clearing`),i.clearLoadedBytes(),t.failWithError(new g(r));return}i.logger(`${e} ${i.segment.externalId} validation passed for already-loaded bytes`),t.completeOnSuccess()}})()}start(e,t){if(this._status===`succeed`)throw Error(`Request ${this.segment.externalId} has been already succeed.`);if(this._status===`loading`)throw Error(`Request ${this.segment.externalId} has been already started.`);this.setStatus(`loading`),this.currentAttempt=b({},e),this.progress={startFromByte:this._loadedBytes,loadedBytes:0,startTimestamp:performance.now()},this.manageBandwidthCalculatorsState(`start`);let{notReceivingBytesTimeoutMs:n}=t;return this._onAbortCallback=t.onAbort,this.notReceivingBytesTimeoutMs=n,n!==void 0&&this.notReceivingBytesTimeout.start(n),this.logger(`${e.downloadSource} ${this.segment.externalId} started`),this.onSegmentStart({segment:Pi(this.segment),downloadSource:e.downloadSource,peerId:e.downloadSource===`p2p`?e.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),{firstBytesReceived:this.firstBytesReceived,addLoadedChunk:this.addLoadedChunk,completeOnSuccess:this.completeOnSuccess,failWithError:this.failWithError}}cancel(){var e,t,n,r;this.throwErrorIfNotLoadingStatus(),this.setStatus(`aborted`),this.logger(`${(e=this.currentAttempt)==null?void 0:e.downloadSource} ${this.segment.externalId} aborted`),(t=this._onAbortCallback)==null||t.call(this,new g(`abort`)),this.onSegmentAbort({segment:Pi(this.segment),downloadSource:(n=this.currentAttempt)==null?void 0:n.downloadSource,peerId:((r=this.currentAttempt)==null?void 0:r.downloadSource)===`p2p`?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this._onAbortCallback=void 0,this.manageBandwidthCalculatorsState(`stop`),this.notReceivingBytesTimeout.clear()}throwErrorIfNotLoadingStatus(){if(this._status!==`loading`)throw Error(`Request has been already ${this.status}.`)}logger(e){var t;this._logger.color=((t=this.currentAttempt)==null?void 0:t.downloadSource)===`http`?`green`:`red`,this._logger(e),this._logger.color=``}manageBandwidthCalculatorsState(e){var t;let{all:n,http:r}=this.bandwidthCalculators,i=e===`start`?`startLoading`:`stopLoading`;((t=this.currentAttempt)==null?void 0:t.downloadSource)===`http`&&r[i](),n[i]()}},Ii=class{constructor(){h(this,`attempts`,[])}add(e){this.attempts.push(e)}get httpAttemptsCount(){return this.attempts.reduce((e,t)=>t.downloadSource===`http`?e+1:e,0)}get p2pAttemptsCount(){return this.attempts.reduce((e,t)=>t.downloadSource===`p2p`?e+1:e,0)}get lastAttempt(){return this.attempts[this.attempts.length-1]}clear(){this.attempts=[]}},Li=class{constructor(e){h(this,`action`,void 0),h(this,`timeoutId`,void 0),h(this,`ms`,void 0),this.action=e}start(e){if(this.timeoutId)throw Error(`Timeout is already started.`);this.ms=e,this.timeoutId=window.setTimeout(this.action,this.ms)}restart(e){this.clear(),e!==void 0&&(this.ms=e),this.ms!==void 0&&(this.timeoutId=window.setTimeout(this.action,this.ms))}clear(){clearTimeout(this.timeoutId),this.timeoutId=void 0}},Ri=class{constructor(e,t,n,r,i,a){h(this,`requestProcessQueueCallback`,void 0),h(this,`bandwidthCalculators`,void 0),h(this,`playback`,void 0),h(this,`config`,void 0),h(this,`eventTarget`,void 0),h(this,`swarmId`,void 0),h(this,`requests`,new Map),this.requestProcessQueueCallback=e,this.bandwidthCalculators=t,this.playback=n,this.config=r,this.eventTarget=i,this.swarmId=a}get executingHttpCount(){let e=0;for(let t of this.httpRequests())t.status===`loading`&&e++;return e}get executingP2PCount(){let e=0;for(let t of this.p2pRequests())t.status===`loading`&&e++;return e}get(e){return this.requests.get(e)}getOrCreateRequest(e){let t=this.requests.get(e);if(!t){let n=Lr(Er(this.swarmId,e.stream));t=new Fi(e,this.requestProcessQueueCallback,this.bandwidthCalculators,this.playback,this.config,this.eventTarget,n),this.requests.set(e,t)}return t}remove(e){this.requests.delete(e.segment)}items(){return this.requests.values()}*httpRequests(){for(let e of this.requests.values())e.downloadSource===`http`&&(yield e)}*p2pRequests(){for(let e of this.requests.values())e.downloadSource===`p2p`&&(yield e)}destroy(){for(let e of this.requests.values())e.status===`loading`&&e.cancel();this.requests.clear()}},zi=class{constructor(e,t){h(this,`segment`,void 0),h(this,`engineCallbacks`,void 0),h(this,`_status`,`pending`),h(this,`_shouldBeStartedImmediately`,!1),this.segment=e,this.engineCallbacks=t}get status(){return this._status}get shouldBeStartedImmediately(){return this._shouldBeStartedImmediately}resolve(e,t){this._status===`pending`&&(this._status=`succeed`,this.engineCallbacks.onSuccess({data:e,bandwidth:t}))}reject(){this._status===`pending`&&(this._status=`failed`,this.engineCallbacks.onError(new se(`failed`)))}abort(){this._status===`pending`&&(this._status=`aborted`,this.engineCallbacks.onError(new se(`aborted`)))}markAsShouldBeStartedImmediately(){this._shouldBeStartedImmediately=!0}};function*Bi(e,t,n,r,i){let{runtimeId:a,stream:o}=e,s=o.segments.get(a);if(!s)return;let c=o.segments.values(),l;do{let e=c.next();if(e.done)return;l=e.value}while(l!==s);let u=Mr(l,t,n,r,i);if(Vi(u)){let e=c.next();if(e.done)return;let a=e.value,o=Mr(a,t,n,r,i);if(Vi(o))return;u.isHighDemand=!0,yield{segment:l,statuses:u},yield{segment:a,statuses:o}}else yield{segment:l,statuses:u};for(let e of c){let a=Mr(e,t,n,r,i);if(Vi(a))break;yield{segment:e,statuses:a}}}function Vi(e){let{isHighDemand:t,isHttpDownloadable:n,isP2PDownloadable:r}=e;return!t&&!n&&!r}var Hi=6e4,Ui=1e3,Wi=class{constructor(e,t,n,r,i,a,o,s,c){var l;h(this,`streamManifestUrl`,void 0),h(this,`lastRequestedSegment`,void 0),h(this,`streamDetails`,void 0),h(this,`config`,void 0),h(this,`bandwidthCalculators`,void 0),h(this,`segmentStorage`,void 0),h(this,`webTorrentSocketPool`,void 0),h(this,`eventTarget`,void 0),h(this,`peerId`,void 0),h(this,`requests`,void 0),h(this,`engineRequest`,void 0),h(this,`p2pLoaders`,void 0),h(this,`playback`,void 0),h(this,`segmentAvgDuration`,void 0),h(this,`logger`,void 0),h(this,`levelChangedTimestamp`,void 0),h(this,`lastQueueProcessingTimeStamp`,void 0),h(this,`randomHttpDownloadTimeout`,void 0),h(this,`initialHttpDelayTimeoutId`,void 0),h(this,`isProcessQueueMicrotaskCreated`,!1),h(this,`swarmId`,void 0),h(this,`createdAt`,performance.now()),h(this,`requestProcessQueueMicrotask`,(e=!0)=>{let t=performance.now();!e&&this.lastQueueProcessingTimeStamp!==void 0&&t-this.lastQueueProcessingTimeStamp<=1e3||this.isProcessQueueMicrotaskCreated||(this.isProcessQueueMicrotaskCreated=!0,Se(()=>{try{this.processQueue(),this.lastQueueProcessingTimeStamp=t}finally{this.isProcessQueueMicrotaskCreated=!1}}))}),this.streamManifestUrl=e,this.lastRequestedSegment=t,this.streamDetails=n,this.config=r,this.bandwidthCalculators=i,this.segmentStorage=a,this.webTorrentSocketPool=o,this.eventTarget=s,this.peerId=c;let u=this.lastRequestedSegment.stream;this.swarmId=(l=this.config.swarmId)==null?this.streamManifestUrl:l,this.playback={position:this.lastRequestedSegment.startTime,rate:1},this.segmentAvgDuration=Ar(u),this.requests=new Ri(this.requestProcessQueueMicrotask,this.bandwidthCalculators,this.playback,this.config,this.eventTarget,this.swarmId),this.p2pLoaders=new ki(this.streamManifestUrl,this.lastRequestedSegment.stream,this.requests,this.segmentStorage,this.config,this.webTorrentSocketPool,this.eventTarget,this.peerId,this.requestProcessQueueMicrotask),this.logger=(0,S.default)(`p2pml-core:hybrid-loader-${u.type}`),this.logger.color=`coral`,this.setIntervalLoading()}setIntervalLoading(){let e=this.p2pLoaders.currentLoader.connectedPeerCount,t=Math.random()*Ui*e+Ui;this.randomHttpDownloadTimeout=window.setTimeout(()=>{this.loadRandomThroughHttp(),this.setIntervalLoading()},t)}loadSegment(e,t){var n=this;return x(function*(){n.logger(`requests: ${gi(e)}`);let{stream:r}=e;r!==n.lastRequestedSegment.stream&&(n.logger(`stream changed to ${hi(r)}`),n.p2pLoaders.changeCurrentLoader(r)),n.lastRequestedSegment=e;let i=Er(n.swarmId,r);n.segmentStorage.onSegmentRequested(n.swarmId,i,e.externalId,e.startTime,e.endTime,r.type,n.streamDetails.isLive);let a=new zi(e,t);try{var o;if(n.segmentStorage.hasSegment(n.swarmId,i,e.externalId)){let t=yield n.segmentStorage.getSegmentData(n.swarmId,i,e.externalId);if(t){let{queueDownloadRatio:e}=n.generateQueue();a.resolve(t,n.getBandwidth(e));return}}(o=n.engineRequest)==null||o.abort(),n.engineRequest=a;let t=n.requests.get(e);(t==null?void 0:t.status)===`failed`&&t.failedAttempts.clear()}catch(t){n.logger(`request failed for ${gi(e)} in ${hi(r)}`,t),a.reject()}finally{n.requestProcessQueueMicrotask()}})()}processRequests(e,t){let{stream:n}=this.lastRequestedSegment,{httpErrorRetries:r}=this.config,i=performance.now();for(let o of this.requests.items()){var a;let{downloadSource:s,status:c,segment:l,isHandledByProcessQueue:u}=o,d=((a=this.engineRequest)==null?void 0:a.segment)===l?this.engineRequest:void 0;switch(c){case`loading`:!e.has(l.runtimeId)&&!d&&(o.cancel(),this.requests.remove(o));break;case`succeed`:{if(!s)break;s===`http`&&this.p2pLoaders.currentLoader.broadcastAnnouncement(),d&&(d.resolve(o.data,this.getBandwidth(t)),this.engineRequest=void 0),this.requests.remove(o),this.logger(`succeed: ${gi(l)} (byteLength: ${o.data.byteLength})`);let e=Er(this.swarmId,n);this.segmentStorage.storeSegment(this.swarmId,e,l.externalId,o.data,l.startTime,l.endTime,l.stream.type,this.streamDetails.isLive);break}case`failed`:s===`http`&&!u&&this.p2pLoaders.currentLoader.broadcastAnnouncement(),!d&&!n.segments.has(o.segment.runtimeId)&&this.requests.remove(o),o.failedAttempts.httpAttemptsCount>=r&&d&&(this.engineRequest=void 0,d.reject());break;case`not-started`:this.requests.remove(o);break;case`aborted`:this.requests.remove(o);break}o.markHandledByProcessQueue();let{lastAttempt:f}=o.failedAttempts;f&&i-f.error.timestamp>Hi&&o.failedAttempts.clear()}}processQueue(){let{queue:e,queueSegmentIds:t,queueDownloadRatio:n}=this.generateQueue();this.processRequests(t,n);let{simultaneousHttpDownloads:r,simultaneousP2PDownloads:i,httpErrorRetries:a,httpDownloadInitialTimeoutMs:o}=this.config,s=performance.now()-this.createdAt,c=o>0&&s<o;c&&(this.initialHttpDelayTimeoutId!=null||(this.initialHttpDelayTimeoutId=window.setTimeout(()=>{this.initialHttpDelayTimeoutId=void 0,this.requestProcessQueueMicrotask()},o-s)));let{engineRequest:l}=this;if(l){let{segment:e}=l,t=this.requests.get(e);if(l.shouldBeStartedImmediately&&l.status===`pending`&&(!t||t.status===`not-started`||t.status===`failed`||t.status===`aborted`)){var u;!c&&((u=t==null?void 0:t.failedAttempts.httpAttemptsCount)==null?0:u)<a&&this.requests.executingHttpCount<r?this.loadThroughHttp(e):this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(e)&&this.requests.executingP2PCount<i&&this.loadThroughP2P(e)}}for(let t of e){let{statuses:n,segment:o}=t,s=this.requests.get(o);if((s==null?void 0:s.status)!==`succeed`)if(n.isHighDemand){var d;let t=!c&&((d=s==null?void 0:s.failedAttempts.httpAttemptsCount)==null?0:d)<a;if((s==null?void 0:s.status)===`loading`){t&&s.downloadSource===`p2p`&&(this.requests.executingHttpCount<r||this.abortLastHttpLoadingInQueueAfterItem(e,o))&&(s.cancel(),this.loadThroughHttp(o));continue}if(t&&(this.requests.executingHttpCount<r||this.abortLastHttpLoadingInQueueAfterItem(e,o))){this.loadThroughHttp(o);continue}this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(o)&&(this.requests.executingP2PCount<i||this.abortLastP2PLoadingInQueueAfterItem(e,o))&&this.loadThroughP2P(o)}else n.isP2PDownloadable&&(s==null?void 0:s.status)!==`loading`&&this.requests.executingP2PCount<i&&this.loadThroughP2P(o)}}abortSegmentRequest(e){var t;((t=this.engineRequest)==null?void 0:t.segment.runtimeId)===e&&(this.engineRequest.abort(),this.logger(`abort: `,gi(this.engineRequest.segment)),this.engineRequest=void 0,this.requestProcessQueueMicrotask())}loadThroughHttp(e){new ge(this.requests.getOrCreateRequest(e),this.config,this.eventTarget).execute(),this.p2pLoaders.currentLoader.broadcastAnnouncement()}loadThroughP2P(e){this.p2pLoaders.currentLoader.downloadSegment(e)}loadRandomThroughHttp(){let{httpDownloadInitialTimeoutMs:e}=this.config;if(e>0&&performance.now()-this.createdAt<e)return;let t=this.getAvailableStorageCapacityPercent();if(t<=10)return;let{simultaneousHttpDownloads:n,httpErrorRetries:r}=this.config,i=this.p2pLoaders.currentLoader;if(this.requests.executingHttpCount>=n||!i.connectedPeerCount)return;let a=[];for(let{segment:e,statuses:n}of Bi(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,t)){let t=Er(this.swarmId,e.stream);if(!n.isHttpDownloadable||n.isP2PDownloadable||this.segmentStorage.hasSegment(this.swarmId,t,e.externalId))continue;let i=this.requests.get(e);i&&(i.status===`loading`||i.status===`succeed`||i.failedAttempts.httpAttemptsCount>=r)||a.push(e)}if(!a.length||n-this.requests.executingHttpCount===0)return;let o=i.connectedPeerCount+1,s=Math.min(a.length,n*o),c=Me(Array.from({length:s},(e,t)=>t)),l=s/o;for(let e of c){if(this.requests.executingHttpCount>=n)break;if(l>=1||Math.random()<=l){let t=a[e];this.loadThroughHttp(t)}if(l--,l<=0)break}}abortLastHttpLoadingInQueueAfterItem(e,t){for(let{segment:n}of De(e)){if(n===t)break;let e=this.requests.get(n);if((e==null?void 0:e.downloadSource)===`http`&&e.status===`loading`)return e.cancel(),!0}return!1}abortLastP2PLoadingInQueueAfterItem(e,t){for(let{segment:n}of De(e)){if(n===t)break;let e=this.requests.get(n);if((e==null?void 0:e.downloadSource)===`p2p`&&e.status===`loading`)return e.cancel(),!0}return!1}getAvailableStorageCapacityPercent(){let{totalCapacity:e,usedCapacity:t}=this.segmentStorage.getUsage();return 100-t/e*100}generateQueue(){let e=[],t=new Set,n=0,r=0,i=this.getAvailableStorageCapacityPercent();for(let o of Bi(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,i)){var a;n++;let{segment:i}=o,s=Er(this.swarmId,i.stream);if(this.segmentStorage.hasSegment(this.swarmId,s,i.externalId)||((a=this.requests.get(i))==null?void 0:a.status)===`succeed`){r++;continue}e.push(o),t.add(i.runtimeId)}return{queue:e,queueSegmentIds:t,maxPossibleLength:n,alreadyLoadedCount:r,queueDownloadRatio:n===0?0:r/n}}getBandwidth(e){let{http:t,all:n}=this.bandwidthCalculators,{activeLevelBitrate:r}=this.streamDetails;if(r===0)return n.getBandwidthLoadingOnly(3);let i=Math.max(n.getBandwidth(30,this.levelChangedTimestamp),n.getBandwidth(60,this.levelChangedTimestamp),n.getBandwidth(90,this.levelChangedTimestamp));if(e>=.8||i>=r*.9)return Math.max(n.getBandwidthLoadingOnly(1),n.getBandwidthLoadingOnly(3),n.getBandwidthLoadingOnly(5));let a=Math.max(t.getBandwidthLoadingOnly(1),t.getBandwidthLoadingOnly(3),t.getBandwidthLoadingOnly(5));return Math.max(i,a)}notifyLevelChanged(){this.levelChangedTimestamp=performance.now()}sendBroadcastAnnouncement(e=!1){this.p2pLoaders.currentLoader.broadcastAnnouncement(e)}updatePlayback(e,t){let n=this.playback.rate!==t,r=this.playback.position!==e;if(!n&&!r)return;let i=Math.abs(e-this.playback.position)/this.segmentAvgDuration>.5;if(r&&(this.playback.position=e),n&&t!==0&&(this.playback.rate=t),i){var a;this.logger(`position significantly changed`),(a=this.engineRequest)==null||a.markAsShouldBeStartedImmediately()}this.segmentStorage.onPlaybackUpdated(e,t),this.requestProcessQueueMicrotask(i)}updateStream(e){e===this.lastRequestedSegment.stream&&(this.logger(`update stream: ${hi(e)}`),this.requestProcessQueueMicrotask())}destroy(){var e;clearTimeout(this.randomHttpDownloadTimeout),clearTimeout(this.initialHttpDelayTimeoutId),(e=this.engineRequest)==null||e.abort(),this.requests.destroy(),this.p2pLoaders.destroy()}},Gi=(e,t)=>`${e}|${t}`,Ki=e=>/Android/i.test(e),qi=e=>/iPad|iPhone/i.test(e),Ji=e=>/Android/i.test(e)&&(/; wv\)/i.test(e)||!/Chrome|Firefox/i.test(e)),Yi=1048576,Xi=class{constructor(){h(this,`userAgent`,navigator.userAgent),h(this,`segmentMemoryStorageLimit`,4*1024),h(this,`currentStorageUsage`,0),h(this,`cache`,new Map),h(this,`logger`,void 0),h(this,`coreConfig`,void 0),h(this,`mainStreamConfig`,void 0),h(this,`secondaryStreamConfig`,void 0),h(this,`currentPlayback`,void 0),h(this,`lastRequestedSegment`,void 0),h(this,`segmentChangeCallback`,void 0),this.logger=(0,S.default)(`p2pml-core:segment-memory-storage`),this.logger.color=`RebeccaPurple`}initialize(e,t,n){var r=this;return x(function*(){r.coreConfig=e,r.mainStreamConfig=t,r.secondaryStreamConfig=n,r.setMemoryStorageLimit(),r.logger(`initialized`)})()}onPlaybackUpdated(e,t){this.currentPlayback={position:e,rate:t}}onSegmentRequested(e,t,n,r,i,a,o){this.lastRequestedSegment={streamId:t,segmentId:n,startTime:r,endTime:i,swarmId:e,streamType:a,isLiveStream:o}}storeSegment(e,t,n,r,i,a,o,s){var c=this;return x(function*(){c.clear(s,r.byteLength);let e=Gi(t,n);if(c.cache.set(e,{data:r,segmentId:n,streamId:t,startTime:i,endTime:a,streamType:o}),c.increaseStorageUsage(r.byteLength),c.logger(`add segment: ${n} to ${t}`),!c.segmentChangeCallback)throw Error(`dispatchStorageUpdatedEvent is not set`);c.segmentChangeCallback(t)})()}getSegmentData(e,t,n){var r=this;return x(function*(){let e=Gi(t,n),i=r.cache.get(e);if(i!==void 0)return i.data})()}getUsage(){if(!this.lastRequestedSegment||!this.currentPlayback)return{totalCapacity:this.segmentMemoryStorageLimit,usedCapacity:this.currentStorageUsage};let e=this.currentPlayback.position,t=0;for(let{endTime:n,data:r}of this.cache.values())e>n||(t+=r.byteLength);return{totalCapacity:this.segmentMemoryStorageLimit,usedCapacity:t/Yi}}hasSegment(e,t,n){let r=Gi(t,n);return this.cache.get(r)!==void 0}getStoredSegmentIds(e,t){let n=[];for(let{segmentId:e,streamId:r}of this.cache.values())r===t&&n.push(e);return n}clear(e,t){if(!this.currentPlayback||!this.mainStreamConfig||!this.secondaryStreamConfig||!this.coreConfig||!this.isMemoryLimitReached(t)&&!e)return;let n=new Set,r=Array.from(this.cache.values()).sort((e,t)=>e.startTime-t.startTime);for(let i of r){let{streamId:r,segmentId:a,data:o}=i,s=Gi(r,a);if(this.shouldRemoveSegment(i,e,this.currentPlayback.position)&&(this.cache.delete(s),n.add(r),this.decreaseStorageUsage(o.byteLength),this.logger(`Removed segment ${a} from stream ${r}`),!this.isMemoryLimitReached(t)&&!e))break}this.sendUpdatesToAffectedStreams(n)}isMemoryLimitReached(e){return this.currentStorageUsage+e/Yi>this.segmentMemoryStorageLimit}setSegmentChangeCallback(e){this.segmentChangeCallback=e}sendUpdatesToAffectedStreams(e){e.size!==0&&e.forEach(e=>{if(!this.segmentChangeCallback)throw Error(`dispatchStorageUpdatedEvent is not set`);this.segmentChangeCallback(e)})}shouldRemoveSegment(e,t,n){let{endTime:r,streamType:i}=e,a=this.getStreamTimeWindow(i,`highDemandTimeWindow`);return n<=r?!1:t?n>a+r:!0}increaseStorageUsage(e){this.currentStorageUsage+=e/Yi}decreaseStorageUsage(e){this.currentStorageUsage-=e/Yi}setMemoryStorageLimit(){var e;if((e=this.coreConfig)!=null&&e.segmentMemoryStorageLimit){this.segmentMemoryStorageLimit=this.coreConfig.segmentMemoryStorageLimit;return}Ji(this.userAgent)||qi(this.userAgent)?this.segmentMemoryStorageLimit=1024:Ki(this.userAgent)&&(this.segmentMemoryStorageLimit=2*1024)}getStreamTimeWindow(e,t){var n;let r=e===`main`?this.mainStreamConfig:this.secondaryStreamConfig;return(n=r==null?void 0:r[t])==null?0:n}destroy(){this.cache.clear(),this.segmentChangeCallback=void 0}},Zi=new WeakMap,Z=new WeakMap,Q=new WeakMap,Qi=new WeakMap,$i=new WeakMap,$=new WeakMap,ea=new WeakMap,ta=new WeakMap,na=new WeakMap,ra=new WeakMap,ia=new WeakSet,aa=class{constructor(e){var t,n,r;w(this,ia),_(this,Zi,void 0),_(this,Z,`disconnected`),_(this,Q,null),_(this,Qi,0),_(this,$i,null),_(this,$,new xn),_(this,ea,()=>{y(Z,this)!==`disposed`&&(T(Z,this,`connected`),T(Qi,this,0),y($,this).dispatchEvent(`connected`))}),_(this,ta,()=>{y(Z,this)!==`disposed`&&(y(Q,this)&&(y(Q,this).onopen=null,y(Q,this).onclose=null,y(Q,this).onerror=null,y(Q,this).onmessage=null,T(Q,this,null)),v(ia,this,oa).call(this),y($,this).dispatchEvent(`disconnected`))}),_(this,na,e=>{y(Z,this)!==`disposed`&&y($,this).dispatchEvent(`error`,e)}),_(this,ra,e=>{y(Z,this)!==`disposed`&&y($,this).dispatchEvent(`message`,e.data)});let i=Math.max(100,(t=e.initialDelay)==null?1e3:t);T(Zi,this,{url:e.url,initialDelay:i,maxDelay:Math.max(i,(n=e.maxDelay)==null?3e4:n),jitterMultiplier:Math.max(0,(r=e.jitterMultiplier)==null?.2:r)})}get state(){return y(Z,this)}addEventListener(e,t){y($,this).addEventListener(e,t)}removeEventListener(e,t){y($,this).removeEventListener(e,t)}connect(){if(!(y(Z,this)===`connected`||y(Z,this)===`connecting`||y(Z,this)===`disposed`)){T(Z,this,`connecting`),v(ia,this,sa).call(this);try{T(Q,this,new WebSocket(y(Zi,this).url)),y(Q,this).binaryType=`arraybuffer`,y(Q,this).onopen=y(ea,this),y(Q,this).onclose=y(ta,this),y(Q,this).onerror=y(na,this),y(Q,this).onmessage=y(ra,this)}catch(e){T(Z,this,`disconnected`);let t=new ErrorEvent(`error`,{message:e instanceof Error?e.message:`Unknown WebSocket creation error`,error:e});y($,this).dispatchEvent(`error`,t)}}}send(e){if(y(Z,this)!==`connected`||!y(Q,this))throw Error(`WebSocketClient: Cannot send data when not connected`);y(Q,this).send(e)}dispose(){T(Z,this,`disposed`),v(ia,this,sa).call(this),y(Q,this)&&(y(Q,this).onopen=null,y(Q,this).onclose=null,y(Q,this).onerror=null,y(Q,this).onmessage=null,y(Q,this).close(),T(Q,this,null)),y($,this).clear()}};function oa(){if(y(Z,this)===`disposed`)return;T(Z,this,`reconnecting`);let e=Math.min(y(Zi,this).initialDelay*Math.pow(2,y(Qi,this)),y(Zi,this).maxDelay),t=e*y(Zi,this).jitterMultiplier,n=Math.random()*2*t-t,r=Math.max(0,e+n);if(e<y(Zi,this).maxDelay){var i;T(Qi,this,(i=y(Qi,this),i++,i))}T($i,this,setTimeout(()=>{y(Z,this)!==`disposed`&&this.connect()},r)),y($,this).dispatchEvent(`reconnecting`)}function sa(){y($i,this)!==null&&(clearTimeout(y($i,this)),T($i,this,null))}var ca=new WeakMap,la=new WeakMap,ua=class{constructor(){_(this,ca,new Map),_(this,la,new xn)}addEventListener(e,t){y(la,this).addEventListener(e,t)}removeEventListener(e,t){y(la,this).removeEventListener(e,t)}acquire(e){let t=y(ca,this).get(e);if(!t){let n=new aa({url:e});n.addEventListener(`error`,t=>{y(la,this).dispatchEvent(`error`,t,e)}),n.connect(),t={client:n,refCount:0},y(ca,this).set(e,t)}t.refCount++;let n=!1;return{client:t.client,release:()=>{n||(n=!0,t.refCount--,t.refCount<=0&&(t.refCount<0&&console.error(`[WebTorrentSocketPool] Negative refCount detected for ${e}`),y(ca,this).get(e)===t&&y(ca,this).delete(e),t.client.dispose()))}}}destroy(){y(la,this).clear();let e=Array.from(y(ca,this).values());y(ca,this).clear();for(let t of e)try{t.client.dispose()}catch(e){console.error(`[WebTorrentSocketPool] Failed to dispose WebSocketClient:`,e)}}},da=class e{constructor(t){h(this,`eventTarget`,new xn),h(this,`manifestResponseUrl`,void 0),h(this,`streams`,new Map),h(this,`mainStreamConfig`,void 0),h(this,`secondaryStreamConfig`,void 0),h(this,`commonCoreConfig`,void 0),h(this,`bandwidthCalculators`,{all:new en,http:new en}),h(this,`segmentStorage`,void 0),h(this,`webTorrentSocketPool`,new ua),h(this,`socketPoolLogger`,(0,S.default)(`p2pml-core:webtorrent-socket-pool`)),h(this,`peerId`,void 0),h(this,`mainStreamLoader`,void 0),h(this,`secondaryStreamLoader`,void 0),h(this,`streamDetails`,{isLive:!1,activeLevelBitrate:0}),h(this,`storageInitPromise`,void 0);let n=Ae(t==null?{}:t);this.commonCoreConfig=Pe({defaultConfig:e.DEFAULT_COMMON_CORE_CONFIG,baseConfig:n}),this.mainStreamConfig=Pe({defaultConfig:e.DEFAULT_STREAM_CONFIG,baseConfig:n,specificStreamConfig:n.mainStream}),this.secondaryStreamConfig=Pe({defaultConfig:e.DEFAULT_STREAM_CONFIG,baseConfig:n,specificStreamConfig:n.secondaryStream}),this.peerId=Rr(this.commonCoreConfig.trackerClientVersionPrefix),this.webTorrentSocketPool.addEventListener(`error`,(e,t)=>{this.socketPoolLogger(`WebSocket error for tracker url ${t}:`,e)})}getConfig(){return b(b({},je(this.commonCoreConfig)),{},{mainStream:je(this.mainStreamConfig),secondaryStream:je(this.secondaryStreamConfig)})}applyDynamicConfig(e){let{mainStream:t,secondaryStream:n}=e,r=je(this.mainStreamConfig),i=je(this.secondaryStreamConfig);this.overrideAllConfigs(e,t,n),this.processSpecificDynamicConfigParams(r,e,`main`),this.processSpecificDynamicConfigParams(i,e,`secondary`)}processSpecificDynamicConfigParams(e,t,n){let r=this.getUpdatedStreamProperty(`isP2PDisabled`,t,n);r&&e.isP2PDisabled!==r&&this.destroyStreamLoader(n);let i=this.getUpdatedStreamProperty(`isP2PUploadDisabled`,t,n);if(i!==void 0&&e.isP2PUploadDisabled!==i){let e=n===`main`?this.mainStreamLoader:this.secondaryStreamLoader;e==null||e.sendBroadcastAnnouncement(i)}}getUpdatedStreamProperty(e,t,n){var r;let i=n===`main`?t.mainStream:t.secondaryStream;return(r=i==null?void 0:i[e])==null?t[e]:r}addEventListener(e,t){this.eventTarget.addEventListener(e,t)}removeEventListener(e,t){this.eventTarget.removeEventListener(e,t)}setManifestResponseUrl(e){this.manifestResponseUrl=e.split(`?`)[0]}hasSegment(e){return!!Dr(this.streams,e)}getStream(e){return this.streams.get(e)}addStreamIfNoneExists(e){this.streams.has(e.runtimeId)||this.streams.set(e.runtimeId,b(b({},e),{},{segments:new Map}))}updateStream(e,t,n){var r,i;let a=this.streams.get(e);if(a){if(t)for(let e of t)a.segments.has(e.runtimeId)||a.segments.set(e.runtimeId,b(b({},e),{},{stream:a}));if(n)for(let e of n)a.segments.delete(e);(r=this.mainStreamLoader)==null||r.updateStream(a),(i=this.secondaryStreamLoader)==null||i.updateStream(a)}}loadSegment(e,t){var n=this;return x(function*(){if(!n.manifestResponseUrl)throw Error(`Manifest response url is not defined`);yield n.initializeSegmentStorage();let r=n.identifySegment(e);n.getStreamHybridLoader(r).loadSegment(r,t)})()}abortSegmentLoading(e){var t,n;(t=this.mainStreamLoader)==null||t.abortSegmentRequest(e),(n=this.secondaryStreamLoader)==null||n.abortSegmentRequest(e)}updatePlayback(e,t){var n,r;(n=this.mainStreamLoader)==null||n.updatePlayback(e,t),(r=this.secondaryStreamLoader)==null||r.updatePlayback(e,t)}setActiveLevelBitrate(e){if(e!==this.streamDetails.activeLevelBitrate){var t,n;this.streamDetails.activeLevelBitrate=e,(t=this.mainStreamLoader)==null||t.notifyLevelChanged(),(n=this.secondaryStreamLoader)==null||n.notifyLevelChanged()}}setIsLive(e){this.streamDetails.isLive=e}isSegmentLoadable(e){try{let t=this.identifySegment(e);return!(t.stream.type===`main`&&this.mainStreamConfig.isP2PDisabled||t.stream.type===`secondary`&&this.secondaryStreamConfig.isP2PDisabled)}catch(e){return!1}}destroy(){var e,t,n,r;this.streams.clear(),(e=this.mainStreamLoader)==null||e.destroy(),(t=this.secondaryStreamLoader)==null||t.destroy(),(n=this.segmentStorage)==null||n.setSegmentChangeCallback(void 0),(r=this.segmentStorage)==null||r.destroy(),this.mainStreamLoader=void 0,this.secondaryStreamLoader=void 0,this.segmentStorage=void 0,this.manifestResponseUrl=void 0,this.streamDetails={isLive:!1,activeLevelBitrate:0},this.storageInitPromise=void 0,this.webTorrentSocketPool.destroy()}initializeSegmentStorage(){var e=this;return x(function*(){if(!e.segmentStorage){if(e.storageInitPromise)return e.storageInitPromise;e.storageInitPromise=x(function*(){let{isLive:t}=e.streamDetails,n=e.commonCoreConfig.customSegmentStorageFactory;if(n&&typeof n!=`function`)throw Error(`Storage configuration is invalid`);let r=n?n(t):new Xi;try{yield r.initialize(e.commonCoreConfig,e.mainStreamConfig,e.secondaryStreamConfig)}catch(e){throw r.destroy(),e}if(!e.storageInitPromise){r.setSegmentChangeCallback(void 0),r.destroy();return}r.setSegmentChangeCallback(t=>{e.eventTarget.dispatchEvent(`onStorageUpdated-${t}`)}),e.segmentStorage=r})();try{yield e.storageInitPromise}finally{e.storageInitPromise=void 0}}})()}identifySegment(e){if(!this.manifestResponseUrl)throw Error(`Manifest response url is undefined`);let t=Dr(this.streams,e);if(!t)throw Error(`Not found segment with id: ${e}`);return t}overrideAllConfigs(e,t,n){Ne(this.commonCoreConfig,e),Ne(this.mainStreamConfig,e),Ne(this.secondaryStreamConfig,e),t&&Ne(this.mainStreamConfig,t),n&&Ne(this.secondaryStreamConfig,n)}destroyStreamLoader(e){if(e===`main`){var t;(t=this.mainStreamLoader)==null||t.destroy(),this.mainStreamLoader=void 0}else{var n;(n=this.secondaryStreamLoader)==null||n.destroy(),this.secondaryStreamLoader=void 0}}getStreamHybridLoader(e){return e.stream.type===`main`?(this.mainStreamLoader!=null||(this.mainStreamLoader=this.createNewHybridLoader(e)),this.mainStreamLoader):(this.secondaryStreamLoader!=null||(this.secondaryStreamLoader=this.createNewHybridLoader(e)),this.secondaryStreamLoader)}createNewHybridLoader(e){if(!this.manifestResponseUrl)throw Error(`Manifest response url is not defined`);if(!this.segmentStorage)throw Error(`Segment storage is not initialized`);let t=e.stream.type===`main`?this.mainStreamConfig:this.secondaryStreamConfig;return new Wi(this.manifestResponseUrl,e,this.streamDetails,t,this.bandwidthCalculators,this.segmentStorage,this.webTorrentSocketPool,this.eventTarget,this.peerId)}};h(da,`DEFAULT_COMMON_CORE_CONFIG`,{segmentMemoryStorageLimit:void 0,customSegmentStorageFactory:void 0,trackerClientVersionPrefix:Pr}),h(da,`DEFAULT_STREAM_CONFIG`,{isP2PUploadDisabled:!1,isP2PDisabled:!1,simultaneousHttpDownloads:2,simultaneousP2PDownloads:3,highDemandTimeWindow:15,httpDownloadInitialTimeoutMs:0,httpDownloadTimeWindow:3e3,p2pDownloadTimeWindow:6e3,webRtcMaxMessageSize:64*1024-1,p2pNotReceivingBytesTimeoutMs:2e3,p2pInactiveLoaderDestroyTimeoutMs:30*1e3,httpNotReceivingBytesTimeoutMs:3e3,httpErrorRetries:3,p2pErrorRetries:3,announceTrackers:[`wss://tracker.novage.com.ua`,`wss://tracker.openwebtorrent.com`],rtcConfig:{iceServers:[{urls:`stun:stun.l.google.com:19302`},{urls:`stun:global.stun.twilio.com:3478`}]},validateP2PSegment:void 0,validateHTTPSegment:void 0,httpRequestSetup:void 0,swarmId:void 0,p2pMaxPeers:50,p2pChurnMaxPeersMultiplier:1.5,p2pChurnCleanupIntervalMs:3e4,p2pChurnGracePeriodMs:15e3,webRtcOffersCount:5,webRtcOfferTimeoutMs:5e4,webRtcIceGatheringTimeoutMs:5e3,webRtcConnectionTimeoutMs:15e3});var fa=10,pa=new WeakMap,ma=new WeakMap,ha=new WeakMap,ga=new WeakMap,_a=new WeakMap,va=new WeakMap,ya=new WeakSet,ba=class{constructor(e,t){w(this,ya),h(this,`context`,void 0),h(this,`config`,void 0),h(this,`stats`,void 0),_(this,pa,void 0),_(this,ma,void 0),_(this,ha,void 0),_(this,ga,void 0),_(this,_a,void 0),_(this,va,void 0),T(ga,this,t),T(ma,this,()=>new e.loader(e)),this.stats={aborted:!1,chunkCount:0,loading:{start:0,first:0,end:0},buffering:{start:0,first:0,end:0},parsing:{start:0,end:0},total:1,loaded:1,bwEstimate:0,retry:0}}load(e,t,n){this.context=e,this.config=t,T(pa,this,n);let{stats:r}=this,{rangeStart:i,rangeEnd:a}=e,o=f(i,a===void 0?void 0:a-1);T(va,this,d(e.url,o));let s=y(ga,this).isSegmentLoadable(y(va,this));if(!y(ga,this).hasSegment(y(va,this))||!s){T(ha,this,y(ma,this).call(this)),y(ha,this).stats=this.stats,y(ha,this).load(e,t,n);return}y(ga,this).loadSegment(y(va,this),{onSuccess:t=>{if(!y(pa,this))return;T(_a,this,t);let n=y(_a,this).data.byteLength;r.loading=Ca(y(_a,this).bandwidth,n,performance.now()),r.total=n,r.loaded=n;let i=y(_a,this).data.slice(0);y(pa,this).onProgress&&y(pa,this).onProgress(this.stats,e,i,void 0),y(pa,this).onSuccess({data:i,url:e.url},this.stats,e,void 0)},onError:e=>{e instanceof se&&e.type===`aborted`&&this.stats.aborted||v(ya,this,xa).call(this,e)}})}abort(){if(y(ha,this))y(ha,this).abort();else{var e,t;v(ya,this,Sa).call(this),(e=y(pa,this))==null||(t=e.onAbort)==null||t.call(e,this.stats,this.context,{})}}destroy(){y(ha,this)?y(ha,this).destroy():(this.stats.aborted||v(ya,this,Sa).call(this),T(pa,this,null),this.config=null)}};function xa(e){var t;let n={code:0,text:``};(e instanceof se&&e.type===`failed`||e instanceof Error)&&(n.text=e.message),(t=y(pa,this))==null||t.onError(n,this.context,null,this.stats)}function Sa(){!y(_a,this)&&y(va,this)&&(this.stats.aborted=!0,y(ga,this).abortSegmentLoading(y(va,this)))}function Ca(e,t,n){let r=e>0?t*8e3/e:0,i=Math.max(0,n-r);return{start:Math.max(0,i-fa),first:i,end:n}}var wa=new WeakMap,Ta=class{constructor(e){_(this,wa,void 0),h(this,`context`,void 0),h(this,`stats`,void 0),T(wa,this,new e.loader(e)),this.stats=y(wa,this).stats,this.context=y(wa,this).context}load(e,t,n){y(wa,this).load(e,t,n)}abort(){y(wa,this).abort()}destroy(){y(wa,this).destroy()}},Ea=class{constructor(e){h(this,`core`,void 0),this.core=e}processMainManifest(e){let{levels:t,audioTracks:n}=e;for(let e of t){let{url:t,bitrate:n,maxBitrate:r,videoCodec:i,width:a,height:o}=e,s=r==null?n:r,c=s===0,l=e.attrs[`FRAME-RATE`],u=e.attrs[`VIDEO-RANGE`],d=Tr({bitrate:s,codecs:c?void 0:i,width:c?void 0:a,height:c?void 0:o,frameRate:c?void 0:l,videoRange:c?void 0:u});this.core.addStreamIfNoneExists({runtimeId:Array.isArray(t)?t[0]:t,type:`main`,index:d})}for(let e of n){let{url:t,audioCodec:n,lang:r,channels:i,name:a}=e,o=Tr({bitrate:0,codecs:n,language:r,channels:i,name:a});this.core.addStreamIfNoneExists({runtimeId:Array.isArray(t)?t[0]:t,type:`secondary`,index:o})}}updatePlaylist(e){let{details:{url:t,fragments:n,live:r}}=e,i=this.core.getStream(t);if(!i)return;let a=new Set(i.segments.keys()),o=[];n.forEach((e,t)=>{let{url:n,byteRange:s,sn:c,start:l,end:u}=e,[p,m]=s,ee=f(p,m===void 0?void 0:m-1),h=d(n,ee);a.delete(h),!i.segments.has(h)&&o.push({runtimeId:h,url:n,externalId:r?c:t,byteRange:ee,startTime:l,endTime:u})}),!(!o.length&&!a.size)&&this.core.updateStream(t,o,a.values())}};function Da(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.includes(r))continue;n[r]=e[r]}return n}function Oa(e,t){if(e==null)return{};var n,r,i=Da(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.includes(n)||{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}var ka=[`p2p`];function Aa(e){var t;return t=new WeakMap,class extends e{get p2pEngine(){return y(t,this)}constructor(...e){var n;let r=e[0],i=r==null?{}:r,{p2p:a}=i,o=Oa(i,ka),s=new Ma(a);super(b(b({},o),s.getConfigForHlsJs())),_(this,t,void 0),s.bindHls(this),T(t,this,s),a==null||(n=a.onHlsJsCreated)==null||n.call(a,this)}}}var ja=120,Ma=class{static injectMixin(e){return Aa(e)}constructor(e){h(this,`core`,void 0),h(this,`segmentManager`,void 0),h(this,`hlsInstanceGetter`,void 0),h(this,`currentHlsInstance`,void 0),h(this,`debug`,(0,S.debug)(`p2pml-hlsjs:engine`)),h(this,`updateMediaElementEventHandlers`,e=>{var t;let n=(t=this.currentHlsInstance)==null?void 0:t.media;if(!n)return;let r=e===`register`?`addEventListener`:`removeEventListener`;n[r](`timeupdate`,this.handlePlaybackUpdate),n[r](`seeking`,this.handlePlaybackUpdate),n[r](`ratechange`,this.handlePlaybackUpdate)}),h(this,`handleManifestLoaded`,(e,t)=>{let n=t.networkDetails;n instanceof XMLHttpRequest?this.core.setManifestResponseUrl(n.responseURL):n instanceof Response&&this.core.setManifestResponseUrl(n.url),this.segmentManager.processMainManifest(t)}),h(this,`handleLevelSwitching`,(e,t)=>{t.bitrate&&this.core.setActiveLevelBitrate(t.bitrate)}),h(this,`handleLevelUpdated`,(e,t)=>{this.currentHlsInstance&&t.details.fragments[0].type===`main`&&t.details.fragments.length>4&&(t.details.live&&!this.currentHlsInstance.userConfig.liveSyncDuration&&!this.currentHlsInstance.userConfig.liveSyncDurationCount&&this.updateLiveSyncDurationCount(t),!this.currentHlsInstance.userConfig.maxBufferLength&&!this.currentHlsInstance.userConfig.maxMaxBufferLength&&this.updateMaxBufferLength(t.details.targetduration)),this.core.setIsLive(t.details.live),this.segmentManager.updatePlaylist(t)}),h(this,`handleMediaAttached`,()=>{this.updateMediaElementEventHandlers(`register`)}),h(this,`handleMediaDetached`,()=>{this.updateMediaElementEventHandlers(`unregister`)}),h(this,`handlePlaybackUpdate`,e=>{let t=e.target;this.core.updatePlayback(t.currentTime,t.playbackRate)}),h(this,`destroyCore`,()=>this.core.destroy()),h(this,`destroy`,()=>{this.destroyCore(),this.updateHlsEventsHandlers(`unregister`),this.updateMediaElementEventHandlers(`unregister`),this.currentHlsInstance=void 0}),this.core=new da(e==null?void 0:e.core),this.segmentManager=new Ea(this.core)}addEventListener(e,t){this.core.addEventListener(e,t)}removeEventListener(e,t){this.core.removeEventListener(e,t)}getConfigForHlsJs(){return{fLoader:this.createFragmentLoaderClass(),pLoader:this.createPlaylistLoaderClass()}}getConfig(){return{core:this.core.getConfig()}}applyDynamicConfig(e){e.core&&this.core.applyDynamicConfig(e.core)}bindHls(e){this.hlsInstanceGetter=typeof e==`function`?e:()=>e}initHlsEvents(){var e;let t=(e=this.hlsInstanceGetter)==null?void 0:e.call(this);this.currentHlsInstance!==t&&(this.currentHlsInstance&&this.destroy(),this.currentHlsInstance=t,this.updateHlsEventsHandlers(`register`),this.updateMediaElementEventHandlers(`register`))}updateHlsEventsHandlers(e){let t=this.currentHlsInstance;if(!t)return;let n=e===`register`?`on`:`off`;t[n](`hlsManifestLoaded`,this.handleManifestLoaded),t[n](`hlsLevelSwitching`,this.handleLevelSwitching),t[n](`hlsLevelUpdated`,this.handleLevelUpdated),t[n](`hlsAudioTrackLoaded`,this.handleLevelUpdated),t[n](`hlsDestroying`,this.destroy),t[n](`hlsMediaAttaching`,this.destroyCore),t[n](`hlsManifestLoading`,this.destroyCore),t[n](`hlsMediaDetached`,this.handleMediaDetached),t[n](`hlsMediaAttached`,this.handleMediaAttached)}updateLiveSyncDurationCount(e){let t=e.details.targetduration,n=Math.floor(ja/t),r=Math.min(e.details.fragments.length-1,n);this.currentHlsInstance&&this.currentHlsInstance.config.liveSyncDurationCount!==r&&(this.debug(`Setting liveSyncDurationCount to ${r}`),this.currentHlsInstance.config.liveSyncDurationCount=r)}updateMaxBufferLength(e){if(!this.currentHlsInstance)return;let t=this.core.getConfig(),n=Math.max(t.mainStream.highDemandTimeWindow,t.secondaryStream.highDemandTimeWindow),r=Math.max(e*2,n);this.currentHlsInstance.config.maxBufferLength>r&&(this.debug(`Setting maxBufferLength to ${r}`),this.currentHlsInstance.config.maxBufferLength=r),this.currentHlsInstance.config.maxMaxBufferLength>r&&(this.debug(`Setting maxMaxBufferLength to ${r}`),this.currentHlsInstance.config.maxMaxBufferLength=r)}createFragmentLoaderClass(){let{core:e}=this,t=this;return class extends ba{constructor(t){super(t,e)}static getEngine(){return t}}}createPlaylistLoaderClass(){let e=this;return class extends Ta{constructor(t){super(t),e.initHlsEvents()}}}};return e.Core=da,e.HlsJsP2PEngine=Ma,e})({});
//# sourceMappingURL=p2p-media-loader-hlsjs.iife.min.js.map