p2p-media-loader-shaka
Version:
P2P Media Loader Shaka Player integration
2 lines • 112 kB
JavaScript
this.p2pml=this.p2pml||{},this.p2pml.shaka=(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){"@babel/helpers - typeof";return d=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},d(e)}function f(e,t){if(d(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(d(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ee(e){var t=f(e,`string`);return d(t)==`symbol`?t:t+``}function p(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),p(this,`type`,void 0),p(this,`cause`,void 0),this.type=e,this.cause=n}},ne=class extends te{constructor(...e){super(...e),p(this,`name`,`PeerError`)}},re=class extends te{constructor(...e){super(...e),p(this,`name`,`PeerWarning`)}},ie=class extends te{constructor(...e){super(...e),p(this,`name`,`TrackerError`)}},ae=class extends te{constructor(...e){super(...e),p(this,`name`,`TrackerWarning`)}},oe=class extends te{constructor(...e){super(...e),p(this,`name`,`PeerConnectError`)}},m=class extends te{constructor(e,t,n){super(e,t,n),p(this,`name`,`RequestError`),p(this,`timestamp`,void 0),this.timestamp=performance.now()}},se=class extends te{constructor(...e){super(...e),p(this,`name`,`CoreRequestError`)}};function ce(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function h(e,t,n){ce(e,t),t.set(e,n)}function g(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 _(e,t){return e.get(g(e,t))}var le=new WeakMap,ue=class{constructor(){p(this,`aborted`,!1),h(this,le,new Set)}addEventListener(e,t){_(le,this).add(t)}removeEventListener(e,t){_(le,this).delete(t)}dispatchEvent(e){this.aborted=!0;for(let e of _(le,this))try{e()}catch(e){}_(le,this).clear()}},de=class{constructor(){p(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 v(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){p(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 y(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){p(this,`request`,void 0),p(this,`httpConfig`,void 0),p(this,`abortController`,new pe),p(this,`expectedBytesLength`,void 0),p(this,`requestByteRange`,void 0),p(this,`onChunkDownloaded`,void 0),this.request=e,this.httpConfig=t,this.onChunkDownloaded=n.getEventDispatcher(`onChunkDownloaded`);let{byteRange:r}=this.request.segment;r&&(this.requestByteRange=v({},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 y(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 m(`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 m(`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 m(`http-bytes-mismatch`,e.statusText)):new m(`http-error`,e.statusText);let{requestByteRange:t}=this;if(t)if(e.status===200){if(this.request.segment.byteRange)throw new m(`http-unexpected-status-code`);this.request.clearLoadedBytes()}else{if(e.status!==206)throw new m(`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 m(`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 m(`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 m?e:new m(`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})),b=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),x=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(v(v(v({},t),n),r)),a=Object.keys(t),o={};return a.forEach(e=>{e in i&&(o[e]=i[e])}),o}function S(e,t){ce(e,t),t.add(e)}function C(e,t,n){return e.set(g(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(){S(this,Ye),h(this,qe,[]),h(this,Je,0)}push(e){g(Ye,this,Ze).call(this,e,`end`)}unshift(e){g(Ye,this,Ze).call(this,e,`start`)}getBytesChunks(){return _(qe,this)}getBuffer(){return Ce(_(qe,this),_(Je,this))}get length(){return _(Je,this)}};function Ze(e,t){let n;n=e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):new Uint8Array([e]),C(Je,this,_(Je,this)+n.length),_(qe,this)[t===`start`?`unshift`:`push`](n)}var w=4,Qe=xt(`cstr`,w),$e=xt(`cend`,w),et=xt(`dstr`,w),tt=xt(`dend`,w),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,w))&&rt.some(e=>wt(n,e,w))}function ot(e){return e.length<it?!1:wt(e,Qe,w)}function st(e){return e.length<it?!1:wt(e.subarray(-4),$e,w)}var ct=class extends Error{constructor(e){super(),p(this,`type`,void 0),this.type=e}},lt=new WeakMap,ut=new WeakMap,dt=new WeakMap,ft=new WeakSet,pt=class{constructor(e){S(this,ft),h(this,lt,new Xe),h(this,ut,`joining`),h(this,dt,void 0),C(dt,this,e)}addCommandChunk(e){if(_(ut,this)===`completed`)return;let t=ot(e);if(!_(lt,this).length&&!t)throw new ct(`no-first-chunk`);if(_(lt,this).length&&t)throw new ct(`incomplete-joining`);_(lt,this).push(g(ft,this,mt).call(this,e)),st(e)&&(C(ut,this,`completed`),_(dt,this).call(this,_(lt,this).getBuffer()))}};function mt(e){if(e.length<it)throw Error(`Command chunk is too short to unframe`);return e.subarray(w,e.length-w)}var T=new WeakMap,ht=new WeakMap,gt=new WeakMap,_t=new WeakMap,vt=class{constructor(e,t){h(this,T,new Xe),h(this,ht,[]),h(this,gt,`creating`),h(this,_t,void 0),C(_t,this,t),_(T,this).push(e)}addInteger(e,t){_(T,this).push(e.charCodeAt(0));let n=Ve(t);_(T,this).push(n)}addUniqueSimilarIntArr(e,t){_(T,this).push(e.charCodeAt(0));let n=Ue(t);_(T,this).push(n)}addString(e,t){_(T,this).push(e.charCodeAt(0));let n=Ge(t);_(T,this).push(n)}complete(){if(!_(T,this).length)throw Error(`Buffer is empty`);if(_(gt,this)===`completed`)return;C(gt,this,`completed`);let e=_(T,this).getBuffer();if(e.length+it<=_(_t,this)){_(ht,this).push(Ct(e,Qe,$e));return}let t=Math.ceil(e.length/_(_t,this));Math.ceil(e.length/t)+it>_(_t,this)&&t++;for(let[n,r]of St(e,t))n===0?_(ht,this).push(Ct(r,Qe,tt)):n===t-1?_(ht,this).push(Ct(r,et,$e)):_(ht,this).push(Ct(r,et,tt))}getResultBuffers(){if(_(gt,this)===`creating`||!_(ht,this).length)throw Error(`Command is not complete.`);return _(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 x.SegmentsAnnouncement:return e;case x.SegmentRequest:return Et(e,`i`,`r`),e;case x.SegmentData:return Et(e,`i`,`r`,`s`),e;case x.SegmentAbsent:case x.CancelSegmentRequest:case x.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 x.CancelSegmentRequest:case x.SegmentAbsent:case x.SegmentDataSendingCompleted:return Ot(e,t);case x.SegmentRequest:return At(e,t);case x.SegmentsAnnouncement:return Dt(e,t);case x.SegmentData:return kt(e,t)}}var Mt=c({BinaryCommandChunksJoiner:()=>pt,BinaryCommandJoiningError:()=>ct,PeerCommandType:()=>x,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){p(this,`channel`,void 0),p(this,`maxMessageSize`,void 0),h(this,Lt,void 0),this.channel=e,this.maxMessageSize=t}sendData(e,t){var n=this;return y(function*(){if(_(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,C(Lt,n,void 0),n.channel.removeEventListener(`bufferedamountlow`,ee),n.channel.removeEventListener(`closing`,l),n.channel.removeEventListener(`close`,l),n.channel.removeEventListener(`error`,u),!0);C(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,ee=()=>{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),!_(Lt,n))return}}catch(e){c()&&a(e instanceof Error?e:Error(String(e)));return}c()&&i()}};return n.channel.addEventListener(`bufferedamountlow`,ee),n.channel.addEventListener(`closing`,l),n.channel.addEventListener(`close`,l),n.channel.addEventListener(`error`,u),ee(),r})()}cancel(){var e;(e=_(Lt,this))==null||e.cancel()}},zt=(0,b.default)(`p2pml-core:peer-protocol`),Bt=new WeakMap,Vt=new WeakMap,E=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 WeakSet,Xt=class{constructor(e,t,n,r,i){if(S(this,Yt),h(this,Bt,void 0),h(this,Vt,void 0),h(this,E,void 0),h(this,Ht,void 0),h(this,Ut,void 0),h(this,Wt,void 0),h(this,Gt,void 0),h(this,Kt,void 0),h(this,qt,void 0),h(this,Jt,e=>{try{let t=new Uint8Array(e.data);at(t)?g(Yt,this,Zt).call(this,t):(_(Kt,this).onSegmentChunkReceived(t),_(Ht,this).call(this,t.byteLength,`p2p`,_(qt,this),_(Gt,this).streamType,_(Gt,this).infoHash))}catch(e){zt(`error handling data channel message: %O`,e),_(Kt,this).onProtocolError(e)}}),C(Wt,this,e),C(Gt,this,t),C(Kt,this,n),C(qt,this,i),C(Vt,this,new Rt(e,t.webRtcMaxMessageSize)),C(Ht,this,r.getEventDispatcher(`onChunkDownloaded`)),C(Ut,this,r.getEventDispatcher(`onChunkUploaded`)),e.binaryType!==`arraybuffer`)throw Error(`Expected binaryType "arraybuffer", got "${e.binaryType}"`);e.addEventListener(`message`,_(Jt,this))}sendCommand(e){if(_(Wt,this).readyState!==`open`)throw Error(`cannot send command ${e.c} (channel state: ${_(Wt,this).readyState})`);let t=jt(e,_(Gt,this).webRtcMaxMessageSize);for(let e of t)_(Wt,this).send(e)}stopUploadingSegmentData(){_(Vt,this).cancel(),C(E,this,void 0)}getUploadingRequestId(){return _(E,this)}splitSegmentDataToChunksAndUploadAsync(e,t){var n=this;return y(function*(){if(_(E,n)!==void 0)throw Error(`Some segment data is already uploading.`);C(E,n,t);try{yield _(Vt,n).sendData(e,e=>{_(Ut,n).call(n,e,_(qt,n),_(Gt,n).streamType,_(Gt,n).infoHash)})}finally{_(E,n)===t&&C(E,n,void 0)}})()}destroy(){_(Wt,this).removeEventListener(`message`,_(Jt,this)),_(Vt,this).cancel(),C(Bt,this,void 0),C(E,this,void 0)}};function Zt(e){_(Bt,this)!=null||C(Bt,this,new pt(e=>{C(Bt,this,void 0);let t;try{t=yt(e)}catch(e){zt(`error deserializing command: %O`,e),_(Kt,this).onProtocolError(e);return}_(Kt,this).onCommandReceived(t)}));try{_(Bt,this).addCommandChunk(e)}catch(e){zt(`error receiving command chunks: %O`,e),C(Bt,this,void 0),_(Kt,this).onProtocolError(e)}}var Qt=1,$t=class{constructor(e=2e4){p(this,`clearThresholdMs`,void 0),p(this,`loadingsCount`,0),p(this,`bytes`,[]),p(this,`loadingOnlyTimestamps`,[]),p(this,`timestamps`,[]),p(this,`noLoadingsTime`,0),p(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,Qt);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,Qt);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:D}=Mt,O=new WeakMap,k=new WeakMap,en=new WeakMap,tn=new WeakMap,nn=new WeakMap,A=new WeakMap,rn=new WeakMap,j=new WeakMap,an=new WeakMap,on=new WeakMap,sn=new WeakMap,cn=new WeakMap,ln=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,M=new WeakSet,pn=class{get isDestroyed(){return _(sn,this)}constructor(e,t,n,r,i,a){var o=this;S(this,M),p(this,`id`,void 0),p(this,`channel`,void 0),p(this,`eventTarget`,void 0),h(this,O,void 0),h(this,k,void 0),h(this,en,new Set),h(this,tn,new Set),h(this,nn,0),h(this,A,new $t),h(this,rn,{value:0,timestamp:0}),h(this,j,(0,b.default)(`p2pml-core:peer`)),h(this,an,0),h(this,on,void 0),h(this,sn,!1),p(this,`connectedAt`,performance.now()),h(this,cn,void 0),h(this,ln,void 0),h(this,un,void 0),h(this,dn,function(){var e=y(function*(e){switch(e.c){case D.SegmentsAnnouncement:C(en,o,new Set(e.l)),C(tn,o,new Set(e.p)),_(ln,o).onSegmentsAnnouncement();break;case D.SegmentRequest:C(on,o,e.r),_(O,o).stopUploadingSegmentData(),_(ln,o).onSegmentRequested(o,e.i,e.r,e.b);break;case D.SegmentData:{if(!_(k,o)||_(k,o).isSegmentDataCommandReceived)break;let{request:t,controls:n,requestId:r}=_(k,o);if(t.segment.externalId!==e.i||r!==e.r)break;_(k,o).isSegmentDataCommandReceived=!0,n.firstBytesReceived(),t.totalBytes===void 0?t.setTotalBytes(t.loadedBytes+e.s):t.totalBytes-t.loadedBytes!==e.s&&g(M,o,mn).call(o,`bytes-length-mismatch`,`Peer response bytes length mismatch`)}break;case D.SegmentDataSendingCompleted:{let t=_(k,o);if(!(t!=null&&t.isSegmentDataCommandReceived))return;let{request:n,controls:r,requestId:i}=t;if(n.segment.externalId!==e.i||i!==e.r){g(M,o,mn).call(o,`protocol-violation`,`Peer protocol violation`);return}if(n.loadedBytes!==n.totalBytes){g(M,o,mn).call(o,`bytes-length-mismatch`,`Peer response bytes length mismatch`);return}let a=yield n.validateData(_(un,o).validateP2PSegment);if(_(sn,o)||_(k,o)!==t)return;if(!a){g(M,o,mn).call(o,`validation-failed`,`P2P segment validation failed`);return}C(nn,o,0),r.completeOnSuccess(),_(A,o).stopLoading(),C(k,o,void 0);break}case D.SegmentAbsent:var t;_(en,o).delete(e.i),((t=_(k,o))==null?void 0:t.request.segment.externalId)===e.i&&_(k,o).requestId===e.r&&g(M,o,hn).call(o,`peer-segment-absent`);break;case D.CancelSegmentRequest:if(_(on,o)===e.r&&C(on,o,void 0),_(O,o).getUploadingRequestId()!==e.r)break;_(O,o).stopUploadingSegmentData();break}});return function(t){return e.apply(this,arguments)}}()),h(this,fn,e=>{var t;if(!((t=_(k,this))!=null&&t.isSegmentDataCommandReceived))return;let{request:n,controls:r}=_(k,this);if(n.totalBytes!==void 0&&n.loadedBytes+e.byteLength>n.totalBytes){g(M,this,mn).call(this,`bytes-length-mismatch`,`Peer response bytes length mismatch`);return}_(A,this).addBytes(e.byteLength),_(rn,this).timestamp=0,r.addLoadedChunk(e)}),this.id=e,this.channel=t,this.eventTarget=a,C(cn,this,n),C(ln,this,r),C(un,this,i),C(O,this,new Xt(t,i,{onSegmentChunkReceived:_(fn,this),onCommandReceived:e=>void _(dn,this).call(this,e).catch(t=>{_(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=_(k,this))==null?void 0:e.request.segment}get isUploadingSegment(){return _(O,this).getUploadingRequestId()!==void 0}getDownloadBandwidth(){let e=performance.now();return e-_(rn,this).timestamp>1e3&&(_(rn,this).value=_(A,this).getBandwidthLoadingOnly(15),_(rn,this).timestamp=e),_(rn,this).value}getSegmentStatus(e){let{externalId:t}=e;if(_(en,this).has(t))return`loaded`;if(_(tn,this).has(t))return`http-loading`}downloadSegment(e){if(_(sn,this))return;if(_(k,this))throw Error(`Some segment already is downloading`);if(e.tryCompleteByLoadedBytes({downloadSource:`p2p`,peerId:this.id},{notReceivingBytesTimeoutMs:_(un,this).p2pNotReceivingBytesTimeoutMs,onAbort:()=>void 0},_(un,this).validateP2PSegment,`p2p-segment-validation-failed`))return;_(A,this).startLoading(),C(an,this,(_(an,this)+1)%1e9),C(k,this,{request:e,requestId:_(an,this),isSegmentDataCommandReceived:!1,controls:e.start({downloadSource:`p2p`,peerId:this.id},{notReceivingBytesTimeoutMs:_(un,this).p2pNotReceivingBytesTimeoutMs,onAbort:t=>{if(!_(k,this)||_(k,this).request!==e)return;let{request:n,requestId:r}=_(k,this);if(g(M,this,gn).call(this,n.segment,r),_(A,this).stopLoading(),t.type!==`abort`&&(_(A,this).clear(),_(rn,this).timestamp=0,_(j,this).call(this,`cleared bandwidth history due to ${t.type}`)),C(k,this,void 0),t.type===`bytes-receiving-timeout`){var i;C(nn,this,(i=_(nn,this),i++,i))}_(nn,this)>=_(un,this).p2pErrorRetries?this.destroy(!1,new ne(`timeout`,`Too many timeout errors`)):t.type===`bytes-receiving-timeout`&&_(ln,this).onWarning(new re(`timeout-strike`,`Timeout strike ${_(nn,this)}/${_(un,this).p2pErrorRetries}`))}})});let t={c:D.SegmentRequest,r:_(k,this).requestId,i:e.segment.externalId};e.loadedBytes&&(t.b=e.loadedBytes),g(M,this,vn).call(this,t)||g(M,this,hn).call(this,`peer-closed`)}uploadSegmentData(e,t,n){var r=this;return y(function*(){if(_(sn,r))return;if(t!==_(on,r)){_(j,r).call(r,`discarding obsolete upload request ${t} for segment ${e.externalId}`);return}let{externalId:i}=e;_(j,r).call(r,`send segment ${e.externalId} to ${r.id} (byteLength: ${n.byteLength})`);let a={c:D.SegmentData,i,r:t,s:n.byteLength};if(g(M,r,vn).call(r,a))try{if(yield _(O,r).splitSegmentDataToChunksAndUploadAsync(n,t),r.isDestroyed||t!==_(on,r))return;g(M,r,_n).call(r,e,t),_(j,r).call(r,`segment ${i} has been sent to ${r.id}`)}catch(e){_(j,r).call(r,`cancel segment uploading ${i}: %O`,e)}})()}sendSegmentsAnnouncementCommand(e,t){let n={c:D.SegmentsAnnouncement,p:t,l:e};g(M,this,vn).call(this,n)}sendSegmentAbsentCommand(e,t){g(M,this,vn).call(this,{c:D.SegmentAbsent,i:e,r:t})}destroy(e=!1,t){_(sn,this)||(C(sn,this,!0),g(M,this,hn).call(this,`peer-closed`,t),_(O,this).destroy(),e||_(cn,this).call(this,t),_(j,this).call(this,`peer closed ${this.id}`))}};function mn(e,t){var n;(n=_(k,this))==null||n.request.clearLoadedBytes();let r=new ne(e,t);g(M,this,hn).call(this,`peer-closed`,r),this.destroy(!1,r)}function hn(e,t){if(!_(k,this))return;let{request:n,controls:r}=_(k,this),{segment:i}=n;_(j,this).call(this,`cancel segment request ${i.externalId} (${e})`);let a=new m(e,void 0,t);r.failWithError(a),_(A,this).stopLoading(),e!==`peer-segment-absent`&&(_(A,this).clear(),_(rn,this).timestamp=0,_(j,this).call(this,`cleared bandwidth history due to ${a.type}`)),C(k,this,void 0)}function gn(e,t){g(M,this,vn).call(this,{c:D.CancelSegmentRequest,i:e.externalId,r:t})}function _n(e,t){g(M,this,vn).call(this,{c:D.SegmentDataSendingCompleted,r:t,i:e.externalId})}function vn(e){if(_(sn,this))return!1;try{return _(O,this).sendCommand(e),!0}catch(t){return _(j,this).call(this,`error sending command %d: %O`,e.c,t),!1}}var yn=class{constructor(){p(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()}},bn,xn,Sn,Cn,N=typeof window<`u`?window:{},wn=(bn=(xn=N.RTCPeerConnection)==null?N.webkitRTCPeerConnection:xn)==null?N.mozRTCPeerConnection:bn,Tn=(Sn=(Cn=N.RTCSessionDescription)==null?N.webkitRTCSessionDescription:Cn)==null?N.mozRTCSessionDescription:Sn,En=(()=>{if(!N.RTCPeerConnection&&!N.webkitRTCPeerConnection&&!N.mozRTCPeerConnection)return!1;let e;try{e=new wn;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 Dn(e,t){return En?e.createOffer(t):new Promise((n,r)=>{try{e.createOffer(n,r,t)}catch(e){r(e)}})}function On(e,t){return En?e.createAnswer(t):new Promise((n,r)=>{try{e.createAnswer(n,r,t)}catch(e){r(e)}})}function kn(e,t){return En?e.setLocalDescription(t):new Promise((n,r)=>{try{e.setLocalDescription(t,n,r)}catch(e){r(e)}})}function An(e,t){return En?e.setRemoteDescription(t):new Promise((n,r)=>{try{e.setRemoteDescription(t,n,r)}catch(e){r(e)}})}var jn=5e4,Mn=15e3,Nn=5,Pn=5e3;function Fn(){let e=``;for(let t=0;t<20;t++)e+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*62));return e}var In=new Set([`offer`,`answer`,`pranswer`,`rollback`]);function Ln(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.type==`string`&&In.has(t.type)&&typeof t.sdp==`string`}var P=new WeakMap,F=new WeakMap,I=new WeakMap,Rn=new WeakMap,L=new WeakMap,R=new WeakMap,zn=new WeakMap,Bn=new WeakMap,Vn=new WeakMap,Hn=new WeakMap,Un=new WeakMap,Wn=new WeakMap,Gn=new WeakMap,z=new WeakSet,Kn=new WeakMap,qn=new WeakMap,Jn=new WeakMap,Yn=class{constructor(e){var t,n,r,i,a,o;S(this,z),h(this,P,void 0),h(this,F,void 0),h(this,I,new yn),h(this,Rn,new Map),h(this,L,new Set),h(this,R,new pe),h(this,zn,null),h(this,Bn,null),h(this,Vn,0),h(this,Hn,null),h(this,Un,void 0),h(this,Wn,null),h(this,Gn,!1),h(this,Kn,()=>{g(z,this,Xn).call(this,lr._),g(z,this,Qn).call(this,`started`).catch(e=>{g(z,this,B).call(this)||_(I,this).dispatchEvent(`error`,new ie(`announce-failed`,`Initial announce failed: ${e instanceof Error?e.message:String(e)}`,e))})}),h(this,qn,()=>{g(z,this,Zn).call(this),C(Bn,this,null)}),h(this,Jn,e=>{if(g(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){_(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!==_(P,this).infoHash)return;let i=n[`warning message`];typeof i==`string`&&_(I,this).dispatchEvent(`warning`,new ae(`tracker-response`,i));let a=n[`failure reason`];if(typeof a==`string`){_(I,this).dispatchEvent(`error`,new ie(`tracker-response`,a));return}let{interval:o}=n;if(typeof o==`number`&&o>0){let e=Math.max(ur._,o);_(Bn,this)!==e&&g(z,this,Xn).call(this,e)}let s=n[`tracker id`];typeof s==`string`&&C(Wn,this,s);let c=n.peer_id;if(typeof c==`string`&&c===_(P,this).peerId)return;let l=n.offer_id;typeof c!=`string`||typeof l!=`string`||(Ln(n.offer)?g(z,this,nr).call(this,{sdp:n.offer,peerId:c,offerId:l}).catch(e=>{g(z,this,B).call(this)||_(I,this).dispatchEvent(`error`,new ie(`signaling-failed`,`Failed to handle offer: ${e instanceof Error?e.message:String(e)}`,e))}):Ln(n.answer)&&g(z,this,rr).call(this,{sdp:n.answer,peerId:c,offerId:l}).catch(e=>{g(z,this,B).call(this)||_(I,this).dispatchEvent(`error`,new ie(`signaling-failed`,`Failed to handle answer: ${e instanceof Error?e.message:String(e)}`,e))}))}),C(P,this,{infoHash:e.infoHash,peerId:e.peerId,rtcConfig:e.rtcConfig,channelConfig:e.channelConfig,offerTimeout:(t=e.offerTimeout)==null?(()=>jn):t,offersCount:(n=e.offersCount)==null?(()=>Nn):n,iceGatheringTimeout:(r=e.iceGatheringTimeout)==null?(()=>Pn):r,connectionTimeout:(i=e.connectionTimeout)==null?(()=>Mn):i,claimPeer:(a=e.claimPeer)==null?(()=>!0):a,shouldGenerateOffers:(o=e.shouldGenerateOffers)==null?(()=>!0):o}),C(F,this,e.wsClient)}addEventListener(e,t){_(I,this).addEventListener(e,t)}removeEventListener(e,t){_(I,this).removeEventListener(e,t)}start(){g(z,this,B).call(this)||_(Gn,this)||(C(Gn,this,!0),_(F,this).addEventListener(`connected`,_(Kn,this)),_(F,this).addEventListener(`disconnected`,_(qn,this)),_(F,this).addEventListener(`message`,_(Jn,this)),_(F,this).state===`connected`&&_(Kn,this).call(this))}destroy(){g(z,this,B).call(this)||(_(R,this).abort(),g(z,this,Zn).call(this),g(z,this,er).call(this),g(z,this,sr).call(this),g(z,this,cr).call(this),_(Gn,this)&&(_(F,this).removeEventListener(`connected`,_(Kn,this)),_(F,this).removeEventListener(`disconnected`,_(qn,this)),_(F,this).removeEventListener(`message`,_(Jn,this))),_(I,this).clear())}};function B(){return _(R,this).signal.aborted}function V(){if(_(R,this).signal.aborted)throw Error(`Client destroyed`)}function Xn(e){var t=this,n;g(z,this,Zn).call(this),C(Bn,this,e);let r=C(Vn,this,(n=_(Vn,this),++n)),i=function(){var e=y(function*(){try{yield g(z,t,Qn).call(t)}catch(e){if(g(z,t,B).call(t))return;_(I,t).dispatchEvent(`error`,new ie(`announce-failed`,`Announce failed: ${e instanceof Error?e.message:String(e)}`,e))}!g(z,t,B).call(t)&&_(Bn,t)!==null&&_(Vn,t)===r&&C(zn,t,setTimeout(i,_(Bn,t)*1e3))});return function(){return e.apply(this,arguments)}}();C(zn,this,setTimeout(i,e*1e3))}function Zn(){_(zn,this)!==null&&(clearTimeout(_(zn,this)),C(zn,this,null))}function Qn(e){var t=this;return y(function*(){if(g(z,t,B).call(t)||_(F,t).state!==`connected`)return;if(e&&C(Un,t,e),_(Hn,t))return _(Hn,t);let n=y(function*(){let e=_(P,t).shouldGenerateOffers()?_(P,t).offersCount():0,n=yield Promise.all(Array.from({length:e},()=>g(z,t,$n).call(t)));if(g(z,t,B).call(t)){for(let e of n)e&&g(z,t,or).call(t,e.offer_id);return}let r=[];for(let e of n)e&&r.push(e);let i=_(Un,t);C(Un,t,void 0);let a=g(z,t,tr).call(t,{numwant:r.length,offers:r,event:i});if(_(F,t).state!==`connected`){for(let e of r)g(z,t,or).call(t,e.offer_id);return}try{_(F,t).send(JSON.stringify(a))}catch(e){for(let e of r)g(z,t,or).call(t,e.offer_id);throw e}})();C(Hn,t,n);try{yield n}finally{_(Hn,t)===n&&C(Hn,t,null)}})()}function $n(){var e=this;return y(function*(){if(g(z,e,B).call(e))return;let t;try{var n,r;t=new wn((n=(r=_(P,e)).rtcConfig)==null?void 0:n.call(r)),_(L,e).add(t);let i=t.createDataChannel(`webtorrent`,_(P,e).channelConfig),a=yield Dn(t);g(z,e,V).call(e),yield kn(t,a),g(z,e,V).call(e),yield g(z,e,ir).call(e,t),g(z,e,V).call(e);let o=t.localDescription;if(!(o!=null&&o.sdp)){t.close();return}let s=Fn();return _(Rn,e).set(s,{connection:t,channel:i,timeoutId:setTimeout(()=>{g(z,e,or).call(e,s)},_(P,e).offerTimeout())}),{offer:{type:o.type,sdp:o.sdp},offer_id:s}}catch(n){t==null||t.close(),g(z,e,B).call(e)||_(I,e).dispatchEvent(`warning`,new ae(`offer-failed`,`Failed to create offer: ${n instanceof Error?n.message:String(n)}`,n))}finally{t&&_(L,e).delete(t)}})()}function er(){if(_(F,this).state!==`connected`)return;let e=g(z,this,tr).call(this,{numwant:0,offers:[],event:`stopped`});try{_(F,this).send(JSON.stringify(e))}catch(e){}}function tr({numwant:e,offers:t,event:n}){let r={action:`announce`,info_hash:_(P,this).infoHash,peer_id:_(P,this).peerId,numwant:e,uploaded:0,downloaded:0,offers:t};return n&&(r.event=n),_(Wn,this)&&(r.trackerid=_(Wn,this)),r}function nr({sdp:e,peerId:t,offerId:n}){var r=this;return y(function*(){if(g(z,r,B).call(r)||!_(P,r).claimPeer(t))return;let i;try{var a,o;i=new wn((a=(o=_(P,r)).rtcConfig)==null?void 0:a.call(o)),_(L,r).add(i),yield An(i,new Tn(e)),g(z,r,V).call(r);let s=yield On(i);g(z,r,V).call(r),yield kn(i,s),g(z,r,V).call(r),yield g(z,r,ir).call(r,i),g(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:_(P,r).infoHash,peer_id:_(P,r).peerId,to_peer_id:t,offer_id:n,answer:{type:c.type,sdp:c.sdp}};_(F,r).send(JSON.stringify(l));let u=yield g(z,r,ar).call(r,i);g(z,r,V).call(r),_(I,r).dispatchEvent(`peerConnected`,{peerId:t,connection:i,channel:u})}catch(e){i==null||i.close(),_(I,r).dispatchEvent(`peerConnectFailed`,{peerId:t,error:new oe(`connection-failed`,e instanceof Error?e.message:String(e),e)})}finally{i&&_(L,r).delete(i)}})()}function rr({sdp:e,peerId:t,offerId:n}){var r=this;return y(function*(){if(g(z,r,B).call(r))return;let i=_(Rn,r).get(n);if(i){if(_(Rn,r).delete(n),clearTimeout(i.timeoutId),!_(P,r).claimPeer(t)){i.connection.close();return}_(L,r).add(i.connection);try{yield An(i.connection,new Tn(e)),g(z,r,V).call(r);let n=yield g(z,r,ar).call(r,i.connection,i.channel);g(z,r,V).call(r),_(I,r).dispatchEvent(`peerConnected`,{peerId:t,connection:i.connection,channel:n})}catch(e){i.connection.close(),_(I,r).dispatchEvent(`peerConnectFailed`,{peerId:t,error:new oe(`connection-failed`,e instanceof Error?e.message:String(e),e)})}finally{_(L,r).delete(i.connection)}}})()}function ir(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),_(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(_(R,this).signal.aborted){c();return}r=setTimeout(()=>{i(),t()},_(P,this).iceGatheringTimeout()),e.addEventListener(`icegatheringstatechange`,a),e.addEventListener(`icecandidate`,o),e.addEventListener(`signalingstatechange`,s),_(R,this).signal.addEventListener(`abort`,c)})}function ar(e,t){let{promise:n,resolve:r,reject:i}=xe(),a,o=t,s=()=>Ft(e.iceConnectionState)?(p(),i(Error(`ICE connection ${e.iceConnectionState}`)),!0):!1,c=()=>{p(),o?r(o):i(Error(`Data channel missing on open`))},l=()=>{p(),i(Error(`Data channel error`))},u=()=>{p(),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)},ee=()=>{p(),i(Error(`Connection aborted due to teardown`))},p=()=>{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)),_(R,this).signal.removeEventListener(`abort`,ee)};return _(R,this).signal.aborted?(ee(),n):s()?n:(a=setTimeout(()=>{p(),i(Error(`Data channel open timeout`))},_(P,this).connectionTimeout()),e.addEventListener(`iceconnectionstatechange`,s),_(R,this).signal.addEventListener(`abort`,ee),o?d(o):e.addEventListener(`datachannel`,f),n)}function or(e,t){let n=t==null?_(Rn,this).get(e):t;n&&(clearTimeout(n.timeoutId),n.connection.close(),_(Rn,this).delete(e))}function sr(){for(let[e,t]of _(Rn,this))g(z,this,or).call(this,e,t)}function cr(){for(let e of _(L,this))e.close();_(L,this).clear()}var lr={_:120},ur={_:20},dr=50,fr=1.5,H=new WeakMap,U=new WeakMap,W=new WeakMap,G=new WeakMap,pr=new WeakMap,mr=new WeakMap,hr=new WeakMap,gr=new WeakMap,_r=new WeakSet,vr=class{constructor(e){var t,n;S(this,_r),h(this,H,void 0),h(this,U,new yn),h(this,W,new Set),h(this,G,new Map),h(this,pr,new Set),h(this,mr,!1),h(this,hr,!1),h(this,gr,e=>{if(_(mr,this)||_(W,this).has(e)||_(G,this).has(e))return!1;let t=Math.floor(_(H,this).maxPeers()*Math.max(1,_(H,this).maxPeersMultiplier()));return _(W,this).size+_(G,this).size>=t?!1:(_(W,this).add(e),!0)}),C(H,this,v(v({},e),{},{maxPeers:(t=e.maxPeers)==null?(()=>dr):t,maxPeersMultiplier:(n=e.maxPeersMultiplier)==null?(()=>fr):n}))}addEventListener(e,t){_(U,this).addEventListener(e,t)}removeEventListener(e,t){_(U,this).removeEventListener(e,t)}start(){if(!(_(mr,this)||_(hr,this))){C(hr,this,!0);try{for(let e of _(H,this).trackerUrls){let{client:t,release:n}=_(H,this).socketPool.acquire(e),r=!1;try{let i=new Yn({infoHash:_(H,this).infoHash,peerId:_(H,this).peerId,wsClient:t,rtcConfig:_(H,this).rtcConfig,channelConfig:_(H,this).channelConfig,claimPeer:_(gr,this),offersCount:_(H,this).offersCount,offerTimeout:_(H,this).offerTimeout,iceGatheringTimeout:_(H,this).iceGatheringTimeout,connectionTimeout:_(H,this).connectionTimeout,shouldGenerateOffers:()=>_(W,this).size+_(G,this).size<_(H,this).maxPeers()}),a=t=>{_(W,this).delete(t.peerId),g(_r,this,br).call(this,t.peerId,t.connection,t.channel,e)},o=t=>{_(W,this).has(t.peerId)&&(_(W,this).delete(t.peerId),_(U,this).dispatchEvent(`peerConnectFailed`,{peerId:t.peerId,trackerUrl:e,error:t.error}))},s=t=>{_(U,this).dispatchEvent(`warning`,{trackerUrl:e,warning:t})},c=t=>{_(U,this).dispatchEvent(`error`,{trackerUrl:e,error:t})};i.addEventListener(`peerConnected`,a),i.addEventListener(`peerConnectFailed`,o),i.addEventListener(`warning`,s),i.addEventListener(`error`,c),_(pr,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(_(mr,this))return;C(mr,this,!0);for(let{client:e,releaseSocket:t,cleanupListeners:n}of _(pr,this))n(),e.destroy(),t();_(pr,this).clear(),_(W,this).clear();let e=[..._(G,this).entries()];_(G,this).clear();for(let[t,n]of e){n.cleanup();try{n.channel.close()}catch(e){}try{n.connection.close()}catch(e){}_(U,this).dispatchEvent(`peerDisconnected`,{peerId:t,trackerUrl:n.trackerUrl,disconnectReason:`Manager destroyed`})}_(U,this).clear()}};function yr(e,t){if(_(mr,this))return;let n=_(G,this).get(e);if(n){_(G,this).delete(e),n.cleanup();try{n.channel.close()}catch(e){}try{n.connection.close()}catch(e){}_(U,this).dispatchEvent(`peerDisconnected`,v({peerId:e,trackerUrl:n.trackerUrl},t))}}function br(e,t,n,r){if(Ft(t.iceConnectionState)){try{t.close()}catch(e){}_(U,this).dispatchEvent(`peerConnectFailed`,{peerId:e,trackerUrl:r,error:new oe(`connection-failed`,`Connection failed during promotion`)});return}let i=t=>g(_r,this,yr).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=>g(_r,this,yr).call(this,e,t?{error:t}:{disconnectReason:`Closed by consumer`});_(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),_(U,this).dispatchEvent(`peerConnected`,{peerId:e,connection:t,channel:n,trackerUrl:r,close:e=>l==null?void 0:l(e)})}function xr(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 Sr=`v2`;function Cr({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():``,ee=s&&!isNaN(Number(s))?Number(s).toString():``,p=c?c.toUpperCase().trim():``,te=`${e==null?0:e}-${l}-${n==null?``:n}-${r==null?``:r}-${u}-${d}-${f}-${ee}-${p}`;return btoa(xr(te))}function wr(e,t){return`${Sr}-${e}-${Dr(t)}`}function Tr(e,t){for(let n of e.values()){let e=n.segments.get(t);if(e)return e}}function Er(e,t){for(let n of e.segments.values())if(n.externalId===t)return n}function Dr(e){return`${e.type}-${e.index}`}function Or(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 kr(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 Ar(e,t,n,r,i){let{highDemandTimeWindow:a,httpDownloadTimeWindow:o,p2pDownloadTimeWindow:s}=kr(n,i);return{isHighDemand:jr(e,t,a),isHttpDownloadable:jr(e,t,o),isP2PDownloadable:jr(e,t,s)&&r.isSegmentLoadingOrLoadedBySomeone(e)}}function jr(e,t,n){let{startTime:r,endTime:i}=e,{position:a,rate:o}=t;return!(a+n*o<r||a>i)}var Mr=`-PM${Lr(`3.0.1`)}-`,Nr=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`,Pr=20;function Fr(e){return btoa(xr(e).slice(0,15))}function Ir(e){let t=[e],n=Pr-e.length;for(let e=0;e<n;e++)t.push(Nr[Math.floor(Math.random()*62)]);return t.join(``)}function Lr(e){let t=e.split(`.`);return`${`00${t[0]}`.slice(-2)}${`00${t[1]}`.slice(-2)}`}var Rr=1e3,K=new WeakMap,q=new WeakMap,zr=new WeakMap,Br=new WeakMap,Vr=new WeakMap,Hr=new WeakMap,Ur=new WeakMap,J=new WeakMap,Wr=new WeakMap,Y=new WeakMap,Gr=new WeakMap,Kr=new WeakMap,X=new WeakMap,qr=new WeakMap,Jr=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 WeakSet,oi=new WeakMap,si=new WeakMap,ci=new WeakMap,li=new WeakMap,ui=class{constructor(e,t,n,r,i,a,o,s,c){var l=this,u;S(this,ai),h(this,K,void 0),h(this,q,new Map),h(this,zr,void 0),h(this,Br,void 0),h(this,Vr,!1),h(this,Hr,(0,b.default)(`p2pml-core:webtorrent-manager`)),h(this,Ur,(0,b.default)(`p2pml-core:churn-cleanup`)),h(this,J,void 0),h(this,Wr,void 0),h(this,Y,void 0),h(this,Gr,void 0),h(this,Kr,void 0),h(this,X,void 0),h(this,qr,void 0),h(this,Jr,void 0),h(this,Yr,void 0),h(this,Xr,void 0),h(this,Zr,void 0),h(this,Qr,void 0),h(this,$r,void 0),h(this,ei,void 0),h(this,ti,void 0),h(this,ni,void 0),h(this,ri,void 0),h(this,ii,()=>{C(Xr,this,setTimeout(_(ii,this),Math.max(Rr,_(X,this).p2pChurnCleanupIntervalMs)));let e=_(q,this).size-_(X,this).p2pMaxPeers;if(e<=0)return;let t=[],n=performance.now();for(let e of _(q,this).values())e.downloadingSegment||e.isUploadingSegment||n-e.connectedAt<_(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);_(Ur,this).call(this,`Background churn cleanup: dropping ${r.length} excess peers (total: ${_(q,this).size}, target: ${_(X,this).p2pMaxPeers}, eligible: ${t.length})`);for(let e of r)_(Ur,this).call(this,`dropping excess peer ${e.id} with bandwidth ${e.getDownloadBandwidth()}`),e.destroy()}),h(this,oi,e=>{if(_(Hr,this).call(this,`peerConnected: peerId=${e.peerId}`),_(q,this).has(e.peerId)){e.close();return}let t=new pn(e.peerId,e.channel,e.close,{onSegmentRequested:(e,t,n,r)=>{_(li,this).call(this,e,t,n,r).catch(n=>{_(Hr,this).call(this,`Error in onSegmentRequested ${t} for peer ${e.id}:`,n)})},onSegmentsAnnouncement:_(Yr,this),onWarning:e=>{_(ti,this).call(this,{peerId:t.id,infoHash:_(J,this),streamType:_(Y,this).type,warning:e})}},{p2pNotReceivingBytesTimeoutMs:_(X,this).p2pNotReceivingBytesTimeoutMs,webRtcMaxMessageSize:_(X,this).webRtcMaxMessageSize,p2pErrorRetries:_(X,this).p2pErrorRetries,validateP2PSegment:_(X,this).validateP2PSegment,streamType:_(Y,this).type,infoHash:_(J,this)},_(Jr,this));if(_(q,this).set(e.peerId,t),_(Zr,this).call(this,{peerId:e.peerId,infoHash:_(J,this),streamType:_(Y,this).type}),_(X,this).isP2PUploadDisabled)return;let{httpLoading:n,loaded:r}=g(ai,this,di).call(this);t.sendSegmentsAnnouncementCommand(r,n)}),h(this,si,e=>{var t;_(Hr,this).call(this,`peerDisconnected: peerId=%s error=%s reason=%s`,e.peerId,(t=e.error)==null?void 0:t.message,e.disconnectReason);let n=_(q,this).get(e.peerId);n&&(_(q,this).delete(e.peerId),n.destroy(!0),e.error&&_(ei,this).call(this,{peerId:e.peerId,infoHash:_(J,this),streamType:_(Y,this).type,error:e.error}),_($r,this).call(this,{peerId:n.id,infoHash:_(J,this),streamType:_(Y,this).type}))}),p(this,`broadcastAnnouncement`,(e=!1)=>{if(e){_(ci,this).call(this,e);return}_(Vr,this)||_(X,this).isP2PUploadDisabled||_(ci,this).call(this)}),h(this,ci,(e=!1)=>{C(Vr,this,!0),Se(()=>{let{loaded:t=[],httpLoading:n=[]}=e?{}:g(ai,this,di).call(this);for(let e of _(q,this).values())e.sendSegmentsAnnouncementCommand(t,n);C(Vr,this,!1)})}),h(this,li,function(){var e=y(function*(e,t,n,r){let i=Er(_(Y,l),t);if(!i)return;if(_(X,l).isP2PUploadDisabled){e.sendSegmentAbsentCommand(t,n);return}let a;try{a=yield _(Kr,l).getSegmentData(_(zr,l),_(Br,l),i.externalId)}catch(n){_(Hr,l).call(l,`Storage error for segment ${t} requested by peer ${e.id}:`,n)}if(_(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)}}()),C(Wr,this,e),C(Y,this,t),C(Gr,this,n),C(Kr,this,r),C(X,this,i),C(qr,this,a),C(Jr,this,o),C(Yr,this,c),C(Zr,this,o.getEventDispatcher(`onPeerConnect`)),C(Qr,this,o.getEventDispatcher(`onPeerConnectError`)),C($r,this,o.getEventDispatcher(`onPeerClose`)),C(ei,this,o.getEventDispatcher(`onPeerError`)),C(ti,this,o.getEventDispatcher(`onPeerWarning`)),C(ni,this,o.getEventDispatcher(`onTrackerWarning`)),C(ri,this,o.getEventDispatcher(`onTrackerError`)),C(zr,this,(u=_(X,this).swarmId)==null?_(Wr,this):u),C(Br,this,wr(_(zr,this),_(Y,this)));let d=Fr(_(Br,this));C(J,this,d),C(K,this,new vr({infoHash:d,peerId:s,trackerUrls:_(X,this).announceTrackers,rtcConfig:()=>_(X,this).rtcConfig,socketPool:_(qr,this),maxPeers:()=>_(X,this).p2pMaxPeers,maxPeersMultiplier:()=>_(X,this).p2pChurnMaxPeersMultiplier,offersCount:()=>_(X,this).webRtcOffersCount,offerTimeout:()=>_(X,this).webRtcOfferTimeoutMs,iceGatheringTimeout:()=>_(X,this).webRtcIceGatheringTimeoutMs,connectionTimeout:()=>_(X,this).webRtcConnectionTimeoutMs})),_(K,this).addEventListener(`peerConnected`,_(oi,this)),_(K,this).addEventListener(`peerDisconnected`,_(si,this)),_(K,this).addEventListener(`peerConnectFailed`,e=>{_(Hr,this).call(this,`Peer connection failed (${e.peerId}) from tracker ${e.trackerUrl}:`,e.error),_(Qr,this).call(this,{peerId:e.peerId,infoHash:_(J,this),streamType:_(Y,this).type,trackerUrl:e.trackerUrl,error:e.error})}),_(K,this).addEventListener(`warning`,e=>{_(Hr,this).call(this,`Tracker warning (${e.trackerUrl}):`,e.warning),_(ni,this).call(this,{trackerUrl:e.trackerUrl,infoHash:_(J,this),streamType:_(Y,this).type,warning:e.warning})}),_(K,this).addEventListener(`error`,e=>{_(Hr,this).call(this,`Tracker error (${e.trackerUrl}):`,e.error),_(ri,this).call(this,{trackerUrl:e.trackerUrl,infoHash:_(J,this),streamType:_(Y,this).type,error:e.error})}),_(Jr,this).addEventListener(`onStorageUpdated-${_(Br,this)}`,this.broadcastAnnouncement),_(K,this).start(),C(Xr,this,setTimeout(_(ii,this),Math.max(Rr,_(X,this).p2pChurnCleanupIntervalMs)))}downloadSegment(e){let t=[];for(let n of _(q,this).values())!n.downloadingSegment&&n.getSegmentStatus(e)===`loaded`&&t.push(n);if(t.length===0)return;let n=fi(t),r=_(Gr,this).getOrCreateRequest(e);n.downloadSegment(r)}isSegmentLoadingOrLoadedBySomeone(e){for(let t of _(q,this).values())if(t.getSegmentStatus(e))return!0;return!1}isSegmentLoadedBySomeone(e){for(let t of _(q,this).values())if(t.getSegmentStatus(e)===`loaded`)return!0;return!1}get connectedPeerCount(){return _(q,this).size}*peers(){for(let e of _(q,this).values())yield e}destroy(){clearTimeout(_(Xr,this)),C(Xr,this,void 0),_(Jr,this).removeEventListener(`onStorageUpdated-${_(Br,this)}`,this.broadcastAnnouncement),_(K,this).destroy();for(let e of _(q,this).values())e.destroy();_(q,this).clear()}};function di(){let e=_(Kr,this).getStoredSegmentIds(_(zr,this),_(Br,this)),t=[];for(let e of _(Gr,this).httpRequests()){let n=_(Y,this).segments.get(e.segment.runtimeId);n&&t.push(n.externalId)}return{loaded:e,httpLoading:t}}function fi(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 pi(e){return`${e.type}-${e.index}`}function mi(e){let{externalId:t}=e;return`(${pi(e.stream)} | ${t})`}var hi=new WeakMap,gi=new WeakMap,_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 WeakSet,Di=class{constructor(e,t,n,r,i,a,o,s,c){S(this,Ei),h(this,hi,new Map),h(this,gi,void 0),h(this,_i,(0,b.default)(`p2pml-core:p2p-loaders-container`)),h(this,vi,void 0),h(this,yi,void 0),h(this,bi,void 0),h(this,xi,void 0),h(this,Si,void 0),h(this,Ci,void 0),h(this,wi,void 0),h(this,Ti,void 0),C(vi,this,e),C(yi,this,n),C(bi,this,r),C(xi,this,i),C(Si,this,a),C(Ci,this,o),C(wi,this,s),C(Ti,this,c),C(gi,this,g(Ei,this,ki).call(this,t)),_(_i,this).call(this,`set current p2p loader: ${pi(t)}`)}changeCurrentLoader(e){var t;let n=(t=_(xi,this).swarmId)==null?_(vi,this):t,r=wr(n,_(gi,this).stream);_(bi,this).getStoredSegmentIds(n,r).length?g(Ei,this,Ai).call(this,_(gi,this)):g(Ei,this,ji).call(this,_(gi,this)),C(gi,this,g(Ei,this,ki).call(this,e)),_(_i,this).call(this,`change current p2p loader: ${pi(e)}`)}get currentLoader(){return _(gi,this).loader}destroy(){for(let{loader:e,destroyTimeoutId:t}of _(hi,this).values())e.destroy(),clearTimeout(t);_(hi,this).clear()}};function Oi(e){if(_(hi,this).has(e.runtimeId))throw Error(`Loader for this stream already exists`);let t=new ui(_(vi,this),e,_(yi,this),_(bi,this),_(xi,this),_(Si,this),_(Ci,this),_(wi,this),()=>{_(gi,this).loader===t&&_(Ti,this).call(this)}),n=pi(e);return _(_i,this).call(this,`created new loader: ${n}`),{loader:t,stream:e,loggerInfo:n}}function ki(e){let t=_(hi,this).get(e.runtimeId);if(t)return clearTimeout(t.destroyTimeoutId),t.destroyTimeoutId=void 0,t;{let t=g(Ei,this,Oi).call(this,e);return _(hi,this).set(e.runtimeId,t),t}}function Ai(e){e.destroyTimeoutId=window.setTimeout(()=>g(Ei,this,ji).call(this,e),_(xi,this).p2pInactiveLoaderDestroyTimeoutMs)}function ji(e){e.loader.destroy(),_(hi,this).delete(e.stream.runtimeId),_(_i,this).call(this,`destroy p2p loader: `,e.loggerInfo)}function Mi(e){return{runtimeId:e.runtimeId,externalId:e.externalId,url:e.url,byteRange:e.byteRange,startTime:e.startTime,endTime:e.endTime}}var Ni=class{constructor(e,t,n,r,i,a,o){p(this,`segment`,void 0),p(this,`requestProcessQueueCallback`,void 0),p(this,`bandwidthCalculators`,void 0),p(this,`playback`,void 0),p(this,`playbackConfig`,void 0),p(this,`infoHash`,void 0),p(this,`currentAttempt`,void 0),p(this,`_failedAttempts`,new Pi),p(this,`finalData`,void 0),p(this,`bytes`,[]),p(this,`_loadedBytes`,0),p(this,`_totalBytes`,void 0),p(this,`_status`,`not-started`),p(this,`progress`,void 0),p(this,`notReceivingBytesTimeout`,void 0),p(this,`_onAbortCallback`,void 0),p(this,`notReceivingBytesTimeoutMs`,void 0),p(this,`_logger`,void 0),p(this,`_isHandledByProcessQueue`,!1),p(this,`onSegmentError`,void 0),p(this,`onSegmentAbort`,void 0),p(this,`onSegmentStart`,void 0),p(this,`onSegmentLoaded`,void 0),p(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 m(`bytes-receiving-timeout`);(t=this._onAbortCallback)==null||t.call(this,r),this.handleFailure(r)}),p(this,`failWithError`,e=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&this.handleFailure(e)}),p(this,`handleFailure`,e=>{this.currentAttempt&&(this.setStatus(`failed`),this.logger(`${this.downloadSource} ${this.segment.externalId} failed ${e.type}`),this._failedAttempts.add(v(v({},this.currentAttempt),{},{error:e})),this.onSegmentError({segment:Mi(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())}),p(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:Mi(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())}),p(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}),p(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 Fi(this.abortOnTimeout);let{type:c}=this.segment.stream;this._logger=(0,b.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 y(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 y(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 m(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=v({},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:Mi(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 m(`abort`)),this.onSegmentAbort({segment:Mi(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]()}},Pi=class{constructor(){p(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=[]}},Fi=class{constructor(e){p(this,`action`,void 0),p(this,`timeoutId`,void 0),p(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}},Ii=class{constructor(e,t,n,r,i,a){p(this,`requestProcessQueueCallback`,void 0),p(this,`bandwidthCalculators`,void 0),p(this,`playback`,void 0),p(this,`config`,void 0),p(this,`eventTarget`,void 0),p(this,`swarmId`,void 0),p(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=Fr(wr(this.swarmId,e.stream));t=new Ni(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()}},Li=class{constructor(e,t){p(this,`segment`,void 0),p(this,`engineCallbacks`,void 0),p(this,`_status`,`pending`),p(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*Ri(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=Ar(l,t,n,r,i);if(zi(u)){let e=c.next();if(e.done)return;let a=e.value,o=Ar(a,t,n,r,i);if(zi(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=Ar(e,t,n,r,i);if(zi(a))break;yield{segment:e,statuses:a}}}function zi(e){let{isHighDemand:t,isHttpDownloadable:n,isP2PDownloadable:r}=e;return!t&&!n&&!r}var Bi=6e4,Vi=1e3,Hi=class{constructor(e,t,n,r,i,a,o,s,c){var l;p(this,`streamManifestUrl`,void 0),p(this,`lastRequestedSegment`,void 0),p(this,`streamDetails`,void 0),p(this,`config`,void 0),p(this,`bandwidthCalculators`,void 0),p(this,`segmentStorage`,void 0),p(this,`webTorrentSocketPool`,void 0),p(this,`eventTarget`,void 0),p(this,`peerId`,void 0),p(this,`requests`,void 0),p(this,`engineRequest`,void 0),p(this,`p2pLoaders`,void 0),p(this,`playback`,void 0),p(this,`segmentAvgDuration`,void 0),p(this,`logger`,void 0),p(this,`levelChangedTimestamp`,void 0),p(this,`lastQueueProcessingTimeStamp`,void 0),p(this,`randomHttpDownloadTimeout`,void 0),p(this,`initialHttpDelayTimeoutId`,void 0),p(this,`isProcessQueueMicrotaskCreated`,!1),p(this,`swarmId`,void 0),p(this,`createdAt`,performance.now()),p(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=Or(u),this.requests=new Ii(this.requestProcessQueueMicrotask,this.bandwidthCalculators,this.playback,this.config,this.eventTarget,this.swarmId),this.p2pLoaders=new Di(this.streamManifestUrl,this.lastRequestedSegment.stream,this.requests,this.segmentStorage,this.config,this.webTorrentSocketPool,this.eventTarget,this.peerId,this.requestProcessQueueMicrotask),this.logger=(0,b.default)(`p2pml-core:hybrid-loader-${u.type}`),this.logger.color=`coral`,this.setIntervalLoading()}setIntervalLoading(){let e=this.p2pLoaders.currentLoader.connectedPeerCount,t=Math.random()*Vi*e+Vi;this.randomHttpDownloadTimeout=window.setTimeout(()=>{this.loadRandomThroughHttp(),this.setIntervalLoading()},t)}loadSegment(e,t){var n=this;return y(function*(){n.logger(`requests: ${mi(e)}`);let{stream:r}=e;r!==n.lastRequestedSegment.stream&&(n.logger(`stream changed to ${pi(r)}`),n.p2pLoaders.changeCurrentLoader(r)),n.lastRequestedSegment=e;let i=wr(n.swarmId,r);n.segmentStorage.onSegmentRequested(n.swarmId,i,e.externalId,e.startTime,e.endTime,r.type,n.streamDetails.isLive);let a=new Li(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 ${mi(e)} in ${pi(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: ${mi(l)} (byteLength: ${o.data.byteLength})`);let e=wr(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>Bi&&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: `,mi(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 Ri(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,t)){let t=wr(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 Ri(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,i)){var a;n++;let{segment:i}=o,s=wr(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: ${pi(e)}`),this.requestProcessQueueMicrotask())}destroy(){var e;clearTimeout(this.randomHttpDownloadTimeout),clearTimeout(this.initialHttpDelayTimeoutId),(e=this.engineRequest)==null||e.abort(),this.requests.destroy(),this.p2pLoaders.destroy()}},Ui=(e,t)=>`${e}|${t}`,Wi=e=>/Android/i.test(e),Gi=e=>/iPad|iPhone/i.test(e),Ki=e=>/Android/i.test(e)&&(/; wv\)/i.test(e)||!/Chrome|Firefox/i.test(e)),qi=1048576,Ji=class{constructor(){p(this,`userAgent`,navigator.userAgent),p(this,`segmentMemoryStorageLimit`,4*1024),p(this,`currentStorageUsage`,0),p(this,`cache`,new Map),p(this,`logger`,void 0),p(this,`coreConfig`,void 0),p(this,`mainStreamConfig`,void 0),p(this,`secondaryStreamConfig`,void 0),p(this,`currentPlayback`,void 0),p(this,`lastRequestedSegment`,void 0),p(this,`segmentChangeCallback`,void 0),this.logger=(0,b.default)(`p2pml-core:segment-memory-storage`),this.logger.color=`RebeccaPurple`}initialize(e,t,n){var r=this;return y(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 y(function*(){c.clear(s,r.byteLength);let e=Ui(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 y(function*(){let e=Ui(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/qi}}hasSegment(e,t,n){let r=Ui(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=Ui(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/qi>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/qi}decreaseStorageUsage(e){this.currentStorageUsage-=e/qi}setMemoryStorageLimit(){var e;if((e=this.coreConfig)!=null&&e.segmentMemoryStorageLimit){this.segmentMemoryStorageLimit=this.coreConfig.segmentMemoryStorageLimit;return}Ki(this.userAgent)||Gi(this.userAgent)?this.segmentMemoryStorageLimit=1024:Wi(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}},Yi=new WeakMap,Z=new WeakMap,Q=new WeakMap,Xi=new WeakMap,Zi=new WeakMap,$=new WeakMap,Qi=new WeakMap,$i=new WeakMap,ea=new WeakMap,ta=new WeakMap,na=new WeakSet,ra=class{constructor(e){var t,n,r;S(this,na),h(this,Yi,void 0),h(this,Z,`disconnected`),h(this,Q,null),h(this,Xi,0),h(this,Zi,null),h(this,$,new yn),h(this,Qi,()=>{_(Z,this)!==`disposed`&&(C(Z,this,`connected`),C(Xi,this,0),_($,this).dispatchEvent(`connected`))}),h(this,$i,()=>{_(Z,this)!==`disposed`&&(_(Q,this)&&(_(Q,this).onopen=null,_(Q,this).onclose=null,_(Q,this).onerror=null,_(Q,this).onmessage=null,C(Q,this,null)),g(na,this,ia).call(this),_($,this).dispatchEvent(`disconnected`))}),h(this,ea,e=>{_(Z,this)!==`disposed`&&_($,this).dispatchEvent(`error`,e)}),h(this,ta,e=>{_(Z,this)!==`disposed`&&_($,this).dispatchEvent(`message`,e.data)});let i=Math.max(100,(t=e.initialDelay)==null?1e3:t);C(Yi,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 _(Z,this)}addEventListener(e,t){_($,this).addEventListener(e,t)}removeEventListener(e,t){_($,this).removeEventListener(e,t)}connect(){if(!(_(Z,this)===`connected`||_(Z,this)===`connecting`||_(Z,this)===`disposed`)){C(Z,this,`connecting`),g(na,this,aa).call(this);try{C(Q,this,new WebSocket(_(Yi,this).url)),_(Q,this).binaryType=`arraybuffer`,_(Q,this).onopen=_(Qi,this),_(Q,this).onclose=_($i,this),_(Q,this).onerror=_(ea,this),_(Q,this).onmessage=_(ta,this)}catch(e){C(Z,this,`disconnected`);let t=new ErrorEvent(`error`,{message:e instanceof Error?e.message:`Unknown WebSocket creation error`,error:e});_($,this).dispatchEvent(`error`,t)}}}send(e){if(_(Z,this)!==`connected`||!_(Q,this))throw Error(`WebSocketClient: Cannot send data when not connected`);_(Q,this).send(e)}dispose(){C(Z,this,`disposed`),g(na,this,aa).call(this),_(Q,this)&&(_(Q,this).onopen=null,_(Q,this).onclose=null,_(Q,this).onerror=null,_(Q,this).onmessage=null,_(Q,this).close(),C(Q,this,null)),_($,this).clear()}};function ia(){if(_(Z,this)===`disposed`)return;C(Z,this,`reconnecting`);let e=Math.min(_(Yi,this).initialDelay*Math.pow(2,_(Xi,this)),_(Yi,this).maxDelay),t=e*_(Yi,this).jitterMultiplier,n=Math.random()*2*t-t,r=Math.max(0,e+n);if(e<_(Yi,this).maxDelay){var i;C(Xi,this,(i=_(Xi,this),i++,i))}C(Zi,this,setTimeout(()=>{_(Z,this)!==`disposed`&&this.connect()},r)),_($,this).dispatchEvent(`reconnecting`)}function aa(){_(Zi,this)!==null&&(clearTimeout(_(Zi,this)),C(Zi,this,null))}var oa=new WeakMap,sa=new WeakMap,ca=class{constructor(){h(this,oa,new Map),h(this,sa,new yn)}addEventListener(e,t){_(sa,this).addEventListener(e,t)}removeEventListener(e,t){_(sa,this).removeEventListener(e,t)}acquire(e){let t=_(oa,this).get(e);if(!t){let n=new ra({url:e});n.addEventListener(`error`,t=>{_(sa,this).dispatchEvent(`error`,t,e)}),n.connect(),t={client:n,refCount:0},_(oa,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}`),_(oa,this).get(e)===t&&_(oa,this).delete(e),t.client.dispose()))}}}destroy(){_(sa,this).clear();let e=Array.from(_(oa,this).values());_(oa,this).clear();for(let t of e)try{t.client.dispose()}catch(e){console.error(`[WebTorrentSocketPool] Failed to dispose WebSocketClient:`,e)}}},la=class e{constructor(t){p(this,`eventTarget`,new yn),p(this,`manifestResponseUrl`,void 0),p(this,`streams`,new Map),p(this,`mainStreamConfig`,void 0),p(this,`secondaryStreamConfig`,void 0),p(this,`commonCoreConfig`,void 0),p(this,`bandwidthCalculators`,{all:new $t,http:new $t}),p(this,`segmentStorage`,void 0),p(this,`webTorrentSocketPool`,new ca),p(this,`socketPoolLogger`,(0,b.default)(`p2pml-core:webtorrent-socket-pool`)),p(this,`peerId`,void 0),p(this,`mainStreamLoader`,void 0),p(this,`secondaryStreamLoader`,void 0),p(this,`streamDetails`,{isLive:!1,activeLevelBitrate:0}),p(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=Ir(this.commonCoreConfig.trackerClientVersionPrefix),this.webTorrentSocketPool.addEventListener(`error`,(e,t)=>{this.socketPoolLogger(`WebSocket error for tracker url ${t}:`,e)})}getConfig(){return v(v({},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!!Tr(this.streams,e)}getStream(e){return this.streams.get(e)}addStreamIfNoneExists(e){this.streams.has(e.runtimeId)||this.streams.set(e.runtimeId,v(v({},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,v(v({},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 y(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 y(function*(){if(!e.segmentStorage){if(e.storageInitPromise)return e.storageInitPromise;e.storageInitPromise=y(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 Ji;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=Tr(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 Hi(this.manifestResponseUrl,e,this.streamDetails,t,this.bandwidthCalculators,this.segmentStorage,this.webTorrentSocketPool,this.eventTarget,this.peerId)}};p(la,`DEFAULT_COMMON_CORE_CONFIG`,{segmentMemoryStorageLimit:void 0,customSegmentStorageFactory:void 0,trackerClientVersionPrefix:Mr}),p(la,`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 ua=[`mp4a`,`ac-3`,`ec-3`,`ec+3`,`opus`,`vorb`,`flac`],da=class{constructor(e,t){p(this,`shaka`,void 0),p(this,`originalManifestParser`,void 0),p(this,`debug`,(0,b.debug)(`p2pml-shaka:manifest-parser`)),p(this,`isHls`,void 0),p(this,`segmentManager`,void 0),p(this,`player`,void 0),this.shaka=e,this.originalManifestParser=t,this.isHls=this.originalManifestParser instanceof e.hls.HlsParser}configure(e){return this.originalManifestParser.configure(e)}banLocation(e){return this.originalManifestParser.banLocation(e)}onInitialVariantChosen(e){return this.originalManifestParser.onInitialVariantChosen(e)}setP2PMediaLoaderData(e){e&&(this.segmentManager=e.segmentManager,this.player=e.player,e.streamInfo.protocol=this.isHls?`hls`:`dash`)}start(e,t){var n=this;return y(function*(){let{p2pml:r}=t.networkingEngine;n.setP2PMediaLoaderData(r);let i=yield n.originalManifestParser.start(e,t);return r?(n.isHls&&n.hookHlsStreamMediaSequenceTimeMaps(i.variants),n.processStreams(i.variants),i):i})()}stop(){return this.originalManifestParser.stop()}update(){return this.originalManifestParser.update()}setMediaElement(e){return this.originalManifestParser.setMediaElement(e)}onExpirationUpdated(e,t){return this.originalManifestParser.onExpirationUpdated(e,t)}processStreams(e){let{segmentManager:t}=this;if(!t)return;let n=new Set,r=(e,r,i)=>(this.hookSegmentIndex(e),t.setStream(e,r,i),n.add(e.id),!0);for(let t of e){let{video:e,audio:o}=t;if(e&&!n.has(e.id)){let n=t.bandwidth===0,i=e.codecs?e.codecs.split(`,`).map(e=>e.trim().toLowerCase()).filter(e=>!ua.some(t=>e.startsWith(t))).join(`,`):void 0,{frameRate:a,hdr:o}=e;r(e,`main`,Cr({bitrate:t.bandwidth,codecs:n?void 0:i,width:n?void 0:e.width,height:n?void 0:e.height,frameRate:n?void 0:a,videoRange:n?void 0:o}))}if(o&&!n.has(o.id)){var i,a;let n=!e,s=(i=(a=o.label)==null?o.originalId:a)==null?void 0:i,c=Cr({bitrate:n?t.bandwidth:0,codecs:n?void 0:o.codecs,language:n?void 0:o.language,channels:n?void 0:o.channelsCount,name:n?void 0:s});r(o,n?`main`:`secondary`,c)}}}hookSegmentIndex(e){let{segmentManager:t}=this;if(!t)return;let n=(n,r=!1)=>{let i=null,a,o,s=n.get,c=l=>{var u;let d=s.call(n,l);if(d===i||!((u=this.player)!=null&&u.isLive())&&e.isSegmentIndexAlreadyRead)return d;i=d,n.get=s;try{let r=ma(n,this.shaka);if(!r)throw Error(`Segment references not found`);let i=r[0],s=r[r.length-1];if(i===a&&s===o)return d;a=i,o=s,t.updateStreamSegments(e,r),e.isSegmentIndexAlreadyRead=!0,this.debug(`Stream ${e.id} is updated`)}catch(e){}finally{var f;(!e.isSegmentIndexAlreadyRead||(f=this.player)!=null&&f.isLive()||!r)&&(n.get=c)}return d};n.get=c};if(e.segmentIndex){n(e.segmentIndex);return}let r=e.createSegmentIndex;e.createSegmentIndex=y(function*(){let t=yield r.call(e);return e.segmentIndex&&n(e.segmentIndex,!0),t})}hookHlsStreamMediaSequenceTimeMaps(e){let t=ha(this.originalManifestParser),n,r,i=[`video`,`audio`,`text`,`image`];for(let e of t)i.every(t=>e.has(t))&&(n=e.get(`video`),r=e.get(`audio`));if(n&&r){for(let t of e){let{video:e,audio:i}=t;e&&(e.mediaSequenceTimeMap=n),i&&(i.mediaSequenceTimeMap=r)}return}let a=t.find(e=>{var t;let n=e.values().next().value;return typeof n==`object`&&(n==null||(t=n.streams)==null?void 0:t.createSegmentIndex)});if(!a)return;let o=[...a.values()];for(let e of o){var s;if(!(e==null||(s=e.stream)==null)&&s.mediaSequenceTimeMap)continue;let t=ha(e).find(e=>{var t;let[n,r]=(t=e.entries().next().value)==null?[]:t;return typeof n==`number`&&typeof r==`number`});t&&(e.stream.mediaSequenceTimeMap=t)}}},fa=class extends da{constructor(e){super(e,new e.hls.HlsParser)}},pa=class extends da{constructor(e){super(e,new e.dash.DashParser)}};function ma(e,t){for(let n in e)if(Array.isArray(e[n])&&e[n].length>0&&e[n][0]instanceof t.media.SegmentReference)return e[n];else if(typeof e[n]==`object`){let r=ma(e[n],t);if(r)return r}return null}function ha(e){return Object.keys(e).map(t=>e[t]).filter(e=>e instanceof Map)}function ga({segmentReference:e,externalId:t,runtimeId:n}){let{byteRange:r,url:i,startTime:a,endTime:o}=ba(e);return{runtimeId:n==null?va(i,r):n,externalId:t,byteRange:r,url:i,startTime:a,endTime:o}}function _a(e){let{url:t,byteRange:n}=ba(e);return va(t,n)}function va(e,t){if(!t)return e;let n=typeof t==`string`?ya(t):t;return n?`${e}|${n.start}-${n.end}`:e}function ya(e){if(!(e!=null&&e.includes(`bytes=`)))return;let t=e.split(`=`)[1].split(`-`),n=parseInt(t[0]),r=parseInt(t[1]);if(!(isNaN(n)||isNaN(r)))return{start:n,end:r}}function ba(e){var t,n;let r=e.getUris(),i=(t=r[1])==null?r[0]:t,a=e.getStartByte(),o=(n=e.getEndByte())==null?void 0:n,s=e.getStartTime(),c=e.getEndTime();return{byteRange:o===void 0?void 0:{start:a,end:o},url:i,startTime:s,endTime:c}}function xa(e){let{shakaStream:t}=e,n=t.mediaSequenceTimeMap;if(!n)return;let r=n.keys().next().value;if(r!==void 0)return r+n.size-1}var Sa=.5,Ca=class{constructor(e,t){p(this,`core`,void 0),p(this,`streamInfo`,void 0),this.core=t,this.streamInfo=e}setStream(e,t,n){this.core.addStreamIfNoneExists({runtimeId:e.id.toString(),type:t,index:n,shakaStream:e}),e.segmentIndex&&this.updateStreamSegments(e)}updateStreamSegments(e,t){let n=this.core.getStream(e.id.toString());if(!n)return;let{segmentIndex:r}=n.shakaStream;if(!t&&r)try{t=[...r].filter(e=>!!e)}catch(e){return}t&&(this.streamInfo.protocol===`hls`?this.processHlsSegmentReferences(n,t):this.processDashSegmentReferences(n,t))}processDashSegmentReferences(e,t){let n=new Set(e.segments.keys()),r=[];for(let i of t){let t=Math.trunc(i.getStartTime()/Sa),a=_a(i);if(!e.segments.has(a)){let e=ga({segmentReference:i,externalId:t,runtimeId:a});r.push(e)}n.delete(a)}!r.length&&!n.size||this.core.updateStream(e.runtimeId,r,n.values())}processHlsSegmentReferences(e,t){let{segments:n}=e,r=xa(e),i=[];if(n.size===0){let n=r===void 0?0:r-t.length+1;for(let[e,r]of t.entries()){let t=ga({segmentReference:r,externalId:n+e});i.push(t)}this.core.updateStream(e.runtimeId,i);return}if(r===void 0)return;let a=r;for(let e of wa(t)){let t=_a(e);if(n.has(t))break;let r=ga({runtimeId:t,segmentReference:e,externalId:a});i.push(r),a--}i.reverse();let o=[],s=i.length;for(let e of Ta(n,s))o.push(e.runtimeId);!i.length&&!o.length||this.core.updateStream(e.runtimeId,i,o)}};function*wa(e){for(let t=e.length-1;t>=0;t--)yield e[t]}function*Ta(e,t){let n=0;for(let r of e.values()){if(n>=t)break;yield r,n++}}var Ea=class{constructor(e,t,n){p(this,`shaka`,void 0),p(this,`core`,void 0),p(this,`streamInfo`,void 0),p(this,`loadArgs`,void 0),this.shaka=e,this.core=t,this.streamInfo=n}defaultLoad(){return this.shaka.net.HttpFetchPlugin.parse(...this.loadArgs)}load(...e){this.loadArgs=e;let{RequestType:t}=this.shaka.net.NetworkingEngine,[n,r,i]=e;if(i===t.SEGMENT)return this.loadSegment(n,r);let a=this.defaultLoad();return i===t.MANIFEST&&this.handleManifestLoading(a.promise).catch(()=>void 0),a}handleManifestLoading(e){var t=this;return y(function*(){if(!t.streamInfo.manifestResponseUrl){let n=yield e;t.setManifestResponseUrl(n.uri)}})()}loadSegment(e,t){var n=this;let r=t.headers.Range,i=va(e,r),a=this.core.isSegmentLoadable(i);if(!this.core.hasSegment(i)||!a)return this.defaultLoad();let o=function(){var r=y(function*(){let{request:r,callbacks:a}=Oa();n.core.loadSegment(i,a);try{let{data:n,bandwidth:i}=yield r;return{data:n,headers:{},originalRequest:t,uri:e,originalUri:e,timeMs:Da(i,n.byteLength)}}catch(e){if(e instanceof se){let{Error:t}=n.shaka.util;if(e.type===`aborted`)throw new t(t.Severity.RECOVERABLE,t.Category.NETWORK,n.shaka.util.Error.Code.OPERATION_ABORTED)}throw e}});return function(){return r.apply(this,arguments)}}();return new this.shaka.util.AbortableOperation(o(),()=>(this.core.abortSegmentLoading(i),Promise.resolve()))}setManifestResponseUrl(e){this.streamInfo.manifestResponseUrl=e,this.core.setManifestResponseUrl(e)}};function Da(e,t){let n=t*8;return e>0?Math.round(n/e)*1e3:0}function Oa(){let e,t;return{request:new Promise((n,r)=>{e=n,t=r}),callbacks:{onSuccess:e,onError:t}}}var ka=25,Aa=class e{constructor(e,t=window.shaka){p(this,`player`,void 0),p(this,`shaka`,void 0),p(this,`streamInfo`,{}),p(this,`core`,void 0),p(this,`segmentManager`,void 0),p(this,`requestFilter`,void 0),p(this,`updatePlayerEventHandlers`,e=>{let{player:t}=this;if(!t)return;let n=t.getNetworkingEngine();if(n)if(e===`register`){let e={player:t,shaka:this.shaka,core:this.core,streamInfo:this.streamInfo,segmentManager:this.segmentManager};this.requestFilter=(t,n)=>{n.p2pml=e},n.p2pml=e,n.registerRequestFilter(this.requestFilter)}else n.p2pml=void 0,this.requestFilter&&n.unregisterRequestFilter(this.requestFilter);let r=e===`register`?`addEventListener`:`removeEventListener`;t[r](`loaded`,this.handlePlayerLoaded),t[r](`loading`,this.destroyCurrentStreamContext),t[r](`unloading`,this.handlePlayerUnloading),t[r](`adaptation`,this.onVariantChanged),t[r](`variantchanged`,this.onVariantChanged)}),p(this,`onVariantChanged`,()=>{if(!this.player)return;let e=this.player.getVariantTracks().find(e=>e.active);e&&this.core.setActiveLevelBitrate(e.bandwidth)}),p(this,`handlePlayerLoaded`,()=>{this.player&&(this.core.setIsLive(this.player.isLive()),this.updateMediaElementEventHandlers(`register`))}),p(this,`handlePlayerUnloading`,()=>{this.destroyCurrentStreamContext(),this.updateMediaElementEventHandlers(`unregister`)}),p(this,`destroyCurrentStreamContext`,()=>{this.streamInfo.protocol=void 0,this.streamInfo.manifestResponseUrl=void 0,this.core.destroy()}),p(this,`updateMediaElementEventHandlers`,e=>{var t;let n=(t=this.player)==null?void 0:t.getMediaElement();if(!n)return;let r=e===`register`?`addEventListener`:`removeEventListener`;n[r](`timeupdate`,this.handlePlaybackUpdate),n[r](`ratechange`,this.handlePlaybackUpdate),n[r](`seeking`,this.handlePlaybackUpdate)}),p(this,`handlePlaybackUpdate`,e=>{let t=e.target;this.core.updatePlayback(t.currentTime,t.playbackRate)}),ja(t),this.shaka=t,this.core=new la(e==null?void 0:e.core),this.segmentManager=new Ca(this.streamInfo,this.core)}bindShakaPlayer(e){if(this.player===e)return;this.player&&this.destroy(),this.player=e,this.player.configure(`manifest.defaultPresentationDelay`,ka),this.player.configure(`manifest.dash.ignoreSuggestedPresentationDelay`,!0);let t=/\d+/.exec(this.shaka.Player.version);parseInt(t?t[0]:`0`,10)>=5?this.player.configure(`streaming.preferNativeHls`,!1):this.player.configure(`streaming.useNativeHlsOnSafari`,!1),this.updatePlayerEventHandlers(`register`)}applyDynamicConfig(e){e.core&&this.core.applyDynamicConfig(e.core)}getConfig(){return{core:this.core.getConfig()}}addEventListener(e,t){this.core.addEventListener(e,t)}removeEventListener(e,t){this.core.removeEventListener(e,t)}destroy(){this.destroyCurrentStreamContext(),this.updatePlayerEventHandlers(`unregister`),this.updateMediaElementEventHandlers(`unregister`),this.player=void 0}static registerManifestParsers(e){let t=()=>new fa(e),n=()=>new pa(e),r=e.media.ManifestParser;r.registerParserByMime(`application/dash+xml`,n),r.registerParserByMime(`application/x-mpegurl`,t),r.registerParserByMime(`application/vnd.apple.mpegurl`,t)}static unregisterManifestParsers(e){let t=e.media.ManifestParser;t.unregisterParserByMime(`mpd`),t.unregisterParserByMime(`application/dash+xml`),t.unregisterParserByMime(`m3u8`),t.unregisterParserByMime(`application/x-mpegurl`),t.unregisterParserByMime(`application/vnd.apple.mpegurl`)}static registerNetworkingEngineSchemes(e){let{NetworkingEngine:t}=e.net,n=(...t)=>{let{p2pml:n}=t[1];return n?new Ea(n.shaka,n.core,n.streamInfo).load(...t):e.net.HttpFetchPlugin.parse(...t)};t.registerScheme(`http`,n),t.registerScheme(`https`,n),t.registerScheme(`data`,n)}static unregisterNetworkingEngineSchemes(e){let{NetworkingEngine:t}=e.net;t.unregisterScheme(`http`),t.unregisterScheme(`https`),t.unregisterScheme(`data`)}static registerPlugins(t=window.shaka){ja(t),e.registerManifestParsers(t),e.registerNetworkingEngineSchemes(t)}static unregisterPlugins(t=window.shaka){ja(t),e.unregisterManifestParsers(t),e.unregisterNetworkingEngineSchemes(t)}};function ja(e){if(!e)throw Error(`shaka namespace is not defined in global scope and not passed as an argument to Shaka P2P engine constructor`)}return e.Core=la,e.ShakaP2PEngine=Aa,e})({});
//# sourceMappingURL=p2p-media-loader-shaka.iife.min.js.map