UNPKG

@ceeblue/webrtc-client

Version:
1 lines 166 kB
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 instanceo