@hubtalk-ai/web-sdk 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +274 -411
- package/README.ru.md +338 -0
- package/dist/errors.d.ts +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +256 -152
- package/dist/types.d.ts +13 -1
- package/dist/voice-client.bundle.js +6 -6
- package/dist/voice-client.d.ts +18 -0
- package/dist/widget-avatar.d.ts +7 -0
- package/dist/widget.bundle.js +267 -0
- package/dist/widget.css +597 -0
- package/dist/widget.d.ts +40 -0
- package/dist/widget.js +787 -0
- package/package.json +20 -7
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
var HubTalkWidget=(function(Io){"use strict";function P_(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var I_=Object.defineProperty,R_=(n,e,t)=>e in n?I_(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,jf=(n,e,t)=>R_(n,typeof e!="symbol"?e+"":e,t);class Dt{constructor(){jf(this,"_locking"),jf(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function ut(n,e){if(!n)throw new Error(e)}const O_=34028234663852886e22,M_=-34028234663852886e22,L_=4294967295,N_=2147483647,F_=-2147483648;function Ro(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>N_||n<F_)throw new Error("invalid int 32: "+n)}function Jl(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>L_||n<0)throw new Error("invalid uint 32: "+n)}function Hf(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>O_||n<M_))throw new Error("invalid float 32: "+n)}const $f=Symbol("@bufbuild/protobuf/enum-type");function U_(n){const e=n[$f];return ut(e,"missing enum type on enum object"),e}function Wf(n,e,t,i){n[$f]=zf(e,t.map(s=>({no:s.no,name:s.name,localName:n[s.no]})))}function zf(n,e,t){const i=Object.create(null),s=Object.create(null),r=[];for(const a of e){const o=Gf(a);r.push(o),i[a.name]=o,s[a.no]=o}return{typeName:n,values:r,findName(a){return i[a]},findNumber(a){return s[a]}}}function B_(n,e,t){const i={};for(const s of e){const r=Gf(s);i[r.localName]=r.no,i[r.no]=r.localName}return Wf(i,n,e),i}function Gf(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class Zl{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),s=i.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const i=this.getType(),s=i.runtime.json,r=s.makeReadOptions(t);return s.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,s=i.makeWriteOptions(e),r=s.writerFactory();return i.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,s=i.makeWriteOptions(e);return i.writeMessage(this,s)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function q_(n,e,t,i){var s;const r=(s=i==null?void 0:i.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),a={[r]:function(o){n.util.initFields(this),n.util.initPartial(o,this)}}[r];return Object.setPrototypeOf(a.prototype,new Zl),Object.assign(a,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return n.util.equals(a,o,c)}}),a}function V_(){let n=0,e=0;for(let i=0;i<28;i+=7){let s=this.buf[this.pos++];if(n|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function eu(n,e,t){for(let r=0;r<28;r=r+7){const a=n>>>r,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)return}const i=n>>>28&15|(e&7)<<4,s=e>>3!=0;if(t.push((s?i|128:i)&255),!!s){for(let r=3;r<31;r=r+7){const a=e>>>r,o=!!(a>>>7),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const Oo=4294967296;function Kf(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,s=0;function r(a,o){const c=Number(n.slice(a,o));s*=t,i=i*t+c,i>=Oo&&(s=s+(i/Oo|0),i=i%Oo)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?Yf(i,s):tu(i,s)}function j_(n,e){let t=tu(n,e);const i=t.hi&2147483648;i&&(t=Yf(t.lo,t.hi));const s=Xf(t.lo,t.hi);return i?"-"+s:s}function Xf(n,e){var t=H_(n,e);if(n=t.lo,e=t.hi,e<=2097151)return String(Oo*e+n);const i=n&16777215,s=(n>>>24|e<<8)&16777215,r=e>>16&65535;let a=i+s*6777216+r*6710656,o=s+r*8147497,c=r*2;const l=1e7;return a>=l&&(o+=Math.floor(a/l),a%=l),o>=l&&(c+=Math.floor(o/l),o%=l),c.toString()+Qf(o)+Qf(a)}function H_(n,e){return{lo:n>>>0,hi:e>>>0}}function tu(n,e){return{lo:n|0,hi:e|0}}function Yf(n,e){return e=~e,n?n=~n+1:e+=1,tu(n,e)}const Qf=n=>{const e=String(n);return"0000000".slice(e.length)+e};function Jf(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function $_(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function W_(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>r||l<s)throw new Error("int64 invalid: ".concat(c));return l},uParse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>o||l<a)throw new Error("uint64 invalid: ".concat(c));return l},enc(c){return n.setBigInt64(0,this.parse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(c){return n.setBigInt64(0,this.uParse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(c,l){return n.setInt32(0,c,!0),n.setInt32(4,l,!0),n.getBigInt64(0,!0)},uDec(c,l){return n.setInt32(0,c,!0),n.setInt32(4,l,!0),n.getBigUint64(0,!0)}}}const t=s=>ut(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),i=s=>ut(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),i(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),Kf(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),i(s),Kf(s)},dec(s,r){return j_(s,r)},uDec(s,r){return Xf(s,r)}}}const nt=W_();var oe;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(oe||(oe={}));var Wn;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(Wn||(Wn={}));function zn(n,e,t){if(e===t)return!0;if(n==oe.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case oe.UINT64:case oe.FIXED64:case oe.INT64:case oe.SFIXED64:case oe.SINT64:return e==t}return!1}function Ys(n,e){switch(n){case oe.BOOL:return!1;case oe.UINT64:case oe.FIXED64:case oe.INT64:case oe.SFIXED64:case oe.SINT64:return e==0?nt.zero:"0";case oe.DOUBLE:case oe.FLOAT:return 0;case oe.BYTES:return new Uint8Array(0);case oe.STRING:return"";default:return 0}}function Zf(n,e){switch(n){case oe.BOOL:return e===!1;case oe.STRING:return e==="";case oe.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}function ep(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,i=Array(e);t<e;t++)i[t]=n[t];return i}function z_(n){if(Array.isArray(n))return n}function Fe(n,e,t){return(e=Y_(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function G_(n,e){var t=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(t!=null){var i,s,r,a,o=[],c=!0,l=!1;try{if(r=(t=t.call(n)).next,e===0){if(Object(t)!==t)return;c=!1}else for(;!(c=(i=r.call(t)).done)&&(o.push(i.value),o.length!==e);c=!0);}catch(u){l=!0,s=u}finally{try{if(!c&&t.return!=null&&(a=t.return(),Object(a)!==a))return}finally{if(l)throw s}}return o}}function K_(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
2
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _e(n,e){return z_(n)||G_(n,e)||Q_(n,e)||K_()}function X_(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Y_(n){var e=X_(n,"string");return typeof e=="symbol"?e:e+""}function Q_(n,e){if(n){if(typeof n=="string")return ep(n,e);var t={}.toString.call(n).slice(8,-1);return t==="Object"&&n.constructor&&(t=n.constructor.name),t==="Map"||t==="Set"?Array.from(n):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?ep(n,e):void 0}}var gt;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(gt||(gt={}));class J_{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),i=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],i),i+=this.chunks[s].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Jl(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ro(e),Jf(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Hf(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Jl(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ro(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ro(e),e=(e<<1^e>>31)>>>0,Jf(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=nt.enc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=nt.uEnc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=nt.enc(e);return eu(t.lo,t.hi,this.buf),this}sint64(e){let t=nt.enc(e),i=t.hi>>31,s=t.lo<<1^i,r=(t.hi<<1|t.lo>>>31)^i;return eu(s,r,this.buf),this}uint64(e){let t=nt.uEnc(e);return eu(t.lo,t.hi,this.buf),this}}class Z_{constructor(e,t){this.varint64=V_,this.uint32=$_,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case gt.Varint:for(;this.buf[this.pos++]&128;);break;case gt.Bit64:this.pos+=4;case gt.Bit32:this.pos+=4;break;case gt.LengthDelimited:let s=this.uint32();this.pos+=s;break;case gt.StartGroup:for(;;){const r=this.tag(),a=_e(r,2),o=a[0],c=a[1];if(c===gt.EndGroup){if(t!==void 0&&o!==t)throw new Error("invalid end group tag");break}this.skip(c,o)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return nt.dec(...this.varint64())}uint64(){return nt.uDec(...this.varint64())}sint64(){let e=this.varint64(),t=_e(e,2),i=t[0],s=t[1],r=-(i&1);return i=(i>>>1|(s&1)<<31)^r,s=s>>>1^r,nt.dec(i,s)}bool(){let e=this.varint64(),t=_e(e,2),i=t[0],s=t[1];return i!==0||s!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return nt.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return nt.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function eS(n,e,t,i){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof i=="function"?i():i;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=n.util.newFieldList([r]).list()[0]}return s},runtime:n}}function tp(n){const e=n.field.localName,t=Object.create(null);return t[e]=tS(n),[t,()=>t[e]]}function tS(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return Ys(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function iS(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let Cn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Mo=[];for(let n=0;n<Cn.length;n++)Mo[Cn[n].charCodeAt(0)]=n;Mo[45]=Cn.indexOf("+"),Mo[95]=Cn.indexOf("/");const ip={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,s=0,r,a=0;for(let o=0;o<n.length;o++){if(r=Mo[n.charCodeAt(o)],r===void 0)switch(n[o]){case"=":s=0;case`
|
|
3
|
+
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=r,s=1;break;case 1:t[i++]=a<<2|(r&48)>>4,a=r,s=2;break;case 2:t[i++]=(a&15)<<4|(r&60)>>2,a=r,s=3;break;case 3:t[i++]=(a&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,s=0;for(let r=0;r<n.length;r++)switch(i=n[r],t){case 0:e+=Cn[i>>2],s=(i&3)<<4,t=1;break;case 1:e+=Cn[s|i>>4],s=(i&15)<<2,t=2;break;case 2:e+=Cn[s|i>>6],e+=Cn[i&63],t=0;break}return t&&(e+=Cn[s],e+="=",t==1&&(e+="=")),e}};function nS(n,e,t){sp(e,n);const i=e.runtime.bin.makeReadOptions(t),s=iS(n.getType().runtime.bin.listUnknownFields(n),e.field),r=tp(e),a=_e(r,2),o=a[0],c=a[1];for(const l of s)e.runtime.bin.readField(o,i.readerFactory(l.data),e.field,l.wireType,i);return c()}function sS(n,e,t,i){sp(e,n);const s=e.runtime.bin.makeReadOptions(i),r=e.runtime.bin.makeWriteOptions(i);if(np(n,e)){const l=n.getType().runtime.bin.listUnknownFields(n).filter(u=>u.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const u of l)n.getType().runtime.bin.onUnknownField(n,u.no,u.wireType,u.data)}const a=r.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,t,a,r);const c=s.readerFactory(a.finish());for(;c.pos<c.len;){const l=c.tag(),u=_e(l,2),h=u[0],p=u[1],y=c.skip(p,h);n.getType().runtime.bin.onUnknownField(n,h,p,y)}}function np(n,e){const t=n.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(n).find(i=>i.no==e.field.no)}function sp(n,e){ut(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function rp(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!Zf(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function ap(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?Ys(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function kn(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(Zl.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function op(n,e){return kn(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}oe.DOUBLE,oe.FLOAT,oe.INT64,oe.UINT64,oe.INT32,oe.UINT32,oe.BOOL,oe.STRING,oe.BYTES;const cp={ignoreUnknownFields:!1},lp={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function rS(n){return n?Object.assign(Object.assign({},cp),n):cp}function aS(n){return n?Object.assign(Object.assign({},lp),n):lp}const Lo=Symbol(),No=Symbol();function oS(){return{makeReadOptions:rS,makeWriteOptions:aS,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(n.typeName," from JSON: ").concat(Ji(e)));i=i??new n;const s=new Map,r=t.typeRegistry;for(const o of Object.entries(e)){var a=_e(o,2);const c=a[0],l=a[1],u=n.fields.findJsonName(c);if(u){if(u.oneof){if(l===null&&u.kind=="scalar")continue;const h=s.get(u.oneof);if(h!==void 0)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: multiple keys for oneof "').concat(u.oneof.name,'" present: "').concat(h,'", "').concat(c,'"'));s.set(u.oneof,c)}up(i,l,u,t,n)}else{let h=!1;if(r!=null&&r.findExtension&&c.startsWith("[")&&c.endsWith("]")){const p=r.findExtension(c.substring(1,c.length-1));if(p&&p.extendee.typeName==n.typeName){h=!0;const y=tp(p),_=_e(y,2),b=_[0],S=_[1];up(b,l,p.field,t,p),sS(i,p,S(),t)}}if(!h&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(c,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let s;try{for(s of t.fields.byNumber()){if(!rp(s,n)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!lS(s))continue}const a=s.oneof?n[s.oneof.localName].value:n[s.localName],o=dp(s,a,e);o!==void 0&&(i[e.useProtoFieldName?s.name:s.jsonName]=o)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(n)){const o=r.findExtensionFor(t.typeName,a.no);if(o&&np(n,o)){const c=nS(n,o,e),l=dp(o.field,c,e);l!==void 0&&(i[o.field.jsonName]=l)}}}catch(r){const a=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),o=r instanceof Error?r.message:String(r);throw new Error(a+(o.length>0?": ".concat(o):""))}return i},readScalar(n,e,t){return ra(n,e,t??Wn.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||Zf(n,e)))return Fo(n,e)},debug:Ji}}function Ji(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function up(n,e,t,i,s){let r=t.localName;if(t.repeated){if(ut(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ji(e)));const o=n[r];for(const c of e){if(c===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ji(c)));switch(t.kind){case"message":o.push(t.T.fromJson(c,i));break;case"enum":const l=iu(t.T,c,i.ignoreUnknownFields,!0);l!==No&&o.push(l);break;case"scalar":try{o.push(ra(t.T,c,t.L,!0))}catch(u){let h="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ji(c));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ji(e)));const o=n[r];for(const c of Object.entries(e)){var a=_e(c,2);const l=a[0],u=a[1];if(u===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let h;try{h=cS(t.K,l)}catch(p){let y="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ji(e));throw p instanceof Error&&p.message.length>0&&(y+=": ".concat(p.message)),new Error(y)}switch(t.V.kind){case"message":o[h]=t.V.T.fromJson(u,i);break;case"enum":const p=iu(t.V.T,u,i.ignoreUnknownFields,!0);p!==No&&(o[h]=p);break;case"scalar":try{o[h]=ra(t.V.T,u,Wn.BIGINT,!0)}catch(y){let _="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ji(e));throw y instanceof Error&&y.message.length>0&&(_+=": ".concat(y.message)),new Error(_)}break}}}else switch(t.oneof&&(n=n[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let c=n[r];kn(c)?c.fromJson(e,i):(n[r]=c=o.fromJson(e,i),o.fieldWrapper&&!t.oneof&&(n[r]=o.fieldWrapper.unwrapField(c)));break;case"enum":const l=iu(t.T,e,i.ignoreUnknownFields,!1);switch(l){case Lo:ap(t,n);break;case No:break;default:n[r]=l;break}break;case"scalar":try{const u=ra(t.T,e,t.L,!1);switch(u){case Lo:ap(t,n);break;default:n[r]=u;break}}catch(u){let h="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Ji(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}function cS(n,e){if(n===oe.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return ra(n,e,Wn.BIGINT,!0).toString()}function ra(n,e,t,i){if(e===null)return i?Ys(n,t):Lo;switch(n){case oe.DOUBLE:case oe.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const s=Number(e);if(Number.isNaN(s)||!Number.isFinite(s))break;return n==oe.FLOAT&&Hf(s),s;case oe.INT32:case oe.FIXED32:case oe.SFIXED32:case oe.SINT32:case oe.UINT32:let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return n==oe.UINT32||n==oe.FIXED32?Jl(r):Ro(r),r;case oe.INT64:case oe.SFIXED64:case oe.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=nt.parse(e);return t?a.toString():a;case oe.FIXED64:case oe.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=nt.uParse(e);return t?o.toString():o;case oe.BOOL:if(typeof e!="boolean")break;return e;case oe.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case oe.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return ip.dec(e)}throw new Error}function iu(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:Lo;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=n.findName(e);if(s!==void 0)return s.no;if(t)return No;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(Ji(e)))}function lS(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function dp(n,e,t){if(n.kind=="map"){ut(typeof e=="object"&&e!=null);const a={},o=Object.entries(e);switch(n.V.kind){case"scalar":for(const l of o){var i=_e(l,2);const u=i[0],h=i[1];a[u.toString()]=Fo(n.V.T,h)}break;case"message":for(const l of o){var s=_e(l,2);const u=s[0],h=s[1];a[u.toString()]=h.toJson(t)}break;case"enum":const c=n.V.T;for(const l of o){var r=_e(l,2);const u=r[0],h=r[1];a[u.toString()]=nu(c,h,t.enumAsInteger)}break}return t.emitDefaultValues||o.length>0?a:void 0}if(n.repeated){ut(Array.isArray(e));const a=[];switch(n.kind){case"scalar":for(let o=0;o<e.length;o++)a.push(Fo(n.T,e[o]));break;case"enum":for(let o=0;o<e.length;o++)a.push(nu(n.T,e[o],t.enumAsInteger));break;case"message":for(let o=0;o<e.length;o++)a.push(e[o].toJson(t));break}return t.emitDefaultValues||a.length>0?a:void 0}switch(n.kind){case"scalar":return Fo(n.T,e);case"enum":return nu(n.T,e,t.enumAsInteger);case"message":return op(n.T,e).toJson(t)}}function nu(n,e,t){var i;if(ut(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=n.findNumber(e);return(i=s==null?void 0:s.name)!==null&&i!==void 0?i:e}function Fo(n,e){switch(n){case oe.INT32:case oe.SFIXED32:case oe.SINT32:case oe.FIXED32:case oe.UINT32:return ut(typeof e=="number"),e;case oe.FLOAT:case oe.DOUBLE:return ut(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case oe.STRING:return ut(typeof e=="string"),e;case oe.BOOL:return ut(typeof e=="boolean"),e;case oe.UINT64:case oe.FIXED64:case oe.INT64:case oe.SFIXED64:case oe.SINT64:return ut(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case oe.BYTES:return ut(e instanceof Uint8Array),ip.enc(e)}}const Qs=Symbol("@bufbuild/protobuf/unknown-fields"),hp={readUnknownFields:!0,readerFactory:n=>new Z_(n)},fp={writeUnknownFields:!0,writerFactory:()=>new J_};function uS(n){return n?Object.assign(Object.assign({},hp),n):hp}function dS(n){return n?Object.assign(Object.assign({},fp),n):fp}function hS(){return{makeReadOptions:uS,makeWriteOptions:dS,listUnknownFields(n){var e;return(e=n[Qs])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[Qs]},writeUnknownFields(n,e){const i=n[Qs];if(i)for(const s of i)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(n,e,t,i){const s=n;Array.isArray(s[Qs])||(s[Qs]=[]),s[Qs].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,s){const r=n.getType(),a=s?e.len:e.pos+t;let o,c;for(;e.pos<a;){var l=e.tag(),u=_e(l,2);if(o=u[0],c=u[1],s===!0&&c==gt.EndGroup)break;const h=r.fields.find(o);if(!h){const p=e.skip(c,o);i.readUnknownFields&&this.onUnknownField(n,o,c,p);continue}pp(n,e,h,c,i)}if(s&&(c!=gt.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:pp,writeMessage(n,e,t){const i=n.getType();for(const s of i.fields.byNumber()){if(!rp(s,n)){if(s.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(s.name," to binary: required field not set"));continue}const r=s.oneof?n[s.oneof.localName].value:n[s.localName];mp(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&mp(n,e,t,i)}}}function pp(n,e,t,i,s){let r=t.repeated,a=t.localName;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=a&&delete n.value,n.case=a,a="value"),t.kind){case"scalar":case"enum":const o=t.kind=="enum"?oe.INT32:t.T;let c=Bo;if(t.kind=="scalar"&&t.L>0&&(c=pS),r){let _=n[a];if(i==gt.LengthDelimited&&o!=oe.STRING&&o!=oe.BYTES){let S=e.uint32()+e.pos;for(;e.pos<S;)_.push(c(e,o))}else _.push(c(e,o))}else n[a]=c(e,o);break;case"message":const l=t.T;r?n[a].push(Uo(e,new l,s,t)):kn(n[a])?Uo(e,n[a],s,t):(n[a]=Uo(e,new l,s,t),l.fieldWrapper&&!t.oneof&&!t.repeated&&(n[a]=l.fieldWrapper.unwrapField(n[a])));break;case"map":let u=fS(t,e,s),h=_e(u,2),p=h[0],y=h[1];n[a][p]=y;break}}function Uo(n,e,t,i){const s=e.getType().runtime.bin,r=i==null?void 0:i.delimited;return s.readMessage(e,n,r?i.no:n.uint32(),t,r),e}function fS(n,e,t){const i=e.uint32(),s=e.pos+i;let r,a;for(;e.pos<s;){const o=e.tag();switch(_e(o,1)[0]){case 1:r=Bo(e,n.K);break;case 2:switch(n.V.kind){case"scalar":a=Bo(e,n.V.T);break;case"enum":a=e.int32();break;case"message":a=Uo(e,new n.V.T,t,void 0);break}break}}if(r===void 0&&(r=Ys(n.K,Wn.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(n.V.kind){case"scalar":a=Ys(n.V.T,Wn.BIGINT);break;case"enum":a=n.V.T.values[0].no;break;case"message":a=new n.V.T;break}return[r,a]}function pS(n,e){const t=Bo(n,e);return typeof t=="bigint"?t.toString():t}function Bo(n,e){switch(e){case oe.STRING:return n.string();case oe.BOOL:return n.bool();case oe.DOUBLE:return n.double();case oe.FLOAT:return n.float();case oe.INT32:return n.int32();case oe.INT64:return n.int64();case oe.UINT64:return n.uint64();case oe.FIXED64:return n.fixed64();case oe.BYTES:return n.bytes();case oe.FIXED32:return n.fixed32();case oe.SFIXED32:return n.sfixed32();case oe.SFIXED64:return n.sfixed64();case oe.SINT64:return n.sint64();case oe.UINT32:return n.uint32();case oe.SINT32:return n.sint32()}}function mp(n,e,t,i){ut(e!==void 0);const s=n.repeated;switch(n.kind){case"scalar":case"enum":let a=n.kind=="enum"?oe.INT32:n.T;if(s)if(ut(Array.isArray(e)),n.packed)gS(t,a,n.no,e);else for(const o of e)aa(t,a,n.no,o);else aa(t,a,n.no,e);break;case"message":if(s){ut(Array.isArray(e));for(const o of e)gp(t,i,n,o)}else gp(t,i,n,e);break;case"map":ut(typeof e=="object"&&e!=null);for(const o of Object.entries(e)){var r=_e(o,2);const c=r[0],l=r[1];mS(t,i,n,c,l)}break}}function mS(n,e,t,i,s){n.tag(t.no,gt.LengthDelimited),n.fork();let r=i;switch(t.K){case oe.INT32:case oe.FIXED32:case oe.UINT32:case oe.SFIXED32:case oe.SINT32:r=Number.parseInt(i);break;case oe.BOOL:ut(i=="true"||i=="false"),r=i=="true";break}switch(aa(n,t.K,1,r),t.V.kind){case"scalar":aa(n,t.V.T,2,s);break;case"enum":aa(n,oe.INT32,2,s);break;case"message":ut(s!==void 0),n.tag(2,gt.LengthDelimited).bytes(s.toBinary(e));break}n.join()}function gp(n,e,t,i){const s=op(t.T,i);t.delimited?n.tag(t.no,gt.StartGroup).raw(s.toBinary(e)).tag(t.no,gt.EndGroup):n.tag(t.no,gt.LengthDelimited).bytes(s.toBinary(e))}function aa(n,e,t,i){ut(i!==void 0);let s=yp(e),r=_e(s,2),a=r[0],o=r[1];n.tag(t,a)[o](i)}function gS(n,e,t,i){if(!i.length)return;n.tag(t,gt.LengthDelimited).fork();let s=yp(e),r=_e(s,2),a=r[1];for(let o=0;o<i.length;o++)n[a](i[o]);n.join()}function yp(n){let e=gt.Varint;switch(n){case oe.BYTES:case oe.STRING:e=gt.LengthDelimited;break;case oe.DOUBLE:case oe.FIXED64:case oe.SFIXED64:e=gt.Bit64;break;case oe.FIXED32:case oe.SFIXED32:case oe.FLOAT:e=gt.Bit32;break}const t=oe[n].toLowerCase();return[e,t]}function yS(){return{setEnumType:Wf,initPartial(n,e){if(n===void 0)return;const t=e.getType();for(const s of t.fields.byMember()){const r=s.localName,a=e,o=n;if(o[r]!=null)switch(s.kind){case"oneof":const c=o[r].case;if(c===void 0)continue;const l=s.findField(c);let u=o[r].value;l&&l.kind=="message"&&!kn(u,l.T)?u=new l.T(u):l&&l.kind==="scalar"&&l.T===oe.BYTES&&(u=oa(u)),a[r]={case:c,value:u};break;case"scalar":case"enum":let h=o[r];s.T===oe.BYTES&&(h=s.repeated?h.map(oa):oa(h)),a[r]=h;break;case"map":switch(s.V.kind){case"scalar":case"enum":if(s.V.T===oe.BYTES)for(const _ of Object.entries(o[r])){var i=_e(_,2);const b=i[0],S=i[1];a[r][b]=oa(S)}else Object.assign(a[r],o[r]);break;case"message":const y=s.V.T;for(const _ of Object.keys(o[r])){let b=o[r][_];y.fieldWrapper||(b=new y(b)),a[r][_]=b}break}break;case"message":const p=s.T;if(s.repeated)a[r]=o[r].map(y=>kn(y,p)?y:new p(y));else{const y=o[r];p.fieldWrapper?p.typeName==="google.protobuf.BytesValue"?a[r]=oa(y):a[r]=y:a[r]=kn(y,p)?y:new p(y)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const s=e[i.localName],r=t[i.localName];if(i.repeated){if(s.length!==r.length)return!1;switch(i.kind){case"message":return s.every((a,o)=>i.T.equals(a,r[o]));case"scalar":return s.every((a,o)=>zn(i.T,a,r[o]));case"enum":return s.every((a,o)=>zn(oe.INT32,a,r[o]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let a=s,o=r;return i.T.fieldWrapper&&(a!==void 0&&!kn(a)&&(a=i.T.fieldWrapper.wrapField(a)),o!==void 0&&!kn(o)&&(o=i.T.fieldWrapper.wrapField(o))),i.T.equals(a,o);case"enum":return zn(oe.INT32,s,r);case"scalar":return zn(i.T,s,r);case"oneof":if(s.case!==r.case)return!1;const c=i.findField(s.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(s.value,r.value);case"enum":return zn(oe.INT32,s.value,r.value);case"scalar":return zn(c.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const l=Object.keys(s).concat(Object.keys(r));switch(i.V.kind){case"message":const u=i.V.T;return l.every(p=>u.equals(s[p],r[p]));case"enum":return l.every(p=>zn(oe.INT32,s[p],r[p]));case"scalar":const h=i.V.T;return l.every(p=>zn(h,s[p],r[p]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const r of e.fields.byMember()){const a=n[r.localName];let o;if(r.repeated)o=a.map(qo);else if(r.kind=="map"){o=i[r.localName];for(const c of Object.entries(a)){var s=_e(c,2);const l=s[0],u=s[1];o[l]=qo(u)}}else r.kind=="oneof"?o=r.findField(a.case)?{case:a.case,value:qo(a.value)}:{case:void 0}:o=qo(a);i[r.localName]=o}for(const r of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,r.no,r.wireType,r.data);return t}}}function qo(n){if(n===void 0)return n;if(kn(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function oa(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function vS(n,e,t){return{syntax:n,json:oS(),bin:hS(),util:Object.assign(Object.assign({},yS()),{newFieldList:e,initFields:t}),makeMessageType(i,s,r){return q_(this,i,s,r)},makeEnum:B_,makeEnumType:zf,getEnumType:U_,makeExtension(i,s,r){return eS(this,i,s,r)}}}class bS{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function vp(n,e){const t=bp(n);return e?t:ES(kS(t))}function TS(n){return vp(n,!1)}const _S=bp;function bp(n){let e=!1;const t=[];for(let i=0;i<n.length;i++){let s=n.charAt(i);switch(s){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const SS=new Set(["constructor","toString","toJSON","valueOf"]),CS=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Tp=n=>"".concat(n,"$"),kS=n=>CS.has(n)?Tp(n):n,ES=n=>SS.has(n)?Tp(n):n;class xS{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=TS(e)}addField(e){ut(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function wS(n,e){var t,i,s,r,a,o;const c=[];let l;for(const u of typeof n=="function"?n():n){const h=u;if(h.localName=vp(u.name,u.oneof!==void 0),h.jsonName=(t=u.jsonName)!==null&&t!==void 0?t:_S(u.name),h.repeated=(i=u.repeated)!==null&&i!==void 0?i:!1,u.kind=="scalar"&&(h.L=(s=u.L)!==null&&s!==void 0?s:Wn.BIGINT),h.delimited=(r=u.delimited)!==null&&r!==void 0?r:!1,h.req=(a=u.req)!==null&&a!==void 0?a:!1,h.opt=(o=u.opt)!==null&&o!==void 0?o:!1,u.packed===void 0&&(h.packed=u.kind=="enum"||u.kind=="scalar"&&u.T!=oe.BYTES&&u.T!=oe.STRING),u.oneof!==void 0){const p=typeof u.oneof=="string"?u.oneof:u.oneof.name;(!l||l.name!=p)&&(l=new xS(p)),h.oneof=l,l.addField(h)}c.push(h)}return c}const H=vS("proto3",n=>new bS(n,e=>wS(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=Ys(e.T,e.L);break}}});class ri extends Zl{constructor(e){super(),this.seconds=nt.zero,this.nanos=0,H.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(H.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const s=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=nt.parse(s/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?i="."+s.substring(0,3)+"Z":s.substring(6)==="000"?i="."+s.substring(0,6)+"Z":i="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return ri.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new ri({seconds:nt.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new ri().fromBinary(e,t)}static fromJson(e,t){return new ri().fromJson(e,t)}static fromJsonString(e,t){return new ri().fromJsonString(e,t)}static equals(e,t){return H.util.equals(ri,e,t)}}ri.runtime=H,ri.typeName="google.protobuf.Timestamp",ri.fields=H.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const AS=H.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ri},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:DS,repeated:!0},{no:5,name:"events",kind:"message",T:IS,repeated:!0}]),DS=H.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:PS,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),PS=H.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ri},{no:3,name:"value",kind:"scalar",T:2}]),IS=H.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:ri},{no:7,name:"normalized_end_timestamp",kind:"message",T:ri,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),_p=H.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Li=H.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),_t=H.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),su=H.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ca=H.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),la=H.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Gt=H.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"},{no:16,name:"AGENT_ERROR"}]),vs=H.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),RS=H.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Pt=H.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),Js=H.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"},{no:2,name:"PTF_USER_DATA"}]),Vo=H.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:jo,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:Fp}]),jo=H.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),OS=H.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:H.getEnumType(_t),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8},{no:13,name:"can_manage_agent_session",kind:"scalar",T:8}]),bs=H.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:H.getEnumType(Zs)},{no:4,name:"tracks",kind:"message",T:tr,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:OS},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:H.getEnumType(er)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:H.getEnumType(Gt)},{no:18,name:"kind_details",kind:"enum",T:H.getEnumType(MS),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:Ho,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5},{no:21,name:"capabilities",kind:"enum",T:H.getEnumType(ua),repeated:!0}]),Zs=H.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),er=H.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),MS=H.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"},{no:5,name:"SIMULATION"}]),Ve=H.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),LS=H.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Gn,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:H.getEnumType(kp)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),tr=H.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:H.getEnumType(Li)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:H.getEnumType(_t)},{no:10,name:"layers",kind:"message",T:Gn,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:LS,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:H.getEnumType(Ve)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Fp},{no:19,name:"audio_features",kind:"enum",T:H.getEnumType(Pt),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:H.getEnumType(_p)},{no:21,name:"packet_trailer_features",kind:"enum",T:H.getEnumType(Js),repeated:!0}]),Ho=H.makeMessageType("livekit.DataTrackInfo",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:H.getEnumType(Ve)},{no:5,name:"frame_encoding",kind:"message",T:Sp,opt:!0},{no:6,name:"schema",kind:"message",T:ru,opt:!0}]),Sp=H.makeMessageType("livekit.DataTrackFrameEncoding",()=>[{no:1,name:"well_known",kind:"enum",T:H.getEnumType(NS),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}]),NS=H.makeEnum("livekit.DataTrackFrameEncoding.WellKnownFrameEncoding",[{no:0,name:"WELL_KNOWN_FRAME_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_FRAME_ENCODING_ROS1",localName:"ROS1"},{no:2,name:"WELL_KNOWN_FRAME_ENCODING_CDR",localName:"CDR"},{no:3,name:"WELL_KNOWN_FRAME_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:4,name:"WELL_KNOWN_FRAME_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:5,name:"WELL_KNOWN_FRAME_ENCODING_CBOR",localName:"CBOR"},{no:6,name:"WELL_KNOWN_FRAME_ENCODING_MSGPACK",localName:"MSGPACK"},{no:7,name:"WELL_KNOWN_FRAME_ENCODING_JSON",localName:"JSON"}]),FS=H.makeMessageType("livekit.DataTrackSchemaEncoding",()=>[{no:1,name:"well_known",kind:"enum",T:H.getEnumType(US),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}]),US=H.makeEnum("livekit.DataTrackSchemaEncoding.WellKnownSchemaEncoding",[{no:0,name:"WELL_KNOWN_SCHEMA_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_SCHEMA_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:2,name:"WELL_KNOWN_SCHEMA_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:3,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS1_MSG",localName:"ROS1_MSG"},{no:4,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_MSG",localName:"ROS2_MSG"},{no:5,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_IDL",localName:"ROS2_IDL"},{no:6,name:"WELL_KNOWN_SCHEMA_ENCODING_OMG_IDL",localName:"OMG_IDL"},{no:7,name:"WELL_KNOWN_SCHEMA_ENCODING_JSON_SCHEMA",localName:"JSON_SCHEMA"}]),ru=H.makeMessageType("livekit.DataTrackSchemaId",()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"encoding",kind:"message",T:FS}]),BS=H.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),au=H.makeMessageType("livekit.DataBlobKey",()=>[{no:1,name:"generic",kind:"scalar",T:9,oneof:"key"},{no:2,name:"schema_id",kind:"message",T:ru,oneof:"key"}]),Cp=H.makeMessageType("livekit.DataBlob",()=>[{no:1,name:"key",kind:"message",T:au},{no:2,name:"contents",kind:"scalar",T:12}]),Gn=H.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:H.getEnumType(su)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}]),kp=H.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),Kt=H.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:H.getEnumType(Kn)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:ou,oneof:"value"},{no:3,name:"speaker",kind:"message",T:qS,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Ap,oneof:"value"},{no:7,name:"transcription",kind:"message",T:VS,oneof:"value"},{no:8,name:"metrics",kind:"message",T:AS,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:$o,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:cu,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Wo,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:lu,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:zo,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:En,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:du,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Ep,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Kn=H.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Ep=H.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:H.getEnumType(Ve)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),xp=H.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:ou,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:$o,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:cu,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Wo,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:lu,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:zo,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:En,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:du,oneof:"value"}]),qS=H.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:wp,repeated:!0}]),wp=H.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),ou=H.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),Ap=H.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),VS=H.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:jS,repeated:!0}]),jS=H.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),$o=H.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),cu=H.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13},{no:6,name:"compressed_payload",kind:"scalar",T:12}]),Wo=H.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),lu=H.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:Dp,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}]),Dp=H.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),Pp=H.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Ip=H.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:H.getEnumType(Rp)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),Rp=H.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Op=H.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:H.getEnumType(Mp)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9},{no:12,name:"client_protocol",kind:"scalar",T:5},{no:13,name:"capabilities",kind:"enum",T:H.getEnumType(ua),repeated:!0}]),Mp=H.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),ua=H.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"},{no:2,name:"CAP_COMPRESSION_DEFLATE_RAW"}]),Lp=H.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Np},{no:2,name:"screen",kind:"message",T:Np},{no:3,name:"resume_connection",kind:"enum",T:H.getEnumType(la)},{no:4,name:"disabled_codecs",kind:"message",T:HS},{no:5,name:"force_relay",kind:"enum",T:H.getEnumType(la)}]),Np=H.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:H.getEnumType(la)}]),HS=H.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:jo,repeated:!0},{no:2,name:"publish",kind:"message",T:jo,repeated:!0}]),Fp=H.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),uu=H.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),qt=H.makeEnum("livekit.DataStream.CompressionType",[{no:0,name:"NONE"},{no:1,name:"DEFLATE_RAW"}]),Up=H.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:H.getEnumType(uu)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),Bp=H.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),zo=H.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:H.getEnumType(Ve)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Up,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Bp,oneof:"content_header"},{no:11,name:"inline_content",kind:"scalar",T:12,opt:!0},{no:12,name:"compression",kind:"enum",T:H.getEnumType(qt)}],{localName:"DataStream_Header"}),En=H.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),du=H.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),$S=H.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),Ni=H.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),hu=H.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),WS=H.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),zS=H.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Xn,oneof:"message"},{no:2,name:"answer",kind:"message",T:Xn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Go,oneof:"message"},{no:4,name:"add_track",kind:"message",T:da,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ko,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Xo,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Hp,oneof:"message"},{no:8,name:"leave",kind:"message",T:Yo,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Wp,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Kp,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:_u,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Zi,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:bu,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Qp,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:vu,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:$p,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:pu,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:gu,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Vp,oneof:"message"},{no:22,name:"store_data_blob_request",kind:"message",T:eC,oneof:"message"},{no:23,name:"get_data_blob_request",kind:"message",T:iC,oneof:"message"}]),qp=H.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:YS,oneof:"message"},{no:2,name:"answer",kind:"message",T:Xn,oneof:"message"},{no:3,name:"offer",kind:"message",T:Xn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Go,oneof:"message"},{no:5,name:"update",kind:"message",T:ZS,oneof:"message"},{no:6,name:"track_published",kind:"message",T:yu,oneof:"message"},{no:8,name:"leave",kind:"message",T:Yo,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ko,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:sC,oneof:"message"},{no:11,name:"room_update",kind:"message",T:rC,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:oC,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:lC,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:dC,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:fC,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:JS,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:QS,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:mC,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:vC,oneof:"message"},{no:22,name:"request_response",kind:"message",T:bC,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:TC,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:pC,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:CC,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:hC,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:mu,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:GS,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:KS,oneof:"message"},{no:30,name:"store_data_blob_response",kind:"message",T:tC,oneof:"message"},{no:31,name:"get_data_blob_response",kind:"message",T:nC,oneof:"message"}]),fu=H.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Gn,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:H.getEnumType(kp)}]),da=H.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:H.getEnumType(Li)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:H.getEnumType(_t)},{no:9,name:"layers",kind:"message",T:Gn,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:fu,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:H.getEnumType(Ve)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:H.getEnumType(_p)},{no:17,name:"audio_features",kind:"enum",T:H.getEnumType(Pt),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:H.getEnumType(Js),repeated:!0}]),pu=H.makeMessageType("livekit.PublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:H.getEnumType(Ve)},{no:4,name:"frame_encoding",kind:"message",T:Sp,opt:!0},{no:5,name:"schema",kind:"message",T:ru,opt:!0}]),mu=H.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:Ho}]),gu=H.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),GS=H.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:Ho}]),KS=H.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:XS}}]),XS=H.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}],{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),Go=H.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:H.getEnumType(Ni)},{no:3,name:"final",kind:"scalar",T:8}]),Ko=H.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),YS=H.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Vo},{no:2,name:"participant",kind:"message",T:bs},{no:3,name:"other_participants",kind:"message",T:bs,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:zp,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:Lp},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:Ip},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:jo,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),QS=H.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:zp,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Lp},{no:3,name:"server_info",kind:"message",T:Ip},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),yu=H.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:tr}]),JS=H.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Xn=H.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),ZS=H.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:bs,repeated:!0}]),Xo=H.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:Pp,repeated:!0}]),Vp=H.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:jp,repeated:!0}]),jp=H.makeMessageType("livekit.UpdateDataSubscription.Update",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:BS}],{localName:"UpdateDataSubscription_Update"}),eC=H.makeMessageType("livekit.StoreDataBlobRequest",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:Cp}]),tC=H.makeMessageType("livekit.StoreDataBlobResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"key",kind:"message",T:au}]),iC=H.makeMessageType("livekit.GetDataBlobRequest",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:9},{no:3,name:"key",kind:"message",T:au}]),nC=H.makeMessageType("livekit.GetDataBlobResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:Cp}]),Hp=H.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:H.getEnumType(su)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),vu=H.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:H.getEnumType(Pt),repeated:!0}]),$p=H.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),Yo=H.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:H.getEnumType(Gt)},{no:3,name:"action",kind:"enum",T:H.getEnumType(ir)},{no:4,name:"regions",kind:"message",T:gC}]),ir=H.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Wp=H.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Gn,repeated:!0}]),bu=H.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),zp=H.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),sC=H.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:wp,repeated:!0}]),rC=H.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Vo}]),aC=H.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:H.getEnumType(ca)},{no:3,name:"score",kind:"scalar",T:2}]),oC=H.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:aC,repeated:!0}]),cC=H.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:H.getEnumType(hu)}]),lC=H.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:cC,repeated:!0}]),Tu=H.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:H.getEnumType(su)},{no:2,name:"enabled",kind:"scalar",T:8}]),uC=H.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Tu,repeated:!0}]),dC=H.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Tu,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:uC,repeated:!0}]),hC=H.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:$S,repeated:!0}]),Gp=H.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),Kp=H.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Gp,repeated:!0}]),fC=H.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),pC=H.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Vo},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:bs},{no:4,name:"other_participants",kind:"message",T:bs,repeated:!0}]),_u=H.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Xn},{no:2,name:"subscription",kind:"message",T:Xo},{no:3,name:"publish_tracks",kind:"message",T:yu,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Yp,repeated:!0},{no:5,name:"offer",kind:"message",T:Xn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Xp,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:mu,repeated:!0}]),Xp=H.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Yp=H.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:H.getEnumType(Ni)}]),Zi=H.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:H.getEnumType(WS),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),Qp=H.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),mC=H.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),gC=H.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:yC,repeated:!0}]),yC=H.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),vC=H.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:H.getEnumType(RS)}]),bC=H.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:H.getEnumType(Ts)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Go,oneof:"request"},{no:5,name:"add_track",kind:"message",T:da,oneof:"request"},{no:6,name:"mute",kind:"message",T:Ko,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:bu,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:vu,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:$p,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:pu,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:gu,oneof:"request"}]),Ts=H.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"},{no:11,name:"INVALID_REQUEST"}]),TC=H.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Jp=H.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}]),_C=H.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Op},{no:2,name:"connection_settings",kind:"message",T:Jp},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:da,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Xn},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:H.getEnumType(vs)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:_u}]),SC=H.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:H.getEnumType(Su)},{no:2,name:"join_request",kind:"scalar",T:12}]),Su=H.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),CC=H.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function kC(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Qo={exports:{}},EC=Qo.exports,Zp;function xC(){return Zp||(Zp=1,(function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(EC,function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},a=null;function o(b,S){var D=b[S];if(typeof D.bind=="function")return D.bind(b);try{return Function.prototype.bind.call(D,b)}catch{return function(){return Function.prototype.apply.apply(D,[b,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(b){return b==="debug"&&(b="log"),typeof console===t?!1:b==="trace"&&i?c:console[b]!==void 0?o(console,b):console.log!==void 0?o(console,"log"):e}function u(){for(var b=this.getLevel(),S=0;S<s.length;S++){var D=s[S];this[D]=S<b?e:this.methodFactory(D,b,this.name)}if(this.log=this.debug,typeof console===t&&b<this.levels.SILENT)return"No console available for logging"}function h(b){return function(){typeof console!==t&&(u.call(this),this[b].apply(this,arguments))}}function p(b,S,D){return l(b)||h.apply(this,arguments)}function y(b,S){var D=this,I,F,w,P="loglevel";typeof b=="string"?P+=":"+b:typeof b=="symbol"&&(P=void 0);function L(j){var G=(s[j]||"silent").toUpperCase();if(!(typeof window===t||!P)){try{window.localStorage[P]=G;return}catch{}try{window.document.cookie=encodeURIComponent(P)+"="+G+";"}catch{}}}function C(){var j;if(!(typeof window===t||!P)){try{j=window.localStorage[P]}catch{}if(typeof j===t)try{var G=window.document.cookie,X=encodeURIComponent(P),z=G.indexOf(X+"=");z!==-1&&(j=/^([^;]+)/.exec(G.slice(z+X.length+1))[1])}catch{}return D.levels[j]===void 0&&(j=void 0),j}}function N(){if(!(typeof window===t||!P)){try{window.localStorage.removeItem(P)}catch{}try{window.document.cookie=encodeURIComponent(P)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function x(j){var G=j;if(typeof G=="string"&&D.levels[G.toUpperCase()]!==void 0&&(G=D.levels[G.toUpperCase()]),typeof G=="number"&&G>=0&&G<=D.levels.SILENT)return G;throw new TypeError("log.setLevel() called with invalid level: "+j)}D.name=b,D.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},D.methodFactory=S||p,D.getLevel=function(){return w??F??I},D.setLevel=function(j,G){return w=x(j),G!==!1&&L(w),u.call(D)},D.setDefaultLevel=function(j){F=x(j),C()||D.setLevel(j,!1)},D.resetLevel=function(){w=null,N(),u.call(D)},D.enableAll=function(j){D.setLevel(D.levels.TRACE,j)},D.disableAll=function(j){D.setLevel(D.levels.SILENT,j)},D.rebuild=function(){if(a!==D&&(I=x(a.getLevel())),u.call(D),a===D)for(var j in r)r[j].rebuild()},I=x(a?a.getLevel():"WARN");var k=C();k!=null&&(w=x(k)),u.call(D)}a=new y,a.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var D=r[S];return D||(D=r[S]=new y(S,a.methodFactory)),D};var _=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=_),a},a.getLoggers=function(){return r},a.default=a,a})})(Qo)),Qo.exports}var Jo=xC(),Cu;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})(Cu||(Cu={}));var yt;(function(n){n.Default="livekit",n.Room="livekit-room",n.TokenSource="livekit-token-source",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee",n.DataTracks="livekit-data-tracks",n.Region="livekit-region",n.ICE="livekit-ice"})(yt||(yt={}));let xe=Jo.getLogger(yt.Default);Object.values(yt).map(n=>Jo.getLogger(n)),xe.setDefaultLevel(Cu.info);function Nt(n,e){const t=Jo.getLogger(n);return t.setDefaultLevel(xe.getLevel()),e?wC(t,e):t}function wC(n,e){const t=s=>(r,a)=>{const o=e(),c=o||a?Object.assign(Object.assign({},o),a):void 0;n[s](r,c)},i=Object.create(n);return i.trace=t("trace"),i.debug=t("debug"),i.info=t("info"),i.warn=t("warn"),i.error=t("error"),i}const AC=Jo.getLogger(yt.E2EE),ha=7e3,DC=[0,300,4*300,9*300,16*300,ha,ha,ha,ha,ha];class PC{constructor(e){this._retryDelays=e!==void 0?[...e]:DC}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function IC(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(n);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(n,i[s])&&(t[i[s]]=n[i[s]]);return t}function O(n,e,t,i){function s(r){return r instanceof t?r:new t(function(a){a(r)})}return new(t||(t=Promise))(function(r,a){function o(u){try{l(i.next(u))}catch(h){a(h)}}function c(u){try{l(i.throw(u))}catch(h){a(h)}}function l(u){u.done?r(u.value):s(u.value).then(o,c)}l((i=i.apply(n,e||[])).next())})}function em(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function xn(n){return this instanceof xn?(this.v=n,this):new xn(n)}function tm(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),s,r=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",a),s[Symbol.asyncIterator]=function(){return this},s;function a(y){return function(_){return Promise.resolve(_).then(y,h)}}function o(y,_){i[y]&&(s[y]=function(b){return new Promise(function(S,D){r.push([y,b,S,D])>1||c(y,b)})},_&&(s[y]=_(s[y])))}function c(y,_){try{l(i[y](_))}catch(b){p(r[0][3],b)}}function l(y){y.value instanceof xn?Promise.resolve(y.value.v).then(u,h):p(r[0][2],y)}function u(y){c("next",y)}function h(y){c("throw",y)}function p(y,_){y(_),r.shift(),r.length&&c(r[0][0],r[0][1])}}function RC(n){var e,t;return e={},i("next"),i("throw",function(s){throw s}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(s,r){e[s]=n[s]?function(a){return(t=!t)?{value:xn(n[s](a)),done:!1}:r?r(a):a}:r}}function ki(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof em=="function"?em(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=n[r]&&function(a){return new Promise(function(o,c){a=n[r](a),s(o,c,a.done,a.value)})}}function s(r,a,o,c){Promise.resolve(c).then(function(l){r({value:l,done:o})},a)}}typeof SuppressedError=="function"&&SuppressedError;var Zo={exports:{}},im;function OC(){if(im)return Zo.exports;im=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(P,L,C){return Function.prototype.apply.call(P,L,C)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(P){return Object.getOwnPropertyNames(P).concat(Object.getOwnPropertySymbols(P))}:t=function(P){return Object.getOwnPropertyNames(P)};function i(w){console&&console.warn&&console.warn(w)}var s=Number.isNaN||function(P){return P!==P};function r(){r.init.call(this)}Zo.exports=r,Zo.exports.once=D,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function o(w){if(typeof w!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof w)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(w){if(typeof w!="number"||w<0||s(w))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+w+".");a=w}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(P){if(typeof P!="number"||P<0||s(P))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+P+".");return this._maxListeners=P,this};function c(w){return w._maxListeners===void 0?r.defaultMaxListeners:w._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(P){for(var L=[],C=1;C<arguments.length;C++)L.push(arguments[C]);var N=P==="error",x=this._events;if(x!==void 0)N=N&&x.error===void 0;else if(!N)return!1;if(N){var k;if(L.length>0&&(k=L[0]),k instanceof Error)throw k;var j=new Error("Unhandled error."+(k?" ("+k.message+")":""));throw j.context=k,j}var G=x[P];if(G===void 0)return!1;if(typeof G=="function")e(G,this,L);else for(var X=G.length,z=_(G,X),C=0;C<X;++C)e(z[C],this,L);return!0};function l(w,P,L,C){var N,x,k;if(o(L),x=w._events,x===void 0?(x=w._events=Object.create(null),w._eventsCount=0):(x.newListener!==void 0&&(w.emit("newListener",P,L.listener?L.listener:L),x=w._events),k=x[P]),k===void 0)k=x[P]=L,++w._eventsCount;else if(typeof k=="function"?k=x[P]=C?[L,k]:[k,L]:C?k.unshift(L):k.push(L),N=c(w),N>0&&k.length>N&&!k.warned){k.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+k.length+" "+String(P)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=w,j.type=P,j.count=k.length,i(j)}return w}r.prototype.addListener=function(P,L){return l(this,P,L,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(P,L){return l(this,P,L,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function h(w,P,L){var C={fired:!1,wrapFn:void 0,target:w,type:P,listener:L},N=u.bind(C);return N.listener=L,C.wrapFn=N,N}r.prototype.once=function(P,L){return o(L),this.on(P,h(this,P,L)),this},r.prototype.prependOnceListener=function(P,L){return o(L),this.prependListener(P,h(this,P,L)),this},r.prototype.removeListener=function(P,L){var C,N,x,k,j;if(o(L),N=this._events,N===void 0)return this;if(C=N[P],C===void 0)return this;if(C===L||C.listener===L)--this._eventsCount===0?this._events=Object.create(null):(delete N[P],N.removeListener&&this.emit("removeListener",P,C.listener||L));else if(typeof C!="function"){for(x=-1,k=C.length-1;k>=0;k--)if(C[k]===L||C[k].listener===L){j=C[k].listener,x=k;break}if(x<0)return this;x===0?C.shift():b(C,x),C.length===1&&(N[P]=C[0]),N.removeListener!==void 0&&this.emit("removeListener",P,j||L)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(P){var L,C,N;if(C=this._events,C===void 0)return this;if(C.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):C[P]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete C[P]),this;if(arguments.length===0){var x=Object.keys(C),k;for(N=0;N<x.length;++N)k=x[N],k!=="removeListener"&&this.removeAllListeners(k);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(L=C[P],typeof L=="function")this.removeListener(P,L);else if(L!==void 0)for(N=L.length-1;N>=0;N--)this.removeListener(P,L[N]);return this};function p(w,P,L){var C=w._events;if(C===void 0)return[];var N=C[P];return N===void 0?[]:typeof N=="function"?L?[N.listener||N]:[N]:L?S(N):_(N,N.length)}r.prototype.listeners=function(P){return p(this,P,!0)},r.prototype.rawListeners=function(P){return p(this,P,!1)},r.listenerCount=function(w,P){return typeof w.listenerCount=="function"?w.listenerCount(P):y.call(w,P)},r.prototype.listenerCount=y;function y(w){var P=this._events;if(P!==void 0){var L=P[w];if(typeof L=="function")return 1;if(L!==void 0)return L.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function _(w,P){for(var L=new Array(P),C=0;C<P;++C)L[C]=w[C];return L}function b(w,P){for(;P+1<w.length;P++)w[P]=w[P+1];w.pop()}function S(w){for(var P=new Array(w.length),L=0;L<P.length;++L)P[L]=w[L].listener||w[L];return P}function D(w,P){return new Promise(function(L,C){function N(k){w.removeListener(P,x),C(k)}function x(){typeof w.removeListener=="function"&&w.removeListener("error",N),L([].slice.call(arguments))}F(w,P,x,{once:!0}),P!=="error"&&I(w,N,{once:!0})})}function I(w,P,L){typeof w.on=="function"&&F(w,"error",P,L)}function F(w,P,L,C){if(typeof w.on=="function")C.once?w.once(P,L):w.on(P,L);else if(typeof w.addEventListener=="function")w.addEventListener(P,function N(x){C.once&&w.removeEventListener(P,N),L(x)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof w)}return Zo.exports}var ai=OC();let nm=!0,sm=!0;function fa(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseFloat(i[t],10)}function _s(n,e,t){if(!n.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable){ku("Unable to polyfill events");return}const s=n.RTCPeerConnection.prototype,r=s.addEventListener;s.addEventListener=function(o,c){if(o!==e)return r.apply(this,arguments);const l=u=>{const h=t(u);h&&(c.handleEvent?c.handleEvent(h):c(h))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(c,l),r.apply(this,[o,l])};const a=s.removeEventListener;s.removeEventListener=function(o,c){if(o!==e||!this._eventMap||!this._eventMap[e])return a.apply(this,arguments);if(!this._eventMap[e].has(c))return a.apply(this,arguments);const l=this._eventMap[e].get(c);return this._eventMap[e].delete(c),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[o,l])},Object.defineProperty(s,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function MC(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(nm=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function LC(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(sm=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function ku(){if(typeof window=="object"){if(nm)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Eu(n,e){sm&&console.warn(n+" is deprecated, please use "+e+" instead.")}function NC(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const t=n.navigator;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(i){const s=parseInt(i.version,10);if(s>=90)return{browser:"chrome",version:s}}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(fa(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(fa(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(fa(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype,e._safariVersion=fa(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function rm(n){return Object.prototype.toString.call(n)==="[object Object]"}function am(n){return rm(n)?Object.keys(n).reduce(function(e,t){const i=rm(n[t]),s=i?am(n[t]):n[t],r=i&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):n}function xu(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?xu(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{xu(n,n.get(s),t)})}))}function om(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return n.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&r.push(a)}),r.forEach(a=>{n.forEach(o=>{o.type===i&&o.trackId===a.id&&xu(n,o,s)})}),s}const cm=ku;function lm(n,e){if(e.version>=64)return;const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const u=typeof o[l]=="object"?o[l]:{ideal:o[l]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const h=function(p,y){return p?p+y.charAt(0).toUpperCase()+y.slice(1):y==="deviceId"?"sourceId":y};if(u.ideal!==void 0){c.optional=c.optional||[];let p={};typeof u.ideal=="number"?(p[h("min",l)]=u.ideal,c.optional.push(p),p={},p[h("max",l)]=u.ideal,c.optional.push(p)):(p[h("",l)]=u.ideal,c.optional.push(p))}u.exact!==void 0&&typeof u.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[h("",l)]=u.exact):["min","max"].forEach(p=>{u[p]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[h(p,l)]=u[p])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},s=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const l=function(u,h,p){h in u&&!(p in u)&&(u[p]=u[h],delete u[h])};o=JSON.parse(JSON.stringify(o)),l(o.audio,"autoGainControl","googAutoGainControl"),l(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let l=o.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const u=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete o.video.facingMode;let h;if(l.exact==="environment"||l.ideal==="environment"?h=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(p=>{p=p.filter(_=>_.kind==="videoinput");let y=p.find(_=>h.some(b=>_.label.toLowerCase().includes(b)));return!y&&p.length&&h.includes("back")&&(y=p[p.length-1]),y&&(o.video.deviceId=l.exact?{exact:y.deviceId}:{ideal:y.deviceId}),o.video=i(o.video),cm("chrome: "+JSON.stringify(o)),c(o)})}o.video=i(o.video)}return cm("chrome: "+JSON.stringify(o)),c(o)},r=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,c,l){s(o,u=>{t.webkitGetUserMedia(u,c,h=>{l&&l(r(h))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,l=>o(l).then(u=>{if(l.audio&&!u.getAudioTracks().length||l.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(r(u))))}}}function um(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function dm(n,e){if(!(e.version>102))if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(i){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=i)},enumerable:!0,configurable:!0});const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=s=>{s.stream.addEventListener("addtrack",r=>{let a;n.RTCPeerConnection.prototype.getReceivers?a=this.getReceivers().find(c=>c.track&&c.track.id===r.track.id):a={track:r.track};const o=new Event("track");o.track=r.track,o.receiver=a,o.transceiver={receiver:a},o.streams=[s.stream],this.dispatchEvent(o)}),s.stream.getTracks().forEach(r=>{let a;n.RTCPeerConnection.prototype.getReceivers?a=this.getReceivers().find(c=>c.track&&c.track.id===r.id):a={track:r};const o=new Event("track");o.track=r,o.receiver=a,o.transceiver={receiver:a},o.streams=[s.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else _s(n,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function hm(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(o,c){let l=s.apply(this,arguments);return l||(l=e(this,o),this._senders.push(l)),l};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){r.apply(this,arguments);const c=this._senders.indexOf(o);c!==-1&&this._senders.splice(c,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],i.apply(this,[r]),r.getTracks().forEach(a=>{const o=this._senders.find(c=>c.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i},Object.defineProperty(n.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function fm(n,e){if(e.version>=67||!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const i=n.RTCPeerConnection.prototype.getSenders;i&&(n.RTCPeerConnection.prototype.getSenders=function(){const a=i.apply(this,[]);return a.forEach(o=>o._pc=this),a});const s=n.RTCPeerConnection.prototype.addTrack;s&&(n.RTCPeerConnection.prototype.addTrack=function(){const a=s.apply(this,arguments);return a._pc=this,a}),n.RTCRtpSender.prototype.getStats=function(){const a=this;return this._pc.getStats().then(o=>om(o,a.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const i=n.RTCPeerConnection.prototype.getReceivers;i&&(n.RTCPeerConnection.prototype.getReceivers=function(){const r=i.apply(this,[]);return r.forEach(a=>a._pc=this),r}),_s(n,"track",s=>(s.receiver._pc=s.srcElement,s)),n.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(a=>om(a,r.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const t=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const s=arguments[0];let r,a,o;return this.getSenders().forEach(c=>{c.track===s&&(r?o=!0:r=c)}),this.getReceivers().forEach(c=>(c.track===s&&(a?o=!0:a=c),c.track===s)),o||r&&a?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():a?a.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function pm(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(l=>{if(this.getSenders().find(h=>h.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(l=>o.indexOf(l)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const s=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function mm(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return pm(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(h=>this._reverseStreams[h.id])};const i=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(h=>{if(this.getSenders().find(y=>y.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const h=new n.MediaStream(u.getTracks());this._streams[u.id]=h,this._reverseStreams[h.id]=u,u=h}i.apply(this,[u])};const s=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},n.RTCPeerConnection.prototype.addTrack=function(u,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const p=[].slice.call(arguments,1);if(p.length!==1||!p[0].getTracks().find(b=>b===u))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(b=>b.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const _=this._streams[h.id];if(_)_.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const b=new n.MediaStream([u]);this._streams[h.id]=b,this._reverseStreams[b.id]=h,this.addStream(b)}return this.getSenders().find(b=>b.track===u)};function r(l,u){let h=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(p=>{const y=l._reverseStreams[p],_=l._streams[y.id];h=h.replace(new RegExp(_.id,"g"),y.id)}),new RTCSessionDescription({type:u.type,sdp:h})}function a(l,u){let h=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(p=>{const y=l._reverseStreams[p],_=l._streams[y.id];h=h.replace(new RegExp(y.id,"g"),_.id)}),new RTCSessionDescription({type:u.type,sdp:h})}["createOffer","createAnswer"].forEach(function(l){const u=n.RTCPeerConnection.prototype[l],h={[l](){const p=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[_=>{const b=r(this,_);p[0].apply(null,[b])},_=>{p[1]&&p[1].apply(null,_)},arguments[2]]):u.apply(this,arguments).then(_=>r(this,_))}};n.RTCPeerConnection.prototype[l]=h[l]});const o=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:r(this,l)}}),n.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let p;Object.keys(this._streams).forEach(y=>{this._streams[y].getTracks().find(b=>u.track===b)&&(p=this._streams[y])}),p&&(p.getTracks().length===1?this.removeStream(this._reverseStreams[p.id]):p.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function wu(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=s[t]})}function gm(n,e){e.version>102||_s(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var ym=Object.freeze({__proto__:null,fixNegotiationNeeded:gm,shimAddTrackRemoveTrack:mm,shimAddTrackRemoveTrackWithNative:pm,shimGetSendersWithDtmf:hm,shimGetUserMedia:lm,shimMediaStream:um,shimOnTrack:dm,shimPeerConnection:wu,shimSenderReceiverGetStats:fm});function vm(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){Eu("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(a,o,c){o in a&&!(c in a)&&(a[c]=a[o],delete a[o])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),r(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function FC(n,e){n.navigator.mediaDevices&&(n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||(n.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(i)}))}function bm(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Au(n,e){typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection)||(!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=s[t]}))}function Tm(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection)||e.version>=151)return;const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const r=Array.prototype.slice.call(arguments),a=r[0],o=r[1],c=r[2];return this.signalingState==="closed"?Promise.resolve(new Map):i.apply(this,[a||null]).then(l=>{if(e.version<53&&!o)try{l.forEach(u=>{u.type=t[u.type]||u.type})}catch(u){if(u.name!=="TypeError")throw u;l.forEach((h,p)=>{l.set(p,Object.assign({},h,{type:t[h.type]||h.type}))})}return l}).then(o,c)}}function _m(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Sm(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i}),_s(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Cm(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){Eu("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function km(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function Em(n,e){if(!(typeof n=="object"&&n.RTCPeerConnection)||e.version>=110)return;const t=n.RTCPeerConnection.prototype.addTransceiver;t&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let s=arguments[1]&&arguments[1].sendEncodings;s===void 0&&(s=[]),s=[...s];const r=s.length>0;r&&s.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const a=t.apply(this,arguments);if(r){const o=a.sender,c=o.getParameters();(!("encodings"in c)||c.encodings.length===1&&Object.keys(c.encodings[0]).length===0)&&(c.encodings=s,o.sendEncodings=s,this.setParametersPromises.push(o.setParameters(c).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return a})}function xm(n,e){if(!(typeof n=="object"&&n.RTCRtpSender)||e.version>=110)return;const t=n.RTCRtpSender.prototype.getParameters;t&&(n.RTCRtpSender.prototype.getParameters=function(){const s=t.apply(this,arguments);return"encodings"in s||(s.encodings=[].concat(this.sendEncodings||[{}])),s})}function wm(n,e){if(!(typeof n=="object"&&n.RTCPeerConnection)||e.version>=110)return;const t=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Am(n,e){if(!(typeof n=="object"&&n.RTCPeerConnection)||e.version>=110)return;const t=n.RTCPeerConnection.prototype.createAnswer;n.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var Dm=Object.freeze({__proto__:null,shimAddTransceiver:Em,shimCreateAnswer:Am,shimCreateOffer:wm,shimGetDisplayMedia:FC,shimGetParameters:xm,shimGetStats:Tm,shimGetUserMedia:vm,shimOnTrack:bm,shimPeerConnection:Au,shimRTCDataChannel:km,shimReceiverGetStats:Sm,shimRemoveStream:Cm,shimSenderGetStats:_m});function Pm(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(s=>e.call(this,s,i)),i.getVideoTracks().forEach(s=>e.call(this,s,i))},n.RTCPeerConnection.prototype.addTrack=function(i){for(var s=arguments.length,r=new Array(s>1?s-1:0),a=1;a<s;a++)r[a-1]=arguments[a];return r&&r.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function Im(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(r)>=0)return;i._remoteStreams.push(r);const a=new Event("addstream");a.stream=r,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function Rm(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(l,u){const h=arguments.length>=2?arguments[2]:arguments[0],p=t.apply(this,[h]);return u?(p.then(l,u),Promise.resolve()):p},e.createAnswer=function(l,u){const h=arguments.length>=2?arguments[2]:arguments[0],p=i.apply(this,[h]);return u?(p.then(l,u),Promise.resolve()):p};let o=function(c,l,u){const h=s.apply(this,[c]);return u?(h.then(l,u),Promise.resolve()):h};e.setLocalDescription=o,o=function(c,l,u){const h=r.apply(this,[c]);return u?(h.then(l,u),Promise.resolve()):h},e.setRemoteDescription=o,o=function(c,l,u){const h=a.apply(this,[c]);return u?(h.then(l,u),Promise.resolve()):h},e.addIceCandidate=o}function Om(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>i(Mm(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,s,r){e.mediaDevices.getUserMedia(i).then(s,r)}).bind(e))}function Mm(n){return n&&n.video!==void 0?Object.assign({},n,{video:am(n.video)}):n}function Lm(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const r=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(Eu("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,r.push(o)):r.push(i.iceServers[a])}i.iceServers=r}return new e(i,s)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Nm(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Fm(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const r=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Um(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var Bm=Object.freeze({__proto__:null,shimAudioContext:Um,shimCallbacksAPI:Rm,shimConstraints:Mm,shimCreateOfferLegacy:Fm,shimGetUserMedia:Om,shimLocalStreamsAPI:Pm,shimRTCIceServerUrls:Lm,shimRemoteStreamsAPI:Im,shimTrackEventTransceiver:Nm}),Du={exports:{}},qm;function UC(){return qm||(qm=1,(function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
|
|
4
|
+
`).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
|
|
5
|
+
m=`).map((s,r)=>(r>0?"m="+s:s).trim()+`\r
|
|
6
|
+
`)},e.getDescription=function(t){const i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){const i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(s=>s.indexOf(i)===0)},e.parseCandidate=function(t){let i;t.indexOf("a=candidate:")===0?i=t.substring(12).split(" "):i=t.substring(10).split(" ");const s={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let r=8;r<i.length;r+=2)switch(i[r]){case"raddr":s.relatedAddress=i[r+1];break;case"rport":s.relatedPort=parseInt(i[r+1],10);break;case"tcptype":s.tcpType=i[r+1];break;case"ufrag":s.ufrag=i[r+1],s.usernameFragment=i[r+1];break;default:s[i[r]]===void 0&&(s[i[r]]=i[r+1]);break}return s},e.writeCandidate=function(t){const i=[];i.push(t.foundation);const s=t.component;s==="rtp"?i.push(1):s==="rtcp"?i.push(2):i.push(s),i.push(t.protocol.toUpperCase()),i.push(t.priority),i.push(t.address||t.ip),i.push(t.port);const r=t.type;return i.push("typ"),i.push(r),r!=="host"&&t.relatedAddress&&t.relatedPort!==void 0&&(i.push("raddr"),i.push(t.relatedAddress),i.push("rport"),i.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(i.push("ufrag"),i.push(t.usernameFragment||t.ufrag)),"candidate:"+i.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let i=t.substring(9).split(" ");const s={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),s.name=i[0],s.clockRate=parseInt(i[1],10),s.channels=i.length===3?parseInt(i[2],10):1,s.numChannels=s.channels,s},e.writeRtpMap=function(t){let i=t.payloadType;t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType);const s=t.channels||t.numChannels||1;return"a=rtpmap:"+i+" "+t.name+"/"+t.clockRate+(s!==1?"/"+s:"")+`\r
|
|
7
|
+
`},e.parseExtmap=function(t){const i=t.substring(9).split(" ");return{id:parseInt(i[0],10),direction:i[0].indexOf("/")>0?i[0].split("/")[1]:"sendrecv",uri:i[1],attributes:i.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
|
|
8
|
+
`},e.parseFmtp=function(t){const i={};let s;const r=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a<r.length;a++)s=r[a].trim().split("="),i[s[0].trim()]=s[1];return i},e.writeFmtp=function(t){let i="",s=t.payloadType;if(t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const r=[];Object.keys(t.parameters).forEach(a=>{t.parameters[a]!==void 0?r.push(a+"="+t.parameters[a]):r.push(a)}),i+="a=fmtp:"+s+" "+r.join(";")+`\r
|
|
9
|
+
`}return i},e.parseRtcpFb=function(t){const i=t.substring(t.indexOf(" ")+1).split(" ");return{type:i.shift(),parameter:i.join(" ")}},e.writeRtcpFb=function(t){let i="",s=t.payloadType;return t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(r=>{i+="a=rtcp-fb:"+s+" "+r.type+(r.parameter&&r.parameter.length?" "+r.parameter:"")+`\r
|
|
10
|
+
`}),i},e.parseSsrcMedia=function(t){const i=t.indexOf(" "),s={ssrc:parseInt(t.substring(7,i),10)},r=t.indexOf(":",i);return r>-1?(s.attribute=t.substring(i+1,r),s.value=t.substring(r+1)):s.attribute=t.substring(i+1),s},e.parseSsrcGroup=function(t){const i=t.substring(13).split(" ");return{semantics:i.shift(),ssrcs:i.map(s=>parseInt(s,10))}},e.getMid=function(t){const i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(t){const i=t.substring(14).split(" ");return{algorithm:i[0].toLowerCase(),value:i[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,i){let s="a=setup:"+i+`\r
|
|
11
|
+
`;return t.fingerprints.forEach(r=>{s+="a=fingerprint:"+r.algorithm+" "+r.value+`\r
|
|
12
|
+
`}),s},e.parseCryptoLine=function(t){const i=t.substring(9).split(" ");return{tag:parseInt(i[0],10),cryptoSuite:i[1],keyParams:i[2],sessionParams:i.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
|
|
13
|
+
`},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const i=t.substring(7).split("|");return{keyMethod:"inline",keySalt:i[0],lifeTime:i[1],mkiValue:i[2]?i[2].split(":")[0]:void 0,mkiLength:i[2]?i[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){const s=e.matchPrefix(t+i,"a=ice-ufrag:")[0],r=e.matchPrefix(t+i,"a=ice-pwd:")[0];return s&&r?{usernameFragment:s.substring(12),password:r.substring(10)}:null},e.writeIceParameters=function(t){let i="a=ice-ufrag:"+t.usernameFragment+`\r
|
|
14
|
+
a=ice-pwd:`+t.password+`\r
|
|
15
|
+
`;return t.iceLite&&(i+=`a=ice-lite\r
|
|
16
|
+
`),i},e.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=e.splitLines(t)[0].split(" ");i.profile=r[2];for(let o=3;o<r.length;o++){const c=r[o],l=e.matchPrefix(t,"a=rtpmap:"+c+" ")[0];if(l){const u=e.parseRtpMap(l),h=e.matchPrefix(t,"a=fmtp:"+c+" ");switch(u.parameters=h.length?e.parseFmtp(h[0]):{},u.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+c+" ").map(e.parseRtcpFb),i.codecs.push(u),u.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(u.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(o=>{i.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(o=>{a.forEach(c=>{o.rtcpFeedback.find(u=>u.type===c.type&&u.parameter===c.parameter)||o.rtcpFeedback.push(c)})}),i},e.writeRtpDescription=function(t,i){let s="";s+="m="+t+" ",s+=i.codecs.length>0?"9":"0",s+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",s+=i.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
|
|
17
|
+
`,s+=`c=IN IP4 0.0.0.0\r
|
|
18
|
+
`,s+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
19
|
+
`,i.codecs.forEach(a=>{s+=e.writeRtpMap(a),s+=e.writeFmtp(a),s+=e.writeRtcpFb(a)});let r=0;return i.codecs.forEach(a=>{a.maxptime>r&&(r=a.maxptime)}),r>0&&(s+="a=maxptime:"+r+`\r
|
|
20
|
+
`),i.headerExtensions&&i.headerExtensions.forEach(a=>{s+=e.writeExtmap(a)}),s},e.parseRtpEncodingParameters=function(t){const i=[],s=e.parseRtpParameters(t),r=s.fecMechanisms.indexOf("RED")!==-1,a=s.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(p=>e.parseSsrcMedia(p)).filter(p=>p.attribute==="cname"),c=o.length>0&&o[0].ssrc;let l;const u=e.matchPrefix(t,"a=ssrc-group:FID").map(p=>p.substring(17).split(" ").map(_=>parseInt(_,10)));u.length>0&&u[0].length>1&&u[0][0]===c&&(l=u[0][1]),s.codecs.forEach(p=>{if(p.name.toUpperCase()==="RTX"&&p.parameters.apt){let y={ssrc:c,codecPayloadType:parseInt(p.parameters.apt,10)};c&&l&&(y.rtx={ssrc:l}),i.push(y),r&&(y=JSON.parse(JSON.stringify(y)),y.fec={ssrc:c,mechanism:a?"red+ulpfec":"red"},i.push(y))}}),i.length===0&&c&&i.push({ssrc:c});let h=e.matchPrefix(t,"b=");return h.length&&(h[0].indexOf("b=TIAS:")===0?h=parseInt(h[0].substring(7),10):h[0].indexOf("b=AS:")===0?h=parseInt(h[0].substring(5),10)*1e3*.95-16e3:h=void 0,i.forEach(p=>{p.maxBitrate=h})),i},e.parseRtcpParameters=function(t){const i={},s=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];s&&(i.cname=s.value,i.ssrc=s.ssrc);const r=e.matchPrefix(t,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=r.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return i.mux=a.length>0,i},e.writeRtcpParameters=function(t){let i="";return t.reducedSize&&(i+=`a=rtcp-rsize\r
|
|
21
|
+
`),t.mux&&(i+=`a=rtcp-mux\r
|
|
22
|
+
`),t.ssrc!==void 0&&t.cname&&(i+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
|
|
23
|
+
`),i},e.parseMsid=function(t){let i;const s=e.matchPrefix(t,"a=msid:");if(s.length===1)return i=s[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(r.length>0)return i=r[0].value.split(" "),{stream:i[0],track:i[1]}},e.parseSctpDescription=function(t){const i=e.parseMLine(t),s=e.matchPrefix(t,"a=max-message-size:");let r;s.length>0&&(r=parseInt(s[0].substring(19),10)),isNaN(r)&&(r=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const c=o[0].substring(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:r}}},e.writeSctpDescription=function(t,i){let s=[];return t.protocol!=="DTLS/SCTP"?s=["m="+t.kind+" 9 "+t.protocol+" "+i.protocol+`\r
|
|
24
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
25
|
+
`,"a=sctp-port:"+i.port+`\r
|
|
26
|
+
`]:s=["m="+t.kind+" 9 "+t.protocol+" "+i.port+`\r
|
|
27
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
28
|
+
`,"a=sctpmap:"+i.port+" "+i.protocol+` 65535\r
|
|
29
|
+
`],i.maxMessageSize!==void 0&&s.push("a=max-message-size:"+i.maxMessageSize+`\r
|
|
30
|
+
`),s.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,i,s){let r;const a=i!==void 0?i:2;return t?r=t:r=e.generateSessionId(),`v=0\r
|
|
31
|
+
o=`+(s||"thisisadapterortc")+" "+r+" "+a+` IN IP4 127.0.0.1\r
|
|
32
|
+
s=-\r
|
|
33
|
+
t=0 0\r
|
|
34
|
+
`},e.getDirection=function(t,i){const s=e.splitLines(t);for(let r=0;r<s.length;r++)switch(s[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[r].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const i=e.splitLines(t);for(let s=0;s<i.length;s++)if(i[s].length<2||i[s].charAt(1)!=="=")return!1;return!0},n.exports=e})(Du)),Du.exports}var Vm=UC(),nr=kC(Vm),BC=P_({__proto__:null,default:nr},[Vm]);function ec(n){if(!n.RTCIceCandidate||n.RTCIceCandidate&&"foundation"in n.RTCIceCandidate.prototype)return;const e=n.RTCIceCandidate;n.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const s=new e(i),r=nr.parseCandidate(i.candidate);for(const a in r)a in s||Object.defineProperty(s,a,{value:r[a]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(i)},n.RTCIceCandidate.prototype=e.prototype,_s(n,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new n.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Pu(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||_s(n,"icecandidate",e=>{if(e.candidate){const t=nr.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function tc(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>102||e.browser==="firefox"&&e.version>=113)return;"sctp"in n.RTCPeerConnection.prototype||Object.defineProperty(n.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const c=nr.splitSections(o.sdp);return c.shift(),c.some(l=>{const u=nr.parseMLine(l);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},i=function(o){const c=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const l=parseInt(c[1],10);return l!==l?-1:l},s=function(o){let c=65536;return e.browser==="firefox"&&(e.version<57?o===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(o,c){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);const u=nr.matchPrefix(o.sdp,"a=max-message-size:");return u.length>0?l=parseInt(u[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(l=2147483637),l},a=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76&&this.getConfiguration().sdpSemantics==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0}),t(arguments[0])){const c=i(arguments[0]),l=s(c),u=r(arguments[0],c);let h;l===0&&u===0?h=Number.POSITIVE_INFINITY:l===0||u===0?h=Math.max(l,u):h=Math.min(l,u);const p={};Object.defineProperty(p,"maxMessageSize",{get(){return h}}),this._sctp=p}return a.apply(this,arguments)}}function ic(n,e){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype)||e.browser==="chrome"&&e.version>=149||e.browser==="firefox"&&e.version>60)return;function t(s,r){const a=s.send;s.send=function(){const c=arguments[0],l=c.length||c.size||c.byteLength;if(s.readyState==="open"&&r.sctp&&l>r.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+r.sctp.maxMessageSize+" bytes)");return a.apply(s,arguments)}}const i=n.RTCPeerConnection.prototype.createDataChannel;n.RTCPeerConnection.prototype.createDataChannel=function(){const r=i.apply(this,arguments);return t(r,this),r},_s(n,"datachannel",s=>(t(s.channel,s.target),s))}function Iu(n){if(!n.RTCPeerConnection||"connectionState"in n.RTCPeerConnection.prototype)return;const e=n.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const r=s.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const a=new Event("connectionstatechange",s);r.dispatchEvent(a)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function Ru(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
|
|
35
|
+
a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
|
|
36
|
+
`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
|
|
37
|
+
`);n.RTCSessionDescription&&s instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function nc(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function sc(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var qC=Object.freeze({__proto__:null,removeExtmapAllowMixed:Ru,shimAddIceCandidateNullOrEmpty:nc,shimConnectionState:Iu,shimMaxMessageSize:tc,shimParameterlessSetLocalDescription:sc,shimRTCIceCandidate:ec,shimRTCIceCandidateRelayProtocol:Pu,shimSendThrowTypeError:ic});function VC(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=n.window,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=ku,s=NC(e),r={browserDetails:s,commonShim:qC,extractVersion:fa,disableLog:MC,disableWarnings:LC,sdp:BC};switch(s.browser){case"chrome":if(!ym||!wu||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(s.version===null)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=ym,nc(e,s),sc(e),lm(e,s),um(e),wu(e,s),dm(e,s),mm(e,s),hm(e),fm(e,s),gm(e,s),ec(e),Pu(e),Iu(e),tc(e,s),ic(e,s),Ru(e,s);break;case"firefox":if(!Dm||!Au||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=Dm,nc(e,s),sc(e),vm(e,s),Au(e,s),Tm(e,s),bm(e),Cm(e),_m(e),Sm(e),km(e),Em(e,s),xm(e,s),wm(e,s),Am(e,s),ec(e),Iu(e),tc(e,s),ic(e,s);break;case"safari":if(!Bm||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=Bm,nc(e,s),sc(e),Lm(e),Fm(e),Rm(e),Pm(e),Im(e),Nm(e),Om(e),Um(e),ec(e),Pu(e),tc(e,s),ic(e,s),Ru(e,s);break;default:i("Unsupported browser!");break}return r}VC({window:typeof window>"u"?void 0:window});var Ou,jm;class Xt extends(jm=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}Ou=Xt,Xt.resolve=n=>Reflect.get(jm,"resolve",Ou).call(Ou,n);const jC=/version\/(\d+(\.?_?\d+)+)/i;let Mu;function Yt(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(Mu===void 0||e){const i=HC.find(s=>s.test.test(t));Mu=i==null?void 0:i.describe(t)}return Mu}const HC=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:rc(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Lu(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:rc(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Lu(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:rc(jC,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:Lu(n)}}}];function rc(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}function Lu(n){return n.includes("mac os")?rc(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var $C="2.21.0";const WC=$C,zC=17,Hm=0,Nu=1,$m=2,GC=$m;class wn extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,typeof(i==null?void 0:i.cause)<"u"&&(this.cause=i==null?void 0:i.cause)}}class Ei extends wn{}var He;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest",n[n.Timeout=5]="Timeout",n[n.WebSocket=6]="WebSocket",n[n.ServiceNotFound=7]="ServiceNotFound"})(He||(He={}));class Se extends Ei{constructor(e,t,i,s){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=s,this.reasonName=He[t]}static notAllowed(e,t,i){return new Se(e,He.NotAllowed,t,i)}static timeout(e){return new Se(e,He.Timeout)}static leaveRequest(e,t){return new Se(e,He.LeaveRequest,void 0,t)}static internal(e,t){return new Se(e,He.InternalError,void 0,t)}static cancelled(e){return new Se(e,He.Cancelled)}static serverUnreachable(e,t){return new Se(e,He.ServerUnreachable,t)}static websocket(e,t,i){return new Se(e,He.WebSocket,t,i)}static serviceNotFound(e,t){return new Se(e,He.ServiceNotFound,void 0,t)}}class Fu extends wn{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class An extends wn{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class KC extends wn{constructor(e){super(10,e||"unsupported server"),this.name="UnsupportedServer"}}class st extends wn{constructor(e){super(12,e||"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Ss extends wn{constructor(e){super(13,e||"unable to negotiate"),this.name="NegotiationError"}}class XC extends wn{constructor(e){super(14,e||"unable to publish data"),this.name="PublishDataError"}}class Wm extends wn{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class zm extends Ei{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:Ts[t]}}var dt;(function(n){n[n.AlreadyOpened=0]="AlreadyOpened",n[n.AbnormalEnd=1]="AbnormalEnd",n[n.DecodeFailed=2]="DecodeFailed",n[n.LengthExceeded=3]="LengthExceeded",n[n.Incomplete=4]="Incomplete",n[n.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",n[n.EncryptionTypeMismatch=8]="EncryptionTypeMismatch",n[n.HeaderTooLarge=9]="HeaderTooLarge",n[n.PayloadTooLarge=10]="PayloadTooLarge"})(dt||(dt={}));class Et extends Ei{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=dt[t]}}class sr extends wn{constructor(e){super(18,e),this.name="SignalReconnectError"}}var en;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(en||(en={})),(function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e})(en||(en={}));class ht{}ht.setTimeout=function(){return setTimeout(...arguments)},ht.setInterval=function(){return setInterval(...arguments)},ht.clearTimeout=function(){return clearTimeout(...arguments)},ht.clearInterval=function(){return clearInterval(...arguments)};var se;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived",n.DataTrackPublished="dataTrackPublished",n.DataTrackUnpublished="dataTrackUnpublished",n.LocalDataTrackPublished="localDataTrackPublished",n.LocalDataTrackUnpublished="localDataTrackUnpublished"})(se||(se={}));var fe;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackCpuConstrained="localTrackCpuConstrained",n.LocalSenderCreated="localSenderCreated",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.TrackCpuConstrained="trackCpuConstrained",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(fe||(fe={}));var le;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved",n.PublishDataTrackResponse="publishDataTrackResponse",n.UnPublishDataTrackResponse="unPublishDataTrackResponse",n.DataTrackSubscriberHandles="dataTrackSubscriberHandles",n.DataTrackPacketReceived="dataTrackPacketReceived",n.Joined="joined",n.TokenRefreshed="tokenRefreshed",n.ServerRegionsReported="serverRegionsReported"})(le||(le={}));var he;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.CpuConstrained="cpuConstrained",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate",n.PreConnectBufferFlushed="preConnectBufferFlushed"})(he||(he={}));function YC(n){return typeof n>"u"?n:typeof structuredClone=="function"?typeof n=="object"&&n!==null?structuredClone(Object.assign({},n)):structuredClone(n):JSON.parse(JSON.stringify(n))}class Ye{constructor(e,t,i,s,r){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:s,priority:r};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const QC=["vp8","h264"],JC=["vp8","h264","vp9","av1","h265"];function Gm(n){return!!QC.find(e=>e===n)}const ZC=Gm;var Km;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(Km||(Km={}));var Uu;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(Uu||(Uu={}));const pa={h90:new Ye(160,90,9e4,20),h180:new Ye(320,180,16e4,20),h216:new Ye(384,216,18e4,20),h360:new Ye(640,360,45e4,20),h540:new Ye(960,540,8e5,25),h720:new Ye(1280,720,17e5,30),h1080:new Ye(1920,1080,3e6,30),h1440:new Ye(2560,1440,5e6,30),h2160:new Ye(3840,2160,8e6,30)},Bu={h120:new Ye(160,120,7e4,20),h180:new Ye(240,180,125e3,20),h240:new Ye(320,240,14e4,20),h360:new Ye(480,360,33e4,20),h480:new Ye(640,480,5e5,20),h540:new Ye(720,540,6e5,25),h720:new Ye(960,720,13e5,30),h1080:new Ye(1440,1080,23e5,30),h1440:new Ye(1920,1440,38e5,30)},qu={h360fps3:new Ye(640,360,2e5,3,"medium"),h360fps15:new Ye(640,360,4e5,15,"medium"),h720fps5:new Ye(1280,720,8e5,5,"medium"),h720fps15:new Ye(1280,720,15e5,15,"medium"),h720fps30:new Ye(1280,720,2e6,30,"medium"),h1080fps15:new Ye(1920,1080,25e5,15,"medium"),h1080fps30:new Ye(1920,1080,5e6,30,"medium"),original:new Ye(0,0,7e6,30,"medium")};function Xm(n,e,t){var i,s,r,a;const o=Jm(n??{}),c=o.optionsWithoutProcessor,l=o.audioProcessor,u=o.videoProcessor,h=e==null?void 0:e.processor,p=t==null?void 0:t.processor,y=c??{};return y.audio===!0&&(y.audio={}),y.video===!0&&(y.video={}),y.audio&&(Vu(y.audio,e),(i=(r=y.audio).deviceId)!==null&&i!==void 0||(r.deviceId={ideal:"default"}),(l||h)&&(y.audio.processor=l??h)),y.video&&(Vu(y.video,t),(s=(a=y.video).deviceId)!==null&&s!==void 0||(a.deviceId={ideal:"default"}),(u||p)&&(y.video.processor=u??p)),y}function Vu(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function ju(n){var e,t,i,s;const r={};if(n.video)if(typeof n.video=="object"){const a={},o=a,c=n.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":Vu(o,c.resolution);break;default:o[l]=c[l]}}),r.video=a,(e=(i=r.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else r.video=n.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return n.audio?typeof n.audio=="object"?(r.audio=n.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Ym(n){return O(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=Qm();if(i){const s=i.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,a=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield Vt(t),s.getByteTimeDomainData(a);const c=a.some(l=>l!==128&&l!==0);return i.close(),!c}return!1})()})}function Qm(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const i=()=>O(this,void 0,void 0,function*(){var s;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}finally{(s=window.document.body)===null||s===void 0||s.removeEventListener("click",i)}});t.addEventListener("statechange",()=>{var s;t.state==="closed"&&((s=window.document.body)===null||s===void 0||s.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return t}}function ek(n){return n==="audioinput"?ae.Source.Microphone:n==="videoinput"?ae.Source.Camera:ae.Source.Unknown}function Hu(n){return n===ae.Source.Microphone?"audioinput":n===ae.Source.Camera?"videoinput":void 0}function tk(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,ks()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function ma(n){return n.split("/")[1].toLowerCase()}function ik(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new yu({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function Le(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?Le(n.track):{})}}function nk(){return typeof RTCRtpReceiver<"u"&&typeof RTCRtpReceiver.prototype.getSynchronizationSources=="function"}function sk(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],s={};for(const r of i)n[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function Jm(n){const e=Object.assign({},n);let t,i;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:YC(e)}}function rk(n){switch(n){case _t.CAMERA:return ae.Source.Camera;case _t.MICROPHONE:return ae.Source.Microphone;case _t.SCREEN_SHARE:return ae.Source.ScreenShare;case _t.SCREEN_SHARE_AUDIO:return ae.Source.ScreenShareAudio;default:return ae.Source.Unknown}}function Zm(n,e){return n.width*n.height<e.width*e.height}function ak(n,e){var t;return(t=n.layers)===null||t===void 0?void 0:t.find(i=>i.quality===e)}const ok=5e3,ga=[];var yi;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(yi||(yi={}));let ae=class sa extends ai.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug("stream state changed: ".concat(this._streamState," -> ").concat(e)),this._streamState=e}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=sa.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=xe,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),ok):this.handleAppVisibilityChanged()},this.loggerContextCb=i.loggerContextCb,this.log=Nt((s=i.loggerName)!==null&&s!==void 0?s:yt.Track,()=>this.logContext),this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=sa.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Le(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===sa.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===sa.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(ga.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&ga.splice(ga.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),rr(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),s=i.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?he.AudioPlaybackStarted:he.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?he.AudioPlaybackFailed:he.VideoPlaybackFailed,r):r.name==="AbortError"?this.log.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(s?"audio":"video"),{error:r}),s&&e&&i.some(a=>a.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(he.ElementAttached,e),e}detach(e){try{if(e){ar(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(he.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{ar(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(he.ElementDetached,i)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.log.debug("stopping track"),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=Nt(e.loggerName,()=>this.logContext))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ga.forEach(i=>{i.parentElement||(t=!1)}),t&&ga.push(e)}}handleAppVisibilityChanged(){return O(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===sa.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){oi()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){oi()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}};function rr(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(s=>{t.removeTrack(s)}),t.addTrack(n)),(!ks()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(ks()||Cs())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function ar(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function s(l){switch(l){case e.Audio:return Li.AUDIO;case e.Video:return Li.VIDEO;default:return Li.DATA}}n.kindToProto=s;function r(l){switch(l){case Li.AUDIO:return e.Audio;case Li.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=r;function a(l){switch(l){case t.Camera:return _t.CAMERA;case t.Microphone:return _t.MICROPHONE;case t.ScreenShare:return _t.SCREEN_SHARE;case t.ScreenShareAudio:return _t.SCREEN_SHARE_AUDIO;default:return _t.UNKNOWN}}n.sourceToProto=a;function o(l){switch(l){case _t.CAMERA:return t.Camera;case _t.MICROPHONE:return t.Microphone;case _t.SCREEN_SHARE:return t.ScreenShare;case _t.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function c(l){switch(l){case hu.ACTIVE:return i.Active;case hu.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(ae||(ae={}));const ck="|",eg="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function lk(n){const e=n.split(ck);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function Vt(n){return new Xt(e=>ht.setTimeout(e,n))}function $u(){return"addTransceiver"in RTCPeerConnection.prototype}function Wu(){return"addTrack"in RTCPeerConnection.prototype}function uk(){if(!("getCapabilities"in RTCRtpSender)||ks()||Cs())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function dk(){if(!("getCapabilities"in RTCRtpSender)||Cs())return!1;if(ks()){const t=Yt();if(t!=null&&t.version&&nn(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&nn(t.osVersion,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function tn(n){return n==="av1"||n==="vp9"}function zu(n){return!document||ya()?!1:(n||(n=document.createElement("audio")),"setSinkId"in n)}function hk(){return typeof RTCPeerConnection>"u"?!1:$u()||Wu()}function Cs(){var n;return((n=Yt())===null||n===void 0?void 0:n.name)==="Firefox"}function fk(){const n=Yt();return!!n&&n.name==="Chrome"&&n.os!=="iOS"}function Gu(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"&&!fk()}function ks(){var n;return((n=Yt())===null||n===void 0?void 0:n.name)==="Safari"}function ya(){const n=Yt();return(n==null?void 0:n.name)==="Safari"||(n==null?void 0:n.os)==="iOS"}function pk(){const n=Yt();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")||(n==null?void 0:n.os)==="iOS"&&!!(n!=null&&n.osVersion)&&nn(n.osVersion,"17")>=0}function mk(n){return n||(n=Yt()),(n==null?void 0:n.name)==="Safari"&&nn(n.version,"18.3")>0||(n==null?void 0:n.os)==="iOS"&&!!(n!=null&&n.osVersion)&&nn(n.osVersion,"18.3")>0}function tg(){var n,e;return oi()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function gk(){const n=Yt(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&nn(n.osVersion,e)>=0?!0:n.name==="Safari"&&nn(n.version,e)>=0}function oi(){return typeof document<"u"}function Fi(){return navigator.product=="ReactNative"}function or(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Ku(n){return or(n)?n.hostname.split(".")[0]:null}function ig(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ng(){if(!Fi())return;let n=ig();if(n)return n.platform}function sg(){if(oi())return window.devicePixelRatio;if(Fi()){let n=ig();if(n)return n.devicePixelRatio}return 1}function nn(n,e){const t=n.split("."),i=e.split("."),s=Math.min(t.length,i.length);for(let r=0;r<s;++r){const a=parseInt(t[r],10),o=parseInt(i[r],10);if(a>o)return 1;if(a<o)return-1;if(r===s-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function yk(n){for(const e of n)e.target.handleResize(e)}function vk(n){for(const e of n)e.target.handleVisibilityChanged(e)}let Xu=null;const rg=()=>(Xu||(Xu=new ResizeObserver(yk)),Xu);let Yu=null;const ag=()=>(Yu||(Yu=new IntersectionObserver(vk,{root:null,rootMargin:"0px"})),Yu);function bk(n){var e;const t=new Op({capabilities:n,sdk:Mp.JS,protocol:zC,clientProtocol:GC,version:WC});return Fi()&&(t.os=(e=ng())!==null&&e!==void 0?e:""),t}function og(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=n,s.height=e;const r=s.getContext("2d");r==null||r.fillRect(0,0,s.width,s.height),i&&r&&(r.beginPath(),r.arc(n/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream().getTracks(),c=_e(o,1),l=c[0];if(!l)throw Error("Could not get empty media stream video track");return l.enabled=t,l}let va;function Qu(){if(!va){const t=new AudioContext,i=t.createOscillator(),s=t.createGain();s.gain.setValueAtTime(0,0);const r=t.createMediaStreamDestination();i.connect(s),s.connect(r),i.start();var n=r.stream.getAudioTracks(),e=_e(n,1);if(va=e[0],!va)throw Error("Could not get empty media stream audio track");va.enabled=!1}return va.clone()}class Ft{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((i,s)=>O(this,void 0,void 0,function*(){this.resolve=i,this.reject=s,e&&(yield e(i,s))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function cg(n){return JC.includes(n)}function cr(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact!==void 0)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal!==void 0)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function Tk(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function ba(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function _k(n,e){return n.segments.map(t=>{let i=t.id,s=t.text,r=t.language,a=t.startTime,o=t.endTime,c=t.final;var l;const u=(l=e.get(i))!==null&&l!==void 0?l:Date.now(),h=Date.now();return c?e.delete(i):e.set(i,u),{id:i,text:s,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:r,firstReceivedTime:u,lastReceivedTime:h}})}function Sk(n){const e=n.id,t=n.timestamp,i=n.message,s=n.editTimestamp;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:i}}function lg(n){switch(n.reason){case He.LeaveRequest:return n.context;case He.Cancelled:return Gt.CLIENT_INITIATED;case He.NotAllowed:return Gt.USER_REJECTED;case He.ServerUnreachable:return Gt.JOIN_FAILURE;default:return Gt.UNKNOWN_REASON}}function Es(n){return n!==void 0?Number(n):void 0}function Ui(n){return n!==void 0?BigInt(n):void 0}function lr(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function sn(n){return!!n&&n.kind==ae.Kind.Audio}function Dn(n){return!!n&&n.kind==ae.Kind.Video}function rn(n){return lr(n)&&Dn(n)}function Pn(n){return lr(n)&&sn(n)}function Ju(n){return!!n&&!n.isLocal}function Ck(n){return!!n&&!n.isLocal}function Zu(n){return Ju(n)&&Dn(n)}function kk(n){return n.isLocal}function Ek(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let s=e;for(;s>0;){const r=i[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(i.slice(0,s)),i=i.slice(s)}return i.length>0&&t.push(i),t}function ac(n){return new ReadableStream({start(e){e.enqueue(n),e.close()}})}function xk(n,e){return tm(this,arguments,function*(){const i=n.getReader();let s=new Uint8Array(0);try{for(;;){const r=yield xn(i.read()),a=r.done,o=r.value;if(a)break;if(o.byteLength===0)continue;const c=new Uint8Array(s.byteLength+o.byteLength);for(c.set(s),c.set(o,s.byteLength),s=c;s.byteLength>=e;)yield yield xn(s.slice(0,e)),s=s.slice(e)}s.byteLength>0&&(yield yield xn(s))}finally{i.releaseLock()}})}function wk(n){var e;const t=n.get("Cache-Control");if(t){const i=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(i)return parseInt(i,10)}}function Yn(){return typeof CompressionStream<"u"}function Ak(){return Yn()&&!Cs()}function Dk(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=Pk(n,e);return t?i:ed(i,"v1")}function Pk(n,e){const t=new URL(Tk(n));return e.forEach((i,s)=>{t.searchParams.set(s,i)}),ed(t,"rtc")}function Ik(n){const e=new URL(ba(n));return ed(e,"validate")}function ug(n){return n.endsWith("/")?n:"".concat(n,"/")}function ed(n,e){return n.pathname="".concat(ug(n.pathname)).concat(e),n}function dg(n){if(typeof n=="string")return qp.fromJson(JSON.parse(n),{ignoreUnknownFields:!0});if(n instanceof ArrayBuffer)return qp.fromBinary(new Uint8Array(n));throw new Error("could not decode websocket message: ".concat(typeof n))}function Rk(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(n instanceof AbortSignal))return e;const t=n.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const Ok=10,Ta="lk_e2ee",Mk={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Ok,keyringSize:16,keySize:128};var Qn;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(Qn||(Qn={}));var hg;(function(n){n.KeyRatcheted="keyRatcheted"})(hg||(hg={}));var Jn;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(Jn||(Jn={}));var fg;(function(n){n.Error="cryptorError"})(fg||(fg={}));function Lk(){return td()||Nk()}function Nk(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"}function td(){return typeof window<"u"&&typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Fk(n){var e,t,i,s,r;if(((e=n.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=n.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((i=n.value)===null||i===void 0?void 0:i.case)!=="speaker"&&((s=n.value)===null||s===void 0?void 0:s.case)!=="transcription"&&((r=n.value)===null||r===void 0?void 0:r.case)!=="encryptedPacket")return new xp({value:n.value})}class sO extends ai.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(t,i,s)=>{xe.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Mk),e),this.on(Qn.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const s={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),s),i!==void 0&&(this.latestManuallySetKeyIndex=i),this.emit(Qn.SetKey,s,i!==void 0)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(e,t){this.emit(Qn.RatchetRequest,e,t)}}var pg;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(pg||(pg={}));function _a(){return Gu()}function Sa(n){return!!(n!=null&&n.worker)&&(td()||_a())}function oc(n){return!!(n!=null&&n.timestamp||n!=null&&n.frameId)}function Uk(n){const e=[];return n!=null&&n.timestamp&&e.push(Js.PTF_USER_TIMESTAMP),n!=null&&n.frameId&&e.push(Js.PTF_FRAME_ID),e}function Bk(n){if(!n||n.length===0)return;const e={};return n.includes(Js.PTF_USER_TIMESTAMP)&&(e.timestamp=!0),n.includes(Js.PTF_FRAME_ID)&&(e.frameId=!0),e.timestamp||e.frameId?e:void 0}function id(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i,s;let r;const a=(i=t.isImmediate)!==null&&i!==void 0?i:!1,o=(s=t.callback)!==null&&s!==void 0?s:!1,c=t.maxWait;let l=Date.now(),u=[];function h(){if(c!==void 0){const y=Date.now()-l;if(y+e>=c)return c-y}return e}const p=function(){for(var y=arguments.length,_=new Array(y),b=0;b<y;b++)_[b]=arguments[b];const S=this;return new Promise((D,I)=>{const F=function(){if(r=void 0,l=Date.now(),!a){const P=n.apply(S,_);o&&o(P),u.forEach(L=>{let C=L.resolve;return C(P)}),u=[]}},w=a&&r===void 0;if(r!==void 0&&ht.clearTimeout(r),r=ht.setTimeout(F,h()),w){const P=n.apply(S,_);return o&&o(P),D(P)}u.push({resolve:D,reject:I})})};return p.cancel=function(y){r!==void 0&&ht.clearTimeout(r),u.forEach(_=>{let b=_.reject;return b(y)}),u=[]},p}const nd=2e3;function cc(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}class mg extends ae{constructor(e,t,i,s,r){super(e,i,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?he.Muted:he.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(he.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return O(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),nd)),nk()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const s=i.timestamp,r=i.rtpTimestamp;r&&this.rtpTimestamp!==r&&(this.emit(he.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}const sd=100;class rd extends mg{constructor(e,t,i,s,r){super(e,t,ae.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>O(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=cc(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=id(()=>{this.updateDimensions()},sd),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}lookupFrameMetadata(e){let t=e.rtpTimestamp;var i;return(i=this.frameMetadataExtractor)===null||i===void 0?void 0:i.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===ae.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?ar(this._mediaStreamTrack,t):rr(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new qk(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);const t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return O(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(i=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&i!==""&&s.get(i)&&(t.mimeType=s.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return O(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const s=this.elementInfos.reduce((c,l)=>Math.max(c,l.visibilityChangedAt||0),0),r=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,a=this.elementInfos.some(c=>c.pictureInPicture),o=this.elementInfos.some(c=>c.visible)&&!r||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-s<sd){ht.setTimeout(()=>{this.updateVisibility()},sd);return}this.lastVisible=o,this.emit(he.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let i=0,s=0;const r=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*r,c=a.height()*r;o+c>i+s&&(i=o,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:i,height:s},this.emit(he.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?sg():t||(sg()>2?2:1)}}class qk{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const r=i.target,a=i.isIntersecting;r===this.element&&(this.isIntersecting=a,this.isPiP=Ca(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var i,s;(s=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var r;this.isPiP=Ca(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)})})},this.onLeavePiP=()=>{var i;this.isPiP=Ca(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??ad(e),this.isPiP=oi()&&Ca(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=ad(this.element),this.isPiP=Ca(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,ag().observe(this.element),rg().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,s,r;(e=ag())===null||e===void 0||e.unobserve(this.element),(t=rg())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function Ca(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?ad(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function ad(n,e){const t=e||window;let i=n.offsetTop,s=n.offsetLeft;const r=n.offsetWidth,a=n.offsetHeight,o=n,c=o.hidden,l=getComputedStyle(n),u=l.display;for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,s+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&s+r>t.pageXOffset&&!c&&u!=="none"}class Vk extends ai.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var s,r;const a=i.data,o=a.kind,c=a.data;switch(o){case"error":if(xe.error(c.error.message),c.uuid){const h=this.decryptDataRequests.get(c.uuid);if(h!=null&&h.reject){h.reject(c.error);break}const p=this.encryptDataRequests.get(c.uuid);if(p!=null&&p.reject){p.reject(c.error);break}}this.emit(Jn.EncryptionError,c.error,c.participantIdentity);break;case"initAck":c.enabled&&this.keyProvider.getKeys().forEach(h=>{this.postKey(h,!1)});break;case"enable":if(c.enabled&&this.keyProvider.getKeys().forEach(h=>{this.postKey(h,!1)}),this.encryptionEnabled!==c.enabled&&c.participantIdentity===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity))this.emit(Jn.ParticipantEncryptionStatusChanged,c.enabled,this.room.localParticipant),this.encryptionEnabled=c.enabled;else if(c.participantIdentity){const h=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(c.participantIdentity);if(!h)throw TypeError("couldn't set encryption status, participant not found".concat(c.participantIdentity));this.emit(Jn.ParticipantEncryptionStatusChanged,c.enabled,h)}break;case"ratchetKey":this.keyProvider.emit(Qn.KeyRatcheted,c.ratchetResult,c.participantIdentity,c.keyIndex);break;case"decryptDataResponse":const l=this.decryptDataRequests.get(c.uuid);l!=null&&l.resolve&&l.resolve(c);break;case"encryptDataResponse":const u=this.encryptDataRequests.get(c.uuid);u!=null&&u.resolve&&u.resolve(c);break;case"packetTrailerMetadata":this.handleFrameMetadata(c.trackId,c.rtpTimestamp,c.ssrc,c.metadata);break}},this.onWorkerError=i=>{xe.error("e2ee worker encountered an error:",{error:i.error}),this.emit(Jn.EncryptionError,i.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Lk())throw new Fu("tried to setup end-to-end encryption on an unsupported browser");if(xe.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:AC.getLevel()}};this.worker&&(xe.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){xe.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?xe.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}handleFrameMetadata(e,t,i,s){if(this.room){for(const r of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(const a of r.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof rd&&a.track.frameMetadataExtractor){a.track.frameMetadataExtractor.storeMetadata(t,i,s);return}}}setupEngine(e){e.on(le.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(se.TrackPublished,(i,s)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==Ve.NONE,s.identity)),e.on(se.ConnectionStateChanged,i=>{i===Be.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==Ve.NONE,s.identity)})})}).on(se.TrackUnsubscribed,(i,s,r)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(se.TrackSubscribed,(i,s,r)=>{this.setupE2EEReceiver(i,r.identity,s.trackInfo)}).on(se.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");const i=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(s=>{var r;this.postKey(s,i===((r=s.keyIndex)!==null&&r!==void 0?r:0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(fe.LocalSenderCreated,(i,s)=>O(this,void 0,void 0,function*(){this.setupE2EESender(s,i)})),e.localParticipant.on(fe.LocalTrackPublished,i=>{if(!Dn(i.track)||!ya())return;const s={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:ma(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(s)}),t.on(Qn.SetKey,(i,s)=>this.postKey(i,s??!0)).on(Qn.RatchetRequest,(i,s)=>this.postRatchetRequest(i,s))}encryptData(e){return O(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},s=new Ft;return s.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,s),this.worker.postMessage(i),s.promise})}handleEncryptedData(e,t,i,s){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:i,keyIndex:s}},o=new Ft;return o.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e,t){let i=e.key,s=e.participantIdentity,r=e.keyIndex;var a;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:s,isPublisher:s===((a=this.room)===null||a===void 0?void 0:a.localParticipant.identity),key:i,keyIndex:r,updateCurrentKeyIndex:t}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(!e.receiver)return;if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");const s=e.kind==="video"&&!!i.packetTrailerFeatures&&i.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?ma(i.mimeType):void 0,s)}setupE2EESender(e,t){var i,s,r;if(!lr(e)||!t){t||xe.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0,Dn(e)?(s=(i=e.publishOptions)===null||i===void 0?void 0:i.frameMetadata)!==null&&s!==void 0?s:(r=e.publishOptions)===null||r===void 0?void 0:r.packetTrailer:void 0)}handleReceiver(e,t,i,s,r){return O(this,void 0,void 0,function*(){if(this.worker){if(Gu()){const a={kind:"decode",participantIdentity:i,trackId:t,codec:s,hasPacketTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(Ta in e&&s){const l={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:i,hasPacketTrailer:r}};this.worker.postMessage(l);return}let a=e.writableStream,o=e.readableStream;if(!a||!o){const l=e.createEncodedStreams();e.writableStream=l.writable,a=l.writable,e.readableStream=l.readable,o=l.readable}const c={kind:"decode",data:{readableStream:o,writableStream:a,trackId:t,codec:s,participantIdentity:i,isReuse:Ta in e,hasPacketTrailer:r}};this.worker.postMessage(c,[o,a])}e[Ta]=!0}})}handleSender(e,t,i,s){var r;if(!(Ta in e||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Gu()){xe.info("initialize script transform");const a={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i,hasPacketTrailer:oc(s),packetTrailer:s};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{xe.info("initialize encoded streams");const a=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:a.readable,writableStream:a.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:oc(s),packetTrailer:s}};this.worker.postMessage(o,[a.readable,a.writable])}e[Ta]=!0}}}const jk=300;class Hk{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,i){for(this.activeSsrc!==0&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=jk;){const s=this.metadataMap.keys().next().value;this.metadataMap.delete(s)}this.metadataMap.set(e,i)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class $k{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=t=>{const i=t.data;if(i.kind==="metadata"){const s=this.extractors.get(i.data.trackId);s&&s.storeMetadata(i.data.rtpTimestamp,i.data.ssrc,i.data.metadata)}},this.onWorkerError=t=>{xe.error("frame metadata worker encountered an error:",{error:t.error})},this.worker=e==null?void 0:e.worker}setup(e){e!==this.room&&(this.room=e,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:"init"})),e.on(se.TrackSubscribed,(t,i,s)=>{t.kind==="video"&&this.setupReceiver(t,i.trackInfo)}).on(se.TrackUnsubscribed,t=>{this.teardownTrack(t)}).on(se.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){var i,s,r;const a=e.receiver;if(!a)return;if(!(!!(t!=null&&t.packetTrailerFeatures)&&t.packetTrailerFeatures.length>0)){!((i=this.room)===null||i===void 0)&&i.hasE2EESetup||this.setupPassthroughReceiver(a,e.mediaStreamID);return}if(!Sa(this.worker?{worker:this.worker}:void 0)&&!(!((s=this.room)===null||s===void 0)&&s.hasE2EESetup)){xe.warn("frame metadata transform not supported; skipping extraction");return}const c=new Hk,l=e.mediaStreamID;this.extractors.set(l,c),e.frameMetadataExtractor=c,!(!((r=this.room)===null||r===void 0)&&r.hasE2EESetup)&&this.setupWorkerReceiver(a,l,!0)}setupPassthroughReceiver(e,t){if(_a()){"transform"in e&&(e.transform=null);return}if(this.worker&&Sa({worker:this.worker})&&!this.workerPipelines.has(e)){this.setupWorkerReceiver(e,t,!1);return}this.worker&&this.workerPipelines.has(e)&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;const s=this.worker;if(!s)return;if(_a()){e.transform=new RTCRtpScriptTransform(s,{kind:"decode",trackId:t});return}const r=this.workerPipelines.get(e);if(r){const c={kind:"updateTrackId",data:{oldTrackId:r,newTrackId:t,hasPacketTrailer:i}};s.postMessage(c),this.workerPipelines.set(e,t);return}if(!("createEncodedStreams"in e)){xe.warn("createEncodedStreams not supported");return}let a;try{a=e.createEncodedStreams()}catch(c){xe.warn("failed to create encoded streams",{error:c});return}const o={kind:"decode",data:{readableStream:a.readable,writableStream:a.writable,trackId:t,hasPacketTrailer:i}};s.postMessage(o,[a.readable,a.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){const t=e.mediaStreamID,i=this.extractors.get(t);i&&(i.dispose(),this.extractors.delete(t)),e instanceof rd&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(const t of this.extractors.values())t.dispose();this.extractors.clear(),this.workerPipelines.clear(),(e=this.worker)===null||e===void 0||e.terminate()}}const Wk=500,zk=15e3;class ur{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new ur),this._instance}addFailedConnectionAttempt(e){var t;const i=new URL(e),s=Ku(i);if(!s)return;let r=(t=this.failedConnectionAttempts.get(s))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(s,r+1),this.backOffPromises.set(s,Vt(Math.min(Wk*Math.pow(2,r),zk)))}getBackOffPromise(e){const t=new URL(e),i=t&&Ku(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&Ku(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}ur._instance=null;const od="default";class It{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new It),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return O(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;if(((r=It.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){xe.debug("awaiting getUserMedia promise");try{t?yield It.userMediaPromiseMap.get(t):yield Promise.all(It.userMediaPromiseMap.values())}catch{xe.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(s&&!(ks()&&i.hasDeviceInUse(t))&&(a.filter(c=>c.kind===t).length===0||a.some(c=>{const l=c.label==="",u=t?c.kind===t:!0;return l&&u}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);a=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(u=>{u.stop()})}return i._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a})()})}normalizeDeviceId(e,t,i){return O(this,void 0,void 0,function*(){if(t!==od)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===od);if(!r){xe.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==od&&o.groupId===(i??r.groupId));if(!a){xe.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?It.userMediaPromiseMap.has(e):It.userMediaPromiseMap.size>0}}It.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],It.userMediaPromiseMap=new Map;const cd=65535,gg=4294967295;class Bi{static u16(e){return new Bi(e,cd)}static u32(e){return new Bi(e,gg)}constructor(e,t){if(this.value=e,e<0)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.");this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new Bi(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){const e=this.value;return this.increment(),new Bi(e,this.maxSize)}isBefore(e){const t=this.value>>>0,s=(e.value>>>0)-t>>>0;return s!==0&&s<this.maxSize+1}}class dr{static fromRtpTicks(e){return new dr(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*gg);return dr.fromRtpTicks(e)}constructor(e,t){this.timestamp=Bi.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new dr(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class xs{constructor(e,t,i){this.epoch=t,this.base=i,this.previous=i.clone(),this.rateInHz=e}static startingNow(e,t){return new xs(t,new Date,e)}static startingAtTime(e,t,i){return new xs(i,e,t)}static rtpStartingNow(e){return xs.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return xs.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),i=xs.durationInMsToTicks(t,this.rateInHz),s=this.base.clone();return s.wrappingAdd(i),s.isBefore(this.previous)&&(s=this.previous),this.previous=s.clone(),s.clone()}static durationInMsToTicks(e,t){let s=(e*1e6*t+5e8)/1e9;return Math.round(s)}}function ld(n){if(n instanceof DataView)return n;if(n instanceof ArrayBuffer)return new DataView(n);if(n instanceof Uint8Array)return new DataView(n.buffer,n.byteOffset,n.byteLength);throw new Error("Error coercing ".concat(n," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var ws;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(ws||(ws={}));class hr extends Ei{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=ws[t]}isReason(e){return this.reason===e}static tooLarge(){return new hr("Value too large to be a valid track handle",ws.TooLarge)}static reserved(e){return new hr("0x".concat(e.toString(16)," is a reserved value."),ws.Reserved)}}const Gk={fromNumber(n){if(n===0)throw hr.reserved(n);if(n>cd)throw hr.tooLarge();return n}};class Kk{constructor(){this.value=0}get(){return this.value+=1,this.value>cd?null:this.value}reset(){this.value=0}}const lc={from(n){return{sid:n.sid,pubHandle:n.pubHandle,name:n.name,usesE2ee:n.encryption!==Ve.NONE}},toProtobuf(n){return new Ho({sid:n.sid,pubHandle:n.pubHandle,name:n.name,encryption:n.usesE2ee?Ve.GCM:Ve.NONE})}};var ka;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(ka||(ka={}));class Xk{constructor(){this.pendingTasks=new Map,this.taskMutex=new Dt,this.nextTaskIndex=0}run(e){return O(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:ka.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=ka.RUNNING,yield e()}finally{t.status=ka.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return O(this,void 0,void 0,function*(){return this.run(()=>O(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class Yk{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,s;if(!((i=t.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,(s=t.protocols)!==null&&s!==void 0?s:[]);r.binaryType="arraybuffer",this.ws=r;const a=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},c=o.closeCode,l=o.reason;return r.close(c,l)};this.opened=new Xt((o,c)=>{const l=()=>{c(Se.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{o({readable:new ReadableStream({start(u){r.onmessage=h=>{let p=h.data;return u.enqueue(p)},r.onerror=h=>u.error(h)},cancel:a}),writable:new WritableStream({write(u){r.send(u)},abort(){r.close()},close:a}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",l)},r.addEventListener("error",l)}),this.closed=new Xt((o,c)=>{const l=()=>O(this,void 0,void 0,function*(){const u=new Xt(p=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",y=>{p(y)},{once:!0})}),h=yield Xt.race([Vt(250),u]);h?o(h):c(Se.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=u=>{let h=u.code,p=u.reason;o({closeCode:h,reason:p}),r.removeEventListener("error",l)},r.addEventListener("error",l)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=a}}const Qk=["syncState","trickle","offer","answer","simulate","leave"];function Jk(n){const e=Qk.indexOf(n.case)>=0;return xe.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var Je;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(Je||(Je={}));const Zk=250,eE=5e3;class ud{get currentState(){return this.state}get isDisconnected(){return this.state===Je.DISCONNECTING||this.state===Je.DISCONNECTED}get isEstablishingConnection(){return this.state===Je.CONNECTING||this.state===Je.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=Je.DISCONNECTED,this.log=xe,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.loggerContextCb=t.loggerContextCb,this.log=Nt((i=t.loggerName)!==null&&i!==void 0?i:yt.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new Xk,this.queuedRequests=[],this.closingLock=new Dt,this.connectionLock=new Dt,this.state=Je.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,s){return O(this,arguments,void 0,function(r,a,o,c){var l=this;let u=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,h=arguments.length>5?arguments[5]:void 0;return(function*(){return l.state=Je.CONNECTING,l.options=o,yield l.connect(r,a,o,c,u,h)})()})}reconnect(e,t,i,s){return O(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring");return}return this.state=Je.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:s}),void 0,this.useV0SignalPath)})}connect(e,t,i,s){return O(this,arguments,void 0,function(r,a,o,c){var l=this;let u=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,h=arguments.length>5?arguments[5]:void 0;return(function*(){const p=yield l.connectionLock.lock();l.connectOptions=o,l.useV0SignalPath=u;const y=bk(o.clientInfoCapabilities),_=u?tE(a,y,o):yield iE(a,y,o,h),b=Dk(r,_,u).toString(),S=Ik(b).toString();return new Promise((D,I)=>O(l,void 0,void 0,function*(){var F,w;try{let P=!1;const L=j=>O(this,void 0,void 0,function*(){if(P)return;P=!0;const G=j instanceof Event?j.currentTarget:j,X=Rk(G,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(X)).catch(z=>{this.log.error(z),this.close()}):this.close(),C(),I(Se.cancelled(X))});c==null||c.addEventListener("abort",L);const C=()=>{clearTimeout(N),c==null||c.removeEventListener("abort",L)},N=setTimeout(()=>{L(Se.timeout("room connection has timed out (signal)"))},o.websocketTimeout),x=(j,G)=>{this.handleSignalConnected(j,N,G)},k=new URL(b);if(k.searchParams.has("access_token")&&k.searchParams.set("access_token","<redacted>"),this.ws){const j=performance.now();yield this.close(!1),this.log.debug("closed previous ws connection in ".concat(performance.now()-j,"ms"))}this.log.info("signal connecting to ".concat(k),{reconnect:o.reconnect,reconnectReason:o.reconnectReason}),this.ws=new Yk(b);try{this.ws.closed.then(re=>{this.isEstablishingConnection&&I(Se.internal("Websocket got closed during a (re)connection attempt: ".concat(re.reason))),re.closeCode!==1e3&&(this.log.warn("websocket closed",{reason:re.reason,code:re.closeCode,wasClean:re.closeCode===1e3,state:this.state}),this.state===Je.CONNECTED&&this.handleOnClose(re.reason||"Unexpected WS error"))}).catch(re=>{this.isEstablishingConnection&&I(Se.internal("Websocket error during a (re)connection attempt: ".concat(re)))});const j=yield this.ws.opened.catch(re=>O(this,void 0,void 0,function*(){if(this.state!==Je.CONNECTED){this.state=Je.DISCONNECTED,clearTimeout(N);const Y=yield this.handleConnectionError(re,S);I(Y);return}this.handleWSError(re),I(re)}));if(clearTimeout(N),!j)return;const G=j.readable.getReader();this.streamWriter=j.writable.getWriter();let X,z;try{X=yield Promise.race([G.read(),new Promise((re,Y)=>{z=setTimeout(()=>{Y(Se.timeout("signal connection timed out while waiting for the first message"))},eE)})])}catch(re){G.releaseLock(),I(re),this.close();return}finally{clearTimeout(z)}if(G.releaseLock(),!X.value)throw Se.internal("no message received as first message");const W=dg(X.value),te=this.validateFirstMessage(W,(F=o.reconnect)!==null&&F!==void 0?F:!1);if(!te.isValid){I(te.error);return}((w=W.message)===null||w===void 0?void 0:w.case)==="join"&&(this.pingTimeoutDuration=W.message.value.pingTimeout,this.pingIntervalDuration=W.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(W.message.value));const Q=te.shouldProcessFirstMessage?W:void 0;x(j,Q),D(te.response)}catch(j){I(j)}finally{C()}}finally{p()}}))})()})}startReadingLoop(e,t){return O(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Vt(this.signalLatency));const i=yield e.read(),s=i.done,r=i.value;if(s)break;const a=dg(r);this.handleSignalResponse(a)}})}close(){return O(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([Je.DISCONNECTING||Je.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const s=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Je.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const r=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([r,Vt(Zk)])}}catch(r){e.log.debug("websocket error while closing",{error:r})}finally{t&&(e.state=Je.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:As(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:As(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new Go({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Ko({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return O(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const o=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new bu({requestId:o,metadata:i,name:s,attributes:a})}),o})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Wp({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Kp({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:nt.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Qp({timestamp:nt.parse(Date.now()),rtt:nt.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new vu({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Yo({reason:Gt.CLIENT_INITIATED,action:ir.DISCONNECT})})}sendPublishDataTrackRequest(e,t,i){return this.sendRequest({case:"publishDataTrackRequest",value:new pu({pubHandle:e,name:t,encryption:i?Ve.GCM:Ve.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new gu({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new Vp({updates:[new jp({trackSid:e,subscribe:t})]})})}sendRequest(e){return O(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!s&&!Jk(t)&&i.state===Je.RECONNECTING){i.queuedRequests.push(()=>O(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield i.requestQueue.flush()),i.signalLatency&&(yield Vt(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case));return}const a=new zS({message:t});try{i.useJSON?yield i.streamWriter.write(a.toJsonString()):yield i.streamWriter.write(a.toBinary().buffer)}catch(o){i.log.error("error sending signal message",{error:o})}})()})}handleSignalResponse(e){var t,i;const s=e.message;if(s==null){this.log.debug("received unsupported message");return}let r=!1;if(s.case==="answer"){const a=yg(s.value);this.onAnswer&&this.onAnswer(a,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const a=yg(s.value);this.onOffer&&this.onOffer(a,s.value.id,s.value.midToTrackId)}else if(s.case==="trickle"){const a=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(a,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=s.value.speakers)!==null&&i!==void 0?i:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):s.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(s.value.token),this.onRoomMoved&&this.onRoomMoved(s.value)):s.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(s.value):s.case==="publishDataTrackResponse"?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(s.value):s.case==="unpublishDataTrackResponse"?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(s.value):s.case==="dataTrackSubscriberHandles"?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(s.value):this.log.debug("unsupported message",{msgCase:s.case}));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return O(this,void 0,void 0,function*(){if(this.state===Je.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.info("websocket connection closed: ".concat(e),{reason:e}),t&&t(e)})}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set");return}this.pingTimeout=ht.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString())),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&ht.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set");return}this.log.debug("start ping interval"),this.pingInterval=ht.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&ht.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=Je.CONNECTED,this.log.info("signal connected"),clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,s,r,a,o;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===Je.RECONNECTING&&((s=e.message)===null||s===void 0?void 0:s.case)!=="leave"?((r=e.message)===null||r===void 0?void 0:r.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received"),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((a=e.message)===null||a===void 0?void 0:a.case)==="leave"?{isValid:!1,error:Se.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:Se.internal("Unexpected first message")}:{isValid:!1,error:Se.internal("did not receive join response, got ".concat((o=e.message)===null||o===void 0?void 0:o.case," instead"))}}handleConnectionError(e,t){return O(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:const s=yield i.text();return s.includes("requested room does not exist")?Se.notAllowed(s,i.status):Se.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const r=yield i.text();return Se.notAllowed(r,i.status);default:break}return e instanceof Se?e:Se.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof Se?i:Se.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function yg(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function As(n,e){return new Xn({sdp:n.sdp,type:n.type,id:e})}function tE(n,e,t){var i;const s=new URLSearchParams;return s.set("access_token",n),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",Fi()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),s.set("client_protocol",e.clientProtocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&s.set("network",navigator.connection.type),s}function iE(n,e,t,i){return O(this,void 0,void 0,function*(){const s=new URLSearchParams;s.set("access_token",n);const r=new _C({clientInfo:e,connectionSettings:new Jp({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0,publisherOffer:i});t.reconnectReason&&(r.reconnectReason=t.reconnectReason);const a=r.toBinary();let o,c;if(Yn()){const p=new CompressionStream("gzip"),y=p.writable.getWriter();y.write(new Uint8Array(a)),y.close();const _=[],b=p.readable.getReader();for(;;){const F=yield b.read(),w=F.done,P=F.value;if(w)break;_.push(P)}const S=_.reduce((F,w)=>F+w.length,0),D=new Uint8Array(S);let I=0;for(const F of _)D.set(F,I),I+=F.length;o=D,c=Su.GZIP}else o=a,c=Su.NONE;const u=new SC({joinRequest:o,compression:c}).toBinary(),h=p=>{const y=Array.from(p,_=>String.fromCodePoint(_)).join("");return btoa(y)};return s.set("join_request",h(u).replace(/\+/g,"-").replace(/\//g,"_")),s})}class nE{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const s=i+this.ttl;return this._map.set(e,{value:t,expiresAt:s}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const i of this._map.entries()){var t=_e(i,2);const s=t[0];t[1].expiresAt<e&&this._map.delete(s)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const i of this._map.entries()){var t=_e(i,2);const s=t[0],r=t[1];r.expiresAt>=Date.now()&&e(r.value,s,this.asValueMap())}}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const r of i.entries()){var s=_e(r,2);const a=s[0],o=s[1];t.push(e(o,a,i))}return t}asValueMap(){const e=new Map;for(const i of this._map.entries()){var t=_e(i,2);const s=t[0],r=t[1];r.expiresAt>=Date.now()&&e.set(s,r.value)}return e}}var qi={},dd={},hd={exports:{}},vg;function fd(){if(vg)return hd.exports;vg=1;var n=hd.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return e.address!=null?"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(e){return e.subtype!=null?"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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{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(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{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(e){return e.maxMessageSize!=null?"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(e){return e.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(e){return"imageattr:%s %s %s"+(e.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(e){return"simulcast:%s %s"+(e.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(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{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(n).forEach(function(e){var t=n[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),hd.exports}var bg;function sE(){return bg||(bg=1,(function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,l,u){if(u&&!l)c[u]=e(o[1]);else for(var h=0;h<l.length;h+=1)o[h+1]!=null&&(c[l[h]]=e(o[h+1]))},i=function(o,c,l){var u=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:u&&!c[o.name]&&(c[o.name]={});var h=o.push?{}:u?c[o.name]:c;t(l.match(o.reg),h,o.names,o.name),o.push&&c[o.push].push(h)},s=fd(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var c={},l=[],u=c;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(h){var p=h[0],y=h.slice(2);p==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var _=0;_<(s[p]||[]).length;_+=1){var b=s[p][_];if(b.reg.test(y))return i(b,u,y)}}),c.media=l,c};var a=function(o,c){var l=c.split(/=(.+)/,2);return l.length===2?o[l[0]]=e(l[1]):l.length===1&&c.length>1&&(o[l[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var c=[],l=o.split(" ").map(e),u=0;u<l.length;u+=3)c.push({component:l[u],ip:l[u+1],port:l[u+2]});return c},n.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(l){var u,h=!1;return l[0]!=="~"?u=e(l):(u=e(l.substring(1,l.length)),h=!0),{scid:u,paused:h}})})}})(dd)),dd}var pd,Tg;function rE(){if(Tg)return pd;Tg=1;var n=fd(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,l=c.length;return a.replace(e,function(u){if(o>=l)return u;var h=c[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(h);case"%d":return Number(h);case"%v":return""}})},i=function(a,o,c){var l=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,u=[a+"="+l];if(o.names)for(var h=0;h<o.names.length;h+=1){var p=o.names[h];o.name?u.push(c[o.name][p]):u.push(c[o.names[h]])}else u.push(c[o.name]);return t.apply(null,u)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return pd=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(h){h.payloads==null&&(h.payloads="")});var c=o.outerOrder||s,l=o.innerOrder||r,u=[];return c.forEach(function(h){n[h].forEach(function(p){p.name in a&&a[p.name]!=null?u.push(i(h,p,a)):p.push in a&&a[p.push]!=null&&a[p.push].forEach(function(y){u.push(i(h,p,y))})})}),a.media.forEach(function(h){u.push(i("m",n.m[0],h)),l.forEach(function(p){n[p].forEach(function(y){y.name in h&&h[y.name]!=null?u.push(i(p,y,h)):y.push in h&&h[y.push]!=null&&h[y.push].forEach(function(_){u.push(i(p,y,_))})})})}),u.join(`\r
|
|
38
|
+
`)+`\r
|
|
39
|
+
`},pd}var _g;function aE(){if(_g)return qi;_g=1;var n=sE(),e=rE(),t=fd();return qi.grammar=t,qi.write=e,qi.parse=n.parse,qi.parseParams=n.parseParams,qi.parseFmtpConfig=n.parseFmtpConfig,qi.parsePayloads=n.parsePayloads,qi.parseRemoteCandidates=n.parseRemoteCandidates,qi.parseImageAttributes=n.parseImageAttributes,qi.parseSimulcastStreamList=n.parseSimulcastStreamList,qi}var xi=aE();const oE=.9,cE=1e3,lE=20,Zn={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",OfferAnswered:"offerAnswered",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Sg extends ai.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=xe,this.iceLog=xe,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=id(s=>O(this,void 0,void 0,function*(){this.emit(Zn.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),lE),this.close=()=>{this._pc&&(this.log.debug("closing peer connection"),this.pendingInitialOffer=void 0,this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.loggerOptions=t,this.log=Nt((i=t.loggerName)!==null&&i!==void 0?i:yt.PCTransport,()=>this.logContext),this.iceLog=Nt(yt.ICE,()=>this.logContext),this.config=e,this._pc=this.createPC(),this.offerLock=new Dt}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&(this.iceLog.debug("local ICE candidate gathered",{candidate:t.candidate.candidate}),(i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;this.iceLog.debug("ICE candidate error",{event:t}),(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug("ICE connection state: ".concat(e.iceConnectionState)),(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug("signaling state: ".concat(e.signalingState)),(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug("connection state: ".concat(e.connectionState)),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;this.log.debug("data channel opened by peer",{label:t.channel.label,id:t.channel.id}),(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return O(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.iceLog.debug("queuing remote ICE candidate until remote description applied",{pendingCount:this.pendingCandidates.length+1}),this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return O(this,void 0,void 0,function*(){var i,s;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",{offerId:t,latestOfferId:this.latestOfferId}),!1;let r;if(e.type==="offer"){let a=dE(e),o=a.stereoMids,c=a.nackMids;this.remoteStereoMids=o,this.remoteNackMids=c}else if(e.type==="answer"){if(this.pendingInitialOffer&&this._pc){const c=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const l=xi.parse((i=c.sdp)!==null&&i!==void 0?i:"");l.media.forEach(u=>{uc(u)}),this.log.debug("setting pending initial offer before processing answer"),yield this.setMungedSDP(c,xi.write(l))}const a=xi.parse((s=e.sdp)!==null&&s!==void 0?s:"");a.media.forEach(c=>{const l=Ea(c.mid);c.type==="audio"&&this.trackBitrates.some(u=>{if(!u.transceiver||l!=u.transceiver.mid)return!1;let h=0;if(c.rtp.some(y=>y.codec.toUpperCase()===u.codec.toUpperCase()?(h=y.payload,!0):!1),h===0)return!0;let p=!1;for(const y of c.fmtp)if(y.payload===h){y.config=y.config.split(";").filter(_=>!_.includes("maxaveragebitrate")).join(";"),u.maxbr>0&&(y.config+=";maxaveragebitrate=".concat(u.maxbr*1e3)),p=!0;break}return p||u.maxbr>0&&c.fmtp.push({payload:h,config:"maxaveragebitrate=".concat(u.maxbr*1e3)}),!0})});const o=this.getPlaceholderMids();o.size>0&&kg(a.media,c=>o.has(Ea(c.mid))),r=xi.write(a)}return yield this.setMungedSDP(e,r,!0),this.pendingCandidates.length>0&&this.iceLog.debug("flushing queued ICE candidates",{count:this.pendingCandidates.length}),this.pendingCandidates.forEach(a=>{this.pc.addIceCandidate(a)}),this.pendingCandidates=[],this.restartingIce=!1,e.type==="answer"&&(this.latestAcknowledgedOfferId=t,this.emit(Zn.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Zn.NegotiationComplete),e.sdp&&xi.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Zn.RTPVideoPayloadTypes,o.rtp)})),!0})}createInitialOffer(){return O(this,void 0,void 0,function*(){var e;const t=yield this.offerLock.lock();try{if(this.pc.signalingState!=="stable"){this.log.warn("signaling state is not stable, cannot create initial offer");return}const i=this.latestOfferId+1;this.latestOfferId=i;const s=yield this.pc.createOffer();this.pendingInitialOffer={sdp:s.sdp,type:s.type};const r=xi.parse((e=s.sdp)!==null&&e!==void 0?e:"");return r.media.forEach(a=>{uc(a)}),s.sdp=xi.write(r),{offer:s,offerId:i}}finally{t()}})}createAndSendOffer(e){return O(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.iceLog.debug("restarting ICE"),this.restartingIce=!0),this._pc&&(this._pc.signalingState==="have-local-offer"||this.pendingInitialOffer)){const c=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&c)yield this._pc.setRemoteDescription(c);else{this.renegotiate=!0,this.log.debug("requesting renegotiation");return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection");return}this.log.debug("starting to negotiate");const s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",{sdp:r.sdp});const a=xi.parse((t=r.sdp)!==null&&t!==void 0?t:"");a.media.forEach(c=>{uc(c),c.type==="audio"?Cg(c,["all"],[]):c.type==="video"&&this.trackBitrates.some(l=>{if(!c.msid||!l.cid||!c.msid.includes(l.cid))return!1;let u=0;if(c.rtp.some(_=>_.codec.toUpperCase()===l.codec.toUpperCase()?(u=_.payload,!0):!1),u===0)return!0;tn(l.codec)&&!ks()&&this.ensureVideoDDExtensionForSVC(c,a);const h=Math.round(l.maxbr*oE),p=l.isScreenShare?h:Math.min(h,cE);let y=!1;for(const _ of c.fmtp)if(_.payload===u){y=!0,_.config.includes("x-google-start-bitrate")||(_.config+=";x-google-start-bitrate=".concat(p));break}return y||c.fmtp.push({payload:u,config:"x-google-start-bitrate=".concat(p)}),!0})});const o=this.getPlaceholderMids();if(o.size>0&&kg(a.media,c=>o.has(Ea(c.mid))),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",{latestOfferId:this.latestOfferId,offerId:s});return}yield this.setMungedSDP(r,xi.write(a)),this.onOffer(r,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return O(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=xi.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{uc(s),s.type==="audio"&&Cg(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,xi.write(i)),t})}getPlaceholderMids(){var e,t;return uE((t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[])}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new st("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new st("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getMaxMessageSize(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.sctp)===null||t===void 0?void 0:t.maxMessageSize}getConnectedAddress(){return O(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,s=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}setMungedSDP(e,t,i){return O(this,void 0,void 0,function*(){var s,r;const a=e.sdp;if(t){e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description")),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(o){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:o,mungedSdp:t,originalSdp:a}),e.sdp=a}}try{i?yield(s=this._pc)===null||s===void 0?void 0:s.setRemoteDescription(e):yield(r=this._pc)===null||r===void 0?void 0:r.setLocalDescription(e)}catch(o){let c="unknown error";o instanceof Error?c=o.message:typeof o=="string"&&(c=o);const l={error:c,sdp:e.sdp};throw t&&t!==a&&(l.mungedSdp=t),!i&&this.pc.remoteDescription&&(l.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),{fields:l}),new Ss(c)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===eg))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;(c=o.ext)===null||c===void 0||c.forEach(l=>{l.value>a&&(a=l.value)})}),this.ddExtID=a+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:eg})}}}function Cg(n,e,t){const i=Ea(n.mid);let s=0;n.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&n.rtcpFb.push({payload:s,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function uE(n){const e=new Set;for(const t of n)t.mid&&!t.sender.track&&e.add(t.mid);return e}function kg(n,e){var t,i;const s=new Map,r=new Set;for(const a of n){const o=e(a);for(const c of(t=a.fmtp)!==null&&t!==void 0?t:[])o?s.has(c.payload)||s.set(c.payload,c.config):(s.set(c.payload,c.config),r.add(c.payload))}if(s.size!==0){for(const a of n)if(e(a))for(const o of(i=a.fmtp)!==null&&i!==void 0?i:[]){const c=s.get(o.payload);c!==void 0&&o.config!==c&&(o.config=c)}}}function dE(n){var e;const t=[],i=[],s=xi.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;const c=Ea(a.mid);a.type==="audio"&&(a.rtp.some(l=>l.codec==="opus"?(r=l.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(l=>l.payload===r&&l.type==="nack")&&i.push(c),a.fmtp.some(l=>l.payload===r?(l.config.includes("sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:i}}function uc(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}function Ea(n){return typeof n=="number"?n.toFixed(0):n}const md="vp8",hE={audioPreset:Uu.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:qu.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:md,backupCodec:!0,preConnectBuffer:!1},Eg={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},xg={deviceId:{ideal:"default"},resolution:pa.h720.resolution},fE={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new PC,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},gd={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ot;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(ot||(ot={}));class wg{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var s;this.peerConnectionTimeout=gd.peerConnectionTimeout,this.log=xe,this.iceLog=xe,this.updateState=()=>{var r,a;const o=this.state,c=this.requiredTransports.map(l=>l.getConnectionState());c.every(l=>l==="connected")?this.state=ot.CONNECTED:c.some(l=>l==="failed")?this.state=ot.FAILED:c.some(l=>l==="connecting")?this.state=ot.CONNECTING:c.every(l=>l==="closed")?this.state=ot.CLOSED:c.some(l=>l==="closed")?this.state=ot.CLOSING:c.every(l=>l==="new")&&(this.state=ot.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(ot[o]," to ").concat(ot[this.state])),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.loggerOptions=t,this.log=Nt((s=t.loggerName)!==null&&s!==void 0?s:yt.PCManager,()=>this.logContext),this.iceLog=Nt(yt.ICE,()=>this.logContext),this.isPublisherConnectionRequired=e!=="subscriber-primary",this.isSubscriberConnectionRequired=e==="subscriber-primary",this.publisher=new Sg(i,t),this._mode=e,e!=="publisher-only"&&(this.subscriber=new Sg(i,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Ni.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,r)},this.subscriber.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Ni.PUBLISHER)},this.publisher.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)},this.publisher.onOffer=(r,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,r,a)},this.state=ot.NEW,this.connectionLock=new Dt,this.remoteOfferLock=new Dt}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return O(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(s){this.log.warn("could not removeTrack",{error:s})}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return O(this,void 0,void 0,function*(){this.iceLog.warn("triggering ICE restart"),this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return O(this,void 0,void 0,function*(){var i;this.iceLog.debug("adding remote ICE candidate",{target:t,candidate:e}),t===Ni.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return O(this,void 0,void 0,function*(){var i,s,r;this.log.debug("received server offer",{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()});const a=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{a()}})}updateConfiguration(e,t){var i;this.log.debug("updating rtc configuration",{iceRestart:t}),this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return O(this,void 0,void 0,function*(){var i;const s=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating"),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return O(this,void 0,void 0,function*(){return new Xt((t,i)=>{const s=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>s){this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),t();return}let r=!1;const a=()=>{r||(r=!0,clearTimeout(l),this.publisher.off(Zn.OfferAnswered,o),e.signal.removeEventListener("abort",c))},o=u=>{u>s&&(a(),t())},c=()=>{a(),i(new Ss("negotiation aborted"))},l=setTimeout(()=>{a(),i(new Ss("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",c),this.publisher.on(Zn.OfferAnswered,o),this.publisher.negotiate(u=>{a(),u instanceof Error?i(u):i(new Error(String(u)))})})})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return i==null?void 0:i.mid}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Ni.PUBLISHER?this.publisher.getConnectedAddress():e===Ni.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return O(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,l)=>O(r,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection"),ht.clearTimeout(h),l(Se.cancelled("room connection has been cancelled"))};s!=null&&s.signal.aborted&&u(),s==null||s.signal.addEventListener("abort",u);const h=ht.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",u),l(Se.internal("could not establish pc connection"))},a);for(;this.state!==ot.CONNECTED;)if(yield Vt(50),s!=null&&s.signal.aborted){l(Se.cancelled("room connection has been cancelled"));return}ht.clearTimeout(h),s==null||s.signal.removeEventListener("abort",u),c()}))})()})}}class Ag{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new Dt,this.waiterAbortController=new AbortController,this.kind=e.kind,this.lowWaterMark=e.lowWaterMark,this.highWaterMark=e.highWaterMark,this.isEngineClosed=e.isEngineClosed,this.onBufferStatusChanged=e.onBufferStatusChanged}get channelHandle(){return this.handle}attach(e){this.handle&&this.handle!==e&&this.invalidateWaiters("data channel replaced"),this.handle=e}detach(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"data channel torn down";this.handle&&this.invalidateWaiters(e),this.handle=void 0}getChannel(){return this.handle}isBelowHighWaterMark(e){return e.bufferedAmount<=this.highWaterMark}isBelowLowWaterMark(e){return e.bufferedAmount<=e.bufferedAmountLowThreshold}lockHeadroom(){return this.headroomLock.lock()}waitForHeadroomWithLock(){return O(this,void 0,void 0,function*(){const e=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock()}finally{e()}})}waitForHeadroomWithoutLock(){return O(this,void 0,void 0,function*(){if(this.isEngineClosed())throw new st("engine closed");const e=this.getChannel();if(!e)throw new st("DataChannel not found, kind: ".concat(this.kind));if(this.isBelowHighWaterMark(e))return;const t=this.waiterAbortController.signal;yield new Xt((i,s)=>{const r=()=>{c(),i()},a=()=>{c(),s(new st("DataChannel ".concat(this.kind," closed while draining the buffer")))},o=()=>{c(),s(new st("DataChannel ".concat(this.kind," was replaced or torn down while waiting for headroom")))},c=()=>{e.removeEventListener("bufferedamountlow",r),e.removeEventListener("close",a),t.removeEventListener("abort",o)};if(t.aborted){o();return}e.addEventListener("bufferedamountlow",r),e.addEventListener("close",a),t.addEventListener("abort",o)})})}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;const t=this.getChannel();if(!t)return;const i=this.isBelowLowWaterMark(t);i!==this.bufferStatusLow&&(this.bufferStatusLow=i,(e=this.onBufferStatusChanged)===null||e===void 0||e.call(this,i))}}class Dg extends Ag{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return O(this,void 0,void 0,function*(){const t=this.getChannel();if(t){switch(this.bufferFullBehavior){case"wait":this.isBelowHighWaterMark(t)||(yield this.waitForHeadroomWithLock());break;case"drop":if(!this.isBelowLowWaterMark(t)){this.dropCount+=1,this.dropCount%100===0&&xe.warn("dropping lossy data channel messages, total dropped: ".concat(this.dropCount));return}}if(this.statCurrentBytes+=e.byteLength,!this.shouldSkipSends())try{t.send(e),this.refreshBufferStatus()}catch(i){if(i instanceof TypeError)xe.error(i);else throw i}}})}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=ht.setInterval(()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;const e=this.getChannel();if(e){const t=this.statByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,this.lowWaterMark),this.highWaterMark)}},1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&(ht.clearInterval(this.statInterval),this.statInterval=void 0),this.dropCount=0}}class Pg{constructor(){this.buffer=[],this._totalSize=0,this._sentSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength,e.sent&&(this._sentSize+=e.data.byteLength)}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength,e.sent&&(this._sentSize-=e.data.byteLength)),e}getAll(){return this.buffer.slice()}getUnsent(){return this.buffer.filter(e=>!e.sent)}markSent(e){e.sent||(e.sent=!0,this._sentSize+=e.data.byteLength)}markAllUnsent(){for(const e of this.buffer)e.sent=!1;this._sentSize=0}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(!t.sent||this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class pE extends Ag{constructor(e){super(e),this.messageBuffer=new Pg,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){const e=this.sequence;return this.sequence+=1,e}send(e,t){return O(this,void 0,void 0,function*(){if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}const i=this.getChannel();if(i){try{yield this.waitForHeadroomWithLock()}catch(s){if(this.isEngineClosed())throw s;this.messageBuffer.push({data:e,sequence:t,sent:!1});return}if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}this.messageBuffer.push({data:e,sequence:t,sent:!0}),i.send(e),this.refreshBufferStatus()}})}replay(e){return O(this,void 0,void 0,function*(){const t=this.getChannel();if(!t)return;this.messageBuffer.popToSequence(e);const i=yield this.lockHeadroom();try{this.messageBuffer.markAllUnsent();for(let s=this.messageBuffer.getUnsent();s.length>0;s=this.messageBuffer.getUnsent())for(const r of s)yield this.waitForHeadroomWithoutLock(),t.send(r.data),this.messageBuffer.markSent(r)}finally{i()}this.refreshBufferStatus()})}refreshBufferStatus(){const e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new Pg,this.sequence=1}}var Re;(function(n){n[n.RELIABLE=0]="RELIABLE",n[n.LOSSY=1]="LOSSY",n[n.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"})(Re||(Re={}));const mE=64*1024,gE=1024*1024,yE=8*1024,vE=256*1024;function bE(n){return n===Re.RELIABLE?mE:yE}function TE(n){return n===Re.RELIABLE?gE:vE}const Ig="_lossy",Rg="_reliable",Og="_data_track";class _E{constructor(e){this.opts=e;const t=i=>({kind:i,lowWaterMark:bE(i),highWaterMark:TE(i),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:s=>e.onBufferStatusChanged(i,s)});this.reliable=new pE(Object.assign(Object.assign({},t(Re.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new Dg(Object.assign(Object.assign({},t(Re.LOSSY)),{bufferFullBehavior:"drop",shouldSkipSends:e.isReconnecting})),this.dataTrack=new Dg(Object.assign(Object.assign({},t(Re.DATA_TRACK_LOSSY)),{bufferFullBehavior:"wait",shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case Re.RELIABLE:return this.reliable;case Re.LOSSY:return this.lossy;case Re.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){if(!(arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1))return this.channelFor(e).channelHandle;switch(e){case Re.RELIABLE:return this.reliableSub;case Re.LOSSY:return this.lossySub;case Re.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return!!(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}createPublisherChannels(e){for(const i of[this.lossy,this.reliable,this.dataTrack]){const s=i.channelHandle;s&&(s.onmessage=null,s.onerror=null,s.onclose=null)}const t=(i,s,r)=>{s.onmessage=r,s.onerror=this.opts.onDataError,s.onclose=()=>this.opts.onChannelClose(i.kind),s.bufferedAmountLowThreshold=i.lowWaterMark,s.onbufferedamountlow=()=>i.refreshBufferStatus(),i.attach(s)};t(this.lossy,e.createPublisherDataChannel(Ig,{ordered:!1,maxRetransmits:0}),this.opts.onDataMessage),t(this.reliable,e.createPublisherDataChannel(Rg,{ordered:!0}),this.opts.onDataMessage),t(this.dataTrack,e.createPublisherDataChannel(Og,{ordered:!1,maxRetransmits:0}),this.opts.onDataTrackMessage),this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===Rg)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===Ig)this.lossySub=e,t=this.opts.onDataMessage;else if(e.label===Og)this.dataTrackSub=e,t=this.opts.onDataTrackMessage;else return!1;return e.onmessage=t,!0}teardown(){const e=t=>{t&&(t.onbufferedamountlow=null,t.onclose=null,t.onclosing=null,t.onerror=null,t.onmessage=null,t.onopen=null,t.close())};for(const t of[this.lossy,this.reliable,this.dataTrack]){const i=t.channelHandle;t.detach("peer connections cleaned up"),e(i)}e(this.lossySub),e(this.reliableSub),e(this.dataTrackSub),this.lossySub=void 0,this.reliableSub=void 0,this.dataTrackSub=void 0,this.reliable.reset()}}const yd=typeof MediaRecorder<"u";class SE{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const CE=yd?MediaRecorder:SE;class kE extends CE{constructor(e,t){if(!yd)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,s;const r=()=>s===void 0,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s==null||s.close(),s=void 0},o=c=>{s==null||s.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,i=l=>O(this,void 0,void 0,function*(){let u;if(l.data.arrayBuffer){const h=yield l.data.arrayBuffer();u=new Uint8Array(h)}else if(l.data.byteArray)u=l.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(u)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function EE(){return yd}const xE=1e3,wE=1e4;class Mg extends ae{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=id(()=>O(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>O(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(he.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new Dt,this.pauseUpstreamLock=new Dt,this.trackChangeLock=new Dt,this.trackChangeLock.lock().then(a=>O(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==ae.Kind.Video)return;const e=this._mediaStreamTrack.getSettings(),t=e.width,i=e.height;if(t&&i)return{width:t,height:i}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,i){return O(this,void 0,void 0,function*(){var s;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(a=>{ar(this._mediaStreamTrack,a)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(rr(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),r=this.processor.processedTrack}this.sender&&((s=this.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=i?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(a=>{rr(r??e,a)}))})}waitForDimensions(){return O(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:xE;return(function*(){var i;if(e.kind===ae.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=Yt())===null||i===void 0?void 0:i.os)==="iOS"&&(yield Vt(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield Vt(50)}throw new An("unable to get track dimensions after timeout")})()})}setDeviceId(e){return O(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===cr(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),cr(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return O(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===ae.Source.ScreenShare)return;const i=e._mediaStreamTrack.getSettings(),s=i.deviceId,r=i.groupId,a=e.kind===ae.Kind.Audio?"audioinput":"videoinput";return t?It.getInstance().normalizeDeviceId(a,s,r):s})()})}mute(){return O(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return O(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return O(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new An("unable to replace an unpublished track");let s,r;typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor())}finally{i()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return O(this,void 0,void 0,function*(){})}restart(e,t){return O(this,void 0,void 0,function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const s=e,r=s.deviceId,a=s.facingMode,o=IC(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const c={audio:!1,video:!1};this.kind===ae.Kind.Video?c.video=r||a?{deviceId:r,facingMode:a}:!0:c.audio=r?Object.assign({deviceId:r},o):!0,this.attachedElements.forEach(h=>{ar(this.mediaStreamTrack,h)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const u=(yield navigator.mediaDevices.getUserMedia(c)).getTracks()[0];return this.kind===ae.Kind.Video&&(yield u.applyConstraints(o)),u.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(u,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(he.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{i()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?he.Muted:he.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return O(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),tg()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return O(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(he.UpstreamPaused,this);const i=Yt();if((i==null?void 0:i.name)==="Safari"&&nn(i.version,"12.0")<0)throw new Fu("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return O(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(he.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return O(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return O(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;const a=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext,localTrack:i};if(yield t.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(rr(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:l})),setTimeout(()=>{o.play().catch(u=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:u}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))}),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&s&&(ar(i._mediaStreamTrack,l),rr(i.processor.processedTrack,l));yield(r=i.sender)===null||r===void 0?void 0:r.replaceTrack(i.processor.processedTrack)}i.emit(he.TrackProcessorUpdate,i.processor)}finally{a()}yield i.onSenderTrackSwapped()})()})}getProcessor(){return this.processor}stopProcessor(){return O(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}yield e.onSenderTrackSwapped()})()})}internalStopProcessor(){return O(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(he.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!EE()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new kE(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},wE)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class dc extends Mg{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,ae.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>O(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=cc(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(he.AudioTrackFeatureUpdate,this,Pt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(he.AudioTrackFeatureUpdate,this,Pt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return O(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===ae.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return O(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===ae.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}restartTrack(e){return O(this,void 0,void 0,function*(){let t;if(e){const i=ju({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}applyConstraints(e){return O(this,void 0,void 0,function*(){const t=yield this.trackChangeLock.lock();try{const i=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),i}finally{t()}})}restart(e,t){const i=Object.create(null,{restart:{get:()=>super.restart}});return O(this,void 0,void 0,function*(){const s=yield i.restart.call(this,e,t);return this.checkForSilence(),s})}startMonitor(){oi()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},nd)))}setProcessor(e){return O(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Fi()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext,localTrack:this};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(he.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return O(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(s=>{s.type==="outbound-rtp"&&(i={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),i})}checkForSilence(){return O(this,void 0,void 0,function*(){const e=yield Ym(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(he.AudioSilenceDetected)),e})}}function AE(n,e,t){switch(n.kind){case"audio":return new dc(n,e,!1,void 0,t);case"video":return new fc(n,e,!1,t);default:throw new An("unsupported track type: ".concat(n.kind))}}const DE=Object.values(pa),PE=Object.values(Bu),IE=Object.values(qu),RE=[pa.h180,pa.h360],OE=[Bu.h180,Bu.h360],ME=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new Ye(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,n.encoding.priority)}),vd=["q","h","f"];function hc(n,e,t,i){var s,r;let a=i==null?void 0:i.videoEncoding;n&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=LE(n,e,t,l),xe.debug("using video encoding",a));const u=a.maxFramerate,h=new Ye(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&tn(l)){const S=new Ug(c),D=[];if(S.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const I=Yt();if(ya()||Fi()||(I==null?void 0:I.name)==="Chrome"&&nn(I==null?void 0:I.version,"113")<0){const F=S.suffix=="h"?2:3,w=mk(I);for(let P=0;P<S.spatial;P+=1)D.push({rid:vd[2-P],maxBitrate:a.maxBitrate/Math.pow(F,P),maxFramerate:h.encoding.maxFramerate,scaleResolutionDownBy:w?Math.pow(2,P):void 0});D[0].scalabilityMode=c}else D.push({maxBitrate:a.maxBitrate,maxFramerate:h.encoding.maxFramerate,scalabilityMode:c});return h.encoding.priority&&(D[0].priority=h.encoding.priority,D[0].networkPriority=h.encoding.priority),xe.debug("using svc encoding",{encodings:D}),D}if(!o)return[a];let p;n?p=(s=Fg(i==null?void 0:i.screenShareSimulcastLayers))!==null&&s!==void 0?s:Ng(n,h):p=(r=Fg(i==null?void 0:i.videoSimulcastLayers))!==null&&r!==void 0?r:Ng(n,h);let y;if(p.length>0){const S=p[0];if(p.length>1){var _=p,b=_e(_,2);y=b[1]}const D=Math.max(e,t);if(D>=960&&y)return bd(e,t,[S,y,h],u);if(D>=480)return bd(e,t,[S,h],u)}return bd(e,t,[h])}function Lg(n,e,t){var i,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&xe.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,l=(r=o.height)!==null&&r!==void 0?r:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===ae.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),hc(n.source===ae.Source.ScreenShare,c,l,t)}function LE(n,e,t,i){const s=NE(n,e,t);let r=s[0].encoding;const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function NE(n,e,t){if(n)return IE;const i=e>t?e/t:t/e;return Math.abs(i-1.7777777777777777)<Math.abs(i-1.3333333333333333)?DE:PE}function Ng(n,e){if(n)return ME(e);const t=e.width,i=e.height,s=t>i?t/i:i/t;return Math.abs(s-1.7777777777777777)<Math.abs(s-1.3333333333333333)?RE:OE}function bd(n,e,t,i){const s=[];if(t.forEach((r,a)=>{if(a>=vd.length)return;const o=Math.min(n,e),l={rid:vd[a],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},u=i&&r.encoding.maxFramerate?Math.min(i,r.encoding.maxFramerate):r.encoding.maxFramerate;u&&(l.maxFramerate=u);const h=Yt(),p=(h==null?void 0:h.name)==="Firefox"&&h.os!=="iOS"||a===0;r.encoding.priority&&p&&(l.priority=r.encoding.priority,l.networkPriority=r.encoding.priority),s.push(l)}),Fi()&&ng()==="ios"){let r;s.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let a=!0;s.forEach(o=>{var c;o.maxFramerate!=r&&(a&&(a=!1,xe.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),xe.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),o.maxFramerate=r)})}return s}function Fg(n){if(n)return n.slice().sort((e,t)=>{const i=e.encoding,s=t.encoding;return i.maxBitrate>s.maxBitrate?1:i.maxBitrate<s.maxBitrate?-1:i.maxBitrate===s.maxBitrate&&i.maxFramerate&&s.maxFramerate?i.maxFramerate>s.maxFramerate?1:-1:0})}class Ug{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function FE(n){switch(n.source){case ae.Source.Camera:return"maintain-framerate";case ae.Source.ScreenShare:return"maintain-resolution";default:return"balanced"}}const UE=5e3;class fc extends Mg{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,ae.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>O(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const a=new Map(r.map(c=>[c.rid,c])),o=r.some(c=>c.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(he.CpuConstrained)),this.prevStats){let c=0;a.forEach((l,u)=>{var h;const p=(h=this.prevStats)===null||h===void 0?void 0:h.get(u);c+=cc(l,p)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new Dt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!oi())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},nd))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return O(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=ki(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0)r=l.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(u){i={error:u}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return O(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=ki(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0){r=l.value,o=!1;const u=r;yield(a=u.sender)===null||a===void 0?void 0:a.replaceTrack(u.mediaStreamTrack)}}catch(u){i={error:u}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return O(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===ae.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return O(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===ae.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return O(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(s=>{var r;if(s.type==="outbound-rtp"){const a={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},o=i.get(s.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((s,r)=>{var a,o;return((a=r.frameWidth)!==null&&a!==void 0?a:0)-((o=s.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=yi.LOW;i<=yi.HIGH;i+=1)t.push(new Tu({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(tn(this.codec),t)}restartTrack(e){return O(this,void 0,void 0,function*(){var t,i,s,r,a;let o;if(e){const h=ju({video:e});typeof h.video!="boolean"&&(o=h.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,l=ki(this.simulcastCodecs.values()),u;u=yield l.next(),t=u.done,!t;c=!0){r=u.value,c=!1;const h=r;h.sender&&((a=h.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(h.mediaStreamTrack=this.mediaStreamTrack.clone(),yield h.sender.replaceTrack(h.mediaStreamTrack))}}catch(h){i={error:h}}finally{try{!c&&!t&&(s=l.return)&&(yield s.call(l))}finally{if(i)throw i.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return O(this,void 0,void 0,function*(){yield this.refreshSenderEncodings()})}refreshSenderEncodings(){return O(this,void 0,void 0,function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;const t=yield this.senderLock.lock();try{let s;try{s=yield this.waitForDimensions()}catch(o){this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:o}));return}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===s.width&&this.lastEncodedDimensions.height===s.height)return;const r=this.source===ae.Source.ScreenShare,a=hc(r,s.width,s.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,a),this.encodings=a,this.lastEncodedDimensions=s;for(const o of this.simulcastCodecs){var i=_e(o,2);const c=i[0],l=i[1];if(!l.sender||((e=l.sender.transport)===null||e===void 0?void 0:e.state)==="closed"||!Gm(c))continue;const u=Object.assign({},this.publishOptions),h=Lg(this,c,u);h&&(yield this.applyEncodingsToSender(l.sender,h),l.encodings=h)}}catch(s){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:s}))}finally{t()}})}applyEncodingsToSender(e,t){return O(this,void 0,void 0,function*(){const i=e.getParameters();!i.encodings||i.encodings.length!==t.length||(i.encodings.forEach((s,r)=>{if(s.active===!1)return;const a=t[r];a.scaleResolutionDownBy!==void 0&&(s.scaleResolutionDownBy=a.scaleResolutionDownBy),a.maxBitrate!==void 0&&(s.maxBitrate=a.maxBitrate),a.maxFramerate!==void 0&&(s.maxFramerate=a.maxFramerate),a.priority!==void 0&&(s.priority=a.priority,s.networkPriority=a.priority)}),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:i.encodings})),yield e.setParameters(i))})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return O(this,arguments,void 0,function(i){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var a,o,c,l,u,h;if(yield t.setProcessor.call(s,i,r),!((u=s.processor)===null||u===void 0)&&u.processedTrack)try{for(var p=!0,y=ki(s.simulcastCodecs.values()),_;_=yield y.next(),a=_.done,!a;p=!0)l=_.value,p=!1,yield(h=l.sender)===null||h===void 0?void 0:h.replaceTrack(s.processor.processedTrack)}catch(b){o={error:b}}finally{try{!p&&!a&&(c=y.return)&&(yield c.call(y))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return O(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},UE))}setPublishingCodecs(e){return O(this,void 0,void 0,function*(){var t,i,s,r,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(tn(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,i=ki(e);s=yield i.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const u=c;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(tn(u.codec),u.qualities);else{const h=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:h})),!h||!h.sender){for(const p of u.qualities)if(p.enabled){l.push(u.codec);break}}else h.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield Bg(h.sender,h.encodings,u.qualities,this.senderLock,tn(u.codec),this.log,this.logContext))}}}catch(u){a={error:u}}finally{try{!t&&!r&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return l})}setPublishingLayers(e,t){return O(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield Bg(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return O(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((i,s)=>{var r;return Object.assign(Object.assign({},i),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&tn(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return O(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),tg()&&this.isInBackground&&this.source===ae.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Bg(n,e,t,i,s,r,a){return O(this,void 0,void 0,function*(){const o=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:n,qualities:t,senderEncodings:e}));try{const c=n.getParameters(),l=c.encodings;if(!l)return;if(l.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:l,senderEncodings:e}));return}let u=!1;!1&&l[0].scalabilityMode||(s&&t.some(y=>y.enabled)&&t.forEach(y=>y.enabled=!0),l.forEach((p,y)=>{var _;let b=(_=p.rid)!==null&&_!==void 0?_:"";b===""&&(b="q");const S=qg(b),D=t.find(I=>I.quality===S);D&&p.active!==D.enabled&&(u=!0,p.active=D.enabled,r.debug("setting layer ".concat(D.quality," to ").concat(p.active?"enabled":"disabled"),a),Cs()&&(D.enabled?(p.scaleResolutionDownBy=e[y].scaleResolutionDownBy,p.maxBitrate=e[y].maxBitrate,p.maxFrameRate=e[y].maxFrameRate):(p.scaleResolutionDownBy=4,p.maxBitrate=10,p.maxFrameRate=2)))})),u&&(c.encodings=l,r.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:c.encodings})),yield n.setParameters(c))}finally{o()}})}function qg(n){switch(n){case"f":return yi.HIGH;case"h":return yi.MEDIUM;case"q":return yi.LOW;default:return yi.HIGH}}function Vg(n,e,t,i){if(!t)return[new Gn({quality:yi.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new Ug(s),a=[],o=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let l=0;l<r.spatial;l+=1)a.push(new Gn({quality:Math.min(yi.HIGH,r.spatial-1)-l,width:Math.ceil(n/Math.pow(o,l)),height:Math.ceil(e/Math.pow(o,l)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let l=qg((a=s.rid)!==null&&a!==void 0?a:"");return new Gn({quality:l,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const BE=2*1e3,Td="leave-reconnect",qE=3e4,VE=3,jE=3;var wi;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(wi||(wi={}));const jg=64e3;class HE extends ai.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}get reliableChannel(){return this.dataChannels.reliable}get lossyChannel(){return this.dataChannels.lossy}get dataTrackChannel(){return this.dataChannels.dataTrack}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=gd.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=wi.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=xe,this.reliableReceivedState=new nE(qE),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>O(this,[i],void 0,function(s){var r=this;let a=s.channel;return(function*(){a&&r.dataChannels.adoptSubscriberChannel(a)&&r.log.debug("on data channel ".concat(a.id,", ").concat(a.label))})()}),this.handleDataMessage=i=>O(this,void 0,void 0,function*(){var s,r,a,o,c;const l=yield this.dataProcessLock.lock();try{const u=yield this.decodeDataMessage(i);if(!u)return;const h=Kt.fromBinary(u);if(h.sequence>0&&h.participantSid!==""){const p=this.reliableReceivedState.get(h.participantSid);if(p&&h.sequence<=p)return;this.reliableReceivedState.set(h.participantSid,h.sequence)}if(((s=h.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(le.ActiveSpeakersUpdate,h.value.value.speakers);else if(((r=h.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up");return}const p=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(h.value.value.encryptedValue,h.value.value.iv,h.participantIdentity,h.value.value.keyIndex),y=xp.fromBinary(p.payload),_=new Kt({value:y.value,participantIdentity:h.participantIdentity,participantSid:h.participantSid});((o=_.value)===null||o===void 0?void 0:o.case)==="user"&&Hg(_,_.value.value),this.emit(le.DataPacketReceived,_,h.value.value.encryptionType)}else((c=h.value)===null||c===void 0?void 0:c.case)==="user"&&Hg(h,h.value.value),this.emit(le.DataPacketReceived,h,Ve.NONE)}finally{l()}}),this.handleDataTrackMessage=i=>O(this,void 0,void 0,function*(){const s=yield this.decodeDataMessage(i);s&&this.emit("dataTrackPacketReceived",s)}),this.handleDataError=i=>{if(this._isClosed)return;const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(typeof RTCErrorEvent<"u"&&i instanceof RTCErrorEvent&&i.error){const a=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(a.message),{error:a,errorDetail:a.errorDetail,sctpCauseCode:a.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(r),{event:i})},this.handleDataChannelClose=i=>()=>{var s;!this._isClosed&&((s=this.pcManager)===null||s===void 0?void 0:s.publisher.getConnectionState())==="connected"&&this.log.error("publisher data channel '".concat(Re[i],"' closed unexpectedly"),this.logContext)},this.handleDisconnect=(i,s)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected")),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up")),this.emit(le.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}i===Td&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(le.TokenRefreshed,this.token),this.reconnectTimeout=ht.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===wi.Connected&&i();const r=()=>{this.off(le.Disconnected,a),i()},a=()=>{this.off(le.Restarted,r),s()};this.once(le.Restarted,r),this.once(le.Disconnected,a)}),this.onRtpMapAvailable=i=>{const s=new Map;i.forEach(r=>{const a=r.codec.toLowerCase();cg(a)&&s.set(r.payload,a)}),this.emit(le.RTPVideoMapUpdate,s)},this.handleBrowserOnLine=()=>O(this,void 0,void 0,function*(){!this.url||!(yield fetch(ba(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===Je.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Je.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(vs.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>O(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(ba(this.url),{method:"HEAD"}),Vt(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=Nt((t=e.loggerName)!==null&&t!==void 0?t:yt.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ud(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new Dt,this.dataProcessLock=new Dt,this.dataChannels=new _E({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:i=>this.handleDataMessage(i),onDataTrackMessage:i=>this.handleDataTrackMessage(i),onDataError:i=>this.handleDataError(i),onChannelClose:i=>this.handleDataChannelClose(i)(),onBufferStatusChanged:(i,s)=>this.emit(le.DCBufferStatusChanged,s,i)}),this.client.onParticipantUpdate=i=>this.emit(le.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(le.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(le.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(le.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(le.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(le.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(le.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(le.SignalRequestResponse,i),this.client.onParticipantUpdate=i=>this.emit(le.ParticipantUpdate,i),this.client.onJoined=i=>this.emit(le.Joined,i)}get logContext(){var e,t,i,s,r,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||s===void 0?void 0:s.sid,participant:(a=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||a===void 0?void 0:a.identity,participantID:this.participantSid}}join(e,t,i,s){return O(this,arguments,void 0,function(r,a,o,c){var l=this;let u=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){var h,p,y;l._isNewlyCreated=!1,l.url=r,l.token=a,l.signalOpts=o,l.maxJoinAttempts=o.maxRetries;try{l.joinAttempts+=1,l.setupSignalClientCallbacks();const _=!u&&Ak();let b;if(_){l.pcManager||(yield l.configure(),l.applyInitialPublisherLayout());const I=yield(h=l.pcManager)===null||h===void 0?void 0:h.publisher.createInitialOffer();I&&(b=As(I.offer,I.offerId))}if(c!=null&&c.aborted)throw Se.cancelled("Connection aborted");if(!u&&l.shouldFailOnV1Path)throw l.shouldFailOnV1Path=!1,Se.serviceNotFound("Simulated v1 path failure","v0-rtc");const S=yield l.client.join(r,a,o,c,u,b);l._isClosed=!1,l.latestJoinResponse=S,l.participantSid=(p=S.participant)===null||p===void 0?void 0:p.sid,l.subscriberPrimary=S.subscriberPrimary,_?(y=l.pcManager)===null||y===void 0||y.updateConfiguration(l.makeRTCConfiguration(S)):(l.pcManager||(yield l.configure(S,!u),u||l.applyInitialPublisherLayout()),(!l.subscriberPrimary||S.fastPublish)&&l.negotiate().catch(I=>{l.log.error(I)})),l.registerOnLineListener(),l.clientConfiguration=S.clientConfiguration,l.emit(le.SignalConnected,S);let D=S.serverInfo;return D||(D={version:S.serverVersion,region:S.serverRegion}),l.log.info("connected to Livekit Server ".concat(Object.entries(D).map(I=>{let F=_e(I,2),w=F[0],P=F[1];return"".concat(w,": ").concat(P)}).join(", "))),{joinResponse:S,serverInfo:D}}catch(_){if(_ instanceof Se){if(_.reason===He.ServerUnreachable){if(l.log.warn("Couldn't connect to server, attempt ".concat(l.joinAttempts," of ").concat(l.maxJoinAttempts)),l.joinAttempts<l.maxJoinAttempts)return l.join(r,a,o,c,u)}else if(_.reason===He.ServiceNotFound)return l.log.warn("Initial connection failed: ".concat(_.message," – Retrying")),l.pcManager&&(l.pcManager.onStateChange=void 0,yield l.cleanupPeerConnections()),l.join(r,a,o,c,!0)}throw _}})()})}close(){return O(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(le.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return O(this,void 0,void 0,function*(){var e;this.dataChannels.teardown(),yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(){return O(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks();for(const e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new An("a track with the same ID has already been published");return new Promise((t,i)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(Se.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",{error:t})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.dataChannelForKind(Re.RELIABLE,!0))===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return O(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return O(this,void 0,void 0,function*(){var i;if(!(this.pcManager&&this.pcManager.currentState!==ot.NEW)){if(e){this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const s=this.makeRTCConfiguration(e);this.pcManager=new wg(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,s)}else{const s=this.makeRTCConfiguration();this.pcManager=new wg("publisher-only",this.loggerOptions,s)}this.emit(le.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,r)=>{this.client.sendIceCandidate(s,r)},this.pcManager.onPublisherOffer=(s,r)=>{this.client.sendOffer(s,r)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,r,a)=>O(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s)),["closed","disconnected","failed"].includes(r)&&(this.publisherConnectionPromise=void 0),s===ot.CONNECTED){const l=this.pcState===wi.New;this.pcState=wi.Connected,l&&this.emit(le.Connected,this.latestJoinResponse)}else s===ot.FAILED&&(this.pcState===wi.Connected||this.pcState===wi.Reconnecting)&&(this.pcState=wi.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?vs.RR_SUBSCRIBER_FAILED:vs.RR_PUBLISHER_FAILED));const o=this.client.isDisconnected||this.client.currentState===Je.RECONNECTING,c=[ot.FAILED,ot.CLOSING,ot.CLOSED].includes(s);o&&c&&!this._isClosed&&this.emit(le.Offline)}),this.pcManager.onTrack=s=>{s.streams.length!==0&&this.emit(le.MediaTrackAdded,s.track,s.streams[0],s.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>O(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i}),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>O(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid}),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),{cid:e.cid});return}const i=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(le.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(le.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(le.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(le.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(le.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(le.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(le.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(le.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(le.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",vs.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info("client leave request received (action=".concat(e==null?void 0:e.action,")"),{reason:e==null?void 0:e.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(le.ServerRegionsReported,e.regions)),e.action){case ir.DISCONNECT:this.emit(le.Disconnected,e==null?void 0:e.reason),this.close();break;case ir.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Td);break;case ir.RESUME:this.handleDisconnect(Td)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((((t=this.signalOpts)===null||t===void 0?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!_a())&&td()&&(this.log.debug("E2EE - setting up transports with insertable streams"),i.encodedInsertableStreams=!0),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",!e)return i;if(e.iceServers&&!i.iceServers){const r=[];e.iceServers.forEach(a=>{const o={urls:a.urls};a.username&&(o.username=a.username),a.credential&&(o.credential=a.credential),r.push(o)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===la.ENABLED&&(i.iceTransportPolicy="relay"),i}applyInitialPublisherLayout(){this.createDataChannels(),Fi()||this.addMediaSections(VE,jE)}addMediaSections(e,t){var i,s;const r={direction:"recvonly"};for(let a=0;a<e;a++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("audio",r);for(let a=0;a<t;a++)(s=this.pcManager)===null||s===void 0||s.addPublisherTransceiverOfKind("video",r)}createDataChannels(){this.pcManager&&this.dataChannels.createPublisherChannels(this.pcManager)}decodeDataMessage(e){return O(this,void 0,void 0,function*(){if(e.data instanceof ArrayBuffer)return new Uint8Array(e.data);if(e.data instanceof Blob)return new Uint8Array(yield e.data.arrayBuffer());this.log.error("unsupported data type",{data:e.data})})}createSender(e,t,i){return O(this,void 0,void 0,function*(){let s;if($u())s=yield this.createTransceiverRTCRtpSender(e,t,i);else if(Wu())this.log.warn("using add-track fallback"),s=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new st("Required webRTC APIs not supported on this device");return this.setupFrameMetadataSender(s,t),s})}createSimulcastSender(e,t,i,s){return O(this,void 0,void 0,function*(){let r;if($u())r=yield this.createSimulcastTransceiverSender(e,t,i,s);else if(Wu())this.log.debug("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new st("Cannot stream on this device");return r&&this.setupFrameMetadataSender(r,i),r})}get frameMetadataWorker(){var e,t;return(t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer)===null||t===void 0?void 0:t.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,s,r;const a=this.frameMetadataWorker;if(!a||!((i=this.signalOpts)===null||i===void 0)&&i.e2eeEnabled)return;const o=(s=t.frameMetadata)!==null&&s!==void 0?s:t.packetTrailer,c=oc(o);if(_a()){c&&(e.transform=new RTCRtpScriptTransform(a,{kind:"encode",packetTrailer:o}));return}if(!Sa((r=this.options.frameMetadata)!==null&&r!==void 0?r:this.options.packetTrailer)||!("createEncodedStreams"in e)){c&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext);return}const l=e.createEncodedStreams(),u=l.readable,h=l.writable;c?a.postMessage({kind:"encode",data:{readableStream:u,writableStream:h,packetTrailer:o}},[u,h]):u.pipeTo(h)}createTransceiverRTCRtpSender(e,t,i){return O(this,void 0,void 0,function*(){if(!this.pcManager)throw new st("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Dn(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,s){return O(this,void 0,void 0,function*(){if(!this.pcManager)throw new st("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return O(this,void 0,void 0,function*(){if(!this.pcManager)throw new st("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return O(this,void 0,void 0,function*(){var t,i,s;if(!this._isClosed){if(this.attemptingReconnect){this.log.warn("already attempting reconnect, returning early");return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===la.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:ot.NEW)===ot.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let a=!0;r instanceof st?(this.log.debug("received unrecoverable error",{error:r}),a=!1):r instanceof sr||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",vs.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(le.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",{error:t})}return null}restartConnection(e){return O(this,void 0,void 0,function*(){var t,i,s;try{if(!this.url||!this.token)throw new st("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(le.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present"),new sr;r=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(a){throw a instanceof Se&&a.reason===He.NotAllowed?new st("could not reconnect, token might be expired"):new sr}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(le.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==Je.CONNECTED)throw new sr("Signal connection got severed during reconnect");(t=this.regionStrategy)===null||t===void 0||t.resetAttempts(),this.emit(le.Restarted)}catch(r){const a=yield(i=this.regionStrategy)===null||i===void 0?void 0:i.getNextUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionStrategy)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return O(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new st("could not reconnect, url or token not saved");if(!this.pcManager)throw new st("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(le.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,{error:s})),s instanceof Se&&s.reason===He.NotAllowed?new st("could not reconnect, token might be expired"):s instanceof Se&&s.reason===He.LeaveRequest?s:new sr(r)}if(this.emit(le.SignalResumed),t){const s=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(s),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Je.CONNECTED)throw new sr("Signal connection got severed during reconnect");this.client.setReconnected();const i=this.dataChannelForKind(Re.RELIABLE);(i==null?void 0:i.readyState)==="open"&&i.id===null&&this.createDataChannels(),t!=null&&t.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq).catch(s=>{this.log.warn("failed to resend reliable messages after resume",Object.assign(Object.assign({},this.logContext),{error:s}))}),this.emit(le.Resumed)})}waitForPCInitialConnection(e,t){return O(this,void 0,void 0,function*(){if(!this.pcManager)throw new st("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return O(this,void 0,void 0,function*(){this.pcState=wi.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield Vt(BE),!this.pcManager)throw new st("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=wi.Connected}catch(e){throw this.pcState=wi.Disconnected,Se.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcAck(e,t){return O(this,void 0,void 0,function*(){const i=new Kt({destinationIdentities:[e],kind:Kn.RELIABLE,value:{case:"rpcAck",value:new Wo({requestId:t})}});yield this.sendDataPacket(i,Re.RELIABLE)})}sendDataPacket(e,t){return O(this,void 0,void 0,function*(){var i,s;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const o=Fk(e);if(o){const c=yield this.e2eeManager.encryptData(o.toBinary());e.value={case:"encryptedPacket",value:new Ep({encryptedValue:c.payload,iv:c.iv,keyIndex:c.keyIndex})}}}t===Re.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());const r=e.toBinary(),a=Math.min((s=(i=this.pcManager)===null||i===void 0?void 0:i.getMaxPublisherMessageSize())!==null&&s!==void 0?s:jg,jg);if(typeof a<"u"&&a!==0&&r.byteLength>a)throw new XC("cannot publish data packet larger than ".concat(a," bytes (got ").concat(r.byteLength,")"));t===Re.RELIABLE?yield this.reliableChannel.send(r,e.sequence):yield this.lossyChannel.send(r)})}sendDataTrackFrame(e){return O(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Re.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)})}resendReliableMessagesForResume(e){return O(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Re.RELIABLE),yield this.reliableChannel.replay(e)})}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return O(this,void 0,void 0,function*(){return this.flowControlFor(e).waitForHeadroomWithLock()})}ensureDataTransportConnected(e){return O(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!i.pcManager)throw new st("PC manager is closed");const a=s?i.pcManager.subscriber:i.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw Se.internal("".concat(o," connection not set"));let c=!1;!s&&!i.dataChannelForKind(t,s)&&(i.createDataChannels(),c=!0),!c&&!s&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate().catch(h=>{i.log.error(h)});const l=i.dataChannelForKind(t,s);if((l==null?void 0:l.readyState)==="open")return;const u=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<u;){if(a.isICEConnected&&((r=i.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield Vt(50)}throw Se.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return O(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![ot.CONNECTING,ot.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return O(this,void 0,void 0,function*(){return new Xt((e,t)=>O(this,void 0,void 0,function*(){if(!this.pcManager){t(new Ss("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.dataChannels.hasPublisherChannels&&this.createDataChannels();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new Ss("cannot negotiate on closed engine")),this.on(le.Closing,s),this.on(le.Restarting,s),this.pcManager.publisher.off(Zn.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(Zn.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(i),e()}catch(r){if(i.signal.aborted){e();return}r instanceof Ss&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",vs.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(le.Closing,s),this.off(le.Restarting,s)}}))})}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}sendSyncState(e,t,i){var s,r,a,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup");return}const c=this.pcManager.publisher.getLocalDescription(),l=this.pcManager.publisher.getRemoteDescription(),u=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getRemoteDescription(),h=(r=this.pcManager.subscriber)===null||r===void 0?void 0:r.getLocalDescription(),p=(o=(a=this.signalOpts)===null||a===void 0?void 0:a.autoSubscribe)!==null&&o!==void 0?o:!0,y=new Array,_=new Array;e.forEach(b=>{b.isDesired!==p&&y.push(b.trackSid),b.isEnabled||_.push(b.trackSid)}),this.client.sendSyncState(new _u({answer:this.pcManager.mode==="publisher-only"?l?As({sdp:l.sdp,type:l.type}):void 0:h?As({sdp:h.sdp,type:h.type}):void 0,offer:this.pcManager.mode==="publisher-only"?c?As({sdp:c.sdp,type:c.type}):void 0:u?As({sdp:u.sdp,type:u.type}):void 0,subscription:new Xo({trackSids:y,subscribe:!p,participantTracks:[]}),publishTracks:ik(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:_,datachannelReceiveStates:this.reliableReceivedState.map((b,S)=>new Xp({publisherSid:S,lastSeq:b})),publishDataTracks:i.map(b=>new mu({info:lc.toProtobuf(b)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new Yp({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(Re.LOSSY),Ni.PUBLISHER),t(this.dataChannelForKind(Re.RELIABLE),Ni.PUBLISHER),t(this.dataChannelForKind(Re.LOSSY,!0),Ni.SUBSCRIBER),t(this.dataChannelForKind(Re.RELIABLE,!0),Ni.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&ht.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){oi()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){oi()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(i){const s=Object.entries(this.midToTrackId).find(r=>_e(r,1)[0]===i);if(s)return s[1]}}}function Hg(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}const pc=Nt(yt.Region),_d=5e3,$E=3e4;class Ue{static fetchRegionSettings(e,t,i){return O(this,void 0,void 0,function*(){const s=yield Ue.fetchLock.lock();try{const r=yield fetch("".concat(WE(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(r.ok){const a=wk(r.headers),o=a?a*1e3:_d;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw r.status===401?Se.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):Se.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof Se?r:i!=null&&i.aborted?Se.cancelled("Region fetching was aborted"):Se.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,i){return O(this,void 0,void 0,function*(){const s=Ue.settingsTimeouts.get(e.hostname);clearTimeout(s),Ue.settingsTimeouts.set(e.hostname,setTimeout(()=>O(this,void 0,void 0,function*(){try{const r=yield Ue.fetchRegionSettings(e,t);Ue.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof Se&&r.reason===He.NotAllowed){pc.debug("token is not valid, cancelling auto region refresh");return}pc.debug("auto refetching of region settings failed",{error:r}),Ue.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){Ue.cache.set(e.hostname,i),Ue.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=Ue.settingsTimeouts.get(e);t&&(clearTimeout(t),Ue.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=Ue.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=Ue.connectionTrackers.get(e);i&&i.connectionCount===0&&(pc.debug("stopping region refetch after disconnect delay",{hostname:e}),Ue.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},$E))}static cancelCleanup(e){const t=Ue.connectionTrackers.get(e);t!=null&&t.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=Ue.connectionTrackers.get(e);t||(t={connectionCount:0},Ue.connectionTrackers.set(e,t)),t.connectionCount++,Ue.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=Ue.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&Ue.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;const i=this.getServerUrl(),s=Ue.cache.get(i.hostname);Ue.scheduleRefetch(this.serverUrl,this.token,(t=s==null?void 0:s.maxAgeInMs)!==null&&t!==void 0?t:_d)}isCloud(){return or(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return O(this,void 0,void 0,function*(){return Ue.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return O(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=Ue.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),Ue.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(i.length>0){const s=i[0];return this.attemptedRegions.push(s),pc.info("switching to region: ".concat(s.region),{region:s.region}),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Ue.updateCachedRegionSettings(this.serverUrl,this.token,e)}}Ue.cache=new Map,Ue.settingsTimeouts=new Map,Ue.connectionTrackers=new Map,Ue.fetchLock=new Dt;function WE(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}function Sd(){return new CompressionStream("deflate-raw")}function $g(){return new DecompressionStream("deflate-raw")}function Wg(n,e){return O(this,void 0,void 0,function*(){const t=new DecompressionStream("deflate-raw"),i=t.writable.getWriter();return i.write(n).catch(()=>{}),i.close().catch(()=>{}),zg(t.readable,e)})}function zg(n,e){return O(this,void 0,void 0,function*(){const t=n.getReader(),i=[];let s=0;for(;;){const o=yield t.read(),c=o.done,l=o.value;if(c)break;if(i.push(l),s+=l.byteLength,typeof e=="number"&&s>e)throw yield t.cancel(),new Et("Decompressed payload exceeds the maximum payload size of ".concat(e," bytes"),dt.PayloadTooLarge)}const r=new Uint8Array(s);let a=0;for(const o of i)r.set(o,a),a+=o.byteLength;return r})}const Ds=15e3,zE=5e9;class Gg{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new Et("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),dt.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Et("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),dt.LengthExceeded)}}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class Kg extends Gg{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>O(this,void 0,void 0,function*(){var i;try{const s=this.signal;if(s!=null&&s.aborted)throw s.reason;const r=yield new Promise((a,o)=>{if(s){const c=()=>o(s.reason);s.addEventListener("abort",c,{once:!0}),e.read().then(a,o).finally(()=>{s.removeEventListener("abort",c)})}else e.read().then(a,o)});return r.done?(this.validateBytesReceived(!0),typeof this.totalByteSize=="number"&&((i=this.onProgress)===null||i===void 0||i.call(this,1)),{done:!0,value:void 0}):(this.handleChunkReceived(r.value),{done:!1,value:r.value.content})}catch(s){throw t(),s}}),return(){return O(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return O(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,u=ki(c),h;h=yield u.next(),i=h.done,!i;l=!0){a=h.value,l=!1;const p=a;o.add(p)}}catch(p){s={error:p}}finally{try{!l&&!i&&(r=u.return)&&(yield r.call(u))}finally{if(s)throw s.error}}return Array.from(o)})()})}}class Xg extends Gg{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Es(e.chunkIndex),s=this.receivedChunks.get(i);if(s&&s.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=new TextDecoder("utf-8",{fatal:!0}),i=this.signal,s=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>O(this,void 0,void 0,function*(){var r;try{if(i!=null&&i.aborted)throw i.reason;const a=yield new Promise((o,c)=>{if(i){const l=()=>c(i.reason);i.addEventListener("abort",l,{once:!0}),e.read().then(o,c).finally(()=>{i.removeEventListener("abort",l)})}else e.read().then(o,c)});if(a.done)return this.validateBytesReceived(!0),typeof this.totalByteSize=="number"&&((r=this.onProgress)===null||r===void 0||r.call(this,1)),{done:!0,value:void 0};{this.handleChunkReceived(a.value);let o;try{o=t.decode(a.value.content)}catch(c){throw new Et("Cannot decode datastream chunk ".concat(a.value.chunkIndex," as text: ").concat(c),dt.DecodeFailed)}return{done:!1,value:o}}}catch(a){throw s(),a}}),return(){return O(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return O(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,u=ki(c),h;h=yield u.next(),i=h.done,!i;l=!0)a=h.value,l=!1,o+=a}catch(p){s={error:p}}finally{try{!l&&!i&&(r=u.return)&&(yield r.call(u))}finally{if(s)throw s.error}}return o})()})}}class GE{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:zE;this.log=xe,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=e}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const t of e){const i=t.packet,s=t.encryptionType;this.handleDataStreamPacket(i,s)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Et('A text stream handler for topic "'.concat(e,'" has already been set.'),dt.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Et('A byte stream handler for topic "'.concat(e,'" has already been set.'),dt.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){const t=Array.from(this.textStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e),i=Array.from(this.byteStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e);if(t.length>0||i.length>0){const a=new Et("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),dt.AbnormalEnd);for(const o of i){var s=_e(o,2);const c=s[0];s[1].controller.error(a),this.byteStreamControllers.delete(c)}for(const o of t){var r=_e(o,2);const c=r[0];r[1].controller.error(a),this.textStreamControllers.delete(c)}}}handleDataStreamPacket(e,t){if(!this.isConnected){this.bufferedPackets.push({packet:e,encryptionType:t});return}switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}}handleStreamHeader(e,t,i){var s;switch(e.contentHeader.case){case"byteHeader":{const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Es(e.timestamp),attributes:e.attributes,encryptionType:i};let c;switch(e.compression){case qt.DEFLATE_RAW:if(!Yn()){xe.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));return}c=!0;break;case qt.NONE:c=!1;break;default:xe.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}const l=e.inlineContent;if(typeof l<"u"){r(new Kg(o,Yg(e.streamId,c?Wg(l,this.maxPayloadByteLength):l),Es(e.totalLength)),{identity:t});return}const u=new ReadableStream({start:h=>{if(a=h,this.byteStreamControllers.has(e.streamId))throw new Et("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),dt.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new Kg(o,c?YE(u,e.streamId,this.maxPayloadByteLength):u,Es(e.totalLength)),{identity:t});return}case"textHeader":{const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds};let c;switch(e.compression){case qt.DEFLATE_RAW:if(!Yn()){xe.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));return}c=!0;break;case qt.NONE:c=!1;break;default:xe.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}const l=e.inlineContent;if(typeof l<"u"){const h=c?Wg(l,this.maxPayloadByteLength):l;r(new Xg(o,Yg(e.streamId,h),Es(e.totalLength)),{identity:t});return}const u=new ReadableStream({start:h=>{if(a=h,this.textStreamControllers.has(e.streamId))throw new Et("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),dt.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new Xg(o,c?QE(u,e.streamId,this.maxPayloadByteLength):u,Es(e.totalLength)),{identity:t});return}}}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Et("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),dt.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new Et("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),dt.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Et("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),dt.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),e.reason?i.controller.error(new Et("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),dt.AbnormalEnd)):i.controller.close()),this.textStreamControllers.delete(e.streamId));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new Et("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),dt.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),e.reason?s.controller.error(new Et("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),dt.AbnormalEnd)):s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}function Yg(n,e){return new ReadableStream({start:t=>O(this,void 0,void 0,function*(){try{const i=yield e;t.enqueue(new En({streamId:n,chunkIndex:BigInt(0),content:i})),t.close()}catch(i){t.error(i)}})})}function Qg(n){let e=-1;return new TransformStream({transform:(t,i)=>{const s=Es(t.chunkIndex);if(s<=e){xe.warn("ignoring duplicate chunk ".concat(s," for compressed data stream ").concat(n," (last processed: ").concat(e,")"));return}if(s>e+1)throw new Et("Missing chunk(s) ".concat(e+1,"..").concat(s-1," for compressed data stream ").concat(n," - cannot continue decompressing"),dt.Incomplete);e=s,i.enqueue(t)}})}function Jg(){return new TransformStream({transform:(n,e)=>{e.enqueue(n.content)}})}function KE(n){let e=0;return new TransformStream({transform:(t,i)=>{t.byteLength>0&&(i.enqueue(new En({streamId:n,chunkIndex:Ui(e),content:t})),e+=1)}})}function XE(n){const e=new TextDecoder("utf-8",{fatal:!0}),t=new TextEncoder;let i=0;const s=r=>{try{return r?e.decode(r,{stream:!0}):e.decode()}catch(a){throw new Et("Cannot decode compressed data stream ".concat(n," as text: ").concat(a),dt.DecodeFailed)}};return new TransformStream({transform:(r,a)=>{const o=s(r);o.length>0&&(a.enqueue(new En({streamId:n,chunkIndex:Ui(i),content:t.encode(o)})),i+=1)},flush:r=>{const a=s();a.length>0&&(r.enqueue(new En({streamId:n,chunkIndex:Ui(i),content:t.encode(a)})),i+=1)}})}function YE(n,e,t){return n.pipeThrough(Qg(e)).pipeThrough(Jg()).pipeThrough($g()).pipeThrough(Zg(e,t)).pipeThrough(KE(e))}function QE(n,e,t){return n.pipeThrough(Qg(e)).pipeThrough(Jg()).pipeThrough($g()).pipeThrough(Zg(e,t)).pipeThrough(XE(e))}function Zg(n,e){let t=0;return new TransformStream({transform:(i,s)=>{if(t+=i.byteLength,t>e)throw new Et("Data stream ".concat(n," exceeds the maximum payload size of ").concat(e," bytes"),dt.PayloadTooLarge);s.enqueue(i)}})}class e0{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return O(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class JE extends e0{}class ZE extends e0{}function Cd(n,e,t){var i;return new zo({streamId:n.id,mimeType:n.mimeType,topic:n.topic,timestamp:Ui(n.timestamp),totalLength:Ui(n.size),attributes:n.attributes,compression:(i=t==null?void 0:t.compression)!==null&&i!==void 0?i:qt.NONE,inlineContent:t==null?void 0:t.inlineContent,contentHeader:{case:"textHeader",value:new Up({version:e==null?void 0:e.version,attachedStreamIds:n.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?uu.UPDATE:uu.CREATE})}})}function mc(n,e){var t;return new zo({streamId:n.id,mimeType:n.mimeType,topic:n.topic,timestamp:Ui(n.timestamp),totalLength:Ui(n.size),attributes:n.attributes,compression:(t=e==null?void 0:e.compression)!==null&&t!==void 0?t:qt.NONE,inlineContent:e==null?void 0:e.inlineContent,contentHeader:{case:"byteHeader",value:new Bp({name:n.name})}})}function Ps(n,e){return new Kt({destinationIdentities:e,value:{case:"streamHeader",value:n}})}const e2=new TextEncoder;class t2{constructor(e,t,i,s,r){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=i,this.getRemoteParticipantCapabilities=s,this.getAllRemoteParticipantIdentities=r}setupEngine(e){this.engine=e}sendText(e,t){return O(this,void 0,void 0,function*(){var i,s,r,a,o;const c=crypto.randomUUID(),l=e2.encode(e),u=l.byteLength,h=(i=t==null?void 0:t.compress)!==null&&i!==void 0?i:!0;let p={id:c,mimeType:"text/plain",timestamp:Date.now(),topic:(s=t==null?void 0:t.topic)!==null&&s!==void 0?s:"",size:u,attributes:t==null?void 0:t.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?Ve.GCM:Ve.NONE},_=h&&Yn()&&this.allRecipientsSupportV2(t==null?void 0:t.destinationIdentities)&&this.allRecipientsSupportCompression(t==null?void 0:t.destinationIdentities)?gc.fromStream(ac(l).pipeThrough(Sd())):null;if((!(t!=null&&t.attachments)||t.attachments.length===0)&&this.allRecipientsSupportV2(t==null?void 0:t.destinationIdentities)){let w=l,P=qt.NONE;if(_){const N=yield _.collect();N.byteLength<l.byteLength&&(w=N,P=qt.DEFLATE_RAW)}const L=Cd(p,void 0,{compression:P,inlineContent:w}),C=Ps(L,t==null?void 0:t.destinationIdentities);if(C.toBinary().byteLength<=Ds)return yield this.engine.sendDataPacket(C,Re.RELIABLE),(a=t==null?void 0:t.onProgress)===null||a===void 0||a.call(t,1),p}const S=(o=t==null?void 0:t.attachments)===null||o===void 0?void 0:o.map(()=>crypto.randomUUID()),D=S?S.length+1:1,I=new Array(D).fill(0),F=(w,P)=>{var L;I[P]=w,(L=t==null?void 0:t.onProgress)===null||L===void 0||L.call(t,I.reduce((C,N)=>C+N,0)/D)};if(_){p.attachedStreamIds=S;const w=Cd(p,void 0,{compression:qt.DEFLATE_RAW}),P=Ps(w,t==null?void 0:t.destinationIdentities);yield this.sendChunkedByteStream(P,c,t==null?void 0:t.destinationIdentities,_.stream().pipeThrough(kd(l.length,L=>F(L,0)))),l.length===0&&F(1,0)}else{const w=yield this.streamText({streamId:c,totalSize:u,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:S,attributes:t==null?void 0:t.attributes});yield w.write(e),F(1,0),yield w.close(),p=w.info}return t!=null&&t.attachments&&S&&(yield Promise.all(t.attachments.map((w,P)=>O(this,void 0,void 0,function*(){return this._sendFile(S[P],w,{topic:t.topic,mimeType:w.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:L=>{F(L,P+1)}})})))),p})}sendBytes(e,t){return O(this,void 0,void 0,function*(){var i,s,r,a,o,c,l;const u=crypto.randomUUID(),h=t==null?void 0:t.destinationIdentities,p=(i=t==null?void 0:t.compress)!==null&&i!==void 0?i:!0,y={id:u,name:(s=t==null?void 0:t.name)!==null&&s!==void 0?s:"unknown",mimeType:(r=t==null?void 0:t.mimeType)!==null&&r!==void 0?r:"application/octet-stream",timestamp:Date.now(),topic:(a=t==null?void 0:t.topic)!==null&&a!==void 0?a:"",size:e.byteLength,attributes:t==null?void 0:t.attributes,encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?Ve.GCM:Ve.NONE},_=kd(e.length,t==null?void 0:t.onProgress);let S=p&&Yn()&&this.allRecipientsSupportV2(h)&&this.allRecipientsSupportCompression(h)?gc.fromStream(ac(e).pipeThrough(_).pipeThrough(Sd())):null;if(this.allRecipientsSupportV2(h)){let w=e,P=qt.NONE;if(S){const N=yield S.collect();N.byteLength<e.byteLength&&(w=N,P=qt.DEFLATE_RAW)}const L=mc(y,{compression:P,inlineContent:w}),C=Ps(L,h);if(C.toBinary().byteLength<=Ds)return yield this.engine.sendDataPacket(C,Re.RELIABLE),(c=t==null?void 0:t.onProgress)===null||c===void 0||c.call(t,1),y}const D=mc(y,{compression:S?qt.DEFLATE_RAW:qt.NONE}),I=Ps(D,h),F=S?S.stream():ac(e).pipeThrough(_);return yield this.sendChunkedByteStream(I,u,h,F),e.length===0&&((l=t==null?void 0:t.onProgress)===null||l===void 0||l.call(t,1)),y})}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(i=>this.getRemoteParticipantClientProtocol(i)>=$m)}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(i=>this.getRemoteParticipantCapabilities(i).includes(ua.CAP_COMPRESSION_DEFLATE_RAW))}sendChunkedByteStream(e,t,i,s){return O(this,void 0,void 0,function*(){var r,a,o,c;const l=this.engine;yield Ed(l,e);let u=0;try{for(var h=!0,p=ki(xk(s,Ds)),y;y=yield p.next(),r=y.done,!r;h=!0){c=y.value,h=!1;const _=c,b=new Kt({destinationIdentities:i,value:{case:"streamChunk",value:new En({content:_,streamId:t,chunkIndex:Ui(u)})}});yield l.sendDataPacket(b,Re.RELIABLE),u+=1}}catch(_){a={error:_}}finally{try{!h&&!r&&(o=p.return)&&(yield o.call(p))}finally{if(a)throw a.error}}yield xd(t,i,l)})}streamText(e){return O(this,void 0,void 0,function*(){var t,i,s;const r=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e==null?void 0:e.destinationIdentities,o={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?Ve.GCM:Ve.NONE,attachedStreamIds:e==null?void 0:e.attachedStreamIds},c=Cd(o,e),l=Ps(c,a);yield Ed(this.engine,l);let u=0;const h=this.engine,p=new WritableStream({write(b){return O(this,void 0,void 0,function*(){for(const S of Ek(b,Ds)){const D=new En({content:S,streamId:r,chunkIndex:Ui(u)}),I=new Kt({destinationIdentities:a,value:{case:"streamChunk",value:D}});yield h.sendDataPacket(I,Re.RELIABLE),u+=1}})},close(){return O(this,void 0,void 0,function*(){yield xd(r,a,h)})},abort(b){console.log("Sink error:",b)}});let y=()=>O(this,void 0,void 0,function*(){yield _.close()});h.once(le.Closing,y);const _=new JE(p,o,()=>this.engine.off(le.Closing,y));return _})}sendFile(e,t){return O(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return O(this,void 0,void 0,function*(){var s,r,a,o,c;const l=i==null?void 0:i.destinationIdentities,u=((s=i==null?void 0:i.compress)!==null&&s!==void 0?s:!0)&&Yn()&&this.allRecipientsSupportV2(l)&&this.allRecipientsSupportCompression(l),h={id:e,name:t.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:t.type,topic:(a=i==null?void 0:i.topic)!==null&&a!==void 0?a:"",timestamp:Date.now(),size:t.size,encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?Ve.GCM:Ve.NONE},p=mc(h,{compression:u?qt.DEFLATE_RAW:qt.NONE}),y=Ps(p,l),_=t.stream().pipeThrough(kd(t.size,i==null?void 0:i.onProgress)),b=u?_.pipeThrough(Sd()):_;return yield this.sendChunkedByteStream(y,e,l,b),t.size===0&&((c=i==null?void 0:i.onProgress)===null||c===void 0||c.call(i,1)),h})}streamBytes(e){return O(this,void 0,void 0,function*(){var t,i,s,r,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,l={id:o,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(s=e==null?void 0:e.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(r=e==null?void 0:e.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?Ve.GCM:Ve.NONE},u=mc(l),h=Ps(u,c);yield Ed(this.engine,h);let p=0;const y=new Dt,_=this.engine,b=this.log,S=new WritableStream({write(I){return O(this,void 0,void 0,function*(){const F=yield y.lock();let w=0;try{for(;w<I.byteLength;){const P=I.slice(w,w+Ds),L=new Kt({destinationIdentities:c,value:{case:"streamChunk",value:new En({content:P,streamId:o,chunkIndex:Ui(p)})}});yield _.sendDataPacket(L,Re.RELIABLE),p+=1,w+=P.byteLength}}finally{F()}})},close(){return O(this,void 0,void 0,function*(){yield xd(o,c,_)})},abort(I){b.error("Sink error:",I)}});return new ZE(S,l)})}}class gc{constructor(e){this.state=e}static fromStream(e){return new gc({type:"stream",stream:e})}collect(){return O(this,void 0,void 0,function*(){switch(this.state.type){case"stream":const e=yield zg(this.state.stream);return this.state={type:"collected",bytes:e},e;case"collected":return this.state.bytes}})}stream(){switch(this.state.type){case"stream":return this.state.stream;case"collected":return ac(this.state.bytes)}}}function kd(n,e){let t=0;return new TransformStream({transform(i,s){t+=i.byteLength,e&&typeof n=="number"&&n>0&&e(Math.min(t/n,1)),s.enqueue(i)}})}function Ed(n,e){return O(this,void 0,void 0,function*(){if(e.toBinary().byteLength>Ds)throw new Et("data stream header exceeds the ".concat(Ds,"-byte limit; reduce attribute size"),dt.HeaderTooLarge);yield n.sendDataPacket(e,Re.RELIABLE)})}function xd(n,e,t){return O(this,void 0,void 0,function*(){const i=new Kt({destinationIdentities:e,value:{case:"streamTrailer",value:new du({streamId:n})}});yield t.sendDataPacket(i,Re.RELIABLE)})}function t0(n){if(n.length===0)return new AbortController().signal;if(n.length===1)return n[0];for(const s of n)if(s.aborted)return s;const e=new AbortController,t=Array(n.length),i=()=>{for(const s of t)s()};return n.forEach((s,r)=>{const a=()=>{e.abort(s.reason),i()};s.addEventListener("abort",a),t[r]=()=>s.removeEventListener("abort",a)}),e.signal}function i0(n){const e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("signal timed out after ".concat(n," ms"),"TimeoutError"))},n),e.signal}const ft=1,In=2,n0=4,i2=8,s0=0,r0=12,a0=5,n2=7,o0=3,s2=3,c0=2,l0=1,u0=0,d0=3,yc=2,h0=2,r2=1,a2=0;var Rn;(function(n){n[n.TooShort=0]="TooShort",n[n.HeaderOverrun=1]="HeaderOverrun",n[n.MissingExtWords=2]="MissingExtWords",n[n.UnsupportedVersion=3]="UnsupportedVersion",n[n.InvalidHandle=4]="InvalidHandle",n[n.MalformedExt=5]="MalformedExt"})(Rn||(Rn={}));class Qt extends Ei{constructor(e,t,i){super(19,e,i),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=Rn[t]}static tooShort(){return new Qt("Too short to contain a valid header",Rn.TooShort)}static headerOverrun(){return new Qt("Header exceeds total packet length",Rn.HeaderOverrun)}static missingExtWords(){return new Qt("Extension word indicator is missing",Rn.MissingExtWords)}static unsupportedVersion(e){return new Qt("Unsupported version ".concat(e),Rn.UnsupportedVersion)}static invalidHandle(e){return new Qt("invalid track handle: ".concat(e.message),Rn.InvalidHandle,{cause:e})}static malformedExt(e){return new Qt("Extension with tag ".concat(e," is malformed"),Rn.MalformedExt)}}var xa;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(xa||(xa={}));class wa extends Ei{constructor(e,t,i){super(19,e,i),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=xa[t]}static tooSmallForHeader(){return new wa("Buffer cannot fit header",xa.TooSmallForHeader)}static tooSmallForPayload(){return new wa("Buffer cannot fit payload",xa.TooSmallForPayload)}}class vc{toBinary(){const e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),i=new DataView(t),s=this.toBinaryInto(i);if(e!==s)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(s," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}var fr;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(fr||(fr={}));class f0 extends vc{}class Vi extends f0{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return ft+ft+Vi.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,Vi.tag),t+=ft,e.setUint8(t,Vi.lengthBytes),t+=ft,e.setBigUint64(t,this.timestamp),t+=i2;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:Vi.tag,lengthBytes:Vi.lengthBytes,timestamp:this.timestamp}}}Vi.tag=fr.UserTimestamp,Vi.lengthBytes=8;class ji extends f0{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return ft+ft+ji.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,ji.tag),t+=ft,e.setUint8(t,ji.lengthBytes),t+=ft,e.setUint8(t,this.keyIndex),t+=ft;for(let s=0;s<this.iv.length;s+=1)e.setUint8(t,this.iv[s]),t+=ft;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:ji.tag,lengthBytes:ji.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}ji.tag=fr.E2ee,ji.lengthBytes=13;class pr extends vc{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){const s=this.e2ee.toBinaryInto(e);t+=s}if(this.userTimestamp){const s=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=s}const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}static fromBinary(e){const t=ld(e);let i,s,r=0;for(;t.byteLength-r>=ft+ft;){const a=t.getUint8(r);r+=ft;const o=t.getUint8(r);if(r+=ft,a!==a2)switch(a){case fr.UserTimestamp:if(t.byteLength-r<Vi.lengthBytes)throw Qt.malformedExt(a);i=new Vi(t.getBigUint64(r)),r+=o;break;case fr.E2ee:if(t.byteLength-r<ji.lengthBytes)throw Qt.malformedExt(a);const c=t.getUint8(r),l=new Uint8Array(12);for(let u=0;u<l.length;u+=1){let h=r;h+=ft,h+=u*ft,l[u]=t.getUint8(h)}s=new ji(c,l),r+=o;break;default:if(t.byteLength-r<o)throw Qt.malformedExt(a);r+=o;break}}return[new pr({userTimestamp:i,e2ee:s}),t.byteLength]}toJSON(){var e,t,i,s;return{userTimestamp:(t=(e=this.userTimestamp)===null||e===void 0?void 0:e.toJSON())!==null&&t!==void 0?t:null,e2ee:(s=(i=this.e2ee)===null||i===void 0?void 0:i.toJSON())!==null&&s!==void 0?s:null}}}const p0={from(n){return{payload:n.payload,extensions:new pr({userTimestamp:n.userTimestamp?new Vi(n.userTimestamp):void 0})}},lossyIntoFrame(n){var e;return{payload:n.payload,userTimestamp:(e=n.extensions.userTimestamp)===null||e===void 0?void 0:e.timestamp}}},m0=Symbol.for("lk.track"),g0=Symbol.for("lk.data-track");class y0{constructor(e,t,i){this.trackSymbol=m0,this.isLocal=!1,this.typeSymbol=g0,this.info=e,this.manager=t,this.publisherIdentity=i.publisherIdentity}subscribe(e){try{const t=this.manager.openSubscriptionStream(this.info.sid,e==null?void 0:e.signal,e==null?void 0:e.bufferSize),i=_e(t,2),s=i[0];return i[1].catch(()=>{}),s}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class Aa extends vc{constructor(e){var t;super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=(t=e.extensions)!==null&&t!==void 0?t:new pr}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((yc+e)/4),i=t*4-yc-e;return{lengthBytes:e,lengthWords:t,paddingLengthBytes:i}}toBinaryLengthBytes(){const e=this.extensionsMetrics(),t=e.lengthBytes,i=e.paddingLengthBytes;let s=r0;return t>0&&(s+=yc+t+i),s}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw wa.tooSmallForHeader();let t=s0<<a0,i;switch(this.marker){case rt.Inter:i=u0;break;case rt.Final:i=l0;break;case rt.Start:i=c0;break;case rt.Single:i=d0;break}t|=i<<o0;const s=this.extensionsMetrics(),r=s.lengthBytes,a=s.lengthWords,o=s.paddingLengthBytes;r>0&&(t|=1<<h0);let c=0;if(e.setUint8(c,t),c+=ft,e.setUint8(c,0),c+=ft,e.setUint16(c,this.trackHandle),c+=In,e.setUint16(c,this.sequence.value),c+=In,e.setUint16(c,this.frameNumber.value),c+=In,e.setUint32(c,this.timestamp.asTicks()),c+=n0,r>0){const u=a-1;e.setUint16(c,u),c+=In;const h=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+c));c+=h;for(let p=0;p<o;p+=1)e.setUint8(c,0),c+=ft}const l=this.toBinaryLengthBytes();if(c!==l)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(c," bytes but expected length was ").concat(l," bytes"));return l}static fromBinary(e){const t=ld(e);if(t.byteLength<r0)throw Qt.tooShort();let i=0;const s=t.getUint8(i);i+=ft;const r=s>>a0&n2;if(r>s0)throw Qt.unsupportedVersion(r);let a;switch(s>>o0&s2){case c0:a=rt.Start;break;case l0:a=rt.Final;break;case d0:a=rt.Single;break;case u0:default:a=rt.Inter;break}const o=(s>>h0&r2)>0;i+=ft;let c;try{c=Gk.fromNumber(t.getUint16(i))}catch(y){throw y instanceof hr&&(y.isReason(ws.Reserved)||y.isReason(ws.TooLarge))?Qt.invalidHandle(y):y}i+=In;const l=Bi.u16(t.getUint16(i));i+=In;const u=Bi.u16(t.getUint16(i));i+=In;const h=dr.fromRtpTicks(t.getUint32(i));i+=n0;let p=new pr;if(o){if(t.byteLength-i<In)throw Qt.missingExtWords();let y=t.getUint16(i);i+=In;let b=4*(y+1)-yc;if(i+b>t.byteLength)throw Qt.headerOverrun();let S=new DataView(t.buffer,t.byteOffset+i,b);const D=pr.fromBinary(S),I=_e(D,2),F=I[0],w=I[1];p=F,i+=w}return[new Aa({marker:a,trackHandle:c,sequence:l,frameNumber:u,timestamp:h,extensions:p}),i]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}var rt;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(rt||(rt={}));class bc extends vc{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0;const i=this.header.toBinaryInto(e);if(t+=i,e.byteLength-t<this.payload.byteLength)throw wa.tooSmallForPayload();for(let r=0;r<this.payload.length;r+=1)e.setUint8(t,this.payload[r]),t+=ft;const s=this.toBinaryLengthBytes();if(t!==s)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(s," bytes"));return s}static fromBinary(e){const t=ld(e),i=Aa.fromBinary(t),s=_e(i,2),r=s[0],a=s[1],o=t.buffer.slice(t.byteOffset+a,t.byteOffset+t.byteLength);return[new bc(r,new Uint8Array(o)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}const wd=Nt(yt.DataTracks);class an extends Ei{constructor(e,t,i,s){super(19,"Frame ".concat(i," dropped: ").concat(e),s),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=Is[t],this.frameNumber=i}static interrupted(e,t){return new an("Interrupted by the start of a new frame ".concat(t),Is.Interrupted,e)}static unknownFrame(e){return new an("Initial packet was never received.",Is.UnknownFrame,e)}static bufferFull(e){return new an("Reorder buffer is full.",Is.BufferFull,e)}static incomplete(e,t,i){return new an("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(i," packets."),Is.Incomplete,e)}}var Is;(function(n){n[n.Interrupted=0]="Interrupted",n[n.UnknownFrame=1]="UnknownFrame",n[n.BufferFull=2]="BufferFull",n[n.Incomplete=3]="Incomplete"})(Is||(Is={}));class Tc{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case rt.Single:return this.frameFromSingle(e,t);case rt.Start:return this.beginPartial(e,t);case rt.Inter:case rt.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){const e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var i;if(e.header.marker!==rt.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));const s=(i=t==null?void 0:t.maxPartialFrames)!==null&&i!==void 0?i:1;if(this.partials.size>=s){const r=this.peekOldestPartialFrameNumber();if(typeof r!="number")throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(r),t!=null&&t.throwOnInterruption)throw an.interrupted(r,e.header.frameNumber.value);wd.warn("Data track frame ".concat(r," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var i;if(e.header.marker!==rt.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));const s=e.header.sequence,r=e.header.frameNumber.value,a={startSequence:s,extensions:e.header.extensions,payloads:new Map([[s.value,e.payload]])},o=(i=t==null?void 0:t.maxPartialFrames)!==null&&i!==void 0?i:1;for(;this.partials.size>=o;){const c=this.peekOldestPartialFrameNumber();if(typeof c!="number")break;if(this.partials.delete(c),t!=null&&t.throwOnInterruption)throw an.interrupted(c,r);wd.warn("Data track partials full (max ".concat(o,"), evicted oldest frame ").concat(c," to make room for new frame ").concat(r,"."))}return this.partials.set(r,a),null}pushToPartial(e){if(e.header.marker!==rt.Inter&&e.header.marker!==rt.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));const t=e.header.frameNumber.value,i=this.partials.get(t);if(!i)throw this.partials.delete(t),an.unknownFrame(t);if(i.payloads.size>=Tc.MAX_BUFFER_PACKETS)throw this.partials.delete(t),an.bufferFull(t);return i.payloads.has(e.header.sequence.value)&&wd.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),i.payloads.set(e.header.sequence.value,e.payload),e.header.marker===rt.Final?this.finalize(t,i,e.header.sequence.value):null}finalize(e,t,i){const s=t.payloads.size;let r=0;for(const l of t.payloads.values())r+=l.length;const a=new Uint8Array(r);let o=t.startSequence.clone(),c=0;for(;;){const l=t.payloads.get(o.value);if(!l)break;t.payloads.delete(o.value);const u=a.length-c;if(l.length>u)throw new Error("Depacketizer.finalize: Expected at least ".concat(l.length," more bytes left in the payload buffer, only got ").concat(u," bytes."));if(a.set(l,c),c+=l.length,o.value!=i){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),an.incomplete(e,s,i-t.startSequence.value+1)}}Tc.MAX_BUFFER_PACKETS=128;var Rs;(function(n){n[n.Unpublished=0]="Unpublished",n[n.Timeout=1]="Timeout",n[n.Disconnected=2]="Disconnected",n[n.Cancelled=4]="Cancelled"})(Rs||(Rs={}));class ci extends Ei{constructor(e,t,i){super(22,e,i),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=Rs[t]}static unpublished(){return new ci("The track has been unpublished and is no longer available",Rs.Unpublished)}static timeout(){return new ci("Request to subscribe to data track timed-out",Rs.Timeout)}static disconnected(){return new ci("Cannot subscribe to data track when disconnected",Rs.Disconnected)}static cancelled(){return new ci("Subscription to data track cancelled by caller",Rs.Cancelled)}}const Ad=Nt(yt.DataTracks);class o2{constructor(e){var t,i;const s=e.e2eeManager!==null;if(e.info.usesE2ee!==s)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const r=new Tc;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=(t=e.e2eeManager)!==null&&t!==void 0?t:null,this.depacketizer=r,this.options=(i=e.pipelineOptions)!==null&&i!==void 0?i:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return O(this,void 0,void 0,function*(){const t=this.depacketize(e);if(!t)return null;const i=yield this.decryptIfNeeded(t);return i||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(i){return Ad.warn("Data frame depacketize error: ".concat(i)),null}return t}decryptIfNeeded(e){return O(this,void 0,void 0,function*(){var t,i;const s=this.e2eeManager;if(!s)return e;const r=(i=(t=e.extensions)===null||t===void 0?void 0:t.e2ee)!==null&&i!==void 0?i:null;if(!r)return Ad.error("Missing E2EE meta"),null;let a;try{a=yield s.handleEncryptedData(e.payload,r.iv,this.publisherIdentity,r.keyIndex)}catch(o){return Ad.error("Error decrypting packet: ".concat(o)),null}return e.payload=a.payload,e})}}const St=Nt(yt.DataTracks),c2=1e4,l2=16;class u2 extends ai.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=(t=e==null?void 0:e.e2eeManager)!==null&&t!==void 0?t:null}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())t.subscription.type==="active"&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){const i=this.descriptors.get(e);if(!i){St.warn("Unknown track ".concat(e,", cannot set pipeline options."));return}i.pipelineOptions=t,i.subscription.type==="active"&&i.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:l2,s=null;const r=new Ft,a=this.descriptors.get(e),o=()=>{t==null||t.removeEventListener("abort",l)},c=()=>{if(o(),!s){St.warn("ReadableStream subscribed to ".concat(e," was not started."));return}if(!a||this.descriptors.get(a.info.sid)!==a){St.warn("Unknown track ".concat(e,", skipping cancel..."));return}if(a.subscription.type!=="active"){St.warn("Subscription for track ".concat(e," is not active, skipping cancel..."));return}a.subscription.streamControllers.delete(s),a.subscription.streamControllers.size===0&&this.unSubscribeRequest(a.info.sid)},l=()=>{var h;s&&((a==null?void 0:a.subscription.type)==="active"&&a.subscription.streamControllers.delete(s),s.error(ci.cancelled()),(h=r.reject)===null||h===void 0||h.call(r,ci.cancelled()),c())};return[new ReadableStream({start:h=>{s=h,this.subscribeRequest(e,t).then(()=>O(this,void 0,void 0,function*(){var p,y,_;if(!a||this.descriptors.get(a.info.sid)!==a){St.error("Unknown track ".concat(e));const b=ci.disconnected();h.error(b),(p=r.reject)===null||p===void 0||p.call(r,b);return}if(a.subscription.type!=="active"){St.error("Subscription for track ".concat(e," is not active"));const b=ci.disconnected();h.error(b),(y=r.reject)===null||y===void 0||y.call(r,b);return}if(t!=null&&t.aborted){l();return}t==null||t.addEventListener("abort",l),a.subscription.streamControllers.set(h,o),(_=r.resolve)===null||_===void 0||_.call(r)})).catch(p=>{var y;h.error(p),(y=r.reject)===null||y===void 0||y.call(r,p)})},cancel:()=>{c()}},new CountQueuingStrategy({highWaterMark:i})),r.promise]}subscribeRequest(e,t){return O(this,void 0,void 0,function*(){const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");const s=(r,a,o)=>O(this,void 0,void 0,function*(){if(r.subscription.type==="active")return;if(r.subscription.type!=="pending")throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(r.subscription.type));const c=t0([a,o].filter(h=>typeof h<"u")),l=new Ft;r.subscription.completionFuture.promise.then(()=>{var h;return(h=l.resolve)===null||h===void 0?void 0:h.call(l)}).catch(h=>{var p;return(p=l.reject)===null||p===void 0?void 0:p.call(l,h)});const u=()=>{var h;if(r.subscription.type==="pending"){if(r.subscription.pendingRequestCount-=1,o!=null&&o.aborted){r.subscription.cancel();return}if(r.subscription.pendingRequestCount<=0){r.subscription.cancel();return}(h=l.reject)===null||h===void 0||h.call(l,ci.cancelled())}};c.aborted&&u(),c.addEventListener("abort",u),yield l.promise,c.removeEventListener("abort",u)});switch(i.subscription.type){case"none":{i.subscription={type:"pending",completionFuture:new Ft,pendingRequestCount:1,cancel:()=>{var a,o;const c=i.subscription;i.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:i.info.sid,subscribe:!1}),c.type==="pending"&&((o=(a=c.completionFuture).reject)===null||o===void 0||o.call(a,r.aborted?ci.timeout():ci.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const r=i0(c2);yield s(i,t,r);return}case"pending":{i.subscription.pendingRequestCount+=1,yield s(i,t);return}case"active":return}})}querySubscribed(){return O(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(t=>t.subscription.type==="active").map(t=>[t.info,t.publisherIdentity])})}unSubscribeRequest(e){var t;const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");if(i.subscription.type!=="active"){St.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat((t=i.subscription)===null||t===void 0?void 0:t.type));return}this.closeStreamControllers(i.subscription.streamControllers,e);const s=i.subscription;i.subscription={type:"none"},this.subscriptionHandles.delete(s.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(const s of e){var i=_e(s,2);const r=i[0],a=i[1];a();try{r.close()}catch(o){St.warn("Failed to close readable stream for track ".concat(t,": ").concat(o))}}}receiveSfuPublicationUpdates(e){return O(this,void 0,void 0,function*(){if(e.size===0)return;const t=new Map;for(const r of e.entries()){var i=_e(r,2);const a=i[0],o=i[1],c=new Set;for(const l of o)c.add(l.sid),!this.descriptors.has(l.sid)&&(this.handleSidReassigned(a,l)||(yield this.handleTrackPublished(a,l)));t.set(a,c)}for(const r of t.entries()){var s=_e(r,2);const a=s[0],o=s[1];let l=Array.from(this.descriptors.entries()).filter(u=>{let h=_e(u,2);return h[0],h[1].publisherIdentity===a}).map(u=>_e(u,1)[0]).filter(u=>!o.has(u));for(const u of l)this.handleTrackUnpublished(u)}})}queryPublications(){return O(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return O(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){St.error("Existing descriptor for track ".concat(t.sid));return}let i={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(i.info.sid,i);const s=new y0(i.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:s})})}handleSidReassigned(e,t){const i=Array.from(this.descriptors.entries()).find(h=>{let p=_e(h,2);p[0];let y=p[1];return y.publisherIdentity===e&&y.info.pubHandle===t.pubHandle});if(!i)return!1;const s=_e(i,2),r=s[0],a=s[1],o=a.info,c=o.name,l=o.usesE2ee;if(c!==t.name||l!==t.usesE2ee)return St.warn("Info mismatch for ".concat(r,", treating as new publication")),!1;const u=t.sid;if(St.debug("SID reassigned: ".concat(r," -> ").concat(u)),!this.descriptors.delete(r))return!1;switch(a.info.sid=u,a.subscription.type){case"none":break;case"pending":case"active":this.emit("sfuUpdateSubscription",{sid:u,subscribe:!0});break}return a.subscription.type==="active"&&this.subscriptionHandles.set(a.subscription.subcriptionHandle,u),this.descriptors.set(u,a),!0}handleTrackUnpublished(e){const t=this.descriptors.get(e);if(!t){St.error("Unknown track ".concat(e));return}this.descriptors.delete(e),t.subscription.type==="active"&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(const i of e.entries()){var t=_e(i,2);const s=t[0],r=t[1];this.registerSubscriberHandle(s,r)}}registerSubscriberHandle(e,t){var i,s;const r=this.descriptors.get(t);if(!r){St.error("Unknown track ".concat(t));return}switch(r.subscription.type){case"none":{St.warn("No subscription for ".concat(t));return}case"active":{this.subscriptionHandles.delete(r.subscription.subcriptionHandle),r.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return}case"pending":{St.debug("data track subscription activated",{sid:t,handle:e});const a=new o2({info:r.info,publisherIdentity:r.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:r.pipelineOptions}),o=r.subscription;r.subscription={type:"active",subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),(s=(i=o.completionFuture).resolve)===null||s===void 0||s.call(i)}}}packetReceived(e){return O(this,void 0,void 0,function*(){let t;try{var i=bc.fromBinary(e),s=_e(i,1);t=s[0]}catch(c){St.error("Failed to deserialize packet: ".concat(c));return}const r=this.subscriptionHandles.get(t.header.trackHandle);if(!r){St.warn("Unknown subscriber handle ".concat(t.header.trackHandle));return}const a=this.descriptors.get(r);if(!a){St.error("Missing descriptor for track ".concat(r));return}if(a.subscription.type!=="active"){St.warn("Received packet for track ".concat(r," without active subscription"));return}const o=yield a.subscription.pipeline.processPacket(t);if(o)for(const c of a.subscription.streamControllers.keys()){if(c.desiredSize!==null&&c.desiredSize<=0){St.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(c.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}const l=p0.lossyIntoFrame(o);c.enqueue(l)}})}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=_e(t,2);const i=e[0];e[1].subscription.type!=="none"&&this.emit("sfuUpdateSubscription",{sid:i,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,i;for(const s of this.descriptors.values())if(s.publisherIdentity===e)switch(s.subscription.type){case"none":break;case"pending":(i=(t=s.subscription.completionFuture).reject)===null||i===void 0||i.call(t,ci.disconnected());break;case"active":this.unSubscribeRequest(s.info.sid);break}}reset(){var e,t;for(const i of this.descriptors.values())this.emit("trackUnpublished",{sid:i.info.sid,publisherIdentity:i.publisherIdentity}),i.subscription.type==="pending"&&((t=(e=i.subscription.completionFuture).reject)===null||t===void 0||t.call(e,ci.disconnected())),i.subscription.type==="active"&&this.closeStreamControllers(i.subscription.streamControllers,i.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class _c extends Ei{constructor(e,t,i){super(19,e,i),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=Sc[t]}static mtuTooShort(){return new _c("MTU is too short to send frame",Sc.MtuTooShort)}}var Sc;(function(n){n[n.MtuTooShort=0]="MtuTooShort"})(Sc||(Sc={}));class Dd{constructor(e,t){this.sequence=Bi.u16(0),this.frameNumber=Bi.u16(0),this.clock=xs.rtpStartingNow(dr.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?rt.Single:e===0?rt.Start:e===t-1?rt.Final:rt.Inter}*packetize(e,t){var i;const s=this.frameNumber.getThenIncrement(),r={marker:rt.Inter,trackHandle:this.handle,sequence:Bi.u16(0),frameNumber:s,timestamp:(i=t==null?void 0:t.now)!==null&&i!==void 0?i:this.clock.now(),extensions:e.extensions},a=new Aa(r).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw _c.mtuTooShort();const o=this.mtuSizeBytes-a,c=Math.ceil(e.payload.byteLength/o);for(let u=0,h=0;h<e.payload.byteLength;l=[u+1,h+o],u=l[0],h=l[1],l){var l;const p=this.sequence.getThenIncrement(),y=new Aa(Object.assign(Object.assign({},r),{marker:Dd.computeFrameMarker(u,c),sequence:p})),_=Math.min(o,e.payload.byteLength-h),b=new Uint8Array(e.payload.buffer,e.payload.byteOffset+h,_);yield new bc(y,b)}}}var Hi;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.DuplicateName=1]="DuplicateName",n[n.Timeout=2]="Timeout",n[n.LimitReached=3]="LimitReached",n[n.Disconnected=4]="Disconnected",n[n.Cancelled=5]="Cancelled",n[n.InvalidName=6]="InvalidName",n[n.Unknown=7]="Unknown"})(Hi||(Hi={}));class xt extends Ei{constructor(e,t,i){super(21,e,i),this.name="DataTrackPublishError",this.reason=t,this.reasonName=Hi[t],this.rawMessage=i==null?void 0:i.rawMessage}static notAllowed(e){return new xt("Data track publishing unauthorized",Hi.NotAllowed,{rawMessage:e})}static duplicateName(e){return new xt("Track name already taken",Hi.DuplicateName,{rawMessage:e})}static invalidName(e){return new xt("Track name is invalid",Hi.InvalidName,{rawMessage:e})}static timeout(){return new xt("Publish data track timed-out. Does the LiveKit server support data tracks?",Hi.Timeout)}static limitReached(e){return new xt("Data track publication limit reached",Hi.LimitReached,{rawMessage:e})}static unknown(e,t){return new xt("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),Hi.Unknown)}static disconnected(){return new xt("Room disconnected",Hi.Disconnected)}static cancelled(){return new xt("Publish data track cancelled by caller",Hi.Cancelled)}}var Da;(function(n){n[n.TrackUnpublished=0]="TrackUnpublished",n[n.Dropped=1]="Dropped"})(Da||(Da={}));class es extends Ei{constructor(e,t,i){super(22,e,i),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=Da[t]}static trackUnpublished(){return new es("Track is no longer published",Da.TrackUnpublished)}static dropped(e){return new es("Frame was dropped",Da.Dropped,{cause:e})}}var Pa;(function(n){n[n.Packetizer=0]="Packetizer",n[n.Encryption=1]="Encryption"})(Pa||(Pa={}));class Ia extends Ei{constructor(e,t,i){super(21,e,i),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=Pa[t]}static packetizer(e){return new Ia("Error packetizing frame",Pa.Packetizer,{cause:e})}static encryption(e){return new Ia("Error encrypting frame",Pa.Encryption,{cause:e})}}class Cc{constructor(e,t){this.trackSymbol=m0,this.isLocal=!0,this.typeSymbol=g0,this.handle=null,this.log=xe,this.flushedFuture=new Ft,this.isFlushed=!0,this.handleManagerReset=()=>{var i,s;(s=(i=this.flushedFuture).resolve)===null||s===void 0||s.call(i),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=i=>{var s,r;this.isFlushed=i.isFlushed,i.isFlushed&&((r=(s=this.flushedFuture).resolve)===null||r===void 0||r.call(s),this.flushedFuture=new Ft)},this.options=e,this.manager=t,this.log=Nt(yt.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,i){const s=new Cc(e,t);return s.handle=i,s}get info(){const e=this.descriptor;if((e==null?void 0:e.type)==="active")return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return O(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(t){throw t}})}isPublished(){var e;return((e=this.descriptor)===null||e===void 0?void 0:e.type)==="active"&&this.descriptor.publishState!=="unpublished"}tryPush(e){if(!this.handle)throw es.trackUnpublished();const t=p0.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(i){throw i}}flush(){return O(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return O(this,void 0,void 0,function*(){if(!this.handle){xe.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'));return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}}class kc{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new Dd(e.info.pubHandle,kc.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return tm(this,arguments,function*(){const i=yield xn(this.encryptIfNeeded(e));try{yield xn(yield*RC(ki(this.packetizer.packetize(i))))}catch(s){throw s instanceof _c?Ia.packetizer(s):s}})}encryptIfNeeded(e){return O(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(i){throw Ia.encryption(i)}return e.payload=t.payload,e.extensions.e2ee=new ji(t.keyIndex,t.iv),e})}}kc.TRANSPORT_MTU_BYTES=16e3;const Ai=Nt(yt.DataTracks),v0={pending(){return{type:"pending",completionFuture:new Ft}},active(n,e){return{type:"active",info:n,publishState:"published",pipeline:new kc({info:n,e2eeManager:e}),unpublishingFuture:new Ft}}},d2=1e4;class Pd extends ai.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new Kk,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=(t=e==null?void 0:e.e2eeManager)!==null&&t!==void 0?t:null}static withDescriptors(e){const t=new Pd;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())t.type==="active"&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return(t=this.descriptors.get(e))!==null&&t!==void 0?t:null}tryProcessAndSend(e,t){return O(this,void 0,void 0,function*(){var i,s,r,a,o;const c=this.getDescriptor(e);if((c==null?void 0:c.type)!=="active"||c.publishState==="unpublished")throw es.trackUnpublished();if(c.publishState==="republishing")throw es.dropped("Data track republishing");try{try{for(var l=!0,u=ki(c.pipeline.processFrame(t)),h;h=yield u.next(),i=h.done,!i;l=!0){a=h.value,l=!1;const p=a,y=(o=this.inFlightPacketCounter.get(e))!==null&&o!==void 0?o:0;this.inFlightPacketCounter.set(e,y+1),y===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:p.toBinary()})}}catch(p){s={error:p}}finally{try{!l&&!i&&(r=u.return)&&(yield r.call(u))}finally{if(s)throw s.error}}}catch(p){throw es.dropped(p)}})}handlePacketSendComplete(e){var t;let s=((t=this.inFlightPacketCounter.get(e))!==null&&t!==void 0?t:0)-1;s<0&&(Ai.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),s=0),this.inFlightPacketCounter.set(e,s),s===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return O(this,void 0,void 0,function*(){const i=this.handleAllocator.get();if(!i)throw xt.limitReached();const s=i0(d2),r=t?t0([t,s]):s;if(this.descriptors.has(i))throw new Error("Descriptor for handle already exists");const a=v0.pending();this.descriptors.set(i,a);const o=()=>{var c,l;const u=this.descriptors.get(i);if(!u){Ai.warn("No descriptor for ".concat(i));return}this.descriptors.delete(i),this.emit("sfuUnpublishRequest",{handle:i}),u.type==="pending"&&((l=(c=u.completionFuture).reject)===null||l===void 0||l.call(c,s.aborted?xt.timeout():xt.cancelled()))};return r.aborted?(o(),a.completionFuture.promise.then(()=>i)):(r.addEventListener("abort",o),this.emit("sfuPublishRequest",{handle:i,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,r.removeEventListener("abort",o),this.emit("trackPublished",{track:Cc.withExplicitHandle(e,this,i)}),i)})}queryPublished(){return Array.from(this.descriptors.values()).filter(t=>t.type==="active").map(t=>t.info)}unpublishRequest(e){return O(this,void 0,void 0,function*(){const t=this.descriptors.get(e);if(!t){Ai.warn("No descriptor for ".concat(e));return}if(t.type!=="active"){Ai.warn("Track ".concat(e," not active"));return}this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var i,s,r,a;const o=this.descriptors.get(e);if(!o){Ai.warn("No descriptor for ".concat(e));return}switch(this.descriptors.delete(e),o.type){case"pending":{if(t.type==="ok"){const c=t.data;Ai.debug("SFU accepted publish request for handle ".concat(e),{sid:c.sid});const l=c.usesE2ee?this.e2eeManager:null;this.descriptors.set(c.pubHandle,v0.active(c,l)),(s=(i=o.completionFuture).resolve)===null||s===void 0||s.call(i)}else Ai.debug("SFU rejected publish request for handle ".concat(e),{error:t.error}),(a=(r=o.completionFuture).reject)===null||a===void 0||a.call(r,t.error);return}case"active":{if(o.publishState!=="republishing"){Ai.warn("Track ".concat(e," already active"));return}if(t.type==="error"){Ai.warn("Republish failed for track ".concat(e));return}Ai.debug("Track ".concat(e," republished")),o.info.sid=t.data.sid,o.publishState="published",this.descriptors.set(o.info.pubHandle,o)}}}receivedSfuUnpublishResponse(e){var t,i;const s=this.descriptors.get(e);if(!s){Ai.warn("No descriptor for ".concat(e));return}if(this.descriptors.delete(e),s.type!=="active"){Ai.warn("Track ".concat(e," not active"));return}s.publishState="unpublished",(i=(t=s.unpublishingFuture).resolve)===null||i===void 0||i.call(t)}sfuWillRepublishTracks(){var e,t;for(const s of this.descriptors.entries()){var i=_e(s,2);const r=i[0],a=i[1];switch(a.type){case"pending":this.descriptors.delete(r),(t=(e=a.completionFuture).reject)===null||t===void 0||t.call(e,xt.disconnected());break;case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return O(this,void 0,void 0,function*(){var e,t,i,s;this.handleAllocator.reset();for(const r of this.descriptors.values())switch(r.type){case"pending":(t=(e=r.completionFuture).reject)===null||t===void 0||t.call(e,xt.disconnected());break;case"active":(s=(i=r.unpublishingFuture).resolve)===null||s===void 0||s.call(i),yield this.unpublishRequest(r.info.pubHandle);break}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}}class ze extends Error{constructor(e,t,i,s){super(t),this.code=e,this.message=C0(t,ze.MAX_MESSAGE_BYTES),this.data=i?C0(i,ze.MAX_DATA_BYTES):void 0,typeof(s==null?void 0:s.cause)<"u"&&(this.cause=s==null?void 0:s.cause)}static fromProto(e){return new ze(e.code,e.message,e.data)}toProto(){return new Dp({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,i){return new ze(ze.ErrorCode[e],ze.ErrorMessage[e],t,i)}}ze.MAX_MESSAGE_BYTES=256,ze.MAX_DATA_BYTES=15360,ze.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},ze.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const b0=15360,T0="lk.rpc_request",_0="lk.rpc_response";var Ut;(function(n){n.RPC_REQUEST_ID="lk.rpc_request_id",n.RPC_REQUEST_METHOD="lk.rpc_request_method",n.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",n.RPC_REQUEST_VERSION="lk.rpc_request_version"})(Ut||(Ut={}));const h2=1,S0=2;function Id(n){return new TextEncoder().encode(n).length}function C0(n,e){if(Id(n)<=e)return n;let t=0,i=n.length;const s=new TextEncoder;for(;t<i;){const r=Math.floor((t+i+1)/2);s.encode(n.slice(0,r)).length<=e?t=r:i=r-1}return n.slice(0,t)}class f2 extends ai.EventEmitter{constructor(e,t,i,s){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i,this.getServerVersion=s}performRpc(e){return O(this,arguments,void 0,function(t){var i=this;let s=t.destinationIdentity,r=t.method,a=t.payload,o=t.responseTimeout,c=o===void 0?15e3:o;return(function*(){const h=i.getRemoteParticipantClientProtocol(s);if(Id(a)>b0&&h<Nu)throw ze.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const y=i.getServerVersion();if(y&&nn(y,"1.8.0")<0)throw ze.builtIn("UNSUPPORTED_SERVER");const _=Math.max(c,8e3),b=crypto.randomUUID(),S=new Ft;let D=null;const I=setTimeout(()=>{var w;i.pendingAcks.delete(b),(w=S.reject)===null||w===void 0||w.call(S,ze.builtIn("CONNECTION_TIMEOUT")),i.pendingResponses.delete(b),D!==null&&clearTimeout(D)},7e3);i.pendingAcks.set(b,{resolve:()=>{clearTimeout(I)},participantIdentity:s}),i.pendingResponses.set(b,{completionFuture:S,participantIdentity:s}),yield i.publishRpcRequest(s,b,r,a,_,h),D=setTimeout(()=>{var w;i.pendingResponses.delete(b),(w=S.reject)===null||w===void 0||w.call(S,ze.builtIn("RESPONSE_TIMEOUT"))},c);const F=S.promise.finally(()=>{clearTimeout(D),i.pendingAcks.has(b)&&(i.log.warn("RPC response received before ack",b),i.pendingAcks.delete(b),clearTimeout(I))});return[b,F]})()})}publishRpcRequest(e,t,i,s,r,a){return O(this,void 0,void 0,function*(){if(a>=Nu){yield this.outgoingDataStreamManager.sendText(s,{topic:T0,destinationIdentities:[e],attributes:{[Ut.RPC_REQUEST_ID]:t,[Ut.RPC_REQUEST_METHOD]:i,[Ut.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(r),[Ut.RPC_REQUEST_VERSION]:"".concat(S0)}});return}this.emit("sendDataPacket",{packet:new Kt({destinationIdentities:[e],kind:Kn.RELIABLE,value:{case:"rpcRequest",value:new cu({id:t,method:i,payload:s,responseTimeoutMs:r,version:h2})}})})})}handleIncomingDataStream(e,t,i){return O(this,void 0,void 0,function*(){const s=i[Ut.RPC_REQUEST_ID];if(!s){this.log.warn("RPC data stream malformed: ".concat(Ut.RPC_REQUEST_ID," not set."));return}const r=this.pendingResponses.get(s);if(r&&r.participantIdentity!==t){this.log.warn("RPC response stream for ".concat(s," arrived from unexpected sender ").concat(t,", expected ").concat(r.participantIdentity,". Ignoring."));return}let a;try{a=yield e.readAll()}catch(o){this.log.warn("Error reading RPC response payload: ".concat(o)),this.handleIncomingRpcResponseFailure(s,ze.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:o}));return}this.handleIncomingRpcResponseSuccess(s,a)})}handleIncomingRpcResponseSuccess(e,t){var i,s;const r=this.pendingResponses.get(e);r?((s=(i=r.completionFuture).resolve)===null||s===void 0||s.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var i,s;const r=this.pendingResponses.get(e);r?((s=(i=r.completionFuture).reject)===null||s===void 0||s.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(const a of this.pendingAcks){var i=_e(a,2);const o=i[0];i[1].participantIdentity===e&&this.pendingAcks.delete(o)}for(const a of this.pendingResponses){var s=_e(a,2);const o=s[0];var r=s[1];const c=r.participantIdentity,l=r.completionFuture;c===e&&((t=l.reject)===null||t===void 0||t.call(l,ze.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(o))}}}class p2 extends ai.EventEmitter{constructor(e,t,i){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return O(this,void 0,void 0,function*(){var i;if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,ze.builtIn("UNSUPPORTED_VERSION"));return}const s=this.rpcHandlers.get(t.method);if(!s){this.publishRpcResponsePacket(e,t.id,null,ze.builtIn("UNSUPPORTED_METHOD"));return}let r;try{r=yield s({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(a){let o;a instanceof ze?o=a:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),a),o=ze.builtIn("APPLICATION_ERROR","Uncaught error: ".concat((i=a==null?void 0:a.message)!==null&&i!==void 0?i:a),{cause:a})),this.publishRpcResponsePacket(e,t.id,null,o);return}yield this.publishRpcResponse(e,t.id,r??"")})}handleIncomingDataStream(e,t,i){return O(this,void 0,void 0,function*(){const s=i[Ut.RPC_REQUEST_ID],r=i[Ut.RPC_REQUEST_METHOD],a=parseInt(i[Ut.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(i[Ut.RPC_REQUEST_VERSION],10);if(!s||!r||Number.isNaN(a)||Number.isNaN(o)){this.log.warn("RPC data stream malformed: ".concat(Ut.RPC_REQUEST_ID," / ").concat(Ut.RPC_REQUEST_METHOD," / ").concat(Ut.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(Ut.RPC_REQUEST_VERSION," not set.")),this.publishRpcResponsePacket(t,s,null,ze.builtIn("APPLICATION_ERROR","RPC data stream malformed"));return}if(this.publishRpcAck(t,s),o!==S0){this.publishRpcResponsePacket(t,s,null,ze.builtIn("UNSUPPORTED_VERSION"));return}let c;try{c=yield e.readAll()}catch(h){this.log.warn("Error reading RPC request payload: ".concat(h)),this.publishRpcResponsePacket(t,s,null,ze.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:h}));return}const l=this.rpcHandlers.get(r);if(!l){this.publishRpcResponsePacket(t,s,null,ze.builtIn("UNSUPPORTED_METHOD"));return}let u;try{u=yield l({requestId:s,callerIdentity:t,payload:c,responseTimeout:a})}catch(h){let p;h instanceof ze?p=h:(this.log.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),h),p=ze.builtIn("APPLICATION_ERROR")),this.publishRpcResponsePacket(t,s,null,p);return}yield this.publishRpcResponse(t,s,u??"")})}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new Kt({destinationIdentities:[e],kind:Kn.RELIABLE,value:{case:"rpcAck",value:new Wo({requestId:t})}})})}publishRpcResponsePacket(e,t,i,s){this.emit("sendDataPacket",{packet:new Kt({destinationIdentities:[e],kind:Kn.RELIABLE,value:{case:"rpcResponse",value:new lu({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}})})}publishRpcResponse(e,t,i){return O(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=Nu){yield this.outgoingDataStreamManager.sendText(i,{topic:_0,destinationIdentities:[e],attributes:{[Ut.RPC_REQUEST_ID]:t}});return}if(Id(i)>b0){this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),this.publishRpcResponsePacket(e,t,null,ze.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));return}this.publishRpcResponsePacket(e,t,i,null)})}}class m2 extends mg{constructor(e,t,i,s,r,a){super(e,t,ae.Kind.Audio,i,a),this.monitorReceiver=()=>O(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=cc(o,this.prevStats)),this.prevStats=o}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Fi()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Fi())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return O(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(zu(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&zu(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{i.connect(s),i=s}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(he.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(he.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return O(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}class On extends ai.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=Ve.NONE,this.log=xe,this.handleMuted=()=>{this.emit(he.Muted)},this.handleUnmuted=()=>{this.emit(he.Unmuted)},this.log=Nt((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:yt.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=ae.Source.Unknown}setTrack(e){this.track&&(this.track.off(he.Muted,this.handleMuted),this.track.off(he.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(he.Muted,this.handleMuted),e.on(he.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Le(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Ve.NONE}get audioTrack(){if(sn(this.track))return this.track}get videoTrack(){if(Dn(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=ae.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===ae.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(n.PermissionStatus||(n.PermissionStatus={}))})(On||(On={}));class Rd extends On{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(he.Ended)},this.handleCpuConstrained=()=>{this.track&&Dn(this.track)&&this.emit(he.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(he.Ended,this.handleTrackEnded),this.track.off(he.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(he.Ended,this.handleTrackEnded),e.on(he.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return O(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return O(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return O(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return O(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(sn(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(Pt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(Pt.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(Pt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(Pt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(Pt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Pt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Ec(n,e){return O(this,void 0,void 0,function*(){n??(n={});let t=!1;const i=Jm(n),s=i.audioProcessor,r=i.videoProcessor,a=i.optionsWithoutProcessor;let o=a.audio,c=a.video;if(s&&typeof a.audio=="object"&&(a.audio.processor=s),r&&typeof a.video=="object"&&(a.video.processor=r),n.audio&&typeof a.audio=="object"&&typeof a.audio.deviceId=="string"){const p=a.audio.deviceId;a.audio.deviceId={exact:p},t=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:p}})}if(a.video&&typeof a.video=="object"&&typeof a.video.deviceId=="string"){const p=a.video.deviceId;a.video.deviceId={exact:p},t=!0,c=Object.assign(Object.assign({},a.video),{deviceId:{ideal:p}})}a.audio===!0?a.audio={deviceId:"default"}:typeof a.audio=="object"&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),a.video===!0?a.video={deviceId:"default"}:typeof a.video=="object"&&!a.video.deviceId&&(a.video.deviceId="default");const l=Xm(a,Eg,xg),u=ju(l),h=navigator.mediaDevices.getUserMedia(u);a.audio&&(It.userMediaPromiseMap.set("audioinput",h),h.catch(()=>It.userMediaPromiseMap.delete("audioinput"))),a.video&&(It.userMediaPromiseMap.set("videoinput",h),h.catch(()=>It.userMediaPromiseMap.delete("videoinput")));try{const p=yield h;return yield Promise.all(p.getTracks().map(y=>O(this,void 0,void 0,function*(){const _=y.kind==="audio";let b;const S=_?u.audio:u.video;typeof S!="boolean"&&(b=S);const D=y.getSettings().deviceId;b!=null&&b.deviceId&&cr(b.deviceId)!==D?b.deviceId=D:b||(b={deviceId:D});const I=AE(y,b,e);return I.kind===ae.Kind.Video?I.source=ae.Source.Camera:I.kind===ae.Kind.Audio&&(I.source=ae.Source.Microphone),I.mediaStream=p,sn(I)&&s?yield I.setProcessor(s):Dn(I)&&r&&(yield I.setProcessor(r)),I})))}catch(p){if(!t)throw p;return Ec(Object.assign(Object.assign({},n),{audio:o,video:c}),e)}})}function g2(n){return O(this,void 0,void 0,function*(){return(yield Ec({audio:!1,video:!0}))[0]})}function y2(n){return O(this,void 0,void 0,function*(){return(yield Ec({audio:!0,video:!1}))[0]})}var ts;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(ts||(ts={}));function v2(n){switch(n){case ca.EXCELLENT:return ts.Excellent;case ca.GOOD:return ts.Good;case ca.POOR:return ts.Poor;case ca.LOST:return ts.Lost;default:return ts.Unknown}}class k0 extends ai.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===er.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Zs.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,s,r,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:er.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=ts.Unknown,this.log=xe,this.loggerOptions=a,this.log=Nt((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:yt.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const i of this.trackPublications){var t=_e(i,2);const s=t[1];if(s.source===e)return s}}getTrackPublicationByName(e){for(const i of this.trackPublications){var t=_e(i,2);const s=t[1];if(s.trackName===e)return s}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Ft,this.once(fe.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(ae.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(ae.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(ae.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Zs.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Zs.ACTIVE&&this.emit(fe.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(fe.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(fe.ParticipantNameChanged,e)}_setAttributes(e){const t=sk(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(fe.AttributesChanged,t)}setPermissions(e){var t,i,s,r,a,o;const c=this.permissions,l=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,h)=>{var p;return u!==((p=this.permissions)===null||p===void 0?void 0:p.canPublishSources[h])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,l&&this.emit(fe.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(fe.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=v2(e),t!==this._connectionQuality&&this.emit(fe.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>sn(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){this.log.debug("adding track publication",{trackSid:e.trackSid,source:e.source,kind:e.kind}),e.on(he.Muted,()=>{this.emit(fe.TrackMuted,e)}),e.on(he.Unmuted,()=>{this.emit(fe.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case ae.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case ae.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function b2(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Gp({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}class T2 extends k0{constructor(e,t,i,s,r,a,o,c){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Ve.NONE,this.e2eeStateMutex=new Dt,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ft)},this.handleReconnected=()=>{var l,u;(u=(l=this.reconnectFuture)===null||l===void 0?void 0:l.resolve)===null||u===void 0||u.call(l),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var l,u,h,p,y,_;this.reconnectFuture&&(this.reconnectFuture.promise.catch(b=>this.log.warn(b.message)),(u=(l=this.reconnectFuture)===null||l===void 0?void 0:l.reject)===null||u===void 0||u.call(l,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((p=(h=this.signalConnectedFuture).reject)===null||p===void 0||p.call(h,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(_=(y=this.activeAgentFuture)===null||y===void 0?void 0:y.reject)===null||_===void 0||_.call(y,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=l=>{var u,h;l.participant&&this.updateInfo(l.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Ft),(h=(u=this.signalConnectedFuture).resolve)===null||h===void 0||h.call(u)},this.handleSignalRequestResponse=l=>{const u=l.requestId,h=l.reason,p=l.message,y=this.pendingSignalRequests.get(u);switch(y&&(h!==Ts.OK&&y.reject(new zm(p,h)),this.pendingSignalRequests.delete(u)),l.request.case){case"publishDataTrack":{let _;switch(l.reason){case Ts.NOT_ALLOWED:_=xt.notAllowed(l.message);break;case Ts.DUPLICATE_NAME:_=xt.duplicateName(l.message);break;case Ts.INVALID_NAME:_=xt.invalidName(l.message);break;case Ts.LIMIT_EXCEEDED:_=xt.limitReached(l.message);break;default:_=xt.unknown(l.reason,l.message);break}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(l.request.value.pubHandle,{type:"error",error:_});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(l=>b2(l)))},this.onTrackUnmuted=l=>{this.onTrackMuted(l,l.isUpstreamPaused)},this.onTrackMuted=(l,u)=>{if(u===void 0&&(u=!0),!l.sid){this.log.error("could not update mute status for unpublished track",Le(l));return}this.engine.updateMuteStatus(l.sid,u)},this.onTrackUpstreamPaused=l=>{this.log.debug("upstream paused",Le(l)),this.onTrackMuted(l,!0)},this.onTrackUpstreamResumed=l=>{this.log.debug("upstream resumed",Le(l)),this.onTrackMuted(l,l.isMuted)},this.onTrackFeatureUpdate=l=>{const u=this.audioTrackPublications.get(l.sid);if(!u){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(l.sid));return}this.engine.client.sendUpdateLocalAudioTrack(u.trackSid,u.getTrackFeatures())},this.onTrackCpuConstrained=(l,u)=>{this.log.debug("track cpu constrained",Le(u)),this.emit(fe.LocalTrackCpuConstrained,l,u)},this.handleSubscribedQualityUpdate=l=>O(this,void 0,void 0,function*(){var u,h,p,y,_;if(!(!((_=this.roomOptions)===null||_===void 0)&&_.dynacast))return;const b=this.videoTrackPublications.get(l.trackSid);if(!b){this.log.warn("received subscribed quality update for unknown track",{trackSid:l.trackSid});return}if(!b.videoTrack)return;const S=yield b.videoTrack.setPublishingCodecs(l.subscribedCodecs);try{for(var D=!0,I=ki(S),F;F=yield I.next(),u=F.done,!u;D=!0){y=F.value,D=!1;const w=y;ZC(w)&&(this.log.debug("publish ".concat(w," for ").concat(b.videoTrack.sid),Le(b)),yield this.publishAdditionalCodecForTrack(b.videoTrack,w,b.options))}}catch(w){h={error:w}}finally{try{!D&&!u&&(p=I.return)&&(yield p.call(I))}finally{if(h)throw h.error}}}),this.handleLocalTrackUnpublished=l=>{const u=this.trackPublications.get(l.trackSid);if(!u){this.log.warn("received unpublished event for unknown track",{trackSid:l.trackSid});return}this.unpublishTrack(u.track)},this.handleTrackEnded=l=>O(this,void 0,void 0,function*(){if(l.source===ae.Source.ScreenShare||l.source===ae.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Le(l)),this.unpublishTrack(l);else if(l.isUserProvided)yield l.mute();else if(Pn(l)||rn(l))try{if(oi())try{const u=yield navigator==null?void 0:navigator.permissions.query({name:l.source===ae.Source.Camera?"camera":"microphone"});if(u&&u.state==="denied")throw this.log.warn("user has revoked access to ".concat(l.source),Le(l)),u.onchange=()=>{u.state!=="denied"&&(l.isMuted||l.restartTrack(),u.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}l.isMuted||(this.log.debug("track ended, attempting to use a different device",Le(l)),Pn(l)?yield l.restartTrack({deviceId:"default"}):yield l.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Le(l)),yield l.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=r,this.roomOutgoingDataTrackManager=a,this.rpcClientManager=o,this.rpcServerManager=c}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Ve.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(le.RemoteMute,(i,s)=>{const r=this.trackPublications.get(i);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(le.Connected,this.handleReconnected).on(le.SignalConnected,this.handleSignalConnected).on(le.SignalRestarted,this.handleReconnected).on(le.SignalResumed,this.handleReconnected).on(le.Restarting,this.handleReconnecting).on(le.Resuming,this.handleReconnecting).on(le.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(le.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(le.Closing,this.handleClosing).on(le.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return O(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return O(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return O(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return O(this,arguments,void 0,function(t){var i=this;let s=t.metadata,r=t.name,a=t.attributes;return(function*(){return new Xt((o,c)=>O(i,void 0,void 0,function*(){var l,u;try{let h=!1;const p=yield this.engine.client.sendUpdateLocalMetadata((l=s??this.metadata)!==null&&l!==void 0?l:"",(u=r??this.name)!==null&&u!==void 0?u:"",a),y=performance.now();for(this.pendingSignalRequests.set(p,{resolve:o,reject:_=>{c(_),h=!0},values:{name:r,metadata:s,attributes:a}});performance.now()-y<5e3&&!h;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!a||Object.entries(a).every(_=>{let b=_e(_,2),S=b[0],D=b[1];return this.attributes[S]===D||D===""&&!this.attributes[S]}))){this.pendingSignalRequests.delete(p),o();return}yield Vt(50)}c(new zm("Request to update local metadata timed out","TimeoutError"))}catch(h){h instanceof Error?c(h):c(new Error(String(h)))}}))})()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(ae.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(ae.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(ae.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return O(this,void 0,void 0,function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?Ve.GCM:Ve.NONE,yield Promise.all(this.pendingPublishPromises.values()),this.trackPublications.size===0||Array.from(this.trackPublications.values()).every(i=>i.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,i,s){return O(this,void 0,void 0,function*(){var r,a;this.log.debug("setTrackEnabled",{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let h;if(this.pendingPublishing.has(e)){const p=yield this.waitForPendingPublicationOfSource(e);return p||this.log.info("waiting for pending publication promise timed out",{source:e}),yield p==null?void 0:p.unmute(),p}this.pendingPublishing.add(e);try{switch(e){case ae.Source.Camera:h=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case ae.Source.Microphone:h=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case ae.Source.ScreenShare:h=yield this.createScreenTracks(Object.assign({},i));break;default:throw new An(e)}}catch(p){throw h==null||h.forEach(y=>{y.stop()}),p instanceof Error&&this.emit(fe.MediaDevicesError,p,Hu(e)),this.pendingPublishing.delete(e),p}for(const p of h){const y=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===ae.Source.Microphone&&sn(p)&&y.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),p.startPreConnectBuffer())}try{const p=[];for(const _ of h)this.log.info("publishing track",Le(_)),p.push(this.publishTrack(_,s));const y=yield Promise.all(p);var c=_e(y,1);o=c[0]}catch(p){throw h==null||h.forEach(y=>{y.stop()}),p}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",{source:e})),o&&o.track)if(e===ae.Source.ScreenShare){const h=[this.unpublishTrack(o.track)],p=this.getTrackPublication(ae.Source.ScreenShareAudio);p&&p.track&&h.push(this.unpublishTrack(p.track));var l=yield Promise.all(h),u=_e(l,1);o=u[0]}else yield o.mute();return o})}enableCameraAndMicrophone(){return O(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(ae.Source.Camera)||this.pendingPublishing.has(ae.Source.Microphone))){this.pendingPublishing.add(ae.Source.Camera),this.pendingPublishing.add(ae.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(ae.Source.Camera),this.pendingPublishing.delete(ae.Source.Microphone)}}})}createTracks(e){return O(this,void 0,void 0,function*(){var t,i;e??(e={});const s=Xm(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Ec(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(sn(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=ae.Source.Microphone,this.emit(fe.AudioStreamAcquired)),Dn(o)&&(this.cameraError=void 0,o.source=ae.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return O(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Fu("getDisplayMedia not supported");e.resolution===void 0&&!pk()&&(e.resolution=qu.h1080fps30.resolution);const t=tk(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new An("no video track found");const r=new fc(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=ae.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(i.getAudioTracks().length>0){this.emit(fe.AudioStreamAcquired);const o=new dc(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=ae.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return O(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:15e3;return new Promise((t,i)=>{const s=()=>{clearTimeout(o),this.engine.off(le.Restarted,r),this.engine.off(le.Closing,a)},r=()=>{s(),t()},a=()=>{s(),i(new Error("engine closed before restart completed"))},o=setTimeout(()=>{s(),i(new Error("timed out waiting for engine restart"))},e);this.engine.once(le.Restarted,r),this.engine.once(le.Closing,a)})}publishOrRepublishTrack(e,t){return O(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;return(function*(){var c,l,u,h;Pn(i)&&i.setAudioContext(r.audioContext),yield(c=r.reconnectFuture)===null||c===void 0?void 0:c.promise,r.republishPromise&&!a&&(yield r.republishPromise),lr(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let p;if(i instanceof MediaStreamTrack)p=i.getConstraints();else{p=i.constraints;let I;switch(i.source){case ae.Source.Microphone:I="audioinput";break;case ae.Source.Camera:I="videoinput"}I&&r.activeDeviceMap.has(I)&&(p=Object.assign(Object.assign({},p),{deviceId:r.activeDeviceMap.get(I)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new dc(i,p,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new fc(i,p,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new An("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let y;if(r.trackPublications.forEach(I=>{I.track&&I.track===i&&(y=I)}),y)return r.log.warn("track has already been published, skipping",Le(y)),y;const _=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),b="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,S=(l=_.forceStereo)!==null&&l!==void 0?l:b;S&&(_.dtx===void 0&&r.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Le(i)),_.red===void 0&&r.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(u=_.dtx)!==null&&u!==void 0||(_.dtx=!1),(h=_.red)!==null&&h!==void 0||(_.red=!1)),!gk()&&r.roomOptions.e2ee&&(r.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2"),_.simulcast=!1),_.source&&(i.source=_.source);const D=new Promise((I,F)=>O(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Je.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:Le(i)});let w=!1;const P=setTimeout(()=>{w=!0,i.stop(),F(new Wm("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(P),w)return;const L=yield this.publish(i,_,S);I(L)}else try{const w=yield this.publish(i,_,S);I(w)}catch(w){F(w)}}catch(w){F(w)}}));r.pendingPublishPromises.set(i,D);try{return yield D}catch(I){if(!o&&I instanceof Ss)return r.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:I}),r.pendingPublishPromises.delete(i),yield r.waitForNextEngineRestart(),yield r.publishOrRepublishTrack(i,s,a,!0);throw I}finally{r.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Ft),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Le(e)),!1;const t=this.permissions,i=t.canPublish,s=t.canPublishSources;return i&&(s.length===0||s.map(r=>rk(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Le(e)),!1)}publish(e,t,i){return O(this,void 0,void 0,function*(){var s,r,a,o,c,l,u,h,p,y;if(!this.hasPermissionsToPublish(e))throw new Wm("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(k=>lr(e)&&k.source===e.source)&&e.source!==ae.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Le(e)),t.stopMicTrackOnMute&&sn(e)&&(e.stopOnMute=!0),e.source===ae.Source.ScreenShare&&Cs()&&(t.simulcast=!1),t.videoCodec==="av1"&&!uk()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!dk()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=md),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(k=>t.videoCodec===ma(k.mime))||(t.videoCodec=ma(this.enabledPublishVideoCodecs[0].mime)));const b=t.videoCodec;e.on(he.Muted,this.onTrackMuted),e.on(he.Unmuted,this.onTrackUnmuted),e.on(he.Ended,this.handleTrackEnded),e.on(he.UpstreamPaused,this.onTrackUpstreamPaused),e.on(he.UpstreamResumed,this.onTrackUpstreamResumed),e.on(he.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const S=[],D=!(!((s=t.dtx)!==null&&s!==void 0)||s),I=e.getSourceTrackSettings();I.autoGainControl&&S.push(Pt.TF_AUTO_GAIN_CONTROL),I.echoCancellation&&S.push(Pt.TF_ECHO_CANCELLATION),I.noiseSuppression&&S.push(Pt.TF_NOISE_SUPPRESSION),I.channelCount&&I.channelCount>1&&S.push(Pt.TF_STEREO),D&&S.push(Pt.TF_NO_DTX),Pn(e)&&e.hasPreConnectBuffer&&S.push(Pt.TF_PRECONNECT_BUFFER);const F=this.normalizeRequestedFrameMetadataOptions(e,t),w=new da({cid:e.mediaStreamTrack.id,name:t.name,type:ae.kindToProto(e.kind),muted:e.isMuted,source:ae.sourceToProto(e.source),disableDtx:D,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:S,packetTrailerFeatures:F});let P;if(e.kind===ae.Kind.Video){let k;try{k=yield e.waitForDimensions()}catch{const G=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:pa.h720.resolution;k={width:G.width,height:G.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},Le(e)),{dims:k}))}w.width=k.width,w.height=k.height,rn(e)&&(tn(b)&&(e.source===ae.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",Le(e)))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),w.simulcastCodecs=[new fu({codec:b,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:md}),t.backupCodec&&b!==t.backupCodec.codec&&w.encryption===Ve.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),w.simulcastCodecs.push(new fu({codec:t.backupCodec.codec,cid:""})))),P=hc(e.source===ae.Source.ScreenShare,w.width,w.height,t),w.layers=Vg(w.width,w.height,P,tn(t.videoCodec))}else e.kind===ae.Kind.Audio&&(P=[{maxBitrate:(l=t.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(h=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&h!==void 0?h:"high",networkPriority:(y=(p=t.audioPreset)===null||p===void 0?void 0:p.priority)!==null&&y!==void 0?y:"high"}]);if(!this.engine||this.engine.isClosed)throw new st("cannot publish track when not connected");const L=()=>O(this,void 0,void 0,function*(){var k,j,G,X;if(!this.engine.pcManager)throw new st("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,P),rn(e)&&(e.publishOptions=t),this.emit(fe.LocalSenderCreated,e.sender,e),rn(e)&&((k=t.degradationPreference)!==null&&k!==void 0||(t.degradationPreference=FE(e)),e.setDegradationPreference(t.degradationPreference)),P){if(Cs()&&e.kind===ae.Kind.Audio){let z;for(const W of this.engine.pcManager.publisher.getTransceivers())if(W.sender===e.sender){z=W;break}z&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:z,codec:"opus",maxbr:!((j=P[0])===null||j===void 0)&&j.maxBitrate?P[0].maxBitrate/1e3:0})}else if(e.codec&&cg(e.codec)){const z=tn(e.codec)?(X=(G=P[0])===null||G===void 0?void 0:G.maxBitrate)!==null&&X!==void 0?X:0:P.reduce((W,te)=>{var Q;return W+((Q=te.maxBitrate)!==null&&Q!==void 0?Q:0)},0);z>0&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:w.cid,codec:e.codec,maxbr:z/1e3,isScreenShare:e.source===ae.Source.ScreenShare})}}yield this.engine.negotiate()});let C;const N=new Promise((k,j)=>O(this,void 0,void 0,function*(){var G;try{C=yield this.engine.addTrack(w),k(C)}catch(X){if(e.sender&&(!((G=this.engine.pcManager)===null||G===void 0)&&G.publisher)){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(z){this.log.error(z)}yield this.engine.negotiate().catch(z=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},Le(e)),{error:z}))})}j(X)}}));if(this.enabledPublishVideoCodecs.length>0&&F.length===0)C=(yield Promise.all([N,L()]))[0];else{C=yield N;let k;if(C.codecs.forEach(j=>{k===void 0&&(k=j.mimeType)}),k&&e.kind===ae.Kind.Video){const j=ma(k);j!==b&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},Le(e)),{codec:j})),t.videoCodec=j,P=hc(e.source===ae.Source.ScreenShare,w.width,w.height,t))}yield L()}const x=new Rd(e.kind,C,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(x.on(he.CpuConstrained,k=>this.onTrackCpuConstrained(k,x)),x.options=t,e.sid=C.sid,rn(e)&&(e.publishOptions=t,w.width&&w.height&&(e.lastEncodedDimensions={width:w.width,height:w.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:P,trackInfo:C}),rn(e)?e.startMonitor(this.engine.client):Pn(e)&&e.startMonitor(),this.addTrackPublication(x),this.emit(fe.LocalTrackPublished,x),Pn(e)&&C.audioFeatures.includes(Pt.TF_PRECONNECT_BUFFER)){const k=e.getPreConnectBuffer(),j=e.getPreConnectBufferMimeType();this.on(fe.LocalTrackSubscribed,G=>{if(G.trackSid===C.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed");return}this.log.debug("finished recording preconnect buffer",Le(e)),e.stopPreConnectBuffer()}}),k&&new Promise((X,z)=>O(this,void 0,void 0,function*(){var W,te,Q,re,Y,ie;try{this.log.debug("waiting for agent",Le(e));const we=setTimeout(()=>{z(new Error("agent not active within 10 seconds"))},1e4),Pe=yield this.waitUntilActiveAgentPresent();clearTimeout(we),this.log.debug("sending preconnect buffer",Le(e));const ve=yield this.streamBytes({name:"preconnect-buffer",mimeType:j,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Pe.identity],attributes:{trackId:x.trackSid,sampleRate:String((Y=I.sampleRate)!==null&&Y!==void 0?Y:"48000"),channels:String((ie=I.channelCount)!==null&&ie!==void 0?ie:"1")}});try{for(var ge=!0,Te=ki(k),be;be=yield Te.next(),W=be.done,!W;ge=!0){re=be.value,ge=!1;const qe=re;yield ve.write(qe)}}catch(qe){te={error:qe}}finally{try{!ge&&!W&&(Q=Te.return)&&(yield Q.call(Te))}finally{if(te)throw te.error}}yield ve.close(),X()}catch(we){z(we)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Le(e))}).catch(X=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},Le(e)),{error:X}))})}return x})}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||Sa((e=this.roomOptions.frameMetadata)!==null&&e!==void 0?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var i;const s=(i=t.frameMetadata)!==null&&i!==void 0?i:t.packetTrailer;if(e.kind!==ae.Kind.Video||!oc(s))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),Le(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];const r=Uk(s),a=Bk(r);return t.frameMetadata=a,t.packetTrailer=a,r}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return O(this,void 0,void 0,function*(){var s;if(this.encryptionType!==Ve.NONE)return;let r;if(this.trackPublications.forEach(_=>{_.track&&_.track===e&&(r=_)}),!r)throw new An("track is not published");if(!rn(e))throw new An("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),o=Lg(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Le(e));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const l=this.normalizeRequestedFrameMetadataOptions(e,a),u=new da({cid:c.mediaStreamTrack.id,type:ae.kindToProto(e.kind),muted:e.isMuted,source:ae.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:l,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(u.layers=Vg(u.width,u.height,o),!this.engine||this.engine.isClosed)throw new st("cannot publish track when not connected");const h=()=>O(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),y=(yield Promise.all([this.engine.addTrack(u),h()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:y})})}unpublishTrack(e,t){return O(this,void 0,void 0,function*(){var i,s;if(lr(e)){const u=this.pendingPublishPromises.get(e);u&&(this.log.debug("awaiting publish promise before attempting to unpublish",Le(e)),yield u)}const r=this.getPublicationForTrack(e),a=r?Le(r):void 0;if(this.log.info("unpublishing track",a),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",a);return}e=r.track,e.off(he.Muted,this.onTrackMuted),e.off(he.Unmuted,this.onTrackUnmuted),e.off(he.Ended,this.handleTrackEnded),e.off(he.UpstreamPaused,this.onTrackUpstreamPaused),e.off(he.UpstreamResumed,this.onTrackUpstreamResumed),e.off(he.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ot.FAILED&&c)try{for(const u of this.engine.pcManager.publisher.getTransceivers())u.sender===c&&(u.direction="inactive",o=!0);try{o=this.engine.removeTrack(c)}catch(u){this.log.warn(u),o=!0}if(rn(e)){for(const u of e.simulcastCodecs){var l=_e(u,2);const h=l[1];if(h.sender){try{o=this.engine.removeTrack(h.sender)}catch(p){this.log.warn(p),o=!0}h.sender=void 0}}e.simulcastCodecs.clear()}}catch(u){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},a),{error:u}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case ae.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case ae.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(fe.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return O(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return O(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Xt((r,a)=>O(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>O(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),s&&!l.isMuted&&l.source!==ae.Source.ScreenShare&&l.source!==ae.Source.ScreenShareAudio&&(Pn(l)||rn(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",{track:c.trackSid}),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),r()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return O(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?Re.RELIABLE:Re.LOSSY,a=s.reliable?Kn.RELIABLE:Kn.LOSSY,o=s.destinationIdentities,c=s.topic;let l=new ou({participantIdentity:i.identity,payload:t,destinationIdentities:o,topic:c});const u=new Kt({kind:a,value:{case:"user",value:l}});yield i.engine.sendDataPacket(u,r)})()})}publishDtmf(e,t){return O(this,void 0,void 0,function*(){const i=new Kt({kind:Kn.RELIABLE,value:{case:"sipDtmf",value:new Ap({code:e,digit:t})}});yield this.engine.sendDataPacket(i,Re.RELIABLE)})}sendChatMessage(e,t){return O(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},s=new Kt({value:{case:"chatMessage",value:new $o(Object.assign(Object.assign({},i),{timestamp:nt.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,Re.RELIABLE),this.emit(fe.ChatMessage,i),i})}editChatMessage(e,t){return O(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new Kt({value:{case:"chatMessage",value:new $o(Object.assign(Object.assign({},i),{timestamp:nt.parse(i.timestamp),editTimestamp:nt.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,Re.RELIABLE),this.emit(fe.ChatMessage,i),i})}sendText(e,t){return O(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return O(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return O(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}sendBytes(e,t){return O(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendBytes(e,t)})}streamBytes(e){return O(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(t=>{let i=_e(t,2);return i[0],i[1]})}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const a=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&s!==void 0?s:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},Le(r)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,i,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Ft),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(Pn(s)||rn(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return O(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>_e(r,1)[0].source===e);if(s)return s[1];yield Vt(20)}})}publishDataTrack(e){return O(this,void 0,void 0,function*(){const t=new Cc(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}}class E0 extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class _2 extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var i,s;super.set(e,t);const r=(i=this.pending)===null||i===void 0?void 0:i.get(e);if(r){for(const a of r)a.isResolved||(s=a.resolve)===null||s===void 0||s.call(a,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return O(this,void 0,void 0,function*(){const i=this.get(e);if(typeof i<"u")return i;if(t!=null&&t.aborted)throw new E0("The operation was aborted.",t.reason);const s=new Ft(void 0,()=>{const a=this.pending.get(e);if(!a)return;const o=a.indexOf(s);o!==-1&&a.splice(o,1),a.length===0&&this.pending.delete(e)}),r=this.pending.get(e);if(r?r.push(s):this.pending.set(e,[s]),t){const a=()=>{var o;s.isResolved||(o=s.reject)===null||o===void 0||o.call(s,new E0("The operation was aborted.",t.reason))};t.addEventListener("abort",a,{once:!0}),s.promise.finally(()=>{t.removeEventListener("abort",a)})}return s.promise})}}class S2 extends On{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(he.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new Xo({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Pp({participantSid:"",trackSids:[this.trackSid]})]});this.emit(he.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?On.SubscriptionStatus.Unsubscribed:super.isSubscribed?On.SubscriptionStatus.Subscribed:On.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?On.PermissionStatus.Allowed:On.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(Zu(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Zu(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:yi.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(he.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(he.VisibilityChanged,this.handleVisibilityChange),s.off(he.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(he.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(he.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(he.VisibilityChanged,this.handleVisibilityChange),e.on(he.Ended,this.handleEnded),this.emit(he.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(he.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?he.Muted:he.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(he.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(he.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Zu(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Hp({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===ae.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Zm(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=ak(this.trackInfo,this.requestedMaxQuality);i&&Zm(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:yi.HIGH})),e.quality=yi.HIGH)}this.emit(he.UpdateSettings,e)}}class xc extends k0{static fromParticipantInfo(e,t,i,s){return new xc(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind,t.dataTracks.map(r=>{const a=lc.from(r);return new y0(a,s,{publisherIdentity:t.identity})}),t.clientProtocol,t.capabilities)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,s,r,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:er.STANDARD,l=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],u=arguments.length>9&&arguments[9]!==void 0?arguments[9]:Hm,h=arguments.length>10&&arguments[10]!==void 0?arguments[10]:[];super(t,i||"",s,r,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new _2(l.map(p=>[p.info.name,p])),this.volumeMap=new Map,this.clientProtocol=u,this.capabilities=h}addTrackPublication(e){super.addTrackPublication(e),e.on(he.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Le(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(he.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(he.SubscriptionPermissionChanged,t=>{this.emit(fe.TrackSubscriptionPermissionChanged,e,t)}),e.on(he.SubscriptionStatusChanged,t=>{this.emit(fe.TrackSubscriptionStatusChanged,e,t)}),e.on(he.Subscribed,t=>{this.emit(fe.TrackSubscribed,t,e)}),e.on(he.Unsubscribed,t=>{this.emit(fe.TrackUnsubscribed,t,e)}),e.on(he.SubscriptionFailed,t=>{this.emit(fe.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ae.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ae.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(fe.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,s,r,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),Le(o))),this.emit(fe.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let l;return c?l=new rd(e,t,s,r):l=new m2(e,t,s,this.audioContext,this.audioOutput),l.source=o.source,l.isMuted=o.isMuted,l.setMediaStream(i),l.start(),o.setTrack(l),this.volumeMap.has(o.source)&&Ju(l)&&sn(l)&&l.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(s=>{var r,a;let o=this.getTrackPublicationBySid(s.sid);if(o)o.updateInfo(s);else{const c=ae.kindFromProto(s.type);if(!c)return;o=new S2(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(s),i.set(s.sid,o);const l=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));l&&o.source!==ae.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Le(l),newTrack:Le(o)})),this.addTrackPublication(o)}t.set(s.sid,o)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Le(s))),this.unpublishTrack(s.trackSid,!0))}),i.forEach(s=>{this.emit(fe.TrackPublished,s)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const s=i.track;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case ae.Kind.Audio:this.audioTrackPublications.delete(e);break;case ae.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(fe.TrackUnpublished,i)}setAudioOutput(e){return O(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;sn(i.track)&&Ju(i.track)&&t.push(i.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(const i of this.dataTracks.entries()){var t=_e(i,2);const s=t[0],r=t[1];e===r.info.sid&&this.dataTracks.delete(s)}}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var Be;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(Be||(Be={}));const C2=4*1e3;class mr extends ai.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,s,r,a,o,c;if(super(),t=this,this.state=Be.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new Dt,this.isVideoPlaybackBlocked=!1,this.log=xe,this.bufferedEvents=[],this.isResuming=!1,this.connect=(l,u,h)=>O(this,void 0,void 0,function*(){var p;if(!hk())throw Fi()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const y=yield this.disconnectLock.lock();if(this.state===Be.Connected)return this.log.info("already connected to room ".concat(this.name)),y(),Promise.resolve();if(this.connectFuture)return y(),this.connectFuture.promise;this.setAndEmitConnectionState(Be.Connecting),((p=this.regionUrlProvider)===null||p===void 0?void 0:p.getServerUrl().toString())!==ug(l)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),or(new URL(l))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ue(l,u):this.regionUrlProvider.updateToken(u),this.regionUrlProvider.fetchRegionSettings().then(S=>{var D;(D=this.regionUrlProvider)===null||D===void 0||D.setServerReportedRegions(S)}).catch(S=>{this.log.warn("could not fetch region settings",{error:S})}));const _=(S,D,I)=>O(this,void 0,void 0,function*(){var F,w;this.abortController&&this.abortController.abort();const P=new AbortController;this.abortController=P,y==null||y();try{if(yield ur.getInstance().getBackOffPromise(l),P.signal.aborted)throw Se.cancelled("Connection attempt aborted");yield this.attemptConnection(I??l,u,h,P),this.abortController=void 0,S()}catch(L){if(this.regionUrlProvider&&L instanceof Se&&L.reason!==He.Cancelled&&L.reason!==He.NotAllowed){let C=null;try{this.log.debug("Fetching next region"),C=yield this.regionUrlProvider.getNextBestRegionUrl((F=this.abortController)===null||F===void 0?void 0:F.signal)}catch(N){if(N instanceof Se&&(N.status===401||N.reason===He.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),D(N);return}}[He.InternalError,He.ServerUnreachable,He.Timeout].includes(L.reason)&&(this.log.debug("Adding failed connection attempt to back off"),ur.getInstance().addFailedConnectionAttempt(l)),C&&!(!((w=this.abortController)===null||w===void 0)&&w.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(L.message,". Retrying with another region: ").concat(C)),this.recreateEngine(!0),yield _(S,D,C)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,lg(L)),D(L))}else{let C=Gt.UNKNOWN_REASON;L instanceof Se&&(C=lg(L)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,C),D(L)}}}),b=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ft((S,D)=>{_(S,D,b)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(l,u,h,p,y,_)=>O(this,void 0,void 0,function*(){const b=yield h.join(l,u,{autoSubscribe:p.autoSubscribe,adaptiveStream:typeof y.adaptiveStream=="object"?!0:y.adaptiveStream,clientInfoCapabilities:this.getClientInfoCapabilities(y),maxRetries:p.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:p.websocketTimeout},_.signal,!y.singlePeerConnection),S=b.joinResponse,D=b.serverInfo;if(this.serverInfo=D,!D.version)throw new KC("unknown server version");return D.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),y.dynacast=!1),S}),this.applyJoinResponse=l=>{const u=l.participant;if(this.localParticipant.sid=u.sid,this.localParticipant.identity=u.identity,this.localParticipant.setEnabledPublishCodecs(l.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(l.sifTrailer)}catch(h){this.log.error(h instanceof Error?h.message:"Could not set SifTrailer",{error:h})}this.handleParticipantUpdates([u,...l.otherParticipants]),l.room&&this.handleRoomUpdate(l.room)},this.attemptConnection=(l,u,h,p)=>O(this,void 0,void 0,function*(){var y,_;this.state===Be.Reconnecting||this.isResuming||!((y=this.engine)===null||y===void 0)&&y.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),!((_=this.regionUrlProvider)===null||_===void 0)&&_.isCloud()&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},gd),h),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const b=yield this.connectSignal(l,u,this.engine,this.connOptions,this.options,p);this.applyJoinResponse(b),this.setupLocalParticipantEvents(),this.emit(se.SignalConnected)}catch(b){yield this.engine.close(),this.recreateEngine();const S=p.signal.aborted?Se.cancelled("Signal connection aborted"):Se.serverUnreachable("could not establish signal connection");throw b instanceof Error&&(S.message="".concat(S.message,": ").concat(b.message)),b instanceof Se&&(S.reason=b.reason,S.status=b.status),this.log.debug("error trying to establish signal connection",{error:b}),S}if(p.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),Se.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,p)}catch(b){throw yield this.engine.close(),this.recreateEngine(),b}oi()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),oi()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Be.Connected),this.emit(se.Connected),ur.getInstance().resetFailedConnectionAttempts(l),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var l=arguments.length,u=new Array(l),h=0;h<l;h++)u[h]=arguments[h];return O(t,[...u],void 0,function(){var p=this;let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var _,b,S;const D=yield p.disconnectLock.lock();try{if(p.state===Be.Disconnected){p.log.debug("already disconnected");return}if(p.log.info("disconnect from room"),p.state===Be.Connecting||p.state===Be.Reconnecting||p.isResuming){const I="Abort connection attempt due to user initiated disconnect";p.log.warn(I),(_=p.abortController)===null||_===void 0||_.abort(I),(S=(b=p.connectFuture)===null||b===void 0?void 0:b.reject)===null||S===void 0||S.call(b,Se.cancelled("Client initiated disconnect")),p.connectFuture=void 0}p.engine&&(p.engine.client.isDisconnected||(yield p.engine.client.sendLeave()),yield p.engine.close()),p.handleDisconnect(y,Gt.CLIENT_INITIATED),p.engine=void 0}finally{D()}})()})},this.onPageLeave=()=>O(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()}),this.startAudio=()=>O(this,void 0,void 0,function*(){const l=[],u=Yt();if(u&&u.os==="iOS"){const h="livekit-dummy-audio-el";let p=document.getElementById(h);if(!p){p=document.createElement("audio"),p.id=h,p.autoplay=!0,p.hidden=!0;const y=Qu();y.enabled=!0;const _=new MediaStream([y]);p.srcObject=_,document.addEventListener("visibilitychange",()=>{p&&(p.srcObject=document.hidden?null:_,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio()))}),document.body.append(p),this.once(se.Disconnected,()=>{p==null||p.remove(),p=null})}l.push(p)}this.remoteParticipants.forEach(h=>{h.audioTrackPublications.forEach(p=>{p.track&&p.track.attachedElements.forEach(y=>{l.push(y)})})});try{yield Promise.all([this.acquireAudioContext(),...l.map(h=>(this.options.webAudioMix||(h.muted=!1),h.play()))]),this.handleAudioPlaybackStarted()}catch(h){throw this.handleAudioPlaybackFailed(h),h}}),this.startVideo=()=>O(this,void 0,void 0,function*(){const l=[];for(const u of this.remoteParticipants.values())u.videoTrackPublications.forEach(h=>{var p;(p=h.track)===null||p===void 0||p.attachedElements.forEach(y=>{l.includes(y)||l.push(y)})});yield Promise.all(l.map(u=>u.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(u=>{u.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const l of this.remoteParticipants.values())this.handleParticipantDisconnected(l.identity,l);this.setAndEmitConnectionState(Be.Reconnecting)&&this.emit(se.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=l=>O(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(l.serverRegion),{region:l.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(l);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(u){this.log.error("error trying to re-publish tracks after reconnection",{error:u})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:l.serverRegion})}catch{return}this.setAndEmitConnectionState(Be.Connected),this.emit(se.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=l=>{var u;for(const p of l){if(p.identity===this.localParticipant.identity){this.localParticipant.updateInfo(p);continue}p.identity===""&&(p.identity=(u=this.sidToIdentity.get(p.sid))!==null&&u!==void 0?u:"");let y=this.remoteParticipants.get(p.identity);p.state===Zs.DISCONNECTED?this.handleParticipantDisconnected(p.identity,y):this.getOrCreateParticipant(p.identity,p)}const h=new Map(l.filter(p=>p.identity!==this.localParticipant.identity).map(p=>[p.identity,p.dataTracks.map(y=>lc.from(y))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(h)},this.handleActiveSpeakersUpdate=l=>{const u=[],h={};l.forEach(p=>{if(h[p.sid]=!0,p.sid===this.localParticipant.sid)this.localParticipant.audioLevel=p.level,this.localParticipant.setIsSpeaking(!0),u.push(this.localParticipant);else{const y=this.getRemoteParticipantBySid(p.sid);y&&(y.audioLevel=p.level,y.setIsSpeaking(!0),u.push(y))}}),h[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(p=>{h[p.sid]||(p.audioLevel=0,p.setIsSpeaking(!1))}),this.activeSpeakers=u,this.emitWhenConnected(se.ActiveSpeakersChanged,u)},this.handleSpeakersChanged=l=>{const u=new Map;this.activeSpeakers.forEach(p=>{const y=this.remoteParticipants.get(p.identity);y&&y.sid!==p.sid||u.set(p.sid,p)}),l.forEach(p=>{let y=this.getRemoteParticipantBySid(p.sid);p.sid===this.localParticipant.sid&&(y=this.localParticipant),y&&(y.audioLevel=p.level,y.setIsSpeaking(p.active),p.active?u.set(p.sid,y):u.delete(p.sid))});const h=Array.from(u.values());h.sort((p,y)=>y.audioLevel-p.audioLevel),this.activeSpeakers=h,this.emitWhenConnected(se.ActiveSpeakersChanged,h)},this.handleStreamStateUpdate=l=>{l.streamStates.forEach(u=>{const h=this.getRemoteParticipantBySid(u.participantSid);if(!h)return;const p=h.getTrackPublicationBySid(u.trackSid);if(!p||!p.track)return;const y=ae.streamStateFromProto(u.state);p.track.setStreamState(y),y!==p.track.streamState&&(h.emit(fe.TrackStreamStateChanged,p,p.track.streamState),this.emitWhenConnected(se.TrackStreamStateChanged,p,p.track.streamState,h))})},this.handleSubscriptionPermissionUpdate=l=>{const u=this.getRemoteParticipantBySid(l.participantSid);if(!u)return;const h=u.getTrackPublicationBySid(l.trackSid);h&&h.setAllowed(l.allowed)},this.handleSubscriptionError=l=>{const u=Array.from(this.remoteParticipants.values()).find(p=>p.trackPublications.has(l.trackSid));if(!u)return;const h=u.getTrackPublicationBySid(l.trackSid);h&&h.setSubscriptionError(l.err)},this.handleDataPacket=(l,u)=>{const h=this.remoteParticipants.get(l.participantIdentity);if(l.value.case==="user")this.handleUserPacket(h,l.value.value,l.kind,u);else if(l.value.case==="transcription")this.handleTranscription(h,l.value.value);else if(l.value.case==="sipDtmf")this.handleSipDtmf(h,l.value.value);else if(l.value.case==="chatMessage")this.handleChatMessage(h,l.value.value);else if(l.value.case==="metrics")this.handleMetrics(l.value.value,h);else if(l.value.case==="streamHeader"||l.value.case==="streamChunk"||l.value.case==="streamTrailer")this.handleDataStream(l,u);else if(l.value.case==="rpcRequest"){const p=l.value.value;this.rpcServerManager.handleIncomingRpcRequest(l.participantIdentity,p)}else if(l.value.case==="rpcResponse"){const p=l.value.value;switch(p.value.case){case"payload":this.rpcClientManager.handleIncomingRpcResponseSuccess(p.requestId,p.value.value);break;case"error":this.rpcClientManager.handleIncomingRpcResponseFailure(p.requestId,ze.fromProto(p.value.value));break;default:this.log.warn("Unknown rpcResponse.value.case: ".concat(p.value.case),this.logContext);break}}else l.value.case==="rpcAck"&&this.rpcClientManager.handleIncomingRpcAck(l.value.value.requestId)},this.handleUserPacket=(l,u,h,p)=>{this.emit(se.DataReceived,u.payload,l,h,u.topic,p),l==null||l.emit(fe.DataReceived,u.payload,h,p)},this.handleSipDtmf=(l,u)=>{this.emit(se.SipDTMFReceived,u,l),l==null||l.emit(fe.SipDTMFReceived,u)},this.handleTranscription=(l,u)=>{const h=u.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(u.transcribedParticipantIdentity),p=h==null?void 0:h.trackPublications.get(u.trackId),y=_k(u,this.transcriptionReceivedTimes);p==null||p.emit(he.TranscriptionReceived,y),h==null||h.emit(fe.TranscriptionReceived,y,p),this.emit(se.TranscriptionReceived,y,h,p)},this.handleChatMessage=(l,u)=>{const h=Sk(u);this.emit(se.ChatMessage,h,l)},this.handleMetrics=(l,u)=>{this.emit(se.MetricsReceived,l,u)},this.handleDataStream=(l,u)=>{this.incomingDataStreamManager.handleDataStreamPacket(l,u)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(se.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=l=>{this.log.warn("could not playback audio",{error:l}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(se.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(se.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(se.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>O(this,void 0,void 0,function*(){var l;((l=Yt())===null||l===void 0?void 0:l.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(se.MediaDevicesChanged)}),this.handleRoomUpdate=l=>{const u=this.roomInfo;this.roomInfo=l,u&&u.metadata!==l.metadata&&this.emitWhenConnected(se.RoomMetadataChanged,l.metadata),(u==null?void 0:u.activeRecording)!==l.activeRecording&&this.emitWhenConnected(se.RecordingStatusChanged,l.activeRecording)},this.handleConnectionQualityUpdate=l=>{l.updates.forEach(u=>{if(u.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(u.quality);return}const h=this.getRemoteParticipantBySid(u.participantSid);h&&h.setConnectionQuality(u.quality)})},this.getRemoteParticipantClientProtocol=l=>{var u,h;return(h=(u=this.remoteParticipants.get(l))===null||u===void 0?void 0:u.clientProtocol)!==null&&h!==void 0?h:Hm},this.getRemoteParticipantCapabilities=l=>{var u,h;return(h=(u=this.remoteParticipants.get(l))===null||u===void 0?void 0:u.capabilities)!==null&&h!==void 0?h:[]},this.getAllRemoteParticipantIdentities=()=>Array.from(this.remoteParticipants.keys()),this.onLocalParticipantMetadataChanged=l=>{this.emit(se.ParticipantMetadataChanged,l,this.localParticipant)},this.onLocalParticipantNameChanged=l=>{this.emit(se.ParticipantNameChanged,l,this.localParticipant)},this.onLocalAttributesChanged=l=>{this.emit(se.ParticipantAttributesChanged,l,this.localParticipant)},this.onLocalTrackMuted=l=>{this.emit(se.TrackMuted,l,this.localParticipant)},this.onLocalTrackUnmuted=l=>{this.emit(se.TrackUnmuted,l,this.localParticipant)},this.onTrackProcessorUpdate=l=>{var u;(u=l==null?void 0:l.onPublish)===null||u===void 0||u.call(l,this)},this.onLocalTrackPublished=l=>O(this,void 0,void 0,function*(){var u,h,p,y,_,b;(u=l.track)===null||u===void 0||u.on(he.TrackProcessorUpdate,this.onTrackProcessorUpdate),(h=l.track)===null||h===void 0||h.on(he.Restarted,this.onLocalTrackRestarted),(_=(y=(p=l.track)===null||p===void 0?void 0:p.getProcessor())===null||y===void 0?void 0:y.onPublish)===null||_===void 0||_.call(y,this),this.emit(se.LocalTrackPublished,l,this.localParticipant),Pn(l.track)&&(yield l.track.checkForSilence())&&this.emit(se.LocalAudioSilenceDetected,l);const S=yield(b=l.track)===null||b===void 0?void 0:b.getDeviceId(!1),D=Hu(l.source);D&&S&&S!==this.localParticipant.activeDeviceMap.get(D)&&(this.localParticipant.activeDeviceMap.set(D,S),this.emit(se.ActiveDeviceChanged,D,S))}),this.onLocalTrackUnpublished=l=>{var u,h;(u=l.track)===null||u===void 0||u.off(he.TrackProcessorUpdate,this.onTrackProcessorUpdate),(h=l.track)===null||h===void 0||h.off(he.Restarted,this.onLocalTrackRestarted),this.emit(se.LocalTrackUnpublished,l,this.localParticipant)},this.onLocalTrackRestarted=l=>O(this,void 0,void 0,function*(){const u=yield l.getDeviceId(!1),h=Hu(l.source);h&&u&&u!==this.localParticipant.activeDeviceMap.get(h)&&(this.log.debug("local track restarted, setting ".concat(h," ").concat(u," active")),this.localParticipant.activeDeviceMap.set(h,u),this.emit(se.ActiveDeviceChanged,h,u))}),this.onLocalConnectionQualityChanged=l=>{this.emit(se.ConnectionQualityChanged,l,this.localParticipant)},this.onMediaDevicesError=(l,u)=>{this.emit(se.MediaDevicesError,l,u)},this.onLocalParticipantPermissionsChanged=l=>{this.emit(se.ParticipantPermissionsChanged,l,this.localParticipant)},this.onLocalChatMessageSent=l=>{this.emit(se.ChatMessage,l,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},fE),e),this.log=Nt((i=this.options.loggerName)!==null&&i!==void 0?i:yt.Room,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Eg),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},xg),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},hE),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new GE,this.outgoingDataStreamManager=new t2(this.engine,this.log,this.getRemoteParticipantClientProtocol,this.getRemoteParticipantCapabilities,this.getAllRemoteParticipantIdentities),this.incomingDataTrackManager=new u2({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on("sfuUpdateSubscription",l=>{this.engine.client.sendUpdateDataSubscription(l.sid,l.subscribe)}).on("trackPublished",l=>{var u;l.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(se.DataTrackPublished,l.track),(u=this.remoteParticipants.get(l.track.publisherIdentity))===null||u===void 0||u.addRemoteDataTrack(l.track))}).on("trackUnpublished",l=>{var u;l.publisherIdentity!==this.localParticipant.identity&&(this.emit(se.DataTrackUnpublished,l.sid),(u=this.remoteParticipants.get(l.publisherIdentity))===null||u===void 0||u.removeRemoteDataTrack(l.sid))}),this.outgoingDataTrackManager=new Pd({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on("sfuPublishRequest",l=>{this.engine.client.sendPublishDataTrackRequest(l.handle,l.name,l.usesE2ee)}).on("sfuUnpublishRequest",l=>{this.engine.client.sendUnPublishDataTrackRequest(l.handle)}).on("trackPublished",l=>{this.emit(se.LocalDataTrackPublished,l.track)}).on("trackUnpublished",l=>{this.emit(se.LocalDataTrackUnpublished,l.sid)}).on("packetAvailable",l=>{let u=l.handle,h=l.bytes;this.engine.sendDataTrackFrame(h).finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(u))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new f2(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,()=>{var l,u;return(u=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||u===void 0?void 0:u.version}),this.rpcClientManager.on("sendDataPacket",l=>{let u=l.packet;var h;(h=this.engine)===null||h===void 0||h.sendDataPacket(u,Re.RELIABLE)}),this.rpcServerManager=new p2(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",l=>{let u=l.packet;var h;(h=this.engine)===null||h===void 0||h.sendDataPacket(u,Re.RELIABLE)}),this.disconnectLock=new Dt,this.localParticipant=new T2("","",this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager((s=this.e2eeManager)!==null&&s!==void 0?s:null),this.outgoingDataTrackManager.updateE2eeManager((r=this.e2eeManager)!==null&&r!==void 0?r:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",cr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",cr(this.options.audioCaptureDefaults.deviceId)),!((a=this.options.audioOutput)===null||a===void 0)&&a.deviceId&&this.switchActiveDevice("audiooutput",cr(this.options.audioOutput.deviceId)).catch(l=>this.log.warn("Could not set audio output: ".concat(l.message))),oi()){const l=new AbortController;let u;if(mr.cleanupRegistry){const h=new WeakRef(this);u=()=>{const p=h.deref();p&&p.handleDeviceChange()},mr.cleanupRegistry.register(this,()=>{l.abort()})}else u=this.handleDeviceChange;(c=(o=navigator.mediaDevices)===null||o===void 0?void 0:o.addEventListener)===null||c===void 0||c.call(o,"devicechange",u,{signal:l.signal})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return O(this,void 0,void 0,function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.e2eeManager)this.isE2EEEnabled!==e&&(yield this.localParticipant.setE2EEEnabled(e),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity));else throw Error("e2ee not configured, please set e2ee settings within the room options")}finally{t()}})}setupE2EE(){var e,t;const i=!!this.options.encryption,s=this.options.encryption||this.options.e2ee;s&&("e2eeManager"in s?(this.e2eeManager=s.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=i):this.e2eeManager=new Vk(s,i),this.e2eeManager.on(Jn.ParticipantEncryptionStatusChanged,(r,a)=>{kk(a)&&(this.isE2EEEnabled=r),this.emit(se.ParticipantEncryptionStatusChanged,r,a)}),this.e2eeManager.on(Jn.EncryptionError,(r,a)=>{const o=a?this.getParticipantByIdentity(a):void 0;this.emit(se.EncryptionError,r,o)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this),(t=this.e2eeManager)===null||t===void 0||t.setupEngine(this.engine))}setupFrameMetadata(){var e;const t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer;this.frameMetadataManager=new $k(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,i;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:(t=this.localParticipant)===null||t===void 0?void 0:t.identity,participantID:(i=this.localParticipant)===null||i===void 0?void 0:i.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===Be.Disconnected?Xt.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?Xt.resolve(this.roomInfo.sid):new Xt((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(le.RoomUpdate,i),e(s.sid))};this.engine.on(le.RoomUpdate,i),this.once(se.Disconnected,()=>{this.engine.off(le.RoomUpdate,i),t(new st("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&(this.engine.isNewlyCreated||!this.engine.isClosed)||(this.engine=new HE(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(le.ParticipantUpdate,this.handleParticipantUpdates).on(le.RoomUpdate,this.handleRoomUpdate).on(le.SpeakersChanged,this.handleSpeakersChanged).on(le.StreamStateChanged,this.handleStreamStateUpdate).on(le.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(le.SubscriptionError,this.handleSubscriptionError).on(le.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(le.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(le.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(le.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(le.DataPacketReceived,this.handleDataPacket).on(le.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(Be.SignalReconnecting)&&this.emit(se.SignalReconnecting)}).on(le.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.setAndEmitConnectionState(Be.Connected)&&this.emit(se.Reconnected),this.emitBufferedEvents()}).on(le.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Be.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(le.Restarting,this.handleRestarting).on(le.Restarted,this.handleRestarted).on(le.SignalRestarted,this.handleSignalRestarted).on(le.Offline,()=>{this.setAndEmitConnectionState(Be.Reconnecting)&&this.emit(se.Reconnecting)}).on(le.DCBufferStatusChanged,(e,t)=>{this.emit(se.DCBufferStatusChanged,e,t)}).on(le.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(le.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(se.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(le.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:"ok",data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==Ve.NONE}})}).on(le.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(le.DataTrackSubscriberHandles,e=>{const t=new Map(Object.entries(e.subHandles).map(i=>{let s=_e(i,2),r=s[0],a=s[1];return[parseInt(r,10),a.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(le.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(t){throw t}}).on(le.Joined,e=>{const t=new Map(e.otherParticipants.map(i=>[i.identity,i.dataTracks.map(s=>lc.from(s))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(le.TokenRefreshed,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)}).on(le.ServerRegionsReported,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:_d})}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>O(this,void 0,void 0,function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null}),resetAttempts:()=>{var e;return(e=this.regionUrlProvider)===null||e===void 0?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return It.getInstance().getDevices(e,t)}prepareConnection(e,t){return O(this,void 0,void 0,function*(){if(this.state===Be.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(or(new URL(e))&&t){this.regionUrlProvider=new Ue(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Be.Disconnected&&(this.regionUrl=i,yield fetch(ba(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(ba(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",{error:i})}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return O(this,void 0,void 0,function*(){let i=()=>O(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":s=new Zi({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Zi({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Zi({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Zi({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>O(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Zi({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>O(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Zi({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":s=new Zi({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>O(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new Yo({reason:Gt.CLIENT_INITIATED,action:ir.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Zi({scenario:{case:"subscriberBandwidth",value:Ui(t)}});break;case"leave-full-reconnect":s=new Zi({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return O(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var o,c,l,u,h,p,y;let _=!0,b=!1;const S=a?{exact:s}:s;if(i==="audioinput"){b=r.localParticipant.audioTrackPublications.size===0;const D=(o=r.getActiveDevice(i))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=S;const I=Array.from(r.localParticipant.audioTrackPublications.values()).filter(w=>w.source===ae.Source.Microphone);try{_=(yield Promise.all(I.map(w=>{var P;return(P=w.audioTrack)===null||P===void 0?void 0:P.setDeviceId(S)}))).every(w=>w===!0)}catch(w){throw r.options.audioCaptureDefaults.deviceId=D,w}const F=I.some(w=>{var P,L;return(L=(P=w.track)===null||P===void 0?void 0:P.isMuted)!==null&&L!==void 0?L:!1});_&&F&&(b=!0)}else if(i==="videoinput"){b=r.localParticipant.videoTrackPublications.size===0;const D=(c=r.getActiveDevice(i))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=S;const I=Array.from(r.localParticipant.videoTrackPublications.values()).filter(w=>w.source===ae.Source.Camera);try{_=(yield Promise.all(I.map(w=>{var P;return(P=w.videoTrack)===null||P===void 0?void 0:P.setDeviceId(S)}))).every(w=>w===!0)}catch(w){throw r.options.videoCaptureDefaults.deviceId=D,w}const F=I.some(w=>{var P,L;return(L=(P=w.track)===null||P===void 0?void 0:P.isMuted)!==null&&L!==void 0?L:!1});_&&F&&(b=!0)}else if(i==="audiooutput"){if(b=!0,!zu()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(l=yield It.getInstance().normalizeDeviceId("audiooutput",s))!==null&&l!==void 0?l:""),(u=(y=r.options).audioOutput)!==null&&u!==void 0||(y.audioOutput={});const D=(h=r.getActiveDevice(i))!==null&&h!==void 0?h:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((p=r.audioContext)===null||p===void 0||p.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(I=>I.setAudioOutput({deviceId:s})))}catch(I){throw r.options.audioOutput.deviceId=D,I}}return b&&(r.localParticipant.activeDeviceMap.set(i,s),r.emit(se.ActiveDeviceChanged,i,s)),_})()})}setupLocalParticipantEvents(){this.localParticipant.on(fe.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(fe.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(fe.AttributesChanged,this.onLocalAttributesChanged).on(fe.TrackMuted,this.onLocalTrackMuted).on(fe.TrackUnmuted,this.onLocalTrackUnmuted).on(fe.LocalTrackPublished,this.onLocalTrackPublished).on(fe.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(fe.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(fe.MediaDevicesError,this.onMediaDevicesError).on(fe.AudioStreamAcquired,this.startAudio).on(fe.ChatMessage,this.onLocalChatMessageSent).on(fe.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){const t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t==null||t.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===Be.Connecting||this.state===Be.Reconnecting){const h=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(y=>y.id)}),this.onTrackAdded(e,t,i),p()},p=()=>{this.off(se.Reconnected,h),this.off(se.Connected,h),this.off(se.Disconnected,p)};this.once(se.Reconnected,h),this.once(se.Connected,h),this.once(se.Disconnected,p);return}if(this.state===Be.Disconnected){this.log.warn("skipping incoming track after Room disconnected");return}if(e.readyState==="ended"){this.log.debug("skipping incoming track as it already ended");return}const s=lk(t.id),r=s[0];let a=s[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant");return}const c=Array.from(this.remoteParticipants.values()).find(h=>h.sid===r);if(!c){r.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r));return}if(!o.startsWith("TR")){const h=this.engine.getTrackIdForReceiver(i);if(!h){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r));return}o=h}o.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(a,", trackId: ").concat(o),{remoteParticipantID:r,streamId:a,trackId:o});let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={});const u=c.addSubscribedMediaTrack(e,o,t,i,l);u!=null&&u.isEncrypted&&!this.e2eeManager&&this.emit(se.EncryptionError,new Error("Encrypted ".concat(u.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleLocalTrackSubscribed(e){const t=()=>this.localParticipant.getTrackPublications().find(c=>c.trackSid===e),i=t();if(i){this.emitLocalTrackSubscribed(i);return}this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});const s=1e4;let r;const a=c=>{c.trackSid===e&&(o(),this.emitLocalTrackSubscribed(c))},o=()=>{clearTimeout(r),this.localParticipant.off(fe.LocalTrackPublished,a),this.off(se.Disconnected,o)};this.localParticipant.on(fe.LocalTrackPublished,a),this.once(se.Disconnected,o),r=setTimeout(()=>{o();const c=t();c?this.emitLocalTrackSubscribed(c):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:e})},s)}emitLocalTrackSubscribed(e){this.localParticipant.emit(fe.LocalTrackSubscribed,e),this.emitWhenConnected(se.LocalTrackSubscribed,e,this.localParticipant)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==Be.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(a=>{r.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var a,o,c;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((a=r.track)===null||a===void 0||a.detach(),(o=r.track)===null||o===void 0||o.stop()):(c=r.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(fe.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(fe.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(fe.AttributesChanged,this.onLocalAttributesChanged).off(fe.TrackMuted,this.onLocalTrackMuted).off(fe.TrackUnmuted,this.onLocalTrackUnmuted).off(fe.LocalTrackPublished,this.onLocalTrackPublished).off(fe.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(fe.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(fe.MediaDevicesError,this.onMediaDevicesError).off(fe.AudioStreamAcquired,this.startAudio).off(fe.ChatMessage,this.onLocalChatMessageSent).off(fe.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),oi()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||s===void 0||s.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Be.Disconnected),this.emit(se.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(se.ParticipantDisconnected,t),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return O(this,void 0,void 0,function*(){var e,t,i;const s=It.getInstance().previousDevices,r=yield It.getInstance().getDevices(void 0,!1),a=Yt();if((a==null?void 0:a.name)==="Chrome"&&a.os!=="iOS")for(let c of r){const l=s.find(u=>u.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(se.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let c of o){const l=ek(c),u=this.localParticipant.getTrackPublication(l);if(u&&(!((e=u.track)===null||e===void 0)&&e.isUserProvided))continue;const h=r.filter(y=>y.kind===c),p=this.getActiveDevice(c);if(p===((t=s.filter(y=>y.kind===c)[0])===null||t===void 0?void 0:t.deviceId)&&h.length>0&&((i=h[0])===null||i===void 0?void 0:i.deviceId)!==p){yield this.switchActiveDevice(c,h[0].deviceId);continue}c==="audioinput"&&!ya()||c==="videoinput"||h.length>0&&!h.find(y=>y.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!ya())&&(yield this.switchActiveDevice(c,h[0].deviceId))}})}acquireAudioContext(){return O(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Qm())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Vt(200)])}catch(s){this.log.warn("Could not resume audio context",{error:s})}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(se.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let s;return t?s=xc.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):s=new xc(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message))),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(se.ParticipantConnected,i),i.on(fe.TrackPublished,s=>{this.emitWhenConnected(se.TrackPublished,s,i)}).on(fe.TrackSubscribed,(s,r)=>{s.kind===ae.Kind.Audio?(s.on(he.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(he.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===ae.Kind.Video&&(s.on(he.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(he.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(se.TrackSubscribed,s,r,i)}).on(fe.TrackUnpublished,s=>{this.emit(se.TrackUnpublished,s,i)}).on(fe.TrackUnsubscribed,(s,r)=>{this.emit(se.TrackUnsubscribed,s,r,i)}).on(fe.TrackMuted,s=>{this.emitWhenConnected(se.TrackMuted,s,i)}).on(fe.TrackUnmuted,s=>{this.emitWhenConnected(se.TrackUnmuted,s,i)}).on(fe.ParticipantMetadataChanged,s=>{this.emitWhenConnected(se.ParticipantMetadataChanged,s,i)}).on(fe.ParticipantNameChanged,s=>{this.emitWhenConnected(se.ParticipantNameChanged,s,i)}).on(fe.AttributesChanged,s=>{this.emitWhenConnected(se.ParticipantAttributesChanged,s,i)}).on(fe.ConnectionQualityChanged,s=>{this.emitWhenConnected(se.ConnectionQualityChanged,s,i)}).on(fe.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(se.ParticipantPermissionsChanged,s,i)}).on(fe.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(se.TrackSubscriptionStatusChanged,s,r,i)}).on(fe.TrackSubscriptionFailed,(s,r)=>{this.emit(se.TrackSubscriptionFailed,s,i,r)}).on(fe.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(se.TrackSubscriptionPermissionChanged,s,r,i)}).on(fe.Active,()=>{this.emitWhenConnected(se.ParticipantActive,i),i.kind===er.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((s,r)=>(s.push(...r.getTrackPublications()),s),[]),t=this.localParticipant.getTrackPublications(),i=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,i)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Ck(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}getClientInfoCapabilities(e){var t;const i=[];return(Sa((t=e.frameMetadata)!==null&&t!==void 0?t:e.packetTrailer)||this.e2eeManager)&&i.push(ua.CAP_PACKET_TRAILER),Yn()&&i.push(ua.CAP_COMPRESSION_DEFLATE_RAW),i}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(T0,(e,t)=>O(this,[e,t],void 0,function(i,s){var r=this;let a=s.identity;return(function*(){var o;const c=(o=i.info.attributes)!==null&&o!==void 0?o:{};yield r.rpcServerManager.handleIncomingDataStream(i,a,c)})()})),this.incomingDataStreamManager.registerTextStreamHandler(_0,(e,t)=>O(this,[e,t],void 0,function(i,s){var r=this;let a=s.identity;return(function*(){var o;const c=(o=i.info.attributes)!==null&&o!==void 0?o:{};yield r.rpcClientManager.handleIncomingDataStream(i,a,c)})()}))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=ht.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Gt.STATE_MISMATCH))):e=0},C2)}clearConnectionReconcile(){this.connectionReconcileInterval&&ht.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.log.info("connection state changed: ".concat(this.state," -> ").concat(e)),this.state=e,this.incomingDataStreamManager.setConnected(e===Be.Connected),this.emit(se.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=_e(e,2),i=t[0],s=t[1];this.emit(i,...s)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(this.state===Be.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Be.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return O(this,void 0,void 0,function*(){var t,i,s,r;const a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Vo({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:nt.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new bs({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(se.SignalConnected),this.emit(se.Connected),this.setAndEmitConnectionState(Be.Connected),a.video){const c=new Rd(ae.Kind.Video,new tr({source:_t.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Li.AUDIO,name:"video-dummy"}),new fc(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:og(160*((i=o.aspectRatios[0])!==null&&i!==void 0?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(fe.LocalTrackPublished,c)}if(a.audio){const c=new Rd(ae.Kind.Audio,new tr({source:_t.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Li.AUDIO}),new dc(a.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Qu(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(fe.LocalTrackPublished,c)}for(let c=0;c<o.count-1;c+=1){let l=new bs({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:Zs.ACTIVE,tracks:[],joinedAt:nt.parse(Date.now())});const u=this.getOrCreateParticipant(l.identity,l);if(o.video){const h=og(160*((r=o.aspectRatios[c%o.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),p=new tr({source:_t.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Li.AUDIO});u.addSubscribedMediaTrack(h,p.sid,new MediaStream([h]),new RTCRtpReceiver),l.tracks=[...l.tracks,p]}if(o.audio){const h=Qu(),p=new tr({source:_t.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Li.AUDIO});u.addSubscribedMediaTrack(h,p.sid,new MediaStream([h]),new RTCRtpReceiver),l.tracks=[...l.tracks,p]}u.updateInfo(l)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(e!==se.ActiveSpeakersChanged&&e!==se.TranscriptionReceived){const r=x0(i).filter(a=>a!==void 0);(e===se.TrackSubscribed||e===se.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),{event:e,args:r}),this.log.debug("room event ".concat(e),{event:e,args:r})}return super.emit(e,...i)}}mr.cleanupRegistry=typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"&&new FinalizationRegistry(n=>{n()});function x0(n){return n.map(e=>{if(e)return Array.isArray(e)?x0(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var $i;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})($i||($i={}));class is extends ai.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=$i.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new mr(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return O(this,void 0,void 0,function*(){if(this.status!==$i.IDLE)throw Error("check is running already");this.setStatus($i.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==$i.SKIPPED&&this.setStatus(this.isSuccess()?$i.SUCCESS:$i.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return O(this,void 0,void 0,function*(){return this.room.state===Be.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return O(this,void 0,void 0,function*(){this.room&&this.room.state!==Be.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus($i.SKIPPED)}switchProtocol(e){return O(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(se.Reconnecting,()=>{t=!0}),this.room.once(se.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(i)return;yield Vt(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class k2 extends is{get description(){return"Cloud regions"}perform(){return O(this,void 0,void 0,function*(){const e=new Ue(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let r=0;r<3;r++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,a)=>(r.duration-a.duration)*.5+(r.rtt-a.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return O(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,c=1e6/a,l="A".repeat(a),u=Date.now();for(let _=0;_<c;_++)yield r.write(l);yield r.close();const h=Date.now(),p=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),y={region:s,rtt:1e4,duration:h-u};return p==null||p.forEach(_=>{_.type==="candidate-pair"&&_.nominated&&(y.rtt=_.currentRoundTripTime*1e3)}),yield this.disconnect(),y})}}const Od=1e4;class E2 extends is{get description(){return"Connection via UDP vs TCP"}perform(){return O(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(Od/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Od/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return O(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,i.fillStyle="hsl(".concat(s,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},h=setInterval(()=>O(this,void 0,void 0,function*(){const p=yield l.getRTCStatsReport();p==null||p.forEach(y=>{y.type==="outbound-rtp"?(u.packetsSent=y.packetsSent,u.qualityLimitationDurations=y.qualityLimitationDurations,u.bitrateTotal+=y.targetBitrate,u.count++):y.type==="remote-inbound-rtp"&&(u.packetsLost=y.packetsLost,u.rttTotal+=y.roundTripTime,u.jitterTotal+=y.jitter)})}),1e3);return yield new Promise(p=>setTimeout(p,Od)),clearInterval(h),o.stop(),t.remove(),yield this.disconnect(),u})}}class x2 extends is{get description(){return"Can publish audio"}perform(){return O(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield y2();if(yield Ym(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let a=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class w2 extends is{get description(){return"Can publish video"}perform(){return O(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield g2();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(r+=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return O(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(s=>{i.onplay=()=>{setTimeout(()=>{var r,a,o,c;const l=document.createElement("canvas"),u=e.getSettings(),h=(a=(r=u.width)!==null&&r!==void 0?r:i.videoWidth)!==null&&a!==void 0?a:1280,p=(c=(o=u.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;l.width=h,l.height=p;const y=l.getContext("2d");y.drawImage(i,0,0);const b=y.getImageData(0,0,l.width,l.height).data;let S=!0;for(let D=0;D<b.length;D+=4)if(b[D]!==0||b[D+1]!==0||b[D+2]!==0){S=!1;break}S?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},i.play()}),t.getTracks().forEach(s=>s.stop()),i.remove()})}}class A2 extends is{get description(){return"Resuming connection after interruption"}perform(){return O(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,s=!1,r;const a=new Promise(l=>{setTimeout(l,5e3),r=l}),o=()=>{i=!0};t.on(se.SignalReconnecting,o).on(se.Reconnecting,o).on(se.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,i){if(!s||t.state!==Be.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class D2 extends is{get description(){return"Can connect via TURN"}perform(){return O(this,void 0,void 0,function*(){var e,t,i;or(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new Ue(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new ud,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,c=!1;for(let l of r.iceServers)for(let u of l.urls)u.startsWith("turn:")?(o=!0,c=!0):u.startsWith("turns:")&&(o=!0,c=!0,a=!0),u.startsWith("stun:")&&(c=!0);c?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(l=>setTimeout(l,0)))})}}class P2 extends is{get description(){return"Establishing WebRTC connection"}perform(){return O(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(se.SignalConnected,()=>{var i;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,a)=>{if(r.candidate){const o=new RTCIceCandidate(r);let c="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(I2(o.address)?c+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,c+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(c)}s&&s(r,a)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),xe.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function I2(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class R2 extends is{get description(){return"Connecting to signal connection via WebSocket"}perform(){return O(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new ud,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(or(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const c=yield new Ue(this.url,this.token).getNextBestRegionUrl();c&&(r=yield s.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===Rp.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=r.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class rO extends ai.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:$i.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==$i.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return O(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),s=a=>{this.updateCheck(t,a)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return O(this,void 0,void 0,function*(){return this.createAndRunCheck(R2)})}checkWebRTC(){return O(this,void 0,void 0,function*(){return this.createAndRunCheck(P2)})}checkTURN(){return O(this,void 0,void 0,function*(){return this.createAndRunCheck(D2)})}checkReconnect(){return O(this,void 0,void 0,function*(){return this.createAndRunCheck(A2)})}checkPublishAudio(){return O(this,void 0,void 0,function*(){return this.createAndRunCheck(x2)})}checkPublishVideo(){return O(this,void 0,void 0,function*(){return this.createAndRunCheck(w2)})}checkConnectionProtocol(){return O(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(E2);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return O(this,void 0,void 0,function*(){return this.createAndRunCheck(k2)})}}new TextEncoder,new TextDecoder;class Jt extends Error{constructor(e,t){var i;super(e,t),Fe(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}Fe(Jt,"code","ERR_JOSE_GENERIC");class O2 extends Jt{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),Fe(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Fe(this,"claim",void 0),Fe(this,"reason",void 0),Fe(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}Fe(O2,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class M2 extends Jt{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),Fe(this,"code","ERR_JWT_EXPIRED"),Fe(this,"claim",void 0),Fe(this,"reason",void 0),Fe(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}Fe(M2,"code","ERR_JWT_EXPIRED");class L2 extends Jt{constructor(){super(...arguments),Fe(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Fe(L2,"code","ERR_JOSE_ALG_NOT_ALLOWED");class N2 extends Jt{constructor(){super(...arguments),Fe(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Fe(N2,"code","ERR_JOSE_NOT_SUPPORTED");class F2 extends Jt{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),Fe(this,"code","ERR_JWE_DECRYPTION_FAILED")}}Fe(F2,"code","ERR_JWE_DECRYPTION_FAILED");class U2 extends Jt{constructor(){super(...arguments),Fe(this,"code","ERR_JWE_INVALID")}}Fe(U2,"code","ERR_JWE_INVALID");class B2 extends Jt{constructor(){super(...arguments),Fe(this,"code","ERR_JWS_INVALID")}}Fe(B2,"code","ERR_JWS_INVALID");class q2 extends Jt{constructor(){super(...arguments),Fe(this,"code","ERR_JWT_INVALID")}}Fe(q2,"code","ERR_JWT_INVALID");class V2 extends Jt{constructor(){super(...arguments),Fe(this,"code","ERR_JWK_INVALID")}}Fe(V2,"code","ERR_JWK_INVALID");class j2 extends Jt{constructor(){super(...arguments),Fe(this,"code","ERR_JWKS_INVALID")}}Fe(j2,"code","ERR_JWKS_INVALID");class H2 extends Jt{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),Fe(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}Fe(H2,"code","ERR_JWKS_NO_MATCHING_KEY");class $2 extends Jt{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),Fe(this,Symbol.asyncIterator,void 0),Fe(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}Fe($2,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class W2 extends Jt{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),Fe(this,"code","ERR_JWKS_TIMEOUT")}}Fe(W2,"code","ERR_JWKS_TIMEOUT");class z2 extends Jt{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),Fe(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}Fe(z2,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");class G2{constructor(e){if(e){this.element=e,this.owned=!1;return}this.element=document.createElement("div"),this.element.style.display="none",document.body.appendChild(this.element),this.owned=!0}attach(e){this.element.appendChild(e.attach())}detach(e){e.detach().forEach(t=>t.remove())}clear(){this.element.replaceChildren()}destroy(){this.clear(),this.owned&&this.element.remove()}}class K2{constructor(){this.listeners=new Map}on(e,t){let i=this.listeners.get(e);i||(i=new Set,this.listeners.set(e,i)),i.add(t)}off(e,t){var i;(i=this.listeners.get(e))==null||i.delete(t)}once(e,t){const i=s=>{this.off(e,i),t(s)};this.on(e,i)}emit(e,t){const i=this.listeners.get(e);if(i)for(const s of[...i])s(t)}clear(){this.listeners.clear()}}const X2={AUDIO_PLAYBACK_BLOCKED:"Tap Enable sound to hear the agent",INVALID_PARAMS:"accessToken и url обязательны",WEBRTC_UNSUPPORTED:"браузер/контекст не поддерживает WebRTC (нужен HTTPS)",MICROPHONE_PERMISSION_DENIED:"доступ к микрофону запрещён пользователем",MICROPHONE_UNAVAILABLE:"микрофон недоступен или занят другим приложением",TOKEN_EXPIRED:"срок действия токена истёк",TOKEN_INVALID:"сервер отклонил токен",CONNECTION_FAILED:"не удалось установить соединение",CONNECTION_LOST:"соединение потеряно, реконнект не восстановил его",ALREADY_IN_CALL:"звонок уже активен",NOT_IN_CALL:"нет активного звонка",SERVER_ERROR:"внутренняя ошибка сервиса сигналинга"};class Y2 extends Error{constructor(e,t,i){super(X2[e]),this.name="VoiceCallError",this.code=e,this.state=t,this.cause=i}}function Q2(n){if(n instanceof Se)switch(n.reason){case He.NotAllowed:return"TOKEN_INVALID";case He.ServerUnreachable:case He.Timeout:case He.WebSocket:return"CONNECTION_FAILED";default:return"SERVER_ERROR"}return"SERVER_ERROR"}function J2(n){return en.getFailure(n)===en.PermissionDenied?"MICROPHONE_PERMISSION_DENIED":"MICROPHONE_UNAVAILABLE"}function Z2(n){const e=en.getFailure(n);return e===en.PermissionDenied?"MICROPHONE_PERMISSION_DENIED":e===en.NotFound||e===en.DeviceInUse||n instanceof DOMException&&["AbortError","OverconstrainedError","SecurityError","InvalidStateError","NotSupportedError"].includes(n.name)?"MICROPHONE_UNAVAILABLE":"SERVER_ERROR"}const w0="[redacted]",e1=/^[\w-]+\.[\w-]+\.[\w-]+$/,t1=/token/i;function wc(n){if(typeof n=="string")return e1.test(n)?w0:n;if(Array.isArray(n))return n.map(wc);if(n&&typeof n=="object"){const e={};for(const[t,i]of Object.entries(n))e[t]=t1.test(t)?w0:wc(i);return e}return n}function i1(n,e){if(n==="silent")return{error:()=>{},debug:()=>{}};const t=e??{error:(i,...s)=>console.error(i,...s),debug:(i,...s)=>console.debug(i,...s)};return{error:(i,...s)=>t.error(i,...s.map(wc)),debug:(i,...s)=>{n==="debug"&&t.debug(i,...s.map(wc))}}}function n1(n=!0){var e;return typeof window>"u"||!window.isSecureContext||typeof RTCPeerConnection>"u"?!1:n?typeof navigator<"u"&&!!((e=navigator.mediaDevices)!=null&&e.getUserMedia):!0}function s1(n){const e=n.split(".")[1];if(!e)return null;try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=decodeURIComponent(Array.from(atob(t)).map(r=>"%"+r.charCodeAt(0).toString(16).padStart(2,"0")).join("")),s=JSON.parse(i);return typeof s.exp=="number"?s.exp:null}catch{return null}}const r1="lk.agent.state",a1=new Set(["initializing","listening","thinking","speaking"]),A0="lk.publish_on_behalf",o1=new Set([Gt.ROOM_DELETED,Gt.PARTICIPANT_REMOVED,Gt.SERVER_SHUTDOWN,Gt.ROOM_CLOSED]),Md=new Set(["connecting","connected","reconnecting"]),D0="lk.transcription",c1="lk.chat",l1="lk.segment_id",u1="lk.transcription_final",d1=1e3;class h1{constructor(e={}){this.emitter=new K2,this.connectionState="idle",this.agentState="unknown",this.room=null,this.callId=null,this.playAudio=!0,this.agentVideoTrack=null,this.agentVideoElements=new Set,this.microphoneEnabled=!1,this.microphoneOperation=Promise.resolve(),this.stoppingLocally=!1,this.reconnectSeen=!1,this.destroyed=!1,this.roomCleanup=[],this.audio=new G2(e.audioContainer),this.log=i1(e.logLevel??"error",e.logger),this.connectTimeoutMs=e.connectTimeoutMs}getState(){return this.connectionState}getAgentState(){return this.agentState}getCallId(){return this.callId}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}once(e,t){this.emitter.once(e,t)}async startCall(e,t={}){if(this.destroyed)throw new Error("VoiceClient has been destroyed");if(Md.has(this.connectionState))throw this.raiseError("ALREADY_IN_CALL",this.connectionState);const i=t.audio!==!1;this.playAudio=i;const{accessToken:s,url:r}=this.validateStartParams(e,i);this.stoppingLocally=!1,this.reconnectSeen=!1,this.setConnectionState("connecting");const a=new mr;if(this.room=a,this.wireRoomEvents(a),await this.connectRoom(a,r,s),this.stoppingLocally||this.destroyed||this.room!==a){await this.abandonConnectingCall(a);return}if(i&&await this.publishMicrophone(a),this.stoppingLocally||this.destroyed||this.room!==a){await this.abandonConnectingCall(a);return}if(i)try{await a.startAudio()}catch{this.room===a&&!this.destroyed&&this.emitter.emit("audioPlaybackBlocked",{})}if(this.stoppingLocally||this.destroyed||this.room!==a){await this.abandonConnectingCall(a);return}this.callId=a.name,this.setConnectionState("connected"),this.syncAgentState(a),this.emitter.emit("callStarted",{callId:this.callId})}validateStartParams(e,t){const i=e.accessToken??e.access_token,s=e.url;if(!i||!s)throw this.raiseError("INVALID_PARAMS","error");if(!n1(t))throw this.raiseError("WEBRTC_UNSUPPORTED","error");const r=s1(i);if(r!==null&&r*1e3<=Date.now())throw this.raiseError("TOKEN_EXPIRED","error");return{accessToken:i,url:s}}async connectRoom(e,t,i){try{await e.connect(t,i,this.connectTimeoutMs===void 0?void 0:{peerConnectionTimeout:this.connectTimeoutMs,websocketTimeout:this.connectTimeoutMs})}catch(s){if(this.destroyed||this.room!==e)return;throw this.teardownRoom(),this.raiseError(Q2(s),"error",s)}}async abandonConnectingCall(e){await e.disconnect().catch(()=>{}),this.room===e&&this.teardownRoom(),!this.destroyed&&!this.room&&this.setConnectionState("disconnected")}async publishMicrophone(e){try{await e.localParticipant.setMicrophoneEnabled(!0),this.room===e&&!this.destroyed&&this.confirmMicrophone(e.localParticipant.isMicrophoneEnabled)}catch(t){if(this.destroyed||this.room!==e)return;const i=J2(t);throw await e.disconnect().catch(()=>{}),this.teardownRoom(),this.raiseError(i,"error",t)}}isMicrophoneEnabled(){return this.microphoneEnabled}async setMicrophoneEnabled(e){const t=this.room;if(!t||!this.playAudio||this.connectionState!=="connected")throw this.raiseError("NOT_IN_CALL",this.connectionState);const i=this.microphoneOperation.then(async()=>{if(!t||this.room!==t||!this.playAudio||this.connectionState!=="connected")throw this.raiseError("NOT_IN_CALL",this.connectionState);try{await t.localParticipant.setMicrophoneEnabled(e)}catch(s){throw this.raiseError(Z2(s),this.connectionState,s)}this.room===t&&!this.destroyed&&this.confirmMicrophone(t.localParticipant.isMicrophoneEnabled)});return this.microphoneOperation=i.catch(()=>{}),i}async resumeAudio(){const e=this.room;if(!e||!this.playAudio||this.connectionState!=="connected")throw this.raiseError("NOT_IN_CALL",this.connectionState);try{await e.startAudio()}catch(t){throw this.room===e&&!this.destroyed&&this.emitter.emit("audioPlaybackBlocked",{}),this.raiseError("AUDIO_PLAYBACK_BLOCKED",this.connectionState,t)}}attachAgentVideo(e){return!this.room||this.destroyed?()=>{}:(this.agentVideoElements.add(e),this.agentVideoTrack&&this.agentVideoTrack.attach(e),()=>{var t;this.agentVideoElements.delete(e),(t=this.agentVideoTrack)==null||t.detach(e)})}confirmMicrophone(e){this.microphoneEnabled!==e&&(this.microphoneEnabled=e,this.emitter.emit("microphoneStateChanged",{enabled:e}))}async sendText(e){const t=this.room;if(!t||!Md.has(this.connectionState))throw this.raiseError("NOT_IN_CALL",this.connectionState);const i=e.trim().slice(0,d1);if(i)try{await t.localParticipant.sendText(i,{topic:c1})}catch(s){throw this.raiseError("SERVER_ERROR",this.connectionState,s)}}async stopCall(){this.stoppingLocally=!0;const e=this.room;!e||!Md.has(this.connectionState)||this.connectionState!=="connecting"&&await e.disconnect().catch(t=>this.log.debug("[voice-client] disconnect",t))}destroy(){this.stopCall(),this.playAudio=!0,this.destroyed=!0,this.teardownRoom(),this.emitter.clear(),this.audio.destroy(),this.agentVideoElements.clear(),this.connectionState="idle",this.agentState="unknown",this.callId=null}wireRoomEvents(e){const t=(u,h,p)=>{this.log.debug("[voice-client] remote track subscribed",{participant:p.identity,participantID:p.sid,trackID:u.sid,streamTrackID:u.mediaStreamTrack.id,kind:u.kind,source:h.source,muted:h.isMuted}),u.kind===ae.Kind.Audio&&this.playAudio&&this.audio.attach(u),u.kind===ae.Kind.Video&&this.syncAgentVideo(e)},i=(u,h,p)=>{this.log.debug("[voice-client] remote track unsubscribed",{participant:p.identity,participantID:p.sid,trackID:u.sid,kind:u.kind,source:h.source}),u.kind===ae.Kind.Audio&&this.audio.detach(u),u.kind===ae.Kind.Video&&this.syncAgentVideo(e)},s=(u,h,p)=>{this.log.debug("[voice-client] remote track subscription failed",{participant:h.identity,participantID:h.sid,trackID:u,reason:p})},r=u=>{this.log.debug("[voice-client] remote participant connected",{room:e.name,participant:u.identity,participantID:u.sid}),!this.destroyed&&this.syncAgentState(e)},a=()=>{this.destroyed||(this.syncAgentState(e),this.syncAgentVideo(e))},o=u=>{this.destroyed||this.applyLkConnectionState(u)},c=u=>{this.log.debug("[voice-client] room disconnected",{room:e.name,reason:u,stoppingLocally:this.stoppingLocally}),!this.destroyed&&this.handleDisconnected(u)};e.registerTextStreamHandler(D0,(u,h)=>{if(this.destroyed)return;const p=h.identity===e.localParticipant.identity?"user":"agent";this.readTranscriptSegment(u,p,e)});const l=()=>{this.playAudio&&!e.canPlaybackAudio&&!this.destroyed&&this.emitter.emit("audioPlaybackBlocked",{})};e.on(se.AudioPlaybackStatusChanged,l),e.on(se.TrackSubscribed,t),e.on(se.TrackUnsubscribed,i),e.on(se.TrackSubscriptionFailed,s),e.on(se.ParticipantAttributesChanged,a),e.on(se.ParticipantConnected,r),e.on(se.ParticipantDisconnected,a),e.on(se.ConnectionStateChanged,o),e.on(se.Disconnected,c),this.roomCleanup=[()=>e.off(se.AudioPlaybackStatusChanged,l),()=>e.unregisterTextStreamHandler(D0),()=>e.off(se.TrackSubscribed,t),()=>e.off(se.TrackUnsubscribed,i),()=>e.off(se.TrackSubscriptionFailed,s),()=>e.off(se.ParticipantAttributesChanged,a),()=>e.off(se.ParticipantConnected,r),()=>e.off(se.ParticipantDisconnected,a),()=>e.off(se.ConnectionStateChanged,o),()=>e.off(se.Disconnected,c)]}readTranscriptSegment(e,t,i){var r;const s=((r=e.info.attributes)==null?void 0:r[l1])||e.info.id;(async()=>{var o;let a="";try{for await(const c of e){if(this.destroyed||this.room!==i)return;a+=c,this.emitter.emit("transcript",{role:t,text:a,final:!1,id:s})}}catch{return}!this.destroyed&&this.room===i&&((o=e.info.attributes)==null?void 0:o[u1])==="true"&&this.emitter.emit("transcript",{role:t,text:a,final:!0,id:s})})()}applyLkConnectionState(e){var t;e===Be.Reconnecting||e===Be.SignalReconnecting?(this.reconnectSeen=!0,this.setConnectionState("reconnecting")):e===Be.Connected&&this.connectionState==="reconnecting"&&(this.confirmMicrophone(this.playAudio&&!!((t=this.room)!=null&&t.localParticipant.isMicrophoneEnabled)),this.setConnectionState("connected"))}handleDisconnected(e){const t=this.callId,i=this.reconnectSeen,s=this.stoppingLocally;if(this.teardownRoom(),s){this.setConnectionState("disconnected"),this.emitter.emit("callEnded",{callId:t,reason:"local"});return}if(i){this.setConnectionState("disconnected"),this.raiseError("CONNECTION_LOST","disconnected"),this.emitter.emit("callEnded",{callId:t,reason:"connection_lost"});return}const a=e!==void 0&&o1.has(e)?"remote":"error";this.setConnectionState("disconnected"),this.emitter.emit("callEnded",{callId:t,reason:a})}teardownRoom(){this.confirmMicrophone(!1),this.setAgentVideoTrack(null),this.roomCleanup.forEach(e=>e()),this.roomCleanup=[],this.audio.clear(),this.room=null,this.agentState="unknown"}syncAgentState(e){var i,s;let t="unknown";for(const r of e.remoteParticipants.values()){if((i=r.attributes)!=null&&i[A0])continue;const a=(s=r.attributes)==null?void 0:s[r1];if(a&&a1.has(a)){t=a;break}}this.setAgentState(t)}findAgentVideoTrack(e){var t;for(const i of e.remoteParticipants.values()){const s=(t=i.attributes)==null?void 0:t[A0];if(!(!s||i.kind!==er.AGENT)&&e.remoteParticipants.has(s))for(const r of i.videoTrackPublications.values()){const a=r.track;if(a&&r.isSubscribed)return a}}return null}syncAgentVideo(e){this.destroyed||this.room!==e||this.setAgentVideoTrack(this.findAgentVideoTrack(e))}setAgentVideoTrack(e){const t=this.agentVideoTrack;t!==e&&(t&&this.agentVideoElements.forEach(i=>t.detach(i)),this.agentVideoTrack=e,e&&this.agentVideoElements.forEach(i=>e.attach(i)),!!t!=!!e&&this.emitter.emit("agentVideoChanged",{available:!!e}))}setConnectionState(e){const t=this.connectionState;t!==e&&(this.connectionState=e,this.emitter.emit("connectionStateChanged",{state:e,previous:t}))}setAgentState(e){const t=this.agentState;t!==e&&(this.agentState=e,this.emitter.emit("agentStateChanged",{state:e,previous:t}),e==="speaking"?this.emitter.emit("agentSpeakingStarted",{}):t==="speaking"&&this.emitter.emit("agentSpeakingStopped",{}))}raiseError(e,t,i){t!==this.connectionState&&this.setConnectionState(t);const s=new Y2(e,this.connectionState,i);return this.log.error(`[voice-client] ${e}`,i),this.emitter.emit("error",s),s}}function f1(n,e,t,i,s){var Q,re;const r=document.createElement("button");r.type="button",r.className="ht-avatar";const a=document.createElement("img");a.src=e.posterUrl,a.alt="";const o=document.createElement("span");o.className="ht-avatar-video",o.setAttribute("aria-hidden","true");const c=document.createElement("video");c.className="ht-avatar-live",c.muted=!0,c.autoplay=!0,c.playsInline=!0,c.controls=!1,c.setAttribute("tabindex","-1"),c.setAttribute("aria-hidden","true"),c.hidden=!0;const l=document.createElement("span");l.className="ht-avatar-ai",l.id=`ht-avatar-ai-${Math.random().toString(36).slice(2,8)}`,l.textContent="AI avatar",l.hidden=!0;const u=document.createElement("span");u.className="ht-mic",u.setAttribute("aria-hidden","true"),u.innerHTML='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v2a7 7 0 0014 0v-2M12 19v3M8 22h8"/><path class="ht-mic-slash" d="M2 2l20 20"/></svg>';const h=document.createElement("span");h.className="ht-avatar-status",h.setAttribute("role","status"),r.append(a,o,c,u,h,l),n.append(r);const p=new AbortController,y=window.matchMedia("(prefers-reduced-motion: reduce)");let _,b=!1,S=!1,D,I=!1,F=!1,w="",P=!1,L=!1,C=!1,N=!1,x,k;function j(){const Y=window.visualViewport,ie=(Y==null?void 0:Y.offsetLeft)??0,ge=(Y==null?void 0:Y.offsetTop)??0,Te=(Y==null?void 0:Y.width)??innerWidth,be=(Y==null?void 0:Y.height)??innerHeight,we=r.offsetWidth||e.size||140,Pe=n.querySelector(".ht-panel"),ve=Pe.getBoundingClientRect();let qe=(x==null?void 0:x.x)??ie+Te-we-20,bt=(x==null?void 0:x.y)??ge+be-we-100;!Pe.hidden&&qe+we>ve.left&&qe<ve.right&&bt+we+32>ve.top&&bt<ve.bottom&&(ve.left-we-16>=ie+8?qe=ve.left-we-16:bt=ve.top-we-40),qe=Math.max(ie+8,Math.min(qe,ie+Te-we-8)),bt=Math.max(ge+8,Math.min(bt,ge+be-we-40)),r.style.left=`${qe}px`,r.style.top=`${bt}px`,x&&(x={x:qe,y:bt})}function G(){if(I)return;if(S){o.hidden=!0,_==null||_.pause();return}if(y.matches){o.hidden=!0,_==null||_.pause();return}if(!_){X();return}o.hidden=!0;const Y=F?e.speakingVideoUrl:e.listeningVideoUrl;Y!==w&&(w=Y,_.src({src:Y,type:"video/mp4"}));const ie=_.play();ie&&ie.catch(()=>{o.hidden=!0})}o.hidden=!0;function X(){b||_||I||(b=!0,Promise.resolve().then(()=>vI).then(({default:Y})=>{if(I||S)return;const ie=document.createElement("video");ie.className="video-js",ie.muted=!0,ie.loop=!0,ie.playsInline=!0,ie.controls=!1,ie.setAttribute("tabindex","-1"),o.append(ie),_=Y(ie,{controls:!1,muted:!0,loop:!0,playsinline:!0,preload:"none",poster:e.posterUrl,children:["mediaLoader"]}),_.on("playing",()=>{y.matches||(o.hidden=!1)}),_.on("waiting",()=>{o.hidden=!0}),_.on("error",()=>{o.hidden=!0}),G()}).catch(()=>{o.hidden=!0}))}function z(Y){var ie;if(!(I||S===Y)){if(S=Y,D==null||D(),D=void 0,Y){D=t.attachAgentVideo(c);try{(ie=c.play())==null||ie.catch(()=>{})}catch{}}c.hidden=!Y,l.hidden=!Y,Y?r.setAttribute("aria-describedby",l.id):r.removeAttribute("aria-describedby"),G()}}t.on("agentVideoChanged",({available:Y})=>z(Y)),G(),y.addEventListener("change",G,{signal:p.signal}),r.addEventListener("pointerdown",Y=>{if(Y.button!==0||!Y.isPrimary)return;C=!1,N=!1;const ie=r.getBoundingClientRect();k={id:Y.pointerId,x:Y.clientX,y:Y.clientY,left:ie.left,top:ie.top},r.setPointerCapture(Y.pointerId)},{signal:p.signal}),r.addEventListener("pointermove",Y=>{if(!k||Y.pointerId!==k.id)return;const ie=Y.clientX-k.x,ge=Y.clientY-k.y;!N&&Math.hypot(ie,ge)<6||(N=!0,C=!0,x={x:k.left+ie,y:k.top+ge},j())},{signal:p.signal});const W=()=>{k=void 0};r.addEventListener("pointerup",Y=>{(k==null?void 0:k.id)===Y.pointerId&&Y.pointerType==="touch"&&!N&&(Y.preventDefault(),C=!0,te()),W()},{signal:p.signal}),r.addEventListener("pointercancel",()=>{C=!0,W()},{signal:p.signal}),r.addEventListener("lostpointercapture",W,{signal:p.signal}),r.addEventListener("click",Y=>{if(Y.detail!==0&&C){C=!1;return}te()},{signal:p.signal});function te(){if(!(L||P)){if(t.getState()!=="connected"){i();return}P=!0,t.setMicrophoneEnabled(!t.isMicrophoneEnabled()).catch(s).finally(()=>{P=!1})}}return window.addEventListener("resize",j,{signal:p.signal}),(Q=window.visualViewport)==null||Q.addEventListener("resize",j,{signal:p.signal}),(re=window.visualViewport)==null||re.addEventListener("scroll",j,{signal:p.signal}),j(),{reposition:j,update(Y,ie){const ge=t.getState(),Te=t.getAgentState(),be=t.isMicrophoneEnabled(),we=ge==="connected";L=Y||ge==="connecting"||ge==="reconnecting"||we&&!ie,r.setAttribute("aria-disabled",String(L)),r.setAttribute("aria-pressed",String(be)),r.setAttribute("aria-label",we?be?"Mute microphone":"Unmute microphone":"Start voice call"),u.classList.toggle("ht-muted",!be);const Pe=we&&Te==="speaking";F!==Pe&&(F=Pe,G());const ve=Y||ge==="connecting"?"Connecting":ge==="reconnecting"?"Reconnecting":we?F?"Speaking":ie?be?Te==="listening"?"Listening":Te==="thinking"?"Thinking":"Getting ready":"Microphone off":"Text chat":"Tap to talk";h.textContent=ve,r.dataset.state=F?"speaking":we&&be&&Te==="listening"?"listening":"idle"},destroy(){I=!0,p.abort(),D==null||D(),D=void 0,_==null||_.dispose(),r.remove()}}}const p1=140,m1='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M6.6 10.8a15.1 15.1 0 0 0 6.6 6.6l2.2-2.2a1 1 0 0 1 1-.25c1.1.37 2.3.57 3.6.57a1 1 0 0 1 1 1V20a1 1 0 0 1-1 1C10.6 21 3 13.4 3 4a1 1 0 0 1 1-1h3.5a1 1 0 0 1 1 1c0 1.3.2 2.5.57 3.6a1 1 0 0 1-.25 1l-2.2 2.2Z" fill="currentColor"/></svg>',g1='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.4 3.3A1 1 0 0 1 4 18.5v-13Z" fill="currentColor"/></svg>',y1='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M6 9l6 6 6-6" stroke="currentColor" stroke-width="2" fill="none"/></svg>',v1='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 19V5m0 0-6 6m6-6 6 6" stroke="currentColor" stroke-width="2"/></svg>';function b1(n){var X;const e=n.mode==="avatar",t=n.avatar;if(e&&(!t||[t.posterUrl,t.listeningVideoUrl,t.speakingVideoUrl].some(z=>typeof z!="string"||!z.trim())))throw new Error("Avatar mode requires posterUrl, listeningVideoUrl and speakingVideoUrl");if((t==null?void 0:t.size)!==void 0&&!(Number.isFinite(t.size)&&t.size>0))throw new Error("avatar.size must be a positive number of pixels");const i=document.createElement("div");i.className="ht-widget",i.dataset.mode=n.mode??"standard",t!=null&&t.size&&i.style.setProperty("--ht-avatar-size",`${t.size}px`),i.innerHTML=`<button type="button" class="ht-launcher" aria-label="Open chat" aria-expanded="false">${e?g1:m1}<span class="ht-live-dot" hidden></span></button>
|
|
40
|
+
<section class="ht-panel" aria-label="Voice agent" hidden>
|
|
41
|
+
<header class="ht-head"><span class="ht-title">Voice agent</span><span class="ht-pill" role="status">Ready</span><span class="ht-timer" hidden>0:00</span><button type="button" class="ht-icon ht-collapse" aria-label="Close chat">${y1}</button></header>
|
|
42
|
+
<details class="ht-details" open><summary>Call details</summary><div class="ht-fields"></div></details>
|
|
43
|
+
<div class="ht-log" role="log" aria-label="Conversation"><p class="ht-empty">Press Call to talk, or Chat to type.</p></div>
|
|
44
|
+
<pre class="ht-debug"></pre>
|
|
45
|
+
<button type="button" class="ht-btn ht-btn-ghost ht-enable-sound" hidden>Enable sound</button>
|
|
46
|
+
<form class="ht-composer"><input aria-label="Message" placeholder="Type a reply and press Enter…" maxlength="1000" disabled><button type="submit" class="ht-icon" aria-label="Send" disabled>${v1}</button></form>
|
|
47
|
+
<div class="ht-actions"><button type="button" class="ht-btn ht-call-button">Call</button><button type="button" class="ht-btn ht-btn-ghost ht-chat-only" title="No microphone or audio">Chat</button><button type="button" class="ht-btn ht-btn-danger ht-end" disabled>${e?"End call":"Hang up"}</button></div>
|
|
48
|
+
</section>`;const s=z=>i.querySelector(z),r=s(".ht-launcher"),a=s(".ht-panel"),o=s(".ht-details"),c=s(".ht-log"),l=s(".ht-composer input"),u=s(".ht-composer button"),h=s(".ht-call-button"),p=s(".ht-chat-only"),y=s(".ht-end"),_=s(".ht-enable-sound"),b=s(".ht-timer");(X=n.renderCallDetails)==null||X.call(n,s(".ht-fields")),o.hidden=!n.renderCallDetails,n.container.append(i);const S=new h1,D=new AbortController,I=new Map;let F=!1,w=!1,P=!0,L,C;function N(z){a.hidden=!z,r.hidden=!e&&z,r.setAttribute("aria-expanded",String(z)),C==null||C.reposition()}function x(z){const W=document.createElement("p");W.className="ht-msg system",W.textContent=z,c.append(W),N(!0)}function k(){if(F)return;const z=S.getState(),W=["connecting","connected","reconnecting"].includes(z),te=w||W;h.disabled=p.disabled=te,y.disabled=!W,l.disabled=u.disabled=z!=="connected",s(".ht-live-dot").hidden=!W;const Q=S.getAgentState();s(".ht-pill").className=`ht-pill ${Q}`,s(".ht-pill").textContent=w||z==="connecting"?"Connecting…":z==="reconnecting"?"Reconnecting…":Q==="unknown"?"Ready":Q[0].toUpperCase()+Q.slice(1),s(".ht-debug").textContent=`state: ${z} · agent: ${Q}${S.getCallId()?`
|
|
49
|
+
callId: `+S.getCallId():""}`,C==null||C.update(w,P)}async function j(z){if(!(w||["connecting","connected","reconnecting"].includes(S.getState()))){w=!0,P=z,_.hidden=!0,k();try{const W=await n.createSession({avatar:e});F||await S.startCall(W,{audio:z})}catch{!F&&S.getState()!=="error"&&x("Could not start the call. Check the call details and try again.")}finally{w=!1,k()}}}function G(z,W,te){z.addEventListener(W,te,{signal:D.signal})}return G(r,"click",()=>N(a.hidden)),G(s(".ht-collapse"),"click",()=>{N(!1),r.focus()}),G(h,"click",()=>{j(!0)}),G(p,"click",()=>{j(!1)}),G(y,"click",()=>{S.stopCall()}),G(_,"click",()=>{S.resumeAudio().then(()=>{_.hidden=!0},()=>{_.hidden=!1})}),G(s(".ht-composer"),"submit",z=>{z.preventDefault();const W=l.value;W.trim()&&S.sendText(W).then(()=>{l.value===W&&(l.value="")},()=>{})}),S.on("connectionStateChanged",k),S.on("agentStateChanged",k),S.on("microphoneStateChanged",k),S.on("audioPlaybackBlocked",()=>{_.hidden=!1,N(!0)}),S.on("callStarted",()=>{c.replaceChildren(),I.clear(),o.hidden=!0;const z=Date.now();clearInterval(L),b.hidden=!1;const W=()=>{const te=Math.floor((Date.now()-z)/1e3);b.textContent=`${Math.floor(te/60)}:${String(te%60).padStart(2,"0")}`};W(),L=setInterval(W,1e3),k()}),S.on("callEnded",z=>{clearInterval(L),b.hidden=!0,_.hidden=!0,o.hidden=!n.renderCallDetails,I.clear(),x(z.reason==="remote"?"The agent ended the call.":z.reason==="connection_lost"?"Connection lost. Try calling again.":"Call ended."),k()}),S.on("error",z=>{x({MICROPHONE_PERMISSION_DENIED:"Allow microphone access in your browser, then try again.",MICROPHONE_UNAVAILABLE:"Microphone unavailable. Check your device or use Chat.",AUDIO_PLAYBACK_BLOCKED:"Tap Enable sound to hear the agent."}[z.code]??`${z.code}: Please try again.`),k()}),S.on("transcript",z=>{var te;(te=s(".ht-empty"))==null||te.remove();let W=I.get(z.id);W||(W=document.createElement("div"),I.set(z.id,W),c.append(W)),W.className=`ht-msg ${z.role}${z.final?"":" interim"}`,W.textContent=z.text,c.scrollTop=c.scrollHeight}),e&&(C=f1(i,n.avatar,S,()=>j(!0),()=>N(!0))),k(),{destroy(){F||(F=!0,D.abort(),clearInterval(L),C==null||C.destroy(),S.destroy(),i.remove(),I.clear())}}}var Ac=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ra(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function T1(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var e=n.default;if(typeof e=="function"){var t=function i(){return this instanceof i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(i){var s=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:function(){return n[i]}})}),t}var Ld,P0;function Dc(){if(P0)return Ld;P0=1;var n;return typeof window<"u"?n=window:typeof Ac<"u"?n=Ac:typeof self<"u"?n=self:n={},Ld=n,Ld}var _1=Dc();const B=Ra(_1),S1=T1(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var Nd,I0;function R0(){if(I0)return Nd;I0=1;var n=typeof Ac<"u"?Ac:typeof window<"u"?window:{},e=S1,t;return typeof document<"u"?t=document:(t=n["__GLOBAL_DOCUMENT_CACHE@4"],t||(t=n["__GLOBAL_DOCUMENT_CACHE@4"]=e)),Nd=t,Nd}var C1=R0();const de=Ra(C1);var Pc={exports:{}},Fd={exports:{}},O0;function k1(){return O0||(O0=1,(function(n){function e(){return n.exports=e=Object.assign?Object.assign.bind():function(t){for(var i=1;i<arguments.length;i++){var s=arguments[i];for(var r in s)({}).hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t},n.exports.__esModule=!0,n.exports.default=n.exports,e.apply(null,arguments)}n.exports=e,n.exports.__esModule=!0,n.exports.default=n.exports})(Fd)),Fd.exports}var Ud,M0;function E1(){if(M0)return Ud;M0=1,Ud=e;var n=Object.prototype.toString;function e(t){if(!t)return!1;var i=n.call(t);return i==="[object Function]"||typeof t=="function"&&i!=="[object RegExp]"||typeof window<"u"&&(t===window.setTimeout||t===window.alert||t===window.confirm||t===window.prompt)}return Ud}var Bd,L0;function x1(){if(L0)return Bd;L0=1;function n(s,r){var a=typeof Symbol<"u"&&s[Symbol.iterator]||s["@@iterator"];if(a)return(a=a.call(s)).next.bind(a);if(Array.isArray(s)||(a=e(s))||r){a&&(s=a);var o=0;return function(){return o>=s.length?{done:!0}:{done:!1,value:s[o++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
50
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function e(s,r){if(s){if(typeof s=="string")return t(s,r);var a=Object.prototype.toString.call(s).slice(8,-1);if(a==="Object"&&s.constructor&&(a=s.constructor.name),a==="Map"||a==="Set")return Array.from(s);if(a==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a))return t(s,r)}}function t(s,r){(r==null||r>s.length)&&(r=s.length);for(var a=0,o=new Array(r);a<r;a++)o[a]=s[a];return o}var i=(function(){function s(){this.typeToInterceptorsMap_=new Map,this.enabled_=!1}var r=s.prototype;return r.getIsEnabled=function(){return this.enabled_},r.enable=function(){this.enabled_=!0},r.disable=function(){this.enabled_=!1},r.reset=function(){this.typeToInterceptorsMap_=new Map,this.enabled_=!1},r.addInterceptor=function(o,c){this.typeToInterceptorsMap_.has(o)||this.typeToInterceptorsMap_.set(o,new Set);var l=this.typeToInterceptorsMap_.get(o);return l.has(c)?!1:(l.add(c),!0)},r.removeInterceptor=function(o,c){var l=this.typeToInterceptorsMap_.get(o);return l&&l.has(c)?(l.delete(c),!0):!1},r.clearInterceptorsByType=function(o){var c=this.typeToInterceptorsMap_.get(o);return c?(this.typeToInterceptorsMap_.delete(o),this.typeToInterceptorsMap_.set(o,new Set),!0):!1},r.clear=function(){return this.typeToInterceptorsMap_.size?(this.typeToInterceptorsMap_=new Map,!0):!1},r.getForType=function(o){return this.typeToInterceptorsMap_.get(o)||new Set},r.execute=function(o,c){for(var l=this.getForType(o),u=n(l),h;!(h=u()).done;){var p=h.value;try{c=p(c)}catch{}}return c},s})();return Bd=i,Bd}var qd,N0;function w1(){if(N0)return qd;N0=1;var n=(function(){function t(){this.maxAttempts_=1,this.delayFactor_=.1,this.fuzzFactor_=.1,this.initialDelay_=1e3,this.enabled_=!1}var i=t.prototype;return i.getIsEnabled=function(){return this.enabled_},i.enable=function(){this.enabled_=!0},i.disable=function(){this.enabled_=!1},i.reset=function(){this.maxAttempts_=1,this.delayFactor_=.1,this.fuzzFactor_=.1,this.initialDelay_=1e3,this.enabled_=!1},i.getMaxAttempts=function(){return this.maxAttempts_},i.setMaxAttempts=function(r){this.maxAttempts_=r},i.getDelayFactor=function(){return this.delayFactor_},i.setDelayFactor=function(r){this.delayFactor_=r},i.getFuzzFactor=function(){return this.fuzzFactor_},i.setFuzzFactor=function(r){this.fuzzFactor_=r},i.getInitialDelay=function(){return this.initialDelay_},i.setInitialDelay=function(r){this.initialDelay_=r},i.createRetry=function(r){var a=r===void 0?{}:r,o=a.maxAttempts,c=a.delayFactor,l=a.fuzzFactor,u=a.initialDelay;return new e({maxAttempts:o||this.maxAttempts_,delayFactor:c||this.delayFactor_,fuzzFactor:l||this.fuzzFactor_,initialDelay:u||this.initialDelay_})},t})(),e=(function(){function t(s){this.maxAttempts_=s.maxAttempts,this.delayFactor_=s.delayFactor,this.fuzzFactor_=s.fuzzFactor,this.currentDelay_=s.initialDelay,this.currentAttempt_=1}var i=t.prototype;return i.moveToNextAttempt=function(){this.currentAttempt_++;var r=this.currentDelay_*this.delayFactor_;this.currentDelay_=this.currentDelay_+r},i.shouldRetry=function(){return this.currentAttempt_<this.maxAttempts_},i.getCurrentDelay=function(){return this.currentDelay_},i.getCurrentMinPossibleDelay=function(){return(1-this.fuzzFactor_)*this.currentDelay_},i.getCurrentMaxPossibleDelay=function(){return(1+this.fuzzFactor_)*this.currentDelay_},i.getCurrentFuzzedDelay=function(){var r=this.getCurrentMinPossibleDelay(),a=this.getCurrentMaxPossibleDelay();return r+Math.random()*(a-r)},t})();return qd=n,qd}var Vd,F0;function A1(){if(F0)return Vd;F0=1;var n=Dc(),e=function(s,r){return r===void 0&&(r=!1),function(a,o,c){if(a){s(a);return}if(o.statusCode>=400&&o.statusCode<=599){var l=c;if(r)if(n.TextDecoder){var u=t(o.headers&&o.headers["content-type"]);try{l=new TextDecoder(u).decode(c)}catch{}}else l=String.fromCharCode.apply(null,new Uint8Array(c));s({cause:l});return}s(null,c)}};function t(i){return i===void 0&&(i=""),i.toLowerCase().split(";").reduce(function(s,r){var a=r.split("="),o=a[0],c=a[1];return o.trim()==="charset"?c.trim():s},"utf-8")}return Vd=e,Vd}var U0;function D1(){if(U0)return Pc.exports;U0=1;var n=Dc(),e=k1(),t=E1(),i=x1(),s=w1();l.httpHandler=A1(),l.requestInterceptorsStorage=new i,l.responseInterceptorsStorage=new i,l.retryManager=new s;/**
|
|
51
|
+
* @license
|
|
52
|
+
* slighly modified parse-headers 2.0.2 <https://github.com/kesla/parse-headers/>
|
|
53
|
+
* Copyright (c) 2014 David Björklund
|
|
54
|
+
* Available under the MIT license
|
|
55
|
+
* <https://github.com/kesla/parse-headers/blob/master/LICENCE>
|
|
56
|
+
*/var r=function(_){var b={};return _&&_.trim().split(`
|
|
57
|
+
`).forEach(function(S){var D=S.indexOf(":"),I=S.slice(0,D).trim().toLowerCase(),F=S.slice(D+1).trim();typeof b[I]>"u"?b[I]=F:Array.isArray(b[I])?b[I].push(F):b[I]=[b[I],F]}),b};Pc.exports=l,Pc.exports.default=l,l.XMLHttpRequest=n.XMLHttpRequest||p,l.XDomainRequest="withCredentials"in new l.XMLHttpRequest?l.XMLHttpRequest:n.XDomainRequest,a(["get","put","post","patch","head","delete"],function(y){l[y==="delete"?"del":y]=function(_,b,S){return b=c(_,b,S),b.method=y.toUpperCase(),u(b)}});function a(y,_){for(var b=0;b<y.length;b++)_(y[b])}function o(y){for(var _ in y)if(y.hasOwnProperty(_))return!1;return!0}function c(y,_,b){var S=y;return t(_)?(b=_,typeof y=="string"&&(S={uri:y})):S=e({},_,{uri:y}),S.callback=b,S}function l(y,_,b){return _=c(y,_,b),u(_)}function u(y){if(typeof y.callback>"u")throw new Error("callback argument missing");if(y.requestType&&l.requestInterceptorsStorage.getIsEnabled()){var _={uri:y.uri||y.url,headers:y.headers||{},body:y.body,metadata:y.metadata||{},retry:y.retry,timeout:y.timeout},b=l.requestInterceptorsStorage.execute(y.requestType,_);y.uri=b.uri,y.headers=b.headers,y.body=b.body,y.metadata=b.metadata,y.retry=b.retry,y.timeout=b.timeout}var S=!1,D=function(re,Y,ie){S||(S=!0,y.callback(re,Y,ie))};function I(){L.readyState===4&&!l.responseInterceptorsStorage.getIsEnabled()&&setTimeout(P,0)}function F(){var Q=void 0;if(L.response?Q=L.response:Q=L.responseText||h(L),z)try{Q=JSON.parse(Q)}catch{}return Q}function w(Q){if(clearTimeout(W),clearTimeout(y.retryTimeout),Q instanceof Error||(Q=new Error(""+(Q||"Unknown XMLHttpRequest Error"))),Q.statusCode=0,!N&&l.retryManager.getIsEnabled()&&y.retry&&y.retry.shouldRetry()){y.retryTimeout=setTimeout(function(){y.retry.moveToNextAttempt(),y.xhr=L,u(y)},y.retry.getCurrentFuzzedDelay());return}if(y.requestType&&l.responseInterceptorsStorage.getIsEnabled()){var re={headers:te.headers||{},body:te.body,responseUrl:L.responseURL,responseType:L.responseType},Y=l.responseInterceptorsStorage.execute(y.requestType,re);te.body=Y.body,te.headers=Y.headers}return D(Q,te)}function P(){if(!N){var Q;clearTimeout(W),clearTimeout(y.retryTimeout),y.useXDR&&L.status===void 0?Q=200:Q=L.status===1223?204:L.status;var re=te,Y=null;if(Q!==0?(re={body:F(),statusCode:Q,method:k,headers:{},url:x,rawRequest:L},L.getAllResponseHeaders&&(re.headers=r(L.getAllResponseHeaders()))):Y=new Error("Internal XMLHttpRequest Error"),y.requestType&&l.responseInterceptorsStorage.getIsEnabled()){var ie={headers:re.headers||{},body:re.body,responseUrl:L.responseURL,responseType:L.responseType},ge=l.responseInterceptorsStorage.execute(y.requestType,ie);re.body=ge.body,re.headers=ge.headers}return D(Y,re,re.body)}}var L=y.xhr||null;L||(y.cors||y.useXDR?L=new l.XDomainRequest:L=new l.XMLHttpRequest);var C,N,x=L.url=y.uri||y.url,k=L.method=y.method||"GET",j=y.body||y.data,G=L.headers=y.headers||{},X=!!y.sync,z=!1,W,te={body:void 0,headers:{},statusCode:0,method:k,url:x,rawRequest:L};if("json"in y&&y.json!==!1&&(z=!0,G.accept||G.Accept||(G.Accept="application/json"),k!=="GET"&&k!=="HEAD"&&(G["content-type"]||G["Content-Type"]||(G["Content-Type"]="application/json"),j=JSON.stringify(y.json===!0?j:y.json))),L.onreadystatechange=I,L.onload=P,L.onerror=w,L.onprogress=function(){},L.onabort=function(){N=!0,clearTimeout(y.retryTimeout)},L.ontimeout=w,L.open(k,x,!X,y.username,y.password),X||(L.withCredentials=!!y.withCredentials),!X&&y.timeout>0&&(W=setTimeout(function(){if(!N){N=!0,L.abort("timeout");var Q=new Error("XMLHttpRequest timeout");Q.code="ETIMEDOUT",w(Q)}},y.timeout)),L.setRequestHeader)for(C in G)G.hasOwnProperty(C)&&L.setRequestHeader(C,G[C]);else if(y.headers&&!o(y.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in y&&(L.responseType=y.responseType),"beforeSend"in y&&typeof y.beforeSend=="function"&&y.beforeSend(L),L.send(j||null),L}function h(y){try{if(y.responseType==="document")return y.responseXML;var _=y.responseXML&&y.responseXML.documentElement.nodeName==="parsererror";if(y.responseType===""&&!_)return y.responseXML}catch{}return null}function p(){}return Pc.exports}var P1=D1();const B0=Ra(P1);var jd={exports:{}},Hd,q0;function I1(){if(q0)return Hd;q0=1;var n=R0(),e=Object.create||(function(){function x(){}return function(k){if(arguments.length!==1)throw new Error("Object.create shim only accepts one parameter.");return x.prototype=k,new x}})();function t(x,k){this.name="ParsingError",this.code=x.code,this.message=k||x.message}t.prototype=e(Error.prototype),t.prototype.constructor=t,t.Errors={BadSignature:{code:0,message:"Malformed WebVTT signature."},BadTimeStamp:{code:1,message:"Malformed time stamp."}};function i(x){function k(G,X,z,W){return(G|0)*3600+(X|0)*60+(z|0)+(W|0)/1e3}var j=x.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);return j?j[3]?k(j[1],j[2],j[3].replace(":",""),j[4]):j[1]>59?k(j[1],j[2],0,j[4]):k(0,j[1],j[2],j[4]):null}function s(){this.values=e(null)}s.prototype={set:function(x,k){!this.get(x)&&k!==""&&(this.values[x]=k)},get:function(x,k,j){return j?this.has(x)?this.values[x]:k[j]:this.has(x)?this.values[x]:k},has:function(x){return x in this.values},alt:function(x,k,j){for(var G=0;G<j.length;++G)if(k===j[G]){this.set(x,k);break}},integer:function(x,k){/^-?\d+$/.test(k)&&this.set(x,parseInt(k,10))},percent:function(x,k){return k.match(/^([\d]{1,3})(\.[\d]*)?%$/)&&(k=parseFloat(k),k>=0&&k<=100)?(this.set(x,k),!0):!1}};function r(x,k,j,G){var X=G?x.split(G):[x];for(var z in X)if(typeof X[z]=="string"){var W=X[z].split(j);if(W.length===2){var te=W[0].trim(),Q=W[1].trim();k(te,Q)}}}function a(x,k,j){var G=x;function X(){var te=i(x);if(te===null)throw new t(t.Errors.BadTimeStamp,"Malformed timestamp: "+G);return x=x.replace(/^[^\sa-zA-Z-]+/,""),te}function z(te,Q){var re=new s;r(te,function(Y,ie){switch(Y){case"region":for(var ge=j.length-1;ge>=0;ge--)if(j[ge].id===ie){re.set(Y,j[ge].region);break}break;case"vertical":re.alt(Y,ie,["rl","lr"]);break;case"line":var Te=ie.split(","),be=Te[0];re.integer(Y,be),re.percent(Y,be)&&re.set("snapToLines",!1),re.alt(Y,be,["auto"]),Te.length===2&&re.alt("lineAlign",Te[1],["start","center","end"]);break;case"position":Te=ie.split(","),re.percent(Y,Te[0]),Te.length===2&&re.alt("positionAlign",Te[1],["start","center","end"]);break;case"size":re.percent(Y,ie);break;case"align":re.alt(Y,ie,["start","center","end","left","right"]);break}},/:/,/\s/),Q.region=re.get("region",null),Q.vertical=re.get("vertical","");try{Q.line=re.get("line","auto")}catch{}Q.lineAlign=re.get("lineAlign","start"),Q.snapToLines=re.get("snapToLines",!0),Q.size=re.get("size",100);try{Q.align=re.get("align","center")}catch{Q.align=re.get("align","middle")}try{Q.position=re.get("position","auto")}catch{Q.position=re.get("position",{start:0,left:0,center:50,middle:50,end:100,right:100},Q.align)}Q.positionAlign=re.get("positionAlign",{start:"start",left:"start",center:"center",middle:"center",end:"end",right:"end"},Q.align)}function W(){x=x.replace(/^\s+/,"")}if(W(),k.startTime=X(),W(),x.substr(0,3)!=="-->")throw new t(t.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '-->'): "+G);x=x.substr(3),W(),k.endTime=X(),W(),z(x,k)}var o=n.createElement&&n.createElement("textarea"),c={c:"span",i:"i",b:"b",u:"u",ruby:"ruby",rt:"rt",v:"span",lang:"span"},l={white:"rgba(255,255,255,1)",lime:"rgba(0,255,0,1)",cyan:"rgba(0,255,255,1)",red:"rgba(255,0,0,1)",yellow:"rgba(255,255,0,1)",magenta:"rgba(255,0,255,1)",blue:"rgba(0,0,255,1)",black:"rgba(0,0,0,1)"},u={v:"title",lang:"lang"},h={rt:"ruby"};function p(x,k){function j(){if(!k)return null;function be(Pe){return k=k.substr(Pe.length),Pe}var we=k.match(/^([^<]*)(<[^>]*>?)?/);return be(we[1]?we[1]:we[2])}function G(be){return o.innerHTML=be,be=o.textContent,o.textContent="",be}function X(be,we){return!h[we.localName]||h[we.localName]===be.localName}function z(be,we){var Pe=c[be];if(!Pe)return null;var ve=x.document.createElement(Pe),qe=u[be];return qe&&we&&(ve[qe]=we.trim()),ve}for(var W=x.document.createElement("div"),te=W,Q,re=[];(Q=j())!==null;){if(Q[0]==="<"){if(Q[1]==="/"){re.length&&re[re.length-1]===Q.substr(2).replace(">","")&&(re.pop(),te=te.parentNode);continue}var Y=i(Q.substr(1,Q.length-2)),ie;if(Y){ie=x.document.createProcessingInstruction("timestamp",Y),te.appendChild(ie);continue}var ge=Q.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!ge||(ie=z(ge[1],ge[3]),!ie)||!X(te,ie))continue;if(ge[2]){var Te=ge[2].split(".");Te.forEach(function(be){var we=/^bg_/.test(be),Pe=we?be.slice(3):be;if(l.hasOwnProperty(Pe)){var ve=we?"background-color":"color",qe=l[Pe];ie.style[ve]=qe}}),ie.className=Te.join(" ")}re.push(ge[1]),te.appendChild(ie),te=ie;continue}te.appendChild(x.document.createTextNode(G(Q)))}return W}var y=[[1470,1470],[1472,1472],[1475,1475],[1478,1478],[1488,1514],[1520,1524],[1544,1544],[1547,1547],[1549,1549],[1563,1563],[1566,1610],[1645,1647],[1649,1749],[1765,1766],[1774,1775],[1786,1805],[1807,1808],[1810,1839],[1869,1957],[1969,1969],[1984,2026],[2036,2037],[2042,2042],[2048,2069],[2074,2074],[2084,2084],[2088,2088],[2096,2110],[2112,2136],[2142,2142],[2208,2208],[2210,2220],[8207,8207],[64285,64285],[64287,64296],[64298,64310],[64312,64316],[64318,64318],[64320,64321],[64323,64324],[64326,64449],[64467,64829],[64848,64911],[64914,64967],[65008,65020],[65136,65140],[65142,65276],[67584,67589],[67592,67592],[67594,67637],[67639,67640],[67644,67644],[67647,67669],[67671,67679],[67840,67867],[67872,67897],[67903,67903],[67968,68023],[68030,68031],[68096,68096],[68112,68115],[68117,68119],[68121,68147],[68160,68167],[68176,68184],[68192,68223],[68352,68405],[68416,68437],[68440,68466],[68472,68479],[68608,68680],[126464,126467],[126469,126495],[126497,126498],[126500,126500],[126503,126503],[126505,126514],[126516,126519],[126521,126521],[126523,126523],[126530,126530],[126535,126535],[126537,126537],[126539,126539],[126541,126543],[126545,126546],[126548,126548],[126551,126551],[126553,126553],[126555,126555],[126557,126557],[126559,126559],[126561,126562],[126564,126564],[126567,126570],[126572,126578],[126580,126583],[126585,126588],[126590,126590],[126592,126601],[126603,126619],[126625,126627],[126629,126633],[126635,126651],[1114109,1114109]];function _(x){for(var k=0;k<y.length;k++){var j=y[k];if(x>=j[0]&&x<=j[1])return!0}return!1}function b(x){var k=[],j="",G;if(!x||!x.childNodes)return"ltr";function X(te,Q){for(var re=Q.childNodes.length-1;re>=0;re--)te.push(Q.childNodes[re])}function z(te){if(!te||!te.length)return null;var Q=te.pop(),re=Q.textContent||Q.innerText;if(re){var Y=re.match(/^.*(\n|\r)/);return Y?(te.length=0,Y[0]):re}if(Q.tagName==="ruby")return z(te);if(Q.childNodes)return X(te,Q),z(te)}for(X(k,x);j=z(k);)for(var W=0;W<j.length;W++)if(G=j.charCodeAt(W),_(G))return"rtl";return"ltr"}function S(x){if(typeof x.line=="number"&&(x.snapToLines||x.line>=0&&x.line<=100))return x.line;if(!x.track||!x.track.textTrackList||!x.track.textTrackList.mediaElement)return-1;for(var k=x.track,j=k.textTrackList,G=0,X=0;X<j.length&&j[X]!==k;X++)j[X].mode==="showing"&&G++;return++G*-1}function D(){}D.prototype.applyStyles=function(x,k){k=k||this.div;for(var j in x)x.hasOwnProperty(j)&&(k.style[j]=x[j])},D.prototype.formatStyle=function(x,k){return x===0?0:x+k};function I(x,k,j){D.call(this),this.cue=k,this.cueDiv=p(x,k.text);var G={color:"rgba(255, 255, 255, 1)",backgroundColor:"rgba(0, 0, 0, 0.8)",position:"relative",left:0,right:0,top:0,bottom:0,display:"inline",writingMode:k.vertical===""?"horizontal-tb":k.vertical==="lr"?"vertical-lr":"vertical-rl",unicodeBidi:"plaintext"};this.applyStyles(G,this.cueDiv),this.div=x.document.createElement("div"),G={direction:b(this.cueDiv),writingMode:k.vertical===""?"horizontal-tb":k.vertical==="lr"?"vertical-lr":"vertical-rl",unicodeBidi:"plaintext",textAlign:k.align==="middle"?"center":k.align,font:j.font,whiteSpace:"pre-line",position:"absolute"},this.applyStyles(G),this.div.appendChild(this.cueDiv);var X=0;switch(k.positionAlign){case"start":case"line-left":X=k.position;break;case"center":X=k.position-k.size/2;break;case"end":case"line-right":X=k.position-k.size;break}k.vertical===""?this.applyStyles({left:this.formatStyle(X,"%"),width:this.formatStyle(k.size,"%")}):this.applyStyles({top:this.formatStyle(X,"%"),height:this.formatStyle(k.size,"%")}),this.move=function(z){this.applyStyles({top:this.formatStyle(z.top,"px"),bottom:this.formatStyle(z.bottom,"px"),left:this.formatStyle(z.left,"px"),right:this.formatStyle(z.right,"px"),height:this.formatStyle(z.height,"px"),width:this.formatStyle(z.width,"px")})}}I.prototype=e(D.prototype),I.prototype.constructor=I;function F(x){var k,j,G,X;if(x.div){j=x.div.offsetHeight,G=x.div.offsetWidth,X=x.div.offsetTop;var z=(z=x.div.childNodes)&&(z=z[0])&&z.getClientRects&&z.getClientRects();x=x.div.getBoundingClientRect(),k=z?Math.max(z[0]&&z[0].height||0,x.height/z.length):0}this.left=x.left,this.right=x.right,this.top=x.top||X,this.height=x.height||j,this.bottom=x.bottom||X+(x.height||j),this.width=x.width||G,this.lineHeight=k!==void 0?k:x.lineHeight}F.prototype.move=function(x,k){switch(k=k!==void 0?k:this.lineHeight,x){case"+x":this.left+=k,this.right+=k;break;case"-x":this.left-=k,this.right-=k;break;case"+y":this.top+=k,this.bottom+=k;break;case"-y":this.top-=k,this.bottom-=k;break}},F.prototype.overlaps=function(x){return this.left<x.right&&this.right>x.left&&this.top<x.bottom&&this.bottom>x.top},F.prototype.overlapsAny=function(x){for(var k=0;k<x.length;k++)if(this.overlaps(x[k]))return!0;return!1},F.prototype.within=function(x){return this.top>=x.top&&this.bottom<=x.bottom&&this.left>=x.left&&this.right<=x.right},F.prototype.overlapsOppositeAxis=function(x,k){switch(k){case"+x":return this.left<x.left;case"-x":return this.right>x.right;case"+y":return this.top<x.top;case"-y":return this.bottom>x.bottom}},F.prototype.intersectPercentage=function(x){var k=Math.max(0,Math.min(this.right,x.right)-Math.max(this.left,x.left)),j=Math.max(0,Math.min(this.bottom,x.bottom)-Math.max(this.top,x.top)),G=k*j;return G/(this.height*this.width)},F.prototype.toCSSCompatValues=function(x){return{top:this.top-x.top,bottom:x.bottom-this.bottom,left:this.left-x.left,right:x.right-this.right,height:this.height,width:this.width}},F.getSimpleBoxPosition=function(x){var k=x.div?x.div.offsetHeight:x.tagName?x.offsetHeight:0,j=x.div?x.div.offsetWidth:x.tagName?x.offsetWidth:0,G=x.div?x.div.offsetTop:x.tagName?x.offsetTop:0;x=x.div?x.div.getBoundingClientRect():x.tagName?x.getBoundingClientRect():x;var X={left:x.left,right:x.right,top:x.top||G,height:x.height||k,bottom:x.bottom||G+(x.height||k),width:x.width||j};return X};function w(x,k,j,G){function X(Pe,ve){for(var qe,bt=new F(Pe),et=1,fi=0;fi<ve.length;fi++){for(;Pe.overlapsOppositeAxis(j,ve[fi])||Pe.within(j)&&Pe.overlapsAny(G);)Pe.move(ve[fi]);if(Pe.within(j))return Pe;var Bn=Pe.intersectPercentage(j);et>Bn&&(qe=new F(Pe),et=Bn),Pe=new F(bt)}return qe||bt}var z=new F(k),W=k.cue,te=S(W),Q=[];if(W.snapToLines){var re;switch(W.vertical){case"":Q=["+y","-y"],re="height";break;case"rl":Q=["+x","-x"],re="width";break;case"lr":Q=["-x","+x"],re="width";break}var Y=z.lineHeight,ie=Y*Math.round(te),ge=j[re]+Y,Te=Q[0];Math.abs(ie)>ge&&(ie=ie<0?-1:1,ie*=Math.ceil(ge/Y)*Y),te<0&&(ie+=W.vertical===""?j.height:j.width,Q=Q.reverse()),z.move(Te,ie)}else{var be=z.lineHeight/j.height*100;switch(W.lineAlign){case"center":te-=be/2;break;case"end":te-=be;break}switch(W.vertical){case"":k.applyStyles({top:k.formatStyle(te,"%")});break;case"rl":k.applyStyles({left:k.formatStyle(te,"%")});break;case"lr":k.applyStyles({right:k.formatStyle(te,"%")});break}Q=["+y","-x","+x","-y"],z=new F(k)}var we=X(z,Q);k.move(we.toCSSCompatValues(j))}function P(){}P.StringDecoder=function(){return{decode:function(x){if(!x)return"";if(typeof x!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(x))}}},P.convertCueToDOMTree=function(x,k){return!x||!k?null:p(x,k)};var L=.05,C="sans-serif",N="1.5%";return P.processCues=function(x,k,j){if(!x||!k||!j)return null;for(;j.firstChild;)j.removeChild(j.firstChild);var G=x.document.createElement("div");G.style.position="absolute",G.style.left="0",G.style.right="0",G.style.top="0",G.style.bottom="0",G.style.margin=N,j.appendChild(G);function X(Y){for(var ie=0;ie<Y.length;ie++)if(Y[ie].hasBeenReset||!Y[ie].displayState)return!0;return!1}if(!X(k)){for(var z=0;z<k.length;z++)G.appendChild(k[z].displayState);return}var W=[],te=F.getSimpleBoxPosition(G),Q=Math.round(te.height*L*100)/100,re={font:Q+"px "+C};(function(){for(var Y,ie,ge=0;ge<k.length;ge++)ie=k[ge],Y=new I(x,ie,re),G.appendChild(Y.div),w(x,Y,te,W),ie.displayState=Y.div,W.push(F.getSimpleBoxPosition(Y))})()},P.Parser=function(x,k,j){j||(j=k,k={}),k||(k={}),this.window=x,this.vttjs=k,this.state="INITIAL",this.buffer="",this.decoder=j||new TextDecoder("utf8"),this.regionList=[]},P.Parser.prototype={reportOrThrowError:function(x){if(x instanceof t)this.onparsingerror&&this.onparsingerror(x);else throw x},parse:function(x){var k=this;x&&(k.buffer+=k.decoder.decode(x,{stream:!0}));function j(){for(var Y=k.buffer,ie=0;ie<Y.length&&Y[ie]!=="\r"&&Y[ie]!==`
|
|
58
|
+
`;)++ie;var ge=Y.substr(0,ie);return Y[ie]==="\r"&&++ie,Y[ie]===`
|
|
59
|
+
`&&++ie,k.buffer=Y.substr(ie),ge}function G(Y){var ie=new s;if(r(Y,function(Te,be){switch(Te){case"id":ie.set(Te,be);break;case"width":ie.percent(Te,be);break;case"lines":ie.integer(Te,be);break;case"regionanchor":case"viewportanchor":var we=be.split(",");if(we.length!==2)break;var Pe=new s;if(Pe.percent("x",we[0]),Pe.percent("y",we[1]),!Pe.has("x")||!Pe.has("y"))break;ie.set(Te+"X",Pe.get("x")),ie.set(Te+"Y",Pe.get("y"));break;case"scroll":ie.alt(Te,be,["up"]);break}},/=/,/\s/),ie.has("id")){var ge=new(k.vttjs.VTTRegion||k.window.VTTRegion);ge.width=ie.get("width",100),ge.lines=ie.get("lines",3),ge.regionAnchorX=ie.get("regionanchorX",0),ge.regionAnchorY=ie.get("regionanchorY",100),ge.viewportAnchorX=ie.get("viewportanchorX",0),ge.viewportAnchorY=ie.get("viewportanchorY",100),ge.scroll=ie.get("scroll",""),k.onregion&&k.onregion(ge),k.regionList.push({id:ie.get("id"),region:ge})}}function X(Y){var ie=new s;r(Y,function(ge,Te){switch(ge){case"MPEGT":ie.integer(ge+"S",Te);break;case"LOCA":ie.set(ge+"L",i(Te));break}},/[^\d]:/,/,/),k.ontimestampmap&&k.ontimestampmap({MPEGTS:ie.get("MPEGTS"),LOCAL:ie.get("LOCAL")})}function z(Y){Y.match(/X-TIMESTAMP-MAP/)?r(Y,function(ie,ge){switch(ie){case"X-TIMESTAMP-MAP":X(ge);break}},/=/):r(Y,function(ie,ge){switch(ie){case"Region":G(ge);break}},/:/)}try{var W;if(k.state==="INITIAL"){if(!/\r\n|\n/.test(k.buffer))return this;W=j();var te=W.match(/^WEBVTT([ \t].*)?$/);if(!te||!te[0])throw new t(t.Errors.BadSignature);k.state="HEADER"}for(var Q=!1;k.buffer;){if(!/\r\n|\n/.test(k.buffer))return this;switch(Q?Q=!1:W=j(),k.state){case"HEADER":/:/.test(W)?z(W):W||(k.state="ID");continue;case"NOTE":W||(k.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(W)){k.state="NOTE";break}if(!W)continue;k.cue=new(k.vttjs.VTTCue||k.window.VTTCue)(0,0,"");try{k.cue.align="center"}catch{k.cue.align="middle"}if(k.state="CUE",W.indexOf("-->")===-1){k.cue.id=W;continue}case"CUE":try{a(W,k.cue,k.regionList)}catch(Y){k.reportOrThrowError(Y),k.cue=null,k.state="BADCUE";continue}k.state="CUETEXT";continue;case"CUETEXT":var re=W.indexOf("-->")!==-1;if(!W||re&&(Q=!0)){k.oncue&&k.oncue(k.cue),k.cue=null,k.state="ID";continue}k.cue.text&&(k.cue.text+=`
|
|
60
|
+
`),k.cue.text+=W.replace(/\u2028/g,`
|
|
61
|
+
`).replace(/u2029/g,`
|
|
62
|
+
`);continue;case"BADCUE":W||(k.state="ID");continue}}}catch(Y){k.reportOrThrowError(Y),k.state==="CUETEXT"&&k.cue&&k.oncue&&k.oncue(k.cue),k.cue=null,k.state=k.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this},flush:function(){var x=this;try{if(x.buffer+=x.decoder.decode(),(x.cue||x.state==="HEADER")&&(x.buffer+=`
|
|
63
|
+
|
|
64
|
+
`,x.parse()),x.state==="INITIAL")throw new t(t.Errors.BadSignature)}catch(k){x.reportOrThrowError(k)}return x.onflush&&x.onflush(),this}},Hd=P,Hd}var $d,V0;function R1(){if(V0)return $d;V0=1;var n="auto",e={"":1,lr:1,rl:1},t={start:1,center:1,end:1,left:1,right:1,auto:1,"line-left":1,"line-right":1};function i(a){if(typeof a!="string")return!1;var o=e[a.toLowerCase()];return o?a.toLowerCase():!1}function s(a){if(typeof a!="string")return!1;var o=t[a.toLowerCase()];return o?a.toLowerCase():!1}function r(a,o,c){this.hasBeenReset=!1;var l="",u=!1,h=a,p=o,y=c,_=null,b="",S=!0,D="auto",I="start",F="auto",w="auto",P=100,L="center";Object.defineProperties(this,{id:{enumerable:!0,get:function(){return l},set:function(C){l=""+C}},pauseOnExit:{enumerable:!0,get:function(){return u},set:function(C){u=!!C}},startTime:{enumerable:!0,get:function(){return h},set:function(C){if(typeof C!="number")throw new TypeError("Start time must be set to a number.");h=C,this.hasBeenReset=!0}},endTime:{enumerable:!0,get:function(){return p},set:function(C){if(typeof C!="number")throw new TypeError("End time must be set to a number.");p=C,this.hasBeenReset=!0}},text:{enumerable:!0,get:function(){return y},set:function(C){y=""+C,this.hasBeenReset=!0}},region:{enumerable:!0,get:function(){return _},set:function(C){_=C,this.hasBeenReset=!0}},vertical:{enumerable:!0,get:function(){return b},set:function(C){var N=i(C);if(N===!1)throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");b=N,this.hasBeenReset=!0}},snapToLines:{enumerable:!0,get:function(){return S},set:function(C){S=!!C,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return D},set:function(C){if(typeof C!="number"&&C!==n)throw new SyntaxError("Line: an invalid number or illegal string was specified.");D=C,this.hasBeenReset=!0}},lineAlign:{enumerable:!0,get:function(){return I},set:function(C){var N=s(C);N?(I=N,this.hasBeenReset=!0):console.warn("lineAlign: an invalid or illegal string was specified.")}},position:{enumerable:!0,get:function(){return F},set:function(C){if(C<0||C>100)throw new Error("Position must be between 0 and 100.");F=C,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return w},set:function(C){var N=s(C);N?(w=N,this.hasBeenReset=!0):console.warn("positionAlign: an invalid or illegal string was specified.")}},size:{enumerable:!0,get:function(){return P},set:function(C){if(C<0||C>100)throw new Error("Size must be between 0 and 100.");P=C,this.hasBeenReset=!0}},align:{enumerable:!0,get:function(){return L},set:function(C){var N=s(C);if(!N)throw new SyntaxError("align: an invalid or illegal alignment string was specified.");L=N,this.hasBeenReset=!0}}}),this.displayState=void 0}return r.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text)},$d=r,$d}var Wd,j0;function O1(){if(j0)return Wd;j0=1;var n={"":!0,up:!0};function e(s){if(typeof s!="string")return!1;var r=n[s.toLowerCase()];return r?s.toLowerCase():!1}function t(s){return typeof s=="number"&&s>=0&&s<=100}function i(){var s=100,r=3,a=0,o=100,c=0,l=100,u="";Object.defineProperties(this,{width:{enumerable:!0,get:function(){return s},set:function(h){if(!t(h))throw new Error("Width must be between 0 and 100.");s=h}},lines:{enumerable:!0,get:function(){return r},set:function(h){if(typeof h!="number")throw new TypeError("Lines must be set to a number.");r=h}},regionAnchorY:{enumerable:!0,get:function(){return o},set:function(h){if(!t(h))throw new Error("RegionAnchorX must be between 0 and 100.");o=h}},regionAnchorX:{enumerable:!0,get:function(){return a},set:function(h){if(!t(h))throw new Error("RegionAnchorY must be between 0 and 100.");a=h}},viewportAnchorY:{enumerable:!0,get:function(){return l},set:function(h){if(!t(h))throw new Error("ViewportAnchorY must be between 0 and 100.");l=h}},viewportAnchorX:{enumerable:!0,get:function(){return c},set:function(h){if(!t(h))throw new Error("ViewportAnchorX must be between 0 and 100.");c=h}},scroll:{enumerable:!0,get:function(){return u},set:function(h){var p=e(h);p===!1?console.warn("Scroll: an invalid or illegal string was specified."):u=p}}})}return Wd=i,Wd}var H0;function M1(){if(H0)return jd.exports;H0=1;var n=Dc(),e=jd.exports={WebVTT:I1(),VTTCue:R1(),VTTRegion:O1()};n.vttjs=e,n.WebVTT=e.WebVTT;var t=e.VTTCue,i=e.VTTRegion,s=n.VTTCue,r=n.VTTRegion;return e.shim=function(){n.VTTCue=t,n.VTTRegion=i},e.restore=function(){n.VTTCue=s,n.VTTRegion=r},n.VTTCue||e.shim(),jd.exports}var L1=M1();const $0=Ra(L1);function vt(){return vt=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(n[i]=t[i])}return n},vt.apply(null,arguments)}var W0="https://example.com",Ic=function(e,t){if(/^[a-z]+:/i.test(t))return t;/^data:/.test(e)&&(e=B.location&&B.location.href||"");var i=/^\/\//.test(e),s=!B.location&&!/\/\//i.test(e);e=new B.URL(e,B.location||W0);var r=new URL(t,e);return s?r.href.slice(W0.length):i?r.href.slice(r.protocol.length):r.href},zd=(function(){function n(){this.listeners={}}var e=n.prototype;return e.on=function(i,s){this.listeners[i]||(this.listeners[i]=[]),this.listeners[i].push(s)},e.off=function(i,s){if(!this.listeners[i])return!1;var r=this.listeners[i].indexOf(s);return this.listeners[i]=this.listeners[i].slice(0),this.listeners[i].splice(r,1),r>-1},e.trigger=function(i){var s=this.listeners[i];if(s)if(arguments.length===2)for(var r=s.length,a=0;a<r;++a)s[a].call(this,arguments[1]);else for(var o=Array.prototype.slice.call(arguments,1),c=s.length,l=0;l<c;++l)s[l].apply(this,o)},e.dispose=function(){this.listeners={}},e.pipe=function(i){this.on("data",function(s){i.push(s)})},n})(),N1=function(e){return B.atob?B.atob(e):Buffer.from(e,"base64").toString("binary")};function z0(n){for(var e=N1(n),t=new Uint8Array(e.length),i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}/*! @name m3u8-parser @version 7.2.0 @license Apache-2.0 */class F1 extends zd{constructor(){super(),this.buffer=""}push(e){let t;for(this.buffer+=e,t=this.buffer.indexOf(`
|
|
65
|
+
`);t>-1;t=this.buffer.indexOf(`
|
|
66
|
+
`))this.trigger("data",this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)}}const U1=" ",Gd=function(n){const e=/([0-9.]*)?@?([0-9.]*)?/.exec(n||""),t={};return e[1]&&(t.length=parseInt(e[1],10)),e[2]&&(t.offset=parseInt(e[2],10)),t},B1=function(){const t="(?:"+"[^=]*"+")=(?:"+'"[^"]*"|[^,]*'+")";return new RegExp("(?:^|,)("+t+")")},Zt=function(n){const e={};if(!n)return e;const t=n.split(B1());let i=t.length,s;for(;i--;)t[i]!==""&&(s=/([^=]*)=(.*)/.exec(t[i]).slice(1),s[0]=s[0].replace(/^\s+|\s+$/g,""),s[1]=s[1].replace(/^\s+|\s+$/g,""),s[1]=s[1].replace(/^['"](.*)['"]$/g,"$1"),e[s[0]]=s[1]);return e},G0=n=>{const e=n.split("x"),t={};return e[0]&&(t.width=parseInt(e[0],10)),e[1]&&(t.height=parseInt(e[1],10)),t};class q1 extends zd{constructor(){super(),this.customParsers=[],this.tagMappers=[]}push(e){let t,i;if(e=e.trim(),e.length===0)return;if(e[0]!=="#"){this.trigger("data",{type:"uri",uri:e});return}this.tagMappers.reduce((r,a)=>{const o=a(e);return o===e?r:r.concat([o])},[e]).forEach(r=>{for(let a=0;a<this.customParsers.length;a++)if(this.customParsers[a].call(this,r))return;if(r.indexOf("#EXT")!==0){this.trigger("data",{type:"comment",text:r.slice(1)});return}if(r=r.replace("\r",""),t=/^#EXTM3U/.exec(r),t){this.trigger("data",{type:"tag",tagType:"m3u"});return}if(t=/^#EXTINF:([0-9\.]*)?,?(.*)?$/.exec(r),t){i={type:"tag",tagType:"inf"},t[1]&&(i.duration=parseFloat(t[1])),t[2]&&(i.title=t[2]),this.trigger("data",i);return}if(t=/^#EXT-X-TARGETDURATION:([0-9.]*)?/.exec(r),t){i={type:"tag",tagType:"targetduration"},t[1]&&(i.duration=parseInt(t[1],10)),this.trigger("data",i);return}if(t=/^#EXT-X-VERSION:([0-9.]*)?/.exec(r),t){i={type:"tag",tagType:"version"},t[1]&&(i.version=parseInt(t[1],10)),this.trigger("data",i);return}if(t=/^#EXT-X-MEDIA-SEQUENCE:(\-?[0-9.]*)?/.exec(r),t){i={type:"tag",tagType:"media-sequence"},t[1]&&(i.number=parseInt(t[1],10)),this.trigger("data",i);return}if(t=/^#EXT-X-DISCONTINUITY-SEQUENCE:(\-?[0-9.]*)?/.exec(r),t){i={type:"tag",tagType:"discontinuity-sequence"},t[1]&&(i.number=parseInt(t[1],10)),this.trigger("data",i);return}if(t=/^#EXT-X-PLAYLIST-TYPE:(.*)?$/.exec(r),t){i={type:"tag",tagType:"playlist-type"},t[1]&&(i.playlistType=t[1]),this.trigger("data",i);return}if(t=/^#EXT-X-BYTERANGE:(.*)?$/.exec(r),t){i=vt(Gd(t[1]),{type:"tag",tagType:"byterange"}),this.trigger("data",i);return}if(t=/^#EXT-X-ALLOW-CACHE:(YES|NO)?/.exec(r),t){i={type:"tag",tagType:"allow-cache"},t[1]&&(i.allowed=!/NO/.test(t[1])),this.trigger("data",i);return}if(t=/^#EXT-X-MAP:(.*)$/.exec(r),t){if(i={type:"tag",tagType:"map"},t[1]){const a=Zt(t[1]);a.URI&&(i.uri=a.URI),a.BYTERANGE&&(i.byterange=Gd(a.BYTERANGE))}this.trigger("data",i);return}if(t=/^#EXT-X-STREAM-INF:(.*)$/.exec(r),t){i={type:"tag",tagType:"stream-inf"},t[1]&&(i.attributes=Zt(t[1]),i.attributes.RESOLUTION&&(i.attributes.RESOLUTION=G0(i.attributes.RESOLUTION)),i.attributes.BANDWIDTH&&(i.attributes.BANDWIDTH=parseInt(i.attributes.BANDWIDTH,10)),i.attributes["FRAME-RATE"]&&(i.attributes["FRAME-RATE"]=parseFloat(i.attributes["FRAME-RATE"])),i.attributes["PROGRAM-ID"]&&(i.attributes["PROGRAM-ID"]=parseInt(i.attributes["PROGRAM-ID"],10))),this.trigger("data",i);return}if(t=/^#EXT-X-MEDIA:(.*)$/.exec(r),t){i={type:"tag",tagType:"media"},t[1]&&(i.attributes=Zt(t[1])),this.trigger("data",i);return}if(t=/^#EXT-X-ENDLIST/.exec(r),t){this.trigger("data",{type:"tag",tagType:"endlist"});return}if(t=/^#EXT-X-DISCONTINUITY/.exec(r),t){this.trigger("data",{type:"tag",tagType:"discontinuity"});return}if(t=/^#EXT-X-PROGRAM-DATE-TIME:(.*)$/.exec(r),t){i={type:"tag",tagType:"program-date-time"},t[1]&&(i.dateTimeString=t[1],i.dateTimeObject=new Date(t[1])),this.trigger("data",i);return}if(t=/^#EXT-X-KEY:(.*)$/.exec(r),t){i={type:"tag",tagType:"key"},t[1]&&(i.attributes=Zt(t[1]),i.attributes.IV&&(i.attributes.IV.substring(0,2).toLowerCase()==="0x"&&(i.attributes.IV=i.attributes.IV.substring(2)),i.attributes.IV=i.attributes.IV.match(/.{8}/g),i.attributes.IV[0]=parseInt(i.attributes.IV[0],16),i.attributes.IV[1]=parseInt(i.attributes.IV[1],16),i.attributes.IV[2]=parseInt(i.attributes.IV[2],16),i.attributes.IV[3]=parseInt(i.attributes.IV[3],16),i.attributes.IV=new Uint32Array(i.attributes.IV))),this.trigger("data",i);return}if(t=/^#EXT-X-START:(.*)$/.exec(r),t){i={type:"tag",tagType:"start"},t[1]&&(i.attributes=Zt(t[1]),i.attributes["TIME-OFFSET"]=parseFloat(i.attributes["TIME-OFFSET"]),i.attributes.PRECISE=/YES/.test(i.attributes.PRECISE)),this.trigger("data",i);return}if(t=/^#EXT-X-CUE-OUT-CONT:(.*)?$/.exec(r),t){i={type:"tag",tagType:"cue-out-cont"},t[1]?i.data=t[1]:i.data="",this.trigger("data",i);return}if(t=/^#EXT-X-CUE-OUT:(.*)?$/.exec(r),t){i={type:"tag",tagType:"cue-out"},t[1]?i.data=t[1]:i.data="",this.trigger("data",i);return}if(t=/^#EXT-X-CUE-IN:?(.*)?$/.exec(r),t){i={type:"tag",tagType:"cue-in"},t[1]?i.data=t[1]:i.data="",this.trigger("data",i);return}if(t=/^#EXT-X-SKIP:(.*)$/.exec(r),t&&t[1]){i={type:"tag",tagType:"skip"},i.attributes=Zt(t[1]),i.attributes.hasOwnProperty("SKIPPED-SEGMENTS")&&(i.attributes["SKIPPED-SEGMENTS"]=parseInt(i.attributes["SKIPPED-SEGMENTS"],10)),i.attributes.hasOwnProperty("RECENTLY-REMOVED-DATERANGES")&&(i.attributes["RECENTLY-REMOVED-DATERANGES"]=i.attributes["RECENTLY-REMOVED-DATERANGES"].split(U1)),this.trigger("data",i);return}if(t=/^#EXT-X-PART:(.*)$/.exec(r),t&&t[1]){i={type:"tag",tagType:"part"},i.attributes=Zt(t[1]),["DURATION"].forEach(function(a){i.attributes.hasOwnProperty(a)&&(i.attributes[a]=parseFloat(i.attributes[a]))}),["INDEPENDENT","GAP"].forEach(function(a){i.attributes.hasOwnProperty(a)&&(i.attributes[a]=/YES/.test(i.attributes[a]))}),i.attributes.hasOwnProperty("BYTERANGE")&&(i.attributes.byterange=Gd(i.attributes.BYTERANGE)),this.trigger("data",i);return}if(t=/^#EXT-X-SERVER-CONTROL:(.*)$/.exec(r),t&&t[1]){i={type:"tag",tagType:"server-control"},i.attributes=Zt(t[1]),["CAN-SKIP-UNTIL","PART-HOLD-BACK","HOLD-BACK"].forEach(function(a){i.attributes.hasOwnProperty(a)&&(i.attributes[a]=parseFloat(i.attributes[a]))}),["CAN-SKIP-DATERANGES","CAN-BLOCK-RELOAD"].forEach(function(a){i.attributes.hasOwnProperty(a)&&(i.attributes[a]=/YES/.test(i.attributes[a]))}),this.trigger("data",i);return}if(t=/^#EXT-X-PART-INF:(.*)$/.exec(r),t&&t[1]){i={type:"tag",tagType:"part-inf"},i.attributes=Zt(t[1]),["PART-TARGET"].forEach(function(a){i.attributes.hasOwnProperty(a)&&(i.attributes[a]=parseFloat(i.attributes[a]))}),this.trigger("data",i);return}if(t=/^#EXT-X-PRELOAD-HINT:(.*)$/.exec(r),t&&t[1]){i={type:"tag",tagType:"preload-hint"},i.attributes=Zt(t[1]),["BYTERANGE-START","BYTERANGE-LENGTH"].forEach(function(a){if(i.attributes.hasOwnProperty(a)){i.attributes[a]=parseInt(i.attributes[a],10);const o=a==="BYTERANGE-LENGTH"?"length":"offset";i.attributes.byterange=i.attributes.byterange||{},i.attributes.byterange[o]=i.attributes[a],delete i.attributes[a]}}),this.trigger("data",i);return}if(t=/^#EXT-X-RENDITION-REPORT:(.*)$/.exec(r),t&&t[1]){i={type:"tag",tagType:"rendition-report"},i.attributes=Zt(t[1]),["LAST-MSN","LAST-PART"].forEach(function(a){i.attributes.hasOwnProperty(a)&&(i.attributes[a]=parseInt(i.attributes[a],10))}),this.trigger("data",i);return}if(t=/^#EXT-X-DATERANGE:(.*)$/.exec(r),t&&t[1]){i={type:"tag",tagType:"daterange"},i.attributes=Zt(t[1]),["ID","CLASS"].forEach(function(o){i.attributes.hasOwnProperty(o)&&(i.attributes[o]=String(i.attributes[o]))}),["START-DATE","END-DATE"].forEach(function(o){i.attributes.hasOwnProperty(o)&&(i.attributes[o]=new Date(i.attributes[o]))}),["DURATION","PLANNED-DURATION"].forEach(function(o){i.attributes.hasOwnProperty(o)&&(i.attributes[o]=parseFloat(i.attributes[o]))}),["END-ON-NEXT"].forEach(function(o){i.attributes.hasOwnProperty(o)&&(i.attributes[o]=/YES/i.test(i.attributes[o]))}),["SCTE35-CMD"," SCTE35-OUT","SCTE35-IN"].forEach(function(o){i.attributes.hasOwnProperty(o)&&(i.attributes[o]=i.attributes[o].toString(16))});const a=/^X-([A-Z]+-)+[A-Z]+$/;for(const o in i.attributes){if(!a.test(o))continue;const c=/[0-9A-Fa-f]{6}/g.test(i.attributes[o]),l=/^\d+(\.\d+)?$/.test(i.attributes[o]);i.attributes[o]=c?i.attributes[o].toString(16):l?parseFloat(i.attributes[o]):String(i.attributes[o])}this.trigger("data",i);return}if(t=/^#EXT-X-INDEPENDENT-SEGMENTS/.exec(r),t){this.trigger("data",{type:"tag",tagType:"independent-segments"});return}if(t=/^#EXT-X-I-FRAMES-ONLY/.exec(r),t){this.trigger("data",{type:"tag",tagType:"i-frames-only"});return}if(t=/^#EXT-X-CONTENT-STEERING:(.*)$/.exec(r),t){i={type:"tag",tagType:"content-steering"},i.attributes=Zt(t[1]),this.trigger("data",i);return}if(t=/^#EXT-X-I-FRAME-STREAM-INF:(.*)$/.exec(r),t){i={type:"tag",tagType:"i-frame-playlist"},i.attributes=Zt(t[1]),i.attributes.URI&&(i.uri=i.attributes.URI),i.attributes.BANDWIDTH&&(i.attributes.BANDWIDTH=parseInt(i.attributes.BANDWIDTH,10)),i.attributes.RESOLUTION&&(i.attributes.RESOLUTION=G0(i.attributes.RESOLUTION)),i.attributes["AVERAGE-BANDWIDTH"]&&(i.attributes["AVERAGE-BANDWIDTH"]=parseInt(i.attributes["AVERAGE-BANDWIDTH"],10)),i.attributes["FRAME-RATE"]&&(i.attributes["FRAME-RATE"]=parseFloat(i.attributes["FRAME-RATE"])),this.trigger("data",i);return}if(t=/^#EXT-X-DEFINE:(.*)$/.exec(r),t){i={type:"tag",tagType:"define"},i.attributes=Zt(t[1]),this.trigger("data",i);return}this.trigger("data",{type:"tag",data:r.slice(4)})})}addParser({expression:e,customType:t,dataParser:i,segment:s}){typeof i!="function"&&(i=r=>r),this.customParsers.push(r=>{if(e.exec(r))return this.trigger("data",{type:"custom",data:i(r),customType:t,segment:s}),!0})}addTagMapper({expression:e,map:t}){const i=s=>e.test(s)?t(s):s;this.tagMappers.push(i)}}const V1=n=>n.toLowerCase().replace(/-(\w)/g,e=>e[1].toUpperCase()),ns=function(n){const e={};return Object.keys(n).forEach(function(t){e[V1(t)]=n[t]}),e},Kd=function(n){const{serverControl:e,targetDuration:t,partTargetDuration:i}=n;if(!e)return;const s="#EXT-X-SERVER-CONTROL",r="holdBack",a="partHoldBack",o=t&&t*3,c=i&&i*2;t&&!e.hasOwnProperty(r)&&(e[r]=o,this.trigger("info",{message:`${s} defaulting HOLD-BACK to targetDuration * 3 (${o}).`})),o&&e[r]<o&&(this.trigger("warn",{message:`${s} clamping HOLD-BACK (${e[r]}) to targetDuration * 3 (${o})`}),e[r]=o),i&&!e.hasOwnProperty(a)&&(e[a]=i*3,this.trigger("info",{message:`${s} defaulting PART-HOLD-BACK to partTargetDuration * 3 (${e[a]}).`})),i&&e[a]<c&&(this.trigger("warn",{message:`${s} clamping PART-HOLD-BACK (${e[a]}) to partTargetDuration * 2 (${c}).`}),e[a]=c)};class j1 extends zd{constructor(e={}){super(),this.lineStream=new F1,this.parseStream=new q1,this.lineStream.pipe(this.parseStream),this.mainDefinitions=e.mainDefinitions||{},this.params=new URL(e.uri,"https://a.com").searchParams,this.lastProgramDateTime=null;const t=this,i=[];let s={},r,a,o=!1;const c=function(){},l={AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},u="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";let h=0;this.manifest={allowCache:!0,discontinuityStarts:[],dateRanges:[],iFramePlaylists:[],segments:[]};let p=0,y=0;const _={};this.on("end",()=>{s.uri||!s.parts&&!s.preloadHints||(!s.map&&r&&(s.map=r),!s.key&&a&&(s.key=a),!s.timeline&&typeof h=="number"&&(s.timeline=h),this.manifest.preloadSegment=s)}),this.parseStream.on("data",function(b){let S,D;if(t.manifest.definitions){for(const I in t.manifest.definitions)if(b.uri&&(b.uri=b.uri.replace(`{$${I}}`,t.manifest.definitions[I])),b.attributes)for(const F in b.attributes)typeof b.attributes[F]=="string"&&(b.attributes[F]=b.attributes[F].replace(`{$${I}}`,t.manifest.definitions[I]))}({tag(){({version(){b.version&&(this.manifest.version=b.version)},"allow-cache"(){this.manifest.allowCache=b.allowed,"allowed"in b||(this.trigger("info",{message:"defaulting allowCache to YES"}),this.manifest.allowCache=!0)},byterange(){const I={};"length"in b&&(s.byterange=I,I.length=b.length,"offset"in b||(b.offset=p)),"offset"in b&&(s.byterange=I,I.offset=b.offset),p=I.offset+I.length},endlist(){this.manifest.endList=!0},inf(){"mediaSequence"in this.manifest||(this.manifest.mediaSequence=0,this.trigger("info",{message:"defaulting media sequence to zero"})),"discontinuitySequence"in this.manifest||(this.manifest.discontinuitySequence=0,this.trigger("info",{message:"defaulting discontinuity sequence to zero"})),b.title&&(s.title=b.title),b.duration>0&&(s.duration=b.duration),b.duration===0&&(s.duration=.01,this.trigger("info",{message:"updating zero segment duration to a small value"})),this.manifest.segments=i},key(){if(!b.attributes){this.trigger("warn",{message:"ignoring key declaration without attribute list"});return}if(b.attributes.METHOD==="NONE"){a=null;return}if(!b.attributes.URI){this.trigger("warn",{message:"ignoring key declaration without URI"});return}if(b.attributes.KEYFORMAT==="com.apple.streamingkeydelivery"){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.apple.fps.1_0"]={attributes:b.attributes};return}if(b.attributes.KEYFORMAT==="com.microsoft.playready"){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.microsoft.playready"]={uri:b.attributes.URI};return}if(b.attributes.KEYFORMAT===u){if(["SAMPLE-AES","SAMPLE-AES-CTR","SAMPLE-AES-CENC"].indexOf(b.attributes.METHOD)===-1){this.trigger("warn",{message:"invalid key method provided for Widevine"});return}if(b.attributes.METHOD==="SAMPLE-AES-CENC"&&this.trigger("warn",{message:"SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"}),b.attributes.URI.substring(0,23)!=="data:text/plain;base64,"){this.trigger("warn",{message:"invalid key URI provided for Widevine"});return}if(!(b.attributes.KEYID&&b.attributes.KEYID.substring(0,2)==="0x")){this.trigger("warn",{message:"invalid key ID provided for Widevine"});return}this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.widevine.alpha"]={attributes:{schemeIdUri:b.attributes.KEYFORMAT,keyId:b.attributes.KEYID.substring(2)},pssh:z0(b.attributes.URI.split(",")[1])};return}b.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),a={method:b.attributes.METHOD||"AES-128",uri:b.attributes.URI},typeof b.attributes.IV<"u"&&(a.iv=b.attributes.IV)},"media-sequence"(){if(!isFinite(b.number)){this.trigger("warn",{message:"ignoring invalid media sequence: "+b.number});return}this.manifest.mediaSequence=b.number},"discontinuity-sequence"(){if(!isFinite(b.number)){this.trigger("warn",{message:"ignoring invalid discontinuity sequence: "+b.number});return}this.manifest.discontinuitySequence=b.number,h=b.number},"playlist-type"(){if(!/VOD|EVENT/.test(b.playlistType)){this.trigger("warn",{message:"ignoring unknown playlist type: "+b.playlist});return}this.manifest.playlistType=b.playlistType},map(){r={},b.uri&&(r.uri=b.uri),b.byterange&&(r.byterange=b.byterange),a&&(r.key=a)},"stream-inf"(){if(this.manifest.playlists=i,this.manifest.mediaGroups=this.manifest.mediaGroups||l,!b.attributes){this.trigger("warn",{message:"ignoring empty stream-inf attributes"});return}s.attributes||(s.attributes={}),vt(s.attributes,b.attributes)},media(){if(this.manifest.mediaGroups=this.manifest.mediaGroups||l,!(b.attributes&&b.attributes.TYPE&&b.attributes["GROUP-ID"]&&b.attributes.NAME)){this.trigger("warn",{message:"ignoring incomplete or missing media group"});return}const I=this.manifest.mediaGroups[b.attributes.TYPE];I[b.attributes["GROUP-ID"]]=I[b.attributes["GROUP-ID"]]||{},S=I[b.attributes["GROUP-ID"]],D={default:/yes/i.test(b.attributes.DEFAULT)},D.default?D.autoselect=!0:D.autoselect=/yes/i.test(b.attributes.AUTOSELECT),b.attributes.LANGUAGE&&(D.language=b.attributes.LANGUAGE),b.attributes.URI&&(D.uri=b.attributes.URI),b.attributes["INSTREAM-ID"]&&(D.instreamId=b.attributes["INSTREAM-ID"]),b.attributes.CHARACTERISTICS&&(D.characteristics=b.attributes.CHARACTERISTICS),b.attributes.FORCED&&(D.forced=/yes/i.test(b.attributes.FORCED)),S[b.attributes.NAME]=D},discontinuity(){h+=1,s.discontinuity=!0,this.manifest.discontinuityStarts.push(i.length)},"program-date-time"(){typeof this.manifest.dateTimeString>"u"&&(this.manifest.dateTimeString=b.dateTimeString,this.manifest.dateTimeObject=b.dateTimeObject),s.dateTimeString=b.dateTimeString,s.dateTimeObject=b.dateTimeObject;const{lastProgramDateTime:I}=this;this.lastProgramDateTime=new Date(b.dateTimeString).getTime(),I===null&&this.manifest.segments.reduceRight((F,w)=>(w.programDateTime=F-w.duration*1e3,w.programDateTime),this.lastProgramDateTime)},targetduration(){if(!isFinite(b.duration)||b.duration<0){this.trigger("warn",{message:"ignoring invalid target duration: "+b.duration});return}this.manifest.targetDuration=b.duration,Kd.call(this,this.manifest)},start(){if(!b.attributes||isNaN(b.attributes["TIME-OFFSET"])){this.trigger("warn",{message:"ignoring start declaration without appropriate attribute list"});return}this.manifest.start={timeOffset:b.attributes["TIME-OFFSET"],precise:b.attributes.PRECISE}},"cue-out"(){s.cueOut=b.data},"cue-out-cont"(){s.cueOutCont=b.data},"cue-in"(){s.cueIn=b.data},skip(){this.manifest.skip=ns(b.attributes),this.warnOnMissingAttributes_("#EXT-X-SKIP",b.attributes,["SKIPPED-SEGMENTS"])},part(){o=!0;const I=this.manifest.segments.length,F=ns(b.attributes);s.parts=s.parts||[],s.parts.push(F),F.byterange&&(F.byterange.hasOwnProperty("offset")||(F.byterange.offset=y),y=F.byterange.offset+F.byterange.length);const w=s.parts.length-1;this.warnOnMissingAttributes_(`#EXT-X-PART #${w} for segment #${I}`,b.attributes,["URI","DURATION"]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach((P,L)=>{P.hasOwnProperty("lastPart")||this.trigger("warn",{message:`#EXT-X-RENDITION-REPORT #${L} lacks required attribute(s): LAST-PART`})})},"server-control"(){const I=this.manifest.serverControl=ns(b.attributes);I.hasOwnProperty("canBlockReload")||(I.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"})),Kd.call(this,this.manifest),I.canSkipDateranges&&!I.hasOwnProperty("canSkipUntil")&&this.trigger("warn",{message:"#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set"})},"preload-hint"(){const I=this.manifest.segments.length,F=ns(b.attributes),w=F.type&&F.type==="PART";s.preloadHints=s.preloadHints||[],s.preloadHints.push(F),F.byterange&&(F.byterange.hasOwnProperty("offset")||(F.byterange.offset=w?y:0,w&&(y=F.byterange.offset+F.byterange.length)));const P=s.preloadHints.length-1;if(this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${P} for segment #${I}`,b.attributes,["TYPE","URI"]),!!F.type)for(let L=0;L<s.preloadHints.length-1;L++){const C=s.preloadHints[L];C.type&&C.type===F.type&&this.trigger("warn",{message:`#EXT-X-PRELOAD-HINT #${P} for segment #${I} has the same TYPE ${F.type} as preload hint #${L}`})}},"rendition-report"(){const I=ns(b.attributes);this.manifest.renditionReports=this.manifest.renditionReports||[],this.manifest.renditionReports.push(I);const F=this.manifest.renditionReports.length-1,w=["LAST-MSN","URI"];o&&w.push("LAST-PART"),this.warnOnMissingAttributes_(`#EXT-X-RENDITION-REPORT #${F}`,b.attributes,w)},"part-inf"(){this.manifest.partInf=ns(b.attributes),this.warnOnMissingAttributes_("#EXT-X-PART-INF",b.attributes,["PART-TARGET"]),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),Kd.call(this,this.manifest)},daterange(){this.manifest.dateRanges.push(ns(b.attributes));const I=this.manifest.dateRanges.length-1;this.warnOnMissingAttributes_(`#EXT-X-DATERANGE #${I}`,b.attributes,["ID","START-DATE"]);const F=this.manifest.dateRanges[I];F.endDate&&F.startDate&&new Date(F.endDate)<new Date(F.startDate)&&this.trigger("warn",{message:"EXT-X-DATERANGE END-DATE must be equal to or later than the value of the START-DATE"}),F.duration&&F.duration<0&&this.trigger("warn",{message:"EXT-X-DATERANGE DURATION must not be negative"}),F.plannedDuration&&F.plannedDuration<0&&this.trigger("warn",{message:"EXT-X-DATERANGE PLANNED-DURATION must not be negative"});const w=!!F.endOnNext;if(w&&!F.class&&this.trigger("warn",{message:"EXT-X-DATERANGE with an END-ON-NEXT=YES attribute must have a CLASS attribute"}),w&&(F.duration||F.endDate)&&this.trigger("warn",{message:"EXT-X-DATERANGE with an END-ON-NEXT=YES attribute must not contain DURATION or END-DATE attributes"}),F.duration&&F.endDate){const L=F.startDate.getTime()+F.duration*1e3;this.manifest.dateRanges[I].endDate=new Date(L)}if(!_[F.id])_[F.id]=F;else{for(const L in _[F.id])if(F[L]&&JSON.stringify(_[F.id][L])!==JSON.stringify(F[L])){this.trigger("warn",{message:"EXT-X-DATERANGE tags with the same ID in a playlist must have the same attributes values"});break}const P=this.manifest.dateRanges.findIndex(L=>L.id===F.id);this.manifest.dateRanges[P]=vt(this.manifest.dateRanges[P],F),_[F.id]=vt(_[F.id],F),this.manifest.dateRanges.pop()}},"independent-segments"(){this.manifest.independentSegments=!0},"i-frames-only"(){this.manifest.iFramesOnly=!0,this.requiredCompatibilityversion(this.manifest.version,4)},"content-steering"(){this.manifest.contentSteering=ns(b.attributes),this.warnOnMissingAttributes_("#EXT-X-CONTENT-STEERING",b.attributes,["SERVER-URI"])},define(){this.manifest.definitions=this.manifest.definitions||{};const I=(F,w)=>{if(F in this.manifest.definitions){this.trigger("error",{message:`EXT-X-DEFINE: Duplicate name ${F}`});return}this.manifest.definitions[F]=w};if("QUERYPARAM"in b.attributes){if("NAME"in b.attributes||"IMPORT"in b.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}const F=this.params.get(b.attributes.QUERYPARAM);if(!F){this.trigger("error",{message:`EXT-X-DEFINE: No query param ${b.attributes.QUERYPARAM}`});return}I(b.attributes.QUERYPARAM,decodeURIComponent(F));return}if("NAME"in b.attributes){if("IMPORT"in b.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}if(!("VALUE"in b.attributes)||typeof b.attributes.VALUE!="string"){this.trigger("error",{message:`EXT-X-DEFINE: No value for ${b.attributes.NAME}`});return}I(b.attributes.NAME,b.attributes.VALUE);return}if("IMPORT"in b.attributes){if(!this.mainDefinitions[b.attributes.IMPORT]){this.trigger("error",{message:`EXT-X-DEFINE: No value ${b.attributes.IMPORT} to import, or IMPORT used on main playlist`});return}I(b.attributes.IMPORT,this.mainDefinitions[b.attributes.IMPORT]);return}this.trigger("error",{message:"EXT-X-DEFINE: No attribute"})},"i-frame-playlist"(){this.manifest.iFramePlaylists.push({attributes:b.attributes,uri:b.uri,timeline:h}),this.warnOnMissingAttributes_("#EXT-X-I-FRAME-STREAM-INF",b.attributes,["BANDWIDTH","URI"])}}[b.tagType]||c).call(t)},uri(){s.uri=b.uri,i.push(s),this.manifest.targetDuration&&!("duration"in s)&&(this.trigger("warn",{message:"defaulting segment duration to the target duration"}),s.duration=this.manifest.targetDuration),a&&(s.key=a),s.timeline=h,r&&(s.map=r),y=0,this.lastProgramDateTime!==null&&(s.programDateTime=this.lastProgramDateTime,this.lastProgramDateTime+=s.duration*1e3),s={}},comment(){},custom(){b.segment?(s.custom=s.custom||{},s.custom[b.customType]=b.data):(this.manifest.custom=this.manifest.custom||{},this.manifest.custom[b.customType]=b.data)}})[b.type].call(t)})}requiredCompatibilityversion(e,t){(e<t||!e)&&this.trigger("warn",{message:`manifest must be at least version ${t}`})}warnOnMissingAttributes_(e,t,i){const s=[];i.forEach(function(r){t.hasOwnProperty(r)||s.push(r)}),s.length&&this.trigger("warn",{message:`${e} lacks required attribute(s): ${s.join(", ")}`})}push(e){this.lineStream.push(e)}end(){this.lineStream.push(`
|
|
67
|
+
`),this.manifest.dateRanges.length&&this.lastProgramDateTime===null&&this.trigger("warn",{message:"A playlist with EXT-X-DATERANGE tag must contain atleast one EXT-X-PROGRAM-DATE-TIME tag"}),this.lastProgramDateTime=null,this.trigger("end")}addParser(e){this.parseStream.addParser(e)}addTagMapper(e){this.parseStream.addTagMapper(e)}}var Os={mp4:/^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,webm:/^(vp0?[89]|av0?1|opus|vorbis)/,ogg:/^(vp0?[89]|theora|flac|opus|vorbis)/,video:/^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,audio:/^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,text:/^(stpp.ttml.im1t)/,muxerVideo:/^(avc0?1)/,muxerAudio:/^(mp4a)/,muxerText:/a^/},H1=["video","audio","text"],K0=["Video","Audio","Text"],X0=function(e){return e&&e.replace(/avc1\.(\d+)\.(\d+)/i,function(t,i,s){var r=("00"+Number(i).toString(16)).slice(-2),a=("00"+Number(s).toString(16)).slice(-2);return"avc1."+r+"00"+a})},on=function(e){e===void 0&&(e="");var t=e.split(","),i=[];return t.forEach(function(s){s=s.trim();var r;H1.forEach(function(a){var o=Os[a].exec(s.toLowerCase());if(!(!o||o.length<=1)){r=a;var c=s.substring(0,o[1].length),l=s.replace(c,"");i.push({type:c,details:l,mediaType:a})}}),r||i.push({type:s,details:"",mediaType:"unknown"})}),i},$1=function(e,t){if(!e.mediaGroups.AUDIO||!t)return null;var i=e.mediaGroups.AUDIO[t];if(!i)return null;for(var s in i){var r=i[s];if(r.default&&r.playlists)return on(r.playlists[0].attributes.CODECS)}return null},Y0=function(e){return e===void 0&&(e=""),Os.audio.test(e.trim().toLowerCase())},W1=function(e){return e===void 0&&(e=""),Os.text.test(e.trim().toLowerCase())},gr=function(e){if(!(!e||typeof e!="string")){var t=e.toLowerCase().split(",").map(function(r){return X0(r.trim())}),i="video";t.length===1&&Y0(t[0])?i="audio":t.length===1&&W1(t[0])&&(i="application");var s="mp4";return t.every(function(r){return Os.mp4.test(r)})?s="mp4":t.every(function(r){return Os.webm.test(r)})?s="webm":t.every(function(r){return Os.ogg.test(r)})&&(s="ogg"),i+"/"+s+';codecs="'+e+'"'}},Oa=function(e,t){return e===void 0&&(e=""),t===void 0&&(t=!1),B.MediaSource&&B.MediaSource.isTypeSupported&&B.MediaSource.isTypeSupported(gr(e))||t&&B.ManagedMediaSource&&B.ManagedMediaSource.isTypeSupported&&B.ManagedMediaSource.isTypeSupported(gr(e))||!1},Xd=function(e){return e===void 0&&(e=""),e.toLowerCase().split(",").every(function(t){t=t.trim();for(var i=0;i<K0.length;i++){var s=K0[i];if(Os["muxer"+s].test(t))return!0}return!1})},Q0="mp4a.40.2",z1="avc1.4d400d",G1=/^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i,K1=/^application\/dash\+xml/i,J0=function(e){return G1.test(e)?"hls":K1.test(e)?"dash":e==="application/vnd.videojs.vhs+json"?"vhs-json":null},X1=function(e){return e.toString(2).length},Y1=function(e){return Math.ceil(X1(e)/8)},Z0=function(e){return ArrayBuffer.isView==="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer},Q1=function(e){return Z0(e)},Ce=function(e){return e instanceof Uint8Array?e:(!Array.isArray(e)&&!Q1(e)&&!(e instanceof ArrayBuffer)&&(typeof e!="number"||typeof e=="number"&&e!==e?e=0:e=[e]),new Uint8Array(e&&e.buffer||e,e&&e.byteOffset||0,e&&e.byteLength||0))},Bt=B.BigInt||Number,Yd=[Bt("0x1"),Bt("0x100"),Bt("0x10000"),Bt("0x1000000"),Bt("0x100000000"),Bt("0x10000000000"),Bt("0x1000000000000"),Bt("0x100000000000000"),Bt("0x10000000000000000")];(function(){var n=new Uint16Array([65484]),e=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return e[0]===255?"big":e[0]===204?"little":"unknown"})();var J1=function(e,t){var i=t===void 0?{}:t,s=i.signed,r=s===void 0?!1:s,a=i.le,o=a===void 0?!1:a;e=Ce(e);var c=o?"reduce":"reduceRight",l=e[c]?e[c]:Array.prototype[c],u=l.call(e,function(p,y,_){var b=o?_:Math.abs(_+1-e.length);return p+Bt(y)*Yd[b]},Bt(0));if(r){var h=Yd[e.length]/Bt(2)-Bt(1);u=Bt(u),u>h&&(u-=h,u-=h,u-=Bt(2))}return Number(u)},Z1=function(e,t){var i={},s=i.le,r=s===void 0?!1:s;(typeof e!="bigint"&&typeof e!="number"||typeof e=="number"&&e!==e)&&(e=0),e=Bt(e);for(var a=Y1(e),o=new Uint8Array(new ArrayBuffer(a)),c=0;c<a;c++){var l=r?c:Math.abs(c+1-o.length);o[l]=Number(e/Yd[c]&Bt(255)),e<0&&(o[l]=Math.abs(~o[l]),o[l]-=c===0?1:2)}return o},ey=function(e,t){if(typeof e!="string"&&e&&typeof e.toString=="function"&&(e=e.toString()),typeof e!="string")return new Uint8Array;t||(e=unescape(encodeURIComponent(e)));for(var i=new Uint8Array(e.length),s=0;s<e.length;s++)i[s]=e.charCodeAt(s);return i},ex=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(t=t.filter(function(o){return o&&(o.byteLength||o.length)&&typeof o!="string"}),t.length<=1)return Ce(t[0]);var s=t.reduce(function(o,c,l){return o+(c.byteLength||c.length)},0),r=new Uint8Array(s),a=0;return t.forEach(function(o){o=Ce(o),r.set(o,a),a+=o.byteLength}),r},tt=function(e,t,i){var s=i===void 0?{}:i,r=s.offset,a=r===void 0?0:r,o=s.mask,c=o===void 0?[]:o;e=Ce(e),t=Ce(t);var l=t.every?t.every:Array.prototype.every;return t.length&&e.length-a>=t.length&&l.call(t,function(u,h){var p=c[h]?c[h]&e[a+h]:e[a+h];return u===p})},tx=function(e,t,i){t.forEach(function(s){for(var r in e.mediaGroups[s])for(var a in e.mediaGroups[s][r]){var o=e.mediaGroups[s][r][a];i(o,s,r,a)}})},Ma={},cn={},ln={},ty;function La(){if(ty)return ln;ty=1;function n(c,l,u){if(u===void 0&&(u=Array.prototype),c&&typeof u.find=="function")return u.find.call(c,l);for(var h=0;h<c.length;h++)if(Object.prototype.hasOwnProperty.call(c,h)){var p=c[h];if(l.call(void 0,p,h,c))return p}}function e(c,l){return l===void 0&&(l=Object),l&&typeof l.freeze=="function"?l.freeze(c):c}function t(c,l){if(c===null||typeof c!="object")throw new TypeError("target is not an object");for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[u]=l[u]);return c}var i=e({HTML:"text/html",isHTML:function(c){return c===i.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),s=e({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(c){return c===s.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),r=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,a=new RegExp("[\\-\\.0-9"+r.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),o=new RegExp("^"+r.source+a.source+"*(?::"+r.source+a.source+"*)?$");return ln.assign=t,ln.find=n,ln.freeze=e,ln.MIME_TYPE=i,ln.NAMESPACE=s,ln.nameStartChar=r,ln.nameChar=a,ln.tagNamePattern=o,ln}var iy;function ny(){if(iy)return cn;iy=1;var n=La(),e=n.find,t=n.NAMESPACE,i=n.tagNamePattern;function s(E){return E!==""}function r(E){return E?E.split(/[\t\n\f\r ]+/).filter(s):[]}function a(E,A){return E.hasOwnProperty(A)||(E[A]=!0),E}function o(E){if(!E)return[];var A=r(E);return Object.keys(A.reduce(a,{}))}function c(E){return function(A){return E&&E.indexOf(A)!==-1}}function l(E,A){for(var V in E)Object.prototype.hasOwnProperty.call(E,V)&&(A[V]=E[V])}function u(E,A){var V=E.prototype;if(!(V instanceof A)){let J=function(){};J.prototype=A.prototype,J=new J,l(V,J),E.prototype=V=J}V.constructor!=E&&(typeof E!="function"&&console.error("unknown Class:"+E),V.constructor=E)}var h={},p=h.ELEMENT_NODE=1,y=h.ATTRIBUTE_NODE=2,_=h.TEXT_NODE=3,b=h.CDATA_SECTION_NODE=4,S=h.ENTITY_REFERENCE_NODE=5,D=h.ENTITY_NODE=6,I=h.PROCESSING_INSTRUCTION_NODE=7,F=h.COMMENT_NODE=8,w=h.DOCUMENT_NODE=9,P=h.DOCUMENT_TYPE_NODE=10,L=h.DOCUMENT_FRAGMENT_NODE=11,C=h.NOTATION_NODE=12,N={},x={};N.INDEX_SIZE_ERR=(x[1]="Index size error",1),N.DOMSTRING_SIZE_ERR=(x[2]="DOMString size error",2);var k=N.HIERARCHY_REQUEST_ERR=(x[3]="Hierarchy request error",3);N.WRONG_DOCUMENT_ERR=(x[4]="Wrong document",4);var j=N.INVALID_CHARACTER_ERR=(x[5]="Invalid character",5);N.NO_DATA_ALLOWED_ERR=(x[6]="No data allowed",6),N.NO_MODIFICATION_ALLOWED_ERR=(x[7]="No modification allowed",7);var G=N.NOT_FOUND_ERR=(x[8]="Not found",8);N.NOT_SUPPORTED_ERR=(x[9]="Not supported",9);var X=N.INUSE_ATTRIBUTE_ERR=(x[10]="Attribute in use",10),z=N.INVALID_STATE_ERR=(x[11]="Invalid state",11);N.SYNTAX_ERR=(x[12]="Syntax error",12),N.INVALID_MODIFICATION_ERR=(x[13]="Invalid modification",13),N.NAMESPACE_ERR=(x[14]="Invalid namespace",14),N.INVALID_ACCESS_ERR=(x[15]="Invalid access",15);function W(E,A){if(A instanceof Error)var V=A;else V=this,Error.call(this,x[E]),this.message=x[E],Error.captureStackTrace&&Error.captureStackTrace(this,W);return V.code=E,A&&(this.message=this.message+": "+A),V}W.prototype=Error.prototype,l(N,W);function te(){}te.prototype={length:0,item:function(E){return E>=0&&E<this.length?this[E]:null},toString:function(E,A,V){for(var J=!!V&&!!V.requireWellFormed,ue=[],me=0;me<this.length;me++)uo(this[me],ue,E,A,null,J);return ue.join("")},filter:function(E){return Array.prototype.filter.call(this,E)},indexOf:function(E){return Array.prototype.indexOf.call(this,E)}};function Q(E,A){this._node=E,this._refresh=A,re(this)}function re(E){var A=E._node._inc||E._node.ownerDocument._inc;if(E._inc!==A){var V=E._refresh(E._node);if(Il(E,"length",V.length),!E.$$length||V.length<E.$$length)for(var J=V.length;J in E;J++)Object.prototype.hasOwnProperty.call(E,J)&&delete E[J];l(V,E),E._inc=A}}Q.prototype.item=function(E){return re(this),this[E]||null},u(Q,te);function Y(){this._nameIndex=Object.create(null)}function ie(E,A){for(var V=E.length;V--;)if(E[V]===A)return V}function ge(E,A){E._nameIndex[A.nodeName]=A}function Te(E,A){E._nameIndex[A.nodeName]===A&&delete E._nameIndex[A.nodeName]}function be(E,A,V,J){if(J?(A[ie(A,J)]=V,Te(A,J)):A[A.length++]=V,ge(A,V),E){V.ownerElement=E;var ue=E.ownerDocument;ue&&(J&&wt(ue,E,J),Bn(ue,E,V))}}function we(E,A,V){var J=ie(A,V);if(J>=0){for(var ue=A.length-1;J<ue;)A[J]=A[++J];if(A.length=ue,Te(A,V),E){var me=E.ownerDocument;me&&(wt(me,E,V),V.ownerElement=null)}}else throw new W(G,new Error(E.tagName+"@"+V))}Y.prototype={length:0,item:te.prototype.item,getNamedItem:function(E){for(var A=this.length;A--;){var V=this[A];if(V.nodeName==E)return V}},setNamedItem:function(E){var A=E.ownerElement;if(A&&A!=this._ownerElement)throw new W(X);var V=this._nameIndex[E.nodeName];return be(this._ownerElement,this,E,V),V},setNamedItemNS:function(E){var A=E.ownerElement,V;if(A&&A!=this._ownerElement)throw new W(X);return V=this.getNamedItemNS(E.namespaceURI,E.localName),be(this._ownerElement,this,E,V),V},removeNamedItem:function(E){var A=this.getNamedItem(E);return we(this._ownerElement,this,A),A},removeNamedItemNS:function(E,A){var V=this.getNamedItemNS(E,A);return we(this._ownerElement,this,V),V},getNamedItemNS:function(E,A){for(var V=this.length;V--;){var J=this[V];if(J.localName==A&&J.namespaceURI==E)return J}return null}};function Pe(){}Pe.prototype={hasFeature:function(E,A){return!0},createDocument:function(E,A,V){var J=new fi;if(J.implementation=this,J.childNodes=new te,J.doctype=V||null,V&&J.appendChild(V),A){var ue=J.createElementNS(E,A);J.appendChild(ue)}return J},createDocumentType:function(E,A,V){var J=new Vn;return J.name=E,J.nodeName=E,J.publicId=A||"",J.systemId=V||"",J}};function ve(){}ve.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(E,A){return hs(this,E,A)},replaceChild:function(E,A){hs(this,E,A,Kr),A&&this.removeChild(A)},removeChild:function(E){return kt(this,E)},appendChild:function(E){return this.insertBefore(E,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(E){return ho(this.ownerDocument||this,this,E)},normalize:function(){et(this,null,{enter:function(E){for(var A=E.firstChild;A;){var V=A.nextSibling;if(V!==null&&V.nodeType===_&&A.nodeType===_){for(var J=[],ue=V;ue!==null&&ue.nodeType===_;)J.push(ue.data),ue=ue.nextSibling;for(var me=A.nextSibling;me!==ue;){var ce=me.nextSibling;me.parentNode=null,me.previousSibling=null,me.nextSibling=null,me=ce}A.nextSibling=ue,ue!==null?ue.previousSibling=A:E.lastChild=A,A.appendData(J.join("")),bn(E.ownerDocument,E),A=ue}else A=V}return!0}})},isSupported:function(E,A){return this.ownerDocument.implementation.hasFeature(E,A)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(E){for(var A=this;A;){var V=A._nsMap;if(V){for(var J in V)if(Object.prototype.hasOwnProperty.call(V,J)&&V[J]===E)return J}A=A.nodeType==y?A.ownerDocument:A.parentNode}return null},lookupNamespaceURI:function(E){for(var A=this;A;){var V=A._nsMap;if(V&&Object.prototype.hasOwnProperty.call(V,E))return V[E];A=A.nodeType==y?A.ownerDocument:A.parentNode}return null},isDefaultNamespace:function(E){var A=this.lookupPrefix(E);return A==null}};function qe(E){return E=="<"&&"<"||E==">"&&">"||E=="&"&&"&"||E=='"'&&"""||"&#"+E.charCodeAt()+";"}l(h,ve),l(h,ve.prototype);function bt(E,A){return et(E,null,{enter:function(V){return A(V)?et.STOP:!0}})===et.STOP}function et(E,A,V){for(var J=[{node:E,context:A,phase:et.ENTER}];J.length>0;){var ue=J.pop();if(ue.phase===et.ENTER){var me=V.enter(ue.node,ue.context);if(me===et.STOP)return et.STOP;if(J.push({node:ue.node,context:me,phase:et.EXIT}),me==null)continue;for(var ce=ue.node.lastChild;ce;)J.push({node:ce,context:me,phase:et.ENTER}),ce=ce.previousSibling}else V.exit&&V.exit(ue.node,ue.context)}}et.STOP=Symbol("walkDOM.STOP"),et.ENTER=0,et.EXIT=1;function fi(){this.ownerDocument=this}function Bn(E,A,V){E&&E._inc++;var J=V.namespaceURI;J===t.XMLNS&&(A._nsMap[V.prefix?V.localName:""]=V.value)}function wt(E,A,V,J){E&&E._inc++;var ue=V.namespaceURI;ue===t.XMLNS&&delete A._nsMap[V.prefix?V.localName:""]}function bn(E,A,V){if(E&&E._inc){E._inc++;var J=A.childNodes;if(V)J[J.length++]=V;else{for(var ue=A.firstChild,me=0;ue;)J[me++]=ue,ue=ue.nextSibling;J.length=me,delete J[J.length]}}}function kt(E,A){var V=A.previousSibling,J=A.nextSibling;return V?V.nextSibling=J:E.firstChild=J,J?J.previousSibling=V:E.lastChild=V,A.parentNode=null,A.previousSibling=null,A.nextSibling=null,bn(E.ownerDocument,E),A}function zr(E){return E&&(E.nodeType===ve.DOCUMENT_NODE||E.nodeType===ve.DOCUMENT_FRAGMENT_NODE||E.nodeType===ve.ELEMENT_NODE)}function ro(E){return E&&(mt(E)||Ge(E)||ii(E)||E.nodeType===ve.DOCUMENT_FRAGMENT_NODE||E.nodeType===ve.COMMENT_NODE||E.nodeType===ve.PROCESSING_INSTRUCTION_NODE)}function ii(E){return E&&E.nodeType===ve.DOCUMENT_TYPE_NODE}function mt(E){return E&&E.nodeType===ve.ELEMENT_NODE}function Ge(E){return E&&E.nodeType===ve.TEXT_NODE}function Ae(E,A){var V=E.childNodes||[];if(e(V,mt)||ii(A))return!1;var J=e(V,ii);return!(A&&J&&V.indexOf(J)>V.indexOf(A))}function Gr(E,A){var V=E.childNodes||[];function J(me){return mt(me)&&me!==A}if(e(V,J))return!1;var ue=e(V,ii);return!(A&&ue&&V.indexOf(ue)>V.indexOf(A))}function ao(E,A,V){if(!zr(E))throw new W(k,"Unexpected parent node type "+E.nodeType);if(V&&V.parentNode!==E)throw new W(G,"child not in parent");if(!ro(A)||ii(A)&&E.nodeType!==ve.DOCUMENT_NODE)throw new W(k,"Unexpected node type "+A.nodeType+" for parent node type "+E.nodeType)}function wf(E,A,V){var J=E.childNodes||[],ue=A.childNodes||[];if(A.nodeType===ve.DOCUMENT_FRAGMENT_NODE){var me=ue.filter(mt);if(me.length>1||e(ue,Ge))throw new W(k,"More than one element or text in fragment");if(me.length===1&&!Ae(E,V))throw new W(k,"Element in fragment can not be inserted before doctype")}if(mt(A)&&!Ae(E,V))throw new W(k,"Only one element can be added and only after doctype");if(ii(A)){if(e(J,ii))throw new W(k,"Only one doctype is allowed");var ce=e(J,mt);if(V&&J.indexOf(ce)<J.indexOf(V))throw new W(k,"Doctype can only be inserted before an element");if(!V&&ce)throw new W(k,"Doctype can not be appended since element is present")}}function Kr(E,A,V){var J=E.childNodes||[],ue=A.childNodes||[];if(A.nodeType===ve.DOCUMENT_FRAGMENT_NODE){var me=ue.filter(mt);if(me.length>1||e(ue,Ge))throw new W(k,"More than one element or text in fragment");if(me.length===1&&!Gr(E,V))throw new W(k,"Element in fragment can not be inserted before doctype")}if(mt(A)&&!Gr(E,V))throw new W(k,"Only one element can be added and only after doctype");if(ii(A)){if(e(J,function(At){return ii(At)&&At!==V}))throw new W(k,"Only one doctype is allowed");var ce=e(J,mt);if(V&&J.indexOf(ce)<J.indexOf(V))throw new W(k,"Doctype can only be inserted before an element")}}function hs(E,A,V,J){ao(E,A,V),E.nodeType===ve.DOCUMENT_NODE&&(J||wf)(E,A,V);var ue=A.parentNode;if(ue&&ue.removeChild(A),A.nodeType===L){var me=A.firstChild;if(me==null)return A;var ce=A.lastChild}else me=ce=A;var Me=V?V.previousSibling:E.lastChild;me.previousSibling=Me,ce.nextSibling=V,Me?Me.nextSibling=me:E.firstChild=me,V==null?E.lastChild=ce:V.previousSibling=ce;do{me.parentNode=E;var At=E.ownerDocument||E;qn(me,At)}while(me!==ce&&(me=me.nextSibling));return bn(E.ownerDocument||E,E),A.nodeType==L&&(A.firstChild=A.lastChild=null),A}function qn(E,A){if(E.ownerDocument!==A){if(E.ownerDocument=A,E.nodeType===p&&E.attributes)for(var V=0;V<E.attributes.length;V++){var J=E.attributes.item(V);J&&(J.ownerDocument=A)}for(var ue=E.firstChild;ue;)qn(ue,A),ue=ue.nextSibling}}function Xr(E,A){A.parentNode&&A.parentNode.removeChild(A),A.parentNode=E,A.previousSibling=E.lastChild,A.nextSibling=null,A.previousSibling?A.previousSibling.nextSibling=A:E.firstChild=A,E.lastChild=A,bn(E.ownerDocument,E,A);var V=E.ownerDocument||E;return qn(A,V),A}fi.prototype={nodeName:"#document",nodeType:w,doctype:null,documentElement:null,_inc:1,insertBefore:function(E,A){if(E.nodeType==L){for(var V=E.firstChild;V;){var J=V.nextSibling;this.insertBefore(V,A),V=J}return E}return hs(this,E,A),qn(E,this),this.documentElement===null&&E.nodeType===p&&(this.documentElement=E),E},removeChild:function(E){return this.documentElement==E&&(this.documentElement=null),kt(this,E)},replaceChild:function(E,A){hs(this,E,A,Kr),qn(E,this),A&&this.removeChild(A),mt(E)&&(this.documentElement=E)},importNode:function(E,A){return Af(this,E,A)},getElementById:function(E){var A=null;return bt(this.documentElement,function(V){if(V.nodeType==p&&V.getAttribute("id")==E)return A=V,!0}),A},getElementsByClassName:function(E){var A=o(E);return new Q(this,function(V){var J=[];return A.length>0&&bt(V.documentElement,function(ue){if(ue!==V&&ue.nodeType===p){var me=ue.getAttribute("class");if(me){var ce=E===me;if(!ce){var Me=o(me);ce=A.every(c(Me))}ce&&J.push(ue)}}}),J})},createElement:function(E){var A=new Ki;A.ownerDocument=this,A.nodeName=E,A.tagName=E,A.localName=E,A.childNodes=new te;var V=A.attributes=new Y;return V._ownerElement=A,A},createDocumentFragment:function(){var E=new Qr;return E.ownerDocument=this,E.childNodes=new te,E},createTextNode:function(E){var A=new Yr;return A.ownerDocument=this,A.appendData(E),A},createComment:function(E){var A=new Ke;return A.ownerDocument=this,A.appendData(E),A},createCDATASection:function(E){if(E.indexOf("]]>")!==-1)throw new W(j,'data contains "]]>"');var A=new oo;return A.ownerDocument=this,A.appendData(E),A},createProcessingInstruction:function(E,A){var V=new lo;return V.ownerDocument=this,V.tagName=V.nodeName=V.target=E,V.nodeValue=V.data=A,V},createAttribute:function(E){var A=new Ws;return A.ownerDocument=this,A.name=E,A.nodeName=E,A.localName=E,A.specified=!0,A},createEntityReference:function(E){if(!i.test(E))throw new W(j,'not a valid xml name "'+E+'"');var A=new co;return A.ownerDocument=this,A.nodeName=E,A},createElementNS:function(E,A){var V=new Ki,J=A.split(":"),ue=V.attributes=new Y;return V.childNodes=new te,V.ownerDocument=this,V.nodeName=A,V.tagName=A,V.namespaceURI=E,J.length==2?(V.prefix=J[0],V.localName=J[1]):V.localName=A,ue._ownerElement=V,V},createAttributeNS:function(E,A){var V=new Ws,J=A.split(":");return V.ownerDocument=this,V.nodeName=A,V.name=A,V.namespaceURI=E,V.specified=!0,J.length==2?(V.prefix=J[0],V.localName=J[1]):V.localName=A,V}},u(fi,ve);function Ki(){this._nsMap={}}Ki.prototype={nodeType:p,hasAttribute:function(E){return this.getAttributeNode(E)!=null},getAttribute:function(E){var A=this.getAttributeNode(E);return A&&A.value||""},getAttributeNode:function(E){return this.attributes.getNamedItem(E)},setAttribute:function(E,A){var V=this.ownerDocument.createAttribute(E);V.value=V.nodeValue=""+A,this.setAttributeNode(V)},removeAttribute:function(E){var A=this.getAttributeNode(E);A&&this.removeAttributeNode(A)},appendChild:function(E){return E.nodeType===L?this.insertBefore(E,null):Xr(this,E)},setAttributeNode:function(E){return this.attributes.setNamedItem(E)},setAttributeNodeNS:function(E){return this.attributes.setNamedItemNS(E)},removeAttributeNode:function(E){return this.attributes.removeNamedItem(E.nodeName)},removeAttributeNS:function(E,A){var V=this.getAttributeNodeNS(E,A);V&&this.removeAttributeNode(V)},hasAttributeNS:function(E,A){return this.getAttributeNodeNS(E,A)!=null},getAttributeNS:function(E,A){var V=this.getAttributeNodeNS(E,A);return V&&V.value||""},setAttributeNS:function(E,A,V){var J=this.ownerDocument.createAttributeNS(E,A);J.value=J.nodeValue=""+V,this.setAttributeNode(J)},getAttributeNodeNS:function(E,A){return this.attributes.getNamedItemNS(E,A)},getElementsByTagName:function(E){return new Q(this,function(A){var V=[];return bt(A,function(J){J!==A&&J.nodeType==p&&(E==="*"||J.tagName==E)&&V.push(J)}),V})},getElementsByTagNameNS:function(E,A){return new Q(this,function(V){var J=[];return bt(V,function(ue){ue!==V&&ue.nodeType===p&&(E==="*"||ue.namespaceURI===E)&&(A==="*"||ue.localName==A)&&J.push(ue)}),J})}},fi.prototype.getElementsByTagName=Ki.prototype.getElementsByTagName,fi.prototype.getElementsByTagNameNS=Ki.prototype.getElementsByTagNameNS,u(Ki,ve);function Ws(){}Ws.prototype.nodeType=y,u(Ws,ve);function fs(){}fs.prototype={data:"",substringData:function(E,A){return this.data.substring(E,E+A)},appendData:function(E){E=this.data+E,this.nodeValue=this.data=E,this.length=E.length},insertData:function(E,A){this.replaceData(E,0,A)},appendChild:function(E){throw new Error(x[k])},deleteData:function(E,A){this.replaceData(E,A,"")},replaceData:function(E,A,V){var J=this.data.substring(0,E),ue=this.data.substring(E+A);V=J+V+ue,this.nodeValue=this.data=V,this.length=V.length}},u(fs,ve);function Yr(){}Yr.prototype={nodeName:"#text",nodeType:_,splitText:function(E){var A=this.data,V=A.substring(E);A=A.substring(0,E),this.data=this.nodeValue=A,this.length=A.length;var J=this.ownerDocument.createTextNode(V);return this.parentNode&&this.parentNode.insertBefore(J,this.nextSibling),J}},u(Yr,fs);function Ke(){}Ke.prototype={nodeName:"#comment",nodeType:F},u(Ke,fs);function oo(){}oo.prototype={nodeName:"#cdata-section",nodeType:b},u(oo,fs);function Vn(){}Vn.prototype.nodeType=P,u(Vn,ve);function xl(){}xl.prototype.nodeType=C,u(xl,ve);function wl(){}wl.prototype.nodeType=D,u(wl,ve);function co(){}co.prototype.nodeType=S,u(co,ve);function Qr(){}Qr.prototype.nodeName="#document-fragment",Qr.prototype.nodeType=L,u(Qr,ve);function lo(){}lo.prototype.nodeType=I,u(lo,ve);function Al(){}Al.prototype.serializeToString=function(E,A,V,J){return Dl.call(E,A,V,J)},ve.prototype.toString=Dl;function Dl(E,A,V){var J=!!V&&!!V.requireWellFormed,ue=[],me=this.nodeType==9&&this.documentElement||this,ce=me.prefix,Me=me.namespaceURI;if(Me&&ce==null){var ce=me.lookupPrefix(Me);if(ce==null)var At=[{namespace:Me,prefix:null}]}return uo(this,ue,E,A,At,J),ue.join("")}function Pl(E,A,V){var J=E.prefix||"",ue=E.namespaceURI;if(!ue||J==="xml"&&ue===t.XML||ue===t.XMLNS)return!1;for(var me=V.length;me--;){var ce=V[me];if(ce.prefix===J)return ce.namespace!==ue}return!0}function Jr(E,A,V,J){if(J&&!i.test(A))throw new W(z,'The attribute name "'+A+'" is not a valid XML QName');E.push(" ",A,'="',V.replace(/[<>&"\t\n\r]/g,qe),'"')}function uo(E,A,V,J,ue,me){ue||(ue=[]),et(E,{ns:ue,isHTML:V},{enter:function(ce,Me){var At=Me.ns,ni=Me.isHTML;if(J)if(ce=J(ce),ce){if(typeof ce=="string")return A.push(ce),null}else return null;switch(ce.nodeType){case p:var pi=ce.attributes,mi=pi.length,Si=ce.tagName;ni=t.isHTML(ce.namespaceURI)||ni;var Ne=Si;if(!ni&&!ce.prefix&&ce.namespaceURI){for(var Zr,jn=0;jn<pi.length;jn++)if(pi.item(jn).name==="xmlns"){Zr=pi.item(jn).value;break}if(!Zr)for(var Mi=At.length-1;Mi>=0;Mi--){var Hn=At[Mi];if(Hn.prefix===""&&Hn.namespace===ce.namespaceURI){Zr=Hn.namespace;break}}if(Zr!==ce.namespaceURI)for(var Mi=At.length-1;Mi>=0;Mi--){var Hn=At[Mi];if(Hn.namespace===ce.namespaceURI){Hn.prefix&&(Ne=Hn.prefix+":"+Si);break}}}if(me&&!i.test(Ne))throw new W(z,'The element name "'+Ne+'" is not a valid XML QName');A.push("<",Ne);for(var zt=At.slice(),je=0;je<mi;je++){var gi=pi.item(je);gi.prefix=="xmlns"?zt.push({prefix:gi.localName,namespace:gi.value}):gi.nodeName=="xmlns"&&zt.push({prefix:"",namespace:gi.value})}for(var je=0;je<mi;je++){var gi=pi.item(je);if(Pl(gi,ni,zt)){var ps=gi.prefix||"",zs=gi.namespaceURI;Jr(A,ps?"xmlns:"+ps:"xmlns",zs,me),zt.push({prefix:ps,namespace:zs})}var Gs=J?J(gi):gi;Gs&&(typeof Gs=="string"?A.push(Gs):Jr(A,Gs.name,Gs.value,me))}if(Si===Ne&&Pl(ce,ni,zt)){var fo=ce.prefix||"",zs=ce.namespaceURI;Jr(A,fo?"xmlns:"+fo:"xmlns",zs,me),zt.push({prefix:fo,namespace:zs})}var Tn=ce.firstChild;if(Tn||ni&&!/^(?:meta|link|img|br|hr|input)$/i.test(Si)){if(A.push(">"),ni&&/^script$/i.test(Si)){for(;Tn;)Tn.data?A.push(Tn.data):uo(Tn,A,ni,J,zt.slice(),me),Tn=Tn.nextSibling;return A.push("</",Si,">"),null}return{ns:zt,isHTML:ni,tag:Ne}}else return A.push("/>"),null;case w:case L:return{ns:At.slice(),isHTML:ni,tag:null};case y:return Jr(A,ce.name,ce.value,me),null;case _:return A.push(ce.data.replace(/[<&>]/g,qe)),null;case b:if(me&&ce.data.indexOf("]]>")!==-1)throw new W(z,'The CDATASection data contains "]]>"');return A.push("<![CDATA[",ce.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case F:if(me&&ce.data.indexOf("-->")!==-1)throw new W(z,'The comment node data contains "-->"');return A.push("<!--",ce.data,"-->"),null;case P:if(me){if(!i.test(ce.name))throw new W(z,'The doctype name "'+ce.name+'" is not a valid XML Name');if(ce.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(ce.publicId))throw new W(z,"DocumentType publicId is not a valid PubidLiteral");if(ce.systemId&&!/^("[^"]*"|'[^']*')$/.test(ce.systemId))throw new W(z,"DocumentType systemId is not a valid SystemLiteral");if(ce.internalSubset&&ce.internalSubset.indexOf("]>")!==-1)throw new W(z,'DocumentType internalSubset contains "]>"')}var ea=ce.publicId,_n=ce.systemId;if(A.push("<!DOCTYPE ",ce.name),ea)A.push(" PUBLIC ",ea),_n&&_n!="."&&A.push(" ",_n),A.push(">");else if(_n&&_n!=".")A.push(" SYSTEM ",_n,">");else{var po=ce.internalSubset;po&&A.push(" [",po,"]"),A.push(">")}return null;case I:if(me){if(!i.test(ce.target)||ce.target.indexOf(":")!==-1||ce.target.toLowerCase()==="xml")throw new W(z,'The processing instruction target "'+ce.target+'" is not a valid XML NCName or is reserved');if(ce.data.indexOf("?>")!==-1)throw new W(z,'The ProcessingInstruction data contains "?>"')}return A.push("<?",ce.target," ",ce.data,"?>"),null;case S:if(me&&!i.test(ce.nodeName))throw new W(z,'The entity reference name "'+ce.nodeName+'" is not a valid XML Name');return A.push("&",ce.nodeName,";"),null;default:return A.push("??",ce.nodeName),null}},exit:function(ce,Me){Me&&Me.tag&&A.push("</",Me.tag,">")}})}function Af(E,A,V){var J;return et(A,null,{enter:function(ue,me){var ce=ue.cloneNode(!1);ce.ownerDocument=E,ce.parentNode=null,me===null?J=ce:me.appendChild(ce);var Me=ue.nodeType===y||V;return Me?ce:null}}),J}function ho(E,A,V){var J;return et(A,null,{enter:function(ue,me){var ce=new ue.constructor;for(var Me in ue)if(Object.prototype.hasOwnProperty.call(ue,Me)){var At=ue[Me];typeof At!="object"&&At!=ce[Me]&&(ce[Me]=At)}ue.childNodes&&(ce.childNodes=new te),ce.ownerDocument=E;var ni=V;switch(ce.nodeType){case p:var pi=ue.attributes,mi=ce.attributes=new Y,Si=pi.length;mi._ownerElement=ce;for(var Ne=0;Ne<Si;Ne++)ce.setAttributeNode(ho(E,pi.item(Ne),!0));break;case y:ni=!0}return me!==null?me.appendChild(ce):J=ce,ni?ce:null}}),J}function Il(E,A,V){E[A]=V}try{Object.defineProperty&&(Object.defineProperty(Q.prototype,"length",{get:function(){return re(this),this.$$length}}),Object.defineProperty(ve.prototype,"textContent",{get:function(){if(this.nodeType===p||this.nodeType===L){var E=[];return et(this,null,{enter:function(A){if(A.nodeType===p||A.nodeType===L)return!0;if(A.nodeType===I||A.nodeType===F)return null;E.push(A.nodeValue)}}),E.join("")}return this.nodeValue},set:function(E){switch(this.nodeType){case p:case L:for(;this.firstChild;)this.removeChild(this.firstChild);(E||String(E))&&this.appendChild(this.ownerDocument.createTextNode(E));break;default:this.data=E,this.value=E,this.nodeValue=E}}}),Il=function(E,A,V){E["$$"+A]=V})}catch{}return cn.DocumentType=Vn,cn.DOMException=W,cn.DOMImplementation=Pe,cn.Element=Ki,cn.Node=ve,cn.NodeList=te,cn.walkDOM=et,cn.XMLSerializer=Al,cn}var Na={},Qd={},sy;function ix(){return sy||(sy=1,(function(n){var e=La().freeze;n.XML_ENTITIES=e({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'}),n.HTML_ENTITIES=e({Aacute:"Á",aacute:"á",Abreve:"Ă",abreve:"ă",ac:"∾",acd:"∿",acE:"∾̳",Acirc:"Â",acirc:"â",acute:"´",Acy:"А",acy:"а",AElig:"Æ",aelig:"æ",af:"",Afr:"𝔄",afr:"𝔞",Agrave:"À",agrave:"à",alefsym:"ℵ",aleph:"ℵ",Alpha:"Α",alpha:"α",Amacr:"Ā",amacr:"ā",amalg:"⨿",AMP:"&",amp:"&",And:"⩓",and:"∧",andand:"⩕",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",Aogon:"Ą",aogon:"ą",Aopf:"𝔸",aopf:"𝕒",ap:"≈",apacir:"⩯",apE:"⩰",ape:"≊",apid:"≋",apos:"'",ApplyFunction:"",approx:"≈",approxeq:"≊",Aring:"Å",aring:"å",Ascr:"𝒜",ascr:"𝒶",Assign:"≔",ast:"*",asymp:"≈",asympeq:"≍",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",awconint:"∳",awint:"⨑",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",Backslash:"∖",Barv:"⫧",barvee:"⊽",Barwed:"⌆",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",Bcy:"Б",bcy:"б",bdquo:"„",becaus:"∵",Because:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",Bernoullis:"ℬ",Beta:"Β",beta:"β",beth:"ℶ",between:"≬",Bfr:"𝔅",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bNot:"⫭",bnot:"⌐",Bopf:"𝔹",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxDL:"╗",boxDl:"╖",boxdL:"╕",boxdl:"┐",boxDR:"╔",boxDr:"╓",boxdR:"╒",boxdr:"┌",boxH:"═",boxh:"─",boxHD:"╦",boxHd:"╤",boxhD:"╥",boxhd:"┬",boxHU:"╩",boxHu:"╧",boxhU:"╨",boxhu:"┴",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxUL:"╝",boxUl:"╜",boxuL:"╛",boxul:"┘",boxUR:"╚",boxUr:"╙",boxuR:"╘",boxur:"└",boxV:"║",boxv:"│",boxVH:"╬",boxVh:"╫",boxvH:"╪",boxvh:"┼",boxVL:"╣",boxVl:"╢",boxvL:"╡",boxvl:"┤",boxVR:"╠",boxVr:"╟",boxvR:"╞",boxvr:"├",bprime:"‵",Breve:"˘",breve:"˘",brvbar:"¦",Bscr:"ℬ",bscr:"𝒷",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",Bumpeq:"≎",bumpeq:"≏",Cacute:"Ć",cacute:"ć",Cap:"⋒",cap:"∩",capand:"⩄",capbrcup:"⩉",capcap:"⩋",capcup:"⩇",capdot:"⩀",CapitalDifferentialD:"ⅅ",caps:"∩︀",caret:"⁁",caron:"ˇ",Cayleys:"ℭ",ccaps:"⩍",Ccaron:"Č",ccaron:"č",Ccedil:"Ç",ccedil:"ç",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"⩌",ccupssm:"⩐",Cdot:"Ċ",cdot:"ċ",cedil:"¸",Cedilla:"¸",cemptyv:"⦲",cent:"¢",CenterDot:"·",centerdot:"·",Cfr:"ℭ",cfr:"𝔠",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",cir:"○",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",CircleDot:"⊙",circledR:"®",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cirE:"⧃",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",Colon:"∷",colon:":",Colone:"⩴",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",Congruent:"≡",Conint:"∯",conint:"∮",ContourIntegral:"∮",Copf:"ℂ",copf:"𝕔",coprod:"∐",Coproduct:"∐",COPY:"©",copy:"©",copysr:"℗",CounterClockwiseContourIntegral:"∳",crarr:"↵",Cross:"⨯",cross:"✗",Cscr:"𝒞",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",Cup:"⋓",cup:"∪",cupbrcap:"⩈",CupCap:"≍",cupcap:"⩆",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",Dagger:"‡",dagger:"†",daleth:"ℸ",Darr:"↡",dArr:"⇓",darr:"↓",dash:"‐",Dashv:"⫤",dashv:"⊣",dbkarow:"⤏",dblac:"˝",Dcaron:"Ď",dcaron:"ď",Dcy:"Д",dcy:"д",DD:"ⅅ",dd:"ⅆ",ddagger:"‡",ddarr:"⇊",DDotrahd:"⤑",ddotseq:"⩷",deg:"°",Del:"∇",Delta:"Δ",delta:"δ",demptyv:"⦱",dfisht:"⥿",Dfr:"𝔇",dfr:"𝔡",dHar:"⥥",dharl:"⇃",dharr:"⇂",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",diam:"⋄",Diamond:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",DifferentialD:"ⅆ",digamma:"ϝ",disin:"⋲",div:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",DJcy:"Ђ",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",Dopf:"𝔻",dopf:"𝕕",Dot:"¨",dot:"˙",DotDot:"⃜",doteq:"≐",doteqdot:"≑",DotEqual:"≐",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",Downarrow:"⇓",downarrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",Dscr:"𝒟",dscr:"𝒹",DScy:"Ѕ",dscy:"ѕ",dsol:"⧶",Dstrok:"Đ",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",DZcy:"Џ",dzcy:"џ",dzigrarr:"⟿",Eacute:"É",eacute:"é",easter:"⩮",Ecaron:"Ě",ecaron:"ě",ecir:"≖",Ecirc:"Ê",ecirc:"ê",ecolon:"≕",Ecy:"Э",ecy:"э",eDDot:"⩷",Edot:"Ė",eDot:"≑",edot:"ė",ee:"ⅇ",efDot:"≒",Efr:"𝔈",efr:"𝔢",eg:"⪚",Egrave:"È",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",Element:"∈",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",Emacr:"Ē",emacr:"ē",empty:"∅",emptyset:"∅",EmptySmallSquare:"◻",emptyv:"∅",EmptyVerySmallSquare:"▫",emsp:" ",emsp13:" ",emsp14:" ",ENG:"Ŋ",eng:"ŋ",ensp:" ",Eogon:"Ę",eogon:"ę",Eopf:"𝔼",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",Equal:"⩵",equals:"=",EqualTilde:"≂",equest:"≟",Equilibrium:"⇌",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erarr:"⥱",erDot:"≓",Escr:"ℰ",escr:"ℯ",esdot:"≐",Esim:"⩳",esim:"≂",Eta:"Η",eta:"η",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",euro:"€",excl:"!",exist:"∃",Exists:"∃",expectation:"ℰ",ExponentialE:"ⅇ",exponentiale:"ⅇ",fallingdotseq:"≒",Fcy:"Ф",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",Ffr:"𝔉",ffr:"𝔣",filig:"fi",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",Fopf:"𝔽",fopf:"𝕗",ForAll:"∀",forall:"∀",fork:"⋔",forkv:"⫙",Fouriertrf:"ℱ",fpartint:"⨍",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",Fscr:"ℱ",fscr:"𝒻",gacute:"ǵ",Gamma:"Γ",gamma:"γ",Gammad:"Ϝ",gammad:"ϝ",gap:"⪆",Gbreve:"Ğ",gbreve:"ğ",Gcedil:"Ģ",Gcirc:"Ĝ",gcirc:"ĝ",Gcy:"Г",gcy:"г",Gdot:"Ġ",gdot:"ġ",gE:"≧",ge:"≥",gEl:"⪌",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",Gfr:"𝔊",gfr:"𝔤",Gg:"⋙",gg:"≫",ggg:"⋙",gimel:"ℷ",GJcy:"Ѓ",gjcy:"ѓ",gl:"≷",gla:"⪥",glE:"⪒",glj:"⪤",gnap:"⪊",gnapprox:"⪊",gnE:"≩",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",Gopf:"𝔾",gopf:"𝕘",grave:"`",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",Gt:"≫",GT:">",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",Hacek:"ˇ",hairsp:" ",half:"½",hamilt:"ℋ",HARDcy:"Ъ",hardcy:"ъ",hArr:"⇔",harr:"↔",harrcir:"⥈",harrw:"↭",Hat:"^",hbar:"ℏ",Hcirc:"Ĥ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",Hfr:"ℌ",hfr:"𝔥",HilbertSpace:"ℋ",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",Hopf:"ℍ",hopf:"𝕙",horbar:"―",HorizontalLine:"─",Hscr:"ℋ",hscr:"𝒽",hslash:"ℏ",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"≏",hybull:"⁃",hyphen:"‐",Iacute:"Í",iacute:"í",ic:"",Icirc:"Î",icirc:"î",Icy:"И",icy:"и",Idot:"İ",IEcy:"Е",iecy:"е",iexcl:"¡",iff:"⇔",Ifr:"ℑ",ifr:"𝔦",Igrave:"Ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",IJlig:"IJ",ijlig:"ij",Im:"ℑ",Imacr:"Ī",imacr:"ī",image:"ℑ",ImaginaryI:"ⅈ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",imof:"⊷",imped:"Ƶ",Implies:"⇒",in:"∈",incare:"℅",infin:"∞",infintie:"⧝",inodot:"ı",Int:"∬",int:"∫",intcal:"⊺",integers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"⋂",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"",InvisibleTimes:"",IOcy:"Ё",iocy:"ё",Iogon:"Į",iogon:"į",Iopf:"𝕀",iopf:"𝕚",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"¿",Iscr:"ℐ",iscr:"𝒾",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"",Itilde:"Ĩ",itilde:"ĩ",Iukcy:"І",iukcy:"і",Iuml:"Ï",iuml:"ï",Jcirc:"Ĵ",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"𝔍",jfr:"𝔧",jmath:"ȷ",Jopf:"𝕁",jopf:"𝕛",Jscr:"𝒥",jscr:"𝒿",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"є",Kappa:"Κ",kappa:"κ",kappav:"ϰ",Kcedil:"Ķ",kcedil:"ķ",Kcy:"К",kcy:"к",Kfr:"𝔎",kfr:"𝔨",kgreen:"ĸ",KHcy:"Х",khcy:"х",KJcy:"Ќ",kjcy:"ќ",Kopf:"𝕂",kopf:"𝕜",Kscr:"𝒦",kscr:"𝓀",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",Lambda:"Λ",lambda:"λ",Lang:"⟪",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"ℒ",laquo:"«",Larr:"↞",lArr:"⇐",larr:"←",larrb:"⇤",larrbfs:"⤟",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",lAtail:"⤛",latail:"⤙",late:"⪭",lates:"⪭︀",lBarr:"⤎",lbarr:"⤌",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ļ",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",lE:"≦",le:"≤",LeftAngleBracket:"⟨",LeftArrow:"←",Leftarrow:"⇐",leftarrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",leftthreetimes:"⋋",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",lEg:"⪋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"𝔏",lfr:"𝔩",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",LJcy:"Љ",ljcy:"љ",Ll:"⋘",ll:"≪",llarr:"⇇",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"◺",Lmidot:"Ŀ",lmidot:"ŀ",lmoust:"⎰",lmoustache:"⎰",lnap:"⪉",lnapprox:"⪉",lnE:"≨",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftarrow:"⟵",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longleftrightarrow:"⟷",longmapsto:"⟼",LongRightArrow:"⟶",Longrightarrow:"⟹",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"𝕃",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"",lrtri:"⊿",lsaquo:"‹",Lscr:"ℒ",lscr:"𝓁",Lsh:"↰",lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Ł",lstrok:"ł",Lt:"≪",LT:"<",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltri:"◃",ltrie:"⊴",ltrif:"◂",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"¯",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",Mcy:"М",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",mfr:"𝔪",mho:"℧",micro:"µ",mid:"∣",midast:"*",midcir:"⫰",middot:"·",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"𝕄",mopf:"𝕞",mp:"∓",Mscr:"ℳ",mscr:"𝓂",mstpos:"∾",Mu:"Μ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"♮",natural:"♮",naturals:"ℕ",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",Ncy:"Н",ncy:"н",ndash:"–",ne:"≠",nearhk:"⤤",neArr:"⇗",nearr:"↗",nearrow:"↗",nedot:"≐̸",NegativeMediumSpace:"",NegativeThickSpace:"",NegativeThinSpace:"",NegativeVeryThinSpace:"",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:`
|
|
68
|
+
`,nexist:"∄",nexists:"∄",Nfr:"𝔑",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",nGg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"њ",nlArr:"⇍",nlarr:"↚",nldr:"‥",nlE:"≦̸",nle:"≰",nLeftarrow:"⇍",nleftarrow:"↚",nLeftrightarrow:"⇎",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"",NonBreakingSpace:" ",Nopf:"ℕ",nopf:"𝕟",Not:"⫬",not:"¬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",NotLeftTriangle:"⋪",NotLeftTriangleBar:"⧏̸",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangle:"⋫",NotRightTriangleBar:"⧐̸",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"⇏",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"↝̸",nRightarrow:"⇏",nrightarrow:"↛",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",Nscr:"𝒩",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"Ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",Nu:"Ν",nu:"ν",num:"#",numero:"№",numsp:" ",nvap:"≍⃒",nVDash:"⊯",nVdash:"⊮",nvDash:"⊭",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwArr:"⇖",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",Oacute:"Ó",oacute:"ó",oast:"⊛",ocir:"⊚",Ocirc:"Ô",ocirc:"ô",Ocy:"О",ocy:"о",odash:"⊝",Odblac:"Ő",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",OElig:"Œ",oelig:"œ",ofcir:"⦿",Ofr:"𝔒",ofr:"𝔬",ogon:"˛",Ograve:"Ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"Ō",omacr:"ō",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"𝕆",oopf:"𝕠",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",Or:"⩔",or:"∨",orarr:"↻",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oS:"Ⓢ",Oscr:"𝒪",oscr:"ℴ",Oslash:"Ø",oslash:"ø",osol:"⊘",Otilde:"Õ",otilde:"õ",Otimes:"⨷",otimes:"⊗",otimesas:"⨶",Ouml:"Ö",ouml:"ö",ovbar:"⌽",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",par:"∥",para:"¶",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"𝔓",pfr:"𝔭",Phi:"Φ",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",Pi:"Π",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",Poincareplane:"ℌ",pointint:"⨕",Popf:"ℙ",popf:"𝕡",pound:"£",Pr:"⪻",pr:"≺",prap:"⪷",prcue:"≼",prE:"⪳",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",Prime:"″",prime:"′",primes:"ℙ",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"∏",Product:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",Proportion:"∷",Proportional:"∝",propto:"∝",prsim:"≾",prurel:"⊰",Pscr:"𝒫",pscr:"𝓅",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"𝔔",qfr:"𝔮",qint:"⨌",Qopf:"ℚ",qopf:"𝕢",qprime:"⁗",Qscr:"𝒬",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",QUOT:'"',quot:'"',rAarr:"⇛",race:"∽̱",Racute:"Ŕ",racute:"ŕ",radic:"√",raemptyv:"⦳",Rang:"⟫",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",Rarr:"↠",rArr:"⇒",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"↝",rAtail:"⤜",ratail:"⤚",ratio:"∶",rationals:"ℚ",RBarr:"⤐",rBarr:"⤏",rbarr:"⤍",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",rceil:"⌉",rcub:"}",Rcy:"Р",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",Re:"ℜ",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",rect:"▭",REG:"®",reg:"®",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",Rfr:"ℜ",rfr:"𝔯",rHar:"⥤",rhard:"⇁",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"ρ",rhov:"ϱ",RightAngleBracket:"⟩",RightArrow:"→",Rightarrow:"⇒",rightarrow:"→",RightArrowBar:"⇥",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",rightthreetimes:"⋌",RightTriangle:"⊳",RightTriangleBar:"⧐",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"",rmoust:"⎱",rmoustache:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",Ropf:"ℝ",ropf:"𝕣",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",Rscr:"ℛ",rscr:"𝓇",Rsh:"↱",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"℞",Sacute:"Ś",sacute:"ś",sbquo:"‚",Sc:"⪼",sc:"≻",scap:"⪸",Scaron:"Š",scaron:"š",sccue:"≽",scE:"⪴",sce:"⪰",Scedil:"Ş",scedil:"ş",Scirc:"Ŝ",scirc:"ŝ",scnap:"⪺",scnE:"⪶",scnsim:"⋩",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"с",sdot:"⋅",sdotb:"⊡",sdote:"⩦",searhk:"⤥",seArr:"⇘",searr:"↘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"𝔖",sfr:"𝔰",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"←",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"ь",sol:"/",solb:"⧄",solbar:"⌿",Sopf:"𝕊",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",squ:"□",Square:"□",square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"▪",squf:"▪",srarr:"→",Sscr:"𝒮",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",Sub:"⋐",sub:"⊂",subdot:"⪽",subE:"⫅",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",Subset:"⋐",subset:"⊂",subseteq:"⊆",subseteqq:"⫅",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",SuchThat:"∋",Sum:"∑",sum:"∑",sung:"♪",Sup:"⋑",sup:"⊃",sup1:"¹",sup2:"²",sup3:"³",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"⫄",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",Supset:"⋑",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swarhk:"⤦",swArr:"⇙",swarr:"↙",swarrow:"↙",swnwar:"⤪",szlig:"ß",Tab:" ",target:"⌖",Tau:"Τ",tau:"τ",tbrk:"⎴",Tcaron:"Ť",tcaron:"ť",Tcedil:"Ţ",tcedil:"ţ",Tcy:"Т",tcy:"т",tdot:"⃛",telrec:"⌕",Tfr:"𝔗",tfr:"𝔱",there4:"∴",Therefore:"∴",therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",ThickSpace:" ",thinsp:" ",ThinSpace:" ",thkap:"≈",thksim:"∼",THORN:"Þ",thorn:"þ",Tilde:"∼",tilde:"˜",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",times:"×",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"∭",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",Topf:"𝕋",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",TRADE:"™",trade:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",Tscr:"𝒯",tscr:"𝓉",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"ћ",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"Ú",uacute:"ú",Uarr:"↟",uArr:"⇑",uarr:"↑",Uarrocir:"⥉",Ubrcy:"Ў",ubrcy:"ў",Ubreve:"Ŭ",ubreve:"ŭ",Ucirc:"Û",ucirc:"û",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Ű",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"𝔘",ufr:"𝔲",Ugrave:"Ù",ugrave:"ù",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",Umacr:"Ū",umacr:"ū",uml:"¨",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"𝕌",uopf:"𝕦",UpArrow:"↑",Uparrow:"⇑",uparrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",Updownarrow:"⇕",updownarrow:"↕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"ϒ",upsi:"υ",upsih:"ϒ",Upsilon:"Υ",upsilon:"υ",UpTee:"⊥",UpTeeArrow:"↥",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",Uring:"Ů",uring:"ů",urtri:"◹",Uscr:"𝒰",uscr:"𝓊",utdot:"⋰",Utilde:"Ũ",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",Uuml:"Ü",uuml:"ü",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",vArr:"⇕",varr:"↕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",Vbar:"⫫",vBar:"⫨",vBarv:"⫩",Vcy:"В",vcy:"в",VDash:"⊫",Vdash:"⊩",vDash:"⊨",vdash:"⊢",Vdashl:"⫦",Vee:"⋁",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"⋮",Verbar:"‖",verbar:"|",Vert:"‖",vert:"|",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"𝕍",vopf:"𝕧",vprop:"∝",vrtri:"⊳",Vscr:"𝒱",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Ŵ",wcirc:"ŵ",wedbar:"⩟",Wedge:"⋀",wedge:"∧",wedgeq:"≙",weierp:"℘",Wfr:"𝔚",wfr:"𝔴",Wopf:"𝕎",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",Wscr:"𝒲",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",Xfr:"𝔛",xfr:"𝔵",xhArr:"⟺",xharr:"⟷",Xi:"Ξ",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"⋻",xodot:"⨀",Xopf:"𝕏",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",Xscr:"𝒳",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",Yacute:"Ý",yacute:"ý",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"¥",Yfr:"𝔜",yfr:"𝔶",YIcy:"Ї",yicy:"ї",Yopf:"𝕐",yopf:"𝕪",Yscr:"𝒴",yscr:"𝓎",YUcy:"Ю",yucy:"ю",Yuml:"Ÿ",yuml:"ÿ",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"",Zeta:"Ζ",zeta:"ζ",Zfr:"ℨ",zfr:"𝔷",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",Zopf:"ℤ",zopf:"𝕫",Zscr:"𝒵",zscr:"𝓏",zwj:"",zwnj:""}),n.entityMap=n.HTML_ENTITIES})(Qd)),Qd}var Rc={},ry;function nx(){if(ry)return Rc;ry=1;var n=La().NAMESPACE,e=La().tagNamePattern,t=0,i=1,s=2,r=3,a=4,o=5,c=6,l=7;function u(C,N){this.message=C,this.locator=N,Error.captureStackTrace&&Error.captureStackTrace(this,u)}u.prototype=new Error,u.prototype.name=u.name;function h(){}h.prototype={parse:function(C,N,x){var k=this.domBuilder;k.startDocument(),I(N,N={}),p(C,N,x,k,this.errorHandler),k.endDocument()}};function p(C,N,x,k,j){function G(Ge){if(Ge>65535){Ge-=65536;var Ae=55296+(Ge>>10),Gr=56320+(Ge&1023);return String.fromCharCode(Ae,Gr)}else return String.fromCharCode(Ge)}function X(Ge){var Ae=Ge.slice(1,-1);return Object.hasOwnProperty.call(x,Ae)?x[Ae]:Ae.charAt(0)==="#"?G(parseInt(Ae.substr(1).replace("x","0x"))):(j.error("entity not found:"+Ge),Ge)}function z(Ge){if(Ge>Te){var Ae=C.substring(Te,Ge).replace(/&#?\w+;/g,X);Y&&W(Te),k.characters(Ae,0,Ge-Te),Te=Ge}}function W(Ge,Ae){for(;Ge>=Q&&(Ae=re.exec(C));)te=Ae.index,Q=te+Ae[0].length,Y.lineNumber++;Y.columnNumber=Ge-te+1}for(var te=0,Q=0,re=/.*(?:\r\n?|\n)|.*$/g,Y=k.locator,ie=[{currentNSMap:N}],ge={},Te=0;;){try{var be=C.indexOf("<",Te);if(be<0){if(!C.substr(Te).match(/^\s*$/)){var we=k.doc,Pe=we.createTextNode(C.substr(Te));we.appendChild(Pe),k.currentElement=Pe}return}switch(be>Te&&z(be),C.charAt(be+1)){case"/":var kt=C.indexOf(">",be+3),ve=C.substring(be+2,kt).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),qe=ie.pop();kt<0?(ve=C.substring(be+2).replace(/[\s<].*/,""),j.error("end tag name: "+ve+" is not complete:"+qe.tagName),kt=be+1+ve.length):ve.match(/\s</)?(ve=ve.replace(/[\s<].*/,""),j.error("end tag name: "+ve+" maybe not complete"),kt=be+1+ve.length):/[ \t\n\r]/.test(ve)&&e.test(ve.split(/[ \t\n\r]/)[0])&&j.error('end tag name is followed by whitespace and trailing content: "'+ve+'"');var bt=qe.localNSMap,et=qe.tagName==ve,fi=et||qe.tagName&&qe.tagName.toLowerCase()==ve.toLowerCase();if(fi){if(k.endElement(qe.uri,qe.localName,ve),bt)for(var Bn in bt)Object.prototype.hasOwnProperty.call(bt,Bn)&&k.endPrefixMapping(Bn);et||j.fatalError("end tag name: "+ve+" is not match the current start tagName:"+qe.tagName)}else ie.push(qe);kt++;break;case"?":Y&&W(be),kt=w(C,be,k);break;case"!":Y&&W(be),kt=F(C,be,k,j);break;default:Y&&W(be);var wt=new P,bn=ie[ie.length-1].currentNSMap,kt=_(C,be,wt,bn,X,j),zr=wt.length;if(!wt.closed&&D(C,kt,wt.tagName,ge)&&(wt.closed=!0,x.nbsp||j.warning("unclosed xml attribute")),Y&&zr){for(var ro=y(Y,{}),ii=0;ii<zr;ii++){var mt=wt[ii];W(mt.offset),mt.locator=y(Y,{})}k.locator=ro,b(wt,k,bn)&&ie.push(wt),k.locator=Y}else b(wt,k,bn)&&ie.push(wt);n.isHTML(wt.uri)&&!wt.closed?kt=S(C,kt,wt.tagName,X,k):kt++}}catch(Ge){if(Ge instanceof u)throw Ge;j.error("element parse error: "+Ge),kt=-1}kt>Te?Te=kt:z(Math.max(be,Te)+1)}}function y(C,N){return N.lineNumber=C.lineNumber,N.columnNumber=C.columnNumber,N}function _(C,N,x,k,j,G){function X(Y,ie,ge){x.attributeNames.hasOwnProperty(Y)&&G.fatalError("Attribute "+Y+" redefined"),x.addValue(Y,ie.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,j),ge)}for(var z,W,te=++N,Q=t;;){var re=C.charAt(te);if(Q===t&&re==="<")throw new Error("unexpected < in tag name: "+C.slice(N,te));switch(re){case"=":if(Q===i)z=C.slice(N,te),Q=r;else if(Q===s)Q=r;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(Q===r||Q===i)if(Q===i&&(G.warning('attribute value must after "="'),z=C.slice(N,te)),N=te+1,te=C.indexOf(re,N),te>0)W=C.slice(N,te),X(z,W,N-1),Q=o;else throw new Error("attribute value no end '"+re+"' match");else if(Q==a)W=C.slice(N,te),X(z,W,N),G.warning('attribute "'+z+'" missed start quot('+re+")!!"),N=te+1,Q=o;else throw new Error('attribute value must after "="');break;case"/":switch(Q){case t:x.setTagName(C.slice(N,te));case o:case c:case l:Q=l,x.closed=!0;case a:case i:break;case s:x.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return G.error("unexpected end of input"),Q==t&&x.setTagName(C.slice(N,te)),te;case">":switch(Q){case t:x.setTagName(C.slice(N,te));case o:case c:case l:break;case a:case i:W=C.slice(N,te),W.slice(-1)==="/"&&(x.closed=!0,W=W.slice(0,-1));case s:Q===s&&(W=z),Q==a?(G.warning('attribute "'+W+'" missed quot(")!'),X(z,W,N)):((!n.isHTML(k[""])||!W.match(/^(?:disabled|checked|selected)$/i))&&G.warning('attribute "'+W+'" missed value!! "'+W+'" instead!!'),X(W,W,N));break;case r:throw new Error("attribute value missed!!")}return te;case"":re=" ";default:if(re<=" ")switch(Q){case t:x.setTagName(C.slice(N,te)),Q=c;break;case i:z=C.slice(N,te),Q=s;break;case a:var W=C.slice(N,te);G.warning('attribute "'+W+'" missed quot(")!!'),X(z,W,N);case o:Q=c;break}else switch(Q){case s:x.tagName,(!n.isHTML(k[""])||!z.match(/^(?:disabled|checked|selected)$/i))&&G.warning('attribute "'+z+'" missed value!! "'+z+'" instead2!!'),X(z,z,N),N=te,Q=i;break;case o:G.warning('attribute space is required"'+z+'"!!');case c:Q=i,N=te;break;case r:Q=a,N=te;break;case l:throw new Error("elements closed character '/' and '>' must be connected to")}}te++}}function b(C,N,x){for(var k=C.tagName,j=null,re=C.length;re--;){var G=C[re],X=G.qName,z=G.value,Y=X.indexOf(":");if(Y>0)var W=G.prefix=X.slice(0,Y),te=X.slice(Y+1),Q=W==="xmlns"&&te;else te=X,W=null,Q=X==="xmlns"&&"";G.localName=te,Q!==!1&&(j==null&&(j={},x=Object.create(x)),x[Q]=j[Q]=z,G.uri=n.XMLNS,N.startPrefixMapping(Q,z))}for(var re=C.length;re--;){G=C[re];var W=G.prefix;W&&(W==="xml"&&(G.uri=n.XML),W!=="xmlns"&&(G.uri=x[W||""]))}var Y=k.indexOf(":");Y>0?(W=C.prefix=k.slice(0,Y),te=C.localName=k.slice(Y+1)):(W=null,te=C.localName=k);var ie=C.uri=x[W||""];if(N.startElement(ie,te,k,C),C.closed){if(N.endElement(ie,te,k),j)for(W in j)Object.prototype.hasOwnProperty.call(j,W)&&N.endPrefixMapping(W)}else return C.currentNSMap=x,C.localNSMap=j,!0}function S(C,N,x,k,j){if(/^(?:script|textarea)$/i.test(x)){var G=C.indexOf("</"+x+">",N),X=C.substring(N+1,G);if(/[&<]/.test(X))return/^script$/i.test(x)?(j.characters(X,0,X.length),G):(X=X.replace(/&#?\w+;/g,k),j.characters(X,0,X.length),G)}return N+1}function D(C,N,x,k){var j=k[x];return j==null&&(j=C.lastIndexOf("</"+x+">"),j<N&&(j=C.lastIndexOf("</"+x)),k[x]=j),j<N}function I(C,N){for(var x in C)Object.prototype.hasOwnProperty.call(C,x)&&(N[x]=C[x])}function F(C,N,x,k){var j=C.charAt(N+2);switch(j){case"-":if(C.charAt(N+3)==="-"){var G=C.indexOf("-->",N+4);return G>N?(x.comment(C,N+4,G-N-4),G+3):(k.error("Unclosed comment"),-1)}else return-1;default:if(C.substr(N+3,6)=="CDATA["){var G=C.indexOf("]]>",N+9);return x.startCDATA(),x.characters(C,N+9,G-N-9),x.endCDATA(),G+3}var X=L(C,N),z=X.length;if(z>1&&/!doctype/i.test(X[0][0])){var W=X[1][0],te=!1,Q=!1;z>3&&(/^public$/i.test(X[2][0])?(te=X[3][0],Q=z>4&&X[4][0]):/^system$/i.test(X[2][0])&&(Q=X[3][0]));var re=X[z-1];return x.startDTD(W,te,Q),x.endDTD(),re.index+re[0].length}}return-1}function w(C,N,x){var k=C.indexOf("?>",N);if(k){var j=C.substring(N,k).match(/^<\?(\S*)\s*([\s\S]*?)$/);return j?(j[0].length,x.processingInstruction(j[1],j[2]),k+2):-1}return-1}function P(){this.attributeNames={}}P.prototype={setTagName:function(C){if(!e.test(C))throw new Error("invalid tagName:"+C);this.tagName=C},addValue:function(C,N,x){if(!e.test(C))throw new Error("invalid attribute:"+C);this.attributeNames[C]=this.length,this[this.length++]={qName:C,value:N,offset:x}},length:0,getLocalName:function(C){return this[C].localName},getLocator:function(C){return this[C].locator},getQName:function(C){return this[C].qName},getURI:function(C){return this[C].uri},getValue:function(C){return this[C].value}};function L(C,N){var x,k=[],j=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(j.lastIndex=N,j.exec(C);x=j.exec(C);)if(k.push(x),x[1])return k}return Rc.XMLReader=h,Rc.ParseError=u,Rc}var ay;function sx(){if(ay)return Na;ay=1;var n=La(),e=ny(),t=ix(),i=nx(),s=e.DOMImplementation,r=n.NAMESPACE,a=i.ParseError,o=i.XMLReader;function c(S){return S.replace(/\r[\n\u0085]/g,`
|
|
69
|
+
`).replace(/[\r\u0085\u2028]/g,`
|
|
70
|
+
`)}function l(S){this.options=S||{locator:{}}}l.prototype.parseFromString=function(S,D){var I=this.options,F=new o,w=I.domBuilder||new h,P=I.errorHandler,L=I.locator,C=I.xmlns||{},N=/\/x?html?$/.test(D),x=N?t.HTML_ENTITIES:t.XML_ENTITIES;L&&w.setDocumentLocator(L),F.errorHandler=u(P,w,L),F.domBuilder=I.domBuilder||w,N&&(C[""]=r.HTML),C.xml=C.xml||r.XML;var k=I.normalizeLineEndings||c;return S&&typeof S=="string"?F.parse(k(S),C,x):F.errorHandler.error("invalid doc source"),w.doc};function u(S,D,I){if(!S){if(D instanceof h)return D;S=D}var F={},w=S instanceof Function;I=I||{};function P(L){var C=S[L];!C&&w&&(C=S.length==2?function(N){S(L,N)}:S),F[L]=C&&function(N){C("[xmldom "+L+"] "+N+y(I))}||function(){}}return P("warning"),P("error"),P("fatalError"),F}function h(){this.cdata=!1}function p(S,D){D.lineNumber=S.lineNumber,D.columnNumber=S.columnNumber}h.prototype={startDocument:function(){this.doc=new s().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(S,D,I,F){var w=this.doc,P=w.createElementNS(S,I||D),L=F.length;b(this,P),this.currentElement=P,this.locator&&p(this.locator,P);for(var C=0;C<L;C++){var S=F.getURI(C),N=F.getValue(C),I=F.getQName(C),x=w.createAttributeNS(S,I);this.locator&&p(F.getLocator(C),x),x.value=x.nodeValue=N,P.setAttributeNode(x)}},endElement:function(S,D,I){var F=this.currentElement;F.tagName,this.currentElement=F.parentNode},startPrefixMapping:function(S,D){},endPrefixMapping:function(S){},processingInstruction:function(S,D){var I=this.doc.createProcessingInstruction(S,D);this.locator&&p(this.locator,I),b(this,I)},ignorableWhitespace:function(S,D,I){},characters:function(S,D,I){if(S=_.apply(this,arguments),S){if(this.cdata)var F=this.doc.createCDATASection(S);else var F=this.doc.createTextNode(S);this.currentElement?this.currentElement.appendChild(F):/^\s*$/.test(S)&&this.doc.appendChild(F),this.locator&&p(this.locator,F)}},skippedEntity:function(S){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(S){(this.locator=S)&&(S.lineNumber=0)},comment:function(S,D,I){S=_.apply(this,arguments);var F=this.doc.createComment(S);this.locator&&p(this.locator,F),b(this,F)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(S,D,I){var F=this.doc.implementation;if(F&&F.createDocumentType){var w=F.createDocumentType(S,D,I);this.locator&&p(this.locator,w),b(this,w),this.doc.doctype=w}},warning:function(S){console.warn("[xmldom warning] "+S,y(this.locator))},error:function(S){console.error("[xmldom error] "+S,y(this.locator))},fatalError:function(S){throw new a(S,this.locator)}};function y(S){if(S)return`
|
|
71
|
+
@`+(S.systemId||"")+"#[line:"+S.lineNumber+",col:"+S.columnNumber+"]"}function _(S,D,I){return typeof S=="string"?S.substr(D,I):S.length>=D+I||D?new java.lang.String(S,D,I)+"":S}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(S){h.prototype[S]=function(){return null}});function b(S,D){S.currentElement?S.currentElement.appendChild(D):S.doc.appendChild(D)}return Na.__DOMHandler=h,Na.normalizeLineEndings=c,Na.DOMParser=l,Na}var oy;function rx(){if(oy)return Ma;oy=1;var n=ny();return Ma.DOMImplementation=n.DOMImplementation,Ma.XMLSerializer=n.XMLSerializer,Ma.DOMParser=sx().DOMParser,Ma}var ax=rx();/*! @name mpd-parser @version 1.4.0 @license Apache-2.0 */const cy=n=>!!n&&typeof n=="object",Rt=(...n)=>n.reduce((e,t)=>(typeof t!="object"||Object.keys(t).forEach(i=>{Array.isArray(e[i])&&Array.isArray(t[i])?e[i]=e[i].concat(t[i]):cy(e[i])&&cy(t[i])?e[i]=Rt(e[i],t[i]):e[i]=t[i]}),e),{}),ly=n=>Object.keys(n).map(e=>n[e]),ox=(n,e)=>{const t=[];for(let i=n;i<e;i++)t.push(i);return t},yr=n=>n.reduce((e,t)=>e.concat(t),[]),uy=n=>{if(!n.length)return[];const e=[];for(let t=0;t<n.length;t++)e.push(n[t]);return e},cx=(n,e)=>n.reduce((t,i,s)=>(i[e]&&t.push(s),t),[]),lx=(n,e)=>ly(n.reduce((t,i)=>(i.forEach(s=>{t[e(s)]=s}),t),{}));var vr={INVALID_NUMBER_OF_PERIOD:"INVALID_NUMBER_OF_PERIOD",DASH_EMPTY_MANIFEST:"DASH_EMPTY_MANIFEST",DASH_INVALID_XML:"DASH_INVALID_XML",NO_BASE_URL:"NO_BASE_URL",SEGMENT_TIME_UNSPECIFIED:"SEGMENT_TIME_UNSPECIFIED",UNSUPPORTED_UTC_TIMING_SCHEME:"UNSUPPORTED_UTC_TIMING_SCHEME"};const Fa=({baseUrl:n="",source:e="",range:t="",indexRange:i=""})=>{const s={uri:e,resolvedUri:Ic(n||"",e)};if(t||i){const a=(t||i).split("-");let o=B.BigInt?B.BigInt(a[0]):parseInt(a[0],10),c=B.BigInt?B.BigInt(a[1]):parseInt(a[1],10);o<Number.MAX_SAFE_INTEGER&&typeof o=="bigint"&&(o=Number(o)),c<Number.MAX_SAFE_INTEGER&&typeof c=="bigint"&&(c=Number(c));let l;typeof c=="bigint"||typeof o=="bigint"?l=B.BigInt(c)-B.BigInt(o)+B.BigInt(1):l=c-o+1,typeof l=="bigint"&&l<Number.MAX_SAFE_INTEGER&&(l=Number(l)),s.byterange={length:l,offset:o}}return s},ux=n=>{let e;return typeof n.offset=="bigint"||typeof n.length=="bigint"?e=B.BigInt(n.offset)+B.BigInt(n.length)-B.BigInt(1):e=n.offset+n.length-1,`${n.offset}-${e}`},dy=n=>(n&&typeof n!="number"&&(n=parseInt(n,10)),isNaN(n)?null:n),dx={static(n){const{duration:e,timescale:t=1,sourceDuration:i,periodDuration:s}=n,r=dy(n.endNumber),a=e/t;return typeof r=="number"?{start:0,end:r}:typeof s=="number"?{start:0,end:s/a}:{start:0,end:i/a}},dynamic(n){const{NOW:e,clientOffset:t,availabilityStartTime:i,timescale:s=1,duration:r,periodStart:a=0,minimumUpdatePeriod:o=0,timeShiftBufferDepth:c=1/0}=n,l=dy(n.endNumber),u=(e+t)/1e3,h=i+a,y=u+o-h,_=Math.ceil(y*s/r),b=Math.floor((u-h-c)*s/r),S=Math.floor((u-h)*s/r);return{start:Math.max(0,b),end:typeof l=="number"?l:Math.min(_,S)}}},hx=n=>e=>{const{duration:t,timescale:i=1,periodStart:s,startNumber:r=1}=n;return{number:r+e,duration:t/i,timeline:s,time:e*t}},Jd=n=>{const{type:e,duration:t,timescale:i=1,periodDuration:s,sourceDuration:r}=n,{start:a,end:o}=dx[e](n),c=ox(a,o).map(hx(n));if(e==="static"){const l=c.length-1,u=typeof s=="number"?s:r;c[l].duration=u-t/i*l}return c},hy=n=>{const{baseUrl:e,initialization:t={},sourceDuration:i,indexRange:s="",periodStart:r,presentationTime:a,number:o=0,duration:c}=n;if(!e)throw new Error(vr.NO_BASE_URL);const l=Fa({baseUrl:e,source:t.sourceURL,range:t.range}),u=Fa({baseUrl:e,source:e,indexRange:s});if(u.map=l,c){const h=Jd(n);h.length&&(u.duration=h[0].duration,u.timeline=h[0].timeline)}else i&&(u.duration=i,u.timeline=r);return u.presentationTime=a||r,u.number=o,[u]},Zd=(n,e,t)=>{const i=n.sidx.map?n.sidx.map:null,s=n.sidx.duration,r=n.timeline||0,a=n.sidx.byterange,o=a.offset+a.length,c=e.timescale,l=e.references.filter(S=>S.referenceType!==1),u=[],h=n.endList?"static":"dynamic",p=n.sidx.timeline;let y=p,_=n.mediaSequence||0,b;typeof e.firstOffset=="bigint"?b=B.BigInt(o)+e.firstOffset:b=o+e.firstOffset;for(let S=0;S<l.length;S++){const D=e.references[S],I=D.referencedSize,F=D.subsegmentDuration;let w;typeof b=="bigint"?w=b+B.BigInt(I)-B.BigInt(1):w=b+I-1;const P=`${b}-${w}`,C=hy({baseUrl:t,timescale:c,timeline:r,periodStart:p,presentationTime:y,number:_,duration:F,sourceDuration:s,indexRange:P,type:h})[0];i&&(C.map=i),u.push(C),typeof b=="bigint"?b+=B.BigInt(I):b+=I,y+=F/c,_++}return n.segments=u,n},fx=["AUDIO","SUBTITLES"],px=1/60,fy=n=>lx(n,({timeline:e})=>e).sort((e,t)=>e.timeline>t.timeline?1:-1),mx=(n,e)=>{for(let t=0;t<n.length;t++)if(n[t].attributes.NAME===e)return n[t];return null},py=n=>{let e=[];return tx(n,fx,(t,i,s,r)=>{e=e.concat(t.playlists||[])}),e},my=({playlist:n,mediaSequence:e})=>{n.mediaSequence=e,n.segments.forEach((t,i)=>{t.number=n.mediaSequence+i})},gx=({oldPlaylists:n,newPlaylists:e,timelineStarts:t})=>{e.forEach(i=>{i.discontinuitySequence=t.findIndex(function({timeline:c}){return c===i.timeline});const s=mx(n,i.attributes.NAME);if(!s||i.sidx)return;const r=i.segments[0],a=s.segments.findIndex(function(c){return Math.abs(c.presentationTime-r.presentationTime)<px});if(a===-1){my({playlist:i,mediaSequence:s.mediaSequence+s.segments.length}),i.segments[0].discontinuity=!0,i.discontinuityStarts.unshift(0),(!s.segments.length&&i.timeline>s.timeline||s.segments.length&&i.timeline>s.segments[s.segments.length-1].timeline)&&i.discontinuitySequence--;return}s.segments[a].discontinuity&&!r.discontinuity&&(r.discontinuity=!0,i.discontinuityStarts.unshift(0),i.discontinuitySequence--),my({playlist:i,mediaSequence:s.segments[a].number})})},yx=({oldManifest:n,newManifest:e})=>{const t=n.playlists.concat(py(n)),i=e.playlists.concat(py(e));return e.timelineStarts=fy([n.timelineStarts,e.timelineStarts]),gx({oldPlaylists:t,newPlaylists:i,timelineStarts:e.timelineStarts}),e},Oc=n=>n&&n.uri+"-"+ux(n.byterange),eh=n=>{const e=n.reduce(function(i,s){return i[s.attributes.baseUrl]||(i[s.attributes.baseUrl]=[]),i[s.attributes.baseUrl].push(s),i},{});let t=[];return Object.values(e).forEach(i=>{const s=ly(i.reduce((r,a)=>{const o=a.attributes.id+(a.attributes.lang||"");return r[o]?(a.segments&&(a.segments[0]&&(a.segments[0].discontinuity=!0),r[o].segments.push(...a.segments)),a.attributes.contentProtection&&(r[o].attributes.contentProtection=a.attributes.contentProtection)):(r[o]=a,r[o].attributes.timelineStarts=[]),r[o].attributes.timelineStarts.push({start:a.attributes.periodStart,timeline:a.attributes.periodStart}),r},{}));t=t.concat(s)}),t.map(i=>(i.discontinuityStarts=cx(i.segments||[],"discontinuity"),i))},th=(n,e)=>{const t=Oc(n.sidx),i=t&&e[t]&&e[t].sidx;return i&&Zd(n,i,n.sidx.resolvedUri),n},vx=(n,e={})=>{if(!Object.keys(e).length)return n;for(const t in n)n[t]=th(n[t],e);return n},bx=({attributes:n,segments:e,sidx:t,mediaSequence:i,discontinuitySequence:s,discontinuityStarts:r},a)=>{const o={attributes:{NAME:n.id,BANDWIDTH:n.bandwidth,CODECS:n.codecs,"PROGRAM-ID":1},uri:"",endList:n.type==="static",timeline:n.periodStart,resolvedUri:n.baseUrl||"",targetDuration:n.duration,discontinuitySequence:s,discontinuityStarts:r,timelineStarts:n.timelineStarts,mediaSequence:i,segments:e};return n.contentProtection&&(o.contentProtection=n.contentProtection),n.serviceLocation&&(o.attributes.serviceLocation=n.serviceLocation),t&&(o.sidx=t),a&&(o.attributes.AUDIO="audio",o.attributes.SUBTITLES="subs"),o},Tx=({attributes:n,segments:e,mediaSequence:t,discontinuityStarts:i,discontinuitySequence:s})=>{typeof e>"u"&&(e=[{uri:n.baseUrl,timeline:n.periodStart,resolvedUri:n.baseUrl||"",duration:n.sourceDuration,number:0}],n.duration=n.sourceDuration);const r={NAME:n.id,BANDWIDTH:n.bandwidth,"PROGRAM-ID":1};n.codecs&&(r.CODECS=n.codecs);const a={attributes:r,uri:"",endList:n.type==="static",timeline:n.periodStart,resolvedUri:n.baseUrl||"",targetDuration:n.duration,timelineStarts:n.timelineStarts,discontinuityStarts:i,discontinuitySequence:s,mediaSequence:t,segments:e};return n.serviceLocation&&(a.attributes.serviceLocation=n.serviceLocation),a},_x=(n,e={},t=!1)=>{let i;const s=n.reduce((r,a)=>{const o=a.attributes.role&&a.attributes.role.value||"",c=a.attributes.lang||"";let l=a.attributes.label||"main";if(c&&!a.attributes.label){const h=o?` (${o})`:"";l=`${a.attributes.lang}${h}`}r[l]||(r[l]={language:c,autoselect:!0,default:o==="main",playlists:[],uri:""});const u=th(bx(a,t),e);return r[l].playlists.push(u),typeof i>"u"&&o==="main"&&(i=a,i.default=!0),r},{});if(!i){const r=Object.keys(s)[0];s[r].default=!0}return s},Sx=(n,e={})=>n.reduce((t,i)=>{const s=i.attributes.label||i.attributes.lang||"text",r=i.attributes.lang||"und";return t[s]||(t[s]={language:r,default:!1,autoselect:!1,playlists:[],uri:""}),t[s].playlists.push(th(Tx(i),e)),t},{}),Cx=n=>n.reduce((e,t)=>(t&&t.forEach(i=>{const{channel:s,language:r}=i;e[r]={autoselect:!1,default:!1,instreamId:s,language:r},i.hasOwnProperty("aspectRatio")&&(e[r].aspectRatio=i.aspectRatio),i.hasOwnProperty("easyReader")&&(e[r].easyReader=i.easyReader),i.hasOwnProperty("3D")&&(e[r]["3D"]=i["3D"])}),e),{}),kx=({attributes:n,segments:e,sidx:t,discontinuityStarts:i})=>{const s={attributes:{NAME:n.id,AUDIO:"audio",SUBTITLES:"subs",RESOLUTION:{width:n.width,height:n.height},CODECS:n.codecs,BANDWIDTH:n.bandwidth,"PROGRAM-ID":1},uri:"",endList:n.type==="static",timeline:n.periodStart,resolvedUri:n.baseUrl||"",targetDuration:n.duration,discontinuityStarts:i,timelineStarts:n.timelineStarts,segments:e};return n.frameRate&&(s.attributes["FRAME-RATE"]=n.frameRate),n.qualityRanking!==void 0&&(s.attributes.SCORE=1/(n.qualityRanking+1)),n.contentProtection&&(s.contentProtection=n.contentProtection),n.serviceLocation&&(s.attributes.serviceLocation=n.serviceLocation),t&&(s.sidx=t),s},Ex=({attributes:n})=>n.mimeType==="video/mp4"||n.mimeType==="video/webm"||n.contentType==="video",xx=({attributes:n})=>n.mimeType==="audio/mp4"||n.mimeType==="audio/webm"||n.contentType==="audio",wx=({attributes:n})=>n.mimeType==="text/vtt"||n.contentType==="text",Ax=(n,e)=>{n.forEach(t=>{t.mediaSequence=0,t.discontinuitySequence=e.findIndex(function({timeline:i}){return i===t.timeline}),t.segments&&t.segments.forEach((i,s)=>{i.number=s})})},gy=n=>n?Object.keys(n).reduce((e,t)=>{const i=n[t];return e.concat(i.playlists)},[]):[],Dx=({dashPlaylists:n,locations:e,contentSteering:t,sidxMapping:i={},previousManifest:s,eventStream:r})=>{if(!n.length)return{};const{sourceDuration:a,type:o,suggestedPresentationDelay:c,minimumUpdatePeriod:l}=n[0].attributes,u=eh(n.filter(Ex)).map(kx),h=eh(n.filter(xx)),p=eh(n.filter(wx)),y=n.map(w=>w.attributes.captionServices).filter(Boolean),_={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:"",duration:a,playlists:vx(u,i)};l>=0&&(_.minimumUpdatePeriod=l*1e3),e&&(_.locations=e),t&&(_.contentSteering=t),o==="dynamic"&&(_.suggestedPresentationDelay=c),r&&r.length>0&&(_.eventStream=r);const b=_.playlists.length===0,S=h.length?_x(h,i,b):null,D=p.length?Sx(p,i):null,I=u.concat(gy(S),gy(D)),F=I.map(({timelineStarts:w})=>w);return _.timelineStarts=fy(F),Ax(I,_.timelineStarts),S&&(_.mediaGroups.AUDIO.audio=S),D&&(_.mediaGroups.SUBTITLES.subs=D),y.length&&(_.mediaGroups["CLOSED-CAPTIONS"].cc=Cx(y)),s?yx({oldManifest:s,newManifest:_}):_},Px=(n,e,t)=>{const{NOW:i,clientOffset:s,availabilityStartTime:r,timescale:a=1,periodStart:o=0,minimumUpdatePeriod:c=0}=n,l=(i+s)/1e3,u=r+o,p=l+c-u;return Math.ceil((p*a-e)/t)},yy=(n,e)=>{const{type:t,minimumUpdatePeriod:i=0,media:s="",sourceDuration:r,timescale:a=1,startNumber:o=1,periodStart:c}=n,l=[];let u=-1;for(let h=0;h<e.length;h++){const p=e[h],y=p.d,_=p.r||0,b=p.t||0;u<0&&(u=b),b&&b>u&&(u=b);let S;if(_<0){const F=h+1;F===e.length?t==="dynamic"&&i>0&&s.indexOf("$Number$")>0?S=Px(n,u,y):S=(r*a-u)/y:S=(e[F].t-u)/y}else S=_+1;const D=o+l.length+S;let I=o+l.length;for(;I<D;)l.push({number:I,duration:y/a,time:u,timeline:c}),u+=y,I++}return l},Ix=/\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g,Rx=n=>(e,t,i,s)=>{if(e==="$$")return"$";if(typeof n[t]>"u")return e;const r=""+n[t];return t==="RepresentationID"||(i?s=parseInt(s,10):s=1,r.length>=s)?r:`${new Array(s-r.length+1).join("0")}${r}`},vy=(n,e)=>n.replace(Ix,Rx(e)),Ox=(n,e)=>!n.duration&&!e?[{number:n.startNumber||1,duration:n.sourceDuration,time:0,timeline:n.periodStart}]:n.duration?Jd(n):yy(n,e),Mx=(n,e)=>{const t={RepresentationID:n.id,Bandwidth:n.bandwidth||0},{initialization:i={sourceURL:"",range:""}}=n,s=Fa({baseUrl:n.baseUrl,source:vy(i.sourceURL,t),range:i.range});return Ox(n,e).map(a=>{t.Number=a.number,t.Time=a.time;const o=vy(n.media||"",t),c=n.timescale||1,l=n.presentationTimeOffset||0,u=n.periodStart+(a.time-l)/c;return{uri:o,timeline:a.timeline,duration:a.duration,resolvedUri:Ic(n.baseUrl||"",o),map:s,number:a.number,presentationTime:u}})},Lx=(n,e)=>{const{baseUrl:t,initialization:i={}}=n,s=Fa({baseUrl:t,source:i.sourceURL,range:i.range}),r=Fa({baseUrl:t,source:e.media,range:e.mediaRange});return r.map=s,r},Nx=(n,e)=>{const{duration:t,segmentUrls:i=[],periodStart:s}=n;if(!t&&!e||t&&e)throw new Error(vr.SEGMENT_TIME_UNSPECIFIED);const r=i.map(c=>Lx(n,c));let a;return t&&(a=Jd(n)),e&&(a=yy(n,e)),a.map((c,l)=>{if(r[l]){const u=r[l],h=n.timescale||1,p=n.presentationTimeOffset||0;return u.timeline=c.timeline,u.duration=c.duration,u.number=c.number,u.presentationTime=s+(c.time-p)/h,u}}).filter(c=>c)},Fx=({attributes:n,segmentInfo:e})=>{let t,i;e.template?(i=Mx,t=Rt(n,e.template)):e.base?(i=hy,t=Rt(n,e.base)):e.list&&(i=Nx,t=Rt(n,e.list));const s={attributes:n};if(!i)return s;const r=i(t,e.segmentTimeline);if(t.duration){const{duration:a,timescale:o=1}=t;t.duration=a/o}else r.length?t.duration=r.reduce((a,o)=>Math.max(a,Math.ceil(o.duration)),0):t.duration=0;return s.attributes=t,s.segments=r,e.base&&t.indexRange&&(s.sidx=r[0],s.segments=[]),s},Ux=n=>n.map(Fx),at=(n,e)=>uy(n.childNodes).filter(({tagName:t})=>t===e),Ua=n=>n.textContent.trim(),Bx=n=>parseFloat(n.split("/").reduce((e,t)=>e/t)),br=n=>{const o=/P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/.exec(n);if(!o)return 0;const[c,l,u,h,p,y]=o.slice(1);return parseFloat(c||0)*31536e3+parseFloat(l||0)*2592e3+parseFloat(u||0)*86400+parseFloat(h||0)*3600+parseFloat(p||0)*60+parseFloat(y||0)},qx=n=>(/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(n)&&(n+="Z"),Date.parse(n)),by={mediaPresentationDuration(n){return br(n)},availabilityStartTime(n){return qx(n)/1e3},minimumUpdatePeriod(n){return br(n)},suggestedPresentationDelay(n){return br(n)},type(n){return n},timeShiftBufferDepth(n){return br(n)},start(n){return br(n)},width(n){return parseInt(n,10)},height(n){return parseInt(n,10)},bandwidth(n){return parseInt(n,10)},frameRate(n){return Bx(n)},startNumber(n){return parseInt(n,10)},timescale(n){return parseInt(n,10)},presentationTimeOffset(n){return parseInt(n,10)},duration(n){const e=parseInt(n,10);return isNaN(e)?br(n):e},d(n){return parseInt(n,10)},t(n){return parseInt(n,10)},r(n){return parseInt(n,10)},presentationTime(n){return parseInt(n,10)},qualityRanking(n){return parseInt(n,10)},qualityranking(n){return parseInt(n,10)},DEFAULT(n){return n}},Vx={qualityranking:"qualityRanking"},Ct=n=>n&&n.attributes?uy(n.attributes).reduce((e,t)=>{const i=by[t.name]||by.DEFAULT,s=Vx[t.name]||t.name;return e[s]=i(t.value),e},{}):{},jx={"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":"org.w3.clearkey","urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":"com.widevine.alpha","urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb":"com.adobe.primetime","urn:mpeg:dash:mp4protection:2011":"mp4protection"},Mc=(n,e)=>e.length?yr(n.map(function(t){return e.map(function(i){const s=Ua(i),r=Ic(t.baseUrl,s),a=Rt(Ct(i),{baseUrl:r});return r!==s&&!a.serviceLocation&&t.serviceLocation&&(a.serviceLocation=t.serviceLocation),a})})):n,ih=n=>{const e=at(n,"SegmentTemplate")[0],t=at(n,"SegmentList")[0],i=t&&at(t,"SegmentURL").map(h=>Rt({tag:"SegmentURL"},Ct(h))),s=at(n,"SegmentBase")[0],r=t||e,a=r&&at(r,"SegmentTimeline")[0],o=t||s||e,c=o&&at(o,"Initialization")[0],l=e&&Ct(e);l&&c?l.initialization=c&&Ct(c):l&&l.initialization&&(l.initialization={sourceURL:l.initialization});const u={template:l,segmentTimeline:a&&at(a,"S").map(h=>Ct(h)),list:t&&Rt(Ct(t),{segmentUrls:i,initialization:Ct(c)}),base:s&&Rt(Ct(s),{initialization:Ct(c)})};return Object.keys(u).forEach(h=>{u[h]||delete u[h]}),u},Hx=(n,e,t)=>i=>{const s=at(i,"BaseURL"),r=Mc(e,s),a=Rt(n,Ct(i)),o=ih(i);return r.map(c=>({segmentInfo:Rt(t,o),attributes:Rt(a,c)}))},$x=n=>n.reduce((e,t)=>{const i=Ct(t);i.schemeIdUri&&(i.schemeIdUri=i.schemeIdUri.toLowerCase());const s=jx[i.schemeIdUri];if(s){e[s]={attributes:i};const r=at(t,"cenc:pssh")[0];if(r){const a=Ua(r);e[s].pssh=a&&z0(a)}}return e},{}),Wx=n=>{if(n.schemeIdUri==="urn:scte:dash:cc:cea-608:2015")return(typeof n.value!="string"?[]:n.value.split(";")).map(t=>{let i,s;return s=t,/^CC\d=/.test(t)?[i,s]=t.split("="):/^CC\d$/.test(t)&&(i=t),{channel:i,language:s}});if(n.schemeIdUri==="urn:scte:dash:cc:cea-708:2015")return(typeof n.value!="string"?[]:n.value.split(";")).map(t=>{const i={channel:void 0,language:void 0,aspectRatio:1,easyReader:0,"3D":0};if(/=/.test(t)){const[s,r=""]=t.split("=");i.channel=s,i.language=t,r.split(",").forEach(a=>{const[o,c]=a.split(":");o==="lang"?i.language=c:o==="er"?i.easyReader=Number(c):o==="war"?i.aspectRatio=Number(c):o==="3D"&&(i["3D"]=Number(c))})}else i.language=t;return i.channel&&(i.channel="SERVICE"+i.channel),i})},zx=n=>yr(at(n.node,"EventStream").map(e=>{const t=Ct(e),i=t.schemeIdUri;return at(e,"Event").map(s=>{const r=Ct(s),a=r.presentationTime||0,o=t.timescale||1,c=r.duration||0,l=a/o+n.attributes.start;return{schemeIdUri:i,value:t.value,id:r.id,start:l,end:l+c/o,messageData:Ua(s)||r.messageData,contentEncoding:t.contentEncoding,presentationTimeOffset:t.presentationTimeOffset||0}})})),Gx=(n,e,t)=>i=>{const s=Ct(i),r=Mc(e,at(i,"BaseURL")),a=at(i,"Role")[0],o={role:Ct(a)};let c=Rt(n,s,o);const l=at(i,"Accessibility")[0],u=Wx(Ct(l));u&&(c=Rt(c,{captionServices:u}));const h=at(i,"Label")[0];if(h&&h.childNodes.length){const S=h.childNodes[0].nodeValue.trim();c=Rt(c,{label:S})}const p=$x(at(i,"ContentProtection"));Object.keys(p).length&&(c=Rt(c,{contentProtection:p}));const y=ih(i),_=at(i,"Representation"),b=Rt(t,y);return yr(_.map(Hx(c,r,b)))},Kx=(n,e)=>(t,i)=>{const s=Mc(e,at(t.node,"BaseURL")),r=Rt(n,{periodStart:t.attributes.start});typeof t.attributes.duration=="number"&&(r.periodDuration=t.attributes.duration);const a=at(t.node,"AdaptationSet"),o=ih(t.node);return yr(a.map(Gx(r,s,o)))},Xx=(n,e)=>{if(n.length>1&&e({type:"warn",message:"The MPD manifest should contain no more than one ContentSteering tag"}),!n.length)return null;const t=Rt({serverURL:Ua(n[0])},Ct(n[0]));return t.queryBeforeStart=t.queryBeforeStart==="true",t},Yx=({attributes:n,priorPeriodAttributes:e,mpdType:t})=>typeof n.start=="number"?n.start:e&&typeof e.start=="number"&&typeof e.duration=="number"?e.start+e.duration:!e&&t==="static"?0:null,Qx=(n,e={})=>{const{manifestUri:t="",NOW:i=Date.now(),clientOffset:s=0,eventHandler:r=function(){}}=e,a=at(n,"Period");if(!a.length)throw new Error(vr.INVALID_NUMBER_OF_PERIOD);const o=at(n,"Location"),c=Ct(n),l=Mc([{baseUrl:t}],at(n,"BaseURL")),u=at(n,"ContentSteering");c.type=c.type||"static",c.sourceDuration=c.mediaPresentationDuration||0,c.NOW=i,c.clientOffset=s,o.length&&(c.locations=o.map(Ua));const h=[];return a.forEach((p,y)=>{const _=Ct(p),b=h[y-1];_.start=Yx({attributes:_,priorPeriodAttributes:b?b.attributes:null,mpdType:c.type}),h.push({node:p,attributes:_})}),{locations:c.locations,contentSteeringInfo:Xx(u,r),representationInfo:yr(h.map(Kx(c,l))),eventStream:yr(h.map(zx))}},Ty=n=>{if(n==="")throw new Error(vr.DASH_EMPTY_MANIFEST);const e=new ax.DOMParser;let t,i;try{t=e.parseFromString(n,"application/xml"),i=t&&t.documentElement.tagName==="MPD"?t.documentElement:null}catch{}if(!i||i&&i.getElementsByTagName("parsererror").length>0)throw new Error(vr.DASH_INVALID_XML);return i},Jx=n=>{const e=at(n,"UTCTiming")[0];if(!e)return null;const t=Ct(e);switch(t.schemeIdUri){case"urn:mpeg:dash:utc:http-head:2014":case"urn:mpeg:dash:utc:http-head:2012":t.method="HEAD";break;case"urn:mpeg:dash:utc:http-xsdate:2014":case"urn:mpeg:dash:utc:http-iso:2014":case"urn:mpeg:dash:utc:http-xsdate:2012":case"urn:mpeg:dash:utc:http-iso:2012":t.method="GET";break;case"urn:mpeg:dash:utc:direct:2014":case"urn:mpeg:dash:utc:direct:2012":t.method="DIRECT",t.value=Date.parse(t.value);break;case"urn:mpeg:dash:utc:http-ntp:2014":case"urn:mpeg:dash:utc:ntp:2014":case"urn:mpeg:dash:utc:sntp:2014":default:throw new Error(vr.UNSUPPORTED_UTC_TIMING_SCHEME)}return t},Zx=(n,e={})=>{const t=Qx(Ty(n),e),i=Ux(t.representationInfo);return Dx({dashPlaylists:i,locations:t.locations,contentSteering:t.contentSteeringInfo,sidxMapping:e.sidxMapping,previousManifest:e.previousManifest,eventStream:t.eventStream})},ew=n=>Jx(Ty(n));var nh,_y;function tw(){if(_y)return nh;_y=1;var n=Math.pow(2,32),e=function(t){var i=new DataView(t.buffer,t.byteOffset,t.byteLength),s;return i.getBigUint64?(s=i.getBigUint64(0),s<Number.MAX_SAFE_INTEGER?Number(s):s):i.getUint32(0)*n+i.getUint32(4)};return nh={getUint64:e,MAX_UINT32:n},nh}var sh,Sy;function iw(){if(Sy)return sh;Sy=1;var n=tw().getUint64,e=function(t){var i=new DataView(t.buffer,t.byteOffset,t.byteLength),s={version:t[0],flags:new Uint8Array(t.subarray(1,4)),references:[],referenceId:i.getUint32(4),timescale:i.getUint32(8)},r=12;s.version===0?(s.earliestPresentationTime=i.getUint32(r),s.firstOffset=i.getUint32(r+4),r+=8):(s.earliestPresentationTime=n(t.subarray(r)),s.firstOffset=n(t.subarray(r+8)),r+=16),r+=2;var a=i.getUint16(r);for(r+=2;a>0;r+=12,a--)s.references.push({referenceType:(t[r]&128)>>>7,referencedSize:i.getUint32(r)&2147483647,subsegmentDuration:i.getUint32(r+4),startsWithSap:!!(t[r+8]&128),sapType:(t[r+8]&112)>>>4,sapDeltaTime:i.getUint32(r+8)&268435455});return s};return sh=e,sh}var nw=iw();const sw=Ra(nw);var rw=Ce([73,68,51]),aw=function(e,t){t===void 0&&(t=0),e=Ce(e);var i=e[t+5],s=e[t+6]<<21|e[t+7]<<14|e[t+8]<<7|e[t+9],r=(i&16)>>4;return r?s+20:s+10},Ba=function n(e,t){return t===void 0&&(t=0),e=Ce(e),e.length-t<10||!tt(e,rw,{offset:t})?t:(t+=aw(e,t),n(e,t))},Cy=function(e){return typeof e=="string"?ey(e):e},ow=function(e){return Array.isArray(e)?e.map(function(t){return Cy(t)}):[Cy(e)]},cw=function n(e,t,i){i===void 0&&(i=!1),t=ow(t),e=Ce(e);var s=[];if(!t.length)return s;for(var r=0;r<e.length;){var a=(e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3])>>>0,o=e.subarray(r+4,r+8);if(a===0)break;var c=r+a;if(c>e.length){if(i)break;c=e.length}var l=e.subarray(r+8,c);tt(o,t[0])&&(t.length===1?s.push(l):s.push.apply(s,n(l,t.slice(1),i))),r=c}return s},Lc={EBML:Ce([26,69,223,163]),DocType:Ce([66,130]),Segment:Ce([24,83,128,103]),SegmentInfo:Ce([21,73,169,102]),Tracks:Ce([22,84,174,107]),Track:Ce([174]),TrackNumber:Ce([215]),DefaultDuration:Ce([35,227,131]),TrackEntry:Ce([174]),TrackType:Ce([131]),FlagDefault:Ce([136]),CodecID:Ce([134]),CodecPrivate:Ce([99,162]),VideoTrack:Ce([224]),AudioTrack:Ce([225]),Cluster:Ce([31,67,182,117]),Timestamp:Ce([231]),TimestampScale:Ce([42,215,177]),BlockGroup:Ce([160]),BlockDuration:Ce([155]),Block:Ce([161]),SimpleBlock:Ce([163])},rh=[128,64,32,16,8,4,2,1],lw=function(e){for(var t=1,i=0;i<rh.length&&!(e&rh[i]);i++)t++;return t},Nc=function(e,t,i,s){i===void 0&&(i=!0),s===void 0&&(s=!1);var r=lw(e[t]),a=e.subarray(t,t+r);return i&&(a=Array.prototype.slice.call(e,t,t+r),a[0]^=rh[r-1]),{length:r,value:J1(a,{signed:s}),bytes:a}},ky=function n(e){return typeof e=="string"?e.match(/.{1,2}/g).map(function(t){return n(t)}):typeof e=="number"?Z1(e):e},uw=function(e){return Array.isArray(e)?e.map(function(t){return ky(t)}):[ky(e)]},dw=function n(e,t,i){if(i>=t.length)return t.length;var s=Nc(t,i,!1);if(tt(e.bytes,s.bytes))return i;var r=Nc(t,i+s.length);return n(e,t,i+r.length+r.value+s.length)},Ey=function n(e,t){t=uw(t),e=Ce(e);var i=[];if(!t.length)return i;for(var s=0;s<e.length;){var r=Nc(e,s,!1),a=Nc(e,s+r.length),o=s+r.length+a.length;a.value===127&&(a.value=dw(r,e,o),a.value!==e.length&&(a.value-=o));var c=o+a.value>e.length?e.length:o+a.value,l=e.subarray(o,c);tt(t[0],r.bytes)&&(t.length===1?i.push(l):i=i.concat(n(l,t.slice(1))));var u=r.length+a.length+l.length;s+=u}return i},hw=Ce([0,0,0,1]),fw=Ce([0,0,1]),pw=Ce([0,0,3]),mw=function(e){for(var t=[],i=1;i<e.length-2;)tt(e.subarray(i,i+3),pw)&&(t.push(i+2),i++),i++;if(t.length===0)return e;var s=e.length-t.length,r=new Uint8Array(s),a=0;for(i=0;i<s;a++,i++)a===t[0]&&(a++,t.shift()),r[i]=e[a];return r},xy=function(e,t,i,s){e=Ce(e),i=[].concat(i);for(var r=0,a,o=0;r<e.length&&(o<s||a);){var c=void 0;if(tt(e.subarray(r),hw)?c=4:tt(e.subarray(r),fw)&&(c=3),!c){r++;continue}if(o++,a)return mw(e.subarray(a,r));var l=void 0;t==="h264"?l=e[r+c]&31:t==="h265"&&(l=e[r+c]>>1&63),i.indexOf(l)!==-1&&(a=r+c),r+=c+(t==="h264"?1:2)}return e.subarray(0,0)},gw=function(e,t,i){return xy(e,"h264",t,i)},yw=function(e,t,i){return xy(e,"h265",t,i)},jt={webm:Ce([119,101,98,109]),matroska:Ce([109,97,116,114,111,115,107,97]),flac:Ce([102,76,97,67]),ogg:Ce([79,103,103,83]),ac3:Ce([11,119]),riff:Ce([82,73,70,70]),avi:Ce([65,86,73]),wav:Ce([87,65,86,69]),"3gp":Ce([102,116,121,112,51,103]),mp4:Ce([102,116,121,112]),fmp4:Ce([115,116,121,112]),mov:Ce([102,116,121,112,113,116]),moov:Ce([109,111,111,118]),moof:Ce([109,111,111,102]),vtt:Ce([87,69,66,86,84,84])},Tr={aac:function(e){var t=Ba(e);return tt(e,[255,16],{offset:t,mask:[255,22]})},mp3:function(e){var t=Ba(e);return tt(e,[255,2],{offset:t,mask:[255,6]})},webm:function(e){var t=Ey(e,[Lc.EBML,Lc.DocType])[0];return tt(t,jt.webm)},mkv:function(e){var t=Ey(e,[Lc.EBML,Lc.DocType])[0];return tt(t,jt.matroska)},mp4:function(e){if(Tr["3gp"](e)||Tr.mov(e))return!1;if(tt(e,jt.mp4,{offset:4})||tt(e,jt.fmp4,{offset:4})||tt(e,jt.moof,{offset:4})||tt(e,jt.moov,{offset:4}))return!0},mov:function(e){return tt(e,jt.mov,{offset:4})},"3gp":function(e){return tt(e,jt["3gp"],{offset:4})},ac3:function(e){var t=Ba(e);return tt(e,jt.ac3,{offset:t})},vtt:function(e){return tt(e,jt.vtt)},ts:function(e){if(e.length<189&&e.length>=1)return e[0]===71;for(var t=0;t+188<e.length&&t<188;){if(e[t]===71&&e[t+188]===71)return!0;t+=1}return!1},flac:function(e){var t=Ba(e);return tt(e,jt.flac,{offset:t})},ogg:function(e){return tt(e,jt.ogg)},avi:function(e){return tt(e,jt.riff)&&tt(e,jt.avi,{offset:8})},wav:function(e){return tt(e,jt.riff)&&tt(e,jt.wav,{offset:8})},h264:function(e){return gw(e,7,3).length},h265:function(e){return yw(e,[32,33],3).length}},ah=Object.keys(Tr).filter(function(n){return n!=="ts"&&n!=="h264"&&n!=="h265"}).concat(["ts","h264","h265"]);ah.forEach(function(n){var e=Tr[n];Tr[n]=function(t){return e(Ce(t))}});var vw=Tr,oh=function(e){e=Ce(e);for(var t=0;t<ah.length;t++){var i=ah[t];if(vw[i](e))return i}return""},bw=function(e){return cw(e,["moof"]).length>0},ch,wy;function Tw(){if(wy)return ch;wy=1;var n=9e4,e,t,i,s,r,a,o;return e=function(c){return c*n},t=function(c,l){return c*l},i=function(c){return c/n},s=function(c,l){return c/l},r=function(c,l){return e(s(c,l))},a=function(c,l){return t(i(c),l)},o=function(c,l,u){return i(u?c:c-l)},ch={ONE_SECOND_IN_TS:n,secondsToVideoTs:e,secondsToAudioTs:t,videoTsToSeconds:i,audioTsToSeconds:s,audioTsToVideoTs:r,videoTsToAudioTs:a,metadataTsToSeconds:o},ch}var Ms=Tw();/**
|
|
72
|
+
* @license
|
|
73
|
+
* Video.js 8.24.0 <http://videojs.com/>
|
|
74
|
+
* Copyright 2010-present Video.js contributors
|
|
75
|
+
* Available under Apache License Version 2.0
|
|
76
|
+
* <https://github.com/videojs/video.js/blob/main/LICENSE>
|
|
77
|
+
*
|
|
78
|
+
* Includes vtt.js <https://github.com/mozilla/vtt.js>
|
|
79
|
+
* Available under Apache License Version 2.0
|
|
80
|
+
* <https://github.com/mozilla/vtt.js/blob/main/LICENSE>
|
|
81
|
+
*/var lh="8.24.0";const Mn={},ss=function(n,e){return Mn[n]=Mn[n]||[],e&&(Mn[n]=Mn[n].concat(e)),Mn[n]},_w=function(n,e){ss(n,e)},Ay=function(n,e){const t=ss(n).indexOf(e);return t<=-1?!1:(Mn[n]=Mn[n].slice(),Mn[n].splice(t,1),!0)},Sw=function(n,e){ss(n,[].concat(e).map(t=>{const i=(...s)=>(Ay(n,i),t(...s));return i}))},Fc={prefixed:!0},Uc=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror","fullscreen"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror","-webkit-full-screen"]],Dy=Uc[0];let qa;for(let n=0;n<Uc.length;n++)if(Uc[n][1]in de){qa=Uc[n];break}if(qa){for(let n=0;n<qa.length;n++)Fc[Dy[n]]=qa[n];Fc.prefixed=qa[0]!==Dy[0]}let li=[];const Cw=(n,e,t)=>(i,s,r)=>{const a=e.levels[s],o=new RegExp(`^(${a})$`);let c=n;if(i!=="log"&&r.unshift(i.toUpperCase()+":"),t&&(c=`%c${n}`,r.unshift(t)),r.unshift(c+":"),li){li.push([].concat(r));const u=li.length-1e3;li.splice(0,u>0?u:0)}if(!B.console)return;let l=B.console[i];!l&&i==="debug"&&(l=B.console.info||B.console.log),!(!l||!a||!o.test(i))&&l[Array.isArray(r)?"apply":"call"](B.console,r)};function uh(n,e=":",t=""){let i="info",s;function r(...a){s("log",i,a)}return s=Cw(n,r,t),r.createLogger=(a,o,c)=>{const l=o!==void 0?o:e,u=c!==void 0?c:t,h=`${n} ${l} ${a}`;return uh(h,l,u)},r.createNewLogger=(a,o,c)=>uh(a,o,c),r.levels={all:"debug|log|warn|error",off:"",debug:"debug|log|warn|error",info:"log|warn|error",warn:"warn|error",error:"error",DEFAULT:i},r.level=a=>{if(typeof a=="string"){if(!r.levels.hasOwnProperty(a))throw new Error(`"${a}" in not a valid log level`);i=a}return i},r.history=()=>li?[].concat(li):[],r.history.filter=a=>(li||[]).filter(o=>new RegExp(`.*${a}.*`).test(o[0])),r.history.clear=()=>{li&&(li.length=0)},r.history.disable=()=>{li!==null&&(li.length=0,li=null)},r.history.enable=()=>{li===null&&(li=[])},r.error=(...a)=>s("error",i,a),r.warn=(...a)=>s("warn",i,a),r.debug=(...a)=>s("debug",i,a),r}const Oe=uh("VIDEOJS"),Py=Oe.createLogger,kw=Object.prototype.toString,Iy=function(n){return un(n)?Object.keys(n):[]};function _r(n,e){Iy(n).forEach(t=>e(n[t],t))}function Ry(n,e,t=0){return Iy(n).reduce((i,s)=>e(i,n[s],s),t)}function un(n){return!!n&&typeof n=="object"}function Sr(n){return un(n)&&kw.call(n)==="[object Object]"&&n.constructor===Object}function Qe(...n){const e={};return n.forEach(t=>{t&&_r(t,(i,s)=>{if(!Sr(i)){e[s]=i;return}Sr(e[s])||(e[s]={}),e[s]=Qe(e[s],i)})}),e}function Oy(n={}){const e=[];for(const t in n)if(n.hasOwnProperty(t)){const i=n[t];e.push(i)}return e}function Bc(n,e,t,i=!0){const s=a=>Object.defineProperty(n,e,{value:a,enumerable:!0,writable:!0}),r={configurable:!0,enumerable:!0,get(){const a=t();return s(a),a}};return i&&(r.set=s),Object.defineProperty(n,e,r)}var Ew=Object.freeze({__proto__:null,each:_r,reduce:Ry,isObject:un,isPlain:Sr,merge:Qe,values:Oy,defineLazyProperty:Bc});let dh=!1,My=null,Wi=!1,Ly,Ny=!1,rs=!1,Cr=!1,dn=!1,hh=null,qc=null;const xw=!!(B.cast&&B.cast.framework&&B.cast.framework.CastReceiverContext);let Fy=null,Vc=!1,jc=!1,Hc=!1,$c=!1,Wc=!1,zc=!1,Gc=!1;const Va=!!(kr()&&("ontouchstart"in B||B.navigator.maxTouchPoints||B.DocumentTouch&&B.document instanceof B.DocumentTouch)),as=B.navigator&&B.navigator.userAgentData;if(as&&as.platform&&as.brands&&(Wi=as.platform==="Android",rs=!!as.brands.find(n=>n.brand==="Microsoft Edge"),Cr=!!as.brands.find(n=>n.brand==="Chromium"),dn=!rs&&Cr,hh=qc=(as.brands.find(n=>n.brand==="Chromium")||{}).version||null,jc=as.platform==="Windows"),!Cr){const n=B.navigator&&B.navigator.userAgent||"";dh=/iPod/i.test(n),My=(function(){const e=n.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null})(),Wi=/Android/i.test(n),Ly=(function(){const e=n.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);return t&&i?parseFloat(e[1]+"."+e[2]):t||null})(),Ny=/Firefox/i.test(n),rs=/Edg/i.test(n),Cr=/Chrome/i.test(n)||/CriOS/i.test(n),dn=!rs&&Cr,hh=qc=(function(){const e=n.match(/(Chrome|CriOS)\/(\d+)/);return e&&e[2]?parseFloat(e[2]):null})(),Fy=(function(){const e=/MSIE\s(\d+)\.\d/.exec(n);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(n)&&/rv:11.0/.test(n)&&(t=11),t})(),Wc=/Tizen/i.test(n),zc=/Web0S/i.test(n),Gc=Wc||zc,Vc=/Safari/i.test(n)&&!dn&&!Wi&&!rs&&!Gc,jc=/Windows/i.test(n),Hc=/iPad/i.test(n)||Vc&&Va&&!/iPhone/i.test(n),$c=/iPhone/i.test(n)&&!Hc}const Ht=$c||Hc||dh,Kc=(Vc||Ht)&&!dn;var Uy=Object.freeze({__proto__:null,get IS_IPOD(){return dh},get IOS_VERSION(){return My},get IS_ANDROID(){return Wi},get ANDROID_VERSION(){return Ly},get IS_FIREFOX(){return Ny},get IS_EDGE(){return rs},get IS_CHROMIUM(){return Cr},get IS_CHROME(){return dn},get CHROMIUM_VERSION(){return hh},get CHROME_VERSION(){return qc},IS_CHROMECAST_RECEIVER:xw,get IE_VERSION(){return Fy},get IS_SAFARI(){return Vc},get IS_WINDOWS(){return jc},get IS_IPAD(){return Hc},get IS_IPHONE(){return $c},get IS_TIZEN(){return Wc},get IS_WEBOS(){return zc},get IS_SMART_TV(){return Gc},TOUCH_ENABLED:Va,IS_IOS:Ht,IS_ANY_SAFARI:Kc});function By(n){return typeof n=="string"&&!!n.trim()}function ww(n){if(n.indexOf(" ")>=0)throw new Error("class has illegal whitespace characters")}function kr(){return de===B.document}function Er(n){return un(n)&&n.nodeType===1}function qy(){try{return B.parent!==B.self}catch{return!0}}function Vy(n){return function(e,t){if(!By(e))return de[n](null);By(t)&&(t=de.querySelector(t));const i=Er(t)?t:de;return i[n]&&i[n](e)}}function Ee(n="div",e={},t={},i){const s=de.createElement(n);return Object.getOwnPropertyNames(e).forEach(function(r){const a=e[r];r==="textContent"?os(s,a):(s[r]!==a||r==="tabIndex")&&(s[r]=a)}),Object.getOwnPropertyNames(t).forEach(function(r){s.setAttribute(r,t[r])}),i&&ph(s,i),s}function os(n,e){return typeof n.textContent>"u"?n.innerText=e:n.textContent=e,n}function fh(n,e){e.firstChild?e.insertBefore(n,e.firstChild):e.appendChild(n)}function ja(n,e){return ww(e),n.classList.contains(e)}function Ls(n,...e){return n.classList.add(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),n}function Xc(n,...e){return n?(n.classList.remove(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),n):(Oe.warn("removeClass was called with an element that doesn't exist"),null)}function jy(n,e,t){return typeof t=="function"&&(t=t(n,e)),typeof t!="boolean"&&(t=void 0),e.split(/\s+/).forEach(i=>n.classList.toggle(i,t)),n}function Hy(n,e){Object.getOwnPropertyNames(e).forEach(function(t){const i=e[t];i===null||typeof i>"u"||i===!1?n.removeAttribute(t):n.setAttribute(t,i===!0?"":i)})}function cs(n){const e={},t=["autoplay","controls","playsinline","loop","muted","default","defaultMuted"];if(n&&n.attributes&&n.attributes.length>0){const i=n.attributes;for(let s=i.length-1;s>=0;s--){const r=i[s].name;let a=i[s].value;t.includes(r)&&(a=a!==null),e[r]=a}}return e}function $y(n,e){return n.getAttribute(e)}function xr(n,e,t){n.setAttribute(e,t)}function Yc(n,e){n.removeAttribute(e)}function Wy(){de.body.focus(),de.onselectstart=function(){return!1}}function zy(){de.onselectstart=function(){return!0}}function wr(n){if(n&&n.getBoundingClientRect&&n.parentNode){const e=n.getBoundingClientRect(),t={};return["bottom","height","left","right","top","width"].forEach(i=>{e[i]!==void 0&&(t[i]=e[i])}),t.height||(t.height=parseFloat(Ar(n,"height"))),t.width||(t.width=parseFloat(Ar(n,"width"))),t}}function Ha(n){if(!n||n&&!n.offsetParent)return{left:0,top:0,width:0,height:0};const e=n.offsetWidth,t=n.offsetHeight;let i=0,s=0;for(;n.offsetParent&&n!==de[Fc.fullscreenElement];)i+=n.offsetLeft,s+=n.offsetTop,n=n.offsetParent;return{left:i,top:s,width:e,height:t}}function Qc(n,e){const t={x:0,y:0};if(Ht){let u=n;for(;u&&u.nodeName.toLowerCase()!=="html";){const h=Ar(u,"transform");if(/^matrix/.test(h)){const p=h.slice(7,-1).split(/,\s/).map(Number);t.x+=p[4],t.y+=p[5]}else if(/^matrix3d/.test(h)){const p=h.slice(9,-1).split(/,\s/).map(Number);t.x+=p[12],t.y+=p[13]}if(u.assignedSlot&&u.assignedSlot.parentElement&&B.WebKitCSSMatrix){const p=B.getComputedStyle(u.assignedSlot.parentElement).transform,y=new B.WebKitCSSMatrix(p);t.x+=y.m41,t.y+=y.m42}u=u.parentNode||u.host}}const i={},s=Ha(e.target),r=Ha(n),a=r.width,o=r.height;let c=e.offsetY-(r.top-s.top),l=e.offsetX-(r.left-s.left);return e.changedTouches&&(l=e.changedTouches[0].pageX-r.left,c=e.changedTouches[0].pageY+r.top,Ht&&(l-=t.x,c-=t.y)),i.y=1-Math.max(0,Math.min(1,c/o)),i.x=Math.max(0,Math.min(1,l/a)),i}function Gy(n){return un(n)&&n.nodeType===3}function Jc(n){for(;n.firstChild;)n.removeChild(n.firstChild);return n}function Ky(n){return typeof n=="function"&&(n=n()),(Array.isArray(n)?n:[n]).map(e=>{if(typeof e=="function"&&(e=e()),Er(e)||Gy(e))return e;if(typeof e=="string"&&/\S/.test(e))return de.createTextNode(e)}).filter(e=>e)}function ph(n,e){return Ky(e).forEach(t=>n.appendChild(t)),n}function Xy(n,e){return ph(Jc(n),e)}function $a(n){return n.button===void 0&&n.buttons===void 0||n.button===0&&n.buttons===void 0||n.type==="mouseup"&&n.button===0&&n.buttons===0||n.type==="mousedown"&&n.button===0&&n.buttons===0?!0:!(n.button!==0||n.buttons!==1)}const ls=Vy("querySelector"),Yy=Vy("querySelectorAll");function Ar(n,e){if(!n||!e)return"";if(typeof B.getComputedStyle=="function"){let t;try{t=B.getComputedStyle(n)}catch{return""}return t?t.getPropertyValue(e)||t[e]:""}return""}function Qy(n){[...de.styleSheets].forEach(e=>{try{const t=[...e.cssRules].map(s=>s.cssText).join(""),i=de.createElement("style");i.textContent=t,n.document.head.appendChild(i)}catch{const i=de.createElement("link");i.rel="stylesheet",i.type=e.type,i.media=e.media.mediaText,i.href=e.href,n.document.head.appendChild(i)}})}var Jy=Object.freeze({__proto__:null,isReal:kr,isEl:Er,isInFrame:qy,createEl:Ee,textContent:os,prependTo:fh,hasClass:ja,addClass:Ls,removeClass:Xc,toggleClass:jy,setAttributes:Hy,getAttributes:cs,getAttribute:$y,setAttribute:xr,removeAttribute:Yc,blockTextSelection:Wy,unblockTextSelection:zy,getBoundingClientRect:wr,findPosition:Ha,getPointerPosition:Qc,isTextNode:Gy,emptyEl:Jc,normalizeContent:Ky,appendContent:ph,insertContent:Xy,isSingleLeftClick:$a,$:ls,$$:Yy,computedStyle:Ar,copyStyleSheetsToWindow:Qy});let Zy=!1,mh;const Aw=function(){if(mh.options.autoSetup===!1)return;const n=Array.prototype.slice.call(de.getElementsByTagName("video")),e=Array.prototype.slice.call(de.getElementsByTagName("audio")),t=Array.prototype.slice.call(de.getElementsByTagName("video-js")),i=n.concat(e,t);if(i&&i.length>0)for(let s=0,r=i.length;s<r;s++){const a=i[s];if(a&&a.getAttribute)a.player===void 0&&a.getAttribute("data-setup")!==null&&mh(a);else{gh(1);break}}else Zy||gh(1)};function gh(n,e){kr()&&(e&&(mh=e),B.setTimeout(Aw,n))}function yh(){Zy=!0,B.removeEventListener("load",yh)}kr()&&(de.readyState==="complete"?yh():B.addEventListener("load",yh));const ev=function(n){const e=de.createElement("style");return e.className=n,e},tv=function(n,e){n.styleSheet?n.styleSheet.cssText=e:n.textContent=e};var ei=new WeakMap;let Dw=3;function Di(){return Dw++}function iv(n,e){if(!ei.has(n))return;const t=ei.get(n);t.handlers[e].length===0&&(delete t.handlers[e],n.removeEventListener?n.removeEventListener(e,t.dispatcher,!1):n.detachEvent&&n.detachEvent("on"+e,t.dispatcher)),Object.getOwnPropertyNames(t.handlers).length<=0&&(delete t.handlers,delete t.dispatcher,delete t.disabled),Object.getOwnPropertyNames(t).length===0&&ei.delete(n)}function vh(n,e,t,i){t.forEach(function(s){n(e,s,i)})}function Zc(n){if(n.fixed_)return n;function e(){return!0}function t(){return!1}if(!n||!n.isPropagationStopped||!n.isImmediatePropagationStopped){const i=n||B.event;n={};const s=["layerX","layerY","keyLocation","path","webkitMovementX","webkitMovementY","mozPressure","mozInputSource"];for(const r in i)s.includes(r)||r==="returnValue"&&i.preventDefault||(n[r]=i[r]);if(n.target||(n.target=n.srcElement||de),n.relatedTarget||(n.relatedTarget=n.fromElement===n.target?n.toElement:n.fromElement),n.preventDefault=function(){i.preventDefault&&i.preventDefault(),n.returnValue=!1,i.returnValue=!1,n.defaultPrevented=!0},n.defaultPrevented=!1,n.stopPropagation=function(){i.stopPropagation&&i.stopPropagation(),n.cancelBubble=!0,i.cancelBubble=!0,n.isPropagationStopped=e},n.isPropagationStopped=t,n.stopImmediatePropagation=function(){i.stopImmediatePropagation&&i.stopImmediatePropagation(),n.isImmediatePropagationStopped=e,n.stopPropagation()},n.isImmediatePropagationStopped=t,n.clientX!==null&&n.clientX!==void 0){const r=de.documentElement,a=de.body;n.pageX=n.clientX+(r&&r.scrollLeft||a&&a.scrollLeft||0)-(r&&r.clientLeft||a&&a.clientLeft||0),n.pageY=n.clientY+(r&&r.scrollTop||a&&a.scrollTop||0)-(r&&r.clientTop||a&&a.clientTop||0)}n.which=n.charCode||n.keyCode,n.button!==null&&n.button!==void 0&&(n.button=n.button&1?0:n.button&4?1:n.button&2?2:0)}return n.fixed_=!0,n}let el;const Pw=function(){if(typeof el!="boolean"){el=!1;try{const n=Object.defineProperty({},"passive",{get(){el=!0}});B.addEventListener("test",null,n),B.removeEventListener("test",null,n)}catch{}}return el},Iw=["touchstart","touchmove"];function vi(n,e,t){if(Array.isArray(e))return vh(vi,n,e,t);ei.has(n)||ei.set(n,{});const i=ei.get(n);if(i.handlers||(i.handlers={}),i.handlers[e]||(i.handlers[e]=[]),t.guid||(t.guid=Di()),i.handlers[e].push(t),i.dispatcher||(i.disabled=!1,i.dispatcher=function(s,r){if(i.disabled)return;s=Zc(s);const a=i.handlers[s.type];if(a){const o=a.slice(0);for(let c=0,l=o.length;c<l&&!s.isImmediatePropagationStopped();c++)try{o[c].call(n,s,r)}catch(u){Oe.error(u)}}}),i.handlers[e].length===1)if(n.addEventListener){let s=!1;Pw()&&Iw.indexOf(e)>-1&&(s={passive:!0}),n.addEventListener(e,i.dispatcher,s)}else n.attachEvent&&n.attachEvent("on"+e,i.dispatcher)}function $t(n,e,t){if(!ei.has(n))return;const i=ei.get(n);if(!i.handlers)return;if(Array.isArray(e))return vh($t,n,e,t);const s=function(a,o){i.handlers[o]=[],iv(a,o)};if(e===void 0){for(const a in i.handlers)Object.prototype.hasOwnProperty.call(i.handlers||{},a)&&s(n,a);return}const r=i.handlers[e];if(r){if(!t){s(n,e);return}if(t.guid)for(let a=0;a<r.length;a++)r[a].guid===t.guid&&r.splice(a--,1);iv(n,e)}}function Dr(n,e,t){const i=ei.has(n)?ei.get(n):{},s=n.parentNode||n.ownerDocument;if(typeof e=="string"?e={type:e,target:n}:e.target||(e.target=n),e=Zc(e),i.dispatcher&&i.dispatcher.call(n,e,t),s&&!e.isPropagationStopped()&&e.bubbles===!0)Dr.call(null,s,e,t);else if(!s&&!e.defaultPrevented&&e.target&&e.target[e.type]){ei.has(e.target)||ei.set(e.target,{});const r=ei.get(e.target);e.target[e.type]&&(r.disabled=!0,typeof e.target[e.type]=="function"&&e.target[e.type](),r.disabled=!1)}return!e.defaultPrevented}function tl(n,e,t){if(Array.isArray(e))return vh(tl,n,e,t);const i=function(){$t(n,e,i),t.apply(this,arguments)};i.guid=t.guid=t.guid||Di(),vi(n,e,i)}function bh(n,e,t){const i=function(){$t(n,e,i),t.apply(this,arguments)};i.guid=t.guid=t.guid||Di(),vi(n,e,i)}var Rw=Object.freeze({__proto__:null,fixEvent:Zc,on:vi,off:$t,trigger:Dr,one:tl,any:bh});const Pi=30,Ze=function(n,e,t){e.guid||(e.guid=Di());const i=e.bind(n);return i.guid=t?t+"_"+e.guid:e.guid,i},hn=function(n,e){let t=B.performance.now();return function(...s){const r=B.performance.now();r-t>=e&&(n(...s),t=r)}},nv=function(n,e,t,i=B){let s;const r=()=>{i.clearTimeout(s),s=null},a=function(){const o=this,c=arguments;let l=function(){s=null,l=null,t||n.apply(o,c)};!s&&t&&n.apply(o,c),i.clearTimeout(s),s=i.setTimeout(l,e)};return a.cancel=r,a};var Ow=Object.freeze({__proto__:null,UPDATE_REFRESH_INTERVAL:Pi,bind_:Ze,throttle:hn,debounce:nv});let Wa;class bi{on(e,t){const i=this.addEventListener;this.addEventListener=()=>{},vi(this,e,t),this.addEventListener=i}off(e,t){$t(this,e,t)}one(e,t){const i=this.addEventListener;this.addEventListener=()=>{},tl(this,e,t),this.addEventListener=i}any(e,t){const i=this.addEventListener;this.addEventListener=()=>{},bh(this,e,t),this.addEventListener=i}trigger(e){const t=e.type||e;typeof e=="string"&&(e={type:t}),e=Zc(e),this.allowedEvents_[t]&&this["on"+t]&&this["on"+t](e),Dr(this,e)}queueTrigger(e){Wa||(Wa=new Map);const t=e.type||e;let i=Wa.get(this);i||(i=new Map,Wa.set(this,i));const s=i.get(t);i.delete(t),B.clearTimeout(s);const r=B.setTimeout(()=>{i.delete(t),i.size===0&&(i=null,Wa.delete(this)),this.trigger(e)},0);i.set(t,r)}}bi.prototype.allowedEvents_={},bi.prototype.addEventListener=bi.prototype.on,bi.prototype.removeEventListener=bi.prototype.off,bi.prototype.dispatchEvent=bi.prototype.trigger;const il=n=>typeof n.name=="function"?n.name():typeof n.name=="string"?n.name:n.name_?n.name_:n.constructor&&n.constructor.name?n.constructor.name:typeof n,Ln=n=>n instanceof bi||!!n.eventBusEl_&&["on","one","off","trigger"].every(e=>typeof n[e]=="function"),Mw=(n,e)=>{Ln(n)?e():(n.eventedCallbacks||(n.eventedCallbacks=[]),n.eventedCallbacks.push(e))},Th=n=>typeof n=="string"&&/\S/.test(n)||Array.isArray(n)&&!!n.length,nl=(n,e,t)=>{if(!n||!n.nodeName&&!Ln(n))throw new Error(`Invalid target for ${il(e)}#${t}; must be a DOM node or evented object.`)},sv=(n,e,t)=>{if(!Th(n))throw new Error(`Invalid event type for ${il(e)}#${t}; must be a non-empty string or array.`)},rv=(n,e,t)=>{if(typeof n!="function")throw new Error(`Invalid listener for ${il(e)}#${t}; must be a function.`)},_h=(n,e,t)=>{const i=e.length<3||e[0]===n||e[0]===n.eventBusEl_;let s,r,a;return i?(s=n.eventBusEl_,e.length>=3&&e.shift(),[r,a]=e):(s=e[0],r=e[1],a=e[2]),nl(s,n,t),sv(r,n,t),rv(a,n,t),a=Ze(n,a),{isTargetingSelf:i,target:s,type:r,listener:a}},Ns=(n,e,t,i)=>{nl(n,n,e),n.nodeName?Rw[e](n,t,i):n[e](t,i)},Lw={on(...n){const{isTargetingSelf:e,target:t,type:i,listener:s}=_h(this,n,"on");if(Ns(t,"on",i,s),!e){const r=()=>this.off(t,i,s);r.guid=s.guid;const a=()=>this.off("dispose",r);a.guid=s.guid,Ns(this,"on","dispose",r),Ns(t,"on","dispose",a)}},one(...n){const{isTargetingSelf:e,target:t,type:i,listener:s}=_h(this,n,"one");if(e)Ns(t,"one",i,s);else{const r=(...a)=>{this.off(t,i,r),s.apply(null,a)};r.guid=s.guid,Ns(t,"one",i,r)}},any(...n){const{isTargetingSelf:e,target:t,type:i,listener:s}=_h(this,n,"any");if(e)Ns(t,"any",i,s);else{const r=(...a)=>{this.off(t,i,r),s.apply(null,a)};r.guid=s.guid,Ns(t,"any",i,r)}},off(n,e,t){if(!n||Th(n))$t(this.eventBusEl_,n,e);else{const i=n,s=e;nl(i,this,"off"),sv(s,this,"off"),rv(t,this,"off"),t=Ze(this,t),this.off("dispose",t),i.nodeName?($t(i,s,t),$t(i,"dispose",t)):Ln(i)&&(i.off(s,t),i.off("dispose",t))}},trigger(n,e){nl(this.eventBusEl_,this,"trigger");const t=n&&typeof n!="string"?n.type:n;if(!Th(t))throw new Error(`Invalid event type for ${il(this)}#trigger; must be a non-empty string or object with a type key that has a non-empty value.`);return Dr(this.eventBusEl_,n,e)}};function Sh(n,e={}){const{eventBusKey:t}=e;if(t){if(!n[t].nodeName)throw new Error(`The eventBusKey "${t}" does not refer to an element.`);n.eventBusEl_=n[t]}else n.eventBusEl_=Ee("span",{className:"vjs-event-bus"});return Object.assign(n,Lw),n.eventedCallbacks&&n.eventedCallbacks.forEach(i=>{i()}),n.on("dispose",()=>{n.off(),[n,n.el_,n.eventBusEl_].forEach(function(i){i&&ei.has(i)&&ei.delete(i)}),B.setTimeout(()=>{n.eventBusEl_=null},0)}),n}const Nw={state:{},setState(n){typeof n=="function"&&(n=n());let e;return _r(n,(t,i)=>{this.state[i]!==t&&(e=e||{},e[i]={from:this.state[i],to:t}),this.state[i]=t}),e&&Ln(this)&&this.trigger({changes:e,type:"statechanged"}),e}};function av(n,e){return Object.assign(n,Nw),n.state=Object.assign({},n.state,e),typeof n.handleStateChanged=="function"&&Ln(n)&&n.on("statechanged",n.handleStateChanged),n}const za=function(n){return typeof n!="string"?n:n.replace(/./,e=>e.toLowerCase())},pt=function(n){return typeof n!="string"?n:n.replace(/./,e=>e.toUpperCase())},ov=function(n,e){return pt(n)===pt(e)};var Fw=Object.freeze({__proto__:null,toLowerCase:za,toTitleCase:pt,titleCaseEquals:ov});class ee{constructor(e,t,i){if(!e&&this.play?this.player_=e=this:this.player_=e,this.isDisposed_=!1,this.parentComponent_=null,this.options_=Qe({},this.options_),t=this.options_=Qe(this.options_,t),this.id_=t.id||t.el&&t.el.id,!this.id_){const s=e&&e.id&&e.id()||"no_player";this.id_=`${s}_component_${Di()}`}this.name_=t.name||null,t.el?this.el_=t.el:t.createEl!==!1&&(this.el_=this.createEl()),t.className&&this.el_&&t.className.split(" ").forEach(s=>this.addClass(s)),["on","off","one","any","trigger"].forEach(s=>{this[s]=void 0}),t.evented!==!1&&(Sh(this,{eventBusKey:this.el_?"el_":null}),this.handleLanguagechange=this.handleLanguagechange.bind(this),this.on(this.player_,"languagechange",this.handleLanguagechange)),av(this,this.constructor.defaultState),this.children_=[],this.childIndex_={},this.childNameIndex_={},this.setTimeoutIds_=new Set,this.setIntervalIds_=new Set,this.rafIds_=new Set,this.namedRafs_=new Map,this.clearingTimersOnDispose_=!1,t.initChildren!==!1&&this.initChildren(),this.ready(i),t.reportTouchActivity!==!1&&this.enableTouchActivity()}dispose(e={}){if(!this.isDisposed_){if(this.readyQueue_&&(this.readyQueue_.length=0),this.trigger({type:"dispose",bubbles:!1}),this.isDisposed_=!0,this.children_)for(let t=this.children_.length-1;t>=0;t--)this.children_[t].dispose&&this.children_[t].dispose();this.children_=null,this.childIndex_=null,this.childNameIndex_=null,this.parentComponent_=null,this.el_&&(this.el_.parentNode&&(e.restoreEl?this.el_.parentNode.replaceChild(e.restoreEl,this.el_):this.el_.parentNode.removeChild(this.el_)),this.el_=null),this.player_=null}}isDisposed(){return!!this.isDisposed_}player(){return this.player_}options(e){return e?(this.options_=Qe(this.options_,e),this.options_):this.options_}el(){return this.el_}createEl(e,t,i){return Ee(e,t,i)}localize(e,t,i=e){const s=this.player_.language&&this.player_.language(),r=this.player_.languages&&this.player_.languages(),a=r&&r[s],o=s&&s.split("-")[0],c=r&&r[o];let l=i;return a&&a[e]?l=a[e]:c&&c[e]&&(l=c[e]),t&&(l=l.replace(/\{(\d+)\}/g,function(u,h){const p=t[h-1];let y=p;return typeof p>"u"&&(y=u),y})),l}handleLanguagechange(){}contentEl(){return this.contentEl_||this.el_}id(){return this.id_}name(){return this.name_}children(){return this.children_}getChildById(e){return this.childIndex_[e]}getChild(e){if(e)return this.childNameIndex_[e]}getDescendant(...e){e=e.reduce((i,s)=>i.concat(s),[]);let t=this;for(let i=0;i<e.length;i++)if(t=t.getChild(e[i]),!t||!t.getChild)return;return t}setIcon(e,t=this.el()){if(!this.player_.options_.experimentalSvgIcons)return;const i="http://www.w3.org/2000/svg",s=Ee("span",{className:"vjs-icon-placeholder vjs-svg-icon"},{"aria-hidden":"true"}),r=de.createElementNS(i,"svg");r.setAttributeNS(null,"viewBox","0 0 512 512");const a=de.createElementNS(i,"use");return r.appendChild(a),a.setAttributeNS(null,"href",`#vjs-icon-${e}`),s.appendChild(r),this.iconIsSet_?t.replaceChild(s,t.querySelector(".vjs-icon-placeholder")):t.appendChild(s),this.iconIsSet_=!0,s}addChild(e,t={},i=this.children_.length){let s,r;if(typeof e=="string"){r=pt(e);const a=t.componentClass||r;t.name=r;const o=ee.getComponent(a);if(!o)throw new Error(`Component ${a} does not exist`);if(typeof o!="function")return null;s=new o(this.player_||this,t)}else s=e;if(s.parentComponent_&&s.parentComponent_.removeChild(s),this.children_.splice(i,0,s),s.parentComponent_=this,typeof s.id=="function"&&(this.childIndex_[s.id()]=s),r=r||s.name&&pt(s.name()),r&&(this.childNameIndex_[r]=s,this.childNameIndex_[za(r)]=s),typeof s.el=="function"&&s.el()){let a=null;this.children_[i+1]&&(this.children_[i+1].el_?a=this.children_[i+1].el_:Er(this.children_[i+1])&&(a=this.children_[i+1])),this.contentEl().insertBefore(s.el(),a)}return s}removeChild(e){if(typeof e=="string"&&(e=this.getChild(e)),!e||!this.children_)return;let t=!1;for(let s=this.children_.length-1;s>=0;s--)if(this.children_[s]===e){t=!0,this.children_.splice(s,1);break}if(!t)return;e.parentComponent_=null,this.childIndex_[e.id()]=null,this.childNameIndex_[pt(e.name())]=null,this.childNameIndex_[za(e.name())]=null;const i=e.el();i&&i.parentNode===this.contentEl()&&this.contentEl().removeChild(e.el())}initChildren(){const e=this.options_.children;if(e){const t=this.options_,i=a=>{const o=a.name;let c=a.opts;if(t[o]!==void 0&&(c=t[o]),c===!1)return;c===!0&&(c={}),c.playerOptions=this.options_.playerOptions;const l=this.addChild(o,c);l&&(this[o]=l)};let s;const r=ee.getComponent("Tech");Array.isArray(e)?s=e:s=Object.keys(e),s.concat(Object.keys(this.options_).filter(function(a){return!s.some(function(o){return typeof o=="string"?a===o:a===o.name})})).map(a=>{let o,c;return typeof a=="string"?(o=a,c=e[o]||this.options_[o]||{}):(o=a.name,c=a),{name:o,opts:c}}).filter(a=>{const o=ee.getComponent(a.opts.componentClass||pt(a.name));return o&&!r.isTech(o)}).forEach(i)}}buildCSSClass(){return""}ready(e,t=!1){if(e){if(!this.isReady_){this.readyQueue_=this.readyQueue_||[],this.readyQueue_.push(e);return}t?e.call(this):this.setTimeout(e,1)}}triggerReady(){this.isReady_=!0,this.setTimeout(function(){const e=this.readyQueue_;this.readyQueue_=[],e&&e.length>0&&e.forEach(function(t){t.call(this)},this),this.trigger("ready")},1)}$(e,t){return ls(e,t||this.contentEl())}$$(e,t){return Yy(e,t||this.contentEl())}hasClass(e){return ja(this.el_,e)}addClass(...e){Ls(this.el_,...e)}removeClass(...e){Xc(this.el_,...e)}toggleClass(e,t){jy(this.el_,e,t)}show(){this.removeClass("vjs-hidden")}hide(){this.addClass("vjs-hidden")}lockShowing(){this.addClass("vjs-lock-showing")}unlockShowing(){this.removeClass("vjs-lock-showing")}getAttribute(e){return $y(this.el_,e)}setAttribute(e,t){xr(this.el_,e,t)}removeAttribute(e){Yc(this.el_,e)}width(e,t){return this.dimension("width",e,t)}height(e,t){return this.dimension("height",e,t)}dimensions(e,t){this.width(e,!0),this.height(t)}dimension(e,t,i){if(t!==void 0){(t===null||t!==t)&&(t=0),(""+t).indexOf("%")!==-1||(""+t).indexOf("px")!==-1?this.el_.style[e]=t:t==="auto"?this.el_.style[e]="":this.el_.style[e]=t+"px",i||this.trigger("componentresize");return}if(!this.el_)return 0;const s=this.el_.style[e],r=s.indexOf("px");return parseInt(r!==-1?s.slice(0,r):this.el_["offset"+pt(e)],10)}currentDimension(e){let t=0;if(e!=="width"&&e!=="height")throw new Error("currentDimension only accepts width or height value");if(t=Ar(this.el_,e),t=parseFloat(t),t===0||isNaN(t)){const i=`offset${pt(e)}`;t=this.el_[i]}return t}currentDimensions(){return{width:this.currentDimension("width"),height:this.currentDimension("height")}}currentWidth(){return this.currentDimension("width")}currentHeight(){return this.currentDimension("height")}getPositions(){const e=this.el_.getBoundingClientRect(),t={x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left},i={x:e.left+e.width/2,y:e.top+e.height/2,width:0,height:0,top:e.top+e.height/2,right:e.left+e.width/2,bottom:e.top+e.height/2,left:e.left+e.width/2};return{boundingClientRect:t,center:i}}focus(){this.el_.focus()}blur(){this.el_.blur()}handleKeyDown(e){this.player_&&(e.key!=="Tab"&&!(this.player_.options_.playerOptions.spatialNavigation&&this.player_.options_.playerOptions.spatialNavigation.enabled)&&e.stopPropagation(),this.player_.handleKeyDown(e))}handleKeyPress(e){this.handleKeyDown(e)}emitTapEvents(){let e=0,t=null;const i=10,s=200;let r;this.on("touchstart",function(o){o.touches.length===1&&(t={pageX:o.touches[0].pageX,pageY:o.touches[0].pageY},e=B.performance.now(),r=!0)}),this.on("touchmove",function(o){if(o.touches.length>1)r=!1;else if(t){const c=o.touches[0].pageX-t.pageX,l=o.touches[0].pageY-t.pageY;Math.sqrt(c*c+l*l)>i&&(r=!1)}});const a=function(){r=!1};this.on("touchleave",a),this.on("touchcancel",a),this.on("touchend",function(o){t=null,r===!0&&B.performance.now()-e<s&&(o.preventDefault(),this.trigger("tap"))})}enableTouchActivity(){if(!this.player()||!this.player().reportUserActivity)return;const e=Ze(this.player(),this.player().reportUserActivity);let t;this.on("touchstart",function(){e(),this.clearInterval(t),t=this.setInterval(e,250)});const i=function(s){e(),this.clearInterval(t)};this.on("touchmove",e),this.on("touchend",i),this.on("touchcancel",i)}setTimeout(e,t){var i;return e=Ze(this,e),this.clearTimersOnDispose_(),i=B.setTimeout(()=>{this.setTimeoutIds_.has(i)&&this.setTimeoutIds_.delete(i),e()},t),this.setTimeoutIds_.add(i),i}clearTimeout(e){return this.setTimeoutIds_.has(e)&&(this.setTimeoutIds_.delete(e),B.clearTimeout(e)),e}setInterval(e,t){e=Ze(this,e),this.clearTimersOnDispose_();const i=B.setInterval(e,t);return this.setIntervalIds_.add(i),i}clearInterval(e){return this.setIntervalIds_.has(e)&&(this.setIntervalIds_.delete(e),B.clearInterval(e)),e}requestAnimationFrame(e){this.clearTimersOnDispose_();var t;return e=Ze(this,e),t=B.requestAnimationFrame(()=>{this.rafIds_.has(t)&&this.rafIds_.delete(t),e()}),this.rafIds_.add(t),t}requestNamedAnimationFrame(e,t){this.namedRafs_.has(e)&&this.cancelNamedAnimationFrame(e),this.clearTimersOnDispose_(),t=Ze(this,t);const i=this.requestAnimationFrame(()=>{t(),this.namedRafs_.has(e)&&this.namedRafs_.delete(e)});return this.namedRafs_.set(e,i),e}cancelNamedAnimationFrame(e){this.namedRafs_.has(e)&&(this.cancelAnimationFrame(this.namedRafs_.get(e)),this.namedRafs_.delete(e))}cancelAnimationFrame(e){return this.rafIds_.has(e)&&(this.rafIds_.delete(e),B.cancelAnimationFrame(e)),e}clearTimersOnDispose_(){this.clearingTimersOnDispose_||(this.clearingTimersOnDispose_=!0,this.one("dispose",()=>{[["namedRafs_","cancelNamedAnimationFrame"],["rafIds_","cancelAnimationFrame"],["setTimeoutIds_","clearTimeout"],["setIntervalIds_","clearInterval"]].forEach(([e,t])=>{this[e].forEach((i,s)=>this[t](s))}),this.clearingTimersOnDispose_=!1}))}getIsDisabled(){return!!this.el_.disabled}getIsExpresslyInert(){return this.el_.inert&&!this.el_.ownerDocument.documentElement.inert}getIsFocusable(e){return(e||this.el_).tabIndex>=0&&!(this.getIsDisabled()||this.getIsExpresslyInert())}getIsAvailableToBeFocused(e){function t(r){const a=B.getComputedStyle(r,null),o=a.getPropertyValue("visibility");return a.getPropertyValue("display")!=="none"&&!["hidden","collapse"].includes(o)}function i(r){return!(!t(r.parentElement)||!t(r)||r.style.opacity==="0"||B.getComputedStyle(r).height==="0px"||B.getComputedStyle(r).width==="0px")}function s(r){if(r.offsetWidth+r.offsetHeight+r.getBoundingClientRect().height+r.getBoundingClientRect().width===0)return!1;const a={x:r.getBoundingClientRect().left+r.offsetWidth/2,y:r.getBoundingClientRect().top+r.offsetHeight/2};if(a.x<0||a.x>(de.documentElement.clientWidth||B.innerWidth)||a.y<0||a.y>(de.documentElement.clientHeight||B.innerHeight))return!1;let o=de.elementFromPoint(a.x,a.y);for(;o;){if(o===r)return!0;if(o.parentNode)o=o.parentNode;else return!1}}return e||(e=this.el()),!!(s(e)&&i(e)&&(!e.parentElement||e.tabIndex>=0))}static registerComponent(e,t){if(typeof e!="string"||!e)throw new Error(`Illegal component name, "${e}"; must be a non-empty string.`);const i=ee.getComponent("Tech"),s=i&&i.isTech(t),r=ee===t||ee.prototype.isPrototypeOf(t.prototype);if(s||!r){let o;throw s?o="techs must be registered using Tech.registerTech()":o="must be a Component subclass",new Error(`Illegal component, "${e}"; ${o}.`)}e=pt(e),ee.components_||(ee.components_={});const a=ee.getComponent("Player");if(e==="Player"&&a&&a.players){const o=a.players,c=Object.keys(o);if(o&&c.length>0){for(let l=0;l<c.length;l++)if(o[c[l]]!==null)throw new Error("Can not register Player component after player has been created.")}}return ee.components_[e]=t,ee.components_[za(e)]=t,t}static getComponent(e){if(!(!e||!ee.components_))return ee.components_[e]}}ee.registerComponent("Component",ee);function Uw(n,e,t){if(typeof e!="number"||e<0||e>t)throw new Error(`Failed to execute '${n}' on 'TimeRanges': The index provided (${e}) is non-numeric or out of bounds (0-${t}).`)}function cv(n,e,t,i){return Uw(n,i,t.length-1),t[i][e]}function Ch(n){let e;return n===void 0||n.length===0?e={length:0,start(){throw new Error("This TimeRanges object is empty")},end(){throw new Error("This TimeRanges object is empty")}}:e={length:n.length,start:cv.bind(null,"start",0,n),end:cv.bind(null,"end",1,n)},B.Symbol&&B.Symbol.iterator&&(e[B.Symbol.iterator]=()=>(n||[]).values()),e}function zi(n,e){return Array.isArray(n)?Ch(n):n===void 0||e===void 0?Ch():Ch([[n,e]])}const lv=function(n,e){n=n<0?0:n;let t=Math.floor(n%60),i=Math.floor(n/60%60),s=Math.floor(n/3600);const r=Math.floor(e/60%60),a=Math.floor(e/3600);return(isNaN(n)||n===1/0)&&(s=i=t="-"),s=s>0||a>0?s+":":"",i=((s||r>=10)&&i<10?"0"+i:i)+":",t=t<10?"0"+t:t,s+i+t};let kh=lv;function uv(n){kh=n}function dv(){kh=lv}function Fs(n,e=n){return kh(n,e)}var Bw=Object.freeze({__proto__:null,createTimeRanges:zi,createTimeRange:zi,setFormatTime:uv,resetFormatTime:dv,formatTime:Fs});function hv(n,e){let t=0,i,s;if(!e)return 0;(!n||!n.length)&&(n=zi(0,0));for(let r=0;r<n.length;r++)i=n.start(r),s=n.end(r),s>e&&(s=e),t+=s-i;return t/e}function ct(n){if(n instanceof ct)return n;typeof n=="number"?this.code=n:typeof n=="string"?this.message=n:un(n)&&(typeof n.code=="number"&&(this.code=n.code),Object.assign(this,n)),this.message||(this.message=ct.defaultMessages[this.code]||"")}ct.prototype.code=0,ct.prototype.message="",ct.prototype.status=null,ct.prototype.metadata=null,ct.errorTypes=["MEDIA_ERR_CUSTOM","MEDIA_ERR_ABORTED","MEDIA_ERR_NETWORK","MEDIA_ERR_DECODE","MEDIA_ERR_SRC_NOT_SUPPORTED","MEDIA_ERR_ENCRYPTED"],ct.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail part-way.",3:"The media playback was aborted due to a corruption problem or because the media used features your browser did not support.",4:"The media could not be loaded, either because the server or network failed or because the format is not supported.",5:"The media is encrypted and we do not have the keys to decrypt it."},ct.MEDIA_ERR_CUSTOM=0,ct.prototype.MEDIA_ERR_CUSTOM=0,ct.MEDIA_ERR_ABORTED=1,ct.prototype.MEDIA_ERR_ABORTED=1,ct.MEDIA_ERR_NETWORK=2,ct.prototype.MEDIA_ERR_NETWORK=2,ct.MEDIA_ERR_DECODE=3,ct.prototype.MEDIA_ERR_DECODE=3,ct.MEDIA_ERR_SRC_NOT_SUPPORTED=4,ct.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED=4,ct.MEDIA_ERR_ENCRYPTED=5,ct.prototype.MEDIA_ERR_ENCRYPTED=5;function Ga(n){return n!=null&&typeof n.then=="function"}function fn(n){Ga(n)&&n.then(null,e=>{})}const Eh=function(n){return["kind","label","language","id","inBandMetadataTrackDispatchType","mode","src"].reduce((t,i,s)=>(n[i]&&(t[i]=n[i]),t),{cues:n.cues&&Array.prototype.map.call(n.cues,function(t){return{startTime:t.startTime,endTime:t.endTime,text:t.text,id:t.id}})})};var xh={textTracksToJson:function(n){const e=n.$$("track"),t=Array.prototype.map.call(e,s=>s.track);return Array.prototype.map.call(e,function(s){const r=Eh(s.track);return s.src&&(r.src=s.src),r}).concat(Array.prototype.filter.call(n.textTracks(),function(s){return t.indexOf(s)===-1}).map(Eh))},jsonToTextTracks:function(n,e){return n.forEach(function(t){const i=e.addRemoteTextTrack(t).track;!t.src&&t.cues&&t.cues.forEach(s=>i.addCue(s))}),e.textTracks()},trackToJson:Eh};const wh="vjs-modal-dialog";class Pr extends ee{constructor(e,t){super(e,t),this.handleKeyDown_=i=>this.handleKeyDown(i),this.close_=i=>this.close(i),this.opened_=this.hasBeenOpened_=this.hasBeenFilled_=!1,this.closeable(!this.options_.uncloseable),this.content(this.options_.content),this.contentEl_=Ee("div",{className:`${wh}-content`},{role:"document"}),this.descEl_=Ee("p",{className:`${wh}-description vjs-control-text`,id:this.el().getAttribute("aria-describedby")}),os(this.descEl_,this.description()),this.el_.appendChild(this.descEl_),this.el_.appendChild(this.contentEl_)}createEl(){return super.createEl("div",{className:this.buildCSSClass(),tabIndex:-1},{"aria-describedby":`${this.id()}_description`,"aria-hidden":"true","aria-label":this.label(),role:"dialog","aria-live":"polite"})}dispose(){this.contentEl_=null,this.descEl_=null,this.previouslyActiveEl_=null,super.dispose()}buildCSSClass(){return`${wh} vjs-hidden ${super.buildCSSClass()}`}label(){return this.localize(this.options_.label||"Modal Window")}description(){let e=this.options_.description||this.localize("This is a modal window.");return this.closeable()&&(e+=" "+this.localize("This modal can be closed by pressing the Escape key or activating the close button.")),e}open(){if(this.opened_){this.options_.fillAlways&&this.fill();return}const e=this.player();this.trigger("beforemodalopen"),this.opened_=!0,(this.options_.fillAlways||!this.hasBeenOpened_&&!this.hasBeenFilled_)&&this.fill(),this.wasPlaying_=!e.paused(),this.options_.pauseOnOpen&&this.wasPlaying_&&e.pause(),this.on("keydown",this.handleKeyDown_),this.hadControls_=e.controls(),e.controls(!1),this.show(),this.conditionalFocus_(),this.el().setAttribute("aria-hidden","false"),this.trigger("modalopen"),this.hasBeenOpened_=!0}opened(e){return typeof e=="boolean"&&this[e?"open":"close"](),this.opened_}close(){if(!this.opened_)return;const e=this.player();this.trigger("beforemodalclose"),this.opened_=!1,this.wasPlaying_&&this.options_.pauseOnOpen&&e.play(),this.off("keydown",this.handleKeyDown_),this.hadControls_&&e.controls(!0),this.hide(),this.el().setAttribute("aria-hidden","true"),this.trigger({type:"modalclose",bubbles:!0}),this.conditionalBlur_(),this.options_.temporary&&this.dispose()}closeable(e){if(typeof e=="boolean"){const t=this.closeable_=!!e;let i=this.getChild("closeButton");if(t&&!i){const s=this.contentEl_;this.contentEl_=this.el_,i=this.addChild("closeButton",{controlText:"Close Modal Dialog"}),this.contentEl_=s,this.on(i,"close",this.close_)}!t&&i&&(this.off(i,"close",this.close_),this.removeChild(i),i.dispose())}return this.closeable_}fill(){this.fillWith(this.content())}fillWith(e){const t=this.contentEl(),i=t.parentNode,s=t.nextSibling;this.trigger("beforemodalfill"),this.hasBeenFilled_=!0,i.removeChild(t),this.empty(),Xy(t,e),this.trigger("modalfill"),s?i.insertBefore(t,s):i.appendChild(t);const r=this.getChild("closeButton");r&&i.appendChild(r.el_),this.trigger("aftermodalfill")}empty(){this.trigger("beforemodalempty"),Jc(this.contentEl()),this.trigger("modalempty")}content(e){return typeof e<"u"&&(this.content_=e),this.content_}conditionalFocus_(){const e=de.activeElement,t=this.player_.el_;this.previouslyActiveEl_=null,(t.contains(e)||t===e)&&(this.previouslyActiveEl_=e,this.focus())}conditionalBlur_(){this.previouslyActiveEl_&&(this.previouslyActiveEl_.focus(),this.previouslyActiveEl_=null)}handleKeyDown(e){if(this.trigger({type:"modalKeydown",originalEvent:e,target:this,bubbles:!0}),e.stopPropagation(),e.key==="Escape"&&this.closeable()){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;const t=this.focusableEls_(),i=this.el_.querySelector(":focus");let s;for(let r=0;r<t.length;r++)if(i===t[r]){s=r;break}de.activeElement===this.el_&&(s=0),e.shiftKey&&s===0?(t[t.length-1].focus(),e.preventDefault()):!e.shiftKey&&s===t.length-1&&(t[0].focus(),e.preventDefault())}focusableEls_(){const e=this.el_.querySelectorAll("*");return Array.prototype.filter.call(e,t=>(t instanceof B.HTMLAnchorElement||t instanceof B.HTMLAreaElement)&&t.hasAttribute("href")||(t instanceof B.HTMLInputElement||t instanceof B.HTMLSelectElement||t instanceof B.HTMLTextAreaElement||t instanceof B.HTMLButtonElement)&&!t.hasAttribute("disabled")||t instanceof B.HTMLIFrameElement||t instanceof B.HTMLObjectElement||t instanceof B.HTMLEmbedElement||t.hasAttribute("tabindex")&&t.getAttribute("tabindex")!==-1||t.hasAttribute("contenteditable"))}}Pr.prototype.options_={pauseOnOpen:!0,temporary:!0},ee.registerComponent("ModalDialog",Pr);class Us extends bi{constructor(e=[]){super(),this.tracks_=[];for(let t=0;t<e.length;t++)this.addTrack(e[t])}get length(){return this.tracks_.length}addTrack(e){const t=this.tracks_.length;""+t in this||Object.defineProperty(this,t,{get(){return this.tracks_[t]}}),this.tracks_.indexOf(e)===-1&&(this.tracks_.push(e),this.trigger({track:e,type:"addtrack",target:this})),e.labelchange_=()=>{this.trigger({track:e,type:"labelchange",target:this})},Ln(e)&&e.addEventListener("labelchange",e.labelchange_)}removeTrack(e){let t;for(let i=0,s=this.length;i<s;i++)if(this[i]===e){t=this[i],t.off&&t.off(),this.tracks_.splice(i,1);break}t&&this.trigger({track:t,type:"removetrack",target:this})}getTrackById(e){let t=null;for(let i=0,s=this.length;i<s;i++){const r=this[i];if(r.id===e){t=r;break}}return t}}Us.prototype.allowedEvents_={change:"change",addtrack:"addtrack",removetrack:"removetrack",labelchange:"labelchange"};for(const n in Us.prototype.allowedEvents_)Us.prototype["on"+n]=null;const Ah=function(n,e){for(let t=0;t<n.length;t++)!Object.keys(n[t]).length||e.id===n[t].id||(n[t].enabled=!1)};class fv extends Us{constructor(e=[]){for(let t=e.length-1;t>=0;t--)if(e[t].enabled){Ah(e,e[t]);break}super(e),this.changing_=!1}addTrack(e){e.enabled&&Ah(this,e),super.addTrack(e),e.addEventListener&&(e.enabledChange_=()=>{this.changing_||(this.changing_=!0,Ah(this,e),this.changing_=!1,this.trigger("change"))},e.addEventListener("enabledchange",e.enabledChange_))}removeTrack(e){super.removeTrack(e),e.removeEventListener&&e.enabledChange_&&(e.removeEventListener("enabledchange",e.enabledChange_),e.enabledChange_=null)}}const Dh=function(n,e){for(let t=0;t<n.length;t++)!Object.keys(n[t]).length||e.id===n[t].id||(n[t].selected=!1)};class pv extends Us{constructor(e=[]){for(let t=e.length-1;t>=0;t--)if(e[t].selected){Dh(e,e[t]);break}super(e),this.changing_=!1,Object.defineProperty(this,"selectedIndex",{get(){for(let t=0;t<this.length;t++)if(this[t].selected)return t;return-1},set(){}})}addTrack(e){e.selected&&Dh(this,e),super.addTrack(e),e.addEventListener&&(e.selectedChange_=()=>{this.changing_||(this.changing_=!0,Dh(this,e),this.changing_=!1,this.trigger("change"))},e.addEventListener("selectedchange",e.selectedChange_))}removeTrack(e){super.removeTrack(e),e.removeEventListener&&e.selectedChange_&&(e.removeEventListener("selectedchange",e.selectedChange_),e.selectedChange_=null)}}class Ph extends Us{addTrack(e){super.addTrack(e),this.queueChange_||(this.queueChange_=()=>this.queueTrigger("change")),this.triggerSelectedlanguagechange||(this.triggerSelectedlanguagechange_=()=>this.trigger("selectedlanguagechange")),e.addEventListener("modechange",this.queueChange_),["metadata","chapters"].indexOf(e.kind)===-1&&e.addEventListener("modechange",this.triggerSelectedlanguagechange_)}removeTrack(e){super.removeTrack(e),e.removeEventListener&&(this.queueChange_&&e.removeEventListener("modechange",this.queueChange_),this.selectedlanguagechange_&&e.removeEventListener("modechange",this.triggerSelectedlanguagechange_))}toJSON(){return this.tracks_.map(e=>e.toJSON())}}class qw{constructor(e=[]){this.trackElements_=[],Object.defineProperty(this,"length",{get(){return this.trackElements_.length}});for(let t=0,i=e.length;t<i;t++)this.addTrackElement_(e[t])}addTrackElement_(e){const t=this.trackElements_.length;""+t in this||Object.defineProperty(this,t,{get(){return this.trackElements_[t]}}),this.trackElements_.indexOf(e)===-1&&this.trackElements_.push(e)}getTrackElementByTrack_(e){let t;for(let i=0,s=this.trackElements_.length;i<s;i++)if(e===this.trackElements_[i].track){t=this.trackElements_[i];break}return t}removeTrackElement_(e){for(let t=0,i=this.trackElements_.length;t<i;t++)if(e===this.trackElements_[t]){this.trackElements_[t].track&&typeof this.trackElements_[t].track.off=="function"&&this.trackElements_[t].track.off(),typeof this.trackElements_[t].off=="function"&&this.trackElements_[t].off(),this.trackElements_.splice(t,1);break}}}class sl{constructor(e){sl.prototype.setCues_.call(this,e),Object.defineProperty(this,"length",{get(){return this.length_}})}setCues_(e){const t=this.length||0;let i=0;const s=e.length;this.cues_=e,this.length_=e.length;const r=function(a){""+a in this||Object.defineProperty(this,""+a,{get(){return this.cues_[a]}})};if(t<s)for(i=t;i<s;i++)r.call(this,i)}getCueById(e){let t=null;for(let i=0,s=this.length;i<s;i++){const r=this[i];if(r.id===e){t=r;break}}return t}}const Vw={alternative:"alternative",captions:"captions",main:"main",sign:"sign",subtitles:"subtitles",commentary:"commentary"},jw={alternative:"alternative",descriptions:"descriptions",main:"main","main-desc":"main-desc",translation:"translation",commentary:"commentary"},Hw={subtitles:"subtitles",captions:"captions",descriptions:"descriptions",chapters:"chapters",metadata:"metadata"},mv={disabled:"disabled",hidden:"hidden",showing:"showing"};class Ih extends bi{constructor(e={}){super();const t={id:e.id||"vjs_track_"+Di(),kind:e.kind||"",language:e.language||""};let i=e.label||"";for(const s in t)Object.defineProperty(this,s,{get(){return t[s]},set(){}});Object.defineProperty(this,"label",{get(){return i},set(s){s!==i&&(i=s,this.trigger("labelchange"))}})}}const Rh=function(n){return new URL(n,de.baseURI)},gv=function(n){return new URL(n,de.baseURI).href},Oh=function(n){if(typeof n=="string"){const t=n.split("?")[0].replace(/\/+$/,"").match(/\.([^.\/]+)$/);return t?t[1].toLowerCase():""}return""},rl=function(n,e=B.location){return Rh(n).origin!==e.origin};var $w=Object.freeze({__proto__:null,parseUrl:Rh,getAbsoluteURL:gv,getFileExtension:Oh,isCrossOrigin:rl});const yv=function(n,e){const t=new B.WebVTT.Parser(B,B.vttjs,B.WebVTT.StringDecoder()),i=[];t.oncue=function(s){e.addCue(s)},t.onparsingerror=function(s){i.push(s)},t.onflush=function(){e.trigger({type:"loadeddata",target:e})},t.parse(n),i.length>0&&(B.console&&B.console.groupCollapsed&&B.console.groupCollapsed(`Text Track parsing errors for ${e.src}`),i.forEach(s=>Oe.error(s)),B.console&&B.console.groupEnd&&B.console.groupEnd()),t.flush()},vv=function(n,e){const t={uri:n},i=rl(n);i&&(t.cors=i);const s=e.tech_.crossOrigin()==="use-credentials";s&&(t.withCredentials=s),B0(t,Ze(this,function(r,a,o){if(r)return Oe.error(r,a);e.loaded_=!0,typeof B.WebVTT!="function"?e.tech_&&e.tech_.any(["vttjsloaded","vttjserror"],c=>{if(c.type==="vttjserror"){Oe.error(`vttjs failed to load, stopping trying to process ${e.src}`);return}return yv(o,e)}):yv(o,e)}))};class Ka extends Ih{constructor(e={}){if(!e.tech)throw new Error("A tech was not provided.");const t=Qe(e,{kind:Hw[e.kind]||"subtitles",language:e.language||e.srclang||""});let i=mv[t.mode]||"disabled";const s=t.default;(t.kind==="metadata"||t.kind==="chapters")&&(i="hidden"),super(t),this.tech_=t.tech,this.cues_=[],this.activeCues_=[],this.preload_=this.tech_.preloadTextTracks!==!1;const r=new sl(this.cues_),a=new sl(this.activeCues_);let o=!1;this.timeupdateHandler=Ze(this,function(l={}){if(!this.tech_.isDisposed()){if(!this.tech_.isReady_){l.type!=="timeupdate"&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler));return}this.activeCues=this.activeCues,o&&(this.trigger("cuechange"),o=!1),l.type!=="timeupdate"&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler))}});const c=()=>{this.stopTracking()};this.tech_.one("dispose",c),i!=="disabled"&&this.startTracking(),Object.defineProperties(this,{default:{get(){return s},set(){}},mode:{get(){return i},set(l){mv[l]&&i!==l&&(i=l,!this.preload_&&i!=="disabled"&&this.cues.length===0&&vv(this.src,this),this.stopTracking(),i!=="disabled"&&this.startTracking(),this.trigger("modechange"))}},cues:{get(){return this.loaded_?r:null},set(){}},activeCues:{get(){if(!this.loaded_)return null;if(this.cues.length===0)return a;const l=this.tech_.currentTime(),u=[];for(let h=0,p=this.cues.length;h<p;h++){const y=this.cues[h];y.startTime<=l&&y.endTime>=l&&u.push(y)}if(o=!1,u.length!==this.activeCues_.length)o=!0;else for(let h=0;h<u.length;h++)this.activeCues_.indexOf(u[h])===-1&&(o=!0);return this.activeCues_=u,a.setCues_(this.activeCues_),a},set(){}}}),t.src?(this.src=t.src,this.preload_||(this.loaded_=!0),(this.preload_||t.kind!=="subtitles"&&t.kind!=="captions")&&vv(this.src,this)):this.loaded_=!0}startTracking(){this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler),this.tech_.on("timeupdate",this.timeupdateHandler)}stopTracking(){this.rvf_&&(this.tech_.cancelVideoFrameCallback(this.rvf_),this.rvf_=void 0),this.tech_.off("timeupdate",this.timeupdateHandler)}addCue(e){let t=e;if(!("getCueAsHTML"in t)){t=new B.vttjs.VTTCue(e.startTime,e.endTime,e.text);for(const s in e)s in t||(t[s]=e[s]);t.id=e.id,t.originalCue_=e}const i=this.tech_.textTracks();for(let s=0;s<i.length;s++)i[s]!==this&&i[s].removeCue(t);this.cues_.push(t),this.cues.setCues_(this.cues_)}toJSON(){return xh.trackToJson(this)}removeCue(e){let t=this.cues_.length;for(;t--;){const i=this.cues_[t];if(i===e||i.originalCue_&&i.originalCue_===e){this.cues_.splice(t,1),this.cues.setCues_(this.cues_);break}}}}Ka.prototype.allowedEvents_={cuechange:"cuechange"};class bv extends Ih{constructor(e={}){const t=Qe(e,{kind:jw[e.kind]||""});super(t);let i=!1;Object.defineProperty(this,"enabled",{get(){return i},set(s){typeof s!="boolean"||s===i||(i=s,this.trigger("enabledchange"))}}),t.enabled&&(this.enabled=t.enabled),this.loaded_=!0}}class Tv extends Ih{constructor(e={}){const t=Qe(e,{kind:Vw[e.kind]||""});super(t);let i=!1;Object.defineProperty(this,"selected",{get(){return i},set(s){typeof s!="boolean"||s===i||(i=s,this.trigger("selectedchange"))}}),t.selected&&(this.selected=t.selected)}}class Nn extends bi{constructor(e={}){super();let t;const i=new Ka(e);this.kind=i.kind,this.src=i.src,this.srclang=i.language,this.label=i.label,this.default=i.default,Object.defineProperties(this,{readyState:{get(){return t}},track:{get(){return i}}}),t=Nn.NONE,i.addEventListener("loadeddata",()=>{t=Nn.LOADED,this.trigger({type:"load",target:this})})}}Nn.prototype.allowedEvents_={load:"load"},Nn.NONE=0,Nn.LOADING=1,Nn.LOADED=2,Nn.ERROR=3;const Ii={audio:{ListClass:fv,TrackClass:bv,capitalName:"Audio"},video:{ListClass:pv,TrackClass:Tv,capitalName:"Video"},text:{ListClass:Ph,TrackClass:Ka,capitalName:"Text"}};Object.keys(Ii).forEach(function(n){Ii[n].getterName=`${n}Tracks`,Ii[n].privateName=`${n}Tracks_`});const Ir={remoteText:{ListClass:Ph,TrackClass:Ka,capitalName:"RemoteText",getterName:"remoteTextTracks",privateName:"remoteTextTracks_"},remoteTextEl:{ListClass:qw,TrackClass:Nn,capitalName:"RemoteTextTrackEls",getterName:"remoteTextTrackEls",privateName:"remoteTextTrackEls_"}},ti=Object.assign({},Ii,Ir);Ir.names=Object.keys(Ir),Ii.names=Object.keys(Ii),ti.names=[].concat(Ir.names).concat(Ii.names);function Ww(n,e,t,i,s={}){const r=n.textTracks();s.kind=e,t&&(s.label=t),i&&(s.language=i),s.tech=n;const a=new ti.text.TrackClass(s);return r.addTrack(a),a}class De extends ee{constructor(e={},t=function(){}){e.reportTouchActivity=!1,super(null,e,t),this.onDurationChange_=i=>this.onDurationChange(i),this.trackProgress_=i=>this.trackProgress(i),this.trackCurrentTime_=i=>this.trackCurrentTime(i),this.stopTrackingCurrentTime_=i=>this.stopTrackingCurrentTime(i),this.disposeSourceHandler_=i=>this.disposeSourceHandler(i),this.queuedHanders_=new Set,this.hasStarted_=!1,this.on("playing",function(){this.hasStarted_=!0}),this.on("loadstart",function(){this.hasStarted_=!1}),ti.names.forEach(i=>{const s=ti[i];e&&e[s.getterName]&&(this[s.privateName]=e[s.getterName])}),this.featuresProgressEvents||this.manualProgressOn(),this.featuresTimeupdateEvents||this.manualTimeUpdatesOn(),["Text","Audio","Video"].forEach(i=>{e[`native${i}Tracks`]===!1&&(this[`featuresNative${i}Tracks`]=!1)}),e.nativeCaptions===!1||e.nativeTextTracks===!1?this.featuresNativeTextTracks=!1:(e.nativeCaptions===!0||e.nativeTextTracks===!0)&&(this.featuresNativeTextTracks=!0),this.featuresNativeTextTracks||this.emulateTextTracks(),this.preloadTextTracks=e.preloadTextTracks!==!1,this.autoRemoteTextTracks_=new ti.text.ListClass,this.initTrackListeners(),e.nativeControlsForTouch||this.emitTapEvents(),this.constructor&&(this.name_=this.constructor.name||"Unknown Tech")}triggerSourceset(e){this.isReady_||this.one("ready",()=>this.setTimeout(()=>this.triggerSourceset(e),1)),this.trigger({src:e,type:"sourceset"})}manualProgressOn(){this.on("durationchange",this.onDurationChange_),this.manualProgress=!0,this.one("ready",this.trackProgress_)}manualProgressOff(){this.manualProgress=!1,this.stopTrackingProgress(),this.off("durationchange",this.onDurationChange_)}trackProgress(e){this.stopTrackingProgress(),this.progressInterval=this.setInterval(Ze(this,function(){const t=this.bufferedPercent();this.bufferedPercent_!==t&&this.trigger("progress"),this.bufferedPercent_=t,t===1&&this.stopTrackingProgress()}),500)}onDurationChange(e){this.duration_=this.duration()}buffered(){return zi(0,0)}bufferedPercent(){return hv(this.buffered(),this.duration_)}stopTrackingProgress(){this.clearInterval(this.progressInterval)}manualTimeUpdatesOn(){this.manualTimeUpdates=!0,this.on("play",this.trackCurrentTime_),this.on("pause",this.stopTrackingCurrentTime_)}manualTimeUpdatesOff(){this.manualTimeUpdates=!1,this.stopTrackingCurrentTime(),this.off("play",this.trackCurrentTime_),this.off("pause",this.stopTrackingCurrentTime_)}trackCurrentTime(){this.currentTimeInterval&&this.stopTrackingCurrentTime(),this.currentTimeInterval=this.setInterval(function(){this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})},250)}stopTrackingCurrentTime(){this.clearInterval(this.currentTimeInterval),this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}dispose(){this.clearTracks(Ii.names),this.manualProgress&&this.manualProgressOff(),this.manualTimeUpdates&&this.manualTimeUpdatesOff(),super.dispose()}clearTracks(e){e=[].concat(e),e.forEach(t=>{const i=this[`${t}Tracks`]()||[];let s=i.length;for(;s--;){const r=i[s];t==="text"&&this.removeRemoteTextTrack(r),i.removeTrack(r)}})}cleanupAutoTextTracks(){const e=this.autoRemoteTextTracks_||[];let t=e.length;for(;t--;){const i=e[t];this.removeRemoteTextTrack(i)}}reset(){}crossOrigin(){}setCrossOrigin(){}error(e){return e!==void 0&&(this.error_=new ct(e),this.trigger("error")),this.error_}played(){return this.hasStarted_?zi(0,0):zi()}play(){}setScrubbing(e){}scrubbing(){}setCurrentTime(e){this.manualTimeUpdates&&this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}initTrackListeners(){Ii.names.forEach(e=>{const t=Ii[e],i=()=>{this.trigger(`${e}trackchange`)},s=this[t.getterName]();s.addEventListener("removetrack",i),s.addEventListener("addtrack",i),this.on("dispose",()=>{s.removeEventListener("removetrack",i),s.removeEventListener("addtrack",i)})})}addWebVttScript_(){if(!B.WebVTT)if(de.body.contains(this.el())){if(!this.options_["vtt.js"]&&Sr($0)&&Object.keys($0).length>0){this.trigger("vttjsloaded");return}const e=de.createElement("script");e.src=this.options_["vtt.js"]||"https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js",e.onload=()=>{this.trigger("vttjsloaded")},e.onerror=()=>{this.trigger("vttjserror")},this.on("dispose",()=>{e.onload=null,e.onerror=null}),B.WebVTT=!0,this.el().parentNode.appendChild(e)}else this.ready(this.addWebVttScript_)}emulateTextTracks(){const e=this.textTracks(),t=this.remoteTextTracks(),i=o=>e.addTrack(o.track),s=o=>e.removeTrack(o.track);t.on("addtrack",i),t.on("removetrack",s),this.addWebVttScript_();const r=()=>this.trigger("texttrackchange"),a=()=>{r();for(let o=0;o<e.length;o++){const c=e[o];c.removeEventListener("cuechange",r),c.mode==="showing"&&c.addEventListener("cuechange",r)}};a(),e.addEventListener("change",a),e.addEventListener("addtrack",a),e.addEventListener("removetrack",a),this.on("dispose",function(){t.off("addtrack",i),t.off("removetrack",s),e.removeEventListener("change",a),e.removeEventListener("addtrack",a),e.removeEventListener("removetrack",a);for(let o=0;o<e.length;o++)e[o].removeEventListener("cuechange",r)})}addTextTrack(e,t,i){if(!e)throw new Error("TextTrack kind is required but was not provided");return Ww(this,e,t,i)}createRemoteTextTrack(e){const t=Qe(e,{tech:this});return new Ir.remoteTextEl.TrackClass(t)}addRemoteTextTrack(e={},t){const i=this.createRemoteTextTrack(e);return typeof t!="boolean"&&(t=!1),this.remoteTextTrackEls().addTrackElement_(i),this.remoteTextTracks().addTrack(i.track),t===!1&&this.ready(()=>this.autoRemoteTextTracks_.addTrack(i.track)),i}removeRemoteTextTrack(e){const t=this.remoteTextTrackEls().getTrackElementByTrack_(e);this.remoteTextTrackEls().removeTrackElement_(t),this.remoteTextTracks().removeTrack(e),this.autoRemoteTextTracks_.removeTrack(e)}getVideoPlaybackQuality(){return{}}requestPictureInPicture(){return Promise.reject()}disablePictureInPicture(){return!0}setDisablePictureInPicture(){}requestVideoFrameCallback(e){const t=Di();return!this.isReady_||this.paused()?(this.queuedHanders_.add(t),this.one("playing",()=>{this.queuedHanders_.has(t)&&(this.queuedHanders_.delete(t),e())})):this.requestNamedAnimationFrame(t,e),t}cancelVideoFrameCallback(e){this.queuedHanders_.has(e)?this.queuedHanders_.delete(e):this.cancelNamedAnimationFrame(e)}setPoster(){}playsinline(){}setPlaysinline(){}overrideNativeAudioTracks(e){}overrideNativeVideoTracks(e){}canPlayType(e){return""}static canPlayType(e){return""}static canPlaySource(e,t){return De.canPlayType(e.type)}static isTech(e){return e.prototype instanceof De||e instanceof De||e===De}static registerTech(e,t){if(De.techs_||(De.techs_={}),!De.isTech(t))throw new Error(`Tech ${e} must be a Tech`);if(!De.canPlayType)throw new Error("Techs must have a static canPlayType method on them");if(!De.canPlaySource)throw new Error("Techs must have a static canPlaySource method on them");return e=pt(e),De.techs_[e]=t,De.techs_[za(e)]=t,e!=="Tech"&&De.defaultTechOrder_.push(e),t}static getTech(e){if(e){if(De.techs_&&De.techs_[e])return De.techs_[e];if(e=pt(e),B&&B.videojs&&B.videojs[e])return Oe.warn(`The ${e} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`),B.videojs[e]}}}ti.names.forEach(function(n){const e=ti[n];De.prototype[e.getterName]=function(){return this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName]}}),De.prototype.featuresVolumeControl=!0,De.prototype.featuresMuteControl=!0,De.prototype.featuresFullscreenResize=!1,De.prototype.featuresPlaybackRate=!1,De.prototype.featuresProgressEvents=!1,De.prototype.featuresSourceset=!1,De.prototype.featuresTimeupdateEvents=!1,De.prototype.featuresNativeTextTracks=!1,De.prototype.featuresVideoFrameCallback=!1,De.withSourceHandlers=function(n){n.registerSourceHandler=function(t,i){let s=n.sourceHandlers;s||(s=n.sourceHandlers=[]),i===void 0&&(i=s.length),s.splice(i,0,t)},n.canPlayType=function(t){const i=n.sourceHandlers||[];let s;for(let r=0;r<i.length;r++)if(s=i[r].canPlayType(t),s)return s;return""},n.selectSourceHandler=function(t,i){const s=n.sourceHandlers||[];let r;for(let a=0;a<s.length;a++)if(r=s[a].canHandleSource(t,i),r)return s[a];return null},n.canPlaySource=function(t,i){const s=n.selectSourceHandler(t,i);return s?s.canHandleSource(t,i):""},["seekable","seeking","duration"].forEach(function(t){const i=this[t];typeof i=="function"&&(this[t]=function(){return this.sourceHandler_&&this.sourceHandler_[t]?this.sourceHandler_[t].apply(this.sourceHandler_,arguments):i.apply(this,arguments)})},n.prototype),n.prototype.setSource=function(t){let i=n.selectSourceHandler(t,this.options_);i||(n.nativeSourceHandler?i=n.nativeSourceHandler:Oe.error("No source handler found for the current source.")),this.disposeSourceHandler(),this.off("dispose",this.disposeSourceHandler_),i!==n.nativeSourceHandler&&(this.currentSource_=t),this.sourceHandler_=i.handleSource(t,this,this.options_),this.one("dispose",this.disposeSourceHandler_)},n.prototype.disposeSourceHandler=function(){this.currentSource_&&(this.clearTracks(["audio","video"]),this.currentSource_=null),this.cleanupAutoTextTracks(),this.sourceHandler_&&(this.sourceHandler_.dispose&&this.sourceHandler_.dispose(),this.sourceHandler_=null)}},ee.registerComponent("Tech",De),De.registerTech("Tech",De),De.defaultTechOrder_=[];const Bs={},al={},ol={};function zw(n,e){Bs[n]=Bs[n]||[],Bs[n].push(e)}function Gw(n,e,t){n.setTimeout(()=>qs(e,Bs[e.type],t,n),1)}function Kw(n,e){n.forEach(t=>t.setTech&&t.setTech(e))}function Xw(n,e,t){return n.reduceRight(Mh(t),e[t]())}function Yw(n,e,t,i){return e[t](n.reduce(Mh(t),i))}function _v(n,e,t,i=null){const s="call"+pt(t),r=n.reduce(Mh(s),i),a=r===ol,o=a?null:e[t](r);return Zw(n,t,o,a),o}const Qw={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1,ended:1},Jw={setCurrentTime:1,setMuted:1,setVolume:1},Sv={play:1,pause:1};function Mh(n){return(e,t)=>e===ol?ol:t[n]?t[n](e):e}function Zw(n,e,t,i){for(let s=n.length-1;s>=0;s--){const r=n[s];r[e]&&r[e](i,t)}}function eA(n){al.hasOwnProperty(n.id())&&delete al[n.id()]}function tA(n,e){const t=al[n.id()];let i=null;if(t==null)return i=e(n),al[n.id()]=[[e,i]],i;for(let s=0;s<t.length;s++){const[r,a]=t[s];r===e&&(i=a)}return i===null&&(i=e(n),t.push([e,i])),i}function qs(n={},e=[],t,i,s=[],r=!1){const[a,...o]=e;if(typeof a=="string")qs(n,Bs[a],t,i,s,r);else if(a){const c=tA(i,a);if(!c.setSource)return s.push(c),qs(n,o,t,i,s,r);c.setSource(Object.assign({},n),function(l,u){if(l)return qs(n,o,t,i,s,r);s.push(c),qs(u,n.type===u.type?o:Bs[u.type],t,i,s,r)})}else o.length?qs(n,o,t,i,s,r):r?t(n,s):qs(n,Bs["*"],t,i,s,!0)}const iA={opus:"video/ogg",ogv:"video/ogg",mp4:"video/mp4",mov:"video/mp4",m4v:"video/mp4",mkv:"video/x-matroska",m4a:"audio/mp4",mp3:"audio/mpeg",aac:"audio/aac",caf:"audio/x-caf",flac:"audio/flac",oga:"audio/ogg",wav:"audio/wav",m3u8:"application/x-mpegURL",mpd:"application/dash+xml",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",png:"image/png",svg:"image/svg+xml",webp:"image/webp"},cl=function(n=""){const e=Oh(n);return iA[e.toLowerCase()]||""},nA=(n,e)=>{if(!e)return"";if(n.cache_.source.src===e&&n.cache_.source.type)return n.cache_.source.type;const t=n.cache_.sources.filter(s=>s.src===e);if(t.length)return t[0].type;const i=n.$$("source");for(let s=0;s<i.length;s++){const r=i[s];if(r.type&&r.src&&r.src===e)return r.type}return cl(e)},Cv=function(n){if(Array.isArray(n)){let e=[];n.forEach(function(t){t=Cv(t),Array.isArray(t)?e=e.concat(t):un(t)&&e.push(t)}),n=e}else typeof n=="string"&&n.trim()?n=[kv({src:n})]:un(n)&&typeof n.src=="string"&&n.src&&n.src.trim()?n=[kv(n)]:n=[];return n};function kv(n){if(!n.type){const e=cl(n.src);e&&(n.type=e)}return n}var sA=`<svg xmlns="http://www.w3.org/2000/svg">
|
|
82
|
+
<defs>
|
|
83
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-play">
|
|
84
|
+
<path d="M16 10v28l22-14z"></path>
|
|
85
|
+
</symbol>
|
|
86
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-pause">
|
|
87
|
+
<path d="M12 38h8V10h-8v28zm16-28v28h8V10h-8z"></path>
|
|
88
|
+
</symbol>
|
|
89
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-audio">
|
|
90
|
+
<path d="M24 2C14.06 2 6 10.06 6 20v14c0 3.31 2.69 6 6 6h6V24h-8v-4c0-7.73 6.27-14 14-14s14 6.27 14 14v4h-8v16h6c3.31 0 6-2.69 6-6V20c0-9.94-8.06-18-18-18z"></path>
|
|
91
|
+
</symbol>
|
|
92
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-captions">
|
|
93
|
+
<path d="M38 8H10c-2.21 0-4 1.79-4 4v24c0 2.21 1.79 4 4 4h28c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zM22 22h-3v-1h-4v6h4v-1h3v2a2 2 0 0 1-2 2h-6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2zm14 0h-3v-1h-4v6h4v-1h3v2a2 2 0 0 1-2 2h-6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2z"></path>
|
|
94
|
+
</symbol>
|
|
95
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-subtitles">
|
|
96
|
+
<path d="M40 8H8c-2.21 0-4 1.79-4 4v24c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zM8 24h8v4H8v-4zm20 12H8v-4h20v4zm12 0h-8v-4h8v4zm0-8H20v-4h20v4z"></path>
|
|
97
|
+
</symbol>
|
|
98
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-fullscreen-enter">
|
|
99
|
+
<path d="M14 28h-4v10h10v-4h-6v-6zm-4-8h4v-6h6v-4H10v10zm24 14h-6v4h10V28h-4v6zm-6-24v4h6v6h4V10H28z"></path>
|
|
100
|
+
</symbol>
|
|
101
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-fullscreen-exit">
|
|
102
|
+
<path d="M10 32h6v6h4V28H10v4zm6-16h-6v4h10V10h-4v6zm12 22h4v-6h6v-4H28v10zm4-22v-6h-4v10h10v-4h-6z"></path>
|
|
103
|
+
</symbol>
|
|
104
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-play-circle">
|
|
105
|
+
<path d="M20 33l12-9-12-9v18zm4-29C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm0 36c-8.82 0-16-7.18-16-16S15.18 8 24 8s16 7.18 16 16-7.18 16-16 16z"></path>
|
|
106
|
+
</symbol>
|
|
107
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-volume-mute">
|
|
108
|
+
<path d="M33 24c0-3.53-2.04-6.58-5-8.05v4.42l4.91 4.91c.06-.42.09-.85.09-1.28zm5 0c0 1.88-.41 3.65-1.08 5.28l3.03 3.03C41.25 29.82 42 27 42 24c0-8.56-5.99-15.72-14-17.54v4.13c5.78 1.72 10 7.07 10 13.41zM8.55 6L6 8.55 15.45 18H6v12h8l10 10V26.55l8.51 8.51c-1.34 1.03-2.85 1.86-4.51 2.36v4.13a17.94 17.94 0 0 0 7.37-3.62L39.45 42 42 39.45l-18-18L8.55 6zM24 8l-4.18 4.18L24 16.36V8z"></path>
|
|
109
|
+
</symbol>
|
|
110
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-volume-low">
|
|
111
|
+
<path d="M14 18v12h8l10 10V8L22 18h-8z"></path>
|
|
112
|
+
</symbol>
|
|
113
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-volume-medium">
|
|
114
|
+
<path d="M37 24c0-3.53-2.04-6.58-5-8.05v16.11c2.96-1.48 5-4.53 5-8.06zm-27-6v12h8l10 10V8L18 18h-8z"></path>
|
|
115
|
+
</symbol>
|
|
116
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-volume-high">
|
|
117
|
+
<path d="M6 18v12h8l10 10V8L14 18H6zm27 6c0-3.53-2.04-6.58-5-8.05v16.11c2.96-1.48 5-4.53 5-8.06zM28 6.46v4.13c5.78 1.72 10 7.07 10 13.41s-4.22 11.69-10 13.41v4.13c8.01-1.82 14-8.97 14-17.54S36.01 8.28 28 6.46z"></path>
|
|
118
|
+
</symbol>
|
|
119
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-spinner">
|
|
120
|
+
<path d="M18.8 21l9.53-16.51C26.94 4.18 25.49 4 24 4c-4.8 0-9.19 1.69-12.64 4.51l7.33 12.69.11-.2zm24.28-3c-1.84-5.85-6.3-10.52-11.99-12.68L23.77 18h19.31zm.52 2H28.62l.58 1 9.53 16.5C41.99 33.94 44 29.21 44 24c0-1.37-.14-2.71-.4-4zm-26.53 4l-7.8-13.5C6.01 14.06 4 18.79 4 24c0 1.37.14 2.71.4 4h14.98l-2.31-4zM4.92 30c1.84 5.85 6.3 10.52 11.99 12.68L24.23 30H4.92zm22.54 0l-7.8 13.51c1.4.31 2.85.49 4.34.49 4.8 0 9.19-1.69 12.64-4.51L29.31 26.8 27.46 30z"></path>
|
|
121
|
+
</symbol>
|
|
122
|
+
<symbol viewBox="0 0 24 24" id="vjs-icon-hd">
|
|
123
|
+
<path d="M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-8 12H9.5v-2h-2v2H6V9h1.5v2.5h2V9H11v6zm2-6h4c.55 0 1 .45 1 1v4c0 .55-.45 1-1 1h-4V9zm1.5 4.5h2v-3h-2v3z"></path>
|
|
124
|
+
</symbol>
|
|
125
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-chapters">
|
|
126
|
+
<path d="M6 26h4v-4H6v4zm0 8h4v-4H6v4zm0-16h4v-4H6v4zm8 8h28v-4H14v4zm0 8h28v-4H14v4zm0-20v4h28v-4H14z"></path>
|
|
127
|
+
</symbol>
|
|
128
|
+
<symbol viewBox="0 0 40 40" id="vjs-icon-downloading">
|
|
129
|
+
<path d="M18.208 36.875q-3.208-.292-5.979-1.729-2.771-1.438-4.812-3.729-2.042-2.292-3.188-5.229-1.146-2.938-1.146-6.23 0-6.583 4.334-11.416 4.333-4.834 10.833-5.5v3.166q-5.167.75-8.583 4.646Q6.25 14.75 6.25 19.958q0 5.209 3.396 9.104 3.396 3.896 8.562 4.646zM20 28.417L11.542 20l2.083-2.083 4.917 4.916v-11.25h2.916v11.25l4.875-4.916L28.417 20zm1.792 8.458v-3.167q1.833-.25 3.541-.958 1.709-.708 3.167-1.875l2.333 2.292q-1.958 1.583-4.25 2.541-2.291.959-4.791 1.167zm6.791-27.792q-1.541-1.125-3.25-1.854-1.708-.729-3.541-1.021V3.042q2.5.25 4.77 1.208 2.271.958 4.271 2.5zm4.584 21.584l-2.25-2.25q1.166-1.5 1.854-3.209.687-1.708.937-3.541h3.209q-.292 2.5-1.229 4.791-.938 2.292-2.521 4.209zm.541-12.417q-.291-1.833-.958-3.562-.667-1.73-1.833-3.188l2.375-2.208q1.541 1.916 2.458 4.208.917 2.292 1.167 4.75z"></path>
|
|
130
|
+
</symbol>
|
|
131
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-file-download">
|
|
132
|
+
<path d="M10.8 40.55q-1.35 0-2.375-1T7.4 37.15v-7.7h3.4v7.7h26.35v-7.7h3.4v7.7q0 1.4-1 2.4t-2.4 1zM24 32.1L13.9 22.05l2.45-2.45 5.95 5.95V7.15h3.4v18.4l5.95-5.95 2.45 2.45z"></path>
|
|
133
|
+
</symbol>
|
|
134
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-file-download-done">
|
|
135
|
+
<path d="M9.8 40.5v-3.45h28.4v3.45zm9.2-9.05L7.4 19.85l2.45-2.35L19 26.65l19.2-19.2 2.4 2.4z"></path>
|
|
136
|
+
</symbol>
|
|
137
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-file-download-off">
|
|
138
|
+
<path d="M4.9 4.75L43.25 43.1 41 45.3l-4.75-4.75q-.05.05-.075.025-.025-.025-.075-.025H10.8q-1.35 0-2.375-1T7.4 37.15v-7.7h3.4v7.7h22.05l-7-7-1.85 1.8L13.9 21.9l1.85-1.85L2.7 7zm26.75 14.7l2.45 2.45-3.75 3.8-2.45-2.5zM25.7 7.15V21.1l-3.4-3.45V7.15z"></path>
|
|
139
|
+
</symbol>
|
|
140
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-share">
|
|
141
|
+
<path d="M36 32.17c-1.52 0-2.89.59-3.93 1.54L17.82 25.4c.11-.45.18-.92.18-1.4s-.07-.95-.18-1.4l14.1-8.23c1.07 1 2.5 1.62 4.08 1.62 3.31 0 6-2.69 6-6s-2.69-6-6-6-6 2.69-6 6c0 .48.07.95.18 1.4l-14.1 8.23c-1.07-1-2.5-1.62-4.08-1.62-3.31 0-6 2.69-6 6s2.69 6 6 6c1.58 0 3.01-.62 4.08-1.62l14.25 8.31c-.1.42-.16.86-.16 1.31A5.83 5.83 0 1 0 36 32.17z"></path>
|
|
142
|
+
</symbol>
|
|
143
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-cog">
|
|
144
|
+
<path d="M38.86 25.95c.08-.64.14-1.29.14-1.95s-.06-1.31-.14-1.95l4.23-3.31c.38-.3.49-.84.24-1.28l-4-6.93c-.25-.43-.77-.61-1.22-.43l-4.98 2.01c-1.03-.79-2.16-1.46-3.38-1.97L29 4.84c-.09-.47-.5-.84-1-.84h-8c-.5 0-.91.37-.99.84l-.75 5.3a14.8 14.8 0 0 0-3.38 1.97L9.9 10.1a1 1 0 0 0-1.22.43l-4 6.93c-.25.43-.14.97.24 1.28l4.22 3.31C9.06 22.69 9 23.34 9 24s.06 1.31.14 1.95l-4.22 3.31c-.38.3-.49.84-.24 1.28l4 6.93c.25.43.77.61 1.22.43l4.98-2.01c1.03.79 2.16 1.46 3.38 1.97l.75 5.3c.08.47.49.84.99.84h8c.5 0 .91-.37.99-.84l.75-5.3a14.8 14.8 0 0 0 3.38-1.97l4.98 2.01a1 1 0 0 0 1.22-.43l4-6.93c.25-.43.14-.97-.24-1.28l-4.22-3.31zM24 31c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"></path>
|
|
145
|
+
</symbol>
|
|
146
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-square">
|
|
147
|
+
<path d="M36 8H12c-2.21 0-4 1.79-4 4v24c0 2.21 1.79 4 4 4h24c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zm0 28H12V12h24v24z"></path>
|
|
148
|
+
</symbol>
|
|
149
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-circle">
|
|
150
|
+
<circle cx="24" cy="24" r="20"></circle>
|
|
151
|
+
</symbol>
|
|
152
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-circle-outline">
|
|
153
|
+
<path d="M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm0 36c-8.82 0-16-7.18-16-16S15.18 8 24 8s16 7.18 16 16-7.18 16-16 16z"></path>
|
|
154
|
+
</symbol>
|
|
155
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-circle-inner-circle">
|
|
156
|
+
<path d="M24 4C12.97 4 4 12.97 4 24s8.97 20 20 20 20-8.97 20-20S35.03 4 24 4zm0 36c-8.82 0-16-7.18-16-16S15.18 8 24 8s16 7.18 16 16-7.18 16-16 16zm6-16c0 3.31-2.69 6-6 6s-6-2.69-6-6 2.69-6 6-6 6 2.69 6 6z"></path>
|
|
157
|
+
</symbol>
|
|
158
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-cancel">
|
|
159
|
+
<path d="M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm10 27.17L31.17 34 24 26.83 16.83 34 14 31.17 21.17 24 14 16.83 16.83 14 24 21.17 31.17 14 34 16.83 26.83 24 34 31.17z"></path>
|
|
160
|
+
</symbol>
|
|
161
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-replay">
|
|
162
|
+
<path d="M24 10V2L14 12l10 10v-8c6.63 0 12 5.37 12 12s-5.37 12-12 12-12-5.37-12-12H8c0 8.84 7.16 16 16 16s16-7.16 16-16-7.16-16-16-16z"></path>
|
|
163
|
+
</symbol>
|
|
164
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-repeat">
|
|
165
|
+
<path d="M14 14h20v6l8-8-8-8v6H10v12h4v-8zm20 20H14v-6l-8 8 8 8v-6h24V26h-4v8z"></path>
|
|
166
|
+
</symbol>
|
|
167
|
+
<symbol viewBox="0 96 48 48" id="vjs-icon-replay-5">
|
|
168
|
+
<path d="M17.689 98l-8.697 8.696 8.697 8.697 2.486-2.485-4.32-4.319h1.302c4.93 0 9.071 1.722 12.424 5.165 3.352 3.443 5.029 7.638 5.029 12.584h3.55c0-2.958-.553-5.73-1.658-8.313-1.104-2.583-2.622-4.841-4.555-6.774-1.932-1.932-4.19-3.45-6.773-4.555-2.584-1.104-5.355-1.657-8.313-1.657H15.5l4.615-4.615zm-8.08 21.659v13.861h11.357v5.008H9.609V143h12.7c.834 0 1.55-.298 2.146-.894.596-.597.895-1.31.895-2.145v-7.781c0-.835-.299-1.55-.895-2.147a2.929 2.929 0 0 0-2.147-.894h-8.227v-5.096H25.35v-4.384z"></path>
|
|
169
|
+
</symbol>
|
|
170
|
+
<symbol viewBox="0 96 48 48" id="vjs-icon-replay-10">
|
|
171
|
+
<path d="M42.315 125.63c0-4.997-1.694-9.235-5.08-12.713-3.388-3.479-7.571-5.218-12.552-5.218h-1.315l4.363 4.363-2.51 2.51-8.787-8.786L25.221 97l2.45 2.45-4.662 4.663h1.375c2.988 0 5.788.557 8.397 1.673 2.61 1.116 4.892 2.65 6.844 4.602 1.953 1.953 3.487 4.234 4.602 6.844 1.116 2.61 1.674 5.41 1.674 8.398zM8.183 142v-19.657H3.176V117.8h9.643V142zm13.63 0c-1.156 0-2.127-.393-2.912-1.178-.778-.778-1.168-1.746-1.168-2.902v-16.04c0-1.156.393-2.127 1.178-2.912.779-.779 1.746-1.168 2.902-1.168h7.696c1.156 0 2.126.392 2.911 1.177.779.78 1.168 1.747 1.168 2.903v16.04c0 1.156-.392 2.127-1.177 2.912-.779.779-1.746 1.168-2.902 1.168zm.556-4.636h6.583v-15.02H22.37z"></path>
|
|
172
|
+
</symbol>
|
|
173
|
+
<symbol viewBox="0 96 48 48" id="vjs-icon-replay-30">
|
|
174
|
+
<path d="M26.047 97l-8.733 8.732 8.733 8.733 2.496-2.494-4.336-4.338h1.307c4.95 0 9.108 1.73 12.474 5.187 3.367 3.458 5.051 7.668 5.051 12.635h3.565c0-2.97-.556-5.751-1.665-8.346-1.109-2.594-2.633-4.862-4.574-6.802-1.94-1.941-4.208-3.466-6.803-4.575-2.594-1.109-5.375-1.664-8.345-1.664H23.85l4.634-4.634zM2.555 117.531v4.688h10.297v5.25H5.873v4.687h6.979v5.156H2.555V142H13.36c1.061 0 1.95-.395 2.668-1.186.718-.79 1.076-1.772 1.076-2.94v-16.218c0-1.168-.358-2.149-1.076-2.94-.717-.79-1.607-1.185-2.668-1.185zm22.482.14c-1.149 0-2.11.39-2.885 1.165-.78.78-1.172 1.744-1.172 2.893v15.943c0 1.149.388 2.11 1.163 2.885.78.78 1.745 1.172 2.894 1.172h7.649c1.148 0 2.11-.388 2.884-1.163.78-.78 1.17-1.745 1.17-2.894v-15.943c0-1.15-.386-2.111-1.16-2.885-.78-.78-1.746-1.172-2.894-1.172zm.553 4.518h6.545v14.93H25.59z"></path>
|
|
175
|
+
</symbol>
|
|
176
|
+
<symbol viewBox="0 96 48 48" id="vjs-icon-forward-5">
|
|
177
|
+
<path d="M29.508 97l-2.431 2.43 4.625 4.625h-1.364c-2.965 0-5.742.554-8.332 1.66-2.589 1.107-4.851 2.629-6.788 4.566-1.937 1.937-3.458 4.2-4.565 6.788-1.107 2.59-1.66 5.367-1.66 8.331h3.557c0-4.957 1.68-9.16 5.04-12.611 3.36-3.45 7.51-5.177 12.451-5.177h1.304l-4.326 4.33 2.49 2.49 8.715-8.716zm-9.783 21.61v13.89h11.382v5.018H19.725V142h12.727a2.93 2.93 0 0 0 2.15-.896 2.93 2.93 0 0 0 .896-2.15v-7.798c0-.837-.299-1.554-.896-2.152a2.93 2.93 0 0 0-2.15-.896h-8.245V123h11.29v-4.392z"></path>
|
|
178
|
+
</symbol>
|
|
179
|
+
<symbol viewBox="0 96 48 48" id="vjs-icon-forward-10">
|
|
180
|
+
<path d="M23.119 97l-2.386 2.383 4.538 4.538h-1.339c-2.908 0-5.633.543-8.173 1.63-2.54 1.085-4.76 2.577-6.66 4.478-1.9 1.9-3.392 4.12-4.478 6.66-1.085 2.54-1.629 5.264-1.629 8.172h3.49c0-4.863 1.648-8.986 4.944-12.372 3.297-3.385 7.368-5.078 12.216-5.078h1.279l-4.245 4.247 2.443 2.442 8.55-8.55zm-9.52 21.45v4.42h4.871V142h4.513v-23.55zm18.136 0c-1.125 0-2.066.377-2.824 1.135-.764.764-1.148 1.709-1.148 2.834v15.612c0 1.124.38 2.066 1.139 2.824.764.764 1.708 1.145 2.833 1.145h7.489c1.125 0 2.066-.378 2.824-1.136.764-.764 1.145-1.709 1.145-2.833v-15.612c0-1.125-.378-2.067-1.136-2.825-.764-.764-1.708-1.145-2.833-1.145zm.54 4.42h6.408v14.617h-6.407z"></path>
|
|
181
|
+
</symbol>
|
|
182
|
+
<symbol viewBox="0 96 48 48" id="vjs-icon-forward-30">
|
|
183
|
+
<path d="M25.549 97l-2.437 2.434 4.634 4.635H26.38c-2.97 0-5.753.555-8.347 1.664-2.594 1.109-4.861 2.633-6.802 4.574-1.94 1.94-3.465 4.207-4.574 6.802-1.109 2.594-1.664 5.377-1.664 8.347h3.565c0-4.967 1.683-9.178 5.05-12.636 3.366-3.458 7.525-5.187 12.475-5.187h1.307l-4.335 4.338 2.495 2.494 8.732-8.732zm-11.553 20.53v4.689h10.297v5.249h-6.978v4.688h6.978v5.156H13.996V142h10.808c1.06 0 1.948-.395 2.666-1.186.718-.79 1.077-1.771 1.077-2.94v-16.217c0-1.169-.36-2.15-1.077-2.94-.718-.79-1.605-1.186-2.666-1.186zm21.174.168c-1.149 0-2.11.389-2.884 1.163-.78.78-1.172 1.745-1.172 2.894v15.942c0 1.15.388 2.11 1.162 2.885.78.78 1.745 1.17 2.894 1.17h7.649c1.149 0 2.11-.386 2.885-1.16.78-.78 1.17-1.746 1.17-2.895v-15.942c0-1.15-.387-2.11-1.161-2.885-.78-.78-1.745-1.172-2.894-1.172zm.552 4.516h6.542v14.931h-6.542z"></path>
|
|
184
|
+
</symbol>
|
|
185
|
+
<symbol viewBox="0 0 512 512" id="vjs-icon-audio-description">
|
|
186
|
+
<g fill-rule="evenodd"><path d="M227.29 381.351V162.993c50.38-1.017 89.108-3.028 117.631 17.126 27.374 19.342 48.734 56.965 44.89 105.325-4.067 51.155-41.335 94.139-89.776 98.475-24.085 2.155-71.972 0-71.972 0s-.84-1.352-.773-2.568m48.755-54.804c31.43 1.26 53.208-16.633 56.495-45.386 4.403-38.51-21.188-63.552-58.041-60.796v103.612c-.036 1.466.575 2.22 1.546 2.57"></path><path d="M383.78 381.328c13.336 3.71 17.387-11.06 23.215-21.408 12.722-22.571 22.294-51.594 22.445-84.774.221-47.594-18.343-82.517-35.6-106.182h-8.51c-.587 3.874 2.226 7.315 3.865 10.276 13.166 23.762 25.367 56.553 25.54 94.194.2 43.176-14.162 79.278-30.955 107.894"></path><path d="M425.154 381.328c13.336 3.71 17.384-11.061 23.215-21.408 12.721-22.571 22.291-51.594 22.445-84.774.221-47.594-18.343-82.517-35.6-106.182h-8.511c-.586 3.874 2.226 7.315 3.866 10.276 13.166 23.762 25.367 56.553 25.54 94.194.2 43.176-14.162 79.278-30.955 107.894"></path><path d="M466.26 381.328c13.337 3.71 17.385-11.061 23.216-21.408 12.722-22.571 22.292-51.594 22.445-84.774.221-47.594-18.343-82.517-35.6-106.182h-8.51c-.587 3.874 2.225 7.315 3.865 10.276 13.166 23.762 25.367 56.553 25.54 94.194.2 43.176-14.162 79.278-30.955 107.894M4.477 383.005H72.58l18.573-28.484 64.169-.135s.065 19.413.065 28.62h48.756V160.307h-58.816c-5.653 9.537-140.85 222.697-140.85 222.697zm152.667-145.282v71.158l-40.453-.27 40.453-70.888z"></path></g>
|
|
187
|
+
</symbol>
|
|
188
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-next-item">
|
|
189
|
+
<path d="M12 36l17-12-17-12v24zm20-24v24h4V12h-4z"></path>
|
|
190
|
+
</symbol>
|
|
191
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-previous-item">
|
|
192
|
+
<path d="M12 12h4v24h-4zm7 12l17 12V12z"></path>
|
|
193
|
+
</symbol>
|
|
194
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-shuffle">
|
|
195
|
+
<path d="M21.17 18.34L10.83 8 8 10.83l10.34 10.34 2.83-2.83zM29 8l4.09 4.09L8 37.17 10.83 40l25.09-25.09L40 19V8H29zm.66 18.83l-2.83 2.83 6.26 6.26L29 40h11V29l-4.09 4.09-6.25-6.26z"></path>
|
|
196
|
+
</symbol>
|
|
197
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-cast">
|
|
198
|
+
<path d="M42 6H6c-2.21 0-4 1.79-4 4v6h4v-6h36v28H28v4h14c2.21 0 4-1.79 4-4V10c0-2.21-1.79-4-4-4zM2 36v6h6c0-3.31-2.69-6-6-6zm0-8v4c5.52 0 10 4.48 10 10h4c0-7.73-6.27-14-14-14zm0-8v4c9.94 0 18 8.06 18 18h4c0-12.15-9.85-22-22-22z"></path>
|
|
199
|
+
</symbol>
|
|
200
|
+
<symbol viewBox="0 0 48 48" id="vjs-icon-picture-in-picture-enter">
|
|
201
|
+
<path d="M38 22H22v11.99h16V22zm8 16V9.96C46 7.76 44.2 6 42 6H6C3.8 6 2 7.76 2 9.96V38c0 2.2 1.8 4 4 4h36c2.2 0 4-1.8 4-4zm-4 .04H6V9.94h36v28.1z"></path>
|
|
202
|
+
</symbol>
|
|
203
|
+
<symbol viewBox="0 0 22 18" id="vjs-icon-picture-in-picture-exit">
|
|
204
|
+
<path d="M18 4H4v10h14V4zm4 12V1.98C22 .88 21.1 0 20 0H2C.9 0 0 .88 0 1.98V16c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2zm-2 .02H2V1.97h18v14.05z"></path>
|
|
205
|
+
<path fill="none" d="M-1-3h24v24H-1z"></path>
|
|
206
|
+
</symbol>
|
|
207
|
+
<symbol viewBox="0 0 1792 1792" id="vjs-icon-facebook">
|
|
208
|
+
<path d="M1343 12v264h-157q-86 0-116 36t-30 108v189h293l-39 296h-254v759H734V905H479V609h255V391q0-186 104-288.5T1115 0q147 0 228 12z"></path>
|
|
209
|
+
</symbol>
|
|
210
|
+
<symbol viewBox="0 0 1792 1792" id="vjs-icon-linkedin">
|
|
211
|
+
<path d="M477 625v991H147V625h330zm21-306q1 73-50.5 122T312 490h-2q-82 0-132-49t-50-122q0-74 51.5-122.5T314 148t133 48.5T498 319zm1166 729v568h-329v-530q0-105-40.5-164.5T1168 862q-63 0-105.5 34.5T999 982q-11 30-11 81v553H659q2-399 2-647t-1-296l-1-48h329v144h-2q20-32 41-56t56.5-52 87-43.5T1285 602q171 0 275 113.5t104 332.5z"></path>
|
|
212
|
+
</symbol>
|
|
213
|
+
<symbol viewBox="0 0 1200 1227" id="vjs-icon-twitter">
|
|
214
|
+
<path d="M714.163 519.284L1160.89 0H1055.03L667.137 450.887L357.328 0H0L468.492 681.821L0 1226.37H105.866L515.491 750.218L842.672 1226.37H1200L714.137 519.284H714.163ZM569.165 687.828L521.697 619.934L144.011 79.6944H306.615L611.412 515.685L658.88 583.579L1055.08 1150.3H892.476L569.165 687.854V687.828Z"/>
|
|
215
|
+
</symbol>
|
|
216
|
+
<symbol viewBox="0 0 1792 1792" id="vjs-icon-tumblr">
|
|
217
|
+
<path d="M1328 1329l80 237q-23 35-111 66t-177 32q-104 2-190.5-26T787 1564t-95-106-55.5-120-16.5-118V676H452V461q72-26 129-69.5t91-90 58-102 34-99T779 12q1-5 4.5-8.5T791 0h244v424h333v252h-334v518q0 30 6.5 56t22.5 52.5 49.5 41.5 81.5 14q78-2 134-29z"></path>
|
|
218
|
+
</symbol>
|
|
219
|
+
<symbol viewBox="0 0 1792 1792" id="vjs-icon-pinterest">
|
|
220
|
+
<path d="M1664 896q0 209-103 385.5T1281.5 1561 896 1664q-111 0-218-32 59-93 78-164 9-34 54-211 20 39 73 67.5t114 28.5q121 0 216-68.5t147-188.5 52-270q0-114-59.5-214T1180 449t-255-63q-105 0-196 29t-154.5 77-109 110.5-67 129.5T377 866q0 104 40 183t117 111q30 12 38-20 2-7 8-31t8-30q6-23-11-43-51-61-51-151 0-151 104.5-259.5T904 517q151 0 235.5 82t84.5 213q0 170-68.5 289T980 1220q-61 0-98-43.5T859 1072q8-35 26.5-93.5t30-103T927 800q0-50-27-83t-77-33q-62 0-105 57t-43 142q0 73 25 122l-99 418q-17 70-13 177-206-91-333-281T128 896q0-209 103-385.5T510.5 231 896 128t385.5 103T1561 510.5 1664 896z"></path>
|
|
221
|
+
</symbol>
|
|
222
|
+
</defs>
|
|
223
|
+
</svg>`;const Ev=Wc?10009:zc?461:8,Rr={codes:{play:415,pause:19,ff:417,rw:412,back:Ev},names:{415:"play",19:"pause",417:"ff",412:"rw",[Ev]:"back"},isEventKey(n,e){return e=e.toLowerCase(),!!(this.names[n.keyCode]&&this.names[n.keyCode]===e)},getEventName(n){if(this.names[n.keyCode])return this.names[n.keyCode];if(this.codes[n.code]){const e=this.codes[n.code];return this.names[e]}return null}},xv=5;class rA extends bi{constructor(e){super(),this.player_=e,this.focusableComponents=[],this.isListening_=!1,this.isPaused_=!1,this.onKeyDown_=this.onKeyDown_.bind(this),this.lastFocusedComponent_=null}start(){this.isListening_||(this.player_.on("keydown",this.onKeyDown_),this.player_.on("modalKeydown",this.onKeyDown_),this.player_.on("loadedmetadata",()=>{this.focus(this.updateFocusableComponents()[0])}),this.player_.on("modalclose",()=>{this.refocusComponent()}),this.player_.on("focusin",this.handlePlayerFocus_.bind(this)),this.player_.on("focusout",this.handlePlayerBlur_.bind(this)),this.isListening_=!0,this.player_.errorDisplay&&this.player_.errorDisplay.on("aftermodalfill",()=>{this.updateFocusableComponents(),this.focusableComponents.length&&(this.focusableComponents.length>1?this.focusableComponents[1].focus():this.focusableComponents[0].focus())}))}stop(){this.player_.off("keydown",this.onKeyDown_),this.isListening_=!1}onKeyDown_(e){const t=e.originalEvent?e.originalEvent:e;if(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(t.key)){if(this.isPaused_)return;t.preventDefault();const i=t.key.substring(5).toLowerCase();this.move(i)}else if(Rr.isEventKey(t,"play")||Rr.isEventKey(t,"pause")||Rr.isEventKey(t,"ff")||Rr.isEventKey(t,"rw")){t.preventDefault();const i=Rr.getEventName(t);this.performMediaAction_(i)}else Rr.isEventKey(t,"Back")&&e.target&&typeof e.target.closeable=="function"&&e.target.closeable()&&(t.preventDefault(),e.target.close())}performMediaAction_(e){if(this.player_)switch(e){case"play":this.player_.paused()&&this.player_.play();break;case"pause":this.player_.paused()||this.player_.pause();break;case"ff":this.userSeek_(this.player_.currentTime()+xv);break;case"rw":this.userSeek_(this.player_.currentTime()-xv);break}}userSeek_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(e)}pause(){this.isPaused_=!0}resume(){this.isPaused_=!1}handlePlayerBlur_(e){const t=e.relatedTarget;let i=null;const s=this.getCurrentComponent(e.target);t&&(i=!!t.closest(".video-js"),t.classList.contains("vjs-text-track-settings")&&!this.isPaused_&&this.searchForTrackSelect_()),(!e.currentTarget.contains(e.relatedTarget)&&!i||!t)&&(s&&s.name()==="CloseButton"?this.refocusComponent():(this.pause(),s&&s.el()&&(this.lastFocusedComponent_=s)))}handlePlayerFocus_(){this.getCurrentComponent()&&this.getCurrentComponent().getIsFocusable()&&this.resume()}updateFocusableComponents(){const e=this.player_,t=[];function i(s){for(const r of s)r.hasOwnProperty("el_")&&r.getIsFocusable()&&r.getIsAvailableToBeFocused(r.el())&&t.push(r),r.hasOwnProperty("children_")&&r.children_.length>0&&i(r.children_)}return e.children_.forEach(s=>{if(s.hasOwnProperty("el_"))if(s.getIsFocusable&&s.getIsAvailableToBeFocused&&s.getIsFocusable()&&s.getIsAvailableToBeFocused(s.el())){t.push(s);return}else s.hasOwnProperty("children_")&&s.children_.length>0?i(s.children_):s.hasOwnProperty("items")&&s.items.length>0?i(s.items):this.findSuitableDOMChild(s)&&t.push(s);if(s.name_==="ErrorDisplay"&&s.opened_){const r=s.el_.querySelector(".vjs-errors-ok-button-container");r&&r.querySelectorAll("button").forEach((o,c)=>{t.push({name:()=>"ModalButton"+(c+1),el:()=>o,getPositions:()=>{const l=o.getBoundingClientRect(),u={x:l.x,y:l.y,width:l.width,height:l.height,top:l.top,right:l.right,bottom:l.bottom,left:l.left},h={x:l.left+l.width/2,y:l.top+l.height/2,width:0,height:0,top:l.top+l.height/2,right:l.left+l.width/2,bottom:l.top+l.height/2,left:l.left+l.width/2};return{boundingClientRect:u,center:h}},getIsAvailableToBeFocused:()=>!0,getIsFocusable:l=>!0,focus:()=>o.focus()})})}}),this.focusableComponents=t,this.focusableComponents}findSuitableDOMChild(e){function t(i){if(e.getIsFocusable(i)&&e.getIsAvailableToBeFocused(i))return i;for(let s=0;s<i.children.length;s++){const r=i.children[s],a=t(r);if(a)return a}return null}return e.el()?t(e.el()):null}getCurrentComponent(e){this.updateFocusableComponents();const t=e||document.activeElement;if(this.focusableComponents.length){for(const i of this.focusableComponents)if(i.el()===t)return i}}add(e){const t=[...this.focusableComponents];e.hasOwnProperty("el_")&&e.getIsFocusable()&&e.getIsAvailableToBeFocused(e.el())&&t.push(e),this.focusableComponents=t,this.trigger({type:"focusableComponentsChanged",focusableComponents:this.focusableComponents})}remove(e){for(let t=0;t<this.focusableComponents.length;t++)if(this.focusableComponents[t].name()===e.name()){this.focusableComponents.splice(t,1),this.trigger({type:"focusableComponentsChanged",focusableComponents:this.focusableComponents});return}}clear(){this.focusableComponents.length>0&&(this.focusableComponents=[],this.trigger({type:"focusableComponentsChanged",focusableComponents:this.focusableComponents}))}move(e){const t=this.getCurrentComponent();if(!t)return;const i=t.getPositions(),s=this.focusableComponents.filter(a=>a!==t&&this.isInDirection_(i.boundingClientRect,a.getPositions().boundingClientRect,e)),r=this.findBestCandidate_(i.center,s,e);r?this.focus(r):this.trigger({type:"endOfFocusableComponents",direction:e,focusedComponent:t})}findBestCandidate_(e,t,i){let s=1/0,r=null;for(const a of t){const o=a.getPositions().center,c=this.calculateDistance_(e,o,i);c<s&&(s=c,r=a)}return r}isInDirection_(e,t,i){switch(i){case"right":return t.left>=e.right;case"left":return t.right<=e.left;case"down":return t.top>=e.bottom;case"up":return t.bottom<=e.top;default:return!1}}refocusComponent(){if(this.lastFocusedComponent_){this.player_.userActive()||this.player_.userActive(!0),this.updateFocusableComponents();for(let e=0;e<this.focusableComponents.length;e++)if(this.focusableComponents[e].name()===this.lastFocusedComponent_.name()){this.focus(this.focusableComponents[e]);return}}else this.focus(this.updateFocusableComponents()[0])}focus(e){typeof e=="object"&&(e.getIsAvailableToBeFocused(e.el())?e.focus():this.findSuitableDOMChild(e)&&this.findSuitableDOMChild(e).focus())}calculateDistance_(e,t,i){const s=Math.abs(e.x-t.x),r=Math.abs(e.y-t.y);let a;switch(i){case"right":case"left":a=s+r*100;break;case"up":a=r*2+s*.5;break;case"down":a=r*5+s;break;default:a=s+r}return a}searchForTrackSelect_(){const e=this;for(const t of e.updateFocusableComponents())if(t.constructor.name==="TextTrackSelect"){e.focus(t);break}}}class aA extends ee{constructor(e,t,i){const s=Qe({createEl:!1},t);if(super(e,s,i),!t.playerOptions.sources||t.playerOptions.sources.length===0)for(let r=0,a=t.playerOptions.techOrder;r<a.length;r++){const o=pt(a[r]);let c=De.getTech(o);if(o||(c=ee.getComponent(o)),c&&c.isSupported()){e.loadTech_(o);break}}else e.src(t.playerOptions.sources)}}ee.registerComponent("MediaLoader",aA);class ll extends ee{constructor(e,t){super(e,t),this.options_.controlText&&this.controlText(this.options_.controlText),this.handleMouseOver_=i=>this.handleMouseOver(i),this.handleMouseOut_=i=>this.handleMouseOut(i),this.handleClick_=i=>this.handleClick(i),this.handleKeyDown_=i=>this.handleKeyDown(i),this.emitTapEvents(),this.enable()}createEl(e="div",t={},i={}){t=Object.assign({className:this.buildCSSClass(),tabIndex:0},t),e==="button"&&Oe.error(`Creating a ClickableComponent with an HTML element of ${e} is not supported; use a Button instead.`),i=Object.assign({role:"button"},i),this.tabIndex_=t.tabIndex;const s=Ee(e,t,i);return this.player_.options_.experimentalSvgIcons||s.appendChild(Ee("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(s),s}dispose(){this.controlTextEl_=null,super.dispose()}createControlTextEl(e){return this.controlTextEl_=Ee("span",{className:"vjs-control-text"},{"aria-live":"polite"}),e&&e.appendChild(this.controlTextEl_),this.controlText(this.controlText_,e),this.controlTextEl_}controlText(e,t=this.el()){if(e===void 0)return this.controlText_||"Need Text";const i=this.localize(e);this.controlText_=e,os(this.controlTextEl_,i),!this.nonIconControl&&!this.player_.options_.noUITitleAttributes&&t.setAttribute("title",i)}buildCSSClass(){return`vjs-control vjs-button ${super.buildCSSClass()}`}enable(){this.enabled_||(this.enabled_=!0,this.removeClass("vjs-disabled"),this.el_.setAttribute("aria-disabled","false"),typeof this.tabIndex_<"u"&&this.el_.setAttribute("tabIndex",this.tabIndex_),this.on(["tap","click"],this.handleClick_),this.on("keydown",this.handleKeyDown_))}disable(){this.enabled_=!1,this.addClass("vjs-disabled"),this.el_.setAttribute("aria-disabled","true"),typeof this.tabIndex_<"u"&&this.el_.removeAttribute("tabIndex"),this.off("mouseover",this.handleMouseOver_),this.off("mouseout",this.handleMouseOut_),this.off(["tap","click"],this.handleClick_),this.off("keydown",this.handleKeyDown_)}handleLanguagechange(){this.controlText(this.controlText_)}handleClick(e){this.options_.clickHandler&&this.options_.clickHandler.call(this,arguments)}handleKeyDown(e){e.key===" "||e.key==="Enter"?(e.preventDefault(),e.stopPropagation(),this.trigger("click")):super.handleKeyDown(e)}}ee.registerComponent("ClickableComponent",ll);class Lh extends ll{constructor(e,t){super(e,t);const{mainContent:i}=t&&t.playerOptions||{};this.isMainContent=i,this.update(),this.update_=s=>this.update(s),e.on("posterchange",this.update_)}dispose(){this.player().off("posterchange",this.update_),super.dispose()}createEl(){return Ee("div",{className:"vjs-poster"})}crossOrigin(e){if(typeof e>"u")return this.$("img")?this.$("img").crossOrigin:this.player_.tech_&&this.player_.tech_.isReady_?this.player_.crossOrigin():this.player_.options_.crossOrigin||this.player_.options_.crossorigin||null;if(e!==null&&e!=="anonymous"&&e!=="use-credentials"){this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${e}"`);return}this.$("img")&&(this.$("img").crossOrigin=e)}update(e){const t=this.player().poster();this.setSrc(t),t?this.show():this.hide()}setSrc(e){if(!e){this.el_.textContent="";return}this.$("img")||this.el_.appendChild(Ee("picture",{className:"vjs-poster",tabIndex:-1},{},Ee("img",{loading:this.isMainContent?"eager":"lazy",fetchPriority:this.isMainContent?"high":"auto",crossOrigin:this.crossOrigin()},{alt:""}))),this.$("img").src=e}handleClick(e){if(!this.player_.controls())return;const t=this.player_.getChild("controlBar"),i=t&&t.getChild("playToggle");rs?(i||this.player_).focus():this.player_.tech(!0)&&this.player_.tech(!0).focus(),this.player_.paused()?fn(this.player_.play()):this.player_.pause()}}Lh.prototype.crossorigin=Lh.prototype.crossOrigin,ee.registerComponent("PosterImage",Lh);const Ri="#222",wv="#ccc",oA={monospace:"monospace",sansSerif:"sans-serif",serif:"serif",monospaceSansSerif:'"Andale Mono", "Lucida Console", monospace',monospaceSerif:'"Courier New", monospace',proportionalSansSerif:"sans-serif",proportionalSerif:"serif",casual:'"Comic Sans MS", Impact, fantasy',script:'"Monotype Corsiva", cursive',smallcaps:'"Andale Mono", "Lucida Console", monospace, sans-serif'};function Nh(n,e){let t;if(n.length===4)t=n[1]+n[1]+n[2]+n[2]+n[3]+n[3];else if(n.length===7)t=n.slice(1);else throw new Error("Invalid color code provided, "+n+"; must be formatted as e.g. #f0e or #f604e2.");return"rgba("+parseInt(t.slice(0,2),16)+","+parseInt(t.slice(2,4),16)+","+parseInt(t.slice(4,6),16)+","+e+")"}function pn(n,e,t){try{n.style[e]=t}catch{return}}function Av(n){return n?`${n}px`:""}class cA extends ee{constructor(e,t,i){super(e,t,i);const s=a=>this.updateDisplay(a),r=a=>{this.updateDisplayOverlay(),this.updateDisplay(a)};e.on("loadstart",a=>this.toggleDisplay(a)),e.on("useractive",s),e.on("userinactive",s),e.on("texttrackchange",s),e.on("loadedmetadata",a=>{this.updateDisplayOverlay(),this.preselectTrack(a)}),e.ready(Ze(this,function(){if(e.tech_&&e.tech_.featuresNativeTextTracks){this.hide();return}e.on("fullscreenchange",r),e.on("playerresize",r);const a=B.screen.orientation||B,o=B.screen.orientation?"change":"orientationchange";a.addEventListener(o,r),e.on("dispose",()=>a.removeEventListener(o,r));const c=this.options_.playerOptions.tracks||[];for(let l=0;l<c.length;l++)this.player_.addRemoteTextTrack(c[l],!0);this.preselectTrack()}))}preselectTrack(){const e={captions:1,subtitles:1},t=this.player_.textTracks(),i=this.player_.cache_.selectedLanguage;let s,r,a;for(let o=0;o<t.length;o++){const c=t[o];i&&i.enabled&&i.language&&i.language===c.language&&c.kind in e?c.kind===i.kind?a=c:a||(a=c):i&&!i.enabled?(a=null,s=null,r=null):c.default&&(c.kind==="descriptions"&&!s?s=c:c.kind in e&&!r&&(r=c))}a?a.mode="showing":r?r.mode="showing":s&&(s.mode="showing")}toggleDisplay(){this.player_.tech_&&this.player_.tech_.featuresNativeTextTracks?this.hide():this.show()}createEl(){return super.createEl("div",{className:"vjs-text-track-display"},{translate:"yes","aria-live":"off","aria-atomic":"true"})}clearDisplay(){typeof B.WebVTT=="function"&&B.WebVTT.processCues(B,[],this.el_)}updateDisplay(){const e=this.player_.textTracks(),t=this.options_.allowMultipleShowingTracks;if(this.clearDisplay(),t){const a=[];for(let o=0;o<e.length;++o){const c=e[o];c.mode==="showing"&&a.push(c)}this.updateForTrack(a);return}let i=null,s=null,r=e.length;for(;r--;){const a=e[r];a.mode==="showing"&&(a.kind==="descriptions"?i=a:s=a)}if(s?(this.getAttribute("aria-live")!=="off"&&this.setAttribute("aria-live","off"),this.updateForTrack(s)):i&&(this.getAttribute("aria-live")!=="assertive"&&this.setAttribute("aria-live","assertive"),this.updateForTrack(i)),!(B.CSS!==void 0&&B.CSS.supports("inset","10px"))){const a=this.el_,o=a.querySelectorAll(".vjs-text-track-cue"),c=this.player_.controlBar.el_.getBoundingClientRect().height,l=this.player_.el_.getBoundingClientRect().height;a.style="",pn(a,"position","relative"),pn(a,"height",l-c+"px"),pn(a,"top","unset"),Gc?pn(a,"bottom",l+"px"):pn(a,"bottom","0px"),o.length>0&&o.forEach(u=>{if(u.style.inset){const h=u.style.inset.split(" ");h.length===3&&Object.assign(u.style,{top:h[0],right:h[1],bottom:h[2],left:"unset"})}})}}updateDisplayOverlay(){if(!this.player_.videoHeight()||!(B.CSS!==void 0&&B.CSS.supports("inset-inline: 10px")))return;const e=this.player_.currentWidth(),t=this.player_.currentHeight(),i=e/t,s=this.player_.videoWidth()/this.player_.videoHeight();let r=0,a=0;Math.abs(i-s)>.1&&(i>s?r=Math.round((e-t*s)/2):a=Math.round((t-e/s)/2)),pn(this.el_,"insetInline",Av(r)),pn(this.el_,"insetBlock",Av(a))}updateDisplayState(e){const t=this.player_.textTrackSettings.getValues(),i=e.activeCues;let s=i.length;for(;s--;){const r=i[s];if(!r)continue;const a=r.displayState;if(t.color&&(a.firstChild.style.color=t.color),t.textOpacity&&pn(a.firstChild,"color",Nh(t.color||"#fff",t.textOpacity)),t.backgroundColor&&(a.firstChild.style.backgroundColor=t.backgroundColor),t.backgroundOpacity&&pn(a.firstChild,"backgroundColor",Nh(t.backgroundColor||"#000",t.backgroundOpacity)),t.windowColor&&(t.windowOpacity?pn(a,"backgroundColor",Nh(t.windowColor,t.windowOpacity)):a.style.backgroundColor=t.windowColor),t.edgeStyle&&(t.edgeStyle==="dropshadow"?a.firstChild.style.textShadow=`2px 2px 3px ${Ri}, 2px 2px 4px ${Ri}, 2px 2px 5px ${Ri}`:t.edgeStyle==="raised"?a.firstChild.style.textShadow=`1px 1px ${Ri}, 2px 2px ${Ri}, 3px 3px ${Ri}`:t.edgeStyle==="depressed"?a.firstChild.style.textShadow=`1px 1px ${wv}, 0 1px ${wv}, -1px -1px ${Ri}, 0 -1px ${Ri}`:t.edgeStyle==="uniform"&&(a.firstChild.style.textShadow=`0 0 4px ${Ri}, 0 0 4px ${Ri}, 0 0 4px ${Ri}, 0 0 4px ${Ri}`)),t.fontPercent&&t.fontPercent!==1){const o=B.parseFloat(a.style.fontSize);a.style.fontSize=o*t.fontPercent+"px",a.style.height="auto",a.style.top="auto"}t.fontFamily&&t.fontFamily!=="default"&&(t.fontFamily==="small-caps"?a.firstChild.style.fontVariant="small-caps":a.firstChild.style.fontFamily=oA[t.fontFamily])}}updateForTrack(e){if(Array.isArray(e)||(e=[e]),typeof B.WebVTT!="function"||e.every(i=>!i.activeCues))return;const t=[];for(let i=0;i<e.length;++i){const s=e[i];for(let r=0;r<s.activeCues.length;++r)t.push(s.activeCues[r])}B.WebVTT.processCues(B,t,this.el_);for(let i=0;i<e.length;++i){const s=e[i];for(let r=0;r<s.activeCues.length;++r){const a=s.activeCues[r].displayState;Ls(a,"vjs-text-track-cue","vjs-text-track-cue-"+(s.language?s.language:i)),s.language&&xr(a,"lang",s.language)}this.player_.textTrackSettings&&this.updateDisplayState(s)}}}ee.registerComponent("TextTrackDisplay",cA);class lA extends ee{createEl(){const e=this.player_.isAudio(),t=this.localize(e?"Audio Player":"Video Player"),i=Ee("span",{className:"vjs-control-text",textContent:this.localize("{1} is loading.",[t])}),s=super.createEl("div",{className:"vjs-loading-spinner",dir:"ltr"});return s.appendChild(i),s}handleLanguagechange(){this.$(".vjs-control-text").textContent=this.localize("{1} is loading.",[this.player_.isAudio()?"Audio Player":"Video Player"])}}ee.registerComponent("LoadingSpinner",lA);class Wt extends ll{createEl(e,t={},i={}){e="button",t=Object.assign({className:this.buildCSSClass()},t),i=Object.assign({type:"button"},i);const s=Ee(e,t,i);return this.player_.options_.experimentalSvgIcons||s.appendChild(Ee("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(s),s}addChild(e,t={}){const i=this.constructor.name;return Oe.warn(`Adding an actionable (user controllable) child to a Button (${i}) is not supported; use a ClickableComponent instead.`),ee.prototype.addChild.call(this,e,t)}enable(){super.enable(),this.el_.removeAttribute("disabled")}disable(){super.disable(),this.el_.setAttribute("disabled","disabled")}handleKeyDown(e){if(e.key===" "||e.key==="Enter"){e.stopPropagation();return}super.handleKeyDown(e)}}ee.registerComponent("Button",Wt);class Dv extends Wt{constructor(e,t){super(e,t),this.mouseused_=!1,this.setIcon("play"),this.on("mousedown",i=>this.handleMouseDown(i))}buildCSSClass(){return"vjs-big-play-button"}handleClick(e){const t=this.player_.play(),i=this.player_.getChild("controlBar"),s=i&&i.getChild("playToggle");if(e.type==="tap"||this.mouseused_&&"clientX"in e&&"clientY"in e){fn(t),rs?(s||this.player_).focus():this.player_.tech(!0)&&this.player_.tech(!0).focus();return}if(!s){this.player_.tech(!0).focus();return}const r=()=>s.focus();Ga(t)?t.then(r,()=>{}):this.setTimeout(r,1)}handleKeyDown(e){this.mouseused_=!1,super.handleKeyDown(e)}handleMouseDown(e){this.mouseused_=!0}}Dv.prototype.controlText_="Play Video",ee.registerComponent("BigPlayButton",Dv);class uA extends Wt{constructor(e,t){super(e,t),this.setIcon("cancel"),this.controlText(t&&t.controlText||this.localize("Close"))}buildCSSClass(){return`vjs-close-button ${super.buildCSSClass()}`}handleClick(e){this.trigger({type:"close",bubbles:!1})}handleKeyDown(e){e.key==="Escape"?(e.preventDefault(),e.stopPropagation(),this.trigger("click")):super.handleKeyDown(e)}}ee.registerComponent("CloseButton",uA);class Pv extends Wt{constructor(e,t={}){super(e,t),t.replay=t.replay===void 0||t.replay,this.setIcon("play"),this.on(e,"play",i=>this.handlePlay(i)),this.on(e,"pause",i=>this.handlePause(i)),t.replay&&this.on(e,"ended",i=>this.handleEnded(i))}buildCSSClass(){return`vjs-play-control ${super.buildCSSClass()}`}handleClick(e){this.player_.paused()?fn(this.player_.play()):this.player_.pause()}handleSeeked(e){this.removeClass("vjs-ended"),this.player_.paused()?this.handlePause(e):this.handlePlay(e)}handlePlay(e){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.setIcon("pause"),this.controlText("Pause")}handlePause(e){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.setIcon("play"),this.controlText("Play")}handleEnded(e){this.removeClass("vjs-playing"),this.addClass("vjs-ended"),this.setIcon("replay"),this.controlText("Replay"),this.one(this.player_,"seeked",t=>this.handleSeeked(t))}}Pv.prototype.controlText_="Play",ee.registerComponent("PlayToggle",Pv);class Or extends ee{constructor(e,t){super(e,t),this.on(e,["timeupdate","ended","seeking"],i=>this.update(i)),this.updateTextNode_()}createEl(){const e=this.buildCSSClass(),t=super.createEl("div",{className:`${e} vjs-time-control vjs-control`}),i=Ee("span",{className:"vjs-control-text",textContent:`${this.localize(this.labelText_)} `},{role:"presentation"});return t.appendChild(i),this.contentEl_=Ee("span",{className:`${e}-display`},{role:"presentation"}),t.appendChild(this.contentEl_),t}dispose(){this.contentEl_=null,this.textNode_=null,super.dispose()}update(e){!this.player_.options_.enableSmoothSeeking&&e.type==="seeking"||this.updateContent(e)}updateTextNode_(e=0){e=Fs(e),this.formattedTime_!==e&&(this.formattedTime_=e,this.requestNamedAnimationFrame("TimeDisplay#updateTextNode_",()=>{if(!this.contentEl_)return;let t=this.textNode_;t&&this.contentEl_.firstChild!==t&&(t=null,Oe.warn("TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.")),this.textNode_=de.createTextNode(this.formattedTime_),this.textNode_&&(t?this.contentEl_.replaceChild(this.textNode_,t):this.contentEl_.appendChild(this.textNode_))}))}updateContent(e){}}Or.prototype.labelText_="Time",Or.prototype.controlText_="Time",ee.registerComponent("TimeDisplay",Or);class Fh extends Or{buildCSSClass(){return"vjs-current-time"}updateContent(e){let t;this.player_.ended()?t=this.player_.duration():e&&e.target&&typeof e.target.pendingSeekTime=="function"&&e.target.pendingSeekTime()!==null?t=e.target.pendingSeekTime():t=this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime(),this.updateTextNode_(t)}}Fh.prototype.labelText_="Current Time",Fh.prototype.controlText_="Current Time",ee.registerComponent("CurrentTimeDisplay",Fh);class Uh extends Or{constructor(e,t){super(e,t);const i=s=>this.updateContent(s);this.on(e,"durationchange",i),this.on(e,"loadstart",i),this.on(e,"loadedmetadata",i)}buildCSSClass(){return"vjs-duration"}updateContent(e){const t=this.player_.duration();this.updateTextNode_(t)}}Uh.prototype.labelText_="Duration",Uh.prototype.controlText_="Duration",ee.registerComponent("DurationDisplay",Uh);class dA extends ee{createEl(){const e=super.createEl("div",{className:"vjs-time-control vjs-time-divider"},{"aria-hidden":!0}),t=super.createEl("div"),i=super.createEl("span",{textContent:"/"});return t.appendChild(i),e.appendChild(t),e}}ee.registerComponent("TimeDivider",dA);class Bh extends Or{constructor(e,t){super(e,t),this.on(e,"durationchange",i=>this.updateContent(i))}buildCSSClass(){return"vjs-remaining-time"}createEl(){const e=super.createEl();return this.options_.displayNegative!==!1&&e.insertBefore(Ee("span",{},{"aria-hidden":!0},"-"),this.contentEl_),e}updateContent(e){if(typeof this.player_.duration()!="number")return;let t;this.player_.ended()?t=0:this.player_.remainingTimeDisplay?t=this.player_.remainingTimeDisplay():t=this.player_.remainingTime(),this.updateTextNode_(t)}}Bh.prototype.labelText_="Remaining Time",Bh.prototype.controlText_="Remaining Time",ee.registerComponent("RemainingTimeDisplay",Bh);class hA extends ee{constructor(e,t){super(e,t),this.updateShowing(),this.on(this.player(),"durationchange",i=>this.updateShowing(i))}createEl(){const e=super.createEl("div",{className:"vjs-live-control vjs-control"});return this.contentEl_=Ee("div",{className:"vjs-live-display"},{"aria-live":"off"}),this.contentEl_.appendChild(Ee("span",{className:"vjs-control-text",textContent:`${this.localize("Stream Type")} `})),this.contentEl_.appendChild(de.createTextNode(this.localize("LIVE"))),e.appendChild(this.contentEl_),e}dispose(){this.contentEl_=null,super.dispose()}updateShowing(e){this.player().duration()===1/0?this.show():this.hide()}}ee.registerComponent("LiveDisplay",hA);class Iv extends Wt{constructor(e,t){super(e,t),this.updateLiveEdgeStatus(),this.player_.liveTracker&&(this.updateLiveEdgeStatusHandler_=i=>this.updateLiveEdgeStatus(i),this.on(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_))}createEl(){const e=super.createEl("button",{className:"vjs-seek-to-live-control vjs-control"});return this.setIcon("circle",e),this.textEl_=Ee("span",{className:"vjs-seek-to-live-text",textContent:this.localize("LIVE")},{"aria-hidden":"true"}),e.appendChild(this.textEl_),e}updateLiveEdgeStatus(){!this.player_.liveTracker||this.player_.liveTracker.atLiveEdge()?(this.setAttribute("aria-disabled",!0),this.addClass("vjs-at-live-edge"),this.controlText("Seek to live, currently playing live")):(this.setAttribute("aria-disabled",!1),this.removeClass("vjs-at-live-edge"),this.controlText("Seek to live, currently behind live"))}handleClick(){this.player_.liveTracker.seekToLiveEdge()}dispose(){this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_),this.textEl_=null,super.dispose()}}Iv.prototype.controlText_="Seek to live, currently playing live",ee.registerComponent("SeekToLive",Iv);function Xa(n,e,t){return n=Number(n),Math.min(t,Math.max(e,isNaN(n)?e:n))}var fA=Object.freeze({__proto__:null,clamp:Xa});class qh extends ee{constructor(e,t){super(e,t),this.handleMouseDown_=i=>this.handleMouseDown(i),this.handleMouseUp_=i=>this.handleMouseUp(i),this.handleKeyDown_=i=>this.handleKeyDown(i),this.handleClick_=i=>this.handleClick(i),this.handleMouseMove_=i=>this.handleMouseMove(i),this.update_=i=>this.update(i),this.bar=this.getChild(this.options_.barName),this.vertical(!!this.options_.vertical),this.enable()}enabled(){return this.enabled_}enable(){this.enabled()||(this.on("mousedown",this.handleMouseDown_),this.on("touchstart",this.handleMouseDown_),this.on("keydown",this.handleKeyDown_),this.on("click",this.handleClick_),this.on(this.player_,"controlsvisible",this.update),this.playerEvent&&this.on(this.player_,this.playerEvent,this.update),this.removeClass("disabled"),this.setAttribute("tabindex",0),this.enabled_=!0)}disable(){if(!this.enabled())return;const e=this.bar.el_.ownerDocument;this.off("mousedown",this.handleMouseDown_),this.off("touchstart",this.handleMouseDown_),this.off("keydown",this.handleKeyDown_),this.off("click",this.handleClick_),this.off(this.player_,"controlsvisible",this.update_),this.off(e,"mousemove",this.handleMouseMove_),this.off(e,"mouseup",this.handleMouseUp_),this.off(e,"touchmove",this.handleMouseMove_),this.off(e,"touchend",this.handleMouseUp_),this.removeAttribute("tabindex"),this.addClass("disabled"),this.playerEvent&&this.off(this.player_,this.playerEvent,this.update),this.enabled_=!1}createEl(e,t={},i={}){return t.className=t.className+" vjs-slider",t=Object.assign({tabIndex:0},t),i=Object.assign({role:"slider","aria-valuenow":0,"aria-valuemin":0,"aria-valuemax":100},i),super.createEl(e,t,i)}handleMouseDown(e){const t=this.bar.el_.ownerDocument;e.type==="mousedown"&&e.preventDefault(),e.type==="touchstart"&&!dn&&e.preventDefault(),Wy(),this.addClass("vjs-sliding"),this.trigger("slideractive"),this.on(t,"mousemove",this.handleMouseMove_),this.on(t,"mouseup",this.handleMouseUp_),this.on(t,"touchmove",this.handleMouseMove_),this.on(t,"touchend",this.handleMouseUp_),this.handleMouseMove(e,!0)}handleMouseMove(e){}handleMouseUp(e){const t=this.bar.el_.ownerDocument;zy(),this.removeClass("vjs-sliding"),this.trigger("sliderinactive"),this.off(t,"mousemove",this.handleMouseMove_),this.off(t,"mouseup",this.handleMouseUp_),this.off(t,"touchmove",this.handleMouseMove_),this.off(t,"touchend",this.handleMouseUp_),this.update()}update(){if(!this.el_||!this.bar)return;const e=this.getProgress();return e===this.progress_||(this.progress_=e,this.requestNamedAnimationFrame("Slider#update",()=>{const t=this.vertical()?"height":"width";this.bar.el().style[t]=(e*100).toFixed(2)+"%"})),e}getProgress(){return Number(Xa(this.getPercent(),0,1).toFixed(4))}calculateDistance(e){const t=Qc(this.el_,e);return this.vertical()?t.y:t.x}handleKeyDown(e){const t=this.options_.playerOptions.spatialNavigation,i=t&&t.enabled,s=t&&t.horizontalSeek;i?s&&e.key==="ArrowLeft"||!s&&e.key==="ArrowDown"?(e.preventDefault(),e.stopPropagation(),this.stepBack()):s&&e.key==="ArrowRight"||!s&&e.key==="ArrowUp"?(e.preventDefault(),e.stopPropagation(),this.stepForward()):(this.pendingSeekTime()&&(this.pendingSeekTime(null),this.userSeek_(this.player_.currentTime())),super.handleKeyDown(e)):e.key==="ArrowLeft"||e.key==="ArrowDown"?(e.preventDefault(),e.stopPropagation(),this.stepBack()):e.key==="ArrowUp"||e.key==="ArrowRight"?(e.preventDefault(),e.stopPropagation(),this.stepForward()):super.handleKeyDown(e)}handleClick(e){e.stopPropagation(),e.preventDefault()}vertical(e){if(e===void 0)return this.vertical_||!1;this.vertical_=!!e,this.vertical_?this.addClass("vjs-slider-vertical"):this.addClass("vjs-slider-horizontal")}}ee.registerComponent("Slider",qh);const Vh=(n,e)=>Xa(n/e*100,0,100).toFixed(2)+"%";class pA extends ee{constructor(e,t){super(e,t),this.partEls_=[],this.on(e,"progress",i=>this.update(i))}createEl(){const e=super.createEl("div",{className:"vjs-load-progress"}),t=Ee("span",{className:"vjs-control-text"}),i=Ee("span",{textContent:this.localize("Loaded")}),s=de.createTextNode(": ");return this.percentageEl_=Ee("span",{className:"vjs-control-text-loaded-percentage",textContent:"0%"}),e.appendChild(t),t.appendChild(i),t.appendChild(s),t.appendChild(this.percentageEl_),e}dispose(){this.partEls_=null,this.percentageEl_=null,super.dispose()}update(e){this.requestNamedAnimationFrame("LoadProgressBar#update",()=>{const t=this.player_.liveTracker,i=this.player_.buffered(),s=t&&t.isLive()?t.seekableEnd():this.player_.duration(),r=this.player_.bufferedEnd(),a=this.partEls_,o=Vh(r,s);this.percent_!==o&&(this.el_.style.width=o,os(this.percentageEl_,o),this.percent_=o);for(let c=0;c<i.length;c++){const l=i.start(c),u=i.end(c);let h=a[c];h||(h=this.el_.appendChild(Ee()),a[c]=h),!(h.dataset.start===l&&h.dataset.end===u)&&(h.dataset.start=l,h.dataset.end=u,h.style.left=Vh(l,r),h.style.width=Vh(u-l,r))}for(let c=a.length;c>i.length;c--)this.el_.removeChild(a[c-1]);a.length=i.length})}}ee.registerComponent("LoadProgressBar",pA);class mA extends ee{constructor(e,t){super(e,t),this.update=hn(Ze(this,this.update),Pi)}createEl(){return super.createEl("div",{className:"vjs-time-tooltip"},{"aria-hidden":"true"})}update(e,t,i){const s=Ha(this.el_),r=wr(this.player_.el()),a=e.width*t;if(!r||!s)return;let o=e.left-r.left+a,c=e.width-a+(r.right-e.right);c||(c=e.width-a,o=a);let l=s.width/2;o<l?l+=l-o:c<l&&(l=c),l<0?l=0:l>s.width&&(l=s.width),l=Math.round(l),this.el_.style.right=`-${l}px`,this.write(i)}write(e){os(this.el_,e)}updateTime(e,t,i,s){this.requestNamedAnimationFrame("TimeTooltip#updateTime",()=>{let r;const a=this.player_.duration();if(this.player_.liveTracker&&this.player_.liveTracker.isLive()){const o=this.player_.liveTracker.liveWindow(),c=o-t*o;r=(c<1?"":"-")+Fs(c,o)}else r=Fs(i,a);this.update(e,t,r),s&&s()})}}ee.registerComponent("TimeTooltip",mA);class jh extends ee{constructor(e,t){super(e,t),this.setIcon("circle"),this.update=hn(Ze(this,this.update),Pi)}createEl(){return super.createEl("div",{className:"vjs-play-progress vjs-slider-bar"},{"aria-hidden":"true"})}update(e,t,i){const s=this.getChild("timeTooltip");if(!s)return;const r=i&&i.target&&typeof i.target.pendingSeekTime=="function"?i.target.pendingSeekTime():this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime();s.updateTime(e,t,r)}}jh.prototype.options_={children:[]},!Ht&&!Wi&&jh.prototype.options_.children.push("timeTooltip"),ee.registerComponent("PlayProgressBar",jh);class Rv extends ee{constructor(e,t){super(e,t),this.update=hn(Ze(this,this.update),Pi)}createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(e,t){const i=t*this.player_.duration();this.getChild("timeTooltip").updateTime(e,t,i,()=>{this.el_.style.left=`${e.width*t}px`})}}Rv.prototype.options_={children:["timeTooltip"]},ee.registerComponent("MouseTimeDisplay",Rv);class ul extends qh{constructor(e,t){t=Qe(ul.prototype.options_,t),t.children=[...t.children];const i=e.options_.disableSeekWhileScrubbingOnMobile&&(Ht||Wi)||e.options_.disableSeekWhileScrubbingOnSTV;(!Ht&&!Wi||i)&&t.children.splice(1,0,"mouseTimeDisplay"),super(e,t),this.shouldDisableSeekWhileScrubbing_=i,this.pendingSeekTime_=null,this.setEventHandlers_()}setEventHandlers_(){this.update_=Ze(this,this.update),this.update=hn(this.update_,Pi),this.on(this.player_,["durationchange","timeupdate"],this.update),this.on(this.player_,["ended"],this.update_),this.player_.liveTracker&&this.on(this.player_.liveTracker,"liveedgechange",this.update),this.updateInterval=null,this.enableIntervalHandler_=e=>this.enableInterval_(e),this.disableIntervalHandler_=e=>this.disableInterval_(e),this.on(this.player_,["playing"],this.enableIntervalHandler_),this.on(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in de&&"visibilityState"in de&&this.on(de,"visibilitychange",this.toggleVisibility_)}toggleVisibility_(e){de.visibilityState==="hidden"?(this.cancelNamedAnimationFrame("SeekBar#update"),this.cancelNamedAnimationFrame("Slider#update"),this.disableInterval_(e)):(!this.player_.ended()&&!this.player_.paused()&&this.enableInterval_(),this.update())}enableInterval_(){this.updateInterval||(this.updateInterval=this.setInterval(this.update,Pi))}disableInterval_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&e&&e.type!=="ended"||this.updateInterval&&(this.clearInterval(this.updateInterval),this.updateInterval=null)}createEl(){return super.createEl("div",{className:"vjs-progress-holder"},{"aria-label":this.localize("Progress Bar")})}update(e){if(de.visibilityState==="hidden")return;const t=super.update();return this.requestNamedAnimationFrame("SeekBar#update",()=>{const i=this.player_.ended()?this.player_.duration():this.getCurrentTime_(),s=this.player_.liveTracker;let r=this.player_.duration();s&&s.isLive()&&(r=this.player_.liveTracker.liveCurrentTime()),this.percent_!==t&&(this.el_.setAttribute("aria-valuenow",(t*100).toFixed(2)),this.percent_=t),(this.currentTime_!==i||this.duration_!==r)&&(this.el_.setAttribute("aria-valuetext",this.localize("progress bar timing: currentTime={1} duration={2}",[Fs(i,r),Fs(r,r)],"{1} of {2}")),this.currentTime_=i,this.duration_=r),this.bar&&this.bar.update(wr(this.el()),this.getProgress(),e)}),t}userSeek_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(e)}getCurrentTime_(){return this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime()}pendingSeekTime(e){if(e!==void 0)if(e!==null){const t=this.player_.duration();this.pendingSeekTime_=Math.max(0,Math.min(e,t))}else this.pendingSeekTime_=null;return this.pendingSeekTime_}getPercent(){if(this.pendingSeekTime()!==null)return this.pendingSeekTime()/this.player_.duration();const e=this.getCurrentTime_();let t;const i=this.player_.liveTracker;return i&&i.isLive()?(t=(e-i.seekableStart())/i.liveWindow(),i.atLiveEdge()&&(t=1)):t=e/this.player_.duration(),t}handleMouseDown(e){$a(e)&&(e.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.shouldDisableSeekWhileScrubbing_||this.player_.pause(),super.handleMouseDown(e))}handleMouseMove(e,t=!1){if(!$a(e)||isNaN(this.player_.duration()))return;!t&&!this.player_.scrubbing()&&this.player_.scrubbing(!0);let i;const s=this.calculateDistance(e),r=this.player_.liveTracker;if(!r||!r.isLive())i=s*this.player_.duration(),i===this.player_.duration()&&(i=i-.1);else{if(s>=.99){r.seekToLiveEdge();return}const a=r.seekableStart(),o=r.liveCurrentTime();if(i=a+s*r.liveWindow(),i>=o&&(i=o),i<=a&&(i=a+.1),i===1/0)return}this.shouldDisableSeekWhileScrubbing_?this.pendingSeekTime(i):this.userSeek_(i),this.player_.options_.enableSmoothSeeking&&this.update()}enable(){super.enable();const e=this.getChild("mouseTimeDisplay");e&&e.show()}disable(){super.disable();const e=this.getChild("mouseTimeDisplay");e&&e.hide()}handleMouseUp(e){super.handleMouseUp(e),e&&e.stopPropagation(),this.player_.scrubbing(!1),this.pendingSeekTime()!==null&&(this.userSeek_(this.pendingSeekTime()),this.pendingSeekTime(null)),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0}),this.videoWasPlaying?fn(this.player_.play()):this.update_()}handlePendingSeek_(e){this.player_.paused()||this.player_.pause();const t=this.pendingSeekTime()!==null?this.pendingSeekTime():this.player_.currentTime();this.pendingSeekTime(t+e),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}stepForward(){this.shouldDisableSeekWhileScrubbing_?this.handlePendingSeek_(this.options().stepSeconds):this.userSeek_(this.player_.currentTime()+this.options().stepSeconds)}stepBack(){this.shouldDisableSeekWhileScrubbing_?this.handlePendingSeek_(-this.options().stepSeconds):this.userSeek_(this.player_.currentTime()-this.options().stepSeconds)}handleAction(e){this.pendingSeekTime()!==null&&(this.userSeek_(this.pendingSeekTime()),this.pendingSeekTime(null)),this.player_.paused()?this.player_.play():this.player_.pause()}handleKeyDown(e){const t=this.player_.liveTracker;if(e.key===" "||e.key==="Enter")e.preventDefault(),e.stopPropagation(),this.handleAction(e);else if(e.key==="Home")e.preventDefault(),e.stopPropagation(),this.userSeek_(0);else if(e.key==="End")e.preventDefault(),e.stopPropagation(),t&&t.isLive()?this.userSeek_(t.liveCurrentTime()):this.userSeek_(this.player_.duration());else if(/^[0-9]$/.test(e.key)){e.preventDefault(),e.stopPropagation();const i=parseInt(e.key,10)*.1;t&&t.isLive()?this.userSeek_(t.seekableStart()+t.liveWindow()*i):this.userSeek_(this.player_.duration()*i)}else e.key==="PageDown"?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()-this.options().stepSeconds*this.options().pageMultiplier)):e.key==="PageUp"?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()+this.options().stepSeconds*this.options().pageMultiplier)):super.handleKeyDown(e)}dispose(){this.disableInterval_(),this.off(this.player_,["durationchange","timeupdate"],this.update),this.off(this.player_,["ended"],this.update_),this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.update),this.off(this.player_,["playing"],this.enableIntervalHandler_),this.off(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in de&&"visibilityState"in de&&this.off(de,"visibilitychange",this.toggleVisibility_),super.dispose()}}ul.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar",stepSeconds:5,pageMultiplier:12},ee.registerComponent("SeekBar",ul);class Ov extends ee{constructor(e,t){super(e,t),this.handleMouseMove=hn(Ze(this,this.handleMouseMove),Pi),this.throttledHandleMouseSeek=hn(Ze(this,this.handleMouseSeek),Pi),this.handleMouseUpHandler_=i=>this.handleMouseUp(i),this.handleMouseDownHandler_=i=>this.handleMouseDown(i),this.enable()}createEl(){return super.createEl("div",{className:"vjs-progress-control vjs-control"})}handleMouseMove(e){const t=this.getChild("seekBar");if(!t)return;const i=t.getChild("playProgressBar"),s=t.getChild("mouseTimeDisplay");if(!i&&!s)return;const r=t.el(),a=Ha(r);let o=Qc(r,e).x;o=Xa(o,0,1),s&&s.update(a,o),i&&i.update(a,t.getProgress())}handleMouseSeek(e){const t=this.getChild("seekBar");t&&t.handleMouseMove(e)}enabled(){return this.enabled_}disable(){if(this.children().forEach(e=>e.disable&&e.disable()),!!this.enabled()&&(this.off(["mousedown","touchstart"],this.handleMouseDownHandler_),this.off(this.el_,["mousemove","touchmove"],this.handleMouseMove),this.removeListenersAddedOnMousedownAndTouchstart(),this.addClass("disabled"),this.enabled_=!1,this.player_.scrubbing())){const e=this.getChild("seekBar");this.player_.scrubbing(!1),e.videoWasPlaying&&fn(this.player_.play())}}enable(){this.children().forEach(e=>e.enable&&e.enable()),!this.enabled()&&(this.on(["mousedown","touchstart"],this.handleMouseDownHandler_),this.on(this.el_,["mousemove","touchmove"],this.handleMouseMove),this.removeClass("disabled"),this.enabled_=!0)}removeListenersAddedOnMousedownAndTouchstart(){const e=this.el_.ownerDocument;this.off(e,"mousemove",this.throttledHandleMouseSeek),this.off(e,"touchmove",this.throttledHandleMouseSeek),this.off(e,"mouseup",this.handleMouseUpHandler_),this.off(e,"touchend",this.handleMouseUpHandler_)}handleMouseDown(e){const t=this.el_.ownerDocument,i=this.getChild("seekBar");i&&i.handleMouseDown(e),this.on(t,"mousemove",this.throttledHandleMouseSeek),this.on(t,"touchmove",this.throttledHandleMouseSeek),this.on(t,"mouseup",this.handleMouseUpHandler_),this.on(t,"touchend",this.handleMouseUpHandler_)}handleMouseUp(e){const t=this.getChild("seekBar");t&&t.handleMouseUp(e),this.removeListenersAddedOnMousedownAndTouchstart()}}Ov.prototype.options_={children:["seekBar"]},ee.registerComponent("ProgressControl",Ov);class Mv extends Wt{constructor(e,t){super(e,t),this.setIcon("picture-in-picture-enter"),this.on(e,["enterpictureinpicture","leavepictureinpicture"],i=>this.handlePictureInPictureChange(i)),this.on(e,["disablepictureinpicturechanged","loadedmetadata"],i=>this.handlePictureInPictureEnabledChange(i)),this.on(e,["loadedmetadata","audioonlymodechange","audiopostermodechange"],()=>this.handlePictureInPictureAudioModeChange()),this.disable()}buildCSSClass(){return`vjs-picture-in-picture-control vjs-hidden ${super.buildCSSClass()}`}handlePictureInPictureAudioModeChange(){if(!(this.player_.currentType().substring(0,5)==="audio"||this.player_.audioPosterMode()||this.player_.audioOnlyMode())){this.show();return}this.player_.isInPictureInPicture()&&this.player_.exitPictureInPicture(),this.hide()}handlePictureInPictureEnabledChange(){de.pictureInPictureEnabled&&this.player_.disablePictureInPicture()===!1||this.player_.options_.enableDocumentPictureInPicture&&"documentPictureInPicture"in B?this.enable():this.disable()}handlePictureInPictureChange(e){this.player_.isInPictureInPicture()?(this.setIcon("picture-in-picture-exit"),this.controlText("Exit Picture-in-Picture")):(this.setIcon("picture-in-picture-enter"),this.controlText("Picture-in-Picture")),this.handlePictureInPictureEnabledChange()}handleClick(e){this.player_.isInPictureInPicture()?this.player_.exitPictureInPicture():this.player_.requestPictureInPicture()}show(){typeof de.exitPictureInPicture=="function"&&super.show()}}Mv.prototype.controlText_="Picture-in-Picture",ee.registerComponent("PictureInPictureToggle",Mv);class Lv extends Wt{constructor(e,t){super(e,t),this.setIcon("fullscreen-enter"),this.on(e,"fullscreenchange",i=>this.handleFullscreenChange(i)),de[e.fsApi_.fullscreenEnabled]===!1&&this.disable()}buildCSSClass(){return`vjs-fullscreen-control ${super.buildCSSClass()}`}handleFullscreenChange(e){this.player_.isFullscreen()?(this.controlText("Exit Fullscreen"),this.setIcon("fullscreen-exit")):(this.controlText("Fullscreen"),this.setIcon("fullscreen-enter"))}handleClick(e){this.player_.isFullscreen()?this.player_.exitFullscreen():this.player_.requestFullscreen()}}Lv.prototype.controlText_="Fullscreen",ee.registerComponent("FullscreenToggle",Lv);const gA=function(n,e){e.tech_&&!e.tech_.featuresVolumeControl&&n.addClass("vjs-hidden"),n.on(e,"loadstart",function(){e.tech_.featuresVolumeControl?n.removeClass("vjs-hidden"):n.addClass("vjs-hidden")})};class yA extends ee{createEl(){const e=super.createEl("div",{className:"vjs-volume-level"});return this.setIcon("circle",e),e.appendChild(super.createEl("span",{className:"vjs-control-text"})),e}}ee.registerComponent("VolumeLevel",yA);class vA extends ee{constructor(e,t){super(e,t),this.update=hn(Ze(this,this.update),Pi)}createEl(){return super.createEl("div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})}update(e,t,i,s){if(!i){const r=wr(this.el_),a=wr(this.player_.el()),o=e.width*t;if(!a||!r)return;const c=e.left-a.left+o,l=e.width-o+(a.right-e.right);let u=r.width/2;c<u?u+=u-c:l<u&&(u=l),u<0?u=0:u>r.width&&(u=r.width),this.el_.style.right=`-${u}px`}this.write(`${s}%`)}write(e){os(this.el_,e)}updateVolume(e,t,i,s,r){this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume",()=>{this.update(e,t,i,s.toFixed(0)),r&&r()})}}ee.registerComponent("VolumeLevelTooltip",vA);class Nv extends ee{constructor(e,t){super(e,t),this.update=hn(Ze(this,this.update),Pi)}createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(e,t,i){const s=100*t;this.getChild("volumeLevelTooltip").updateVolume(e,t,i,s,()=>{i?this.el_.style.bottom=`${e.height*t}px`:this.el_.style.left=`${e.width*t}px`})}}Nv.prototype.options_={children:["volumeLevelTooltip"]},ee.registerComponent("MouseVolumeLevelDisplay",Nv);class dl extends qh{constructor(e,t){super(e,t),this.on("slideractive",i=>this.updateLastVolume_(i)),this.on(e,"volumechange",i=>this.updateARIAAttributes(i)),e.ready(()=>this.updateARIAAttributes())}createEl(){return super.createEl("div",{className:"vjs-volume-bar vjs-slider-bar"},{"aria-label":this.localize("Volume Level"),"aria-live":"polite"})}handleMouseDown(e){$a(e)&&super.handleMouseDown(e)}handleMouseMove(e){const t=this.getChild("mouseVolumeLevelDisplay");if(t){const i=this.el(),s=wr(i),r=this.vertical();let a=Qc(i,e);a=r?a.y:a.x,a=Xa(a,0,1),t.update(s,a,r)}$a(e)&&(this.checkMuted(),this.player_.volume(this.calculateDistance(e)))}checkMuted(){this.player_.muted()&&this.player_.muted(!1)}getPercent(){return this.player_.muted()?0:this.player_.volume()}stepForward(){this.checkMuted(),this.player_.volume(this.player_.volume()+.1)}stepBack(){this.checkMuted(),this.player_.volume(this.player_.volume()-.1)}updateARIAAttributes(e){const t=this.player_.muted()?0:this.volumeAsPercentage_();this.el_.setAttribute("aria-valuenow",t),this.el_.setAttribute("aria-valuetext",t+"%")}volumeAsPercentage_(){return Math.round(this.player_.volume()*100)}updateLastVolume_(){const e=this.player_.volume();this.one("sliderinactive",()=>{this.player_.volume()===0&&this.player_.lastVolume_(e)})}}dl.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"},!Ht&&!Wi&&dl.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay"),dl.prototype.playerEvent="volumechange",ee.registerComponent("VolumeBar",dl);class Fv extends ee{constructor(e,t={}){t.vertical=t.vertical||!1,(typeof t.volumeBar>"u"||Sr(t.volumeBar))&&(t.volumeBar=t.volumeBar||{},t.volumeBar.vertical=t.vertical),super(e,t),gA(this,e),this.throttledHandleMouseMove=hn(Ze(this,this.handleMouseMove),Pi),this.handleMouseUpHandler_=i=>this.handleMouseUp(i),this.on("mousedown",i=>this.handleMouseDown(i)),this.on("touchstart",i=>this.handleMouseDown(i)),this.on("mousemove",i=>this.handleMouseMove(i)),this.on(this.volumeBar,["focus","slideractive"],()=>{this.volumeBar.addClass("vjs-slider-active"),this.addClass("vjs-slider-active"),this.trigger("slideractive")}),this.on(this.volumeBar,["blur","sliderinactive"],()=>{this.volumeBar.removeClass("vjs-slider-active"),this.removeClass("vjs-slider-active"),this.trigger("sliderinactive")})}createEl(){let e="vjs-volume-horizontal";return this.options_.vertical&&(e="vjs-volume-vertical"),super.createEl("div",{className:`vjs-volume-control vjs-control ${e}`})}handleMouseDown(e){const t=this.el_.ownerDocument;this.on(t,"mousemove",this.throttledHandleMouseMove),this.on(t,"touchmove",this.throttledHandleMouseMove),this.on(t,"mouseup",this.handleMouseUpHandler_),this.on(t,"touchend",this.handleMouseUpHandler_)}handleMouseUp(e){const t=this.el_.ownerDocument;this.off(t,"mousemove",this.throttledHandleMouseMove),this.off(t,"touchmove",this.throttledHandleMouseMove),this.off(t,"mouseup",this.handleMouseUpHandler_),this.off(t,"touchend",this.handleMouseUpHandler_)}handleMouseMove(e){this.volumeBar.handleMouseMove(e)}}Fv.prototype.options_={children:["volumeBar"]},ee.registerComponent("VolumeControl",Fv);const bA=function(n,e){e.tech_&&!e.tech_.featuresMuteControl&&n.addClass("vjs-hidden"),n.on(e,"loadstart",function(){e.tech_.featuresMuteControl?n.removeClass("vjs-hidden"):n.addClass("vjs-hidden")})};class Uv extends Wt{constructor(e,t){super(e,t),bA(this,e),this.on(e,["loadstart","volumechange"],i=>this.update(i))}buildCSSClass(){return`vjs-mute-control ${super.buildCSSClass()}`}handleClick(e){const t=this.player_.volume(),i=this.player_.lastVolume_();if(t===0){const s=i<.1?.1:i;this.player_.volume(s),this.player_.muted(!1)}else this.player_.muted(!this.player_.muted())}update(e){this.updateIcon_(),this.updateControlText_()}updateIcon_(){const e=this.player_.volume();let t=3;this.setIcon("volume-high"),Ht&&this.player_.tech_&&this.player_.tech_.el_&&this.player_.muted(this.player_.tech_.el_.muted),e===0||this.player_.muted()?(this.setIcon("volume-mute"),t=0):e<.33?(this.setIcon("volume-low"),t=1):e<.67&&(this.setIcon("volume-medium"),t=2),Xc(this.el_,[0,1,2,3].reduce((i,s)=>i+`${s?" ":""}vjs-vol-${s}`,"")),Ls(this.el_,`vjs-vol-${t}`)}updateControlText_(){const t=this.player_.muted()||this.player_.volume()===0?"Unmute":"Mute";this.controlText()!==t&&this.controlText(t)}}Uv.prototype.controlText_="Mute",ee.registerComponent("MuteToggle",Uv);class Bv extends ee{constructor(e,t={}){typeof t.inline<"u"?t.inline=t.inline:t.inline=!0,(typeof t.volumeControl>"u"||Sr(t.volumeControl))&&(t.volumeControl=t.volumeControl||{},t.volumeControl.vertical=!t.inline),super(e,t),this.handleKeyPressHandler_=i=>this.handleKeyPress(i),this.on(e,["loadstart"],i=>this.volumePanelState_(i)),this.on(this.muteToggle,"keyup",i=>this.handleKeyPress(i)),this.on(this.volumeControl,"keyup",i=>this.handleVolumeControlKeyUp(i)),this.on("keydown",i=>this.handleKeyPress(i)),this.on("mouseover",i=>this.handleMouseOver(i)),this.on("mouseout",i=>this.handleMouseOut(i)),this.on(this.volumeControl,["slideractive"],this.sliderActive_),this.on(this.volumeControl,["sliderinactive"],this.sliderInactive_)}sliderActive_(){this.addClass("vjs-slider-active")}sliderInactive_(){this.removeClass("vjs-slider-active")}volumePanelState_(){this.volumeControl.hasClass("vjs-hidden")&&this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-hidden"),this.volumeControl.hasClass("vjs-hidden")&&!this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-mute-toggle-only")}createEl(){let e="vjs-volume-panel-horizontal";return this.options_.inline||(e="vjs-volume-panel-vertical"),super.createEl("div",{className:`vjs-volume-panel vjs-control ${e}`})}dispose(){this.handleMouseOut(),super.dispose()}handleVolumeControlKeyUp(e){e.key==="Escape"&&this.muteToggle.focus()}handleMouseOver(e){this.addClass("vjs-hover"),vi(de,"keyup",this.handleKeyPressHandler_)}handleMouseOut(e){this.removeClass("vjs-hover"),$t(de,"keyup",this.handleKeyPressHandler_)}handleKeyPress(e){e.key==="Escape"&&this.handleMouseOut()}}Bv.prototype.options_={children:["muteToggle","volumeControl"]},ee.registerComponent("VolumePanel",Bv);class qv extends Wt{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipForwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`forward-${this.skipTime}`),this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipForwardTime(){const e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.forward}buildCSSClass(){return`vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`}handleClick(e){if(isNaN(this.player_.duration()))return;const t=this.player_.currentTime(),i=this.player_.liveTracker,s=i&&i.isLive()?i.seekableEnd():this.player_.duration();let r;t+this.skipTime<=s?r=t+this.skipTime:r=s,this.player_.currentTime(r)}handleLanguagechange(){this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime]))}}qv.prototype.controlText_="Skip Forward",ee.registerComponent("SkipForward",qv);class Vv extends Wt{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipBackwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`replay-${this.skipTime}`),this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipBackwardTime(){const e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.backward}buildCSSClass(){return`vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`}handleClick(e){const t=this.player_.currentTime(),i=this.player_.liveTracker,s=i&&i.isLive()&&i.seekableStart();let r;s&&t-this.skipTime<=s?r=s:t>=this.skipTime?r=t-this.skipTime:r=0,this.player_.currentTime(r)}handleLanguagechange(){this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime]))}}Vv.prototype.controlText_="Skip Backward",ee.registerComponent("SkipBackward",Vv);class jv extends ee{constructor(e,t){super(e,t),t&&(this.menuButton_=t.menuButton),this.focusedChild_=-1,this.on("keydown",i=>this.handleKeyDown(i)),this.boundHandleBlur_=i=>this.handleBlur(i),this.boundHandleTapClick_=i=>this.handleTapClick(i)}addEventListenerForItem(e){e instanceof ee&&(this.on(e,"blur",this.boundHandleBlur_),this.on(e,["tap","click"],this.boundHandleTapClick_))}removeEventListenerForItem(e){e instanceof ee&&(this.off(e,"blur",this.boundHandleBlur_),this.off(e,["tap","click"],this.boundHandleTapClick_))}removeChild(e){typeof e=="string"&&(e=this.getChild(e)),this.removeEventListenerForItem(e),super.removeChild(e)}addItem(e){const t=this.addChild(e);t&&this.addEventListenerForItem(t)}createEl(){const e=this.options_.contentElType||"ul";this.contentEl_=Ee(e,{className:"vjs-menu-content"}),this.contentEl_.setAttribute("role","menu");const t=super.createEl("div",{append:this.contentEl_,className:"vjs-menu"});return t.appendChild(this.contentEl_),vi(t,"click",function(i){i.preventDefault(),i.stopImmediatePropagation()}),t}dispose(){this.contentEl_=null,this.boundHandleBlur_=null,this.boundHandleTapClick_=null,super.dispose()}handleBlur(e){const t=e.relatedTarget||de.activeElement;if(!this.children().some(i=>i.el()===t)){const i=this.menuButton_;i&&i.buttonPressed_&&t!==i.el().firstChild&&i.unpressButton()}}handleTapClick(e){if(this.menuButton_){this.menuButton_.unpressButton();const t=this.children();if(!Array.isArray(t))return;const i=t.filter(s=>s.el()===e.target)[0];if(!i)return;i.name()!=="CaptionSettingsMenuItem"&&this.menuButton_.focus()}}handleKeyDown(e){e.key==="ArrowLeft"||e.key==="ArrowDown"?(e.preventDefault(),e.stopPropagation(),this.stepForward()):(e.key==="ArrowRight"||e.key==="ArrowUp")&&(e.preventDefault(),e.stopPropagation(),this.stepBack())}stepForward(){let e=0;this.focusedChild_!==void 0&&(e=this.focusedChild_+1),this.focus(e)}stepBack(){let e=0;this.focusedChild_!==void 0&&(e=this.focusedChild_-1),this.focus(e)}focus(e=0){const t=this.children().slice();t.length&&t[0].hasClass("vjs-menu-title")&&t.shift(),t.length>0&&(e<0?e=0:e>=t.length&&(e=t.length-1),this.focusedChild_=e,t[e].el_.focus())}}ee.registerComponent("Menu",jv);class Hh extends ee{constructor(e,t={}){super(e,t),this.menuButton_=new Wt(e,t),this.menuButton_.controlText(this.controlText_),this.menuButton_.el_.setAttribute("aria-haspopup","true");const i=Wt.prototype.buildCSSClass();this.menuButton_.el_.className=this.buildCSSClass()+" "+i,this.menuButton_.removeClass("vjs-control"),this.addChild(this.menuButton_),this.update(),this.enabled_=!0;const s=r=>this.handleClick(r);this.handleMenuKeyUp_=r=>this.handleMenuKeyUp(r),this.on(this.menuButton_,"tap",s),this.on(this.menuButton_,"click",s),this.on(this.menuButton_,"keydown",r=>this.handleKeyDown(r)),this.on(this.menuButton_,"mouseenter",()=>{this.addClass("vjs-hover"),this.menu.show(),vi(de,"keyup",this.handleMenuKeyUp_)}),this.on("mouseleave",r=>this.handleMouseLeave(r)),this.on("keydown",r=>this.handleSubmenuKeyDown(r))}update(){const e=this.createMenu();this.menu&&(this.menu.dispose(),this.removeChild(this.menu)),this.menu=e,this.addChild(e),this.buttonPressed_=!1,this.menuButton_.el_.setAttribute("aria-expanded","false"),this.items&&this.items.length<=this.hideThreshold_?(this.hide(),this.menu.contentEl_.removeAttribute("role")):(this.show(),this.menu.contentEl_.setAttribute("role","menu"))}createMenu(){const e=new jv(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){const t=Ee("li",{className:"vjs-menu-title",textContent:pt(this.options_.title),tabIndex:-1}),i=new ee(this.player_,{el:t});e.addItem(i)}if(this.items=this.createItems(),this.items)for(let t=0;t<this.items.length;t++)e.addItem(this.items[t]);return e}createItems(){}createEl(){return super.createEl("div",{className:this.buildWrapperCSSClass()},{})}setIcon(e){return super.setIcon(e,this.menuButton_.el_)}buildWrapperCSSClass(){let e="vjs-menu-button";this.options_.inline===!0?e+="-inline":e+="-popup";const t=Wt.prototype.buildCSSClass();return`vjs-menu-button ${e} ${t} ${super.buildCSSClass()}`}buildCSSClass(){let e="vjs-menu-button";return this.options_.inline===!0?e+="-inline":e+="-popup",`vjs-menu-button ${e} ${super.buildCSSClass()}`}controlText(e,t=this.menuButton_.el()){return this.menuButton_.controlText(e,t)}dispose(){this.handleMouseLeave(),super.dispose()}handleClick(e){this.buttonPressed_?this.unpressButton():this.pressButton()}handleMouseLeave(e){this.removeClass("vjs-hover"),$t(de,"keyup",this.handleMenuKeyUp_)}focus(){this.menuButton_.focus()}blur(){this.menuButton_.blur()}handleKeyDown(e){e.key==="Escape"||e.key==="Tab"?(this.buttonPressed_&&this.unpressButton(),!e.key==="Tab"&&(e.preventDefault(),this.menuButton_.focus())):(e.key==="Up"||e.key==="Down"&&!(this.player_.options_.playerOptions.spatialNavigation&&this.player_.options_.playerOptions.spatialNavigation.enabled))&&(this.buttonPressed_||(e.preventDefault(),this.pressButton()))}handleMenuKeyUp(e){(e.key==="Escape"||e.key==="Tab")&&this.removeClass("vjs-hover")}handleSubmenuKeyPress(e){this.handleSubmenuKeyDown(e)}handleSubmenuKeyDown(e){(e.key==="Escape"||e.key==="Tab")&&(this.buttonPressed_&&this.unpressButton(),!e.key==="Tab"&&(e.preventDefault(),this.menuButton_.focus()))}pressButton(){if(this.enabled_){if(this.buttonPressed_=!0,this.menu.show(),this.menu.lockShowing(),this.menuButton_.el_.setAttribute("aria-expanded","true"),Ht&&qy())return;this.menu.focus()}}unpressButton(){this.enabled_&&(this.buttonPressed_=!1,this.menu.unlockShowing(),this.menu.hide(),this.menuButton_.el_.setAttribute("aria-expanded","false"))}disable(){this.unpressButton(),this.enabled_=!1,this.addClass("vjs-disabled"),this.menuButton_.disable()}enable(){this.enabled_=!0,this.removeClass("vjs-disabled"),this.menuButton_.enable()}}ee.registerComponent("MenuButton",Hh);class $h extends Hh{constructor(e,t){const i=t.tracks;super(e,t),this.items.length<=1&&this.hide(),i&&(this.updateHandler_=Ze(this,this.update),this.cleanupHandler_=Ze(this,this.cleanupTrackListeners_),i.addEventListener("removetrack",this.updateHandler_),i.addEventListener("addtrack",this.updateHandler_),i.addEventListener("labelchange",this.updateHandler_),this.player_.on("ready",this.updateHandler_),this.player_.on("dispose",this.cleanupHandler_))}cleanupTrackListeners_(){if(!this.updateHandler_)return;const e=this.options_.tracks;e&&(e.removeEventListener("removetrack",this.updateHandler_),e.removeEventListener("addtrack",this.updateHandler_),e.removeEventListener("labelchange",this.updateHandler_)),this.player_&&(this.player_.off("ready",this.updateHandler_),this.player_.off("dispose",this.cleanupHandler_)),this.updateHandler_=null,this.cleanupHandler_=null}dispose(){this.cleanupTrackListeners_(),super.dispose()}}ee.registerComponent("TrackButton",$h);class Ya extends ll{constructor(e,t){super(e,t),this.selectable=t.selectable,this.isSelected_=t.selected||!1,this.multiSelectable=t.multiSelectable,this.selected(this.isSelected_),this.selectable?this.multiSelectable?this.el_.setAttribute("role","menuitemcheckbox"):this.el_.setAttribute("role","menuitemradio"):this.el_.setAttribute("role","menuitem")}createEl(e,t,i){this.nonIconControl=!0;const s=super.createEl("li",Object.assign({className:"vjs-menu-item",tabIndex:-1},t),i),r=Ee("span",{className:"vjs-menu-item-text",textContent:this.localize(this.options_.label)});return this.player_.options_.experimentalSvgIcons?s.appendChild(r):s.replaceChild(r,s.querySelector(".vjs-icon-placeholder")),s}handleKeyDown(e){["Tab","Escape","ArrowUp","ArrowLeft","ArrowRight","ArrowDown"].includes(e.key)||super.handleKeyDown(e)}handleClick(e){this.selected(!0)}selected(e){this.selectable&&(e?(this.addClass("vjs-selected"),this.el_.setAttribute("aria-checked","true"),this.controlText(", selected"),this.isSelected_=!0):(this.removeClass("vjs-selected"),this.el_.setAttribute("aria-checked","false"),this.controlText(""),this.isSelected_=!1))}}ee.registerComponent("MenuItem",Ya);class Qa extends Ya{constructor(e,t){const i=t.track,s=e.textTracks();t.label=i.label||i.language||"Unknown",t.selected=i.mode==="showing",super(e,t),this.track=i,this.kinds=(t.kinds||[t.kind||this.track.kind]).filter(Boolean);const r=(...o)=>{this.handleTracksChange.apply(this,o)},a=(...o)=>{this.handleSelectedLanguageChange.apply(this,o)};if(e.on(["loadstart","texttrackchange"],r),s.addEventListener("change",r),s.addEventListener("selectedlanguagechange",a),this.on("dispose",function(){e.off(["loadstart","texttrackchange"],r),s.removeEventListener("change",r),s.removeEventListener("selectedlanguagechange",a)}),s.onchange===void 0){let o;this.on(["tap","click"],function(){if(typeof B.Event!="object")try{o=new B.Event("change")}catch{}o||(o=de.createEvent("Event"),o.initEvent("change",!0,!0)),s.dispatchEvent(o)})}this.handleTracksChange()}handleClick(e){const t=this.track,i=this.player_.textTracks();if(super.handleClick(e),!!i)for(let s=0;s<i.length;s++){const r=i[s];this.kinds.indexOf(r.kind)!==-1&&(r===t?r.mode!=="showing"&&(r.mode="showing"):r.mode!=="disabled"&&(r.mode="disabled"))}}handleTracksChange(e){const t=this.track.mode==="showing";t!==this.isSelected_&&this.selected(t)}handleSelectedLanguageChange(e){if(this.track.mode==="showing"){const t=this.player_.cache_.selectedLanguage;if(t&&t.enabled&&t.language===this.track.language&&t.kind!==this.track.kind)return;this.player_.cache_.selectedLanguage={enabled:!0,language:this.track.language,kind:this.track.kind}}}dispose(){this.track=null,super.dispose()}}ee.registerComponent("TextTrackMenuItem",Qa);class Hv extends Qa{constructor(e,t){t.track={player:e,kind:t.kind,kinds:t.kinds,default:!1,mode:"disabled"},t.kinds||(t.kinds=[t.kind]),t.label?t.track.label=t.label:t.track.label=t.kinds.join(" and ")+" off",t.selectable=!0,t.multiSelectable=!1,super(e,t)}handleTracksChange(e){const t=this.player().textTracks();let i=!0;for(let s=0,r=t.length;s<r;s++){const a=t[s];if(this.options_.kinds.indexOf(a.kind)>-1&&a.mode==="showing"){i=!1;break}}i!==this.isSelected_&&this.selected(i)}handleSelectedLanguageChange(e){const t=this.player().textTracks();let i=!0;for(let s=0,r=t.length;s<r;s++){const a=t[s];if(["captions","descriptions","subtitles"].indexOf(a.kind)>-1&&a.mode==="showing"){i=!1;break}}i&&(this.player_.cache_.selectedLanguage={enabled:!1})}handleLanguagechange(){this.$(".vjs-menu-item-text").textContent=this.player_.localize(this.options_.label),super.handleLanguagechange()}}ee.registerComponent("OffTextTrackMenuItem",Hv);class Mr extends $h{constructor(e,t={}){t.tracks=e.textTracks(),super(e,t)}createItems(e=[],t=Qa){let i;this.label_&&(i=`${this.label_} off`),e.push(new Hv(this.player_,{kinds:this.kinds_,kind:this.kind_,label:i})),this.hideThreshold_+=1;const s=this.player_.textTracks();Array.isArray(this.kinds_)||(this.kinds_=[this.kind_]);for(let r=0;r<s.length;r++){const a=s[r];if(this.kinds_.indexOf(a.kind)>-1){const o=new t(this.player_,{track:a,kinds:this.kinds_,kind:this.kind_,selectable:!0,multiSelectable:!1});o.addClass(`vjs-${a.kind}-menu-item`),e.push(o)}}return e}}ee.registerComponent("TextTrackButton",Mr);class $v extends Ya{constructor(e,t){const i=t.track,s=t.cue,r=e.currentTime();t.selectable=!0,t.multiSelectable=!1,t.label=s.text,t.selected=s.startTime<=r&&r<s.endTime,super(e,t),this.track=i,this.cue=s}handleClick(e){super.handleClick(),this.player_.currentTime(this.cue.startTime)}}ee.registerComponent("ChaptersTrackMenuItem",$v);class Wh extends Mr{constructor(e,t,i){super(e,t,i),this.setIcon("chapters"),this.selectCurrentItem_=()=>{this.items.forEach(s=>{s.selected(this.track_.activeCues[0]===s.cue)})}}buildCSSClass(){return`vjs-chapters-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-chapters-button ${super.buildWrapperCSSClass()}`}update(e){if(e&&e.track&&e.track.kind!=="chapters")return;const t=this.findChaptersTrack();t!==this.track_?(this.setTrack(t),super.update()):(!this.items||t&&t.cues&&t.cues.length!==this.items.length)&&super.update()}setTrack(e){if(this.track_!==e){if(this.updateHandler_||(this.updateHandler_=this.update.bind(this)),this.track_){const t=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);t&&t.removeEventListener("load",this.updateHandler_),this.track_.removeEventListener("cuechange",this.selectCurrentItem_),this.track_=null}if(this.track_=e,this.track_){this.track_.mode="hidden";const t=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);t&&t.addEventListener("load",this.updateHandler_),this.track_.addEventListener("cuechange",this.selectCurrentItem_)}}}findChaptersTrack(){const e=this.player_.textTracks()||[];for(let t=e.length-1;t>=0;t--){const i=e[t];if(i.kind===this.kind_)return i}}getMenuCaption(){return this.track_&&this.track_.label?this.track_.label:this.localize(pt(this.kind_))}createMenu(){return this.options_.title=this.getMenuCaption(),super.createMenu()}createItems(){const e=[];if(!this.track_)return e;const t=this.track_.cues;if(!t)return e;for(let i=0,s=t.length;i<s;i++){const r=t[i],a=new $v(this.player_,{track:this.track_,cue:r});e.push(a)}return e}}Wh.prototype.kind_="chapters",Wh.prototype.controlText_="Chapters",ee.registerComponent("ChaptersButton",Wh);class zh extends Mr{constructor(e,t,i){super(e,t,i),this.setIcon("audio-description");const s=e.textTracks(),r=Ze(this,this.handleTracksChange);s.addEventListener("change",r),this.on("dispose",function(){s.removeEventListener("change",r)})}handleTracksChange(e){const t=this.player().textTracks();let i=!1;for(let s=0,r=t.length;s<r;s++){const a=t[s];if(a.kind!==this.kind_&&a.mode==="showing"){i=!0;break}}i?this.disable():this.enable()}buildCSSClass(){return`vjs-descriptions-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-descriptions-button ${super.buildWrapperCSSClass()}`}}zh.prototype.kind_="descriptions",zh.prototype.controlText_="Descriptions",ee.registerComponent("DescriptionsButton",zh);class Gh extends Mr{constructor(e,t,i){super(e,t,i),this.setIcon("subtitles")}buildCSSClass(){return`vjs-subtitles-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-subtitles-button ${super.buildWrapperCSSClass()}`}}Gh.prototype.kind_="subtitles",Gh.prototype.controlText_="Subtitles",ee.registerComponent("SubtitlesButton",Gh);class Kh extends Qa{constructor(e,t){t.track={player:e,kind:t.kind,label:t.kind+" settings",selectable:!1,default:!1,mode:"disabled"},t.selectable=!1,t.name="CaptionSettingsMenuItem",super(e,t),this.addClass("vjs-texttrack-settings"),this.controlText(", opens "+t.kind+" settings dialog")}handleClick(e){this.player().getChild("textTrackSettings").open()}handleLanguagechange(){this.$(".vjs-menu-item-text").textContent=this.player_.localize(this.options_.kind+" settings"),super.handleLanguagechange()}}ee.registerComponent("CaptionSettingsMenuItem",Kh);class Xh extends Mr{constructor(e,t,i){super(e,t,i),this.setIcon("captions")}buildCSSClass(){return`vjs-captions-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-captions-button ${super.buildWrapperCSSClass()}`}createItems(){const e=[];return!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild("textTrackSettings")&&(e.push(new Kh(this.player_,{kind:this.kind_})),this.hideThreshold_+=1),super.createItems(e)}}Xh.prototype.kind_="captions",Xh.prototype.controlText_="Captions",ee.registerComponent("CaptionsButton",Xh);class Wv extends Qa{createEl(e,t,i){const s=super.createEl(e,t,i),r=s.querySelector(".vjs-menu-item-text");return this.options_.track.kind==="captions"&&(this.player_.options_.experimentalSvgIcons?this.setIcon("captions",s):r.appendChild(Ee("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),r.appendChild(Ee("span",{className:"vjs-control-text",textContent:` ${this.localize("Captions")}`}))),s}}ee.registerComponent("SubsCapsMenuItem",Wv);class Yh extends Mr{constructor(e,t={}){super(e,t),this.label_="subtitles",this.setIcon("subtitles"),["en","en-us","en-ca","fr-ca"].indexOf(this.player_.language_)>-1&&(this.label_="captions",this.setIcon("captions")),this.menuButton_.controlText(pt(this.label_))}buildCSSClass(){return`vjs-subs-caps-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-subs-caps-button ${super.buildWrapperCSSClass()}`}createItems(){let e=[];return!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild("textTrackSettings")&&(e.push(new Kh(this.player_,{kind:this.label_})),this.hideThreshold_+=1),e=super.createItems(e,Wv),e}}Yh.prototype.kinds_=["captions","subtitles"],Yh.prototype.controlText_="Subtitles",ee.registerComponent("SubsCapsButton",Yh);class zv extends Ya{constructor(e,t){const i=t.track,s=e.audioTracks();t.label=i.label||i.language||"Unknown",t.selected=i.enabled,super(e,t),this.track=i,this.addClass(`vjs-${i.kind}-menu-item`);const r=(...a)=>{this.handleTracksChange.apply(this,a)};s.addEventListener("change",r),this.on("dispose",()=>{s.removeEventListener("change",r)})}createEl(e,t,i){const s=super.createEl(e,t,i),r=s.querySelector(".vjs-menu-item-text");return["main-desc","descriptions","description"].indexOf(this.options_.track.kind)>=0&&(r.appendChild(Ee("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),r.appendChild(Ee("span",{className:"vjs-control-text",textContent:" "+this.localize("Descriptions")}))),s}handleClick(e){if(super.handleClick(e),this.track.enabled=!0,this.player_.tech_.featuresNativeAudioTracks){const t=this.player_.audioTracks();for(let i=0;i<t.length;i++){const s=t[i];s!==this.track&&(s.enabled=s===this.track)}}}handleTracksChange(e){this.selected(this.track.enabled)}}ee.registerComponent("AudioTrackMenuItem",zv);class Gv extends $h{constructor(e,t={}){t.tracks=e.audioTracks(),super(e,t),this.setIcon("audio")}buildCSSClass(){return`vjs-audio-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-audio-button ${super.buildWrapperCSSClass()}`}createItems(e=[]){this.hideThreshold_=1;const t=this.player_.audioTracks();for(let i=0;i<t.length;i++){const s=t[i];e.push(new zv(this.player_,{track:s,selectable:!0,multiSelectable:!1}))}return e}}Gv.prototype.controlText_="Audio Track",ee.registerComponent("AudioTrackButton",Gv);class Qh extends Ya{constructor(e,t){const i=t.rate,s=parseFloat(i,10);t.label=i,t.selected=s===e.playbackRate(),t.selectable=!0,t.multiSelectable=!1,super(e,t),this.label=i,this.rate=s,this.on(e,"ratechange",r=>this.update(r))}handleClick(e){super.handleClick(),this.player().playbackRate(this.rate)}update(e){this.selected(this.player().playbackRate()===this.rate)}}Qh.prototype.contentElType="button",ee.registerComponent("PlaybackRateMenuItem",Qh);class Kv extends Hh{constructor(e,t){super(e,t),this.menuButton_.el_.setAttribute("aria-describedby",this.labelElId_),this.updateVisibility(),this.updateLabel(),this.on(e,"loadstart",i=>this.updateVisibility(i)),this.on(e,"ratechange",i=>this.updateLabel(i)),this.on(e,"playbackrateschange",i=>this.handlePlaybackRateschange(i))}createEl(){const e=super.createEl();return this.labelElId_="vjs-playback-rate-value-label-"+this.id_,this.labelEl_=Ee("div",{className:"vjs-playback-rate-value",id:this.labelElId_,textContent:"1x"}),e.appendChild(this.labelEl_),e}dispose(){this.labelEl_=null,super.dispose()}buildCSSClass(){return`vjs-playback-rate ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-playback-rate ${super.buildWrapperCSSClass()}`}createItems(){const e=this.playbackRates(),t=[];for(let i=e.length-1;i>=0;i--)t.push(new Qh(this.player(),{rate:e[i]+"x"}));return t}handlePlaybackRateschange(e){this.update()}playbackRates(){const e=this.player();return e.playbackRates&&e.playbackRates()||[]}playbackRateSupported(){return this.player().tech_&&this.player().tech_.featuresPlaybackRate&&this.playbackRates()&&this.playbackRates().length>0}updateVisibility(e){this.playbackRateSupported()?this.removeClass("vjs-hidden"):this.addClass("vjs-hidden")}updateLabel(e){this.playbackRateSupported()&&(this.labelEl_.textContent=this.player().playbackRate()+"x")}}Kv.prototype.controlText_="Playback Rate",ee.registerComponent("PlaybackRateMenuButton",Kv);class Xv extends ee{buildCSSClass(){return`vjs-spacer ${super.buildCSSClass()}`}createEl(e="div",t={},i={}){return t.className||(t.className=this.buildCSSClass()),super.createEl(e,t,i)}}ee.registerComponent("Spacer",Xv);class TA extends Xv{buildCSSClass(){return`vjs-custom-control-spacer ${super.buildCSSClass()}`}createEl(){return super.createEl("div",{className:this.buildCSSClass(),textContent:" "})}}ee.registerComponent("CustomControlSpacer",TA);class Yv extends ee{createEl(){return super.createEl("div",{className:"vjs-control-bar",dir:"ltr"})}}Yv.prototype.options_={children:["playToggle","skipBackward","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","pictureInPictureToggle","fullscreenToggle"]},ee.registerComponent("ControlBar",Yv);class Qv extends Pr{constructor(e,t){super(e,t),this.on(e,"error",i=>{this.open(i)})}buildCSSClass(){return`vjs-error-display ${super.buildCSSClass()}`}content(){const e=this.player().error();return e?this.localize(e.message):""}}Qv.prototype.options_=Object.assign({},Pr.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0}),ee.registerComponent("ErrorDisplay",Qv);class Jv extends ee{constructor(e,t={}){super(e,t),this.el_.setAttribute("aria-labelledby",this.selectLabelledbyIds)}createEl(){return this.selectLabelledbyIds=[this.options_.legendId,this.options_.labelId].join(" ").trim(),Ee("select",{id:this.options_.id},{},this.options_.SelectOptions.map(t=>{const i=(this.options_.labelId?this.options_.labelId:`vjs-track-option-${Di()}`)+"-"+t[1].replace(/\W+/g,""),s=Ee("option",{id:i,value:this.localize(t[0]),textContent:this.localize(t[1])});return s.setAttribute("aria-labelledby",`${this.selectLabelledbyIds} ${i}`),s}))}}ee.registerComponent("TextTrackSelect",Jv);class Vs extends ee{constructor(e,t={}){super(e,t);const i=Ee("legend",{textContent:this.localize(this.options_.legendText),id:this.options_.legendId});this.el().appendChild(i);const s=this.options_.selects;for(const r of s){const a=this.options_.selectConfigs[r],o=a.className,c=a.id.replace("%s",this.options_.id_);let l=null;const u=`vjs_select_${Di()}`;if(this.options_.type==="colors"){l=Ee("span",{className:o});const p=Ee("label",{id:c,className:"vjs-label",textContent:this.localize(a.label)});p.setAttribute("for",u),l.appendChild(p)}const h=new Jv(e,{SelectOptions:a.options,legendId:this.options_.legendId,id:u,labelId:c});this.addChild(h),this.options_.type==="colors"&&(l.appendChild(h.el()),this.el().appendChild(l))}}createEl(){return Ee("fieldset",{className:this.options_.className})}}ee.registerComponent("TextTrackFieldset",Vs);class Zv extends ee{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,s=new Vs(e,{id_:i,legendId:`captions-text-legend-${i}`,legendText:this.localize("Text"),className:"vjs-fg vjs-track-setting",selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(s);const r=new Vs(e,{id_:i,legendId:`captions-background-${i}`,legendText:this.localize("Text Background"),className:"vjs-bg vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(r);const a=new Vs(e,{id_:i,legendId:`captions-window-${i}`,legendText:this.localize("Caption Area Background"),className:"vjs-window vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(a)}createEl(){return Ee("div",{className:"vjs-track-settings-colors"})}}ee.registerComponent("TextTrackSettingsColors",Zv);class eb extends ee{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,s=new Vs(e,{id_:i,legendId:`captions-font-size-${i}`,legendText:"Font Size",className:"vjs-font-percent vjs-track-setting",selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(s);const r=new Vs(e,{id_:i,legendId:`captions-edge-style-${i}`,legendText:this.localize("Text Edge Style"),className:"vjs-edge-style vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(r);const a=new Vs(e,{id_:i,legendId:`captions-font-family-${i}`,legendText:this.localize("Font Family"),className:"vjs-font-family vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(a)}createEl(){return Ee("div",{className:"vjs-track-settings-font"})}}ee.registerComponent("TextTrackSettingsFont",eb);class tb extends ee{constructor(e,t={}){super(e,t);const i=new Wt(e,{controlText:this.localize("restore all settings to the default values"),className:"vjs-default-button"});i.el().classList.remove("vjs-control","vjs-button"),i.el().textContent=this.localize("Reset"),this.addChild(i);const s=this.localize("Done"),r=new Wt(e,{controlText:s,className:"vjs-done-button"});r.el().classList.remove("vjs-control","vjs-button"),r.el().textContent=s,this.addChild(r)}createEl(){return Ee("div",{className:"vjs-track-settings-controls"})}}ee.registerComponent("TrackSettingsControls",tb);const Jh="vjs-text-track-settings",ib=["#000","Black"],nb=["#00F","Blue"],sb=["#0FF","Cyan"],rb=["#0F0","Green"],ab=["#F0F","Magenta"],ob=["#F00","Red"],cb=["#FFF","White"],lb=["#FF0","Yellow"],Zh=["1","Opaque"],ef=["0.5","Semi-Transparent"],ub=["0","Transparent"],us={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[ib,cb,ob,rb,nb,lb,ab,sb],className:"vjs-bg-color"},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Opacity",options:[Zh,ef,ub],className:"vjs-bg-opacity vjs-opacity"},color:{selector:".vjs-text-color > select",id:"captions-foreground-color-%s",label:"Color",options:[cb,ib,ob,rb,nb,lb,ab,sb],className:"vjs-text-color"},edgeStyle:{selector:".vjs-edge-style > select",id:"",label:"Text Edge Style",options:[["none","None"],["raised","Raised"],["depressed","Depressed"],["uniform","Uniform"],["dropshadow","Drop shadow"]]},fontFamily:{selector:".vjs-font-family > select",id:"",label:"Font Family",options:[["proportionalSansSerif","Proportional Sans-Serif"],["monospaceSansSerif","Monospace Sans-Serif"],["proportionalSerif","Proportional Serif"],["monospaceSerif","Monospace Serif"],["casual","Casual"],["script","Script"],["small-caps","Small Caps"]]},fontPercent:{selector:".vjs-font-percent > select",id:"",label:"Font Size",options:[["0.50","50%"],["0.75","75%"],["1.00","100%"],["1.25","125%"],["1.50","150%"],["1.75","175%"],["2.00","200%"],["3.00","300%"],["4.00","400%"]],default:2,parser:n=>n==="1.00"?null:Number(n)},textOpacity:{selector:".vjs-text-opacity > select",id:"captions-foreground-opacity-%s",label:"Opacity",options:[Zh,ef],className:"vjs-text-opacity vjs-opacity"},windowColor:{selector:".vjs-window-color > select",id:"captions-window-color-%s",label:"Color",className:"vjs-window-color"},windowOpacity:{selector:".vjs-window-opacity > select",id:"captions-window-opacity-%s",label:"Opacity",options:[ub,ef,Zh],className:"vjs-window-opacity vjs-opacity"}};us.windowColor.options=us.backgroundColor.options;function db(n,e){if(e&&(n=e(n)),n&&n!=="none")return n}function _A(n,e){const t=n.options[n.options.selectedIndex].value;return db(t,e)}function SA(n,e,t){if(e){for(let i=0;i<n.options.length;i++)if(db(n.options[i].value,t)===e){n.selectedIndex=i;break}}}class CA extends Pr{constructor(e,t){t.temporary=!1,super(e,t),this.updateDisplay=this.updateDisplay.bind(this),this.fill(),this.hasBeenOpened_=this.hasBeenFilled_=!0,this.renderModalComponents(e),this.endDialog=Ee("p",{className:"vjs-control-text",textContent:this.localize("End of dialog window.")}),this.el().appendChild(this.endDialog),this.setDefaults(),t.persistTextTrackSettings===void 0&&(this.options_.persistTextTrackSettings=this.options_.playerOptions.persistTextTrackSettings),this.bindFunctionsToSelectsAndButtons(),this.options_.persistTextTrackSettings&&this.restoreSettings()}renderModalComponents(e){const t=new Zv(e,{textTrackComponentid:this.id_,selectConfigs:us,fieldSets:[["color","textOpacity"],["backgroundColor","backgroundOpacity"],["windowColor","windowOpacity"]]});this.addChild(t);const i=new eb(e,{textTrackComponentid:this.id_,selectConfigs:us,fieldSets:[["fontPercent"],["edgeStyle"],["fontFamily"]]});this.addChild(i);const s=new tb(e);this.addChild(s)}bindFunctionsToSelectsAndButtons(){this.on(this.$(".vjs-done-button"),["click","tap"],()=>{this.saveSettings(),this.close()}),this.on(this.$(".vjs-default-button"),["click","tap"],()=>{this.setDefaults(),this.updateDisplay()}),_r(us,e=>{this.on(this.$(e.selector),"change",this.updateDisplay)})}dispose(){this.endDialog=null,super.dispose()}label(){return this.localize("Caption Settings Dialog")}description(){return this.localize("Beginning of dialog window. Escape will cancel and close the window.")}buildCSSClass(){return super.buildCSSClass()+" vjs-text-track-settings"}getValues(){return Ry(us,(e,t,i)=>{const s=_A(this.$(t.selector),t.parser);return s!==void 0&&(e[i]=s),e},{})}setValues(e){_r(us,(t,i)=>{SA(this.$(t.selector),e[i],t.parser)})}setDefaults(){_r(us,e=>{const t=e.hasOwnProperty("default")?e.default:0;this.$(e.selector).selectedIndex=t})}restoreSettings(){let e;try{e=JSON.parse(B.localStorage.getItem(Jh))}catch(t){Oe.warn(t)}e&&this.setValues(e)}saveSettings(){if(!this.options_.persistTextTrackSettings)return;const e=this.getValues();try{Object.keys(e).length?B.localStorage.setItem(Jh,JSON.stringify(e)):B.localStorage.removeItem(Jh)}catch(t){Oe.warn(t)}}updateDisplay(){const e=this.player_.getChild("textTrackDisplay");e&&e.updateDisplay()}handleLanguagechange(){this.fill(),this.renderModalComponents(this.player_),this.bindFunctionsToSelectsAndButtons()}}ee.registerComponent("TextTrackSettings",CA);class kA extends ee{constructor(e,t){let i=t.ResizeObserver||B.ResizeObserver;t.ResizeObserver===null&&(i=!1);const s=Qe({createEl:!i,reportTouchActivity:!1},t);super(e,s),this.ResizeObserver=t.ResizeObserver||B.ResizeObserver,this.loadListener_=null,this.resizeObserver_=null,this.debouncedHandler_=nv(()=>{this.resizeHandler()},100,!1,this),i?(this.resizeObserver_=new this.ResizeObserver(this.debouncedHandler_),this.resizeObserver_.observe(e.el())):(this.loadListener_=()=>{if(!this.el_||!this.el_.contentWindow)return;const r=this.debouncedHandler_;let a=this.unloadListener_=function(){$t(this,"resize",r),$t(this,"unload",a),a=null};vi(this.el_.contentWindow,"unload",a),vi(this.el_.contentWindow,"resize",r)},this.one("load",this.loadListener_))}createEl(){return super.createEl("iframe",{className:"vjs-resize-manager",tabIndex:-1,title:this.localize("No content")},{"aria-hidden":"true"})}resizeHandler(){!this.player_||!this.player_.trigger||this.player_.trigger("playerresize")}dispose(){this.debouncedHandler_&&this.debouncedHandler_.cancel(),this.resizeObserver_&&(this.player_.el()&&this.resizeObserver_.unobserve(this.player_.el()),this.resizeObserver_.disconnect()),this.loadListener_&&this.off("load",this.loadListener_),this.el_&&this.el_.contentWindow&&this.unloadListener_&&this.unloadListener_.call(this.el_.contentWindow),this.ResizeObserver=null,this.resizeObserver=null,this.debouncedHandler_=null,this.loadListener_=null,super.dispose()}}ee.registerComponent("ResizeManager",kA);const EA={trackingThreshold:20,liveTolerance:15};class xA extends ee{constructor(e,t){const i=Qe(EA,t,{createEl:!1});super(e,i),this.trackLiveHandler_=()=>this.trackLive_(),this.handlePlay_=s=>this.handlePlay(s),this.handleFirstTimeupdate_=s=>this.handleFirstTimeupdate(s),this.handleSeeked_=s=>this.handleSeeked(s),this.seekToLiveEdge_=s=>this.seekToLiveEdge(s),this.reset_(),this.on(this.player_,"durationchange",s=>this.handleDurationchange(s)),this.on(this.player_,"canplay",()=>this.toggleTracking())}trackLive_(){const e=this.player_.seekable();if(!e||!e.length)return;const t=Number(B.performance.now().toFixed(4)),i=this.lastTime_===-1?0:(t-this.lastTime_)/1e3;this.lastTime_=t,this.pastSeekEnd_=this.pastSeekEnd()+i;const s=this.liveCurrentTime(),r=this.player_.currentTime();let a=this.player_.paused()||this.seekedBehindLive_||Math.abs(s-r)>this.options_.liveTolerance;(!this.timeupdateSeen_||s===1/0)&&(a=!1),a!==this.behindLiveEdge_&&(this.behindLiveEdge_=a,this.trigger("liveedgechange"))}handleDurationchange(){this.toggleTracking()}toggleTracking(){this.player_.duration()===1/0&&this.liveWindow()>=this.options_.trackingThreshold?(this.player_.options_.liveui&&this.player_.addClass("vjs-liveui"),this.startTracking()):(this.player_.removeClass("vjs-liveui"),this.stopTracking())}startTracking(){this.isTracking()||(this.timeupdateSeen_||(this.timeupdateSeen_=this.player_.hasStarted()),this.trackingInterval_=this.setInterval(this.trackLiveHandler_,Pi),this.trackLive_(),this.on(this.player_,["play","pause"],this.trackLiveHandler_),this.timeupdateSeen_?this.on(this.player_,"seeked",this.handleSeeked_):(this.one(this.player_,"play",this.handlePlay_),this.one(this.player_,"timeupdate",this.handleFirstTimeupdate_)))}handleFirstTimeupdate(){this.timeupdateSeen_=!0,this.on(this.player_,"seeked",this.handleSeeked_)}handleSeeked(){const e=Math.abs(this.liveCurrentTime()-this.player_.currentTime());this.seekedBehindLive_=this.nextSeekedFromUser_&&e>2,this.nextSeekedFromUser_=!1,this.trackLive_()}handlePlay(){this.one(this.player_,"timeupdate",this.seekToLiveEdge_)}reset_(){this.lastTime_=-1,this.pastSeekEnd_=0,this.lastSeekEnd_=-1,this.behindLiveEdge_=!0,this.timeupdateSeen_=!1,this.seekedBehindLive_=!1,this.nextSeekedFromUser_=!1,this.clearInterval(this.trackingInterval_),this.trackingInterval_=null,this.off(this.player_,["play","pause"],this.trackLiveHandler_),this.off(this.player_,"seeked",this.handleSeeked_),this.off(this.player_,"play",this.handlePlay_),this.off(this.player_,"timeupdate",this.handleFirstTimeupdate_),this.off(this.player_,"timeupdate",this.seekToLiveEdge_)}nextSeekedFromUser(){this.nextSeekedFromUser_=!0}stopTracking(){this.isTracking()&&(this.reset_(),this.trigger("liveedgechange"))}seekableEnd(){const e=this.player_.seekable(),t=[];let i=e?e.length:0;for(;i--;)t.push(e.end(i));return t.length?t.sort()[t.length-1]:1/0}seekableStart(){const e=this.player_.seekable(),t=[];let i=e?e.length:0;for(;i--;)t.push(e.start(i));return t.length?t.sort()[0]:0}liveWindow(){const e=this.liveCurrentTime();return e===1/0?0:e-this.seekableStart()}isLive(){return this.isTracking()}atLiveEdge(){return!this.behindLiveEdge()}liveCurrentTime(){return this.pastSeekEnd()+this.seekableEnd()}pastSeekEnd(){const e=this.seekableEnd();return this.lastSeekEnd_!==-1&&e!==this.lastSeekEnd_&&(this.pastSeekEnd_=0),this.lastSeekEnd_=e,this.pastSeekEnd_}behindLiveEdge(){return this.behindLiveEdge_}isTracking(){return typeof this.trackingInterval_=="number"}seekToLiveEdge(){this.seekedBehindLive_=!1,!this.atLiveEdge()&&(this.nextSeekedFromUser_=!1,this.player_.currentTime(this.liveCurrentTime()))}dispose(){this.stopTracking(),super.dispose()}}ee.registerComponent("LiveTracker",xA);class wA extends ee{constructor(e,t){super(e,t),this.on("statechanged",i=>this.updateDom_()),this.updateDom_()}createEl(){return this.els={title:Ee("div",{className:"vjs-title-bar-title",id:`vjs-title-bar-title-${Di()}`}),description:Ee("div",{className:"vjs-title-bar-description",id:`vjs-title-bar-description-${Di()}`})},Ee("div",{className:"vjs-title-bar"},{},Oy(this.els))}updateDom_(){const e=this.player_.tech_,t=e&&e.el_,i={title:"aria-labelledby",description:"aria-describedby"};["title","description"].forEach(s=>{const r=this.state[s],a=this.els[s],o=i[s];Jc(a),r&&os(a,r),t&&(t.removeAttribute(o),r&&t.setAttribute(o,a.id))}),this.state.title||this.state.description?this.show():this.hide()}update(e){this.setState(e)}dispose(){const e=this.player_.tech_,t=e&&e.el_;t&&(t.removeAttribute("aria-labelledby"),t.removeAttribute("aria-describedby")),super.dispose(),this.els=null}}ee.registerComponent("TitleBar",wA);const AA={initialDisplay:4e3,position:[],takeFocus:!1};class DA extends Wt{constructor(e,t){t=Qe(AA,t),super(e,t),this.controlText(t.controlText),this.hide(),this.on(this.player_,["useractive","userinactive"],i=>{this.removeClass("force-display")})}buildCSSClass(){return`vjs-transient-button focus-visible ${this.options_.position.map(e=>`vjs-${e}`).join(" ")}`}createEl(){const e=Ee("button",{},{type:"button",class:this.buildCSSClass()},Ee("span"));return this.controlTextEl_=e.querySelector("span"),e}show(){super.show(),this.addClass("force-display"),this.options_.takeFocus&&this.el().focus({preventScroll:!0}),this.forceDisplayTimeout=this.player_.setTimeout(()=>{this.removeClass("force-display")},this.options_.initialDisplay)}hide(){this.removeClass("force-display"),super.hide()}dispose(){this.player_.clearTimeout(this.forceDisplayTimeout),super.dispose()}}ee.registerComponent("TransientButton",DA);const tf=n=>{const e=n.el();if(e.hasAttribute("src"))return n.triggerSourceset(e.src),!0;const t=n.$$("source"),i=[];let s="";if(!t.length)return!1;for(let r=0;r<t.length;r++){const a=t[r].src;a&&i.indexOf(a)===-1&&i.push(a)}return i.length?(i.length===1&&(s=i[0]),n.triggerSourceset(s),!0):!1},PA=Object.defineProperty({},"innerHTML",{get(){return this.cloneNode(!0).innerHTML},set(n){const e=de.createElement(this.nodeName.toLowerCase());e.innerHTML=n;const t=de.createDocumentFragment();for(;e.childNodes.length;)t.appendChild(e.childNodes[0]);return this.innerText="",B.Element.prototype.appendChild.call(this,t),this.innerHTML}}),hb=(n,e)=>{let t={};for(let i=0;i<n.length&&(t=Object.getOwnPropertyDescriptor(n[i],e),!(t&&t.set&&t.get));i++);return t.enumerable=!0,t.configurable=!0,t},IA=n=>hb([n.el(),B.HTMLMediaElement.prototype,B.Element.prototype,PA],"innerHTML"),fb=function(n){const e=n.el();if(e.resetSourceWatch_)return;const t={},i=IA(n),s=r=>(...a)=>{const o=r.apply(e,a);return tf(n),o};["append","appendChild","insertAdjacentHTML"].forEach(r=>{e[r]&&(t[r]=e[r],e[r]=s(t[r]))}),Object.defineProperty(e,"innerHTML",Qe(i,{set:s(i.set)})),e.resetSourceWatch_=()=>{e.resetSourceWatch_=null,Object.keys(t).forEach(r=>{e[r]=t[r]}),Object.defineProperty(e,"innerHTML",i)},n.one("sourceset",e.resetSourceWatch_)},RA=Object.defineProperty({},"src",{get(){return this.hasAttribute("src")?gv(B.Element.prototype.getAttribute.call(this,"src")):""},set(n){return B.Element.prototype.setAttribute.call(this,"src",n),n}}),OA=n=>hb([n.el(),B.HTMLMediaElement.prototype,RA],"src"),MA=function(n){if(!n.featuresSourceset)return;const e=n.el();if(e.resetSourceset_)return;const t=OA(n),i=e.setAttribute,s=e.load;Object.defineProperty(e,"src",Qe(t,{set:r=>{const a=t.set.call(e,r);return n.triggerSourceset(e.src),a}})),e.setAttribute=(r,a)=>{const o=i.call(e,r,a);return/src/i.test(r)&&n.triggerSourceset(e.src),o},e.load=()=>{const r=s.call(e);return tf(n)||(n.triggerSourceset(""),fb(n)),r},e.currentSrc?n.triggerSourceset(e.currentSrc):tf(n)||fb(n),e.resetSourceset_=()=>{e.resetSourceset_=null,e.load=s,e.setAttribute=i,Object.defineProperty(e,"src",t),e.resetSourceWatch_&&e.resetSourceWatch_()}};class ye extends De{constructor(e,t){super(e,t);const i=e.source;let s=!1;if(this.featuresVideoFrameCallback=this.featuresVideoFrameCallback&&this.el_.tagName==="VIDEO",i&&(this.el_.currentSrc!==i.src||e.tag&&e.tag.initNetworkState_===3)?this.setSource(i):this.handleLateInit_(this.el_),e.enableSourceset&&this.setupSourcesetHandling_(),this.isScrubbing_=!1,this.el_.hasChildNodes()){const r=this.el_.childNodes;let a=r.length;const o=[];for(;a--;){const c=r[a];c.nodeName.toLowerCase()==="track"&&(this.featuresNativeTextTracks?(this.remoteTextTrackEls().addTrackElement_(c),this.remoteTextTracks().addTrack(c.track),this.textTracks().addTrack(c.track),!s&&!this.el_.hasAttribute("crossorigin")&&rl(c.src)&&(s=!0)):o.push(c))}for(let c=0;c<o.length;c++)this.el_.removeChild(o[c])}this.proxyNativeTracks_(),this.featuresNativeTextTracks&&s&&Oe.warn(`Text Tracks are being loaded from another origin but the crossorigin attribute isn't used.
|
|
224
|
+
This may prevent text tracks from loading.`),this.restoreMetadataTracksInIOSNativePlayer_(),(Va||$c)&&e.nativeControlsForTouch===!0&&this.setControls(!0),this.proxyWebkitFullscreen_(),this.triggerReady()}dispose(){this.el_&&this.el_.resetSourceset_&&this.el_.resetSourceset_(),ye.disposeMediaElement(this.el_),this.options_=null,super.dispose()}setupSourcesetHandling_(){MA(this)}restoreMetadataTracksInIOSNativePlayer_(){const e=this.textTracks();let t;const i=()=>{t=[];for(let r=0;r<e.length;r++){const a=e[r];a.kind==="metadata"&&t.push({track:a,storedMode:a.mode})}};i(),e.addEventListener("change",i),this.on("dispose",()=>e.removeEventListener("change",i));const s=()=>{for(let r=0;r<t.length;r++){const a=t[r];a.track.mode==="disabled"&&a.track.mode!==a.storedMode&&(a.track.mode=a.storedMode)}e.removeEventListener("change",s)};this.on("webkitbeginfullscreen",()=>{e.removeEventListener("change",i),e.removeEventListener("change",s),e.addEventListener("change",s)}),this.on("webkitendfullscreen",()=>{e.removeEventListener("change",i),e.addEventListener("change",i),e.removeEventListener("change",s)})}overrideNative_(e,t){if(t!==this[`featuresNative${e}Tracks`])return;const i=e.toLowerCase();this[`${i}TracksListeners_`]&&Object.keys(this[`${i}TracksListeners_`]).forEach(s=>{this.el()[`${i}Tracks`].removeEventListener(s,this[`${i}TracksListeners_`][s])}),this[`featuresNative${e}Tracks`]=!t,this[`${i}TracksListeners_`]=null,this.proxyNativeTracksForType_(i)}overrideNativeAudioTracks(e){this.overrideNative_("Audio",e)}overrideNativeVideoTracks(e){this.overrideNative_("Video",e)}proxyNativeTracksForType_(e){const t=Ii[e],i=this.el()[t.getterName],s=this[t.getterName]();if(!this[`featuresNative${t.capitalName}Tracks`]||!i||!i.addEventListener)return;const r={change:o=>{const c={type:"change",target:s,currentTarget:s,srcElement:s};s.trigger(c),e==="text"&&this[Ir.remoteText.getterName]().trigger(c)},addtrack(o){s.addTrack(o.track)},removetrack(o){s.removeTrack(o.track)}},a=function(){const o=[];for(let c=0;c<s.length;c++){let l=!1;for(let u=0;u<i.length;u++)if(i[u]===s[c]){l=!0;break}l||o.push(s[c])}for(;o.length;)s.removeTrack(o.shift())};this[t.getterName+"Listeners_"]=r,Object.keys(r).forEach(o=>{const c=r[o];i.addEventListener(o,c),this.on("dispose",l=>i.removeEventListener(o,c))}),this.on("loadstart",a),this.on("dispose",o=>this.off("loadstart",a))}proxyNativeTracks_(){Ii.names.forEach(e=>{this.proxyNativeTracksForType_(e)})}createEl(){let e=this.options_.tag;if(!e||!(this.options_.playerElIngest||this.movingMediaElementInDOM)){if(e){const i=e.cloneNode(!0);e.parentNode&&e.parentNode.insertBefore(i,e),ye.disposeMediaElement(e),e=i}else{e=de.createElement("video");const i=this.options_.tag&&cs(this.options_.tag),s=Qe({},i);(!Va||this.options_.nativeControlsForTouch!==!0)&&delete s.controls,Hy(e,Object.assign(s,{id:this.options_.techId,class:"vjs-tech"}))}e.playerId=this.options_.playerId}typeof this.options_.preload<"u"&&xr(e,"preload",this.options_.preload),this.options_.disablePictureInPicture!==void 0&&(e.disablePictureInPicture=this.options_.disablePictureInPicture);const t=["loop","muted","playsinline","autoplay"];for(let i=0;i<t.length;i++){const s=t[i],r=this.options_[s];typeof r<"u"&&(r?xr(e,s,s):Yc(e,s),e[s]=r)}return e}handleLateInit_(e){if(e.networkState===0||e.networkState===3)return;if(e.readyState===0){let i=!1;const s=function(){i=!0};this.on("loadstart",s);const r=function(){i||this.trigger("loadstart")};this.on("loadedmetadata",r),this.ready(function(){this.off("loadstart",s),this.off("loadedmetadata",r),i||this.trigger("loadstart")});return}const t=["loadstart"];t.push("loadedmetadata"),e.readyState>=2&&t.push("loadeddata"),e.readyState>=3&&t.push("canplay"),e.readyState>=4&&t.push("canplaythrough"),this.ready(function(){t.forEach(function(i){this.trigger(i)},this)})}setScrubbing(e){this.isScrubbing_=e}scrubbing(){return this.isScrubbing_}setCurrentTime(e){try{this.isScrubbing_&&this.el_.fastSeek&&Kc?this.el_.fastSeek(e):this.el_.currentTime=e}catch(t){Oe(t,"Video is not ready. (Video.js)")}}duration(){if(this.el_.duration===1/0&&Wi&&dn&&this.el_.currentTime===0){const e=()=>{this.el_.currentTime>0&&(this.el_.duration===1/0&&this.trigger("durationchange"),this.off("timeupdate",e))};return this.on("timeupdate",e),NaN}return this.el_.duration||NaN}width(){return this.el_.offsetWidth}height(){return this.el_.offsetHeight}proxyWebkitFullscreen_(){if(!("webkitDisplayingFullscreen"in this.el_))return;const e=function(){this.trigger("fullscreenchange",{isFullscreen:!1}),this.el_.controls&&!this.options_.nativeControlsForTouch&&this.controls()&&(this.el_.controls=!1)},t=function(){"webkitPresentationMode"in this.el_&&this.el_.webkitPresentationMode!=="picture-in-picture"&&(this.one("webkitendfullscreen",e),this.trigger("fullscreenchange",{isFullscreen:!0,nativeIOSFullscreen:!0}))};this.on("webkitbeginfullscreen",t),this.on("dispose",()=>{this.off("webkitbeginfullscreen",t),this.off("webkitendfullscreen",e)})}supportsFullScreen(){return typeof this.el_.webkitEnterFullScreen=="function"}enterFullScreen(){const e=this.el_;if(e.paused&&e.networkState<=e.HAVE_METADATA)fn(this.el_.play()),this.setTimeout(function(){e.pause();try{e.webkitEnterFullScreen()}catch(t){this.trigger("fullscreenerror",t)}},0);else try{e.webkitEnterFullScreen()}catch(t){this.trigger("fullscreenerror",t)}}exitFullScreen(){if(!this.el_.webkitDisplayingFullscreen){this.trigger("fullscreenerror",new Error("The video is not fullscreen"));return}this.el_.webkitExitFullScreen()}requestPictureInPicture(){return this.el_.requestPictureInPicture()}requestVideoFrameCallback(e){return this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.requestVideoFrameCallback(e):super.requestVideoFrameCallback(e)}cancelVideoFrameCallback(e){this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.cancelVideoFrameCallback(e):super.cancelVideoFrameCallback(e)}src(e){if(e===void 0)return this.el_.src;this.setSrc(e)}addSourceElement(e,t){if(!e)return Oe.error("Invalid source URL."),!1;const i={src:e};t&&(i.type=t);const s=Ee("source",{},i);return this.el_.appendChild(s),!0}removeSourceElement(e){if(!e)return Oe.error("Source URL is required to remove the source element."),!1;const t=this.el_.querySelectorAll("source");for(const i of t)if(i.src===e)return this.el_.removeChild(i),!0;return Oe.warn(`No matching source element found with src: ${e}`),!1}reset(){ye.resetMediaElement(this.el_)}currentSrc(){return this.currentSource_?this.currentSource_.src:this.el_.currentSrc}setControls(e){this.el_.controls=!!e}addTextTrack(e,t,i){return this.featuresNativeTextTracks?this.el_.addTextTrack(e,t,i):super.addTextTrack(e,t,i)}createRemoteTextTrack(e){if(!this.featuresNativeTextTracks)return super.createRemoteTextTrack(e);const t=de.createElement("track");return e.kind&&(t.kind=e.kind),e.label&&(t.label=e.label),(e.language||e.srclang)&&(t.srclang=e.language||e.srclang),e.default&&(t.default=e.default),e.id&&(t.id=e.id),e.src&&(t.src=e.src),t}addRemoteTextTrack(e,t){const i=super.addRemoteTextTrack(e,t);return this.featuresNativeTextTracks&&this.el().appendChild(i),i}removeRemoteTextTrack(e){if(super.removeRemoteTextTrack(e),this.featuresNativeTextTracks){const t=this.$$("track");let i=t.length;for(;i--;)(e===t[i]||e===t[i].track)&&this.el().removeChild(t[i])}}getVideoPlaybackQuality(){if(typeof this.el().getVideoPlaybackQuality=="function")return this.el().getVideoPlaybackQuality();const e={};return typeof this.el().webkitDroppedFrameCount<"u"&&typeof this.el().webkitDecodedFrameCount<"u"&&(e.droppedVideoFrames=this.el().webkitDroppedFrameCount,e.totalVideoFrames=this.el().webkitDecodedFrameCount),B.performance&&(e.creationTime=B.performance.now()),e}}Bc(ye,"TEST_VID",function(){if(!kr())return;const n=de.createElement("video"),e=de.createElement("track");return e.kind="captions",e.srclang="en",e.label="English",n.appendChild(e),n}),ye.isSupported=function(){try{ye.TEST_VID.volume=.5}catch{return!1}return!!(ye.TEST_VID&&ye.TEST_VID.canPlayType)},ye.canPlayType=function(n){return ye.TEST_VID.canPlayType(n)},ye.canPlaySource=function(n,e){return ye.canPlayType(n.type)},ye.canControlVolume=function(){try{const n=ye.TEST_VID.volume;ye.TEST_VID.volume=n/2+.1;const e=n!==ye.TEST_VID.volume;return e&&Ht?(B.setTimeout(()=>{ye&&ye.prototype&&(ye.prototype.featuresVolumeControl=n!==ye.TEST_VID.volume)}),!1):e}catch{return!1}},ye.canMuteVolume=function(){try{const n=ye.TEST_VID.muted;return ye.TEST_VID.muted=!n,ye.TEST_VID.muted?xr(ye.TEST_VID,"muted","muted"):Yc(ye.TEST_VID,"muted","muted"),n!==ye.TEST_VID.muted}catch{return!1}},ye.canControlPlaybackRate=function(){if(Wi&&dn&&qc<58)return!1;try{const n=ye.TEST_VID.playbackRate;return ye.TEST_VID.playbackRate=n/2+.1,n!==ye.TEST_VID.playbackRate}catch{return!1}},ye.canOverrideAttributes=function(){try{const n=()=>{};Object.defineProperty(de.createElement("video"),"src",{get:n,set:n}),Object.defineProperty(de.createElement("audio"),"src",{get:n,set:n}),Object.defineProperty(de.createElement("video"),"innerHTML",{get:n,set:n}),Object.defineProperty(de.createElement("audio"),"innerHTML",{get:n,set:n})}catch{return!1}return!0},ye.supportsNativeTextTracks=function(){return Kc||Ht&&dn},ye.supportsNativeVideoTracks=function(){return!!(ye.TEST_VID&&ye.TEST_VID.videoTracks)},ye.supportsNativeAudioTracks=function(){return!!(ye.TEST_VID&&ye.TEST_VID.audioTracks)},ye.Events=["loadstart","suspend","abort","error","emptied","stalled","loadedmetadata","loadeddata","canplay","canplaythrough","playing","waiting","seeking","seeked","ended","durationchange","timeupdate","progress","play","pause","ratechange","resize","volumechange"],[["featuresMuteControl","canMuteVolume"],["featuresPlaybackRate","canControlPlaybackRate"],["featuresSourceset","canOverrideAttributes"],["featuresNativeTextTracks","supportsNativeTextTracks"],["featuresNativeVideoTracks","supportsNativeVideoTracks"],["featuresNativeAudioTracks","supportsNativeAudioTracks"]].forEach(function([n,e]){Bc(ye.prototype,n,()=>ye[e](),!0)}),ye.prototype.featuresVolumeControl=ye.canControlVolume(),ye.prototype.movingMediaElementInDOM=!Ht,ye.prototype.featuresFullscreenResize=!0,ye.prototype.featuresProgressEvents=!0,ye.prototype.featuresTimeupdateEvents=!0,ye.prototype.featuresVideoFrameCallback=!!(ye.TEST_VID&&ye.TEST_VID.requestVideoFrameCallback),ye.disposeMediaElement=function(n){if(n){for(n.parentNode&&n.parentNode.removeChild(n);n.hasChildNodes();)n.removeChild(n.firstChild);n.removeAttribute("src"),typeof n.load=="function"&&(function(){try{n.load()}catch{}})()}},ye.resetMediaElement=function(n){if(!n)return;const e=n.querySelectorAll("source");let t=e.length;for(;t--;)n.removeChild(e[t]);n.removeAttribute("src"),typeof n.load=="function"&&(function(){try{n.load()}catch{}})()},["muted","defaultMuted","autoplay","controls","loop","playsinline"].forEach(function(n){ye.prototype[n]=function(){return this.el_[n]||this.el_.hasAttribute(n)}}),["muted","defaultMuted","autoplay","loop","playsinline"].forEach(function(n){ye.prototype["set"+pt(n)]=function(e){this.el_[n]=e,e?this.el_.setAttribute(n,n):this.el_.removeAttribute(n)}}),["paused","currentTime","buffered","volume","poster","preload","error","seeking","seekable","ended","playbackRate","defaultPlaybackRate","disablePictureInPicture","played","networkState","readyState","videoWidth","videoHeight","crossOrigin"].forEach(function(n){ye.prototype[n]=function(){return this.el_[n]}}),["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach(function(n){ye.prototype["set"+pt(n)]=function(e){this.el_[n]=e}}),["pause","load","play"].forEach(function(n){ye.prototype[n]=function(){return this.el_[n]()}}),De.withSourceHandlers(ye),ye.nativeSourceHandler={},ye.nativeSourceHandler.canPlayType=function(n){try{return ye.TEST_VID.canPlayType(n)}catch{return""}},ye.nativeSourceHandler.canHandleSource=function(n,e){if(n.type)return ye.nativeSourceHandler.canPlayType(n.type);if(n.src){const t=Oh(n.src);return ye.nativeSourceHandler.canPlayType(`video/${t}`)}return""},ye.nativeSourceHandler.handleSource=function(n,e,t){e.setSrc(n.src)},ye.nativeSourceHandler.dispose=function(){},ye.registerSourceHandler(ye.nativeSourceHandler),De.registerTech("Html5",ye);const pb=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],nf={canplay:"CanPlay",canplaythrough:"CanPlayThrough",playing:"Playing",seeked:"Seeked"},sf=["tiny","xsmall","small","medium","large","xlarge","huge"],hl={};sf.forEach(n=>{const e=n.charAt(0)==="x"?`x-${n.substring(1)}`:n;hl[n]=`vjs-layout-${e}`});const LA={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0};class $e extends ee{constructor(e,t,i){if(e.id=e.id||t.id||`vjs_video_${Di()}`,t=Object.assign($e.getTagSettings(e),t),t.initChildren=!1,t.createEl=!1,t.evented=!1,t.reportTouchActivity=!1,!t.language){const a=e.closest("[lang]");a&&(t.language=a.getAttribute("lang"))}if(super(null,t,i),this.boundDocumentFullscreenChange_=a=>this.documentFullscreenChange_(a),this.boundFullWindowOnEscKey_=a=>this.fullWindowOnEscKey(a),this.boundUpdateStyleEl_=a=>this.updateStyleEl_(a),this.boundApplyInitTime_=a=>this.applyInitTime_(a),this.boundUpdateCurrentBreakpoint_=a=>this.updateCurrentBreakpoint_(a),this.boundHandleTechClick_=a=>this.handleTechClick_(a),this.boundHandleTechDoubleClick_=a=>this.handleTechDoubleClick_(a),this.boundHandleTechTouchStart_=a=>this.handleTechTouchStart_(a),this.boundHandleTechTouchMove_=a=>this.handleTechTouchMove_(a),this.boundHandleTechTouchEnd_=a=>this.handleTechTouchEnd_(a),this.boundHandleTechTap_=a=>this.handleTechTap_(a),this.boundUpdatePlayerHeightOnAudioOnlyMode_=a=>this.updatePlayerHeightOnAudioOnlyMode_(a),this.isFullscreen_=!1,this.log=Py(this.id_),this.fsApi_=Fc,this.isPosterFromTech_=!1,this.queuedCallbacks_=[],this.isReady_=!1,this.hasStarted_=!1,this.userActive_=!1,this.debugEnabled_=!1,this.audioOnlyMode_=!1,this.audioPosterMode_=!1,this.audioOnlyCache_={controlBarHeight:null,playerHeight:null,hiddenChildren:[]},!this.options_||!this.options_.techOrder||!this.options_.techOrder.length)throw new Error("No techOrder specified. Did you overwrite videojs.options instead of just changing the properties you want to override?");if(this.tag=e,this.tagAttributes=e&&cs(e),this.language(this.options_.language),t.languages){const a={};Object.getOwnPropertyNames(t.languages).forEach(function(o){a[o.toLowerCase()]=t.languages[o]}),this.languages_=a}else this.languages_=$e.prototype.options_.languages;this.resetCache_(),this.poster_=t.poster||"",this.controls_=!!t.controls,e.controls=!1,e.removeAttribute("controls"),this.changingSrc_=!1,this.playCallbacks_=[],this.playTerminatedQueue_=[],e.hasAttribute("autoplay")?this.autoplay(!0):this.autoplay(this.options_.autoplay),t.plugins&&Object.keys(t.plugins).forEach(a=>{if(typeof this[a]!="function")throw new Error(`plugin "${a}" does not exist`)}),this.scrubbing_=!1,this.el_=this.createEl(),Sh(this,{eventBusKey:"el_"}),this.fsApi_.requestFullscreen&&(vi(de,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),this.on(this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_)),this.fluid_&&this.on(["playerreset","resize"],this.boundUpdateStyleEl_);const s=Qe(this.options_);if(t.plugins&&Object.keys(t.plugins).forEach(a=>{this[a](t.plugins[a])}),t.debug&&this.debug(!0),this.options_.playerOptions=s,this.middleware_=[],this.playbackRates(t.playbackRates),t.experimentalSvgIcons){const o=new B.DOMParser().parseFromString(sA,"image/svg+xml");if(o.querySelector("parsererror"))Oe.warn("Failed to load SVG Icons. Falling back to Font Icons."),this.options_.experimentalSvgIcons=null;else{const l=o.documentElement;l.style.display="none",this.el_.appendChild(l),this.addClass("vjs-svg-icons-enabled")}}this.initChildren(),this.isAudio(e.nodeName.toLowerCase()==="audio"),this.controls()?this.addClass("vjs-controls-enabled"):this.addClass("vjs-controls-disabled"),this.el_.setAttribute("role","region"),this.isAudio()?this.el_.setAttribute("aria-label",this.localize("Audio Player")):this.el_.setAttribute("aria-label",this.localize("Video Player")),this.isAudio()&&this.addClass("vjs-audio"),t.spatialNavigation&&t.spatialNavigation.enabled&&(this.spatialNavigation=new rA(this),this.addClass("vjs-spatial-navigation-enabled")),Va&&this.addClass("vjs-touch-enabled"),Ht||this.addClass("vjs-workinghover"),$e.players[this.id_]=this;const r=lh.split(".")[0];this.addClass(`vjs-v${r}`),this.userActive(!0),this.reportUserActivity(),this.one("play",a=>this.listenForUserActivity_(a)),this.on("keydown",a=>this.handleKeyDown(a)),this.on("languagechange",a=>this.handleLanguagechange(a)),this.breakpoints(this.options_.breakpoints),this.responsive(this.options_.responsive),this.on("ready",()=>{this.audioPosterMode(this.options_.audioPosterMode),this.audioOnlyMode(this.options_.audioOnlyMode)})}dispose(){this.trigger("dispose"),this.off("dispose"),$t(de,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),$t(de,"keydown",this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),$e.players[this.id_]=null,this.tag&&this.tag.player&&(this.tag.player=null),this.el_&&this.el_.player&&(this.el_.player=null),this.tech_&&(this.tech_.dispose(),this.isPosterFromTech_=!1,this.poster_=""),this.playerElIngest_&&(this.playerElIngest_=null),this.tag&&(this.tag=null),eA(this),ti.names.forEach(e=>{const t=ti[e],i=this[t.getterName]();i&&i.off&&i.off()}),super.dispose({restoreEl:this.options_.restoreEl})}createEl(){let e=this.tag,t,i=this.playerElIngest_=e.parentNode&&e.parentNode.hasAttribute&&e.parentNode.hasAttribute("data-vjs-player");const s=this.tag.tagName.toLowerCase()==="video-js";i?t=this.el_=e.parentNode:s||(t=this.el_=super.createEl("div"));const r=cs(e);if(s){for(t=this.el_=e,e=this.tag=de.createElement("video");t.children.length;)e.appendChild(t.firstChild);ja(t,"video-js")||Ls(t,"video-js"),t.appendChild(e),i=this.playerElIngest_=t,Object.keys(t).forEach(c=>{try{e[c]=t[c]}catch{}})}e.setAttribute("tabindex","-1"),r.tabindex="-1",dn&&jc&&(e.setAttribute("role","application"),r.role="application"),e.removeAttribute("width"),e.removeAttribute("height"),"width"in r&&delete r.width,"height"in r&&delete r.height,Object.getOwnPropertyNames(r).forEach(function(c){s&&c==="class"||t.setAttribute(c,r[c]),s&&e.setAttribute(c,r[c])}),e.playerId=e.id,e.id+="_html5_api",e.className="vjs-tech",e.player=t.player=this,this.addClass("vjs-paused");const a=["IS_SMART_TV","IS_TIZEN","IS_WEBOS","IS_ANDROID","IS_IPAD","IS_IPHONE","IS_CHROMECAST_RECEIVER"].filter(c=>Uy[c]).map(c=>"vjs-device-"+c.substring(3).toLowerCase().replace(/\_/g,"-"));if(this.addClass(...a),B.VIDEOJS_NO_DYNAMIC_STYLE!==!0){this.styleEl_=ev("vjs-styles-dimensions");const c=ls(".vjs-styles-defaults"),l=ls("head");l.insertBefore(this.styleEl_,c?c.nextSibling:l.firstChild)}this.fill_=!1,this.fluid_=!1,this.width(this.options_.width),this.height(this.options_.height),this.fill(this.options_.fill),this.fluid(this.options_.fluid),this.aspectRatio(this.options_.aspectRatio),this.crossOrigin(this.options_.crossOrigin||this.options_.crossorigin);const o=e.getElementsByTagName("a");for(let c=0;c<o.length;c++){const l=o.item(c);Ls(l,"vjs-hidden"),l.setAttribute("hidden","hidden")}return e.initNetworkState_=e.networkState,e.parentNode&&!i&&e.parentNode.insertBefore(t,e),fh(e,t),this.children_.unshift(e),this.el_.setAttribute("lang",this.language_),this.el_.setAttribute("translate","no"),this.el_=t,t}crossOrigin(e){if(typeof e>"u")return this.techGet_("crossOrigin");if(e!==null&&e!=="anonymous"&&e!=="use-credentials"){Oe.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${e}"`);return}this.techCall_("setCrossOrigin",e),this.posterImage&&this.posterImage.crossOrigin(e)}width(e){return this.dimension("width",e)}height(e){return this.dimension("height",e)}dimension(e,t){const i=e+"_";if(t===void 0)return this[i]||0;if(t===""||t==="auto"){this[i]=void 0,this.updateStyleEl_();return}const s=parseFloat(t);if(isNaN(s)){Oe.error(`Improper value "${t}" supplied for for ${e}`);return}this[i]=s,this.updateStyleEl_()}fluid(e){if(e===void 0)return!!this.fluid_;this.fluid_=!!e,Ln(this)&&this.off(["playerreset","resize"],this.boundUpdateStyleEl_),e?(this.addClass("vjs-fluid"),this.fill(!1),Mw(this,()=>{this.on(["playerreset","resize"],this.boundUpdateStyleEl_)})):this.removeClass("vjs-fluid"),this.updateStyleEl_()}fill(e){if(e===void 0)return!!this.fill_;this.fill_=!!e,e?(this.addClass("vjs-fill"),this.fluid(!1)):this.removeClass("vjs-fill")}aspectRatio(e){if(e===void 0)return this.aspectRatio_;if(!/^\d+\:\d+$/.test(e))throw new Error("Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.");this.aspectRatio_=e,this.fluid(!0),this.updateStyleEl_()}updateStyleEl_(){if(B.VIDEOJS_NO_DYNAMIC_STYLE===!0){const o=typeof this.width_=="number"?this.width_:this.options_.width,c=typeof this.height_=="number"?this.height_:this.options_.height,l=this.tech_&&this.tech_.el();l&&(o>=0&&(l.width=o),c>=0&&(l.height=c));return}let e,t,i,s;this.aspectRatio_!==void 0&&this.aspectRatio_!=="auto"?i=this.aspectRatio_:this.videoWidth()>0?i=this.videoWidth()+":"+this.videoHeight():i="16:9";const r=i.split(":"),a=r[1]/r[0];this.width_!==void 0?e=this.width_:this.height_!==void 0?e=this.height_/a:e=this.videoWidth()||300,this.height_!==void 0?t=this.height_:t=e*a,/^[^a-zA-Z]/.test(this.id())?s="dimensions-"+this.id():s=this.id()+"-dimensions",this.addClass(s),tv(this.styleEl_,`
|
|
225
|
+
.${s} {
|
|
226
|
+
width: ${e}px;
|
|
227
|
+
height: ${t}px;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
.${s}.vjs-fluid:not(.vjs-audio-only-mode) {
|
|
231
|
+
padding-top: ${a*100}%;
|
|
232
|
+
}
|
|
233
|
+
`)}loadTech_(e,t){this.tech_&&this.unloadTech_();const i=pt(e),s=e.charAt(0).toLowerCase()+e.slice(1);i!=="Html5"&&this.tag&&(De.getTech("Html5").disposeMediaElement(this.tag),this.tag.player=null,this.tag=null),this.techName_=i,this.isReady_=!1;let r=this.autoplay();(typeof this.autoplay()=="string"||this.autoplay()===!0&&this.options_.normalizeAutoplay)&&(r=!1);const a={source:t,autoplay:r,nativeControlsForTouch:this.options_.nativeControlsForTouch,playerId:this.id(),techId:`${this.id()}_${s}_api`,playsinline:this.options_.playsinline,preload:this.options_.preload,loop:this.options_.loop,disablePictureInPicture:this.options_.disablePictureInPicture,muted:this.options_.muted,poster:this.poster(),language:this.language(),playerElIngest:this.playerElIngest_||!1,"vtt.js":this.options_["vtt.js"],canOverridePoster:!!this.options_.techCanOverridePoster,enableSourceset:this.options_.enableSourceset};ti.names.forEach(c=>{const l=ti[c];a[l.getterName]=this[l.privateName]}),Object.assign(a,this.options_[i]),Object.assign(a,this.options_[s]),Object.assign(a,this.options_[e.toLowerCase()]),this.tag&&(a.tag=this.tag),t&&t.src===this.cache_.src&&this.cache_.currentTime>0&&(a.startTime=this.cache_.currentTime);const o=De.getTech(e);if(!o)throw new Error(`No Tech named '${i}' exists! '${i}' should be registered using videojs.registerTech()'`);this.tech_=new o(a),this.tech_.ready(Ze(this,this.handleTechReady_),!0),xh.jsonToTextTracks(this.textTracksJson_||[],this.tech_),pb.forEach(c=>{this.on(this.tech_,c,l=>this[`handleTech${pt(c)}_`](l))}),Object.keys(nf).forEach(c=>{this.on(this.tech_,c,l=>{if(this.tech_.playbackRate()===0&&this.tech_.seeking()){this.queuedCallbacks_.push({callback:this[`handleTech${nf[c]}_`].bind(this),event:l});return}this[`handleTech${nf[c]}_`](l)})}),this.on(this.tech_,"loadstart",c=>this.handleTechLoadStart_(c)),this.on(this.tech_,"sourceset",c=>this.handleTechSourceset_(c)),this.on(this.tech_,"waiting",c=>this.handleTechWaiting_(c)),this.on(this.tech_,"ended",c=>this.handleTechEnded_(c)),this.on(this.tech_,"seeking",c=>this.handleTechSeeking_(c)),this.on(this.tech_,"play",c=>this.handleTechPlay_(c)),this.on(this.tech_,"pause",c=>this.handleTechPause_(c)),this.on(this.tech_,"durationchange",c=>this.handleTechDurationChange_(c)),this.on(this.tech_,"fullscreenchange",(c,l)=>this.handleTechFullscreenChange_(c,l)),this.on(this.tech_,"fullscreenerror",(c,l)=>this.handleTechFullscreenError_(c,l)),this.on(this.tech_,"enterpictureinpicture",c=>this.handleTechEnterPictureInPicture_(c)),this.on(this.tech_,"leavepictureinpicture",c=>this.handleTechLeavePictureInPicture_(c)),this.on(this.tech_,"error",c=>this.handleTechError_(c)),this.on(this.tech_,"posterchange",c=>this.handleTechPosterChange_(c)),this.on(this.tech_,"textdata",c=>this.handleTechTextData_(c)),this.on(this.tech_,"ratechange",c=>this.handleTechRateChange_(c)),this.on(this.tech_,"loadedmetadata",this.boundUpdateStyleEl_),this.usingNativeControls(this.techGet_("controls")),this.controls()&&!this.usingNativeControls()&&this.addTechControlsListeners_(),this.tech_.el().parentNode!==this.el()&&(i!=="Html5"||!this.tag)&&fh(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)}unloadTech_(){ti.names.forEach(e=>{const t=ti[e];this[t.privateName]=this[t.getterName]()}),this.textTracksJson_=xh.textTracksToJson(this.tech_),this.isReady_=!1,this.tech_.dispose(),this.tech_=!1,this.isPosterFromTech_&&(this.poster_="",this.trigger("posterchange")),this.isPosterFromTech_=!1}tech(e){return e===void 0&&Oe.warn(`Using the tech directly can be dangerous. I hope you know what you're doing.
|
|
234
|
+
See https://github.com/videojs/video.js/issues/2617 for more info.
|
|
235
|
+
`),this.tech_}version(){return{"video.js":lh}}addTechControlsListeners_(){this.removeTechControlsListeners_(),this.on(this.tech_,"click",this.boundHandleTechClick_),this.on(this.tech_,"dblclick",this.boundHandleTechDoubleClick_),this.on(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.on(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.on(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.on(this.tech_,"tap",this.boundHandleTechTap_)}removeTechControlsListeners_(){this.off(this.tech_,"tap",this.boundHandleTechTap_),this.off(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.off(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.off(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.off(this.tech_,"click",this.boundHandleTechClick_),this.off(this.tech_,"dblclick",this.boundHandleTechDoubleClick_)}handleTechReady_(){this.triggerReady(),this.cache_.volume&&this.techCall_("setVolume",this.cache_.volume),this.handleTechPosterChange_(),this.handleTechDurationChange_()}handleTechLoadStart_(){this.removeClass("vjs-ended","vjs-seeking"),this.error(null),this.handleTechDurationChange_(),this.paused()?(this.hasStarted(!1),this.trigger("loadstart")):this.trigger("loadstart"),this.manualAutoplay_(this.autoplay()===!0&&this.options_.normalizeAutoplay?"play":this.autoplay())}manualAutoplay_(e){if(!this.tech_||typeof e!="string")return;const t=()=>{const s=this.muted();this.muted(!0);const r=()=>{this.muted(s)};this.playTerminatedQueue_.push(r);const a=this.play();if(Ga(a))return a.catch(o=>{throw r(),new Error(`Rejection at manualAutoplay. Restoring muted value. ${o||""}`)})};let i;if(e==="any"&&!this.muted()?(i=this.play(),Ga(i)&&(i=i.catch(t))):e==="muted"&&!this.muted()?i=t():i=this.play(),!!Ga(i))return i.then(()=>{this.trigger({type:"autoplay-success",autoplay:e})}).catch(()=>{this.trigger({type:"autoplay-failure",autoplay:e})})}updateSourceCaches_(e=""){let t=e,i="";typeof t!="string"&&(t=e.src,i=e.type),this.cache_.source=this.cache_.source||{},this.cache_.sources=this.cache_.sources||[],t&&!i&&(i=nA(this,t)),this.cache_.source=Qe({},e,{src:t,type:i});const s=this.cache_.sources.filter(c=>c.src&&c.src===t),r=[],a=this.$$("source"),o=[];for(let c=0;c<a.length;c++){const l=cs(a[c]);r.push(l),l.src&&l.src===t&&o.push(l.src)}o.length&&!s.length?this.cache_.sources=r:s.length||(this.cache_.sources=[this.cache_.source]),this.cache_.src=t}handleTechSourceset_(e){if(!this.changingSrc_){let t=r=>this.updateSourceCaches_(r);const i=this.currentSource().src,s=e.src;i&&!/^blob:/.test(i)&&/^blob:/.test(s)&&(!this.lastSource_||this.lastSource_.tech!==s&&this.lastSource_.player!==i)&&(t=()=>{}),t(s),e.src||this.tech_.any(["sourceset","loadstart"],r=>{if(r.type==="sourceset")return;const a=this.techGet_("currentSrc");this.lastSource_.tech=a,this.updateSourceCaches_(a)})}this.lastSource_={player:this.currentSource().src,tech:e.src},this.trigger({src:e.src,type:"sourceset"})}hasStarted(e){if(e===void 0)return this.hasStarted_;e!==this.hasStarted_&&(this.hasStarted_=e,this.hasStarted_?this.addClass("vjs-has-started"):this.removeClass("vjs-has-started"))}handleTechPlay_(){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.hasStarted(!0),this.trigger("play")}handleTechRateChange_(){this.tech_.playbackRate()>0&&this.cache_.lastPlaybackRate===0&&(this.queuedCallbacks_.forEach(e=>e.callback(e.event)),this.queuedCallbacks_=[]),this.cache_.lastPlaybackRate=this.tech_.playbackRate(),this.trigger("ratechange")}handleTechWaiting_(){this.addClass("vjs-waiting"),this.trigger("waiting");const e=this.currentTime(),t=()=>{e!==this.currentTime()&&(this.removeClass("vjs-waiting"),this.off("timeupdate",t))};this.on("timeupdate",t)}handleTechCanPlay_(){this.removeClass("vjs-waiting"),this.trigger("canplay")}handleTechCanPlayThrough_(){this.removeClass("vjs-waiting"),this.trigger("canplaythrough")}handleTechPlaying_(){this.removeClass("vjs-waiting"),this.trigger("playing")}handleTechSeeking_(){this.addClass("vjs-seeking"),this.trigger("seeking")}handleTechSeeked_(){this.removeClass("vjs-seeking","vjs-ended"),this.trigger("seeked")}handleTechPause_(){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.trigger("pause")}handleTechEnded_(){this.addClass("vjs-ended"),this.removeClass("vjs-waiting"),this.options_.loop?(this.currentTime(0),this.play()):this.paused()||this.pause(),this.trigger("ended")}handleTechDurationChange_(){this.duration(this.techGet_("duration"))}handleTechClick_(e){this.controls_&&(this.options_===void 0||this.options_.userActions===void 0||this.options_.userActions.click===void 0||this.options_.userActions.click!==!1)&&(this.options_!==void 0&&this.options_.userActions!==void 0&&typeof this.options_.userActions.click=="function"?this.options_.userActions.click.call(this,e):this.paused()?fn(this.play()):this.pause())}handleTechDoubleClick_(e){if(!this.controls_)return;Array.prototype.some.call(this.$$(".vjs-control-bar, .vjs-modal-dialog"),i=>i.contains(e.target))||(this.options_===void 0||this.options_.userActions===void 0||this.options_.userActions.doubleClick===void 0||this.options_.userActions.doubleClick!==!1)&&(this.options_!==void 0&&this.options_.userActions!==void 0&&typeof this.options_.userActions.doubleClick=="function"?this.options_.userActions.doubleClick.call(this,e):this.isInPictureInPicture()&&!de.pictureInPictureElement?this.exitPictureInPicture():this.isFullscreen()?this.exitFullscreen():this.requestFullscreen())}handleTechTap_(){this.userActive(!this.userActive())}handleTechTouchStart_(){this.userWasActive=this.userActive()}handleTechTouchMove_(){this.userWasActive&&this.reportUserActivity()}handleTechTouchEnd_(e){e.cancelable&&e.preventDefault()}toggleFullscreenClass_(){this.isFullscreen()?this.addClass("vjs-fullscreen"):this.removeClass("vjs-fullscreen")}documentFullscreenChange_(e){const t=e.target.player;if(t&&t!==this)return;const i=this.el();let s=de[this.fsApi_.fullscreenElement]===i;!s&&i.matches&&(s=i.matches(":"+this.fsApi_.fullscreen)),this.isFullscreen(s)}handleTechFullscreenChange_(e,t){t&&(t.nativeIOSFullscreen&&(this.addClass("vjs-ios-native-fs"),this.tech_.one("webkitendfullscreen",()=>{this.removeClass("vjs-ios-native-fs")})),this.isFullscreen(t.isFullscreen))}handleTechFullscreenError_(e,t){this.trigger("fullscreenerror",t)}togglePictureInPictureClass_(){this.isInPictureInPicture()?this.addClass("vjs-picture-in-picture"):this.removeClass("vjs-picture-in-picture")}handleTechEnterPictureInPicture_(e){this.isInPictureInPicture(!0)}handleTechLeavePictureInPicture_(e){this.isInPictureInPicture(!1)}handleTechError_(){const e=this.tech_.error();e&&this.error(e)}handleTechTextData_(){let e=null;arguments.length>1&&(e=arguments[1]),this.trigger("textdata",e)}getCache(){return this.cache_}resetCache_(){this.cache_={currentTime:0,initTime:0,inactivityTimeout:this.options_.inactivityTimeout,duration:NaN,lastVolume:1,lastPlaybackRate:this.defaultPlaybackRate(),media:null,src:"",source:{},sources:[],playbackRates:[],volume:1}}techCall_(e,t){this.ready(function(){if(e in Jw)return Yw(this.middleware_,this.tech_,e,t);if(e in Sv)return _v(this.middleware_,this.tech_,e,t);try{this.tech_&&this.tech_[e](t)}catch(i){throw Oe(i),i}},!0)}techGet_(e){if(!(!this.tech_||!this.tech_.isReady_)){if(e in Qw)return Xw(this.middleware_,this.tech_,e);if(e in Sv)return _v(this.middleware_,this.tech_,e);try{return this.tech_[e]()}catch(t){throw this.tech_[e]===void 0?(Oe(`Video.js: ${e} method not defined for ${this.techName_} playback technology.`,t),t):t.name==="TypeError"?(Oe(`Video.js: ${e} unavailable on ${this.techName_} playback technology element.`,t),this.tech_.isReady_=!1,t):(Oe(t),t)}}}play(){return new Promise(e=>{this.play_(e)})}play_(e=fn){this.playCallbacks_.push(e);const t=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),i=!!(Kc||Ht);if(this.waitToPlay_&&(this.off(["ready","loadstart"],this.waitToPlay_),this.waitToPlay_=null),!this.isReady_||!t){this.waitToPlay_=a=>{this.play_()},this.one(["ready","loadstart"],this.waitToPlay_),!t&&i&&this.load();return}const s=this.techGet_("play");i&&this.hasClass("vjs-ended")&&this.resetProgressBar_(),s===null?this.runPlayTerminatedQueue_():this.runPlayCallbacks_(s)}runPlayTerminatedQueue_(){const e=this.playTerminatedQueue_.slice(0);this.playTerminatedQueue_=[],e.forEach(function(t){t()})}runPlayCallbacks_(e){const t=this.playCallbacks_.slice(0);this.playCallbacks_=[],this.playTerminatedQueue_=[],t.forEach(function(i){i(e)})}pause(){this.techCall_("pause")}paused(){return this.techGet_("paused")!==!1}played(){return this.techGet_("played")||zi(0,0)}scrubbing(e){if(typeof e>"u")return this.scrubbing_;this.scrubbing_=!!e,this.techCall_("setScrubbing",this.scrubbing_),e?this.addClass("vjs-scrubbing"):this.removeClass("vjs-scrubbing")}currentTime(e){if(e===void 0)return this.cache_.currentTime=this.techGet_("currentTime")||0,this.cache_.currentTime;if(e<0&&(e=0),!this.isReady_||this.changingSrc_||!this.tech_||!this.tech_.isReady_){this.cache_.initTime=e,this.off("canplay",this.boundApplyInitTime_),this.one("canplay",this.boundApplyInitTime_);return}this.techCall_("setCurrentTime",e),this.cache_.initTime=0,isFinite(e)&&(this.cache_.currentTime=Number(e))}applyInitTime_(){this.currentTime(this.cache_.initTime)}duration(e){if(e===void 0)return this.cache_.duration!==void 0?this.cache_.duration:NaN;e=parseFloat(e),e<0&&(e=1/0),e!==this.cache_.duration&&(this.cache_.duration=e,e===1/0?this.addClass("vjs-live"):this.removeClass("vjs-live"),isNaN(e)||this.trigger("durationchange"))}remainingTime(){return this.duration()-this.currentTime()}remainingTimeDisplay(){return Math.floor(this.duration())-Math.floor(this.currentTime())}buffered(){let e=this.techGet_("buffered");return(!e||!e.length)&&(e=zi(0,0)),e}seekable(){let e=this.techGet_("seekable");return(!e||!e.length)&&(e=zi(0,0)),e}seeking(){return this.techGet_("seeking")}ended(){return this.techGet_("ended")}networkState(){return this.techGet_("networkState")}readyState(){return this.techGet_("readyState")}bufferedPercent(){return hv(this.buffered(),this.duration())}bufferedEnd(){const e=this.buffered(),t=this.duration();let i=e.end(e.length-1);return i>t&&(i=t),i}volume(e){let t;if(e!==void 0){t=Math.max(0,Math.min(1,e)),this.cache_.volume=t,this.techCall_("setVolume",t),t>0&&this.lastVolume_(t);return}return t=parseFloat(this.techGet_("volume")),isNaN(t)?1:t}muted(e){if(e!==void 0){this.techCall_("setMuted",e);return}return this.techGet_("muted")||!1}defaultMuted(e){return e!==void 0&&this.techCall_("setDefaultMuted",e),this.techGet_("defaultMuted")||!1}lastVolume_(e){if(e!==void 0&&e!==0){this.cache_.lastVolume=e;return}return this.cache_.lastVolume}supportsFullScreen(){return this.techGet_("supportsFullScreen")||!1}isFullscreen(e){if(e!==void 0){const t=this.isFullscreen_;this.isFullscreen_=!!e,this.isFullscreen_!==t&&this.fsApi_.prefixed&&this.trigger("fullscreenchange"),this.toggleFullscreenClass_();return}return this.isFullscreen_}requestFullscreen(e){this.isInPictureInPicture()&&this.exitPictureInPicture();const t=this;return new Promise((i,s)=>{function r(){t.off("fullscreenerror",o),t.off("fullscreenchange",a)}function a(){r(),i()}function o(l,u){r(),s(u)}t.one("fullscreenchange",a),t.one("fullscreenerror",o);const c=t.requestFullscreenHelper_(e);c&&(c.then(r,r),c.then(i,s))})}requestFullscreenHelper_(e){let t;if(this.fsApi_.prefixed||(t=this.options_.fullscreen&&this.options_.fullscreen.options||{},e!==void 0&&(t=e)),this.fsApi_.requestFullscreen){const i=this.el_[this.fsApi_.requestFullscreen](t);return i&&i.then(()=>this.isFullscreen(!0),()=>this.isFullscreen(!1)),i}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("enterFullScreen"):this.enterFullWindow()}exitFullscreen(){const e=this;return new Promise((t,i)=>{function s(){e.off("fullscreenerror",a),e.off("fullscreenchange",r)}function r(){s(),t()}function a(c,l){s(),i(l)}e.one("fullscreenchange",r),e.one("fullscreenerror",a);const o=e.exitFullscreenHelper_();o&&(o.then(s,s),o.then(t,i))})}exitFullscreenHelper_(){if(this.fsApi_.requestFullscreen){const e=de[this.fsApi_.exitFullscreen]();return e&&fn(e.then(()=>this.isFullscreen(!1))),e}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("exitFullScreen"):this.exitFullWindow()}enterFullWindow(){this.isFullscreen(!0),this.isFullWindow=!0,this.docOrigOverflow=de.documentElement.style.overflow,vi(de,"keydown",this.boundFullWindowOnEscKey_),de.documentElement.style.overflow="hidden",Ls(de.body,"vjs-full-window"),this.trigger("enterFullWindow")}fullWindowOnEscKey(e){e.key==="Escape"&&this.isFullscreen()===!0&&(this.isFullWindow?this.exitFullWindow():this.exitFullscreen())}exitFullWindow(){this.isFullscreen(!1),this.isFullWindow=!1,$t(de,"keydown",this.boundFullWindowOnEscKey_),de.documentElement.style.overflow=this.docOrigOverflow,Xc(de.body,"vjs-full-window"),this.trigger("exitFullWindow")}disablePictureInPicture(e){if(e===void 0)return this.techGet_("disablePictureInPicture");this.techCall_("setDisablePictureInPicture",e),this.options_.disablePictureInPicture=e,this.trigger("disablepictureinpicturechanged")}isInPictureInPicture(e){if(e!==void 0){this.isInPictureInPicture_=!!e,this.togglePictureInPictureClass_();return}return!!this.isInPictureInPicture_}requestPictureInPicture(){if(this.options_.enableDocumentPictureInPicture&&B.documentPictureInPicture){const e=de.createElement(this.el().tagName);return e.classList=this.el().classList,e.classList.add("vjs-pip-container"),this.posterImage&&e.appendChild(this.posterImage.el().cloneNode(!0)),this.titleBar&&e.appendChild(this.titleBar.el().cloneNode(!0)),e.appendChild(Ee("p",{className:"vjs-pip-text"},{},this.localize("Playing in picture-in-picture"))),B.documentPictureInPicture.requestWindow({width:this.videoWidth(),height:this.videoHeight()}).then(t=>(Qy(t),this.el_.parentNode.insertBefore(e,this.el_),t.document.body.appendChild(this.el_),t.document.body.classList.add("vjs-pip-window"),this.player_.isInPictureInPicture(!0),this.player_.trigger({type:"enterpictureinpicture",pipWindow:t}),t.addEventListener("pagehide",i=>{const s=i.target.querySelector(".video-js");e.parentNode.replaceChild(s,e),this.player_.isInPictureInPicture(!1),this.player_.trigger("leavepictureinpicture")}),t))}return"pictureInPictureEnabled"in de&&this.disablePictureInPicture()===!1?this.techGet_("requestPictureInPicture"):Promise.reject("No PiP mode is available")}exitPictureInPicture(){if(B.documentPictureInPicture&&B.documentPictureInPicture.window)return B.documentPictureInPicture.window.close(),Promise.resolve();if("pictureInPictureEnabled"in de)return de.exitPictureInPicture()}handleKeyDown(e){const{userActions:t}=this.options_;!t||!t.hotkeys||(s=>{const r=s.tagName.toLowerCase();if(s.isContentEditable)return!0;const a=["button","checkbox","hidden","radio","reset","submit"];return r==="input"?a.indexOf(s.type)===-1:["textarea"].indexOf(r)!==-1})(this.el_.ownerDocument.activeElement)||(typeof t.hotkeys=="function"?t.hotkeys.call(this,e):this.handleHotkeys(e))}handleHotkeys(e){const t=this.options_.userActions?this.options_.userActions.hotkeys:{},{fullscreenKey:i=a=>e.key.toLowerCase()==="f",muteKey:s=a=>e.key.toLowerCase()==="m",playPauseKey:r=a=>e.key.toLowerCase()==="k"||e.key.toLowerCase()===" "}=t;if(i.call(this,e)){e.preventDefault(),e.stopPropagation();const a=ee.getComponent("FullscreenToggle");de[this.fsApi_.fullscreenEnabled]!==!1&&a.prototype.handleClick.call(this,e)}else s.call(this,e)?(e.preventDefault(),e.stopPropagation(),ee.getComponent("MuteToggle").prototype.handleClick.call(this,e)):r.call(this,e)&&(e.preventDefault(),e.stopPropagation(),ee.getComponent("PlayToggle").prototype.handleClick.call(this,e))}canPlayType(e){let t;for(let i=0,s=this.options_.techOrder;i<s.length;i++){const r=s[i];let a=De.getTech(r);if(a||(a=ee.getComponent(r)),!a){Oe.error(`The "${r}" tech is undefined. Skipped browser support check for that tech.`);continue}if(a.isSupported()&&(t=a.canPlayType(e),t))return t}return""}selectSource(e){const t=this.options_.techOrder.map(o=>[o,De.getTech(o)]).filter(([o,c])=>c?c.isSupported():(Oe.error(`The "${o}" tech is undefined. Skipped browser support check for that tech.`),!1)),i=function(o,c,l){let u;return o.some(h=>c.some(p=>{if(u=l(h,p),u)return!0})),u};let s;const r=o=>(c,l)=>o(l,c),a=([o,c],l)=>{if(c.canPlaySource(l,this.options_[o.toLowerCase()]))return{source:l,tech:o}};return this.options_.sourceOrder?s=i(e,t,r(a)):s=i(t,e,a),s||!1}handleSrc_(e,t){if(typeof e>"u")return this.cache_.src||"";this.resetRetryOnError_&&this.resetRetryOnError_();const i=Cv(e);if(!i.length){this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0);return}if(this.changingSrc_=!0,t||(this.cache_.sources=i),this.updateSourceCaches_(i[0]),Gw(this,i[0],(s,r)=>{if(this.middleware_=r,t||(this.cache_.sources=i),this.updateSourceCaches_(s),this.src_(s)){if(i.length>1)return this.handleSrc_(i.slice(1));this.changingSrc_=!1,this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0),this.triggerReady();return}Kw(r,this.tech_)}),i.length>1){const s=()=>{this.error(null),this.handleSrc_(i.slice(1),!0)},r=()=>{this.off("error",s)};this.one("error",s),this.one("playing",r),this.resetRetryOnError_=()=>{this.off("error",s),this.off("playing",r)}}}src(e){return this.handleSrc_(e,!1)}src_(e){const t=this.selectSource([e]);return t?ov(t.tech,this.techName_)?(this.ready(function(){this.tech_.constructor.prototype.hasOwnProperty("setSource")?this.techCall_("setSource",e):this.techCall_("src",e.src),this.changingSrc_=!1},!0),!1):(this.changingSrc_=!0,this.loadTech_(t.tech,t.source),this.tech_.ready(()=>{this.changingSrc_=!1}),!1):!0}addSourceElement(e,t){return this.tech_?this.tech_.addSourceElement(e,t):!1}removeSourceElement(e){return this.tech_?this.tech_.removeSourceElement(e):!1}load(){if(this.tech_&&this.tech_.vhs){this.src(this.currentSource());return}this.techCall_("load")}reset(){if(this.paused())this.doReset_();else{const e=this.play();fn(e.then(()=>this.doReset_()))}}doReset_(){this.tech_&&this.tech_.clearTracks("text"),this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.resetCache_(),this.poster(""),this.loadTech_(this.options_.techOrder[0],null),this.techCall_("reset"),this.resetControlBarUI_(),this.error(null),this.titleBar&&this.titleBar.update({title:void 0,description:void 0}),Ln(this)&&this.trigger("playerreset")}resetControlBarUI_(){this.resetProgressBar_(),this.resetPlaybackRate_(),this.resetVolumeBar_()}resetProgressBar_(){this.currentTime(0);const{currentTimeDisplay:e,durationDisplay:t,progressControl:i,remainingTimeDisplay:s}=this.controlBar||{},{seekBar:r}=i||{};e&&e.updateContent(),t&&t.updateContent(),s&&s.updateContent(),r&&(r.update(),r.loadProgressBar&&r.loadProgressBar.update())}resetPlaybackRate_(){this.playbackRate(this.defaultPlaybackRate()),this.handleTechRateChange_()}resetVolumeBar_(){this.volume(1),this.trigger("volumechange")}currentSources(){const e=this.currentSource(),t=[];return Object.keys(e).length!==0&&t.push(e),this.cache_.sources||t}currentSource(){return this.cache_.source||{}}currentSrc(){return this.currentSource()&&this.currentSource().src||""}currentType(){return this.currentSource()&&this.currentSource().type||""}preload(e){if(e!==void 0){this.techCall_("setPreload",e),this.options_.preload=e;return}return this.techGet_("preload")}autoplay(e){if(e===void 0)return this.options_.autoplay||!1;let t;typeof e=="string"&&/(any|play|muted)/.test(e)||e===!0&&this.options_.normalizeAutoplay?(this.options_.autoplay=e,this.manualAutoplay_(typeof e=="string"?e:"play"),t=!1):e?this.options_.autoplay=!0:this.options_.autoplay=!1,t=typeof t>"u"?this.options_.autoplay:t,this.tech_&&this.techCall_("setAutoplay",t)}playsinline(e){return e!==void 0&&(this.techCall_("setPlaysinline",e),this.options_.playsinline=e),this.techGet_("playsinline")}loop(e){if(e!==void 0){this.techCall_("setLoop",e),this.options_.loop=e;return}return this.techGet_("loop")}poster(e){if(e===void 0)return this.poster_;e||(e=""),e!==this.poster_&&(this.poster_=e,this.techCall_("setPoster",e),this.isPosterFromTech_=!1,this.trigger("posterchange"))}handleTechPosterChange_(){if((!this.poster_||this.options_.techCanOverridePoster)&&this.tech_&&this.tech_.poster){const e=this.tech_.poster()||"";e!==this.poster_&&(this.poster_=e,this.isPosterFromTech_=!0,this.trigger("posterchange"))}}controls(e){if(e===void 0)return!!this.controls_;e=!!e,this.controls_!==e&&(this.controls_=e,this.usingNativeControls()&&this.techCall_("setControls",e),this.controls_?(this.removeClass("vjs-controls-disabled"),this.addClass("vjs-controls-enabled"),this.trigger("controlsenabled"),this.usingNativeControls()||this.addTechControlsListeners_()):(this.removeClass("vjs-controls-enabled"),this.addClass("vjs-controls-disabled"),this.trigger("controlsdisabled"),this.usingNativeControls()||this.removeTechControlsListeners_()))}usingNativeControls(e){if(e===void 0)return!!this.usingNativeControls_;e=!!e,this.usingNativeControls_!==e&&(this.usingNativeControls_=e,this.usingNativeControls_?(this.addClass("vjs-using-native-controls"),this.trigger("usingnativecontrols")):(this.removeClass("vjs-using-native-controls"),this.trigger("usingcustomcontrols")))}error(e){if(e===void 0)return this.error_||null;if(ss("beforeerror").forEach(t=>{const i=t(this,e);if(!(un(i)&&!Array.isArray(i)||typeof i=="string"||typeof i=="number"||i===null)){this.log.error("please return a value that MediaError expects in beforeerror hooks");return}e=i}),this.options_.suppressNotSupportedError&&e&&e.code===4){const t=function(){this.error(e)};this.options_.suppressNotSupportedError=!1,this.any(["click","touchstart"],t),this.one("loadstart",function(){this.off(["click","touchstart"],t)});return}if(e===null){this.error_=null,this.removeClass("vjs-error"),this.errorDisplay&&this.errorDisplay.close();return}this.error_=new ct(e),this.addClass("vjs-error"),Oe.error(`(CODE:${this.error_.code} ${ct.errorTypes[this.error_.code]})`,this.error_.message,this.error_),this.trigger("error"),ss("error").forEach(t=>t(this,this.error_))}reportUserActivity(e){this.userActivity_=!0}userActive(e){if(e===void 0)return this.userActive_;if(e=!!e,e!==this.userActive_){if(this.userActive_=e,this.userActive_){this.userActivity_=!0,this.removeClass("vjs-user-inactive"),this.addClass("vjs-user-active"),this.trigger("useractive");return}this.tech_&&this.tech_.one("mousemove",function(t){t.stopPropagation(),t.preventDefault()}),this.userActivity_=!1,this.removeClass("vjs-user-active"),this.addClass("vjs-user-inactive"),this.trigger("userinactive")}}listenForUserActivity_(){let e,t,i;const s=Ze(this,this.reportUserActivity),r=function(h){(h.screenX!==t||h.screenY!==i)&&(t=h.screenX,i=h.screenY,s())},a=function(){s(),this.clearInterval(e),e=this.setInterval(s,250)},o=function(h){s(),this.clearInterval(e)};this.on("mousedown",a),this.on("mousemove",r),this.on("mouseup",o),this.on("mouseleave",o);const c=this.getChild("controlBar");c&&!Ht&&!Wi&&(c.on("mouseenter",function(h){this.player().options_.inactivityTimeout!==0&&(this.player().cache_.inactivityTimeout=this.player().options_.inactivityTimeout),this.player().options_.inactivityTimeout=0}),c.on("mouseleave",function(h){this.player().options_.inactivityTimeout=this.player().cache_.inactivityTimeout})),this.on("keydown",s),this.on("keyup",s);let l;const u=function(){if(!this.userActivity_)return;this.userActivity_=!1,this.userActive(!0),this.clearTimeout(l);const h=this.options_.inactivityTimeout;h<=0||(l=this.setTimeout(function(){this.userActivity_||this.userActive(!1)},h))};this.setInterval(u,250)}playbackRate(e){if(e!==void 0){this.techCall_("setPlaybackRate",e);return}return this.tech_&&this.tech_.featuresPlaybackRate?this.cache_.lastPlaybackRate||this.techGet_("playbackRate"):1}defaultPlaybackRate(e){return e!==void 0?this.techCall_("setDefaultPlaybackRate",e):this.tech_&&this.tech_.featuresPlaybackRate?this.techGet_("defaultPlaybackRate"):1}isAudio(e){if(e!==void 0){this.isAudio_=!!e;return}return!!this.isAudio_}updatePlayerHeightOnAudioOnlyMode_(){const e=this.getChild("ControlBar");!e||this.audioOnlyCache_.controlBarHeight===e.currentHeight()||(this.audioOnlyCache_.controlBarHeight=e.currentHeight(),this.height(this.audioOnlyCache_.controlBarHeight))}enableAudioOnlyUI_(){this.addClass("vjs-audio-only-mode");const e=this.children(),t=this.getChild("ControlBar"),i=t&&t.currentHeight();e.forEach(s=>{s!==t&&s.el_&&!s.hasClass("vjs-hidden")&&(s.hide(),this.audioOnlyCache_.hiddenChildren.push(s))}),this.audioOnlyCache_.playerHeight=this.currentHeight(),this.audioOnlyCache_.controlBarHeight=i,this.on("playerresize",this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.height(i),this.trigger("audioonlymodechange")}disableAudioOnlyUI_(){this.removeClass("vjs-audio-only-mode"),this.off("playerresize",this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.audioOnlyCache_.hiddenChildren.forEach(e=>e.show()),this.height(this.audioOnlyCache_.playerHeight),this.trigger("audioonlymodechange")}audioOnlyMode(e){if(typeof e!="boolean"||e===this.audioOnlyMode_)return this.audioOnlyMode_;if(this.audioOnlyMode_=e,e){const t=[];return this.isInPictureInPicture()&&t.push(this.exitPictureInPicture()),this.isFullscreen()&&t.push(this.exitFullscreen()),this.audioPosterMode()&&t.push(this.audioPosterMode(!1)),Promise.all(t).then(()=>this.enableAudioOnlyUI_())}return Promise.resolve().then(()=>this.disableAudioOnlyUI_())}enablePosterModeUI_(){(this.tech_&&this.tech_).hide(),this.addClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}disablePosterModeUI_(){(this.tech_&&this.tech_).show(),this.removeClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}audioPosterMode(e){return typeof e!="boolean"||e===this.audioPosterMode_?this.audioPosterMode_:(this.audioPosterMode_=e,e?this.audioOnlyMode()?this.audioOnlyMode(!1).then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.disablePosterModeUI_()}))}addTextTrack(e,t,i){if(this.tech_)return this.tech_.addTextTrack(e,t,i)}addRemoteTextTrack(e,t){if(this.tech_)return this.tech_.addRemoteTextTrack(e,t)}removeRemoteTextTrack(e={}){let{track:t}=e;if(t||(t=e),this.tech_)return this.tech_.removeRemoteTextTrack(t)}getVideoPlaybackQuality(){return this.techGet_("getVideoPlaybackQuality")}videoWidth(){return this.tech_&&this.tech_.videoWidth&&this.tech_.videoWidth()||0}videoHeight(){return this.tech_&&this.tech_.videoHeight&&this.tech_.videoHeight()||0}language(e){if(e===void 0)return this.language_;this.language_!==String(e).toLowerCase()&&(this.language_=String(e).toLowerCase(),Ln(this)&&this.trigger("languagechange"))}languages(){return Qe($e.prototype.options_.languages,this.languages_)}toJSON(){const e=Qe(this.options_),t=e.tracks;e.tracks=[];for(let i=0;i<t.length;i++){let s=t[i];s=Qe(s),s.player=void 0,e.tracks[i]=s}return e}createModal(e,t){t=t||{},t.content=e||"";const i=new Pr(this,t);return this.addChild(i),i.on("dispose",()=>{this.removeChild(i)}),i.open(),i}updateCurrentBreakpoint_(){if(!this.responsive())return;const e=this.currentBreakpoint(),t=this.currentWidth();for(let i=0;i<sf.length;i++){const s=sf[i],r=this.breakpoints_[s];if(t<=r){if(e===s)return;e&&this.removeClass(hl[e]),this.addClass(hl[s]),this.breakpoint_=s;break}}}removeCurrentBreakpoint_(){const e=this.currentBreakpointClass();this.breakpoint_="",e&&this.removeClass(e)}breakpoints(e){return e===void 0?Object.assign(this.breakpoints_):(this.removeCurrentBreakpoint_(),this.breakpoints_=Object.assign({},LA,e),this.updateCurrentBreakpoint_(),Object.assign(this.breakpoints_))}responsive(e){if(e===void 0)return this.responsive_;e=!!e;const t=this.responsive_;if(e!==t)return this.responsive_=e,e?(this.on("playerresize",this.boundUpdateCurrentBreakpoint_),this.updateCurrentBreakpoint_()):(this.off("playerresize",this.boundUpdateCurrentBreakpoint_),this.removeCurrentBreakpoint_()),e}currentBreakpoint(){return this.breakpoint_}currentBreakpointClass(){return hl[this.breakpoint_]||""}loadMedia(e,t){if(!e||typeof e!="object")return;const i=this.crossOrigin();this.reset(),this.cache_.media=Qe(e);const{artist:s,artwork:r,description:a,poster:o,src:c,textTracks:l,title:u}=this.cache_.media;!r&&o&&(this.cache_.media.artwork=[{src:o,type:cl(o)}]),i&&this.crossOrigin(i),c&&this.src(c),o&&this.poster(o),Array.isArray(l)&&l.forEach(h=>this.addRemoteTextTrack(h,!1)),this.titleBar&&this.titleBar.update({title:u,description:a||s||""}),this.ready(t)}getMedia(){if(!this.cache_.media){const e=this.poster(),t=this.currentSources(),i=Array.prototype.map.call(this.remoteTextTracks(),r=>({kind:r.kind,label:r.label,language:r.language,src:r.src})),s={src:t,textTracks:i};return e&&(s.poster=e,s.artwork=[{src:s.poster,type:cl(s.poster)}]),s}return Qe(this.cache_.media)}static getTagSettings(e){const t={sources:[],tracks:[]},i=cs(e),s=i["data-setup"];if(ja(e,"vjs-fill")&&(i.fill=!0),ja(e,"vjs-fluid")&&(i.fluid=!0),s!==null)try{Object.assign(i,JSON.parse(s||"{}"))}catch(r){Oe.error("data-setup",r)}if(Object.assign(t,i),e.hasChildNodes()){const r=e.childNodes;for(let a=0,o=r.length;a<o;a++){const c=r[a],l=c.nodeName.toLowerCase();l==="source"?t.sources.push(cs(c)):l==="track"&&t.tracks.push(cs(c))}}return t}debug(e){if(e===void 0)return this.debugEnabled_;e?(this.trigger("debugon"),this.previousLogLevel_=this.log.level,this.log.level("debug"),this.debugEnabled_=!0):(this.trigger("debugoff"),this.log.level(this.previousLogLevel_),this.previousLogLevel_=void 0,this.debugEnabled_=!1)}playbackRates(e){if(e===void 0)return this.cache_.playbackRates;Array.isArray(e)&&e.every(t=>typeof t=="number")&&(this.cache_.playbackRates=e,this.trigger("playbackrateschange"))}}$e.prototype.videoTracks=()=>{},$e.prototype.audioTracks=()=>{},$e.prototype.textTracks=()=>{},$e.prototype.remoteTextTracks=()=>{},$e.prototype.remoteTextTrackEls=()=>{},ti.names.forEach(function(n){const e=ti[n];$e.prototype[e.getterName]=function(){return this.tech_?this.tech_[e.getterName]():(this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName])}}),$e.prototype.crossorigin=$e.prototype.crossOrigin,$e.players={};const Ja=B.navigator;$e.prototype.options_={techOrder:De.defaultTechOrder_,html5:{},enableSourceset:!0,inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:["mediaLoader","posterImage","titleBar","textTrackDisplay","loadingSpinner","bigPlayButton","liveTracker","controlBar","errorDisplay","textTrackSettings","resizeManager"],language:Ja&&(Ja.languages&&Ja.languages[0]||Ja.userLanguage||Ja.language)||"en",languages:{},notSupportedMessage:"No compatible source was found for this media.",normalizeAutoplay:!1,fullscreen:{options:{navigationUI:"hide"}},breakpoints:{},responsive:!1,audioOnlyMode:!1,audioPosterMode:!1,spatialNavigation:{enabled:!1,horizontalSeek:!1},enableSmoothSeeking:!1,disableSeekWhileScrubbingOnMobile:!1,disableSeekWhileScrubbingOnSTV:!1},pb.forEach(function(n){$e.prototype[`handleTech${pt(n)}_`]=function(){return this.trigger(n)}}),ee.registerComponent("Player",$e);const fl="plugin",Lr="activePlugins_",Nr={},pl=n=>Nr.hasOwnProperty(n),ml=n=>pl(n)?Nr[n]:void 0,mb=(n,e)=>{n[Lr]=n[Lr]||{},n[Lr][e]=!0},gl=(n,e,t)=>{const i=(t?"before":"")+"pluginsetup";n.trigger(i,e),n.trigger(i+":"+e.name,e)},NA=function(n,e){const t=function(){gl(this,{name:n,plugin:e,instance:null},!0);const i=e.apply(this,arguments);return mb(this,n),gl(this,{name:n,plugin:e,instance:i}),i};return Object.keys(e).forEach(function(i){t[i]=e[i]}),t},gb=(n,e)=>(e.prototype.name=n,function(...t){gl(this,{name:n,plugin:e,instance:null},!0);const i=new e(this,...t);return this[n]=()=>i,gl(this,i.getEventHash()),i});class ui{constructor(e){if(this.constructor===ui)throw new Error("Plugin must be sub-classed; not directly instantiated.");this.player=e,this.log||(this.log=this.player.log.createLogger(this.name)),Sh(this),delete this.trigger,av(this,this.constructor.defaultState),mb(e,this.name),this.dispose=this.dispose.bind(this),e.on("dispose",this.dispose)}version(){return this.constructor.VERSION}getEventHash(e={}){return e.name=this.name,e.plugin=this.constructor,e.instance=this,e}trigger(e,t={}){return Dr(this.eventBusEl_,e,this.getEventHash(t))}handleStateChanged(e){}dispose(){const{name:e,player:t}=this;this.trigger("dispose"),this.off(),t.off("dispose",this.dispose),t[Lr][e]=!1,this.player=this.state=null,t[e]=gb(e,Nr[e])}static isBasic(e){const t=typeof e=="string"?ml(e):e;return typeof t=="function"&&!ui.prototype.isPrototypeOf(t.prototype)}static registerPlugin(e,t){if(typeof e!="string")throw new Error(`Illegal plugin name, "${e}", must be a string, was ${typeof e}.`);if(pl(e))Oe.warn(`A plugin named "${e}" already exists. You may want to avoid re-registering plugins!`);else if($e.prototype.hasOwnProperty(e))throw new Error(`Illegal plugin name, "${e}", cannot share a name with an existing player method!`);if(typeof t!="function")throw new Error(`Illegal plugin for "${e}", must be a function, was ${typeof t}.`);return Nr[e]=t,e!==fl&&(ui.isBasic(t)?$e.prototype[e]=NA(e,t):$e.prototype[e]=gb(e,t)),t}static deregisterPlugin(e){if(e===fl)throw new Error("Cannot de-register base plugin.");pl(e)&&(delete Nr[e],delete $e.prototype[e])}static getPlugins(e=Object.keys(Nr)){let t;return e.forEach(i=>{const s=ml(i);s&&(t=t||{},t[i]=s)}),t}static getPluginVersion(e){const t=ml(e);return t&&t.VERSION||""}}ui.getPlugin=ml,ui.BASE_PLUGIN_NAME=fl,ui.registerPlugin(fl,ui),$e.prototype.usingPlugin=function(n){return!!this[Lr]&&this[Lr][n]===!0},$e.prototype.hasPlugin=function(n){return!!pl(n)};function FA(n,e){let t=!1;return function(...i){return t||Oe.warn(n),t=!0,e.apply(this,i)}}function Gi(n,e,t,i){return FA(`${e} is deprecated and will be removed in ${n}.0; please use ${t} instead.`,i)}var UA={NetworkBadStatus:"networkbadstatus",NetworkRequestFailed:"networkrequestfailed",NetworkRequestAborted:"networkrequestaborted",NetworkRequestTimeout:"networkrequesttimeout",NetworkBodyParserFailed:"networkbodyparserfailed",StreamingHlsPlaylistParserError:"streaminghlsplaylistparsererror",StreamingDashManifestParserError:"streamingdashmanifestparsererror",StreamingContentSteeringParserError:"streamingcontentsteeringparsererror",StreamingVttParserError:"streamingvttparsererror",StreamingFailedToSelectNextSegment:"streamingfailedtoselectnextsegment",StreamingFailedToDecryptSegment:"streamingfailedtodecryptsegment",StreamingFailedToTransmuxSegment:"streamingfailedtotransmuxsegment",StreamingFailedToAppendSegment:"streamingfailedtoappendsegment",StreamingCodecsChangeError:"streamingcodecschangeerror"};const yb=n=>n.indexOf("#")===0?n.slice(1):n;function K(n,e,t){let i=K.getPlayer(n);if(i)return e&&Oe.warn(`Player "${n}" is already initialised. Options will not be applied.`),t&&i.ready(t),i;const s=typeof n=="string"?ls("#"+yb(n)):n;if(!Er(s))throw new TypeError("The element or ID supplied is not valid. (videojs)");const a=("getRootNode"in s?s.getRootNode()instanceof B.ShadowRoot:!1)?s.getRootNode():s.ownerDocument.body;(!s.ownerDocument.defaultView||!a.contains(s))&&Oe.warn("The element supplied is not included in the DOM"),e=e||{},e.restoreEl===!0&&(e.restoreEl=(s.parentNode&&s.parentNode.hasAttribute&&s.parentNode.hasAttribute("data-vjs-player")?s.parentNode:s).cloneNode(!0)),ss("beforesetup").forEach(c=>{const l=c(s,Qe(e));if(!un(l)||Array.isArray(l)){Oe.error("please return an object in beforesetup hooks");return}e=Qe(e,l)});const o=ee.getComponent("Player");return i=new o(s,e,t),ss("setup").forEach(c=>c(i)),i}if(K.hooks_=Mn,K.hooks=ss,K.hook=_w,K.hookOnce=Sw,K.removeHook=Ay,B.VIDEOJS_NO_DYNAMIC_STYLE!==!0&&kr()){let n=ls(".vjs-styles-defaults");if(!n){n=ev("vjs-styles-defaults");const e=ls("head");e&&e.insertBefore(n,e.firstChild),tv(n,`
|
|
236
|
+
.video-js {
|
|
237
|
+
width: 300px;
|
|
238
|
+
height: 150px;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
.vjs-fluid:not(.vjs-audio-only-mode) {
|
|
242
|
+
padding-top: 56.25%
|
|
243
|
+
}
|
|
244
|
+
`)}}gh(1,K),K.VERSION=lh,K.options=$e.prototype.options_,K.getPlayers=()=>$e.players,K.getPlayer=n=>{const e=$e.players;let t;if(typeof n=="string"){const i=yb(n),s=e[i];if(s)return s;t=ls("#"+i)}else t=n;if(Er(t)){const{player:i,playerId:s}=t;if(i||e[s])return i||e[s]}},K.getAllPlayers=()=>Object.keys($e.players).map(n=>$e.players[n]).filter(Boolean),K.players=$e.players,K.getComponent=ee.getComponent,K.registerComponent=(n,e)=>(De.isTech(e)&&Oe.warn(`The ${n} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`),ee.registerComponent.call(ee,n,e)),K.getTech=De.getTech,K.registerTech=De.registerTech,K.use=zw,Object.defineProperty(K,"middleware",{value:{},writeable:!1,enumerable:!0}),Object.defineProperty(K.middleware,"TERMINATOR",{value:ol,writeable:!1,enumerable:!0}),K.browser=Uy,K.obj=Ew,K.mergeOptions=Gi(9,"videojs.mergeOptions","videojs.obj.merge",Qe),K.defineLazyProperty=Gi(9,"videojs.defineLazyProperty","videojs.obj.defineLazyProperty",Bc),K.bind=Gi(9,"videojs.bind","native Function.prototype.bind",Ze),K.registerPlugin=ui.registerPlugin,K.deregisterPlugin=ui.deregisterPlugin,K.plugin=(n,e)=>(Oe.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),ui.registerPlugin(n,e)),K.getPlugins=ui.getPlugins,K.getPlugin=ui.getPlugin,K.getPluginVersion=ui.getPluginVersion,K.addLanguage=function(n,e){return n=(""+n).toLowerCase(),K.options.languages=Qe(K.options.languages,{[n]:e}),K.options.languages[n]},K.log=Oe,K.createLogger=Py,K.time=Bw,K.createTimeRange=Gi(9,"videojs.createTimeRange","videojs.time.createTimeRanges",zi),K.createTimeRanges=Gi(9,"videojs.createTimeRanges","videojs.time.createTimeRanges",zi),K.formatTime=Gi(9,"videojs.formatTime","videojs.time.formatTime",Fs),K.setFormatTime=Gi(9,"videojs.setFormatTime","videojs.time.setFormatTime",uv),K.resetFormatTime=Gi(9,"videojs.resetFormatTime","videojs.time.resetFormatTime",dv),K.parseUrl=Gi(9,"videojs.parseUrl","videojs.url.parseUrl",Rh),K.isCrossOrigin=Gi(9,"videojs.isCrossOrigin","videojs.url.isCrossOrigin",rl),K.EventTarget=bi,K.any=bh,K.on=vi,K.one=tl,K.off=$t,K.trigger=Dr,K.xhr=B0,K.TrackList=Us,K.TextTrack=Ka,K.TextTrackList=Ph,K.AudioTrack=bv,K.AudioTrackList=fv,K.VideoTrack=Tv,K.VideoTrackList=pv,["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach(n=>{K[n]=function(){return Oe.warn(`videojs.${n}() is deprecated; use videojs.dom.${n}() instead`),Jy[n].apply(null,arguments)}}),K.computedStyle=Gi(9,"videojs.computedStyle","videojs.dom.computedStyle",Ar),K.dom=Jy,K.fn=Ow,K.num=fA,K.str=Fw,K.url=$w,K.Error=UA;/*! @name videojs-contrib-quality-levels @version 4.1.0 @license Apache-2.0 */class BA{constructor(e){let t=this;return t.id=e.id,t.label=t.id,t.width=e.width,t.height=e.height,t.bitrate=e.bandwidth,t.frameRate=e.frameRate,t.enabled_=e.enabled,Object.defineProperty(t,"enabled",{get(){return t.enabled_()},set(i){t.enabled_(i)}}),t}}class yl extends K.EventTarget{constructor(){super();let e=this;return e.levels_=[],e.selectedIndex_=-1,Object.defineProperty(e,"selectedIndex",{get(){return e.selectedIndex_}}),Object.defineProperty(e,"length",{get(){return e.levels_.length}}),e[Symbol.iterator]=()=>e.levels_.values(),e}addQualityLevel(e){let t=this.getQualityLevelById(e.id);if(t)return t;const i=this.levels_.length;return t=new BA(e),""+i in this||Object.defineProperty(this,i,{get(){return this.levels_[i]}}),this.levels_.push(t),this.trigger({qualityLevel:t,type:"addqualitylevel"}),t}removeQualityLevel(e){let t=null;for(let i=0,s=this.length;i<s;i++)if(this[i]===e){t=this.levels_.splice(i,1)[0],this.selectedIndex_===i?this.selectedIndex_=-1:this.selectedIndex_>i&&this.selectedIndex_--;break}return t&&this.trigger({qualityLevel:e,type:"removequalitylevel"}),t}getQualityLevelById(e){for(let t=0,i=this.length;t<i;t++){const s=this[t];if(s.id===e)return s}return null}dispose(){this.selectedIndex_=-1,this.levels_.length=0}}yl.prototype.allowedEvents_={change:"change",addqualitylevel:"addqualitylevel",removequalitylevel:"removequalitylevel"};for(const n in yl.prototype.allowedEvents_)yl.prototype["on"+n]=null;var vb="4.1.0";const qA=function(n,e){const t=n.qualityLevels,i=new yl,s=function(){i.dispose(),n.qualityLevels=t,n.off("dispose",s)};return n.on("dispose",s),n.qualityLevels=()=>i,n.qualityLevels.VERSION=vb,i},bb=function(n){return qA(this,K.obj.merge({},n))};K.registerPlugin("qualityLevels",bb),bb.VERSION=vb;/*! @name @videojs/http-streaming @version 3.17.5 @license Apache-2.0 */const di=Ic,vl=(n,e)=>e&&e.responseURL&&n!==e.responseURL?e.responseURL:n,Oi=n=>K.log.debug?K.log.debug.bind(K,"VHS:",`${n} >`):function(){};function We(...n){const e=K.obj||K;return(e.merge||e.mergeOptions).apply(e,n)}function Ot(...n){const e=K.time||K;return(e.createTimeRanges||e.createTimeRanges).apply(e,n)}function VA(n){if(n.length===0)return"Buffered Ranges are empty";let e=`Buffered Ranges:
|
|
245
|
+
`;for(let t=0;t<n.length;t++){const i=n.start(t),s=n.end(t);e+=`${i} --> ${s}. Duration (${s-i})
|
|
246
|
+
`}return e}const mn=1/30,gn=mn*3,Tb=function(n,e){const t=[];let i;if(n&&n.length)for(i=0;i<n.length;i++)e(n.start(i),n.end(i))&&t.push([n.start(i),n.end(i)]);return Ot(t)},Fr=function(n,e){return Tb(n,function(t,i){return t-gn<=e&&i+gn>=e})},bl=function(n,e){return Tb(n,function(t){return t-mn>=e})},jA=function(n){if(n.length<2)return Ot();const e=[];for(let t=1;t<n.length;t++){const i=n.end(t-1),s=n.start(t);e.push([i,s])}return Ot(e)},HA=function(n,e){let t=null,i=null,s=0;const r=[],a=[];if(!n||!n.length||!e||!e.length)return Ot();let o=n.length;for(;o--;)r.push({time:n.start(o),type:"start"}),r.push({time:n.end(o),type:"end"});for(o=e.length;o--;)r.push({time:e.start(o),type:"start"}),r.push({time:e.end(o),type:"end"});for(r.sort(function(c,l){return c.time-l.time}),o=0;o<r.length;o++)r[o].type==="start"?(s++,s===2&&(t=r[o].time)):r[o].type==="end"&&(s--,s===1&&(i=r[o].time)),t!==null&&i!==null&&(a.push([t,i]),t=null,i=null);return Ot(a)},_b=n=>{const e=[];if(!n||!n.length)return"";for(let t=0;t<n.length;t++)e.push(n.start(t)+" => "+n.end(t));return e.join(", ")},$A=function(n,e,t=1){return((n.length?n.end(n.length-1):0)-e)/t},js=n=>{const e=[];for(let t=0;t<n.length;t++)e.push({start:n.start(t),end:n.end(t)});return e},WA=function(n,e){if(n===e)return!1;if(!n&&e||!e&&n||n.length!==e.length)return!0;for(let t=0;t<n.length;t++)if(n.start(t)!==e.start(t)||n.end(t)!==e.end(t))return!0;return!1},rf=function(n){if(!(!n||!n.length||!n.end))return n.end(n.length-1)},af=function(n,e){let t=0;if(!n||!n.length)return t;for(let i=0;i<n.length;i++){const s=n.start(i),r=n.end(i);if(!(e>r)){if(e>s&&e<=r){t+=r-e;continue}t+=r-s}}return t},of=(n,e)=>{if(!e.preload)return e.duration;let t=0;return(e.parts||[]).forEach(function(i){t+=i.duration}),(e.preloadHints||[]).forEach(function(i){i.type==="PART"&&(t+=n.partTargetDuration)}),t},cf=n=>(n.segments||[]).reduce((e,t,i)=>(t.parts?t.parts.forEach(function(s,r){e.push({duration:s.duration,segmentIndex:i,partIndex:r,part:s,segment:t})}):e.push({duration:t.duration,segmentIndex:i,partIndex:null,segment:t,part:null}),e),[]),Sb=n=>{const e=n.segments&&n.segments.length&&n.segments[n.segments.length-1];return e&&e.parts||[]},Cb=({preloadSegment:n})=>{if(!n)return;const{parts:e,preloadHints:t}=n;let i=(t||[]).reduce((s,r)=>s+(r.type==="PART"?1:0),0);return i+=e&&e.length?e.length:0,i},kb=(n,e)=>{if(e.endList)return 0;if(n&&n.suggestedPresentationDelay)return n.suggestedPresentationDelay;const t=Sb(e).length>0;return t&&e.serverControl&&e.serverControl.partHoldBack?e.serverControl.partHoldBack:t&&e.partTargetDuration?e.partTargetDuration*3:e.serverControl&&e.serverControl.holdBack?e.serverControl.holdBack:e.targetDuration?e.targetDuration*3:0},zA=function(n,e){let t=0,i=e-n.mediaSequence,s=n.segments[i];if(s){if(typeof s.start<"u")return{result:s.start,precise:!0};if(typeof s.end<"u")return{result:s.end-s.duration,precise:!0}}for(;i--;){if(s=n.segments[i],typeof s.end<"u")return{result:t+s.end,precise:!0};if(t+=of(n,s),typeof s.start<"u")return{result:t+s.start,precise:!0}}return{result:t,precise:!1}},GA=function(n,e){let t=0,i,s=e-n.mediaSequence;for(;s<n.segments.length;s++){if(i=n.segments[s],typeof i.start<"u")return{result:i.start-t,precise:!0};if(t+=of(n,i),typeof i.end<"u")return{result:i.end-t,precise:!0}}return{result:-1,precise:!1}},Eb=function(n,e,t){if(typeof e>"u"&&(e=n.mediaSequence+n.segments.length),e<n.mediaSequence)return 0;const i=zA(n,e);if(i.precise)return i.result;const s=GA(n,e);return s.precise?s.result:i.result+t},xb=function(n,e,t){if(!n)return 0;if(typeof t!="number"&&(t=0),typeof e>"u"){if(n.totalDuration)return n.totalDuration;if(!n.endList)return B.Infinity}return Eb(n,e,t)},Za=function({defaultDuration:n,durationList:e,startIndex:t,endIndex:i}){let s=0;if(t>i&&([t,i]=[i,t]),t<0){for(let r=t;r<Math.min(0,i);r++)s+=n;t=0}for(let r=t;r<i;r++)s+=e[r].duration;return s},wb=function(n,e,t,i){if(!n||!n.segments)return null;if(n.endList)return xb(n);if(e===null)return null;e=e||0;let s=Eb(n,n.mediaSequence+n.segments.length,e);return t&&(i=typeof i=="number"?i:kb(null,n),s-=i),Math.max(0,s)},KA=function(n,e,t){const s=e||0;let r=wb(n,e,!0,t);return r===null?Ot():(r<s&&(r=s),Ot(s,r))},XA=function({playlist:n,currentTime:e,startingSegmentIndex:t,startingPartIndex:i,startTime:s,exactManifestTimings:r}){let a=e-s;const o=cf(n);let c=0;for(let l=0;l<o.length;l++){const u=o[l];if(t===u.segmentIndex&&!(typeof i=="number"&&typeof u.partIndex=="number"&&i!==u.partIndex)){c=l;break}}if(a<0){if(c>0)for(let l=c-1;l>=0;l--){const u=o[l];if(a+=u.duration,r){if(a<0)continue}else if(a+mn<=0)continue;return{partIndex:u.partIndex,segmentIndex:u.segmentIndex,startTime:s-Za({defaultDuration:n.targetDuration,durationList:o,startIndex:c,endIndex:l})}}return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:e}}if(c<0){for(let l=c;l<0;l++)if(a-=n.targetDuration,a<0)return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:e};c=0}for(let l=c;l<o.length;l++){const u=o[l];a-=u.duration;const h=u.duration>mn,p=a===0,y=h&&a+mn>=0;if(!((p||y)&&l!==o.length-1)){if(r){if(a>0)continue}else if(a-mn>=0)continue;return{partIndex:u.partIndex,segmentIndex:u.segmentIndex,startTime:s+Za({defaultDuration:n.targetDuration,durationList:o,startIndex:c,endIndex:l})}}}return{segmentIndex:o[o.length-1].segmentIndex,partIndex:o[o.length-1].partIndex,startTime:e}},Ab=function(n){return n.excludeUntil&&n.excludeUntil>Date.now()},lf=function(n){return n.excludeUntil&&n.excludeUntil===1/0},Tl=function(n){const e=Ab(n);return!n.disabled&&!e},YA=function(n){return n.disabled},QA=function(n){for(let e=0;e<n.segments.length;e++)if(n.segments[e].key)return!0;return!1},Db=function(n,e){return e.attributes&&e.attributes[n]},JA=function(n,e,t,i=0){return Db("BANDWIDTH",t)?(n*t.attributes.BANDWIDTH-i*8)/e:NaN},uf=(n,e)=>{if(n.playlists.length===1)return!0;const t=e.attributes.BANDWIDTH||Number.MAX_VALUE;return n.playlists.filter(i=>Tl(i)?(i.attributes.BANDWIDTH||0)<t:!1).length===0},df=(n,e)=>!n&&!e||!n&&e||n&&!e?!1:!!(n===e||n.id&&e.id&&n.id===e.id||n.resolvedUri&&e.resolvedUri&&n.resolvedUri===e.resolvedUri||n.uri&&e.uri&&n.uri===e.uri),Pb=function(n,e){const t=n&&n.mediaGroups&&n.mediaGroups.AUDIO||{};let i=!1;for(const s in t){for(const r in t[s])if(i=e(t[s][r]),i)break;if(i)break}return!!i},eo=n=>{if(!n||!n.playlists||!n.playlists.length)return Pb(n,t=>t.playlists&&t.playlists.length||t.uri);for(let e=0;e<n.playlists.length;e++){const t=n.playlists[e],i=t.attributes&&t.attributes.CODECS;if(!(i&&i.split(",").every(r=>Y0(r))||Pb(n,r=>df(t,r))))return!1}return!0};var hi={liveEdgeDelay:kb,duration:xb,seekable:KA,getMediaInfoForTime:XA,isEnabled:Tl,isDisabled:YA,isExcluded:Ab,isIncompatible:lf,playlistEnd:wb,isAes:QA,hasAttribute:Db,estimateSegmentRequestTime:JA,isLowestEnabledRendition:uf,isAudioOnly:eo,playlistMatch:df,segmentDurationWithParts:of};const{log:Ib}=K,Ur=(n,e)=>`${n}-${e}`,Rb=(n,e,t)=>`placeholder-uri-${n}-${e}-${t}`,ZA=({onwarn:n,oninfo:e,manifestString:t,customTagParsers:i=[],customTagMappers:s=[],llhls:r})=>{const a=new j1;n&&a.on("warn",n),e&&a.on("info",e),i.forEach(l=>a.addParser(l)),s.forEach(l=>a.addTagMapper(l)),a.push(t),a.end();const o=a.manifest;if(r||(["preloadSegment","skip","serverControl","renditionReports","partInf","partTargetDuration"].forEach(function(l){o.hasOwnProperty(l)&&delete o[l]}),o.segments&&o.segments.forEach(function(l){["parts","preloadHints"].forEach(function(u){l.hasOwnProperty(u)&&delete l[u]})})),!o.targetDuration){let l=10;o.segments&&o.segments.length&&(l=o.segments.reduce((u,h)=>Math.max(u,h.duration),0)),n&&n({message:`manifest has no targetDuration defaulting to ${l}`}),o.targetDuration=l}const c=Sb(o);if(c.length&&!o.partTargetDuration){const l=c.reduce((u,h)=>Math.max(u,h.duration),0);n&&(n({message:`manifest has no partTargetDuration defaulting to ${l}`}),Ib.error("LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.")),o.partTargetDuration=l}return o},Br=(n,e)=>{n.mediaGroups&&["AUDIO","SUBTITLES"].forEach(t=>{if(n.mediaGroups[t])for(const i in n.mediaGroups[t])for(const s in n.mediaGroups[t][i]){const r=n.mediaGroups[t][i][s];e(r,t,i,s)}})},Ob=({playlist:n,uri:e,id:t})=>{n.id=t,n.playlistErrors_=0,e&&(n.uri=e),n.attributes=n.attributes||{}},eD=n=>{let e=n.playlists.length;for(;e--;){const t=n.playlists[e];Ob({playlist:t,id:Ur(e,t.uri)}),t.resolvedUri=di(n.uri,t.uri),n.playlists[t.id]=t,n.playlists[t.uri]=t,t.attributes.BANDWIDTH||Ib.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}},tD=n=>{Br(n,e=>{e.uri&&(e.resolvedUri=di(n.uri,e.uri))})},iD=(n,e)=>{const t=Ur(0,e),i={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:B.location.href,resolvedUri:B.location.href,playlists:[{uri:e,id:t,resolvedUri:e,attributes:{}}]};return i.playlists[t]=i.playlists[0],i.playlists[e]=i.playlists[0],i},Mb=(n,e,t=Rb)=>{n.uri=e;for(let s=0;s<n.playlists.length;s++)if(!n.playlists[s].uri){const r=`placeholder-uri-${s}`;n.playlists[s].uri=r}const i=eo(n);Br(n,(s,r,a,o)=>{if(!s.playlists||!s.playlists.length){if(i&&r==="AUDIO"&&!s.uri)for(let c=0;c<n.playlists.length;c++){const l=n.playlists[c];if(l.attributes&&l.attributes.AUDIO&&l.attributes.AUDIO===a)return}s.playlists=[vt({},s)]}s.playlists.forEach(function(c,l){const u=t(r,a,o,c),h=Ur(l,u);c.uri?c.resolvedUri=c.resolvedUri||di(n.uri,c.uri):(c.uri=l===0?u:h,c.resolvedUri=c.uri),c.id=c.id||h,c.attributes=c.attributes||{},n.playlists[c.id]=c,n.playlists[c.uri]=c})}),eD(n),tD(n)};class Lb{constructor(){this.offset_=null,this.pendingDateRanges_=new Map,this.processedDateRanges_=new Map}setOffset(e=[]){if(this.offset_!==null||!e.length)return;const[t]=e;t.programDateTime!==void 0&&(this.offset_=t.programDateTime/1e3)}setPendingDateRanges(e=[]){if(!e.length)return;const[t]=e,i=t.startDate.getTime();this.trimProcessedDateRanges_(i),this.pendingDateRanges_=e.reduce((s,r)=>(s.set(r.id,r),s),new Map)}processDateRange(e){this.pendingDateRanges_.delete(e.id),this.processedDateRanges_.set(e.id,e)}getDateRangesToProcess(){if(this.offset_===null)return[];const e={},t=[];this.pendingDateRanges_.forEach((i,s)=>{if(!this.processedDateRanges_.has(s)&&(i.startTime=i.startDate.getTime()/1e3-this.offset_,i.processDateRange=()=>this.processDateRange(i),t.push(i),!!i.class))if(e[i.class]){const r=e[i.class].push(i);i.classListIndex=r-1}else e[i.class]=[i],i.classListIndex=0});for(const i of t){const s=e[i.class]||[];i.endDate?i.endTime=i.endDate.getTime()/1e3-this.offset_:i.endOnNext&&s[i.classListIndex+1]?i.endTime=s[i.classListIndex+1].startTime:i.duration?i.endTime=i.startTime+i.duration:i.plannedDuration?i.endTime=i.startTime+i.plannedDuration:i.endTime=i.startTime}return t}trimProcessedDateRanges_(e){new Map(this.processedDateRanges_).forEach((i,s)=>{i.startDate.getTime()<e&&this.processedDateRanges_.delete(s)})}}const Nb=22,Hs=({requestType:n,request:e,error:t,parseFailure:i})=>{const s=e.status<200||e.status>299,r=e.status>=400&&e.status<=499,a={uri:e.uri,requestType:n},o=s&&!r||i;if(t&&r)a.error=vt({},t),a.errorType=K.Error.NetworkRequestFailed;else if(e.aborted)a.errorType=K.Error.NetworkRequestAborted;else if(e.timedout)a.errorType=K.Error.NetworkRequestTimeout;else if(o){const c=i?K.Error.NetworkBodyParserFailed:K.Error.NetworkBadStatus;a.errorType=c,a.status=e.status,a.headers=e.headers}return a},nD=Oi("CodecUtils"),Fb=function(n){const e=n.attributes||{};if(e.CODECS)return on(e.CODECS)},Ub=(n,e)=>{const t=e.attributes||{};return n&&n.mediaGroups&&n.mediaGroups.AUDIO&&t.AUDIO&&n.mediaGroups.AUDIO[t.AUDIO]},sD=(n,e)=>{if(!Ub(n,e))return!0;const t=e.attributes||{},i=n.mediaGroups.AUDIO[t.AUDIO];for(const s in i)if(!i[s].uri&&!i[s].playlists)return!0;return!1},to=function(n){const e={};return n.forEach(({mediaType:t,type:i,details:s})=>{e[t]=e[t]||[],e[t].push(X0(`${i}${s}`))}),Object.keys(e).forEach(function(t){if(e[t].length>1){nD(`multiple ${t} codecs found as attributes: ${e[t].join(", ")}. Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.`),e[t]=null;return}e[t]=e[t][0]}),e},Bb=function(n){let e=0;return n.audio&&e++,n.video&&e++,e},io=function(n,e){const t=e.attributes||{},i=to(Fb(e)||[]);if(Ub(n,e)&&!i.audio&&!sD(n,e)){const s=to($1(n,t.AUDIO)||[]);s.audio&&(i.audio=s.audio)}return i},{EventTarget:rD}=K,aD=(n,e)=>{if(e.endList||!e.serverControl)return n;const t={};if(e.serverControl.canBlockReload){const{preloadSegment:i}=e;let s=e.mediaSequence+e.segments.length;if(i){const r=i.parts||[],a=Cb(e)-1;a>-1&&a!==r.length-1&&(t._HLS_part=a),(a>-1||r.length)&&s--}t._HLS_msn=s}if(e.serverControl&&e.serverControl.canSkipUntil&&(t._HLS_skip=e.serverControl.canSkipDateranges?"v2":"YES"),Object.keys(t).length){const i=new B.URL(n);["_HLS_skip","_HLS_msn","_HLS_part"].forEach(function(s){t.hasOwnProperty(s)&&i.searchParams.set(s,t[s])}),n=i.toString()}return n},oD=(n,e)=>{if(!n)return e;const t=We(n,e);if(n.preloadHints&&!e.preloadHints&&delete t.preloadHints,n.parts&&!e.parts)delete t.parts;else if(n.parts&&e.parts)for(let i=0;i<e.parts.length;i++)n.parts&&n.parts[i]&&(t.parts[i]=We(n.parts[i],e.parts[i]));return!n.skipped&&e.skipped&&(t.skipped=!1),n.preload&&!e.preload&&(t.preload=!1),t},cD=(n,e,t)=>{const i=n.slice(),s=e.slice();t=t||0;const r=[];let a;for(let o=0;o<s.length;o++){const c=i[o+t],l=s[o];c?(a=c.map||a,r.push(oD(c,l))):(a&&!l.map&&(l.map=a),r.push(l))}return r},qb=(n,e)=>{!n.resolvedUri&&n.uri&&(n.resolvedUri=di(e,n.uri)),n.key&&!n.key.resolvedUri&&(n.key.resolvedUri=di(e,n.key.uri)),n.map&&!n.map.resolvedUri&&(n.map.resolvedUri=di(e,n.map.uri)),n.map&&n.map.key&&!n.map.key.resolvedUri&&(n.map.key.resolvedUri=di(e,n.map.key.uri)),n.parts&&n.parts.length&&n.parts.forEach(t=>{t.resolvedUri||(t.resolvedUri=di(e,t.uri))}),n.preloadHints&&n.preloadHints.length&&n.preloadHints.forEach(t=>{t.resolvedUri||(t.resolvedUri=di(e,t.uri))})},Vb=function(n){const e=n.segments||[],t=n.preloadSegment;if(t&&t.parts&&t.parts.length){if(t.preloadHints){for(let i=0;i<t.preloadHints.length;i++)if(t.preloadHints[i].type==="MAP")return e}t.duration=n.targetDuration,t.preload=!0,e.push(t)}return e},jb=(n,e)=>n===e||n.segments&&e.segments&&n.segments.length===e.segments.length&&n.endList===e.endList&&n.mediaSequence===e.mediaSequence&&n.preloadSegment===e.preloadSegment,hf=(n,e,t=jb)=>{const i=We(n,{}),s=i.playlists[e.id];if(!s||t(s,e))return null;e.segments=Vb(e);const r=We(s,e);if(r.preloadSegment&&!e.preloadSegment&&delete r.preloadSegment,s.segments){if(e.skip){e.segments=e.segments||[];for(let a=0;a<e.skip.skippedSegments;a++)e.segments.unshift({skipped:!0})}r.segments=cD(s.segments,e.segments,e.mediaSequence-s.mediaSequence)}r.segments.forEach(a=>{qb(a,r.resolvedUri)});for(let a=0;a<i.playlists.length;a++)i.playlists[a].id===e.id&&(i.playlists[a]=r);return i.playlists[e.id]=r,i.playlists[e.uri]=r,Br(n,(a,o,c,l)=>{if(a.playlists)for(let u=0;u<a.playlists.length;u++)e.id===a.playlists[u].id&&(a.playlists[u]=r)}),i},ff=(n,e)=>{const t=n.segments||[],i=t[t.length-1],s=i&&i.parts&&i.parts[i.parts.length-1],r=s&&s.duration||i&&i.duration;return e&&r?r*1e3:(n.partTargetDuration||n.targetDuration||10)*500},Hb=(n,e,t)=>{if(!n)return;const i=[];return n.forEach(s=>{if(!s.attributes)return;const{BANDWIDTH:r,RESOLUTION:a,CODECS:o}=s.attributes;i.push({id:s.id,bandwidth:r,resolution:a,codecs:o})}),{type:e,isLive:t,renditions:i}};class qr extends rD{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=Oi("PlaylistLoader");const{withCredentials:s=!1}=i;this.src=e,this.vhs_=t,this.withCredentials=s,this.addDateRangesToTextTrack_=i.addDateRangesToTextTrack;const r=t.options_;this.customTagParsers=r&&r.customTagParsers||[],this.customTagMappers=r&&r.customTagMappers||[],this.llhls=r&&r.llhls,this.dateRangesStorage_=new Lb,this.state="HAVE_NOTHING",this.handleMediaupdatetimeout_=this.handleMediaupdatetimeout_.bind(this),this.on("mediaupdatetimeout",this.handleMediaupdatetimeout_),this.on("loadedplaylist",this.handleLoadedPlaylist_.bind(this))}handleLoadedPlaylist_(){const e=this.media();if(!e)return;this.dateRangesStorage_.setOffset(e.segments),this.dateRangesStorage_.setPendingDateRanges(e.dateRanges);const t=this.dateRangesStorage_.getDateRangesToProcess();!t.length||!this.addDateRangesToTextTrack_||this.addDateRangesToTextTrack_(t)}handleMediaupdatetimeout_(){if(this.state!=="HAVE_METADATA")return;const e=this.media();let t=di(this.main.uri,e.uri);this.llhls&&(t=aD(t,e)),this.state="HAVE_CURRENT_METADATA",this.request=this.vhs_.xhr({uri:t,withCredentials:this.withCredentials,requestType:"hls-playlist"},(i,s)=>{if(this.request){if(i)return this.playlistRequestError(this.request,this.media(),"HAVE_METADATA");this.haveMetadata({playlistString:this.request.responseText,url:this.media().uri,id:this.media().id})}})}playlistRequestError(e,t,i){const{uri:s,id:r}=t;this.request=null,i&&(this.state=i),this.error={playlist:this.main.playlists[r],status:e.status,message:`HLS playlist request error at URL: ${s}.`,responseText:e.responseText,code:e.status>=500?4:2,metadata:Hs({requestType:e.requestType,request:e,error:e.error})},this.trigger("error")}parseManifest_({url:e,manifestString:t}){try{const i=ZA({onwarn:({message:s})=>this.logger_(`m3u8-parser warn for ${e}: ${s}`),oninfo:({message:s})=>this.logger_(`m3u8-parser info for ${e}: ${s}`),manifestString:t,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers,llhls:this.llhls});return!i.playlists||!i.playlists.length||this.excludeAudioOnlyVariants(i.playlists),i}catch(i){this.error=i,this.error.metadata={errorType:K.Error.StreamingHlsPlaylistParserError,error:i}}}excludeAudioOnlyVariants(e){const t=i=>{const s=i.attributes||{},{width:r,height:a}=s.RESOLUTION||{};if(r&&a)return!0;const o=Fb(i)||[];return!!to(o).video};e.some(t)&&e.forEach(i=>{t(i)||(i.excludeUntil=1/0)})}haveMetadata({playlistString:e,playlistObject:t,url:i,id:s}){this.request=null,this.state="HAVE_METADATA";const r={playlistInfo:{type:"media",uri:i}};this.trigger({type:"playlistparsestart",metadata:r});const a=t||this.parseManifest_({url:i,manifestString:e});a.lastRequest=Date.now(),Ob({playlist:a,uri:i,id:s});const o=hf(this.main,a);this.targetDuration=a.partTargetDuration||a.targetDuration,this.pendingMedia_=null,o?(this.main=o,this.media_=this.main.playlists[s]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(ff(this.media(),!!o)),r.parsedPlaylist=Hb(this.main.playlists,r.playlistInfo.type,!this.media_.endList),this.trigger({type:"playlistparsecomplete",metadata:r}),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),B.clearTimeout(this.mediaUpdateTimeout),B.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new Lb,this.off()}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e,t){if(!e)return this.media_;if(this.state==="HAVE_NOTHING")throw new Error("Cannot switch media playlist from "+this.state);if(typeof e=="string"){if(!this.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.main.playlists[e]}if(B.clearTimeout(this.finalRenditionTimeout),t){const o=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;this.finalRenditionTimeout=B.setTimeout(this.media.bind(this,e,!1),o);return}const i=this.state,s=!this.media_||e.id!==this.media_.id,r=this.main.playlists[e.id];if(r&&r.endList||e.endList&&e.segments.length){this.request&&(this.request.onreadystatechange=null,this.request.abort(),this.request=null),this.state="HAVE_METADATA",this.media_=e,s&&(this.trigger("mediachanging"),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange"));return}if(this.updateMediaUpdateTimeout_(ff(e,!0)),!s)return;if(this.state="SWITCHING_MEDIA",this.request){if(e.resolvedUri===this.request.url)return;this.request.onreadystatechange=null,this.request.abort(),this.request=null}this.media_&&this.trigger("mediachanging"),this.pendingMedia_=e;const a={playlistInfo:{type:"media",uri:e.uri}};this.trigger({type:"playlistrequeststart",metadata:a}),this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials,requestType:"hls-playlist"},(o,c)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=vl(e.resolvedUri,c),o)return this.playlistRequestError(this.request,e,i);this.trigger({type:"playlistrequestcomplete",metadata:a}),this.haveMetadata({playlistString:c.responseText,url:e.uri,id:e.id}),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}})}pause(){this.mediaUpdateTimeout&&(B.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.stopRequest(),this.state==="HAVE_NOTHING"&&(this.started=!1),this.state==="SWITCHING_MEDIA"?this.media_?this.state="HAVE_METADATA":this.state="HAVE_MAIN_MANIFEST":this.state==="HAVE_CURRENT_METADATA"&&(this.state="HAVE_METADATA")}load(e){this.mediaUpdateTimeout&&(B.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const t=this.media();if(e){const i=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=B.setTimeout(()=>{this.mediaUpdateTimeout=null,this.load()},i);return}if(!this.started){this.start();return}t&&!t.endList?this.trigger("mediaupdatetimeout"):this.trigger("loadedplaylist")}updateMediaUpdateTimeout_(e){this.mediaUpdateTimeout&&(B.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),!(!this.media()||this.media().endList)&&(this.mediaUpdateTimeout=B.setTimeout(()=>{this.mediaUpdateTimeout=null,this.trigger("mediaupdatetimeout"),this.updateMediaUpdateTimeout_(e)},e))}start(){if(this.started=!0,typeof this.src=="object"){this.src.uri||(this.src.uri=B.location.href),this.src.resolvedUri=this.src.uri,setTimeout(()=>{this.setupInitialPlaylist(this.src)},0);return}const e={playlistInfo:{type:"multivariant",uri:this.src}};this.trigger({type:"playlistrequeststart",metadata:e}),this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials,requestType:"hls-playlist"},(t,i)=>{if(!this.request)return;if(this.request=null,t)return this.error={status:i.status,message:`HLS playlist request error at URL: ${this.src}.`,responseText:i.responseText,code:2,metadata:Hs({requestType:i.requestType,request:i,error:t})},this.state==="HAVE_NOTHING"&&(this.started=!1),this.trigger("error");this.trigger({type:"playlistrequestcomplete",metadata:e}),this.src=vl(this.src,i),this.trigger({type:"playlistparsestart",metadata:e});const s=this.parseManifest_({manifestString:i.responseText,url:this.src});e.parsedPlaylist=Hb(s.playlists,e.playlistInfo.type,!1),this.trigger({type:"playlistparsecomplete",metadata:e}),this.setupInitialPlaylist(s)})}srcUri(){return typeof this.src=="string"?this.src:this.src.uri}setupInitialPlaylist(e){if(this.state="HAVE_MAIN_MANIFEST",e.playlists){this.main=e,Mb(this.main,this.srcUri()),e.playlists.forEach(i=>{i.segments=Vb(i),i.segments.forEach(s=>{qb(s,i.resolvedUri)})}),this.trigger("loadedplaylist"),this.request||this.media(this.main.playlists[0]);return}const t=this.srcUri()||B.location.href;this.main=iD(e,t),this.haveMetadata({playlistObject:e,url:t,id:this.main.playlists[0].id}),this.trigger("loadedmetadata")}updateOrDeleteClone(e,t){const i=this.main,s=e.ID;let r=i.playlists.length;for(;r--;){const a=i.playlists[r];if(a.attributes["PATHWAY-ID"]===s){const o=a.resolvedUri,c=a.id;if(t){const l=this.createCloneURI_(a.resolvedUri,e),u=Ur(s,l),h=this.createCloneAttributes_(s,a.attributes),p=this.createClonePlaylist_(a,u,e,h);i.playlists[r]=p,i.playlists[u]=p,i.playlists[l]=p}else i.playlists.splice(r,1);delete i.playlists[c],delete i.playlists[o]}}this.updateOrDeleteCloneMedia(e,t)}updateOrDeleteCloneMedia(e,t){const i=this.main,s=e.ID;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(r=>{if(!(!i.mediaGroups[r]||!i.mediaGroups[r][s])){for(const a in i.mediaGroups[r])if(a===s){for(const o in i.mediaGroups[r][a])i.mediaGroups[r][a][o].playlists.forEach((l,u)=>{const h=i.playlists[l.id],p=h.id,y=h.resolvedUri;delete i.playlists[p],delete i.playlists[y]});delete i.mediaGroups[r][a]}}}),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){const i=this.main,s=i.playlists.length,r=this.createCloneURI_(t.resolvedUri,e),a=Ur(e.ID,r),o=this.createCloneAttributes_(e.ID,t.attributes),c=this.createClonePlaylist_(t,a,e,o);i.playlists[s]=c,i.playlists[a]=c,i.playlists[r]=c,this.createClonedMediaGroups_(e)}createClonedMediaGroups_(e){const t=e.ID,i=e["BASE-ID"],s=this.main;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(r=>{if(!(!s.mediaGroups[r]||s.mediaGroups[r][t]))for(const a in s.mediaGroups[r]){if(a===i)s.mediaGroups[r][t]={};else continue;for(const o in s.mediaGroups[r][a]){const c=s.mediaGroups[r][a][o];s.mediaGroups[r][t][o]=vt({},c);const l=s.mediaGroups[r][t][o],u=this.createCloneURI_(c.resolvedUri,e);l.resolvedUri=u,l.uri=u,l.playlists=[],c.playlists.forEach((h,p)=>{const y=s.playlists[h.id],_=Rb(r,t,o),b=Ur(t,_);if(y&&!s.playlists[b]){const S=this.createClonePlaylist_(y,b,e),D=S.resolvedUri;s.playlists[b]=S,s.playlists[D]=S}l.playlists[p]=this.createClonePlaylist_(h,b,e)})}}})}createClonePlaylist_(e,t,i,s){const r=this.createCloneURI_(e.resolvedUri,i),a={resolvedUri:r,uri:r,id:t};return e.segments&&(a.segments=[]),s&&(a.attributes=s),We(e,a)}createCloneURI_(e,t){const i=new URL(e);i.hostname=t["URI-REPLACEMENT"].HOST;const s=t["URI-REPLACEMENT"].PARAMS;for(const r of Object.keys(s))i.searchParams.set(r,s[r]);return i.href}createCloneAttributes_(e,t){const i={"PATHWAY-ID":e};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(s=>{t[s]&&(i[s]=e)}),i}getKeyIdSet(e){const t=new Set;if(!e||!e.contentProtection)return t;for(const i in e.contentProtection)if(e.contentProtection[i]&&e.contentProtection[i].attributes&&e.contentProtection[i].attributes.keyId){const s=e.contentProtection[i].attributes.keyId;t.add(s.toLowerCase())}return t}}const pf=function(n,e,t,i){const s=n.responseType==="arraybuffer"?n.response:n.responseText;!e&&s&&(n.responseTime=Date.now(),n.roundTripTime=n.responseTime-n.requestTime,n.bytesReceived=s.byteLength||s.length,n.bandwidth||(n.bandwidth=Math.floor(n.bytesReceived/n.roundTripTime*8*1e3))),t.headers&&(n.responseHeaders=t.headers),e&&e.code==="ETIMEDOUT"&&(n.timedout=!0),!e&&!n.aborted&&t.statusCode!==200&&t.statusCode!==206&&t.statusCode!==0&&(e=new Error("XHR Failed with a response of: "+(n&&(s||n.responseText)))),i(e,n)},lD=(n,e)=>{if(!n||!n.size)return;let t=e;return n.forEach(i=>{t=i(t)}),t},uD=(n,e,t,i)=>{!n||!n.size||n.forEach(s=>{s(e,t,i)})},$b=function(){const n=function e(t,i){t=We({timeout:45e3},t);const s=e.beforeRequest||K.Vhs.xhr.beforeRequest,r=e._requestCallbackSet||K.Vhs.xhr._requestCallbackSet||new Set,a=e._responseCallbackSet||K.Vhs.xhr._responseCallbackSet;s&&typeof s=="function"&&(K.log.warn("beforeRequest is deprecated, use onRequest instead."),r.add(s));const o=K.Vhs.xhr.original===!0?K.xhr:K.Vhs.xhr,c=lD(r,t);r.delete(s);const l=o(c||t,function(h,p){return uD(a,l,h,p),pf(l,h,p,i)}),u=l.abort;return l.abort=function(){return l.aborted=!0,u.apply(l,arguments)},l.uri=t.uri,l.requestType=t.requestType,l.requestTime=Date.now(),l};return n.original=!0,n},dD=function(n){let e;const t=n.offset;return typeof n.offset=="bigint"||typeof n.length=="bigint"?e=B.BigInt(n.offset)+B.BigInt(n.length)-B.BigInt(1):e=n.offset+n.length-1,"bytes="+t+"-"+e},mf=function(n){const e={};return n.byterange&&(e.Range=dD(n.byterange)),e},hD=function(n,e){return n.start(e)+"-"+n.end(e)},fD=function(n,e){const t=n.toString(16);return"00".substring(0,2-t.length)+t+(e%2?" ":"")},pD=function(n){return n>=32&&n<126?String.fromCharCode(n):"."},Wb=function(n){const e={};return Object.keys(n).forEach(t=>{const i=n[t];Z0(i)?e[t]={bytes:i.buffer,byteOffset:i.byteOffset,byteLength:i.byteLength}:e[t]=i}),e},_l=function(n){const e=n.byterange||{length:1/0,offset:0};return[e.length,e.offset,n.resolvedUri].join(",")},zb=function(n){return n.resolvedUri},Gb=n=>{const e=Array.prototype.slice.call(n),t=16;let i="",s,r;for(let a=0;a<e.length/t;a++)s=e.slice(a*t,a*t+t).map(fD).join(""),r=e.slice(a*t,a*t+t).map(pD).join(""),i+=s+" "+r+`
|
|
247
|
+
`;return i};var mD=Object.freeze({__proto__:null,createTransferableMessage:Wb,initSegmentId:_l,segmentKeyId:zb,hexDump:Gb,tagDump:({bytes:n})=>Gb(n),textRanges:n=>{let e="",t;for(t=0;t<n.length;t++)e+=hD(n,t)+" ";return e}});const Kb=.25,gD=(n,e)=>{if(!e.dateTimeObject)return null;const t=e.videoTimingInfo.transmuxerPrependedSeconds,s=e.videoTimingInfo.transmuxedPresentationStart+t,r=n-s;return new Date(e.dateTimeObject.getTime()+r*1e3)},yD=n=>n.transmuxedPresentationEnd-n.transmuxedPresentationStart-n.transmuxerPrependedSeconds,vD=(n,e)=>{let t;try{t=new Date(n)}catch{return null}if(!e||!e.segments||e.segments.length===0)return null;let i=e.segments[0];if(t<new Date(i.dateTimeObject))return null;for(let c=0;c<e.segments.length-1;c++){i=e.segments[c];const l=new Date(e.segments[c+1].dateTimeObject);if(t<l)break}const s=e.segments[e.segments.length-1],r=s.dateTimeObject,a=s.videoTimingInfo?yD(s.videoTimingInfo):s.duration+s.duration*Kb,o=new Date(r.getTime()+a*1e3);return t>o?null:(t>new Date(r)&&(i=s),{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:hi.duration(e,e.mediaSequence+e.segments.indexOf(i)),type:i.videoTimingInfo?"accurate":"estimate"})},bD=(n,e)=>{if(!e||!e.segments||e.segments.length===0)return null;let t=0,i;for(let r=0;r<e.segments.length&&(i=e.segments[r],t=i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationEnd:t+i.duration,!(n<=t));r++);const s=e.segments[e.segments.length-1];if(s.videoTimingInfo&&s.videoTimingInfo.transmuxedPresentationEnd<n)return null;if(n>t){if(n>t+s.duration*Kb)return null;i=s}return{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:t-i.duration,type:i.videoTimingInfo?"accurate":"estimate"}},TD=(n,e)=>{let t,i;try{t=new Date(n),i=new Date(e)}catch{}const s=t.getTime();return(i.getTime()-s)/1e3},_D=n=>{if(!n.segments||n.segments.length===0)return!1;for(let e=0;e<n.segments.length;e++)if(!n.segments[e].dateTimeObject)return!1;return!0},SD=({playlist:n,time:e=void 0,callback:t})=>{if(!t)throw new Error("getProgramTime: callback must be provided");if(!n||e===void 0)return t({message:"getProgramTime: playlist and time must be provided"});const i=bD(e,n);if(!i)return t({message:"valid programTime was not found"});if(i.type==="estimate")return t({message:"Accurate programTime could not be determined. Please seek to e.seekTime and try again",seekTime:i.estimatedStart});const s={mediaSeconds:e},r=gD(e,i.segment);return r&&(s.programDateTime=r.toISOString()),t(null,s)},Xb=({programTime:n,playlist:e,retryCount:t=2,seekTo:i,pauseAfterSeek:s=!0,tech:r,callback:a})=>{if(!a)throw new Error("seekToProgramTime: callback must be provided");if(typeof n>"u"||!e||!i)return a({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!e.endList&&!r.hasStarted_)return a({message:"player must be playing a live stream to start buffering"});if(!_D(e))return a({message:"programDateTime tags must be provided in the manifest "+e.resolvedUri});const o=vD(n,e);if(!o)return a({message:`${n} was not found in the stream`});const c=o.segment,l=TD(c.dateTimeObject,n);if(o.type==="estimate"){if(t===0)return a({message:`${n} is not buffered yet. Try again`});i(o.estimatedStart+l),r.one("seeked",()=>{Xb({programTime:n,playlist:e,retryCount:t-1,seekTo:i,pauseAfterSeek:s,tech:r,callback:a})});return}const u=c.start+l,h=()=>a(null,r.currentTime());r.one("seeked",h),s&&r.pause(),i(u)},gf=(n,e)=>{if(n.readyState===4)return e()},CD=(n,e,t,i)=>{let s=[],r,a=!1;const o=function(h,p,y,_){return p.abort(),a=!0,t(h,p,y,_)},c=function(h,p){if(a)return;if(h)return h.metadata=Hs({requestType:i,request:p,error:h}),o(h,p,"",s);const y=p.responseText.substring(s&&s.byteLength||0,p.responseText.length);if(s=ex(s,ey(y,!0)),r=r||Ba(s),s.length<10||r&&s.length<r+2)return gf(p,()=>o(h,p,"",s));const _=oh(s);return _==="ts"&&s.length<188?gf(p,()=>o(h,p,"",s)):!_&&s.length<376?gf(p,()=>o(h,p,"",s)):o(null,p,_,s)},u=e({uri:n,beforeSend(h){h.overrideMimeType("text/plain; charset=x-user-defined"),h.addEventListener("progress",function({total:p,loaded:y}){return pf(h,null,{statusCode:h.status},c)})}},function(h,p){return pf(u,h,p,c)});return u},{EventTarget:kD}=K,Yb=function(n,e){if(!jb(n,e)||n.sidx&&e.sidx&&(n.sidx.offset!==e.sidx.offset||n.sidx.length!==e.sidx.length))return!1;if(!n.sidx&&e.sidx||n.sidx&&!e.sidx||n.segments&&!e.segments||!n.segments&&e.segments)return!1;if(!n.segments&&!e.segments)return!0;for(let t=0;t<n.segments.length;t++){const i=n.segments[t],s=e.segments[t];if(i.uri!==s.uri)return!1;if(!i.byterange&&!s.byterange)continue;const r=i.byterange,a=s.byterange;if(r&&!a||!r&&a||r.offset!==a.offset||r.length!==a.length)return!1}return!0},ED=(n,e,t,i)=>{const s=i.attributes.NAME||t;return`placeholder-uri-${n}-${e}-${s}`},xD=({mainXml:n,srcUrl:e,clientOffset:t,sidxMapping:i,previousManifest:s})=>{const r=Zx(n,{manifestUri:e,clientOffset:t,sidxMapping:i,previousManifest:s});return Mb(r,e,ED),r},wD=(n,e)=>{Br(n,(t,i,s,r)=>{(!e.mediaGroups[i][s]||!(r in e.mediaGroups[i][s]))&&delete n.mediaGroups[i][s][r]})},AD=(n,e,t)=>{let i=!0,s=We(n,{duration:e.duration,minimumUpdatePeriod:e.minimumUpdatePeriod,timelineStarts:e.timelineStarts});for(let r=0;r<e.playlists.length;r++){const a=e.playlists[r];if(a.sidx){const c=Oc(a.sidx);t&&t[c]&&t[c].sidx&&Zd(a,t[c].sidx,a.sidx.resolvedUri)}const o=hf(s,a,Yb);o&&(s=o,i=!1)}return Br(e,(r,a,o,c)=>{if(r.playlists&&r.playlists.length){const l=r.playlists[0].id,u=hf(s,r.playlists[0],Yb);u&&(s=u,c in s.mediaGroups[a][o]||(s.mediaGroups[a][o][c]=r),s.mediaGroups[a][o][c].playlists[0]=s.playlists[l],i=!1)}}),wD(s,e),e.minimumUpdatePeriod!==n.minimumUpdatePeriod&&(i=!1),i?null:s},DD=(n,e)=>(!n.map&&!e.map||!!(n.map&&e.map&&n.map.byterange.offset===e.map.byterange.offset&&n.map.byterange.length===e.map.byterange.length))&&n.uri===e.uri&&n.byterange.offset===e.byterange.offset&&n.byterange.length===e.byterange.length,Qb=(n,e)=>{const t={};for(const i in n){const r=n[i].sidx;if(r){const a=Oc(r);if(!e[a])break;const o=e[a].sidxInfo;DD(o,r)&&(t[a]=e[a])}}return t},PD=(n,e)=>{let i=Qb(n.playlists,e);return Br(n,(s,r,a,o)=>{if(s.playlists&&s.playlists.length){const c=s.playlists;i=We(i,Qb(c,e))}}),i};class yf extends kD{constructor(e,t,i={},s){super(),this.isPaused_=!0,this.mainPlaylistLoader_=s||this,s||(this.isMain_=!0);const{withCredentials:r=!1}=i;if(this.vhs_=t,this.withCredentials=r,this.addMetadataToTextTrack=i.addMetadataToTextTrack,!e)throw new Error("A non-empty playlist URL or object is required");this.on("minimumUpdatePeriod",()=>{this.refreshXml_()}),this.on("mediaupdatetimeout",()=>{this.refreshMedia_(this.media().id)}),this.state="HAVE_NOTHING",this.loadedPlaylists_={},this.logger_=Oi("DashPlaylistLoader"),this.isMain_?(this.mainPlaylistLoader_.srcUrl=e,this.mainPlaylistLoader_.sidxMapping_={}):this.childPlaylist_=e}get isPaused(){return this.isPaused_}requestErrored_(e,t,i){if(!this.request)return!0;if(this.request=null,e)return this.error=typeof e=="object"&&!(e instanceof Error)?e:{status:t.status,message:"DASH request error at URL: "+t.uri,response:t.response,code:2,metadata:e.metadata},i&&(this.state=i),this.trigger("error"),!0}addSidxSegments_(e,t,i){const s=e.sidx&&Oc(e.sidx);if(!e.sidx||!s||this.mainPlaylistLoader_.sidxMapping_[s]){B.clearTimeout(this.mediaRequest_),this.mediaRequest_=B.setTimeout(()=>i(!1),0);return}const r=vl(e.sidx.resolvedUri),a=(c,l)=>{if(this.requestErrored_(c,l,t))return;const u=this.mainPlaylistLoader_.sidxMapping_,{requestType:h}=l;let p;try{p=sw(Ce(l.response).subarray(8))}catch(y){y.metadata=Hs({requestType:h,request:l,parseFailure:!0}),this.requestErrored_(y,l,t);return}return u[s]={sidxInfo:e.sidx,sidx:p},Zd(e,p,e.sidx.resolvedUri),i(!0)},o="dash-sidx";this.request=CD(r,this.vhs_.xhr,(c,l,u,h)=>{if(c)return a(c,l);if(!u||u!=="mp4"){const _=u||"unknown";return a({status:l.status,message:`Unsupported ${_} container type for sidx segment at URL: ${r}`,response:"",playlist:e,internal:!0,playlistExclusionDuration:1/0,code:2},l)}const{offset:p,length:y}=e.sidx.byterange;if(h.length>=y+p)return a(c,{response:h.subarray(p,p+y),status:l.status,uri:l.uri});this.request=this.vhs_.xhr({uri:r,responseType:"arraybuffer",requestType:"dash-sidx",headers:mf({byterange:e.sidx.byterange})},a)},o)}dispose(){this.isPaused_=!0,this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},B.clearTimeout(this.minimumUpdatePeriodTimeout_),B.clearTimeout(this.mediaRequest_),B.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.mediaRequest_=null,this.minimumUpdatePeriodTimeout_=null,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.off()}hasPendingRequest(){return this.request||this.mediaRequest_}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e){if(!e)return this.media_;if(this.state==="HAVE_NOTHING")throw new Error("Cannot switch media playlist from "+this.state);const t=this.state;if(typeof e=="string"){if(!this.mainPlaylistLoader_.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.mainPlaylistLoader_.main.playlists[e]}const i=!this.media_||e.id!==this.media_.id;if(i&&this.loadedPlaylists_[e.id]&&this.loadedPlaylists_[e.id].endList){this.state="HAVE_METADATA",this.media_=e,i&&(this.trigger("mediachanging"),this.trigger("mediachange"));return}i&&(this.media_&&this.trigger("mediachanging"),this.addSidxSegments_(e,t,s=>{this.haveMetadata({startingState:t,playlist:e})}))}haveMetadata({startingState:e,playlist:t}){this.state="HAVE_METADATA",this.loadedPlaylists_[t.id]=t,B.clearTimeout(this.mediaRequest_),this.mediaRequest_=null,this.refreshMedia_(t.id),e==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}pause(){this.isPaused_=!0,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.stopRequest(),B.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(B.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),this.state==="HAVE_NOTHING"&&(this.started=!1)}load(e){this.isPaused_=!1,B.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const t=this.media();if(e){const i=t?t.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=B.setTimeout(()=>this.load(),i);return}if(!this.started){this.start();return}t&&!t.endList?(this.isMain_&&!this.minimumUpdatePeriodTimeout_&&(this.trigger("minimumUpdatePeriod"),this.updateMinimumUpdatePeriodTimeout_()),this.trigger("mediaupdatetimeout")):this.trigger("loadedplaylist")}start(){if(this.started=!0,!this.isMain_){B.clearTimeout(this.mediaRequest_),this.mediaRequest_=B.setTimeout(()=>this.haveMain_(),0);return}this.requestMain_((e,t)=>{this.haveMain_(),!this.hasPendingRequest()&&!this.media_&&this.media(this.mainPlaylistLoader_.main.playlists[0])})}requestMain_(e){const t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestrequeststart",metadata:t}),this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials,requestType:"dash-manifest"},(i,s)=>{if(i){const{requestType:a}=s;i.metadata=Hs({requestType:a,request:s,error:i})}if(this.requestErrored_(i,s)){this.state==="HAVE_NOTHING"&&(this.started=!1);return}this.trigger({type:"manifestrequestcomplete",metadata:t});const r=s.responseText!==this.mainPlaylistLoader_.mainXml_;if(this.mainPlaylistLoader_.mainXml_=s.responseText,s.responseHeaders&&s.responseHeaders.date?this.mainLoaded_=Date.parse(s.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=vl(this.mainPlaylistLoader_.srcUrl,s),r){this.handleMain_(),this.syncClientServerClock_(()=>e(s,r));return}return e(s,r)})}syncClientServerClock_(e){const t=ew(this.mainPlaylistLoader_.mainXml_);if(t===null)return this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e();if(t.method==="DIRECT")return this.mainPlaylistLoader_.clientOffset_=t.value-Date.now(),e();this.request=this.vhs_.xhr({uri:di(this.mainPlaylistLoader_.srcUrl,t.value),method:t.method,withCredentials:this.withCredentials,requestType:"dash-clock-sync"},(i,s)=>{if(!this.request)return;if(i){const{requestType:a}=s;return this.error.metadata=Hs({requestType:a,request:s,error:i}),this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e()}let r;t.method==="HEAD"?!s.responseHeaders||!s.responseHeaders.date?r=this.mainLoaded_:r=Date.parse(s.responseHeaders.date):r=Date.parse(s.responseText),this.mainPlaylistLoader_.clientOffset_=r-Date.now(),e()})}haveMain_(){this.state="HAVE_MAIN_MANIFEST",this.isMain_?this.trigger("loadedplaylist"):this.media_||this.media(this.childPlaylist_)}handleMain_(){B.clearTimeout(this.mediaRequest_),this.mediaRequest_=null;const e=this.mainPlaylistLoader_.main,t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestparsestart",metadata:t});let i;try{i=xD({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:e})}catch(r){this.error=r,this.error.metadata={errorType:K.Error.StreamingDashManifestParserError,error:r},this.trigger("error")}e&&(i=AD(e,i,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=i||e;const s=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];if(s&&s!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=s),(!e||i&&i.minimumUpdatePeriod!==e.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),this.addEventStreamToMetadataTrack_(i),i){const{duration:r,endList:a}=i,o=[];i.playlists.forEach(l=>{o.push({id:l.id,bandwidth:l.attributes.BANDWIDTH,resolution:l.attributes.RESOLUTION,codecs:l.attributes.CODECS})});const c={duration:r,isLive:!a,renditions:o};t.parsedManifest=c,this.trigger({type:"manifestparsecomplete",metadata:t})}return!!i}updateMinimumUpdatePeriodTimeout_(){const e=this.mainPlaylistLoader_;e.createMupOnMedia_&&(e.off("loadedmetadata",e.createMupOnMedia_),e.createMupOnMedia_=null),e.minimumUpdatePeriodTimeout_&&(B.clearTimeout(e.minimumUpdatePeriodTimeout_),e.minimumUpdatePeriodTimeout_=null);let t=e.main&&e.main.minimumUpdatePeriod;if(t===0&&(e.media()?t=e.media().targetDuration*1e3:(e.createMupOnMedia_=e.updateMinimumUpdatePeriodTimeout_,e.one("loadedmetadata",e.createMupOnMedia_))),typeof t!="number"||t<=0){t<0&&this.logger_(`found invalid minimumUpdatePeriod of ${t}, not setting a timeout`);return}this.createMUPTimeout_(t)}createMUPTimeout_(e){const t=this.mainPlaylistLoader_;t.minimumUpdatePeriodTimeout_=B.setTimeout(()=>{t.minimumUpdatePeriodTimeout_=null,t.trigger("minimumUpdatePeriod"),t.createMUPTimeout_(e)},e)}refreshXml_(){this.requestMain_((e,t)=>{t&&(this.media_&&(this.media_=this.mainPlaylistLoader_.main.playlists[this.media_.id]),this.mainPlaylistLoader_.sidxMapping_=PD(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.sidxMapping_),this.addSidxSegments_(this.media(),this.state,i=>{this.refreshMedia_(this.media().id)}))})}refreshMedia_(e){if(!e)throw new Error("refreshMedia_ must take a media id");this.media_&&this.isMain_&&this.handleMain_();const t=this.mainPlaylistLoader_.main.playlists,i=!this.media_||this.media_!==t[e];if(i?this.media_=t[e]:this.trigger("playlistunchanged"),!this.mediaUpdateTimeout){const s=()=>{this.media().endList||(this.mediaUpdateTimeout=B.setTimeout(()=>{this.trigger("mediaupdatetimeout"),s()},ff(this.media(),!!i)))};s()}this.trigger("loadedplaylist")}addEventStreamToMetadataTrack_(e){if(e&&this.mainPlaylistLoader_.main.eventStream){const t=this.mainPlaylistLoader_.main.eventStream.map(i=>({cueTime:i.start,frames:[{data:i.messageData}]}));this.addMetadataToTextTrack("EventStream",t,this.mainPlaylistLoader_.main.duration)}}getKeyIdSet(e){if(e.contentProtection){const t=new Set;for(const i in e.contentProtection){const s=e.contentProtection[i].attributes["cenc:default_KID"];s&&t.add(s.replace(/-/g,"").toLowerCase())}return t}}}var Mt={GOAL_BUFFER_LENGTH:30,MAX_GOAL_BUFFER_LENGTH:60,BACK_BUFFER_LENGTH:30,GOAL_BUFFER_LENGTH_RATE:1,INITIAL_BANDWIDTH:4194304,BANDWIDTH_VARIANCE:1.2,BUFFER_LOW_WATER_LINE:0,MAX_BUFFER_LOW_WATER_LINE:30,EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:16,BUFFER_LOW_WATER_LINE_RATE:1,BUFFER_HIGH_WATER_LINE:30};const ID=n=>{const e=new Uint8Array(new ArrayBuffer(n.length));for(let t=0;t<n.length;t++)e[t]=n.charCodeAt(t);return e.buffer},Jb=function(n){return n.on=n.addEventListener,n.off=n.removeEventListener,n},RD=function(n){try{return URL.createObjectURL(new Blob([n],{type:"application/javascript"}))}catch{const t=new BlobBuilder;return t.append(n),URL.createObjectURL(t.getBlob())}},Zb=function(n){return function(){const e=RD(n),t=Jb(new Worker(e));t.objURL=e;const i=t.terminate;return t.on=t.addEventListener,t.off=t.removeEventListener,t.terminate=function(){return URL.revokeObjectURL(e),i.call(this)},t}},eT=function(n){return`var browserWorkerPolyFill = ${Jb.toString()};
|
|
248
|
+
browserWorkerPolyFill(self);
|
|
249
|
+
`+n},tT=function(n){return n.toString().replace(/^function.+?{/,"").slice(0,-1)},OD=eT(tT(function(){var n=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=function(){this.init=function(){var d={};this.on=function(f,g){d[f]||(d[f]=[]),d[f]=d[f].concat(g)},this.off=function(f,g){var m;return d[f]?(m=d[f].indexOf(g),d[f]=d[f].slice(),d[f].splice(m,1),m>-1):!1},this.trigger=function(f){var g,m,v,T;if(g=d[f],!!g)if(arguments.length===2)for(v=g.length,m=0;m<v;++m)g[m].call(this,arguments[1]);else{for(T=[],m=arguments.length,m=1;m<arguments.length;++m)T.push(arguments[m]);for(v=g.length,m=0;m<v;++m)g[m].apply(this,T)}},this.dispose=function(){d={}}}};e.prototype.pipe=function(d){return this.on("data",function(f){d.push(f)}),this.on("done",function(f){d.flush(f)}),this.on("partialdone",function(f){d.partialFlush(f)}),this.on("endedtimeline",function(f){d.endTimeline(f)}),this.on("reset",function(f){d.reset(f)}),d},e.prototype.push=function(d){this.trigger("data",d)},e.prototype.flush=function(d){this.trigger("done",d)},e.prototype.partialFlush=function(d){this.trigger("partialdone",d)},e.prototype.endTimeline=function(d){this.trigger("endedtimeline",d)},e.prototype.reset=function(d){this.trigger("reset",d)};var t=e,i=Math.pow(2,32),s=function(d){var f=new DataView(d.buffer,d.byteOffset,d.byteLength),g;return f.getBigUint64?(g=f.getBigUint64(0),g<Number.MAX_SAFE_INTEGER?Number(g):g):f.getUint32(0)*i+f.getUint32(4)},r={getUint64:s,MAX_UINT32:i},a=r.MAX_UINT32,o,c,l,u,h,p,y,_,b,S,D,I,F,w,P,L,C,N,x,k,j,G,X,z,W,te,Q,re,Y,ie,ge,Te,be,we,Pe,ve;(function(){var d;if(X={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],mvex:[],mvhd:[],pasp:[],sdtp:[],smhd:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],styp:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[]},!(typeof Uint8Array>"u")){for(d in X)X.hasOwnProperty(d)&&(X[d]=[d.charCodeAt(0),d.charCodeAt(1),d.charCodeAt(2),d.charCodeAt(3)]);z=new Uint8Array([105,115,111,109]),te=new Uint8Array([97,118,99,49]),W=new Uint8Array([0,0,0,1]),Q=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),re=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]),Y={video:Q,audio:re},Te=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),ge=new Uint8Array([0,0,0,0,0,0,0,0]),be=new Uint8Array([0,0,0,0,0,0,0,0]),we=be,Pe=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),ve=be,ie=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}})(),o=function(d){var f=[],g=0,m,v,T;for(m=1;m<arguments.length;m++)f.push(arguments[m]);for(m=f.length;m--;)g+=f[m].byteLength;for(v=new Uint8Array(g+8),T=new DataView(v.buffer,v.byteOffset,v.byteLength),T.setUint32(0,v.byteLength),v.set(d,4),m=0,g=8;m<f.length;m++)v.set(f[m],g),g+=f[m].byteLength;return v},c=function(){return o(X.dinf,o(X.dref,Te))},l=function(d){return o(X.esds,new Uint8Array([0,0,0,0,3,25,0,0,0,4,17,64,21,0,6,0,0,0,218,192,0,0,218,192,5,2,d.audioobjecttype<<3|d.samplingfrequencyindex>>>1,d.samplingfrequencyindex<<7|d.channelcount<<3,6,1,2]))},u=function(){return o(X.ftyp,z,W,z,te)},L=function(d){return o(X.hdlr,Y[d])},h=function(d){return o(X.mdat,d)},P=function(d){var f=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,d.duration>>>24&255,d.duration>>>16&255,d.duration>>>8&255,d.duration&255,85,196,0,0]);return d.samplerate&&(f[12]=d.samplerate>>>24&255,f[13]=d.samplerate>>>16&255,f[14]=d.samplerate>>>8&255,f[15]=d.samplerate&255),o(X.mdhd,f)},w=function(d){return o(X.mdia,P(d),L(d.type),y(d))},p=function(d){return o(X.mfhd,new Uint8Array([0,0,0,0,(d&4278190080)>>24,(d&16711680)>>16,(d&65280)>>8,d&255]))},y=function(d){return o(X.minf,d.type==="video"?o(X.vmhd,ie):o(X.smhd,ge),c(),N(d))},_=function(d,f){for(var g=[],m=f.length;m--;)g[m]=k(f[m]);return o.apply(null,[X.moof,p(d)].concat(g))},b=function(d){for(var f=d.length,g=[];f--;)g[f]=I(d[f]);return o.apply(null,[X.moov,D(4294967295)].concat(g).concat(S(d)))},S=function(d){for(var f=d.length,g=[];f--;)g[f]=j(d[f]);return o.apply(null,[X.mvex].concat(g))},D=function(d){var f=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(d&4278190080)>>24,(d&16711680)>>16,(d&65280)>>8,d&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return o(X.mvhd,f)},C=function(d){var f=d.samples||[],g=new Uint8Array(4+f.length),m,v;for(v=0;v<f.length;v++)m=f[v].flags,g[v+4]=m.dependsOn<<4|m.isDependedOn<<2|m.hasRedundancy;return o(X.sdtp,g)},N=function(d){return o(X.stbl,x(d),o(X.stts,ve),o(X.stsc,we),o(X.stsz,Pe),o(X.stco,be))},(function(){var d,f;x=function(g){return o(X.stsd,new Uint8Array([0,0,0,0,0,0,0,1]),g.type==="video"?d(g):f(g))},d=function(g){var m=g.sps||[],v=g.pps||[],T=[],R=[],M,U;for(M=0;M<m.length;M++)T.push((m[M].byteLength&65280)>>>8),T.push(m[M].byteLength&255),T=T.concat(Array.prototype.slice.call(m[M]));for(M=0;M<v.length;M++)R.push((v[M].byteLength&65280)>>>8),R.push(v[M].byteLength&255),R=R.concat(Array.prototype.slice.call(v[M]));if(U=[X.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,(g.width&65280)>>8,g.width&255,(g.height&65280)>>8,g.height&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o(X.avcC,new Uint8Array([1,g.profileIdc,g.profileCompatibility,g.levelIdc,255].concat([m.length],T,[v.length],R))),o(X.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],g.sarRatio){var q=g.sarRatio[0],$=g.sarRatio[1];U.push(o(X.pasp,new Uint8Array([(q&4278190080)>>24,(q&16711680)>>16,(q&65280)>>8,q&255,($&4278190080)>>24,($&16711680)>>16,($&65280)>>8,$&255])))}return o.apply(null,U)},f=function(g){return o(X.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(g.channelcount&65280)>>8,g.channelcount&255,(g.samplesize&65280)>>8,g.samplesize&255,0,0,0,0,(g.samplerate&65280)>>8,g.samplerate&255,0,0]),l(g))}})(),F=function(d){var f=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(d.id&4278190080)>>24,(d.id&16711680)>>16,(d.id&65280)>>8,d.id&255,0,0,0,0,(d.duration&4278190080)>>24,(d.duration&16711680)>>16,(d.duration&65280)>>8,d.duration&255,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,(d.width&65280)>>8,d.width&255,0,0,(d.height&65280)>>8,d.height&255,0,0]);return o(X.tkhd,f)},k=function(d){var f,g,m,v,T,R,M;return f=o(X.tfhd,new Uint8Array([0,0,0,58,(d.id&4278190080)>>24,(d.id&16711680)>>16,(d.id&65280)>>8,d.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),R=Math.floor(d.baseMediaDecodeTime/a),M=Math.floor(d.baseMediaDecodeTime%a),g=o(X.tfdt,new Uint8Array([1,0,0,0,R>>>24&255,R>>>16&255,R>>>8&255,R&255,M>>>24&255,M>>>16&255,M>>>8&255,M&255])),T=92,d.type==="audio"?(m=G(d,T),o(X.traf,f,g,m)):(v=C(d),m=G(d,v.length+T),o(X.traf,f,g,m,v))},I=function(d){return d.duration=d.duration||4294967295,o(X.trak,F(d),w(d))},j=function(d){var f=new Uint8Array([0,0,0,0,(d.id&4278190080)>>24,(d.id&16711680)>>16,(d.id&65280)>>8,d.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return d.type!=="video"&&(f[f.length-1]=0),o(X.trex,f)},(function(){var d,f,g;g=function(m,v){var T=0,R=0,M=0,U=0;return m.length&&(m[0].duration!==void 0&&(T=1),m[0].size!==void 0&&(R=2),m[0].flags!==void 0&&(M=4),m[0].compositionTimeOffset!==void 0&&(U=8)),[0,0,T|R|M|U,1,(m.length&4278190080)>>>24,(m.length&16711680)>>>16,(m.length&65280)>>>8,m.length&255,(v&4278190080)>>>24,(v&16711680)>>>16,(v&65280)>>>8,v&255]},f=function(m,v){var T,R,M,U,q,$;for(U=m.samples||[],v+=20+16*U.length,M=g(U,v),R=new Uint8Array(M.length+U.length*16),R.set(M),T=M.length,$=0;$<U.length;$++)q=U[$],R[T++]=(q.duration&4278190080)>>>24,R[T++]=(q.duration&16711680)>>>16,R[T++]=(q.duration&65280)>>>8,R[T++]=q.duration&255,R[T++]=(q.size&4278190080)>>>24,R[T++]=(q.size&16711680)>>>16,R[T++]=(q.size&65280)>>>8,R[T++]=q.size&255,R[T++]=q.flags.isLeading<<2|q.flags.dependsOn,R[T++]=q.flags.isDependedOn<<6|q.flags.hasRedundancy<<4|q.flags.paddingValue<<1|q.flags.isNonSyncSample,R[T++]=q.flags.degradationPriority&61440,R[T++]=q.flags.degradationPriority&15,R[T++]=(q.compositionTimeOffset&4278190080)>>>24,R[T++]=(q.compositionTimeOffset&16711680)>>>16,R[T++]=(q.compositionTimeOffset&65280)>>>8,R[T++]=q.compositionTimeOffset&255;return o(X.trun,R)},d=function(m,v){var T,R,M,U,q,$;for(U=m.samples||[],v+=20+8*U.length,M=g(U,v),T=new Uint8Array(M.length+U.length*8),T.set(M),R=M.length,$=0;$<U.length;$++)q=U[$],T[R++]=(q.duration&4278190080)>>>24,T[R++]=(q.duration&16711680)>>>16,T[R++]=(q.duration&65280)>>>8,T[R++]=q.duration&255,T[R++]=(q.size&4278190080)>>>24,T[R++]=(q.size&16711680)>>>16,T[R++]=(q.size&65280)>>>8,T[R++]=q.size&255;return o(X.trun,T)},G=function(m,v){return m.type==="audio"?d(m,v):f(m,v)}})();var qe={ftyp:u,mdat:h,moof:_,moov:b,initSegment:function(d){var f=u(),g=b(d),m;return m=new Uint8Array(f.byteLength+g.byteLength),m.set(f),m.set(g,f.byteLength),m}},bt=function(d){var f,g,m=[],v=[];for(v.byteLength=0,v.nalCount=0,v.duration=0,m.byteLength=0,f=0;f<d.length;f++)g=d[f],g.nalUnitType==="access_unit_delimiter_rbsp"?(m.length&&(m.duration=g.dts-m.dts,v.byteLength+=m.byteLength,v.nalCount+=m.length,v.duration+=m.duration,v.push(m)),m=[g],m.byteLength=g.data.byteLength,m.pts=g.pts,m.dts=g.dts):(g.nalUnitType==="slice_layer_without_partitioning_rbsp_idr"&&(m.keyFrame=!0),m.duration=g.dts-m.dts,m.byteLength+=g.data.byteLength,m.push(g));return v.length&&(!m.duration||m.duration<=0)&&(m.duration=v[v.length-1].duration),v.byteLength+=m.byteLength,v.nalCount+=m.length,v.duration+=m.duration,v.push(m),v},et=function(d){var f,g,m=[],v=[];for(m.byteLength=0,m.nalCount=0,m.duration=0,m.pts=d[0].pts,m.dts=d[0].dts,v.byteLength=0,v.nalCount=0,v.duration=0,v.pts=d[0].pts,v.dts=d[0].dts,f=0;f<d.length;f++)g=d[f],g.keyFrame?(m.length&&(v.push(m),v.byteLength+=m.byteLength,v.nalCount+=m.nalCount,v.duration+=m.duration),m=[g],m.nalCount=g.length,m.byteLength=g.byteLength,m.pts=g.pts,m.dts=g.dts,m.duration=g.duration):(m.duration+=g.duration,m.nalCount+=g.length,m.byteLength+=g.byteLength,m.push(g));return v.length&&m.duration<=0&&(m.duration=v[v.length-1].duration),v.byteLength+=m.byteLength,v.nalCount+=m.nalCount,v.duration+=m.duration,v.push(m),v},fi=function(d){var f;return!d[0][0].keyFrame&&d.length>1&&(f=d.shift(),d.byteLength-=f.byteLength,d.nalCount-=f.nalCount,d[0][0].dts=f.dts,d[0][0].pts=f.pts,d[0][0].duration+=f.duration),d},Bn=function(){return{size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}}},wt=function(d,f){var g=Bn();return g.dataOffset=f,g.compositionTimeOffset=d.pts-d.dts,g.duration=d.duration,g.size=4*d.length,g.size+=d.byteLength,d.keyFrame&&(g.flags.dependsOn=2,g.flags.isNonSyncSample=0),g},bn=function(d,f){var g,m,v,T,R,M=f||0,U=[];for(g=0;g<d.length;g++)for(T=d[g],m=0;m<T.length;m++)R=T[m],v=wt(R,M),M+=v.size,U.push(v);return U},kt=function(d){var f,g,m,v,T,R,M=0,U=d.byteLength,q=d.nalCount,$=U+4*q,Z=new Uint8Array($),pe=new DataView(Z.buffer);for(f=0;f<d.length;f++)for(v=d[f],g=0;g<v.length;g++)for(T=v[g],m=0;m<T.length;m++)R=T[m],pe.setUint32(M,R.data.byteLength),M+=4,Z.set(R.data,M),M+=R.data.byteLength;return Z},zr=function(d,f){var g,m=f||0,v=[];return g=wt(d,m),v.push(g),v},ro=function(d){var f,g,m=0,v=d.byteLength,T=d.length,R=v+4*T,M=new Uint8Array(R),U=new DataView(M.buffer);for(f=0;f<d.length;f++)g=d[f],U.setUint32(m,g.data.byteLength),m+=4,M.set(g.data,m),m+=g.data.byteLength;return M},ii={groupNalsIntoFrames:bt,groupFramesIntoGops:et,extendFirstKeyFrame:fi,generateSampleTable:bn,concatenateNalData:kt,generateSampleTableForFrame:zr,concatenateNalDataForFrame:ro},mt=[33,16,5,32,164,27],Ge=[33,65,108,84,1,2,4,8,168,2,4,8,17,191,252],Ae=function(d){for(var f=[];d--;)f.push(0);return f},Gr=function(d){return Object.keys(d).reduce(function(f,g){return f[g]=new Uint8Array(d[g].reduce(function(m,v){return m.concat(v)},[])),f},{})},ao,wf=function(){if(!ao){var d={96e3:[mt,[227,64],Ae(154),[56]],88200:[mt,[231],Ae(170),[56]],64e3:[mt,[248,192],Ae(240),[56]],48e3:[mt,[255,192],Ae(268),[55,148,128],Ae(54),[112]],44100:[mt,[255,192],Ae(268),[55,163,128],Ae(84),[112]],32e3:[mt,[255,192],Ae(268),[55,234],Ae(226),[112]],24e3:[mt,[255,192],Ae(268),[55,255,128],Ae(268),[111,112],Ae(126),[224]],16e3:[mt,[255,192],Ae(268),[55,255,128],Ae(268),[111,255],Ae(269),[223,108],Ae(195),[1,192]],12e3:[Ge,Ae(268),[3,127,248],Ae(268),[6,255,240],Ae(268),[13,255,224],Ae(268),[27,253,128],Ae(259),[56]],11025:[Ge,Ae(268),[3,127,248],Ae(268),[6,255,240],Ae(268),[13,255,224],Ae(268),[27,255,192],Ae(268),[55,175,128],Ae(108),[112]],8e3:[Ge,Ae(268),[3,121,16],Ae(47),[7]]};ao=Gr(d)}return ao},Kr=9e4,hs,qn,Xr,Ki,Ws,fs,Yr;hs=function(d){return d*Kr},qn=function(d,f){return d*f},Xr=function(d){return d/Kr},Ki=function(d,f){return d/f},Ws=function(d,f){return hs(Ki(d,f))},fs=function(d,f){return qn(Xr(d),f)},Yr=function(d,f,g){return Xr(g?d:d-f)};var Ke={ONE_SECOND_IN_TS:Kr,secondsToVideoTs:hs,secondsToAudioTs:qn,videoTsToSeconds:Xr,audioTsToSeconds:Ki,audioTsToVideoTs:Ws,videoTsToAudioTs:fs,metadataTsToSeconds:Yr},oo=wf,Vn=Ke,xl=function(d){var f,g,m=0;for(f=0;f<d.length;f++)g=d[f],m+=g.data.byteLength;return m},wl=function(d,f,g,m){var v,T=0,R=0,M=0,U=0,q,$,Z;if(f.length&&(v=Vn.audioTsToVideoTs(d.baseMediaDecodeTime,d.samplerate),T=Math.ceil(Vn.ONE_SECOND_IN_TS/(d.samplerate/1024)),g&&m&&(R=v-Math.max(g,m),M=Math.floor(R/T),U=M*T),!(M<1||U>Vn.ONE_SECOND_IN_TS/2))){for(q=oo()[d.samplerate],q||(q=f[0].data),$=0;$<M;$++)Z=f[0],f.splice(0,0,{data:q,dts:Z.dts-T,pts:Z.pts-T});return d.baseMediaDecodeTime-=Math.floor(Vn.videoTsToAudioTs(U,d.samplerate)),U}},co=function(d,f,g){return f.minSegmentDts>=g?d:(f.minSegmentDts=1/0,d.filter(function(m){return m.dts>=g?(f.minSegmentDts=Math.min(f.minSegmentDts,m.dts),f.minSegmentPts=f.minSegmentDts,!0):!1}))},Qr=function(d){var f,g,m=[];for(f=0;f<d.length;f++)g=d[f],m.push({size:g.data.byteLength,duration:1024});return m},lo=function(d){var f,g,m=0,v=new Uint8Array(xl(d));for(f=0;f<d.length;f++)g=d[f],v.set(g.data,m),m+=g.data.byteLength;return v},Al={prefixWithSilence:wl,trimAdtsFramesByEarliestDts:co,generateSampleTable:Qr,concatenateFrameData:lo},Dl=Ke.ONE_SECOND_IN_TS,Pl=function(d,f){typeof f.pts=="number"&&(d.timelineStartInfo.pts===void 0&&(d.timelineStartInfo.pts=f.pts),d.minSegmentPts===void 0?d.minSegmentPts=f.pts:d.minSegmentPts=Math.min(d.minSegmentPts,f.pts),d.maxSegmentPts===void 0?d.maxSegmentPts=f.pts:d.maxSegmentPts=Math.max(d.maxSegmentPts,f.pts)),typeof f.dts=="number"&&(d.timelineStartInfo.dts===void 0&&(d.timelineStartInfo.dts=f.dts),d.minSegmentDts===void 0?d.minSegmentDts=f.dts:d.minSegmentDts=Math.min(d.minSegmentDts,f.dts),d.maxSegmentDts===void 0?d.maxSegmentDts=f.dts:d.maxSegmentDts=Math.max(d.maxSegmentDts,f.dts))},Jr=function(d){delete d.minSegmentDts,delete d.maxSegmentDts,delete d.minSegmentPts,delete d.maxSegmentPts},uo=function(d,f){var g,m,v=d.minSegmentDts;return f||(v-=d.timelineStartInfo.dts),g=d.timelineStartInfo.baseMediaDecodeTime,g+=v,g=Math.max(0,g),d.type==="audio"&&(m=d.samplerate/Dl,g*=m,g=Math.floor(g)),g},Af={clearDtsInfo:Jr,calculateTrackBaseMediaDecodeTime:uo,collectDtsInfo:Pl},ho=4,Il=128,E=function(d){for(var f=0,g={payloadType:-1,payloadSize:0},m=0,v=0;f<d.byteLength&&d[f]!==Il;){for(;d[f]===255;)m+=255,f++;for(m+=d[f++];d[f]===255;)v+=255,f++;if(v+=d[f++],!g.payload&&m===ho){var T=String.fromCharCode(d[f+3],d[f+4],d[f+5],d[f+6]);if(T==="GA94"){g.payloadType=m,g.payloadSize=v,g.payload=d.subarray(f,f+v);break}else g.payload=void 0}f+=v,m=0,v=0}return g},A=function(d){return d.payload[0]!==181||(d.payload[1]<<8|d.payload[2])!==49||String.fromCharCode(d.payload[3],d.payload[4],d.payload[5],d.payload[6])!=="GA94"||d.payload[7]!==3?null:d.payload.subarray(8,d.payload.length-1)},V=function(d,f){var g=[],m,v,T,R;if(!(f[0]&64))return g;for(v=f[0]&31,m=0;m<v;m++)T=m*3,R={type:f[T+2]&3,pts:d},f[T+2]&4&&(R.ccData=f[T+3]<<8|f[T+4],g.push(R));return g},J=function(d){for(var f=d.byteLength,g=[],m=1,v,T;m<f-2;)d[m]===0&&d[m+1]===0&&d[m+2]===3?(g.push(m+2),m+=2):m++;if(g.length===0)return d;v=f-g.length,T=new Uint8Array(v);var R=0;for(m=0;m<v;R++,m++)R===g[0]&&(R++,g.shift()),T[m]=d[R];return T},ue={parseSei:E,parseUserData:A,parseCaptionPackets:V,discardEmulationPreventionBytes:J,USER_DATA_REGISTERED_ITU_T_T35:ho},me=t,ce=ue,Me=function(d){d=d||{},Me.prototype.init.call(this),this.parse708captions_=typeof d.parse708captions=="boolean"?d.parse708captions:!0,this.captionPackets_=[],this.ccStreams_=[new je(0,0),new je(0,1),new je(1,0),new je(1,1)],this.parse708captions_&&(this.cc708Stream_=new Ne({captionServices:d.captionServices})),this.reset(),this.ccStreams_.forEach(function(f){f.on("data",this.trigger.bind(this,"data")),f.on("partialdone",this.trigger.bind(this,"partialdone")),f.on("done",this.trigger.bind(this,"done"))},this),this.parse708captions_&&(this.cc708Stream_.on("data",this.trigger.bind(this,"data")),this.cc708Stream_.on("partialdone",this.trigger.bind(this,"partialdone")),this.cc708Stream_.on("done",this.trigger.bind(this,"done")))};Me.prototype=new me,Me.prototype.push=function(d){var f,g,m;if(d.nalUnitType==="sei_rbsp"&&(f=ce.parseSei(d.escapedRBSP),!!f.payload&&f.payloadType===ce.USER_DATA_REGISTERED_ITU_T_T35&&(g=ce.parseUserData(f),!!g))){if(d.dts<this.latestDts_){this.ignoreNextEqualDts_=!0;return}else if(d.dts===this.latestDts_&&this.ignoreNextEqualDts_){this.numSameDts_--,this.numSameDts_||(this.ignoreNextEqualDts_=!1);return}m=ce.parseCaptionPackets(d.pts,g),this.captionPackets_=this.captionPackets_.concat(m),this.latestDts_!==d.dts&&(this.numSameDts_=0),this.numSameDts_++,this.latestDts_=d.dts}},Me.prototype.flushCCStreams=function(d){this.ccStreams_.forEach(function(f){return d==="flush"?f.flush():f.partialFlush()},this)},Me.prototype.flushStream=function(d){if(!this.captionPackets_.length){this.flushCCStreams(d);return}this.captionPackets_.forEach(function(f,g){f.presortIndex=g}),this.captionPackets_.sort(function(f,g){return f.pts===g.pts?f.presortIndex-g.presortIndex:f.pts-g.pts}),this.captionPackets_.forEach(function(f){f.type<2?this.dispatchCea608Packet(f):this.dispatchCea708Packet(f)},this),this.captionPackets_.length=0,this.flushCCStreams(d)},Me.prototype.flush=function(){return this.flushStream("flush")},Me.prototype.partialFlush=function(){return this.flushStream("partialFlush")},Me.prototype.reset=function(){this.latestDts_=null,this.ignoreNextEqualDts_=!1,this.numSameDts_=0,this.activeCea608Channel_=[null,null],this.ccStreams_.forEach(function(d){d.reset()})},Me.prototype.dispatchCea608Packet=function(d){this.setsTextOrXDSActive(d)?this.activeCea608Channel_[d.type]=null:this.setsChannel1Active(d)?this.activeCea608Channel_[d.type]=0:this.setsChannel2Active(d)&&(this.activeCea608Channel_[d.type]=1),this.activeCea608Channel_[d.type]!==null&&this.ccStreams_[(d.type<<1)+this.activeCea608Channel_[d.type]].push(d)},Me.prototype.setsChannel1Active=function(d){return(d.ccData&30720)===4096},Me.prototype.setsChannel2Active=function(d){return(d.ccData&30720)===6144},Me.prototype.setsTextOrXDSActive=function(d){return(d.ccData&28928)===256||(d.ccData&30974)===4138||(d.ccData&30974)===6186},Me.prototype.dispatchCea708Packet=function(d){this.parse708captions_&&this.cc708Stream_.push(d)};var At={127:9834,4128:32,4129:160,4133:8230,4138:352,4140:338,4144:9608,4145:8216,4146:8217,4147:8220,4148:8221,4149:8226,4153:8482,4154:353,4156:339,4157:8480,4159:376,4214:8539,4215:8540,4216:8541,4217:8542,4218:9168,4219:9124,4220:9123,4221:9135,4222:9126,4223:9121,4256:12600},ni=function(d){var f=At[d]||d;return d&4096&&d===f?"":String.fromCharCode(f)},pi=function(d){return 32<=d&&d<=127||160<=d&&d<=255},mi=function(d){this.windowNum=d,this.reset()};mi.prototype.reset=function(){this.clearText(),this.pendingNewLine=!1,this.winAttr={},this.penAttr={},this.penLoc={},this.penColor={},this.visible=0,this.rowLock=0,this.columnLock=0,this.priority=0,this.relativePositioning=0,this.anchorVertical=0,this.anchorHorizontal=0,this.anchorPoint=0,this.rowCount=1,this.virtualRowCount=this.rowCount+1,this.columnCount=41,this.windowStyle=0,this.penStyle=0},mi.prototype.getText=function(){return this.rows.join(`
|
|
250
|
+
`)},mi.prototype.clearText=function(){this.rows=[""],this.rowIdx=0},mi.prototype.newLine=function(d){for(this.rows.length>=this.virtualRowCount&&typeof this.beforeRowOverflow=="function"&&this.beforeRowOverflow(d),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},mi.prototype.isEmpty=function(){return this.rows.length===0?!0:this.rows.length===1?this.rows[0]==="":!1},mi.prototype.addText=function(d){this.rows[this.rowIdx]+=d},mi.prototype.backspace=function(){if(!this.isEmpty()){var d=this.rows[this.rowIdx];this.rows[this.rowIdx]=d.substr(0,d.length-1)}};var Si=function(d,f,g){this.serviceNum=d,this.text="",this.currentWindow=new mi(-1),this.windows=[],this.stream=g,typeof f=="string"&&this.createTextDecoder(f)};Si.prototype.init=function(d,f){this.startPts=d;for(var g=0;g<8;g++)this.windows[g]=new mi(g),typeof f=="function"&&(this.windows[g].beforeRowOverflow=f)},Si.prototype.setCurrentWindow=function(d){this.currentWindow=this.windows[d]},Si.prototype.createTextDecoder=function(d){if(typeof TextDecoder>"u")this.stream.trigger("log",{level:"warn",message:"The `encoding` option is unsupported without TextDecoder support"});else try{this.textDecoder_=new TextDecoder(d)}catch(f){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+d+" encoding. "+f})}};var Ne=function(d){d=d||{},Ne.prototype.init.call(this);var f=this,g=d.captionServices||{},m={},v;Object.keys(g).forEach(T=>{v=g[T],/^SERVICE/.test(T)&&(m[T]=v.encoding)}),this.serviceEncodings=m,this.current708Packet=null,this.services={},this.push=function(T){T.type===3?(f.new708Packet(),f.add708Bytes(T)):(f.current708Packet===null&&f.new708Packet(),f.add708Bytes(T))}};Ne.prototype=new me,Ne.prototype.new708Packet=function(){this.current708Packet!==null&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},Ne.prototype.add708Bytes=function(d){var f=d.ccData,g=f>>>8,m=f&255;this.current708Packet.ptsVals.push(d.pts),this.current708Packet.data.push(g),this.current708Packet.data.push(m)},Ne.prototype.push708Packet=function(){var d=this.current708Packet,f=d.data,g=null,m=null,v=0,T=f[v++];for(d.seq=T>>6,d.sizeCode=T&63;v<f.length;v++)T=f[v++],g=T>>5,m=T&31,g===7&&m>0&&(T=f[v++],g=T),this.pushServiceBlock(g,v,m),m>0&&(v+=m-1)},Ne.prototype.pushServiceBlock=function(d,f,g){var m,v=f,T=this.current708Packet.data,R=this.services[d];for(R||(R=this.initService(d,v));v<f+g&&v<T.length;v++)m=T[v],pi(m)?v=this.handleText(v,R):m===24?v=this.multiByteCharacter(v,R):m===16?v=this.extendedCommands(v,R):128<=m&&m<=135?v=this.setCurrentWindow(v,R):152<=m&&m<=159?v=this.defineWindow(v,R):m===136?v=this.clearWindows(v,R):m===140?v=this.deleteWindows(v,R):m===137?v=this.displayWindows(v,R):m===138?v=this.hideWindows(v,R):m===139?v=this.toggleWindows(v,R):m===151?v=this.setWindowAttributes(v,R):m===144?v=this.setPenAttributes(v,R):m===145?v=this.setPenColor(v,R):m===146?v=this.setPenLocation(v,R):m===143?R=this.reset(v,R):m===8?R.currentWindow.backspace():m===12?R.currentWindow.clearText():m===13?R.currentWindow.pendingNewLine=!0:m===14?R.currentWindow.clearText():m===141&&v++},Ne.prototype.extendedCommands=function(d,f){var g=this.current708Packet.data,m=g[++d];return pi(m)&&(d=this.handleText(d,f,{isExtended:!0})),d},Ne.prototype.getPts=function(d){return this.current708Packet.ptsVals[Math.floor(d/2)]},Ne.prototype.initService=function(d,f){var m="SERVICE"+d,g=this,m,v;return m in this.serviceEncodings&&(v=this.serviceEncodings[m]),this.services[d]=new Si(d,v,g),this.services[d].init(this.getPts(f),function(T){g.flushDisplayed(T,g.services[d])}),this.services[d]},Ne.prototype.handleText=function(d,f,g){var m=g&&g.isExtended,v=g&&g.isMultiByte,T=this.current708Packet.data,R=m?4096:0,M=T[d],U=T[d+1],q=f.currentWindow,$,Z;function pe(ne){return ne.map(ke=>("0"+(ke&255).toString(16)).slice(-2)).join("")}if(v?(Z=[M,U],d++):Z=[M],f.textDecoder_&&!m)$=f.textDecoder_.decode(new Uint8Array(Z));else if(v){const ne=pe(Z);$=String.fromCharCode(parseInt(ne,16))}else $=ni(R|M);return q.pendingNewLine&&!q.isEmpty()&&q.newLine(this.getPts(d)),q.pendingNewLine=!1,q.addText($),d},Ne.prototype.multiByteCharacter=function(d,f){var g=this.current708Packet.data,m=g[d+1],v=g[d+2];return pi(m)&&pi(v)&&(d=this.handleText(++d,f,{isMultiByte:!0})),d},Ne.prototype.setCurrentWindow=function(d,f){var g=this.current708Packet.data,m=g[d],v=m&7;return f.setCurrentWindow(v),d},Ne.prototype.defineWindow=function(d,f){var g=this.current708Packet.data,m=g[d],v=m&7;f.setCurrentWindow(v);var T=f.currentWindow;return m=g[++d],T.visible=(m&32)>>5,T.rowLock=(m&16)>>4,T.columnLock=(m&8)>>3,T.priority=m&7,m=g[++d],T.relativePositioning=(m&128)>>7,T.anchorVertical=m&127,m=g[++d],T.anchorHorizontal=m,m=g[++d],T.anchorPoint=(m&240)>>4,T.rowCount=m&15,m=g[++d],T.columnCount=m&63,m=g[++d],T.windowStyle=(m&56)>>3,T.penStyle=m&7,T.virtualRowCount=T.rowCount+1,d},Ne.prototype.setWindowAttributes=function(d,f){var g=this.current708Packet.data,m=g[d],v=f.currentWindow.winAttr;return m=g[++d],v.fillOpacity=(m&192)>>6,v.fillRed=(m&48)>>4,v.fillGreen=(m&12)>>2,v.fillBlue=m&3,m=g[++d],v.borderType=(m&192)>>6,v.borderRed=(m&48)>>4,v.borderGreen=(m&12)>>2,v.borderBlue=m&3,m=g[++d],v.borderType+=(m&128)>>5,v.wordWrap=(m&64)>>6,v.printDirection=(m&48)>>4,v.scrollDirection=(m&12)>>2,v.justify=m&3,m=g[++d],v.effectSpeed=(m&240)>>4,v.effectDirection=(m&12)>>2,v.displayEffect=m&3,d},Ne.prototype.flushDisplayed=function(d,f){for(var g=[],m=0;m<8;m++)f.windows[m].visible&&!f.windows[m].isEmpty()&&g.push(f.windows[m].getText());f.endPts=d,f.text=g.join(`
|
|
251
|
+
|
|
252
|
+
`),this.pushCaption(f),f.startPts=d},Ne.prototype.pushCaption=function(d){d.text!==""&&(this.trigger("data",{startPts:d.startPts,endPts:d.endPts,text:d.text,stream:"cc708_"+d.serviceNum}),d.text="",d.startPts=d.endPts)},Ne.prototype.displayWindows=function(d,f){var g=this.current708Packet.data,m=g[++d],v=this.getPts(d);this.flushDisplayed(v,f);for(var T=0;T<8;T++)m&1<<T&&(f.windows[T].visible=1);return d},Ne.prototype.hideWindows=function(d,f){var g=this.current708Packet.data,m=g[++d],v=this.getPts(d);this.flushDisplayed(v,f);for(var T=0;T<8;T++)m&1<<T&&(f.windows[T].visible=0);return d},Ne.prototype.toggleWindows=function(d,f){var g=this.current708Packet.data,m=g[++d],v=this.getPts(d);this.flushDisplayed(v,f);for(var T=0;T<8;T++)m&1<<T&&(f.windows[T].visible^=1);return d},Ne.prototype.clearWindows=function(d,f){var g=this.current708Packet.data,m=g[++d],v=this.getPts(d);this.flushDisplayed(v,f);for(var T=0;T<8;T++)m&1<<T&&f.windows[T].clearText();return d},Ne.prototype.deleteWindows=function(d,f){var g=this.current708Packet.data,m=g[++d],v=this.getPts(d);this.flushDisplayed(v,f);for(var T=0;T<8;T++)m&1<<T&&f.windows[T].reset();return d},Ne.prototype.setPenAttributes=function(d,f){var g=this.current708Packet.data,m=g[d],v=f.currentWindow.penAttr;return m=g[++d],v.textTag=(m&240)>>4,v.offset=(m&12)>>2,v.penSize=m&3,m=g[++d],v.italics=(m&128)>>7,v.underline=(m&64)>>6,v.edgeType=(m&56)>>3,v.fontStyle=m&7,d},Ne.prototype.setPenColor=function(d,f){var g=this.current708Packet.data,m=g[d],v=f.currentWindow.penColor;return m=g[++d],v.fgOpacity=(m&192)>>6,v.fgRed=(m&48)>>4,v.fgGreen=(m&12)>>2,v.fgBlue=m&3,m=g[++d],v.bgOpacity=(m&192)>>6,v.bgRed=(m&48)>>4,v.bgGreen=(m&12)>>2,v.bgBlue=m&3,m=g[++d],v.edgeRed=(m&48)>>4,v.edgeGreen=(m&12)>>2,v.edgeBlue=m&3,d},Ne.prototype.setPenLocation=function(d,f){var g=this.current708Packet.data,m=g[d],v=f.currentWindow.penLoc;return f.currentWindow.pendingNewLine=!0,m=g[++d],v.row=m&15,m=g[++d],v.column=m&63,d},Ne.prototype.reset=function(d,f){var g=this.getPts(d);return this.flushDisplayed(g,f),this.initService(f.serviceNum,d)};var Zr={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,304:174,305:176,306:189,307:191,308:8482,309:162,310:163,311:9834,312:224,313:160,314:232,315:226,316:234,317:238,318:244,319:251,544:193,545:201,546:211,547:218,548:220,549:252,550:8216,551:161,552:42,553:39,554:8212,555:169,556:8480,557:8226,558:8220,559:8221,560:192,561:194,562:199,563:200,564:202,565:203,566:235,567:206,568:207,569:239,570:212,571:217,572:249,573:219,574:171,575:187,800:195,801:227,802:205,803:204,804:236,805:210,806:242,807:213,808:245,809:123,810:125,811:92,812:94,813:95,814:124,815:126,816:196,817:228,818:214,819:246,820:223,821:165,822:164,823:9474,824:197,825:229,826:216,827:248,828:9484,829:9488,830:9492,831:9496},jn=function(d){return d===null?"":(d=Zr[d]||d,String.fromCharCode(d))},Mi=14,Hn=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],zt=function(){for(var d=[],f=Mi+1;f--;)d.push({text:"",indent:0,offset:0});return d},je=function(d,f){je.prototype.init.call(this),this.field_=d||0,this.dataChannel_=f||0,this.name_="CC"+((this.field_<<1|this.dataChannel_)+1),this.setConstants(),this.reset(),this.push=function(g){var m,v,T,R,M;if(m=g.ccData&32639,m===this.lastControlCode_){this.lastControlCode_=null;return}if((m&61440)===4096?this.lastControlCode_=m:m!==this.PADDING_&&(this.lastControlCode_=null),T=m>>>8,R=m&255,m!==this.PADDING_)if(m===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(m===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(g.pts),this.flushDisplayed(g.pts),v=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=v,this.startPts_=g.pts;else if(m===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(g.pts);else if(m===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(g.pts);else if(m===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(g.pts);else if(m===this.CARRIAGE_RETURN_)this.clearFormatting(g.pts),this.flushDisplayed(g.pts),this.shiftRowsUp_(),this.startPts_=g.pts;else if(m===this.BACKSPACE_)this.mode_==="popOn"?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1);else if(m===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(g.pts),this.displayed_=zt();else if(m===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=zt();else if(m===this.RESUME_DIRECT_CAPTIONING_)this.mode_!=="paintOn"&&(this.flushDisplayed(g.pts),this.displayed_=zt()),this.mode_="paintOn",this.startPts_=g.pts;else if(this.isSpecialCharacter(T,R))T=(T&3)<<8,M=jn(T|R),this[this.mode_](g.pts,M),this.column_++;else if(this.isExtCharacter(T,R))this.mode_==="popOn"?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1),T=(T&3)<<8,M=jn(T|R),this[this.mode_](g.pts,M),this.column_++;else if(this.isMidRowCode(T,R))this.clearFormatting(g.pts),this[this.mode_](g.pts," "),this.column_++,(R&14)===14&&this.addFormatting(g.pts,["i"]),(R&1)===1&&this.addFormatting(g.pts,["u"]);else if(this.isOffsetControlCode(T,R)){const q=R&3;this.nonDisplayed_[this.row_].offset=q,this.column_+=q}else if(this.isPAC(T,R)){var U=Hn.indexOf(m&7968);if(this.mode_==="rollUp"&&(U-this.rollUpRows_+1<0&&(U=this.rollUpRows_-1),this.setRollUp(g.pts,U)),U!==this.row_&&U>=0&&U<=14&&(this.clearFormatting(g.pts),this.row_=U),R&1&&this.formatting_.indexOf("u")===-1&&this.addFormatting(g.pts,["u"]),(m&16)===16){const q=(m&14)>>1;this.column_=q*4,this.nonDisplayed_[this.row_].indent+=q}this.isColorPAC(R)&&(R&14)===14&&this.addFormatting(g.pts,["i"])}else this.isNormalChar(T)&&(R===0&&(R=null),M=jn(T),M+=jn(R),this[this.mode_](g.pts,M),this.column_+=M.length)}};je.prototype=new me,je.prototype.flushDisplayed=function(d){const f=m=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+m+"."})},g=[];this.displayed_.forEach((m,v)=>{if(m&&m.text&&m.text.length){try{m.text=m.text.trim()}catch{f(v)}m.text.length&&g.push({text:m.text,line:v+1,position:10+Math.min(70,m.indent*10)+m.offset*2.5})}else m==null&&f(v)}),g.length&&this.trigger("data",{startPts:this.startPts_,endPts:d,content:g,stream:this.name_})},je.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=zt(),this.nonDisplayed_=zt(),this.lastControlCode_=null,this.column_=0,this.row_=Mi,this.rollUpRows_=2,this.formatting_=[]},je.prototype.setConstants=function(){this.dataChannel_===0?(this.BASE_=16,this.EXT_=17,this.CONTROL_=(20|this.field_)<<8,this.OFFSET_=23):this.dataChannel_===1&&(this.BASE_=24,this.EXT_=25,this.CONTROL_=(28|this.field_)<<8,this.OFFSET_=31),this.PADDING_=0,this.RESUME_CAPTION_LOADING_=this.CONTROL_|32,this.END_OF_CAPTION_=this.CONTROL_|47,this.ROLL_UP_2_ROWS_=this.CONTROL_|37,this.ROLL_UP_3_ROWS_=this.CONTROL_|38,this.ROLL_UP_4_ROWS_=this.CONTROL_|39,this.CARRIAGE_RETURN_=this.CONTROL_|45,this.RESUME_DIRECT_CAPTIONING_=this.CONTROL_|41,this.BACKSPACE_=this.CONTROL_|33,this.ERASE_DISPLAYED_MEMORY_=this.CONTROL_|44,this.ERASE_NON_DISPLAYED_MEMORY_=this.CONTROL_|46},je.prototype.isSpecialCharacter=function(d,f){return d===this.EXT_&&f>=48&&f<=63},je.prototype.isExtCharacter=function(d,f){return(d===this.EXT_+1||d===this.EXT_+2)&&f>=32&&f<=63},je.prototype.isMidRowCode=function(d,f){return d===this.EXT_&&f>=32&&f<=47},je.prototype.isOffsetControlCode=function(d,f){return d===this.OFFSET_&&f>=33&&f<=35},je.prototype.isPAC=function(d,f){return d>=this.BASE_&&d<this.BASE_+8&&f>=64&&f<=127},je.prototype.isColorPAC=function(d){return d>=64&&d<=79||d>=96&&d<=127},je.prototype.isNormalChar=function(d){return d>=32&&d<=127},je.prototype.setRollUp=function(d,f){if(this.mode_!=="rollUp"&&(this.row_=Mi,this.mode_="rollUp",this.flushDisplayed(d),this.nonDisplayed_=zt(),this.displayed_=zt()),f!==void 0&&f!==this.row_)for(var g=0;g<this.rollUpRows_;g++)this.displayed_[f-g]=this.displayed_[this.row_-g],this.displayed_[this.row_-g]={text:"",indent:0,offset:0};f===void 0&&(f=this.row_),this.topRow_=f-this.rollUpRows_+1},je.prototype.addFormatting=function(d,f){this.formatting_=this.formatting_.concat(f);var g=f.reduce(function(m,v){return m+"<"+v+">"},"");this[this.mode_](d,g)},je.prototype.clearFormatting=function(d){if(this.formatting_.length){var f=this.formatting_.reverse().reduce(function(g,m){return g+"</"+m+">"},"");this.formatting_=[],this[this.mode_](d,f)}},je.prototype.popOn=function(d,f){var g=this.nonDisplayed_[this.row_].text;g+=f,this.nonDisplayed_[this.row_].text=g},je.prototype.rollUp=function(d,f){var g=this.displayed_[this.row_].text;g+=f,this.displayed_[this.row_].text=g},je.prototype.shiftRowsUp_=function(){var d;for(d=0;d<this.topRow_;d++)this.displayed_[d]={text:"",indent:0,offset:0};for(d=this.row_+1;d<Mi+1;d++)this.displayed_[d]={text:"",indent:0,offset:0};for(d=this.topRow_;d<this.row_;d++)this.displayed_[d]=this.displayed_[d+1];this.displayed_[this.row_]={text:"",indent:0,offset:0}},je.prototype.paintOn=function(d,f){var g=this.displayed_[this.row_].text;g+=f,this.displayed_[this.row_].text=g};var gi={CaptionStream:Me,Cea608Stream:je,Cea708Stream:Ne},ps={H264_STREAM_TYPE:27,ADTS_STREAM_TYPE:15,METADATA_STREAM_TYPE:21},zs=t,Gs=8589934592,fo=4294967296,Tn="shared",ea=function(d,f){var g=1;for(d>f&&(g=-1);Math.abs(f-d)>fo;)d+=g*Gs;return d},_n=function(d){var f,g;_n.prototype.init.call(this),this.type_=d||Tn,this.push=function(m){if(m.type==="metadata"){this.trigger("data",m);return}this.type_!==Tn&&m.type!==this.type_||(g===void 0&&(g=m.dts),m.dts=ea(m.dts,g),m.pts=ea(m.pts,g),f=m.dts,this.trigger("data",m))},this.flush=function(){g=f,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){g=void 0,f=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};_n.prototype=new zs;var po={TimestampRolloverStream:_n,handleRollover:ea},bI=(d,f,g)=>{if(!d)return-1;for(var m=g;m<d.length;m++)if(d[m]===f)return m;return-1},TI={typedArrayIndexOf:bI},Rl=TI.typedArrayIndexOf,Ol={Utf8:3},$T=function(d,f,g){var m,v="";for(m=f;m<g;m++)v+="%"+("00"+d[m].toString(16)).slice(-2);return v},mo=function(d,f,g){return decodeURIComponent($T(d,f,g))},go=function(d,f,g){return unescape($T(d,f,g))},yo=function(d){return d[0]<<21|d[1]<<14|d[2]<<7|d[3]},vo={APIC:function(d){var f=1,g,m,v="-->";d.data[0]===Ol.Utf8&&(g=Rl(d.data,0,f),!(g<0)&&(d.mimeType=go(d.data,f,g),f=g+1,d.pictureType=d.data[f],f++,m=Rl(d.data,0,f),!(m<0)&&(d.description=mo(d.data,f,m),f=m+1,d.mimeType===v?d.url=go(d.data,f,d.data.length):d.pictureData=d.data.subarray(f,d.data.length))))},"T*":function(d){d.data[0]===Ol.Utf8&&(d.value=mo(d.data,1,d.data.length).replace(/\0*$/,""),d.values=d.value.split("\0"))},TXXX:function(d){var f;d.data[0]===Ol.Utf8&&(f=Rl(d.data,0,1),f!==-1&&(d.description=mo(d.data,1,f),d.value=mo(d.data,f+1,d.data.length).replace(/\0*$/,""),d.data=d.value))},"W*":function(d){d.url=go(d.data,0,d.data.length).replace(/\0.*$/,"")},WXXX:function(d){var f;d.data[0]===Ol.Utf8&&(f=Rl(d.data,0,1),f!==-1&&(d.description=mo(d.data,1,f),d.url=go(d.data,f+1,d.data.length).replace(/\0.*$/,"")))},PRIV:function(d){var f;for(f=0;f<d.data.length;f++)if(d.data[f]===0){d.owner=go(d.data,0,f);break}d.privateData=d.data.subarray(f+1),d.data=d.privateData}},_I=function(d){var f,g,m=10,v=0,T=[];if(!(d.length<10||d[0]!==73||d[1]!==68||d[2]!==51)){v=yo(d.subarray(6,10)),v+=10;var R=d[5]&64;R&&(m+=4,m+=yo(d.subarray(10,14)),v-=yo(d.subarray(16,20)));do{if(f=yo(d.subarray(m+4,m+8)),f<1)break;g=String.fromCharCode(d[m],d[m+1],d[m+2],d[m+3]);var M={id:g,data:d.subarray(m+10,m+f+10)};M.key=M.id,vo[M.id]?vo[M.id](M):M.id[0]==="T"?vo["T*"](M):M.id[0]==="W"&&vo["W*"](M),T.push(M),m+=10,m+=f}while(m<v);return T}},WT={parseId3Frames:_I,parseSyncSafeInteger:yo,frameParsers:vo},SI=t,CI=ps,ms=WT,Ml;Ml=function(d){var f={descriptor:d&&d.descriptor},g=0,m=[],v=0,T;if(Ml.prototype.init.call(this),this.dispatchType=CI.METADATA_STREAM_TYPE.toString(16),f.descriptor)for(T=0;T<f.descriptor.length;T++)this.dispatchType+=("00"+f.descriptor[T].toString(16)).slice(-2);this.push=function(R){var M,U,q,$,Z,pe;if(R.type==="timed-metadata"){if(R.dataAlignmentIndicator&&(v=0,m.length=0),m.length===0&&(R.data.length<10||R.data[0]!==73||R.data[1]!==68||R.data[2]!==51)){this.trigger("log",{level:"warn",message:"Skipping unrecognized metadata packet"});return}if(m.push(R),v+=R.data.byteLength,m.length===1&&(g=ms.parseSyncSafeInteger(R.data.subarray(6,10)),g+=10),!(v<g)){for(M={data:new Uint8Array(g),frames:[],pts:m[0].pts,dts:m[0].dts},Z=0;Z<g;)M.data.set(m[0].data.subarray(0,g-Z),Z),Z+=m[0].data.byteLength,v-=m[0].data.byteLength,m.shift();U=10,M.data[5]&64&&(U+=4,U+=ms.parseSyncSafeInteger(M.data.subarray(10,14)),g-=ms.parseSyncSafeInteger(M.data.subarray(16,20)));do{if(q=ms.parseSyncSafeInteger(M.data.subarray(U+4,U+8)),q<1){this.trigger("log",{level:"warn",message:"Malformed ID3 frame encountered. Skipping remaining metadata parsing."});break}if(pe=String.fromCharCode(M.data[U],M.data[U+1],M.data[U+2],M.data[U+3]),$={id:pe,data:M.data.subarray(U+10,U+q+10)},$.key=$.id,ms.frameParsers[$.id]?ms.frameParsers[$.id]($):$.id[0]==="T"?ms.frameParsers["T*"]($):$.id[0]==="W"&&ms.frameParsers["W*"]($),$.owner==="com.apple.streaming.transportStreamTimestamp"){var ne=$.data,ke=(ne[3]&1)<<30|ne[4]<<22|ne[5]<<14|ne[6]<<6|ne[7]>>>2;ke*=4,ke+=ne[7]&3,$.timeStamp=ke,M.pts===void 0&&M.dts===void 0&&(M.pts=$.timeStamp,M.dts=$.timeStamp),this.trigger("timestamp",$)}M.frames.push($),U+=10,U+=q}while(U<g);this.trigger("data",M)}}}},Ml.prototype=new SI;var kI=Ml,Df=t,Pf=gi,Xi=ps,EI=po.TimestampRolloverStream,Ll,bo,Nl,ta=188,If=71;Ll=function(){var d=new Uint8Array(ta),f=0;Ll.prototype.init.call(this),this.push=function(g){var m=0,v=ta,T;for(f?(T=new Uint8Array(g.byteLength+f),T.set(d.subarray(0,f)),T.set(g,f),f=0):T=g;v<T.byteLength;){if(T[m]===If&&T[v]===If){this.trigger("data",T.subarray(m,v)),m+=ta,v+=ta;continue}m++,v++}m<T.byteLength&&(d.set(T.subarray(m),0),f=T.byteLength-m)},this.flush=function(){f===ta&&d[0]===If&&(this.trigger("data",d),f=0),this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.reset=function(){f=0,this.trigger("reset")}},Ll.prototype=new Df,bo=function(){var d,f,g,m;bo.prototype.init.call(this),m=this,this.packetsWaitingForPmt=[],this.programMapTable=void 0,d=function(v,T){var R=0;T.payloadUnitStartIndicator&&(R+=v[R]+1),T.type==="pat"?f(v.subarray(R),T):g(v.subarray(R),T)},f=function(v,T){T.section_number=v[7],T.last_section_number=v[8],m.pmtPid=(v[10]&31)<<8|v[11],T.pmtPid=m.pmtPid},g=function(v,T){var R,M,U,q;if(v[5]&1){for(m.programMapTable={video:null,audio:null,"timed-metadata":{}},R=(v[1]&15)<<8|v[2],M=3+R-4,U=(v[10]&15)<<8|v[11],q=12+U;q<M;){var $=v[q],Z=(v[q+1]&31)<<8|v[q+2];$===Xi.H264_STREAM_TYPE&&m.programMapTable.video===null?m.programMapTable.video=Z:$===Xi.ADTS_STREAM_TYPE&&m.programMapTable.audio===null?m.programMapTable.audio=Z:$===Xi.METADATA_STREAM_TYPE&&(m.programMapTable["timed-metadata"][Z]=$),q+=((v[q+3]&15)<<8|v[q+4])+5}T.programMapTable=m.programMapTable}},this.push=function(v){var T={},R=4;if(T.payloadUnitStartIndicator=!!(v[1]&64),T.pid=v[1]&31,T.pid<<=8,T.pid|=v[2],(v[3]&48)>>>4>1&&(R+=v[R]+1),T.pid===0)T.type="pat",d(v.subarray(R),T),this.trigger("data",T);else if(T.pid===this.pmtPid)for(T.type="pmt",d(v.subarray(R),T),this.trigger("data",T);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else this.programMapTable===void 0?this.packetsWaitingForPmt.push([v,R,T]):this.processPes_(v,R,T)},this.processPes_=function(v,T,R){R.pid===this.programMapTable.video?R.streamType=Xi.H264_STREAM_TYPE:R.pid===this.programMapTable.audio?R.streamType=Xi.ADTS_STREAM_TYPE:R.streamType=this.programMapTable["timed-metadata"][R.pid],R.type="pes",R.data=v.subarray(T),this.trigger("data",R)}},bo.prototype=new Df,bo.STREAM_TYPES={h264:27,adts:15},Nl=function(){var d=this,f=!1,g={data:[],size:0},m={data:[],size:0},v={data:[],size:0},T,R=function(U,q){var $;const Z=U[0]<<16|U[1]<<8|U[2];q.data=new Uint8Array,Z===1&&(q.packetLength=6+(U[4]<<8|U[5]),q.dataAlignmentIndicator=(U[6]&4)!==0,$=U[7],$&192&&(q.pts=(U[9]&14)<<27|(U[10]&255)<<20|(U[11]&254)<<12|(U[12]&255)<<5|(U[13]&254)>>>3,q.pts*=4,q.pts+=(U[13]&6)>>>1,q.dts=q.pts,$&64&&(q.dts=(U[14]&14)<<27|(U[15]&255)<<20|(U[16]&254)<<12|(U[17]&255)<<5|(U[18]&254)>>>3,q.dts*=4,q.dts+=(U[18]&6)>>>1)),q.data=U.subarray(9+U[8]))},M=function(U,q,$){var Z=new Uint8Array(U.size),pe={type:q},ne=0,ke=0,Ie=!1,Lt;if(!(!U.data.length||U.size<9)){for(pe.trackId=U.data[0].pid,ne=0;ne<U.data.length;ne++)Lt=U.data[ne],Z.set(Lt.data,ke),ke+=Lt.data.byteLength;R(Z,pe),Ie=q==="video"||pe.packetLength<=U.size,($||Ie)&&(U.size=0,U.data.length=0),Ie&&d.trigger("data",pe)}};Nl.prototype.init.call(this),this.push=function(U){({pat:function(){},pes:function(){var q,$;switch(U.streamType){case Xi.H264_STREAM_TYPE:q=g,$="video";break;case Xi.ADTS_STREAM_TYPE:q=m,$="audio";break;case Xi.METADATA_STREAM_TYPE:q=v,$="timed-metadata";break;default:return}U.payloadUnitStartIndicator&&M(q,$,!0),q.data.push(U),q.size+=U.data.byteLength},pmt:function(){var q={type:"metadata",tracks:[]};T=U.programMapTable,T.video!==null&&q.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+T.video,codec:"avc",type:"video"}),T.audio!==null&&q.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+T.audio,codec:"adts",type:"audio"}),f=!0,d.trigger("data",q)}})[U.type]()},this.reset=function(){g.size=0,g.data.length=0,m.size=0,m.data.length=0,this.trigger("reset")},this.flushStreams_=function(){M(g,"video"),M(m,"audio"),M(v,"timed-metadata")},this.flush=function(){if(!f&&T){var U={type:"metadata",tracks:[]};T.video!==null&&U.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+T.video,codec:"avc",type:"video"}),T.audio!==null&&U.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+T.audio,codec:"adts",type:"audio"}),d.trigger("data",U)}f=!1,this.flushStreams_(),this.trigger("done")}},Nl.prototype=new Df;var zT={PAT_PID:0,MP2T_PACKET_LENGTH:ta,TransportPacketStream:Ll,TransportParseStream:bo,ElementaryStream:Nl,TimestampRolloverStream:EI,CaptionStream:Pf.CaptionStream,Cea608Stream:Pf.Cea608Stream,Cea708Stream:Pf.Cea708Stream,MetadataStream:kI};for(var Rf in Xi)Xi.hasOwnProperty(Rf)&&(zT[Rf]=Xi[Rf]);var xI=zT,wI=t,AI=Ke.ONE_SECOND_IN_TS,Fl,GT=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];Fl=function(d){var f,g=0;Fl.prototype.init.call(this),this.skipWarn_=function(m,v){this.trigger("log",{level:"warn",message:`adts skiping bytes ${m} to ${v} in frame ${g} outside syncword`})},this.push=function(m){var v=0,T,R,M,U,q;if(d||(g=0),m.type==="audio"){f&&f.length?(M=f,f=new Uint8Array(M.byteLength+m.data.byteLength),f.set(M),f.set(m.data,M.byteLength)):f=m.data;for(var $;v+7<f.length;){if(f[v]!==255||(f[v+1]&246)!==240){typeof $!="number"&&($=v),v++;continue}if(typeof $=="number"&&(this.skipWarn_($,v),$=null),R=(~f[v+1]&1)*2,T=(f[v+3]&3)<<11|f[v+4]<<3|(f[v+5]&224)>>5,U=((f[v+6]&3)+1)*1024,q=U*AI/GT[(f[v+2]&60)>>>2],f.byteLength-v<T)break;this.trigger("data",{pts:m.pts+g*q,dts:m.dts+g*q,sampleCount:U,audioobjecttype:(f[v+2]>>>6&3)+1,channelcount:(f[v+2]&1)<<2|(f[v+3]&192)>>>6,samplerate:GT[(f[v+2]&60)>>>2],samplingfrequencyindex:(f[v+2]&60)>>>2,samplesize:16,data:f.subarray(v+7+R,v+T)}),g++,v+=T}typeof $=="number"&&(this.skipWarn_($,v),$=null),f=f.subarray(v)}},this.flush=function(){g=0,this.trigger("done")},this.reset=function(){f=void 0,this.trigger("reset")},this.endTimeline=function(){f=void 0,this.trigger("endedtimeline")}},Fl.prototype=new wI;var DI=Fl,KT;KT=function(d){var f=d.byteLength,g=0,m=0;this.length=function(){return 8*f},this.bitsAvailable=function(){return 8*f+m},this.loadWord=function(){var v=d.byteLength-f,T=new Uint8Array(4),R=Math.min(4,f);if(R===0)throw new Error("no bytes available");T.set(d.subarray(v,v+R)),g=new DataView(T.buffer).getUint32(0),m=R*8,f-=R},this.skipBits=function(v){var T;m>v?(g<<=v,m-=v):(v-=m,T=Math.floor(v/8),v-=T*8,f-=T,this.loadWord(),g<<=v,m-=v)},this.readBits=function(v){var T=Math.min(m,v),R=g>>>32-T;return m-=T,m>0?g<<=T:f>0&&this.loadWord(),T=v-T,T>0?R<<T|this.readBits(T):R},this.skipLeadingZeros=function(){var v;for(v=0;v<m;++v)if((g&2147483648>>>v)!==0)return g<<=v,m-=v,v;return this.loadWord(),v+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var v=this.skipLeadingZeros();return this.readBits(v+1)-1},this.readExpGolomb=function(){var v=this.readUnsignedExpGolomb();return 1&v?1+v>>>1:-1*(v>>>1)},this.readBoolean=function(){return this.readBits(1)===1},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};var PI=KT,XT=t,II=PI,Ul,Bl,YT;Bl=function(){var d=0,f,g;Bl.prototype.init.call(this),this.push=function(m){var v;g?(v=new Uint8Array(g.byteLength+m.data.byteLength),v.set(g),v.set(m.data,g.byteLength),g=v):g=m.data;for(var T=g.byteLength;d<T-3;d++)if(g[d+2]===1){f=d+5;break}for(;f<T;)switch(g[f]){case 0:if(g[f-1]!==0){f+=2;break}else if(g[f-2]!==0){f++;break}d+3!==f-2&&this.trigger("data",g.subarray(d+3,f-2));do f++;while(g[f]!==1&&f<T);d=f-2,f+=3;break;case 1:if(g[f-1]!==0||g[f-2]!==0){f+=3;break}this.trigger("data",g.subarray(d+3,f-2)),d=f-2,f+=3;break;default:f+=3;break}g=g.subarray(d),f-=d,d=0},this.reset=function(){g=null,d=0,this.trigger("reset")},this.flush=function(){g&&g.byteLength>3&&this.trigger("data",g.subarray(d+3)),g=null,d=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}},Bl.prototype=new XT,YT={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},Ul=function(){var d=new Bl,f,g,m,v,T,R,M;Ul.prototype.init.call(this),f=this,this.push=function(U){U.type==="video"&&(g=U.trackId,m=U.pts,v=U.dts,d.push(U))},d.on("data",function(U){var q={trackId:g,pts:m,dts:v,data:U,nalUnitTypeCode:U[0]&31};switch(q.nalUnitTypeCode){case 5:q.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:q.nalUnitType="sei_rbsp",q.escapedRBSP=T(U.subarray(1));break;case 7:q.nalUnitType="seq_parameter_set_rbsp",q.escapedRBSP=T(U.subarray(1)),q.config=R(q.escapedRBSP);break;case 8:q.nalUnitType="pic_parameter_set_rbsp";break;case 9:q.nalUnitType="access_unit_delimiter_rbsp";break}f.trigger("data",q)}),d.on("done",function(){f.trigger("done")}),d.on("partialdone",function(){f.trigger("partialdone")}),d.on("reset",function(){f.trigger("reset")}),d.on("endedtimeline",function(){f.trigger("endedtimeline")}),this.flush=function(){d.flush()},this.partialFlush=function(){d.partialFlush()},this.reset=function(){d.reset()},this.endTimeline=function(){d.endTimeline()},M=function(U,q){var $=8,Z=8,pe,ne;for(pe=0;pe<U;pe++)Z!==0&&(ne=q.readExpGolomb(),Z=($+ne+256)%256),$=Z===0?$:Z},T=function(U){for(var q=U.byteLength,$=[],Z=1,pe,ne;Z<q-2;)U[Z]===0&&U[Z+1]===0&&U[Z+2]===3?($.push(Z+2),Z+=2):Z++;if($.length===0)return U;pe=q-$.length,ne=new Uint8Array(pe);var ke=0;for(Z=0;Z<pe;ke++,Z++)ke===$[0]&&(ke++,$.shift()),ne[Z]=U[ke];return ne},R=function(U){var q=0,$=0,Z=0,pe=0,ne,ke,Ie,Lt,Ci,ys,xo,wo,Ao,Do,Ql,it=[1,1],Po,Qi;if(ne=new II(U),ke=ne.readUnsignedByte(),Lt=ne.readUnsignedByte(),Ie=ne.readUnsignedByte(),ne.skipUnsignedExpGolomb(),YT[ke]&&(Ci=ne.readUnsignedExpGolomb(),Ci===3&&ne.skipBits(1),ne.skipUnsignedExpGolomb(),ne.skipUnsignedExpGolomb(),ne.skipBits(1),ne.readBoolean()))for(Ql=Ci!==3?8:12,Qi=0;Qi<Ql;Qi++)ne.readBoolean()&&(Qi<6?M(16,ne):M(64,ne));if(ne.skipUnsignedExpGolomb(),ys=ne.readUnsignedExpGolomb(),ys===0)ne.readUnsignedExpGolomb();else if(ys===1)for(ne.skipBits(1),ne.skipExpGolomb(),ne.skipExpGolomb(),xo=ne.readUnsignedExpGolomb(),Qi=0;Qi<xo;Qi++)ne.skipExpGolomb();if(ne.skipUnsignedExpGolomb(),ne.skipBits(1),wo=ne.readUnsignedExpGolomb(),Ao=ne.readUnsignedExpGolomb(),Do=ne.readBits(1),Do===0&&ne.skipBits(1),ne.skipBits(1),ne.readBoolean()&&(q=ne.readUnsignedExpGolomb(),$=ne.readUnsignedExpGolomb(),Z=ne.readUnsignedExpGolomb(),pe=ne.readUnsignedExpGolomb()),ne.readBoolean()&&ne.readBoolean()){switch(Po=ne.readUnsignedByte(),Po){case 1:it=[1,1];break;case 2:it=[12,11];break;case 3:it=[10,11];break;case 4:it=[16,11];break;case 5:it=[40,33];break;case 6:it=[24,11];break;case 7:it=[20,11];break;case 8:it=[32,11];break;case 9:it=[80,33];break;case 10:it=[18,11];break;case 11:it=[15,11];break;case 12:it=[64,33];break;case 13:it=[160,99];break;case 14:it=[4,3];break;case 15:it=[3,2];break;case 16:it=[2,1];break;case 255:{it=[ne.readUnsignedByte()<<8|ne.readUnsignedByte(),ne.readUnsignedByte()<<8|ne.readUnsignedByte()];break}}it&&it[0]/it[1]}return{profileIdc:ke,levelIdc:Ie,profileCompatibility:Lt,width:(wo+1)*16-q*2-$*2,height:(2-Do)*(Ao+1)*16-Z*2-pe*2,sarRatio:it}}},Ul.prototype=new XT;var RI={H264Stream:Ul},OI=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],QT=function(d,f){var g=d[f+6]<<21|d[f+7]<<14|d[f+8]<<7|d[f+9],m=d[f+5],v=(m&16)>>4;return g=g>=0?g:0,v?g+20:g+10},JT=function(d,f){return d.length-f<10||d[f]!==73||d[f+1]!==68||d[f+2]!==51?f:(f+=QT(d,f),JT(d,f))},MI=function(d){var f=JT(d,0);return d.length>=f+2&&(d[f]&255)===255&&(d[f+1]&240)===240&&(d[f+1]&22)===16},ZT=function(d){return d[0]<<21|d[1]<<14|d[2]<<7|d[3]},LI=function(d,f,g){var m,v="";for(m=f;m<g;m++)v+="%"+("00"+d[m].toString(16)).slice(-2);return v},NI=function(d,f,g){return unescape(LI(d,f,g))},FI=function(d,f){var g=(d[f+5]&224)>>5,m=d[f+4]<<3,v=d[f+3]&6144;return v|m|g},UI=function(d,f){return d[f]===73&&d[f+1]===68&&d[f+2]===51?"timed-metadata":d[f]&!0&&(d[f+1]&240)===240?"audio":null},BI=function(d){for(var f=0;f+5<d.length;){if(d[f]!==255||(d[f+1]&246)!==240){f++;continue}return OI[(d[f+2]&60)>>>2]}return null},qI=function(d){var f,g,m,v;f=10,d[5]&64&&(f+=4,f+=ZT(d.subarray(10,14)));do{if(g=ZT(d.subarray(f+4,f+8)),g<1)return null;if(v=String.fromCharCode(d[f],d[f+1],d[f+2],d[f+3]),v==="PRIV"){m=d.subarray(f+10,f+g+10);for(var T=0;T<m.byteLength;T++)if(m[T]===0){var R=NI(m,0,T);if(R==="com.apple.streaming.transportStreamTimestamp"){var M=m.subarray(T+1),U=(M[3]&1)<<30|M[4]<<22|M[5]<<14|M[6]<<6|M[7]>>>2;return U*=4,U+=M[7]&3,U}break}}f+=10,f+=g}while(f<d.byteLength);return null},Of={isLikelyAacData:MI,parseId3TagSize:QT,parseAdtsSize:FI,parseType:UI,parseSampleRate:BI,parseAacTimestamp:qI},VI=t,e_=Of,ql;ql=function(){var d=new Uint8Array,f=0;ql.prototype.init.call(this),this.setTimestamp=function(g){f=g},this.push=function(g){var m=0,v=0,T,R,M,U;for(d.length?(U=d.length,d=new Uint8Array(g.byteLength+U),d.set(d.subarray(0,U)),d.set(g,U)):d=g;d.length-v>=3;){if(d[v]===73&&d[v+1]===68&&d[v+2]===51){if(d.length-v<10||(m=e_.parseId3TagSize(d,v),v+m>d.length))break;R={type:"timed-metadata",data:d.subarray(v,v+m)},this.trigger("data",R),v+=m;continue}else if((d[v]&255)===255&&(d[v+1]&240)===240){if(d.length-v<7||(m=e_.parseAdtsSize(d,v),v+m>d.length))break;M={type:"audio",data:d.subarray(v,v+m),pts:f,dts:f},this.trigger("data",M),v+=m;continue}v++}T=d.length-v,T>0?d=d.subarray(v):d=new Uint8Array},this.reset=function(){d=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){d=new Uint8Array,this.trigger("endedtimeline")}},ql.prototype=new VI;var jI=ql,HI=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],$I=HI,WI=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],zI=WI,Vl=t,To=qe,_o=ii,jl=Al,Yi=Af,$n=xI,Hl=Ke,t_=DI,GI=RI.H264Stream,KI=jI,XI=Of.isLikelyAacData,YI=Ke.ONE_SECOND_IN_TS,i_=$I,n_=zI,$l,So,Wl,Ks,QI=function(d,f){f.stream=d,this.trigger("log",f)},s_=function(d,f){for(var g=Object.keys(f),m=0;m<g.length;m++){var v=g[m];v==="headOfPipeline"||!f[v].on||f[v].on("log",QI.bind(d,v))}},r_=function(d,f){var g;if(d.length!==f.length)return!1;for(g=0;g<d.length;g++)if(d[g]!==f[g])return!1;return!0},a_=function(d,f,g,m,v,T){var R=g-f,M=m-f,U=v-g;return{start:{dts:d,pts:d+R},end:{dts:d+M,pts:d+U},prependedContentDuration:T,baseMediaDecodeTime:d}};So=function(d,f){var g=[],m,v=0,T=0,R=1/0;f=f||{},m=f.firstSequenceNumber||0,So.prototype.init.call(this),this.push=function(M){Yi.collectDtsInfo(d,M),d&&i_.forEach(function(U){d[U]=M[U]}),g.push(M)},this.setEarliestDts=function(M){v=M},this.setVideoBaseMediaDecodeTime=function(M){R=M},this.setAudioAppendStart=function(M){T=M},this.flush=function(){var M,U,q,$,Z,pe,ne;if(g.length===0){this.trigger("done","AudioSegmentStream");return}M=jl.trimAdtsFramesByEarliestDts(g,d,v),d.baseMediaDecodeTime=Yi.calculateTrackBaseMediaDecodeTime(d,f.keepOriginalTimestamps),ne=jl.prefixWithSilence(d,M,T,R),d.samples=jl.generateSampleTable(M),q=To.mdat(jl.concatenateFrameData(M)),g=[],U=To.moof(m,[d]),$=new Uint8Array(U.byteLength+q.byteLength),m++,$.set(U),$.set(q,U.byteLength),Yi.clearDtsInfo(d),Z=Math.ceil(YI*1024/d.samplerate),M.length&&(pe=M.length*Z,this.trigger("segmentTimingInfo",a_(Hl.audioTsToVideoTs(d.baseMediaDecodeTime,d.samplerate),M[0].dts,M[0].pts,M[0].dts+pe,M[0].pts+pe,ne||0)),this.trigger("timingInfo",{start:M[0].pts,end:M[0].pts+pe})),this.trigger("data",{track:d,boxes:$}),this.trigger("done","AudioSegmentStream")},this.reset=function(){Yi.clearDtsInfo(d),g=[],this.trigger("reset")}},So.prototype=new Vl,$l=function(d,f){var g,m=[],v=[],T,R;f=f||{},g=f.firstSequenceNumber||0,$l.prototype.init.call(this),delete d.minPTS,this.gopCache_=[],this.push=function(M){Yi.collectDtsInfo(d,M),M.nalUnitType==="seq_parameter_set_rbsp"&&!T&&(T=M.config,d.sps=[M.data],n_.forEach(function(U){d[U]=T[U]},this)),M.nalUnitType==="pic_parameter_set_rbsp"&&!R&&(R=M.data,d.pps=[M.data]),m.push(M)},this.flush=function(){for(var M,U,q,$,Z,pe,ne=0,ke,Ie;m.length&&m[0].nalUnitType!=="access_unit_delimiter_rbsp";)m.shift();if(m.length===0){this.resetStream_(),this.trigger("done","VideoSegmentStream");return}if(M=_o.groupNalsIntoFrames(m),q=_o.groupFramesIntoGops(M),q[0][0].keyFrame||(U=this.getGopForFusion_(m[0],d),U?(ne=U.duration,q.unshift(U),q.byteLength+=U.byteLength,q.nalCount+=U.nalCount,q.pts=U.pts,q.dts=U.dts,q.duration+=U.duration):q=_o.extendFirstKeyFrame(q)),v.length){var Lt;if(f.alignGopsAtEnd?Lt=this.alignGopsAtEnd_(q):Lt=this.alignGopsAtStart_(q),!Lt){this.gopCache_.unshift({gop:q.pop(),pps:d.pps,sps:d.sps}),this.gopCache_.length=Math.min(6,this.gopCache_.length),m=[],this.resetStream_(),this.trigger("done","VideoSegmentStream");return}Yi.clearDtsInfo(d),q=Lt}Yi.collectDtsInfo(d,q),d.samples=_o.generateSampleTable(q),Z=To.mdat(_o.concatenateNalData(q)),d.baseMediaDecodeTime=Yi.calculateTrackBaseMediaDecodeTime(d,f.keepOriginalTimestamps),this.trigger("processedGopsInfo",q.map(function(Ci){return{pts:Ci.pts,dts:Ci.dts,byteLength:Ci.byteLength}})),ke=q[0],Ie=q[q.length-1],this.trigger("segmentTimingInfo",a_(d.baseMediaDecodeTime,ke.dts,ke.pts,Ie.dts+Ie.duration,Ie.pts+Ie.duration,ne)),this.trigger("timingInfo",{start:q[0].pts,end:q[q.length-1].pts+q[q.length-1].duration}),this.gopCache_.unshift({gop:q.pop(),pps:d.pps,sps:d.sps}),this.gopCache_.length=Math.min(6,this.gopCache_.length),m=[],this.trigger("baseMediaDecodeTime",d.baseMediaDecodeTime),this.trigger("timelineStartInfo",d.timelineStartInfo),$=To.moof(g,[d]),pe=new Uint8Array($.byteLength+Z.byteLength),g++,pe.set($),pe.set(Z,$.byteLength),this.trigger("data",{track:d,boxes:pe}),this.resetStream_(),this.trigger("done","VideoSegmentStream")},this.reset=function(){this.resetStream_(),m=[],this.gopCache_.length=0,v.length=0,this.trigger("reset")},this.resetStream_=function(){Yi.clearDtsInfo(d),T=void 0,R=void 0},this.getGopForFusion_=function(M){var U=45e3,q=1/0,$,Z,pe,ne,ke;for(ke=0;ke<this.gopCache_.length;ke++)ne=this.gopCache_[ke],pe=ne.gop,!(!(d.pps&&r_(d.pps[0],ne.pps[0]))||!(d.sps&&r_(d.sps[0],ne.sps[0])))&&(pe.dts<d.timelineStartInfo.dts||($=M.dts-pe.dts-pe.duration,$>=-1e4&&$<=U&&(!Z||q>$)&&(Z=ne,q=$)));return Z?Z.gop:null},this.alignGopsAtStart_=function(M){var U,q,$,Z,pe,ne,ke,Ie;for(pe=M.byteLength,ne=M.nalCount,ke=M.duration,U=q=0;U<v.length&&q<M.length&&($=v[U],Z=M[q],$.pts!==Z.pts);){if(Z.pts>$.pts){U++;continue}q++,pe-=Z.byteLength,ne-=Z.nalCount,ke-=Z.duration}return q===0?M:q===M.length?null:(Ie=M.slice(q),Ie.byteLength=pe,Ie.duration=ke,Ie.nalCount=ne,Ie.pts=Ie[0].pts,Ie.dts=Ie[0].dts,Ie)},this.alignGopsAtEnd_=function(M){var U,q,$,Z,pe,ne;for(U=v.length-1,q=M.length-1,pe=null,ne=!1;U>=0&&q>=0;){if($=v[U],Z=M[q],$.pts===Z.pts){ne=!0;break}if($.pts>Z.pts){U--;continue}U===v.length-1&&(pe=q),q--}if(!ne&&pe===null)return null;var ke;if(ne?ke=q:ke=pe,ke===0)return M;var Ie=M.slice(ke),Lt=Ie.reduce(function(Ci,ys){return Ci.byteLength+=ys.byteLength,Ci.duration+=ys.duration,Ci.nalCount+=ys.nalCount,Ci},{byteLength:0,duration:0,nalCount:0});return Ie.byteLength=Lt.byteLength,Ie.duration=Lt.duration,Ie.nalCount=Lt.nalCount,Ie.pts=Ie[0].pts,Ie.dts=Ie[0].dts,Ie},this.alignGopsWith=function(M){v=M}},$l.prototype=new Vl,Ks=function(d,f){this.numberOfTracks=0,this.metadataStream=f,d=d||{},typeof d.remux<"u"?this.remuxTracks=!!d.remux:this.remuxTracks=!0,typeof d.keepOriginalTimestamps=="boolean"?this.keepOriginalTimestamps=d.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,Ks.prototype.init.call(this),this.push=function(g){if(g.content||g.text)return this.pendingCaptions.push(g);if(g.frames)return this.pendingMetadata.push(g);this.pendingTracks.push(g.track),this.pendingBytes+=g.boxes.byteLength,g.track.type==="video"&&(this.videoTrack=g.track,this.pendingBoxes.push(g.boxes)),g.track.type==="audio"&&(this.audioTrack=g.track,this.pendingBoxes.unshift(g.boxes))}},Ks.prototype=new Vl,Ks.prototype.flush=function(d){var f=0,g={captions:[],captionStreams:{},metadata:[],info:{}},m,v,T,R=0,M;if(this.pendingTracks.length<this.numberOfTracks){if(d!=="VideoSegmentStream"&&d!=="AudioSegmentStream")return;if(this.remuxTracks)return;if(this.pendingTracks.length===0){this.emittedTracks++,this.emittedTracks>=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0);return}}if(this.videoTrack?(R=this.videoTrack.timelineStartInfo.pts,n_.forEach(function(U){g.info[U]=this.videoTrack[U]},this)):this.audioTrack&&(R=this.audioTrack.timelineStartInfo.pts,i_.forEach(function(U){g.info[U]=this.audioTrack[U]},this)),this.videoTrack||this.audioTrack){for(this.pendingTracks.length===1?g.type=this.pendingTracks[0].type:g.type="combined",this.emittedTracks+=this.pendingTracks.length,T=To.initSegment(this.pendingTracks),g.initSegment=new Uint8Array(T.byteLength),g.initSegment.set(T),g.data=new Uint8Array(this.pendingBytes),M=0;M<this.pendingBoxes.length;M++)g.data.set(this.pendingBoxes[M],f),f+=this.pendingBoxes[M].byteLength;for(M=0;M<this.pendingCaptions.length;M++)m=this.pendingCaptions[M],m.startTime=Hl.metadataTsToSeconds(m.startPts,R,this.keepOriginalTimestamps),m.endTime=Hl.metadataTsToSeconds(m.endPts,R,this.keepOriginalTimestamps),g.captionStreams[m.stream]=!0,g.captions.push(m);for(M=0;M<this.pendingMetadata.length;M++)v=this.pendingMetadata[M],v.cueTime=Hl.metadataTsToSeconds(v.pts,R,this.keepOriginalTimestamps),g.metadata.push(v);for(g.metadata.dispatchType=this.metadataStream.dispatchType,this.pendingTracks.length=0,this.videoTrack=null,this.pendingBoxes.length=0,this.pendingCaptions.length=0,this.pendingBytes=0,this.pendingMetadata.length=0,this.trigger("data",g),M=0;M<g.captions.length;M++)m=g.captions[M],this.trigger("caption",m);for(M=0;M<g.metadata.length;M++)v=g.metadata[M],this.trigger("id3Frame",v)}this.emittedTracks>=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},Ks.prototype.setRemux=function(d){this.remuxTracks=d},Wl=function(d){var f=this,g=!0,m,v;Wl.prototype.init.call(this),d=d||{},this.baseMediaDecodeTime=d.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var T={};this.transmuxPipeline_=T,T.type="aac",T.metadataStream=new $n.MetadataStream,T.aacStream=new KI,T.audioTimestampRolloverStream=new $n.TimestampRolloverStream("audio"),T.timedMetadataTimestampRolloverStream=new $n.TimestampRolloverStream("timed-metadata"),T.adtsStream=new t_,T.coalesceStream=new Ks(d,T.metadataStream),T.headOfPipeline=T.aacStream,T.aacStream.pipe(T.audioTimestampRolloverStream).pipe(T.adtsStream),T.aacStream.pipe(T.timedMetadataTimestampRolloverStream).pipe(T.metadataStream).pipe(T.coalesceStream),T.metadataStream.on("timestamp",function(R){T.aacStream.setTimestamp(R.timeStamp)}),T.aacStream.on("data",function(R){R.type!=="timed-metadata"&&R.type!=="audio"||T.audioSegmentStream||(v=v||{timelineStartInfo:{baseMediaDecodeTime:f.baseMediaDecodeTime},codec:"adts",type:"audio"},T.coalesceStream.numberOfTracks++,T.audioSegmentStream=new So(v,d),T.audioSegmentStream.on("log",f.getLogTrigger_("audioSegmentStream")),T.audioSegmentStream.on("timingInfo",f.trigger.bind(f,"audioTimingInfo")),T.adtsStream.pipe(T.audioSegmentStream).pipe(T.coalesceStream),f.trigger("trackinfo",{hasAudio:!!v,hasVideo:!!m}))}),T.coalesceStream.on("data",this.trigger.bind(this,"data")),T.coalesceStream.on("done",this.trigger.bind(this,"done")),s_(this,T)},this.setupTsPipeline=function(){var T={};this.transmuxPipeline_=T,T.type="ts",T.metadataStream=new $n.MetadataStream,T.packetStream=new $n.TransportPacketStream,T.parseStream=new $n.TransportParseStream,T.elementaryStream=new $n.ElementaryStream,T.timestampRolloverStream=new $n.TimestampRolloverStream,T.adtsStream=new t_,T.h264Stream=new GI,T.captionStream=new $n.CaptionStream(d),T.coalesceStream=new Ks(d,T.metadataStream),T.headOfPipeline=T.packetStream,T.packetStream.pipe(T.parseStream).pipe(T.elementaryStream).pipe(T.timestampRolloverStream),T.timestampRolloverStream.pipe(T.h264Stream),T.timestampRolloverStream.pipe(T.adtsStream),T.timestampRolloverStream.pipe(T.metadataStream).pipe(T.coalesceStream),T.h264Stream.pipe(T.captionStream).pipe(T.coalesceStream),T.elementaryStream.on("data",function(R){var M;if(R.type==="metadata"){for(M=R.tracks.length;M--;)!m&&R.tracks[M].type==="video"?(m=R.tracks[M],m.timelineStartInfo.baseMediaDecodeTime=f.baseMediaDecodeTime):!v&&R.tracks[M].type==="audio"&&(v=R.tracks[M],v.timelineStartInfo.baseMediaDecodeTime=f.baseMediaDecodeTime);m&&!T.videoSegmentStream&&(T.coalesceStream.numberOfTracks++,T.videoSegmentStream=new $l(m,d),T.videoSegmentStream.on("log",f.getLogTrigger_("videoSegmentStream")),T.videoSegmentStream.on("timelineStartInfo",function(U){v&&!d.keepOriginalTimestamps&&(v.timelineStartInfo=U,T.audioSegmentStream.setEarliestDts(U.dts-f.baseMediaDecodeTime))}),T.videoSegmentStream.on("processedGopsInfo",f.trigger.bind(f,"gopInfo")),T.videoSegmentStream.on("segmentTimingInfo",f.trigger.bind(f,"videoSegmentTimingInfo")),T.videoSegmentStream.on("baseMediaDecodeTime",function(U){v&&T.audioSegmentStream.setVideoBaseMediaDecodeTime(U)}),T.videoSegmentStream.on("timingInfo",f.trigger.bind(f,"videoTimingInfo")),T.h264Stream.pipe(T.videoSegmentStream).pipe(T.coalesceStream)),v&&!T.audioSegmentStream&&(T.coalesceStream.numberOfTracks++,T.audioSegmentStream=new So(v,d),T.audioSegmentStream.on("log",f.getLogTrigger_("audioSegmentStream")),T.audioSegmentStream.on("timingInfo",f.trigger.bind(f,"audioTimingInfo")),T.audioSegmentStream.on("segmentTimingInfo",f.trigger.bind(f,"audioSegmentTimingInfo")),T.adtsStream.pipe(T.audioSegmentStream).pipe(T.coalesceStream)),f.trigger("trackinfo",{hasAudio:!!v,hasVideo:!!m})}}),T.coalesceStream.on("data",this.trigger.bind(this,"data")),T.coalesceStream.on("id3Frame",function(R){R.dispatchType=T.metadataStream.dispatchType,f.trigger("id3Frame",R)}),T.coalesceStream.on("caption",this.trigger.bind(this,"caption")),T.coalesceStream.on("done",this.trigger.bind(this,"done")),s_(this,T)},this.setBaseMediaDecodeTime=function(T){var R=this.transmuxPipeline_;d.keepOriginalTimestamps||(this.baseMediaDecodeTime=T),v&&(v.timelineStartInfo.dts=void 0,v.timelineStartInfo.pts=void 0,Yi.clearDtsInfo(v),R.audioTimestampRolloverStream&&R.audioTimestampRolloverStream.discontinuity()),m&&(R.videoSegmentStream&&(R.videoSegmentStream.gopCache_=[]),m.timelineStartInfo.dts=void 0,m.timelineStartInfo.pts=void 0,Yi.clearDtsInfo(m),R.captionStream.reset()),R.timestampRolloverStream&&R.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(T){v&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(T)},this.setRemux=function(T){var R=this.transmuxPipeline_;d.remux=T,R&&R.coalesceStream&&R.coalesceStream.setRemux(T)},this.alignGopsWith=function(T){m&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(T)},this.getLogTrigger_=function(T){var R=this;return function(M){M.stream=T,R.trigger("log",M)}},this.push=function(T){if(g){var R=XI(T);R&&this.transmuxPipeline_.type!=="aac"?this.setupAacPipeline():!R&&this.transmuxPipeline_.type!=="ts"&&this.setupTsPipeline(),g=!1}this.transmuxPipeline_.headOfPipeline.push(T)},this.flush=function(){g=!0,this.transmuxPipeline_.headOfPipeline.flush()},this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline()},this.reset=function(){this.transmuxPipeline_.headOfPipeline&&this.transmuxPipeline_.headOfPipeline.reset()},this.resetCaptions=function(){this.transmuxPipeline_.captionStream&&this.transmuxPipeline_.captionStream.reset()}},Wl.prototype=new Vl;var JI={Transmuxer:Wl},ZI=function(d){return d>>>0},eR=function(d){return("00"+d.toString(16)).slice(-2)},zl={toUnsigned:ZI,toHexString:eR},tR=function(d){var f="";return f+=String.fromCharCode(d[0]),f+=String.fromCharCode(d[1]),f+=String.fromCharCode(d[2]),f+=String.fromCharCode(d[3]),f},o_=tR,iR=zl.toUnsigned,nR=o_,c_=function(d,f){var g=[],m,v,T,R,M;if(!f.length)return null;for(m=0;m<d.byteLength;)v=iR(d[m]<<24|d[m+1]<<16|d[m+2]<<8|d[m+3]),T=nR(d.subarray(m+4,m+8)),R=v>1?m+v:d.byteLength,T===f[0]&&(f.length===1?g.push(d.subarray(m+8,R)):(M=c_(d.subarray(m+8,R),f.slice(1)),M.length&&(g=g.concat(M)))),m=R;return g},Mf=c_,sR=zl.toUnsigned,rR=r.getUint64,aR=function(d){var f={version:d[0],flags:new Uint8Array(d.subarray(1,4))};return f.version===1?f.baseMediaDecodeTime=rR(d.subarray(4)):f.baseMediaDecodeTime=sR(d[4]<<24|d[5]<<16|d[6]<<8|d[7]),f},Lf=aR,oR=function(d){var f=new DataView(d.buffer,d.byteOffset,d.byteLength),g={version:d[0],flags:new Uint8Array(d.subarray(1,4)),trackId:f.getUint32(4)},m=g.flags[2]&1,v=g.flags[2]&2,T=g.flags[2]&8,R=g.flags[2]&16,M=g.flags[2]&32,U=g.flags[0]&65536,q=g.flags[0]&131072,$;return $=8,m&&($+=4,g.baseDataOffset=f.getUint32(12),$+=4),v&&(g.sampleDescriptionIndex=f.getUint32($),$+=4),T&&(g.defaultSampleDuration=f.getUint32($),$+=4),R&&(g.defaultSampleSize=f.getUint32($),$+=4),M&&(g.defaultSampleFlags=f.getUint32($)),U&&(g.durationIsEmpty=!0),!m&&q&&(g.baseDataOffsetIsMoof=!0),g},l_=oR,cR=function(d){return{isLeading:(d[0]&12)>>>2,dependsOn:d[0]&3,isDependedOn:(d[1]&192)>>>6,hasRedundancy:(d[1]&48)>>>4,paddingValue:(d[1]&14)>>>1,isNonSyncSample:d[1]&1,degradationPriority:d[2]<<8|d[3]}},lR=cR,u_=lR,uR=function(d){var f={version:d[0],flags:new Uint8Array(d.subarray(1,4)),samples:[]},g=new DataView(d.buffer,d.byteOffset,d.byteLength),m=f.flags[2]&1,v=f.flags[2]&4,T=f.flags[1]&1,R=f.flags[1]&2,M=f.flags[1]&4,U=f.flags[1]&8,q=g.getUint32(4),$=8,Z;for(m&&(f.dataOffset=g.getInt32($),$+=4),v&&q&&(Z={flags:u_(d.subarray($,$+4))},$+=4,T&&(Z.duration=g.getUint32($),$+=4),R&&(Z.size=g.getUint32($),$+=4),U&&(f.version===1?Z.compositionTimeOffset=g.getInt32($):Z.compositionTimeOffset=g.getUint32($),$+=4),f.samples.push(Z),q--);q--;)Z={},T&&(Z.duration=g.getUint32($),$+=4),R&&(Z.size=g.getUint32($),$+=4),M&&(Z.flags=u_(d.subarray($,$+4)),$+=4),U&&(f.version===1?Z.compositionTimeOffset=g.getInt32($):Z.compositionTimeOffset=g.getUint32($),$+=4),f.samples.push(Z);return f},d_=uR,h_={tfdt:Lf,trun:d_},f_={parseTfdt:h_.tfdt,parseTrun:h_.trun},dR=function(d){for(var f=0,g=String.fromCharCode(d[f]),m="";g!=="\0";)m+=g,f++,g=String.fromCharCode(d[f]);return m+=g,m},hR={uint8ToCString:dR},Gl=hR.uint8ToCString,fR=r.getUint64,pR=function(d){var f=4,g=d[0],m,v,T,R,M,U,q,$;if(g===0){m=Gl(d.subarray(f)),f+=m.length,v=Gl(d.subarray(f)),f+=v.length;var Z=new DataView(d.buffer);T=Z.getUint32(f),f+=4,M=Z.getUint32(f),f+=4,U=Z.getUint32(f),f+=4,q=Z.getUint32(f),f+=4}else if(g===1){var Z=new DataView(d.buffer);T=Z.getUint32(f),f+=4,R=fR(d.subarray(f)),f+=8,U=Z.getUint32(f),f+=4,q=Z.getUint32(f),f+=4,m=Gl(d.subarray(f)),f+=m.length,v=Gl(d.subarray(f)),f+=v.length}$=new Uint8Array(d.subarray(f,d.byteLength));var pe={scheme_id_uri:m,value:v,timescale:T||1,presentation_time:R,presentation_time_delta:M,event_duration:U,id:q,message_data:$};return gR(g,pe)?pe:void 0},mR=function(d,f,g,m){return d||d===0?d/f:m+g/f},gR=function(d,f){var g=f.scheme_id_uri!=="\0",m=d===0&&p_(f.presentation_time_delta)&&g,v=d===1&&p_(f.presentation_time)&&g;return!(d>1)&&m||v},p_=function(d){return d!==void 0||d!==null},yR={parseEmsgBox:pR,scaleTime:mR},Co;typeof window<"u"?Co=window:typeof n<"u"?Co=n:typeof self<"u"?Co=self:Co={};var m_=Co,Kl=zl.toUnsigned,ko=zl.toHexString,Tt=Mf,ia=o_,Nf=yR,vR=l_,bR=d_,TR=Lf,_R=r.getUint64,g_,y_,v_,b_,T_,Ff,__,Uf=m_,SR=WT.parseId3Frames;g_=function(d){var f={},g=Tt(d,["moov","trak"]);return g.reduce(function(m,v){var T,R,M,U,q;return T=Tt(v,["tkhd"])[0],!T||(R=T[0],M=R===0?12:20,U=Kl(T[M]<<24|T[M+1]<<16|T[M+2]<<8|T[M+3]),q=Tt(v,["mdia","mdhd"])[0],!q)?null:(R=q[0],M=R===0?12:20,m[U]=Kl(q[M]<<24|q[M+1]<<16|q[M+2]<<8|q[M+3]),m)},f)},y_=function(d,f){var g;g=Tt(f,["moof","traf"]);var m=g.reduce(function(v,T){var R=Tt(T,["tfhd"])[0],M=Kl(R[4]<<24|R[5]<<16|R[6]<<8|R[7]),U=d[M]||9e4,q=Tt(T,["tfdt"])[0],$=new DataView(q.buffer,q.byteOffset,q.byteLength),Z;q[0]===1?Z=_R(q.subarray(4,12)):Z=$.getUint32(4);let pe;return typeof Z=="bigint"?pe=Z/Uf.BigInt(U):typeof Z=="number"&&!isNaN(Z)&&(pe=Z/U),pe<Number.MAX_SAFE_INTEGER&&(pe=Number(pe)),pe<v&&(v=pe),v},1/0);return typeof m=="bigint"||isFinite(m)?m:0},v_=function(d,f){var g=Tt(f,["moof","traf"]),m=0,v=0,T;if(g&&g.length){var R=Tt(g[0],["tfhd"])[0],M=Tt(g[0],["trun"])[0],U=Tt(g[0],["tfdt"])[0];if(R){var q=vR(R);T=q.trackId}if(U){var $=TR(U);m=$.baseMediaDecodeTime}if(M){var Z=bR(M);Z.samples&&Z.samples.length&&(v=Z.samples[0].compositionTimeOffset||0)}}var pe=d[T]||9e4;typeof m=="bigint"&&(v=Uf.BigInt(v),pe=Uf.BigInt(pe));var ne=(m+v)/pe;return typeof ne=="bigint"&&ne<Number.MAX_SAFE_INTEGER&&(ne=Number(ne)),ne},b_=function(d){var f=Tt(d,["moov","trak"]),g=[];return f.forEach(function(m){var v=Tt(m,["mdia","hdlr"]),T=Tt(m,["tkhd"]);v.forEach(function(R,M){var U=ia(R.subarray(8,12)),q=T[M],$,Z,pe;U==="vide"&&($=new DataView(q.buffer,q.byteOffset,q.byteLength),Z=$.getUint8(0),pe=Z===0?$.getUint32(12):$.getUint32(20),g.push(pe))})}),g},Ff=function(d){var f=d[0],g=f===0?12:20;return Kl(d[g]<<24|d[g+1]<<16|d[g+2]<<8|d[g+3])},T_=function(d){var f=Tt(d,["moov","trak"]),g=[];return f.forEach(function(m){var v={},T=Tt(m,["tkhd"])[0],R,M;T&&(R=new DataView(T.buffer,T.byteOffset,T.byteLength),M=R.getUint8(0),v.id=M===0?R.getUint32(12):R.getUint32(20));var U=Tt(m,["mdia","hdlr"])[0];if(U){var q=ia(U.subarray(8,12));q==="vide"?v.type="video":q==="soun"?v.type="audio":v.type=q}var $=Tt(m,["mdia","minf","stbl","stsd"])[0];if($){var Z=$.subarray(8);v.codec=ia(Z.subarray(4,8));var pe=Tt(Z,[v.codec])[0],ne,ke;pe&&(/^[asm]vc[1-9]$/i.test(v.codec)?(ne=pe.subarray(78),ke=ia(ne.subarray(4,8)),ke==="avcC"&&ne.length>11?(v.codec+=".",v.codec+=ko(ne[9]),v.codec+=ko(ne[10]),v.codec+=ko(ne[11])):v.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(v.codec)?(ne=pe.subarray(28),ke=ia(ne.subarray(4,8)),ke==="esds"&&ne.length>20&&ne[19]!==0?(v.codec+="."+ko(ne[19]),v.codec+="."+ko(ne[20]>>>2&63).replace(/^0/,"")):v.codec="mp4a.40.2"):v.codec=v.codec.toLowerCase())}var Ie=Tt(m,["mdia","mdhd"])[0];Ie&&(v.timescale=Ff(Ie)),g.push(v)}),g},__=function(d,f=0){var g=Tt(d,["emsg"]);return g.map(m=>{var v=Nf.parseEmsgBox(new Uint8Array(m)),T=SR(v.message_data);return{cueTime:Nf.scaleTime(v.presentation_time,v.timescale,v.presentation_time_delta,f),duration:Nf.scaleTime(v.event_duration,v.timescale),frames:T}})};var Eo={findBox:Tt,parseType:ia,timescale:g_,startTime:y_,compositionStartTime:v_,videoTrackIds:b_,tracks:T_,getTimescaleFromMediaHeader:Ff,getEmsgID3:__};const{parseTrun:CR}=f_,{findBox:S_}=Eo;var C_=m_,kR=function(d){var f=S_(d,["moof","traf"]),g=S_(d,["mdat"]),m=[];return g.forEach(function(v,T){var R=f[T];m.push({mdat:v,traf:R})}),m},ER=function(d,f,g){var m=f,v=g.defaultSampleDuration||0,T=g.defaultSampleSize||0,R=g.trackId,M=[];return d.forEach(function(U){var q=CR(U),$=q.samples;$.forEach(function(Z){Z.duration===void 0&&(Z.duration=v),Z.size===void 0&&(Z.size=T),Z.trackId=R,Z.dts=m,Z.compositionTimeOffset===void 0&&(Z.compositionTimeOffset=0),typeof m=="bigint"?(Z.pts=m+C_.BigInt(Z.compositionTimeOffset),m+=C_.BigInt(Z.duration)):(Z.pts=m+Z.compositionTimeOffset,m+=Z.duration)}),M=M.concat($)}),M},k_={getMdatTrafPairs:kR,parseSamples:ER},xR=ue.discardEmulationPreventionBytes,wR=gi.CaptionStream,Bf=Mf,AR=Lf,DR=l_,{getMdatTrafPairs:PR,parseSamples:IR}=k_,RR=function(d,f){for(var g=d,m=0;m<f.length;m++){var v=f[m];if(g<v.size)return v;g-=v.size}return null},OR=function(d,f,g){var m=new DataView(d.buffer,d.byteOffset,d.byteLength),v={logs:[],seiNals:[]},T,R,M,U;for(R=0;R+4<d.length;R+=M)if(M=m.getUint32(R),R+=4,!(M<=0))switch(d[R]&31){case 6:var q=d.subarray(R+1,R+1+M),$=RR(R,f);if(T={nalUnitType:"sei_rbsp",size:M,data:q,escapedRBSP:xR(q),trackId:g},$)T.pts=$.pts,T.dts=$.dts,U=$;else if(U)T.pts=U.pts,T.dts=U.dts;else{v.logs.push({level:"warn",message:"We've encountered a nal unit without data at "+R+" for trackId "+g+". See mux.js#223."});break}v.seiNals.push(T);break}return v},MR=function(d,f){var g={},m=PR(d);return m.forEach(function(v){var T=v.mdat,R=v.traf,M=Bf(R,["tfhd"]),U=DR(M[0]),q=U.trackId,$=Bf(R,["tfdt"]),Z=$.length>0?AR($[0]).baseMediaDecodeTime:0,pe=Bf(R,["trun"]),ne,ke;f===q&&pe.length>0&&(ne=IR(pe,Z,U),ke=OR(T,ne,q),g[q]||(g[q]={seiNals:[],logs:[]}),g[q].seiNals=g[q].seiNals.concat(ke.seiNals),g[q].logs=g[q].logs.concat(ke.logs))}),g},LR=function(d,f,g){var m;if(f===null)return null;m=MR(d,f);var v=m[f]||{};return{seiNals:v.seiNals,logs:v.logs,timescale:g}},NR=function(){var d=!1,f,g,m,v,T,R;this.isInitialized=function(){return d},this.init=function(M){f=new wR,d=!0,R=M?M.isPartial:!1,f.on("data",function(U){U.startTime=U.startPts/v,U.endTime=U.endPts/v,T.captions.push(U),T.captionStreams[U.stream]=!0}),f.on("log",function(U){T.logs.push(U)})},this.isNewInit=function(M,U){return M&&M.length===0||U&&typeof U=="object"&&Object.keys(U).length===0?!1:m!==M[0]||v!==U[m]},this.parse=function(M,U,q){var $;if(this.isInitialized()){if(!U||!q)return null;if(this.isNewInit(U,q))m=U[0],v=q[m];else if(m===null||!v)return g.push(M),null}else return null;for(;g.length>0;){var Z=g.shift();this.parse(Z,U,q)}return $=LR(M,m,v),$&&$.logs&&(T.logs=T.logs.concat($.logs)),$===null||!$.seiNals?T.logs.length?{logs:T.logs,captions:[],captionStreams:[]}:null:(this.pushNals($.seiNals),this.flushStream(),T)},this.pushNals=function(M){if(!this.isInitialized()||!M||M.length===0)return null;M.forEach(function(U){f.push(U)})},this.flushStream=function(){if(!this.isInitialized())return null;R?f.partialFlush():f.flush()},this.clearParsedCaptions=function(){T.captions=[],T.captionStreams={},T.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;f.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){g=[],m=null,v=null,T?this.clearParsedCaptions():T={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()},FR=NR;const{parseTfdt:UR}=f_,gs=Mf,{getTimescaleFromMediaHeader:BR}=Eo,{parseSamples:qR,getMdatTrafPairs:VR}=k_;var E_=function(){let d=9e4;this.init=function(f){const g=gs(f,["moov","trak","mdia","mdhd"])[0];g&&(d=BR(g))},this.parseSegment=function(f){const g=[],m=VR(f);let v=0;return m.forEach(function(T){const R=T.mdat,M=T.traf,U=gs(M,["tfdt"])[0],q=gs(M,["tfhd"])[0],$=gs(M,["trun"]);if(U&&(v=UR(U).baseMediaDecodeTime),$.length&&q){const Z=qR($,v,q);let pe=0;Z.forEach(function(ne){const ke="utf-8",Ie=new TextDecoder(ke),Lt=R.slice(pe,pe+ne.size);if(gs(Lt,["vtte"])[0]){pe+=ne.size;return}gs(Lt,["vttc"]).forEach(function(xo){const wo=gs(xo,["payl"])[0],Ao=gs(xo,["sttg"])[0],Do=ne.pts/d,Ql=(ne.pts+ne.duration)/d;let it,Po;if(wo)try{it=Ie.decode(wo)}catch(Qi){console.error(Qi)}if(Ao)try{Po=Ie.decode(Ao)}catch(Qi){console.error(Qi)}ne.duration&&it&&g.push({cueText:it,start:Do,end:Ql,settings:Po})}),pe+=ne.size})}}),g}},qf=ps,x_=function(d){var f=d[1]&31;return f<<=8,f|=d[2],f},Xl=function(d){return!!(d[1]&64)},Yl=function(d){var f=0;return(d[3]&48)>>>4>1&&(f+=d[4]+1),f},jR=function(d,f){var g=x_(d);return g===0?"pat":g===f?"pmt":f?"pes":null},HR=function(d){var f=Xl(d),g=4+Yl(d);return f&&(g+=d[g]+1),(d[g+10]&31)<<8|d[g+11]},$R=function(d){var f={},g=Xl(d),m=4+Yl(d);if(g&&(m+=d[m]+1),!!(d[m+5]&1)){var v,T,R;v=(d[m+1]&15)<<8|d[m+2],T=3+v-4,R=(d[m+10]&15)<<8|d[m+11];for(var M=12+R;M<T;){var U=m+M;f[(d[U+1]&31)<<8|d[U+2]]=d[U],M+=((d[U+3]&15)<<8|d[U+4])+5}return f}},WR=function(d,f){var g=x_(d),m=f[g];switch(m){case qf.H264_STREAM_TYPE:return"video";case qf.ADTS_STREAM_TYPE:return"audio";case qf.METADATA_STREAM_TYPE:return"timed-metadata";default:return null}},zR=function(d){var f=Xl(d);if(!f)return null;var g=4+Yl(d);if(g>=d.byteLength)return null;var m=null,v;return v=d[g+7],v&192&&(m={},m.pts=(d[g+9]&14)<<27|(d[g+10]&255)<<20|(d[g+11]&254)<<12|(d[g+12]&255)<<5|(d[g+13]&254)>>>3,m.pts*=4,m.pts+=(d[g+13]&6)>>>1,m.dts=m.pts,v&64&&(m.dts=(d[g+14]&14)<<27|(d[g+15]&255)<<20|(d[g+16]&254)<<12|(d[g+17]&255)<<5|(d[g+18]&254)>>>3,m.dts*=4,m.dts+=(d[g+18]&6)>>>1)),m},Vf=function(d){switch(d){case 5:return"slice_layer_without_partitioning_rbsp_idr";case 6:return"sei_rbsp";case 7:return"seq_parameter_set_rbsp";case 8:return"pic_parameter_set_rbsp";case 9:return"access_unit_delimiter_rbsp";default:return null}},GR=function(d){for(var f=4+Yl(d),g=d.subarray(f),m=0,v=0,T=!1,R;v<g.byteLength-3;v++)if(g[v+2]===1){m=v+5;break}for(;m<g.byteLength;)switch(g[m]){case 0:if(g[m-1]!==0){m+=2;break}else if(g[m-2]!==0){m++;break}v+3!==m-2&&(R=Vf(g[v+3]&31),R==="slice_layer_without_partitioning_rbsp_idr"&&(T=!0));do m++;while(g[m]!==1&&m<g.length);v=m-2,m+=3;break;case 1:if(g[m-1]!==0||g[m-2]!==0){m+=3;break}R=Vf(g[v+3]&31),R==="slice_layer_without_partitioning_rbsp_idr"&&(T=!0),v=m-2,m+=3;break;default:m+=3;break}return g=g.subarray(v),m-=v,v=0,g&&g.byteLength>3&&(R=Vf(g[v+3]&31),R==="slice_layer_without_partitioning_rbsp_idr"&&(T=!0)),T},KR={parseType:jR,parsePat:HR,parsePmt:$R,parsePayloadUnitStartIndicator:Xl,parsePesType:WR,parsePesTime:zR,videoPacketContainsKeyFrame:GR},w_=ps,na=po.handleRollover,Xe={};Xe.ts=KR,Xe.aac=Of;var Xs=Ke.ONE_SECOND_IN_TS,si=188,Sn=71,XR=function(d,f){for(var g=0,m=si,v,T;m<d.byteLength;){if(d[g]===Sn&&d[m]===Sn){switch(v=d.subarray(g,m),T=Xe.ts.parseType(v,f.pid),T){case"pat":f.pid=Xe.ts.parsePat(v);break;case"pmt":var R=Xe.ts.parsePmt(v);f.table=f.table||{},Object.keys(R).forEach(function(M){f.table[M]=R[M]});break}g+=si,m+=si;continue}g++,m++}},A_=function(d,f,g){for(var m=0,v=si,T,R,M,U,q,$=!1;v<=d.byteLength;){if(d[m]===Sn&&(d[v]===Sn||v===d.byteLength)){switch(T=d.subarray(m,v),R=Xe.ts.parseType(T,f.pid),R){case"pes":M=Xe.ts.parsePesType(T,f.table),U=Xe.ts.parsePayloadUnitStartIndicator(T),M==="audio"&&U&&(q=Xe.ts.parsePesTime(T),q&&(q.type="audio",g.audio.push(q),$=!0));break}if($)break;m+=si,v+=si;continue}m++,v++}for(v=d.byteLength,m=v-si,$=!1;m>=0;){if(d[m]===Sn&&(d[v]===Sn||v===d.byteLength)){switch(T=d.subarray(m,v),R=Xe.ts.parseType(T,f.pid),R){case"pes":M=Xe.ts.parsePesType(T,f.table),U=Xe.ts.parsePayloadUnitStartIndicator(T),M==="audio"&&U&&(q=Xe.ts.parsePesTime(T),q&&(q.type="audio",g.audio.push(q),$=!0));break}if($)break;m-=si,v-=si;continue}m--,v--}},YR=function(d,f,g){for(var m=0,v=si,T,R,M,U,q,$,Z,pe,ne=!1,ke={data:[],size:0};v<d.byteLength;){if(d[m]===Sn&&d[v]===Sn){switch(T=d.subarray(m,v),R=Xe.ts.parseType(T,f.pid),R){case"pes":if(M=Xe.ts.parsePesType(T,f.table),U=Xe.ts.parsePayloadUnitStartIndicator(T),M==="video"&&(U&&!ne&&(q=Xe.ts.parsePesTime(T),q&&(q.type="video",g.video.push(q),ne=!0)),!g.firstKeyFrame)){if(U&&ke.size!==0){for($=new Uint8Array(ke.size),Z=0;ke.data.length;)pe=ke.data.shift(),$.set(pe,Z),Z+=pe.byteLength;if(Xe.ts.videoPacketContainsKeyFrame($)){var Ie=Xe.ts.parsePesTime($);Ie?(g.firstKeyFrame=Ie,g.firstKeyFrame.type="video"):console.warn("Failed to extract PTS/DTS from PES at first keyframe. This could be an unusual TS segment, or else mux.js did not parse your TS segment correctly. If you know your TS segments do contain PTS/DTS on keyframes please file a bug report! You can try ffprobe to double check for yourself.")}ke.size=0}ke.data.push(T),ke.size+=T.byteLength}break}if(ne&&g.firstKeyFrame)break;m+=si,v+=si;continue}m++,v++}for(v=d.byteLength,m=v-si,ne=!1;m>=0;){if(d[m]===Sn&&d[v]===Sn){switch(T=d.subarray(m,v),R=Xe.ts.parseType(T,f.pid),R){case"pes":M=Xe.ts.parsePesType(T,f.table),U=Xe.ts.parsePayloadUnitStartIndicator(T),M==="video"&&U&&(q=Xe.ts.parsePesTime(T),q&&(q.type="video",g.video.push(q),ne=!0));break}if(ne)break;m-=si,v-=si;continue}m--,v--}},QR=function(d,f){if(d.audio&&d.audio.length){var g=f;(typeof g>"u"||isNaN(g))&&(g=d.audio[0].dts),d.audio.forEach(function(T){T.dts=na(T.dts,g),T.pts=na(T.pts,g),T.dtsTime=T.dts/Xs,T.ptsTime=T.pts/Xs})}if(d.video&&d.video.length){var m=f;if((typeof m>"u"||isNaN(m))&&(m=d.video[0].dts),d.video.forEach(function(T){T.dts=na(T.dts,m),T.pts=na(T.pts,m),T.dtsTime=T.dts/Xs,T.ptsTime=T.pts/Xs}),d.firstKeyFrame){var v=d.firstKeyFrame;v.dts=na(v.dts,m),v.pts=na(v.pts,m),v.dtsTime=v.dts/Xs,v.ptsTime=v.pts/Xs}}},JR=function(d){for(var f=!1,g=0,m=null,v=null,T=0,R=0,M;d.length-R>=3;){var U=Xe.aac.parseType(d,R);switch(U){case"timed-metadata":if(d.length-R<10){f=!0;break}if(T=Xe.aac.parseId3TagSize(d,R),T>d.length){f=!0;break}v===null&&(M=d.subarray(R,R+T),v=Xe.aac.parseAacTimestamp(M)),R+=T;break;case"audio":if(d.length-R<7){f=!0;break}if(T=Xe.aac.parseAdtsSize(d,R),T>d.length){f=!0;break}m===null&&(M=d.subarray(R,R+T),m=Xe.aac.parseSampleRate(M)),g++,R+=T;break;default:R++;break}if(f)return null}if(m===null||v===null)return null;var q=Xs/m,$={audio:[{type:"audio",dts:v,pts:v},{type:"audio",dts:v+g*1024*q,pts:v+g*1024*q}]};return $},ZR=function(d){var f={pid:null,table:null},g={};XR(d,f);for(var m in f.table)if(f.table.hasOwnProperty(m)){var v=f.table[m];switch(v){case w_.H264_STREAM_TYPE:g.video=[],YR(d,f,g),g.video.length===0&&delete g.video;break;case w_.ADTS_STREAM_TYPE:g.audio=[],A_(d,f,g),g.audio.length===0&&delete g.audio;break}}return g},eO=function(d,f){var g=Xe.aac.isLikelyAacData(d),m;return g?m=JR(d):m=ZR(d),!m||!m.audio&&!m.video?null:(QR(m,f),m)},tO={inspect:eO,parseAudioPes_:A_};const iO=function(d,f){f.on("data",function(g){const m=g.initSegment;g.initSegment={data:m.buffer,byteOffset:m.byteOffset,byteLength:m.byteLength};const v=g.data;g.data=v.buffer,d.postMessage({action:"data",segment:g,byteOffset:v.byteOffset,byteLength:v.byteLength},[g.data])}),f.on("done",function(g){d.postMessage({action:"done"})}),f.on("gopInfo",function(g){d.postMessage({action:"gopInfo",gopInfo:g})}),f.on("videoSegmentTimingInfo",function(g){const m={start:{decode:Ke.videoTsToSeconds(g.start.dts),presentation:Ke.videoTsToSeconds(g.start.pts)},end:{decode:Ke.videoTsToSeconds(g.end.dts),presentation:Ke.videoTsToSeconds(g.end.pts)},baseMediaDecodeTime:Ke.videoTsToSeconds(g.baseMediaDecodeTime)};g.prependedContentDuration&&(m.prependedContentDuration=Ke.videoTsToSeconds(g.prependedContentDuration)),d.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:m})}),f.on("audioSegmentTimingInfo",function(g){const m={start:{decode:Ke.videoTsToSeconds(g.start.dts),presentation:Ke.videoTsToSeconds(g.start.pts)},end:{decode:Ke.videoTsToSeconds(g.end.dts),presentation:Ke.videoTsToSeconds(g.end.pts)},baseMediaDecodeTime:Ke.videoTsToSeconds(g.baseMediaDecodeTime)};g.prependedContentDuration&&(m.prependedContentDuration=Ke.videoTsToSeconds(g.prependedContentDuration)),d.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:m})}),f.on("id3Frame",function(g){d.postMessage({action:"id3Frame",id3Frame:g})}),f.on("caption",function(g){d.postMessage({action:"caption",caption:g})}),f.on("trackinfo",function(g){d.postMessage({action:"trackinfo",trackInfo:g})}),f.on("audioTimingInfo",function(g){d.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:Ke.videoTsToSeconds(g.start),end:Ke.videoTsToSeconds(g.end)}})}),f.on("videoTimingInfo",function(g){d.postMessage({action:"videoTimingInfo",videoTimingInfo:{start:Ke.videoTsToSeconds(g.start),end:Ke.videoTsToSeconds(g.end)}})}),f.on("log",function(g){d.postMessage({action:"log",log:g})})};class D_{constructor(f,g){this.options=g||{},this.self=f,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new JI.Transmuxer(this.options),iO(this.self,this.transmuxer)}pushMp4Captions(f){this.captionParser||(this.captionParser=new FR,this.captionParser.init());const g=new Uint8Array(f.data,f.byteOffset,f.byteLength),m=this.captionParser.parse(g,f.trackIds,f.timescales);this.self.postMessage({action:"mp4Captions",captions:m&&m.captions||[],logs:m&&m.logs||[],data:g.buffer},[g.buffer])}initMp4WebVttParser(f){this.webVttParser||(this.webVttParser=new E_);const g=new Uint8Array(f.data,f.byteOffset,f.byteLength);this.webVttParser.init(g)}getMp4WebVttText(f){this.webVttParser||(this.webVttParser=new E_);const g=new Uint8Array(f.data,f.byteOffset,f.byteLength),m=this.webVttParser.parseSegment(g);this.self.postMessage({action:"getMp4WebVttText",mp4VttCues:m||[],data:g.buffer},[g.buffer])}probeMp4StartTime({timescales:f,data:g}){const m=Eo.startTime(f,g);this.self.postMessage({action:"probeMp4StartTime",startTime:m,data:g},[g.buffer])}probeMp4Tracks({data:f}){const g=Eo.tracks(f);this.self.postMessage({action:"probeMp4Tracks",tracks:g,data:f},[f.buffer])}probeEmsgID3({data:f,offset:g}){const m=Eo.getEmsgID3(f,g);this.self.postMessage({action:"probeEmsgID3",id3Frames:m,emsgData:f},[f.buffer])}probeTs({data:f,baseStartTime:g}){const m=typeof g=="number"&&!isNaN(g)?g*Ke.ONE_SECOND_IN_TS:void 0,v=tO.inspect(f,m);let T=null;v&&(T={hasVideo:v.video&&v.video.length===2||!1,hasAudio:v.audio&&v.audio.length===2||!1},T.hasVideo&&(T.videoStart=v.video[0].ptsTime),T.hasAudio&&(T.audioStart=v.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:T,data:f},[f.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(f){const g=new Uint8Array(f.data,f.byteOffset,f.byteLength);this.transmuxer.push(g)}reset(){this.transmuxer.reset()}setTimestampOffset(f){const g=f.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(Ke.secondsToVideoTs(g)))}setAudioAppendStart(f){this.transmuxer.setAudioAppendStart(Math.ceil(Ke.secondsToVideoTs(f.appendStart)))}setRemux(f){this.transmuxer.setRemux(f.remux)}flush(f){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(f){this.transmuxer.alignGopsWith(f.gopsToAlignWith.slice())}}self.onmessage=function(d){if(d.data.action==="init"&&d.data.options){this.messageHandlers=new D_(self,d.data.options);return}this.messageHandlers||(this.messageHandlers=new D_(self)),d.data&&d.data.action&&d.data.action!=="init"&&this.messageHandlers[d.data.action]&&this.messageHandlers[d.data.action](d.data)}}));var MD=Zb(OD);const LD=(n,e,t)=>{const{type:i,initSegment:s,captions:r,captionStreams:a,metadata:o,videoFrameDtsTime:c,videoFramePtsTime:l}=n.data.segment;e.buffer.push({captions:r,captionStreams:a,metadata:o});const u=n.data.segment.boxes||{data:n.data.segment.data},h={type:i,data:new Uint8Array(u.data,u.data.byteOffset,u.data.byteLength),initSegment:new Uint8Array(s.data,s.byteOffset,s.byteLength)};typeof c<"u"&&(h.videoFrameDtsTime=c),typeof l<"u"&&(h.videoFramePtsTime=l),t(h)},ND=({transmuxedData:n,callback:e})=>{n.buffer=[],e(n)},FD=(n,e)=>{e.gopInfo=n.data.gopInfo},iT=n=>{const{transmuxer:e,bytes:t,audioAppendStart:i,gopsToAlignWith:s,remux:r,onData:a,onTrackInfo:o,onAudioTimingInfo:c,onVideoTimingInfo:l,onVideoSegmentTimingInfo:u,onAudioSegmentTimingInfo:h,onId3:p,onCaptions:y,onDone:_,onEndedTimeline:b,onTransmuxerLog:S,isEndOfTimeline:D,segment:I,triggerSegmentEventFn:F}=n,w={buffer:[]};let P=D;const L=N=>{e.currentTransmux===n&&(N.data.action==="data"&&LD(N,w,a),N.data.action==="trackinfo"&&o(N.data.trackInfo),N.data.action==="gopInfo"&&FD(N,w),N.data.action==="audioTimingInfo"&&c(N.data.audioTimingInfo),N.data.action==="videoTimingInfo"&&l(N.data.videoTimingInfo),N.data.action==="videoSegmentTimingInfo"&&u(N.data.videoSegmentTimingInfo),N.data.action==="audioSegmentTimingInfo"&&h(N.data.audioSegmentTimingInfo),N.data.action==="id3Frame"&&p([N.data.id3Frame],N.data.id3Frame.dispatchType),N.data.action==="caption"&&y(N.data.caption),N.data.action==="endedtimeline"&&(P=!1,b()),N.data.action==="log"&&S(N.data.log),N.data.type==="transmuxed"&&(P||(e.onmessage=null,ND({transmuxedData:w,callback:_}),nT(e))))},C=()=>{const N={message:"Received an error message from the transmuxer worker",metadata:{errorType:K.Error.StreamingFailedToTransmuxSegment,segmentInfo:$s({segment:I})}};_(null,N)};if(e.onmessage=L,e.onerror=C,i&&e.postMessage({action:"setAudioAppendStart",appendStart:i}),Array.isArray(s)&&e.postMessage({action:"alignGopsWith",gopsToAlignWith:s}),typeof r<"u"&&e.postMessage({action:"setRemux",remux:r}),t.byteLength){const N=t instanceof ArrayBuffer?t:t.buffer,x=t instanceof ArrayBuffer?0:t.byteOffset;F({type:"segmenttransmuxingstart",segment:I}),e.postMessage({action:"push",data:N,byteOffset:x,byteLength:t.byteLength},[N])}D&&e.postMessage({action:"endTimeline"}),e.postMessage({action:"flush"})},nT=n=>{n.currentTransmux=null,n.transmuxQueue.length&&(n.currentTransmux=n.transmuxQueue.shift(),typeof n.currentTransmux=="function"?n.currentTransmux():iT(n.currentTransmux))},sT=(n,e)=>{n.postMessage({action:e}),nT(n)},rT=(n,e)=>{if(!e.currentTransmux){e.currentTransmux=n,sT(e,n);return}e.transmuxQueue.push(sT.bind(null,e,n))},UD=n=>{rT("reset",n)},BD=n=>{rT("endTimeline",n)},aT=n=>{if(!n.transmuxer.currentTransmux){n.transmuxer.currentTransmux=n,iT(n);return}n.transmuxer.transmuxQueue.push(n)};var vf={reset:UD,endTimeline:BD,transmux:aT,createTransmuxer:n=>{const e=new MD;e.currentTransmux=null,e.transmuxQueue=[];const t=e.terminate;return e.terminate=()=>(e.currentTransmux=null,e.transmuxQueue.length=0,t.call(e)),e.postMessage({action:"init",options:n}),e}};const Vr=function(n){const e=n.transmuxer,t=n.endAction||n.action,i=n.callback,s=vt({},n,{endAction:null,transmuxer:null,callback:null}),r=a=>{a.data.action===t&&(e.removeEventListener("message",r),a.data.data&&(a.data.data=new Uint8Array(a.data.data,n.byteOffset||0,n.byteLength||a.data.data.byteLength),n.data&&(n.data=a.data.data)),i(a.data))};if(e.addEventListener("message",r),n.data){const a=n.data instanceof ArrayBuffer;s.byteOffset=a?0:n.data.byteOffset,s.byteLength=n.data.byteLength;const o=[a?n.data:n.data.buffer];e.postMessage(s,o)}else e.postMessage(s)},yn={FAILURE:2,TIMEOUT:-101,ABORTED:-102},oT="wvtt",bf=n=>{n.forEach(e=>{e.abort()})},qD=n=>({bandwidth:n.bandwidth,bytesReceived:n.bytesReceived||0,roundTripTime:n.roundTripTime||0}),VD=n=>{const e=n.target,i={bandwidth:1/0,bytesReceived:0,roundTripTime:Date.now()-e.requestTime||0};return i.bytesReceived=n.loaded,i.bandwidth=Math.floor(i.bytesReceived/i.roundTripTime*8*1e3),i},Tf=(n,e)=>{const{requestType:t}=e,i=Hs({requestType:t,request:e,error:n});return e.timedout?{status:e.status,message:"HLS request timed-out at URL: "+e.uri,code:yn.TIMEOUT,xhr:e,metadata:i}:e.aborted?{status:e.status,message:"HLS request aborted at URL: "+e.uri,code:yn.ABORTED,xhr:e,metadata:i}:n?{status:e.status,message:"HLS request errored at URL: "+e.uri,code:yn.FAILURE,xhr:e,metadata:i}:e.responseType==="arraybuffer"&&e.response.byteLength===0?{status:e.status,message:"Empty HLS response at URL: "+e.uri,code:yn.FAILURE,xhr:e,metadata:i}:null},cT=(n,e,t,i)=>(s,r)=>{const a=r.response,o=Tf(s,r);if(o)return t(o,n);if(a.byteLength!==16)return t({status:r.status,message:"Invalid HLS key at URL: "+r.uri,code:yn.FAILURE,xhr:r},n);const c=new DataView(a),l=new Uint32Array([c.getUint32(0),c.getUint32(4),c.getUint32(8),c.getUint32(12)]);for(let h=0;h<e.length;h++)e[h].bytes=l;const u={uri:r.uri};return i({type:"segmentkeyloadcomplete",segment:n,keyInfo:u}),t(null,n)},jD=(n,e)=>{e===oT&&n.transmuxer.postMessage({action:"initMp4WebVttParser",data:n.map.bytes})},HD=(n,e,t)=>{e===oT&&Vr({action:"getMp4WebVttText",data:n.bytes,transmuxer:n.transmuxer,callback:({data:i,mp4VttCues:s})=>{n.bytes=i,t(null,n,{mp4VttCues:s})}})},lT=(n,e)=>{const t=oh(n.map.bytes);if(t!=="mp4"){const i=n.map.resolvedUri||n.map.uri,s=t||"unknown";return e({internal:!0,message:`Found unsupported ${s} container for initialization segment at URL: ${i}`,code:yn.FAILURE,metadata:{mediaType:s}})}Vr({action:"probeMp4Tracks",data:n.map.bytes,transmuxer:n.transmuxer,callback:({tracks:i,data:s})=>(n.map.bytes=s,i.forEach(function(r){n.map.tracks=n.map.tracks||{},!n.map.tracks[r.type]&&(n.map.tracks[r.type]=r,typeof r.id=="number"&&r.timescale&&(n.map.timescales=n.map.timescales||{},n.map.timescales[r.id]=r.timescale),r.type==="text"&&jD(n,r.codec))}),e(null))})},$D=({segment:n,finishProcessingFn:e,triggerSegmentEventFn:t})=>(i,s)=>{const r=Tf(i,s);if(r)return e(r,n);const a=new Uint8Array(s.response);if(t({type:"segmentloaded",segment:n}),n.map.key)return n.map.encryptedBytes=a,e(null,n);n.map.bytes=a,lT(n,function(o){if(o)return o.xhr=s,o.status=s.status,e(o,n);e(null,n)})},WD=({segment:n,finishProcessingFn:e,responseType:t,triggerSegmentEventFn:i})=>(s,r)=>{const a=Tf(s,r);if(a)return e(a,n);i({type:"segmentloaded",segment:n});const o=t==="arraybuffer"||!r.responseText?r.response:ID(r.responseText.substring(n.lastReachedChar||0));return n.stats=qD(r),n.key?n.encryptedBytes=new Uint8Array(o):n.bytes=new Uint8Array(o),e(null,n)},zD=({segment:n,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:p,triggerSegmentEventFn:y})=>{const _=n.map&&n.map.tracks||{},b=!!(_.audio&&_.video);let S=i.bind(null,n,"audio","start");const D=i.bind(null,n,"audio","end");let I=i.bind(null,n,"video","start");const F=i.bind(null,n,"video","end"),w=()=>aT({bytes:e,transmuxer:n.transmuxer,audioAppendStart:n.audioAppendStart,gopsToAlignWith:n.gopsToAlignWith,remux:b,onData:P=>{P.type=P.type==="combined"?"video":P.type,u(n,P)},onTrackInfo:P=>{t&&(b&&(P.isMuxed=!0),t(n,P))},onAudioTimingInfo:P=>{S&&typeof P.start<"u"&&(S(P.start),S=null),D&&typeof P.end<"u"&&D(P.end)},onVideoTimingInfo:P=>{I&&typeof P.start<"u"&&(I(P.start),I=null),F&&typeof P.end<"u"&&F(P.end)},onVideoSegmentTimingInfo:P=>{const L={pts:{start:P.start.presentation,end:P.end.presentation},dts:{start:P.start.decode,end:P.end.decode}};y({type:"segmenttransmuxingtiminginfoavailable",segment:n,timingInfo:L}),s(P)},onAudioSegmentTimingInfo:P=>{const L={pts:{start:P.start.pts,end:P.end.pts},dts:{start:P.start.dts,end:P.end.dts}};y({type:"segmenttransmuxingtiminginfoavailable",segment:n,timingInfo:L}),r(P)},onId3:(P,L)=>{a(n,P,L)},onCaptions:P=>{o(n,[P])},isEndOfTimeline:c,onEndedTimeline:()=>{l()},onTransmuxerLog:p,onDone:(P,L)=>{h&&(P.type=P.type==="combined"?"video":P.type,y({type:"segmenttransmuxingcomplete",segment:n}),h(L,n,P))},segment:n,triggerSegmentEventFn:y});Vr({action:"probeTs",transmuxer:n.transmuxer,data:e,baseStartTime:n.baseStartTime,callback:P=>{n.bytes=e=P.data;const L=P.result;L&&(t(n,{hasAudio:L.hasAudio,hasVideo:L.hasVideo,isMuxed:b}),t=null),w()}})},uT=({segment:n,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:p,triggerSegmentEventFn:y})=>{let _=new Uint8Array(e);if(bw(_)){n.isFmp4=!0;const{tracks:b}=n.map;if(b.text&&(!b.audio||!b.video)){u(n,{data:_,type:"text"}),HD(n,b.text.codec,h);return}const D={isFmp4:!0,hasVideo:!!b.video,hasAudio:!!b.audio};b.audio&&b.audio.codec&&b.audio.codec!=="enca"&&(D.audioCodec=b.audio.codec),b.video&&b.video.codec&&b.video.codec!=="encv"&&(D.videoCodec=b.video.codec),b.video&&b.audio&&(D.isMuxed=!0),t(n,D);const I=(F,w)=>{u(n,{data:_,type:D.hasAudio&&!D.isMuxed?"audio":"video"}),w&&w.length&&a(n,w),F&&F.length&&o(n,F),h(null,n,{})};Vr({action:"probeMp4StartTime",timescales:n.map.timescales,data:_,transmuxer:n.transmuxer,callback:({data:F,startTime:w})=>{e=F.buffer,n.bytes=_=F,D.hasAudio&&!D.isMuxed&&i(n,"audio","start",w),D.hasVideo&&i(n,"video","start",w),Vr({action:"probeEmsgID3",data:_,transmuxer:n.transmuxer,offset:w,callback:({emsgData:P,id3Frames:L})=>{if(e=P.buffer,n.bytes=_=P,!b.video||!P.byteLength||!n.transmuxer){I(void 0,L);return}Vr({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:n.transmuxer,data:_,timescales:n.map.timescales,trackIds:[b.video.id],callback:C=>{e=C.data.buffer,n.bytes=_=C.data,C.logs.forEach(function(N){p(We(N,{stream:"mp4CaptionParser"}))}),I(C.captions,L)}})}})}});return}if(!n.transmuxer){h(null,n,{});return}if(typeof n.container>"u"&&(n.container=oh(_)),n.container!=="ts"&&n.container!=="aac"){t(n,{hasAudio:!1,hasVideo:!1}),h(null,n,{});return}zD({segment:n,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:p,triggerSegmentEventFn:y})},dT=function({id:n,key:e,encryptedBytes:t,decryptionWorker:i,segment:s,doneFn:r},a){const o=l=>{if(l.data.source===n){i.removeEventListener("message",o);const u=l.data.decrypted;a(new Uint8Array(u.bytes,u.byteOffset,u.byteLength))}};i.onerror=()=>{const l="An error occurred in the decryption worker",u=$s({segment:s}),h={message:l,metadata:{error:new Error(l),errorType:K.Error.StreamingFailedToDecryptSegment,segmentInfo:u,keyInfo:{uri:s.key.resolvedUri||s.map.key.resolvedUri}}};r(h,s)},i.addEventListener("message",o);let c;e.bytes.slice?c=e.bytes.slice():c=new Uint32Array(Array.prototype.slice.call(e.bytes)),i.postMessage(Wb({source:n,encrypted:t,key:c,iv:e.iv}),[t.buffer,c.buffer])},GD=({decryptionWorker:n,segment:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:p,triggerSegmentEventFn:y})=>{y({type:"segmentdecryptionstart"}),dT({id:e.requestId,key:e.key,encryptedBytes:e.encryptedBytes,decryptionWorker:n,segment:e,doneFn:h},_=>{e.bytes=_,y({type:"segmentdecryptioncomplete",segment:e}),uT({segment:e,bytes:e.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:p,triggerSegmentEventFn:y})})},KD=({activeXhrs:n,decryptionWorker:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:p,triggerSegmentEventFn:y})=>{let _=0,b=!1;return(S,D)=>{if(!b){if(S)return b=!0,bf(n),h(S,D);if(_+=1,_===n.length){const I=function(){if(D.encryptedBytes)return GD({decryptionWorker:e,segment:D,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:p,triggerSegmentEventFn:y});uT({segment:D,bytes:D.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:p,triggerSegmentEventFn:y})};if(D.endOfAllRequests=Date.now(),D.map&&D.map.encryptedBytes&&!D.map.bytes)return y({type:"segmentdecryptionstart",segment:D}),dT({decryptionWorker:e,id:D.requestId+"-init",encryptedBytes:D.map.encryptedBytes,key:D.map.key,segment:D,doneFn:h},F=>{D.map.bytes=F,y({type:"segmentdecryptioncomplete",segment:D}),lT(D,w=>{if(w)return bf(n),h(w,D);I()})});I()}}}},XD=({loadendState:n,abortFn:e})=>t=>{t.target.aborted&&e&&!n.calledAbortFn&&(e(),n.calledAbortFn=!0)},YD=({segment:n,progressFn:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:c,endedTimelineFn:l,dataFn:u})=>h=>{if(!h.target.aborted)return n.stats=We(n.stats,VD(h)),!n.stats.firstBytesReceivedAt&&n.stats.bytesReceived&&(n.stats.firstBytesReceivedAt=Date.now()),e(h,n)},QD=({xhr:n,xhrOptions:e,decryptionWorker:t,segment:i,abortFn:s,progressFn:r,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:l,id3Fn:u,captionsFn:h,isEndOfTimeline:p,endedTimelineFn:y,dataFn:_,doneFn:b,onTransmuxerLog:S,triggerSegmentEventFn:D})=>{const I=[],F=KD({activeXhrs:I,decryptionWorker:t,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:l,id3Fn:u,captionsFn:h,isEndOfTimeline:p,endedTimelineFn:y,dataFn:_,doneFn:b,onTransmuxerLog:S,triggerSegmentEventFn:D});if(i.key&&!i.key.bytes){const N=[i.key];i.map&&!i.map.bytes&&i.map.key&&i.map.key.resolvedUri===i.key.resolvedUri&&N.push(i.map.key);const x=We(e,{uri:i.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),k=cT(i,N,F,D),j={uri:i.key.resolvedUri};D({type:"segmentkeyloadstart",segment:i,keyInfo:j});const G=n(x,k);I.push(G)}if(i.map&&!i.map.bytes){if(i.map.key&&(!i.key||i.key.resolvedUri!==i.map.key.resolvedUri)){const G=We(e,{uri:i.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),X=cT(i,[i.map.key],F,D),z={uri:i.map.key.resolvedUri};D({type:"segmentkeyloadstart",segment:i,keyInfo:z});const W=n(G,X);I.push(W)}const x=We(e,{uri:i.map.resolvedUri,responseType:"arraybuffer",headers:mf(i.map),requestType:"segment-media-initialization"}),k=$D({segment:i,finishProcessingFn:F,triggerSegmentEventFn:D});D({type:"segmentloadstart",segment:i});const j=n(x,k);I.push(j)}const w=We(e,{uri:i.part&&i.part.resolvedUri||i.resolvedUri,responseType:"arraybuffer",headers:mf(i),requestType:"segment"}),P=WD({segment:i,finishProcessingFn:F,responseType:w.responseType,triggerSegmentEventFn:D});D({type:"segmentloadstart",segment:i});const L=n(w,P);L.addEventListener("progress",YD({segment:i,progressFn:r,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:l,id3Fn:u,captionsFn:h,isEndOfTimeline:p,endedTimelineFn:y,dataFn:_})),I.push(L);const C={};return I.forEach(N=>{N.addEventListener("loadend",XD({loadendState:C,abortFn:s}))}),()=>bf(I)},Sl=Oi("PlaylistSelector"),hT=function(n){if(!n||!n.playlist)return;const e=n.playlist;return JSON.stringify({id:e.id,bandwidth:n.bandwidth,width:n.width,height:n.height,codecs:e.attributes&&e.attributes.CODECS||""})},jr=function(n,e){if(!n)return"";const t=B.getComputedStyle(n);return t?t[e]:""},Hr=function(n,e){const t=n.slice();n.sort(function(i,s){const r=e(i,s);return r===0?t.indexOf(i)-t.indexOf(s):r})},_f=function(n,e){let t,i;return n.attributes.BANDWIDTH&&(t=n.attributes.BANDWIDTH),t=t||B.Number.MAX_VALUE,e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||B.Number.MAX_VALUE,t-i},JD=function(n,e){let t,i;return n.attributes.RESOLUTION&&n.attributes.RESOLUTION.width&&(t=n.attributes.RESOLUTION.width),t=t||B.Number.MAX_VALUE,e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||B.Number.MAX_VALUE,t===i&&n.attributes.BANDWIDTH&&e.attributes.BANDWIDTH?n.attributes.BANDWIDTH-e.attributes.BANDWIDTH:t-i};let fT=function(n){const{main:e,bandwidth:t,playerWidth:i,playerHeight:s,playerObjectFit:r,limitRenditionByPlayerDimensions:a,playlistController:o}=n;if(!e)return;const c={bandwidth:t,width:i,height:s,limitRenditionByPlayerDimensions:a};let l=e.playlists;hi.isAudioOnly(e)&&(l=o.getAudioTrackPlaylists_(),c.audioOnly=!0);let u=l.map(C=>{let N;const x=C.attributes&&C.attributes.RESOLUTION&&C.attributes.RESOLUTION.width,k=C.attributes&&C.attributes.RESOLUTION&&C.attributes.RESOLUTION.height;return N=C.attributes&&C.attributes.BANDWIDTH,N=N||B.Number.MAX_VALUE,{bandwidth:N,width:x,height:k,playlist:C}});Hr(u,(C,N)=>C.bandwidth-N.bandwidth),u=u.filter(C=>!hi.isIncompatible(C.playlist));let h=u.filter(C=>hi.isEnabled(C.playlist));h.length||(h=u.filter(C=>!hi.isDisabled(C.playlist)));const p=h.filter(C=>C.bandwidth*Mt.BANDWIDTH_VARIANCE<t);let y=p[p.length-1];const _=p.filter(C=>C.bandwidth===y.bandwidth)[0];if(a===!1){const C=_||h[0]||u[0];if(C&&C.playlist){let N="sortedPlaylistReps";return _&&(N="bandwidthBestRep"),h[0]&&(N="enabledPlaylistReps"),Sl(`choosing ${hT(C)} using ${N} with options`,c),C.playlist}return Sl("could not choose a playlist with options",c),null}const b=p.filter(C=>C.width&&C.height);Hr(b,(C,N)=>C.width-N.width);const S=b.filter(C=>C.width===i&&C.height===s);y=S[S.length-1];const D=S.filter(C=>C.bandwidth===y.bandwidth)[0];let I,F,w;D||(I=b.filter(C=>r==="cover"?C.width>i&&C.height>s:C.width>i||C.height>s),F=I.filter(C=>C.width===I[0].width&&C.height===I[0].height),y=F[F.length-1],w=F.filter(C=>C.bandwidth===y.bandwidth)[0]);let P;if(o.leastPixelDiffSelector){const C=b.map(N=>(N.pixelDiff=Math.abs(N.width-i)+Math.abs(N.height-s),N));Hr(C,(N,x)=>N.pixelDiff===x.pixelDiff?x.bandwidth-N.bandwidth:N.pixelDiff-x.pixelDiff),P=C[0]}const L=P||w||D||_||h[0]||u[0];if(L&&L.playlist){let C="sortedPlaylistReps";return P?C="leastPixelDiffRep":w?C="resolutionPlusOneRep":D?C="resolutionBestRep":_?C="bandwidthBestRep":h[0]&&(C="enabledPlaylistReps"),Sl(`choosing ${hT(L)} using ${C} with options`,c),L.playlist}return Sl("could not choose a playlist with options",c),null};const pT=function(){let n=this.useDevicePixelRatio&&B.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(n=this.customPixelRatio),fT({main:this.playlists.main,bandwidth:this.systemBandwidth,playerWidth:parseInt(jr(this.tech_.el(),"width"),10)*n,playerHeight:parseInt(jr(this.tech_.el(),"height"),10)*n,playerObjectFit:this.usePlayerObjectFit?jr(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})},ZD=function(n){let e=-1,t=-1;if(n<0||n>1)throw new Error("Moving average bandwidth decay must be between 0 and 1.");return function(){let i=this.useDevicePixelRatio&&B.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(i=this.customPixelRatio),e<0&&(e=this.systemBandwidth,t=this.systemBandwidth),this.systemBandwidth>0&&this.systemBandwidth!==t&&(e=n*this.systemBandwidth+(1-n)*e,t=this.systemBandwidth),fT({main:this.playlists.main,bandwidth:e,playerWidth:parseInt(jr(this.tech_.el(),"width"),10)*i,playerHeight:parseInt(jr(this.tech_.el(),"height"),10)*i,playerObjectFit:this.usePlayerObjectFit?jr(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})}},eP=function(n){const{main:e,currentTime:t,bandwidth:i,duration:s,segmentDuration:r,timeUntilRebuffer:a,currentTimeline:o,syncController:c}=n,l=e.playlists.filter(_=>!hi.isIncompatible(_));let u=l.filter(hi.isEnabled);u.length||(u=l.filter(_=>!hi.isDisabled(_)));const p=u.filter(hi.hasAttribute.bind(null,"BANDWIDTH")).map(_=>{const S=c.getSyncPoint(_,s,o,t)?1:2,I=hi.estimateSegmentRequestTime(r,i,_)*S-a;return{playlist:_,rebufferingImpact:I}}),y=p.filter(_=>_.rebufferingImpact<=0);return Hr(y,(_,b)=>_f(b.playlist,_.playlist)),y.length?y[0]:(Hr(p,(_,b)=>_.rebufferingImpact-b.rebufferingImpact),p[0]||null)},tP=function(){const n=this.playlists.main.playlists.filter(hi.isEnabled);return Hr(n,(t,i)=>_f(t,i)),n.filter(t=>!!io(this.playlists.main,t).video)[0]||null},iP=n=>{let e=0,t;return n.bytes&&(t=new Uint8Array(n.bytes),n.segments.forEach(i=>{t.set(i,e),e+=i.byteLength})),t};function mT(n){try{return new URL(n).pathname.split("/").slice(-2).join("/")}catch{return""}}const nP=function(n,e,t){if(!n[t]){e.trigger({type:"usage",name:"vhs-608"});let i=t;/^cc708_/.test(t)&&(i="SERVICE"+t.split("_")[1]);const s=e.textTracks().getTrackById(i);if(s)n[t]=s;else{const r=e.options_.vhs&&e.options_.vhs.captionServices||{};let a=t,o=t,c=!1;const l=r[i];l&&(a=l.label,o=l.language,c=l.default),n[t]=e.addRemoteTextTrack({kind:"captions",id:i,default:c,label:a,language:o},!1).track}}},sP=function({inbandTextTracks:n,captionArray:e,timestampOffset:t}){if(!e)return;const i=B.WebKitDataCue||B.VTTCue;e.forEach(s=>{const r=s.stream;s.content?s.content.forEach(a=>{const o=new i(s.startTime+t,s.endTime+t,a.text);o.line=a.line,o.align="left",o.position=a.position,o.positionAlign="line-left",n[r].addCue(o)}):n[r].addCue(new i(s.startTime+t,s.endTime+t,s.text))})},rP=function(n){Object.defineProperties(n.frame,{id:{get(){return K.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),n.value.key}},value:{get(){return K.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),n.value.data}},privateData:{get(){return K.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),n.value.data}}})},aP=({inbandTextTracks:n,metadataArray:e,timestampOffset:t,videoDuration:i})=>{if(!e)return;const s=B.WebKitDataCue||B.VTTCue,r=n.metadataTrack_;if(!r||(e.forEach(u=>{const h=u.cueTime+t;typeof h!="number"||B.isNaN(h)||h<0||!(h<1/0)||!u.frames||!u.frames.length||u.frames.forEach(p=>{const y=new s(h,h,p.value||p.url||p.data||"");y.frame=p,y.value=p,rP(y),r.addCue(y)})}),!r.cues||!r.cues.length))return;const a=r.cues,o=[];for(let u=0;u<a.length;u++)a[u]&&o.push(a[u]);const c=o.reduce((u,h)=>{const p=u[h.startTime]||[];return p.push(h),u[h.startTime]=p,u},{}),l=Object.keys(c).sort((u,h)=>Number(u)-Number(h));l.forEach((u,h)=>{const p=c[u],y=isFinite(i)?i:u,_=Number(l[h+1])||y;p.forEach(b=>{b.endTime=_})})},oP={id:"ID",class:"CLASS",startDate:"START-DATE",duration:"DURATION",endDate:"END-DATE",endOnNext:"END-ON-NEXT",plannedDuration:"PLANNED-DURATION",scte35Out:"SCTE35-OUT",scte35In:"SCTE35-IN"},cP=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),lP=({inbandTextTracks:n,dateRanges:e})=>{const t=n.metadataTrack_;if(!t)return;const i=B.WebKitDataCue||B.VTTCue;e.forEach(s=>{for(const r of Object.keys(s)){if(cP.has(r))continue;const a=new i(s.startTime,s.endTime,"");a.id=s.id,a.type="com.apple.quicktime.HLS",a.value={key:oP[r],data:s[r]},(r==="scte35Out"||r==="scte35In")&&(a.value.data=new Uint8Array(a.value.data.match(/[\da-f]{2}/gi)).buffer),t.addCue(a)}s.processDateRange()})},gT=(n,e,t)=>{n.metadataTrack_||(n.metadataTrack_=t.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,K.browser.IS_ANY_SAFARI||(n.metadataTrack_.inBandMetadataTrackDispatchType=e))},no=function(n,e,t){let i,s;if(t&&t.cues)for(i=t.cues.length;i--;)s=t.cues[i],s.startTime>=n&&s.endTime<=e&&t.removeCue(s)},uP=function(n){const e=n.cues;if(!e)return;const t={};for(let i=e.length-1;i>=0;i--){const s=e[i],r=`${s.startTime}-${s.endTime}-${s.text}`;t[r]?n.removeCue(s):t[r]=s}},dP=(n,e,t)=>{if(typeof e>"u"||e===null||!n.length)return[];const i=Math.ceil((e-t+3)*Ms.ONE_SECOND_IN_TS);let s;for(s=0;s<n.length&&!(n[s].pts>i);s++);return n.slice(s)},hP=(n,e,t)=>{if(!e.length)return n;if(t)return e.slice();const i=e[0].pts;let s=0;for(s;s<n.length&&!(n[s].pts>=i);s++);return n.slice(0,s).concat(e)},fP=(n,e,t,i)=>{const s=Math.ceil((e-i)*Ms.ONE_SECOND_IN_TS),r=Math.ceil((t-i)*Ms.ONE_SECOND_IN_TS),a=n.slice();let o=n.length;for(;o--&&!(n[o].pts<=r););if(o===-1)return a;let c=o+1;for(;c--&&!(n[c].pts<=s););return c=Math.max(c,0),a.splice(c,o-c+1),a},pP=function(n,e){if(!n&&!e||!n&&e||n&&!e)return!1;if(n===e)return!0;const t=Object.keys(n).sort(),i=Object.keys(e).sort();if(t.length!==i.length)return!1;for(let s=0;s<t.length;s++){const r=t[s];if(r!==i[s]||n[r]!==e[r])return!1}return!0},mP=function(n,e,t){e=e||[];const i=[];let s=0;for(let r=0;r<e.length;r++){const a=e[r];if(n===a.timeline&&(i.push(r),s+=a.duration,s>t))return r}return i.length===0?0:i[i.length-1]},so=1,gP=500,yT=n=>typeof n=="number"&&isFinite(n),Cl=1/60,yP=(n,e,t)=>n!=="main"||!e||!t?null:!t.hasAudio&&!t.hasVideo?"Neither audio nor video found in segment.":e.hasVideo&&!t.hasVideo?"Only audio found in segment when we expected video. We can't switch to audio only from a stream that had video. To get rid of this message, please add codec information to the manifest.":!e.hasVideo&&t.hasVideo?"Video found in segment when we expected only audio. We can't switch to a stream with video from an audio only stream. To get rid of this message, please add codec information to the manifest.":null,vP=(n,e,t)=>{let i=e-Mt.BACK_BUFFER_LENGTH;n.length&&(i=Math.max(i,n.start(0)));const s=e-t;return Math.min(s,i)},$r=n=>{const{startOfSegment:e,duration:t,segment:i,part:s,playlist:{mediaSequence:r,id:a,segments:o=[]},mediaIndex:c,partIndex:l,timeline:u}=n,h=o.length-1;let p="mediaIndex/partIndex increment";n.getMediaInfoForTime?p=`getMediaInfoForTime (${n.getMediaInfoForTime})`:n.isSyncRequest&&(p="getSyncSegmentCandidate (isSyncRequest)"),n.independent&&(p+=` with independent ${n.independent}`);const y=typeof l=="number",_=n.segment.uri?"segment":"pre-segment",b=y?Cb({preloadSegment:i})-1:0;return`${_} [${r+c}/${r+h}]`+(y?` part [${l}/${b}]`:"")+` segment start/end [${i.start} => ${i.end}]`+(y?` part start/end [${s.start} => ${s.end}]`:"")+` startOfSegment [${e}] duration [${t}] timeline [${u}] selected by [${p}] playlist [${a}]`},vT=n=>`${n}TimingInfo`,bP=({segmentTimeline:n,currentTimeline:e,startOfSegment:t,buffered:i,overrideCheck:s})=>!s&&n===e?null:n<e?t:i.length?i.end(i.length-1):t,Sf=({timelineChangeController:n,currentTimeline:e,segmentTimeline:t,loaderType:i,audioDisabled:s})=>{if(e===t)return!1;if(i==="audio"){const r=n.lastTimelineChange({type:"main"});return!r||r.to!==t}if(i==="main"&&s){const r=n.pendingTimelineChange({type:"audio"});return!(r&&r.to===t)}return!1},TP=n=>{if(!n)return!1;const e=n.pendingTimelineChange({type:"audio"}),t=n.pendingTimelineChange({type:"main"}),i=e&&t,s=i&&e.to!==t.to;return!!(i&&e.from!==-1&&t.from!==-1&&s)},_P=n=>{const e=n.timelineChangeController_.pendingTimelineChange({type:"audio"}),t=n.timelineChangeController_.pendingTimelineChange({type:"main"});return e&&t&&e.to<t.to},ds=n=>{const e=n.pendingSegment_;if(!e)return;if(Sf({timelineChangeController:n.timelineChangeController_,currentTimeline:n.currentTimeline_,segmentTimeline:e.timeline,loaderType:n.loaderType_,audioDisabled:n.audioDisabled_})&&TP(n.timelineChangeController_)){if(_P(n)){n.timelineChangeController_.trigger("audioTimelineBehind");return}n.timelineChangeController_.trigger("fixBadTimelineChange")}},SP=n=>{let e=0;return["video","audio"].forEach(function(t){const i=n[`${t}TimingInfo`];if(!i)return;const{start:s,end:r}=i;let a;typeof s=="bigint"||typeof r=="bigint"?a=B.BigInt(r)-B.BigInt(s):typeof s=="number"&&typeof r=="number"&&(a=r-s),typeof a<"u"&&a>e&&(e=a)}),typeof e=="bigint"&&e<Number.MAX_SAFE_INTEGER&&(e=Number(e)),e},bT=({segmentDuration:n,maxDuration:e})=>n?Math.round(n)>e+mn:!1,CP=(n,e)=>{if(e!=="hls")return null;const t=SP({audioTimingInfo:n.audioTimingInfo,videoTimingInfo:n.videoTimingInfo});if(!t)return null;const i=n.playlist.targetDuration,s=bT({segmentDuration:t,maxDuration:i*2}),r=bT({segmentDuration:t,maxDuration:i}),a=`Segment with index ${n.mediaIndex} from playlist ${n.playlist.id} has a duration of ${t} when the reported duration is ${n.duration} and the target duration is ${i}. For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1`;return s||r?{severity:s?"warn":"info",message:a}:null},$s=({type:n,segment:e})=>{if(!e)return;const t=!!(e.key||e.map&&e.map.ke),i=!!(e.map&&!e.map.bytes),s=e.startOfSegment===void 0?e.start:e.startOfSegment;return{type:n||e.type,uri:e.resolvedUri||e.uri,start:s,duration:e.duration,isEncrypted:t,isMediaInitialization:i}};class Cf extends K.EventTarget{constructor(e,t={}){if(super(),!e)throw new TypeError("Initialization settings are required");if(typeof e.currentTime!="function")throw new TypeError("No currentTime getter specified");if(!e.mediaSource)throw new TypeError("No MediaSource specified");this.bandwidth=e.bandwidth,this.throughput={rate:0,count:0},this.roundTrip=NaN,this.resetStats_(),this.mediaIndex=null,this.partIndex=null,this.hasPlayed_=e.hasPlayed,this.currentTime_=e.currentTime,this.seekable_=e.seekable,this.seeking_=e.seeking,this.duration_=e.duration,this.mediaSource_=e.mediaSource,this.vhs_=e.vhs,this.loaderType_=e.loaderType,this.currentMediaInfo_=void 0,this.startingMediaInfo_=void 0,this.segmentMetadataTrack_=e.segmentMetadataTrack,this.goalBufferLength_=e.goalBufferLength,this.sourceType_=e.sourceType,this.sourceUpdater_=e.sourceUpdater,this.inbandTextTracks_=e.inbandTextTracks,this.state_="INIT",this.timelineChangeController_=e.timelineChangeController,this.shouldSaveSegmentTimingInfo_=!0,this.parse708captions_=e.parse708captions,this.useDtsForTimestampOffset_=e.useDtsForTimestampOffset,this.captionServices_=e.captionServices,this.exactManifestTimings=e.exactManifestTimings,this.addMetadataToTextTrack=e.addMetadataToTextTrack,this.checkBufferTimeout_=null,this.error_=void 0,this.currentTimeline_=-1,this.shouldForceTimestampOffsetAfterResync_=!1,this.pendingSegment_=null,this.xhrOptions_=null,this.pendingSegments_=[],this.audioDisabled_=!1,this.isPendingTimestampOffset_=!1,this.gopBuffer_=[],this.timeMapping_=0,this.safeAppend_=!1,this.appendInitSegment_={audio:!0,video:!0},this.playlistOfLastInitSegment_={audio:null,video:null},this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_={id3:[],caption:[]},this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=null,this.activeInitSegmentId_=null,this.initSegments_={},this.cacheEncryptionKeys_=e.cacheEncryptionKeys,this.keyCache_={},this.decrypter_=e.decrypter,this.syncController_=e.syncController,this.syncPoint_={segmentIndex:0,time:0},this.transmuxer_=this.createTransmuxer_(),this.triggerSyncInfoUpdate_=()=>this.trigger("syncinfoupdate"),this.syncController_.on("syncinfoupdate",this.triggerSyncInfoUpdate_),this.mediaSource_.addEventListener("sourceopen",()=>{this.isEndOfStream_()||(this.ended_=!1)}),this.fetchAtBuffer_=!1,this.logger_=Oi(`SegmentLoader[${this.loaderType_}]`),Object.defineProperty(this,"state",{get(){return this.state_},set(i){i!==this.state_&&(this.logger_(`${this.state_} -> ${i}`),this.state_=i,this.trigger("statechange"))}}),this.sourceUpdater_.on("ready",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():ds(this)}),this.sourceUpdater_.on("codecschange",i=>{this.trigger(vt({type:"codecschange"},i))}),this.loaderType_==="main"&&this.timelineChangeController_.on("pendingtimelinechange",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():ds(this)}),this.loaderType_==="audio"&&this.timelineChangeController_.on("timelinechange",i=>{this.trigger(vt({type:"timelinechange"},i)),this.hasEnoughInfoToLoad_()?this.processLoadQueue_():ds(this),this.hasEnoughInfoToAppend_()?this.processCallQueue_():ds(this)})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return vf.createTransmuxer({remux:!1,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:!0,parse708captions:this.parse708captions_,captionServices:this.captionServices_})}resetStats_(){this.mediaBytesTransferred=0,this.mediaRequests=0,this.mediaRequestsAborted=0,this.mediaRequestsTimedout=0,this.mediaRequestsErrored=0,this.mediaTransferDuration=0,this.mediaSecondsLoaded=0,this.mediaAppends=0}dispose(){this.trigger("dispose"),this.state="DISPOSED",this.pause(),this.abort_(),this.transmuxer_&&this.transmuxer_.terminate(),this.resetStats_(),this.checkBufferTimeout_&&B.clearTimeout(this.checkBufferTimeout_),this.syncController_&&this.triggerSyncInfoUpdate_&&this.syncController_.off("syncinfoupdate",this.triggerSyncInfoUpdate_),this.off()}setAudio(e){this.audioDisabled_=!e,e?this.appendInitSegment_.audio=!0:this.sourceUpdater_.removeAudio(0,this.duration_())}abort(){if(this.state!=="WAITING"){this.pendingSegment_&&(this.pendingSegment_=null),this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);return}this.abort_(),this.state="READY",this.paused()||this.monitorBuffer_()}abort_(){this.pendingSegment_&&this.pendingSegment_.abortRequests&&this.pendingSegment_.abortRequests(),this.pendingSegment_=null,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_),this.waitingOnRemove_=!1,B.clearTimeout(this.quotaExceededErrorRetryTimeout_),this.quotaExceededErrorRetryTimeout_=null}checkForAbort_(e){return this.state==="APPENDING"&&!this.pendingSegment_?(this.state="READY",!0):!this.pendingSegment_||this.pendingSegment_.requestId!==e}error(e){return typeof e<"u"&&(this.logger_("error occurred:",e),this.error_=e),this.pendingSegment_=null,this.error_}endOfStream(){this.ended_=!0,this.transmuxer_&&vf.reset(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered_(){const e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return Ot();if(this.loaderType_==="main"){const{hasAudio:t,hasVideo:i,isMuxed:s}=e;if(i&&t&&!this.audioDisabled_&&!s)return this.sourceUpdater_.buffered();if(i)return this.sourceUpdater_.videoBuffered()}return this.sourceUpdater_.audioBuffered()}initSegmentForMap(e,t=!1){if(!e)return null;const i=_l(e);let s=this.initSegments_[i];return t&&!s&&e.bytes&&(this.initSegments_[i]=s={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:e.bytes,tracks:e.tracks,timescales:e.timescales}),s||e}segmentKey(e,t=!1){if(!e)return null;const i=zb(e);let s=this.keyCache_[i];this.cacheEncryptionKeys_&&t&&!s&&e.bytes&&(this.keyCache_[i]=s={resolvedUri:e.resolvedUri,bytes:e.bytes});const r={resolvedUri:(s||e).resolvedUri};return s&&(r.bytes=s.bytes),r}couldBeginLoading_(){return this.playlist_&&!this.paused()}load(){if(this.monitorBuffer_(),!!this.playlist_){if(this.state==="INIT"&&this.couldBeginLoading_())return this.init_();!this.couldBeginLoading_()||this.state!=="READY"&&this.state!=="INIT"||(this.state="READY")}}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}playlist(e,t={}){if(!e||this.playlist_&&this.playlist_.endList&&e.endList&&this.playlist_.uri===e.uri)return;const i=this.playlist_,s=this.pendingSegment_;this.playlist_=e,this.xhrOptions_=t,this.state==="INIT"&&(e.syncInfo={mediaSequence:e.mediaSequence,time:0},this.loaderType_==="main"&&this.syncController_.setDateTimeMappingForStart(e));let r=null;if(i&&(i.id?r=i.id:i.uri&&(r=i.uri)),this.logger_(`playlist update [${r} => ${e.id||e.uri}]`),this.mediaSequenceSync_&&(this.mediaSequenceSync_.update(e,this.currentTime_()),this.logger_(`Playlist update:
|
|
253
|
+
currentTime: ${this.currentTime_()}
|
|
254
|
+
bufferedEnd: ${rf(this.buffered_())}
|
|
255
|
+
`,this.mediaSequenceSync_.diagnostics)),this.trigger("syncinfoupdate"),this.state==="INIT"&&this.couldBeginLoading_())return this.init_();if(!i||i.uri!==e.uri){this.mediaIndex!==null&&(!e.endList&&typeof e.partTargetDuration=="number"?this.resetLoader():this.resyncLoader()),this.currentMediaInfo_=void 0,this.trigger("playlistupdate");return}const a=e.mediaSequence-i.mediaSequence;if(this.logger_(`live window shift [${a}]`),this.mediaIndex!==null)if(this.mediaIndex-=a,this.mediaIndex<0)this.mediaIndex=null,this.partIndex=null;else{const o=this.playlist_.segments[this.mediaIndex];if(this.partIndex&&(!o.parts||!o.parts.length||!o.parts[this.partIndex])){const c=this.mediaIndex;this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`),this.resetLoader(),this.mediaIndex=c}}s&&(s.mediaIndex-=a,s.mediaIndex<0?(s.mediaIndex=null,s.partIndex=null):(s.mediaIndex>=0&&(s.segment=e.segments[s.mediaIndex]),s.partIndex>=0&&s.segment.parts&&(s.part=s.segment.parts[s.partIndex]))),this.syncController_.saveExpiredSegmentInfo(i,e)}pause(){this.checkBufferTimeout_&&(B.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=null)}paused(){return this.checkBufferTimeout_===null}resetEverything(e){this.ended_=!1,this.activeInitSegmentId_=null,this.appendInitSegment_={audio:!0,video:!0},this.resetLoader(),this.remove(0,1/0,e),this.transmuxer_&&(this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.transmuxer_.postMessage({action:"reset"}))}resetLoader(){this.fetchAtBuffer_=!1,this.mediaSequenceSync_&&this.mediaSequenceSync_.resetAppendedStatus(),this.resyncLoader()}resyncLoader(){this.transmuxer_&&vf.reset(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1;const e=this.currentMediaInfo_&&this.currentMediaInfo_.isFmp4;this.sourceType_==="hls"&&!e&&(this.shouldForceTimestampOffsetAfterResync_=!0),this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.abort(),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}remove(e,t,i=()=>{},s=!1){if(t===1/0&&(t=this.duration_()),t<=e){this.logger_("skipping remove because end ${end} is <= start ${start}");return}if(!this.sourceUpdater_||!this.getMediaInfo_()){this.logger_("skipping remove because no source updater or starting media info");return}let r=1;const a=()=>{r--,r===0&&i()};(s||!this.audioDisabled_)&&(r++,this.sourceUpdater_.removeAudio(e,t,a)),(s||this.loaderType_==="main")&&(this.gopBuffer_=fP(this.gopBuffer_,e,t,this.timeMapping_),r++,this.sourceUpdater_.removeVideo(e,t,a));for(const o in this.inbandTextTracks_)no(e,t,this.inbandTextTracks_[o]);no(e,t,this.segmentMetadataTrack_),a()}monitorBuffer_(){this.checkBufferTimeout_&&B.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=B.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){this.state==="READY"&&this.fillBuffer_(),this.checkBufferTimeout_&&B.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=B.setTimeout(this.monitorBufferTick_.bind(this),gP)}fillBuffer_(){if(this.sourceUpdater_.updating())return;const e=this.chooseNextRequest_();if(!e)return;const t={segmentInfo:$s({type:this.loaderType_,segment:e})};this.trigger({type:"segmentselected",metadata:t}),typeof e.timestampOffset=="number"&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline})),this.loadSegment_(e)}isEndOfStream_(e=this.mediaIndex,t=this.playlist_,i=this.partIndex){if(!t||!this.mediaSource_)return!1;const s=typeof e=="number"&&t.segments[e],r=e+1===t.segments.length,a=!s||!s.parts||i+1===s.parts.length;return t.endList&&this.mediaSource_.readyState==="open"&&r&&a}chooseNextRequest_(){const e=this.buffered_(),t=rf(e)||0,i=af(e,this.currentTime_()),s=!this.hasPlayed_()&&i>=1,r=i>=this.goalBufferLength_(),a=this.playlist_.segments;if(!a.length||s||r)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_(),this.loaderType_);const o={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:!this.syncPoint_};if(o.isSyncRequest)o.mediaIndex=mP(this.currentTimeline_,a,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${o.mediaIndex}`);else if(this.mediaIndex!==null){const p=a[this.mediaIndex],y=typeof this.partIndex=="number"?this.partIndex:-1;o.startOfSegment=p.end?p.end:t,p.parts&&p.parts[y+1]?(o.mediaIndex=this.mediaIndex,o.partIndex=y+1):o.mediaIndex=this.mediaIndex+1}else{let p,y,_;const b=this.fetchAtBuffer_?t:this.currentTime_();if(this.mediaSequenceSync_&&this.logger_(`chooseNextRequest_ request after Quality Switch:
|
|
256
|
+
For TargetTime: ${b}.
|
|
257
|
+
CurrentTime: ${this.currentTime_()}
|
|
258
|
+
BufferedEnd: ${t}
|
|
259
|
+
Fetch At Buffer: ${this.fetchAtBuffer_}
|
|
260
|
+
`,this.mediaSequenceSync_.diagnostics),this.mediaSequenceSync_&&this.mediaSequenceSync_.isReliable){const S=this.getSyncInfoFromMediaSequenceSync_(b);if(!S){const D="No sync info found while using media sequence sync";return this.error({message:D,metadata:{errorType:K.Error.StreamingFailedToSelectNextSegment,error:new Error(D)}}),this.logger_("chooseNextRequest_ - no sync info found using media sequence sync"),null}this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${S.start} --> ${S.end})`),p=S.segmentIndex,y=S.partIndex,_=S.start}else{this.logger_("chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.");const S=hi.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:b,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});p=S.segmentIndex,y=S.partIndex,_=S.startTime}o.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${b}`:`currentTime ${b}`,o.mediaIndex=p,o.startOfSegment=_,o.partIndex=y,this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${o.mediaIndex} `)}const c=a[o.mediaIndex];let l=c&&typeof o.partIndex=="number"&&c.parts&&c.parts[o.partIndex];if(!c||typeof o.partIndex=="number"&&!l)return null;typeof o.partIndex!="number"&&c.parts&&(o.partIndex=0,l=c.parts[0]);const u=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;if(!i&&l&&!u&&!l.independent)if(o.partIndex===0){const p=a[o.mediaIndex-1],y=p.parts&&p.parts.length&&p.parts[p.parts.length-1];y&&y.independent&&(o.mediaIndex-=1,o.partIndex=p.parts.length-1,o.independent="previous segment")}else c.parts[o.partIndex-1].independent&&(o.partIndex-=1,o.independent="previous part");const h=this.mediaSource_&&this.mediaSource_.readyState==="ended";return o.mediaIndex>=a.length-1&&h&&!this.seeking_()?null:(this.shouldForceTimestampOffsetAfterResync_&&(this.shouldForceTimestampOffsetAfterResync_=!1,o.forceTimestampOffset=!0,this.logger_("choose next request. Force timestamp offset after loader resync")),this.generateSegmentInfo_(o))}getSyncInfoFromMediaSequenceSync_(e){if(!this.mediaSequenceSync_)return null;const t=Math.max(e,this.mediaSequenceSync_.start);e!==t&&this.logger_(`getSyncInfoFromMediaSequenceSync_. Pulled target time from ${e} to ${t}`);const i=this.mediaSequenceSync_.getSyncInfoForTime(t);if(!i)return null;if(!i.isAppended)return i;const s=this.mediaSequenceSync_.getSyncInfoForTime(i.end);return s?(s.isAppended&&this.logger_("getSyncInfoFromMediaSequenceSync_: We encounter unexpected scenario where next media sequence sync info is also appended!"),s):null}generateSegmentInfo_(e){const{independent:t,playlist:i,mediaIndex:s,startOfSegment:r,isSyncRequest:a,partIndex:o,forceTimestampOffset:c,getMediaInfoForTime:l}=e,u=i.segments[s],h=typeof o=="number"&&u.parts[o],p={requestId:"segment-loader-"+Math.random(),uri:h&&h.resolvedUri||u.resolvedUri,mediaIndex:s,partIndex:h?o:null,isSyncRequest:a,startOfSegment:r,playlist:i,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:u.timeline,duration:h&&h.duration||u.duration,segment:u,part:h,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:l,independent:t},y=typeof c<"u"?c:this.isPendingTimestampOffset_;p.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:u.timeline,currentTimeline:this.currentTimeline_,startOfSegment:r,buffered:this.buffered_(),overrideCheck:y});const _=rf(this.sourceUpdater_.audioBuffered());return typeof _=="number"&&(p.audioAppendStart=_-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(p.gopsToAlignWith=dP(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),p}timestampOffsetForSegment_(e){return bP(e)}earlyAbortWhenNeeded_(e){if(this.vhs_.tech_.paused()||!this.xhrOptions_.timeout||!this.playlist_.attributes.BANDWIDTH||Date.now()-(e.firstBytesReceivedAt||Date.now())<1e3)return;const t=this.currentTime_(),i=e.bandwidth,s=this.pendingSegment_.duration,r=hi.estimateSegmentRequestTime(s,i,this.playlist_,e.bytesReceived),a=$A(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(r<=a)return;const o=eP({main:this.vhs_.playlists.main,currentTime:t,bandwidth:i,duration:this.duration_(),segmentDuration:s,timeUntilRebuffer:a,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!o)return;const l=r-a-o.rebufferingImpact;let u=.5;a<=mn&&(u=1),!(!o.playlist||o.playlist.uri===this.playlist_.uri||l<u)&&(this.bandwidth=o.playlist.attributes.BANDWIDTH*Mt.BANDWIDTH_VARIANCE+1,this.trigger("earlyabort"))}handleAbort_(e){this.logger_(`Aborting ${$r(e)}`),this.mediaRequestsAborted+=1}handleProgress_(e,t){this.earlyAbortWhenNeeded_(t.stats),!this.checkForAbort_(t.requestId)&&this.trigger("progress")}handleTrackInfo_(e,t){const{hasAudio:i,hasVideo:s}=t,r={segmentInfo:$s({type:this.loaderType_,segment:e}),trackInfo:{hasAudio:i,hasVideo:s}};this.trigger({type:"segmenttransmuxingtrackinfoavailable",metadata:r}),this.earlyAbortWhenNeeded_(e.stats),!this.checkForAbort_(e.requestId)&&(this.checkForIllegalMediaSwitch(t)||(t=t||{},pP(this.currentMediaInfo_,t)||(this.appendInitSegment_={audio:!0,video:!0},this.startingMediaInfo_=t,this.currentMediaInfo_=t,this.logger_("trackinfo update",t),this.trigger("trackinfo")),!this.checkForAbort_(e.requestId)&&(this.pendingSegment_.trackInfo=t,this.hasEnoughInfoToAppend_()?this.processCallQueue_():ds(this))))}handleTimingInfo_(e,t,i,s){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;const r=this.pendingSegment_,a=vT(t);r[a]=r[a]||{},r[a][i]=s,this.logger_(`timinginfo: ${t} - ${i} - ${s}`),this.hasEnoughInfoToAppend_()?this.processCallQueue_():ds(this)}handleCaptions_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(t.length===0){this.logger_("SegmentLoader received no captions from a caption event");return}if(!this.pendingSegment_.hasAppendedData_){this.metadataQueue_.caption.push(this.handleCaptions_.bind(this,e,t));return}const s=this.sourceUpdater_.videoTimestampOffset()===null?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset(),r={};t.forEach(a=>{r[a.stream]=r[a.stream]||{startTime:1/0,captions:[],endTime:0};const o=r[a.stream];o.startTime=Math.min(o.startTime,a.startTime+s),o.endTime=Math.max(o.endTime,a.endTime+s),o.captions.push(a)}),Object.keys(r).forEach(a=>{const{startTime:o,endTime:c,captions:l}=r[a],u=this.inbandTextTracks_;this.logger_(`adding cues from ${o} -> ${c} for ${a}`),nP(u,this.vhs_.tech_,a),no(o,c,u[a]),sP({captionArray:l,inbandTextTracks:u,timestampOffset:s})}),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}handleId3_(e,t,i){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(!this.pendingSegment_.hasAppendedData_){this.metadataQueue_.id3.push(this.handleId3_.bind(this,e,t,i));return}this.addMetadataToTextTrack(i,t,this.duration_())}processMetadataQueue_(){this.metadataQueue_.id3.forEach(e=>e()),this.metadataQueue_.caption.forEach(e=>e()),this.metadataQueue_.id3=[],this.metadataQueue_.caption=[]}processCallQueue_(){const e=this.callQueue_;this.callQueue_=[],e.forEach(t=>t())}processLoadQueue_(){const e=this.loadQueue_;this.loadQueue_=[],e.forEach(t=>t())}hasEnoughInfoToLoad_(){if(this.loaderType_!=="audio")return!0;const e=this.pendingSegment_;return e?this.getCurrentMediaInfo_()?!Sf({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}):!0:!1}getCurrentMediaInfo_(e=this.pendingSegment_){return e&&e.trackInfo||this.currentMediaInfo_}getMediaInfo_(e=this.pendingSegment_){return this.getCurrentMediaInfo_(e)||this.startingMediaInfo_}getPendingSegmentPlaylist(){return this.pendingSegment_?this.pendingSegment_.playlist:null}hasEnoughInfoToAppend_(){if(!this.sourceUpdater_.ready()||this.waitingOnRemove_||this.quotaExceededErrorRetryTimeout_)return!1;const e=this.pendingSegment_,t=this.getCurrentMediaInfo_();if(!e||!t)return!1;const{hasAudio:i,hasVideo:s,isMuxed:r}=t;return!(s&&!e.videoTimingInfo||i&&!this.audioDisabled_&&!r&&!e.audioTimingInfo||Sf({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}handleData_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(this.callQueue_.length||!this.hasEnoughInfoToAppend_()){ds(this),this.callQueue_.push(this.handleData_.bind(this,e,t));return}const i=this.pendingSegment_;if(this.setTimeMapping_(i.timeline),this.updateMediaSecondsLoaded_(i.part||i.segment),this.mediaSource_.readyState!=="closed"){if(e.map&&(e.map=this.initSegmentForMap(e.map,!0),i.segment.map=e.map),e.key&&this.segmentKey(e.key,!0),i.isFmp4=e.isFmp4,i.timingInfo=i.timingInfo||{},i.isFmp4)this.trigger("fmp4"),i.timingInfo.start=i[vT(t.type)].start;else{const s=this.getCurrentMediaInfo_(),r=this.loaderType_==="main"&&s&&s.hasVideo;let a;r&&(a=i.videoTimingInfo.start),i.timingInfo.start=this.trueSegmentStart_({currentStart:i.timingInfo.start,playlist:i.playlist,mediaIndex:i.mediaIndex,currentVideoTimestampOffset:this.sourceUpdater_.videoTimestampOffset(),useVideoTimingInfo:r,firstVideoFrameTimeForData:a,videoTimingInfo:i.videoTimingInfo,audioTimingInfo:i.audioTimingInfo})}if(this.updateAppendInitSegmentStatus(i,t.type),this.updateSourceBufferTimestampOffset_(i),i.isSyncRequest){this.updateTimingInfoEnd_(i),this.syncController_.saveSegmentTimingInfo({segmentInfo:i,shouldSaveTimelineMapping:this.loaderType_==="main"});const s=this.chooseNextRequest_();if(s.mediaIndex!==i.mediaIndex||s.partIndex!==i.partIndex){this.logger_("sync segment was incorrect, not appending");return}this.logger_("sync segment was correct, appending")}i.hasAppendedData_=!0,this.processMetadataQueue_(),this.appendData_(i,t)}}updateAppendInitSegmentStatus(e,t){this.loaderType_==="main"&&typeof e.timestampOffset=="number"&&!e.changedTimestampOffset&&(this.appendInitSegment_={audio:!0,video:!0}),this.playlistOfLastInitSegment_[t]!==e.playlist&&(this.appendInitSegment_[t]=!0)}getInitSegmentAndUpdateState_({type:e,initSegment:t,map:i,playlist:s}){if(i){const r=_l(i);if(this.activeInitSegmentId_===r)return null;t=this.initSegmentForMap(i,!0).bytes,this.activeInitSegmentId_=r}return t&&this.appendInitSegment_[e]?(this.playlistOfLastInitSegment_[e]=s,this.appendInitSegment_[e]=!1,this.activeInitSegmentId_=null,t):null}handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i},s){const r=this.sourceUpdater_.audioBuffered(),a=this.sourceUpdater_.videoBuffered();r.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+js(r).join(", ")),a.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+js(a).join(", "));const o=r.length?r.start(0):0,c=r.length?r.end(r.length-1):0,l=a.length?a.start(0):0,u=a.length?a.end(a.length-1):0;if(c-o<=so&&u-l<=so){this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${i.byteLength}, audio buffer: ${js(r).join(", ")}, video buffer: ${js(a).join(", ")}, `),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:1/0}),this.trigger("error");return}this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:e,type:t,bytes:i}));const p=this.currentTime_()-so;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${p}`),this.remove(0,p,()=>{this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${so}s`),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=B.setTimeout(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()},so*1e3)},!0)}handleAppendError_({segmentInfo:e,type:t,bytes:i},s){if(s){if(s.code===Nb){this.handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i});return}this.logger_("Received non QUOTA_EXCEEDED_ERR on append",s),this.error({message:`${t} append of ${i.length}b failed for segment #${e.mediaIndex} in playlist ${e.playlist.id}`,metadata:{errorType:K.Error.StreamingFailedToAppendSegment}}),this.trigger("appenderror")}}appendToSourceBuffer_({segmentInfo:e,type:t,initSegment:i,data:s,bytes:r}){if(!r){const o=[s];let c=s.byteLength;i&&(o.unshift(i),c+=i.byteLength),r=iP({bytes:c,segments:o})}const a={segmentInfo:$s({type:this.loaderType_,segment:e})};this.trigger({type:"segmentappendstart",metadata:a}),this.sourceUpdater_.appendBuffer({segmentInfo:e,type:t,bytes:r},this.handleAppendError_.bind(this,{segmentInfo:e,type:t,bytes:r}))}handleSegmentTimingInfo_(e,t,i){if(!this.pendingSegment_||t!==this.pendingSegment_.requestId)return;const s=this.pendingSegment_.segment,r=`${e}TimingInfo`;s[r]||(s[r]={}),s[r].transmuxerPrependedSeconds=i.prependedContentDuration||0,s[r].transmuxedPresentationStart=i.start.presentation,s[r].transmuxedDecodeStart=i.start.decode,s[r].transmuxedPresentationEnd=i.end.presentation,s[r].transmuxedDecodeEnd=i.end.decode,s[r].baseMediaDecodeTime=i.baseMediaDecodeTime}appendData_(e,t){const{type:i,data:s}=t;if(!s||!s.byteLength||i==="audio"&&this.audioDisabled_)return;const r=this.getInitSegmentAndUpdateState_({type:i,initSegment:t.initSegment,playlist:e.playlist,map:e.isFmp4?e.segment.map:null});this.appendToSourceBuffer_({segmentInfo:e,type:i,initSegment:r,data:s})}loadSegment_(e){if(this.state="WAITING",this.pendingSegment_=e,this.trimBackBuffer_(e),typeof e.timestampOffset=="number"&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),!this.hasEnoughInfoToLoad_()){ds(this),this.loadQueue_.push(()=>{const t=vt({},e,{forceTimestampOffset:!0});vt(e,this.generateSegmentInfo_(t)),this.isPendingTimestampOffset_=!1,this.updateTransmuxerAndRequestSegment_(e)});return}this.updateTransmuxerAndRequestSegment_(e)}updateTransmuxerAndRequestSegment_(e){this.shouldUpdateTransmuxerTimestampOffset_(e.timestampOffset)&&(this.gopBuffer_.length=0,e.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:"reset"}),this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:e.timestampOffset}));const t=this.createSimplifiedSegmentObj_(e),i=this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex),s=this.mediaIndex!==null,r=e.timeline!==this.currentTimeline_&&e.timeline>0,a=i||s&&r;this.logger_(`Requesting
|
|
261
|
+
${mT(e.uri)}
|
|
262
|
+
${$r(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=QD({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:t,abortFn:this.handleAbort_.bind(this,e),progressFn:this.handleProgress_.bind(this),trackInfoFn:this.handleTrackInfo_.bind(this),timingInfoFn:this.handleTimingInfo_.bind(this),videoSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"video",e.requestId),audioSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"audio",e.requestId),captionsFn:this.handleCaptions_.bind(this),isEndOfTimeline:a,endedTimelineFn:()=>{this.logger_("received endedtimeline callback")},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this),onTransmuxerLog:({message:o,level:c,stream:l})=>{this.logger_(`${$r(e)} logged from transmuxer stream ${l} as a ${c}: ${o}`)},triggerSegmentEventFn:({type:o,segment:c,keyInfo:l,trackInfo:u,timingInfo:h})=>{const y={segmentInfo:$s({segment:c})};l&&(y.keyInfo=l),u&&(y.trackInfo=u),h&&(y.timingInfo=h),this.trigger({type:o,metadata:y})}})}trimBackBuffer_(e){const t=vP(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);t>0&&this.remove(0,t)}createSimplifiedSegmentObj_(e){const t=e.segment,i=e.part,s=e.segment.key||e.segment.map&&e.segment.map.key,r=e.segment.map&&!e.segment.map.bytes,a={resolvedUri:i?i.resolvedUri:t.resolvedUri,byterange:i?i.byterange:t.byterange,requestId:e.requestId,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,part:e.part,type:this.loaderType_,start:e.startOfSegment,duration:e.duration,isEncrypted:s,isMediaInitialization:r},o=e.playlist.segments[e.mediaIndex-1];if(o&&o.timeline===t.timeline&&(o.videoTimingInfo?a.baseStartTime=o.videoTimingInfo.transmuxedDecodeEnd:o.audioTimingInfo&&(a.baseStartTime=o.audioTimingInfo.transmuxedDecodeEnd)),t.key){const c=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);a.key=this.segmentKey(t.key),a.key.iv=c}return t.map&&(a.map=this.initSegmentForMap(t.map)),a}saveTransferStats_(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)}saveBandwidthRelatedStats_(e,t){if(this.pendingSegment_.byteLength=t.bytesReceived,e<Cl){this.logger_(`Ignoring segment's bandwidth because its duration of ${e} is less than the min to record ${Cl}`);return}const i={bandwidthInfo:{from:this.bandwidth,to:t.bandwidth}};this.trigger({type:"bandwidthupdated",metadata:i}),this.bandwidth=t.bandwidth,this.roundTrip=t.roundTripTime}handleTimeout_(){this.mediaRequestsTimedout+=1,this.bandwidth=1,this.roundTrip=NaN,this.trigger("bandwidthupdate"),this.trigger("timeout")}segmentRequestFinished_(e,t,i){if(this.callQueue_.length){this.callQueue_.push(this.segmentRequestFinished_.bind(this,e,t,i));return}if(this.saveTransferStats_(t.stats),!this.pendingSegment_||t.requestId!==this.pendingSegment_.requestId)return;if(e){if(this.pendingSegment_=null,this.state="READY",e.code===yn.ABORTED)return;if(this.pause(),e.code===yn.TIMEOUT){this.handleTimeout_();return}this.mediaRequestsErrored+=1,this.error(e),this.trigger("error");return}const s=this.pendingSegment_;this.saveBandwidthRelatedStats_(s.duration,t.stats),s.endOfAllRequests=t.endOfAllRequests,i.gopInfo&&(this.gopBuffer_=hP(this.gopBuffer_,i.gopInfo,this.safeAppend_)),this.state="APPENDING",this.trigger("appending"),this.waitForAppendsToComplete_(s)}setTimeMapping_(e){const t=this.syncController_.mappingForTimeline(e);t!==null&&(this.timeMapping_=t)}updateMediaSecondsLoaded_(e){typeof e.start=="number"&&typeof e.end=="number"?this.mediaSecondsLoaded+=e.end-e.start:this.mediaSecondsLoaded+=e.duration}shouldUpdateTransmuxerTimestampOffset_(e){return e===null?!1:this.loaderType_==="main"&&e!==this.sourceUpdater_.videoTimestampOffset()||!this.audioDisabled_&&e!==this.sourceUpdater_.audioTimestampOffset()}trueSegmentStart_({currentStart:e,playlist:t,mediaIndex:i,firstVideoFrameTimeForData:s,currentVideoTimestampOffset:r,useVideoTimingInfo:a,videoTimingInfo:o,audioTimingInfo:c}){if(typeof e<"u")return e;if(!a)return c.start;const l=t.segments[i-1];return i===0||!l||typeof l.start>"u"||l.end!==s+r?s:o.start}waitForAppendsToComplete_(e){const t=this.getCurrentMediaInfo_(e);if(!t){this.error({message:"No starting media returned, likely due to an unsupported media format.",playlistExclusionDuration:1/0}),this.trigger("error");return}const{hasAudio:i,hasVideo:s,isMuxed:r}=t,a=this.loaderType_==="main"&&s,o=!this.audioDisabled_&&i&&!r;if(e.waitingOnAppends=0,!e.hasAppendedData_){!e.timingInfo&&typeof e.timestampOffset=="number"&&(this.isPendingTimestampOffset_=!0),e.timingInfo={start:0},e.waitingOnAppends++,this.isPendingTimestampOffset_||(this.updateSourceBufferTimestampOffset_(e),this.processMetadataQueue_()),this.checkAppendsDone_(e);return}a&&e.waitingOnAppends++,o&&e.waitingOnAppends++,a&&this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this,e)),o&&this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this,e))}checkAppendsDone_(e){this.checkForAbort_(e.requestId)||(e.waitingOnAppends--,e.waitingOnAppends===0&&this.handleAppendsDone_())}checkForIllegalMediaSwitch(e){const t=yP(this.loaderType_,this.getCurrentMediaInfo_(),e);return t?(this.error({message:t,playlistExclusionDuration:1/0}),this.trigger("error"),!0):!1}updateSourceBufferTimestampOffset_(e){if(e.timestampOffset===null||typeof e.timingInfo.start!="number"||e.changedTimestampOffset||this.loaderType_!=="main")return;let t=!1;e.timestampOffset-=this.getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e.segment.videoTimingInfo,audioTimingInfo:e.segment.audioTimingInfo,timingInfo:e.timingInfo}),e.changedTimestampOffset=!0,e.timestampOffset!==this.sourceUpdater_.videoTimestampOffset()&&(this.sourceUpdater_.videoTimestampOffset(e.timestampOffset),t=!0),e.timestampOffset!==this.sourceUpdater_.audioTimestampOffset()&&(this.sourceUpdater_.audioTimestampOffset(e.timestampOffset),t=!0),t&&this.trigger("timestampoffset")}getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e,audioTimingInfo:t,timingInfo:i}){return this.useDtsForTimestampOffset_?e&&typeof e.transmuxedDecodeStart=="number"?e.transmuxedDecodeStart:t&&typeof t.transmuxedDecodeStart=="number"?t.transmuxedDecodeStart:i.start:i.start}updateTimingInfoEnd_(e){e.timingInfo=e.timingInfo||{};const t=this.getMediaInfo_(),s=this.loaderType_==="main"&&t&&t.hasVideo&&e.videoTimingInfo?e.videoTimingInfo:e.audioTimingInfo;s&&(e.timingInfo.end=typeof s.end=="number"?s.end:s.start+e.duration)}handleAppendsDone_(){if(this.pendingSegment_){const c={segmentInfo:$s({type:this.loaderType_,segment:this.pendingSegment_})};this.trigger({type:"appendsdone",metadata:c})}if(!this.pendingSegment_){this.state="READY",this.paused()||this.monitorBuffer_();return}const e=this.pendingSegment_;e.part&&e.part.syncInfo?e.part.syncInfo.markAppended():e.segment.syncInfo&&e.segment.syncInfo.markAppended(),this.updateTimingInfoEnd_(e),this.shouldSaveSegmentTimingInfo_&&this.syncController_.saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:this.loaderType_==="main"});const t=CP(e,this.sourceType_);if(t&&(t.severity==="warn"?K.log.warn(t.message):this.logger_(t.message)),this.recordThroughput_(e),this.pendingSegment_=null,this.state="READY",e.isSyncRequest&&(this.trigger("syncinfoupdate"),!e.hasAppendedData_)){this.logger_(`Throwing away un-appended sync request ${$r(e)}`);return}this.logger_(`Appended ${$r(e)}`),this.addSegmentMetadataCue_(e),this.fetchAtBuffer_=!0,this.currentTimeline_!==e.timeline&&(this.timelineChangeController_.lastTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline}),this.loaderType_==="main"&&!this.audioDisabled_&&this.timelineChangeController_.lastTimelineChange({type:"audio",from:this.currentTimeline_,to:e.timeline})),this.currentTimeline_=e.timeline,this.trigger("syncinfoupdate");const i=e.segment,s=e.part,r=i.end&&this.currentTime_()-i.end>e.playlist.targetDuration*3,a=s&&s.end&&this.currentTime_()-s.end>e.playlist.partTargetDuration*3;if(r||a){this.logger_(`bad ${r?"segment":"part"} ${$r(e)}`),this.resetEverything();return}this.mediaIndex!==null&&this.trigger("bandwidthupdate"),this.trigger("progress"),this.mediaIndex=e.mediaIndex,this.partIndex=e.partIndex,this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex)&&this.endOfStream(),this.trigger("appended"),e.hasAppendedData_&&this.mediaAppends++,this.paused()||this.monitorBuffer_()}recordThroughput_(e){if(e.duration<Cl){this.logger_(`Ignoring segment's throughput because its duration of ${e.duration} is less than the min to record ${Cl}`);return}const t=this.throughput.rate,i=Date.now()-e.endOfAllRequests+1,s=Math.floor(e.byteLength/i*8*1e3);this.throughput.rate+=(s-t)/++this.throughput.count}addSegmentMetadataCue_(e){if(!this.segmentMetadataTrack_)return;const t=e.segment,i=t.start,s=t.end;if(!yT(i)||!yT(s))return;no(i,s,this.segmentMetadataTrack_);const r=B.WebKitDataCue||B.VTTCue,a={custom:t.custom,dateTimeObject:t.dateTimeObject,dateTimeString:t.dateTimeString,programDateTime:t.programDateTime,bandwidth:e.playlist.attributes.BANDWIDTH,resolution:e.playlist.attributes.RESOLUTION,codecs:e.playlist.attributes.CODECS,byteLength:e.byteLength,uri:e.uri,timeline:e.timeline,playlist:e.playlist.id,start:i,end:s},o=JSON.stringify(a),c=new r(i,s,o);c.value=a,this.segmentMetadataTrack_.addCue(c)}}function Fn(){}const TT=function(n){return typeof n!="string"?n:n.replace(/./,e=>e.toUpperCase())},kP=["video","audio"],kf=(n,e)=>{const t=e[`${n}Buffer`];return t&&t.updating||e.queuePending[n]},EP=(n,e)=>{for(let t=0;t<e.length;t++){const i=e[t];if(i.type==="mediaSource")return null;if(i.type===n)return t}return null},Wr=(n,e)=>{if(e.queue.length===0)return;let t=0,i=e.queue[t];if(i.type==="mediaSource"){!e.updating()&&e.mediaSource.readyState!=="closed"&&(e.queue.shift(),i.action(e),i.doneFn&&i.doneFn(),Wr("audio",e),Wr("video",e));return}if(n!=="mediaSource"&&!(!e.ready()||e.mediaSource.readyState==="closed"||kf(n,e))){if(i.type!==n){if(t=EP(n,e.queue),t===null)return;i=e.queue[t]}if(e.queue.splice(t,1),e.queuePending[n]=i,i.action(n,e),!i.doneFn){e.queuePending[n]=null,Wr(n,e);return}}},_T=(n,e)=>{const t=e[`${n}Buffer`],i=TT(n);t&&(t.removeEventListener("updateend",e[`on${i}UpdateEnd_`]),t.removeEventListener("error",e[`on${i}Error_`]),e.codecs[n]=null,e[`${n}Buffer`]=null)},vn=(n,e)=>n&&e&&Array.prototype.indexOf.call(n.sourceBuffers,e)!==-1,Ti={appendBuffer:(n,e,t)=>(i,s)=>{const r=s[`${i}Buffer`];if(vn(s.mediaSource,r)){s.logger_(`Appending segment ${e.mediaIndex}'s ${n.length} bytes to ${i}Buffer`);try{r.appendBuffer(n)}catch(a){s.logger_(`Error with code ${a.code} `+(a.code===Nb?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${e.mediaIndex} to ${i}Buffer`),s.queuePending[i]=null,t(a)}}},remove:(n,e)=>(t,i)=>{const s=i[`${t}Buffer`];if(vn(i.mediaSource,s)){i.logger_(`Removing ${n} to ${e} from ${t}Buffer`);try{s.remove(n,e)}catch{i.logger_(`Remove ${n} to ${e} from ${t}Buffer failed`)}}},timestampOffset:n=>(e,t)=>{const i=t[`${e}Buffer`];vn(t.mediaSource,i)&&(t.logger_(`Setting ${e}timestampOffset to ${n}`),i.timestampOffset=n)},callback:n=>(e,t)=>{n()},endOfStream:n=>e=>{if(e.mediaSource.readyState==="open"){e.logger_(`Calling mediaSource endOfStream(${n||""})`);try{e.mediaSource.endOfStream(n)}catch(t){K.log.warn("Failed to call media source endOfStream",t)}}},duration:n=>e=>{e.logger_(`Setting mediaSource duration to ${n}`);try{e.mediaSource.duration=n}catch(t){K.log.warn("Failed to set media source duration",t)}},abort:()=>(n,e)=>{if(e.mediaSource.readyState!=="open")return;const t=e[`${n}Buffer`];if(vn(e.mediaSource,t)){e.logger_(`calling abort on ${n}Buffer`);try{t.abort()}catch(i){K.log.warn(`Failed to abort on ${n}Buffer`,i)}}},addSourceBuffer:(n,e)=>t=>{const i=TT(n),s=gr(e);t.logger_(`Adding ${n}Buffer with codec ${e} to mediaSource`);const r=t.mediaSource.addSourceBuffer(s);r.addEventListener("updateend",t[`on${i}UpdateEnd_`]),r.addEventListener("error",t[`on${i}Error_`]),t.codecs[n]=e,t[`${n}Buffer`]=r},removeSourceBuffer:n=>e=>{const t=e[`${n}Buffer`];if(_T(n,e),!!vn(e.mediaSource,t)){e.logger_(`Removing ${n}Buffer with codec ${e.codecs[n]} from mediaSource`);try{e.mediaSource.removeSourceBuffer(t)}catch(i){K.log.warn(`Failed to removeSourceBuffer ${n}Buffer`,i)}}},changeType:n=>(e,t)=>{const i=t[`${e}Buffer`],s=gr(n);if(!vn(t.mediaSource,i))return;const r=n.substring(0,n.indexOf(".")),a=t.codecs[e];if(a.substring(0,a.indexOf("."))===r)return;const c={codecsChangeInfo:{from:a,to:n}};t.trigger({type:"codecschange",metadata:c}),t.logger_(`changing ${e}Buffer codec from ${a} to ${n}`);try{i.changeType(s),t.codecs[e]=n}catch(l){c.errorType=K.Error.StreamingCodecsChangeError,c.error=l,l.metadata=c,t.error_=l,t.trigger("error"),K.log.warn(`Failed to changeType on ${e}Buffer`,l)}}},_i=({type:n,sourceUpdater:e,action:t,doneFn:i,name:s})=>{e.queue.push({type:n,action:t,doneFn:i,name:s}),Wr(n,e)},ST=(n,e)=>t=>{const i=e[`${n}Buffered`](),s=VA(i);if(e.logger_(`received "updateend" event for ${n} Source Buffer: `,s),e.queuePending[n]){const r=e.queuePending[n].doneFn;e.queuePending[n]=null,r&&r(e[`${n}Error_`])}Wr(n,e)};class CT extends K.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>Wr("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=Oi("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=ST("video",this),this.onAudioUpdateEnd_=ST("audio",this),this.onVideoError_=t=>{this.videoError_=t},this.onAudioError_=t=>{this.audioError_=t},this.createdSourceBuffers_=!1,this.initializedEme_=!1,this.triggeredReady_=!1}initializedEme(){this.initializedEme_=!0,this.triggerReady()}hasCreatedSourceBuffers(){return this.createdSourceBuffers_}hasInitializedAnyEme(){return this.initializedEme_}ready(){return this.hasCreatedSourceBuffers()&&this.hasInitializedAnyEme()}createSourceBuffers(e){this.hasCreatedSourceBuffers()||(this.addOrChangeSourceBuffers(e),this.createdSourceBuffers_=!0,this.trigger("createdsourcebuffers"),this.triggerReady())}triggerReady(){this.ready()&&!this.triggeredReady_&&(this.triggeredReady_=!0,this.trigger("ready"))}addSourceBuffer(e,t){_i({type:"mediaSource",sourceUpdater:this,action:Ti.addSourceBuffer(e,t),name:"addSourceBuffer"})}abort(e){_i({type:e,sourceUpdater:this,action:Ti.abort(e),name:"abort"})}removeSourceBuffer(e){if(!this.canRemoveSourceBuffer()){K.log.error("removeSourceBuffer is not supported!");return}_i({type:"mediaSource",sourceUpdater:this,action:Ti.removeSourceBuffer(e),name:"removeSourceBuffer"})}canRemoveSourceBuffer(){return!K.browser.IS_FIREFOX&&B.MediaSource&&B.MediaSource.prototype&&typeof B.MediaSource.prototype.removeSourceBuffer=="function"}static canChangeType(){return B.SourceBuffer&&B.SourceBuffer.prototype&&typeof B.SourceBuffer.prototype.changeType=="function"}canChangeType(){return this.constructor.canChangeType()}changeType(e,t){if(!this.canChangeType()){K.log.error("changeType is not supported!");return}_i({type:e,sourceUpdater:this,action:Ti.changeType(t),name:"changeType"})}addOrChangeSourceBuffers(e){if(!e||typeof e!="object"||Object.keys(e).length===0)throw new Error("Cannot addOrChangeSourceBuffers to undefined codecs");Object.keys(e).forEach(t=>{const i=e[t];if(!this.hasCreatedSourceBuffers())return this.addSourceBuffer(t,i);this.canChangeType()&&this.changeType(t,i)})}appendBuffer(e,t){const{segmentInfo:i,type:s,bytes:r}=e;if(this.processedAppend_=!0,s==="audio"&&this.videoBuffer&&!this.videoAppendQueued_){this.delayedAudioAppendQueue_.push([e,t]),this.logger_(`delayed audio append of ${r.length} until video append`);return}const a=t;if(_i({type:s,sourceUpdater:this,action:Ti.appendBuffer(r,i||{mediaIndex:-1},a),doneFn:t,name:"appendBuffer"}),s==="video"){if(this.videoAppendQueued_=!0,!this.delayedAudioAppendQueue_.length)return;const o=this.delayedAudioAppendQueue_.slice();this.logger_(`queuing delayed audio ${o.length} appendBuffers`),this.delayedAudioAppendQueue_.length=0,o.forEach(c=>{this.appendBuffer.apply(this,c)})}}audioBuffered(){return vn(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:Ot()}videoBuffered(){return vn(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:Ot()}buffered(){const e=vn(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=vn(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():HA(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=Fn){_i({type:"mediaSource",sourceUpdater:this,action:Ti.duration(e),name:"duration",doneFn:t})}endOfStream(e=null,t=Fn){typeof e!="string"&&(e=void 0),_i({type:"mediaSource",sourceUpdater:this,action:Ti.endOfStream(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=Fn){if(!this.audioBuffered().length||this.audioBuffered().end(0)===0){i();return}_i({type:"audio",sourceUpdater:this,action:Ti.remove(e,t),doneFn:i,name:"remove"})}removeVideo(e,t,i=Fn){if(!this.videoBuffered().length||this.videoBuffered().end(0)===0){i();return}_i({type:"video",sourceUpdater:this,action:Ti.remove(e,t),doneFn:i,name:"remove"})}updating(){return!!(kf("audio",this)||kf("video",this))}audioTimestampOffset(e){return typeof e<"u"&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(_i({type:"audio",sourceUpdater:this,action:Ti.timestampOffset(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return typeof e<"u"&&this.videoBuffer&&this.videoTimestampOffset_!==e&&(_i({type:"video",sourceUpdater:this,action:Ti.timestampOffset(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&_i({type:"audio",sourceUpdater:this,action:Ti.callback(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&_i({type:"video",sourceUpdater:this,action:Ti.callback(e),name:"callback"})}dispose(){this.trigger("dispose"),kP.forEach(e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`](()=>_T(e,this))}),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const kT=n=>decodeURIComponent(escape(String.fromCharCode.apply(null,n))),xP=n=>{const e=new Uint8Array(n);return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")},ET=new Uint8Array(`
|
|
263
|
+
|
|
264
|
+
`.split("").map(n=>n.charCodeAt(0)));class wP extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class AP extends Cf{constructor(e,t={}){super(e,t),this.mediaSource_=null,this.subtitlesTrack_=null,this.featuresNativeTextTracks_=e.featuresNativeTextTracks,this.loadVttJs=e.loadVttJs,this.shouldSaveSegmentTimingInfo_=!1}buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues||!this.subtitlesTrack_.cues.length)return Ot();const e=this.subtitlesTrack_.cues,t=e[0].startTime,i=e[e.length-1].startTime;return Ot([[t,i]])}initSegmentForMap(e,t=!1){if(!e)return null;const i=_l(e);let s=this.initSegments_[i];if(t&&!s&&e.bytes){const r=ET.byteLength+e.bytes.byteLength,a=new Uint8Array(r);a.set(e.bytes),a.set(ET,e.bytes.byteLength),this.initSegments_[i]=s={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:a}}return s||e}couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused()}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}track(e){return typeof e>"u"?this.subtitlesTrack_:(this.subtitlesTrack_=e,this.state==="INIT"&&this.couldBeginLoading_()&&this.init_(),this.subtitlesTrack_)}remove(e,t){no(e,t,this.subtitlesTrack_)}fillBuffer_(){const e=this.chooseNextRequest_();if(e){if(this.syncController_.timestampOffsetForTimeline(e.timeline)===null){const t=()=>{this.state="READY",this.paused()||this.monitorBuffer_()};this.syncController_.one("timestampoffset",t),this.state="WAITING_ON_TIMELINE";return}this.loadSegment_(e)}}timestampOffsetForSegment_(){return null}chooseNextRequest_(){return this.skipEmptySegments_(super.chooseNextRequest_())}skipEmptySegments_(e){for(;e&&e.segment.empty;){if(e.mediaIndex+1>=e.playlist.segments.length){e=null;break}e=this.generateSegmentInfo_({playlist:e.playlist,mediaIndex:e.mediaIndex+1,startOfSegment:e.startOfSegment+e.duration,isSyncRequest:e.isSyncRequest})}return e}stopForError(e){this.error(e),this.state="READY",this.pause(),this.trigger("error")}segmentRequestFinished_(e,t,i){if(!this.subtitlesTrack_){this.state="READY";return}if(this.saveTransferStats_(t.stats),!this.pendingSegment_){this.state="READY",this.mediaRequestsAborted+=1;return}if(e){e.code===yn.TIMEOUT&&this.handleTimeout_(),e.code===yn.ABORTED?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,this.stopForError(e);return}const s=this.pendingSegment_,r=i.mp4VttCues&&i.mp4VttCues.length;r&&(s.mp4VttCues=i.mp4VttCues),this.saveBandwidthRelatedStats_(s.duration,t.stats),t.key&&this.segmentKey(t.key,!0),this.state="APPENDING",this.trigger("appending");const a=s.segment;if(a.map&&(a.map.bytes=t.map.bytes),s.bytes=t.bytes,typeof B.WebVTT!="function"&&typeof this.loadVttJs=="function"){this.state="WAITING_ON_VTTJS",this.loadVttJs().then(()=>this.segmentRequestFinished_(e,t,i),()=>this.stopForError({message:"Error loading vtt.js"}));return}a.requested=!0;try{this.parseVTTCues_(s)}catch(o){this.stopForError({message:o.message,metadata:{errorType:K.Error.StreamingVttParserError,error:o}});return}if(r||this.updateTimeMapping_(s,this.syncController_.timelines[s.timeline],this.playlist_),s.cues.length?s.timingInfo={start:s.cues[0].startTime,end:s.cues[s.cues.length-1].endTime}:s.timingInfo={start:s.startOfSegment,end:s.startOfSegment+s.duration},s.isSyncRequest){this.trigger("syncinfoupdate"),this.pendingSegment_=null,this.state="READY";return}s.byteLength=s.bytes.byteLength,this.mediaSecondsLoaded+=a.duration,s.cues.forEach(o=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new B.VTTCue(o.startTime,o.endTime,o.text):o)}),uP(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(e,t){const i=e&&e.type==="vtt",s=t&&t.type==="text";i&&s&&super.handleData_(e,t)}updateTimingInfoEnd_(){}parseMp4VttCues_(e){const t=this.sourceUpdater_.videoTimestampOffset()===null?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();e.mp4VttCues.forEach(i=>{const s=i.start+t,r=i.end+t,a=new B.VTTCue(s,r,i.cueText);i.settings&&i.settings.split(" ").forEach(o=>{const c=o.split(":"),l=c[0],u=c[1];a[l]=isNaN(u)?u:Number(u)}),e.cues.push(a)})}parseVTTCues_(e){let t,i=!1;if(typeof B.WebVTT!="function")throw new wP;if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},e.mp4VttCues){this.parseMp4VttCues_(e);return}typeof B.TextDecoder=="function"?t=new B.TextDecoder("utf8"):(t=B.WebVTT.StringDecoder(),i=!0);const s=new B.WebVTT.Parser(B,B.vttjs,t);if(s.oncue=e.cues.push.bind(e.cues),s.ontimestampmap=a=>{e.timestampmap=a},s.onparsingerror=a=>{K.log.warn("Error encountered when parsing cues: "+a.message)},e.segment.map){let a=e.segment.map.bytes;i&&(a=kT(a)),s.parse(a)}let r=e.bytes;i&&(r=kT(r)),s.parse(r),s.flush()}updateTimeMapping_(e,t,i){const s=e.segment;if(!t)return;if(!e.cues.length){s.empty=!0;return}const{MPEGTS:r,LOCAL:a}=e.timestampmap,c=r/Ms.ONE_SECOND_IN_TS-a+t.mapping;if(e.cues.forEach(l=>{const u=l.endTime-l.startTime,h=this.handleRollover_(l.startTime+c,t.time);l.startTime=Math.max(h,0),l.endTime=Math.max(h+u,0)}),!i.syncInfo){const l=e.cues[0].startTime,u=e.cues[e.cues.length-1].startTime;i.syncInfo={mediaSequence:i.mediaSequence+e.mediaIndex,time:Math.min(l,u-s.duration)}}}handleRollover_(e,t){if(t===null)return e;let i=e*Ms.ONE_SECOND_IN_TS;const s=t*Ms.ONE_SECOND_IN_TS;let r;for(s<i?r=-8589934592:r=8589934592;Math.abs(i-s)>4294967296;)i+=r;return i/Ms.ONE_SECOND_IN_TS}}const DP=function(n,e){const t=n.cues;for(let i=0;i<t.length;i++){const s=t[i];if(e>=s.adStartTime&&e<=s.adEndTime)return s}return null},PP=function(n,e,t=0){if(!n.segments)return;let i=t,s;for(let r=0;r<n.segments.length;r++){const a=n.segments[r];if(s||(s=DP(e,i+a.duration/2)),s){if("cueIn"in a){s.endTime=i,s.adEndTime=i,i+=a.duration,s=null;continue}if(i<s.endTime){i+=a.duration;continue}s.endTime+=a.duration}else if("cueOut"in a&&(s=new B.VTTCue(i,i+a.duration,a.cueOut),s.adStartTime=i,s.adEndTime=i+parseFloat(a.cueOut),e.addCue(s)),"cueOutCont"in a){const[o,c]=a.cueOutCont.split("/").map(parseFloat);s=new B.VTTCue(i,i+a.duration,""),s.adStartTime=i-o,s.adEndTime=s.adStartTime+c,e.addCue(s)}i+=a.duration}};class xT{constructor({start:e,end:t,segmentIndex:i,partIndex:s=null,appended:r=!1}){this.start_=e,this.end_=t,this.segmentIndex_=i,this.partIndex_=s,this.appended_=r}isInRange(e){return e>=this.start&&e<this.end}markAppended(){this.appended_=!0}resetAppendedStatus(){this.appended_=!1}get isAppended(){return this.appended_}get start(){return this.start_}get end(){return this.end_}get segmentIndex(){return this.segmentIndex_}get partIndex(){return this.partIndex_}}class IP{constructor(e,t=[]){this.segmentSyncInfo_=e,this.partsSyncInfo_=t}get segmentSyncInfo(){return this.segmentSyncInfo_}get partsSyncInfo(){return this.partsSyncInfo_}get hasPartsSyncInfo(){return this.partsSyncInfo_.length>0}resetAppendStatus(){this.segmentSyncInfo_.resetAppendedStatus(),this.partsSyncInfo_.forEach(e=>e.resetAppendedStatus())}}class wT{constructor(){this.storage_=new Map,this.diagnostics_="",this.isReliable_=!1,this.start_=-1/0,this.end_=1/0}get start(){return this.start_}get end(){return this.end_}get diagnostics(){return this.diagnostics_}get isReliable(){return this.isReliable_}resetAppendedStatus(){this.storage_.forEach(e=>e.resetAppendStatus())}update(e,t){const{mediaSequence:i,segments:s}=e;if(this.isReliable_=this.isReliablePlaylist_(i,s),!!this.isReliable_)return this.updateStorage_(s,i,this.calculateBaseTime_(i,s,t))}getSyncInfoForTime(e){for(const{segmentSyncInfo:t,partsSyncInfo:i}of this.storage_.values())if(i.length){for(const s of i)if(s.isInRange(e))return s}else if(t.isInRange(e))return t;return null}getSyncInfoForMediaSequence(e){return this.storage_.get(e)}updateStorage_(e,t,i){const s=new Map;let r=`
|
|
265
|
+
`,a=i,o=t;this.start_=a,e.forEach((c,l)=>{const u=this.storage_.get(o),h=a,p=h+c.duration,y=!!(u&&u.segmentSyncInfo&&u.segmentSyncInfo.isAppended),_=new xT({start:h,end:p,appended:y,segmentIndex:l});c.syncInfo=_;let b=a;const S=(c.parts||[]).map((D,I)=>{const F=b,w=b+D.duration,P=!!(u&&u.partsSyncInfo&&u.partsSyncInfo[I]&&u.partsSyncInfo[I].isAppended),L=new xT({start:F,end:w,appended:P,segmentIndex:l,partIndex:I});return b=w,r+=`Media Sequence: ${o}.${I} | Range: ${F} --> ${w} | Appended: ${P}
|
|
266
|
+
`,D.syncInfo=L,L});s.set(o,new IP(_,S)),r+=`${mT(c.resolvedUri)} | Media Sequence: ${o} | Range: ${h} --> ${p} | Appended: ${y}
|
|
267
|
+
`,o++,a=p}),this.end_=a,this.storage_=s,this.diagnostics_=r}calculateBaseTime_(e,t,i){if(!this.storage_.size)return 0;if(this.storage_.has(e))return this.storage_.get(e).segmentSyncInfo.start;const s=Math.min(...this.storage_.keys());if(e<s){const r=s-e;let a=this.storage_.get(s).segmentSyncInfo.start;for(let o=0;o<r;o++){const c=t[o];a-=c.duration}return a}return i}isReliablePlaylist_(e,t){return e!=null&&Array.isArray(t)&&t.length}}class AT extends wT{constructor(e){super(),this.parent_=e}calculateBaseTime_(e,t,i){if(!this.storage_.size){const s=this.parent_.getSyncInfoForMediaSequence(e);return s?s.segmentSyncInfo.start:0}return super.calculateBaseTime_(e,t,i)}}const RP=86400,Ef=[{name:"VOD",run:(n,e,t,i,s)=>t!==1/0?{time:0,segmentIndex:0,partIndex:null}:null},{name:"MediaSequence",run:(n,e,t,i,s,r)=>{const a=n.getMediaSequenceSync(r);if(!a||!a.isReliable)return null;const o=a.getSyncInfoForTime(s);return o?{time:o.start,partIndex:o.partIndex,segmentIndex:o.segmentIndex}:null}},{name:"ProgramDateTime",run:(n,e,t,i,s)=>{if(!Object.keys(n.timelineToDatetimeMappings).length)return null;let r=null,a=null;const o=cf(e);s=s||0;for(let c=0;c<o.length;c++){const l=e.endList||s===0?c:o.length-(c+1),u=o[l],h=u.segment,p=n.timelineToDatetimeMappings[h.timeline];if(!p||!h.dateTimeObject)continue;let _=h.dateTimeObject.getTime()/1e3+p;if(h.parts&&typeof u.partIndex=="number")for(let S=0;S<u.partIndex;S++)_+=h.parts[S].duration;const b=Math.abs(s-_);if(a!==null&&(b===0||a<b))break;a=b,r={time:_,segmentIndex:u.segmentIndex,partIndex:u.partIndex}}return r}},{name:"Segment",run:(n,e,t,i,s)=>{let r=null,a=null;s=s||0;const o=cf(e);for(let c=0;c<o.length;c++){const l=e.endList||s===0?c:o.length-(c+1),u=o[l],h=u.segment,p=u.part&&u.part.start||h&&h.start;if(h.timeline===i&&typeof p<"u"){const y=Math.abs(s-p);if(a!==null&&a<y)break;(!r||a===null||a>=y)&&(a=y,r={time:p,segmentIndex:u.segmentIndex,partIndex:u.partIndex})}}return r}},{name:"Discontinuity",run:(n,e,t,i,s)=>{let r=null;if(s=s||0,e.discontinuityStarts&&e.discontinuityStarts.length){let a=null;for(let o=0;o<e.discontinuityStarts.length;o++){const c=e.discontinuityStarts[o],l=e.discontinuitySequence+o+1,u=n.discontinuities[l];if(u){const h=Math.abs(s-u.time);if(a!==null&&a<h)break;(!r||a===null||a>=h)&&(a=h,r={time:u.time,segmentIndex:c,partIndex:null})}}}return r}},{name:"Playlist",run:(n,e,t,i,s)=>e.syncInfo?{time:e.syncInfo.time,segmentIndex:e.syncInfo.mediaSequence-e.mediaSequence,partIndex:null}:null}];class OP extends K.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};const t=new wT,i=new AT(t),s=new AT(t);this.mediaSequenceStorage_={main:t,audio:i,vtt:s},this.logger_=Oi("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,i,s,r){if(t!==1/0)return Ef.find(({name:c})=>c==="VOD").run(this,e,t);const a=this.runStrategies_(e,t,i,s,r);if(!a.length)return null;for(const o of a){const{syncPoint:c,strategy:l}=o,{segmentIndex:u,time:h}=c;if(u<0)continue;const p=e.segments[u],y=h,_=y+p.duration;if(this.logger_(`Strategy: ${l}. Current time: ${s}. selected segment: ${u}. Time: [${y} -> ${_}]}`),s>=y&&s<_)return this.logger_("Found sync point with exact match: ",c),c}return this.selectSyncPoint_(a,{key:"time",value:s})}getExpiredTime(e,t){if(!e||!e.segments)return null;const i=this.runStrategies_(e,t,e.discontinuitySequence,0);if(!i.length)return null;const s=this.selectSyncPoint_(i,{key:"segmentIndex",value:0});return s.segmentIndex>0&&(s.time*=-1),Math.abs(s.time+Za({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:s.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,s,r){const a=[];for(let o=0;o<Ef.length;o++){const c=Ef[o],l=c.run(this,e,t,i,s,r);l&&(l.strategy=c.name,a.push({strategy:c.name,syncPoint:l}))}return a}selectSyncPoint_(e,t){let i=e[0].syncPoint,s=Math.abs(e[0].syncPoint[t.key]-t.value),r=e[0].strategy;for(let a=1;a<e.length;a++){const o=Math.abs(e[a].syncPoint[t.key]-t.value);o<s&&(s=o,i=e[a].syncPoint,r=e[a].strategy)}return this.logger_(`syncPoint for [${t.key}: ${t.value}] chosen with strategy [${r}]: [time:${i.time}, segmentIndex:${i.segmentIndex}`+(typeof i.partIndex=="number"?`,partIndex:${i.partIndex}`:"")+"]"),i}saveExpiredSegmentInfo(e,t){const i=t.mediaSequence-e.mediaSequence;if(i>RP){K.log.warn(`Not saving expired segment info. Media sequence gap ${i} is too large.`);return}for(let s=i-1;s>=0;s--){const r=e.segments[s];if(r&&typeof r.start<"u"){t.syncInfo={mediaSequence:e.mediaSequence+s,time:r.start},this.logger_(`playlist refresh sync: [time:${t.syncInfo.time}, mediaSequence: ${t.syncInfo.mediaSequence}]`),this.trigger("syncinfoupdate");break}}}setDateTimeMappingForStart(e){if(this.timelineToDatetimeMappings={},e.segments&&e.segments.length&&e.segments[0].dateTimeObject){const t=e.segments[0],i=t.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[t.timeline]=-i}}saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:t}){const i=this.calculateSegmentTimeMapping_(e,e.timingInfo,t),s=e.segment;i&&(this.saveDiscontinuitySyncInfo_(e),e.playlist.syncInfo||(e.playlist.syncInfo={mediaSequence:e.playlist.mediaSequence+e.mediaIndex,time:s.start}));const r=s.dateTimeObject;s.discontinuity&&t&&r&&(this.timelineToDatetimeMappings[s.timeline]=-(r.getTime()/1e3))}timestampOffsetForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].time}mappingForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].mapping}calculateSegmentTimeMapping_(e,t,i){const s=e.segment,r=e.part;let a=this.timelines[e.timeline],o,c;if(typeof e.timestampOffset=="number")a={time:e.startOfSegment,mapping:e.startOfSegment-t.start},i&&(this.timelines[e.timeline]=a,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${a.time}] [mapping: ${a.mapping}]`)),o=e.startOfSegment,c=t.end+a.mapping;else if(a)o=t.start+a.mapping,c=t.end+a.mapping;else return!1;return r&&(r.start=o,r.end=c),(!s.start||o<s.start)&&(s.start=o),s.end=c,!0}saveDiscontinuitySyncInfo_(e){const t=e.playlist,i=e.segment;if(i.discontinuity)this.discontinuities[i.timeline]={time:i.start,accuracy:0};else if(t.discontinuityStarts&&t.discontinuityStarts.length)for(let s=0;s<t.discontinuityStarts.length;s++){const r=t.discontinuityStarts[s],a=t.discontinuitySequence+s+1,o=r-e.mediaIndex,c=Math.abs(o);if(!this.discontinuities[a]||this.discontinuities[a].accuracy>c){let l;o<0?l=i.start-Za({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:r}):l=i.end+Za({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:r}),this.discontinuities[a]={time:l,accuracy:c}}}}dispose(){this.trigger("dispose"),this.off()}}class MP extends K.EventTarget{constructor(){super(),this.pendingTimelineChanges_={},this.lastTimelineChanges_={}}clearPendingTimelineChange(e){this.pendingTimelineChanges_[e]=null,this.trigger("pendingtimelinechange")}pendingTimelineChange({type:e,from:t,to:i}){return typeof t=="number"&&typeof i=="number"&&(this.pendingTimelineChanges_[e]={type:e,from:t,to:i},this.trigger("pendingtimelinechange")),this.pendingTimelineChanges_[e]}lastTimelineChange({type:e,from:t,to:i}){if(typeof t=="number"&&typeof i=="number"){this.lastTimelineChanges_[e]={type:e,from:t,to:i},delete this.pendingTimelineChanges_[e];const s={timelineChangeInfo:{from:t,to:i}};this.trigger({type:"timelinechange",metadata:s})}return this.lastTimelineChanges_[e]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}const LP=eT(tT(function(){var n=(function(){function b(){this.listeners={}}var S=b.prototype;return S.on=function(I,F){this.listeners[I]||(this.listeners[I]=[]),this.listeners[I].push(F)},S.off=function(I,F){if(!this.listeners[I])return!1;var w=this.listeners[I].indexOf(F);return this.listeners[I]=this.listeners[I].slice(0),this.listeners[I].splice(w,1),w>-1},S.trigger=function(I){var F=this.listeners[I];if(F)if(arguments.length===2)for(var w=F.length,P=0;P<w;++P)F[P].call(this,arguments[1]);else for(var L=Array.prototype.slice.call(arguments,1),C=F.length,N=0;N<C;++N)F[N].apply(this,L)},S.dispose=function(){this.listeners={}},S.pipe=function(I){this.on("data",function(F){I.push(F)})},b})();/*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */function e(b){return b.subarray(0,b.byteLength-b[b.byteLength-1])}/*! @name aes-decrypter @version 4.0.2 @license Apache-2.0 */const t=function(){const b=[[[],[],[],[],[]],[[],[],[],[],[]]],S=b[0],D=b[1],I=S[4],F=D[4];let w,P,L;const C=[],N=[];let x,k,j,G,X,z;for(w=0;w<256;w++)N[(C[w]=w<<1^(w>>7)*283)^w]=w;for(P=L=0;!I[P];P^=x||1,L=N[L]||1)for(G=L^L<<1^L<<2^L<<3^L<<4,G=G>>8^G&255^99,I[P]=G,F[G]=P,j=C[k=C[x=C[P]]],z=j*16843009^k*65537^x*257^P*16843008,X=C[G]*257^G*16843008,w=0;w<4;w++)S[w][P]=X=X<<24^X>>>8,D[w][G]=z=z<<24^z>>>8;for(w=0;w<5;w++)S[w]=S[w].slice(0),D[w]=D[w].slice(0);return b};let i=null;class s{constructor(S){i||(i=t()),this._tables=[[i[0][0].slice(),i[0][1].slice(),i[0][2].slice(),i[0][3].slice(),i[0][4].slice()],[i[1][0].slice(),i[1][1].slice(),i[1][2].slice(),i[1][3].slice(),i[1][4].slice()]];let D,I,F;const w=this._tables[0][4],P=this._tables[1],L=S.length;let C=1;if(L!==4&&L!==6&&L!==8)throw new Error("Invalid aes key size");const N=S.slice(0),x=[];for(this._key=[N,x],D=L;D<4*L+28;D++)F=N[D-1],(D%L===0||L===8&&D%L===4)&&(F=w[F>>>24]<<24^w[F>>16&255]<<16^w[F>>8&255]<<8^w[F&255],D%L===0&&(F=F<<8^F>>>24^C<<24,C=C<<1^(C>>7)*283)),N[D]=N[D-L]^F;for(I=0;D;I++,D--)F=N[I&3?D:D-4],D<=4||I<4?x[I]=F:x[I]=P[0][w[F>>>24]]^P[1][w[F>>16&255]]^P[2][w[F>>8&255]]^P[3][w[F&255]]}decrypt(S,D,I,F,w,P){const L=this._key[1];let C=S^L[0],N=F^L[1],x=I^L[2],k=D^L[3],j,G,X;const z=L.length/4-2;let W,te=4;const Q=this._tables[1],re=Q[0],Y=Q[1],ie=Q[2],ge=Q[3],Te=Q[4];for(W=0;W<z;W++)j=re[C>>>24]^Y[N>>16&255]^ie[x>>8&255]^ge[k&255]^L[te],G=re[N>>>24]^Y[x>>16&255]^ie[k>>8&255]^ge[C&255]^L[te+1],X=re[x>>>24]^Y[k>>16&255]^ie[C>>8&255]^ge[N&255]^L[te+2],k=re[k>>>24]^Y[C>>16&255]^ie[N>>8&255]^ge[x&255]^L[te+3],te+=4,C=j,N=G,x=X;for(W=0;W<4;W++)w[(3&-W)+P]=Te[C>>>24]<<24^Te[N>>16&255]<<16^Te[x>>8&255]<<8^Te[k&255]^L[te++],j=C,C=N,N=x,x=k,k=j}}class r extends n{constructor(){super(n),this.jobs=[],this.delay=1,this.timeout_=null}processJob_(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null}push(S){this.jobs.push(S),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const a=function(b){return b<<24|(b&65280)<<8|(b&16711680)>>8|b>>>24},o=function(b,S,D){const I=new Int32Array(b.buffer,b.byteOffset,b.byteLength>>2),F=new s(Array.prototype.slice.call(S)),w=new Uint8Array(b.byteLength),P=new Int32Array(w.buffer);let L,C,N,x,k,j,G,X,z;for(L=D[0],C=D[1],N=D[2],x=D[3],z=0;z<I.length;z+=4)k=a(I[z]),j=a(I[z+1]),G=a(I[z+2]),X=a(I[z+3]),F.decrypt(k,j,G,X,P,z),P[z]=a(P[z]^L),P[z+1]=a(P[z+1]^C),P[z+2]=a(P[z+2]^N),P[z+3]=a(P[z+3]^x),L=k,C=j,N=G,x=X;return w};class c{constructor(S,D,I,F){const w=c.STEP,P=new Int32Array(S.buffer),L=new Uint8Array(S.byteLength);let C=0;for(this.asyncStream_=new r,this.asyncStream_.push(this.decryptChunk_(P.subarray(C,C+w),D,I,L)),C=w;C<P.length;C+=w)I=new Uint32Array([a(P[C-4]),a(P[C-3]),a(P[C-2]),a(P[C-1])]),this.asyncStream_.push(this.decryptChunk_(P.subarray(C,C+w),D,I,L));this.asyncStream_.push(function(){F(null,e(L))})}static get STEP(){return 32e3}decryptChunk_(S,D,I,F){return function(){const w=o(S,D,I);F.set(w,S.byteOffset)}}}var l=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},u;typeof window<"u"?u=window:typeof l<"u"?u=l:typeof self<"u"?u=self:u={};var h=u,p=function(S){return ArrayBuffer.isView==="function"?ArrayBuffer.isView(S):S&&S.buffer instanceof ArrayBuffer},y=h.BigInt||Number;y("0x1"),y("0x100"),y("0x10000"),y("0x1000000"),y("0x100000000"),y("0x10000000000"),y("0x1000000000000"),y("0x100000000000000"),y("0x10000000000000000"),(function(){var b=new Uint16Array([65484]),S=new Uint8Array(b.buffer,b.byteOffset,b.byteLength);return S[0]===255?"big":S[0]===204?"little":"unknown"})();const _=function(b){const S={};return Object.keys(b).forEach(D=>{const I=b[D];p(I)?S[D]={bytes:I.buffer,byteOffset:I.byteOffset,byteLength:I.byteLength}:S[D]=I}),S};self.onmessage=function(b){const S=b.data,D=new Uint8Array(S.encrypted.bytes,S.encrypted.byteOffset,S.encrypted.byteLength),I=new Uint32Array(S.key.bytes,S.key.byteOffset,S.key.byteLength/4),F=new Uint32Array(S.iv.bytes,S.iv.byteOffset,S.iv.byteLength/4);new c(D,I,F,function(w,P){self.postMessage(_({source:S.source,decrypted:P}),[P.buffer])})}}));var NP=Zb(LP);const FP=n=>{let e=n.default?"main":"alternative";return n.characteristics&&n.characteristics.indexOf("public.accessibility.describes-video")>=0&&(e="main-desc"),e},DT=(n,e)=>{n.abort(),n.pause(),e&&e.activePlaylistLoader&&(e.activePlaylistLoader.pause(),e.activePlaylistLoader=null)},xf=(n,e)=>{e.activePlaylistLoader=n,n.load()},UP=(n,e)=>()=>{const{segmentLoaders:{[n]:t,main:i},mediaTypes:{[n]:s}}=e,r=s.activeTrack(),a=s.getActiveGroup(),o=s.activePlaylistLoader,c=s.lastGroup_;if(!(a&&c&&a.id===c.id)&&(s.lastGroup_=a,s.lastTrack_=r,DT(t,s),!(!a||a.isMainPlaylist))){if(!a.playlistLoader){o&&i.resetEverything();return}t.resyncLoader(),xf(a.playlistLoader,s)}},BP=(n,e)=>()=>{const{segmentLoaders:{[n]:t},mediaTypes:{[n]:i}}=e;i.lastGroup_=null,t.abort(),t.pause()},qP=(n,e)=>()=>{const{mainPlaylistLoader:t,segmentLoaders:{[n]:i,main:s},mediaTypes:{[n]:r}}=e,a=r.activeTrack(),o=r.getActiveGroup(),c=r.activePlaylistLoader,l=r.lastTrack_;if(!(l&&a&&l.id===a.id)&&(r.lastGroup_=o,r.lastTrack_=a,DT(i,r),!!o)){if(o.isMainPlaylist){if(!a||!l||a.id===l.id)return;const u=e.vhs.playlistController_,h=u.selectPlaylist();if(u.media()===h)return;r.logger_(`track change. Switching main audio from ${l.id} to ${a.id}`),t.pause(),s.resetEverything(),u.fastQualityChange_(h);return}if(n==="AUDIO"){if(!o.playlistLoader){s.setAudio(!0),s.resetEverything();return}i.setAudio(!0),s.setAudio(!1)}if(c===o.playlistLoader){xf(o.playlistLoader,r);return}i.track&&i.track(a),i.resetEverything(),xf(o.playlistLoader,r)}},kl={AUDIO:(n,e)=>()=>{const{mediaTypes:{[n]:t},excludePlaylist:i}=e,s=t.activeTrack(),r=t.activeGroup(),a=(r.filter(c=>c.default)[0]||r[0]).id,o=t.tracks[a];if(s===o){i({error:{message:"Problem encountered loading the default audio track."}});return}K.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");for(const c in t.tracks)t.tracks[c].enabled=t.tracks[c]===o;t.onTrackChanged()},SUBTITLES:(n,e)=>()=>{const{mediaTypes:{[n]:t}}=e;K.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const i=t.activeTrack();i&&(i.mode="disabled"),t.onTrackChanged()}},PT={AUDIO:(n,e,t)=>{if(!e)return;const{tech:i,requestOptions:s,segmentLoaders:{[n]:r}}=t;e.on("loadedmetadata",()=>{const a=e.media();r.playlist(a,s),(!i.paused()||a.endList&&i.preload()!=="none")&&r.load()}),e.on("loadedplaylist",()=>{r.playlist(e.media(),s),i.paused()||r.load()}),e.on("error",kl[n](n,t))},SUBTITLES:(n,e,t)=>{const{tech:i,requestOptions:s,segmentLoaders:{[n]:r},mediaTypes:{[n]:a}}=t;e.on("loadedmetadata",()=>{const o=e.media();r.playlist(o,s),r.track(a.activeTrack()),(!i.paused()||o.endList&&i.preload()!=="none")&&r.load()}),e.on("loadedplaylist",()=>{r.playlist(e.media(),s),i.paused()||r.load()}),e.on("error",kl[n](n,t))}},VP={AUDIO:(n,e)=>{const{vhs:t,sourceType:i,segmentLoaders:{[n]:s},requestOptions:r,main:{mediaGroups:a},mediaTypes:{[n]:{groups:o,tracks:c,logger_:l}},mainPlaylistLoader:u}=e,h=eo(u.main);(!a[n]||Object.keys(a[n]).length===0)&&(a[n]={main:{default:{default:!0}}},h&&(a[n].main.default.playlists=u.main.playlists));for(const p in a[n]){o[p]||(o[p]=[]);for(const y in a[n][p]){let _=a[n][p][y],b;if(h?(l(`AUDIO group '${p}' label '${y}' is a main playlist`),_.isMainPlaylist=!0,b=null):i==="vhs-json"&&_.playlists?b=new qr(_.playlists[0],t,r):_.resolvedUri?b=new qr(_.resolvedUri,t,r):_.playlists&&i==="dash"?b=new yf(_.playlists[0],t,r,u):b=null,_=We({id:y,playlistLoader:b},_),PT[n](n,_.playlistLoader,e),o[p].push(_),typeof c[y]>"u"){const S=new K.AudioTrack({id:y,kind:FP(_),enabled:!1,language:_.language,default:_.default,label:y});c[y]=S}}}s.on("error",kl[n](n,e))},SUBTITLES:(n,e)=>{const{tech:t,vhs:i,sourceType:s,segmentLoaders:{[n]:r},requestOptions:a,main:{mediaGroups:o},mediaTypes:{[n]:{groups:c,tracks:l}},mainPlaylistLoader:u}=e;for(const h in o[n]){c[h]||(c[h]=[]);for(const p in o[n][h]){if(!i.options_.useForcedSubtitles&&o[n][h][p].forced)continue;let y=o[n][h][p],_;if(s==="hls")_=new qr(y.resolvedUri,i,a);else if(s==="dash"){if(!y.playlists.filter(S=>S.excludeUntil!==1/0).length)return;_=new yf(y.playlists[0],i,a,u)}else s==="vhs-json"&&(_=new qr(y.playlists?y.playlists[0]:y.resolvedUri,i,a));if(y=We({id:p,playlistLoader:_},y),PT[n](n,y.playlistLoader,e),c[h].push(y),typeof l[p]>"u"){const b=t.addRemoteTextTrack({id:p,kind:"subtitles",default:y.default&&y.autoselect,language:y.language,label:p},!1).track;l[p]=b}}}r.on("error",kl[n](n,e))},"CLOSED-CAPTIONS":(n,e)=>{const{tech:t,main:{mediaGroups:i},mediaTypes:{[n]:{groups:s,tracks:r}}}=e;for(const a in i[n]){s[a]||(s[a]=[]);for(const o in i[n][a]){const c=i[n][a][o];if(!/^(?:CC|SERVICE)/.test(c.instreamId))continue;const l=t.options_.vhs&&t.options_.vhs.captionServices||{};let u={label:o,language:c.language,instreamId:c.instreamId,default:c.default&&c.autoselect};if(l[u.instreamId]&&(u=We(u,l[u.instreamId])),u.default===void 0&&delete u.default,s[a].push(We({id:o},c)),typeof r[o]>"u"){const h=t.addRemoteTextTrack({id:u.instreamId,kind:"captions",default:u.default,language:u.language,label:u.label},!1).track;r[o]=h}}}}},IT=(n,e)=>{for(let t=0;t<n.length;t++)if(df(e,n[t])||n[t].playlists&&IT(n[t].playlists,e))return!0;return!1},jP=(n,e)=>t=>{const{mainPlaylistLoader:i,mediaTypes:{[n]:{groups:s}}}=e,r=i.media();if(!r)return null;let a=null;r.attributes[n]&&(a=s[r.attributes[n]]);const o=Object.keys(s);if(!a)if(n==="AUDIO"&&o.length>1&&eo(e.main))for(let c=0;c<o.length;c++){const l=s[o[c]];if(IT(l,r)){a=l;break}}else s.main?a=s.main:o.length===1&&(a=s[o[0]]);return typeof t>"u"?a:t===null||!a?null:a.filter(c=>c.id===t.id)[0]||null},HP={AUDIO:(n,e)=>()=>{const{mediaTypes:{[n]:{tracks:t}}}=e;for(const i in t)if(t[i].enabled)return t[i];return null},SUBTITLES:(n,e)=>()=>{const{mediaTypes:{[n]:{tracks:t}}}=e;for(const i in t)if(t[i].mode==="showing"||t[i].mode==="hidden")return t[i];return null}},$P=(n,{mediaTypes:e})=>()=>{const t=e[n].activeTrack();return t?e[n].activeGroup(t):null},WP=n=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(l=>{VP[l](l,n)});const{mediaTypes:e,mainPlaylistLoader:t,tech:i,vhs:s,segmentLoaders:{["AUDIO"]:r,main:a}}=n;["AUDIO","SUBTITLES"].forEach(l=>{e[l].activeGroup=jP(l,n),e[l].activeTrack=HP[l](l,n),e[l].onGroupChanged=UP(l,n),e[l].onGroupChanging=BP(l,n),e[l].onTrackChanged=qP(l,n),e[l].getActiveGroup=$P(l,n)});const o=e.AUDIO.activeGroup();if(o){const l=(o.filter(h=>h.default)[0]||o[0]).id;e.AUDIO.tracks[l].enabled=!0,e.AUDIO.onGroupChanged(),e.AUDIO.onTrackChanged(),e.AUDIO.getActiveGroup().playlistLoader?(a.setAudio(!1),r.setAudio(!0)):a.setAudio(!0)}t.on("mediachange",()=>{["AUDIO","SUBTITLES"].forEach(l=>e[l].onGroupChanged())}),t.on("mediachanging",()=>{["AUDIO","SUBTITLES"].forEach(l=>e[l].onGroupChanging())});const c=()=>{e.AUDIO.onTrackChanged(),i.trigger({type:"usage",name:"vhs-audio-change"})};i.audioTracks().addEventListener("change",c),i.remoteTextTracks().addEventListener("change",e.SUBTITLES.onTrackChanged),s.on("dispose",()=>{i.audioTracks().removeEventListener("change",c),i.remoteTextTracks().removeEventListener("change",e.SUBTITLES.onTrackChanged)}),i.clearTracks("audio");for(const l in e.AUDIO.tracks)i.audioTracks().addTrack(e.AUDIO.tracks[l])},zP=()=>{const n={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{n[e]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:Fn,activeTrack:Fn,getActiveGroup:Fn,onGroupChanged:Fn,onTrackChanged:Fn,lastTrack_:null,logger_:Oi(`MediaGroups[${e}]`)}}),n};class RT{constructor(){this.priority_=[],this.pathwayClones_=new Map}set version(e){e===1&&(this.version_=e)}set ttl(e){this.ttl_=e||300}set reloadUri(e){e&&(this.reloadUri_=di(this.reloadUri_,e))}set priority(e){e&&e.length&&(this.priority_=e)}set pathwayClones(e){e&&e.length&&(this.pathwayClones_=new Map(e.map(t=>[t.ID,t])))}get version(){return this.version_}get ttl(){return this.ttl_}get reloadUri(){return this.reloadUri_}get priority(){return this.priority_}get pathwayClones(){return this.pathwayClones_}}class GP extends K.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new RT,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.currentPathwayClones=new Map,this.nextPathwayClones=new Map,this.excludedSteeringManifestURLs=new Set,this.logger_=Oi("Content Steering"),this.xhr_=e,this.getBandwidth_=t}assignTagProperties(e,t){this.manifestType_=t.serverUri?"HLS":"DASH";const i=t.serverUri||t.serverURL;if(!i){this.logger_(`steering manifest URL is ${i}, cannot request steering manifest.`),this.trigger("error");return}if(i.startsWith("data:")){this.decodeDataUriManifest_(i.substring(i.indexOf(",")+1));return}this.steeringManifest.reloadUri=di(e,i),this.defaultPathway=t.pathwayId||t.defaultServiceLocation,this.queryBeforeStart=t.queryBeforeStart,this.proxyServerUrl_=t.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger("content-steering")}requestSteeringManifest(e){const t=this.steeringManifest.reloadUri;if(!t)return;const i=e?t:this.getRequestURI(t);if(!i){this.logger_("No valid content steering manifest URIs. Stopping content steering."),this.trigger("error"),this.dispose();return}const s={contentSteeringInfo:{uri:i}};this.trigger({type:"contentsteeringloadstart",metadata:s}),this.request_=this.xhr_({uri:i,requestType:"content-steering-manifest"},(r,a)=>{if(r){if(a.status===410){this.logger_(`manifest request 410 ${r}.`),this.logger_(`There will be no more content steering requests to ${i} this session.`),this.excludedSteeringManifestURLs.add(i);return}if(a.status===429){const l=a.responseHeaders["retry-after"];this.logger_(`manifest request 429 ${r}.`),this.logger_(`content steering will retry in ${l} seconds.`),this.startTTLTimeout_(parseInt(l,10));return}this.logger_(`manifest failed to load ${r}.`),this.startTTLTimeout_();return}this.trigger({type:"contentsteeringloadcomplete",metadata:s});let o;try{o=JSON.parse(this.request_.responseText)}catch(l){const u={errorType:K.Error.StreamingContentSteeringParserError,error:l};this.trigger({type:"error",metadata:u})}this.assignSteeringProperties_(o);const c={contentSteeringInfo:s.contentSteeringInfo,contentSteeringManifest:{version:this.steeringManifest.version,reloadUri:this.steeringManifest.reloadUri,priority:this.steeringManifest.priority}};this.trigger({type:"contentsteeringparsed",metadata:c}),this.startTTLTimeout_()})}setProxyServerUrl_(e){const t=new B.URL(e),i=new B.URL(this.proxyServerUrl_);return i.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(i.toString())}decodeDataUriManifest_(e){const t=JSON.parse(B.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new B.URL(e),i=this.getPathway(),s=this.getBandwidth_();if(i){const r=`_${this.manifestType_}_pathway`;t.searchParams.set(r,i)}if(s){const r=`_${this.manifestType_}_throughput`;t.searchParams.set(r,s)}return t.toString()}assignSteeringProperties_(e){if(this.steeringManifest.version=e.VERSION,!this.steeringManifest.version){this.logger_(`manifest version is ${e.VERSION}, which is not supported.`),this.trigger("error");return}this.steeringManifest.ttl=e.TTL,this.steeringManifest.reloadUri=e["RELOAD-URI"],this.steeringManifest.priority=e["PATHWAY-PRIORITY"]||e["SERVICE-LOCATION-PRIORITY"],this.steeringManifest.pathwayClones=e["PATHWAY-CLONES"],this.nextPathwayClones=this.steeringManifest.pathwayClones,this.availablePathways_.size||(this.logger_("There are no available pathways for content steering. Ending content steering."),this.trigger("error"),this.dispose());const i=(s=>{for(const r of s)if(this.availablePathways_.has(r))return r;return[...this.availablePathways_][0]})(this.steeringManifest.priority);this.currentPathway!==i&&(this.currentPathway=i,this.trigger("content-steering"))}getPathway(){return this.currentPathway||this.defaultPathway}getRequestURI(e){if(!e)return null;const t=s=>this.excludedSteeringManifestURLs.has(s);if(this.proxyServerUrl_){const s=this.setProxyServerUrl_(e);if(!t(s))return s}const i=this.setSteeringParams_(e);return t(i)?null:i}startTTLTimeout_(e=this.steeringManifest.ttl){const t=e*1e3;this.ttlTimeout_=B.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){B.clearTimeout(this.ttlTimeout_),this.ttlTimeout_=null}abort(){this.request_&&this.request_.abort(),this.request_=null}dispose(){this.off("content-steering"),this.off("error"),this.abort(),this.clearTTLTimeout_(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=null,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.excludedSteeringManifestURLs=new Set,this.availablePathways_=new Set,this.steeringManifest=new RT}addAvailablePathway(e){e&&this.availablePathways_.add(e)}clearAvailablePathways(){this.availablePathways_.clear()}excludePathway(e){return this.availablePathways_.delete(e)}didDASHTagChange(e,t){return!t&&this.steeringManifest.reloadUri||t&&(di(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}}const KP=(n,e)=>{let t=null;return(...i)=>{clearTimeout(t),t=setTimeout(()=>{n.apply(null,i)},e)}},XP=10;let Un;const YP=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],QP=function(n){return this.audioSegmentLoader_[n]+this.mainSegmentLoader_[n]},JP=function({currentPlaylist:n,buffered:e,currentTime:t,nextPlaylist:i,bufferLowWaterLine:s,bufferHighWaterLine:r,duration:a,bufferBasedABR:o,log:c}){if(!i)return K.log.warn("We received no playlist to switch to. Please check your stream."),!1;const l=`allowing switch ${n&&n.id||"null"} -> ${i.id}`;if(!n)return c(`${l} as current playlist is not set`),!0;if(i.id===n.id)return!1;const u=!!Fr(e,t).length;if(!n.endList)return!u&&typeof n.partTargetDuration=="number"?(c(`not ${l} as current playlist is live llhls, but currentTime isn't in buffered.`),!1):(c(`${l} as current playlist is live`),!0);const h=af(e,t),p=o?Mt.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:Mt.MAX_BUFFER_LOW_WATER_LINE;if(a<p)return c(`${l} as duration < max low water line (${a} < ${p})`),!0;const y=i.attributes.BANDWIDTH,_=n.attributes.BANDWIDTH;if(y<_&&(!o||h<r)){let b=`${l} as next bandwidth < current bandwidth (${y} < ${_})`;return o&&(b+=` and forwardBuffer < bufferHighWaterLine (${h} < ${r})`),c(b),!0}if((!o||y>_)&&h>=s){let b=`${l} as forwardBuffer >= bufferLowWaterLine (${h} >= ${s})`;return o&&(b+=` and next bandwidth > current bandwidth (${y} > ${_})`),c(b),!0}return c(`not ${l} as no switching criteria met`),!1};class ZP extends K.EventTarget{constructor(e){super(),this.fastQualityChange_=KP(this.fastQualityChange_.bind(this),100);const{src:t,withCredentials:i,tech:s,bandwidth:r,externVhs:a,useCueTags:o,playlistExclusionDuration:c,enableLowInitialPlaylist:l,sourceType:u,cacheEncryptionKeys:h,bufferBasedABR:p,leastPixelDiffSelector:y,captionServices:_,experimentalUseMMS:b}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:S}=e;(S===null||typeof S>"u")&&(S=1/0),Un=a,this.bufferBasedABR=!!p,this.leastPixelDiffSelector=!!y,this.withCredentials=i,this.tech_=s,this.vhs_=s.vhs,this.player_=e.player_,this.sourceType_=u,this.useCueTags_=o,this.playlistExclusionDuration=c,this.maxPlaylistRetries=S,this.enableLowInitialPlaylist=l,this.usingManagedMediaSource_=!1,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:i,maxPlaylistRetries:S,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=zP(),b&&B.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new B.ManagedMediaSource,this.usingManagedMediaSource_=!0,K.log("Using ManagedMediaSource")):B.MediaSource&&(this.mediaSource=new B.MediaSource),this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.load=this.load.bind(this),this.pause=this.pause.bind(this),this.mediaSource.addEventListener("durationchange",this.handleDurationChange_),this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_),this.mediaSource.addEventListener("startstreaming",this.load),this.mediaSource.addEventListener("endstreaming",this.pause),this.seekable_=Ot(),this.hasPlayed_=!1,this.syncController_=new OP(e),this.segmentMetadataTrack_=s.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.segmentMetadataTrack_.mode="hidden",this.decrypter_=new NP,this.sourceUpdater_=new CT(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new MP,this.keyStatusMap_=new Map;const D={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:_,mediaSource:this.mediaSource,currentTime:this.tech_.currentTime.bind(this.tech_),seekable:()=>this.seekable(),seeking:()=>this.tech_.seeking(),duration:()=>this.duration(),hasPlayed:()=>this.hasPlayed_,goalBufferLength:()=>this.goalBufferLength(),bandwidth:r,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:h,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_=this.sourceType_==="dash"?new yf(t,this.vhs_,We(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new qr(t,this.vhs_,We(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new Cf(We(D,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new Cf(We(D,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new AP(We(D,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((w,P)=>{function L(){s.off("vttjserror",C),w()}function C(){s.off("vttjsloaded",L),P()}s.one("vttjsloaded",L),s.one("vttjserror",C),s.addWebVttScript_()})}),e);const I=()=>this.mainSegmentLoader_.bandwidth;this.contentSteeringController_=new GP(this.vhs_.xhr,I),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",()=>this.startABRTimer_()),this.tech_.on("pause",()=>this.stopABRTimer_()),this.tech_.on("play",()=>this.startABRTimer_())),YP.forEach(w=>{this[w+"_"]=QP.bind(this,w)}),this.logger_=Oi("pc"),this.triggeredFmp4Usage=!1,this.tech_.preload()==="none"?(this.loadOnPlay_=()=>{this.loadOnPlay_=null,this.mainPlaylistLoader_.load()},this.tech_.one("play",this.loadOnPlay_)):this.mainPlaylistLoader_.load(),this.timeToLoadedData__=-1,this.mainAppendsToLoadedData__=-1,this.audioAppendsToLoadedData__=-1;const F=this.tech_.preload()==="none"?"play":"loadstart";this.tech_.one(F,()=>{const w=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-w,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends})})}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){const e=this.mainAppendsToLoadedData_(),t=this.audioAppendsToLoadedData_();return e===-1||t===-1?-1:e+t}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(e="abr"){const t=this.selectPlaylist();t&&this.shouldSwitchToMedia_(t)&&this.switchMedia_(t,e)}switchMedia_(e,t,i){const s=this.media(),r=s&&(s.id||s.uri),a=e&&(e.id||e.uri);if(r&&r!==a){this.logger_(`switch media ${r} -> ${a} from ${t}`);const o={renditionInfo:{id:a,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS},cause:t};this.trigger({type:"renditionselected",metadata:o}),this.tech_.trigger({type:"usage",name:`vhs-rendition-change-${t}`})}this.mainPlaylistLoader_.media(e,i)}switchMediaForDASHContentSteering_(){["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{const t=this.mediaTypes_[e],i=t?t.activeGroup():null,s=this.contentSteeringController_.getPathway();if(i&&s){const a=(i.length?i[0].playlists:i.playlists).filter(o=>o.attributes.serviceLocation===s);a.length&&this.mediaTypes_[e].activePlaylistLoader.media(a[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=B.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(B.clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){const e=this.main(),t=e&&e.playlists||[];if(!e||!e.mediaGroups||!e.mediaGroups.AUDIO)return t;const i=e.mediaGroups.AUDIO,s=Object.keys(i);let r;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)r=this.mediaTypes_.AUDIO.activeTrack();else{const o=i.main||s.length&&i[s[0]];for(const c in o)if(o[c].default){r={label:c};break}}if(!r)return t;const a=[];for(const o in i)if(i[o][r.label]){const c=i[o][r.label];if(c.playlists&&c.playlists.length)a.push.apply(a,c.playlists);else if(c.uri)a.push(c);else if(e.playlists.length)for(let l=0;l<e.playlists.length;l++){const u=e.playlists[l];u.attributes&&u.attributes.AUDIO&&u.attributes.AUDIO===o&&a.push(u)}}return a.length?a:t}setupMainPlaylistLoaderListeners_(){this.mainPlaylistLoader_.on("loadedmetadata",()=>{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;uf(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=i,t.endList&&this.tech_.preload()!=="none"&&(this.mainSegmentLoader_.playlist(t,this.requestOptions_),this.mainSegmentLoader_.load()),WP({sourceType:this.sourceType_,segmentLoaders:{AUDIO:this.audioSegmentLoader_,SUBTITLES:this.subtitleSegmentLoader_,main:this.mainSegmentLoader_},tech:this.tech_,requestOptions:this.requestOptions_,mainPlaylistLoader:this.mainPlaylistLoader_,vhs:this.vhs_,main:this.main(),mediaTypes:this.mediaTypes_,excludePlaylist:this.excludePlaylist.bind(this)}),this.triggerPresenceUsage_(this.main(),t),this.setupFirstPlay(),!this.mediaTypes_.AUDIO.activePlaylistLoader||this.mediaTypes_.AUDIO.activePlaylistLoader.media()?this.trigger("selectedinitialmedia"):this.mediaTypes_.AUDIO.activePlaylistLoader.one("loadedmetadata",()=>{this.trigger("selectedinitialmedia")})}),this.mainPlaylistLoader_.on("loadedplaylist",()=>{this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_);let t=this.mainPlaylistLoader_.media();if(!t){this.attachContentSteeringListeners_(),this.initContentSteeringController_(),this.excludeUnsupportedVariants_();let i;if(this.enableLowInitialPlaylist&&(i=this.selectInitialPlaylist()),i||(i=this.selectPlaylist()),!i||!this.shouldSwitchToMedia_(i)||(this.initialMedia_=i,this.switchMedia_(this.initialMedia_,"initial"),!(this.sourceType_==="vhs-json"&&this.initialMedia_.segments)))return;t=this.initialMedia_}this.handleUpdatedMediaPlaylist(t)}),this.mainPlaylistLoader_.on("error",()=>{const t=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:t.playlist,error:t})}),this.mainPlaylistLoader_.on("mediachanging",()=>{this.mainSegmentLoader_.abort(),this.mainSegmentLoader_.pause()}),this.mainPlaylistLoader_.on("mediachange",()=>{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;uf(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=i,this.sourceType_==="dash"&&this.mainPlaylistLoader_.isPaused&&this.mainPlaylistLoader_.load(),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(t,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():this.mainSegmentLoader_.load(),this.tech_.trigger({type:"mediachange",bubbles:!0})}),this.mainPlaylistLoader_.on("playlistunchanged",()=>{const t=this.mainPlaylistLoader_.media();if(t.lastExcludeReason_==="playlist-unchanged")return;this.stuckAtPlaylistEnd_(t)&&(this.excludePlaylist({error:{message:"Playlist no longer updating.",reason:"playlist-unchanged"}}),this.tech_.trigger("playliststuck"))}),this.mainPlaylistLoader_.on("renditiondisabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-disabled"})}),this.mainPlaylistLoader_.on("renditionenabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-enabled"})}),["manifestrequeststart","manifestrequestcomplete","manifestparsestart","manifestparsecomplete","playlistrequeststart","playlistrequestcomplete","playlistparsestart","playlistparsecomplete","renditiondisabled","renditionenabled"].forEach(t=>{this.mainPlaylistLoader_.on(t,i=>{this.player_.trigger(vt({},i))})})}handleUpdatedMediaPlaylist(e){this.useCueTags_&&this.updateAdCues_(e),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_(),this.updateDuration(!e.endList),this.tech_.paused()||(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(e,t){const i=e.mediaGroups||{};let s=!0;const r=Object.keys(i.AUDIO);for(const a in i.AUDIO)for(const o in i.AUDIO[a])i.AUDIO[a][o].uri||(s=!1);s&&this.tech_.trigger({type:"usage",name:"vhs-demuxed"}),Object.keys(i.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"}),Un.Playlist.isAes(t)&&this.tech_.trigger({type:"usage",name:"vhs-aes"}),r.length&&Object.keys(i.AUDIO[r[0]]).length>1&&this.tech_.trigger({type:"usage",name:"vhs-alternate-audio"}),this.useCueTags_&&this.tech_.trigger({type:"usage",name:"vhs-playlist-cue-tags"})}shouldSwitchToMedia_(e){const t=this.mainPlaylistLoader_.media()||this.mainPlaylistLoader_.pendingMedia_,i=this.tech_.currentTime(),s=this.bufferLowWaterLine(),r=this.bufferHighWaterLine(),a=this.tech_.buffered();return JP({buffered:a,currentTime:i,currentPlaylist:t,nextPlaylist:e,bufferLowWaterLine:s,bufferHighWaterLine:r,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.mainSegmentLoader_.on("bandwidthupdate",()=>{this.checkABR_("bandwidthupdate"),this.tech_.trigger("bandwidthupdate")}),this.mainSegmentLoader_.on("timeout",()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()}),this.bufferBasedABR||this.mainSegmentLoader_.on("progress",()=>{this.trigger("progress")}),this.mainSegmentLoader_.on("error",()=>{const i=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:i.playlist,error:i})}),this.mainSegmentLoader_.on("appenderror",()=>{this.error=this.mainSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.mainSegmentLoader_.on("timestampoffset",()=>{this.tech_.trigger({type:"usage",name:"vhs-timestamp-offset"})}),this.audioSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.audioSegmentLoader_.on("appenderror",()=>{this.error=this.audioSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("ended",()=>{this.logger_("main segment loader ended"),this.onEndOfStream()}),this.timelineChangeController_.on("audioTimelineBehind",()=>{const i=this.audioSegmentLoader_.pendingSegment_;if(!i||!i.segment||!i.segment.syncInfo)return;const s=i.segment.syncInfo.end+.01;this.tech_.setCurrentTime(s)}),this.timelineChangeController_.on("fixBadTimelineChange",()=>{this.logger_("Fix bad timeline change. Restarting al segment loaders..."),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}),this.mainSegmentLoader_.on("earlyabort",i=>{this.bufferBasedABR||(this.delegateLoaders_("all",["abort"]),this.excludePlaylist({error:{message:"Aborted early because there isn't enough bandwidth to complete the request without rebuffering."},playlistExclusionDuration:XP}))});const e=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();const i=this.getCodecsOrExclude_();i&&this.sourceUpdater_.addOrChangeSourceBuffers(i)};this.mainSegmentLoader_.on("trackinfo",e),this.audioSegmentLoader_.on("trackinfo",e),this.mainSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("ended",()=>{this.logger_("audioSegmentLoader ended"),this.onEndOfStream()}),["segmentselected","segmentloadstart","segmentloaded","segmentkeyloadstart","segmentkeyloadcomplete","segmentdecryptionstart","segmentdecryptioncomplete","segmenttransmuxingstart","segmenttransmuxingcomplete","segmenttransmuxingtrackinfoavailable","segmenttransmuxingtiminginfoavailable","segmentappendstart","appendsdone","bandwidthupdated","timelinechange","codecschange"].forEach(i=>{this.mainSegmentLoader_.on(i,s=>{this.player_.trigger(vt({},s))}),this.audioSegmentLoader_.on(i,s=>{this.player_.trigger(vt({},s))}),this.subtitleSegmentLoader_.on(i,s=>{this.player_.trigger(vt({},s))})})}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}pause(){this.mainSegmentLoader_.pause(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.pause(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.pause()}fastQualityChange_(e=this.selectPlaylist()){if(e&&e===this.mainPlaylistLoader_.media()){this.logger_("skipping fastQualityChange because new media is same as old");return}this.switchMedia_(e,"fast-quality"),this.waitingForFastQualityPlaylistReceived_=!0}runFastQualitySwitch_(){this.waitingForFastQualityPlaylistReceived_=!1,this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}play(){if(this.setupFirstPlay())return;this.tech_.ended()&&this.tech_.setCurrentTime(0),this.hasPlayed_&&this.load();const e=this.tech_.seekable();if(this.tech_.duration()===1/0&&this.tech_.currentTime()<e.start(0))return this.tech_.setCurrentTime(e.end(e.length-1))}setupFirstPlay(){const e=this.mainPlaylistLoader_.media();if(!e||this.tech_.paused()||this.hasPlayed_)return!1;if(!e.endList||e.start){const t=this.seekable();if(!t.length)return!1;const i=t.end(0);let s=i;if(e.start){const r=e.start.timeOffset;if(r<0){const a=this.mainPlaylistLoader_.main,o=Un.Playlist.liveEdgeDelay(a,e),c=i+o;s=Math.max(Math.min(c+r,i),t.start(0))}else s=Math.min(i,r)}this.trigger("firstplay"),this.tech_.setCurrentTime(s)}return this.hasPlayed_=!0,this.load(),!0}handleSourceOpen_(){if(this.tryToCreateSourceBuffers_(),this.tech_.autoplay()){const e=this.tech_.play();typeof e<"u"&&typeof e.then=="function"&&e.then(null,t=>{})}this.trigger("sourceopen")}handleSourceEnded_(){if(!this.inbandTextTracks_.metadataTrack_)return;const e=this.inbandTextTracks_.metadataTrack_.cues;if(!e||!e.length)return;const t=this.duration();e[e.length-1].endTime=isNaN(t)||Math.abs(t)===1/0?Number.MAX_VALUE:t}handleDurationChange_(){this.tech_.trigger("durationchange")}onEndOfStream(){let e=this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){const t=this.mainSegmentLoader_.getCurrentMediaInfo_();!t||t.hasVideo?e=e&&this.audioSegmentLoader_.ended_:e=this.audioSegmentLoader_.ended_}e&&(this.stopABRTimer_(),this.sourceUpdater_.endOfStream())}stuckAtPlaylistEnd_(e){if(!this.seekable().length)return!1;const i=this.syncController_.getExpiredTime(e,this.duration());if(i===null)return!1;const s=Un.Playlist.playlistEnd(e,i),r=this.tech_.currentTime(),a=this.tech_.buffered();if(!a.length)return s-r<=gn;const o=a.end(a.length-1);return o-r<=gn&&s-o<=gn}excludePlaylist({playlistToExclude:e=this.mainPlaylistLoader_.media(),error:t={},playlistExclusionDuration:i}){if(e=e||this.mainPlaylistLoader_.media(),i=i||t.playlistExclusionDuration||this.playlistExclusionDuration,!e){this.error=t,this.mediaSource.readyState!=="open"?this.trigger("error"):this.sourceUpdater_.endOfStream("network");return}e.playlistErrors_++;const s=this.mainPlaylistLoader_.main.playlists,r=s.filter(Tl),a=r.length===1&&r[0]===e;if(s.length===1&&i!==1/0)return K.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(a);if(a){if(this.main().contentSteering){const _=this.pathwayAttribute_(e),b=this.contentSteeringController_.steeringManifest.ttl*1e3;this.contentSteeringController_.excludePathway(_),this.excludeThenChangePathway_(),setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(_)},b);return}let y=!1;s.forEach(_=>{if(_===e)return;const b=_.excludeUntil;typeof b<"u"&&b!==1/0&&(y=!0,delete _.excludeUntil)}),y&&(K.log.warn("Removing other playlists from the exclusion list because the last rendition is about to be excluded."),this.tech_.trigger("retryplaylist"))}let o;e.playlistErrors_>this.maxPlaylistRetries?o=1/0:o=Date.now()+i*1e3,e.excludeUntil=o,t.reason&&(e.lastExcludeReason_=t.reason),this.tech_.trigger("excludeplaylist"),this.tech_.trigger({type:"usage",name:"vhs-rendition-excluded"});const c=this.selectPlaylist();if(!c){this.error="Playback cannot continue. No available working or supported playlists.",this.trigger("error");return}const l=t.internal?this.logger_:K.log.warn,u=t.message?" "+t.message:"";l(`${t.internal?"Internal problem":"Problem"} encountered with playlist ${e.id}.${u} Switching to playlist ${c.id}.`),c.attributes.AUDIO!==e.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),c.attributes.SUBTITLES!==e.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]);const h=c.targetDuration/2*1e3||5*1e3,p=typeof c.lastRequest=="number"&&Date.now()-c.lastRequest<=h;return this.switchMedia_(c,"exclude",a||p)}pauseLoading(){this.delegateLoaders_("all",["abort","pause"]),this.stopABRTimer_()}delegateLoaders_(e,t){const i=[],s=e==="all";(s||e==="main")&&i.push(this.mainPlaylistLoader_);const r=[];(s||e==="audio")&&r.push("AUDIO"),(s||e==="subtitle")&&(r.push("CLOSED-CAPTIONS"),r.push("SUBTITLES")),r.forEach(a=>{const o=this.mediaTypes_[a]&&this.mediaTypes_[a].activePlaylistLoader;o&&i.push(o)}),["main","audio","subtitle"].forEach(a=>{const o=this[`${a}SegmentLoader_`];o&&(e===a||e==="all")&&i.push(o)}),i.forEach(a=>t.forEach(o=>{typeof a[o]=="function"&&a[o]()}))}setCurrentTime(e){const t=Fr(this.tech_.buffered(),e);if(!(this.mainPlaylistLoader_&&this.mainPlaylistLoader_.media())||!this.mainPlaylistLoader_.media().segments)return 0;if(t&&t.length)return e;this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}duration(){if(!this.mainPlaylistLoader_)return 0;const e=this.mainPlaylistLoader_.media();return e?e.endList?this.mediaSource?this.mediaSource.duration:Un.Playlist.duration(e):1/0:0}seekable(){return this.seekable_}getSeekableRange_(e,t){const i=e.media();if(!i)return null;const s=this.syncController_.getMediaSequenceSync(t);if(s&&s.isReliable){const o=s.start,c=s.end;if(!isFinite(o)||!isFinite(c))return null;const l=Un.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i),u=Math.max(o,c-l);return Ot([[o,u]])}const r=this.syncController_.getExpiredTime(i,this.duration());if(r===null)return null;const a=Un.Playlist.seekable(i,r,Un.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i));return a.length?a:null}computeFinalSeekable_(e,t){if(!t)return e;const i=e.start(0),s=e.end(0),r=t.start(0),a=t.end(0);return r>s||i>a?e:Ot([[Math.max(i,r),Math.min(s,a)]])}onSyncInfoUpdate_(){if(!this.mainPlaylistLoader_)return;const e=this.getSeekableRange_(this.mainPlaylistLoader_,"main");if(!e)return;let t;if(this.mediaTypes_.AUDIO.activePlaylistLoader&&(t=this.getSeekableRange_(this.mediaTypes_.AUDIO.activePlaylistLoader,"audio"),!t))return;const i=this.seekable_;if(this.seekable_=this.computeFinalSeekable_(e,t),!this.seekable_||i&&i.length&&this.seekable_.length&&i.start(0)===this.seekable_.start(0)&&i.end(0)===this.seekable_.end(0))return;this.logger_(`seekable updated [${_b(this.seekable_)}]`);const s={seekableRanges:this.seekable_};this.trigger({type:"seekablerangeschanged",metadata:s}),this.tech_.trigger("seekablechanged")}updateDuration(e){if(this.updateDuration_&&(this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.updateDuration_=null),this.mediaSource.readyState!=="open"){this.updateDuration_=this.updateDuration.bind(this,e),this.mediaSource.addEventListener("sourceopen",this.updateDuration_);return}if(e){const s=this.seekable();if(!s.length)return;(isNaN(this.mediaSource.duration)||this.mediaSource.duration<s.end(s.length-1))&&this.sourceUpdater_.setDuration(s.end(s.length-1));return}const t=this.tech_.buffered();let i=Un.Playlist.duration(this.mainPlaylistLoader_.media());t.length>0&&(i=Math.max(i,t.end(t.length-1))),this.mediaSource.duration!==i&&this.sourceUpdater_.setDuration(i)}dispose(){this.trigger("dispose"),this.decrypter_.terminate(),this.mainPlaylistLoader_.dispose(),this.mainSegmentLoader_.dispose(),this.contentSteeringController_.dispose(),this.keyStatusMap_.clear(),this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_),["AUDIO","SUBTITLES"].forEach(e=>{const t=this.mediaTypes_[e].groups;for(const i in t)t[i].forEach(s=>{s.playlistLoader&&s.playlistLoader.dispose()})}),this.audioSegmentLoader_.dispose(),this.subtitleSegmentLoader_.dispose(),this.sourceUpdater_.dispose(),this.timelineChangeController_.dispose(),this.stopABRTimer_(),this.updateDuration_&&this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.mediaSource.removeEventListener("durationchange",this.handleDurationChange_),this.mediaSource.removeEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.removeEventListener("sourceended",this.handleSourceEnded_),this.off()}main(){return this.mainPlaylistLoader_.main}media(){return this.mainPlaylistLoader_.media()||this.initialMedia_}areMediaTypesKnown_(){const e=!!this.mediaTypes_.AUDIO.activePlaylistLoader,t=!!this.mainSegmentLoader_.getCurrentMediaInfo_(),i=e?!!this.audioSegmentLoader_.getCurrentMediaInfo_():!0;return!(!t||!i)}getCodecsOrExclude_(){const e={main:this.mainSegmentLoader_.getCurrentMediaInfo_()||{},audio:this.audioSegmentLoader_.getCurrentMediaInfo_()||{}},t=this.mainSegmentLoader_.getPendingSegmentPlaylist()||this.media();e.video=e.main;const i=io(this.main(),t),s={},r=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(s.video=i.video||e.main.videoCodec||z1),e.main.isMuxed&&(s.video+=`,${i.audio||e.main.audioCodec||Q0}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||r)&&(s.audio=i.audio||e.main.audioCodec||e.audio.audioCodec||Q0,e.audio.isFmp4=e.main.hasAudio&&!e.main.isMuxed?e.main.isFmp4:e.audio.isFmp4),!s.audio&&!s.video){this.excludePlaylist({playlistToExclude:t,error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});return}const a=(l,u)=>l?Oa(u,this.usingManagedMediaSource_):Xd(u),o={};let c;if(["video","audio"].forEach(function(l){if(s.hasOwnProperty(l)&&!a(e[l].isFmp4,s[l])){const u=e[l].isFmp4?"browser":"muxer";o[u]=o[u]||[],o[u].push(s[l]),l==="audio"&&(c=u)}}),r&&c&&t.attributes.AUDIO){const l=t.attributes.AUDIO;this.main().playlists.forEach(u=>{(u.attributes&&u.attributes.AUDIO)===l&&u!==t&&(u.excludeUntil=1/0)}),this.logger_(`excluding audio group ${l} as ${c} does not support codec(s): "${s.audio}"`)}if(Object.keys(o).length){const l=Object.keys(o).reduce((u,h)=>(u&&(u+=", "),u+=`${h} does not support codec(s): "${o[h].join(",")}"`,u),"")+".";this.excludePlaylist({playlistToExclude:t,error:{internal:!0,message:l},playlistExclusionDuration:1/0});return}if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const l=[];if(["video","audio"].forEach(u=>{const h=(on(this.sourceUpdater_.codecs[u]||"")[0]||{}).type,p=(on(s[u]||"")[0]||{}).type;h&&p&&h.toLowerCase()!==p.toLowerCase()&&l.push(`"${this.sourceUpdater_.codecs[u]}" -> "${s[u]}"`)}),l.length){this.excludePlaylist({playlistToExclude:t,error:{message:`Codec switching not supported: ${l.join(", ")}.`,internal:!0},playlistExclusionDuration:1/0});return}}return s}tryToCreateSourceBuffers_(){if(this.mediaSource.readyState!=="open"||this.sourceUpdater_.hasCreatedSourceBuffers()||!this.areMediaTypesKnown_())return;const e=this.getCodecsOrExclude_();if(!e)return;this.sourceUpdater_.createSourceBuffers(e);const t=[e.video,e.audio].filter(Boolean).join(",");this.excludeIncompatibleVariants_(t)}excludeUnsupportedVariants_(){const e=this.main().playlists,t=[];Object.keys(e).forEach(i=>{const s=e[i];if(t.indexOf(s.id)!==-1)return;t.push(s.id);const r=io(this.main,s),a=[];r.audio&&!Xd(r.audio)&&!Oa(r.audio,this.usingManagedMediaSource_)&&a.push(`audio codec ${r.audio}`),r.video&&!Xd(r.video)&&!Oa(r.video,this.usingManagedMediaSource_)&&a.push(`video codec ${r.video}`),r.text&&r.text==="stpp.ttml.im1t"&&a.push(`text codec ${r.text}`),a.length&&(s.excludeUntil=1/0,this.logger_(`excluding ${s.id} for unsupported: ${a.join(", ")}`))})}excludeIncompatibleVariants_(e){const t=[],i=this.main().playlists,s=to(on(e)),r=Bb(s),a=s.video&&on(s.video)[0]||null,o=s.audio&&on(s.audio)[0]||null;Object.keys(i).forEach(c=>{const l=i[c];if(t.indexOf(l.id)!==-1||l.excludeUntil===1/0)return;t.push(l.id);const u=[],h=io(this.mainPlaylistLoader_.main,l),p=Bb(h);if(!(!h.audio&&!h.video)){if(p!==r&&u.push(`codec count "${p}" !== "${r}"`),!this.sourceUpdater_.canChangeType()){const y=h.video&&on(h.video)[0]||null,_=h.audio&&on(h.audio)[0]||null;y&&a&&y.type.toLowerCase()!==a.type.toLowerCase()&&u.push(`video codec "${y.type}" !== "${a.type}"`),_&&o&&_.type.toLowerCase()!==o.type.toLowerCase()&&u.push(`audio codec "${_.type}" !== "${o.type}"`)}u.length&&(l.excludeUntil=1/0,this.logger_(`excluding ${l.id}: ${u.join(" && ")}`))}})}updateAdCues_(e){let t=0;const i=this.seekable();i.length&&(t=i.start(0)),PP(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=Mt.GOAL_BUFFER_LENGTH,i=Mt.GOAL_BUFFER_LENGTH_RATE,s=Math.max(t,Mt.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,s)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=Mt.BUFFER_LOW_WATER_LINE,i=Mt.BUFFER_LOW_WATER_LINE_RATE,s=Math.max(t,Mt.MAX_BUFFER_LOW_WATER_LINE),r=Math.max(t,Mt.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?r:s)}bufferHighWaterLine(){return Mt.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){gT(this.inbandTextTracks_,"com.apple.streaming",this.tech_),lP({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){const s=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();gT(this.inbandTextTracks_,e,this.tech_),aP({inbandTextTracks:this.inbandTextTracks_,metadataArray:t,timestampOffset:s,videoDuration:i})}pathwayAttribute_(e){return e.attributes["PATHWAY-ID"]||e.attributes.serviceLocation}initContentSteeringController_(){const e=this.main();if(e.contentSteering){for(const t of e.playlists)this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(t));if(this.contentSteeringController_.assignTagProperties(e.uri,e.contentSteering),this.contentSteeringController_.queryBeforeStart){this.contentSteeringController_.requestSteeringManifest(!0);return}this.tech_.one("canplay",()=>{this.contentSteeringController_.requestSteeringManifest()})}}resetContentSteeringController_(){this.contentSteeringController_.clearAvailablePathways(),this.contentSteeringController_.dispose(),this.initContentSteeringController_()}attachContentSteeringListeners_(){this.contentSteeringController_.on("content-steering",this.excludeThenChangePathway_.bind(this)),["contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"].forEach(t=>{this.contentSteeringController_.on(t,i=>{this.trigger(vt({},i))})}),this.sourceType_==="dash"&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{const t=this.main();(this.contentSteeringController_.didDASHTagChange(t.uri,t.contentSteering)||(()=>{const r=this.contentSteeringController_.getAvailablePathways(),a=[];for(const o of t.playlists){const c=o.attributes.serviceLocation;if(c&&(a.push(c),!r.has(c)))return!0}return!!(!a.length&&r.size)})())&&this.resetContentSteeringController_()})}excludeThenChangePathway_(){const e=this.contentSteeringController_.getPathway();if(!e)return;this.handlePathwayClones_();const i=this.main().playlists,s=new Set;let r=!1;Object.keys(i).forEach(a=>{const o=i[a],c=this.pathwayAttribute_(o),l=c&&e!==c;o.excludeUntil===1/0&&o.lastExcludeReason_==="content-steering"&&!l&&(delete o.excludeUntil,delete o.lastExcludeReason_,r=!0);const h=!o.excludeUntil&&o.excludeUntil!==1/0;!s.has(o.id)&&l&&h&&(s.add(o.id),o.excludeUntil=1/0,o.lastExcludeReason_="content-steering",this.logger_(`excluding ${o.id} for ${o.lastExcludeReason_}`))}),this.contentSteeringController_.manifestType_==="DASH"&&Object.keys(this.mediaTypes_).forEach(a=>{const o=this.mediaTypes_[a];if(o.activePlaylistLoader){const c=o.activePlaylistLoader.media_;c&&c.attributes.serviceLocation!==e&&(r=!0)}}),r&&this.changeSegmentPathway_()}handlePathwayClones_(){const t=this.main().playlists,i=this.contentSteeringController_.currentPathwayClones,s=this.contentSteeringController_.nextPathwayClones;if(i&&i.size||s&&s.size){for(const[a,o]of i.entries())s.get(a)||(this.mainPlaylistLoader_.updateOrDeleteClone(o),this.contentSteeringController_.excludePathway(a));for(const[a,o]of s.entries()){const c=i.get(a);if(!c){t.filter(u=>u.attributes["PATHWAY-ID"]===o["BASE-ID"]).forEach(u=>{this.mainPlaylistLoader_.addClonePathway(o,u)}),this.contentSteeringController_.addAvailablePathway(a);continue}this.equalPathwayClones_(c,o)||(this.mainPlaylistLoader_.updateOrDeleteClone(o,!0),this.contentSteeringController_.addAvailablePathway(a))}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...s])))}}equalPathwayClones_(e,t){if(e["BASE-ID"]!==t["BASE-ID"]||e.ID!==t.ID||e["URI-REPLACEMENT"].HOST!==t["URI-REPLACEMENT"].HOST)return!1;const i=e["URI-REPLACEMENT"].PARAMS,s=t["URI-REPLACEMENT"].PARAMS;for(const r in i)if(i[r]!==s[r])return!1;for(const r in s)if(i[r]!==s[r])return!1;return!0}changeSegmentPathway_(){const e=this.selectPlaylist();this.pauseLoading(),this.contentSteeringController_.manifestType_==="DASH"&&this.switchMediaForDASHContentSteering_(),this.switchMedia_(e,"content-steering")}excludeNonUsablePlaylistsByKeyId_(){if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.main)return;let e=0;const t="non-usable";this.mainPlaylistLoader_.main.playlists.forEach(i=>{const s=this.mainPlaylistLoader_.getKeyIdSet(i);!s||!s.size||s.forEach(r=>{const a="usable",o=this.keyStatusMap_.has(r)&&this.keyStatusMap_.get(r)===a,c=i.lastExcludeReason_===t&&i.excludeUntil===1/0;o?o&&c&&(delete i.excludeUntil,delete i.lastExcludeReason_,this.logger_(`enabling playlist ${i.id} because key ID ${r} is ${a}`)):(i.excludeUntil!==1/0&&i.lastExcludeReason_!==t&&(i.excludeUntil=1/0,i.lastExcludeReason_=t,this.logger_(`excluding playlist ${i.id} because the key ID ${r} doesn't exist in the keyStatusMap or is not ${a}`)),e++)})}),e>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach(i=>{const s=i&&i.attributes&&i.attributes.RESOLUTION&&i.attributes.RESOLUTION.height<720,r=i.excludeUntil===1/0&&i.lastExcludeReason_===t;s&&r&&(delete i.excludeUntil,K.log.warn(`enabling non-HD playlist ${i.id} because all playlists were excluded due to ${t} key IDs`))})}addKeyStatus_(e,t){const r=(typeof e=="string"?e:xP(e)).slice(0,32).toLowerCase();this.logger_(`KeyStatus '${t}' with key ID ${r} added to the keyStatusMap`),this.keyStatusMap_.set(r,t)}updatePlaylistByKeyStatus(e,t){this.addKeyStatus_(e,t),this.waitingForFastQualityPlaylistReceived_||this.excludeNonUsableThenChangePlaylist_(),this.mainPlaylistLoader_.off("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this)),this.mainPlaylistLoader_.on("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this))}excludeNonUsableThenChangePlaylist_(){this.excludeNonUsablePlaylistsByKeyId_(),this.fastQualityChange_()}}const eI=(n,e,t)=>i=>{const s=n.main.playlists[e],r=lf(s),a=Tl(s);if(typeof i>"u")return a;i?delete s.disabled:s.disabled=!0;const o={renditionInfo:{id:e,bandwidth:s.attributes.BANDWIDTH,resolution:s.attributes.RESOLUTION,codecs:s.attributes.CODECS},cause:"fast-quality"};return i!==a&&!r&&(i?(t(s),n.trigger({type:"renditionenabled",metadata:o})):n.trigger({type:"renditiondisabled",metadata:o})),i};class tI{constructor(e,t,i){const{playlistController_:s}=e,r=s.fastQualityChange_.bind(s);if(t.attributes){const a=t.attributes.RESOLUTION;this.width=a&&a.width,this.height=a&&a.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}this.codecs=io(s.main(),t),this.playlist=t,this.id=i,this.enabled=eI(e.playlists,t.id,r)}}const iI=function(n){n.representations=()=>{const e=n.playlistController_.main(),t=eo(e)?n.playlistController_.getAudioTrackPlaylists_():e.playlists;return t?t.filter(i=>!lf(i)).map((i,s)=>new tI(n,i,i.id)):[]}},OT=["seeking","seeked","pause","playing","error"];class nI extends K.EventTarget{constructor(e){super(),this.playlistController_=e.playlistController,this.tech_=e.tech,this.seekable=e.seekable,this.allowSeeksWithinUnsafeLiveWindow=e.allowSeeksWithinUnsafeLiveWindow,this.liveRangeSafeTimeDelta=e.liveRangeSafeTimeDelta,this.media=e.media,this.playedRanges_=[],this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=Oi("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),s=()=>this.techWaiting_(),r=()=>this.resetTimeUpdate_(),a=this.playlistController_,o=["main","subtitle","audio"],c={};o.forEach(u=>{c[u]={reset:()=>this.resetSegmentDownloads_(u),updateend:()=>this.checkSegmentDownloads_(u)},a[`${u}SegmentLoader_`].on("appendsdone",c[u].updateend),a[`${u}SegmentLoader_`].on("playlistupdate",c[u].reset),this.tech_.on(["seeked","seeking"],c[u].reset)});const l=u=>{["main","audio"].forEach(h=>{a[`${h}SegmentLoader_`][u]("appended",this.seekingAppendCheck_)})};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),l("off"))},this.clearSeekingAppendCheck_=()=>l("off"),this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_(),l("on")},this.tech_.on("seeked",this.clearSeekingAppendCheck_),this.tech_.on("seeking",this.watchForBadSeeking_),this.tech_.on("waiting",s),this.tech_.on(OT,r),this.tech_.on("canplay",i),this.tech_.one("play",t),this.dispose=()=>{this.clearSeekingAppendCheck_(),this.logger_("dispose"),this.tech_.off("waiting",s),this.tech_.off(OT,r),this.tech_.off("canplay",i),this.tech_.off("play",t),this.tech_.off("seeking",this.watchForBadSeeking_),this.tech_.off("seeked",this.clearSeekingAppendCheck_),o.forEach(u=>{a[`${u}SegmentLoader_`].off("appendsdone",c[u].updateend),a[`${u}SegmentLoader_`].off("playlistupdate",c[u].reset),this.tech_.off(["seeked","seeking"],c[u].reset)}),this.checkCurrentTimeTimeout_&&B.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&B.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=B.setTimeout(this.monitorCurrentTime_.bind(this),250)}resetSegmentDownloads_(e){const t=this.playlistController_[`${e}SegmentLoader_`];this[`${e}StalledDownloads_`]>0&&this.logger_(`resetting possible stalled download count for ${e} loader`),this[`${e}StalledDownloads_`]=0,this[`${e}Buffered_`]=t.buffered_()}checkSegmentDownloads_(e){const t=this.playlistController_,i=t[`${e}SegmentLoader_`],s=i.buffered_(),r=WA(this[`${e}Buffered_`],s);if(this[`${e}Buffered_`]=s,r){const a={bufferedRanges:s};t.trigger({type:"bufferedrangeschanged",metadata:a}),this.resetSegmentDownloads_(e);return}this[`${e}StalledDownloads_`]++,this.logger_(`found #${this[`${e}StalledDownloads_`]} ${e} appends that did not increase buffer (possible stalled download)`,{playlistId:i.playlist_&&i.playlist_.id,buffered:js(s)}),!(this[`${e}StalledDownloads_`]<10)&&(this.logger_(`${e} loader stalled download exclusion`),this.resetSegmentDownloads_(e),this.tech_.trigger({type:"usage",name:`vhs-${e}-download-exclusion`}),e!=="subtitle"&&t.excludePlaylist({error:{message:`Excessive ${e} segment downloading detected.`},playlistExclusionDuration:1/0}))}checkCurrentTime_(){if(this.tech_.paused()||this.tech_.seeking())return;const e=this.tech_.currentTime(),t=this.tech_.buffered();if(this.lastRecordedTime===e&&(!t.length||e+gn>=t.end(t.length-1)))return this.techWaiting_();if(this.consecutiveUpdates>=5&&e===this.lastRecordedTime)this.consecutiveUpdates++,this.waiting_();else if(e===this.lastRecordedTime)this.consecutiveUpdates++;else{this.playedRanges_.push(Ot([this.lastRecordedTime,e]));const i={playedRanges:this.playedRanges_};this.playlistController_.trigger({type:"playedrangeschanged",metadata:i}),this.consecutiveUpdates=0,this.lastRecordedTime=e}}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){if(!this.tech_.seeking())return!1;const t=this.seekable(),i=this.tech_.currentTime(),s=this.afterSeekableWindow_(t,i,this.media(),this.allowSeeksWithinUnsafeLiveWindow);let r;if(s&&(r=t.end(t.length-1)),this.beforeSeekableWindow_(t,i)){const _=t.start(0);r=_+(_===t.end(0)?0:gn)}if(typeof r<"u")return this.logger_(`Trying to seek outside of seekable at time ${i} with seekable range ${_b(t)}. Seeking to ${r}.`),this.tech_.setCurrentTime(r),!0;const a=this.playlistController_.sourceUpdater_,o=this.tech_.buffered(),c=a.audioBuffer?a.audioBuffered():null,l=a.videoBuffer?a.videoBuffered():null,u=this.media(),h=u.partTargetDuration?u.partTargetDuration:(u.targetDuration-mn)*2,p=[c,l];for(let _=0;_<p.length;_++){if(!p[_])continue;if(af(p[_],i)<h)return!1}const y=bl(o,i);return y.length===0?!1:(r=y.start(0)+gn,this.logger_(`Buffered region starts (${y.start(0)}) just beyond seek point (${i}). Seeking to ${r}.`),this.tech_.setCurrentTime(r),!0)}waiting_(){if(this.techWaiting_())return;const e=this.tech_.currentTime(),t=this.tech_.buffered(),i=Fr(t,e);if(i.length&&e+3<=i.end(0)){this.resetTimeUpdate_(),this.tech_.setCurrentTime(e),this.logger_(`Stopped at ${e} while inside a buffered region [${i.start(0)} -> ${i.end(0)}]. Attempting to resume playback by seeking to the current time.`),this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"});return}}techWaiting_(){const e=this.seekable(),t=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(e,t)){const o=e.end(e.length-1);return this.logger_(`Fell out of live window at time ${t}. Seeking to live point (seekable end) ${o}`),this.resetTimeUpdate_(),this.tech_.setCurrentTime(o),this.tech_.trigger({type:"usage",name:"vhs-live-resync"}),!0}const i=this.tech_.vhs.playlistController_.sourceUpdater_,s=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:i.audioBuffered(),videoBuffered:i.videoBuffered(),currentTime:t}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(t),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),!0;const a=bl(s,t);return a.length>0?(this.logger_(`Stopped at ${t} and seeking to ${a.start(0)}`),this.resetTimeUpdate_(),this.skipTheGap_(t),!0):!1}afterSeekableWindow_(e,t,i,s=!1){if(!e.length)return!1;let r=e.end(e.length-1)+gn;const a=!i.endList,o=typeof i.partTargetDuration=="number";return a&&(o||s)&&(r=e.end(e.length-1)+i.targetDuration*3),t>r}beforeSeekableWindow_(e,t){return!!(e.length&&e.start(0)>0&&t<e.start(0)-this.liveRangeSafeTimeDelta)}videoUnderflow_({videoBuffered:e,audioBuffered:t,currentTime:i}){if(!e)return;let s;if(e.length&&t.length){const r=Fr(e,i-3),a=Fr(e,i),o=Fr(t,i);o.length&&!a.length&&r.length&&(s={start:r.end(0),end:o.end(0)})}else bl(e,i).length||(s=this.gapFromVideoUnderflow_(e,i));return s?(this.logger_(`Encountered a gap in video from ${s.start} to ${s.end}. Seeking to current time ${i}`),!0):!1}skipTheGap_(e){const t=this.tech_.buffered(),i=this.tech_.currentTime(),s=bl(t,i);if(this.resetTimeUpdate_(),s.length===0||i!==e)return;this.logger_("skipTheGap_:","currentTime:",i,"scheduled currentTime:",e,"nextRange start:",s.start(0)),this.tech_.setCurrentTime(s.start(0)+mn);const r={gapInfo:{from:i,to:s.start(0)}};this.playlistController_.trigger({type:"gapjumped",metadata:r}),this.tech_.trigger({type:"usage",name:"vhs-gap-skip"})}gapFromVideoUnderflow_(e,t){const i=jA(e);for(let s=0;s<i.length;s++){const r=i.start(s),a=i.end(s);if(t-r<4&&t-r>2)return{start:r,end:a}}return null}}const sI={errorInterval:30,getSource(n){const t=this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource();return n(t)}},MT=function(n,e){let t=0,i=0;const s=We(sI,e);n.ready(()=>{n.trigger({type:"usage",name:"vhs-error-reload-initialized"})});const r=function(){i&&n.currentTime(i)},a=function(u){u!=null&&(i=n.duration()!==1/0&&n.currentTime()||0,n.one("loadedmetadata",r),n.src(u),n.trigger({type:"usage",name:"vhs-error-reload"}),n.play())},o=function(){if(Date.now()-t<s.errorInterval*1e3){n.trigger({type:"usage",name:"vhs-error-reload-canceled"});return}if(!s.getSource||typeof s.getSource!="function"){K.log.error("ERROR: reloadSourceOnError - The option getSource must be a function!");return}return t=Date.now(),s.getSource.call(n,a)},c=function(){n.off("loadedmetadata",r),n.off("error",o),n.off("dispose",c)},l=function(u){c(),MT(n,u)};n.on("error",o),n.on("dispose",c),n.reloadSourceOnError=l},rI=function(n){MT(this,n)};var LT="3.17.5",aI="7.1.0",oI="1.4.0",cI="7.2.0",lI="4.0.2";const lt={PlaylistLoader:qr,Playlist:hi,utils:mD,STANDARD_PLAYLIST_SELECTOR:pT,INITIAL_PLAYLIST_SELECTOR:tP,lastBandwidthSelector:pT,movingAverageBandwidthSelector:ZD,comparePlaylistBandwidth:_f,comparePlaylistResolution:JD,xhr:$b()};Object.keys(Mt).forEach(n=>{Object.defineProperty(lt,n,{get(){return K.log.warn(`using Vhs.${n} is UNSAFE be sure you know what you are doing`),Mt[n]},set(e){if(K.log.warn(`using Vhs.${n} is UNSAFE be sure you know what you are doing`),typeof e!="number"||e<0){K.log.warn(`value of Vhs.${n} must be greater than or equal to 0`);return}Mt[n]=e}})});const NT="videojs-vhs",FT=function(n,e){const t=e.media();let i=-1;for(let s=0;s<n.length;s++)if(n[s].id===t.id){i=s;break}n.selectedIndex_=i,n.trigger({selectedIndex:i,type:"change"})},uI=function(n,e){e.representations().forEach(t=>{n.addQualityLevel(t)}),FT(n,e.playlists)};lt.canPlaySource=function(){return K.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const dI=(n,e,t)=>{if(!n)return n;let i={};e&&e.attributes&&e.attributes.CODECS&&(i=to(on(e.attributes.CODECS))),t&&t.attributes&&t.attributes.CODECS&&(i.audio=t.attributes.CODECS);const s=gr(i.video),r=gr(i.audio),a={};for(const o in n)a[o]={},r&&(a[o].audioContentType=r),s&&(a[o].videoContentType=s),e.contentProtection&&e.contentProtection[o]&&e.contentProtection[o].pssh&&(a[o].pssh=e.contentProtection[o].pssh),typeof n[o]=="string"&&(a[o].url=n[o]);return We(n,a)},hI=(n,e)=>n.reduce((t,i)=>{if(!i.contentProtection)return t;const s=e.reduce((r,a)=>{const o=i.contentProtection[a];return o&&o.pssh&&(r[a]={pssh:o.pssh}),r},{});return Object.keys(s).length&&t.push(s),t},[]),fI=({player:n,sourceKeySystems:e,audioMedia:t,mainPlaylists:i})=>{if(!n.eme.initializeMediaKeys)return Promise.resolve();const s=t?i.concat([t]):i,r=hI(s,Object.keys(e)),a=[],o=[];return r.forEach(c=>{o.push(new Promise((l,u)=>{n.tech_.one("keysessioncreated",l)})),a.push(new Promise((l,u)=>{n.eme.initializeMediaKeys({keySystems:c},h=>{if(h){u(h);return}l()})}))}),Promise.race([Promise.all(a),Promise.race(o)])},pI=({player:n,sourceKeySystems:e,media:t,audioMedia:i})=>{const s=dI(e,t,i);return s?(n.currentSource().keySystems=s,s&&!n.eme?(K.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1):!0):!1},UT=()=>{if(!B.localStorage)return null;const n=B.localStorage.getItem(NT);if(!n)return null;try{return JSON.parse(n)}catch{return null}},mI=n=>{if(!B.localStorage)return!1;let e=UT();e=e?We(e,n):n;try{B.localStorage.setItem(NT,JSON.stringify(e))}catch{return!1}return e},gI=n=>n.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")===0?JSON.parse(n.substring(n.indexOf(",")+1)):n,BT=(n,e)=>{n._requestCallbackSet||(n._requestCallbackSet=new Set),n._requestCallbackSet.add(e)},qT=(n,e)=>{n._responseCallbackSet||(n._responseCallbackSet=new Set),n._responseCallbackSet.add(e)},VT=(n,e)=>{n._requestCallbackSet&&(n._requestCallbackSet.delete(e),n._requestCallbackSet.size||delete n._requestCallbackSet)},jT=(n,e)=>{n._responseCallbackSet&&(n._responseCallbackSet.delete(e),n._responseCallbackSet.size||delete n._responseCallbackSet)};lt.supportsNativeHls=(function(){if(!de||!de.createElement)return!1;const n=de.createElement("video");return K.getTech("Html5").isSupported()?["application/vnd.apple.mpegurl","audio/mpegurl","audio/x-mpegurl","application/x-mpegurl","video/x-mpegurl","video/mpegurl","application/mpegurl"].some(function(t){return/maybe|probably/i.test(n.canPlayType(t))}):!1})(),lt.supportsNativeDash=(function(){return!de||!de.createElement||!K.getTech("Html5").isSupported()?!1:/maybe|probably/i.test(de.createElement("video").canPlayType("application/dash+xml"))})(),lt.supportsTypeNatively=n=>n==="hls"?lt.supportsNativeHls:n==="dash"?lt.supportsNativeDash:!1,lt.isSupported=function(){return K.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")},lt.xhr.onRequest=function(n){BT(lt.xhr,n)},lt.xhr.onResponse=function(n){qT(lt.xhr,n)},lt.xhr.offRequest=function(n){VT(lt.xhr,n)},lt.xhr.offResponse=function(n){jT(lt.xhr,n)};const yI=K.getComponent("Component");class HT extends yI{constructor(e,t,i){if(super(t,i.vhs),typeof i.initialBandwidth=="number"&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=Oi("VhsHandler"),t.options_&&t.options_.playerId){const s=K.getPlayer(t.options_.playerId);this.player_=s}if(this.tech_=t,this.source_=e,this.stats={},this.ignoreNextSeekingEvent_=!1,this.setOptions_(),this.options_.overrideNative&&t.overrideNativeAudioTracks&&t.overrideNativeVideoTracks)t.overrideNativeAudioTracks(!0),t.overrideNativeVideoTracks(!0);else if(this.options_.overrideNative&&(t.featuresNativeVideoTracks||t.featuresNativeAudioTracks))throw new Error("Overriding native VHS requires emulated tracks. See https://git.io/vMpjB");this.on(de,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],s=>{const r=de.fullscreenElement||de.webkitFullscreenElement||de.mozFullScreenElement||de.msFullscreenElement;r&&r.contains(this.tech_.el())?this.playlistController_.fastQualityChange_():this.playlistController_.checkABR_()}),this.on(this.tech_,"seeking",function(){if(this.ignoreNextSeekingEvent_){this.ignoreNextSeekingEvent_=!1;return}this.setCurrentTime(this.tech_.currentTime())}),this.on(this.tech_,"error",function(){this.tech_.error()&&this.playlistController_&&this.playlistController_.pauseLoading()}),this.on(this.tech_,"play",this.play)}setOptions_(e={}){if(this.options_=We(this.options_,e),this.options_.withCredentials=this.options_.withCredentials||!1,this.options_.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions!==!1,this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1,this.options_.usePlayerObjectFit=this.options_.usePlayerObjectFit||!1,this.options_.useBandwidthFromLocalStorage=typeof this.source_.useBandwidthFromLocalStorage<"u"?this.source_.useBandwidthFromLocalStorage:this.options_.useBandwidthFromLocalStorage||!1,this.options_.useForcedSubtitles=this.options_.useForcedSubtitles||!1,this.options_.useNetworkInformationApi=typeof this.options_.useNetworkInformationApi<"u"?this.options_.useNetworkInformationApi:!0,this.options_.useDtsForTimestampOffset=this.options_.useDtsForTimestampOffset||!1,this.options_.customTagParsers=this.options_.customTagParsers||[],this.options_.customTagMappers=this.options_.customTagMappers||[],this.options_.cacheEncryptionKeys=this.options_.cacheEncryptionKeys||!1,this.options_.llhls=this.options_.llhls!==!1,this.options_.bufferBasedABR=this.options_.bufferBasedABR||!1,typeof this.options_.playlistExclusionDuration!="number"&&(this.options_.playlistExclusionDuration=60),typeof this.options_.bandwidth!="number"&&this.options_.useBandwidthFromLocalStorage){const i=UT();i&&i.bandwidth&&(this.options_.bandwidth=i.bandwidth,this.tech_.trigger({type:"usage",name:"vhs-bandwidth-from-local-storage"})),i&&i.throughput&&(this.options_.throughput=i.throughput,this.tech_.trigger({type:"usage",name:"vhs-throughput-from-local-storage"}))}typeof this.options_.bandwidth!="number"&&(this.options_.bandwidth=Mt.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===Mt.INITIAL_BANDWIDTH,["withCredentials","useDevicePixelRatio","usePlayerObjectFit","customPixelRatio","limitRenditionByPlayerDimensions","bandwidth","customTagParsers","customTagMappers","cacheEncryptionKeys","playlistSelector","initialPlaylistSelector","bufferBasedABR","liveRangeSafeTimeDelta","llhls","useForcedSubtitles","useNetworkInformationApi","useDtsForTimestampOffset","exactManifestTimings","leastPixelDiffSelector"].forEach(i=>{typeof this.source_[i]<"u"&&(this.options_[i]=this.source_[i])}),this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions,this.useDevicePixelRatio=this.options_.useDevicePixelRatio,this.usePlayerObjectFit=this.options_.usePlayerObjectFit;const t=this.options_.customPixelRatio;typeof t=="number"&&t>=0&&(this.customPixelRatio=t)}setOptions(e={}){this.setOptions_(e)}src(e,t){if(!e)return;this.setOptions_(),this.options_.src=gI(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=lt,this.options_.sourceType=J0(t),this.options_.seekTo=r=>{this.tech_.setCurrentTime(r)},this.options_.player_=this.player_,this.playlistController_=new ZP(this.options_);const i=We({liveRangeSafeTimeDelta:gn},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new nI(i),this.attachStreamingEventListeners_(),this.playlistController_.on("error",()=>{const r=K.players[this.tech_.options_.playerId];let a=this.playlistController_.error;typeof a=="object"&&!a.code?a.code=3:typeof a=="string"&&(a={message:a,code:3}),r.error(a)});const s=this.options_.bufferBasedABR?lt.movingAverageBandwidthSelector(.55):lt.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):s.bind(this),this.playlistController_.selectInitialPlaylist=lt.INITIAL_PLAYLIST_SELECTOR.bind(this),this.playlists=this.playlistController_.mainPlaylistLoader_,this.mediaSource=this.playlistController_.mediaSource,Object.defineProperties(this,{selectPlaylist:{get(){return this.playlistController_.selectPlaylist},set(r){this.playlistController_.selectPlaylist=r.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(r){this.playlistController_.mainSegmentLoader_.throughput.rate=r,this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let r=this.playlistController_.mainSegmentLoader_.bandwidth;const a=B.navigator.connection||B.navigator.mozConnection||B.navigator.webkitConnection,o=1e7;if(this.options_.useNetworkInformationApi&&a){const c=a.downlink*1e3*1e3;c>=o&&r>=o?r=Math.max(r,c):r=c}return r},set(r){this.playlistController_.mainSegmentLoader_.bandwidth=r,this.playlistController_.mainSegmentLoader_.throughput={rate:0,count:0}}},systemBandwidth:{get(){const r=1/(this.bandwidth||1);let a;return this.throughput>0?a=1/this.throughput:a=0,Math.floor(1/(r+a))},set(){K.log.error('The "systemBandwidth" property is read-only')}}}),this.options_.bandwidth&&(this.bandwidth=this.options_.bandwidth),this.options_.throughput&&(this.throughput=this.options_.throughput),Object.defineProperties(this.stats,{bandwidth:{get:()=>this.bandwidth||0,enumerable:!0},mediaRequests:{get:()=>this.playlistController_.mediaRequests_()||0,enumerable:!0},mediaRequestsAborted:{get:()=>this.playlistController_.mediaRequestsAborted_()||0,enumerable:!0},mediaRequestsTimedout:{get:()=>this.playlistController_.mediaRequestsTimedout_()||0,enumerable:!0},mediaRequestsErrored:{get:()=>this.playlistController_.mediaRequestsErrored_()||0,enumerable:!0},mediaTransferDuration:{get:()=>this.playlistController_.mediaTransferDuration_()||0,enumerable:!0},mediaBytesTransferred:{get:()=>this.playlistController_.mediaBytesTransferred_()||0,enumerable:!0},mediaSecondsLoaded:{get:()=>this.playlistController_.mediaSecondsLoaded_()||0,enumerable:!0},mediaAppends:{get:()=>this.playlistController_.mediaAppends_()||0,enumerable:!0},mainAppendsToLoadedData:{get:()=>this.playlistController_.mainAppendsToLoadedData_()||0,enumerable:!0},audioAppendsToLoadedData:{get:()=>this.playlistController_.audioAppendsToLoadedData_()||0,enumerable:!0},appendsToLoadedData:{get:()=>this.playlistController_.appendsToLoadedData_()||0,enumerable:!0},timeToLoadedData:{get:()=>this.playlistController_.timeToLoadedData_()||0,enumerable:!0},buffered:{get:()=>js(this.tech_.buffered()),enumerable:!0},currentTime:{get:()=>this.tech_.currentTime(),enumerable:!0},currentSource:{get:()=>this.tech_.currentSource_,enumerable:!0},currentTech:{get:()=>this.tech_.name_,enumerable:!0},duration:{get:()=>this.tech_.duration(),enumerable:!0},main:{get:()=>this.playlists.main,enumerable:!0},playerDimensions:{get:()=>this.tech_.currentDimensions(),enumerable:!0},seekable:{get:()=>js(this.tech_.seekable()),enumerable:!0},timestamp:{get:()=>Date.now(),enumerable:!0},videoPlaybackQuality:{get:()=>this.tech_.getVideoPlaybackQuality(),enumerable:!0}}),this.tech_.one("canplay",this.playlistController_.setupFirstPlay.bind(this.playlistController_)),this.tech_.on("bandwidthupdate",()=>{this.options_.useBandwidthFromLocalStorage&&mI({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{iI(this)}),this.playlistController_.sourceUpdater_.on("createdsourcebuffers",()=>{this.setupEme_()}),this.on(this.playlistController_,"progress",function(){this.tech_.trigger("progress")}),this.on(this.playlistController_,"firstplay",function(){this.ignoreNextSeekingEvent_=!0}),this.setupQualityLevels_(),this.tech_.el()&&(this.mediaSourceUrl_=B.URL.createObjectURL(this.playlistController_.mediaSource),(K.browser.IS_ANY_SAFARI||K.browser.IS_IOS)&&this.options_.overrideNative&&this.options_.sourceType==="hls"&&typeof this.tech_.addSourceElement=="function"?(this.tech_.addSourceElement(this.mediaSourceUrl_),this.tech_.addSourceElement(this.source_.src)):this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation"),fI({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:e&&e.media(),mainPlaylists:this.playlists.main.playlists}).then(()=>{this.logger_("created EME key session"),this.playlistController_.sourceUpdater_.initializedEme()}).catch(t=>{this.logger_("error while creating EME key session",t),this.player_.error({message:"Failed to initialize media keys for EME",code:3})})}handleWaitingForKey_(){this.logger_("waitingforkey fired, attempting to create any new key sessions"),this.createKeySessions_()}setupEme_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader,t=pI({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:e&&e.media()});if(this.player_.tech_.on("keystatuschange",i=>{this.playlistController_.updatePlaylistByKeyStatus(i.keyId,i.status)}),this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this),this.player_.tech_.on("waitingforkey",this.handleWaitingForKey_),!t){this.playlistController_.sourceUpdater_.initializedEme();return}this.createKeySessions_()}setupQualityLevels_(){const e=K.players[this.tech_.options_.playerId];!e||!e.qualityLevels||this.qualityLevels_||(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on("selectedinitialmedia",()=>{uI(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{FT(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":LT,"mux.js":aI,"mpd-parser":oI,"m3u8-parser":cI,"aes-decrypter":lI}}version(){return this.constructor.version()}canChangeType(){return CT.canChangeType()}play(){this.playlistController_.play()}setCurrentTime(e){this.playlistController_.setCurrentTime(e)}duration(){return this.playlistController_.duration()}seekable(){return this.playlistController_.seekable()}dispose(){this.playbackWatcher_&&this.playbackWatcher_.dispose(),this.playlistController_&&this.playlistController_.dispose(),this.qualityLevels_&&this.qualityLevels_.dispose(),this.tech_&&this.tech_.vhs&&delete this.tech_.vhs,this.mediaSourceUrl_&&B.URL.revokeObjectURL&&(B.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return SD({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,s=2){return Xb({programTime:e,playlist:this.playlistController_.media(),retryCount:s,pauseAfterSeek:i,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})}setupXhrHooks_(){this.xhr.onRequest=e=>{BT(this.xhr,e)},this.xhr.onResponse=e=>{qT(this.xhr,e)},this.xhr.offRequest=e=>{VT(this.xhr,e)},this.xhr.offResponse=e=>{jT(this.xhr,e)},this.player_.trigger("xhr-hooks-ready")}attachStreamingEventListeners_(){const e=["seekablerangeschanged","bufferedrangeschanged","contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"],t=["gapjumped","playedrangeschanged"];e.forEach(i=>{this.playlistController_.on(i,s=>{this.player_.trigger(vt({},s))})}),t.forEach(i=>{this.playbackWatcher_.on(i,s=>{this.player_.trigger(vt({},s))})})}}const El={name:"videojs-http-streaming",VERSION:LT,canHandleSource(n,e={}){const t=We(K.options,e);return!t.vhs.experimentalUseMMS&&!Oa("avc1.4d400d,mp4a.40.2",!1)?!1:El.canPlayType(n.type,t)},handleSource(n,e,t={}){const i=We(K.options,t);return e.vhs=new HT(n,e,i),e.vhs.xhr=$b(),e.vhs.setupXhrHooks_(),e.vhs.src(n.src,n.type),e.vhs},canPlayType(n,e){const t=J0(n);if(!t)return"";const i=El.getOverrideNative(e);return!lt.supportsTypeNatively(t)||i?"maybe":""},getOverrideNative(n={}){const{vhs:e={}}=n,t=!(K.browser.IS_ANY_SAFARI||K.browser.IS_IOS),{overrideNative:i=t}=e;return i}};Oa("avc1.4d400d,mp4a.40.2",!0)&&K.getTech("Html5").registerSourceHandler(El,0),K.VhsHandler=HT,K.VhsSourceHandler=El,K.Vhs=lt,K.use||K.registerComponent("Vhs",lt),K.options.vhs=K.options.vhs||{},(!K.getPlugin||!K.getPlugin("reloadSourceOnError"))&&K.registerPlugin("reloadSourceOnError",rI);const vI=Object.freeze(Object.defineProperty({__proto__:null,default:K},Symbol.toStringTag,{value:"Module"}));return Io.DEFAULT_AVATAR_SIZE=p1,Io.mountWidget=b1,Object.defineProperty(Io,Symbol.toStringTag,{value:"Module"}),Io})({});
|