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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ this.p2pml=this.p2pml||{},this.p2pml.dashjs=(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||!o.call(e,`default`)?n(i,`default`,{value:e,enumerable:!0}):i,e)),d=u(s(((e,t)=>{t.exports=typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:{}}))()),f=`https://example.com`,p=function(e,t){if(/^[a-z]+:/i.test(t))return t;/^data:/.test(e)&&(e=d.default.location&&d.default.location.href||``);var n=/^\/\//.test(e),r=!d.default.location&&!/\/\//i.test(e);e=new d.default.URL(e,d.default.location||f);var i=new URL(t,e);return r?i.href.slice(f.length):n?i.href.slice(i.protocol.length):i.href},m=function(e,t,n){t.forEach(function(t){for(var r in e.mediaGroups[t])for(var i in e.mediaGroups[t][r]){var a=e.mediaGroups[t][r][i];n(a,t,r,i)}})},ee=function(e){return d.default.atob?d.default.atob(e):Buffer.from(e,`base64`).toString(`binary`)};function h(e){for(var t=ee(e),n=new Uint8Array(t.length),r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}var{DOMParser:te}=window,ne=e=>!!e&&typeof e==`object`,g=(...e)=>e.reduce((e,t)=>(typeof t==`object`&&Object.keys(t).forEach(n=>{e[n]=Array.isArray(e[n])&&Array.isArray(t[n])?e[n].concat(t[n]):ne(e[n])&&ne(t[n])?g(e[n],t[n]):t[n]}),e),{}),re=e=>Object.keys(e).map(t=>e[t]),ie=(e,t)=>{let n=[];for(let r=e;r<t;r++)n.push(r);return n},ae=e=>e.reduce((e,t)=>e.concat(t),[]),oe=e=>{if(!e.length)return[];let t=[];for(let n=0;n<e.length;n++)t.push(e[n]);return t},se=(e,t)=>e.reduce((e,n,r)=>(n[t]&&e.push(r),e),[]),ce=(e,t)=>re(e.reduce((e,n)=>(n.forEach(n=>{e[t(n)]=n}),e),{})),le={INVALID_NUMBER_OF_PERIOD:`INVALID_NUMBER_OF_PERIOD`,INVALID_NUMBER_OF_CONTENT_STEERING:`INVALID_NUMBER_OF_CONTENT_STEERING`,DASH_EMPTY_MANIFEST:`DASH_EMPTY_MANIFEST`,DASH_INVALID_XML:`DASH_INVALID_XML`,NO_BASE_URL:`NO_BASE_URL`,MISSING_SEGMENT_INFORMATION:`MISSING_SEGMENT_INFORMATION`,SEGMENT_TIME_UNSPECIFIED:`SEGMENT_TIME_UNSPECIFIED`,UNSUPPORTED_UTC_TIMING_SCHEME:`UNSUPPORTED_UTC_TIMING_SCHEME`},ue=({baseUrl:e=``,source:t=``,range:n=``,indexRange:r=``})=>{let i={uri:t,resolvedUri:p(e||``,t)};if(n||r){let e=(n||r).split(`-`),t=d.default.BigInt?d.default.BigInt(e[0]):parseInt(e[0],10),a=d.default.BigInt?d.default.BigInt(e[1]):parseInt(e[1],10);t<9007199254740991&&typeof t==`bigint`&&(t=Number(t)),a<9007199254740991&&typeof a==`bigint`&&(a=Number(a));let o;o=typeof a==`bigint`||typeof t==`bigint`?d.default.BigInt(a)-d.default.BigInt(t)+d.default.BigInt(1):a-t+1,typeof o==`bigint`&&o<9007199254740991&&(o=Number(o)),i.byterange={length:o,offset:t}}return i},de=e=>{let t;return t=typeof e.offset==`bigint`||typeof e.length==`bigint`?d.default.BigInt(e.offset)+d.default.BigInt(e.length)-d.default.BigInt(1):e.offset+e.length-1,`${e.offset}-${t}`},fe=e=>(e&&typeof e!=`number`&&(e=parseInt(e,10)),isNaN(e)?null:e),pe={static(e){let{duration:t,timescale:n=1,sourceDuration:r,periodDuration:i}=e,a=fe(e.endNumber),o=t/n;return typeof a==`number`?{start:0,end:a}:typeof i==`number`?{start:0,end:i/o}:{start:0,end:r/o}},dynamic(e){let{NOW:t,clientOffset:n,availabilityStartTime:r,timescale:i=1,duration:a,periodStart:o=0,minimumUpdatePeriod:s=0,timeShiftBufferDepth:c=1/0}=e,l=fe(e.endNumber),u=(t+n)/1e3,d=r+o,f=u+s-d,p=Math.ceil(f*i/a),m=Math.floor((u-d-c)*i/a),ee=Math.floor((u-d)*i/a);return{start:Math.max(0,m),end:typeof l==`number`?l:Math.min(p,ee)}}},me=e=>t=>{let{duration:n,timescale:r=1,periodStart:i,startNumber:a=1}=e;return{number:a+t,duration:n/r,timeline:i,time:t*n}},he=e=>{let{type:t,duration:n,timescale:r=1,periodDuration:i,sourceDuration:a}=e,{start:o,end:s}=pe[t](e),c=ie(o,s).map(me(e));if(t===`static`){let e=c.length-1,t=typeof i==`number`?i:a;c[e].duration=t-n/r*e}return c},ge=e=>{let{baseUrl:t,initialization:n={},sourceDuration:r,indexRange:i=``,periodStart:a,presentationTime:o,number:s=0,duration:c}=e;if(!t)throw Error(le.NO_BASE_URL);let l=ue({baseUrl:t,source:n.sourceURL,range:n.range}),u=ue({baseUrl:t,source:t,indexRange:i});if(u.map=l,c){let t=he(e);t.length&&(u.duration=t[0].duration,u.timeline=t[0].timeline)}else r&&(u.duration=r,u.timeline=a);return u.presentationTime=o||a,u.number=s,[u]},_e=(e,t,n)=>{let r=e.sidx.map?e.sidx.map:null,i=e.sidx.duration,a=e.timeline||0,o=e.sidx.byterange,s=o.offset+o.length,c=t.timescale,l=t.references.filter(e=>e.referenceType!==1),u=[],f=e.endList?`static`:`dynamic`,p=e.sidx.timeline,m=p,ee=e.mediaSequence||0,h;h=typeof t.firstOffset==`bigint`?d.default.BigInt(s)+t.firstOffset:s+t.firstOffset;for(let e=0;e<l.length;e++){let o=t.references[e],s=o.referencedSize,l=o.subsegmentDuration,te;te=typeof h==`bigint`?h+d.default.BigInt(s)-d.default.BigInt(1):h+s-1;let ne=`${h}-${te}`,g=ge({baseUrl:n,timescale:c,timeline:a,periodStart:p,presentationTime:m,number:ee,duration:l,sourceDuration:i,indexRange:ne,type:f})[0];r&&(g.map=r),u.push(g),h+=typeof h==`bigint`?d.default.BigInt(s):s,m+=l/c,ee++}return e.segments=u,e},ve=[`AUDIO`,`SUBTITLES`],ye=1/60,be=e=>ce(e,({timeline:e})=>e).sort((e,t)=>e.timeline>t.timeline?1:-1),xe=(e,t)=>{for(let n=0;n<e.length;n++)if(e[n].attributes.NAME===t)return e[n];return null},Se=e=>{let t=[];return m(e,ve,(e,n,r,i)=>{t=t.concat(e.playlists||[])}),t},Ce=({playlist:e,mediaSequence:t})=>{e.mediaSequence=t,e.segments.forEach((t,n)=>{t.number=e.mediaSequence+n})},we=({oldPlaylists:e,newPlaylists:t,timelineStarts:n})=>{t.forEach(t=>{t.discontinuitySequence=n.findIndex(function({timeline:e}){return e===t.timeline});let r=xe(e,t.attributes.NAME);if(!r||t.sidx)return;let i=t.segments[0],a=r.segments.findIndex(function(e){return Math.abs(e.presentationTime-i.presentationTime)<ye});if(a===-1){Ce({playlist:t,mediaSequence:r.mediaSequence+r.segments.length}),t.segments[0].discontinuity=!0,t.discontinuityStarts.unshift(0),(!r.segments.length&&t.timeline>r.timeline||r.segments.length&&t.timeline>r.segments[r.segments.length-1].timeline)&&t.discontinuitySequence--;return}r.segments[a].discontinuity&&!i.discontinuity&&(i.discontinuity=!0,t.discontinuityStarts.unshift(0),t.discontinuitySequence--),Ce({playlist:t,mediaSequence:r.segments[a].number})})},Te=({oldManifest:e,newManifest:t})=>{let n=e.playlists.concat(Se(e)),r=t.playlists.concat(Se(t));return t.timelineStarts=be([e.timelineStarts,t.timelineStarts]),we({oldPlaylists:n,newPlaylists:r,timelineStarts:t.timelineStarts}),t},Ee=e=>e&&e.uri+`-`+de(e.byterange),De=e=>{let t=e.reduce(function(e,t){return e[t.attributes.baseUrl]||(e[t.attributes.baseUrl]=[]),e[t.attributes.baseUrl].push(t),e},{}),n=[];return Object.values(t).forEach(e=>{let t=re(e.reduce((e,t)=>{let n=t.attributes.id+(t.attributes.lang||``);return e[n]?(t.segments&&(t.segments[0]&&(t.segments[0].discontinuity=!0),e[n].segments.push(...t.segments)),t.attributes.contentProtection&&(e[n].attributes.contentProtection=t.attributes.contentProtection)):(e[n]=t,e[n].attributes.timelineStarts=[]),e[n].attributes.timelineStarts.push({start:t.attributes.periodStart,timeline:t.attributes.periodStart}),e},{}));n=n.concat(t)}),n.map(e=>(e.discontinuityStarts=se(e.segments||[],`discontinuity`),e))},Oe=(e,t)=>{let n=Ee(e.sidx),r=n&&t[n]&&t[n].sidx;return r&&_e(e,r,e.sidx.resolvedUri),e},ke=(e,t={})=>{if(!Object.keys(t).length)return e;for(let n in e)e[n]=Oe(e[n],t);return e},Ae=({attributes:e,segments:t,sidx:n,mediaSequence:r,discontinuitySequence:i,discontinuityStarts:a},o)=>{let s={attributes:{NAME:e.id,BANDWIDTH:e.bandwidth,CODECS:e.codecs,"PROGRAM-ID":1},uri:``,endList:e.type===`static`,timeline:e.periodStart,resolvedUri:e.baseUrl||``,targetDuration:e.duration,discontinuitySequence:i,discontinuityStarts:a,timelineStarts:e.timelineStarts,mediaSequence:r,segments:t};return e.contentProtection&&(s.contentProtection=e.contentProtection),e.serviceLocation&&(s.attributes.serviceLocation=e.serviceLocation),n&&(s.sidx=n),o&&(s.attributes.AUDIO=`audio`,s.attributes.SUBTITLES=`subs`),s},je=({attributes:e,segments:t,mediaSequence:n,discontinuityStarts:r,discontinuitySequence:i})=>{t===void 0&&(t=[{uri:e.baseUrl,timeline:e.periodStart,resolvedUri:e.baseUrl||``,duration:e.sourceDuration,number:0}],e.duration=e.sourceDuration);let a={NAME:e.id,BANDWIDTH:e.bandwidth,"PROGRAM-ID":1};e.codecs&&(a.CODECS=e.codecs);let o={attributes:a,uri:``,endList:e.type===`static`,timeline:e.periodStart,resolvedUri:e.baseUrl||``,targetDuration:e.duration,timelineStarts:e.timelineStarts,discontinuityStarts:r,discontinuitySequence:i,mediaSequence:n,segments:t};return e.serviceLocation&&(o.attributes.serviceLocation=e.serviceLocation),o},Me=(e,t={},n=!1)=>{let r,i=e.reduce((e,i)=>{let a=i.attributes.role&&i.attributes.role.value||``,o=i.attributes.lang||``,s=i.attributes.label||`main`;if(o&&!i.attributes.label){let e=a?` (${a})`:``;s=`${i.attributes.lang}${e}`}e[s]||(e[s]={language:o,autoselect:!0,default:a===`main`,playlists:[],uri:``});let c=Oe(Ae(i,n),t);return e[s].playlists.push(c),r===void 0&&a===`main`&&(r=i,r.default=!0),e},{});if(!r){let e=Object.keys(i)[0];i[e].default=!0}return i},Ne=(e,t={})=>e.reduce((e,n)=>{let r=n.attributes.label||n.attributes.lang||`text`,i=n.attributes.lang||`und`;return e[r]||(e[r]={language:i,default:!1,autoselect:!1,playlists:[],uri:``}),e[r].playlists.push(Oe(je(n),t)),e},{}),Pe=e=>e.reduce((e,t)=>(t&&t.forEach(t=>{let{channel:n,language:r}=t;e[r]={autoselect:!1,default:!1,instreamId:n,language:r},t.hasOwnProperty(`aspectRatio`)&&(e[r].aspectRatio=t.aspectRatio),t.hasOwnProperty(`easyReader`)&&(e[r].easyReader=t.easyReader),t.hasOwnProperty(`3D`)&&(e[r][`3D`]=t[`3D`])}),e),{}),Fe=({attributes:e,segments:t,sidx:n,discontinuityStarts:r})=>{let i={attributes:{NAME:e.id,AUDIO:`audio`,SUBTITLES:`subs`,RESOLUTION:{width:e.width,height:e.height},CODECS:e.codecs,BANDWIDTH:e.bandwidth,"PROGRAM-ID":1},uri:``,endList:e.type===`static`,timeline:e.periodStart,resolvedUri:e.baseUrl||``,targetDuration:e.duration,discontinuityStarts:r,timelineStarts:e.timelineStarts,segments:t};return e.frameRate&&(i.attributes[`FRAME-RATE`]=e.frameRate),e.qualityRanking!==void 0&&(i.attributes.SCORE=1/(e.qualityRanking+1)),e.contentProtection&&(i.contentProtection=e.contentProtection),e.serviceLocation&&(i.attributes.serviceLocation=e.serviceLocation),n&&(i.sidx=n),i},Ie=({attributes:e})=>e.mimeType===`video/mp4`||e.mimeType===`video/webm`||e.contentType===`video`,Le=({attributes:e})=>e.mimeType===`audio/mp4`||e.mimeType===`audio/webm`||e.contentType===`audio`,Re=({attributes:e})=>e.mimeType===`text/vtt`||e.contentType===`text`,ze=(e,t)=>{e.forEach(e=>{e.mediaSequence=0,e.discontinuitySequence=t.findIndex(function({timeline:t}){return t===e.timeline}),e.segments&&e.segments.forEach((e,t)=>{e.number=t})})},Be=e=>e?Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(r.playlists)},[]):[],Ve=({dashPlaylists:e,locations:t,contentSteering:n,sidxMapping:r={},previousManifest:i,eventStream:a})=>{if(!e.length)return{};let{sourceDuration:o,type:s,suggestedPresentationDelay:c,minimumUpdatePeriod:l}=e[0].attributes,u=De(e.filter(Ie)).map(Fe),d=De(e.filter(Le)),f=De(e.filter(Re)),p=e.map(e=>e.attributes.captionServices).filter(Boolean),m={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:``,duration:o,playlists:ke(u,r)};l>=0&&(m.minimumUpdatePeriod=l*1e3),t&&(m.locations=t),n&&(m.contentSteering=n),s===`dynamic`&&(m.suggestedPresentationDelay=c),a&&a.length>0&&(m.eventStream=a);let ee=m.playlists.length===0,h=d.length?Me(d,r,ee):null,te=f.length?Ne(f,r):null,ne=u.concat(Be(h),Be(te));return m.timelineStarts=be(ne.map(({timelineStarts:e})=>e)),ze(ne,m.timelineStarts),h&&(m.mediaGroups.AUDIO.audio=h),te&&(m.mediaGroups.SUBTITLES.subs=te),p.length&&(m.mediaGroups[`CLOSED-CAPTIONS`].cc=Pe(p)),i?Te({oldManifest:i,newManifest:m}):m},He=(e,t,n)=>{let{NOW:r,clientOffset:i,availabilityStartTime:a,timescale:o=1,periodStart:s=0,minimumUpdatePeriod:c=0}=e,l=(r+i)/1e3,u=a+s,d=l+c-u;return Math.ceil((d*o-t)/n)},Ue=(e,t)=>{let{type:n,minimumUpdatePeriod:r=0,media:i=``,sourceDuration:a,timescale:o=1,startNumber:s=1,periodStart:c}=e,l=[],u=-1;for(let d=0;d<t.length;d++){let f=t[d],p=f.d,m=f.r||0,ee=f.t||0;u<0&&(u=ee),ee&&ee>u&&(u=ee);let h;if(m<0){let s=d+1;h=s===t.length?n===`dynamic`&&r>0&&i.indexOf(`$Number$`)>0?He(e,u,p):(a*o-u)/p:(t[s].t-u)/p}else h=m+1;let te=s+l.length+h,ne=s+l.length;for(;ne<te;)l.push({number:ne,duration:p/o,time:u,timeline:c}),u+=p,ne++}return l},We=/\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g,Ge=e=>(t,n,r,i)=>{if(t===`$$`)return`$`;if(e[n]===void 0)return t;let a=``+e[n];return n===`RepresentationID`||(i=r?parseInt(i,10):1,a.length>=i)?a:`${Array(i-a.length+1).join(`0`)}${a}`},Ke=(e,t)=>e.replace(We,Ge(t)),qe=(e,t)=>!e.duration&&!t?[{number:e.startNumber||1,duration:e.sourceDuration,time:0,timeline:e.periodStart}]:e.duration?he(e):Ue(e,t),Je=(e,t)=>{let n={RepresentationID:e.id,Bandwidth:e.bandwidth||0},{initialization:r={sourceURL:``,range:``}}=e,i=ue({baseUrl:e.baseUrl,source:Ke(r.sourceURL,n),range:r.range});return qe(e,t).map(t=>{n.Number=t.number,n.Time=t.time;let r=Ke(e.media||``,n),a=e.timescale||1,o=e.presentationTimeOffset||0,s=e.periodStart+(t.time-o)/a;return{uri:r,timeline:t.timeline,duration:t.duration,resolvedUri:p(e.baseUrl||``,r),map:i,number:t.number,presentationTime:s}})},Ye=(e,t)=>{let{baseUrl:n,initialization:r={}}=e,i=ue({baseUrl:n,source:r.sourceURL,range:r.range}),a=ue({baseUrl:n,source:t.media,range:t.mediaRange});return a.map=i,a},Xe=(e,t)=>{let{duration:n,segmentUrls:r=[],periodStart:i}=e;if(!n&&!t||n&&t)throw Error(le.SEGMENT_TIME_UNSPECIFIED);let a=r.map(t=>Ye(e,t)),o;return n&&(o=he(e)),t&&(o=Ue(e,t)),o.map((t,n)=>{if(a[n]){let r=a[n],o=e.timescale||1,s=e.presentationTimeOffset||0;return r.timeline=t.timeline,r.duration=t.duration,r.number=t.number,r.presentationTime=i+(t.time-s)/o,r}}).filter(e=>e)},Ze=({attributes:e,segmentInfo:t})=>{let n,r;t.template?(r=Je,n=g(e,t.template)):t.base?(r=ge,n=g(e,t.base)):t.list&&(r=Xe,n=g(e,t.list));let i={attributes:e};if(!r)return i;let a=r(n,t.segmentTimeline);if(n.duration){let{duration:e,timescale:t=1}=n;n.duration=e/t}else a.length?n.duration=a.reduce((e,t)=>Math.max(e,Math.ceil(t.duration)),0):n.duration=0;return i.attributes=n,i.segments=a,t.base&&n.indexRange&&(i.sidx=a[0],i.segments=[]),i},Qe=e=>e.map(Ze),_=(e,t)=>oe(e.childNodes).filter(({tagName:e})=>e===t),$e=e=>e.textContent.trim(),et=e=>parseFloat(e.split(`/`).reduce((e,t)=>e/t)),tt=e=>{let t=/P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/.exec(e);if(!t)return 0;let[n,r,i,a,o,s]=t.slice(1);return parseFloat(n||0)*31536e3+parseFloat(r||0)*2592e3+parseFloat(i||0)*86400+parseFloat(a||0)*3600+parseFloat(o||0)*60+parseFloat(s||0)},nt=e=>(/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(e)&&(e+=`Z`),Date.parse(e)),rt={mediaPresentationDuration(e){return tt(e)},availabilityStartTime(e){return nt(e)/1e3},minimumUpdatePeriod(e){return tt(e)},suggestedPresentationDelay(e){return tt(e)},type(e){return e},timeShiftBufferDepth(e){return tt(e)},start(e){return tt(e)},width(e){return parseInt(e,10)},height(e){return parseInt(e,10)},bandwidth(e){return parseInt(e,10)},frameRate(e){return et(e)},startNumber(e){return parseInt(e,10)},timescale(e){return parseInt(e,10)},presentationTimeOffset(e){return parseInt(e,10)},duration(e){let t=parseInt(e,10);return isNaN(t)?tt(e):t},d(e){return parseInt(e,10)},t(e){return parseInt(e,10)},r(e){return parseInt(e,10)},presentationTime(e){return parseInt(e,10)},qualityRanking(e){return parseInt(e,10)},qualityranking(e){return parseInt(e,10)},DEFAULT(e){return e}},it={qualityranking:`qualityRanking`},v=e=>e&&e.attributes?oe(e.attributes).reduce((e,t)=>{let n=rt[t.name]||rt.DEFAULT,r=it[t.name]||t.name;return e[r]=n(t.value),e},{}):{},at={"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":`org.w3.clearkey`,"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":`com.widevine.alpha`,"urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":`com.microsoft.playready`,"urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb":`com.adobe.primetime`,"urn:mpeg:dash:mp4protection:2011":`mp4protection`},ot=(e,t)=>t.length?ae(e.map(function(e){return t.map(function(t){let n=$e(t),r=p(e.baseUrl,n),i=g(v(t),{baseUrl:r});return r!==n&&!i.serviceLocation&&e.serviceLocation&&(i.serviceLocation=e.serviceLocation),i})})):e,st=e=>{let t=_(e,`SegmentTemplate`)[0],n=_(e,`SegmentList`)[0],r=n&&_(n,`SegmentURL`).map(e=>g({tag:`SegmentURL`},v(e))),i=_(e,`SegmentBase`)[0],a=n||t,o=a&&_(a,`SegmentTimeline`)[0],s=n||i||t,c=s&&_(s,`Initialization`)[0],l=t&&v(t);l&&c?l.initialization=c&&v(c):l&&l.initialization&&(l.initialization={sourceURL:l.initialization});let u={template:l,segmentTimeline:o&&_(o,`S`).map(e=>v(e)),list:n&&g(v(n),{segmentUrls:r,initialization:v(c)}),base:i&&g(v(i),{initialization:v(c)})};return Object.keys(u).forEach(e=>{u[e]||delete u[e]}),u},ct=(e,t,n)=>r=>{let i=ot(t,_(r,`BaseURL`)),a=g(e,v(r)),o=st(r);return i.map(e=>({segmentInfo:g(n,o),attributes:g(a,e)}))},lt=e=>e.reduce((e,t)=>{let n=v(t);n.schemeIdUri&&(n.schemeIdUri=n.schemeIdUri.toLowerCase());let r=at[n.schemeIdUri];if(r){e[r]={attributes:n};let i=_(t,`cenc:pssh`)[0];if(i){let t=$e(i);e[r].pssh=t&&h(t)}}return e},{}),ut=e=>{if(e.schemeIdUri===`urn:scte:dash:cc:cea-608:2015`)return(typeof e.value==`string`?e.value.split(`;`):[]).map(e=>{let t,n;return n=e,/^CC\d=/.test(e)?[t,n]=e.split(`=`):/^CC\d$/.test(e)&&(t=e),{channel:t,language:n}});if(e.schemeIdUri===`urn:scte:dash:cc:cea-708:2015`)return(typeof e.value==`string`?e.value.split(`;`):[]).map(e=>{let t={channel:void 0,language:void 0,aspectRatio:1,easyReader:0,"3D":0};if(/=/.test(e)){let[n,r=``]=e.split(`=`);t.channel=n,t.language=e,r.split(`,`).forEach(e=>{let[n,r]=e.split(`:`);n===`lang`?t.language=r:n===`er`?t.easyReader=Number(r):n===`war`?t.aspectRatio=Number(r):n===`3D`&&(t[`3D`]=Number(r))})}else t.language=e;return t.channel&&(t.channel=`SERVICE`+t.channel),t})},dt=e=>ae(_(e.node,`EventStream`).map(t=>{let n=v(t),r=n.schemeIdUri;return _(t,`Event`).map(t=>{let i=v(t),a=i.presentationTime||0,o=n.timescale||1,s=i.duration||0,c=a/o+e.attributes.start;return{schemeIdUri:r,value:n.value,id:i.id,start:c,end:c+s/o,messageData:$e(t)||i.messageData,contentEncoding:n.contentEncoding,presentationTimeOffset:n.presentationTimeOffset||0}})})),ft=(e,t,n)=>r=>{let i=v(r),a=ot(t,_(r,`BaseURL`)),o=_(r,`Role`)[0],s=g(e,i,{role:v(o)}),c=_(r,`Accessibility`)[0],l=ut(v(c));l&&(s=g(s,{captionServices:l}));let u=_(r,`Label`)[0];if(u&&u.childNodes.length){let e=u.childNodes[0].nodeValue.trim();s=g(s,{label:e})}let d=lt(_(r,`ContentProtection`));Object.keys(d).length&&(s=g(s,{contentProtection:d}));let f=st(r),p=_(r,`Representation`),m=g(n,f);return ae(p.map(ct(s,a,m)))},pt=(e,t)=>(n,r)=>{let i=ot(t,_(n.node,`BaseURL`)),a=g(e,{periodStart:n.attributes.start});typeof n.attributes.duration==`number`&&(a.periodDuration=n.attributes.duration);let o=_(n.node,`AdaptationSet`),s=st(n.node);return ae(o.map(ft(a,i,s)))},mt=(e,t)=>{if(e.length>1&&t({type:`warn`,message:`The MPD manifest should contain no more than one ContentSteering tag`}),!e.length)return null;let n=g({serverURL:$e(e[0])},v(e[0]));return n.queryBeforeStart=n.queryBeforeStart===`true`,n},ht=({attributes:e,priorPeriodAttributes:t,mpdType:n})=>typeof e.start==`number`?e.start:t&&typeof t.start==`number`&&typeof t.duration==`number`?t.start+t.duration:!t&&n===`static`?0:null,gt=(e,t={})=>{let{manifestUri:n=``,NOW:r=Date.now(),clientOffset:i=0,eventHandler:a=function(){}}=t,o=_(e,`Period`);if(!o.length)throw Error(le.INVALID_NUMBER_OF_PERIOD);let s=_(e,`Location`),c=v(e),l=ot([{baseUrl:n}],_(e,`BaseURL`)),u=_(e,`ContentSteering`);c.type=c.type||`static`,c.sourceDuration=c.mediaPresentationDuration||0,c.NOW=r,c.clientOffset=i,s.length&&(c.locations=s.map($e));let d=[];return o.forEach((e,t)=>{let n=v(e),r=d[t-1];n.start=ht({attributes:n,priorPeriodAttributes:r?r.attributes:null,mpdType:c.type}),d.push({node:e,attributes:n})}),{locations:c.locations,contentSteeringInfo:mt(u,a),representationInfo:ae(d.map(pt(c,l))),eventStream:ae(d.map(dt))}},_t=e=>{if(e===``)throw Error(le.DASH_EMPTY_MANIFEST);let t=new te,n,r;try{n=t.parseFromString(e,`application/xml`),r=n&&n.documentElement.tagName===`MPD`?n.documentElement:null}catch(e){}if(!r||r&&r.getElementsByTagName(`parsererror`).length>0)throw Error(le.DASH_INVALID_XML);return r},vt=(e,t={})=>{let n=gt(_t(e),t);return Ve({dashPlaylists:Qe(n.representationInfo),locations:n.locations,contentSteering:n.contentSteeringInfo,sidxMapping:t.sidxMapping,previousManifest:t.previousManifest,eventStream:n.eventStream})};function yt(){let e=Object;typeof e.values!=`function`&&(e.values=e=>Object.keys(e).map(t=>e[t]))}var bt={mp4:/^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,webm:/^(vp0?[89]|av0?1|opus|vorbis)/,ogg:/^(vp0?[89]|theora|flac|opus|vorbis)/,video:/^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,audio:/^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,text:/^(stpp.ttml.im1t)/,muxerVideo:/^(avc0?1)/,muxerAudio:/^(mp4a)/,muxerText:/a^/},xt=[`video`,`audio`,`text`],St=function(e){e===void 0&&(e=``);var t=e.split(`,`),n=[];return t.forEach(function(e){e=e.trim();var t;xt.forEach(function(r){var i=bt[r].exec(e.toLowerCase());if(!(!i||i.length<=1)){t=r;var a=e.substring(0,i[1].length),o=e.replace(a,``);n.push({type:a,details:o,mediaType:r})}}),t||n.push({type:e,details:``,mediaType:`unknown`})}),n};function Ct(e,t){if(!e)return;let n=St(e).filter(e=>e.mediaType===t).map(e=>`${e.type}${e.details}`);return n.length?n.join(`,`):void 0}function wt(e){return Ct(e,`video`)}function Tt(e){var t;let n=(t=e.bandwidth)==null?0:t,r=n===0;return{bitrate:n,codecs:r?void 0:wt(e.codecs),width:r?void 0:e.width,height:r?void 0:e.height,frameRate:r?void 0:e.frameRate,videoRange:r?void 0:e.videoRange}}function Et(e){return{bitrate:0,codecs:e.codecs,language:e.language,channels:e.channels,name:e.name}}var Dt=new Set([`CMCD`]);function Ot(e){let t=e.indexOf(`?`);if(t===-1)return e;let n=new URLSearchParams(e.slice(t+1)),r=!1;for(let e of Dt)n.has(e)&&(n.delete(e),r=!0);if(!r)return e;let i=n.toString();return i?`${e.slice(0,t)}?${i}`:e.slice(0,t)}function kt(e,t){let n=Ot(e);return t?`${n}|${t.start}-${t.end}`:n}function At(e){if(!(!e||e.length<=0))return{start:e.offset,end:e.offset+e.length-1}}function jt(e){if(!e)return;let t=/^\s*bytes=(\d+)-(\d+)\s*$/i.exec(e);if(!t)return;let n=Number(t[1]),r=Number(t[2]);return n<=r?{start:n,end:r}:void 0}yt();var Mt={protocol:`dash`,canParse(e){return/<MPD[\s>]/.test(e.slice(0,2048))},parse(e,t){var n;let r=vt(e,{manifestUri:t}),i=/<MPD[^>]*\btype\s*=\s*["']dynamic["']/.test(e.slice(0,4096)),a=Ft(e),o=[];for(let e of r.playlists)o.push(Pt(e,`main`,i,Nt));let s=(n=r.mediaGroups.AUDIO)==null?{}:n;for(let e of Object.keys(s)){let t=s[e];for(let e of Object.keys(t)){let n=t[e];for(let e of n.playlists)o.push(Pt(e,`secondary`,i,e=>Et({codecs:e.CODECS,language:n.language,channels:e.NAME?a.get(e.NAME):void 0,name:e.NAME})))}}return{protocol:`dash`,url:t,streams:o}}};function Nt(e){var t,n;return Tt({bandwidth:e.BANDWIDTH,codecs:e.CODECS,width:(t=e.RESOLUTION)==null?void 0:t.width,height:(n=e.RESOLUTION)==null?void 0:n.height,frameRate:e[`FRAME-RATE`]})}function Pt(e,t,n,r){var i,a,o,s,c;let{sidx:l}=e,u=l?{kind:`external`,url:l.resolvedUri,byteRange:(i=At(l.byterange))==null?{start:0,end:0}:i,periodStart:(a=l.timeline)==null?0:a}:{kind:`manifest`},d=e.segments.map(e=>({url:e.resolvedUri,byteRange:At(e.byterange),duration:e.duration,sequence:e.number,presentationTime:e.presentationTime})),f=(o=(s=e.segments[0])==null?void 0:s.map)==null?l==null?void 0:l.map:o;return{key:(c=e.attributes.NAME)==null?e.resolvedUri:c,type:t,properties:r(e.attributes),segments:d,initSegment:f?{url:f.resolvedUri,byteRange:At(f.byterange)}:void 0,indexSource:u,isLive:n}}function Ft(e){let t=new Map,n;try{n=_t(e)}catch(e){return t}for(let e of Array.from(n.getElementsByTagName(`AdaptationSet`))){let n=Lt(e);for(let i of Array.from(e.getElementsByTagName(`Representation`))){var r;let e=i.getAttribute(`id`),a=(r=Lt(i))==null?n:r;e&&a!==void 0&&t.set(e,a)}}return t}var It=`23003:3:audio_channel_configuration`;function Lt(e){for(let n of Array.from(e.childNodes)){var t;if(n.nodeType!==1||n.localName!==`AudioChannelConfiguration`)continue;let e=n;if(!((t=e.getAttribute(`schemeIdUri`))==null?``:t).includes(It))continue;let r=Number(e.getAttribute(`value`));if(Number.isInteger(r)&&r>0)return r}}function Rt(e){"@babel/helpers - typeof";return Rt=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},Rt(e)}function zt(e,t){if(Rt(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Rt(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Bt(e){var t=zt(e,`string`);return Rt(t)==`symbol`?t:t+``}function y(e,t,n){return(t=Bt(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var Vt=class extends Error{constructor(e,t,n){super(t),y(this,`type`,void 0),y(this,`cause`,void 0),this.type=e,this.cause=n}},Ht=class extends Vt{constructor(...e){super(...e),y(this,`name`,`PeerError`)}},Ut=class extends Vt{constructor(...e){super(...e),y(this,`name`,`PeerWarning`)}},Wt=class extends Vt{constructor(...e){super(...e),y(this,`name`,`TrackerError`)}},Gt=class extends Vt{constructor(...e){super(...e),y(this,`name`,`TrackerWarning`)}},Kt=class extends Vt{constructor(...e){super(...e),y(this,`name`,`PeerConnectError`)}},b=class extends Vt{constructor(e,t,n){super(e,t,n),y(this,`name`,`RequestError`),y(this,`timestamp`,void 0),this.timestamp=performance.now()}},qt=class extends Vt{constructor(...e){super(...e),y(this,`name`,`CoreRequestError`)}};function Jt(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function x(e,t,n){Jt(e,t),t.set(e,n)}function S(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 C(e,t){return e.get(S(e,t))}var Yt=new WeakMap,Xt=class{constructor(){y(this,`aborted`,!1),x(this,Yt,new Set)}addEventListener(e,t){C(Yt,this).add(t)}removeEventListener(e,t){C(Yt,this).delete(t)}dispatchEvent(e){this.aborted=!0;for(let e of C(Yt,this))try{e()}catch(e){}C(Yt,this).clear()}},Zt=class{constructor(){y(this,`signal`,new Xt)}abort(){this.signal.dispatchEvent(`abort`)}},Qt=typeof AbortController<`u`,$t=Qt?AbortController:Zt;function en(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 w(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?en(Object(n),!0).forEach(function(t){y(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):en(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function tn(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 T(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var a=e.apply(t,n);function o(e){tn(a,r,i,o,s,`next`,e)}function s(e){tn(a,r,i,o,s,`throw`,e)}o(void 0)})}}var nn=class{isAborted(){return this.abortController.signal.aborted}constructor(e,t,n){y(this,`request`,void 0),y(this,`httpConfig`,void 0),y(this,`abortController`,new $t),y(this,`expectedBytesLength`,void 0),y(this,`requestByteRange`,void 0),y(this,`onChunkDownloaded`,void 0),this.request=e,this.httpConfig=t,this.onChunkDownloaded=n.getEventDispatcher(`onChunkDownloaded`);let{byteRange:r}=this.request.segment;r&&(this.requestByteRange=w({},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 T(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=Qt?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 b(`http-bytes-mismatch`,`HTTP response truncated: received ${t.request.loadedBytes} of ${t.request.totalBytes} bytes`);if(t.request.loadedBytes===0)throw t.request.clearLoadedBytes(),new b(`http-bytes-mismatch`,`HTTP response carried no 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 b(`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 b(`http-bytes-mismatch`,e.statusText)):new b(`http-error`,e.statusText);let{requestByteRange:t}=this;if(t){if(e.status===200){if(this.request.segment.byteRange)throw new b(`http-unexpected-status-code`);this.request.clearLoadedBytes()}else{if(e.status!==206)throw new b(`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 b(`http-bytes-mismatch`,e.statusText);let r=e.headers.get(`Content-Range`),i=r?an(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 b(`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 b?e:new b(`http-error`,e.message);t.failWithError(n)}}},rn=/^bytes (?:(?:(\d+)|)-(?:(\d+)|)|\*)\/(?:(\d+)|\*)$/;function an(e){let t=rn.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 on=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`:``)}})),sn=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=on(),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})),E=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=sn()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}}))(),1),D=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 cn(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}function ln(e){Promise.resolve().then(e)}function un(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 dn(e){return e[Math.floor(Math.random()*e.length)]}function fn(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 pn(e){return new TextEncoder().encode(e)}function*mn(e){for(let t=e.length-1;t>=0;t--)yield e[t]}function hn(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function gn(e){return Array.isArray(e)}function _n(e){function t(e){if(hn(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}return e}return t(e)}function vn(e){if(gn(e))return e.map(e=>vn(e));if(hn(e)){let t={};for(let n of Object.keys(e))t[n]=vn(e[n]);return t}return e}function yn(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&&(e[r]=a===void 0?o===void 0?void 0:o:a)}),e}function bn(e){let{defaultConfig:t,baseConfig:n={},specificStreamConfig:r={}}=e,i=vn(w(w(w({},t),n),r)),a=Object.keys(t),o={};return a.forEach(e=>{e in i&&(o[e]=i[e])}),o}function O(e,t){Jt(e,t),t.add(e)}function k(e,t,n){return e.set(S(e,t),n),n}var xn=new TextEncoder,Sn=new TextDecoder(`utf8`),Cn=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 wn(e){if(e===0)return 1;let t=Math.floor(Math.log2(Math.abs(e)))+2;return Math.ceil(t/8)}function Tn(e){let t=e<0,n=wn(e),r=new Uint8Array(n);e=Math.abs(e);for(let t=0;t<n;t++){let i=8*(n-1-t),a=Math.floor(e/Math.pow(2,i))&255;r[t]=a}return t&&(r[0]|=128),r}function En(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 Dn(e){let t=Tn(e),n=0|t.length;return new Uint8Array([n,...t])}function On(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:En(e.subarray(1,r)),byteLength:n+1}}function kn(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 In:n;a.length||t.set(i,a),a.push(e)}let r=new In;r.push([16,t.size]);for(let[e,n]of t){let{length:t}=n,i=e+(t&255);n.unshift(Dn(i)),r.push(n.getBuffer())}return r.getBuffer()}function An(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}=On(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 jn(e){let t=xn.encode(e),{length:n}=t;if(n>4095)throw Error(`String exceeds maximum length of 4095 bytes`);let r=new In;return r.push([32|n>>8&15,n&255]),r.push(t),r.getBuffer()}function Mn(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:Sn.decode(i),byteLength:r+2}}var Nn=new WeakMap,Pn=new WeakMap,Fn=new WeakSet,In=class{constructor(){O(this,Fn),x(this,Nn,[]),x(this,Pn,0)}push(e){S(Fn,this,Ln).call(this,e,`end`)}unshift(e){S(Fn,this,Ln).call(this,e,`start`)}getBytesChunks(){return C(Nn,this)}getBuffer(){return un(C(Nn,this),C(Pn,this))}get length(){return C(Pn,this)}};function Ln(e,t){let n;n=e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):new Uint8Array([e]),k(Pn,this,C(Pn,this)+n.length),C(Nn,this)[t===`start`?`unshift`:`push`](n)}var A=4,Rn=sr(`cstr`,A),zn=sr(`cend`,A),Bn=sr(`dstr`,A),Vn=sr(`dend`,A),Hn=[Rn,Bn],Un=[zn,Vn],Wn=Rn.length+zn.length;function Gn(e){if(e.length<Wn)return!1;let{length:t}=Rn,n=e.subarray(-t);return Hn.some(t=>ur(e,t,A))&&Un.some(e=>ur(n,e,A))}function Kn(e){return e.length<Wn?!1:ur(e,Rn,A)}function qn(e){return e.length<Wn?!1:ur(e.subarray(-4),zn,A)}var Jn=class extends Error{constructor(e){super(),y(this,`type`,void 0),this.type=e}},Yn=new WeakMap,Xn=new WeakMap,Zn=new WeakMap,Qn=new WeakSet,$n=class{constructor(e){O(this,Qn),x(this,Yn,new In),x(this,Xn,`joining`),x(this,Zn,void 0),k(Zn,this,e)}addCommandChunk(e){if(C(Xn,this)===`completed`)return;let t=Kn(e);if(!C(Yn,this).length&&!t)throw new Jn(`no-first-chunk`);if(C(Yn,this).length&&t)throw new Jn(`incomplete-joining`);C(Yn,this).push(S(Qn,this,er).call(this,e)),qn(e)&&(k(Xn,this,`completed`),C(Zn,this).call(this,C(Yn,this).getBuffer()))}};function er(e){if(e.length<Wn)throw Error(`Command chunk is too short to unframe`);return e.subarray(A,e.length-A)}var j=new WeakMap,tr=new WeakMap,nr=new WeakMap,rr=new WeakMap,ir=class{constructor(e,t){x(this,j,new In),x(this,tr,[]),x(this,nr,`creating`),x(this,rr,void 0),k(rr,this,t),C(j,this).push(e)}addInteger(e,t){C(j,this).push(e.charCodeAt(0));let n=Dn(t);C(j,this).push(n)}addUniqueSimilarIntArr(e,t){C(j,this).push(e.charCodeAt(0));let n=kn(t);C(j,this).push(n)}addString(e,t){C(j,this).push(e.charCodeAt(0));let n=jn(t);C(j,this).push(n)}complete(){if(!C(j,this).length)throw Error(`Buffer is empty`);if(C(nr,this)===`completed`)return;k(nr,this,`completed`);let e=C(j,this).getBuffer();if(e.length+Wn<=C(rr,this)){C(tr,this).push(lr(e,Rn,zn));return}let t=Math.ceil(e.length/C(rr,this));Math.ceil(e.length/t)+Wn>C(rr,this)&&t++;for(let[n,r]of cr(e,t))n===0?C(tr,this).push(lr(r,Rn,Vn)):n===t-1?C(tr,this).push(lr(r,Bn,zn)):C(tr,this).push(lr(r,Bn,Vn))}getResultBuffers(){if(C(nr,this)===`creating`||!C(tr,this).length)throw Error(`Command is not complete.`);return C(tr,this)}};function ar(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++,or(e[r])){case Cn.Int:{let{number:i,byteLength:a}=On(e.subarray(r));n[t]=i,r+=a}break;case Cn.SimilarIntArray:{let{numbers:i,byteLength:a}=An(e.subarray(r));n[t]=i,r+=a}break;case Cn.String:{let{string:i,byteLength:a}=Mn(e.subarray(r));n[t]=i,r+=a}}}return dr(n)}function or(e){let t=e>>4;if(t<=Cn.Min||t>=Cn.Max)throw Error(`Not existing type`);return t}function sr(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*cr(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 lr(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 ur(e,t,n){for(let r=0;r<n;r++)if(e[r]!==t[r])return!1;return!0}function dr(e){switch(e.c){case D.SegmentsAnnouncement:return e;case D.SegmentRequest:return fr(e,`i`,`r`),e;case D.SegmentData:return fr(e,`i`,`r`,`s`),e;case D.SegmentAbsent:case D.CancelSegmentRequest:case D.SegmentDataSendingCompleted:return fr(e,`i`,`r`),e;default:throw Error(`Unknown peer command type: ${String(e.c)}`)}}function fr(e,...t){for(let n of t)if(typeof e[n]!=`number`)throw Error(`Expected number field "${n}", got ${typeof e[n]}`)}function pr(e,t){let{c:n,p:r,l:i}=e,a=new ir(n,t);return i!=null&&i.length&&a.addUniqueSimilarIntArr(`l`,i),r!=null&&r.length&&a.addUniqueSimilarIntArr(`p`,r),a.complete(),a.getResultBuffers()}function mr(e,t){let n=new ir(e.c,t);return n.addInteger(`i`,e.i),n.addInteger(`r`,e.r),n.complete(),n.getResultBuffers()}function hr(e,t){let n=new ir(e.c,t);return n.addInteger(`i`,e.i),n.addInteger(`s`,e.s),n.addInteger(`r`,e.r),n.complete(),n.getResultBuffers()}function gr(e,t){let n=new ir(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 _r(e,t){switch(e.c){case D.CancelSegmentRequest:case D.SegmentAbsent:case D.SegmentDataSendingCompleted:return mr(e,t);case D.SegmentRequest:return gr(e,t);case D.SegmentsAnnouncement:return pr(e,t);case D.SegmentData:return hr(e,t)}}var vr=c({BinaryCommandChunksJoiner:()=>$n,PeerCommandType:()=>D,deserializeCommand:()=>ar,isCommandChunk:()=>Gn,serializePeerCommand:()=>_r});function yr(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 br(e,t=`RTC error`){return yr(e,t).message}function xr(e){return e===`failed`||e===`closed`||e===`disconnected`}var Sr=65536,Cr=new WeakMap,wr=class{constructor(e,t){y(this,`channel`,void 0),y(this,`maxMessageSize`,void 0),x(this,Cr,void 0),this.channel=e,this.maxMessageSize=t}sendData(e,t){var n=this;return T(function*(){if(C(Cr,n))throw Error(`Already sending data`);if(n.channel.readyState!==`open`)throw Error(`Data channel is not open`);n.channel.bufferedAmountLowThreshold=Sr;let{promise:r,resolve:i,reject:a}=cn(),o=0,s=!1,c=()=>!s&&(s=!0,k(Cr,n,void 0),n.channel.removeEventListener(`bufferedamountlow`,p),n.channel.removeEventListener(`closing`,l),n.channel.removeEventListener(`close`,l),n.channel.removeEventListener(`error`,u),!0);k(Cr,n,{cancel:()=>{c()&&a(Error(`Send cancelled`))}});let l=()=>{c()&&a(Error(`Data channel closed`))},u=e=>{if(!c())return;let t=br(e,`Unknown error`);a(Error(`Data channel error: ${t}`))},d=ArrayBuffer.isView(e)?e.buffer:e,f=ArrayBuffer.isView(e)?e.byteOffset:0,p=()=>{if(!s){if(n.channel.readyState!==`open`){c()&&a(Error(`Data channel not open (state: ${n.channel.readyState})`));return}try{for(;o<e.byteLength;){if(n.channel.bufferedAmount>Sr)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),!C(Cr,n))return}}catch(e){c()&&a(e instanceof Error?e:Error(String(e)));return}c()&&i()}};return n.channel.addEventListener(`bufferedamountlow`,p),n.channel.addEventListener(`closing`,l),n.channel.addEventListener(`close`,l),n.channel.addEventListener(`error`,u),p(),r})()}cancel(){var e;(e=C(Cr,this))==null||e.cancel()}},Tr=(0,E.default)(`p2pml-core:peer-protocol`),Er=new WeakMap,Dr=new WeakMap,Or=new WeakMap,kr=new WeakMap,Ar=new WeakMap,jr=new WeakMap,Mr=new WeakMap,Nr=new WeakMap,Pr=new WeakMap,Fr=new WeakMap,Ir=new WeakSet,Lr=class{constructor(e,t,n,r,i){if(O(this,Ir),x(this,Er,void 0),x(this,Dr,void 0),x(this,Or,void 0),x(this,kr,void 0),x(this,Ar,void 0),x(this,jr,void 0),x(this,Mr,void 0),x(this,Nr,void 0),x(this,Pr,void 0),x(this,Fr,e=>{try{let t=new Uint8Array(e.data);Gn(t)?S(Ir,this,Rr).call(this,t):(C(Nr,this).onSegmentChunkReceived(t),C(kr,this).call(this,t.byteLength,`p2p`,C(Pr,this),C(Mr,this).streamType,C(Mr,this).infoHash))}catch(e){Tr(`error handling data channel message: %O`,e),C(Nr,this).onProtocolError(e)}}),k(jr,this,e),k(Mr,this,t),k(Nr,this,n),k(Pr,this,i),k(Dr,this,new wr(e,t.webRtcMaxMessageSize)),k(kr,this,r.getEventDispatcher(`onChunkDownloaded`)),k(Ar,this,r.getEventDispatcher(`onChunkUploaded`)),e.binaryType!==`arraybuffer`)throw Error(`Expected binaryType "arraybuffer", got "${e.binaryType}"`);e.addEventListener(`message`,C(Fr,this))}sendCommand(e){if(C(jr,this).readyState!==`open`)throw Error(`cannot send command ${e.c} (channel state: ${C(jr,this).readyState})`);let t=_r(e,C(Mr,this).webRtcMaxMessageSize);for(let e of t)C(jr,this).send(e)}stopUploadingSegmentData(){C(Dr,this).cancel(),k(Or,this,void 0)}getUploadingRequestId(){return C(Or,this)}splitSegmentDataToChunksAndUploadAsync(e,t){var n=this;return T(function*(){if(C(Or,n)!==void 0)throw Error(`Some segment data is already uploading.`);k(Or,n,t);try{yield C(Dr,n).sendData(e,e=>{C(Ar,n).call(n,e,C(Pr,n),C(Mr,n).streamType,C(Mr,n).infoHash)})}finally{C(Or,n)===t&&k(Or,n,void 0)}})()}destroy(){C(jr,this).removeEventListener(`message`,C(Fr,this)),C(Dr,this).cancel(),k(Er,this,void 0),k(Or,this,void 0)}};function Rr(e){C(Er,this)!=null||k(Er,this,new $n(e=>{k(Er,this,void 0);let t;try{t=ar(e)}catch(e){Tr(`error deserializing command: %O`,e),C(Nr,this).onProtocolError(e);return}C(Nr,this).onCommandReceived(t)}));try{C(Er,this).addCommandChunk(e)}catch(e){Tr(`error receiving command chunks: %O`,e),k(Er,this,void 0),C(Nr,this).onProtocolError(e)}}var zr=1,Br=class{constructor(e=2e4){y(this,`clearThresholdMs`,void 0),y(this,`loadingsCount`,0),y(this,`bytes`,[]),y(this,`loadingOnlyTimestamps`,[]),y(this,`timestamps`,[]),y(this,`noLoadingsTime`,0),y(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,zr);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,zr);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:M}=vr,N=new WeakMap,P=new WeakMap,Vr=new WeakMap,Hr=new WeakMap,Ur=new WeakMap,F=new WeakMap,Wr=new WeakMap,I=new WeakMap,Gr=new WeakMap,Kr=new WeakMap,qr=new WeakMap,Jr=new WeakMap,Yr=new WeakMap,Xr=new WeakMap,Zr=new WeakMap,Qr=new WeakMap,L=new WeakSet,$r=class{get isDestroyed(){return C(qr,this)}constructor(e,t,n,r,i,a){var o=this;O(this,L),y(this,`id`,void 0),y(this,`channel`,void 0),y(this,`eventTarget`,void 0),x(this,N,void 0),x(this,P,void 0),x(this,Vr,new Set),x(this,Hr,new Set),x(this,Ur,0),x(this,F,new Br),x(this,Wr,{value:0,timestamp:0}),x(this,I,(0,E.default)(`p2pml-core:peer`)),x(this,Gr,0),x(this,Kr,void 0),x(this,qr,!1),y(this,`connectedAt`,performance.now()),x(this,Jr,void 0),x(this,Yr,void 0),x(this,Xr,void 0),x(this,Zr,function(){var e=T(function*(e){switch(e.c){case M.SegmentsAnnouncement:k(Vr,o,new Set(e.l)),k(Hr,o,new Set(e.p)),C(Yr,o).onSegmentsAnnouncement();break;case M.SegmentRequest:k(Kr,o,e.r),C(N,o).stopUploadingSegmentData(),C(Yr,o).onSegmentRequested(o,e.i,e.r,e.b);break;case M.SegmentData:{if(!C(P,o)||C(P,o).isSegmentDataCommandReceived)break;let{request:t,controls:n,requestId:r}=C(P,o);if(t.segment.externalId!==e.i||r!==e.r)break;if(e.s===0&&t.loadedBytes===0){S(L,o,ei).call(o,`bytes-length-mismatch`,`Peer sent a segment of zero length`);break}C(P,o).isSegmentDataCommandReceived=!0,n.firstBytesReceived(),t.totalBytes===void 0?t.setTotalBytes(t.loadedBytes+e.s):t.totalBytes-t.loadedBytes!==e.s&&S(L,o,ei).call(o,`bytes-length-mismatch`,`Peer response bytes length mismatch`)}break;case M.SegmentDataSendingCompleted:{let t=C(P,o);if(!(t!=null&&t.isSegmentDataCommandReceived))return;let{request:n,controls:r,requestId:i}=t;if(n.segment.externalId!==e.i||i!==e.r){S(L,o,ei).call(o,`protocol-violation`,`Peer protocol violation`);return}if(n.loadedBytes!==n.totalBytes){S(L,o,ei).call(o,`bytes-length-mismatch`,`Peer response bytes length mismatch`);return}let a=yield n.validateData(C(Xr,o).validateP2PSegment);if(C(qr,o)||C(P,o)!==t)return;if(!a){S(L,o,ei).call(o,`validation-failed`,`P2P segment validation failed`);return}k(Ur,o,0),r.completeOnSuccess(),C(F,o).stopLoading(),k(P,o,void 0);break}case M.SegmentAbsent:var t;C(Vr,o).delete(e.i),((t=C(P,o))==null?void 0:t.request.segment.externalId)===e.i&&C(P,o).requestId===e.r&&S(L,o,ti).call(o,`peer-segment-absent`);break;case M.CancelSegmentRequest:if(C(Kr,o)===e.r&&k(Kr,o,void 0),C(N,o).getUploadingRequestId()!==e.r)break;C(N,o).stopUploadingSegmentData()}});return function(t){return e.apply(this,arguments)}}()),x(this,Qr,e=>{var t;if(!((t=C(P,this))!=null&&t.isSegmentDataCommandReceived))return;let{request:n,controls:r}=C(P,this);if(n.totalBytes!==void 0&&n.loadedBytes+e.byteLength>n.totalBytes){S(L,this,ei).call(this,`bytes-length-mismatch`,`Peer response bytes length mismatch`);return}C(F,this).addBytes(e.byteLength),C(Wr,this).timestamp=0,r.addLoadedChunk(e)}),this.id=e,this.channel=t,this.eventTarget=a,k(Jr,this,n),k(Yr,this,r),k(Xr,this,i),k(N,this,new Lr(t,i,{onSegmentChunkReceived:C(Qr,this),onCommandReceived:e=>void C(Zr,this).call(this,e).catch(t=>{C(I,this).call(this,`error processing command %O: %O`,e,t),this.destroy(!1,new Ht(`protocol-violation`,t instanceof Error?t.message:`Error processing command`,t))}),onProtocolError:e=>{this.destroy(!1,new Ht(`protocol-violation`,e instanceof Error?e.message:`Protocol error`,e))}},a,e))}get downloadingSegment(){var e;return(e=C(P,this))==null?void 0:e.request.segment}get isUploadingSegment(){return C(N,this).getUploadingRequestId()!==void 0}getDownloadBandwidth(){let e=performance.now();return e-C(Wr,this).timestamp>1e3&&(C(Wr,this).value=C(F,this).getBandwidthLoadingOnly(15),C(Wr,this).timestamp=e),C(Wr,this).value}getSegmentStatus(e){let{externalId:t}=e;if(C(Vr,this).has(t))return`loaded`;if(C(Hr,this).has(t))return`http-loading`}downloadSegment(e){if(C(qr,this))return;if(C(P,this))throw Error(`Some segment already is downloading`);if(e.tryCompleteByLoadedBytes({downloadSource:`p2p`,peerId:this.id},{notReceivingBytesTimeoutMs:C(Xr,this).p2pNotReceivingBytesTimeoutMs,onAbort:()=>void 0},C(Xr,this).validateP2PSegment,`p2p-segment-validation-failed`))return;C(F,this).startLoading(),k(Gr,this,(C(Gr,this)+1)%1e9),k(P,this,{request:e,requestId:C(Gr,this),isSegmentDataCommandReceived:!1,controls:e.start({downloadSource:`p2p`,peerId:this.id},{notReceivingBytesTimeoutMs:C(Xr,this).p2pNotReceivingBytesTimeoutMs,onAbort:t=>{if(!C(P,this)||C(P,this).request!==e)return;let{request:n,requestId:r}=C(P,this);if(S(L,this,ni).call(this,n.segment,r),C(F,this).stopLoading(),t.type!==`abort`&&(C(F,this).clear(),C(Wr,this).timestamp=0,C(I,this).call(this,`cleared bandwidth history due to ${t.type}`)),k(P,this,void 0),t.type===`bytes-receiving-timeout`){var i;k(Ur,this,(i=C(Ur,this),i++,i))}C(Ur,this)>=C(Xr,this).p2pErrorRetries?this.destroy(!1,new Ht(`timeout`,`Too many timeout errors`)):t.type===`bytes-receiving-timeout`&&C(Yr,this).onWarning(new Ut(`timeout-strike`,`Timeout strike ${C(Ur,this)}/${C(Xr,this).p2pErrorRetries}`))}})});let t={c:M.SegmentRequest,r:C(P,this).requestId,i:e.segment.externalId};e.loadedBytes&&(t.b=e.loadedBytes),S(L,this,ii).call(this,t)||S(L,this,ti).call(this,`peer-closed`)}uploadSegmentData(e,t,n){var r=this;return T(function*(){if(C(qr,r))return;if(t!==C(Kr,r)){C(I,r).call(r,`discarding obsolete upload request ${t} for segment ${e.externalId}`);return}let{externalId:i}=e;C(I,r).call(r,`send segment ${e.externalId} to ${r.id} (byteLength: ${n.byteLength})`);let a={c:M.SegmentData,i,r:t,s:n.byteLength};if(S(L,r,ii).call(r,a))try{if(yield C(N,r).splitSegmentDataToChunksAndUploadAsync(n,t),r.isDestroyed||t!==C(Kr,r))return;S(L,r,ri).call(r,e,t),C(I,r).call(r,`segment ${i} has been sent to ${r.id}`)}catch(e){C(I,r).call(r,`cancel segment uploading ${i}: %O`,e)}})()}sendSegmentsAnnouncementCommand(e,t){let n={c:M.SegmentsAnnouncement,p:t,l:e};S(L,this,ii).call(this,n)}sendSegmentAbsentCommand(e,t){S(L,this,ii).call(this,{c:M.SegmentAbsent,i:e,r:t})}destroy(e=!1,t){C(qr,this)||(k(qr,this,!0),S(L,this,ti).call(this,`peer-closed`,t),C(N,this).destroy(),e||C(Jr,this).call(this,t),C(I,this).call(this,`peer closed ${this.id}`))}};function ei(e,t){var n;(n=C(P,this))==null||n.request.clearLoadedBytes();let r=new Ht(e,t);S(L,this,ti).call(this,`peer-closed`,r),this.destroy(!1,r)}function ti(e,t){if(!C(P,this))return;let{request:n,controls:r}=C(P,this),{segment:i}=n;C(I,this).call(this,`cancel segment request ${i.externalId} (${e})`);let a=new b(e,void 0,t);r.failWithError(a),C(F,this).stopLoading(),e!==`peer-segment-absent`&&(C(F,this).clear(),C(Wr,this).timestamp=0,C(I,this).call(this,`cleared bandwidth history due to ${a.type}`)),k(P,this,void 0)}function ni(e,t){S(L,this,ii).call(this,{c:M.CancelSegmentRequest,i:e.externalId,r:t})}function ri(e,t){S(L,this,ii).call(this,{c:M.SegmentDataSendingCompleted,r:t,i:e.externalId})}function ii(e){if(C(qr,this))return!1;try{return C(N,this).sendCommand(e),!0}catch(t){return C(I,this).call(this,`error sending command %d: %O`,e.c,t),!1}}var ai=class{constructor(){y(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()}},oi,si,ci,li,R=typeof window<`u`?window:{},ui=(oi=(si=R.RTCPeerConnection)==null?R.webkitRTCPeerConnection:si)==null?R.mozRTCPeerConnection:oi,di=(ci=(li=R.RTCSessionDescription)==null?R.webkitRTCSessionDescription:li)==null?R.mozRTCSessionDescription:ci,fi=(()=>{if(!R.RTCPeerConnection&&!R.webkitRTCPeerConnection&&!R.mozRTCPeerConnection)return!1;let e;try{e=new ui;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 pi(e,t){return fi?e.createOffer(t):new Promise((n,r)=>{try{e.createOffer(n,r,t)}catch(e){r(e)}})}function mi(e,t){return fi?e.createAnswer(t):new Promise((n,r)=>{try{e.createAnswer(n,r,t)}catch(e){r(e)}})}function hi(e,t){return fi?e.setLocalDescription(t):new Promise((n,r)=>{try{e.setLocalDescription(t,n,r)}catch(e){r(e)}})}function gi(e,t){return fi?e.setRemoteDescription(t):new Promise((n,r)=>{try{e.setRemoteDescription(t,n,r)}catch(e){r(e)}})}var _i=5e4,vi=15e3,yi=5,bi=5e3;function xi(){let e=``;for(let t=0;t<20;t++)e+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*62));return e}var Si=new Set([`offer`,`answer`,`pranswer`,`rollback`]);function Ci(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.type==`string`&&Si.has(t.type)&&typeof t.sdp==`string`}var z=new WeakMap,B=new WeakMap,V=new WeakMap,wi=new WeakMap,Ti=new WeakMap,H=new WeakMap,Ei=new WeakMap,Di=new WeakMap,Oi=new WeakMap,ki=new WeakMap,Ai=new WeakMap,ji=new WeakMap,Mi=new WeakMap,U=new WeakSet,Ni=new WeakMap,Pi=new WeakMap,Fi=new WeakMap,Ii=class{constructor(e){var t,n,r,i,a,o;O(this,U),x(this,z,void 0),x(this,B,void 0),x(this,V,new ai),x(this,wi,new Map),x(this,Ti,new Set),x(this,H,new $t),x(this,Ei,null),x(this,Di,null),x(this,Oi,0),x(this,ki,null),x(this,Ai,void 0),x(this,ji,null),x(this,Mi,!1),x(this,Ni,()=>{S(U,this,Li).call(this,Xi._),S(U,this,zi).call(this,`started`).catch(e=>{S(U,this,W).call(this)||C(V,this).dispatchEvent(`error`,new Wt(`announce-failed`,`Initial announce failed: ${e instanceof Error?e.message:String(e)}`,e))})}),x(this,Pi,()=>{S(U,this,Ri).call(this),k(Di,this,null)}),x(this,Fi,e=>{if(S(U,this,W).call(this))return;let t;try{let n=typeof e==`string`?e:new TextDecoder().decode(e);t=JSON.parse(n)}catch(e){C(V,this).dispatchEvent(`error`,new Wt(`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!==C(z,this).infoHash)return;let i=n[`warning message`];typeof i==`string`&&C(V,this).dispatchEvent(`warning`,new Gt(`tracker-response`,i));let a=n[`failure reason`];if(typeof a==`string`){C(V,this).dispatchEvent(`error`,new Wt(`tracker-response`,a));return}let{interval:o}=n;if(typeof o==`number`&&o>0){let e=Math.max(Zi._,o);C(Di,this)!==e&&S(U,this,Li).call(this,e)}let s=n[`tracker id`];typeof s==`string`&&k(ji,this,s);let c=n.peer_id;if(typeof c==`string`&&c===C(z,this).peerId)return;let l=n.offer_id;typeof c==`string`&&typeof l==`string`&&(Ci(n.offer)?S(U,this,Ui).call(this,{sdp:n.offer,peerId:c,offerId:l}).catch(e=>{S(U,this,W).call(this)||C(V,this).dispatchEvent(`error`,new Wt(`signaling-failed`,`Failed to handle offer: ${e instanceof Error?e.message:String(e)}`,e))}):Ci(n.answer)&&S(U,this,Wi).call(this,{sdp:n.answer,peerId:c,offerId:l}).catch(e=>{S(U,this,W).call(this)||C(V,this).dispatchEvent(`error`,new Wt(`signaling-failed`,`Failed to handle answer: ${e instanceof Error?e.message:String(e)}`,e))}))}),k(z,this,{infoHash:e.infoHash,peerId:e.peerId,rtcConfig:e.rtcConfig,channelConfig:e.channelConfig,offerTimeout:(t=e.offerTimeout)==null?(()=>_i):t,offersCount:(n=e.offersCount)==null?(()=>yi):n,iceGatheringTimeout:(r=e.iceGatheringTimeout)==null?(()=>bi):r,connectionTimeout:(i=e.connectionTimeout)==null?(()=>vi):i,claimPeer:(a=e.claimPeer)==null?(()=>!0):a,shouldGenerateOffers:(o=e.shouldGenerateOffers)==null?(()=>!0):o}),k(B,this,e.wsClient)}addEventListener(e,t){C(V,this).addEventListener(e,t)}removeEventListener(e,t){C(V,this).removeEventListener(e,t)}start(){S(U,this,W).call(this)||C(Mi,this)||(k(Mi,this,!0),C(B,this).addEventListener(`connected`,C(Ni,this)),C(B,this).addEventListener(`disconnected`,C(Pi,this)),C(B,this).addEventListener(`message`,C(Fi,this)),C(B,this).state===`connected`&&C(Ni,this).call(this))}destroy(){S(U,this,W).call(this)||(C(H,this).abort(),S(U,this,Ri).call(this),S(U,this,Vi).call(this),S(U,this,Ji).call(this),S(U,this,Yi).call(this),C(Mi,this)&&(C(B,this).removeEventListener(`connected`,C(Ni,this)),C(B,this).removeEventListener(`disconnected`,C(Pi,this)),C(B,this).removeEventListener(`message`,C(Fi,this))),C(V,this).clear())}};function W(){return C(H,this).signal.aborted}function G(){if(C(H,this).signal.aborted)throw Error(`Client destroyed`)}function Li(e){var t=this,n;S(U,this,Ri).call(this),k(Di,this,e);let r=k(Oi,this,(n=C(Oi,this),++n)),i=function(){var e=T(function*(){try{yield S(U,t,zi).call(t)}catch(e){if(S(U,t,W).call(t))return;C(V,t).dispatchEvent(`error`,new Wt(`announce-failed`,`Announce failed: ${e instanceof Error?e.message:String(e)}`,e))}!S(U,t,W).call(t)&&C(Di,t)!==null&&C(Oi,t)===r&&k(Ei,t,setTimeout(i,C(Di,t)*1e3))});return function(){return e.apply(this,arguments)}}();k(Ei,this,setTimeout(i,e*1e3))}function Ri(){C(Ei,this)!==null&&(clearTimeout(C(Ei,this)),k(Ei,this,null))}function zi(e){var t=this;return T(function*(){if(S(U,t,W).call(t)||C(B,t).state!==`connected`)return;if(e&&k(Ai,t,e),C(ki,t))return C(ki,t);let n=T(function*(){let e=C(z,t).shouldGenerateOffers()?C(z,t).offersCount():0,n=yield Promise.all(Array.from({length:e},()=>S(U,t,Bi).call(t)));if(S(U,t,W).call(t)){for(let e of n)e&&S(U,t,qi).call(t,e.offer_id);return}let r=[];for(let e of n)e&&r.push(e);let i=C(Ai,t);k(Ai,t,void 0);let a=S(U,t,Hi).call(t,{numwant:r.length,offers:r,event:i});if(C(B,t).state!==`connected`){for(let e of r)S(U,t,qi).call(t,e.offer_id);return}try{C(B,t).send(JSON.stringify(a))}catch(e){for(let e of r)S(U,t,qi).call(t,e.offer_id);throw e}})();k(ki,t,n);try{yield n}finally{C(ki,t)===n&&k(ki,t,null)}})()}function Bi(){var e=this;return T(function*(){if(S(U,e,W).call(e))return;let t;try{var n,r;t=new ui((n=(r=C(z,e)).rtcConfig)==null?void 0:n.call(r)),C(Ti,e).add(t);let i=t.createDataChannel(`webtorrent`,C(z,e).channelConfig),a=yield pi(t);S(U,e,G).call(e),yield hi(t,a),S(U,e,G).call(e),yield S(U,e,Gi).call(e,t),S(U,e,G).call(e);let o=t.localDescription;if(!(o!=null&&o.sdp)){t.close();return}let s=xi();return C(wi,e).set(s,{connection:t,channel:i,timeoutId:setTimeout(()=>{S(U,e,qi).call(e,s)},C(z,e).offerTimeout())}),{offer:{type:o.type,sdp:o.sdp},offer_id:s}}catch(n){t==null||t.close(),S(U,e,W).call(e)||C(V,e).dispatchEvent(`warning`,new Gt(`offer-failed`,`Failed to create offer: ${n instanceof Error?n.message:String(n)}`,n))}finally{t&&C(Ti,e).delete(t)}})()}function Vi(){if(C(B,this).state!==`connected`)return;let e=S(U,this,Hi).call(this,{numwant:0,offers:[],event:`stopped`});try{C(B,this).send(JSON.stringify(e))}catch(e){}}function Hi({numwant:e,offers:t,event:n}){let r={action:`announce`,info_hash:C(z,this).infoHash,peer_id:C(z,this).peerId,numwant:e,uploaded:0,downloaded:0,offers:t};return n&&(r.event=n),C(ji,this)&&(r.trackerid=C(ji,this)),r}function Ui({sdp:e,peerId:t,offerId:n}){var r=this;return T(function*(){if(S(U,r,W).call(r)||!C(z,r).claimPeer(t))return;let i;try{var a,o;i=new ui((a=(o=C(z,r)).rtcConfig)==null?void 0:a.call(o)),C(Ti,r).add(i),yield gi(i,new di(e)),S(U,r,G).call(r);let s=yield mi(i);S(U,r,G).call(r),yield hi(i,s),S(U,r,G).call(r),yield S(U,r,Gi).call(r,i),S(U,r,G).call(r);let c=i.localDescription;if(!c)throw Error(`Failed to get local description after ICE gathering`);let l={action:`announce`,info_hash:C(z,r).infoHash,peer_id:C(z,r).peerId,to_peer_id:t,offer_id:n,answer:{type:c.type,sdp:c.sdp}};C(B,r).send(JSON.stringify(l));let u=yield S(U,r,Ki).call(r,i);S(U,r,G).call(r),C(V,r).dispatchEvent(`peerConnected`,{peerId:t,connection:i,channel:u})}catch(e){i==null||i.close(),C(V,r).dispatchEvent(`peerConnectFailed`,{peerId:t,error:new Kt(`connection-failed`,e instanceof Error?e.message:String(e),e)})}finally{i&&C(Ti,r).delete(i)}})()}function Wi({sdp:e,peerId:t,offerId:n}){var r=this;return T(function*(){if(S(U,r,W).call(r))return;let i=C(wi,r).get(n);if(i){if(C(wi,r).delete(n),clearTimeout(i.timeoutId),!C(z,r).claimPeer(t)){i.connection.close();return}C(Ti,r).add(i.connection);try{yield gi(i.connection,new di(e)),S(U,r,G).call(r);let n=yield S(U,r,Ki).call(r,i.connection,i.channel);S(U,r,G).call(r),C(V,r).dispatchEvent(`peerConnected`,{peerId:t,connection:i.connection,channel:n})}catch(e){i.connection.close(),C(V,r).dispatchEvent(`peerConnectFailed`,{peerId:t,error:new Kt(`connection-failed`,e instanceof Error?e.message:String(e),e)})}finally{C(Ti,r).delete(i.connection)}}})()}function Gi(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),C(H,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(C(H,this).signal.aborted){c();return}r=setTimeout(()=>{i(),t()},C(z,this).iceGatheringTimeout()),e.addEventListener(`icegatheringstatechange`,a),e.addEventListener(`icecandidate`,o),e.addEventListener(`signalingstatechange`,s),C(H,this).signal.addEventListener(`abort`,c)})}function Ki(e,t){let{promise:n,resolve:r,reject:i}=cn(),a,o=t,s=()=>xr(e.iceConnectionState)?(m(),i(Error(`ICE connection ${e.iceConnectionState}`)),!0):!1,c=()=>{m(),o?r(o):i(Error(`Data channel missing on open`))},l=()=>{m(),i(Error(`Data channel error`))},u=()=>{m(),i(Error(`Data channel closed prematurely`))},d=e=>{o=e,e.readyState===`open`?c():e.readyState===`closed`||e.readyState===`closing`?u():(e.addEventListener(`open`,c),e.addEventListener(`error`,l),e.addEventListener(`close`,u),e.addEventListener(`closing`,u))},f=e=>{o||d(e.channel)},p=()=>{m(),i(Error(`Connection aborted due to teardown`))},m=()=>{clearTimeout(a),e.removeEventListener(`iceconnectionstatechange`,s),e.removeEventListener(`datachannel`,f),o&&(o.removeEventListener(`open`,c),o.removeEventListener(`error`,l),o.removeEventListener(`close`,u),o.removeEventListener(`closing`,u)),C(H,this).signal.removeEventListener(`abort`,p)};return C(H,this).signal.aborted?(p(),n):s()?n:(a=setTimeout(()=>{m(),i(Error(`Data channel open timeout`))},C(z,this).connectionTimeout()),e.addEventListener(`iceconnectionstatechange`,s),C(H,this).signal.addEventListener(`abort`,p),o?d(o):e.addEventListener(`datachannel`,f),n)}function qi(e,t){let n=t==null?C(wi,this).get(e):t;n&&(clearTimeout(n.timeoutId),n.connection.close(),C(wi,this).delete(e))}function Ji(){for(let[e,t]of C(wi,this))S(U,this,qi).call(this,e,t)}function Yi(){for(let e of C(Ti,this))e.close();C(Ti,this).clear()}var Xi={_:120},Zi={_:20},Qi=50,$i=1.5,K=new WeakMap,q=new WeakMap,ea=new WeakMap,ta=new WeakMap,na=new WeakMap,ra=new WeakMap,ia=new WeakMap,aa=new WeakMap,oa=new WeakSet,sa=class{constructor(e){var t,n;O(this,oa),x(this,K,void 0),x(this,q,new ai),x(this,ea,new Set),x(this,ta,new Map),x(this,na,new Set),x(this,ra,!1),x(this,ia,!1),x(this,aa,e=>{if(C(ra,this)||C(ea,this).has(e)||C(ta,this).has(e))return!1;let t=Math.floor(C(K,this).maxPeers()*Math.max(1,C(K,this).maxPeersMultiplier()));return C(ea,this).size+C(ta,this).size>=t?!1:(C(ea,this).add(e),!0)}),k(K,this,w(w({},e),{},{maxPeers:(t=e.maxPeers)==null?(()=>Qi):t,maxPeersMultiplier:(n=e.maxPeersMultiplier)==null?(()=>$i):n}))}addEventListener(e,t){C(q,this).addEventListener(e,t)}removeEventListener(e,t){C(q,this).removeEventListener(e,t)}start(){if(!(C(ra,this)||C(ia,this))){k(ia,this,!0);try{for(let e of C(K,this).trackerUrls){let{client:t,release:n}=C(K,this).socketPool.acquire(e),r=!1;try{let i=new Ii({infoHash:C(K,this).infoHash,peerId:C(K,this).peerId,wsClient:t,rtcConfig:C(K,this).rtcConfig,channelConfig:C(K,this).channelConfig,claimPeer:C(aa,this),offersCount:C(K,this).offersCount,offerTimeout:C(K,this).offerTimeout,iceGatheringTimeout:C(K,this).iceGatheringTimeout,connectionTimeout:C(K,this).connectionTimeout,shouldGenerateOffers:()=>C(ea,this).size+C(ta,this).size<C(K,this).maxPeers()}),a=t=>{C(ea,this).delete(t.peerId),S(oa,this,la).call(this,t.peerId,t.connection,t.channel,e)},o=t=>{C(ea,this).has(t.peerId)&&(C(ea,this).delete(t.peerId),C(q,this).dispatchEvent(`peerConnectFailed`,{peerId:t.peerId,trackerUrl:e,error:t.error}))},s=t=>{C(q,this).dispatchEvent(`warning`,{trackerUrl:e,warning:t})},c=t=>{C(q,this).dispatchEvent(`error`,{trackerUrl:e,error:t})};i.addEventListener(`peerConnected`,a),i.addEventListener(`peerConnectFailed`,o),i.addEventListener(`warning`,s),i.addEventListener(`error`,c),C(na,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(C(ra,this))return;k(ra,this,!0);for(let{client:e,releaseSocket:t,cleanupListeners:n}of C(na,this))n(),e.destroy(),t();C(na,this).clear(),C(ea,this).clear();let e=[...C(ta,this).entries()];C(ta,this).clear();for(let[t,n]of e){n.cleanup();try{n.channel.close()}catch(e){}try{n.connection.close()}catch(e){}C(q,this).dispatchEvent(`peerDisconnected`,{peerId:t,trackerUrl:n.trackerUrl,disconnectReason:`Manager destroyed`})}C(q,this).clear()}};function ca(e,t){if(C(ra,this))return;let n=C(ta,this).get(e);if(n){C(ta,this).delete(e),n.cleanup();try{n.channel.close()}catch(e){}try{n.connection.close()}catch(e){}C(q,this).dispatchEvent(`peerDisconnected`,w({peerId:e,trackerUrl:n.trackerUrl},t))}}function la(e,t,n,r){if(xr(t.iceConnectionState)){try{t.close()}catch(e){}C(q,this).dispatchEvent(`peerConnectFailed`,{peerId:e,trackerUrl:r,error:new Kt(`connection-failed`,`Connection failed during promotion`)});return}let i=t=>S(oa,this,ca).call(this,e,t),a=()=>{xr(t.iceConnectionState)&&i({error:new Ht(`connection-lost`,`ICE connection state became ${t.iceConnectionState}`)})},o=()=>i({disconnectReason:`Data channel closed`}),s=()=>i({disconnectReason:`Data channel closing`}),c=e=>{let t=br(e,`Data channel error`);i({error:new Ht(`transport-error`,`Data channel error: ${t}`)})},l=t=>S(oa,this,ca).call(this,e,t?{error:t}:{disconnectReason:`Closed by consumer`});C(ta,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),C(q,this).dispatchEvent(`peerConnected`,{peerId:e,connection:t,channel:n,trackerUrl:r,close:e=>l==null?void 0:l(e)})}function ua(e,t){for(let n of e.values()){let e=n.segments.get(t);if(e)return e}}function da(e,t){for(let n of e.segments.values())if(n.externalId===t)return n}function fa(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 pa(e,t,n,r,i){let{highDemandTimeWindow:a,httpDownloadTimeWindow:o,p2pDownloadTimeWindow:s}=fa(n,i);return{isHighDemand:ha(e,t,a),isHttpDownloadable:ha(e,t,o),isP2PDownloadable:ha(e,t,s)&&r.isSegmentLoadingOrLoadedBySomeone(e)}}function ma(e,t){let{bufferEdge:n,bufferAhead:r}=t;return{start:e.startTime-n+r,end:e.endTime-n+r}}function ha(e,t,n){let{start:r,end:i}=ma(e,t);return!(n*t.rate<r||0>i)}var ga=1e3,_a=new WeakMap,J=new WeakMap,va=new WeakMap,ya=new WeakMap,ba=new WeakMap,Y=new WeakMap,xa=new WeakMap,Sa=new WeakMap,X=new WeakMap,Ca=new WeakMap,wa=new WeakMap,Ta=new WeakMap,Ea=new WeakMap,Da=new WeakMap,Oa=new WeakMap,ka=new WeakMap,Aa=new WeakMap,ja=new WeakMap,Ma=new WeakMap,Na=new WeakMap,Pa=new WeakMap,Fa=new WeakSet,Ia=new WeakMap,La=new WeakMap,Ra=new WeakMap,za=new WeakMap,Ba=class{constructor(e,t,n,r,i,a,o,s){var c=this;O(this,Fa),x(this,_a,void 0),x(this,J,new Map),x(this,va,!1),x(this,ya,(0,E.default)(`p2pml-core:webtorrent-manager`)),x(this,ba,(0,E.default)(`p2pml-core:churn-cleanup`)),x(this,Y,void 0),x(this,xa,void 0),x(this,Sa,void 0),x(this,X,void 0),x(this,Ca,void 0),x(this,wa,void 0),x(this,Ta,void 0),x(this,Ea,void 0),x(this,Da,void 0),x(this,Oa,void 0),x(this,ka,void 0),x(this,Aa,void 0),x(this,ja,void 0),x(this,Ma,void 0),x(this,Na,void 0),x(this,Pa,()=>{k(Ea,this,setTimeout(C(Pa,this),Math.max(ga,C(X,this).p2pChurnCleanupIntervalMs)));let e=C(J,this).size-C(X,this).p2pMaxPeers;if(e<=0)return;let t=[],n=performance.now();for(let e of C(J,this).values())e.downloadingSegment||e.isUploadingSegment||n-e.connectedAt<C(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);C(ba,this).call(this,`Background churn cleanup: dropping ${r.length} excess peers (total: ${C(J,this).size}, target: ${C(X,this).p2pMaxPeers}, eligible: ${t.length})`);for(let e of r)C(ba,this).call(this,`dropping excess peer ${e.id} with bandwidth ${e.getDownloadBandwidth()}`),e.destroy()}),x(this,Ia,e=>{if(C(ya,this).call(this,`peerConnected: peerId=${e.peerId}`),C(J,this).has(e.peerId)){e.close();return}let t=new $r(e.peerId,e.channel,e.close,{onSegmentRequested:(e,t,n,r)=>{C(za,this).call(this,e,t,n,r).catch(n=>{C(ya,this).call(this,`Error in onSegmentRequested ${t} for peer ${e.id}:`,n)})},onSegmentsAnnouncement:C(Ta,this),onWarning:n=>{C(ja,this).call(this,{peerId:t.id,infoHash:C(Y,this).infoHash,streamType:C(Y,this).type,trackerUrl:e.trackerUrl,warning:n})}},{p2pNotReceivingBytesTimeoutMs:C(X,this).p2pNotReceivingBytesTimeoutMs,webRtcMaxMessageSize:C(X,this).webRtcMaxMessageSize,p2pErrorRetries:C(X,this).p2pErrorRetries,validateP2PSegment:C(X,this).validateP2PSegment,streamType:C(Y,this).type,infoHash:C(Y,this).infoHash},C(wa,this));if(C(J,this).set(e.peerId,t),C(Da,this).call(this,{peerId:e.peerId,infoHash:C(Y,this).infoHash,streamType:C(Y,this).type,trackerUrl:e.trackerUrl}),C(X,this).isP2PUploadDisabled)return;let{httpLoading:n,loaded:r}=S(Fa,this,Va).call(this);t.sendSegmentsAnnouncementCommand(r,n)}),x(this,La,e=>{var t;C(ya,this).call(this,`peerDisconnected: peerId=%s error=%s reason=%s`,e.peerId,(t=e.error)==null?void 0:t.message,e.disconnectReason);let n=C(J,this).get(e.peerId);n&&(C(J,this).delete(e.peerId),n.destroy(!0),e.error&&C(Aa,this).call(this,{peerId:e.peerId,infoHash:C(Y,this).infoHash,streamType:C(Y,this).type,trackerUrl:e.trackerUrl,error:e.error}),C(ka,this).call(this,{peerId:n.id,infoHash:C(Y,this).infoHash,streamType:C(Y,this).type,trackerUrl:e.trackerUrl}))}),y(this,`broadcastAnnouncement`,(e=!1)=>{if(e){C(Ra,this).call(this,e);return}C(va,this)||C(X,this).isP2PUploadDisabled||C(Ra,this).call(this)}),x(this,Ra,(e=!1)=>{k(va,this,!0),ln(()=>{let{loaded:t=[],httpLoading:n=[]}=e?{}:S(Fa,this,Va).call(this);for(let e of C(J,this).values())e.sendSegmentsAnnouncementCommand(t,n);k(va,this,!1)})}),x(this,za,function(){var e=T(function*(e,t,n,r){let i=da(C(Y,c),t);if(!i)return;if(C(X,c).isP2PUploadDisabled){e.sendSegmentAbsentCommand(t,n);return}let a;try{a=yield C(Sa,c).getSegmentData(C(Y,c).swarmId,C(Y,c).streamSwarmId,i.externalId)}catch(n){C(ya,c).call(c,`Storage error for segment ${t} requested by peer ${e.id}:`,n)}if(C(J,c).has(e.id)){if(!a||a.byteLength===0){a&&C(ya,c).call(c,`refusing to upload empty segment ${t} to peer ${e.id}: segment storage returned no bytes`),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)}}()),k(Y,this,e),k(xa,this,t),k(Sa,this,n),k(X,this,r),k(Ca,this,i),k(wa,this,a),k(Ta,this,s),k(Da,this,a.getEventDispatcher(`onPeerConnect`)),k(Oa,this,a.getEventDispatcher(`onPeerConnectError`)),k(ka,this,a.getEventDispatcher(`onPeerClose`)),k(Aa,this,a.getEventDispatcher(`onPeerError`)),k(ja,this,a.getEventDispatcher(`onPeerWarning`)),k(Ma,this,a.getEventDispatcher(`onTrackerWarning`)),k(Na,this,a.getEventDispatcher(`onTrackerError`)),k(_a,this,new sa({infoHash:C(Y,this).infoHash,peerId:o,trackerUrls:C(X,this).announceTrackers,rtcConfig:()=>C(X,this).rtcConfig,socketPool:C(Ca,this),maxPeers:()=>C(X,this).p2pMaxPeers,maxPeersMultiplier:()=>C(X,this).p2pChurnMaxPeersMultiplier,offersCount:()=>C(X,this).webRtcOffersCount,offerTimeout:()=>C(X,this).webRtcOfferTimeoutMs,iceGatheringTimeout:()=>C(X,this).webRtcIceGatheringTimeoutMs,connectionTimeout:()=>C(X,this).webRtcConnectionTimeoutMs})),C(_a,this).addEventListener(`peerConnected`,C(Ia,this)),C(_a,this).addEventListener(`peerDisconnected`,C(La,this)),C(_a,this).addEventListener(`peerConnectFailed`,e=>{C(ya,this).call(this,`Peer connection failed (${e.peerId}) from tracker ${e.trackerUrl}:`,e.error),C(Oa,this).call(this,{peerId:e.peerId,infoHash:C(Y,this).infoHash,streamType:C(Y,this).type,trackerUrl:e.trackerUrl,error:e.error})}),C(_a,this).addEventListener(`warning`,e=>{C(ya,this).call(this,`Tracker warning (${e.trackerUrl}):`,e.warning),C(Ma,this).call(this,{trackerUrl:e.trackerUrl,infoHash:C(Y,this).infoHash,streamType:C(Y,this).type,warning:e.warning})}),C(_a,this).addEventListener(`error`,e=>{C(ya,this).call(this,`Tracker error (${e.trackerUrl}):`,e.error),C(Na,this).call(this,{trackerUrl:e.trackerUrl,infoHash:C(Y,this).infoHash,streamType:C(Y,this).type,error:e.error})}),C(wa,this).addEventListener(`onStorageUpdated-${C(Y,this).streamSwarmId}`,this.broadcastAnnouncement),C(_a,this).start(),k(Ea,this,setTimeout(C(Pa,this),Math.max(ga,C(X,this).p2pChurnCleanupIntervalMs)))}downloadSegment(e){let t=[];for(let n of C(J,this).values())!n.downloadingSegment&&n.getSegmentStatus(e)===`loaded`&&t.push(n);if(t.length===0)return;let n=Ha(t),r=C(xa,this).getOrCreateRequest(e);n.downloadSegment(r)}isSegmentLoadingOrLoadedBySomeone(e){for(let t of C(J,this).values())if(t.getSegmentStatus(e))return!0;return!1}isSegmentLoadedBySomeone(e){for(let t of C(J,this).values())if(t.getSegmentStatus(e)===`loaded`)return!0;return!1}get connectedPeerIds(){return C(J,this).keys()}get connectedPeerCount(){return C(J,this).size}*peers(){for(let e of C(J,this).values())yield e}destroy(){clearTimeout(C(Ea,this)),k(Ea,this,void 0),C(wa,this).removeEventListener(`onStorageUpdated-${C(Y,this).streamSwarmId}`,this.broadcastAnnouncement),C(_a,this).destroy();for(let e of C(J,this).values())e.destroy();C(J,this).clear()}};function Va(){let e=C(Sa,this).getStoredSegmentIds(C(Y,this).swarmId,C(Y,this).streamSwarmId),t=[];for(let e of C(xa,this).httpRequests()){let n=C(Y,this).segments.get(e.segment.runtimeId);n&&t.push(n.externalId)}return{loaded:e,httpLoading:t}}function Ha(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),fn(e,e=>Math.max(e.getDownloadBandwidth(),a))}return dn(e)}function Ua(e){return`${e.type}-${e.identityHash}`}function Wa(e){let{externalId:t}=e;return`(${Ua(e.stream)} | ${t})`}var Ga=new WeakMap,Ka=new WeakMap,qa=new WeakMap,Ja=new WeakMap,Ya=new WeakMap,Xa=new WeakMap,Za=new WeakMap,Qa=new WeakMap,$a=new WeakMap,eo=new WeakMap,to=new WeakSet,no=class{constructor(e,t,n,r,i,a,o,s){O(this,to),x(this,Ga,new Map),x(this,Ka,void 0),x(this,qa,(0,E.default)(`p2pml-core:p2p-loaders-container`)),x(this,Ja,void 0),x(this,Ya,void 0),x(this,Xa,void 0),x(this,Za,void 0),x(this,Qa,void 0),x(this,$a,void 0),x(this,eo,void 0),k(Ja,this,t),k(Ya,this,n),k(Xa,this,r),k(Za,this,i),k(Qa,this,a),k($a,this,o),k(eo,this,s),k(Ka,this,S(to,this,io).call(this,e)),C(qa,this).call(this,`set current p2p loader: ${Ua(e)}`)}changeCurrentLoader(e){let t=C(Ka,this).stream;C(Ya,this).getStoredSegmentIds(t.swarmId,t.streamSwarmId).length?S(to,this,ao).call(this,C(Ka,this)):S(to,this,oo).call(this,C(Ka,this)),k(Ka,this,S(to,this,io).call(this,e)),C(qa,this).call(this,`change current p2p loader: ${Ua(e)}`)}get currentLoader(){return C(Ka,this).loader}destroy(){for(let{loader:e,destroyTimeoutId:t}of C(Ga,this).values())e.destroy(),clearTimeout(t);C(Ga,this).clear()}};function ro(e){if(C(Ga,this).has(e.runtimeId))throw Error(`Loader for this stream already exists`);let t=new Ba(e,C(Ja,this),C(Ya,this),C(Xa,this),C(Za,this),C(Qa,this),C($a,this),()=>{C(Ka,this).loader===t&&C(eo,this).call(this)}),n=Ua(e);return C(qa,this).call(this,`created new loader: ${n}`),{loader:t,stream:e,loggerInfo:n}}function io(e){let t=C(Ga,this).get(e.runtimeId);if(t)return clearTimeout(t.destroyTimeoutId),t.destroyTimeoutId=void 0,t;{let t=S(to,this,ro).call(this,e);return C(Ga,this).set(e.runtimeId,t),t}}function ao(e){e.destroyTimeoutId=window.setTimeout(()=>S(to,this,oo).call(this,e),C(Xa,this).p2pInactiveLoaderDestroyTimeoutMs)}function oo(e){e.loader.destroy(),C(Ga,this).delete(e.stream.runtimeId),C(qa,this).call(this,`destroy p2p loader: `,e.loggerInfo)}function so(e){return{runtimeId:e.runtimeId,externalId:e.externalId,url:e.url,byteRange:e.byteRange&&w({},e.byteRange),startTime:e.startTime,endTime:e.endTime}}var co=class{constructor(e,t,n,r,i,a,o){y(this,`segment`,void 0),y(this,`requestProcessQueueCallback`,void 0),y(this,`bandwidthCalculators`,void 0),y(this,`playback`,void 0),y(this,`playbackConfig`,void 0),y(this,`infoHash`,void 0),y(this,`currentAttempt`,void 0),y(this,`_failedAttempts`,new lo),y(this,`finalData`,void 0),y(this,`bytes`,[]),y(this,`_loadedBytes`,0),y(this,`_totalBytes`,void 0),y(this,`_status`,`not-started`),y(this,`progress`,void 0),y(this,`notReceivingBytesTimeout`,void 0),y(this,`_onAbortCallback`,void 0),y(this,`notReceivingBytesTimeoutMs`,void 0),y(this,`_logger`,void 0),y(this,`_isHandledByProcessQueue`,!1),y(this,`onSegmentError`,void 0),y(this,`onSegmentAbort`,void 0),y(this,`onSegmentStart`,void 0),y(this,`onSegmentLoaded`,void 0),y(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 b(`bytes-receiving-timeout`);(t=this._onAbortCallback)==null||t.call(this,r),this.handleFailure(r)}),y(this,`failWithError`,e=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&this.handleFailure(e)}),y(this,`handleFailure`,e=>{this.currentAttempt&&(this.setStatus(`failed`),this.logger(`${this.downloadSource} ${this.segment.externalId} failed ${e.type}`),this._failedAttempts.add(w(w({},this.currentAttempt),{},{error:e})),this.onSegmentError({segment:so(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())}),y(this,`completeOnSuccess`,()=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&(this.manageBandwidthCalculatorsState(`stop`),this.notReceivingBytesTimeout.clear(),this.setStatus(`succeed`),this._totalBytes=this._loadedBytes,this.onSegmentLoaded({segment:so(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())}),y(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}),y(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 uo(this.abortOnTimeout);let{type:c}=this.segment.stream;this._logger=(0,E.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=un(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 T(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 T(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 b(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=w({},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:so(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 b(`abort`)),this.onSegmentAbort({segment:so(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]()}},lo=class{constructor(){y(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=[]}},uo=class{constructor(e){y(this,`action`,void 0),y(this,`timeoutId`,void 0),y(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}},fo=class{constructor(e,t,n,r,i){y(this,`requestProcessQueueCallback`,void 0),y(this,`bandwidthCalculators`,void 0),y(this,`playback`,void 0),y(this,`config`,void 0),y(this,`eventTarget`,void 0),y(this,`requests`,new Map),this.requestProcessQueueCallback=e,this.bandwidthCalculators=t,this.playback=n,this.config=r,this.eventTarget=i}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);return t||(t=new co(e,this.requestProcessQueueCallback,this.bandwidthCalculators,this.playback,this.config,this.eventTarget,e.stream.infoHash),this.requests.set(e,t)),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()}},po=class{constructor(e,t){y(this,`segment`,void 0),y(this,`engineCallbacks`,void 0),y(this,`_status`,`pending`),y(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.slice(0),bandwidth:t}))}reject(){this._status===`pending`&&(this._status=`failed`,this.engineCallbacks.onError(new qt(`failed`)))}abort(){this._status===`pending`&&(this._status=`aborted`,this.engineCallbacks.onError(new qt(`aborted`)))}markAsShouldBeStartedImmediately(){this._shouldBeStartedImmediately=!0}};function*mo(e,t,n,r,i){var a;let{runtimeId:o,stream:s}=e,c=(a=s.segments.get(o))==null?ho(s,e):a;if(!c)return;let l=s.segments.values(),u;do{let e=l.next();if(e.done)return;u=e.value}while(u!==c);let d=pa(u,t,n,r,i);if(go(d)){let e=l.next();if(e.done)return;let a=e.value,o=pa(a,t,n,r,i);if(go(o))return;d.isHighDemand=!0,yield{segment:u,statuses:d},yield{segment:a,statuses:o}}else yield{segment:u,statuses:d};for(let e of l){let a=pa(e,t,n,r,i);if(go(a))break;yield{segment:e,statuses:a}}}function ho(e,t){for(let n of e.segments.values())if(n.startTime>=t.startTime)return n}function go(e){let{isHighDemand:t,isHttpDownloadable:n,isP2PDownloadable:r}=e;return!t&&!n&&!r}function _o(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t^=t>>>16,t=Math.imul(t,2246822507),t^=t>>>13,t=Math.imul(t,3266489909),t^=t>>>16,t>>>0}function vo(e,t){return _o(`${e}|${t}`)}function yo(e,t,n){let r=vo(e,n),i=0;for(let a of t){let t=vo(a,n);(t<r||t===r&&a<e)&&i++}return i}var bo=.5;function xo(e){let{rank:t,secondsToHighDemand:n,estimatedFetchSeconds:r}=e;return t===0||n<=r*(1+1/t)+bo}var So={reportStaleAfterMs:2e3,initialBufferTarget:30,maxBufferTarget:120,inferredSafetyFactor:.7,idleFullBufferRatio:.5},Co=class{constructor(e,t={},n=()=>performance.now()){y(this,`config`,void 0),y(this,`now`,void 0),y(this,`reported`,void 0),y(this,`bufferEdge`,void 0),y(this,`anchor`,void 0),y(this,`lastDeliveryEndedAt`,0),y(this,`atMs`,void 0),y(this,`atBuffer`,0),y(this,`atDelivered`,0),y(this,`delivered`,0),y(this,`bufferTarget`,void 0),this.config=w(w({},So),t),this.now=n,this.bufferTarget=this.config.initialBufferTarget,this.anchor=e,this.bufferEdge=e.startTime,this.atMs=this.now()}report(e){this.reported={state:{bufferAhead:Math.max(0,e.bufferAhead),rate:e.rate},at:this.now()}}onSegmentRequested(e){let t=this.now(),n=this.anchor;if(this.anchor=e,this.bufferEdge=e.startTime,!(e.externalId===n.externalId||To(n,e)))return this.reanchor(t,0),!0;let r=(t-this.lastDeliveryEndedAt)/1e3,i=e.endTime-e.startTime;return this.lastDeliveryEndedAt>0&&i>0&&r>i*this.config.idleFullBufferRatio&&(this.learnBufferTarget(this.rawInferredBufferAhead(t)),this.reanchor(t,this.bufferTarget)),!1}onSegmentDelivered(e){this.delivered+=Math.max(0,e.endTime-e.startTime),this.lastDeliveryEndedAt=this.now(),this.bufferEdge=Math.max(this.bufferEdge,e.endTime)}getPlayback(){let e=this.now(),{reported:t}=this,n=t&&(t.state.rate===0||e-t.at<=this.config.reportStaleAfterMs);return t&&n?{bufferEdge:this.bufferEdge,bufferAhead:t.state.bufferAhead,rate:t.state.rate,source:`reported`}:{bufferEdge:this.bufferEdge,bufferAhead:this.rawInferredBufferAhead(e)*this.config.inferredSafetyFactor,rate:1,source:`inferred`}}rawInferredBufferAhead(e){let t=(e-this.atMs)/1e3,n=this.delivered-this.atDelivered;return wo(this.atBuffer+n-t,0,this.bufferTarget)}reanchor(e,t){this.atMs=e,this.atBuffer=t,this.atDelivered=this.delivered}learnBufferTarget(e){if(e<=0)return;let t=this.bufferTarget*.8+e*.2;this.bufferTarget=wo(t,1,this.config.maxBufferTarget)}};function wo(e,t,n){return Math.min(n,Math.max(t,e))}function To(e,t){let n=Math.min(e.endTime-e.startTime,t.endTime-t.startTime)/2;return Math.abs(t.startTime-e.endTime)<=n}var Eo=6e4,Do=1e3,Oo=.3,ko=class{constructor(e,t,n,r,i,a,o,s){y(this,`lastRequestedSegment`,void 0),y(this,`streamDetails`,void 0),y(this,`config`,void 0),y(this,`bandwidthCalculators`,void 0),y(this,`segmentStorage`,void 0),y(this,`webTorrentSocketPool`,void 0),y(this,`eventTarget`,void 0),y(this,`peerId`,void 0),y(this,`requests`,void 0),y(this,`engineRequest`,void 0),y(this,`p2pLoaders`,void 0),y(this,`playback`,void 0),y(this,`playbackTracker`,void 0),y(this,`logger`,void 0),y(this,`oracleLogger`,(0,E.default)(`p2pml:playback-oracle`)),y(this,`levelChangedTimestamp`,void 0),y(this,`lastQueueProcessingTimeStamp`,void 0),y(this,`randomHttpDownloadTimeout`,void 0),y(this,`segmentBytesByStream`,new Map),y(this,`initialHttpDelayTimeoutId`,void 0),y(this,`isProcessQueueMicrotaskCreated`,!1),y(this,`createdAt`,performance.now()),y(this,`requestProcessQueueMicrotask`,(e=!0)=>{let t=performance.now();!e&&this.lastQueueProcessingTimeStamp!==void 0&&t-this.lastQueueProcessingTimeStamp<=1e3||this.isProcessQueueMicrotaskCreated||(this.isProcessQueueMicrotaskCreated=!0,ln(()=>{try{this.processQueue(),this.lastQueueProcessingTimeStamp=t}finally{this.isProcessQueueMicrotaskCreated=!1}}))}),this.lastRequestedSegment=e,this.streamDetails=t,this.config=n,this.bandwidthCalculators=r,this.segmentStorage=i,this.webTorrentSocketPool=a,this.eventTarget=o,this.peerId=s;let c=this.lastRequestedSegment.stream;this.playbackTracker=new Co(this.lastRequestedSegment),this.playback=this.playbackTracker.getPlayback(),this.requests=new fo(this.requestProcessQueueMicrotask,this.bandwidthCalculators,this.playback,this.config,this.eventTarget),this.p2pLoaders=new no(this.lastRequestedSegment.stream,this.requests,this.segmentStorage,this.config,this.webTorrentSocketPool,this.eventTarget,this.peerId,this.requestProcessQueueMicrotask),this.logger=(0,E.default)(`p2pml-core:hybrid-loader-${c.type}`),this.logger.color=`coral`,this.setIntervalLoading()}setIntervalLoading(){let e=this.p2pLoaders.currentLoader.connectedPeerCount,t=Math.random()*Do*e+Do;this.randomHttpDownloadTimeout=window.setTimeout(()=>{this.prefetchThroughHttp(),this.setIntervalLoading()},t)}loadSegment(e,t){var n=this;return T(function*(){n.logger(`requests: ${Wa(e)}`);let{stream:r}=e;r!==n.lastRequestedSegment.stream&&(n.logger(`stream changed to ${Ua(r)}`),n.p2pLoaders.changeCurrentLoader(r),n.levelChangedTimestamp=performance.now()),n.lastRequestedSegment=e;let i=n.playbackTracker.onSegmentRequested(e);n.syncPlayback(),i&&n.logger(`seek detected: buffer edge re-anchored`),n.segmentStorage.onSegmentRequested(r.swarmId,r.streamSwarmId,e.externalId,e.startTime,e.endTime,r.type,n.streamDetails.isLive);let a=new po(e,t);i&&a.markAsShouldBeStartedImmediately();try{var o;if(n.segmentStorage.hasSegment(r.swarmId,r.streamSwarmId,e.externalId)){let t=yield n.segmentStorage.getSegmentData(r.swarmId,r.streamSwarmId,e.externalId);if((t==null?void 0:t.byteLength)===0&&(n.logger(`storage returned an empty segment for ${Wa(e)}; loading it again`),a.markAsShouldBeStartedImmediately()),t&&t.byteLength>0){let{queueDownloadRatio:r}=n.generateQueue();a.resolve(t,n.getBandwidth(r)),n.playbackTracker.onSegmentDelivered(e),n.syncPlayback();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 ${Wa(e)} in ${Ua(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.playbackTracker.onSegmentDelivered(l),this.syncPlayback()),this.requests.remove(o),this.noteSegmentBytes(l,o.data.byteLength),this.logger(`succeed: ${Wa(l)} (byteLength: ${o.data.byteLength})`),this.segmentStorage.storeSegment(n.swarmId,n.streamSwarmId,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)}o.markHandledByProcessQueue();let{lastAttempt:f}=o.failedAttempts;f&&i-f.error.timestamp>Eo&&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.abortLastLoadingInQueueAfterItem(e,o,`http`))&&(s.cancel(),this.loadThroughHttp(o));continue}if(t&&(this.requests.executingHttpCount<r||this.abortLastLoadingInQueueAfterItem(e,o,`http`))){this.loadThroughHttp(o);continue}this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(o)&&(this.requests.executingP2PCount<i||this.abortLastLoadingInQueueAfterItem(e,o,`p2p`))&&this.loadThroughP2P(o)}else n.isP2PDownloadable&&(s==null?void 0:s.status)!==`loading`&&this.requests.executingP2PCount<i&&this.loadThroughP2P(o)}}c||this.prefetchThroughHttp()}abortSegmentRequest(e){var t;((t=this.engineRequest)==null?void 0:t.segment.runtimeId)===e&&(this.engineRequest.abort(),this.logger(`abort: `,Wa(this.engineRequest.segment)),this.engineRequest=void 0,this.requestProcessQueueMicrotask())}loadThroughHttp(e){new nn(this.requests.getOrCreateRequest(e),this.config,this.eventTarget).execute(),this.p2pLoaders.currentLoader.broadcastAnnouncement()}loadThroughP2P(e){this.p2pLoaders.currentLoader.downloadSegment(e)}prefetchThroughHttp(){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,highDemandTimeWindow:i}=this.config,a=this.p2pLoaders.currentLoader;if(!a.connectedPeerCount)return;this.syncPlayback();let o=Array.from(a.connectedPeerIds);for(let{segment:e,statuses:s}of mo(this.lastRequestedSegment,this.playback,this.config,a,t)){if(this.requests.executingHttpCount>=n)break;if(!s.isHttpDownloadable||s.isP2PDownloadable||this.segmentStorage.hasSegment(e.stream.swarmId,e.stream.streamSwarmId,e.externalId))continue;let t=this.requests.get(e);if(t&&(t.status===`loading`||t.status===`succeed`||t.failedAttempts.httpAttemptsCount>=r))continue;let a=yo(this.peerId,o,e.externalId);xo({rank:a,secondsToHighDemand:ma(e,this.playback).start-i*this.playback.rate,estimatedFetchSeconds:this.estimateFetchSeconds(e)})&&(this.logger(`prefetch ${Wa(e)} as ${a===0?`owner`:`backup #${a}`}`),this.loadThroughHttp(e))}}estimateFetchSeconds(e){var t,n;let{stream:r}=e,i=Math.max(0,e.endTime-e.startTime),a=(t=r.properties.bitrate)==null?0:t,o=(n=this.segmentBytesByStream.get(r.runtimeId))==null?a*i/8:n;if(o<=0)return i;let{http:s}=this.bandwidthCalculators,c=Math.max(s.getBandwidthLoadingOnly(10),s.getBandwidthLoadingOnly(30)),l=c>0?c:a;return l<=0?i:o*8/l}noteSegmentBytes(e,t){if(t<=0)return;let n=e.stream.runtimeId,r=this.segmentBytesByStream.get(n);this.segmentBytesByStream.set(n,r===void 0?t:r+Oo*(t-r))}abortLastLoadingInQueueAfterItem(e,t,n){for(let{segment:r}of mn(e)){if(r===t)break;let e=this.requests.get(r);if((e==null?void 0:e.downloadSource)===n&&e.status===`loading`)return e.cancel(),!0}return!1}getAvailableStorageCapacityPercent(){let{totalCapacity:e,usedCapacity:t}=this.segmentStorage.getUsage();return 100-t/e*100}generateQueue(){this.syncPlayback();let e=[],t=new Set,n=0,r=0,i=this.getAvailableStorageCapacityPercent();for(let o of mo(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,i)){var a;n++;let{segment:i}=o;if(this.segmentStorage.hasSegment(i.stream.swarmId,i.stream.streamSwarmId,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){var t;let{http:n,all:r}=this.bandwidthCalculators,i=(t=this.lastRequestedSegment.stream.properties.bitrate)==null?0:t;if(i===0)return r.getBandwidthLoadingOnly(3);let a=Math.max(r.getBandwidth(30,this.levelChangedTimestamp),r.getBandwidth(60,this.levelChangedTimestamp),r.getBandwidth(90,this.levelChangedTimestamp));if(e>=.8||a>=i*.9)return Math.max(r.getBandwidthLoadingOnly(1),r.getBandwidthLoadingOnly(3),r.getBandwidthLoadingOnly(5));let o=Math.max(n.getBandwidthLoadingOnly(1),n.getBandwidthLoadingOnly(3),n.getBandwidthLoadingOnly(5));return Math.max(a,o)}sendBroadcastAnnouncement(e=!1){this.p2pLoaders.currentLoader.broadcastAnnouncement(e)}updatePlayback(e){if(this.playbackTracker.report(e),!this.syncPlayback())return;if(this.oracleLogger.enabled){let{bufferEdge:e,bufferAhead:t,source:n}=this.playback;this.oracleLogger(`${this.lastRequestedSegment.stream.type} playhead≈${(e-t).toFixed(3)} (${n})`)}let{bufferEdge:t,bufferAhead:n,rate:r}=this.playback;this.segmentStorage.onPlaybackUpdated(t-n,r),this.requestProcessQueueMicrotask(!1)}syncPlayback(){let e=this.playbackTracker.getPlayback(),t=e.rate===0?this.playback.rate:e.rate,n=this.playback.bufferEdge!==e.bufferEdge||this.playback.bufferAhead!==e.bufferAhead||this.playback.rate!==t||this.playback.source!==e.source;return this.playback.bufferEdge=e.bufferEdge,this.playback.bufferAhead=e.bufferAhead,this.playback.rate=t,this.playback.source=e.source,n}updateStream(e){e===this.lastRequestedSegment.stream&&(this.logger(`update stream: ${Ua(e)}`),this.requestProcessQueueMicrotask())}destroy(){var e;clearTimeout(this.randomHttpDownloadTimeout),clearTimeout(this.initialHttpDelayTimeoutId),(e=this.engineRequest)==null||e.abort(),this.requests.destroy(),this.p2pLoaders.destroy()}};function Ao(e){let t=pn(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}function jo(e){var t;let n=e=>e==null?``:String(e),r=[(t=e.bitrate)==null?0:t,n(e.codecs),n(e.width),n(e.height),n(e.language),n(e.channels),n(e.name),n(e.frameRate),n(e.videoRange)].join(`-`);return btoa(Ao(r))}function Mo(e){let t=e.map(e=>w(w({},e.properties),{},{bitrate:void 0})),n=new Map,r=e.map((e,r)=>{var i;let a=`${e.type}|${jo(t[r])}`;return n.set(a,((i=n.get(a))==null?0:i)+1),a});return e.map((e,i)=>{var a;return((a=n.get(r[i]))==null?0:a)>1?e.properties:t[i]})}function No(e,t,n){return`v3-${e}-${t}-${n}`}function Po(e){return btoa(Ao(e).slice(0,15))}var Fo=2097151;function Io(e){let t=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),n=0;for(;n+8<=t.byteLength;){let e=t.getUint32(n),r=String.fromCharCode(t.getUint8(n+4),t.getUint8(n+5),t.getUint8(n+6),t.getUint8(n+7)),i=8;if(e===1){let r=Ro(t,n+8);if(r===void 0)return;e=r,i=16}else e===0&&(e=t.byteLength-n);if(e<i)return;if(r===`sidx`){let r=Lo(t,n+i,Math.min(n+e,t.byteLength));return r&&w({boxOffset:n,boxSize:e},r)}n+=e}}function Lo(e,t,n){if(t+12>n)return;let r=e.getUint8(t),i=e.getUint32(t+8),a=t+12,o,s;if(r===0){if(a+8>n)return;o=e.getUint32(a),s=e.getUint32(a+4),a+=8}else if(o=Ro(e,a),s=Ro(e,a+8),a+=16,o===void 0||s===void 0)return;if(a+4>n)return;let c=e.getUint16(a+2);if(a+=4,i===0)return;let l=[];for(let t=0;t<c;t++){if(a+12>n)return;let t=e.getUint32(a);l.push({referenceType:+(t>>>31==1),referencedSize:t&2147483647,subsegmentDuration:e.getUint32(a+4)}),a+=12}return{timescale:i,earliestPresentationTime:o,firstOffset:s,references:l}}function Ro(e,t){if(t+8>e.byteLength)return;let n=e.getUint32(t);if(!(n>Fo))return n*4294967296+e.getUint32(t+4)}function zo(e,t){return!e||e.start<=t.start&&e.end>=t.end}var Bo=class{constructor(){y(this,`streams`,new Map)}getStreams(){return Array.from(this.streams.values())}getStream(e){return this.streams.get(e)}apply(e){let t=[],n=Mo(e.streams);for(let[r,i]of e.streams.entries()){let a=this.upsertStream(i,e,n[r]);i.segments&&t.push(this.applySegments(a,i.segments,e.protocol))}return t}streamsAwaitingIndex(e,t){let n=Ot(e),r=[];for(let e of this.streams.values()){let i=e.indexSource;i.kind===`external`&&Ot(i.url)===n&&zo(t,i.byteRange)&&r.push(e)}return r}resolveExternalIndex(e,t,n){let r=[];for(let a of this.streamsAwaitingIndex(e,t)){var i;let e=a.indexSource;if(e.kind!==`external`)continue;let o=[],s=((i=t==null?void 0:t.start)==null?0:i)+n.boxOffset+n.boxSize+n.firstOffset,c=e.periodStart;for(let t of n.references){if(t.referenceType===1)continue;let r=t.subsegmentDuration/n.timescale;o.push({url:e.url,byteRange:{start:s,end:s+t.referencedSize-1},duration:r,sequence:o.length,presentationTime:c}),s+=t.referencedSize,c+=r}let l=this.streams.get(a.key);l&&r.push(this.applySegments(l,o,`dash`))}return r}upsertStream(e,t,n){var r,i,a,o,s;let c=this.resolveStreamKey(e,t),l=this.streams.get(c),u=!e.segments||!l,d={key:c,type:(r=l==null?void 0:l.type)==null?e.type:r,properties:u?e.properties:l.properties,identityHash:u?jo(n):l.identityHash,indexSource:e.indexSource,initSegment:(i=e.initSegment)==null?l==null?void 0:l.initSegment:i,isLive:(a=e.isLive)==null?l==null?void 0:l.isLive:a,segments:(o=l==null?void 0:l.segments)==null?new Map:o,timeline:(s=l==null?void 0:l.timeline)==null?new Map:s};return this.streams.set(c,d),d}resolveStreamKey(e,t){if(this.streams.has(e.key)||t.protocol!==`hls`||!e.segments)return e.key;let n=Ho(Ot(e.key));for(let e of this.streams.keys())if(Ho(Ot(e))===n)return e;return e.key}applySegments(e,t=[],n){let r=new Map,i=this.layoutTimeline(e,t,n);t.forEach((e,t)=>{let a=kt(e.url,e.byteRange),o=i[t];r.set(a,{key:a,url:e.url,byteRange:e.byteRange,externalId:Vo(e,n),startTime:o,endTime:o+e.duration})});let a=0,o=0;for(let t of e.segments.keys())r.has(t)||(e.segments.delete(t),o++);for(let[t,n]of r)e.segments.has(t)||a++,e.segments.set(t,n);let s=1/0,c=-1/0;for(let e of r.values())s=Math.min(s,e.startTime),c=Math.max(c,e.endTime);return{streamKey:e.key,type:e.type,isLive:e.isLive===!0,start:r.size?s:0,end:r.size?c:0,segmentCount:r.size,added:a,removed:o}}layoutTimeline(e,t,n){if(n===`dash`)return t.map(e=>{var t;return(t=e.presentationTime)==null?0:t});if(t.every(e=>e.programDateTime!==void 0))return t.map(e=>e.programDateTime/1e3);let{timeline:r}=e,i=t.findIndex(e=>r.has(e.sequence)),a=Array(t.length);if(i===-1){let n=0;if(r.size){var o,s;let t=Math.max(...r.keys());n=((o=r.get(t))==null?0:o)+((s=this.durationOf(e,t))==null?0:s)}for(let e=0;e<t.length;e++)a[e]=n,n+=t[e].duration}else{var c;a[i]=(c=r.get(t[i].sequence))==null?0:c;for(let e=i+1;e<t.length;e++)a[e]=a[e-1]+t[e-1].duration;for(let e=i-1;e>=0;e--)a[e]=a[e+1]-t[e].duration}if(t.forEach((e,t)=>r.set(e.sequence,a[t])),r.size>t.length*4){let e=new Set(t.map(e=>e.sequence));for(let t of r.keys())e.has(t)||r.delete(t)}return a}durationOf(e,t){for(let n of e.segments.values())if(n.externalId===t)return n.endTime-n.startTime}};function Vo(e,t){var n;return t===`dash`?Math.round(((n=e.presentationTime)==null?0:n)*10):e.sequence}function Ho(e){let t=e.indexOf(`?`);return t===-1?e:e.slice(0,t)}var Uo=(e,t)=>`${e}|${t}`,Wo=e=>/Android/i.test(e),Go=e=>/iPad|iPhone/i.test(e),Ko=e=>/Android/i.test(e)&&(/; wv\)/i.test(e)||!/Chrome|Firefox/i.test(e)),qo=1048576,Jo=class{constructor(){y(this,`userAgent`,navigator.userAgent),y(this,`segmentMemoryStorageLimit`,4096),y(this,`currentStorageUsage`,0),y(this,`cache`,new Map),y(this,`logger`,void 0),y(this,`coreConfig`,void 0),y(this,`mainStreamConfig`,void 0),y(this,`secondaryStreamConfig`,void 0),y(this,`currentPlayback`,void 0),y(this,`lastRequestedSegment`,void 0),y(this,`segmentChangeCallback`,void 0),this.logger=(0,E.default)(`p2pml-core:segment-memory-storage`),this.logger.color=`RebeccaPurple`}initialize(e,t,n){var r=this;return T(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={streamSwarmId: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 T(function*(){c.clear(s,r.byteLength);let e=Uo(t,n);if(c.cache.set(e,{data:r,segmentId:n,streamSwarmId: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 T(function*(){let e=Uo(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/qo}}hasSegment(e,t,n){let r=Uo(t,n);return this.cache.get(r)!==void 0}getStoredSegmentIds(e,t){let n=[];for(let{segmentId:e,streamSwarmId: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{streamSwarmId:r,segmentId:a,data:o}=i,s=Uo(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/qo>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}increaseStorageUsage(e){this.currentStorageUsage+=e/qo}decreaseStorageUsage(e){this.currentStorageUsage-=e/qo}setMemoryStorageLimit(){var e;if((e=this.coreConfig)!=null&&e.segmentMemoryStorageLimit){this.segmentMemoryStorageLimit=this.coreConfig.segmentMemoryStorageLimit;return}Ko(this.userAgent)||Go(this.userAgent)?this.segmentMemoryStorageLimit=1024:Wo(this.userAgent)&&(this.segmentMemoryStorageLimit=2048)}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}},Yo=`-PM${$o(`5.0.0-alpha.1`)}-`,Xo=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`,Zo=20;function Qo(e){let t=[e],n=Zo-e.length;for(let e=0;e<n;e++)t.push(Xo[Math.floor(Math.random()*62)]);return t.join(``)}function $o(e){let t=e.split(`.`);return`${`00${t[0]}`.slice(-2)}${`00${t[1]}`.slice(-2)}`}var es=new WeakMap,Z=new WeakMap,Q=new WeakMap,ts=new WeakMap,ns=new WeakMap,$=new WeakMap,rs=new WeakMap,is=new WeakMap,as=new WeakMap,os=new WeakMap,ss=new WeakSet,cs=class{constructor(e){var t,n,r;O(this,ss),x(this,es,void 0),x(this,Z,`disconnected`),x(this,Q,null),x(this,ts,0),x(this,ns,null),x(this,$,new ai),x(this,rs,()=>{C(Z,this)!==`disposed`&&(k(Z,this,`connected`),k(ts,this,0),C($,this).dispatchEvent(`connected`))}),x(this,is,()=>{C(Z,this)!==`disposed`&&(C(Q,this)&&(C(Q,this).onopen=null,C(Q,this).onclose=null,C(Q,this).onerror=null,C(Q,this).onmessage=null,k(Q,this,null)),S(ss,this,ls).call(this),C($,this).dispatchEvent(`disconnected`))}),x(this,as,e=>{C(Z,this)!==`disposed`&&C($,this).dispatchEvent(`error`,e)}),x(this,os,e=>{C(Z,this)!==`disposed`&&C($,this).dispatchEvent(`message`,e.data)});let i=Math.max(100,(t=e.initialDelay)==null?1e3:t);k(es,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 C(Z,this)}addEventListener(e,t){C($,this).addEventListener(e,t)}removeEventListener(e,t){C($,this).removeEventListener(e,t)}connect(){if(C(Z,this)!==`connected`&&C(Z,this)!==`connecting`&&C(Z,this)!==`disposed`){k(Z,this,`connecting`),S(ss,this,us).call(this);try{k(Q,this,new WebSocket(C(es,this).url)),C(Q,this).binaryType=`arraybuffer`,C(Q,this).onopen=C(rs,this),C(Q,this).onclose=C(is,this),C(Q,this).onerror=C(as,this),C(Q,this).onmessage=C(os,this)}catch(e){k(Z,this,`disconnected`);let t=new ErrorEvent(`error`,{message:e instanceof Error?e.message:`Unknown WebSocket creation error`,error:e});C($,this).dispatchEvent(`error`,t)}}}send(e){if(C(Z,this)!==`connected`||!C(Q,this))throw Error(`WebSocketClient: Cannot send data when not connected`);C(Q,this).send(e)}dispose(){k(Z,this,`disposed`),S(ss,this,us).call(this),C(Q,this)&&(C(Q,this).onopen=null,C(Q,this).onclose=null,C(Q,this).onerror=null,C(Q,this).onmessage=null,C(Q,this).close(),k(Q,this,null)),C($,this).clear()}};function ls(){if(C(Z,this)===`disposed`)return;k(Z,this,`reconnecting`);let e=Math.min(C(es,this).initialDelay*Math.pow(2,C(ts,this)),C(es,this).maxDelay),t=e*C(es,this).jitterMultiplier,n=Math.random()*2*t-t,r=Math.max(0,e+n);if(e<C(es,this).maxDelay){var i;k(ts,this,(i=C(ts,this),i++,i))}k(ns,this,setTimeout(()=>{C(Z,this)!==`disposed`&&this.connect()},r)),C($,this).dispatchEvent(`reconnecting`)}function us(){C(ns,this)!==null&&(clearTimeout(C(ns,this)),k(ns,this,null))}var ds=new WeakMap,fs=new WeakMap,ps=class{constructor(){x(this,ds,new Map),x(this,fs,new ai)}addEventListener(e,t){C(fs,this).addEventListener(e,t)}removeEventListener(e,t){C(fs,this).removeEventListener(e,t)}acquire(e){let t=C(ds,this).get(e);if(!t){let n=new cs({url:e});n.addEventListener(`error`,t=>{C(fs,this).dispatchEvent(`error`,t,e)}),n.connect(),t={client:n,refCount:0},C(ds,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}`),C(ds,this).get(e)===t&&C(ds,this).delete(e),t.client.dispose()))}}}destroy(){C(fs,this).clear();let e=Array.from(C(ds,this).values());C(ds,this).clear();for(let t of e)try{t.client.dispose()}catch(e){console.error(`[WebTorrentSocketPool] Failed to dispose WebSocketClient:`,e)}}};function ms(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.includes(r))continue;n[r]=e[r]}return n}function hs(e,t){if(e==null)return{};var n,r,i=ms(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.includes(n)||{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}var gs=[`segments`],_s=class e{constructor(t){var n;y(this,`eventTarget`,new ai),y(this,`manifestResponseUrl`,void 0),y(this,`streams`,new Map),y(this,`failedStreamKeys`,new Set),y(this,`initSegmentKeys`,new Set),y(this,`mainStreamConfig`,void 0),y(this,`secondaryStreamConfig`,void 0),y(this,`commonCoreConfig`,void 0),y(this,`bandwidthCalculators`,{all:new Br,http:new Br}),y(this,`segmentStorage`,void 0),y(this,`webTorrentSocketPool`,new ps),y(this,`logger`,(0,E.default)(`p2pml-core:core`)),y(this,`socketPoolLogger`,(0,E.default)(`p2pml-core:webtorrent-socket-pool`)),y(this,`peerId`,void 0),y(this,`mainStreamLoader`,void 0),y(this,`secondaryStreamLoader`,void 0),y(this,`streamDetails`,{isLive:!1}),y(this,`storageInitPromise`,void 0),y(this,`manifestParsers`,void 0),y(this,`manifestRegistry`,new Bo),y(this,`manifestLogger`,(0,E.default)(`p2pml-core:manifest`)),y(this,`registryMissLogger`,(0,E.default)(`p2pml-core:registry-miss`));let r=_n(t==null?{}:t);this.commonCoreConfig=bn({defaultConfig:e.DEFAULT_COMMON_CORE_CONFIG,baseConfig:r}),this.mainStreamConfig=bn({defaultConfig:e.DEFAULT_STREAM_CONFIG,baseConfig:r,specificStreamConfig:r.mainStream}),this.secondaryStreamConfig=bn({defaultConfig:e.DEFAULT_STREAM_CONFIG,baseConfig:r,specificStreamConfig:r.secondaryStream}),this.peerId=Qo(this.commonCoreConfig.trackerClientVersionPrefix),this.manifestParsers=(n=t==null?void 0:t.manifestParsers)==null?[]:n,this.webTorrentSocketPool.addEventListener(`error`,(e,t)=>{this.socketPoolLogger(`WebSocket error for tracker url ${t}:`,e)})}getConfig(){return w(w({},vn(this.commonCoreConfig)),{},{mainStream:vn(this.mainStreamConfig),secondaryStream:vn(this.secondaryStreamConfig)})}applyDynamicConfig(e){let{mainStream:t,secondaryStream:n}=e,r=vn(this.mainStreamConfig),i=vn(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=vs(e)}processManifest(e){let t=typeof e.data==`string`?e.data:new TextDecoder().decode(e.data),n=e.protocol?this.manifestParsers.find(t=>t.protocol===e.protocol):this.manifestParsers.find(e=>e.canParse(t));if(!n){this.manifestLogger(`no parser for manifest %s`,e.url);return}let r;try{r=this.manifestRegistry.apply(n.parse(t,e.url))}catch(t){this.manifestLogger(`failed to parse %s: %O`,e.url,t);return}return this.manifestResponseUrl!=null||(this.manifestResponseUrl=vs(e.url)),this.syncStreamsFromRegistry(),this.logRegistryUpdates(e.url,r),ys(r)}processSegmentIndex(e){let t=Io(e.data);if(!t){this.manifestLogger(`no sidx box in the index fetched from %s`,e.url);return}let n=this.manifestRegistry.resolveExternalIndex(e.url,e.byteRange,t);if(!n.length){this.manifestLogger(`no stream awaits an index at %s`,e.url);return}return this.syncStreamsFromRegistry(),this.logRegistryUpdates(e.url,n),ys(n)}isSegmentIndex(e,t){return this.manifestRegistry.streamsAwaitingIndex(e,t).length>0}logRegistryUpdates(e,t){if(!this.manifestLogger.enabled)return;let n=t.filter(e=>e.added||e.removed);this.manifestLogger(`%s — %d streams registered, %s`,e,this.streams.size,n.length?n.map(e=>`${e.streamKey}: +${e.added} -${e.removed}`).join(`, `):`no segment changes`)}syncStreamsFromRegistry(){let e=!1;for(let t of this.manifestRegistry.getStreams()){if(e||(e=t.isLive===!0),t.initSegment){let{url:e,byteRange:n}=t.initSegment;this.initSegmentKeys.add(kt(e,n))}let n=this.streams.get(t.key);!n&&(this.failedStreamKeys.has(t.key)||(n=this.registerStream(t),!n))||this.syncSegments(n,t)}this.streamDetails.isLive=e}syncSegments(e,t){var n,r;let i=!1;for(let n of e.segments.keys())t.segments.has(n)||(e.segments.delete(n),i=!0);for(let[n,r]of t.segments)e.segments.has(n)||(e.segments.set(n,{runtimeId:n,externalId:r.externalId,url:r.url,byteRange:r.byteRange,startTime:r.startTime,endTime:r.endTime,stream:e}),i=!0);i&&((n=this.mainStreamLoader)==null||n.updateStream(e),(r=this.secondaryStreamLoader)==null||r.updateStream(e))}hasSegment(e,t){return!!ua(this.streams,kt(e,t))}getStream(e){let t=this.streams.get(e);return t&&this.toStreamSnapshot(t)}getStreams(){return Array.from(this.streams.values(),e=>this.toStreamSnapshot(e))}toStreamSnapshot(e){let{segments:t}=e;return hs(e,gs)}registerStream(e){let t=Object.freeze(w({},e.properties));try{return this.addStream(e,t)}catch(n){this.failedStreamKeys.add(e.key),this.logger(`failed to register stream %s: %O`,e.key,n),this.eventTarget.dispatchEvent(`onStreamRegistrationError`,{runtimeId:e.key,streamType:e.type,properties:t,error:n instanceof Error?n:Error(String(n))});return}}addStream(e,t){var n;let r=e.type===`main`?this.mainStreamConfig:this.secondaryStreamConfig,i=(n=r.swarmId)==null?this.manifestResponseUrl:n;if(i===void 0)throw Error(`Failed to register stream: no swarmId is configured and no manifest has named the swarm.`);let{identityHash:a}=e,o=No(i,e.type,a);if(r.streamSwarmIdBuilder){let n=r.streamSwarmIdBuilder({swarmId:i,runtimeId:e.key,streamType:e.type,properties:t,identityHash:a,defaultStreamSwarmId:o,peerProtocolVersion:`v3`});if(n!==void 0){if(typeof n!=`string`||n===``)throw Error(`streamSwarmIdBuilder must return a non-empty string or undefined`);o=n}}for(let t of this.streams.values())if(t.streamSwarmId===o&&(t.swarmId!==i||t.type!==e.type||t.identityHash!==a))throw Error(`streamSwarmIdBuilder produced the same stream swarm ID ("${o}") for streams with different identities. Peers of these streams would exchange segments of the wrong stream.`);let s={runtimeId:e.key,type:e.type,properties:t,swarmId:i,identityHash:a,streamSwarmId:o,infoHash:Po(o),segments:new Map};return this.streams.set(e.key,s),this.eventTarget.dispatchEvent(`onStreamAdded`,{stream:this.toStreamSnapshot(s)}),s}loadSegment(e){var t=this;return T(function*(e,n={}){let r=kt(e,n.byteRange),{signal:i}=n;if(i!=null&&i.aborted||(yield t.initializeSegmentStorage(),i!=null&&i.aborted))throw new qt(`aborted`);let a=t.identifySegment(r),o=t.getStreamHybridLoader(a);return new Promise((e,t)=>{let n={onSuccess:t=>{i==null||i.removeEventListener(`abort`,s),e(t)},onError:e=>{i==null||i.removeEventListener(`abort`,s),t(e)}},s=()=>o.abortSegmentRequest(r);i==null||i.addEventListener(`abort`,s),o.loadSegment(a,n)})}).apply(this,arguments)}abortSegmentLoading(e,t){var n,r;let i=kt(e,t);(n=this.mainStreamLoader)==null||n.abortSegmentRequest(i),(r=this.secondaryStreamLoader)==null||r.abortSegmentRequest(i)}updatePlayback(e){var t,n;(t=this.mainStreamLoader)==null||t.updatePlayback(e),(n=this.secondaryStreamLoader)==null||n.updatePlayback(e)}isSegmentLoadable(e,t){let n=kt(e,t),r=ua(this.streams,n);return r?!(r.stream.type===`main`?this.mainStreamConfig:this.secondaryStreamConfig).isP2PDisabled:(!this.initSegmentKeys.has(n)&&!this.isSegmentIndex(e,t)&&(this.registryMissLogger(`%s`,n),this.eventTarget.dispatchEvent(`onSegmentRegistryMiss`,{url:e,byteRange:t})),!1)}destroy(){var e,t,n,r;this.manifestRegistry=new Bo,this.streams.clear(),this.failedStreamKeys.clear(),this.initSegmentKeys.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},this.storageInitPromise=void 0,this.webTorrentSocketPool.destroy()}initializeSegmentStorage(){var e=this;return T(function*(){if(!e.segmentStorage){if(e.storageInitPromise)return e.storageInitPromise;e.storageInitPromise=T(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 Jo;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){let t=ua(this.streams,e);if(!t)throw Error(`Segment is not in the registry: ${e}`);return t}overrideAllConfigs(e,t,n){let r=this.stripStaticOnlyProps(e),i=t&&this.stripStaticOnlyProps(t),a=n&&this.stripStaticOnlyProps(n);yn(this.commonCoreConfig,r),yn(this.mainStreamConfig,r),yn(this.secondaryStreamConfig,r),i&&yn(this.mainStreamConfig,i),a&&yn(this.secondaryStreamConfig,a)}stripStaticOnlyProps(e){if(!(`swarmId`in e)&&!(`streamSwarmIdBuilder`in e))return e;this.logger(`swarmId and streamSwarmIdBuilder cannot be changed at runtime; ignoring them in the dynamic configuration update`);let t=w({},e);return delete t.swarmId,delete t.streamSwarmIdBuilder,t}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.segmentStorage)throw Error(`Segment storage is not initialized`);let t=e.stream.type===`main`?this.mainStreamConfig:this.secondaryStreamConfig;return new ko(e,this.streamDetails,t,this.bandwidthCalculators,this.segmentStorage,this.webTorrentSocketPool,this.eventTarget,this.peerId)}};y(_s,`DEFAULT_COMMON_CORE_CONFIG`,{segmentMemoryStorageLimit:void 0,customSegmentStorageFactory:void 0,trackerClientVersionPrefix:Yo}),y(_s,`DEFAULT_STREAM_CONFIG`,{isP2PUploadDisabled:!1,isP2PDisabled:!1,simultaneousHttpDownloads:2,simultaneousP2PDownloads:3,highDemandTimeWindow:15,httpDownloadInitialTimeoutMs:0,httpDownloadTimeWindow:3e3,p2pDownloadTimeWindow:6e3,webRtcMaxMessageSize:65535,p2pNotReceivingBytesTimeoutMs:2e3,p2pInactiveLoaderDestroyTimeoutMs:3e4,httpNotReceivingBytesTimeoutMs:3e3,httpErrorRetries:3,p2pErrorRetries:3,announceTrackers:[`wss://tracker.webtorrent.dev`,`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,streamSwarmIdBuilder:void 0,p2pMaxPeers:50,p2pChurnMaxPeersMultiplier:1.5,p2pChurnCleanupIntervalMs:3e4,p2pChurnGracePeriodMs:15e3,webRtcOffersCount:5,webRtcOfferTimeoutMs:5e4,webRtcIceGatheringTimeoutMs:5e3,webRtcConnectionTimeoutMs:15e3});function vs(e){return e.split(`?`)[0]}function ys(e){return{streams:e.map(e=>({key:e.streamKey,type:e.type,isLive:e.isLive,start:e.start,end:e.end,segmentCount:e.segmentCount}))}}function bs(e,t){for(let{start:n,end:r}of e)if(n<=t&&t<=r)return Math.max(0,r-t);return 0}function xs(e){let{buffered:t,currentTime:n}=e,r=[];for(let e=0;e<t.length;e++)r.push({start:t.start(e),end:t.end(e)});return{bufferAhead:bs(r,n),rate:e.paused?0:e.playbackRate}}var Ss=60,Cs=1;function ws(e){let t;for(let n of e.streams){if(!n.isLive||n.type!==`main`||n.segmentCount===0)continue;let e=n.end-n.start;if(!(e>0))continue;let r=e/n.segmentCount,i=Math.max(r,Math.min(e-Cs*r,Ss));(!t||i>t.delay)&&(t={delay:i,segment:r})}return t}var Ts={MPD:`MPD`,INIT_SEGMENT:`InitializationSegment`,MEDIA_SEGMENT:`MediaSegment`,INDEX_SEGMENT:`IndexSegment`},Es=new Set([Ts.INIT_SEGMENT,Ts.MEDIA_SEGMENT,Ts.INDEX_SEGMENT]);function Ds(e,t={}){return function(){let{parent:n}=this,r=new Os(e,{load:n.load.bind(n),abort:n.abort.bind(n)},t);return{load:(e,t)=>r.load(e,t),abort:()=>r.abort()}}}var Os=class{constructor(e,t,n){y(this,`core`,void 0),y(this,`parent`,void 0),y(this,`hooks`,void 0),y(this,`logger`,(0,E.debug)(`p2pml-dashjs:loader`)),y(this,`abortCurrent`,void 0),this.core=e,this.parent=t,this.hooks=n}load(e,t){var n,r,i,a,o;let s=(n=(r=e.customData)==null||(r=r.request)==null?void 0:r.type)==null?void 0:n,{url:c}=e,l=jt((i=(a=e.headers)==null?void 0:a.Range)==null?(o=e.headers)==null?void 0:o.range:i);if(s===Ts.MPD)return this.passThroughAndObserve(e,t,e=>{var n,r;if(typeof e!=`string`&&!ks(e))return;let i=t.url,a=this.core.processManifest({url:i!==void 0&&i!==``?i:c,data:e});a&&((n=(r=this.hooks).onManifestProcessed)==null||n.call(r,a))});if(s!==void 0&&Es.has(s)){if(this.core.isSegmentIndex(c,l))return this.passThroughAndObserve(e,t,e=>{ks(e)&&this.core.processSegmentIndex({url:c,byteRange:l,data:e})});if(s===Ts.MEDIA_SEGMENT&&this.core.isSegmentLoadable(c,l))return this.serve(e,t,l),!0}return this.parent.load(e,t)}abort(){var e;(e=this.abortCurrent)==null||e.call(this),this.parent.abort()}passThroughAndObserve(e,t,n){e.customData!=null||(e.customData={});let{customData:r}=e,i=r.onloadend;return r.onloadend=()=>{try{t.status>=200&&t.status<=299&&n(t.data)}catch(t){this.logger(`failed to process %s: %O`,e.url,t)}i==null||i()},this.parent.load(e,t)}serve(e,t,n){let{url:r}=e;e.customData!=null||(e.customData={});let{customData:i}=e,a=!1,o=()=>{a||this.core.abortSegmentLoading(r,n)};i.abort=o,this.abortCurrent=o,this.core.loadSegment(r,{byteRange:n}).then(({data:e,bandwidth:n})=>{var o,s,c;a=!0,t.url=r,t.status=200,t.statusText=`OK`,t.headers={},t.data=e;let l=e.byteLength;(o=i.onprogress)==null||o.call(i,{lengthComputable:!0,loaded:0,total:l,time:1}),(s=i.onprogress)==null||s.call(i,{lengthComputable:!0,loaded:l,total:l,time:As(n,l)}),(c=i.onloadend)==null||c.call(i)}).catch(e=>{var n;if(a=!0,e instanceof qt&&e.type===`aborted`){var o;(o=i.onabort)==null||o.call(i);return}t.url=r,t.status=0,t.statusText=e instanceof Error?e.message:String(e),t.data=void 0,this.logger(`core failed to load %s: %O`,r,e),(n=i.onloadend)==null||n.call(i)})}};function ks(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}function As(e,t){return e<=0?1:Math.max(1,Math.round(t*8*1e3/e))}var js=25,Ms=2,Ns=1,Ps=`streamInitialized`,Fs=`streamTeardownComplete`,Is=[`timeupdate`,`progress`,`seeking`,`seeked`,`ratechange`,`play`,`pause`,`waiting`],Ls=class{constructor(e){var t,n;y(this,`player`,void 0),y(this,`media`,void 0),y(this,`core`,void 0),y(this,`managesLiveDelay`,!1),y(this,`debug`,(0,E.debug)(`p2pml-dashjs:engine`)),y(this,`applyLivePlacement`,e=>{var t;if(!this.player||!this.managesLiveDelay)return;let n=ws(e);if(!n)return;let r=(t=this.player.getSettings().streaming)==null||(t=t.delay)==null?void 0:t.liveDelay;if(r!==void 0&&!Number.isNaN(r)&&Math.abs(r-n.delay)<n.segment/2)return;let i=this.forwardBufferSettings(n);this.debug(`Setting liveDelay to ${n.delay}, forward buffer to ${i.bufferTimeDefault}`),this.player.updateSettings({streaming:{delay:{liveDelay:n.delay},buffer:i}})}),y(this,`handleStreamInitialized`,()=>{this.registerMediaElement()}),y(this,`handleStreamTeardown`,()=>{this.core.destroy(),this.unregisterMediaElement()}),y(this,`handlePlaybackUpdate`,e=>{let t=e.target;this.core.updatePlayback(xs(t))}),this.core=new _s(w(w({},e==null?void 0:e.core),{},{manifestParsers:(t=e==null||(n=e.core)==null?void 0:n.manifestParsers)==null?[Mt]:t}))}bindPlayer(e){var t;if(this.player===e)return;this.player&&this.destroy(),this.player=e;let n=(t=e.getSettings().streaming)==null||(t=t.delay)==null?void 0:t.liveDelay;this.managesLiveDelay=n===void 0||Number.isNaN(n),this.managesLiveDelay&&e.updateSettings({streaming:{delay:{liveDelay:js,useSuggestedPresentationDelay:!1}}}),e.extend(`XHRLoader`,Ds(this.core,{onManifestProcessed:this.applyLivePlacement}),!0),e.on(Ps,this.handleStreamInitialized),e.on(Fs,this.handleStreamTeardown),this.registerMediaElement()}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)}forwardBufferSettings(e){var t;let{mainStream:n,secondaryStream:r}=this.core.getConfig(),i=Math.max(n.highDemandTimeWindow,r.highDemandTimeWindow),a=Math.max(e.segment*Ms,Math.min(i,e.delay-e.segment*Ns)),o=(t=this.player)==null||(t=t.getSettings().streaming)==null?void 0:t.buffer,s=e=>e===void 0||Number.isNaN(e)||e>a?a:e;return{bufferTimeDefault:s(o==null?void 0:o.bufferTimeDefault),bufferTimeAtTopQuality:s(o==null?void 0:o.bufferTimeAtTopQuality),bufferTimeAtTopQualityLongForm:s(o==null?void 0:o.bufferTimeAtTopQualityLongForm)}}registerMediaElement(){let e;try{var t;e=(t=this.player)==null?void 0:t.getVideoElement()}catch(e){return}if(e&&e!==this.media){this.unregisterMediaElement(),this.media=e;for(let t of Is)e.addEventListener(t,this.handlePlaybackUpdate)}}unregisterMediaElement(){let{media:e}=this;if(e){for(let t of Is)e.removeEventListener(t,this.handlePlaybackUpdate);this.media=void 0}}destroy(){this.core.destroy(),this.unregisterMediaElement(),this.player&&(this.player.off(Ps,this.handleStreamInitialized),this.player.off(Fs,this.handleStreamTeardown)),this.player=void 0}};return e.Core=_s,e.DashJsP2PEngine=Ls,e})({});
2
+ //# sourceMappingURL=p2p-media-loader-dashjs.iife.min.js.map