function t(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{c(i.next(t))}catch(t){s(t)}}function a(t){try{c(i.throw(t))}catch(t){s(t)}}function c(t){var e;t.done?r(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}c((i=i.apply(t,e||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const e=new TextDecoder;function n(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{c(i.next(t))}catch(t){s(t)}}function a(t){try{c(i.throw(t))}catch(t){s(t)}}function c(t){var e;t.done?r(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(o,a)}c((i=i.apply(t,e||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const i=new TextDecoder,r=new TextEncoder,s=performance,o=()=>{};function a(){return Math.floor(s.now())}function c(t=("undefined"==typeof location?void 0:location)){if(!t)return{};try{t=new URL(t).searchParams}catch(e){"string"==typeof t&&(t.startsWith("?")&&(t=t.substring(1)),t=new URLSearchParams(t))}return l(t,{withType:!0,noEmptyString:!0})}function l(t,e){e=Object.assign({withType:!1,noEmptyString:!1},e);const n={};if(!t)return n;for(const[i,r]of u(t)){if(t=r,e.withType&&null!=t&&t.substring)if(t){const e=Number(t);if(isNaN(e))switch(t.toLowerCase()){case"true":t=!0;break;case"false":t=!1;break;case"null":t=null;break;case"undefined":t=void 0}else t=e}else e.noEmptyString&&(t=!0);n[i]?(Array.isArray(n[i])||(n[i]=new Array(n[i])),n[i].push(t)):n[i]=t}return n}function u(t){return t?("function"==typeof t.entries&&(t=t.entries()),"function"==typeof t[Symbol.iterator]?t:function*(){for(const e in t)yield[e.toString(),t[e]]}()):function*(){}()}function h(t){return r.encode(t)}function d(t,e){return n(this,void 0,void 0,function*(){const n=yield self.fetch(t,e);return n.ok||(n.body&&(n.error=yield n.text()),n.error||(n.error=n.statusText||n.status.toString()||"Unknown error")),n})}function f(t){const e=t.lastIndexOf(".");return e>=0&&e>t.lastIndexOf("/")?t.substring(e):""}function p(t){return t.substring(t.lastIndexOf("/")+1)}function m(t){const e=t.lastIndexOf("."),n=t.lastIndexOf("/")+1;return e>=0&&e>=n?t.substring(n,e):t.substring(n)}function g(t){const e=[];for(let n=0;n<t.length;++n)e.push(t.charCodeAt(n));return e}function _(t,e=" "){const n=g(e);let i=0;for(;i<t.length&&n.includes(t.charCodeAt(i));)++i;return t.substring(i)}var v,y=Object.freeze({__proto__:null,EMPTY_FUNCTION:o,caseInsensitive:function(t){return new Proxy(t,{get(t,e,n){if("string"==typeof e){const i=Object.keys(t).find(t=>t.toLowerCase()===e.toLowerCase());if(void 0!==i)return Reflect.get(t,i,n)}return Reflect.get(t,e,n)}})},equal:function t(e,n,i=new WeakMap){if(e===n)return!0;if(Number.isNaN(e)&&Number.isNaN(n))return!0;if(Object(e)!==e||Object(n)!==n)return!1;if(i.has(e))return i.get(e)===n;i.set(e,n);const r=Object.prototype.toString.call(e);if(r!==Object.prototype.toString.call(n))return!1;switch(r){case"[object Date]":return e.getTime()===n.getTime();case"[object RegExp]":return e.source===n.source&&e.flags===n.flags;case"[object Set]":case"[object Map]":{if(e.size!==n.size)return!1;const i=e.keys(),r=e.keys(),s=e.values(),o=n.values();let a;for(;!(a=i.next()).done;){if(!t(a.value,r.next().value))return!1;const e=s.next().value,n=o.next().value;if(e!==a&&!t(e,n))return!1}return!0}}if(Array.isArray(e)){if(!Array.isArray(n)||e.length!==n.length)return!1;for(let r=0;r<e.length;r++)if(!t(e[r],n[r],i))return!1;return!0}const s=[...Object.keys(e),...Object.getOwnPropertySymbols(e)];if(s.length!==Object.keys(n).length+Object.getOwnPropertySymbols(n).length)return!1;for(const r of s)if(!t(e[r],n[r],i))return!1;return!0},fetch:d,fetchWithRTT:function(t,e){return n(this,void 0,void 0,function*(){yield d(t,Object.assign(Object.assign({},e),{method:"OPTIONS"}));const n=a(),i=yield d(t,e);i.rtt=a()-n;let r=Number(i.headers.get("Response-Delay"))||0;if(!r){const t=i.headers.get("cmsd-dynamic");if(t)for(const e of t.split(";")){const[t,n]=e.split("=");"rd"===t.trim().toLowerCase()&&(r=Number(n)||r)}}return i.rtt=Math.max(1,i.rtt-r),i})},getBaseFile:m,getExtension:f,getFile:p,iterableEntries:u,objectFrom:l,options:c,safePromise:function(t,e){let n;return Promise.race([e instanceof Promise?e:new Promise(e),new Promise((e,i)=>n=setTimeout(()=>i("timed out in "+t+"ms"),t))]).finally(()=>clearTimeout(n))},sleep:function(t){return n(this,void 0,void 0,function*(){return new Promise(e=>{setTimeout(e,t)})})},stringify:function t(e,n={}){if(n=Object.assign({space:" ",decimal:2,recursion:2,noBin:!1},n),null==e)return String(e);const r=e.error||e.message;if(r&&(e=r),e.toFixed)return e.toFixed(Number(n.decimal)||0);if(null!=e.byteLength&&(null==e?void 0:e[Symbol.iterator]))return n.noBin?"["+e.byteLength+"#bytes]":i.decode(e);if("boolean"==typeof e||e.substring||!n.recursion)return"object"==typeof e?Object.prototype.toString.call(e):String(e);const s=n.space;if(e instanceof Set){let i="Set[",r=!0;for(const o of e.values())r||(i+=","+s),r=!1,i+=t(o,Object.assign(Object.assign({},n),{recursion:n.recursion-1}));return i+"]"}if(e instanceof Map){let i="Map{",r=!0;for(const[o,a]of e.entries())r||(i+=","+s),r=!1,i+=t(o,Object.assign(Object.assign({},n),{recursion:n.recursion-1})),i+=":"+t(a,Object.assign(Object.assign({},n),{recursion:n.recursion-1}));return i+"}"}if(Array.isArray(e)){let i="[",r=!0;for(const o of e)r||(i+=","+s),r=!1,i+=t(o,Object.assign(Object.assign({},n),{recursion:n.recursion-1}));return i+"]"}let o="{",a=!0;for(const i in e)a||(o+=","+s),a=!1,o+=i+":",o+=t(e[i],Object.assign(Object.assign({},n),{recursion:n.recursion-1}));return o+"}"},time:a,toBin:h,trim:function(t,e=" "){const n=g(e);let i=0;for(;i<t.length&&n.includes(t.charCodeAt(i));)++i;let r=t.length;for(;r>0&&n.includes(t.charCodeAt(r-1));)--r;return t.substring(i,r)},trimEnd:function(t,e=" "){const n=g(e);let i=t.length;for(;i>0&&n.includes(t.charCodeAt(i-1));)--i;return t.substring(0,i)},trimStart:_,unixTime:function(){return Math.floor(s.timeOrigin+s.now())}});!function(t){t.ERROR="error",t.WARN="warn",t.INFO="info",t.DEBUG="debug"}(v||(v={}));let b=0;setInterval(()=>{console.assert(0===b,b.toFixed(),"calls to log was useless")},1e4);const S=c()["!cb-override-log-level"],w=new Array(128);w[101]=w[69]=1,w[119]=w[87]=2,w[105]=w[73]=3,w[100]=w[68]=4;class T{get error(){return this._bind(v.ERROR)}get warn(){return this._bind(v.WARN)}get info(){return this._bind(v.INFO)}get debug(){return this._bind(v.DEBUG)}constructor(t,...e){e.length||e.push(void 0),this._args=e,this._log=t,++b}_onLog(t,e){var n,i;const r=null!==(i=null!==(n=null!=S?S:t.level)&&void 0!==n?n:E.level)&&void 0!==i?i:v.INFO;return!1!==r&&(!(!0!==r&&w[e.charCodeAt(0)]>w[r.charCodeAt(0)])&&(t.on&&t.on(e,this._args),!!this._args.length))}_bind(t){return this._done||(this._done=!0,--b),this._onLog(E,t)&&(this._log===E||this._onLog(this._log,t))?console[t].bind(console,...this._args):o}}class C{constructor(){this.log=(...t)=>new T(this.log,...t)}}const E=(...t)=>new T(E,...t);class R{onBytes(t){}get interval(){return this._interval}set interval(t){this._interval=t,this.updateSamples()}constructor(t=1e3){this._interval=t,this.clear()}value(){return Math.round(this.exact())}exact(){this.updateSamples();const t=a()-this._time;return t?this._bytes/t*1e3:0}addBytes(t){var e;const n=a(),i=this.updateSamples(n)[this._samples.length-1];if(n>(null!==(e=null==i?void 0:i.time)&&void 0!==e?e:this._time))this._samples.push({bytes:t,time:n,clip:!1});else{if(!i)return this;i.bytes+=t}return this._bytes+=t,this.onBytes(t),this}clear(){return this._bytes=0,this._time=a(),this._samples=[],this._clip=!1,this}clip(){if(this._clip){this._clip=!1;let t=0;for(const e of this._samples)if(this._bytes-=e.bytes,++t,this._time=e.time,e.clip)break;this._samples.splice(0,t)}const t=this._samples[this._samples.length-1];return t&&(t.clip=!0,this._clip=!0),this}updateSamples(t=a()){const e=t-this._interval;let n,i=0;for(;this._time<e&&(n=this._samples[i]);){if(this._bytes-=n.bytes,n.clip&&(this._clip=n.clip=!1),n.time>e){n.bytes*=(n.time-e)/(n.time-this._time),this._time=e,this._bytes+=n.bytes;break}++i,this._time=n.time}return this._samples.splice(0,i),this._samples}}class k{static fixProtocol(t,e){const n=(e=e.replace(/^[\/]+/,"")).indexOf("://");return n>=0&&(n>2&&"s"===e.charAt(n-1).toLowerCase()?(t.length<=2||!t.endsWith("s"))&&(t+="s"):t.length>2&&t.endsWith("s")&&(t=t.slice(0,-1)),e=e.substring(n+3)),t+"://"+e}get host(){return this._host}get domain(){return this._domain}get port(){return this._port}toString(){return this._address}valueOf(){return this._address}constructor(t,e){this._address=t;let n=t.indexOf("/");n>=0&&(47===t.charCodeAt(n+1)?n>0?58===t.charCodeAt(n-1)&&(t=t.substring(n+2)):t=t.substring(2):n||(t=t.substring(1))),n=t.indexOf("/"),n>=0&&(t=t.substring(0,n)),this._host=t,this._domain=t,this._port=e;const i=this._host.match(/^(?:\[([0-9a-fA-F:]+)\]|([^:/?#]+))(?::(\d+))?(?=[/#?]|$)/);if(i&&(this._domain=i[1]||i[2],i[3])){const t=parseInt(i[3]);t>=0&&t<=65535&&(this._port=t)}}}var U;function x(t,e){var n;if(!e.mediaExt)try{const t=new URL(e.endPoint);e.mediaExt=null!==(n=t.searchParams.get("ext"))&&void 0!==n?n:f(p(t.pathname))}catch(t){e.mediaExt=""}switch(e.mediaExt=_(e.mediaExt,".").toLowerCase(),t){case U.DIRECT_STREAMING:e.mediaExt||(e.mediaExt="mp4");break;case U.HESP:e.mediaExt="mp4";break;case U.WEBRTC:e.mediaExt="rtp";break;case U.WRTS:e.mediaExt&&"json"!==e.mediaExt||(e.mediaExt="rts");break;case U.META:e.mediaExt="js";break;case U.DATA:e.mediaExt="json";break;default:E("Unknown params type "+t).warn()}}!function(t){t.HESP="HESP",t.WRTS="WebRTS",t.WEBRTC="WebRTC",t.DIRECT_STREAMING="DirectStreaming",t.META="Meta",t.DATA="Data"}(U||(U={}));var A=Object.freeze({__proto__:null,get Type(){return U},buildURL:function(t,e,n="wss"){var i;x(t,e);const r=new URL(k.fixProtocol(n,e.endPoint));if(r.pathname.length<=1)switch(t){case U.HESP:r.pathname="/hesp/"+e.streamName+"/index.json";break;case U.WEBRTC:r.pathname="/webrtc/"+e.streamName;break;case U.WRTS:r.pathname="/wrts/"+e.streamName+"."+e.mediaExt;break;case U.DIRECT_STREAMING:r.pathname="/live/"+e.streamName+"."+e.mediaExt;break;case U.META:r.pathname="/json_"+e.streamName+".js";break;case U.DATA:r.pathname="/"+e.streamName+".json";break;default:E("Unknown url type "+t).warn()}else if(!e.streamName){const t=r.pathname.split("/");e.streamName=m(t[2]||t[1]||t[0])}e.accessToken&&r.searchParams.set("id",e.accessToken);for(const[t,n]of null!==(i=e.query)&&void 0!==i?i:[])r.searchParams.set(t,n);return r},defineMediaExt:x});class I extends C{constructor(){super(),this._events=new Map;let t=Object.getPrototypeOf(this);for(;t&&t!==Object.prototype;){for(const e of Object.getOwnPropertyNames(t)){if(e.length<3||!e.startsWith("on"))continue;let n=t[e];if(n instanceof Function){const t=new Set;this._events.set(e.substring(2).toLowerCase(),t);const i=(...e)=>{const i=n?n.call(this,...e):void 0;for(const n of t)n(...e);return i};Object.defineProperties(this,{[e]:{get:()=>i,set:t=>{n=t}}})}}t=Object.getPrototypeOf(t)}}on(t,e,n){var i;if("function"!=typeof e)throw Error("event callback must be a function");const r=this._event(t);r.add(e),null===(i=null==n?void 0:n.signal)||void 0===i||i.addEventListener("abort",()=>r.delete(e),{once:!0})}once(t,e,n){var i;if("function"!=typeof e)throw Error("event callback must be a function");const r=this._event(t),s=(...t)=>{r.delete(s),e(...t)};r.add(s),null===(i=null==n?void 0:n.signal)||void 0===i||i.addEventListener("abort",()=>r.delete(s),{once:!0})}off(t,e){if(!e)throw Error("event to unsubscribe cannot be null");return this._event(t).delete(e)}_event(t){const e=this._events.get(t.toLowerCase());if(!e)throw Error("No event on"+t+" on class "+this.constructor.name);return e}}class M{[Symbol.iterator](){return this._map[Symbol.iterator]()}get size(){return this._map.size}constructor(t){this._initValue=t,this._map=new Map}get(t){let e=this.find(t);return void 0===e&&this._map.set(t,e=this._initValue()),e}find(t){return this._map.get(t)}has(t){return this._map.has(t)}clear(){this._map.clear()}delete(t){return this._map.delete(t)}set(t,e){return this._map.set(t,e),e}forEach(t,e){this._map.forEach(t,e)}}class D{get size(){return this._queue.length}get capacity(){return this._capacity}set capacity(t){this._capacity=t,null!=t&&this._queue.length>t&&this._queue.splice(0,this._queue.length-t)}get front(){return this._queue[0]}get back(){return this._queue[this._queue.length-1]}[Symbol.iterator](){return this._queue[Symbol.iterator]()}constructor(t){this._capacity=t,this._queue=new Array}push(t){return null!=this._capacity&&this._queue.push(t)>this._capacity&&this.pop(),this}pop(){return this._queue.shift()}clear(){return this._queue.length=0,this}}class O extends D{get minimum(){return this._min}get maximum(){return this._max}get average(){return null==this._average&&(this._average=this.size?this._sum/this.size:0),this._average}constructor(t){super(t),this._sum=0,this._min=0,this._max=0}push(t){return t>this._max?this._max=t:t<this._min&&(this._min=t),this._average=void 0,this._sum+=t,super.push(t),this}pop(){const t=super.pop();return t===this._max?this._max=Math.max(0,...this):t===this._min&&(this._min=Math.min(0,...this)),this._average=void 0,this._sum-=t||0,t}clear(){return this._min=this._max=this._sum=0,super.clear(),this}}const N={fromString(t){if(Array.isArray(t))return t;const e=new Array;let n,i=e;for(let r of t.toString().split("\n")){if(r=r.trim(),!r)continue;let t=r[0];const s=r.substring(r.indexOf("=")+1).trim();switch(t.toLowerCase()){case"a":if(!s)continue;t=this.addAttribute(i,s),e===i&&"fingerprint"===t.toLowerCase()&&(n=i.fingerprint);break;case"m":e.length&&n&&!e[e.length-1].fingerprint&&(i.fingerprint=n),e.push(i={m:s});break;default:i[t]=s}}return e.length&&n&&!e[e.length-1].fingerprint&&(i.fingerprint=n),e},toString(t){if("string"==typeof t)return t;const e=[];let n="v"in t?"v="+t.v+"\n":"";"o"in t&&(n+="o="+t.o+"\n"),"s"in t&&(n+="s="+t.s+"\n");const i=t;for(const r of Object.keys(t)){if("v"===r||"o"===r||"s"===r)continue;const t=i[r];if(null==t)continue;const s=parseInt(r);if(!isNaN(s)){e[s]=t;continue}const o=Array.isArray(t)&&t.length||1;for(let e=0;e<o;++e){const i=Array.isArray(t)&&t.length?t[e]:t;r.length>1?(n+="a="+r,i&&(n+=":")):n+=r+"=",n+=i+"\n"}}for(const t of e)n+=this.toString(t);return n},addAttribute(t,e){var n;const i=N.parseAttribute(e),r=null!==(n=i.value)&&void 0!==n?n:"",s=t,o=s[i.key];return o?Array.isArray(o)?o.push(r):r!==o&&(s[i.key]=[o,r]):s[i.key]=r,i.key},removeAttribute(t,e){const n=N.parseAttribute(e),i=t;if(void 0===n.value)return delete i[e],e;const r=i[e];if(Array.isArray(n.value)){const t=r.findIndex(t=>t===n.value);t>=0&&r.splice(t,1)}else r===n.value&&delete i[e];return n.key},parseAttribute(t){const e=t.indexOf(":");return{key:(e>=0?t.substring(0,e):t).trim(),value:e>=0?t.substring(e+1).trim():void 0}}};Object.freeze(N);class P extends I{onOpen(){}onMessage(t){}onClose(t){t?this.log("onClose",t).error():this.log("onClose").info()}get binaryType(){return"arraybuffer"}get recvByteRate(){return this._recvByteRate.value()}get sendByteRate(){return this._sendByteRate.value()}get url(){var t,e;return null!==(e=null===(t=this._ws)||void 0===t?void 0:t.url)&&void 0!==e?e:""}get extensions(){var t,e;return null!==(e=null===(t=this._ws)||void 0===t?void 0:t.extensions)&&void 0!==e?e:""}get protocol(){var t,e;return null!==(e=null===(t=this._ws)||void 0===t?void 0:t.protocol)&&void 0!==e?e:""}get opened(){return this._opened}get readyState(){return this._ws?this._ws.readyState:3}get closed(){return this._closed}get bufferedAmount(){var t;return this._queueingBytes+((null===(t=this._ws)||void 0===t?void 0:t.bufferedAmount)||0)}get queueing(){return this._queueing}constructor(t,e){super(),this._queueing=[],this._queueingBytes=0,this._opened=!1,this._closed=!0,this._recvByteRate=new R,this._sendByteRate=new R,t&&this.open(t,e)}open(t,e){this._closed=!1;const n=this._ws=new WebSocket(t,e);return n.binaryType=this.binaryType,n.onmessage=t=>{var e;this._recvByteRate.addBytes(null!==(e=t.data.byteLength)&&void 0!==e?e:t.data.length),this.onMessage(t.data)},n.onclose=e=>{this._opened?1e3===e.code||1005===e.code?this.close({type:"WebSocketReliableError",name:"Server shutdown",url:t.toString()}):this.close({type:"WebSocketReliableError",name:"Socket disconnection",url:t.toString(),reason:String(e.reason||e.code)}):this.close({type:"WebSocketReliableError",name:"Connection failed",url:t.toString(),reason:String(e.reason||e.code)})},n.onopen=t=>{this._opened=!0,this.flush(),this.onOpen()},this}send(t,e=!1){if(this._closed)throw Error("Open socket before to send data");return e||!this._opened?(this._queueing.push(t),this._queueingBytes+="string"==typeof t?t.length:t.byteLength):this._send(t),this}flush(){if(this._ws)for(const t of this._queueing)this._send(t);this._queueing.length=0,this._queueingBytes=0}close(t){this._ws&&!this._closed&&(this._closed=!0,this._ws.onopen=this._ws.onclose=this._ws.onmessage=null,this._ws.close(),this._queueing.length=0,this._queueingBytes=0,this.onClose(t),this._opened=!1)}_send(t){this._ws&&(this._sendByteRate.addBytes("string"==typeof t?t.length:t.byteLength),this._ws.send(t))}}function $(t,e,n=.2){const i=Math.floor(e/32);let r="";if(i<1)return null;const s=32*i,o=Math.floor(i/2),a=t.getImageData(0,o,s,1).data,c=new Uint32Array(a.buffer),l=255*n,u=255*(1-n);for(let t=0;t<s;t+=i){const e=16777215&c[t+o],n=.299*(e>>16&255)+.587*(e>>8&255)+.114*(255&e);if(n<l)r+="1";else{if(!(n>u))return null;r+="0"}}const h=parseInt(r.slice(0,5),2),d=parseInt(r.slice(5,10),2),f=parseInt(r.slice(10,16),2),p=parseInt(r.slice(16,22),2),m=parseInt(r.slice(22,32),2);if(h<1||h>31||d>23||f>59||p>59||m>999)return null;const g=new Date;return new Date(Date.UTC(g.getUTCFullYear(),g.getUTCMonth(),h,d,f,p,m))}var B=Object.freeze({__proto__:null,decodeTimestamp:$,encodeTimestamp:function(t,e,n=32,i=new Date){const r=Math.floor(e/n),s=i.getUTCDate(),o=i.getUTCHours(),a=i.getUTCMinutes(),c=i.getUTCSeconds(),l=i.getUTCMilliseconds(),u=s.toString(2).padStart(5,"0")+o.toString(2).padStart(5,"0")+a.toString(2).padStart(6,"0")+c.toString(2).padStart(6,"0")+l.toString(2).padStart(10,"0");for(let e=0;e<u.length;e++){const i=e%n*r,s=Math.floor(e/n)*r;t.fillStyle="1"===u[e]?"black":"white",t.fillRect(i,s,r,r)}},getLatency:function(t,e,n,i=new Date,r=.2){if(e.width=t.videoWidth,e.height=Math.floor(e.width/32),!e.width||!e.height)return 0;n.drawImage(t,0,0,e.width,e.height,0,0,e.width,e.height);const s=$(n,e.width,r);return null==s?0:i.getTime()-s.getTime()}});const L={ERROR:0,TEXT:1,WARNING:2,INFO:2,DEBUG:3,DATA:3};class F{constructor(){this.time=null,this.verboseLevel=L.ERROR}log(t,e){if(this.verboseLevel>=t){const n="function"==typeof e?e():e;console.log(`${this.time} [${t}] ${n}`)}}}class z{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){const e=["foreground","underline","italics","background","flash"];for(let n=0;n<e.length;n++){const i=e[n];Object.prototype.hasOwnProperty.call(t,i)&&(this[i]=t[i])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}}class V{constructor(){this.uchar=" ",this.penState=new z}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}const j=100,W={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499};function H(t){return String.fromCharCode(W[t]||t)}class Y{constructor(t=new F){this.chars=[],this.cueStartTime=null,this.pos=0,this.currPenState=new z;for(let t=0;t<j;t++)this.chars.push(new V);this.logger=t}equals(t){for(let e=0;e<j;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<j;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<j;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(L.DEBUG,"Negative cursor position "+this.pos),this.pos=0):this.pos>j&&(this.logger.log(L.DEBUG,"Too large cursor position "+this.pos),this.pos=j)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t<e+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=H(t);this.pos>=j?this.logger.log(L.ERROR,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<j;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let n=0;n<j;n++){const i=this.chars[n].uchar;" "!==i&&(e=!1),t.push(i)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}const X=15;class q{constructor(t=new F){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null;for(let e=0;e<X;e++)this.rows.push(new Y(t));this.logger=t}reset(){for(let t=0;t<X;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let n=0;n<X;n++)if(!this.rows[n].equals(t.rows[n])){e=!1;break}return e}copy(t){for(let e=0;e<X;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<X;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(L.INFO,"setCursor: "+t);this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(L.INFO,()=>"pacData = "+JSON.stringify(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<X;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const i=n.rows[t].cueStartTime,r=this.logger.time;if(null!==i&&null!==r&&i<r)for(let i=0;i<this.nrRollUpRows;i++)this.rows[e-this.nrRollUpRows+i+1].copy(n.rows[t+i])}}this.currRow=e;const n=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,i=Math.max(e-1,0);n.setCursor(t.indent),t.color=n.chars[i].penState.foreground}const i={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(t){this.logger.log(L.INFO,()=>"bkgData = "+JSON.stringify(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(L.DEBUG,"roll_up but nrRollUpRows not set yet");this.logger.log(L.TEXT,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(L.INFO,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let n="",i=-1;for(let n=0;n<X;n++){const r=this.rows[n].getTextString();r&&(i=n+1,t?e.push("Row "+i+": '"+r+"'"):e.push(r.trim()))}return e.length>0&&(n=t?"["+e.join(" | ")+"]":e.join("\n")),n}getTextAndFormat(){return this.rows}}class G{constructor(t,e,n=new F){this.chNr=t,this.outputFilter=e,this.mode=null,this.displayedMemory=new q(n),this.nonDisplayedMemory=new q(n),this.lastOutputScreen=new q(n),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n,this.logger.log(L.INFO,"new Cea608Channel("+this.chNr+")")}reset(){var t,e;this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),null===(e=null===(t=this.outputFilter)||void 0===t?void 0:t.reset)||void 0===e||e.call(t),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(L.INFO,()=>"MODE="+t),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.setRollUpRows(null),this.nonDisplayedMemory.setRollUpRows(null)),this.mode=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(L.INFO,()=>e+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(L.TEXT,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(L.INFO,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(L.INFO,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(L.INFO,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(L.INFO,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(L.INFO,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(L.INFO,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(L.INFO,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(L.INFO,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(L.INFO,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(L.INFO,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(L.INFO,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(L.INFO,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(L.TEXT,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(L.INFO,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const n=Math.floor(t/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=i[n]}this.logger.log(L.INFO,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}const K=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];function J(t,e,n){return n.a===t&&n.b===e}function Q(t){const e=[];for(let n=0;n<t.length;n++)e.push(t[n].toString(16));return e}const Z={17:2,18:4,21:6,22:8,23:10,19:13,20:15},tt={25:2,26:4,29:6,30:8,31:10,27:13,28:15},et={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},nt={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14};function it(t,e,n){n.a=t,n.b=e}let rt,st,ot;function at(t){return t?ot(t):(console.error("Can't parse empty HLS Manifest"),{})}function ct(t,e){var n,i,r,s;if(t.$.contentType)return t.$.contentType;if(null===(n=t.ContentComponent)||void 0===n?void 0:n.at(0))return t.ContentComponent.at(0).$.contentType;if(t.$.mimeType||(null==e?void 0:e.$.mimeType)){const n=(null===(i=t.$.mimeType)||void 0===i?void 0:i.split("/")[0])||(null===(r=null==e?void 0:e.$.mimeType)||void 0===r?void 0:r.split("/")[0]);if("audio"===n||"video"===n||"text"===n)return n;if("application"===n)return"text"}if(t.$.maxHeight)return"video";const o=null!==(s=t.$.id)&&void 0!==s?s:`group: ${t.$.group}, lang: ${t.$.lang}`;return console.error(`Could not find contentType from adaptationSet ${o}`),console.info('Using "text" as default contentType'),"text"}function lt(t,e){return t&&e?+(null!=t?t:1)/+(null!=e?e:1):1}function ut(t,e,n){return e.$.media.replace(/\$(.*?)\$/g,e=>e.includes("RepresentationID")?t.$.id:e.includes("Number%04d")?n.toString().padStart(4,"0"):e.includes("Number")?n:(console.error(`Unknown property ${e} from the SegmentTemplate on representation ${t.$.id}`),e))}function ht(t,e,n){var i;const r=function(t,e){return Math.round(e/lt(t.$.duration,t.$.timescale))}(n,e),s=+(null!==(i=n.$.startNumber)&&void 0!==i?i:0),o=[];for(let e=s;e<r+s;e++)o.push({duration:lt(n.$.duration,n.$.timescale),url:ut(t,n,e)});return o}function dt(t,e,n){var i,r,s,o;const a=null!==(r=null===(i=t.SegmentTemplate)||void 0===i?void 0:i.at(0))&&void 0!==r?r:null===(s=e.SegmentTemplate)||void 0===s?void 0:s.at(0),c=null!==(o=t.SegmentList)&&void 0!==o?o:e.SegmentList;return e.SegmentBase?function(t,e){return t.SegmentBase.map(n=>{var i;return{duration:e,url:null!==(i=t.BaseURL[0])&&void 0!==i?i:"",byteRange:n.$.indexRange}})}(e,n):c?function(t){const e=[];return t.map(t=>{if(t.SegmentURL)return t.SegmentURL.forEach(n=>{var i;e.push({duration:lt(t.$.duration,t.$.timescale),url:null!==(i=n.$.media)&&void 0!==i?i:""})})}),e}(c):a?ht(e,n,a):(console.error(`Representation ${e.$.id} has no segments`),[])}function ft(t,e){var n,i,r,s,o,a;const c=+(null!==(a=null!==(r=null===(i=null===(n=t.AudioChannelConfiguration)||void 0===n?void 0:n.at(0))||void 0===i?void 0:i.$.value)&&void 0!==r?r:null===(o=null===(s=e.AudioChannelConfiguration)||void 0===s?void 0:s.at(0))||void 0===o?void 0:o.$.value)&&void 0!==a?a:0);return c||console.error(`Representation ${e.$.id} has no channels`),c}function pt(t,e){var n,i;const r=null!==(i=null!==(n=e.$.codecs)&&void 0!==n?n:t.$.codecs)&&void 0!==i?i:"";return r||console.error(`Representation ${e.$.id} has no codecs`),r}const mt="@";function gt(t,e){var n,i,r,s;const o=null!==(i=null!==(n=e.$.frameRate)&&void 0!==n?n:t.$.frameRate)&&void 0!==i?i:"";o||console.error(`Representation ${e.$.id} has no frame rate`);const a=o.split("/"),c=parseInt(null!==(r=a.at(0))&&void 0!==r?r:""),l=parseInt(null!==(s=a.at(1))&&void 0!==s?s:"");return{frameRateNumerator:isNaN(c)?30:c,frameRateDenominator:isNaN(l)?0:l}}function _t(t){let e=t.$.lang;return e||(console.info(`AdaptationSet ${t.$.id} has no lang, using "und" as default`),e="und"),e}function vt(t,e){var n,i;const r=+(null!==(i=null!==(n=e.$.audioSamplingRate)&&void 0!==n?n:t.$.audioSamplingRate)&&void 0!==i?i:0);return r||console.error(`Representation ${e.$.id} has no audioSamplingRate`),r}function yt(t,e){var n,i;const r=null!==(i=null!==(n=e.$.sar)&&void 0!==n?n:t.$.sar)&&void 0!==i?i:"";return r||console.error(`Representation ${e.$.id} has no sar`),r}function bt(t){return t.reduce((t,e)=>t+e.duration,0)}function St(t){return t.MPD.Period.map(t=>{const e=function(t){const e=/(?:([.,\d]+)H)/.exec(t),n=/(?:([.,\d]+)M)/.exec(t),i=/(?:([.,\d]+)S)/.exec(t);let r=0;return e&&(r+=60*+e[1]*60),n&&(r+=60*+n[1]),i&&(r+=+i[1]),r}(t.$.duration),n=function(t,e){var n;return null!==(n=t.$.id)&&void 0!==n?n:`presentation-id-${e}`}(t,e),i={};t.AdaptationSet.map(t=>{var n,r,s,o;const a=t.Representation.map(n=>{const i=dt(t,n,e);return function(t,e,n,i){var r,s,o,a,c,l,u,h,d,f;if(!t)throw new Error("Error: AdaptationSet is undefined");const p=ct(t,e);return"video"===p?{bandwidth:+(null!==(r=e.$.bandwidth)&&void 0!==r?r:0),codec:pt(t,e),duration:bt(n),frameRate:gt(t,e),height:+(null!==(s=e.$.height)&&void 0!==s?s:0),id:null!==(o=e.$.id)&&void 0!==o?o:"",language:_t(t),par:null!==(a=t.$.par)&&void 0!==a?a:"",sar:yt(t,e),scanType:null!==(c=e.$.scanType)&&void 0!==c?c:"",segments:n,type:p,width:+(null!==(l=e.$.width)&&void 0!==l?l:0),urlInitialization:i}:"audio"===p?{bandwidth:+(null!==(u=e.$.bandwidth)&&void 0!==u?u:0),channels:ft(t,e),codec:pt(t,e),duration:bt(n),id:null!==(h=e.$.id)&&void 0!==h?h:"",language:_t(t),sampleRate:vt(t,e),segments:n,type:p,urlInitialization:i}:{bandwidth:+(null!==(d=e.$.bandwidth)&&void 0!==d?d:0),codec:pt(t,e),duration:bt(n),id:null!==(f=e.$.id)&&void 0!==f?f:"",language:_t(t),segments:n,type:p,urlInitialization:i}}(t,n,i,function(t,e){var n,i,r,s,o,a,c,l,u,h;let d;return e.SegmentBase?d=null!==(n=e.BaseURL[0])&&void 0!==n?n:"":(t.SegmentList||e.SegmentList)&&(d=(null===(r=null===(i=e.SegmentList)||void 0===i?void 0:i.at(0))||void 0===r?void 0:r.Initialization[0].$.sourceURL)||(null===(o=null===(s=t.SegmentList)||void 0===s?void 0:s.at(0))||void 0===o?void 0:o.Initialization[0].$.sourceURL)),(t.SegmentTemplate||e.SegmentTemplate)&&(d=(null===(c=null===(a=t.SegmentTemplate)||void 0===a?void 0:a.at(0))||void 0===c?void 0:c.$.initialization)||(null===(u=null===(l=e.SegmentTemplate)||void 0===l?void 0:l.at(0))||void 0===u?void 0:u.$.initialization),(null==d?void 0:d.includes("$RepresentationID$"))&&(d=d.replace("$RepresentationID$",null!==(h=e.$.id)&&void 0!==h?h:""))),d}(t,n))}),c=function(t){var e;return null!==(e=t.$.group)&&void 0!==e?e:ct(t)}(t);i[c]||(i[c]={id:c,switchingSets:[]}),i[c].switchingSets.push({id:null!==(o=null!==(n=t.$.id)&&void 0!==n?n:null===(s=null===(r=t.ContentComponent)||void 0===r?void 0:r.at(0))||void 0===s?void 0:s.$.id)&&void 0!==o?o:c,tracks:a})});return{id:n,selectionSets:Object.values(i)}})}function wt(t){var e;const n=[];if(t.segments.length>0&&t.byteRange&&t.segments[0].byteRange&&t.segments[0].byteRange.includes("@")){let i;const r=t.byteRange.includes("-")?t.byteRange.split("-")[1]:t.byteRange.includes("@")?t.byteRange.split("@")[0]:"",s=+r-1;if(i={$:{indexRange:`${r}-${+(t.segments[0].byteRange.includes("-")?t.segments[0].byteRange.split("-")[1]:t.segments[0].byteRange.includes("@")?t.segments[0].byteRange.split("@")[1]:"")-1}`},Initialization:[{$:{range:`0-${s}`}}]},i&&"audio"===t.type){const n=t;i.$.timescale=null!==(e=n.sampleRate.toString())&&void 0!==e?e:""}i&&n.push(i)}else t.segments.forEach(e=>{var i;let r;if(e.byteRange){const t=+e.byteRange.split("-")[0]-1;r={$:{indexRange:e.byteRange},Initialization:[{$:{range:`0-${t}`}}]}}if(r&&"audio"===t.type){const e=t;r.$.timescale=null!==(i=e.sampleRate.toString())&&void 0!==i?i:""}r&&n.push(r)});return n}function Tt(t){var e;const n=[],i=[];if(t.segments.forEach(t=>{i.push({$:{media:t.url}})}),!(null===(e=t.segments.at(0))||void 0===e?void 0:e.byteRange)){const e=function(t){if("audio"===(null==t?void 0:t.type)){const e=t;return 0!==e.sampleRate?e.sampleRate:48e3}return"video"===(null==t?void 0:t.type)?9e4:"text"===(null==t?void 0:t.type)?1e3:9e4}(t);n.push({$:{duration:(t.duration*e/i.length).toString(),timescale:e.toString()},Initialization:[{$:{sourceURL:t.urlInitialization}}],SegmentURL:i})}return n}function Ct(t){var e;let n;if("video"===(null==t?void 0:t.type)){const i=t;n=`${null!==(e=i.frameRate.frameRateNumerator)&&void 0!==e?e:30}`,n=0!==i.frameRate.frameRateDenominator?`${n}/${i.frameRate.frameRateDenominator}`:n}return n}function Et(t){const e=Math.floor(t/3600),n=Math.floor(t%3600/60),i=t%60;return e>0?`PT${e}H${n}M${i}S`:n>0?`PT${n}M${i}S`:`PT${i}S`}function Rt(t){const e=t.map(t=>{return{$:{duration:Et(t.selectionSets[0].switchingSets[0].tracks[0].duration),id:t.id,start:"PT0S"},AdaptationSet:(e=t.selectionSets,e.flatMap(t=>t.switchingSets.map(e=>{const n=e.tracks[0];return{$:{id:e.id,group:t.id,contentType:null==n?void 0:n.type,mimeType:`${null==n?void 0:n.type}/mp4`,frameRate:Ct(n),lang:null==n?void 0:n.language,codecs:null==n?void 0:n.codec},Representation:(i=e.tracks,i.map(t=>{var e,n;const i={$:{id:t.id,bandwidth:t.bandwidth.toString()},SegmentBase:wt(t),SegmentList:Tt(t)};if(i.$.mimeType=`${t.type}/mp4`,"video"===t.type){const e=t;i.$={...i.$,frameRate:Ct(t),width:e.width.toString(),height:e.height.toString(),codecs:e.codec},e.scanType&&(i.$.scanType=e.scanType)}if("audio"===t.type){const n=t;i.$={...i.$,audioSamplingRate:n.sampleRate.toString(),codecs:n.codec},i.AudioChannelConfiguration=[{$:{schemeIdUri:"urn:mpeg:dash:23003:3:audio_channel_configuration:2011",value:null!==(e=n.channels.toString())&&void 0!==e?e:""}}]}return(null===(n=t.segments[0])||void 0===n?void 0:n.byteRange)&&(i.BaseURL=[t.segments[0].url]),i}))};var i})))};var e});const n=e[0].$.duration;return st({MPD:{$:{mediaPresentationDuration:n,type:"static"},Period:e}})}function kt(t){const e=null==t?void 0:t.metadata;return JSON.parse(JSON.stringify(e))}class Ut{getManifestMetadata(){return kt(this.manifest)}toHam(t){const e=(n=t.manifest,rt(n));var n;return e?(function(t,e){e.metadata||(e.metadata=new Map),t.MPD.$&&t.MPD.$.profiles&&e.metadata.set("profiles",t.MPD.$.profiles),t.MPD.$&&t.MPD.$.type&&e.metadata.set("type",t.MPD.$.type)}(e,t),St(e)):[]}toManifest(t){return{manifest:Rt(t),ancillaryManifests:[],type:"dash"}}}class xt{constructor(){}static getInstance(){return xt.instance||(xt.instance=new xt),xt.instance}setStrategy(t){this.strategy=t}getHamFormat(t){return this.strategy.toHam(t)}getManifestFormat(t){return this.strategy.toManifest(t)}getManifestMetadata(){return this.strategy.getManifestMetadata()}}function At(t){return`#EXT-X-MAP:URI="${function(t){var e,n;return null!==(n=null===(e=t.urlInitialization)||void 0===e?void 0:e.replaceAll(" ","%20"))&&void 0!==n?n:""}(t)}",${function(t){var e,n,i,r;return t.byteRange?`BYTERANGE:${t.byteRange.replace("-",mt)}\n`:(null===(n=null===(e=t.segments)||void 0===e?void 0:e.at(0))||void 0===n?void 0:n.byteRange)?`BYTERANGE:0@${Number(null===(r=null===(i=t.segments.at(0))||void 0===i?void 0:i.byteRange)||void 0===r?void 0:r.replace("-",mt).split(mt)[0])-1}\n`:""}(t)}\n`}function It(t){var e;const n=null!==(e=t.fileName)&&void 0!==e?e:`${t.id}.m3u8`;let i="",r=`#EXTM3U\n#EXT-X-TARGETDURATION:${t.duration/t.segments.length}\n#EXT-X-PLAYLIST-TYPE:VOD\n#EXT-X-MEDIA-SEQUENCE:0\n`;if("video"===t.type.toLowerCase()){const e=t;i+=`#EXT-X-STREAM-INF:BANDWIDTH=${e.bandwidth},CODECS="${e.codec}",RESOLUTION=${e.width}x${e.height}\n${n}\n`,r+=At(e)}else if("audio"===t.type.toLowerCase()){const e=t;i+=`#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="${e.id}",LANGUAGE="${e.language}",NAME="${e.id}",URI="${n}"\n`,r+=At(e)}else if("text"===t.type.toLowerCase()){const e=t;i+=`#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="${e.id}",NAME="${e.id}",LANGUAGE="${e.language}",URI="${n}"\n`}var s;return r+=`${s=t.segments,s.map(t=>{const e=t.byteRange?`#EXT-X-BYTERANGE:${t.byteRange.replace("-",mt)}\n`:"",n=t.url.replaceAll(" ","%20");return`#EXTINF:${t.duration},\n${e}\n${n}`}).join("\n")}#EXT-X-ENDLIST`,{mainRef:i,playlist:r}}function Mt(t){return t?`${t.length}@${t.offset}`:""}function Dt(t){var e;return null!==(e=null==t?void 0:t.map(t=>{const e=Mt(null==t?void 0:t.byterange);return{duration:t.duration,url:t.uri,...e&&{byteRange:e}}}))&&void 0!==e?e:[]}function Ot(t,e){var n;return"audio"===t?"mp4a.40.2":"video"===t&&null!==(n=null==e?void 0:e.split(",").at(0))&&void 0!==n?n:""}function Nt(t,e){return(null==t?void 0:t.targetDuration)?(null==t?void 0:t.targetDuration)*e.length:(console.error("Could not calculate duration, manifest is undefined."),null)}function Pt(t){var e,n;const i=at(t.manifest),r=function(t,e){return t.metadata||(t.metadata=new Map),e.version||t.metadata.set("version",e.version),e.mediaSequence||t.metadata.set("mediaSequence",e.mediaSequence),t}(t,i),s=[],o=r.ancillaryManifests?[...r.ancillaryManifests]:[],a=function(t,e){var n,i;const r=[],s=[];for(const r in t){const o=t[r];for(const t in o){const r=o[t],{language:a,uri:c}=r,l=at(null===(n=e.shift())||void 0===n?void 0:n.manifest),u=null===(i=null==l?void 0:l.segments[0])||void 0===i?void 0:i.map,h=Dt(null==l?void 0:l.segments),d=Mt(null==u?void 0:u.byterange);s.push({id:t,type:"audio",fileName:c,codec:Ot("audio"),duration:Nt(l,h),language:a,bandwidth:0,segments:h,sampleRate:0,channels:2,...d&&{byteRange:d},...(null==u?void 0:u.uri)&&{urlInitialization:null==u?void 0:u.uri}})}}return r.push({id:"audio",tracks:s}),r}(null===(e=i.mediaGroups)||void 0===e?void 0:e.AUDIO,o),c=function(t,e){var n;const i=[],r=[];for(const i in t){const s=t[i];for(const t in s){const i=s[t],{language:o,uri:a}=i,c=at(null===(n=e.shift())||void 0===n?void 0:n.manifest),l=Dt(null==c?void 0:c.segments);r.push({id:t,type:"text",fileName:a,codec:Ot("text"),duration:Nt(c,l),language:o,bandwidth:0,segments:l})}}return i.push({id:"text",tracks:r}),i}(null===(n=i.mediaGroups)||void 0===n?void 0:n.SUBTITLES,o),l=function(t,e){const n=[],i=[];let r=0;return t.map(t=>{var n,s,o,a;const c=at(null===(n=e.shift())||void 0===n?void 0:n.manifest),l=Dt(null==c?void 0:c.segments),{LANGUAGE:u,CODECS:h,BANDWIDTH:d}=t.attributes,f=null===(o=null===(s=null==c?void 0:c.segments)||void 0===s?void 0:s.at(0))||void 0===o?void 0:o.map,p=Mt(null==f?void 0:f.byterange);i.push({id:"video-"+r++,type:"video",fileName:t.uri,codec:Ot("video",h),duration:Nt(c,l),language:null!=u?u:"und",bandwidth:d,segments:l,width:t.attributes.RESOLUTION.width,height:t.attributes.RESOLUTION.height,frameRate:{frameRateNumerator:null!==(a=t.attributes["FRAME-RATE"])&&void 0!==a?a:30,frameRateDenominator:0},par:"",sar:"",scanType:"",...p&&{byteRange:p},...(null==f?void 0:f.uri)&&{urlInitialization:null==f?void 0:f.uri}})}),n.push({id:"video",tracks:i}),n}(i.playlists,o);let u=0;a.length>0&&s.push({id:(u++).toString(),switchingSets:a}),c.length>0&&s.push({id:(u++).toString(),switchingSets:c}),l.length>0&&s.push({id:(u++).toString(),switchingSets:l});let h=0;return[{id:(h++).toString(),selectionSets:s}]}class $t{getManifestMetadata(){return kt(this.manifest)}toHam(t){const e=Pt(t);return this.manifest=t,e}toManifest(t){return function(t){let e="#EXTM3U\n#EXT-X-VERSION:7\n\n";const n=[];return t.map(t=>{t.selectionSets.map(t=>{t.switchingSets.map(t=>{t.tracks.map(t=>{var i;const{mainRef:r,playlist:s}=It(t);e+=r;const o=null!==(i=t.fileName)&&void 0!==i?i:`${t.id}.m3u8`;n.push({manifest:s,type:"hls",fileName:o})})})})}),{manifest:e,ancillaryManifests:n,type:"hls"}}(t)}}function Bt(t,e){const n=t.tracks;return e?n.filter(e):n}function Lt(t,e){const n=t.switchingSets.flatMap(t=>Bt(t));return e?n.filter(e):n}function Ft(t,e,n){const i=null!=n?n:{status:!0,errorMessages:[]},r=e?` in the track with id = ${e}`:".";return t.duration||(i.status=!1,i.errorMessages.push(`Segment duration is undefined${r}`)),t.url||(i.status=!1,i.errorMessages.push(`Segment url is undefined${r}`)),i}function zt(t,e,n){const i=null!=n?n:{status:!0,errorMessages:[]};return t.forEach(t=>{Ft(t,e,i)}),i}function Vt(t,e,n){const i=null!=n?n:{status:!0,errorMessages:[]},r=e?` in the switching set with id = ${e}`:".";switch(t.id||(i.status=!1,i.errorMessages.push(`Track id is undefined${r}`)),t.type){case"video":!function(t,e,n){const i=null!=n?n:{status:!0,errorMessages:[]},r=e?` in the switching set with id = ${e}`:".";t.codec||(i.status=!1,i.errorMessages.push(`VideoTrack with id: ${t.id} does not have codec${r}`))}(t,e,i);break;case"audio":!function(t,e,n){const i=null!=n?n:{status:!0,errorMessages:[]},r=e?` in the switching set with id = ${e}`:".";t.codec||(i.status=!1,i.errorMessages.push(`AudioTrack with id: ${t.id} does not have codec${r}`))}(t,e,i);break;case"text":!function(t,e,n){const i=null!=n?n:{status:!0,errorMessages:[]},r=e?` in the switching set with id = ${e}`:".";t.language||(i.status=!1,i.errorMessages.push(`TextTrack with id: ${t.id} does not have codec${r}`))}(t,e,i)}return zt(t.segments,t.id,i),i}function jt(t,e,n){const i=null!=n?n:{status:!0,errorMessages:[]},r=e?` in the switching set with id = ${e}`:".";let s;return t.forEach(t=>{s||(s=t.duration),s!==t.duration&&(i.status=!1,i.errorMessages.push(`All the tracks must have the same duration${r}`)),Vt(t,e,i)}),i}function Wt(t,e,n){const i=null!=n?n:{status:!0,errorMessages:[]},r=e?` in the selection set with id = ${e}`:".";return t.id||(i.status=!1,i.errorMessages.push(`SwitchingSet id is undefined${r}`)),jt(t.tracks,t.id,i),i}function Ht(t,e,n){const i=null!=n?n:{status:!0,errorMessages:[]};return t.forEach(t=>{Wt(t,e,i)}),i}function Yt(t,e,n){const i=null!=n?n:{status:!0,errorMessages:[]},r=e?` in the presentation with id = ${e}`:".";return t.id||(i.status=!1,i.errorMessages.push(`SelectionSet id is undefined${r}`)),Ht(t.switchingSets,t.id,i),i}function Xt(t,e,n){const i=null!=n?n:{status:!0,errorMessages:[]};return t.forEach(t=>{Yt(t,e,i)}),i}class qt{constructor(t,e){Array.isArray(t)&&(t=t.map(t=>t instanceof qt?t:new qt(t))),this.value=t,this.params=e}}const Gt="Dict";function Kt(t,e,n,i){return new Error(`failed to ${t} "${r=e,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${n}`,{cause:i});var r}function Jt(t,e,n){return Kt("serialize",t,e,n)}class Qt{constructor(t){this.description=t}}const Zt="Bare Item",te="Boolean";function ee(t){return btoa(String.fromCharCode(...t))}const ne="Byte Sequence";const ie="Integer";function re(t){return t<-999999999999999||999999999999999<t}function se(t){if(re(t))throw Jt(t,ie);return t.toString()}function oe(t,e){if(t<0)return-oe(-t,e);const n=Math.pow(10,e);if(Math.abs(t*n%1-.5)<Number.EPSILON){const e=Math.floor(t*n);return(e%2==0?e:e+1)/n}return Math.round(t*n)/n}const ae="Decimal";const ce="String",le=/[\x00-\x1f\x7f]+/;function ue(t){return t.description||t.toString().slice(7,-1)}const he="Token";function de(t){const e=ue(t);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw Jt(e,he);return e}function fe(t){switch(typeof t){case"number":if(!Number.isFinite(t))throw Jt(t,Zt);return Number.isInteger(t)?se(t):function(t){const e=oe(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Jt(t,ae);const n=e.toString();return n.includes(".")?n:`${n}.0`}(t);case"string":return function(t){if(le.test(t))throw Jt(t,ce);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return de(t);case"boolean":return function(t){if("boolean"!=typeof t)throw Jt(t,te);return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${se(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return function(t){if(!1===ArrayBuffer.isView(t))throw Jt(t,ne);return`:${ee(t)}:`}(t);if(t instanceof Qt)return de(t);default:throw Jt(t,Zt)}}function pe(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw Jt(t,"Key");return t}function me(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${pe(t)}`:`;${pe(t)}=${fe(e)}`).join("")}function ge(t){return t instanceof qt?`${fe(t.value)}${me(t.params)}`:fe(t)}function _e(t){return`(${t.value.map(ge).join(" ")})${me(t.params)}`}function ve(t,e){return function(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw Jt(t,Gt);const n=t instanceof Map?t.entries():Object.entries(t),i=(null==e?void 0:e.whitespace)?" ":"";return Array.from(n).map(([t,e])=>{e instanceof qt==0&&(e=new qt(e));let n=pe(t);return!0===e.value?n+=me(e.params):(n+="=",Array.isArray(e.value)?n+=_e(e):n+=ge(e)),n}).join(`,${i}`)}(t,e)}const ye="CMCD-Object",be="CMCD-Request",Se="CMCD-Session",we="CMCD-Status",Te={br:ye,ab:ye,d:ye,ot:ye,tb:ye,tpb:ye,lb:ye,tab:ye,lab:ye,url:ye,pb:be,bl:be,tbl:be,dl:be,ltc:be,mtp:be,nor:be,nrr:be,rc:be,sn:be,sta:be,su:be,ttfb:be,ttfbb:be,ttlb:be,cmsdd:be,cmsds:be,smrt:be,df:be,cs:be,ts:be,cid:Se,pr:Se,sf:Se,sid:Se,st:Se,v:Se,msd:Se,bs:we,bsd:we,cdn:we,rtp:we,bg:we,pt:we,ec:we,e:we},Ce={OBJECT:ye,REQUEST:be,SESSION:Se,STATUS:we};function Ee(t,e){const n={};if(!t)return n;const i=Object.keys(t),r=e?(s=e,Object.keys(s).reduce((t,e)=>{var n;return null===(n=s[e])||void 0===n||n.forEach(n=>t[n]=e),t},{})):{};var s;return i.reduce((e,n)=>{var i;const s=Te[n]||r[n]||Ce.REQUEST;return(null!==(i=e[s])&&void 0!==i?i:e[s]={})[n]=t[n],e},n)}function Re(t){return["ot","sf","st","e","sta"].includes(t)}function ke(t){return"number"==typeof t?Number.isFinite(t):null!=t&&""!==t&&!1!==t}const Ue="event";function xe(t,e){const n=new URL(t),i=new URL(e);if(n.origin!==i.origin)return t;const r=n.pathname.split("/").slice(1),s=i.pathname.split("/").slice(1,-1),o=Math.min(r.length,s.length);for(let t=0;t<o&&r[t]===s[t];t++)r.shift(),s.shift();for(;s.length;)s.shift(),r.unshift("..");return r.join("/")+n.search+n.hash}const Ae=t=>Math.round(t),Ie=(t,e)=>Array.isArray(t)?t.map(t=>Ie(t,e)):t instanceof qt&&"string"==typeof t.value?new qt(Ie(t.value,e),t.params):(e.baseUrl&&(t=xe(t,e.baseUrl)),1===e.version?encodeURIComponent(t):t),Me=t=>100*Ae(t/100),De={br:Ae,d:Ae,bl:Me,dl:Me,mtp:Me,nor:(t,e)=>{let n=t;return e.version>=2&&(t instanceof qt&&"string"==typeof t.value?n=new qt([t]):"string"==typeof t&&(n=[t])),Ie(n,e)},rtp:Me,tb:Ae},Oe="request",Ne="response",Pe=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],$e=["e"],Be=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Le(t){return Be.test(t)}function Fe(t){return Pe.includes(t)||$e.includes(t)||Le(t)}const ze=["d","dl","nor","ot","rtp","su"];function Ve(t){return Pe.includes(t)||ze.includes(t)||Le(t)}const je=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function We(t){return Pe.includes(t)||ze.includes(t)||je.includes(t)||Le(t)}const He=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Ye(t){return He.includes(t)||Le(t)}const Xe={[Ne]:We,[Ue]:Fe,[Oe]:Ve};function qe(t,e={}){const n={};if(null==t||"object"!=typeof t)return n;const i=e.version||t.v||1,r=e.reportingMode||Oe,s=1===i?Ye:Xe[r];let o=Object.keys(t).filter(s);const a=e.filter;"function"==typeof a&&(o=o.filter(a));const c=r===Ne||r===Ue;c&&!o.includes("ts")&&o.push("ts"),i>1&&!o.includes("v")&&o.push("v");const l=Object.assign({},De,e.formatters),u={version:i,reportingMode:r,baseUrl:e.baseUrl};return o.sort().forEach(e=>{let r=t[e];const s=l[e];if("function"==typeof s&&(r=s(r,u)),"v"===e){if(1===i)return;r=i}"pr"==e&&1===r||(c&&"ts"===e&&!Number.isFinite(r)&&(r=Date.now()),ke(r)&&(Re(e)&&"string"==typeof r&&(r=new Qt(r)),n[e]=r))}),n}function Ge(t,e={}){const n={};if(!t)return n;const i=Ee(qe(t,e),null==e?void 0:e.customHeaderMap);return Object.entries(i).reduce((t,[e,n])=>{const i=ve(n,{whitespace:!1});return i&&(t[e]=i),t},n)}const Ke="CMCD";function Je(t,e={}){return t?ve(qe(t,e),{whitespace:!1}):""}function Qe(t,e={}){if(!t)return"";const n=Je(t,e);return encodeURIComponent(n)}function Ze(t,e={}){if(!t)return"";const n=Qe(t,e);return`${Ke}=${n}`}const tn=/CMCD=[^&#]+/;const en="headers",nn="json",rn=new Set([...He,...Pe,...ze,...je,...$e]),sn=Array.from(rn),on="query",an={JSON:nn,QUERY:on,HEADERS:en},cn=an,ln=De,un={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},hn=un,dn={REQUEST:Oe,RESPONSE:Ne,EVENT:Ue},fn={DASH:"d",HLS:"h",SMOOTH:"s",OTHER:"o"},pn=fn,mn={VOD:"v",LIVE:"l"},gn=mn;function _n(t,e){return{value:t,src:e}}function vn(t,e,n){return Kt("parse",t,e,n)}const yn="Inner List";function bn(t){return new Uint8Array([...atob(t)].map(t=>t.charCodeAt(0)))}const Sn="Date",wn=`${ie} or ${ae}`;function Tn(t){let e,n=1,i="";const r=vn(t,wn);if("-"===t[0]&&(n=-1,t=t.substring(1)),t.length<=0)throw r;const s=/^(\d+)?/g,o=s.exec(t);if(0===o[0].length)throw r;if(i+=o[1],"."===(t=t.substring(s.lastIndex))[0]){if(i.length>12)throw r;const s=/^(\.\d+)?/g,o=s.exec(t);if(t=t.substring(s.lastIndex),0===o[0].length||o[1].length>4)throw r;if(i+=o[1],i.length>16)throw r;e=parseFloat(i)*n}else{if(i.length>15)throw r;if(e=parseInt(i)*n,re(e))throw vn(i,wn)}return _n(e,t)}function Cn(t,e){const n=t[0];if('"'===n)return function(t){let e="",n=0;if('"'!==t[n])throw vn(t,ce);for(n++;t.length>n;){if("\\"===t[n]){if(t.length<=n+1)throw vn(t,ce);if(n++,'"'!==t[n]&&"\\"!==t[n])throw vn(t,ce);e+=t[n]}else{if('"'===t[n])return _n(e,t.substring(++n));if(le.test(t[n]))throw vn(t,ce);e+=t[n]}n++}throw vn(t,ce)}(t);if(/^[-0-9]/.test(n))return Tn(t);if("?"===n)return function(t){let e=0;if("?"!==t[e])throw vn(t,te);if(e++,"1"===t[e])return _n(!0,t.substring(++e));if("0"===t[e])return _n(!1,t.substring(++e));throw vn(t,te)}(t);if(":"===n)return function(t){if(":"!==t[0])throw vn(t,ne);if(!1===(t=t.substring(1)).includes(":"))throw vn(t,ne);const e=/(^.*?)(:)/g,n=e.exec(t)[1];return t=t.substring(e.lastIndex),_n(bn(n),t)}(t);if(/^[a-zA-Z*]/.test(n))return function(t,e){if(!1===/^[a-zA-Z*]$/.test(t[0]))throw vn(t,he);const n=/^([!#$%&'*+\-.^_`|~\w:/]+)/g,i=n.exec(t)[1];return t=t.substring(n.lastIndex),_n(!1===(null==e?void 0:e.useSymbol)?new Qt(i):Symbol.for(i),t)}(t,e);if("@"===n)return function(t){let e=0;if("@"!==t[e])throw vn(t,Sn);e++;const n=Tn(t.substring(e));if(!1===Number.isInteger(n.value))throw vn(t,Sn);return _n(new Date(1e3*n.value),n.src)}(t);throw vn(t,Zt)}function En(t){let e=0;if(!1===/^[a-z*]$/.test(t[e]))throw vn(t,"Key");let n="";for(;t.length>e;){if(!1===/^[a-z0-9_\-.*]$/.test(t[e]))return _n(n,t.substring(e));n+=t[e],e++}return _n(n,t.substring(e))}function Rn(t,e){let n;for(;t.length>0&&";"===t[0];){const i=En(t=t.substring(1).trim()),r=i.value;let s=!0;if("="===(t=i.src)[0]){const n=Cn(t=t.substring(1),e);s=n.value,t=n.src}null==n&&(n={}),n[r]=s}return _n(n,t)}function kn(t,e){const n=Cn(t,e),i=Rn(t=n.src,e);return t=i.src,_n(new qt(n.value,i.value),t)}function Un(t,e){return"("===t[0]?function(t,e){if("("!==t[0])throw vn(t,yn);t=t.substring(1);const n=[];for(;t.length>0;){if(")"===(t=t.trim())[0]){const i=Rn(t=t.substring(1),e);return _n(new qt(n,i.value),i.src)}const i=kn(t,e);if(n.push(i.value)," "!==(t=i.src)[0]&&")"!==t[0])throw vn(t,yn)}throw vn(t,yn)}(t,e):kn(t,e)}function xn(t,e){try{const{src:n,value:i}=function(t,e){const n={};for(;t.length>0;){let i;const r=En(t),s=r.value;if("="===(t=r.src)[0]){const n=Un(t.substring(1),e);i=n.value,t=n.src}else{const n=Rn(t,e);i=new qt(!0,n.value),t=n.src}if(n[s]=i,0===(t=t.trim()).length)return _n(n,t);if(","!==t[0])throw vn(t,Gt);if(0===(t=t.substring(1).trim()).length||","===t[0])throw vn(t,Gt)}return _n(n,t)}(t.trim(),e);if(""!==n)throw vn(n,Gt);return i}catch(e){throw vn(t,Gt,e)}}function An(t){return Array.isArray(t)?t.map(An):"symbol"==typeof t?ue(t):t instanceof qt&&!t.params?An(t.value):"string"==typeof t?decodeURIComponent(t):t}function In(t){if(!t)return{};const e=xn(t);return Object.entries(e).reduce((t,[e,n])=>(t[e]=An(n.value),t),{})}const Mn=[ye,be,Se,we];const Dn="CMSD-Dynamic",On="CMSD-Static",Nn={STATIC:On,DYNAMIC:Dn},Pn=un,$n=fn,Bn=mn,Ln="List";function Fn(t,e){try{const{src:n,value:i}=function(t,e){const n=[];for(;t.length>0;){const i=Un(t,e);if(n.push(i.value),0===(t=i.src.trim()).length)return _n(n,t);if(","!==t[0])throw vn(t,Ln);if(0===(t=t.substring(1).trim()).length||","===t[0])throw vn(t,Ln)}return _n(n,t)}(t.trim(),e);if(""!==n)throw vn(n,Ln);return i}catch(e){throw vn(t,Ln,e)}}function zn(t,e){return function(t,e={whitespace:!0}){if(!1===Array.isArray(t))throw Jt(t,Ln);const n=(null==e?void 0:e.whitespace)?" ":"";return t.map(t=>{t instanceof qt==0&&(t=new qt(t));const e=t;return Array.isArray(e.value)?_e(e):ge(e)}).join(`,${n}`)}(t,e)}function Vn(t){if("object"!=typeof t||!t)return!1;const{ID:e,"BASE-ID":n,"URI-REPLACEMENT":i}=t;return"string"==typeof e&&"string"==typeof n&&null!=i&&"object"==typeof i}const jn=/\$(RepresentationID|Number|SubNumber|Bandwidth|Time)?(?:%0([0-9]+)([diouxX]))?\$/g;const Wn="cbcs",Hn="cenc",Yn="urn:mpeg:dash:mp4protection:2011";function Xn(t){if(!t)return{};const e=new DataView(t instanceof ArrayBuffer?t:t.buffer),n={};let i=0;for(;!(i>=e.byteLength);){const r=i,s=i+e.getUint32(i);if(i+=4,1886614376!==e.getUint32(i)){i=s;continue}i+=4;const o=e.getUint8(i);if(0!==o&&1!==o){i=s;continue}i+=1,i+=3;let a,c="";for(let t=0;t<4;t++)a=e.getUint8(i+t).toString(16),c+=1===a.length?"0"+a:a;i+=4,c+="-";for(let t=0;t<2;t++)a=e.getUint8(i+t).toString(16),c+=1===a.length?"0"+a:a;i+=2,c+="-";for(let t=0;t<2;t++)a=e.getUint8(i+t).toString(16),c+=1===a.length?"0"+a:a;i+=2,c+="-";for(let t=0;t<2;t++)a=e.getUint8(i+t).toString(16),c+=1===a.length?"0"+a:a;i+=2,c+="-";for(let t=0;t<6;t++)a=e.getUint8(i+t).toString(16),c+=1===a.length?"0"+a:a;i+=6,c=c.toLowerCase(),i+=4,n[c]=t.slice(r,s),i=s}return n}function qn(t,e){const n={};return t&&t.length>0&&(n.audioCapabilities=t),e&&e.length>0&&(n.videoCapabilities=e),n.distinctiveIdentifier="optional",n.persistentState="optional",n.sessionTypes=["temporary"],n}const Gn="undefined"!=typeof MediaKeys&&"function"==typeof MediaKeys.isTypeSupported?MediaKeys.isTypeSupported:void 0;function Kn(t,e){if(!e||void 0===Gn)return{supportedAudio:[],supportedVideo:[]};for(const n of e){const e=n.audioCapabilities||[],i=n.videoCapabilities||[],r=e.filter(e=>{var n;return Gn(t,null!==(n=e.contentType)&&void 0!==n?n:"")}),s=i.filter(e=>{var n;return Gn(t,null!==(n=e.contentType)&&void 0!==n?n:"")}),o=r.length>0,a=s.length>0;if(o||a)return{supportedAudio:r,supportedVideo:s}}return{supportedAudio:[],supportedVideo:[]}}function Jn(t){const e=new ArrayBuffer(2*t.length),n=new DataView(e);for(let e=0;e<t.length;e++)n.setUint16(2*e,t.charCodeAt(e),!0);return new Uint16Array(e)}const Qn="utf-16",Zn="utf-16be",ti="utf-16le",ei="utf-8";function ni(t,e={}){let n;n=t instanceof ArrayBuffer?new DataView(t):new DataView(t.buffer,t.byteOffset,t.byteLength);let i=0,{encoding:r}=e;if(!r){const t=n.getUint8(0),e=n.getUint8(1);239==t&&187==e&&191==n.getUint8(2)?(r=ei,i=3):254==t&&255==e?(r=Zn,i=2):255==t&&254==e?(r=ti,i=2):r=ei}if("undefined"!=typeof TextDecoder)return new TextDecoder(r).decode(n);const{byteLength:s}=n,o=r!==Zn;let a,c="";for(;i<s;){switch(r){case ei:if(a=n.getUint8(i),a<128)i++;else if(a>=194&&a<=223)if(i+1<s){const t=n.getUint8(i+1);t>=128&&t<=191?(a=(31&a)<<6|63&t,i+=2):i++}else i++;else if(a>=224&&a<=239)if(i+2<=s-1){const t=n.getUint8(i+1),e=n.getUint8(i+2);t>=128&&t<=191&&e>=128&&e<=191?(a=(15&a)<<12|(63&t)<<6|63&e,i+=3):i++}else i++;else if(a>=240&&a<=244)if(i+3<=s-1){const t=n.getUint8(i+1),e=n.getUint8(i+2),r=n.getUint8(i+3);t>=128&&t<=191&&e>=128&&e<=191&&r>=128&&r<=191?(a=(7&a)<<18|(63&t)<<12|(63&e)<<6|63&r,i+=4):i++}else i++;else i++;break;case Zn:case Qn:case ti:a=n.getUint16(i,o),i+=2}c+=String.fromCodePoint(a)}return c}function ii(t,e=Qn){return ni(t,{encoding:e}).split("skd://")[1]||""}function ri(t,e,n=[]){if(!t)return n;if(t.nodeName===e&&n.push(t),t.childNodes)for(const i of t.childNodes)ri(i,e,n);return n}const si=/&(?:amp|lt|gt|quot|apos|nbsp|lrm|rlm|#[xX]?[0-9a-fA-F]+);/g;function oi(t){return-1===t.indexOf("&")?t:t.replace(si,t=>{switch(t){case"&amp;":return"&";case"&lt;":return"<";case"&gt;":return">";case"&quot;":return'"';case"&apos;":return"'";case"&nbsp;":return" ";case"&lrm;":return"‎";case"&rlm;":return"‏";default:if("#"===t[1]){const e="x"===t[2]||"X"===t[2]?parseInt(t.slice(3),16):parseInt(t.slice(2),10);return String.fromCodePoint(e)}return t}})}function ai(t,e={}){let n=e.pos||0;const i=t.length,r=!!e.keepComments,s=!!e.keepWhitespace,o="<".charCodeAt(0),a=">".charCodeAt(0),c="-".charCodeAt(0),l="/".charCodeAt(0),u="?".charCodeAt(0),h="!".charCodeAt(0),d="'".charCodeAt(0),f='"'.charCodeAt(0),p="[".charCodeAt(0),m="]".charCodeAt(0);function g(t,e="#text"){return{nodeName:e,nodeValue:t,attributes:{},childNodes:[]}}function _(e=""){const d=[];for(;t[n];)if(t.charCodeAt(n)==o){if(t.charCodeAt(n+1)===l){const i=n+2;if(n=t.indexOf(">",n),!t.startsWith(e,i)){const e=t.substring(0,n).split("\n");throw new Error("Unexpected close tag\nLine: "+(e.length-1)+"\nColumn: "+(e[e.length-1].length+1)+"\nChar: "+t[n])}return n+1&&(n+=1),d}if(t.charCodeAt(n+1)===u){n=t.indexOf(">",n),n++;continue}if(t.charCodeAt(n+1)===h){if(t.charCodeAt(n+2)==c){const e=n;for(;-1!==n&&(t.charCodeAt(n)!==a||t.charCodeAt(n-1)!=c||t.charCodeAt(n-2)!=c||-1==n);)n=t.indexOf(">",n+1);-1===n&&(n=i),r&&d.push(g(t.substring(e,n+1),"#comment"))}else{if(t.charCodeAt(n+2)===p&&t.charCodeAt(n+8)===p&&t.startsWith("CDATA",n+3)){const e=t.indexOf("]]>",n);-1==e?(d.push(g(t.substr(n+9),"#cdata")),n=i):(d.push(g(t.substring(n+9,e),"#cdata")),n=e+3);continue}{const e=n+1;n+=2;let i=!1;for(;(t.charCodeAt(n)!==a||!0===i)&&t[n];)t.charCodeAt(n)===p?i=!0:!0===i&&t.charCodeAt(n)===m&&(i=!1),n++;d.push(g(t.substring(e,n),"#doctype"))}}n++;continue}const s=b();d.push(s)}else{const t=v();if(s)t.length>0&&d.push(g(t));else{const e=t.trim();e.length>0&&d.push(g(e))}n++}return d}function v(){const e=n;return n=t.indexOf("<",n)-1,-2===n&&(n=i),oi(t.slice(e,n+1))}function y(){const e=n;for(;-1==="\r\n\t>/= ".indexOf(t[n])&&t[n];)n++;return t.slice(e,n)}function b(){n++;const e=y();let i=e,r=null;const s=e.indexOf(":");-1!==s&&(r=e.slice(0,s),i=e.slice(s+1));const o=function(){const e={};for(;t.charCodeAt(n)!==a&&t[n];){const i=t.charCodeAt(n);if(i>64&&i<91||i>96&&i<123){const i=y();let r="",s=t.charCodeAt(n);for(;s!==d&&s!==f;)n++,s=t.charCodeAt(n);if(s===d||s===f){if(r=S(),-1===n)throw new Error("Missing closing quote")}else n--;e[i]=oi(r)}n++}return e}();let c=[];const u=t.charCodeAt(n-1);return n++,u!==l&&(c=_(e)),{nodeName:e,nodeValue:null,attributes:o,childNodes:c,prefix:r,localName:i}}function S(){const e=t[n],i=n+1;return n=t.indexOf(e,i),t.slice(i,n)}return{nodeName:"#document",nodeValue:null,childNodes:_(""),attributes:{}}}const ci="Challenge",li="PlayReadyKeyMessage";const ui="Content-Type",hi="HttpHeaders",di="text/xml; charset=utf-8";const fi={CENC:Hn,CBCS:Wn},pi="expired",mi="HW_SECURE_ALL",gi="HW_SECURE_CRYPTO",_i="HW_SECURE_DECODE",vi="individualization-request",yi="keyids",bi="webm",Si={CENC:Hn,CBCS:Wn,KEYIDS:yi,WEBM:bi},wi="internal-error",Ti="license-release",Ci="license-renewal",Ei="license-request",Ri={LICENSE_REQUEST:Ei,LICENSE_RENEWAL:Ci,LICENSE_RELEASE:Ti,INDIVIDUALIZATION_REQUEST:vi},ki="output-downscaled",Ui="output-restricted",xi="released",Ai="status-pending",Ii="usable",Mi={USABLE:Ii,EXPIRED:pi,RELEASED:xi,OUTPUT_RESTRICTED:Ui,OUTPUT_DOWNSCALED:ki,STATUS_PENDING:Ai,INTERNAL_ERROR:wi},Di="SW_SECURE_CRYPTO",Oi="SW_SECURE_DECODE",Ni={SW_SECURE_CRYPTO:Di,SW_SECURE_DECODE:Oi,HW_SECURE_CRYPTO:gi,HW_SECURE_DECODE:_i,HW_SECURE_ALL:mi};function Pi(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function $i(t,e){let n=0;return n=(127&t[e])<<21,n|=(127&t[e+1])<<14,n|=(127&t[e+2])<<7,n|=127&t[e+3],n}function Bi(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Li(t,e=!1){const n=e?t.indexOf(0):t.length,i=ni(new DataView(t.buffer,t.byteOffset,n),{encoding:ei});return e?i:i.replace(/\0/g,"")}function Fi(t,e=0,n=1/0){return function(t,e,n,i){const r=function(t){return t instanceof ArrayBuffer?t:t.buffer}(t);let s=1;"BYTES_PER_ELEMENT"in i&&(s=i.BYTES_PER_ELEMENT);const o=(h=t,h&&h.buffer instanceof ArrayBuffer&&void 0!==h.byteLength&&void 0!==h.byteOffset?t.byteOffset:0),a=(o+t.byteLength)/s,c=(o+e)/s,l=Math.floor(Math.max(0,Math.min(c,a))),u=Math.floor(Math.min(l+Math.max(n,0),a));var h;return new i(r,l,u-l)}(t,e,n,Uint8Array)}function zi(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const n=t.data.subarray(1).indexOf(0);if(-1===n)return;const i=Li(Fi(t.data,1,n)),r=t.data[2+n],s=t.data.subarray(3+n).indexOf(0);if(-1===s)return;const o=Li(Fi(t.data,3+n,s));let a;return a="--\x3e"===i?Li(Fi(t.data,4+n+s)):function(t){return t instanceof ArrayBuffer?t:0==t.byteOffset&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}(t.data.subarray(4+n+s)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=a,e}function Vi(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=Li(t.data,!0),n=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:n.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const n=Li(t.data.subarray(e),!0);e+=n.length+1;const i=Li(t.data.subarray(e));return{key:t.type,info:n,data:i}}const e=Li(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?zi(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const{data:n}=t,i=Li(n.subarray(e),!0);e+=i.length+1;const r=Li(n.subarray(e));return{key:t.type,info:i,data:r}}const e=Li(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function ji(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),n=$i(t,4);return{type:e,size:n,data:t.subarray(10,10+n)}}function Wi(t){let e=0;const n=[];for(;Pi(t,e);){const i=$i(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const r=e+i;for(;e+10<r;){const i=ji(t.subarray(e)),r=Vi(i);r&&n.push(r),e+=i.size+10}Bi(t,e)&&(e+=10)}return n}function Hi(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function Yi(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),n=1&e[3];let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,n&&(i+=47721858.84),Math.round(i)}}const Xi=/^([-])?P(?:([\d.]*)Y)?(?:([\d.]*)M)?(?:([\d.]*)D)?T?(?:([\d.]*)H)?(?:([\d.]*)M)?(?:([\d.]*)S)?$/;const qi=["dinf","edts","enca","encv","grpl","mdia","meco","meta","mfra","minf","moof","moov","mvex","prsl","schi","sinf","stbl","strk","traf","trak","tref","udta","vttc"],Gi="data",Ki="int",Ji="string",Qi="template",Zi="uint",tr="utf8";function er(t,e,n){const i=e-t.byteOffset;let r,s,o=NaN;switch(n){case 1:o=t.getUint8(i);break;case 2:o=t.getUint16(i);break;case 3:r=t.getUint16(i),s=t.getUint8(i+2),o=(r<<8)+s;break;case 4:o=t.getUint32(i);break;case 8:r=t.getUint32(i),s=t.getUint32(i+4),o=r*Math.pow(2,32)+s}return o}function nr(t,e,n){let i="";for(let r=0;r<n;r++){const n=er(t,e+r,1);i+=String.fromCharCode(n)}return i}class ir{constructor(t,e){this.truncated=!1,this.slice=t=>{const e=new DataView(this.dataView.buffer,this.offset,t);return this.offset+=t,new ir(e,this.config)},this.read=(t,e=0)=>{const{dataView:n,offset:i}=this;let r,s=e;switch(t){case Zi:r=er(n,i,e);break;case Ki:r=function(t,e,n){let i=NaN;const r=e-t.byteOffset;switch(n){case 1:i=t.getInt8(r);break;case 2:i=t.getInt16(r);break;case 4:i=t.getInt32(r);break;case 8:const e=t.getInt32(r),n=t.getInt32(r+4);i=e*Math.pow(2,32)+n}return i}(n,i,e);break;case Qi:r=function(t,e,n){const i=n/2;return er(t,e,i)+er(t,e+i,i)/Math.pow(2,i)}(n,i,e);break;case Ji:-1===e?(r=function(t,e){let n="",i=e;for(;i-t.byteOffset<t.byteLength;){const e=er(t,i,1);if(0===e)break;n+=String.fromCharCode(e),i++}return n}(n,i),s=r.length+1):r=nr(n,i,e);break;case Gi:r=function(t,e,n){const i=n>0?n:t.byteLength-(e-t.byteOffset);return new Uint8Array(t.buffer,e,Math.max(i,0))}(n,i,e),s=r.length;break;case tr:-1===e?(r=function(t,e){const n=t.byteLength-(e-t.byteOffset);let i="";if(n>0){const r=new DataView(t.buffer,e,n);let s=0;for(;s<n&&0!==r.getUint8(s);s++);i=ni(new DataView(t.buffer,e,s),{encoding:ei})}return i}(n,i),s=r.length+1):r=function(t,e){const n=t.byteLength-(e-t.byteOffset);return n>0?ni(new DataView(t.buffer,e,n),{encoding:ei}):""}(n,i);break;default:r=-1}return this.offset+=s,r},this.readUint=t=>this.read(Zi,t),this.readInt=t=>this.read(Ki,t),this.readString=t=>this.read(Ji,t),this.readTemplate=t=>this.read(Qi,t),this.readData=t=>this.read(Gi,t),this.readUtf8=t=>this.read(tr,t),this.readFullBox=()=>({version:this.readUint(1),flags:this.readUint(3)}),this.readArray=(t,e,n)=>{const i=[];for(let r=0;r<n;r++)i.push(this.read(t,e));return i},this.readBox=()=>{const{dataView:t,offset:e}=this;let n=0;const i={size:er(t,e,4),type:nr(t,e+4,4)};n+=8,1===i.size&&(i.largesize=er(t,e+n,8),n+=8);const r=i.largesize||i.size;if(this.cursor+r>t.byteLength)throw this.truncated=!0,new Error("Truncated box");this.offset+=n,"uuid"===i.type&&(i.usertype=this.readArray("uint",1,16));const s=0===i.size?this.bytesRemaining:r-n;return i.data=this.slice(s),i},this.readBoxes=t=>{const e=[];for(const n of this)if(e.push(n),t>0&&e.length>=t)break;return e},this.readEntries=(t,e)=>{const n=[];for(let i=0;i<t;i++)n.push(e());return n},this.dataView=t instanceof ArrayBuffer?new DataView(t):t instanceof Uint8Array?new DataView(t.buffer,t.byteOffset,t.byteLength):t,this.offset=this.dataView.byteOffset,this.config=e||{recursive:!1,parsers:{}}}get cursor(){return this.offset-this.dataView.byteOffset}get done(){return this.cursor>=this.dataView.byteLength||this.truncated}get bytesRemaining(){return this.dataView.byteLength-this.cursor}*[Symbol.iterator](){const{parsers:t={},recursive:e=!1}=this.config;for(;!this.done;)try{const{type:n,data:i,...r}=this.readBox(),s={type:n,...r},o=t[n]||t[n.trim()];if(o&&Object.assign(s,o(i,this.config)),s.view=i,qi.includes(n)){const t=[];for(const n of i)e&&(yield n),t.push(n);s.boxes=t}yield s}catch(t){break}}}function rr(t,e){return new ir(t,e)}function sr(t,e,n,i){for(const r of t){e(r)&&i.push(r);const{boxes:t}=r;n&&Array.isArray(t)&&sr(t,e,n,i)}return i}function or(t,e,n){var i;(t instanceof DataView||t instanceof Uint8Array||t instanceof ArrayBuffer)&&(t=rr(t,{...n,recursive:!1}));return sr(t,e,null===(i=null==n?void 0:n.recursive)||void 0===i||i,[])}function ar(t,e,n){for(const i of t){if(n(i))return i;const{boxes:t}=i;if(e&&Array.isArray(t)){const i=ar(t,e,n);if(i)return i}}return null}function cr(t,e,n){var i;const r=null===(i=null==n?void 0:n.recursive)||void 0===i||i;return(t instanceof DataView||t instanceof Uint8Array||t instanceof ArrayBuffer)&&(t=rr(t,{...n,recursive:!1})),ar(t,r,e)}function lr(t){const{readArray:e,readUint:n,readInt:i,readTemplate:r,readData:s}=t;return{reserved1:e(Zi,1,6),dataReferenceIndex:n(2),preDefined1:n(2),reserved2:n(2),preDefined2:e(Zi,4,3),width:n(2),height:n(2),horizresolution:r(4),vertresolution:r(4),reserved3:n(4),frameCount:n(2),compressorName:e(Zi,1,32),depth:n(2),preDefined3:i(2),config:s(-1)}}function ur(t){const{readArray:e,readUint:n,readTemplate:i,readData:r}=t;return{reserved1:e(Zi,1,6),dataReferenceIndex:n(2),reserved2:e(Zi,4,2),channelcount:n(2),samplesize:n(2),preDefined:n(2),reserved3:n(2),samplerate:i(4),esds:r(-1)}}function hr(t){return{data:t.readData(-1)}}function dr(t){const e=t.readString(4),n=t.readUint(4),i=t.bytesRemaining/4;return{majorBrand:e,minorVersion:n,compatibleBrands:t.readArray(Ji,4,i)}}const fr="Item";function pr(t){const e=t.duration/1e3;return 8*t.encodedBodySize/e}class mr{constructor(t){this.alpha=t,this.estimate=0,this.totalDuration=0}sample(t,e){const n=Math.pow(this.alpha,t);this.estimate=n*e+(1-n)*this.estimate,this.totalDuration+=t}getEstimate(){const t=1-Math.pow(this.alpha,this.totalDuration);return this.estimate/t}getTotalDuration(){return this.totalDuration}}function gr(t){return new Uint8Array(t).reduce((t,e)=>t+e.toString(16).padStart(2,"0"),"")}const _r={UTF8:ei,UTF16:Qn,UTF16BE:Zn,UTF16LE:ti};function vr(t){const e=new ArrayBuffer(t.length/2),n=new Uint8Array(e);for(let e=0;e<t.length;e+=2)n[e/2]=parseInt(t.slice(e,e+2),16);return e}function yr(){return{id:"",startTime:0,endTime:0,region:null,snapToLines:!0,line:"auto",lineAlign:"start",position:"auto",positionAlign:"auto",size:100,align:"center",vertical:"",pauseOnExit:!1,text:""}}function br(){return{id:"",width:100,lines:3,regionAnchorX:0,regionAnchorY:100,viewportAnchorX:0,viewportAnchorY:100,scroll:""}}class Sr extends Error{constructor(t){super(t),this.name="WebVttParsingError"}}function wr(t,e,n,i){const r=i?t.split(i):[t];for(const t in r){if("string"!=typeof r[t])continue;const i=r[t].split(n);if(2!==i.length)continue;e(i[0],i[1].trim())}}function Tr(t,e,n,i){return 3600*(0|t)+60*(0|e)+(0|n)+(0|i)/1e3}function Cr(t){var e;const n=t.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);if(!n)return null;const i=parseInt(n[1]),r=parseInt(n[2]),s=parseInt((null===(e=n[3])||void 0===e?void 0:e.replace(":",""))||"0"),o=parseInt(n[4]);return n[3]?Tr(i,r,s,o):i>59?Tr(i,r,0,o):Tr(0,i,r,o)}class Er{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e){return this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,n){for(let i=0;i<n.length;++i)if(e===n[i]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(e.match(/^([\d]{1,3})(\.[\d]*)?%$/)){const n=parseFloat(e);if(n>=0&&n<=100)return this.set(t,n),!0}return!1}}const Rr="Malformed time stamp.";function kr(t,e,n){const i=t;function r(){const e=Cr(t);if(null===e)throw new Sr(Rr+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function s(){t=t.replace(/^\s+/,"")}if(s(),e.startTime=r(),s(),"--\x3e"!==t.substr(0,3))throw new Sr(Rr+" (time stamps must be separated by '--\x3e'): ");t=t.substr(3),s(),e.endTime=r(),s(),function(t,e){const i=new Er;wr(t,function(t,e){switch(t){case"region":for(let r=n.length-1;r>=0;r--)if(n[r].id===e){i.set(t,n[r]);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":{const n=e.split(","),r=n[0];i.integer(t,r),i.percent(t,r)&&i.set("snapToLines",!1),i.alt(t,r,["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start","center","end"]);break}case"position":{const n=e.split(",");i.percent(t,n[0]),2===n.length&&i.alt("positionAlign",n[1],["line-left","center","line-right","auto"]);break}case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start","center","end","left","right"])}},/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");try{e.line=i.get("line","auto")}catch(t){}e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100);try{e.align=i.get("align","center")}catch(t){e.align=i.get("align","middle")}try{e.position=i.get("position","auto")}catch(t){const n={start:0,left:0,center:50,middle:50,end:100,right:100};e.position=i.get("position",n[e.align])}e.positionAlign=i.get("positionAlign","auto")}(t,e)}const Ur="INITIAL",xr="HEADER",Ar="REGION",Ir="STYLE",Mr="NOTE",Dr="BLOCKS",Or="ID",Nr="CUE",Pr="CUE_EXT",$r="BAD_CUE",Br="BAD_WEBVTT",Lr="Malformed WebVTT signature.",Fr=()=>"undefined"!=typeof VTTCue?new VTTCue(0,0,""):{id:"",startTime:0,endTime:0,region:null,snapToLines:!0,line:"auto",lineAlign:"start",position:"auto",positionAlign:"auto",size:100,align:"center",vertical:"",pauseOnExit:!1,text:""},zr=()=>"undefined"!=typeof VTTRegion?new VTTRegion:{id:"",width:100,lines:3,regionAnchorX:0,regionAnchorY:100,viewportAnchorX:0,viewportAnchorY:100,scroll:""};class Vr{constructor(t={}){var e;this.regionSettings=null,this.cue=null;const n=null===(e=t.useDomTypes)||void 0===e||e;this.createCue=t.createCue||n?Fr:yr,this.createRegion=t.createRegion||n?zr:br,this.state=Ur,this.buffer="",this.style="",this.regionList=[]}parse(t,e=!1){var n,i,r,s,o,a;t&&(this.buffer+=t);const c=()=>{const t=this.buffer;let e=0;for(;e<t.length&&"\r"!==t[e]&&"\n"!==t[e];)++e;const n=t.substr(0,e);return"\r"===t[e]&&++e,"\n"===t[e]&&++e,this.buffer=t.substr(e),n},l=t=>{var e;const n=new Er;wr(t,(t,e)=>{switch(t){case"MPEGT":n.integer(t+"S",e);break;case"LOCA":n.set(t+"L",Cr(e))}},/[^\d]:/,/,/),null===(e=this.ontimestampmap)||void 0===e||e.call(this,{MPEGTS:n.get("MPEGTS"),LOCAL:n.get("LOCAL")})},u=t=>{t.match(/X-TIMESTAMP-MAP/)&&wr(t,(t,e)=>{if("X-TIMESTAMP-MAP"===t)l(e)},/=/)};try{let t;if(this.state===Ur){if(!/\r\n|\n/.test(this.buffer))return this;t=c(),65279===t.charCodeAt(0)&&(t=t.slice(1));const e=t.match(/^WEBVTT([ \t].*)?$/);if(!e||!e[0])throw new Sr(Lr);this.state=xr}let l=!1;var h=e;for(e||(this.cue=null,this.regionSettings=null);this.buffer;){if(!/\r\n|\n/.test(this.buffer))return this;switch(l?l=!1:t=c(),this.state){case xr:/:/.test(t)?u(t):t||(this.state=Dr);continue;case Ar:if(!t&&this.regionSettings){const t=this.createRegion();t.id=this.regionSettings.get("id",""),t.width=this.regionSettings.get("width",100),t.lines=this.regionSettings.get("lines",3),t.regionAnchorX=this.regionSettings.get("regionanchorX",0),t.regionAnchorY=this.regionSettings.get("regionanchorY",100),t.viewportAnchorX=this.regionSettings.get("viewportanchorX",0),t.viewportAnchorY=this.regionSettings.get("viewportanchorY",100),t.scroll=this.regionSettings.get("scroll",""),null===(n=this.onregion)||void 0===n||n.call(this,t),this.regionList.push(t),this.regionSettings=null,this.state=Dr;break}null===this.regionSettings&&(this.regionSettings=new Er);const e=this.regionSettings;wr(t,(t,n)=>{switch(t){case"id":e.set(t,n);break;case"width":e.percent(t,n);break;case"lines":e.integer(t,n);break;case"regionanchor":case"viewportanchor":const i=n.split(",");if(2!==i.length)break;const r=new Er;if(r.percent("x",i[0]),r.percent("y",i[1]),!r.has("x")||!r.has("y"))break;e.set(t+"X",r.get("x")),e.set(t+"Y",r.get("y"));break;case"scroll":e.alt(t,n,["up"])}},/:/,/\s/);continue;case Ir:if(!t){null===(i=this.onstyle)||void 0===i||i.call(this,this.style),this.style="",this.state=Dr;break}this.style+=t+"\n";continue;case Mr:t||(this.state=Or);continue;case Dr:if(!t)continue;if(/^NOTE($[ \t])/.test(t)){this.state=Mr;break}if(/^REGION/.test(t)&&!h){this.state=Ar;break}if(/^STYLE/.test(t)&&!h){this.state=Ir;break}this.state=Or;case Or:if(/^NOTE($|[ \t])/.test(t)){this.state=Mr;break}if(!t)continue;if(h=!0,this.cue=this.createCue(),null!==(r=(a=this.cue).text)&&void 0!==r||(a.text=""),this.state=Nr,-1===t.indexOf("--\x3e")){this.cue.id=t;continue}case Nr:try{kr(t,this.cue,this.regionList)}catch(t){this.reportOrThrowError(t),this.cue=null,this.state=$r;continue}this.state=Pr;continue;case Pr:const c=-1!==t.indexOf("--\x3e");if(!t||c&&(l=!0)){null===(s=this.oncue)||void 0===s||s.call(this,this.cue),this.cue=null,this.state=Or;continue}(null===(o=this.cue)||void 0===o?void 0:o.text)&&(this.cue.text+="\n"),this.cue.text+=t.replace(/\u2028/g,"\n").replace(/u2029/g,"\n");continue;case $r:t||(this.state=Or);continue}}}catch(t){this.reportOrThrowError(t),this.state===Pr&&this.cue&&this.oncue&&this.oncue(this.cue),this.cue=null,this.regionSettings=null,this.state=this.state===Ur?Br:$r}return this}flush(){var t;try{if(this.buffer+="",(this.cue||this.state===xr)&&(this.buffer+="\n\n",this.parse(void 0,!0)),this.state===Ur)throw new Sr(Lr)}catch(t){this.reportOrThrowError(t)}return null===(t=this.onflush)||void 0===t||t.call(this),this}reportOrThrowError(t){var e;if(!(t instanceof Sr))throw t;null===(e=this.onparsingerror)||void 0===e||e.call(this,t)}}const jr="cue",Wr="region",Hr="timestampmap",Yr="style",Xr="error";class qr{constructor(){this.results=[],this.parser=new Vr,this.parser.oncue=t=>this.results.push({type:jr,data:t}),this.parser.onregion=t=>this.results.push({type:Wr,data:t}),this.parser.onstyle=t=>this.results.push({type:Yr,data:t}),this.parser.ontimestampmap=t=>this.results.push({type:Hr,data:t}),this.parser.onparsingerror=t=>this.results.push({type:Xr,data:t})}enqueueResults(t){for(const e of this.results)t.enqueue(e);this.results=[]}transform(t,e){try{this.parser.parse(t),this.enqueueResults(e)}catch(t){e.error(t)}}flush(t){try{this.parser.flush(),this.enqueueResults(t)}catch(e){t.error(e)}}}class Gr extends TransformStream{constructor(t,e){super(new qr,t,e)}}var Kr=Object.freeze({__proto__:null,ArithmeticMeanEstimator:class{constructor(){this.samples=[]}sample(t){this.samples.push(t)}getEstimate(){let t=0;for(let e=0;e<this.samples.length;e++)t+=pr(this.samples[e]);return t/this.samples.length}},CBCS:Wn,CENC:Hn,CHALLENGE:ci,CLEAR_KEY_SYSTEM:"org.w3.clearkey",CLEAR_KEY_UUID:"e2719d58-a985-b3c9-781a-b030af78d30e",CMCD_COMMON_KEYS:Pe,CMCD_DEFAULT_TIME_INTERVAL:30,CMCD_EVENT_KEYS:$e,CMCD_EVENT_MODE:Ue,CMCD_FORMATTER_MAP:De,CMCD_HEADERS:en,CMCD_JSON:nn,CMCD_KEYS:sn,CMCD_OBJECT:ye,CMCD_PARAM:Ke,CMCD_QUERY:on,CMCD_REQUEST:be,CMCD_REQUEST_KEYS:ze,CMCD_REQUEST_MODE:Oe,CMCD_RESPONSE_KEYS:je,CMCD_RESPONSE_MODE:Ne,CMCD_SESSION:Se,CMCD_STATUS:we,CMCD_V1:1,CMCD_V1_KEYS:He,CMCD_V2:2,CMSD_DYNAMIC:Dn,CMSD_STATIC:On,CMSD_V1:1,CONTENT_TYPE:ui,CaptionScreen:q,CaptionsLogger:F,CmcdEncoding:cn,CmcdEventType:{PLAY_STATE:"ps",ERROR:"e",TIME_INTERVAL:"t",CONTENT_ID:"c",BACKGROUNDED_MODE:"b",MUTE:"m",UNMUTE:"um",PLAYER_EXPAND:"pe",PLAYER_COLLAPSE:"pc"},CmcdFormatters:ln,CmcdHeaderField:Ce,CmcdObjectType:hn,CmcdPlayerState:{STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",WAITING:"w",ENDED:"e",FATAL_ERROR:"f",QUIT:"q",PRELOADING:"d"},CmcdReportingMode:dn,CmcdStreamType:gn,CmcdStreamingFormat:pn,CmcdTransmissionMode:an,CmsdHeaderField:Nn,CmsdObjectType:Pn,CmsdStreamType:Bn,CmsdStreamingFormat:$n,Cta608Channel:G,Cta608Parser:class{constructor(t,e,n){this.currentChannel=0,this.cmdHistory={a:null,b:null},this.lastTime=null;const i=this.logger=new F;this.channels=[null,new G(t,e,i),new G(t+1,n,i)]}addData(t,e){this.lastTime=t,this.logger.time=t;for(let n=0;n<e.length;n+=2){const i=127&e[n],r=127&e[n+1];let s=!1,o=null;if(null!==this.lastTime&&(t=this.lastTime+.5*n*1001/3e4,this.logger.time=t),0===i&&0===r)continue;this.logger.log(L.DATA,()=>"["+Q([e[n],e[n+1]])+"] -> ("+Q([i,r])+")");const a=this.cmdHistory;if(i>=16&&i<=31){if(J(i,r,a)){it(null,null,a),this.logger.log(L.DEBUG,()=>"Repeated command ("+Q([i,r])+") is dropped");continue}it(i,r,this.cmdHistory),s=this.parseCmd(i,r),s||(s=this.parseMidrow(i,r)),s||(s=this.parsePAC(i,r)),s||(s=this.parseBackgroundAttributes(i,r))}else it(null,null,a);if(!s&&(o=this.parseChars(i,r),o.length)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(o)}else this.logger.log(L.WARNING,"No channel found yet. TEXT-MODE?")}s||o||this.logger.log(L.WARNING,()=>"Couldn't parse cleaned data "+Q([i,r])+" orig: "+Q([e[n],e[n+1]]))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const n=20===t||21===t||23===t?1:2,i=this.channels[n];return 20===t||21===t||28===t||29===t?32===e?i.ccRCL():33===e?i.ccBS():34===e?i.ccAOF():35===e?i.ccAON():36===e?i.ccDER():37===e?i.ccRU(2):38===e?i.ccRU(3):39===e?i.ccRU(4):40===e?i.ccFON():41===e?i.ccRDC():42===e?i.ccTR():43===e?i.ccRTD():44===e?i.ccEDM():45===e?i.ccCR():46===e?i.ccENM():47===e&&i.ccEOC():i.ccTO(e-32),this.currentChannel=n,!0}parseMidrow(t,e){let n=0;if((17===t||25===t)&&e>=32&&e<=47){if(n=17===t?1:2,n!==this.currentChannel)return this.logger.log(L.ERROR,"Mismatch channel in midrow parsing"),!1;const i=this.channels[n];return!!i&&(i.ccMIDROW(e),this.logger.log(L.DEBUG,()=>"MIDROW ("+Q([t,e])+")"),!0)}return!1}parsePAC(t,e){let n;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const i=t<=23?1:2;n=e>=64&&e<=95?1===i?et[t]:nt[t]:1===i?Z[t]:tt[t];const r=this.channels[i];return!!r&&(r.setPAC(this.interpretPAC(n,e)),this.currentChannel=i,!0)}interpretPAC(t,e){let n;const i={color:null,italics:!1,indent:null,underline:!1,row:t};return n=e>95?e-96:e-64,i.underline=!(1&~n),n<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)]:n<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((n-16)/2),i}parseChars(t,e){let n,i=[],r=null;if(t>=25?(n=2,r=t-8):(n=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(L.INFO,()=>"Special char '"+H(t)+"' in channel "+n),i=[t]}else t>=32&&t<=127&&(i=0===e?[t]:[t,e]);return i&&this.logger.log(L.DEBUG,()=>"Char codes =  "+Q(i).join(",")),i}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let n;const i={};16===t||24===t?(n=Math.floor((e-32)/2),i.background=K[n],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));const r=t<=23?1:2;return this.channels[r].setBkgData(i),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}it(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const n=this.channels[e];n&&n.cueSplitAtTime(t)}}},DATA:Gi,DEFAULT_PATHWAY_PENALTY:3e5,DEFAULT_TTL:300,EXPIRED:pi,Encoding:_r,EncryptionScheme:fi,Ewma:mr,EwmaEstimator:class{constructor(t){this.slowEwma=new mr(t.slowHalfLife),this.fastEwma=new mr(t.fastHalfLife)}sample(t){const e=t.duration/1e3,n=pr(t);this.slowEwma.sample(e,n),this.fastEwma.sample(e,n)}getEstimate(){return Math.min(this.fastEwma.getEstimate(),this.slowEwma.getEstimate())}canEstimate(){return!0}},FAIRPLAY_KEY_SYSTEM:"com.apple.fps.1_0",FAIRPLAY_UUID:"29701fe4-3cc7-4a34-8c5b-ae90c7439a47",HTTP_HEADERS:hi,HW_SECURE_ALL:mi,HW_SECURE_CRYPTO:gi,HW_SECURE_DECODE:_i,HarmonicMeanEstimator:class{constructor(){this.samples=[]}sample(t){this.samples.push(t)}getEstimate(){let t=0;for(let e=0;e<this.samples.length;e++)t+=1/pr(this.samples[e]);return this.samples.length/t}},ID3_SCHEME_ID_URI:"https://aomedia.org/emsg/ID3",INDIVIDUALIZATION_REQUEST:vi,INT:Ki,INTERNAL_ERROR:wi,InitializationDataType:Si,IsoView:ir,KEYIDS:yi,LICENSE_ACQUISITION:"LicenseAcquisition",LICENSE_RELEASE:Ti,LICENSE_RENEWAL:Ci,LICENSE_REQUEST:Ei,MP4_PROTECTION_SCHEME:Yn,MediaKeyMessageType:Ri,MediaKeyStatus:Mi,OUTPUT_DOWNSCALED:ki,OUTPUT_RESTRICTED:Ui,PLAYREADY_KEY_MESSAGE:li,PLAYREADY_KEY_SYSTEM:"com.microsoft.playready",PLAYREADY_RECOMMENDATION_KEY_SYSTEM:"com.microsoft.playready.recommendation",PLAYREADY_UUID:"9a04f079-9840-4286-ab92-e65be0885f95",PenState:z,RELEASED:xi,Row:Y,STATUS_PENDING:Ai,STRING:Ji,SW_SECURE_CRYPTO:Di,SW_SECURE_DECODE:Oi,SccParser:class{constructor(t,e=1){this.hasHeader=!1,this.nrLinesParsed=0,this.processor=t,this.field=e}parse(t){const e=t.split(/\r?\n/);this.nrLinesParsed=0,"Scenarist_SCC V1.0"===e[0]&&(this.hasHeader=!0,this.nrLinesParsed++);for(let t=1;t<e.length&&""===e[t];t+=2){this.nrLinesParsed++;const n=this.parseDataLine(e[t+1]);if(null===n)break;this.nrLinesParsed++,this.processor.addData(n[0],n[1])}}parseDataLine(t){if(!t)return null;const e=t.split(/\s+/),n=e[0],i=[];for(let t=1;t<e.length;t++){const n=e[t],r=parseInt(n.substring(0,2),16),s=parseInt(n.substring(2,4),16);i.push(r,s)}return[this.timeConverter(n),i]}timeConverter(t){const e=t.split(":");if(3===e.length){const t=e[2].split(";");e[2]=t[0];const n=parseInt(t[1],10);return 1001*(30*(60*(60*parseInt(e[0],10)+parseInt(e[1],10))+parseInt(e[2],10))+n)/3e4}return 0}getHeaderStatus(){return this.hasHeader}getField(){return this.field}getLinesParsed(){return this.nrLinesParsed}},SfItem:qt,SfToken:Qt,StyledUnicodeChar:V,TEMPLATE:Qi,TEXT_XML_UTF8:di,THUMBNAIL_TILE_SCHEME_ID_URI:"http://dashif.org/guidelines/thumbnail_tile",UINT:Zi,USABLE:Ii,UTF8:tr,UTF_16:Qn,UTF_16_BE:Zn,UTF_16_LE:ti,UTF_8:ei,VerboseLevel:L,W3C_CLEAR_KEY_UUID:"1077efec-c0b2-4d02-ace3-3c1e52e2fb4b",WEBM:bi,WIDEVINE_KEY_SYSTEM:"com.widevine.alpha",WIDEVINE_UUID:"edef8ba9-79d6-4ace-a3c8-27dcd51d21ed",WebVttParser:Vr,WebVttParsingError:Sr,WebVttTransformStream:Gr,WebVttTransformer:qr,WidevineRobustness:Ni,ZlemaEstimator:class{constructor(){this.samples=[]}sample(t){this.samples.push(t)}getEstimate(){if(0===this.samples.length)return NaN;const t=2/(this.samples.length+1);let e,n;e=n=pr(this.samples[this.samples.length-1]);for(let i=0;i<this.samples.length;i++)e=t*pr(this.samples[i])+(1-t)*e,n=t*e+(1-t)*n;return n}},appendCmcdHeaders:function(t,e,n){return Object.assign(t,Ge(e,n))},appendCmcdQuery:function(t,e,n){const i=Ze(e,n);if(!i)return t;if(tn.test(t))return t.replace(tn,i);const r=t.includes("?")?"&":"?";return`${t}${r}${i}`},ardi:function(t){return{...t.readFullBox(),audioRenderingIndication:t.readUint(1)}},arrayBufferToHex:gr,arrayBufferToUuid:function(t){return gr(t).replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5")},avc1:lr,avc2:function(t){return lr(t)},avc3:function(t){return lr(t)},avc4:function(t){return lr(t)},base64decode:function(t){return bn(t)},base64encode:function(t){return ee(t)},canParseId3:function(t,e){return Pi(t,e)&&$i(t,e+6)+10<=t.length-e},concatInitDataIdAndCertificate:function(t,e,n){"string"==typeof e&&(e=Jn(e));const i=new ArrayBuffer(t.byteLength+4+e.byteLength+4+n.byteLength),r=new DataView(i);let s=0;return new Uint8Array(i,s,t.byteLength).set(t),s+=t.byteLength,r.setUint32(s,e.byteLength,!0),s+=4,new Uint16Array(i,s,e.length).set(e),s+=e.byteLength,r.setUint32(s,n.byteLength,!0),s+=4,new Uint8Array(i,s,n.byteLength).set(n),new Uint8Array(i)},convertUint8ToUint16:function(t){if(t.length%2!=0){const e=new Uint8Array(t.length+1);return e.set(t),new Uint16Array(e.buffer)}return new Uint16Array(t.buffer)},createIsoView:rr,createMediaKeySystemConfiguration:qn,createWebVttCue:yr,createWebVttRegion:br,ctts:function(t){const{version:e,flags:n}=t.readFullBox(),i=1===e?t.readInt:t.readUint,r=t.readUint(4);return{version:e,flags:n,entryCount:r,entries:t.readEntries(r,()=>({sampleCount:t.readUint(4),sampleOffset:i(4)}))}},dashToHam:function(t){const e=xt.getInstance();return e.setStrategy(new Ut),e.getHamFormat({manifest:t,type:"dash"})},decodeBase64:bn,decodeCmcd:In,decodeCmsdDynamic:function(t){return t?Fn(t):[]},decodeCmsdStatic:function(t){return t?Object.entries(xn(t)).reduce((t,[e,n])=>{const{value:i}=n;return t[e]="symbol"==typeof i?ue(i):i,t},{}):{}},decodeFairPlayLicense:function(t){return"string"==typeof t?bn(t):new Uint8Array(t)},decodeIso8601Duration:function(t){const e=Xi.exec(t);if(!e)return NaN;const n=31536e3*Number(e[2]||0)+2592e3*Number(e[3]||0)+86400*Number(e[4]||0)+3600*Number(e[5]||0)+60*Number(e[6]||0)+Number(e[7]||0);return isFinite(n)?void 0===e[1]?n:-n:NaN},decodeSfDict:xn,decodeSfItem:function(t,e){try{const{src:n,value:i}=kn(t.trim(),e);if(""!==n)throw vn(n,fr);return i}catch(e){throw vn(t,fr,e)}},decodeSfList:Fn,decodeText:ni,dref:function(t){const{version:e,flags:n}=t.readFullBox(),i=t.readUint(4);return{version:e,flags:n,entryCount:i,entries:t.readBoxes(i)}},elng:function(t){return{...t.readFullBox(),extendedLanguage:t.readUtf8(-1)}},elst:function(t){const{version:e,flags:n}=t.readFullBox(),i=1===e?8:4,r=t.readUint(4);return{version:e,flags:n,entryCount:r,entries:t.readEntries(r,()=>({segmentDuration:t.readUint(i),mediaTime:t.readInt(i),mediaRateInteger:t.readInt(2),mediaRateFraction:t.readInt(2)}))}},emsg:function(t){const{readUint:e,readString:n,readData:i}=t,r={...t.readFullBox()};return 1==r.version?(r.timescale=e(4),r.presentationTime=e(8),r.eventDuration=e(4),r.id=e(4),r.schemeIdUri=n(-1),r.value=n(-1)):(r.schemeIdUri=n(-1),r.value=n(-1),r.timescale=e(4),r.presentationTimeDelta=e(4),r.eventDuration=e(4),r.id=e(4)),r.messageData=i(-1),r},enca:function(t){return ur(t)},encodeBase64:ee,encodeCmcd:Je,encodeCmsdDynamic:function(t,e){if(!t)return"";if("string"==typeof t){if(!e)return"";t=[new qt(t,e)]}return zn(t,{whitespace:!1})},encodeCmsdStatic:function(t,e){return t?ve(function(t,e){const n={};if(null==t||"object"!=typeof t)return n;const i=Object.keys(t),r=!1!==(null==e?void 0:e.useSymbol);return i.forEach(e=>{let i=t[e];"v"===e&&1===i||ke(i)&&(Re(e)&&"string"==typeof i&&(i=r?Symbol.for(i):new Qt(i)),n[e]=i)}),n}(t,e),{whitespace:!1}):""},encodeIso8601Duration:function(t){if(!isFinite(t))return"PT";const e=Math.floor(t/3600),n=Math.floor(t%3600/60),i=t%60;return e>0?`PT${e}H${n}M${i}S`:n>0?`PT${n}M${i}S`:`PT${i}S`},encodeSfDict:ve,encodeSfItem:function(t,e){return t instanceof qt||(t=new qt(t,e)),ge(t)},encodeSfList:zn,encv:function(t){return lr(t)},extractContentId:ii,extractCta608Data:function(t,e){let n=e[0];const i=[[],[]];n+=8;const r=31&t.getUint8(n);n+=2;for(let e=0;e<r;e++){const e=t.getUint8(n),r=4&e,s=3&e;n++;const o=t.getUint8(n);n++;const a=t.getUint8(n);n++,r&&(127&o)+(127&a)!=0&&(0===s?(i[0].push(o),i[0].push(a)):1===s&&(i[1].push(o),i[1].push(a)))}return i},filterBoxes:or,filterBoxesByType:function(t,e,n={}){return Array.isArray(e)||(e=[e]),or(t,t=>e.includes(t.type),n)},findBox:cr,findBoxByType:function(t,e,n={}){return cr(t,t=>t.type===e,n)},findCencContentProtection:function(t){var e;if(!t)return null;for(const n of t)if((null===(e=n.schemeIdUri)||void 0===e?void 0:e.toLowerCase())===Yn&&n.value&&(n.value.toLowerCase()===Hn||n.value.toLowerCase()===Wn))return n;return null},findCta608Nalus:function(t,e,n){let i=0,r=e,s=0;const o=[],a=(t,e,n,i)=>{if(4!==t||e<8)return null;const r=n.getUint8(i),s=n.getUint16(i+1),o=n.getUint32(i+3),a=n.getUint8(i+7);return 181==r&&49==s&&1195456820==o&&3==a};for(;r<e+n;){if(i=t.getUint32(r),s=31&t.getUint8(r+4),6===s){let e=r+5,n=-1;for(;e<r+4+i-1;){n=0;let i=255;for(;255===i;)i=t.getUint8(e),n+=i,e++;let r=0;for(i=255;255===i;)i=t.getUint8(e),r+=i,e++;a(n,r,t,e)&&o.push([e,r]),e+=r}}r+=i+4}return o},free:hr,frma:function(t){return{dataFormat:t.readUint(4)}},fromCmcdHeaders:function(t){return t instanceof Headers||(t=new Headers(t)),Mn.reduce((e,n)=>{const i=t.get(n);return Object.assign(e,In(i))},{})},fromCmcdQuery:function(t){return"string"==typeof t&&(t=new URLSearchParams(t)),In(t.get(Ke))},fromCmcdUrl:function(t){return In(decodeURIComponent(t.replace(/^CMCD=/,"")))},ftyp:dr,getElementsByName:ri,getId:function(t,e,n="ContentId"){try{const i=new URL(t);return new URLSearchParams(i.search).get(n)||ii(e)}catch{return ii(e)}},getId3Data:function(t,e){const n=e;let i=0;for(;Pi(t,e);){i+=10;i+=$i(t,e+6),Bi(t,e+10)&&(i+=10),e+=i}if(i>0)return t.subarray(n,n+i)},getId3Frames:Wi,getId3Timestamp:function(t){const e=Wi(t);for(let t=0;t<e.length;t++){const n=e[t];if(Hi(n))return Yi(n)}},getKeySystemAccess:async function(t){for(const{keySystem:e,configurations:n}of t)try{return await navigator.requestMediaKeySystemAccess(e,n)}catch{}return null},getLegacyKeySystemAccess:function(t){for(const{keySystem:e,configurations:n}of t){const t=Kn(e,n);if(t){return{keySystem:e,configurations:[qn(t.supportedAudio,t.supportedVideo)]}}}return null},getLicenseRequestFromMessage:function(t,e=Qn){var n;if(e===Qn&&(null==t?void 0:t.byteLength)%2==1)return t;const i=ri(ai(ni(t,{encoding:e})),li)[0];if(!i)return t;const r=ri(i,ci)[0],s=null===(n=null==r?void 0:r.childNodes[0])||void 0===n?void 0:n.nodeValue;return s?bn(s).buffer:t},getLicenseServerUrl:function(t){let e="";for(let n=0;n<t.length;n++)0!==t[n]&&(e+=String.fromCharCode(t[n]));const n=e.match(/skd:\/\/([^"\s]+)/);return n?`https://${n[1]}`:""},getLicenseServerUrlFromContentProtection:function(t,e){var n;return(null===(n=t.find(t=>t.schemeIdUri===e))||void 0===n?void 0:n.laUrl)||null},getPsshData:function(t){const e=new DataView(t);let n=28;if(e.getUint8(8)>0){n+=4+16*e.getUint32(n)}return n+=4,t.slice(n)},getPsshForKeySystem:function(t,e){return e&&t&&Xn(e)[t.toLowerCase()]||null},getRequestHeadersFromMessage:function(t,e=Qn){var n,i,r,s,o;const a={};if(e===Qn&&t&&t.byteLength%2==1)return a[ui]=di,a;const c=null===(n=ri(ai(ni(t,{encoding:e})),hi)[0])||void 0===n?void 0:n.childNodes;if(!c)return a;for(const t of c){const e=null===(r=null===(i=ri(t,"name")[0])||void 0===i?void 0:i.childNodes[0])||void 0===r?void 0:r.nodeValue,n=null===(o=null===(s=ri(t,"value")[0])||void 0===s?void 0:s.childNodes[0])||void 0===o?void 0:o.nodeValue;e&&n&&(a[e]=n)}return a.hasOwnProperty("Content")&&(a[ui]=a.Content,delete a.Content),a.hasOwnProperty(ui)||(a[ui]=di),a},getSupportedKeySystemConfiguration:Kn,getTracksFromPresentation:function(t,e){const n=t.selectionSets.flatMap(t=>Lt(t));return e?n.filter(e):n},getTracksFromSelectionSet:Lt,getTracksFromSwitchingSet:Bt,groupCmcdHeaders:Ee,hamToDash:function(t){const e=xt.getInstance();return e.setStrategy(new Ut),e.getManifestFormat(t)},hamToHls:function(t){const e=xt.getInstance();return e.setStrategy(new $t),e.getManifestFormat(t)},hdlr:function(t){return{...t.readFullBox(),preDefined:t.readUint(4),handlerType:t.readString(4),reserved:t.readArray(Zi,4,3),name:t.readString(-1)}},hev1:function(t){return lr(t)},hexToArrayBuffer:vr,hlsToHam:function(t,e){const n=xt.getInstance();return n.setStrategy(new $t),n.getHamFormat({manifest:t,ancillaryManifests:e.map(t=>({manifest:t,type:"hls"})),type:"hls"})},hvc1:function(t){return lr(t)},iden:function(t){return{cueId:t.readUtf8(-1)}},imda:function(t){return{imdaIdentifier:t.readUint(4),data:t.readData(-1)}},isCmcdCustomKey:Le,isCmcdEventKey:Fe,isCmcdRequestKey:Ve,isCmcdResponseKey:We,isCmcdV1Key:Ye,isId3TimestampFrame:Hi,isValidPathwayClone:Vn,isValidSteeringManifest:function(t){if(!t)return!1;const{VERSION:e,TTL:n,"PATHWAY-PRIORITY":i,"PATHWAY-CLONES":r}=t;return"number"==typeof e&&1===e&&(!("number"!=typeof n||n<=0)&&(!(!Array.isArray(i)||0===i.length||new Set(i).size!==i.length)&&!(r&&(!Array.isArray(r)||0===r.length||r.some(t=>!Vn(t))))))},kind:function(t){return{...t.readFullBox(),schemeUri:t.readUtf8(-1),value:t.readUtf8(-1)}},labl:function(t){const{version:e,flags:n}=t.readFullBox();return{version:e,flags:n,isGroupLabel:!!(1&n),labelId:t.readUint(2),language:t.readUtf8(-1),label:t.readUtf8(-1)}},mdat:function(t){return{data:t.readData(-1)}},mdhd:function(t){const{version:e,flags:n}=t.readFullBox(),i=t.readUint(1==e?8:4),r=t.readUint(1==e?8:4),s=t.readUint(4),o=t.readUint(1==e?8:4),a=t.readUint(2);return{version:e,flags:n,creationTime:i,modificationTime:r,timescale:s,duration:o,language:String.fromCharCode(96+(a>>10&31),96+(a>>5&31),96+(31&a)),preDefined:t.readUint(2)}},mehd:function(t){const{version:e,flags:n}=t.readFullBox();return{version:e,flags:n,fragmentDuration:t.readUint(1===e?8:4)}},meta:function(t){return t.readFullBox()},mfhd:function(t){return{...t.readFullBox(),sequenceNumber:t.readUint(4)}},mfro:function(t){return{...t.readFullBox(),mfraSize:t.readUint(4)}},mp4a:ur,mvhd:function(t){const{readUint:e,readTemplate:n,readArray:i}=t,{version:r,flags:s}=t.readFullBox(),o=1==r?8:4;return{version:r,flags:s,creationTime:e(o),modificationTime:e(o),timescale:e(4),duration:e(o),rate:n(4),volume:n(2),reserved1:e(2),reserved2:i(Zi,4,2),matrix:i(Zi,4,9),preDefined:i(Zi,4,6),nextTrackId:e(4)}},parseBoxes:function(t,e){const n=[];for(const i of rr(t,e))n.push(i);return n},parseFrameRate:function(t){const[e,n]=t.split("/").map(t=>parseInt(t,10));return void 0===n?e:isNaN(e)||isNaN(n)||0===n?NaN:e/n},parseInitDataFromContentProtection:function(t,e){if((null==t?void 0:t.pssh)&&t.pssh){const n=t.pssh.replace(/\r?\n|\r/g,"").replace(/\s+/g,"");return e.decodeArray(n).buffer}return null},parsePsshList:Xn,parseWebVtt:async function(t,e){const n=new Vr(e),i=[],r=[],s=[],o=[];return n.oncue=t=>i.push(t),n.onregion=t=>r.push(t),n.onstyle=t=>s.push(t),n.onparsingerror=t=>o.push(t),n.parse(t),n.flush(),{cues:i,regions:r,styles:s,errors:o}},parseXml:ai,payl:function(t){return{cueText:t.readUtf8(-1)}},prepareCmcdData:qe,prft:function(t){const{version:e,flags:n}=t.readFullBox();return{version:e,flags:n,referenceTrackId:t.readUint(4),ntpTimestampSec:t.readUint(4),ntpTimestampFrac:t.readUint(4),mediaTime:t.readUint(1===e?8:4)}},processUriTemplate:function(t,e,n,i,r,s){const o=t.replace(jn,(t,o,a,c)=>{let l,u;switch(o){case void 0:return"$";case"RepresentationID":l=e;break;case"Number":l=n;break;case"SubNumber":l=i;break;case"Bandwidth":l=r;break;case"Time":if("string"==typeof s)return s;l=s?Math.round(s):s;break;default:l=null}if(null==l)return t;switch(c){case void 0:case"d":case"i":case"u":u=l.toString();break;case"o":u=l.toString(8);break;case"x":u=l.toString(16);break;case"X":u=l.toString(16).toUpperCase();break;default:u=l.toString()}const h=parseInt(a,10)||1;return u.padStart(h,"0")});return o},prsl:function(t){const{version:e,flags:n}=t.readFullBox(),i=t.readUint(4),r=t.readUint(4);return{version:e,flags:n,groupId:i,numEntitiesInGroup:r,entities:t.readEntries(r,()=>({entityId:t.readUint(4)})),preselectionTag:4096&n?t.readUtf8(-1):void 0,selectionPriority:8192&n?t.readUint(1):void 0,interleavingTag:16384&n?t.readUtf8(-1):void 0}},pssh:function(t){const{readUint:e,readArray:n}=t,{version:i,flags:r}=t.readFullBox(),s=n(Zi,1,16);let o=0,a=[];i>0&&(o=e(4),a=n(Zi,1,o));const c=e(4);return{version:i,flags:r,systemId:s,kidCount:o,kid:a,dataSize:c,data:n(Zi,1,c)}},roundToEven:oe,schm:function(t){const{version:e,flags:n}=t.readFullBox();return{version:e,flags:n,schemeType:t.readUint(4),schemeVersion:t.readUint(4),schemeUri:1&n?t.readString(-1):void 0}},sdtp:function(t){return{...t.readFullBox(),sampleDependencyTable:t.readArray(Zi,1,t.bytesRemaining)}},setDashParser:function(t){rt=t},setDashSerializer:function(t){st=t},setHlsParser:function(t){ot=t},sidx:function(t){const{readUint:e}=t,{version:n,flags:i}=t.readFullBox(),r=1===n?8:4,s=e(4),o=e(4),a=e(r),c=e(r),l=e(2),u=e(2);return{version:n,flags:i,referenceId:s,timescale:o,earliestPresentationTime:a,firstOffset:c,reserved:l,references:t.readEntries(u,()=>{const t={};return t.reference=e(4),t.subsegmentDuration=e(4),t.sap=e(4),t.referenceType=t.reference>>31&1,t.referencedSize=2147483647&t.reference,t.startsWithSap=t.sap>>31&1,t.sapType=t.sap>>28&7,t.sapDeltaTime=268435455&t.sap,t})}},skip:function(t){return hr(t)},smhd:function(t){return{...t.readFullBox(),balance:t.readUint(2),reserved:t.readUint(2)}},ssix:function(t){const{version:e,flags:n}=t.readFullBox(),i=t.readUint(4);return{version:e,flags:n,subsegmentCount:i,subsegments:t.readEntries(i,()=>{const e=t.readUint(4);return{rangesCount:e,ranges:t.readEntries(e,()=>({level:t.readUint(1),rangeSize:t.readUint(3)}))}})}},sthd:function(t){return t.readFullBox()},stringToUint16:Jn,stsd:function(t){const{version:e,flags:n}=t.readFullBox(),i=t.readUint(4);return{version:e,flags:n,entryCount:i,entries:t.readBoxes(i)}},stss:function(t){const{version:e,flags:n}=t.readFullBox(),i=t.readUint(4);return{version:e,flags:n,entryCount:i,entries:t.readEntries(i,()=>({sampleNumber:t.readUint(4)}))}},sttg:function(t){return{settings:t.readUtf8(-1)}},stts:function(t){const{version:e,flags:n}=t.readFullBox(),i=t.readUint(4);return{version:e,flags:n,entryCount:i,entries:t.readEntries(i,()=>({sampleCount:t.readUint(4),sampleDelta:t.readUint(4)}))}},styp:function(t){return dr(t)},subs:function(t){const{version:e,flags:n}=t.readFullBox(),i=t.readUint(4),r=t.readEntries(i,()=>{const n=t.readUint(4),i=t.readUint(2);return{sampleDelta:n,subsampleCount:i,subsamples:t.readEntries(i,()=>({subsampleSize:t.readUint(1===e?4:2),subsamplePriority:t.readUint(1),discardable:t.readUint(1),codecSpecificParameters:t.readUint(4)}))}});return{version:e,flags:n,entryCount:i,entries:r}},tenc:function(t){return{...t.readFullBox(),defaultIsEncrypted:t.readUint(3),defaultIvSize:t.readUint(1),defaultKid:t.readArray(Zi,1,16)}},tfdt:function(t){const{version:e,flags:n}=t.readFullBox();return{version:e,flags:n,baseMediaDecodeTime:t.readUint(1==e?8:4)}},tfhd:function(t){const{version:e,flags:n}=t.readFullBox();return{version:e,flags:n,trackId:t.readUint(4),baseDataOffset:1&n?t.readUint(8):void 0,sampleDescriptionIndex:2&n?t.readUint(4):void 0,defaultSampleDuration:8&n?t.readUint(4):void 0,defaultSampleSize:16&n?t.readUint(4):void 0,defaultSampleFlags:32&n?t.readUint(4):void 0}},tfra:function(t){const{version:e,flags:n}=t.readFullBox(),i=t.readUint(4),r=t.readUint(4),s=(48&r)>>4,o=(12&r)>>2,a=3&r,c=t.readUint(4),l=t.readEntries(c,()=>({time:t.readUint(1===e?8:4),moofOffset:t.readUint(1===e?8:4),trafNumber:t.readUint(s+1),trunNumber:t.readUint(o+1),sampleNumber:t.readUint(a+1)}));return{version:e,flags:n,trackId:i,reserved:r,lengthSizeOfTrafNum:s,lengthSizeOfTrunNum:o,lengthSizeOfSampleNum:a,numberOfEntry:c,entries:l}},tkhd:function(t){const{version:e,flags:n}=t.readFullBox(),i=1===e?8:4;return{version:e,flags:n,creationTime:t.readUint(i),modificationTime:t.readUint(i),trackId:t.readUint(4),reserved1:t.readUint(4),duration:t.readUint(i),reserved2:t.readArray(Zi,4,2),layer:t.readUint(2),alternateGroup:t.readUint(2),volume:t.readTemplate(2),reserved3:t.readUint(2),matrix:t.readArray(Qi,4,9),width:t.readTemplate(4),height:t.readTemplate(4)}},toBigEndianKeyId:function(t){if(16!==t.byteLength)return t;const e=t.slice(0),n=new DataView(e);return n.setUint32(0,n.getUint32(0,!0),!1),n.setUint16(4,n.getUint16(4,!0),!1),n.setUint16(6,n.getUint16(6,!0),!1),e},toCmcdHeaders:Ge,toCmcdJson:function(t,e){const n=qe(t,e);return JSON.stringify(n,(t,e)=>"symbol"==typeof e||e instanceof Qt?ue(e):e)},toCmcdQuery:Ze,toCmcdReport:function(t,e){if(!e||!e.url)return null;const n=new URL(e.url),i=e.method||"GET",r={},s=e.transmissionMode||on,o={version:e.version,reportingMode:e.reportingMode};switch(e.enabledKeys&&(o.filter=t=>e.enabledKeys.includes(t)),s){case on:const e=Je(t,o);e&&n.searchParams.set(Ke,e);break;case en:Object.assign(r,Ge(t,o))}return{url:n.toString(),method:i,headers:r}},toCmcdUrl:Qe,toVttCue:function(t){const e=new VTTCue(t.startTime,t.endTime,t.text);e.id=t.id,e.region=t.region,e.vertical=t.vertical,e.snapToLines=t.snapToLines,e.line=t.line,e.lineAlign=t.lineAlign,e.position=t.position,e.positionAlign=t.positionAlign,e.size=t.size,e.pauseOnExit=t.pauseOnExit;try{e.align="center"}catch(t){e.align="middle"}return e},toVttRegion:function(t){const e=new VTTRegion;return e.id=t.id,e.width=t.width,e.lines=t.lines,e.regionAnchorX=t.regionAnchorX,e.regionAnchorY=t.regionAnchorY,e.viewportAnchorX=t.viewportAnchorX,e.viewportAnchorY=t.viewportAnchorY,e.scroll=t.scroll,e},trex:function(t){return{...t.readFullBox(),trackId:t.readUint(4),defaultSampleDescriptionIndex:t.readUint(4),defaultSampleDuration:t.readUint(4),defaultSampleSize:t.readUint(4),defaultSampleFlags:t.readUint(4)}},trun:function(t){const{version:e,flags:n}=t.readFullBox(),i=t.readUint(4);let r,s;1&n&&(r=t.readInt(4)),4&n&&(s=t.readUint(4));const o=t.readEntries(i,()=>{const i={};return 256&n&&(i.sampleDuration=t.readUint(4)),512&n&&(i.sampleSize=t.readUint(4)),1024&n&&(i.sampleFlags=t.readUint(4)),2048&n&&(i.sampleCompositionTimeOffset=1===e?t.readInt(4):t.readUint(4)),i});return{version:e,flags:n,sampleCount:i,dataOffset:r,firstSampleFlags:s,samples:o}},unescapeHtml:oi,url:function(t){return{...t.readFullBox(),location:t.readString(-1)}},urlToRelativePath:xe,urn:function(t){return{...t.readFullBox(),name:t.readString(-1),location:t.readString(-1)}},utf8ArrayToStr:Li,uuid:function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?n:3&n|8).toString(16)})}}},uuidToArrayBuffer:function(t){return vr(t.replace(/-/g,""))},validatePresentation:function(t){const e={status:!0,errorMessages:[]};return t.id||(e.status=!1,e.errorMessages.push("Presentation id is undefined")),Xt(t.selectionSets,t.id,e),e},validateSegment:Ft,validateSegments:zt,validateSelectionSet:Yt,validateSelectionSets:Xt,validateSwitchingSet:Wt,validateSwitchingSets:Ht,validateTrack:Vt,validateTracks:jt,vlab:function(t){return{sourceLabel:t.readUtf8(-1)}},vmhd:function(t){return{...t.readFullBox(),graphicsmode:t.readUint(2),opcolor:t.readArray(Zi,2,3)}},vttC:function(t){return{config:t.readUtf8()}},vtte:function(){return{}}});let Jr=class extends C{toCmcd(t,e,n){var i,r,s,o,a,c,l,u,h,d,f;const p={},m=null!==(i=this.playbackRate)&&void 0!==i?i:this.playbackSpeed;e===this.audioTrackId?p.ot=hn.AUDIO:e===this.videoTrackId?p.ot=hn.VIDEO:p.ot=hn.OTHER,p.st=gn.LIVE,p.cid=t.pathname.split("/").pop(),null!=this.bufferAmount&&null!=m&&(p.dl=this.bufferAmount*m),e===this.videoTrackId?p.br=null!==(r=this.videoTrackBandwidth)&&void 0!==r?r:0:e===this.audioTrackId?p.br=null!==(s=this.audioTrackBandwidth)&&void 0!==s?s:0:p.br=(null!==(o=this.audioTrackBandwidth)&&void 0!==o?o:0)+(null!==(a=this.videoTrackBandwidth)&&void 0!==a?a:0),null!=this.stallCount&&(p.bs=this.stallCount-(null!==(c=null==n?void 0:n.stallCount)&&void 0!==c?c:0)>0),null!=this.bufferAmount&&(p.bl=this.bufferAmount),null==this.audioByteRate&&null==this.videoByteRate&&null==this.dataByteRate||(p.mtp=(null!==(l=this.audioByteRate)&&void 0!==l?l:0)+(null!==(u=this.videoByteRate)&&void 0!==u?u:0)+(null!==(h=this.dataByteRate)&&void 0!==h?h:0)),null!=m&&(p.pr=Number(m.toFixed(2)));const g={dash:"d",hls:"h",smooth:"s"},_=null===(d=this.protocol)||void 0===d?void 0:d.toLowerCase();return null!=_&&(p.sf=null!==(f=g[_])&&void 0!==f?f:"o"),null!=this.waitingData&&(p.su=this.waitingData),p}};var Qr,Zr=Object.freeze({__proto__:null,BinaryReader:class{constructor(t){this._data="buffer"in t?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),this._size=this._data.byteLength,this._position=0,this._view=new DataView(this._data.buffer,this._data.byteOffset,this._size)}data(){return this._data}size(){return this._size}available(){return this._size-this._position}value(t=this._position){return this._data[t]}position(){return this._position}reset(t=0){this._position=Math.max(0,t>this._size?this._size:t)}shrink(t){const e=this._size-this._position;return t>e?e:(this._size=this._position+t,t)}next(t=1){const e=this._size-this._position;return t>e&&(t=e),this._position=Math.max(0,this._position+t),t}read8(){return 1===this.next(1)?this._view.getUint8(this._position-1):0}read16(){return 2===this.next(2)?this._view.getUint16(this._position-2):0}read24(){return 3===this.next(3)?this._view.getUint16(this._position-3)<<8|255&this._view.getUint8(this._position-1):0}read32(){return 4===this.next(4)?this._view.getUint32(this._position-4):0}read64(){return 8!==this.next(8)?0:4294967296*this._view.getUint32(this._position-8)+this._view.getUint32(this._position-4)}readFloat(){return 4===this.next(4)?this._view.getFloat32(this._position-4):0}readDouble(){return 8===this.next(8)?this._view.getFloat64(this._position-8):0}read7Bit(){let t=0,e=1;for(;this.available();){const n=this.read8();if(t+=(127&n)*e,!(128&n))break;e*=128}return t}readString(){let t=this._position;for(;t<this._size&&this._data[t];)++t;const n=this.read(t-this._position);return this.next(),e.decode(n)}readHex(t){let e="";for(;t-- >0;)e+=("0"+this.read8().toString(16)).slice(-2);return e}read(t=this.available()){if(this.available()<t)return new Uint8Array(t);const e=this._position;return this._data.subarray(e,Math.max(e,this._position+=t))}},BinaryWriter:class{get view(){return this._view||(this._view=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength)),this._view}get capacity(){return this._data.byteLength}constructor(t=64,e=0,n){"number"==typeof t?(this._data=new Uint8Array(t),this._size=0):"buffer"in t?(this._data=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),this._size=t.byteLength):(this._isConst=!0,null==n&&(n=t.byteLength),this._data=new Uint8Array(t,e,n),this._size=0)}data(){return new Uint8Array(this._data.buffer,this._data.byteOffset,this._size)}size(){return this._size||0}next(t=1){return this.reserve(this._size+=t)}clear(t=0){return this.reserve(this._size=t)}write(t){var e;let n;return n="string"==typeof t?h(t):t instanceof ArrayBuffer?new Uint8Array(t):"buffer"in t?new Uint8Array(t.buffer,null!==(e=t.byteOffset)&&void 0!==e?e:0,t.byteLength):t,this.reserve(this._size+n.length),this._data.set(n,this._size),this._size+=n.length,this}write8(t){return t>255&&(t=255),this.reserve(this._size+1),this._data[this._size++]=t,this}write16(t){return t>65535&&(t=65535),this.reserve(this._size+2),this.view.setUint16(this._size,t),this._size+=2,this}write24(t){return t>16777215&&(t=16777215),this.reserve(this._size+3),this.view.setUint16(this._size,t>>8),this.view.setUint8(this._size+=2,255&t),++this._size,this}write32(t){return t>4294967295&&(t=4294967295),this.reserve(this._size+4),this.view.setUint32(this._size,t),this._size+=4,this}write64(t){return this.write32(t/4294967296),this.write32(4294967295&t)}writeFloat(t){return this.reserve(this._size+4),this.view.setFloat32(this._size,t),this._size+=4,this}writeDouble(t){return this.reserve(this._size+8),this.view.setFloat64(this._size,t),this._size+=8,this}write7Bit(t){let e=127&t;for(;t=Math.floor(t/128);)this.write8(128|e),e=127&t;return this.write8(e)}writeString(t){return this.write(h(t)).write8(0)}writeHex(t){for(let e=0;e<t.length;e+=2)this.write8(parseInt(t.substring(e,e+2),16));return this}reserve(t){if(!this._data)throw Error("buffer not writable");if(t<=this._data.byteLength)return this;if(this._isConst)throw Error("writing exceeds maximum "+this._data.byteLength+" bytes limit");--t,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,++t;const e=new Uint8Array(t);return e.set(this._data),this._data=e,this._view=void 0,this}},BitReader:class extends C{constructor(t){super(),this._data="buffer"in t?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),this._size=this._data.byteLength,this._position=0,this._bit=0}data(){return this._data}size(){return this._size}available(){return 8*(this._size-this._position)-this._bit}next(t=1){let e=0;for(;this._position!==this._size&&t--;)++e,8===++this._bit&&(this._bit=0,++this._position);return e}read(t=1){let e=0;for(;this._position!==this._size&&t--;)e<<=1,this._data[this._position]&128>>this._bit++&&(e|=1),8===this._bit&&(this._bit=0,++this._position);return e}read8(){return this.read(8)}read16(){return this.read(16)}read24(){return this.read(24)}read32(){return this.read(32)}readExpGolomb(){let t=0;for(;!this.read();){if(!this.available())return 0;++t}const e=this.read(t);return t>15?(this.log("Exponential-Golomb code exceeding unsigned 16 bits").warn(),0):e+(1<<t)-1}},ByteRate:R,CML:Kr,Connect:A,EpochTime:B,EventEmitter:I,FixMap:M,Log:T,get LogLevel(){return v},Loggable:C,NetAddress:k,Numbers:O,PlayerStats:Jr,Queue:D,SDP:N,UIMetrics:class{get graphMargin(){return this._graphMargin}set graphMargin(t){this._graphMargin=t}get textMargin(){return this._textMargin}set textMargin(t){this._textMargin=t}get lineHeight(){return this._lineHeight}set lineHeight(t){this._lineHeight=t}get labelWidth(){return this._labelWidth}set labelWidth(t){this._labelWidth=t}get legendFontSize(){return this._legendFontSize}set legendFontSize(t){this._legendFontSize=t}get stepSize(){return this._stepSize}set stepSize(t){this._stepSize=t}get averageDisplayWidth(){return this._legendFontSize/2*7}get displayableCount(){const t=this._ui.clientWidth-this.averageDisplayWidth;return Math.ceil((t-this._labelWidth)/this._stepSize)}constructor(t){this._ui=t,t.addEventListener("mousemove",t=>{this._mouseX=t.offsetX}),t.addEventListener("mouseleave",t=>{this._mouseX=void 0}),this._lineHeight=40,this._labelWidth=170,this._graphMargin=5,this._textMargin=5,this._legendFontSize=13,this._stepSize=10,this._ranges={}}reset(){this._ranges={}}display(t){if(null!=this._html)return;this._html="";const e=this.averageDisplayWidth,n=e/2,i=this._ui.clientWidth-e,r=this._lineHeight-2*this._graphMargin,s=Math.round(this._lineHeight/2),o=Math.round(this._lineHeight/2+this._textMargin),a=this._labelWidth-2*this._textMargin;for(const[e,c]of t){const t=Math.ceil((i-this._labelWidth)/this._stepSize),l=c.slice(Math.max(0,c.length-t));if(!l.length)continue;let u=this._labelWidth+l.length*this._stepSize;this._html+='<svg class="list-group-item p-0" style="height: '+this._lineHeight+'px" xmlns="http://www.w3.org/2000/svg">',this._html+='<text x="'+this._textMargin+'" y="'+o+'">'+e+"</text>",this._html+='<text x="'+a+'" y="'+o+'" text-anchor="end">'+l[l.length-1].toString()+"</text>",this._html+='<path fill="none" d="M'+this._labelWidth+" "+s,this._html+="H"+(i+n),this._html+='" stroke-width="1" stroke="lightgray" stroke-dasharray="10,10"/>',this._html+='<path fill="none" stroke-width="1" stroke="brown" d="M';let h=Number.POSITIVE_INFINITY,d=Number.NEGATIVE_INFINITY;for(let t=0;t<l.length;++t){const e=parseFloat(l[t].toString());e<h&&(h=e),e>d&&(d=e)}let f=this._ranges[e];f||(this._ranges[e]=f={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY}),f.min=Math.min(f.min,h),f.max=Math.max(f.max,d);const p=f.max-f.min;let m="",g="",_=null==this._mouseX||this._mouseX>u?null:"";for(let t=0;t<l.length;++t){u-=this._stepSize;const e=parseFloat(l[t].toString()),n=s+(p?Math.round((.5-(e-f.min)/p)*r):0);this._html+=u+" "+n+" ",e===h?g=g||this._drawCircle(u,n,e):e===d&&(m=m||this._drawCircle(u,n,e)),""===_&&u<=(this._mouseX||0)&&(_=this._drawCircle(u,n,e,"blue",""))}this._html+='" />';const v=Math.round((d-h)/2);this._html+='<text text-anchor="middle" font-size="'+this._legendFontSize+'" y="'+o+'">',this._html+='<tspan x="'+(i+n)+'" dy="-0.5em">'+(h!==d?"≈":"=")+(h+v)+"</tspan>",this._html+='<tspan x="'+(i+n)+'" dy="1em">±'+v+"</tspan>",this._html+="</text>",this._html+=m+g+(null!=_?_:""),_&&(this._html+=_),this._html+="</svg>"}requestAnimationFrame(()=>{null!=this._html&&(this._ui.innerHTML=this._html,this._html=void 0)})}_drawCircle(t,e,n,i="green",r="italic"){let s='<circle cx="'+t+'" cy="'+e+'" r="2" fill="'+i+'" />';const o=.7*this._legendFontSize;return e<Math.round(this._lineHeight/2)?e+=this.textMargin+o:e-=this.textMargin,s+='<text font-style="'+r+'" font-size="'+this._legendFontSize+'" x="'+(t-this._legendFontSize)+'" y="'+e+'">'+n+"</text>",s}},Util:y,VERSION:"7.7.0",WebSocketReliable:P,log:E});function ts(t,e,n){for(let i=0;i<e.length;++i){const r=e[i];n.has(r.codec.toLowerCase())||(t.delete(r.idx),e.splice(i--,1))}}!function(t){t.AUDIO="audio",t.VIDEO="video",t.DATA="data"}(Qr||(Qr={}));class es{constructor(){this.type="",this.width=0,this.height=0,this.sources=new Map,this.tracks=new Map,this.audios=[],this.videos=[],this.datas=[]}subset(t){const e=Object.assign({},this);if(t){ts(e.tracks,e.audios,t),ts(e.tracks,e.videos,t);for(const[,t]of e.tracks){for(;t.up&&!e.tracks.has(t.up.idx);)t.up=t.up.up;for(;t.down&&!e.tracks.has(t.down.idx);)t.down=t.down.down}}return e}}const ns=(t,e)=>e.maxbps-t.maxbps;var is;!function(t){t.UNKNOWN="",t.ONLINE="Stream is online",t.OFFLINE="Stream is offline",t.INITIALIZING="Stream is initializing",t.BOOTING="Stream is booting",t.WAITING="Stream is waiting for data"}(is||(is={}));class rs extends I{onState(t){this.log("onState",t).info()}onClose(t){this.log("onClose").info()}onMetadata(t){this.log(y.stringify(t)).info()}get url(){return this._ws.url}get streamState(){return this._streamState}get connectParams(){return this._connectParams}get metadata(){return this._metadata}get closed(){return this._ws.closed}constructor(t){super();const e=new Map;for(const t of Object.values(is))e.set(t,t);e.set("Stream status is unknown?!",is.UNKNOWN),this._connectParams=t,this._streamState=is.UNKNOWN,this._ws=new P(A.buildURL(A.Type.META,t)),this._ws.onClose=t=>this.close(t),this._ws.onMessage=n=>{var i,r;try{const s=JSON.parse(n);if(s.error){const n=e.get(s.error);return void(n?this.onState(this._streamState=n):this.close({type:"StreamMetadataError",name:s.error,stream:null!==(i=t.streamName)&&void 0!==i?i:""}))}this._metadata=new es,this._metadata.type=s.type,this._metadata.width=s.width,this._metadata.height=s.height,this._metadata.sources.clear();for(const t of s.source||[])this._metadata.sources.set(t.hrn,t);const o=[];if(this._metadata.tracks.clear(),null===(r=s.meta)||void 0===r?void 0:r.tracks)for(const[t,e]of y.iterableEntries(s.meta.tracks)){switch(e.name=t,e.type=e.type.toLowerCase(),e.type){case"audio":this._metadata.audios.push(e);continue;case"video":this._metadata.videos.push(e);continue;case"meta":e.type=Qr.DATA,this._metadata.datas.push(e);break;default:this.log(`Unknown track type ${e.type}`).warn()}o.push(e)}this._addSortedTrack(this._metadata.audios,this._metadata.tracks),this._addSortedTrack(this._metadata.videos,this._metadata.tracks);for(const t of o)this._metadata.tracks.set(t.idx,t);this.onState(this._streamState=is.ONLINE)}catch(t){return void this.log(y.stringify(t)).error()}this.onMetadata(this._metadata)}}close(t){this._ws.onClose!==y.EMPTY_FUNCTION&&(this._ws.onClose=y.EMPTY_FUNCTION,this._ws.close(),this._metadata=new es,this.onClose(t))}_addSortedTrack(t,e){t.sort(ns);for(let n=0;n<t.length;++n){const i=t[n];e.set(i.idx,i),n&&(i.up=t[n-1],t[n-1].down=i)}}}class ss extends Jr{constructor(){super(),this._prevTime=0,this._prevAudioBytes=0,this._prevVideoBytes=0,this._prevVideoEmittedCount=0,this._prevAudioEmittedCount=0,this._prevVideoJitterDelay=0,this._prevAudioJitterDelay=0,this._prevSkippedAudio=0,this._prevAudioConcealedSamples=0,this._prevSkippedVideo=0,this._prevVideoDroppedFrames=0,this._prevVideoTime=0,this._prevRealTime=0,this.protocol="WebRTC"}onRelease(){}serialize(){return t(this,void 0,void 0,function*(){return this})}compute(t,e,n,i,r){var s,o,a,c,l,u,h,d,f,p,m;const g=null===(s=t.inputs)||void 0===s?void 0:s.audio,_=null===(o=t.inputs)||void 0===o?void 0:o.video;this.videoTrackId=r;const v=null!=r?e.tracks.get(r):void 0;this.audioTrackId=i;const y=null!=i?e.tracks.get(i):void 0;let b=performance.now();const S=Math.max(1,b-this._prevTime);this._prevTime=b;const w=null==g?void 0:g.bytesReceived;null!=w?(this.audioByteRate=Math.max(0,w-this._prevAudioBytes)/S,this._prevAudioBytes=w):this.audioByteRate=void 0;const T=null==_?void 0:_.bytesReceived;null!=T?(this.videoByteRate=Math.max(0,T-this._prevVideoBytes)/S,this._prevVideoBytes=T):this.videoByteRate=void 0;const C=null==_?void 0:_.jitterBufferDelay,E=null==_?void 0:_.jitterBufferEmittedCount;let R;null!=C&&null!=E&&(E>this._prevVideoEmittedCount&&(R=1e3*Math.max(0,C-this._prevVideoJitterDelay)/(E-this._prevVideoEmittedCount)),this._prevVideoEmittedCount=E,this._prevVideoJitterDelay=C);const k=null==g?void 0:g.jitterBufferDelay,U=null==g?void 0:g.jitterBufferEmittedCount;let x;null!=k&&null!=U&&(U>this._prevAudioEmittedCount&&(x=1e3*Math.max(0,k-this._prevAudioJitterDelay)/(U-this._prevAudioEmittedCount)),this._prevAudioEmittedCount=U,this._prevAudioJitterDelay=k),this.bufferAmount=null!=R||null!=x?Math.max(null!=R?R:0,null!=x?x:0):void 0,this.videoPerSecond=null==_?void 0:_.framesPerSecond;const A=null==g?void 0:g.concealedSamples;if(null!=A&&y&&y.rate){const t=Math.max(A-this._prevAudioConcealedSamples,0);this._prevAudioConcealedSamples=A,this.skippedAudio=this._prevSkippedAudio+t/y.rate*1e3,this._prevSkippedAudio=this.skippedAudio}else this.skippedAudio=void 0;const I=null==_?void 0:_.framesDropped;if(null!=I&&this.videoPerSecond){const t=Math.max(I-this._prevVideoDroppedFrames,0);this._prevVideoDroppedFrames=I,this.skippedVideo=this._prevSkippedVideo+t/this.videoPerSecond*1e3,this._prevSkippedVideo=this.skippedVideo}else this.skippedVideo=void 0;this.stallCount=null==_?void 0:_.freezeCount,this.audioTrackBandwidth=null!==(a=null==y?void 0:y.ebps)&&void 0!==a?a:null==y?void 0:y.bps,this.videoTrackBandwidth=null!==(c=null==v?void 0:v.ebps)&&void 0!==c?c:null==v?void 0:v.bps,b=performance.now();const M=n;let D=0;if(void 0!==this._prevVideoTime&&void 0!==this._prevRealTime){const t=M-this._prevVideoTime,e=(b-this._prevRealTime)/1e3;t>=0&&e>.05&&(D=t/e)}this._prevVideoTime=M,this._prevRealTime=b,this.playbackSpeed=D,this.rtt=null===(l=null==t?void 0:t.candidate)||void 0===l?void 0:l.currentRoundTripTime,null!=(null==_?void 0:_.jitter)||null!=(null==g?void 0:g.jitter)?this.jitter=Math.max(null!==(u=null==_?void 0:_.jitter)&&void 0!==u?u:0,null!==(h=null==g?void 0:g.jitter)&&void 0!==h?h:0):this.jitter=void 0,null!=(null==_?void 0:_.packetsLost)||null!=(null==g?void 0:g.packetsLost)?this.lostPacketCount=(null!==(d=null==_?void 0:_.packetsLost)&&void 0!==d?d:0)+(null!==(f=null==g?void 0:g.packetsLost)&&void 0!==f?f:0):this.lostPacketCount=void 0,null!=(null==_?void 0:_.nackCount)||null!=(null==g?void 0:g.nackCount)?this.nackCount=(null!==(p=null==_?void 0:_.nackCount)&&void 0!==p?p:0)+(null!==(m=null==g?void 0:g.nackCount)&&void 0!==m?m:0):this.nackCount=void 0}}function os(t){return"send"in t}var as,cs,ls,us,hs,ds={},fs={},ps={exports:{}};function ms(){if(as)return ps.exports;as=1;var t=ps.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(t){return t.encoding?"rtpmap:%d %s/%s/%s":t.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(t){return null!=t.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(t){return null!=t.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(t){return"extmap:%d"+(t.direction?"/%s":"%v")+(t["encrypt-uri"]?" %s":"%v")+" %s"+(t.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(t){return null!=t.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(t){var e="candidate:%s %d %s %d %s %d typ %s";return e+=null!=t.raddr?" raddr %s rport %d":"%v%v",e+=null!=t.tcptype?" tcptype %s":"%v",null!=t.generation&&(e+=" generation %d"),e+=null!=t["network-id"]?" network-id %d":"%v",e+=null!=t["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(t){var e="ssrc:%d";return null!=t.attribute&&(e+=" %s",null!=t.value&&(e+=":%s")),e}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(t){return null!=t.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(t){return t.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(t){return"imageattr:%s %s %s"+(t.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(t){return"simulcast:%s %s"+(t.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(t){return"ts-refclk:%s"+(null!=t.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(t){var e="mediaclk:";return e+=null!=t.id?"id=%s %s":"%v%s",e+=null!=t.mediaClockValue?"=%s":"",e+=null!=t.rateNumerator?" rate=%s":"",e+=null!=t.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(t).forEach(function(e){t[e].forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})}),ps.exports}function gs(){return cs||(cs=1,function(t){var e=function(t){return String(Number(t))===t?Number(t):t},n=function(t,n,i){var r=t.name&&t.names;t.push&&!n[t.push]?n[t.push]=[]:r&&!n[t.name]&&(n[t.name]={});var s=t.push?{}:r?n[t.name]:n;!function(t,n,i,r){if(r&&!i)n[r]=e(t[1]);else for(var s=0;s<i.length;s+=1)null!=t[s+1]&&(n[i[s]]=e(t[s+1]))}(i.match(t.reg),s,t.names,t.name),t.push&&n[t.push].push(s)},i=ms(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(t){var e={},s=[],o=e;return t.split(/(\r\n|\r|\n)/).filter(r).forEach(function(t){var e=t[0],r=t.slice(2);"m"===e&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(i[e]||[]).length;a+=1){var c=i[e][a];if(c.reg.test(r))return n(c,o,r)}}),e.media=s,e};var s=function(t,n){var i=n.split(/=(.+)/,2);return 2===i.length?t[i[0]]=e(i[1]):1===i.length&&n.length>1&&(t[i[0]]=void 0),t};t.parseParams=function(t){return t.split(/;\s?/).reduce(s,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(t){return t.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(t){for(var n=[],i=t.split(" ").map(e),r=0;r<i.length;r+=3)n.push({component:i[r],ip:i[r+1],port:i[r+2]});return n},t.parseImageAttributes=function(t){return t.split(" ").map(function(t){return t.substring(1,t.length-1).split(",").reduce(s,{})})},t.parseSimulcastStreamList=function(t){return t.split(";").map(function(t){return t.split(",").map(function(t){var n,i=!1;return"~"!==t[0]?n=e(t):(n=e(t.substring(1,t.length)),i=!0),{scid:n,paused:i}})})}}(fs)),fs}function _s(){if(us)return ls;us=1;var t=ms(),e=/%[sdv%]/g,n=function(t){var n=1,i=arguments,r=i.length;return t.replace(e,function(t){if(n>=r)return t;var e=i[n];switch(n+=1,t){case"%%":return"%";case"%s":return String(e);case"%d":return Number(e);case"%v":return""}})},i=function(t,e,i){var r=[t+"="+(e.format instanceof Function?e.format(e.push?i:i[e.name]):e.format)];if(e.names)for(var s=0;s<e.names.length;s+=1){var o=e.names[s];e.name?r.push(i[e.name][o]):r.push(i[e.names[s]])}else r.push(i[e.name]);return n.apply(null,r)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return ls=function(e,n){n=n||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach(function(t){null==t.payloads&&(t.payloads="")});var o=n.outerOrder||r,a=n.innerOrder||s,c=[];return o.forEach(function(n){t[n].forEach(function(t){t.name in e&&null!=e[t.name]?c.push(i(n,t,e)):t.push in e&&null!=e[t.push]&&e[t.push].forEach(function(e){c.push(i(n,t,e))})})}),e.media.forEach(function(e){c.push(i("m",t.m[0],e)),a.forEach(function(n){t[n].forEach(function(t){t.name in e&&null!=e[t.name]?c.push(i(n,t,e)):t.push in e&&null!=e[t.push]&&e[t.push].forEach(function(e){c.push(i(n,t,e))})})})}),c.join("\r\n")+"\r\n"}}var vs=function(){if(hs)return ds;hs=1;var t=gs(),e=_s(),n=ms();return ds.grammar=n,ds.write=e,ds.parse=t.parse,ds.parseParams=t.parseParams,ds.parseFmtpConfig=t.parseFmtpConfig,ds.parsePayloads=t.parsePayloads,ds.parseRemoteCandidates=t.parseRemoteCandidates,ds.parseImageAttributes=t.parseImageAttributes,ds.parseSimulcastStreamList=t.parseSimulcastStreamList,ds}();const ys=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);class bs extends I{onOpen(t){this.log("onOpen").info()}onClose(t){t?this.log("onClose",t).error():this.log("onClose").info()}get opened(){return!(!this._peerConnection||this._peerConnection.ontrack!==y.EMPTY_FUNCTION)}get closed(){return this._closed}get stream(){return this._stream}get streamName(){return this._streamName}get codecs(){return this._codecs}constructor(t,e){var n;super(),this._closed=!1,this._streamName=null!==(n=t.streamName)&&void 0!==n?n:"",this._endPoint=t.endPoint,this._stream=e,this._connectionInfosTime=0,this._codecs=new Set}connectionInfos(){return t(this,arguments,void 0,function*(t=1e3){if(!this._peerConnection)return Promise.reject("Not connected");if(!this._connectionInfos||y.time()-t>this._connectionInfosTime){const t=yield this._peerConnection.getStats(null);this._connectionInfos={inputs:{},outputs:{}};const e=new Map,n=new Map;for(const i of t.values())switch(i.type){case"track":e.set(i.id,i);break;case"outbound-rtp":n.set(i.trackId,i),this._connectionInfos.outputs["audio"===(i.kind||i.mediaType)?"audio":"video"]=i;break;case"inbound-rtp":n.set(i.trackId,i),this._connectionInfos.inputs["audio"===(i.kind||i.mediaType)?"audio":"video"]=i;break;case"candidate-pair":if(null!=i.selected){if(!i.selected)continue}else if(null!=i.nominated&&!i.nominated)continue;this._connectionInfos.candidate=i}for(const[t,i]of e){const e=n.get(t);e&&Object.assign(e,Object.assign(Object.assign({},i),e))}this._connectionInfosTime=y.time()}return this._connectionInfos})}close(t){if(this._closed)return;this._closed=!0,this._clearPeerConnectionIdleTimeout();const e=this._peerConnection;e&&(this._peerConnection=void 0,e.getReceivers().forEach(t=>t.track&&t.track.stop()),e.getSenders().forEach(t=>t.track&&t.track.stop()),e.close()),this._stream&&this._stream.getTracks().forEach(t=>t.stop()),this.onClose(t)}_open(t){if(!t){const e=new k(this._endPoint,443).domain;t={urls:["turn:"+e+":3478?transport=tcp","turn:"+e+":3478"],username:"ceeblue",credential:"ceeblue"}}try{this._peerConnection=new RTCPeerConnection({iceServers:[t]})}catch(t){return void this.close({type:"ConnectorError",name:"RTCPeerConnection failed",detail:y.stringify(t)})}if(this._peerConnection.onconnectionstatechange=t=>{const e=t.target;if(e){const t=null==e?void 0:e.connectionState;switch(this.log(`Peer connection state: ${t}`).info(),t){case"connected":case"connecting":this._clearPeerConnectionIdleTimeout();break;case"disconnected":case"failed":this.log(`Peer connection state: ${t}`).warn(),this._startPeerConnectionIdleTimeout();break;case"closed":this.log(`Peer connection state: ${t}`).warn(),this.close()}}},this._stream)for(const t of this._stream.getTracks())this._peerConnection.addTrack(t);else this._peerConnection.ontrack=t=>{this._stream=t.streams[0],this._tryToOpen()};if(ys)if(this._stream){const t=this._peerConnection.getTransceivers();for(const e of t)"audio"!==e.receiver.track.kind&&"video"!==e.receiver.track.kind||(e.direction="sendonly")}else this._peerConnection.addTransceiver("audio",{direction:"recvonly"}),this._peerConnection.addTransceiver("video",{direction:"recvonly"});let e;this._peerConnection.createOffer({offerToReceiveAudio:!this._stream,offerToReceiveVideo:!this._stream}).then(t=>{if(this._peerConnection)return t.sdp=e=t.sdp?function(t){const e=vs.parse(t);for(const t of e.media)if("audio"===t.type){const e=[];for(const n of t.rtp)"opus"===n.codec&&e.push(n.payload);if(!e.length)continue;for(const n of t.fmtp)if(e.includes(n.payload)){const t=vs.parseParams(n.config);t.stereo=1,n.config="";for(const e in t)n.config+=(n.config?";":"")+e+"="+t[e]}}return vs.write(e)}(t.sdp):"",this.log(`Offer\r\n${e}`).debug(),this._peerConnection.setLocalDescription(t)}).then(t=>{if(this._peerConnection)return e?this._sip(e):Promise.reject("invalid empty sdp offer")}).then(t=>{if(t&&this._peerConnection)return this.log(`Answer\r\n${t}`).debug(),this.updateCodecs(t),this._peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:t}))}).then(()=>this._tryToOpen()).catch(t=>this.close({type:"ConnectorError",name:"SIP failed",detail:y.stringify(t)}))}replaceTrack(e,n){return t(this,void 0,void 0,function*(){if(this._closed||!this._peerConnection)throw Error("Connector is closed");if(!this._stream)throw Error("No local stream to update");let t;"function"==typeof this._peerConnection.getTransceivers&&(t=this._peerConnection.getTransceivers().find(t=>t.sender&&(t.receiver&&t.receiver.track&&t.receiver.track.kind===e||t.sender.track&&t.sender.track.kind===e)));let i=null==t?void 0:t.sender;if(i||(i=this._peerConnection.getSenders().find(t=>t.track&&t.track.kind===e)),!i)return void this.close({type:"ConnectorError",name:"Replace track failed",detail:`No existing ${e} sender to replace; restart is required for this direction.`});yield i.replaceTrack(n);const r=this._stream;("video"===e?r.getVideoTracks():r.getAudioTracks()).forEach(t=>r.removeTrack(t)),n&&r.addTrack(n)})}updateCodecs(t){const e=vs.parse(t);for(const t of e.media)for(const e of t.rtp)this._codecs.add(e.codec.toLowerCase())}_tryToOpen(){this._stream&&this._peerConnection&&this._peerConnection.ontrack!==y.EMPTY_FUNCTION&&(this._peerConnection.ontrack=y.EMPTY_FUNCTION,this.onOpen(this._stream))}_startPeerConnectionIdleTimeout(){this._peerConnectionIdleTimeout||(this._peerConnectionIdleTimeout=setTimeout(()=>{this.log("Peer connection idle timeout!").error(),this.close({type:"ConnectorError",name:"Connection idle"})},15e3))}_clearPeerConnectionIdleTimeout(){this._peerConnectionIdleTimeout&&(clearTimeout(this._peerConnectionIdleTimeout),this._peerConnectionIdleTimeout=void 0)}}const Ss=3e4;class ws extends bs{onRTPProps(t){}onMediaReport(t){}onVideoBitrate(t,e){this.log(`onVideoBitrate ${y.stringify({video_bitrate:t,video_bitrate_constraint:e})}`).info()}onPlaying(t){this.log(`onPlaying ${y.stringify(t)}`).debug()}constructor(t,e){super(t,e),this._reportReceivedTimestamp=y.time(),this._ws=new P(A.buildURL(A.Type.WEBRTC,t,"wss")),this._ws.onClose=t=>this.close(t),this._ws.onOpen=()=>{this._startReportWatchdog(),this._open(t.iceServer)},this._ws.onMessage=t=>{try{this._eventHandler(JSON.parse(t))}catch(t){this.log(`Invalid signaling message, ${y.stringify(t)}`).warn()}}}setRTPProps(t,e){this.send("rtp_props",{nack:t,drop:e})}setVideoBitrate(t){this.send("video_bitrate",{video_bitrate:t})}setTracks(t){this.send("tracks",t)}send(t,e){try{this.log(`Command ${t} ${y.stringify(e)}`).info(),this._ws.send(JSON.stringify(Object.assign({type:t},e)))}catch(t){this.log(y.stringify(t)).error()}}close(t){this._ws.onClose!==y.EMPTY_FUNCTION&&(this._ws.onClose=y.EMPTY_FUNCTION,this._ws.close(),this._clearReportWatchdog(),this._promise&&(this._promise(Error("closing")),this._promise=void 0),super.close(t))}_sip(t){return new Promise((e,n)=>{this._promise=t=>{t instanceof Error?n(t):e(t)},this._ws.send(JSON.stringify({type:"offer_sdp",offer_sdp:t}))})}_eventHandler(t){var e,n;switch(this.log(`EventHandler ${y.stringify(t,{recursion:2})}`).debug(),t.type){case"on_answer_sdp":if(!0!==t.result)return void this.close({type:"ConnectorError",name:"Access denied"});this._promise&&this._promise(t.answer_sdp);break;case"on_error":if(!this.opened)return void this.close({type:"ConnectorError",name:"Connection failed",detail:y.stringify(t)});this.log(y.stringify(t)).warn();break;case"on_video_bitrate":this.onVideoBitrate(t.video_bitrate,t.video_bitrate_constraint);break;case"on_stop":return this.log("on_stop").info(),void this.close();case"on_track_drop":{const i=null!==(e=t.mediatype)&&void 0!==e?e:"?",r=null!==(n=t.track)&&void 0!==n?n:"?";this.log(`${i} track #${r} dropped`).warn();break}case"on_rtp_props":this.onRTPProps(t);break;case"on_media_receive":this._reportReceivedTimestamp=y.time(),t.stats.loss_perc&&!t.stats.loss_num&&(t.stats.loss_perc=0),this.onMediaReport(t);break;case"set_speed":case"on_seek":break;case"on_time":this._reportReceivedTimestamp=y.time(),this.onPlaying(t);break;default:this.log(`Unhandled event: ${t.type}`).warn()}}_startReportWatchdog(){this._reportReceivedTimestamp=y.time(),this._reportWatchdogInterval=setInterval(()=>{const t=y.time()-this._reportReceivedTimestamp;t>=1e4&&this.log(`No updates received for the last ${(t/1e3).toFixed(1)}s`).warn(),t>=Ss&&this.close({type:"ConnectorError",name:"Connection idle"})},5e3)}_clearReportWatchdog(){this._reportWatchdogInterval&&(clearInterval(this._reportWatchdogInterval),this._reportWatchdogInterval=void 0)}}class Ts extends bs{constructor(t,e){super(t,e),this._url=A.buildURL(A.Type.WEBRTC,t,"https"),this._fetch=new AbortController,setTimeout(()=>{this._open(t.iceServer)},0)}close(t){this._fetch.abort(),super.close(t)}_sip(e){return t(this,void 0,void 0,function*(){const t=yield fetch(this._url,{method:"POST",body:e,headers:{"Content-Type":"application/sdp"},signal:this._fetch.signal});return t.ok?t.text():Promise.reject(`HTTP ${t.status} ${t.statusText} status`)})}}class Cs extends I{onClose(t){this.log("onClose").info()}onData(t,e,n){this.log(`Data received on track ${t} at ${e}: ${y.stringify(n)}`).info()}get url(){return this._url}get tracks(){return[...this._tracks]}set tracks(t){this._tracks=[...t],this._sendTracks()}get closed(){return!this._ws||this._ws.closed}constructor(t){super(),this._url=A.buildURL(A.Type.DATA,t).toString(),this._tracks=Array(),this._ws=new P,this._ws.onOpen=()=>this._sendTracks(),this._ws.onClose=t=>this.onClose(t),this._ws.onMessage=t=>{let e;try{if(e=JSON.parse(t),e.error)throw Error(e.error)}catch(t){return void this.log(y.stringify(t)).error()}"time"in e&&"track"in e&&"data"in e?this.onData(e.track,e.time,e.data):"on_time"!==e.type&&this.log(`Internal JSON: ${y.stringify(e)}`).debug()}}close(t){this._ws.close(t)}_sendTracks(){this._tracks.length?this._ws.closed?this._ws.open(this._url):this._ws.opened&&this._ws.send(JSON.stringify({type:"tracks",tracks:this._tracks.join(",")})):this.close()}}class Es extends C{get upDelay(){return this._upDelay}get learningUpStep(){return this._learningUpStep}get maximumUpDelay(){return this._maximumUpDelay}constructor(t){super();const e=Object.assign({learningUpStep:1400,maximumUpDelay:28e3},t);this._learningUpStep=e.learningUpStep,this._maximumUpDelay=e.maximumUpDelay,this._upDelay=0,this._testTime=0}reset(){this._upDelay=0,this._mTrack=void 0}compute(t,e,n){var i;const r=null!==(i=e.video)&&void 0!==i?i:e.audio;if(null==r)return this._mTrack=void 0,!1;const s=y.time();if(!(this._mTrack&&this._mTrack.idx===r||(this._appreciationTime=void 0,this._testTime=s,this._mTrack=t.tracks.get(r),this._mTrack)))return this.log(`Can't find track ${r} absent from metadata`).error(),!1;const o=r===e.video?n.video:n.audio;if(!o)return this.log(`Can't compute ${this._mTrack.type} track ${this._mTrack.idx} without statistics`).error(),!1;const a=this._downBitrate(s-this._testTime,this._mTrack,o);if(a)this._appreciationTime=void 0;else{this._appreciationTime||(this._appreciationTime=s);const t=s-this._appreciationTime;if(!this._upBitrate(t,this._mTrack,o)||t<this._upDelay)return!1}let c=this.updateTrack(e.audio,t,a);if(c)e.audio=c.idx;else{if(c=this.updateTrack(e.video,t,a),!c)return!1;e.video=c.idx}return a&&(this._upDelay=Math.min(this._upDelay+this._learningUpStep,this._maximumUpDelay)),this.log(`${a?"DOWN":"UP"} from ${this._mTrack.type} track ${this._mTrack.idx} (${this._mTrack.maxbps}bps) to ${c.type} track ${c.idx} (${c.maxbps}bps)`).info(),!0}updateTrack(t,e,n){if(null==t)return;const i=n?"down":"up",r=e.tracks.get(t);if(r)return r[i];this.log(`Can't find track ${t} from metadata`).error()}}class Rs extends Es{constructor(t){super(t),this._keyFramesDecoded=0,this._lost=0,this._nackCount=0}_downBitrate(t,e,n){const i=n.packetsLost,r=n.nackCount;if(null==i)return this.log(`No packetsLost information in ${y.stringify(n)}`).warn(),!1;const s=t>0&&i>this._lost&&(!r||r>this._nackCount);return this._lost=i,this._nackCount=r||0,s}_upBitrate(t,e,n){if(e.type===Qr.AUDIO)return!0;if(t>1e4)return!0;const i=n.keyFramesDecoded;if(null==i)return!1;if(t){if(i>this._keyFramesDecoded){if(!this._keyFramesDecoded)return!0;this._keyFramesDecoded=0}}else this._keyFramesDecoded=i;return!1}}const ks=3e3;class Us extends I{onStart(t){this.log("onStart").info()}onStop(t){t?this.log("onStop",t).error():this.log("onStop").info()}onState(t){this.log("onState",t).info()}onPlaying(t){this.log(`onPlaying ${y.stringify(t)}`).debug()}onMetadata(t){this.log(y.stringify(t)).info()}onData(t,e,n){this.log(`Data received on track ${e} at ${t} : ${y.stringify(n)}`).info()}get streamName(){return this._connector?this._connector.streamName:""}get stream(){return this._connector&&this._connector.stream}get running(){return!!this._connector}get controller(){return this._controller}get connector(){return this._connector}get streamState(){var t;return(null===(t=this._streamMetadata)||void 0===t?void 0:t.streamState)||is.UNKNOWN}get metadata(){return this._metadata}get playingInfos(){return this._playingInfos}get audioTrack(){return this._audioTrack}set audioTrack(t){if(this._audioTrackFixed=null!=t,this._audioTrackFixed&&this._audioTrack!==t&&(this._audioTrack=t,this._connector)){if(!this._controller)throw Error("Cannot set audioTrack without start a controllable session");this._controller.setTracks({audio:t})}}get videoTrack(){return this._videoTrack}set videoTrack(t){if(this._videoTrackFixed=null!=t,this._videoTrackFixed&&this._videoTrack!==t&&(this._videoTrack=t,this._connector)){if(!this._controller)throw Error("Cannot set videoTrack without start a controllable session");this._controller.setTracks({video:t})}}get dataTracks(){return[...this._dataTracks]}set dataTracks(t){this._dataTracks=[...t],this._streamData&&(this._streamData.tracks=t)}constructor(t,e){super(),this.Connector=e,this._dataTracks=new Array,this._videoElement=t,this._playerStats=new ss}connectionInfos(){return this._connector?this._connector.connectionInfos():Promise.reject("Start player before to request connection infos")}start(e,n={}){let i,r,s,o;this.stop(),"connectParams"in e&&(s=e,e=e.connectParams),e.query=new URLSearchParams(e.query),null!=this._audioTrack&&e.query.set("audio",this._audioTrack.toFixed()),null!=this._videoTrack&&e.query.set("video",this._videoTrack.toFixed()),this._audioTrackFixed=!1,this._videoTrackFixed=!1,this._connector=new(this.Connector||(e.endPoint.startsWith("http")?Ts:ws))(e),this._connector.log=this.log.bind(this,"Signaling:"),this._connector.onOpen=t=>{var e,n;this._pollStats(),this.onStart(t),(null===(e=this._streamMetadata)||void 0===e?void 0:e.metadata)&&this._streamMetadata.onMetadata(null===(n=this._streamMetadata)||void 0===n?void 0:n.metadata),r&&this._controller&&this._controller.onPlaying(r)},this._connector.onClose=t=>{var n,r;null==i||i.reset(),this.streamState===is.OFFLINE?this.stop({type:"StreamMetadataError",name:is.OFFLINE,stream:null!==(n=e.streamName)&&void 0!==n?n:""}):"WebSocketReliableError"===(null==t?void 0:t.type)&&"Socket disconnection"===t.name?this.stop({type:"StreamMetadataError",name:"Resource not available",stream:null!==(r=e.streamName)&&void 0!==r?r:""}):this.stop(t)},e.endPoint=new k(e.endPoint).host,this._initStreamMetadata(Object.assign({},e),null!=s?s:new rs(e)),this._newStreamData(Object.assign({},e)),os(this._connector)?(n&&("compute"in n?i=n:(i=new Rs(n),i.log=this.log.bind(this,"MultiBitrate:"))),this._controller=this._connector,this._controller.onPlaying=e=>t(this,void 0,void 0,function*(){if(r=e,this._controller&&this._controller.opened&&(this._playingInfos=r,this._updateTracks(),this.onPlaying(r),i))if(this._audioTrackFixed&&this._videoTrackFixed)i.reset();else try{const t=yield this._controller.connectionInfos(1e3);if(t===o)return;const e={audio:this._audioTrackFixed?void 0:this._audioTrack,video:this._videoTrackFixed?void 0:this._videoTrack};this._controller&&this._metadata&&i.compute(this._metadata,e,(o=t).inputs)&&(this._audioTrack=e.audio,this._videoTrack=e.video,this._controller.setTracks(e))}catch(t){this.log(`Can't compute MBR, ${y.stringify(t)}`).error()}})):n&&this.log(`Cannot use a multiple bitrate without a controller: Connector ${this._connector.constructor.name} doesn't implement IController`).warn()}stop(t){const e=this._connector;e&&(this._connector=void 0,clearTimeout(this._statsPollingTimeout),this._playerStats=new ss,this._videoElement.pause(),this._videoElement.srcObject=null,this._videoElement.load(),clearTimeout(this._streamMetadataReconnectTimeout),this._streamMetadata&&(this._streamMetadata.onClose=y.EMPTY_FUNCTION,this._streamMetadata.close(),this._streamMetadata=void 0),clearTimeout(this._streamDataReconnectTimeout),this._streamData&&(this._streamData.onClose=y.EMPTY_FUNCTION,this._streamData.close(),this._streamData=void 0),e.close(),this._audioTrack=void 0,this._videoTrack=void 0,this._playingInfos=void 0,this._metadata=void 0,this._dataTracks.length=0,this.onStop(t))}computeStats(){return this._playerStats}_updateTracks(){if(!this._playingInfos||!this._metadata)return;const t=new Array,e=new Array;for(const n of this._playingInfos.tracks){const i=this._metadata.tracks.get(n);i&&(i.type===Qr.AUDIO?t.push(n):i.type===Qr.VIDEO&&e.push(n))}1===t.length&&(this._audioTrack=t[0]),1===e.length&&(this._videoTrack=e[0])}_initStreamMetadata(t,e){this._streamMetadata=e,e.log=this.log.bind(this,"StreamMetadata:"),e.onState=t=>this.onState(t),e.onMetadata=t=>{this._connector&&this._connector.opened&&(this._metadata=t.subset(this._connector.codecs),this._updateTracks(),this.onMetadata(this._metadata))},e.onClose=n=>{"StreamMetadataError"!==(null==n?void 0:n.type)?(e.log(`${n||"disconnection"}, try to reconnect to ${t.endPoint} in 3000 ms`).warn(),this._streamMetadataReconnectTimeout=setTimeout(()=>{this._initStreamMetadata(t,new rs(t))},ks)):this.stop(n)}}_newStreamData(t){const e=this._streamData=new Cs(t);e.log=this.log.bind("Timed Metadatas:"),e.onData=(t,e,n)=>this.onData(e,t,n),e.tracks=this._dataTracks,e.onClose=n=>{e.log(`${n||"disconnection"}, try to reconnect to ${t.endPoint} in 3000 ms`).warn(),this._streamDataReconnectTimeout=setTimeout(()=>{e.tracks=this._dataTracks},ks)}}_pollStats(){this._statsPollingTimeout=setTimeout(()=>t(this,void 0,void 0,function*(){var t;if(this._connector){try{yield this._playerStats.compute(yield this._connector.connectionInfos(100),null!==(t=this._metadata)&&void 0!==t?t:new es,this._videoElement.currentTime,this._audioTrack,this._videoTrack)}catch(t){}this.running&&this._pollStats()}}),1e3)}}class xs extends I{get startup(){return this._startup}set startup(t){this._startup=Math.max(this._minimum,Math.min(Math.round(t),this._maximum))}get minimum(){return this._minimum}set minimum(t){t=Math.round(t),(this._minimum=t)>this._maximum?this._maximum=this._startup=t:this._startup<t&&(this._startup=t)}get maximum(){return this._maximum}set maximum(t){t=Math.round(t),(this._maximum=t)<this._minimum?this._minimum=this._startup=t:this._startup>t&&(this._startup=t)}get constraint(){return this._bitrateConstraint}get recoverySteps(){return this._recoverySteps}set recoverySteps(t){this._recoverySteps=Math.max(1,t)}get appreciationDuration(){return this._appreciationDuration}set appreciationDuration(t){this._appreciationDuration=t}get value(){return this._bitrate}valueOf(){return this.value}get stream(){return this._stream}constructor(t,e){super();const n=Object.assign({startup:2e6,maximum:3e6,minimum:2e5,recoverySteps:2,appreciationDuration:4e3},t);this._startup=n.startup,this._minimum=n.minimum,this._maximum=n.maximum,this._appreciationDuration=n.appreciationDuration,this._stream=e,this._recoverySteps=0,this.recoverySteps=n.recoverySteps}compute(t,e,n){const i=null==t?this.startup:Math.max(this.minimum,Math.min(this._computeBitrate(t,e,n),this.maximum));return null==t?this.log(`Set startup bitrate to ${i}`).info():i>t?this.log(`Increase bitrate ${t} => ${i}`).info():i<t&&this.log(`Decrease bitrate ${t} => ${i}`).info(),this._bitrate=t,this._bitrateConstraint=e,i}reset(){this._bitrate=void 0,this._bitrateConstraint=void 0}_updateVideoConstraints(t){const e=this._stream;if(!e)return;const n=e.getVideoTracks()[0];if(!n)return;const i=n.getSettings();if(!i.width||!i.height)return;const r=i.width*i.height;t>=12e5?r<645120&&this._upgradeVideoConstraint(n,2):r>645120&&r<1198080&&this._upgradeVideoConstraint(n,.5)}_upgradeVideoConstraint(t,e){const n={},i=t.getSettings().width;null!=i&&(n.width=i*e);const r=t.getSettings().height;null!=r&&(n.height=r*e),this.log(`Resolution change ${i}X${r} => ${n.width}X${n.height}`).info(),t.applyConstraints(n)}}let As=class{constructor(t){this.recoverySteps=t,this.stableTime=0,this.stableBitrate=0,this.lastLoss=Number.POSITIVE_INFINITY}};class Is extends xs{constructor(t,e){super(t,e),this._vars=new As(this.recoverySteps-1)}reset(){super.reset(),this._vars=new As(this.recoverySteps-1)}_computeBitrate(t,e,n){const i=n&&n.stats,r=this._vars;if(e&&t>e)r.stableTime=0,t=e;else if(i&&i.loss_perc)i.loss_perc>=r.lastLoss&&(t=Math.round((1-i.loss_perc/100)*t)),r.stableTime=0,r.lastLoss=i.loss_perc;else{r.lastLoss=Number.POSITIVE_INFINITY;const e=y.time();e>=r.stableTime&&(r.stableTime?(this._updateVideoConstraints(t),t+=Math.ceil((this.maximum-r.stableBitrate)/r.recoverySteps),r.recoverySteps=Math.max(r.recoverySteps-1,this.recoverySteps)):(r.stableBitrate=t,++r.recoverySteps),r.stableTime=e+this.appreciationDuration)}return t}}class Ms extends I{onStart(t){this.log("onStart").info()}onStop(t){t?this.log("onStop",t).error():this.log("onStop").info()}onRTPProps(t){}onMediaReport(t){}onVideoBitrate(t,e){this.log(`onVideoBitrate ${y.stringify({videoBitrate:t,videoBitrateConstraint:e})}`).info()}get streamName(){return this._connector?this._connector.streamName:""}get stream(){return this._connector&&this._connector.stream}get running(){return!!this._connector}get controller(){return this._controller}get connector(){return this._connector}get mediaReport(){return this._mediaReport}get rtpProps(){return this._rtpProps}get videoBitrate(){return this._videoBitrate}set videoBitrate(t){if(t!==this._videoBitrate){if(!this._controller)throw Error("Cannot set videoBitrate without start a controllable session");null!=t?(this._videoBitrateFixed=!0,this._videoBitrate=t,this._controller.setVideoBitrate(t)):this._videoBitrateFixed=!1}}get videoBitrateConstraint(){return this._videoBitrateConstraint}get audioTrack(){var t,e;const n=this._connector&&this._connector.stream;return null!==(e=null===(t=null==n?void 0:n.getAudioTracks())||void 0===t?void 0:t[0])&&void 0!==e?e:null}get videoTrack(){var t,e;const n=this._connector&&this._connector.stream;return null!==(e=null===(t=null==n?void 0:n.getVideoTracks())||void 0===t?void 0:t[0])&&void 0!==e?e:null}constructor(t){super(),this.Connector=t,this._videoBitrateFixed=!1}setAudioTrack(t){return this._replaceTrack("audio",t)}setVideoTrack(t){return this._replaceTrack("video",t)}setRTPProps(t,e){if(!this._controller)throw Error("Cannot set rtpProps without start a controllable session");this._controller.setRTPProps(t,e)}connectionInfos(){return this._connector?this._connector.connectionInfos():Promise.reject("Start streamer before to request connection infos")}start(e,n,i={}){let r;this.stop(),this._videoBitrateFixed=!1,this._connector=new(this.Connector||(n.endPoint.startsWith("http")?Ts:ws))(n,e),this._connector.log=this.log.bind(this,"Signaling:"),this._connector.onOpen=t=>this.onStart(t),this._connector.onClose=t=>{null==r||r.reset(),this.stop(t)},os(this._connector)?(i&&("compute"in i?r=i:(r=new Is(i),r.log=this.log.bind(this,"AdaptiveBitrate:"))),this._controller=this._connector,this._controller.onOpen=t=>{this._computeVideoBitrate(r),this.onStart(t)},this._controller.onRTPProps=t=>{this._rtpProps=t,this.onRTPProps(t)},this._controller.onMediaReport=e=>t(this,void 0,void 0,function*(){this._mediaReport=e,this._computeVideoBitrate(r),this.onMediaReport(e)}),this._controller.onVideoBitrate=(t,e)=>{this._videoBitrate=t,this._videoBitrateConstraint=e,this.onVideoBitrate(t,e)}):i&&this.log(`Cannot use an adaptive bitrate without a controller: Connector ${this._connector.constructor.name} doesn't implement IController`).error()}stop(t){const e=this._connector;e&&(this._connector=void 0,e.close(),this._controller=void 0,this._mediaReport=void 0,this._videoBitrate=void 0,this._videoBitrateConstraint=void 0,this._rtpProps=void 0,this.onStop(t))}_replaceTrack(e,n){return t(this,void 0,void 0,function*(){if(!this._connector)throw Error("Cannot call _replaceTrack before start()");const t=this._connector.stream;if(!t)throw Error("Cannot call _replaceTrack without a stream");let i=null;if(null!==n){if(n.kind!==e)throw Error(`_replaceTrack: provided track kind "${n.kind}" does not match requested kind "${e}"`);i=n}yield this._connector.replaceTrack(e,i),"video"===e?t.getVideoTracks().forEach(e=>t.removeTrack(e)):t.getAudioTracks().forEach(e=>t.removeTrack(e)),i&&t.addTrack(i)})}_computeVideoBitrate(t){if(!this._controller||this._videoBitrateFixed)return;const e=t.compute(this._videoBitrate,this.videoBitrateConstraint,this.mediaReport);e!==this._videoBitrate&&(this._videoBitrate=e,this._controller.setVideoBitrate(e))}}class Ds{constructor(){this.lossPercents=new O(5),this.stableBitrates=new O(15),this.stableBitrateUpdateTime=0,this.bitrateRecoveryTimeout=1e4,this.bitrateRecoveryNextTime=0}}class Os extends xs{constructor(t,e){super(t,e),this._vars=new Ds}reset(){super.reset(),this._vars=new Ds}_computeBitrate(t,e,n){var i;const r=this._vars,s=n&&n.stats;s&&null!=s.loss_perc&&r.lossPercents.push(s.loss_perc);const o=y.time();o>=r.stableBitrateUpdateTime&&r.lossPercents.average<.2&&(r.stableBitrateUpdateTime=o+4e3,r.stableBitrates.push(Math.min(null!==(i=null!=e?e:this.constraint)&&void 0!==i?i:0,t,this.maximum)));const a=r.stableBitrates.average,c=r.stableBitrates.minimum,l=r.stableBitrates.maximum;if(c>=.8*a&&l<=1.2*a&&this._updateVideoConstraints(a),null!=e&&null!=this.constraint&&e<this.constraint){if(this.log(`onVideoBitrateConstraint: ${this._formatBitrate(e-this.constraint)}`).info(),r.bitrateConstraintTime){if(r.bitrateRecoveryTime){(o-r.bitrateRecoveryTime<r.bitrateRecoveryTimeout||2500===r.bitrateRecoveryTimeout)&&(this._increaseRecoveryTimeout(),r.bitrateRecoveryTime=void 0)}}else r.bitrateRecoveryTime||(this.log("VideoBitrateConstraint: First constrain! Halve bitrate!").info(),t=Math.round(t/2));r.bitrateConstraintTime=o}if(e&&(e<this.minimum&&(t=this.minimum),this.maximum>e&&o>=r.bitrateRecoveryNextTime)){const n=r.bitrateRecoveryNextTime&&this._bitrateRecoveryHandler(e);n?(r.bitrateRecoveryTimeout=o,r.bitrateRecoveryNextTime=0,t=n):(r.bitrateRecoveryNextTime=o+r.bitrateRecoveryTimeout,this.log(`startVideoBitrateRecoveryTimer ${r.bitrateRecoveryTimeout}`).info())}return t}_bitrateRecoveryHandler(t){const e=this._vars,n=e.lossPercents.average;if(this.log(`videoBitrateRecoveryHandler loss: ${n.toFixed(2)}`).info(),n<.2){let n=this._increaseTargetBitrate(t);return e.bitrateConstraintTime&&n>e.stableBitrates.average&&(n=this._increaseTargetBitrate(t,1.005)),this._decreaseRecoveryTimeout(),this.log(`videoBitrateRecoveryHandler increases bitrate to ${this._formatBitrate(n)}`).info(),n}if(n<5){this._increaseRecoveryTimeout();const e=this._decreaseTargetBitrate(t);return this.log(`videoBitrateRecoveryHandler decreases bitrate to ${this._formatBitrate(e)}`).info(),e}}_increaseTargetBitrate(t,e=1.05){let n=Math.round(t*e);return n>this.maximum&&(n=this.maximum),n}_decreaseTargetBitrate(t){let e=Math.round(.99*t);return e<this.minimum&&(e=this.minimum),e}_increaseRecoveryTimeout(){this._vars.bitrateRecoveryTimeout=Math.min(6e4,2*this._vars.bitrateRecoveryTimeout)}_decreaseRecoveryTimeout(){this._vars.bitrateRecoveryTimeout=Math.max(2500,Math.round(.75*this._vars.bitrateRecoveryTimeout))}_formatBitrate(t){return(t/1e6).toFixed(3)}}class Ns extends C{get url(){return this._url}get reporting(){return this._reporting}constructor(t){if(super(),(t=new URL(t)).protocol.startsWith("ws"))this._ws=new P;else if(!t.protocol.startsWith("http"))throw Error("Protocol "+t.protocol+" not supported");this._url=t.toString(),this._reporting=0}report(e,n){e.log=this.log.bind(this,e.constructor.name);let i=e.onRelease=()=>{i&&(i=void 0,clearInterval(r),this.log(`Stop ${e.constructor.name} reporting`).info(),--this._reporting>0||(this._ws&&this._ws.close(),this._fetch&&this._fetch.abort()))};const r=(n?setInterval:setTimeout)(()=>t(this,void 0,void 0,function*(){!n&&i&&i();try{yield this._send(e)}catch(t){e.log(y.stringify(t)).error()}}),1e3*n);++this._reporting,this.log(`Start ${e.constructor.name} reporting every ${n} seconds`).info()}_send(e){return t(this,void 0,void 0,function*(){let t,n,i;try{t=yield e.serialize()}catch(t){if(!t)return;throw t}t instanceof ArrayBuffer?(i="application/octet-stream",n=t):"string"==typeof t?(i="text/plain",n=t):(i="application/json",n=JSON.stringify(t)),this._ws?(this._ws.closed&&this._ws.open(this._url),this._ws.queueing.length=0,this._ws.send(n)):(this._fetch&&this._fetch.abort(),this._fetch=new AbortController,fetch(this._url,{method:"POST",body:n,headers:{"Content-Type":i},signal:this._fetch.signal}))})}}class Ps extends I{onRelease(){}constructor(t){super(),this._streamer=t,this._lastBytesSend=0,this._lastBytesSendTime=Date.now(),t.once("stop",()=>this.onRelease())}serialize(){return t(this,void 0,void 0,function*(){if(!this._streamer.running)return Promise.reject();const t={streamId:this._streamer.streamName,vbt:this._streamer.videoBitrate,vbc:this._streamer.videoBitrateConstraint},e=this._streamer.mediaReport;let n;e&&(t.server={millis:e.millis,tracks:e.tracks},e.stats&&(t.server.jitterMs=e.stats.jitter_ms,t.server.lossNum=e.stats.loss_num,t.server.lossPerc=e.stats.loss_perc,t.server.nackNum=e.stats.nack_num));try{n=yield this._streamer.connectionInfos()}catch(e){return this.log(`Report stats without connection infos, ${y.stringify(e)}`).warn(),t}const i=n.candidate;if(i){if(t.sessionId=i.id,t.timestamp=i.timestamp,t.currentRoundTripTime=i.currentRoundTripTime,t.totalRoundTripTime=i.totalRoundTripTime,t.requestsReceived=i.requestsReceived,t.requestsSent=i.requestsSent,t.responsesReceived=i.responsesReceived,t.responsesSent=i.responsesSent,t.bytesSent=i.bytesSent,t.bytesReceived=i.bytesReceived,null==i.availableOutgoingBitrate){const e=t.bytesSent-this._lastBytesSend;this._lastBytesSend=t.bytesSent;const n=Date.now(),r=(n-this._lastBytesSendTime)/1e3;this._lastBytesSendTime=n,i.availableOutgoingBitrate=8*e/r}t.availableOutgoingBitrate=i.availableOutgoingBitrate}const r=n.outputs.audio;r&&(t.audio={bytesSent:r.bytesSent,packetsSent:r.packetsSent,retransmittedBytesSent:r.retransmittedBytesSent,retransmittedPacketsSent:r.retransmittedPacketsSent});const s=n.outputs.audio;return s&&(t.video={bytesSent:s.bytesSent,packetsSent:s.packetsSent,retransmittedBytesSent:s.retransmittedBytesSent,retransmittedPacketsSent:s.retransmittedPacketsSent,firCount:s.firCount,framesEncoded:s.framesEncoded,nackCount:s.nackCount,totalEncodeTime:s.totalEncodeTime,hugeFramesSent:s.hugeFramesSent,framesSent:s.framesSent,frameHeight:s.frameHeight,frameWidth:s.frameWidth}),t})}}const $s="5.2.0";export{xs as ABRAbstract,Os as ABRGrade,Is as ABRLinear,Ts as HTTPConnector,Es as MBRAbstract,Rs as MBRLinear,Qr as MType,es as Metadata,Us as Player,ss as PlayerStats,bs as SIPConnector,rs as StreamMetadata,is as StreamState,Ms as Streamer,Ps as StreamerStats,Ns as Telemetry,$s as VERSION,ws as WSController,Cs as WSStreamData,Zr as utils};//# sourceMappingURL=webrtc-client.bundle.min.js.map
