@brandbrigade/ott-bb-player 1.0.55 → 1.0.56

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.
Files changed (2) hide show
  1. package/dist/OTTPlayer.js +7 -138
  2. package/package.json +1 -1
package/dist/OTTPlayer.js CHANGED
@@ -1,138 +1,7 @@
1
- (function(b,w){typeof exports=="object"&&typeof module<"u"?module.exports=w():typeof define=="function"&&define.amd?define(w):(b=typeof globalThis<"u"?globalThis:b||self,b.OTTPlayer=w())})(this,function(){"use strict";const b=s=>Math.abs(s-59.94005994005994)<20?59.94:Math.abs(s-29.97002997002997)<10?29.97:Math.abs(s-14.985014985014985)<8?14.98:0,w=s=>s>30&&s<70?59.94005994005994:s>15?29.97002997002997:s>7?14.985014985014985:0;class P{constructor(t){this.frameDurations=[],this.frameDurationsCapacity=t,this.lastTimestamp=null}addFrameDuration(t){return this.frameDurations.push(t),this.frameDurations.length>this.frameDurationsCapacity&&this.frameDurations.shift(),this.calculateAverage()}addTimestamp(t){if(this.lastTimestamp===null)return this.lastTimestamp=t,null;const e=t-this.lastTimestamp;return this.lastTimestamp=t,this.addFrameDuration(e)}calculateAverage(){if(this.frameDurations.length===0)return 0;const e=this.frameDurations.reduce((a,o)=>a+o,0)/this.frameDurations.length,i=this.frameDurations.filter(a=>Math.abs(a-e)<=e*.2);return i.reduce((a,o)=>a+o,0)/i.length||e}getFPS(){const t=this.calculateAverage();if(t===0)return 0;const e=1/t;return w(e)}getPerciseFPS(){const t=this.calculateAverage();return t===0?0:1/t}}const S=(()=>{const s=()=>{const c=navigator.userAgent;return/windows/i.test(c)?"Windows":/android/i.test(c)?"Android":/iphone|ipad|ipod/i.test(c)?"iOS":/mac/i.test(c)?"Mac":/ipad/i.test(c)?"iPad":"Something else"},t=()=>s()==="Mac",e=()=>s()==="iPad",i=()=>s()==="iOS",r=()=>{const c=s();return c==="iOS"||c==="Mac"||c==="iPad"},n=()=>s()==="Windows",a=()=>s()==="Android",o=()=>{switch(s()){case"Windows":return"a Windows PC";case"Android":return"an Android phone";case"iOS":return"an iPhone";case"Mac":return"a Mac";case"iPad":return"an iPad";default:return"an Unknown device"}},h=()=>({header:[navigator.platform,navigator.userAgent,navigator.appVersion,navigator.vendor,window.opera],dataos:[{name:"Windows Phone",value:"Windows Phone",version:"OS"},{name:"Windows",value:"Win",version:"NT"},{name:"iPhone",value:"iPhone",version:"OS"},{name:"iPad",value:"iPad",version:"OS"},{name:"Kindle",value:"Silk",version:"Silk"},{name:"Android",value:"Android",version:"Android"},{name:"PlayBook",value:"PlayBook",version:"OS"},{name:"BlackBerry",value:"BlackBerry",version:"/"},{name:"Macintosh",value:"Mac",version:"OS X"},{name:"Linux",value:"Linux",version:"rv"},{name:"Palm",value:"Palm",version:"PalmOS"}],databrowser:[{name:"Chrome",value:"Chrome",version:"Chrome"},{name:"Firefox",value:"Firefox",version:"Firefox"},{name:"Safari",value:"Safari",version:"Version"},{name:"Internet Explorer",value:"MSIE",version:"MSIE"},{name:"Opera",value:"Opera",version:"Opera"},{name:"BlackBerry",value:"CLDC",version:"CLDC"},{name:"Mozilla",value:"Mozilla",version:"Mozilla"}],init(){const D=this.header.join(" ");return this.matchItem(D,this.dataos)},matchItem(D,T){for(let F=0;F<T.length;F+=1)if(new RegExp(T[F].value,"i").test(D))return T[F].name;return"unknown"}}).init(),l=()=>{const c=navigator.userAgent;return c.indexOf("Chrome")>-1&&c.indexOf("Edge")===-1?"Chrome":c.indexOf("Safari")>-1&&c.indexOf("Chrome")===-1?"Safari":c.indexOf("Firefox")>-1?"Firefox":c.indexOf("MSIE")>-1||c.indexOf("Trident")>-1?"Internet Explorer":c.indexOf("Edge")>-1?"Edge":"Unknown"};return{getCurrentPlatform:s,isMac:t,isiPad:e,isiPhone:i,isApple:r,isWindows:n,isAndroid:a,getDeviceDescription:o,getDeviceName:h,getBrowserName:l,isSafariMac:()=>t()&&l()==="Safari",isChromeMac:()=>t()&&l()==="Chrome",isChromeWin:()=>n()&&l()==="Chrome",isFirefoxMac:()=>t()&&l()==="Firefox",isFirefoxWin:()=>n()&&l()==="Firefox"}})(),u=class u{constructor(t,e,i,r,n){this.copy=()=>new u(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const a=":";let o=("0"+this.h).slice(-2)+a+("0"+this.m).slice(-2)+a+("0"+this.s).slice(-2)+a+("0"+this.f).slice(-2);return o+="."+(this.field?"1":"2"),o},this.toZipTimeCodeString=()=>{const a=this.copy();return a.f=0,a.s=a.s%2===0?a.s:a.s-1,a.field=0,u.toStr(a)},this.toFrames=a=>{let o=60,h=0;Math.floor(a)==60?(o=60,h=0):Math.floor(a)==59?(o=60,h=4):Math.floor(a)==30?(o=30,h=0):Math.floor(a)==29&&(o=30,h=2);let l=this.h,d=this.m,p=this.s,_=this.f,m=this.field;const f=l*60+d,c=(f-Math.floor(f/10))*h;return l*(o*3600)+d*(o*60)+p*o+(_*2+m)-c},this.addSeconds=a=>{let o=this.copy();return o.s+=a,o.s>=60&&(o.s=0,o.m++,o.m>=60&&(o.m=0,o.h++)),o},this.addFrames=(a,o)=>{let h=this.toFrames(o);return h+=a,u.fromFrames(h,o)},this.subtractFrames=(a,o)=>this.addFrames(-a,o),this.h=t||0,this.m=e||0,this.s=i||0,this.f=r||0,this.field=n||0}static compare(t,e){return t.h!==e.h?t.h<e.h?-1:1:t.m!==e.m?t.m<e.m?-1:1:t.s!==e.s?t.s<e.s?-1:1:t.f!==e.f?t.f<e.f?-1:1:t.field!==e.field?t.field<e.field?-1:1:0}static generateTimecodeRange(t,e,i){const r=[];let n=t;for(;u.compare(n,e)<=0;)r.push(n),n=n.addSeconds(i);return r}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(t){return this.toFrames(t)*1e3/t}};u.calculateCurrentTimeCode=t=>{var p;if(!t.video||!t.clocker||!t.gameParams)throw new Error("OTTPlayer is not initialized");const e=t.video,i=t.clocker,r=i.videoFPScalculator.getFPS(),o=(e.currentTime-i.syncPoint.playerTime)%(60*60*24)*r+i.syncPoint.frame;if(o===0||r===0)throw new Error("Current frame is 0 or fps is 0");const h=u.calculateCurrentOffset(o,(p=t.gameParams)==null?void 0:p.offsets);if(h===void 0)throw new Error("Offset is undefined");let l=Math.floor(o-h);return l<0&&(l+=5178816),l>=5178816&&(l-=5178816),u.fromFrames(l,r)},u.calculateCurrentOffset=(t,e)=>{for(let i=1;i<e.length;i++)if(t<e[i].frame)return e[i-1].offset;return e[e.length-1].offset},u.fromFrames=(t,e)=>{let i=60,r=0;Math.floor(e)==60?(i=60,r=0):Math.floor(e)==59?(i=60,r=4):Math.floor(e)==30?(i=30,r=0):Math.floor(e)==29&&(i=30,r=2);let n=Math.floor(e*60),a=Math.floor(e*60*10),o=a*6,h=t,l=Math.floor(h/o);h-=l*o;let d=Math.floor(h/a);h-=d*a,h>=i*60&&(h+=r*(Math.floor((h-i*60)/n)+1));let p=Math.floor(h/(i*60));h-=p*(i*60);let _=Math.floor(h/i);h-=_*i;let m=h;p+=d*10;let f=0;return f=m%2,m=Math.floor(m/2),new u(l,p,_,m,f)},u.toStr=t=>{const e="_";let i=("0"+t.h).slice(-2)+e+("0"+t.m).slice(-2)+e+("0"+t.s).slice(-2)+e+("0"+t.f).slice(-2);return t.field&&(i+="_1"),i},u.fromStr=t=>{const i=t.split("_").map(Number);if(i.length==4){const[r,n,a,o]=i;return new u(r,n,a,o,0)}else if(i.length==5){const[r,n,a,o,h]=i;return new u(r,n,a,o,h)}else throw new Error("Invalid timecode format: "+t)},u.fromMetadata=t=>{const e=/^(\d{2}):(\d{2}):(\d{2}):(\d{2})(?:\.(\d))?$/,i=t.timecode.match(e);if(!i)throw new Error("Invalid timecode format: "+t.timecode);const[,r,n,a,o,h]=i,l=Number(r),d=Number(n),p=Number(a),_=Number(o),m=h?Number(h):0;return new u(l,d,p,_,m)};let g=u,R=0,C=0;const B=s=>{if(s.metadata.messageData){s.metadata.messageData=M(s.metadata.messageData,s.metadata.presentationTime);return}if(s.metadata.frames&&s.metadata.frames.length&&s.metadata.frames[0].key&&s.metadata.frames[0].key.toLowerCase()==="priv"){const t=s.metadata.frames.filter(e=>e.info&&e.info.toLowerCase().includes("ntc"));if(t.length){const e=t[t.length-1],i=`${e.info}\0${String.fromCharCode(...e.data)}`;s.metadata.messageData=M(i,s.metadata.presentationTime)}}},k=()=>{const s=new Date(R-C);let t=Math.round(s.getUTCMilliseconds()*30*2/1001)/2;const e=t%1;let i=1;return e===.5&&(t=Math.floor(t),i=2),new g(s.getUTCHours(),s.getUTCMinutes(),s.getUTCSeconds(),Math.floor(t),i===1?0:1)},W=s=>{if((s&&s.metadata&&s.metadata.id==0||S.isSafariMac())&&(B(s),s.metadata.id==0||S.isSafariMac()&&C==0))return k()},j=s=>(B(s),k()),M=(s,t)=>{let e="";if(s&&s.includes("www.mediakind.com/NTC")){const i=s.replace(/.*NTC./,"");let r=0;for(;r+8<=i.length;){const n=i.substring(r,r+4),a=((i.charCodeAt(r+4)*256+i.charCodeAt(r+5))*256+i.charCodeAt(r+6))*256+i.charCodeAt(r+7);if(r+8+a>i.length)break;const o=i.substring(r+8,r+8+a);n==="utc_"&&new Date(parseInt(o)).getTime()/1e3,n==="tc__"&&(R=new Date(parseInt(o)).getTime()),n==="offs"&&(C=parseInt(o)/90),r+=8+a}}return e},$=(s,t,e)=>{const i=e.toFrames(t),r=e.print();console.log("New segment ("+s.url+"): "+r+" ("+i+") playing at "+s.playbackTime);const n=s.playbackTime;return{frame:i,playerTime:n,stringTime:r}},K=(s,t,e)=>{const i=e.toFrames(t),r=e.print(),n=s.metadata.presentationTime;return{frame:i,playerTime:n,stringTime:r}},X=async s=>{let t;typeof document>"u"?t=new URL(self.location.href):t=new URL(document.location.href);const e=t.searchParams.get("config");if(e){const r=await(await fetch(e)).json();Object.assign(s,r)}},y=(s,t)=>!s.debug||!s.debug.on?!1:s.debug[`log${t}`];class q{constructor(t){this.last10=[],this.errorsInProgress=[],this.lastFrameTC=null,this.fps=t}setFPS(t){this.fps=t}timecodeRecieved(t){if(!t)return;const e=g.fromStr(t);if(this.last10.push(e),this.last10.length>10&&this.last10.shift(),this.lastFrameTC){const i=this.incrementInterlaced(this.lastFrameTC);g.compare(e,i)!==0&&(console.warn("Timecode sequence is invalid! Detected at:",t),this.errorsInProgress.push({preTCs:[...this.last10],postTCs:[],framesAfter:0,printed:!1}))}for(const i of this.errorsInProgress)i.printed||(i.postTCs.push(e),i.framesAfter++);for(const i of this.errorsInProgress)if(!i.printed&&i.framesAfter>=10){console.error("Full 20-frame sequence around error:");const r=[...i.preTCs,...i.postTCs];console.error(r.map(n=>g.toStr(n))),i.printed=!0}this.lastFrameTC=e}incrementInterlaced(t){const e=t.copy();return e.field===0?(e.field=1,e):(e.field=0,e.f++,e.f>=30&&(e.f=0,e.s++,e.s>=60&&(e.s=0,e.m++,e.m>=60&&(e.m=0,e.h++))),e)}}class J{constructor(t,e){this.click=async i=>{const r=this.video.getBoundingClientRect(),n=(i.clientX-r.left)/r.width,a=(i.clientY-r.top)/r.height,o={x:n,y:a};this.renderer.postMessage({type:"VIDEO_CLICK",clickData:o})},this.video=t,this.renderer=e,this.renderer.onmessage=i=>{if(i.data.type==="OPEN_URL"){const r=i.data.url;r&&window.open(r,"_blank")}}}}const I='(function(){"use strict";const d=(l,t)=>!l.debug||!l.debug.on?!1:l.debug[`log${t}`];class O{constructor(t){this.fetchGameParams=async(s,r)=>{const n=`${s}/${r}.json`;this.options&&d(this.options,"Fetcher")&&console.log(`[Fetcher] Fetching GameParams from ${n}`);const a=await fetch(n);if(!a.ok)throw new Error(`HTTP error! Status: ${a.status}`);const o=await a.json();return o.hasOwnProperty("bucketName")&&o.hasOwnProperty("offsets")?o:(this.options&&d(this.options,"Errors")&&console.error(`[Fetcher] Game params for ${r} not found in JSON.`),a)},this.fetchMetadata=async(s,r,n,a)=>{const e=`${`${s}/${r}`}/manifests/59.94/${a}.zip`;this.options&&d(this.options,"Fetcher")&&console.log(`[Fetcher] Fetching metadata from ${e}`);const i=await fetch(e),c=i.headers.get("x-tgi-ott-actions");let f;if(c?f=JSON.parse(c):f={toggle:{ios:!0,android:!0,web:!0}},!i.ok)throw new Error(`HTTP error! Status: ${i.status}`);return{arrayBuffer:await i.arrayBuffer(),ottActions:f}},this.options=t}}const h=class h{constructor(t,s,r,n,a){this.copy=()=>new h(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const o=":";let e=("0"+this.h).slice(-2)+o+("0"+this.m).slice(-2)+o+("0"+this.s).slice(-2)+o+("0"+this.f).slice(-2);return e+="."+(this.field?"1":"2"),e},this.toZipTimeCodeString=()=>{const o=this.copy();return o.f=0,o.s=o.s%2===0?o.s:o.s-1,o.field=0,h.toStr(o)},this.toFrames=o=>{let e=60,i=0;Math.floor(o)==60?(e=60,i=0):Math.floor(o)==59?(e=60,i=4):Math.floor(o)==30?(e=30,i=0):Math.floor(o)==29&&(e=30,i=2);let c=this.h,f=this.m,m=this.s,p=this.f,w=this.field;const b=c*60+f,R=(b-Math.floor(b/10))*i;return c*(e*3600)+f*(e*60)+m*e+(p*2+w)-R},this.addSeconds=o=>{let e=this.copy();return e.s+=o,e.s>=60&&(e.s=0,e.m++,e.m>=60&&(e.m=0,e.h++)),e},this.addFrames=(o,e)=>{let i=this.toFrames(e);return i+=o,h.fromFrames(i,e)},this.subtractFrames=(o,e)=>this.addFrames(-o,e),this.h=t||0,this.m=s||0,this.s=r||0,this.f=n||0,this.field=a||0}static compare(t,s){return t.h!==s.h?t.h<s.h?-1:1:t.m!==s.m?t.m<s.m?-1:1:t.s!==s.s?t.s<s.s?-1:1:t.f!==s.f?t.f<s.f?-1:1:t.field!==s.field?t.field<s.field?-1:1:0}static generateTimecodeRange(t,s,r){const n=[];let a=t;for(;h.compare(a,s)<=0;)n.push(a),a=a.addSeconds(r);return n}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(t){return this.toFrames(t)*1e3/t}};h.calculateCurrentTimeCode=t=>{var m;if(!t.video||!t.clocker||!t.gameParams)throw new Error("OTTPlayer is not initialized");const s=t.video,r=t.clocker,n=r.videoFPScalculator.getFPS(),e=(s.currentTime-r.syncPoint.playerTime)%(60*60*24)*n+r.syncPoint.frame;if(e===0||n===0)throw new Error("Current frame is 0 or fps is 0");const i=h.calculateCurrentOffset(e,(m=t.gameParams)==null?void 0:m.offsets);if(i===void 0)throw new Error("Offset is undefined");let c=Math.floor(e-i);return c<0&&(c+=5178816),c>=5178816&&(c-=5178816),h.fromFrames(c,n)},h.calculateCurrentOffset=(t,s)=>{for(let r=1;r<s.length;r++)if(t<s[r].frame)return s[r-1].offset;return s[s.length-1].offset},h.fromFrames=(t,s)=>{let r=60,n=0;Math.floor(s)==60?(r=60,n=0):Math.floor(s)==59?(r=60,n=4):Math.floor(s)==30?(r=30,n=0):Math.floor(s)==29&&(r=30,n=2);let a=Math.floor(s*60),o=Math.floor(s*60*10),e=o*6,i=t,c=Math.floor(i/e);i-=c*e;let f=Math.floor(i/o);i-=f*o,i>=r*60&&(i+=n*(Math.floor((i-r*60)/a)+1));let m=Math.floor(i/(r*60));i-=m*(r*60);let p=Math.floor(i/r);i-=p*r;let w=i;m+=f*10;let b=0;return b=w%2,w=Math.floor(w/2),new h(c,m,p,w,b)},h.toStr=t=>{const s="_";let r=("0"+t.h).slice(-2)+s+("0"+t.m).slice(-2)+s+("0"+t.s).slice(-2)+s+("0"+t.f).slice(-2);return t.field&&(r+="_1"),r},h.fromStr=t=>{const r=t.split("_").map(Number);if(r.length==4){const[n,a,o,e]=r;return new h(n,a,o,e,0)}else if(r.length==5){const[n,a,o,e,i]=r;return new h(n,a,o,e,i)}else throw new Error("Invalid timecode format: "+t)},h.fromMetadata=t=>{const s=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,r=t.timecode.match(s);if(!r)throw new Error("Invalid timecode format: "+t.timecode);const[,n,a,o,e,i]=r,c=Number(n),f=Number(a),m=Number(o),p=Number(e),w=i?Number(i):0;return new h(c,f,m,p,w)};let D=h;class E{constructor(t,s,r){this.jobsQueue=[],this.processedTimecodes=[],this.downloaderStopped=!1,this.updateStreamData=n=>{this.streamData=n,this.initiateJobs(this.options.DOWNLOADER_ZIP_START_OFFSET,this.options.DOWNLOADER_ZIP_END_OFFSET,this.options.DOWNLOADER_ZIP_LENGTH_SECONDS),this.clearOldJobs(1)},this.initiateJobs=(n,a,o)=>{if(!this.streamData){this.options&&d(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}const e=D.fromStr(this.streamData.timeCode),i=e.addSeconds(n),c=e.addSeconds(a),f=D.generateTimecodeRange(i,c,o);for(const m of f){const p=m.toZipTimeCodeString();this.processedTimecodes.includes(p)||(this.processedTimecodes.push(p),this.addJob(p))}},this.clearOldJobs=n=>{if(!this.streamData){this.options&&d(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}const o=D.fromStr(this.streamData.timeCode).totalSeconds()-n;this.processedTimecodes=this.processedTimecodes.filter(e=>D.fromStr(e).totalSeconds()>o)},this.clearAllJobs=()=>{this.jobsQueue=[],this.currentJob=void 0,this.processedTimecodes=[]},this.addJob=n=>{if(this.jobsQueue.some(a=>a===n)){this.options&&d(this.options,"Downloader")&&console.log(`[Downloader] Job already exists for timeCode=${n}`);return}this.jobsQueue.push(n),this.startNextJob()},this.startNextJob=()=>{!this.currentJob&&this.jobsQueue.length>0&&(this.currentJob=this.jobsQueue.shift(),this.options&&d(this.options,"Downloader")&&console.log(`[Downloader] Starting job timeCode=${this.currentJob}`),this.downloadZip(this.currentJob))},this.jobDone=()=>{this.currentJob=void 0,this.startNextJob()},this.downloadZip=async n=>{if(!this.streamData){this.options&&d(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}const{fps:a,cloudFrontURL:o,bucketName:e}=this.streamData;try{this.options&&d(this.options,"Downloader")&&console.log(`[Downloader] Fetching zip for timeCode=${n}`);const{arrayBuffer:i,ottActions:c}=await this.fetcher.fetchMetadata(o,e,a,n);if(this.downloaderStopped)return;this.postOTTActionsToRenderer(c),this.postArrayBufferToDecoder(n,i)}catch(i){this.options&&d(this.options,"Errors")&&console.error("[Downloader] Error:",i)}this.jobDone()},this.stop=()=>{this.downloaderStopped=!0,this.clearAllJobs()},this.postArrayBufferToDecoder=t,this.postOTTActionsToRenderer=s,this.options=r,this.fetcher=new O(r)}}let S=null,g=null,F,u;self.onmessage=async l=>{const{data:t}=l;if(t.type==="SET_RENDERER_PORT"&&(S=t.port,S.onmessage=M),t.type==="SET_DECODER_PORT"&&(g=t.port,g.onmessage=N),t.type==="SET_OPTIONS"&&(u=t.options,F=new E(T,y,u)),t.type==="VIDEO_SEEKED"){if(!u)return;F.stop(),F=new E(T,y,u)}};async function M(l){const{data:t}=l;t.type==="DOWNLOADER_INPUT"&&F.updateStreamData(t.streamData)}function T(l,t){if(!g)return;u&&d(u,"Downloader")&&console.log(`[DownloaderWorker] Posting an ArrayBuffer to Decoder, timeCode=${l}`);const s={type:"DECODER_INPUT",timeCode:l,arrayBuffer:t};g==null||g.postMessage(s,{transfer:[t]})}function y(l){if(!S)return;u&&d(u,"Downloader")&&console.log(`[DownloaderWorker] Posting OTTActions to Renderer, toggle=${l.toggle}`);const t={type:"OTT_ACTIONS",ottActions:l};S==null||S.postMessage(t)}function N(l){u&&d(u,"Downloader")&&console.log("[DownloaderWorker] Received message from Decoder:",l.data)}})();\n',L=typeof self<"u"&&self.Blob&&new Blob([I],{type:"text/javascript;charset=utf-8"});function Q(s){let t;try{if(t=L&&(self.URL||self.webkitURL).createObjectURL(L),!t)throw"";const e=new Worker(t,{name:s==null?void 0:s.name});return e.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(I),{name:s==null?void 0:s.name})}finally{t&&(self.URL||self.webkitURL).revokeObjectURL(t)}}const z=`(function(){"use strict";const D=(C,f)=>!C.debug||!C.debug.on?!1:C.debug[\`log\${f}\`];function tt(C){return C&&C.__esModule&&Object.prototype.hasOwnProperty.call(C,"default")?C.default:C}var W={},et;function st(){return et||(et=1,function(C){var f=function(){var t=new Date,e=4,r=3,n=2,o=1,d=e,u={setLogLevel:function(_){_==this.debug?d=o:_==this.info?d=n:_==this.warn?d=r:(_==this.error,d=e)},debug:function(_,U){console.debug===void 0&&(console.debug=console.log),o>=d&&console.debug("["+f.getDurationString(new Date-t,1e3)+"]","["+_+"]",U)},log:function(_,U){this.debug(_.msg)},info:function(_,U){n>=d&&console.info("["+f.getDurationString(new Date-t,1e3)+"]","["+_+"]",U)},warn:function(_,U){r>=d&&console.warn("["+f.getDurationString(new Date-t,1e3)+"]","["+_+"]",U)},error:function(_,U){e>=d&&console.error("["+f.getDurationString(new Date-t,1e3)+"]","["+_+"]",U)}};return u}();f.getDurationString=function(t,e){var r;function n(S,b){for(var E=""+S,B=E.split(".");B[0].length<b;)B[0]="0"+B[0];return B.join(".")}t<0?(r=!0,t=-t):r=!1;var o=e||1,d=t/o,u=Math.floor(d/3600);d-=u*3600;var _=Math.floor(d/60);d-=_*60;var U=d*1e3;return d=Math.floor(d),U-=d*1e3,U=Math.floor(U),(r?"-":"")+u+":"+n(_,2)+":"+n(d,2)+"."+n(U,3)},f.printRanges=function(t){var e=t.length;if(e>0){for(var r="",n=0;n<e;n++)n>0&&(r+=","),r+="["+f.getDurationString(t.start(n))+","+f.getDurationString(t.end(n))+"]";return r}else return"(empty)"},C.Log=f;var h=function(t){if(t instanceof ArrayBuffer)this.buffer=t,this.dataview=new DataView(t);else throw"Needs an array buffer";this.position=0};h.prototype.getPosition=function(){return this.position},h.prototype.getEndPosition=function(){return this.buffer.byteLength},h.prototype.getLength=function(){return this.buffer.byteLength},h.prototype.seek=function(t){var e=Math.max(0,Math.min(this.buffer.byteLength,t));return this.position=isNaN(e)||!isFinite(e)?0:e,!0},h.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},h.prototype.readAnyInt=function(t,e){var r=0;if(this.position+t<=this.buffer.byteLength){switch(t){case 1:e?r=this.dataview.getInt8(this.position):r=this.dataview.getUint8(this.position);break;case 2:e?r=this.dataview.getInt16(this.position):r=this.dataview.getUint16(this.position);break;case 3:if(e)throw"No method for reading signed 24 bits values";r=this.dataview.getUint8(this.position)<<16,r|=this.dataview.getUint8(this.position+1)<<8,r|=this.dataview.getUint8(this.position+2);break;case 4:e?r=this.dataview.getInt32(this.position):r=this.dataview.getUint32(this.position);break;case 8:if(e)throw"No method for reading signed 64 bits values";r=this.dataview.getUint32(this.position)<<32,r|=this.dataview.getUint32(this.position+4);break;default:throw"readInt method not implemented for size: "+t}return this.position+=t,r}else throw"Not enough bytes in buffer"},h.prototype.readUint8=function(){return this.readAnyInt(1,!1)},h.prototype.readUint16=function(){return this.readAnyInt(2,!1)},h.prototype.readUint24=function(){return this.readAnyInt(3,!1)},h.prototype.readUint32=function(){return this.readAnyInt(4,!1)},h.prototype.readUint64=function(){return this.readAnyInt(8,!1)},h.prototype.readString=function(t){if(this.position+t<=this.buffer.byteLength){for(var e="",r=0;r<t;r++)e+=String.fromCharCode(this.readUint8());return e}else throw"Not enough bytes in buffer"},h.prototype.readCString=function(){for(var t=[];;){var e=this.readUint8();if(e!==0)t.push(e);else break}return String.fromCharCode.apply(null,t)},h.prototype.readInt8=function(){return this.readAnyInt(1,!0)},h.prototype.readInt16=function(){return this.readAnyInt(2,!0)},h.prototype.readInt32=function(){return this.readAnyInt(4,!0)},h.prototype.readInt64=function(){return this.readAnyInt(8,!1)},h.prototype.readUint8Array=function(t){for(var e=new Uint8Array(t),r=0;r<t;r++)e[r]=this.readUint8();return e},h.prototype.readInt16Array=function(t){for(var e=new Int16Array(t),r=0;r<t;r++)e[r]=this.readInt16();return e},h.prototype.readUint16Array=function(t){for(var e=new Int16Array(t),r=0;r<t;r++)e[r]=this.readUint16();return e},h.prototype.readUint32Array=function(t){for(var e=new Uint32Array(t),r=0;r<t;r++)e[r]=this.readUint32();return e},h.prototype.readInt32Array=function(t){for(var e=new Int32Array(t),r=0;r<t;r++)e[r]=this.readInt32();return e},C.MP4BoxStream=h;var a=function(t,e,r){this._byteOffset=e||0,t instanceof ArrayBuffer?this.buffer=t:typeof t=="object"?(this.dataView=t,e&&(this._byteOffset+=e)):this.buffer=new ArrayBuffer(t||0),this.position=0,this.endianness=r??a.LITTLE_ENDIAN};a.prototype={},a.prototype.getPosition=function(){return this.position},a.prototype._realloc=function(t){if(this._dynamicSize){var e=this._byteOffset+this.position+t,r=this._buffer.byteLength;if(e<=r){e>this._byteLength&&(this._byteLength=e);return}for(r<1&&(r=1);e>r;)r*=2;var n=new ArrayBuffer(r),o=new Uint8Array(this._buffer),d=new Uint8Array(n,0,o.length);d.set(o),this.buffer=n,this._byteLength=e}},a.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var t=new ArrayBuffer(this._byteLength),e=new Uint8Array(t),r=new Uint8Array(this._buffer,0,e.length);e.set(r),this.buffer=t}},a.BIG_ENDIAN=!1,a.LITTLE_ENDIAN=!0,a.prototype._byteLength=0,Object.defineProperty(a.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(a.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(t){this._buffer=t,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(a.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(t){this._byteOffset=t,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(a.prototype,"dataView",{get:function(){return this._dataView},set:function(t){this._byteOffset=t.byteOffset,this._buffer=t.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+t.byteLength}}),a.prototype.seek=function(t){var e=Math.max(0,Math.min(this.byteLength,t));this.position=isNaN(e)||!isFinite(e)?0:e},a.prototype.isEof=function(){return this.position>=this._byteLength},a.prototype.mapUint8Array=function(t){this._realloc(t*1);var e=new Uint8Array(this._buffer,this.byteOffset+this.position,t);return this.position+=t*1,e},a.prototype.readInt32Array=function(t,e){t=t??this.byteLength-this.position/4;var r=new Int32Array(t);return a.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),a.arrayToNative(r,e??this.endianness),this.position+=r.byteLength,r},a.prototype.readInt16Array=function(t,e){t=t??this.byteLength-this.position/2;var r=new Int16Array(t);return a.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),a.arrayToNative(r,e??this.endianness),this.position+=r.byteLength,r},a.prototype.readInt8Array=function(t){t=t??this.byteLength-this.position;var e=new Int8Array(t);return a.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,t*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e},a.prototype.readUint32Array=function(t,e){t=t??this.byteLength-this.position/4;var r=new Uint32Array(t);return a.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),a.arrayToNative(r,e??this.endianness),this.position+=r.byteLength,r},a.prototype.readUint16Array=function(t,e){t=t??this.byteLength-this.position/2;var r=new Uint16Array(t);return a.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),a.arrayToNative(r,e??this.endianness),this.position+=r.byteLength,r},a.prototype.readUint8Array=function(t){t=t??this.byteLength-this.position;var e=new Uint8Array(t);return a.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,t*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e},a.prototype.readFloat64Array=function(t,e){t=t??this.byteLength-this.position/8;var r=new Float64Array(t);return a.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),a.arrayToNative(r,e??this.endianness),this.position+=r.byteLength,r},a.prototype.readFloat32Array=function(t,e){t=t??this.byteLength-this.position/4;var r=new Float32Array(t);return a.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),a.arrayToNative(r,e??this.endianness),this.position+=r.byteLength,r},a.prototype.readInt32=function(t){var e=this._dataView.getInt32(this.position,t??this.endianness);return this.position+=4,e},a.prototype.readInt16=function(t){var e=this._dataView.getInt16(this.position,t??this.endianness);return this.position+=2,e},a.prototype.readInt8=function(){var t=this._dataView.getInt8(this.position);return this.position+=1,t},a.prototype.readUint32=function(t){var e=this._dataView.getUint32(this.position,t??this.endianness);return this.position+=4,e},a.prototype.readUint16=function(t){var e=this._dataView.getUint16(this.position,t??this.endianness);return this.position+=2,e},a.prototype.readUint8=function(){var t=this._dataView.getUint8(this.position);return this.position+=1,t},a.prototype.readFloat32=function(t){var e=this._dataView.getFloat32(this.position,t??this.endianness);return this.position+=4,e},a.prototype.readFloat64=function(t){var e=this._dataView.getFloat64(this.position,t??this.endianness);return this.position+=8,e},a.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,a.memcpy=function(t,e,r,n,o){var d=new Uint8Array(t,e,o),u=new Uint8Array(r,n,o);d.set(u)},a.arrayToNative=function(t,e){return e==this.endianness?t:this.flipArrayEndianness(t)},a.nativeToEndian=function(t,e){return this.endianness==e?t:this.flipArrayEndianness(t)},a.flipArrayEndianness=function(t){for(var e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),r=0;r<t.byteLength;r+=t.BYTES_PER_ELEMENT)for(var n=r+t.BYTES_PER_ELEMENT-1,o=r;n>o;n--,o++){var d=e[o];e[o]=e[n],e[n]=d}return t},a.prototype.failurePosition=0,String.fromCharCodeUint8=function(t){for(var e=[],r=0;r<t.length;r++)e[r]=t[r];return String.fromCharCode.apply(null,e)},a.prototype.readString=function(t,e){return e==null||e=="ASCII"?String.fromCharCodeUint8.apply(null,[this.mapUint8Array(t??this.byteLength-this.position)]):new TextDecoder(e).decode(this.mapUint8Array(t))},a.prototype.readCString=function(t){var e=this.byteLength-this.position,r=new Uint8Array(this._buffer,this._byteOffset+this.position),n=e;t!=null&&(n=Math.min(t,e));for(var o=0;o<n&&r[o]!==0;o++);var d=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(o)]);return t!=null?this.position+=n-o:o!=e&&(this.position+=1),d};var c=Math.pow(2,32);a.prototype.readInt64=function(){return this.readInt32()*c+this.readUint32()},a.prototype.readUint64=function(){return this.readUint32()*c+this.readUint32()},a.prototype.readInt64=function(){return this.readUint32()*c+this.readUint32()},a.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},C.DataStream=a,a.prototype.save=function(t){var e=new Blob([this.buffer]);if(window.URL&&URL.createObjectURL){var r=window.URL.createObjectURL(e),n=document.createElement("a");document.body.appendChild(n),n.setAttribute("href",r),n.setAttribute("download",t),n.setAttribute("target","_self"),n.click(),window.URL.revokeObjectURL(r)}else throw"DataStream.save: Can't create object URL."},a.prototype._dynamicSize=!0,Object.defineProperty(a.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(t){t||this._trimAlloc(),this._dynamicSize=t}}),a.prototype.shift=function(t){var e=new ArrayBuffer(this._byteLength-t),r=new Uint8Array(e),n=new Uint8Array(this._buffer,t,r.length);r.set(n),this.buffer=e,this.position-=t},a.prototype.writeInt32Array=function(t,e){if(this._realloc(t.length*4),t instanceof Int32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)a.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt32Array(t.length,e);else for(var r=0;r<t.length;r++)this.writeInt32(t[r],e)},a.prototype.writeInt16Array=function(t,e){if(this._realloc(t.length*2),t instanceof Int16Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)a.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt16Array(t.length,e);else for(var r=0;r<t.length;r++)this.writeInt16(t[r],e)},a.prototype.writeInt8Array=function(t){if(this._realloc(t.length*1),t instanceof Int8Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)a.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt8Array(t.length);else for(var e=0;e<t.length;e++)this.writeInt8(t[e])},a.prototype.writeUint32Array=function(t,e){if(this._realloc(t.length*4),t instanceof Uint32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)a.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint32Array(t.length,e);else for(var r=0;r<t.length;r++)this.writeUint32(t[r],e)},a.prototype.writeUint16Array=function(t,e){if(this._realloc(t.length*2),t instanceof Uint16Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)a.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint16Array(t.length,e);else for(var r=0;r<t.length;r++)this.writeUint16(t[r],e)},a.prototype.writeUint8Array=function(t){if(this._realloc(t.length*1),t instanceof Uint8Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)a.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint8Array(t.length);else for(var e=0;e<t.length;e++)this.writeUint8(t[e])},a.prototype.writeFloat64Array=function(t,e){if(this._realloc(t.length*8),t instanceof Float64Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)a.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapFloat64Array(t.length,e);else for(var r=0;r<t.length;r++)this.writeFloat64(t[r],e)},a.prototype.writeFloat32Array=function(t,e){if(this._realloc(t.length*4),t instanceof Float32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)a.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapFloat32Array(t.length,e);else for(var r=0;r<t.length;r++)this.writeFloat32(t[r],e)},a.prototype.writeInt32=function(t,e){this._realloc(4),this._dataView.setInt32(this.position,t,e??this.endianness),this.position+=4},a.prototype.writeInt16=function(t,e){this._realloc(2),this._dataView.setInt16(this.position,t,e??this.endianness),this.position+=2},a.prototype.writeInt8=function(t){this._realloc(1),this._dataView.setInt8(this.position,t),this.position+=1},a.prototype.writeUint32=function(t,e){this._realloc(4),this._dataView.setUint32(this.position,t,e??this.endianness),this.position+=4},a.prototype.writeUint16=function(t,e){this._realloc(2),this._dataView.setUint16(this.position,t,e??this.endianness),this.position+=2},a.prototype.writeUint8=function(t){this._realloc(1),this._dataView.setUint8(this.position,t),this.position+=1},a.prototype.writeFloat32=function(t,e){this._realloc(4),this._dataView.setFloat32(this.position,t,e??this.endianness),this.position+=4},a.prototype.writeFloat64=function(t,e){this._realloc(8),this._dataView.setFloat64(this.position,t,e??this.endianness),this.position+=8},a.prototype.writeUCS2String=function(t,e,r){r==null&&(r=t.length);for(var n=0;n<t.length&&n<r;n++)this.writeUint16(t.charCodeAt(n),e);for(;n<r;n++)this.writeUint16(0)},a.prototype.writeString=function(t,e,r){var n=0;if(e==null||e=="ASCII")if(r!=null){var o=Math.min(t.length,r);for(n=0;n<o;n++)this.writeUint8(t.charCodeAt(n));for(;n<r;n++)this.writeUint8(0)}else for(n=0;n<t.length;n++)this.writeUint8(t.charCodeAt(n));else this.writeUint8Array(new TextEncoder(e).encode(t.substring(0,r)))},a.prototype.writeCString=function(t,e){var r=0;if(e!=null){var n=Math.min(t.length,e);for(r=0;r<n;r++)this.writeUint8(t.charCodeAt(r));for(;r<e;r++)this.writeUint8(0)}else{for(r=0;r<t.length;r++)this.writeUint8(t.charCodeAt(r));this.writeUint8(0)}},a.prototype.writeStruct=function(t,e){for(var r=0;r<t.length;r+=2){var n=t[r+1];this.writeType(n,e[t[r]],e)}},a.prototype.writeType=function(t,e,r){var n;if(typeof t=="function")return t(this,e);if(typeof t=="object"&&!(t instanceof Array))return t.set(this,e,r);var o=null,d="ASCII",u=this.position;switch(typeof t=="string"&&/:/.test(t)&&(n=t.split(":"),t=n[0],o=parseInt(n[1])),typeof t=="string"&&/,/.test(t)&&(n=t.split(","),t=n[0],d=parseInt(n[1])),t){case"uint8":this.writeUint8(e);break;case"int8":this.writeInt8(e);break;case"uint16":this.writeUint16(e,this.endianness);break;case"int16":this.writeInt16(e,this.endianness);break;case"uint32":this.writeUint32(e,this.endianness);break;case"int32":this.writeInt32(e,this.endianness);break;case"float32":this.writeFloat32(e,this.endianness);break;case"float64":this.writeFloat64(e,this.endianness);break;case"uint16be":this.writeUint16(e,a.BIG_ENDIAN);break;case"int16be":this.writeInt16(e,a.BIG_ENDIAN);break;case"uint32be":this.writeUint32(e,a.BIG_ENDIAN);break;case"int32be":this.writeInt32(e,a.BIG_ENDIAN);break;case"float32be":this.writeFloat32(e,a.BIG_ENDIAN);break;case"float64be":this.writeFloat64(e,a.BIG_ENDIAN);break;case"uint16le":this.writeUint16(e,a.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(e,a.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(e,a.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(e,a.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(e,a.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(e,a.LITTLE_ENDIAN);break;case"cstring":this.writeCString(e,o);break;case"string":this.writeString(e,d,o);break;case"u16string":this.writeUCS2String(e,this.endianness,o);break;case"u16stringle":this.writeUCS2String(e,a.LITTLE_ENDIAN,o);break;case"u16stringbe":this.writeUCS2String(e,a.BIG_ENDIAN,o);break;default:if(t.length==3){for(var _=t[1],U=0;U<e.length;U++)this.writeType(_,e[U]);break}else{this.writeStruct(t,e);break}}o!=null&&(this.position=u,this._realloc(o),this.position=u+o)},a.prototype.writeUint64=function(t){var e=Math.floor(t/c);this.writeUint32(e),this.writeUint32(t&4294967295)},a.prototype.writeUint24=function(t){this.writeUint8((t&16711680)>>16),this.writeUint8((t&65280)>>8),this.writeUint8(t&255)},a.prototype.adjustUint32=function(t,e){var r=this.position;this.seek(t),this.writeUint32(e),this.seek(r)},a.prototype.mapInt32Array=function(t,e){this._realloc(t*4);var r=new Int32Array(this._buffer,this.byteOffset+this.position,t);return a.arrayToNative(r,e??this.endianness),this.position+=t*4,r},a.prototype.mapInt16Array=function(t,e){this._realloc(t*2);var r=new Int16Array(this._buffer,this.byteOffset+this.position,t);return a.arrayToNative(r,e??this.endianness),this.position+=t*2,r},a.prototype.mapInt8Array=function(t){this._realloc(t*1);var e=new Int8Array(this._buffer,this.byteOffset+this.position,t);return this.position+=t*1,e},a.prototype.mapUint32Array=function(t,e){this._realloc(t*4);var r=new Uint32Array(this._buffer,this.byteOffset+this.position,t);return a.arrayToNative(r,e??this.endianness),this.position+=t*4,r},a.prototype.mapUint16Array=function(t,e){this._realloc(t*2);var r=new Uint16Array(this._buffer,this.byteOffset+this.position,t);return a.arrayToNative(r,e??this.endianness),this.position+=t*2,r},a.prototype.mapFloat64Array=function(t,e){this._realloc(t*8);var r=new Float64Array(this._buffer,this.byteOffset+this.position,t);return a.arrayToNative(r,e??this.endianness),this.position+=t*8,r},a.prototype.mapFloat32Array=function(t,e){this._realloc(t*4);var r=new Float32Array(this._buffer,this.byteOffset+this.position,t);return a.arrayToNative(r,e??this.endianness),this.position+=t*4,r};var l=function(t){this.buffers=[],this.bufferIndex=-1,t&&(this.insertBuffer(t),this.bufferIndex=0)};l.prototype=new a(new ArrayBuffer,0,a.BIG_ENDIAN),l.prototype.initialized=function(){var t;return this.bufferIndex>-1?!0:this.buffers.length>0?(t=this.buffers[0],t.fileStart===0?(this.buffer=t,this.bufferIndex=0,f.debug("MultiBufferStream","Stream ready for parsing"),!0):(f.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)):(f.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1)},ArrayBuffer.concat=function(t,e){f.debug("ArrayBuffer","Trying to create a new buffer of size: "+(t.byteLength+e.byteLength));var r=new Uint8Array(t.byteLength+e.byteLength);return r.set(new Uint8Array(t),0),r.set(new Uint8Array(e),t.byteLength),r.buffer},l.prototype.reduceBuffer=function(t,e,r){var n;return n=new Uint8Array(r),n.set(new Uint8Array(t,e,r)),n.buffer.fileStart=t.fileStart+e,n.buffer.usedBytes=0,n.buffer},l.prototype.insertBuffer=function(t){for(var e=!0,r=0;r<this.buffers.length;r++){var n=this.buffers[r];if(t.fileStart<=n.fileStart){if(t.fileStart===n.fileStart)if(t.byteLength>n.byteLength){this.buffers.splice(r,1),r--;continue}else f.warn("MultiBufferStream","Buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+") already appended, ignoring");else t.fileStart+t.byteLength<=n.fileStart||(t=this.reduceBuffer(t,0,n.fileStart-t.fileStart)),f.debug("MultiBufferStream","Appending new buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+")"),this.buffers.splice(r,0,t),r===0&&(this.buffer=t);e=!1;break}else if(t.fileStart<n.fileStart+n.byteLength){var o=n.fileStart+n.byteLength-t.fileStart,d=t.byteLength-o;if(d>0)t=this.reduceBuffer(t,o,d);else{e=!1;break}}}e&&(f.debug("MultiBufferStream","Appending new buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+")"),this.buffers.push(t),r===0&&(this.buffer=t))},l.prototype.logBufferLevel=function(t){var e,r,n,o,d=[],u,_="";for(n=0,o=0,e=0;e<this.buffers.length;e++)r=this.buffers[e],e===0?(u={},d.push(u),u.start=r.fileStart,u.end=r.fileStart+r.byteLength,_+="["+u.start+"-"):u.end===r.fileStart?u.end=r.fileStart+r.byteLength:(u={},u.start=r.fileStart,_+=d[d.length-1].end-1+"], ["+u.start+"-",u.end=r.fileStart+r.byteLength,d.push(u)),n+=r.usedBytes,o+=r.byteLength;d.length>0&&(_+=u.end-1+"]");var U=t?f.info:f.debug;this.buffers.length===0?U("MultiBufferStream","No more buffer in memory"):U("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+n+"/"+o+" bytes), continuous ranges: "+_)},l.prototype.cleanBuffers=function(){var t,e;for(t=0;t<this.buffers.length;t++)e=this.buffers[t],e.usedBytes===e.byteLength&&(f.debug("MultiBufferStream","Removing buffer #"+t),this.buffers.splice(t,1),t--)},l.prototype.mergeNextBuffer=function(){var t;if(this.bufferIndex+1<this.buffers.length)if(t=this.buffers[this.bufferIndex+1],t.fileStart===this.buffer.fileStart+this.buffer.byteLength){var e=this.buffer.byteLength,r=this.buffer.usedBytes,n=this.buffer.fileStart;return this.buffers[this.bufferIndex]=ArrayBuffer.concat(this.buffer,t),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=r,this.buffer.fileStart=n,f.debug("ISOFile","Concatenating buffer for box parsing (length: "+e+"->"+this.buffer.byteLength+")"),!0}else return!1;else return!1},l.prototype.findPosition=function(t,e,r){var n,o=null,d=-1;for(t===!0?n=0:n=this.bufferIndex;n<this.buffers.length&&(o=this.buffers[n],o.fileStart<=e);){d=n,r&&(o.fileStart+o.byteLength<=e?o.usedBytes=o.byteLength:o.usedBytes=e-o.fileStart,this.logBufferLevel());n++}return d!==-1?(o=this.buffers[d],o.fileStart+o.byteLength>=e?(f.debug("MultiBufferStream","Found position in existing buffer #"+d),d):-1):-1},l.prototype.findEndContiguousBuf=function(t){var e,r,n,o=t!==void 0?t:this.bufferIndex;if(r=this.buffers[o],this.buffers.length>o+1)for(e=o+1;e<this.buffers.length&&(n=this.buffers[e],n.fileStart===r.fileStart+r.byteLength);e++)r=n;return r.fileStart+r.byteLength},l.prototype.getEndFilePositionAfter=function(t){var e=this.findPosition(!0,t,!1);return e!==-1?this.findEndContiguousBuf(e):t},l.prototype.addUsedBytes=function(t){this.buffer.usedBytes+=t,this.logBufferLevel()},l.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},l.prototype.seek=function(t,e,r){var n;return n=this.findPosition(e,t,r),n!==-1?(this.buffer=this.buffers[n],this.bufferIndex=n,this.position=t-this.buffer.fileStart,f.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(f.debug("MultiBufferStream","Position "+t+" not found in buffered data"),!1)},l.prototype.getPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.position},l.prototype.getLength=function(){return this.byteLength},l.prototype.getEndPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.byteLength},C.MultiBufferStream=l;var p=function(){var t=3,e=4,r=5,n=6,o=[];o[t]="ES_Descriptor",o[e]="DecoderConfigDescriptor",o[r]="DecoderSpecificInfo",o[n]="SLConfigDescriptor",this.getDescriptorName=function(_){return o[_]};var d=this,u={};return this.parseOneDescriptor=function(_){var U=0,S,b,E;for(S=_.readUint8(),E=_.readUint8();E&128;)U=(U<<7)+(E&127),E=_.readUint8();return U=(U<<7)+(E&127),f.debug("MPEG4DescriptorParser","Found "+(o[S]||"Descriptor "+S)+", size "+U+" at position "+_.getPosition()),o[S]?b=new u[o[S]](U):b=new u.Descriptor(U),b.parse(_),b},u.Descriptor=function(_,U){this.tag=_,this.size=U,this.descs=[]},u.Descriptor.prototype.parse=function(_){this.data=_.readUint8Array(this.size)},u.Descriptor.prototype.findDescriptor=function(_){for(var U=0;U<this.descs.length;U++)if(this.descs[U].tag==_)return this.descs[U];return null},u.Descriptor.prototype.parseRemainingDescriptors=function(_){for(var U=_.position;_.position<U+this.size;){var S=d.parseOneDescriptor(_);this.descs.push(S)}},u.ES_Descriptor=function(_){u.Descriptor.call(this,t,_)},u.ES_Descriptor.prototype=new u.Descriptor,u.ES_Descriptor.prototype.parse=function(_){if(this.ES_ID=_.readUint16(),this.flags=_.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=_.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){var U=_.readUint8();this.URL=_.readString(U),this.size-=U+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=_.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(_)},u.ES_Descriptor.prototype.getOTI=function(_){var U=this.findDescriptor(e);return U?U.oti:0},u.ES_Descriptor.prototype.getAudioConfig=function(_){var U=this.findDescriptor(e);if(!U)return null;var S=U.findDescriptor(r);if(S&&S.data){var b=(S.data[0]&248)>>3;return b===31&&S.data.length>=2&&(b=32+((S.data[0]&7)<<3)+((S.data[1]&224)>>5)),b}else return null},u.DecoderConfigDescriptor=function(_){u.Descriptor.call(this,e,_)},u.DecoderConfigDescriptor.prototype=new u.Descriptor,u.DecoderConfigDescriptor.prototype.parse=function(_){this.oti=_.readUint8(),this.streamType=_.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=_.readUint24(),this.maxBitrate=_.readUint32(),this.avgBitrate=_.readUint32(),this.size-=13,this.parseRemainingDescriptors(_)},u.DecoderSpecificInfo=function(_){u.Descriptor.call(this,r,_)},u.DecoderSpecificInfo.prototype=new u.Descriptor,u.SLConfigDescriptor=function(_){u.Descriptor.call(this,n,_)},u.SLConfigDescriptor.prototype=new u.Descriptor,this};C.MPEG4DescriptorParser=p;var s={ERR_INVALID_DATA:-1,ERR_NOT_ENOUGH_DATA:0,OK:1,BASIC_BOXES:["mdat","idat","free","skip","meco","strk"],FULL_BOXES:["hmhd","nmhd","iods","xml ","bxml","ipro","mere"],CONTAINER_BOXES:[["moov",["trak","pssh"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl",["sgpd","sbgp"]],["mvex",["trex"]],["moof",["traf"]],["traf",["trun","sgpd","sbgp"]],["vttc"],["tref"],["iref"],["mfra",["tfra"]],["meco"],["hnti"],["hinf"],["strk"],["strd"],["sinf"],["rinf"],["schi"],["trgr"],["udta",["kind"]],["iprp",["ipma"]],["ipco"],["grpl"],["j2kH"],["etyp",["tyco"]]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){s.FullBox.prototype=new s.Box,s.ContainerBox.prototype=new s.Box,s.SampleEntry.prototype=new s.Box,s.TrackGroupTypeBox.prototype=new s.FullBox,s.BASIC_BOXES.forEach(function(t){s.createBoxCtor(t)}),s.FULL_BOXES.forEach(function(t){s.createFullBoxCtor(t)}),s.CONTAINER_BOXES.forEach(function(t){s.createContainerBoxCtor(t[0],null,t[1])})},Box:function(t,e,r){this.type=t,this.size=e,this.uuid=r},FullBox:function(t,e,r){s.Box.call(this,t,e,r),this.flags=0,this.version=0},ContainerBox:function(t,e,r){s.Box.call(this,t,e,r),this.boxes=[]},SampleEntry:function(t,e,r,n){s.ContainerBox.call(this,t,e),this.hdr_size=r,this.start=n},SampleGroupEntry:function(t){this.grouping_type=t},TrackGroupTypeBox:function(t,e){s.FullBox.call(this,t,e)},createBoxCtor:function(t,e){s.boxCodes.push(t),s[t+"Box"]=function(r){s.Box.call(this,t,r)},s[t+"Box"].prototype=new s.Box,e&&(s[t+"Box"].prototype.parse=e)},createFullBoxCtor:function(t,e){s[t+"Box"]=function(r){s.FullBox.call(this,t,r)},s[t+"Box"].prototype=new s.FullBox,s[t+"Box"].prototype.parse=function(r){this.parseFullHeader(r),e&&e.call(this,r)}},addSubBoxArrays:function(t){if(t){this.subBoxNames=t;for(var e=t.length,r=0;r<e;r++)this[t[r]+"s"]=[]}},createContainerBoxCtor:function(t,e,r){s[t+"Box"]=function(n){s.ContainerBox.call(this,t,n),s.addSubBoxArrays.call(this,r)},s[t+"Box"].prototype=new s.ContainerBox,e&&(s[t+"Box"].prototype.parse=e)},createMediaSampleEntryCtor:function(t,e,r){s.sampleEntryCodes[t]=[],s[t+"SampleEntry"]=function(n,o){s.SampleEntry.call(this,n,o),s.addSubBoxArrays.call(this,r)},s[t+"SampleEntry"].prototype=new s.SampleEntry,e&&(s[t+"SampleEntry"].prototype.parse=e)},createSampleEntryCtor:function(t,e,r,n){s.sampleEntryCodes[t].push(e),s[e+"SampleEntry"]=function(o){s[t+"SampleEntry"].call(this,e,o),s.addSubBoxArrays.call(this,n)},s[e+"SampleEntry"].prototype=new s[t+"SampleEntry"],r&&(s[e+"SampleEntry"].prototype.parse=r)},createEncryptedSampleEntryCtor:function(t,e,r){s.createSampleEntryCtor.call(this,t,e,r,["sinf"])},createSampleGroupCtor:function(t,e){s[t+"SampleGroupEntry"]=function(r){s.SampleGroupEntry.call(this,t,r)},s[t+"SampleGroupEntry"].prototype=new s.SampleGroupEntry,e&&(s[t+"SampleGroupEntry"].prototype.parse=e)},createTrackGroupCtor:function(t,e){s[t+"TrackGroupTypeBox"]=function(r){s.TrackGroupTypeBox.call(this,t,r)},s[t+"TrackGroupTypeBox"].prototype=new s.TrackGroupTypeBox,e&&(s[t+"TrackGroupTypeBox"].prototype.parse=e)},createUUIDBox:function(t,e,r,n){s.UUIDs.push(t),s.UUIDBoxes[t]=function(o){e?s.FullBox.call(this,"uuid",o,t):r?s.ContainerBox.call(this,"uuid",o,t):s.Box.call(this,"uuid",o,t)},s.UUIDBoxes[t].prototype=e?new s.FullBox:r?new s.ContainerBox:new s.Box,n&&(e?s.UUIDBoxes[t].prototype.parse=function(o){this.parseFullHeader(o),n&&n.call(this,o)}:s.UUIDBoxes[t].prototype.parse=n)}};s.initialize(),s.TKHD_FLAG_ENABLED=1,s.TKHD_FLAG_IN_MOVIE=2,s.TKHD_FLAG_IN_PREVIEW=4,s.TFHD_FLAG_BASE_DATA_OFFSET=1,s.TFHD_FLAG_SAMPLE_DESC=2,s.TFHD_FLAG_SAMPLE_DUR=8,s.TFHD_FLAG_SAMPLE_SIZE=16,s.TFHD_FLAG_SAMPLE_FLAGS=32,s.TFHD_FLAG_DUR_EMPTY=65536,s.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,s.TRUN_FLAGS_DATA_OFFSET=1,s.TRUN_FLAGS_FIRST_FLAG=4,s.TRUN_FLAGS_DURATION=256,s.TRUN_FLAGS_SIZE=512,s.TRUN_FLAGS_FLAGS=1024,s.TRUN_FLAGS_CTS_OFFSET=2048,s.Box.prototype.add=function(t){return this.addBox(new s[t+"Box"])},s.Box.prototype.addBox=function(t){return this.boxes.push(t),this[t.type+"s"]?this[t.type+"s"].push(t):this[t.type]=t,t},s.Box.prototype.set=function(t,e){return this[t]=e,this},s.Box.prototype.addEntry=function(t,e){var r=e||"entries";return this[r]||(this[r]=[]),this[r].push(t),this},C.BoxParser=s,s.parseUUID=function(t){return s.parseHex16(t)},s.parseHex16=function(t){for(var e="",r=0;r<16;r++){var n=t.readUint8().toString(16);e+=n.length===1?"0"+n:n}return e},s.parseOneBox=function(t,e,r){var n,o=t.getPosition(),d=0,u,_;if(t.getEndPosition()-o<8)return f.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:s.ERR_NOT_ENOUGH_DATA};if(r&&r<8)return f.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:s.ERR_NOT_ENOUGH_DATA};var U=t.readUint32(),S=t.readString(4),b=S;if(f.debug("BoxParser","Found box of type '"+S+"' and size "+U+" at position "+o),d=8,S=="uuid"){if(t.getEndPosition()-t.getPosition()<16||r-d<16)return t.seek(o),f.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:s.ERR_NOT_ENOUGH_DATA};_=s.parseUUID(t),d+=16,b=_}if(U==1){if(t.getEndPosition()-t.getPosition()<8||r&&r-d<8)return t.seek(o),f.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+S+'" box'),{code:s.ERR_NOT_ENOUGH_DATA};U=t.readUint64(),d+=8}else if(U===0){if(r)U=r;else if(S!=="mdat")return f.error("BoxParser","Unlimited box size not supported for type: '"+S+"'"),n=new s.Box(S,U),{code:s.OK,box:n,size:n.size}}return U!==0&&U<d?(f.error("BoxParser","Box of type "+S+" has an invalid size "+U+" (too small to be a box)"),{code:s.ERR_NOT_ENOUGH_DATA,type:S,size:U,hdr_size:d,start:o}):U!==0&&r&&U>r?(f.error("BoxParser","Box of type '"+S+"' has a size "+U+" greater than its container size "+r),{code:s.ERR_NOT_ENOUGH_DATA,type:S,size:U,hdr_size:d,start:o}):U!==0&&o+U>t.getEndPosition()?(t.seek(o),f.info("BoxParser","Not enough data in stream to parse the entire '"+S+"' box"),{code:s.ERR_NOT_ENOUGH_DATA,type:S,size:U,hdr_size:d,start:o}):e?{code:s.OK,type:S,size:U,hdr_size:d,start:o}:(s[S+"Box"]?n=new s[S+"Box"](U):S!=="uuid"?(f.warn("BoxParser","Unknown box type: '"+S+"'"),n=new s.Box(S,U),n.has_unparsed_data=!0):s.UUIDBoxes[_]?n=new s.UUIDBoxes[_](U):(f.warn("BoxParser","Unknown uuid type: '"+_+"'"),n=new s.Box(S,U),n.uuid=_,n.has_unparsed_data=!0),n.hdr_size=d,n.start=o,n.write===s.Box.prototype.write&&n.type!=="mdat"&&(f.info("BoxParser","'"+b+"' box writing not yet implemented, keeping unparsed data in memory for later write"),n.parseDataAndRewind(t)),n.parse(t),u=t.getPosition()-(n.start+n.size),u<0?(f.warn("BoxParser","Parsing of box '"+b+"' did not read the entire indicated box data size (missing "+-u+" bytes), seeking forward"),t.seek(n.start+n.size)):u>0&&(f.error("BoxParser","Parsing of box '"+b+"' read "+u+" more bytes than the indicated box data size, seeking backwards"),n.size!==0&&t.seek(n.start+n.size)),{code:s.OK,box:n,size:n.size})},s.Box.prototype.parse=function(t){this.type!="mdat"?this.data=t.readUint8Array(this.size-this.hdr_size):this.size===0?t.seek(t.getEndPosition()):t.seek(this.start+this.size)},s.Box.prototype.parseDataAndRewind=function(t){this.data=t.readUint8Array(this.size-this.hdr_size),t.position-=this.size-this.hdr_size},s.FullBox.prototype.parseDataAndRewind=function(t){this.parseFullHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,t.position-=this.size-this.hdr_size},s.FullBox.prototype.parseFullHeader=function(t){this.version=t.readUint8(),this.flags=t.readUint24(),this.hdr_size+=4},s.FullBox.prototype.parse=function(t){this.parseFullHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size)},s.ContainerBox.prototype.parse=function(t){for(var e,r;t.getPosition()<this.start+this.size;)if(e=s.parseOneBox(t,!1,this.size-(t.getPosition()-this.start)),e.code===s.OK)if(r=e.box,this.boxes.push(r),this.subBoxNames&&this.subBoxNames.indexOf(r.type)!=-1)this[this.subBoxNames[this.subBoxNames.indexOf(r.type)]+"s"].push(r);else{var n=r.type!=="uuid"?r.type:r.uuid;this[n]?f.warn("Box of type "+n+" already stored in field of this type"):this[n]=r}else return},s.Box.prototype.parseLanguage=function(t){this.language=t.readUint16();var e=[];e[0]=this.language>>10&31,e[1]=this.language>>5&31,e[2]=this.language&31,this.languageString=String.fromCharCode(e[0]+96,e[1]+96,e[2]+96)},s.SAMPLE_ENTRY_TYPE_VISUAL="Visual",s.SAMPLE_ENTRY_TYPE_AUDIO="Audio",s.SAMPLE_ENTRY_TYPE_HINT="Hint",s.SAMPLE_ENTRY_TYPE_METADATA="Metadata",s.SAMPLE_ENTRY_TYPE_SUBTITLE="Subtitle",s.SAMPLE_ENTRY_TYPE_SYSTEM="System",s.SAMPLE_ENTRY_TYPE_TEXT="Text",s.SampleEntry.prototype.parseHeader=function(t){t.readUint8Array(6),this.data_reference_index=t.readUint16(),this.hdr_size+=8},s.SampleEntry.prototype.parse=function(t){this.parseHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size)},s.SampleEntry.prototype.parseDataAndRewind=function(t){this.parseHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,t.position-=this.size-this.hdr_size},s.SampleEntry.prototype.parseFooter=function(t){s.ContainerBox.prototype.parse.call(this,t)},s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_HINT),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SYSTEM),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_TEXT),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,function(t){var e;this.parseHeader(t),t.readUint16(),t.readUint16(),t.readUint32Array(3),this.width=t.readUint16(),this.height=t.readUint16(),this.horizresolution=t.readUint32(),this.vertresolution=t.readUint32(),t.readUint32(),this.frame_count=t.readUint16(),e=Math.min(31,t.readUint8()),this.compressorname=t.readString(e),e<31&&t.readString(31-e),this.depth=t.readUint16(),t.readUint16(),this.parseFooter(t)}),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,function(t){this.parseHeader(t),t.readUint32Array(2),this.channel_count=t.readUint16(),this.samplesize=t.readUint16(),t.readUint16(),t.readUint16(),this.samplerate=t.readUint32()/65536,this.parseFooter(t)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc4"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"av01"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"dav1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"hvc1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"hev1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"hvt1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"lhe1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"dvh1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"dvhe"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvc1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvi1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvs1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvcN"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vp08"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vp09"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avs3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"j2ki"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"mjp2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"mjpg"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"uncv"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mp4a"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"ac-3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"ac-4"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"ec-3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"Opus"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mha1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mha2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mhm1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mhm2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"fLaC"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"encv"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"enca"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"encu"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SYSTEM,"encs"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_TEXT,"enct"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"encm"),s.createBoxCtor("a1lx",function(t){var e=t.readUint8()&1,r=((e&1)+1)*16;this.layer_size=[];for(var n=0;n<3;n++)r==16?this.layer_size[n]=t.readUint16():this.layer_size[n]=t.readUint32()}),s.createBoxCtor("a1op",function(t){this.op_index=t.readUint8()}),s.createFullBoxCtor("auxC",function(t){this.aux_type=t.readCString();var e=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=t.readUint8Array(e)}),s.createBoxCtor("av1C",function(t){var e=t.readUint8();if(e>>7&!1){f.error("av1C marker problem");return}if(this.version=e&127,this.version!==1){f.error("av1C version "+this.version+" not supported");return}if(e=t.readUint8(),this.seq_profile=e>>5&7,this.seq_level_idx_0=e&31,e=t.readUint8(),this.seq_tier_0=e>>7&1,this.high_bitdepth=e>>6&1,this.twelve_bit=e>>5&1,this.monochrome=e>>4&1,this.chroma_subsampling_x=e>>3&1,this.chroma_subsampling_y=e>>2&1,this.chroma_sample_position=e&3,e=t.readUint8(),this.reserved_1=e>>5&7,this.reserved_1!==0){f.error("av1C reserved_1 parsing problem");return}if(this.initial_presentation_delay_present=e>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=e&15;else if(this.reserved_2=e&15,this.reserved_2!==0){f.error("av1C reserved_2 parsing problem");return}var r=this.size-this.hdr_size-4;this.configOBUs=t.readUint8Array(r)}),s.createBoxCtor("avcC",function(t){var e,r;for(this.configurationVersion=t.readUint8(),this.AVCProfileIndication=t.readUint8(),this.profile_compatibility=t.readUint8(),this.AVCLevelIndication=t.readUint8(),this.lengthSizeMinusOne=t.readUint8()&3,this.nb_SPS_nalus=t.readUint8()&31,r=this.size-this.hdr_size-6,this.SPS=[],e=0;e<this.nb_SPS_nalus;e++)this.SPS[e]={},this.SPS[e].length=t.readUint16(),this.SPS[e].nalu=t.readUint8Array(this.SPS[e].length),r-=2+this.SPS[e].length;for(this.nb_PPS_nalus=t.readUint8(),r--,this.PPS=[],e=0;e<this.nb_PPS_nalus;e++)this.PPS[e]={},this.PPS[e].length=t.readUint16(),this.PPS[e].nalu=t.readUint8Array(this.PPS[e].length),r-=2+this.PPS[e].length;r>0&&(this.ext=t.readUint8Array(r))}),s.createBoxCtor("btrt",function(t){this.bufferSizeDB=t.readUint32(),this.maxBitrate=t.readUint32(),this.avgBitrate=t.readUint32()}),s.createFullBoxCtor("ccst",function(t){var e=t.readUint8();this.all_ref_pics_intra=(e&128)==128,this.intra_pred_used=(e&64)==64,this.max_ref_per_pic=(e&63)>>2,t.readUint24()}),s.createBoxCtor("cdef",function(t){var e;for(this.channel_count=t.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[],e=0;e<this.channel_count;e++)this.channel_indexes.push(t.readUint16()),this.channel_types.push(t.readUint16()),this.channel_associations.push(t.readUint16())}),s.createBoxCtor("clap",function(t){this.cleanApertureWidthN=t.readUint32(),this.cleanApertureWidthD=t.readUint32(),this.cleanApertureHeightN=t.readUint32(),this.cleanApertureHeightD=t.readUint32(),this.horizOffN=t.readUint32(),this.horizOffD=t.readUint32(),this.vertOffN=t.readUint32(),this.vertOffD=t.readUint32()}),s.createBoxCtor("clli",function(t){this.max_content_light_level=t.readUint16(),this.max_pic_average_light_level=t.readUint16()}),s.createFullBoxCtor("cmex",function(t){this.flags&1&&(this.pos_x=t.readInt32()),this.flags&2&&(this.pos_y=t.readInt32()),this.flags&4&&(this.pos_z=t.readInt32()),this.flags&8&&(this.version==0?this.flags&16?(this.quat_x=t.readInt32(),this.quat_y=t.readInt32(),this.quat_z=t.readInt32()):(this.quat_x=t.readInt16(),this.quat_y=t.readInt16(),this.quat_z=t.readInt16()):this.version==1),this.flags&32&&(this.id=t.readUint32())}),s.createFullBoxCtor("cmin",function(t){this.focal_length_x=t.readInt32(),this.principal_point_x=t.readInt32(),this.principal_point_y=t.readInt32(),this.flags&1&&(this.focal_length_y=t.readInt32(),this.skew_factor=t.readInt32())}),s.createBoxCtor("cmpd",function(t){for(this.component_count=t.readUint32(),this.component_types=[],this.component_type_urls=[],i=0;i<this.component_count;i++){var e=t.readUint16();this.component_types.push(e),e>=32768&&this.component_type_urls.push(t.readCString())}}),s.createFullBoxCtor("co64",function(t){var e,r;if(e=t.readUint32(),this.chunk_offsets=[],this.version===0)for(r=0;r<e;r++)this.chunk_offsets.push(t.readUint64())}),s.createFullBoxCtor("CoLL",function(t){this.maxCLL=t.readUint16(),this.maxFALL=t.readUint16()}),s.createBoxCtor("colr",function(t){if(this.colour_type=t.readString(4),this.colour_type==="nclx"){this.colour_primaries=t.readUint16(),this.transfer_characteristics=t.readUint16(),this.matrix_coefficients=t.readUint16();var e=t.readUint8();this.full_range_flag=e>>7}else this.colour_type==="rICC"?this.ICC_profile=t.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=t.readUint8Array(this.size-4))}),s.createFullBoxCtor("cprt",function(t){this.parseLanguage(t),this.notice=t.readCString()}),s.createFullBoxCtor("cslg",function(t){this.version===0&&(this.compositionToDTSShift=t.readInt32(),this.leastDecodeToDisplayDelta=t.readInt32(),this.greatestDecodeToDisplayDelta=t.readInt32(),this.compositionStartTime=t.readInt32(),this.compositionEndTime=t.readInt32())}),s.createFullBoxCtor("ctts",function(t){var e,r;if(e=t.readUint32(),this.sample_counts=[],this.sample_offsets=[],this.version===0)for(r=0;r<e;r++){this.sample_counts.push(t.readUint32());var n=t.readInt32();n<0&&f.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(n)}else if(this.version==1)for(r=0;r<e;r++)this.sample_counts.push(t.readUint32()),this.sample_offsets.push(t.readInt32())}),s.createBoxCtor("dac3",function(t){var e=t.readUint8(),r=t.readUint8(),n=t.readUint8();this.fscod=e>>6,this.bsid=e>>1&31,this.bsmod=(e&1)<<2|r>>6&3,this.acmod=r>>3&7,this.lfeon=r>>2&1,this.bit_rate_code=r&3|n>>5&7}),s.createBoxCtor("dec3",function(t){var e=t.readUint16();this.data_rate=e>>3,this.num_ind_sub=e&7,this.ind_subs=[];for(var r=0;r<this.num_ind_sub+1;r++){var n={};this.ind_subs.push(n);var o=t.readUint8(),d=t.readUint8(),u=t.readUint8();n.fscod=o>>6,n.bsid=o>>1&31,n.bsmod=(o&1)<<4|d>>4&15,n.acmod=d>>1&7,n.lfeon=d&1,n.num_dep_sub=u>>1&15,n.num_dep_sub>0&&(n.chan_loc=(u&1)<<8|t.readUint8())}}),s.createFullBoxCtor("dfLa",function(t){var e=127,r=128,n=[],o=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];do{var d=t.readUint8(),u=Math.min(d&e,o.length-1);if(u?t.readUint8Array(t.readUint24()):(t.readUint8Array(13),this.samplerate=t.readUint32()>>12,t.readUint8Array(20)),n.push(o[u]),d&r)break}while(!0);this.numMetadataBlocks=n.length+" ("+n.join(", ")+")"}),s.createBoxCtor("dimm",function(t){this.bytessent=t.readUint64()}),s.createBoxCtor("dmax",function(t){this.time=t.readUint32()}),s.createBoxCtor("dmed",function(t){this.bytessent=t.readUint64()}),s.createBoxCtor("dOps",function(t){if(this.Version=t.readUint8(),this.OutputChannelCount=t.readUint8(),this.PreSkip=t.readUint16(),this.InputSampleRate=t.readUint32(),this.OutputGain=t.readInt16(),this.ChannelMappingFamily=t.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=t.readUint8(),this.CoupledCount=t.readUint8(),this.ChannelMapping=[];for(var e=0;e<this.OutputChannelCount;e++)this.ChannelMapping[e]=t.readUint8()}}),s.createFullBoxCtor("dref",function(t){var e,r;this.entries=[];for(var n=t.readUint32(),o=0;o<n;o++)if(e=s.parseOneBox(t,!1,this.size-(t.getPosition()-this.start)),e.code===s.OK)r=e.box,this.entries.push(r);else return}),s.createBoxCtor("drep",function(t){this.bytessent=t.readUint64()}),s.createFullBoxCtor("elng",function(t){this.extended_language=t.readString(this.size-this.hdr_size)}),s.createFullBoxCtor("elst",function(t){this.entries=[];for(var e=t.readUint32(),r=0;r<e;r++){var n={};this.entries.push(n),this.version===1?(n.segment_duration=t.readUint64(),n.media_time=t.readInt64()):(n.segment_duration=t.readUint32(),n.media_time=t.readInt32()),n.media_rate_integer=t.readInt16(),n.media_rate_fraction=t.readInt16()}}),s.createFullBoxCtor("emsg",function(t){this.version==1?(this.timescale=t.readUint32(),this.presentation_time=t.readUint64(),this.event_duration=t.readUint32(),this.id=t.readUint32(),this.scheme_id_uri=t.readCString(),this.value=t.readCString()):(this.scheme_id_uri=t.readCString(),this.value=t.readCString(),this.timescale=t.readUint32(),this.presentation_time_delta=t.readUint32(),this.event_duration=t.readUint32(),this.id=t.readUint32());var e=this.size-this.hdr_size-(4*4+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version==1&&(e-=4),this.message_data=t.readUint8Array(e)}),s.createEntityToGroupCtor=function(t,e){s[t+"Box"]=function(r){s.FullBox.call(this,t,r)},s[t+"Box"].prototype=new s.FullBox,s[t+"Box"].prototype.parse=function(r){if(this.parseFullHeader(r),e)e.call(this,r);else for(this.group_id=r.readUint32(),this.num_entities_in_group=r.readUint32(),this.entity_ids=[],i=0;i<this.num_entities_in_group;i++){var n=r.readUint32();this.entity_ids.push(n)}}},s.createEntityToGroupCtor("aebr"),s.createEntityToGroupCtor("afbr"),s.createEntityToGroupCtor("albc"),s.createEntityToGroupCtor("altr"),s.createEntityToGroupCtor("brst"),s.createEntityToGroupCtor("dobr"),s.createEntityToGroupCtor("eqiv"),s.createEntityToGroupCtor("favc"),s.createEntityToGroupCtor("fobr"),s.createEntityToGroupCtor("iaug"),s.createEntityToGroupCtor("pano"),s.createEntityToGroupCtor("slid"),s.createEntityToGroupCtor("ster"),s.createEntityToGroupCtor("tsyn"),s.createEntityToGroupCtor("wbbr"),s.createEntityToGroupCtor("prgr"),s.createEntityToGroupCtor("pymd",function(t){this.group_id=t.readUint32(),this.num_entities_in_group=t.readUint32(),this.entity_ids=[];for(var e=0;e<this.num_entities_in_group;e++){var r=t.readUint32();this.entity_ids.push(r)}for(this.tile_size_x=t.readUint16(),this.tile_size_y=t.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[],e=0;e<this.num_entities_in_group;e++)this.layer_binning[e]=t.readUint16(),this.tiles_in_layer_row_minus1[e]=t.readUint16(),this.tiles_in_layer_column_minus1[e]=t.readUint16()}),s.createFullBoxCtor("esds",function(t){var e=t.readUint8Array(this.size-this.hdr_size);if(typeof p<"u"){var r=new p;this.esd=r.parseOneDescriptor(new a(e.buffer,0,a.BIG_ENDIAN))}}),s.createBoxCtor("fiel",function(t){this.fieldCount=t.readUint8(),this.fieldOrdering=t.readUint8()}),s.createBoxCtor("frma",function(t){this.data_format=t.readString(4)}),s.createBoxCtor("ftyp",function(t){var e=this.size-this.hdr_size;this.major_brand=t.readString(4),this.minor_version=t.readUint32(),e-=8,this.compatible_brands=[];for(var r=0;e>=4;)this.compatible_brands[r]=t.readString(4),e-=4,r++}),s.createFullBoxCtor("hdlr",function(t){this.version===0&&(t.readUint32(),this.handler=t.readString(4),t.readUint32Array(3),this.name=t.readString(this.size-this.hdr_size-20),this.name[this.name.length-1]==="\\0"&&(this.name=this.name.slice(0,-1)))}),s.createBoxCtor("hvcC",function(t){var e,r,n,o;this.configurationVersion=t.readUint8(),o=t.readUint8(),this.general_profile_space=o>>6,this.general_tier_flag=(o&32)>>5,this.general_profile_idc=o&31,this.general_profile_compatibility=t.readUint32(),this.general_constraint_indicator=t.readUint8Array(6),this.general_level_idc=t.readUint8(),this.min_spatial_segmentation_idc=t.readUint16()&4095,this.parallelismType=t.readUint8()&3,this.chroma_format_idc=t.readUint8()&3,this.bit_depth_luma_minus8=t.readUint8()&7,this.bit_depth_chroma_minus8=t.readUint8()&7,this.avgFrameRate=t.readUint16(),o=t.readUint8(),this.constantFrameRate=o>>6,this.numTemporalLayers=(o&13)>>3,this.temporalIdNested=(o&4)>>2,this.lengthSizeMinusOne=o&3,this.nalu_arrays=[];var d=t.readUint8();for(e=0;e<d;e++){var u=[];this.nalu_arrays.push(u),o=t.readUint8(),u.completeness=(o&128)>>7,u.nalu_type=o&63;var _=t.readUint16();for(r=0;r<_;r++){var U={};u.push(U),n=t.readUint16(),U.data=t.readUint8Array(n)}}}),s.createFullBoxCtor("iinf",function(t){var e;this.version===0?this.entry_count=t.readUint16():this.entry_count=t.readUint32(),this.item_infos=[];for(var r=0;r<this.entry_count;r++)if(e=s.parseOneBox(t,!1,this.size-(t.getPosition()-this.start)),e.code===s.OK)e.box.type!=="infe"&&f.error("BoxParser","Expected 'infe' box, got "+e.box.type),this.item_infos[r]=e.box;else return}),s.createFullBoxCtor("iloc",function(t){var e;e=t.readUint8(),this.offset_size=e>>4&15,this.length_size=e&15,e=t.readUint8(),this.base_offset_size=e>>4&15,this.version===1||this.version===2?this.index_size=e&15:this.index_size=0,this.items=[];var r=0;if(this.version<2)r=t.readUint16();else if(this.version===2)r=t.readUint32();else throw"version of iloc box not supported";for(var n=0;n<r;n++){var o={};if(this.items.push(o),this.version<2)o.item_ID=t.readUint16();else if(this.version===2)o.item_ID=t.readUint32();else throw"version of iloc box not supported";switch(this.version===1||this.version===2?o.construction_method=t.readUint16()&15:o.construction_method=0,o.data_reference_index=t.readUint16(),this.base_offset_size){case 0:o.base_offset=0;break;case 4:o.base_offset=t.readUint32();break;case 8:o.base_offset=t.readUint64();break;default:throw"Error reading base offset size"}var d=t.readUint16();o.extents=[];for(var u=0;u<d;u++){var _={};if(o.extents.push(_),this.version===1||this.version===2)switch(this.index_size){case 0:_.extent_index=0;break;case 4:_.extent_index=t.readUint32();break;case 8:_.extent_index=t.readUint64();break;default:throw"Error reading extent index"}switch(this.offset_size){case 0:_.extent_offset=0;break;case 4:_.extent_offset=t.readUint32();break;case 8:_.extent_offset=t.readUint64();break;default:throw"Error reading extent index"}switch(this.length_size){case 0:_.extent_length=0;break;case 4:_.extent_length=t.readUint32();break;case 8:_.extent_length=t.readUint64();break;default:throw"Error reading extent index"}}}}),s.createBoxCtor("imir",function(t){var e=t.readUint8();this.reserved=e>>7,this.axis=e&1}),s.createFullBoxCtor("infe",function(t){if((this.version===0||this.version===1)&&(this.item_ID=t.readUint16(),this.item_protection_index=t.readUint16(),this.item_name=t.readCString(),this.content_type=t.readCString(),this.content_encoding=t.readCString()),this.version===1){this.extension_type=t.readString(4),f.warn("BoxParser","Cannot parse extension type"),t.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=t.readUint16():this.version===3&&(this.item_ID=t.readUint32()),this.item_protection_index=t.readUint16(),this.item_type=t.readString(4),this.item_name=t.readCString(),this.item_type==="mime"?(this.content_type=t.readCString(),this.content_encoding=t.readCString()):this.item_type==="uri "&&(this.item_uri_type=t.readCString()))}),s.createFullBoxCtor("ipma",function(t){var e,r;for(entry_count=t.readUint32(),this.associations=[],e=0;e<entry_count;e++){var n={};this.associations.push(n),this.version<1?n.id=t.readUint16():n.id=t.readUint32();var o=t.readUint8();for(n.props=[],r=0;r<o;r++){var d=t.readUint8(),u={};n.props.push(u),u.essential=(d&128)>>7===1,this.flags&1?u.property_index=(d&127)<<8|t.readUint8():u.property_index=d&127}}}),s.createFullBoxCtor("iref",function(t){var e,r;for(this.references=[];t.getPosition()<this.start+this.size;)if(e=s.parseOneBox(t,!0,this.size-(t.getPosition()-this.start)),e.code===s.OK)this.version===0?r=new s.SingleItemTypeReferenceBox(e.type,e.size,e.hdr_size,e.start):r=new s.SingleItemTypeReferenceBoxLarge(e.type,e.size,e.hdr_size,e.start),r.write===s.Box.prototype.write&&r.type!=="mdat"&&(f.warn("BoxParser",r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(t)),r.parse(t),this.references.push(r);else return}),s.createBoxCtor("irot",function(t){this.angle=t.readUint8()&3}),s.createFullBoxCtor("ispe",function(t){this.image_width=t.readUint32(),this.image_height=t.readUint32()}),s.createFullBoxCtor("kind",function(t){this.schemeURI=t.readCString(),this.value=t.readCString()}),s.createFullBoxCtor("leva",function(t){var e=t.readUint8();this.levels=[];for(var r=0;r<e;r++){var n={};this.levels[r]=n,n.track_ID=t.readUint32();var o=t.readUint8();switch(n.padding_flag=o>>7,n.assignment_type=o&127,n.assignment_type){case 0:n.grouping_type=t.readString(4);break;case 1:n.grouping_type=t.readString(4),n.grouping_type_parameter=t.readUint32();break;case 2:break;case 3:break;case 4:n.sub_track_id=t.readUint32();break;default:f.warn("BoxParser","Unknown leva assignement type")}}}),s.createBoxCtor("lhvC",function(t){var e,r,n;this.configurationVersion=t.readUint8(),this.min_spatial_segmentation_idc=t.readUint16()&4095,this.parallelismType=t.readUint8()&3,n=t.readUint8(),this.numTemporalLayers=(n&13)>>3,this.temporalIdNested=(n&4)>>2,this.lengthSizeMinusOne=n&3,this.nalu_arrays=[];var o=t.readUint8();for(e=0;e<o;e++){var d=[];this.nalu_arrays.push(d),n=t.readUint8(),d.completeness=(n&128)>>7,d.nalu_type=n&63;var u=t.readUint16();for(r=0;r<u;r++){var _={};d.push(_);var U=t.readUint16();_.data=t.readUint8Array(U)}}}),s.createBoxCtor("lsel",function(t){this.layer_id=t.readUint16()}),s.createBoxCtor("maxr",function(t){this.period=t.readUint32(),this.bytes=t.readUint32()});function g(t,e){this.x=t,this.y=e}g.prototype.toString=function(){return"("+this.x+","+this.y+")"},s.createBoxCtor("mdcv",function(t){this.display_primaries=[],this.display_primaries[0]=new g(t.readUint16(),t.readUint16()),this.display_primaries[1]=new g(t.readUint16(),t.readUint16()),this.display_primaries[2]=new g(t.readUint16(),t.readUint16()),this.white_point=new g(t.readUint16(),t.readUint16()),this.max_display_mastering_luminance=t.readUint32(),this.min_display_mastering_luminance=t.readUint32()}),s.createFullBoxCtor("mdhd",function(t){this.version==1?(this.creation_time=t.readUint64(),this.modification_time=t.readUint64(),this.timescale=t.readUint32(),this.duration=t.readUint64()):(this.creation_time=t.readUint32(),this.modification_time=t.readUint32(),this.timescale=t.readUint32(),this.duration=t.readUint32()),this.parseLanguage(t),t.readUint16()}),s.createFullBoxCtor("mehd",function(t){this.flags&1&&(f.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version==1?this.fragment_duration=t.readUint64():this.fragment_duration=t.readUint32()}),s.createFullBoxCtor("meta",function(t){this.boxes=[],s.ContainerBox.prototype.parse.call(this,t)}),s.createFullBoxCtor("mfhd",function(t){this.sequence_number=t.readUint32()}),s.createFullBoxCtor("mfro",function(t){this._size=t.readUint32()}),s.createFullBoxCtor("mskC",function(t){this.bits_per_pixel=t.readUint8()}),s.createFullBoxCtor("mvhd",function(t){this.version==1?(this.creation_time=t.readUint64(),this.modification_time=t.readUint64(),this.timescale=t.readUint32(),this.duration=t.readUint64()):(this.creation_time=t.readUint32(),this.modification_time=t.readUint32(),this.timescale=t.readUint32(),this.duration=t.readUint32()),this.rate=t.readUint32(),this.volume=t.readUint16()>>8,t.readUint16(),t.readUint32Array(2),this.matrix=t.readUint32Array(9),t.readUint32Array(6),this.next_track_id=t.readUint32()}),s.createBoxCtor("npck",function(t){this.packetssent=t.readUint32()}),s.createBoxCtor("nump",function(t){this.packetssent=t.readUint64()}),s.createFullBoxCtor("padb",function(t){var e=t.readUint32();this.padbits=[];for(var r=0;r<Math.floor((e+1)/2);r++)this.padbits=t.readUint8()}),s.createBoxCtor("pasp",function(t){this.hSpacing=t.readUint32(),this.vSpacing=t.readUint32()}),s.createBoxCtor("payl",function(t){this.text=t.readString(this.size-this.hdr_size)}),s.createBoxCtor("payt",function(t){this.payloadID=t.readUint32();var e=t.readUint8();this.rtpmap_string=t.readString(e)}),s.createFullBoxCtor("pdin",function(t){var e=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var r=0;r<e;r++)this.rate[r]=t.readUint32(),this.initial_delay[r]=t.readUint32()}),s.createFullBoxCtor("pitm",function(t){this.version===0?this.item_id=t.readUint16():this.item_id=t.readUint32()}),s.createFullBoxCtor("pixi",function(t){var e;for(this.num_channels=t.readUint8(),this.bits_per_channels=[],e=0;e<this.num_channels;e++)this.bits_per_channels[e]=t.readUint8()}),s.createBoxCtor("pmax",function(t){this.bytes=t.readUint32()}),s.createFullBoxCtor("prdi",function(t){if(this.step_count=t.readUint16(),this.item_count=[],this.flags&2)for(var e=0;e<this.step_count;e++)this.item_count[e]=t.readUint16()}),s.createFullBoxCtor("prft",function(t){this.ref_track_id=t.readUint32(),this.ntp_timestamp=t.readUint64(),this.version===0?this.media_time=t.readUint32():this.media_time=t.readUint64()}),s.createFullBoxCtor("pssh",function(t){if(this.system_id=s.parseHex16(t),this.version>0){var e=t.readUint32();this.kid=[];for(var r=0;r<e;r++)this.kid[r]=s.parseHex16(t)}var n=t.readUint32();n>0&&(this.data=t.readUint8Array(n))}),s.createFullBoxCtor("clef",function(t){this.width=t.readUint32(),this.height=t.readUint32()}),s.createFullBoxCtor("enof",function(t){this.width=t.readUint32(),this.height=t.readUint32()}),s.createFullBoxCtor("prof",function(t){this.width=t.readUint32(),this.height=t.readUint32()}),s.createContainerBoxCtor("tapt",null,["clef","prof","enof"]),s.createBoxCtor("rtp ",function(t){this.descriptionformat=t.readString(4),this.sdptext=t.readString(this.size-this.hdr_size-4)}),s.createFullBoxCtor("saio",function(t){this.flags&1&&(this.aux_info_type=t.readString(4),this.aux_info_type_parameter=t.readUint32());var e=t.readUint32();this.offset=[];for(var r=0;r<e;r++)this.version===0?this.offset[r]=t.readUint32():this.offset[r]=t.readUint64()}),s.createFullBoxCtor("saiz",function(t){if(this.flags&1&&(this.aux_info_type=t.readString(4),this.aux_info_type_parameter=t.readUint32()),this.default_sample_info_size=t.readUint8(),this.sample_count=t.readUint32(),this.sample_info_size=[],this.default_sample_info_size===0)for(var e=0;e<this.sample_count;e++)this.sample_info_size[e]=t.readUint8()}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"mett",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"metx",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.namespace=t.readCString(),this.schema_location=t.readCString(),this.parseFooter(t)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"sbtt",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"stpp",function(t){this.parseHeader(t),this.namespace=t.readCString(),this.schema_location=t.readCString(),this.auxiliary_mime_types=t.readCString(),this.parseFooter(t)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"stxt",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"tx3g",function(t){this.parseHeader(t),this.displayFlags=t.readUint32(),this.horizontal_justification=t.readInt8(),this.vertical_justification=t.readInt8(),this.bg_color_rgba=t.readUint8Array(4),this.box_record=t.readInt16Array(4),this.style_record=t.readUint8Array(12),this.parseFooter(t)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"wvtt",function(t){this.parseHeader(t),this.parseFooter(t)}),s.createSampleGroupCtor("alst",function(t){var e,r=t.readUint16();for(this.first_output_sample=t.readUint16(),this.sample_offset=[],e=0;e<r;e++)this.sample_offset[e]=t.readUint32();var n=this.description_length-4-4*r;for(this.num_output_samples=[],this.num_total_samples=[],e=0;e<n/4;e++)this.num_output_samples[e]=t.readUint16(),this.num_total_samples[e]=t.readUint16()}),s.createSampleGroupCtor("avll",function(t){this.layerNumber=t.readUint8(),this.accurateStatisticsFlag=t.readUint8(),this.avgBitRate=t.readUint16(),this.avgFrameRate=t.readUint16()}),s.createSampleGroupCtor("avss",function(t){this.subSequenceIdentifier=t.readUint16(),this.layerNumber=t.readUint8();var e=t.readUint8();this.durationFlag=e>>7,this.avgRateFlag=e>>6&1,this.durationFlag&&(this.duration=t.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=t.readUint8(),this.avgBitRate=t.readUint16(),this.avgFrameRate=t.readUint16()),this.dependency=[];for(var r=t.readUint8(),n=0;n<r;n++){var o={};this.dependency.push(o),o.subSeqDirectionFlag=t.readUint8(),o.layerNumber=t.readUint8(),o.subSequenceIdentifier=t.readUint16()}}),s.createSampleGroupCtor("dtrt",function(t){f.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("mvif",function(t){f.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("prol",function(t){this.roll_distance=t.readInt16()}),s.createSampleGroupCtor("rap ",function(t){var e=t.readUint8();this.num_leading_samples_known=e>>7,this.num_leading_samples=e&127}),s.createSampleGroupCtor("rash",function(t){if(this.operation_point_count=t.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)f.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=t.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=t.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(var e=0;e<this.operation_point_count;e++)this.available_bitrate[e]=t.readUint32(),this.target_rate_share[e]=t.readUint16()}this.maximum_bitrate=t.readUint32(),this.minimum_bitrate=t.readUint32(),this.discard_priority=t.readUint8()}}),s.createSampleGroupCtor("roll",function(t){this.roll_distance=t.readInt16()}),s.SampleGroupEntry.prototype.parse=function(t){f.warn("BoxParser","Unknown Sample Group type: "+this.grouping_type),this.data=t.readUint8Array(this.description_length)},s.createSampleGroupCtor("scif",function(t){f.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("scnm",function(t){f.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("seig",function(t){this.reserved=t.readUint8();var e=t.readUint8();this.crypt_byte_block=e>>4,this.skip_byte_block=e&15,this.isProtected=t.readUint8(),this.Per_Sample_IV_Size=t.readUint8(),this.KID=s.parseHex16(t),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=t.readUint8(),this.constant_IV=t.readUint8Array(this.constant_IV_size))}),s.createSampleGroupCtor("stsa",function(t){f.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("sync",function(t){var e=t.readUint8();this.NAL_unit_type=e&63}),s.createSampleGroupCtor("tele",function(t){var e=t.readUint8();this.level_independently_decodable=e>>7}),s.createSampleGroupCtor("tsas",function(t){f.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("tscl",function(t){f.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("vipr",function(t){f.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createFullBoxCtor("sbgp",function(t){this.grouping_type=t.readString(4),this.version===1?this.grouping_type_parameter=t.readUint32():this.grouping_type_parameter=0,this.entries=[];for(var e=t.readUint32(),r=0;r<e;r++){var n={};this.entries.push(n),n.sample_count=t.readInt32(),n.group_description_index=t.readInt32()}});function v(t,e){this.bad_pixel_row=t,this.bad_pixel_column=e}v.prototype.toString=function(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"},s.createFullBoxCtor("sbpm",function(t){var e;for(this.component_count=t.readUint16(),this.component_index=[],e=0;e<this.component_count;e++)this.component_index.push(t.readUint16());var r=t.readUint8();for(this.correction_applied=(r&128)==128,this.num_bad_rows=t.readUint32(),this.num_bad_cols=t.readUint32(),this.num_bad_pixels=t.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[],e=0;e<this.num_bad_rows;e++)this.bad_rows.push(t.readUint32());for(e=0;e<this.num_bad_cols;e++)this.bad_columns.push(t.readUint32());for(e=0;e<this.num_bad_pixels;e++){var n=t.readUint32(),o=t.readUint32();this.bad_pixels.push(new v(n,o))}}),s.createFullBoxCtor("schm",function(t){this.scheme_type=t.readString(4),this.scheme_version=t.readUint32(),this.flags&1&&(this.scheme_uri=t.readString(this.size-this.hdr_size-8))}),s.createBoxCtor("sdp ",function(t){this.sdptext=t.readString(this.size-this.hdr_size)}),s.createFullBoxCtor("sdtp",function(t){var e,r=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var n=0;n<r;n++)e=t.readUint8(),this.is_leading[n]=e>>6,this.sample_depends_on[n]=e>>4&3,this.sample_is_depended_on[n]=e>>2&3,this.sample_has_redundancy[n]=e&3}),s.createFullBoxCtor("senc"),s.createFullBoxCtor("sgpd",function(t){this.grouping_type=t.readString(4),f.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=t.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=t.readUint32()),this.entries=[];for(var e=t.readUint32(),r=0;r<e;r++){var n;s[this.grouping_type+"SampleGroupEntry"]?n=new s[this.grouping_type+"SampleGroupEntry"](this.grouping_type):n=new s.SampleGroupEntry(this.grouping_type),this.entries.push(n),this.version===1?this.default_length===0?n.description_length=t.readUint32():n.description_length=this.default_length:n.description_length=this.default_length,n.write===s.SampleGroupEntry.prototype.write&&(f.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),n.data=t.readUint8Array(n.description_length),t.position-=n.description_length),n.parse(t)}}),s.createFullBoxCtor("sidx",function(t){this.reference_ID=t.readUint32(),this.timescale=t.readUint32(),this.version===0?(this.earliest_presentation_time=t.readUint32(),this.first_offset=t.readUint32()):(this.earliest_presentation_time=t.readUint64(),this.first_offset=t.readUint64()),t.readUint16(),this.references=[];for(var e=t.readUint16(),r=0;r<e;r++){var n={};this.references.push(n);var o=t.readUint32();n.reference_type=o>>31&1,n.referenced_size=o&2147483647,n.subsegment_duration=t.readUint32(),o=t.readUint32(),n.starts_with_SAP=o>>31&1,n.SAP_type=o>>28&7,n.SAP_delta_time=o&268435455}}),s.SingleItemTypeReferenceBox=function(t,e,r,n){s.Box.call(this,t,e),this.hdr_size=r,this.start=n},s.SingleItemTypeReferenceBox.prototype=new s.Box,s.SingleItemTypeReferenceBox.prototype.parse=function(t){this.from_item_ID=t.readUint16();var e=t.readUint16();this.references=[];for(var r=0;r<e;r++)this.references[r]={},this.references[r].to_item_ID=t.readUint16()},s.SingleItemTypeReferenceBoxLarge=function(t,e,r,n){s.Box.call(this,t,e),this.hdr_size=r,this.start=n},s.SingleItemTypeReferenceBoxLarge.prototype=new s.Box,s.SingleItemTypeReferenceBoxLarge.prototype.parse=function(t){this.from_item_ID=t.readUint32();var e=t.readUint16();this.references=[];for(var r=0;r<e;r++)this.references[r]={},this.references[r].to_item_ID=t.readUint32()},s.createFullBoxCtor("SmDm",function(t){this.primaryRChromaticity_x=t.readUint16(),this.primaryRChromaticity_y=t.readUint16(),this.primaryGChromaticity_x=t.readUint16(),this.primaryGChromaticity_y=t.readUint16(),this.primaryBChromaticity_x=t.readUint16(),this.primaryBChromaticity_y=t.readUint16(),this.whitePointChromaticity_x=t.readUint16(),this.whitePointChromaticity_y=t.readUint16(),this.luminanceMax=t.readUint32(),this.luminanceMin=t.readUint32()}),s.createFullBoxCtor("smhd",function(t){this.balance=t.readUint16(),t.readUint16()}),s.createFullBoxCtor("ssix",function(t){this.subsegments=[];for(var e=t.readUint32(),r=0;r<e;r++){var n={};this.subsegments.push(n),n.ranges=[];for(var o=t.readUint32(),d=0;d<o;d++){var u={};n.ranges.push(u),u.level=t.readUint8(),u.range_size=t.readUint24()}}}),s.createFullBoxCtor("stco",function(t){var e;if(e=t.readUint32(),this.chunk_offsets=[],this.version===0)for(var r=0;r<e;r++)this.chunk_offsets.push(t.readUint32())}),s.createFullBoxCtor("stdp",function(t){var e=(this.size-this.hdr_size)/2;this.priority=[];for(var r=0;r<e;r++)this.priority[r]=t.readUint16()}),s.createFullBoxCtor("sthd"),s.createFullBoxCtor("stri",function(t){this.switch_group=t.readUint16(),this.alternate_group=t.readUint16(),this.sub_track_id=t.readUint32();var e=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(var r=0;r<e;r++)this.attribute_list[r]=t.readUint32()}),s.createFullBoxCtor("stsc",function(t){var e,r;if(e=t.readUint32(),this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(r=0;r<e;r++)this.first_chunk.push(t.readUint32()),this.samples_per_chunk.push(t.readUint32()),this.sample_description_index.push(t.readUint32())}),s.createFullBoxCtor("stsd",function(t){var e,r,n,o;for(this.entries=[],n=t.readUint32(),e=1;e<=n;e++)if(r=s.parseOneBox(t,!0,this.size-(t.getPosition()-this.start)),r.code===s.OK)s[r.type+"SampleEntry"]?(o=new s[r.type+"SampleEntry"](r.size),o.hdr_size=r.hdr_size,o.start=r.start):(f.warn("BoxParser","Unknown sample entry type: "+r.type),o=new s.SampleEntry(r.type,r.size,r.hdr_size,r.start)),o.write===s.SampleEntry.prototype.write&&(f.info("BoxParser","SampleEntry "+o.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),o.parseDataAndRewind(t)),o.parse(t),this.entries.push(o);else return}),s.createFullBoxCtor("stsg",function(t){this.grouping_type=t.readUint32();var e=t.readUint16();this.group_description_index=[];for(var r=0;r<e;r++)this.group_description_index[r]=t.readUint32()}),s.createFullBoxCtor("stsh",function(t){var e,r;if(e=t.readUint32(),this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(r=0;r<e;r++)this.shadowed_sample_numbers.push(t.readUint32()),this.sync_sample_numbers.push(t.readUint32())}),s.createFullBoxCtor("stss",function(t){var e,r;if(r=t.readUint32(),this.version===0)for(this.sample_numbers=[],e=0;e<r;e++)this.sample_numbers.push(t.readUint32())}),s.createFullBoxCtor("stsz",function(t){var e;if(this.sample_sizes=[],this.version===0)for(this.sample_size=t.readUint32(),this.sample_count=t.readUint32(),e=0;e<this.sample_count;e++)this.sample_size===0?this.sample_sizes.push(t.readUint32()):this.sample_sizes[e]=this.sample_size}),s.createFullBoxCtor("stts",function(t){var e,r,n;if(e=t.readUint32(),this.sample_counts=[],this.sample_deltas=[],this.version===0)for(r=0;r<e;r++)this.sample_counts.push(t.readUint32()),n=t.readInt32(),n<0&&(f.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),n=1),this.sample_deltas.push(n)}),s.createFullBoxCtor("stvi",function(t){var e=t.readUint32();this.single_view_allowed=e&3,this.stereo_scheme=t.readUint32();var r=t.readUint32();this.stereo_indication_type=t.readString(r);var n,o;for(this.boxes=[];t.getPosition()<this.start+this.size;)if(n=s.parseOneBox(t,!1,this.size-(t.getPosition()-this.start)),n.code===s.OK)o=n.box,this.boxes.push(o),this[o.type]=o;else return}),s.createBoxCtor("styp",function(t){s.ftypBox.prototype.parse.call(this,t)}),s.createFullBoxCtor("stz2",function(t){var e,r;if(this.sample_sizes=[],this.version===0)if(this.reserved=t.readUint24(),this.field_size=t.readUint8(),r=t.readUint32(),this.field_size===4)for(e=0;e<r;e+=2){var n=t.readUint8();this.sample_sizes[e]=n>>4&15,this.sample_sizes[e+1]=n&15}else if(this.field_size===8)for(e=0;e<r;e++)this.sample_sizes[e]=t.readUint8();else if(this.field_size===16)for(e=0;e<r;e++)this.sample_sizes[e]=t.readUint16();else f.error("BoxParser","Error in length field in stz2 box")}),s.createFullBoxCtor("subs",function(t){var e,r,n,o;for(n=t.readUint32(),this.entries=[],e=0;e<n;e++){var d={};if(this.entries[e]=d,d.sample_delta=t.readUint32(),d.subsamples=[],o=t.readUint16(),o>0)for(r=0;r<o;r++){var u={};d.subsamples.push(u),this.version==1?u.size=t.readUint32():u.size=t.readUint16(),u.priority=t.readUint8(),u.discardable=t.readUint8(),u.codec_specific_parameters=t.readUint32()}}}),s.createFullBoxCtor("tenc",function(t){if(t.readUint8(),this.version===0)t.readUint8();else{var e=t.readUint8();this.default_crypt_byte_block=e>>4&15,this.default_skip_byte_block=e&15}this.default_isProtected=t.readUint8(),this.default_Per_Sample_IV_Size=t.readUint8(),this.default_KID=s.parseHex16(t),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=t.readUint8(),this.default_constant_IV=t.readUint8Array(this.default_constant_IV_size))}),s.createFullBoxCtor("tfdt",function(t){this.version==1?this.baseMediaDecodeTime=t.readUint64():this.baseMediaDecodeTime=t.readUint32()}),s.createFullBoxCtor("tfhd",function(t){var e=0;this.track_id=t.readUint32(),this.size-this.hdr_size>e&&this.flags&s.TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=t.readUint64(),e+=8):this.base_data_offset=0,this.size-this.hdr_size>e&&this.flags&s.TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=t.readUint32(),e+=4):this.default_sample_description_index=0,this.size-this.hdr_size>e&&this.flags&s.TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=t.readUint32(),e+=4):this.default_sample_duration=0,this.size-this.hdr_size>e&&this.flags&s.TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=t.readUint32(),e+=4):this.default_sample_size=0,this.size-this.hdr_size>e&&this.flags&s.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=t.readUint32(),e+=4):this.default_sample_flags=0}),s.createFullBoxCtor("tfra",function(t){this.track_ID=t.readUint32(),t.readUint24();var e=t.readUint8();this.length_size_of_traf_num=e>>4&3,this.length_size_of_trun_num=e>>2&3,this.length_size_of_sample_num=e&3,this.entries=[];for(var r=t.readUint32(),n=0;n<r;n++)this.version===1?(this.time=t.readUint64(),this.moof_offset=t.readUint64()):(this.time=t.readUint32(),this.moof_offset=t.readUint32()),this.traf_number=t["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=t["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=t["readUint"+8*(this.length_size_of_sample_num+1)]()}),s.createFullBoxCtor("tkhd",function(t){this.version==1?(this.creation_time=t.readUint64(),this.modification_time=t.readUint64(),this.track_id=t.readUint32(),t.readUint32(),this.duration=t.readUint64()):(this.creation_time=t.readUint32(),this.modification_time=t.readUint32(),this.track_id=t.readUint32(),t.readUint32(),this.duration=t.readUint32()),t.readUint32Array(2),this.layer=t.readInt16(),this.alternate_group=t.readInt16(),this.volume=t.readInt16()>>8,t.readUint16(),this.matrix=t.readInt32Array(9),this.width=t.readUint32(),this.height=t.readUint32()}),s.createBoxCtor("tmax",function(t){this.time=t.readUint32()}),s.createBoxCtor("tmin",function(t){this.time=t.readUint32()}),s.createBoxCtor("totl",function(t){this.bytessent=t.readUint32()}),s.createBoxCtor("tpay",function(t){this.bytessent=t.readUint32()}),s.createBoxCtor("tpyl",function(t){this.bytessent=t.readUint64()}),s.TrackGroupTypeBox.prototype.parse=function(t){this.parseFullHeader(t),this.track_group_id=t.readUint32()},s.createTrackGroupCtor("msrc"),s.TrackReferenceTypeBox=function(t,e,r,n){s.Box.call(this,t,e),this.hdr_size=r,this.start=n},s.TrackReferenceTypeBox.prototype=new s.Box,s.TrackReferenceTypeBox.prototype.parse=function(t){this.track_ids=t.readUint32Array((this.size-this.hdr_size)/4)},s.trefBox.prototype.parse=function(t){for(var e,r;t.getPosition()<this.start+this.size;)if(e=s.parseOneBox(t,!0,this.size-(t.getPosition()-this.start)),e.code===s.OK)r=new s.TrackReferenceTypeBox(e.type,e.size,e.hdr_size,e.start),r.write===s.Box.prototype.write&&r.type!=="mdat"&&(f.info("BoxParser","TrackReference "+r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(t)),r.parse(t),this.boxes.push(r);else return},s.createFullBoxCtor("trep",function(t){for(this.track_ID=t.readUint32(),this.boxes=[];t.getPosition()<this.start+this.size;)if(ret=s.parseOneBox(t,!1,this.size-(t.getPosition()-this.start)),ret.code===s.OK)box=ret.box,this.boxes.push(box);else return}),s.createFullBoxCtor("trex",function(t){this.track_id=t.readUint32(),this.default_sample_description_index=t.readUint32(),this.default_sample_duration=t.readUint32(),this.default_sample_size=t.readUint32(),this.default_sample_flags=t.readUint32()}),s.createBoxCtor("trpy",function(t){this.bytessent=t.readUint64()}),s.createFullBoxCtor("trun",function(t){var e=0;if(this.sample_count=t.readUint32(),e+=4,this.size-this.hdr_size>e&&this.flags&s.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=t.readInt32(),e+=4):this.data_offset=0,this.size-this.hdr_size>e&&this.flags&s.TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=t.readUint32(),e+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>e)for(var r=0;r<this.sample_count;r++)this.flags&s.TRUN_FLAGS_DURATION&&(this.sample_duration[r]=t.readUint32()),this.flags&s.TRUN_FLAGS_SIZE&&(this.sample_size[r]=t.readUint32()),this.flags&s.TRUN_FLAGS_FLAGS&&(this.sample_flags[r]=t.readUint32()),this.flags&s.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?this.sample_composition_time_offset[r]=t.readUint32():this.sample_composition_time_offset[r]=t.readInt32())}),s.createFullBoxCtor("tsel",function(t){this.switch_group=t.readUint32();var e=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var r=0;r<e;r++)this.attribute_list[r]=t.readUint32()}),s.createFullBoxCtor("txtC",function(t){this.config=t.readCString()}),s.createBoxCtor("tyco",function(t){var e=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(var r=0;r<e;r++)this.compatible_brands[r]=t.readString(4)}),s.createFullBoxCtor("udes",function(t){this.lang=t.readCString(),this.name=t.readCString(),this.description=t.readCString(),this.tags=t.readCString()}),s.createFullBoxCtor("uncC",function(t){var e;if(this.profile=t.readUint32(),this.version!=1){if(this.version==0){for(this.component_count=t.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[],e=0;e<this.component_count;e++)this.component_index.push(t.readUint16()),this.component_bit_depth_minus_one.push(t.readUint8()),this.component_format.push(t.readUint8()),this.component_align_size.push(t.readUint8());this.sampling_type=t.readUint8(),this.interleave_type=t.readUint8(),this.block_size=t.readUint8();var r=t.readUint8();this.component_little_endian=r>>7&1,this.block_pad_lsb=r>>6&1,this.block_little_endian=r>>5&1,this.block_reversed=r>>4&1,this.pad_unknown=r>>3&1,this.pixel_size=t.readUint32(),this.row_align_size=t.readUint32(),this.tile_align_size=t.readUint32(),this.num_tile_cols_minus_one=t.readUint32(),this.num_tile_rows_minus_one=t.readUint32()}}}),s.createFullBoxCtor("url ",function(t){this.flags!==1&&(this.location=t.readCString())}),s.createFullBoxCtor("urn ",function(t){this.name=t.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=t.readCString())}),s.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66",!0,!1,function(t){this.LiveServerManifest=t.readString(this.size-this.hdr_size).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}),s.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3",!0,!1,function(t){this.system_id=s.parseHex16(t);var e=t.readUint32();e>0&&(this.data=t.readUint8Array(e))}),s.createUUIDBox("a2394f525a9b4f14a2446c427c648df4",!0,!1),s.createUUIDBox("8974dbce7be74c5184f97148f9882554",!0,!1,function(t){this.default_AlgorithmID=t.readUint24(),this.default_IV_size=t.readUint8(),this.default_KID=s.parseHex16(t)}),s.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f",!0,!1,function(t){this.fragment_count=t.readUint8(),this.entries=[];for(var e=0;e<this.fragment_count;e++){var r={},n=0,o=0;this.version===1?(n=t.readUint64(),o=t.readUint64()):(n=t.readUint32(),o=t.readUint32()),r.absolute_time=n,r.absolute_duration=o,this.entries.push(r)}}),s.createUUIDBox("6d1d9b0542d544e680e2141daff757b2",!0,!1,function(t){this.version===1?(this.absolute_time=t.readUint64(),this.duration=t.readUint64()):(this.absolute_time=t.readUint32(),this.duration=t.readUint32())}),s.createFullBoxCtor("vmhd",function(t){this.graphicsmode=t.readUint16(),this.opcolor=t.readUint16Array(3)}),s.createFullBoxCtor("vpcC",function(t){var e;this.version===1?(this.profile=t.readUint8(),this.level=t.readUint8(),e=t.readUint8(),this.bitDepth=e>>4,this.chromaSubsampling=e>>1&7,this.videoFullRangeFlag=e&1,this.colourPrimaries=t.readUint8(),this.transferCharacteristics=t.readUint8(),this.matrixCoefficients=t.readUint8(),this.codecIntializationDataSize=t.readUint16(),this.codecIntializationData=t.readUint8Array(this.codecIntializationDataSize)):(this.profile=t.readUint8(),this.level=t.readUint8(),e=t.readUint8(),this.bitDepth=e>>4&15,this.colorSpace=e&15,e=t.readUint8(),this.chromaSubsampling=e>>4&15,this.transferFunction=e>>1&7,this.videoFullRangeFlag=e&1,this.codecIntializationDataSize=t.readUint16(),this.codecIntializationData=t.readUint8Array(this.codecIntializationDataSize))}),s.createBoxCtor("vttC",function(t){this.text=t.readString(this.size-this.hdr_size)}),s.createFullBoxCtor("vvcC",function(t){var e,r,n={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(F){this.held_bits=F.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(F){this.held_bits=F.readUint16(),this.num_held_bits=16},extract_bits:function(F){var I=this.held_bits>>this.num_held_bits-F&(1<<F)-1;return this.num_held_bits-=F,I}};if(n.stream_read_1_bytes(t),n.extract_bits(5),this.lengthSizeMinusOne=n.extract_bits(2),this.ptl_present_flag=n.extract_bits(1),this.ptl_present_flag){n.stream_read_2_bytes(t),this.ols_idx=n.extract_bits(9),this.num_sublayers=n.extract_bits(3),this.constant_frame_rate=n.extract_bits(2),this.chroma_format_idc=n.extract_bits(2),n.stream_read_1_bytes(t),this.bit_depth_minus8=n.extract_bits(3),n.extract_bits(5);{if(n.stream_read_2_bytes(t),n.extract_bits(2),this.num_bytes_constraint_info=n.extract_bits(6),this.general_profile_idc=n.extract_bits(7),this.general_tier_flag=n.extract_bits(1),this.general_level_idc=t.readUint8(),n.stream_read_1_bytes(t),this.ptl_frame_only_constraint_flag=n.extract_bits(1),this.ptl_multilayer_enabled_flag=n.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(e=0;e<this.num_bytes_constraint_info-1;e++){var o=n.extract_bits(6);n.stream_read_1_bytes(t);var d=n.extract_bits(2);this.general_constraint_info[e]=o<<2|d}this.general_constraint_info[this.num_bytes_constraint_info-1]=n.extract_bits(6)}else n.extract_bits(6);if(this.num_sublayers>1){for(n.stream_read_1_bytes(t),this.ptl_sublayer_present_mask=0,r=this.num_sublayers-2;r>=0;--r){var u=n.extract_bits(1);this.ptl_sublayer_present_mask|=u<<r}for(r=this.num_sublayers;r<=8&&this.num_sublayers>1;++r)n.extract_bits(1);for(this.sublayer_level_idc=[],r=this.num_sublayers-2;r>=0;--r)this.ptl_sublayer_present_mask&1<<r&&(this.sublayer_level_idc[r]=t.readUint8())}if(this.ptl_num_sub_profiles=t.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(e=0;e<this.ptl_num_sub_profiles;e++)this.general_sub_profile_idc.push(t.readUint32())}this.max_picture_width=t.readUint16(),this.max_picture_height=t.readUint16(),this.avg_frame_rate=t.readUint16()}var _=12,U=13;this.nalu_arrays=[];var S=t.readUint8();for(e=0;e<S;e++){var b=[];this.nalu_arrays.push(b),n.stream_read_1_bytes(t),b.completeness=n.extract_bits(1),n.extract_bits(2),b.nalu_type=n.extract_bits(5);var E=1;for(b.nalu_type!=U&&b.nalu_type!=_&&(E=t.readUint16()),r=0;r<E;r++){var B=t.readUint16();b.push({data:t.readUint8Array(B),length:B})}}}),s.createFullBoxCtor("vvnC",function(t){var e=strm.readUint8();this.lengthSizeMinusOne=e&3}),s.SampleEntry.prototype.isVideo=function(){return!1},s.SampleEntry.prototype.isAudio=function(){return!1},s.SampleEntry.prototype.isSubtitle=function(){return!1},s.SampleEntry.prototype.isMetadata=function(){return!1},s.SampleEntry.prototype.isHint=function(){return!1},s.SampleEntry.prototype.getCodec=function(){return this.type.replace(".","")},s.SampleEntry.prototype.getWidth=function(){return""},s.SampleEntry.prototype.getHeight=function(){return""},s.SampleEntry.prototype.getChannelCount=function(){return""},s.SampleEntry.prototype.getSampleRate=function(){return""},s.SampleEntry.prototype.getSampleSize=function(){return""},s.VisualSampleEntry.prototype.isVideo=function(){return!0},s.VisualSampleEntry.prototype.getWidth=function(){return this.width},s.VisualSampleEntry.prototype.getHeight=function(){return this.height},s.AudioSampleEntry.prototype.isAudio=function(){return!0},s.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_count},s.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},s.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},s.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},s.MetadataSampleEntry.prototype.isMetadata=function(){return!0},s.decimalToHex=function(t,e){var r=Number(t).toString(16);for(e=typeof e>"u"||e===null?e=2:e;r.length<e;)r="0"+r;return r},s.avc1SampleEntry.prototype.getCodec=s.avc2SampleEntry.prototype.getCodec=s.avc3SampleEntry.prototype.getCodec=s.avc4SampleEntry.prototype.getCodec=function(){var t=s.SampleEntry.prototype.getCodec.call(this);return this.avcC?t+"."+s.decimalToHex(this.avcC.AVCProfileIndication)+s.decimalToHex(this.avcC.profile_compatibility)+s.decimalToHex(this.avcC.AVCLevelIndication):t},s.hev1SampleEntry.prototype.getCodec=s.hvc1SampleEntry.prototype.getCodec=function(){var t,e=s.SampleEntry.prototype.getCodec.call(this);if(this.hvcC){switch(e+=".",this.hvcC.general_profile_space){case 0:e+="";break;case 1:e+="A";break;case 2:e+="B";break;case 3:e+="C";break}e+=this.hvcC.general_profile_idc,e+=".";var r=this.hvcC.general_profile_compatibility,n=0;for(t=0;t<32&&(n|=r&1,t!=31);t++)n<<=1,r>>=1;e+=s.decimalToHex(n,0),e+=".",this.hvcC.general_tier_flag===0?e+="L":e+="H",e+=this.hvcC.general_level_idc;var o=!1,d="";for(t=5;t>=0;t--)(this.hvcC.general_constraint_indicator[t]||o)&&(d="."+s.decimalToHex(this.hvcC.general_constraint_indicator[t],0)+d,o=!0);e+=d}return e},s.vvc1SampleEntry.prototype.getCodec=s.vvi1SampleEntry.prototype.getCodec=function(){var t,e=s.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){e+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?e+=".H":e+=".L",e+=this.vvcC.general_level_idc;var r="";if(this.vvcC.general_constraint_info){var n=[],o=0;o|=this.vvcC.ptl_frame_only_constraint<<7,o|=this.vvcC.ptl_multilayer_enabled<<6;var d;for(t=0;t<this.vvcC.general_constraint_info.length;++t)o|=this.vvcC.general_constraint_info[t]>>2&63,n.push(o),o&&(d=t),o=this.vvcC.general_constraint_info[t]>>2&3;if(d===void 0)r=".CA";else{r=".C";var u="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",_=0,U=0;for(t=0;t<=d;++t)for(_=_<<8|n[t],U+=8;U>=5;){var S=_>>U-5&31;r+=u[S],U-=5,_&=(1<<U)-1}U&&(_<<=5-U,r+=u[_&31])}}e+=r}return e},s.mp4aSampleEntry.prototype.getCodec=function(){var t=s.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var e=this.esds.esd.getOTI(),r=this.esds.esd.getAudioConfig();return t+"."+s.decimalToHex(e)+(r?"."+r:"")}else return t},s.stxtSampleEntry.prototype.getCodec=function(){var t=s.SampleEntry.prototype.getCodec.call(this);return this.mime_format?t+"."+this.mime_format:t},s.vp08SampleEntry.prototype.getCodec=s.vp09SampleEntry.prototype.getCodec=function(){var t=s.SampleEntry.prototype.getCodec.call(this),e=this.vpcC.level;e==0&&(e="00");var r=this.vpcC.bitDepth;return r==8&&(r="08"),t+".0"+this.vpcC.profile+"."+e+"."+r},s.av01SampleEntry.prototype.getCodec=function(){var t=s.SampleEntry.prototype.getCodec.call(this),e=this.av1C.seq_level_idx_0;e<10&&(e="0"+e);var r;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?r=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(r=this.av1C.high_bitdepth===1?"10":"08"),t+"."+this.av1C.seq_profile+"."+e+(this.av1C.seq_tier_0?"H":"M")+"."+r},s.Box.prototype.writeHeader=function(t,e){this.size+=8,this.size>c&&(this.size+=8),this.type==="uuid"&&(this.size+=16),f.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+t.getPosition()+(e||"")),this.size>c?t.writeUint32(1):(this.sizePosition=t.getPosition(),t.writeUint32(this.size)),t.writeString(this.type,null,4),this.type==="uuid"&&t.writeUint8Array(this.uuid),this.size>c&&t.writeUint64(this.size)},s.FullBox.prototype.writeHeader=function(t){this.size+=4,s.Box.prototype.writeHeader.call(this,t," v="+this.version+" f="+this.flags),t.writeUint8(this.version),t.writeUint24(this.flags)},s.Box.prototype.write=function(t){this.type==="mdat"?this.data&&(this.size=this.data.length,this.writeHeader(t),t.writeUint8Array(this.data)):(this.size=this.data?this.data.length:0,this.writeHeader(t),this.data&&t.writeUint8Array(this.data))},s.ContainerBox.prototype.write=function(t){this.size=0,this.writeHeader(t);for(var e=0;e<this.boxes.length;e++)this.boxes[e]&&(this.boxes[e].write(t),this.size+=this.boxes[e].size);f.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},s.TrackReferenceTypeBox.prototype.write=function(t){this.size=this.track_ids.length*4,this.writeHeader(t),t.writeUint32Array(this.track_ids)},s.avcCBox.prototype.write=function(t){var e;for(this.size=7,e=0;e<this.SPS.length;e++)this.size+=2+this.SPS[e].length;for(e=0;e<this.PPS.length;e++)this.size+=2+this.PPS[e].length;for(this.ext&&(this.size+=this.ext.length),this.writeHeader(t),t.writeUint8(this.configurationVersion),t.writeUint8(this.AVCProfileIndication),t.writeUint8(this.profile_compatibility),t.writeUint8(this.AVCLevelIndication),t.writeUint8(this.lengthSizeMinusOne+252),t.writeUint8(this.SPS.length+224),e=0;e<this.SPS.length;e++)t.writeUint16(this.SPS[e].length),t.writeUint8Array(this.SPS[e].nalu);for(t.writeUint8(this.PPS.length),e=0;e<this.PPS.length;e++)t.writeUint16(this.PPS[e].length),t.writeUint8Array(this.PPS[e].nalu);this.ext&&t.writeUint8Array(this.ext)},s.co64Box.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(t),t.writeUint32(this.chunk_offsets.length),e=0;e<this.chunk_offsets.length;e++)t.writeUint64(this.chunk_offsets[e])},s.cslgBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(t),t.writeInt32(this.compositionToDTSShift),t.writeInt32(this.leastDecodeToDisplayDelta),t.writeInt32(this.greatestDecodeToDisplayDelta),t.writeInt32(this.compositionStartTime),t.writeInt32(this.compositionEndTime)},s.cttsBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(t),t.writeUint32(this.sample_counts.length),e=0;e<this.sample_counts.length;e++)t.writeUint32(this.sample_counts[e]),this.version===1?t.writeInt32(this.sample_offsets[e]):t.writeUint32(this.sample_offsets[e])},s.drefBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.entries.length);for(var e=0;e<this.entries.length;e++)this.entries[e].write(t),this.size+=this.entries[e].size;f.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},s.elngBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(t),t.writeString(this.extended_language)},s.elstBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4+12*this.entries.length,this.writeHeader(t),t.writeUint32(this.entries.length);for(var e=0;e<this.entries.length;e++){var r=this.entries[e];t.writeUint32(r.segment_duration),t.writeInt32(r.media_time),t.writeInt16(r.media_rate_integer),t.writeInt16(r.media_rate_fraction)}},s.emsgBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4*4+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(t),t.writeCString(this.scheme_id_uri),t.writeCString(this.value),t.writeUint32(this.timescale),t.writeUint32(this.presentation_time_delta),t.writeUint32(this.event_duration),t.writeUint32(this.id),t.writeUint8Array(this.message_data)},s.ftypBox.prototype.write=function(t){this.size=8+4*this.compatible_brands.length,this.writeHeader(t),t.writeString(this.major_brand,null,4),t.writeUint32(this.minor_version);for(var e=0;e<this.compatible_brands.length;e++)t.writeString(this.compatible_brands[e],null,4)},s.hdlrBox.prototype.write=function(t){this.size=5*4+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(t),t.writeUint32(0),t.writeString(this.handler,null,4),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeCString(this.name)},s.hvcCBox.prototype.write=function(t){var e,r;for(this.size=23,e=0;e<this.nalu_arrays.length;e++)for(this.size+=3,r=0;r<this.nalu_arrays[e].length;r++)this.size+=2+this.nalu_arrays[e][r].data.length;for(this.writeHeader(t),t.writeUint8(this.configurationVersion),t.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),t.writeUint32(this.general_profile_compatibility),t.writeUint8Array(this.general_constraint_indicator),t.writeUint8(this.general_level_idc),t.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),t.writeUint8(this.parallelismType+252),t.writeUint8(this.chroma_format_idc+252),t.writeUint8(this.bit_depth_luma_minus8+248),t.writeUint8(this.bit_depth_chroma_minus8+248),t.writeUint16(this.avgFrameRate),t.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),t.writeUint8(this.nalu_arrays.length),e=0;e<this.nalu_arrays.length;e++)for(t.writeUint8((this.nalu_arrays[e].completeness<<7)+this.nalu_arrays[e].nalu_type),t.writeUint16(this.nalu_arrays[e].length),r=0;r<this.nalu_arrays[e].length;r++)t.writeUint16(this.nalu_arrays[e][r].data.length),t.writeUint8Array(this.nalu_arrays[e][r].data)},s.kindBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value.length+1),this.writeHeader(t),t.writeCString(this.schemeURI),t.writeCString(this.value)},s.mdhdBox.prototype.write=function(t){this.size=4*4+2*2,this.flags=0,this.version=0,this.writeHeader(t),t.writeUint32(this.creation_time),t.writeUint32(this.modification_time),t.writeUint32(this.timescale),t.writeUint32(this.duration),t.writeUint16(this.language),t.writeUint16(0)},s.mehdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.fragment_duration)},s.mfhdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.sequence_number)},s.mvhdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=23*4+2*2,this.writeHeader(t),t.writeUint32(this.creation_time),t.writeUint32(this.modification_time),t.writeUint32(this.timescale),t.writeUint32(this.duration),t.writeUint32(this.rate),t.writeUint16(this.volume<<8),t.writeUint16(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32Array(this.matrix),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(this.next_track_id)},s.SampleEntry.prototype.writeHeader=function(t){this.size=8,s.Box.prototype.writeHeader.call(this,t),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint16(this.data_reference_index)},s.SampleEntry.prototype.writeFooter=function(t){for(var e=0;e<this.boxes.length;e++)this.boxes[e].write(t),this.size+=this.boxes[e].size;f.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},s.SampleEntry.prototype.write=function(t){this.writeHeader(t),t.writeUint8Array(this.data),this.size+=this.data.length,f.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},s.VisualSampleEntry.prototype.write=function(t){this.writeHeader(t),this.size+=2*7+6*4+32,t.writeUint16(0),t.writeUint16(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint16(this.width),t.writeUint16(this.height),t.writeUint32(this.horizresolution),t.writeUint32(this.vertresolution),t.writeUint32(0),t.writeUint16(this.frame_count),t.writeUint8(Math.min(31,this.compressorname.length)),t.writeString(this.compressorname,null,31),t.writeUint16(this.depth),t.writeInt16(-1),this.writeFooter(t)},s.AudioSampleEntry.prototype.write=function(t){this.writeHeader(t),this.size+=2*4+3*4,t.writeUint32(0),t.writeUint32(0),t.writeUint16(this.channel_count),t.writeUint16(this.samplesize),t.writeUint16(0),t.writeUint16(0),t.writeUint32(this.samplerate<<16),this.writeFooter(t)},s.stppSampleEntry.prototype.write=function(t){this.writeHeader(t),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,t.writeCString(this.namespace),t.writeCString(this.schema_location),t.writeCString(this.auxiliary_mime_types),this.writeFooter(t)},s.SampleGroupEntry.prototype.write=function(t){t.writeUint8Array(this.data)},s.sbgpBox.prototype.write=function(t){this.version=1,this.flags=0,this.size=12+8*this.entries.length,this.writeHeader(t),t.writeString(this.grouping_type,null,4),t.writeUint32(this.grouping_type_parameter),t.writeUint32(this.entries.length);for(var e=0;e<this.entries.length;e++){var r=this.entries[e];t.writeInt32(r.sample_count),t.writeInt32(r.group_description_index)}},s.sgpdBox.prototype.write=function(t){var e,r;for(this.flags=0,this.size=12,e=0;e<this.entries.length;e++)r=this.entries[e],this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=r.data.length);for(this.writeHeader(t),t.writeString(this.grouping_type,null,4),this.version===1&&t.writeUint32(this.default_length),this.version>=2&&t.writeUint32(this.default_sample_description_index),t.writeUint32(this.entries.length),e=0;e<this.entries.length;e++)r=this.entries[e],this.version===1&&this.default_length===0&&t.writeUint32(r.description_length),r.write(t)},s.sidxBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4*4+2+2+12*this.references.length,this.writeHeader(t),t.writeUint32(this.reference_ID),t.writeUint32(this.timescale),t.writeUint32(this.earliest_presentation_time),t.writeUint32(this.first_offset),t.writeUint16(0),t.writeUint16(this.references.length);for(var e=0;e<this.references.length;e++){var r=this.references[e];t.writeUint32(r.reference_type<<31|r.referenced_size),t.writeUint32(r.subsegment_duration),t.writeUint32(r.starts_with_SAP<<31|r.SAP_type<<28|r.SAP_delta_time)}},s.smhdBox.prototype.write=function(t){this.version=0,this.flags=1,this.size=4,this.writeHeader(t),t.writeUint16(this.balance),t.writeUint16(0)},s.stcoBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(t),t.writeUint32(this.chunk_offsets.length),t.writeUint32Array(this.chunk_offsets)},s.stscBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(t),t.writeUint32(this.first_chunk.length),e=0;e<this.first_chunk.length;e++)t.writeUint32(this.first_chunk[e]),t.writeUint32(this.samples_per_chunk[e]),t.writeUint32(this.sample_description_index[e])},s.stsdBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=0,this.writeHeader(t),t.writeUint32(this.entries.length),this.size+=4,e=0;e<this.entries.length;e++)this.entries[e].write(t),this.size+=this.entries[e].size;f.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},s.stshBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(t),t.writeUint32(this.shadowed_sample_numbers.length),e=0;e<this.shadowed_sample_numbers.length;e++)t.writeUint32(this.shadowed_sample_numbers[e]),t.writeUint32(this.sync_sample_numbers[e])},s.stssBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(t),t.writeUint32(this.sample_numbers.length),t.writeUint32Array(this.sample_numbers)},s.stszBox.prototype.write=function(t){var e,r=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0)for(e=0;e+1<this.sample_sizes.length;)if(this.sample_sizes[e+1]!==this.sample_sizes[0]){r=!1;break}else e++;else r=!1;this.size=8,r||(this.size+=4*this.sample_sizes.length),this.writeHeader(t),r?t.writeUint32(this.sample_sizes[0]):t.writeUint32(0),t.writeUint32(this.sample_sizes.length),r||t.writeUint32Array(this.sample_sizes)},s.sttsBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(t),t.writeUint32(this.sample_counts.length),e=0;e<this.sample_counts.length;e++)t.writeUint32(this.sample_counts[e]),t.writeUint32(this.sample_deltas[e])},s.tfdtBox.prototype.write=function(t){var e=Math.pow(2,32)-1;this.version=this.baseMediaDecodeTime>e?1:0,this.flags=0,this.size=4,this.version===1&&(this.size+=4),this.writeHeader(t),this.version===1?t.writeUint64(this.baseMediaDecodeTime):t.writeUint32(this.baseMediaDecodeTime)},s.tfhdBox.prototype.write=function(t){this.version=0,this.size=4,this.flags&s.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&s.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&s.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&s.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&s.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(t),t.writeUint32(this.track_id),this.flags&s.TFHD_FLAG_BASE_DATA_OFFSET&&t.writeUint64(this.base_data_offset),this.flags&s.TFHD_FLAG_SAMPLE_DESC&&t.writeUint32(this.default_sample_description_index),this.flags&s.TFHD_FLAG_SAMPLE_DUR&&t.writeUint32(this.default_sample_duration),this.flags&s.TFHD_FLAG_SAMPLE_SIZE&&t.writeUint32(this.default_sample_size),this.flags&s.TFHD_FLAG_SAMPLE_FLAGS&&t.writeUint32(this.default_sample_flags)},s.tkhdBox.prototype.write=function(t){this.version=0,this.size=4*18+2*4,this.writeHeader(t),t.writeUint32(this.creation_time),t.writeUint32(this.modification_time),t.writeUint32(this.track_id),t.writeUint32(0),t.writeUint32(this.duration),t.writeUint32(0),t.writeUint32(0),t.writeInt16(this.layer),t.writeInt16(this.alternate_group),t.writeInt16(this.volume<<8),t.writeUint16(0),t.writeInt32Array(this.matrix),t.writeUint32(this.width),t.writeUint32(this.height)},s.trexBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(t),t.writeUint32(this.track_id),t.writeUint32(this.default_sample_description_index),t.writeUint32(this.default_sample_duration),t.writeUint32(this.default_sample_size),t.writeUint32(this.default_sample_flags)},s.trunBox.prototype.write=function(t){this.version=0,this.size=4,this.flags&s.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&s.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&s.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&s.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&s.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&s.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(t),t.writeUint32(this.sample_count),this.flags&s.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=t.getPosition(),t.writeInt32(this.data_offset)),this.flags&s.TRUN_FLAGS_FIRST_FLAG&&t.writeUint32(this.first_sample_flags);for(var e=0;e<this.sample_count;e++)this.flags&s.TRUN_FLAGS_DURATION&&t.writeUint32(this.sample_duration[e]),this.flags&s.TRUN_FLAGS_SIZE&&t.writeUint32(this.sample_size[e]),this.flags&s.TRUN_FLAGS_FLAGS&&t.writeUint32(this.sample_flags[e]),this.flags&s.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?t.writeUint32(this.sample_composition_time_offset[e]):t.writeInt32(this.sample_composition_time_offset[e]))},s["url Box"].prototype.write=function(t){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(t),this.location&&t.writeCString(this.location)},s["urn Box"].prototype.write=function(t){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(t),t.writeCString(this.name),this.location&&t.writeCString(this.location)},s.vmhdBox.prototype.write=function(t){this.version=0,this.flags=1,this.size=8,this.writeHeader(t),t.writeUint16(this.graphicsmode),t.writeUint16Array(this.opcolor)},s.cttsBox.prototype.unpack=function(t){var e,r,n;for(n=0,e=0;e<this.sample_counts.length;e++)for(r=0;r<this.sample_counts[e];r++)t[n].pts=t[n].dts+this.sample_offsets[e],n++},s.sttsBox.prototype.unpack=function(t){var e,r,n;for(n=0,e=0;e<this.sample_counts.length;e++)for(r=0;r<this.sample_counts[e];r++)n===0?t[n].dts=0:t[n].dts=t[n-1].dts+this.sample_deltas[e],n++},s.stcoBox.prototype.unpack=function(t){var e;for(e=0;e<this.chunk_offsets.length;e++)t[e].offset=this.chunk_offsets[e]},s.stscBox.prototype.unpack=function(t){var e,r,n,o,d;for(o=0,d=0,e=0;e<this.first_chunk.length;e++)for(r=0;r<(e+1<this.first_chunk.length?this.first_chunk[e+1]:1/0);r++)for(d++,n=0;n<this.samples_per_chunk[e];n++){if(t[o])t[o].description_index=this.sample_description_index[e],t[o].chunk_index=d;else return;o++}},s.stszBox.prototype.unpack=function(t){var e;for(e=0;e<this.sample_sizes.length;e++)t[e].size=this.sample_sizes[e]},s.DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],s.DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"],s.boxEqualFields=function(t,e){if(t&&!e)return!1;var r;for(r in t)if(!(s.DIFF_BOXES_PROP_NAMES.indexOf(r)>-1)){if(t[r]instanceof s.Box||e[r]instanceof s.Box)continue;if(typeof t[r]>"u"||typeof e[r]>"u")continue;if(typeof t[r]=="function"||typeof e[r]=="function")continue;if(t.subBoxNames&&t.subBoxNames.indexOf(r.slice(0,4))>-1||e.subBoxNames&&e.subBoxNames.indexOf(r.slice(0,4))>-1)continue;if(r==="data"||r==="start"||r==="size"||r==="creation_time"||r==="modification_time")continue;if(s.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(r)>-1)continue;if(t[r]!==e[r])return!1}return!0},s.boxEqual=function(t,e){if(!s.boxEqualFields(t,e))return!1;for(var r=0;r<s.DIFF_BOXES_PROP_NAMES.length;r++){var n=s.DIFF_BOXES_PROP_NAMES[r];if(t[n]&&e[n]&&!s.boxEqual(t[n],e[n]))return!1}return!0};var x=function(){};x.prototype.parseSample=function(t){var e,r,n=new h(t.buffer);for(e=[];!n.isEos();)r=s.parseOneBox(n,!1),r.code===s.OK&&r.box.type==="vttc"&&e.push(r.box);return e},x.prototype.getText=function(t,e,r){function n(S,b,E){return E=E||"0",S=S+"",S.length>=b?S:new Array(b-S.length+1).join(E)+S}function o(S){var b=Math.floor(S/3600),E=Math.floor((S-b*3600)/60),B=Math.floor(S-b*3600-E*60),F=Math.floor((S-b*3600-E*60-B)*1e3);return""+n(b,2)+":"+n(E,2)+":"+n(B,2)+"."+n(F,3)}for(var d=this.parseSample(r),u="",_=0;_<d.length;_++){var U=d[_];u+=o(t)+" --> "+o(e)+\`\\r
2
- \`,u+=U.payl.text}return u};var m=function(){};m.prototype.parseSample=function(t){var e={},r;e.resources=[];var n=new h(t.data.buffer);if(!t.subsamples||t.subsamples.length===0)e.documentString=n.readString(t.data.length);else if(e.documentString=n.readString(t.subsamples[0].size),t.subsamples.length>1)for(r=1;r<t.subsamples.length;r++)e.resources[r]=n.readUint8Array(t.subsamples[r].size);return typeof DOMParser<"u"&&(e.document=new DOMParser().parseFromString(e.documentString,"application/xml")),e};var w=function(){};w.prototype.parseSample=function(t){var e,r=new h(t.data.buffer);return e=r.readString(t.data.length),e},w.prototype.parseConfig=function(t){var e,r=new h(t.buffer);return r.readUint32(),e=r.readCString(),e},C.VTTin4Parser=x,C.XMLSubtitlein4Parser=m,C.Textin4Parser=w;var y=function(t){this.stream=t||new l,this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.onMoovStart=null,this.moovStartSent=!1,this.onReady=null,this.readySent=!1,this.onSegment=null,this.onSamples=null,this.onError=null,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.items=[],this.entity_groups=[],this.onSidx=null,this.sidxSent=!1};y.prototype.setSegmentOptions=function(t,e,r){var n=this.getTrackById(t);if(n){var o={};this.fragmentedTracks.push(o),o.id=t,o.user=e,o.trak=n,n.nextSample=0,o.segmentStream=null,o.nb_samples=1e3,o.rapAlignement=!0,r&&(r.nbSamples&&(o.nb_samples=r.nbSamples),r.rapAlignement&&(o.rapAlignement=r.rapAlignement))}},y.prototype.unsetSegmentOptions=function(t){for(var e=-1,r=0;r<this.fragmentedTracks.length;r++){var n=this.fragmentedTracks[r];n.id==t&&(e=r)}e>-1&&this.fragmentedTracks.splice(e,1)},y.prototype.setExtractionOptions=function(t,e,r){var n=this.getTrackById(t);if(n){var o={};this.extractedTracks.push(o),o.id=t,o.user=e,o.trak=n,n.nextSample=0,o.nb_samples=1e3,o.samples=[],r&&r.nbSamples&&(o.nb_samples=r.nbSamples)}},y.prototype.unsetExtractionOptions=function(t){for(var e=-1,r=0;r<this.extractedTracks.length;r++){var n=this.extractedTracks[r];n.id==t&&(e=r)}e>-1&&this.extractedTracks.splice(e,1)},y.prototype.parse=function(){var t,e,r=!1;if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else if(this.saveParsePosition&&this.saveParsePosition(),t=s.parseOneBox(this.stream,r),t.code===s.ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(t))continue;return}else return;else{var n;switch(e=t.box,n=e.type!=="uuid"?e.type:e.uuid,this.boxes.push(e),n){case"mdat":this.mdats.push(e);break;case"moof":this.moofs.push(e);break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[n]!==void 0&&f.warn("ISOFile","Duplicate Box of type: "+n+", overriding previous occurrence"),this[n]=e;break}this.updateUsedBytes&&this.updateUsedBytes(e,t)}},y.prototype.checkBuffer=function(t){if(t==null)throw"Buffer must be defined and non empty";if(t.fileStart===void 0)throw"Buffer must have a fileStart property";return t.byteLength===0?(f.warn("ISOFile","Ignoring empty buffer (fileStart: "+t.fileStart+")"),this.stream.logBufferLevel(),!1):(f.info("ISOFile","Processing buffer (fileStart: "+t.fileStart+")"),t.usedBytes=0,this.stream.insertBuffer(t),this.stream.logBufferLevel(),this.stream.initialized()?!0:(f.warn("ISOFile","Not ready to start parsing"),!1))},y.prototype.appendBuffer=function(t,e){var r;if(this.checkBuffer(t))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(e),this.nextSeekPosition?(r=this.nextSeekPosition,this.nextSeekPosition=void 0):r=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(r=this.stream.getEndFilePositionAfter(r))):this.nextParsePosition?r=this.nextParsePosition:r=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(f.info("ISOFile","Done processing buffer (fileStart: "+t.fileStart+") - next buffer to fetch should have a fileStart position of "+r),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),f.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),r},y.prototype.getInfo=function(){var t,e,r={},n,o,d,u,_=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(r.hasMoov=!0,r.duration=this.moov.mvhd.duration,r.timescale=this.moov.mvhd.timescale,r.isFragmented=this.moov.mvex!=null,r.isFragmented&&this.moov.mvex.mehd&&(r.fragment_duration=this.moov.mvex.mehd.fragment_duration),r.isProgressive=this.isProgressive,r.hasIOD=this.moov.iods!=null,r.brands=[],r.brands.push(this.ftyp.major_brand),r.brands=r.brands.concat(this.ftyp.compatible_brands),r.created=new Date(_+this.moov.mvhd.creation_time*1e3),r.modified=new Date(_+this.moov.mvhd.modification_time*1e3),r.tracks=[],r.audioTracks=[],r.videoTracks=[],r.subtitleTracks=[],r.metadataTracks=[],r.hintTracks=[],r.otherTracks=[],t=0;t<this.moov.traks.length;t++){if(n=this.moov.traks[t],u=n.mdia.minf.stbl.stsd.entries[0],o={},r.tracks.push(o),o.id=n.tkhd.track_id,o.name=n.mdia.hdlr.name,o.references=[],n.tref)for(e=0;e<n.tref.boxes.length;e++)d={},o.references.push(d),d.type=n.tref.boxes[e].type,d.track_ids=n.tref.boxes[e].track_ids;n.edts&&(o.edits=n.edts.elst.entries),o.created=new Date(_+n.tkhd.creation_time*1e3),o.modified=new Date(_+n.tkhd.modification_time*1e3),o.movie_duration=n.tkhd.duration,o.movie_timescale=r.timescale,o.layer=n.tkhd.layer,o.alternate_group=n.tkhd.alternate_group,o.volume=n.tkhd.volume,o.matrix=n.tkhd.matrix,o.track_width=n.tkhd.width/65536,o.track_height=n.tkhd.height/65536,o.timescale=n.mdia.mdhd.timescale,o.cts_shift=n.mdia.minf.stbl.cslg,o.duration=n.mdia.mdhd.duration,o.samples_duration=n.samples_duration,o.codec=u.getCodec(),o.kind=n.udta&&n.udta.kinds.length?n.udta.kinds[0]:{schemeURI:"",value:""},o.language=n.mdia.elng?n.mdia.elng.extended_language:n.mdia.mdhd.languageString,o.nb_samples=n.samples.length,o.size=n.samples_size,o.bitrate=o.size*8*o.timescale/o.samples_duration,u.isAudio()?(o.type="audio",r.audioTracks.push(o),o.audio={},o.audio.sample_rate=u.getSampleRate(),o.audio.channel_count=u.getChannelCount(),o.audio.sample_size=u.getSampleSize()):u.isVideo()?(o.type="video",r.videoTracks.push(o),o.video={},o.video.width=u.getWidth(),o.video.height=u.getHeight()):u.isSubtitle()?(o.type="subtitles",r.subtitleTracks.push(o)):u.isHint()?(o.type="metadata",r.hintTracks.push(o)):u.isMetadata()?(o.type="metadata",r.metadataTracks.push(o)):(o.type="metadata",r.otherTracks.push(o))}else r.hasMoov=!1;if(r.mime="",r.hasMoov&&r.tracks){for(r.videoTracks&&r.videoTracks.length>0?r.mime+='video/mp4; codecs="':r.audioTracks&&r.audioTracks.length>0?r.mime+='audio/mp4; codecs="':r.mime+='application/mp4; codecs="',t=0;t<r.tracks.length;t++)t!==0&&(r.mime+=","),r.mime+=r.tracks[t].codec;r.mime+='"; profiles="',r.mime+=this.ftyp.compatible_brands.join(),r.mime+='"'}return r},y.prototype.setNextSeekPositionFromSample=function(t){t&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(t.offset+t.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=t.offset+t.alreadyRead)},y.prototype.processSamples=function(t){var e,r;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==null)for(e=0;e<this.fragmentedTracks.length;e++){var n=this.fragmentedTracks[e];for(r=n.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){f.debug("ISOFile","Creating media fragment on track #"+n.id+" for sample "+r.nextSample);var o=this.createFragment(n.id,r.nextSample,n.segmentStream);if(o)n.segmentStream=o,r.nextSample++;else break;if((r.nextSample%n.nb_samples===0||t||r.nextSample>=r.samples.length)&&(f.info("ISOFile","Sending fragmented data on track #"+n.id+" for samples ["+Math.max(0,r.nextSample-n.nb_samples)+","+(r.nextSample-1)+"]"),f.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(n.id,n.user,n.segmentStream.buffer,r.nextSample,t||r.nextSample>=r.samples.length),n.segmentStream=null,n!==this.fragmentedTracks[e]))break}}if(this.onSamples!==null)for(e=0;e<this.extractedTracks.length;e++){var d=this.extractedTracks[e];for(r=d.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){f.debug("ISOFile","Exporting on track #"+d.id+" sample #"+r.nextSample);var u=this.getSample(r,r.nextSample);if(u)r.nextSample++,d.samples.push(u);else{this.setNextSeekPositionFromSample(r.samples[r.nextSample]);break}if((r.nextSample%d.nb_samples===0||r.nextSample>=r.samples.length)&&(f.debug("ISOFile","Sending samples on track #"+d.id+" for sample "+r.nextSample),this.onSamples&&this.onSamples(d.id,d.user,d.samples),d.samples=[],d!==this.extractedTracks[e]))break}}}},y.prototype.getBox=function(t){var e=this.getBoxes(t,!0);return e.length?e[0]:null},y.prototype.getBoxes=function(t,e){var r=[];return y._sweep.call(this,t,r,e),r},y._sweep=function(t,e,r){this.type&&this.type==t&&e.push(this);for(var n in this.boxes){if(e.length&&r)return;y._sweep.call(this.boxes[n],t,e,r)}},y.prototype.getTrackSamplesInfo=function(t){var e=this.getTrackById(t);if(e)return e.samples},y.prototype.getTrackSample=function(t,e){var r=this.getTrackById(t),n=this.getSample(r,e);return n},y.prototype.releaseUsedSamples=function(t,e){var r=0,n=this.getTrackById(t);n.lastValidSample||(n.lastValidSample=0);for(var o=n.lastValidSample;o<e;o++)r+=this.releaseSample(n,o);f.info("ISOFile","Track #"+t+" released samples up to "+e+" (released size: "+r+", remaining: "+this.samplesDataSize+")"),n.lastValidSample=e},y.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},y.prototype.stop=function(){this.sampleProcessingStarted=!1},y.prototype.flush=function(){f.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},y.prototype.seekTrack=function(t,e,r){var n,o,d=1/0,u=0,_=0,U;if(r.samples.length===0)return f.info("ISOFile","No sample in track, cannot seek! Using time "+f.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(n=0;n<r.samples.length;n++){if(o=r.samples[n],n===0)_=0,U=o.timescale;else if(o.cts>t*o.timescale){_=n-1;break}e&&o.is_sync&&(u=n)}for(e&&(_=u),t=r.samples[_].cts,r.nextSample=_;r.samples[_].alreadyRead===r.samples[_].size&&r.samples[_+1];)_++;return d=r.samples[_].offset+r.samples[_].alreadyRead,f.info("ISOFile","Seeking to "+(e?"RAP":"")+" sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+f.getDurationString(t,U)+" and offset: "+d),{offset:d,time:t/U}},y.prototype.getTrackDuration=function(t){var e;return t.samples?(e=t.samples[t.samples.length-1],(e.cts+e.duration)/e.timescale):1/0},y.prototype.seek=function(t,e){var r=this.moov,n,o,d,u={offset:1/0,time:1/0};if(this.moov){for(d=0;d<r.traks.length;d++)n=r.traks[d],!(t>this.getTrackDuration(n))&&(o=this.seekTrack(t,e,n),o.offset<u.offset&&(u.offset=o.offset),o.time<u.time&&(u.time=o.time));return f.info("ISOFile","Seeking at time "+f.getDurationString(u.time,1)+" needs a buffer with a fileStart position of "+u.offset),u.offset===1/0?u={offset:this.nextParsePosition,time:0}:u.offset=this.stream.getEndFilePositionAfter(u.offset),f.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+u.offset),u}else throw"Cannot seek: moov not received!"},y.prototype.equal=function(t){for(var e=0;e<this.boxes.length&&e<t.boxes.length;){var r=this.boxes[e],n=t.boxes[e];if(!s.boxEqual(r,n))return!1;e++}return!0},C.ISOFile=y,y.prototype.lastBoxStartPosition=0,y.prototype.parsingMdat=null,y.prototype.nextParsePosition=0,y.prototype.discardMdatData=!1,y.prototype.processIncompleteBox=function(t){var e,r,n;return t.type==="mdat"?(e=new s[t.type+"Box"](t.size),this.parsingMdat=e,this.boxes.push(e),this.mdats.push(e),e.start=t.start,e.hdr_size=t.hdr_size,this.stream.addUsedBytes(e.hdr_size),this.lastBoxStartPosition=e.start+e.size,n=this.stream.seek(e.start+e.size,!1,this.discardMdatData),n?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=e.start+e.size,!1)):(t.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),r=this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1,r?(this.nextParsePosition=this.stream.getEndPosition(),!0):(t.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+t.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},y.prototype.hasIncompleteMdat=function(){return this.parsingMdat!==null},y.prototype.processIncompleteMdat=function(){var t,e;return t=this.parsingMdat,e=this.stream.seek(t.start+t.size,!1,this.discardMdatData),e?(f.debug("ISOFile","Found 'mdat' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},y.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},y.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},y.prototype.updateUsedBytes=function(t,e){this.stream.addUsedBytes&&(t.type==="mdat"?(this.stream.addUsedBytes(t.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(t.size-t.hdr_size)):this.stream.addUsedBytes(t.size))},y.prototype.add=s.Box.prototype.add,y.prototype.addBox=s.Box.prototype.addBox,y.prototype.init=function(t){var e=t||{};this.add("ftyp").set("major_brand",e.brands&&e.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",e.brands||["iso4"]);var r=this.add("moov");return r.add("mvhd").set("timescale",e.timescale||600).set("rate",e.rate||65536).set("creation_time",0).set("modification_time",0).set("duration",e.duration||0).set("volume",e.width?0:256).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("next_track_id",1),r.add("mvex"),this},y.prototype.addTrack=function(t){this.moov||this.init(t);var e=t||{};e.width=e.width||320,e.height=e.height||320,e.id=e.id||this.moov.mvhd.next_track_id,e.type=e.type||"avc1";var r=this.moov.add("trak");this.moov.mvhd.next_track_id=e.id+1,r.add("tkhd").set("flags",s.TKHD_FLAG_ENABLED|s.TKHD_FLAG_IN_MOVIE|s.TKHD_FLAG_IN_PREVIEW).set("creation_time",0).set("modification_time",0).set("track_id",e.id).set("duration",e.duration||0).set("layer",e.layer||0).set("alternate_group",0).set("volume",1).set("matrix",[0,0,0,0,0,0,0,0,0]).set("width",e.width<<16).set("height",e.height<<16);var n=r.add("mdia");n.add("mdhd").set("creation_time",0).set("modification_time",0).set("timescale",e.timescale||1).set("duration",e.media_duration||0).set("language",e.language||"und"),n.add("hdlr").set("handler",e.hdlr||"vide").set("name",e.name||"Track created with MP4Box.js"),n.add("elng").set("extended_language",e.language||"fr-FR");var o=n.add("minf");if(s[e.type+"SampleEntry"]!==void 0){var d=new s[e.type+"SampleEntry"];d.data_reference_index=1;var u="";for(var _ in s.sampleEntryCodes)for(var U=s.sampleEntryCodes[_],S=0;S<U.length;S++)if(U.indexOf(e.type)>-1){u=_;break}switch(u){case"Visual":if(o.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),d.set("width",e.width).set("height",e.height).set("horizresolution",72<<16).set("vertresolution",72<<16).set("frame_count",1).set("compressorname",e.type+" Compressor").set("depth",24),e.avcDecoderConfigRecord){var b=new s.avcCBox;b.parse(new h(e.avcDecoderConfigRecord)),d.addBox(b)}else if(e.hevcDecoderConfigRecord){var E=new s.hvcCBox;E.parse(new h(e.hevcDecoderConfigRecord)),d.addBox(E)}break;case"Audio":o.add("smhd").set("balance",e.balance||0),d.set("channel_count",e.channel_count||2).set("samplesize",e.samplesize||16).set("samplerate",e.samplerate||65536);break;case"Hint":o.add("hmhd");break;case"Subtitle":switch(o.add("sthd"),e.type){case"stpp":d.set("namespace",e.namespace||"nonamespace").set("schema_location",e.schema_location||"").set("auxiliary_mime_types",e.auxiliary_mime_types||"");break}break;case"Metadata":o.add("nmhd");break;case"System":o.add("nmhd");break;default:o.add("nmhd");break}e.description&&d.addBox(e.description),e.description_boxes&&e.description_boxes.forEach(function(F){d.addBox(F)}),o.add("dinf").add("dref").addEntry(new s["url Box"]().set("flags",1));var B=o.add("stbl");return B.add("stsd").addEntry(d),B.add("stts").set("sample_counts",[]).set("sample_deltas",[]),B.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),B.add("stco").set("chunk_offsets",[]),B.add("stsz").set("sample_sizes",[]),this.moov.mvex.add("trex").set("track_id",e.id).set("default_sample_description_index",e.default_sample_description_index||1).set("default_sample_duration",e.default_sample_duration||0).set("default_sample_size",e.default_sample_size||0).set("default_sample_flags",e.default_sample_flags||0),this.buildTrakSampleLists(r),e.id}},s.Box.prototype.computeSize=function(t){var e=t||new a;e.endianness=a.BIG_ENDIAN,this.write(e)},y.prototype.addSample=function(t,e,r){var n=r||{},o={},d=this.getTrackById(t);if(d!==null){o.number=d.samples.length,o.track_id=d.tkhd.track_id,o.timescale=d.mdia.mdhd.timescale,o.description_index=n.sample_description_index?n.sample_description_index-1:0,o.description=d.mdia.minf.stbl.stsd.entries[o.description_index],o.data=e,o.size=e.byteLength,o.alreadyRead=o.size,o.duration=n.duration||1,o.cts=n.cts||0,o.dts=n.dts||0,o.is_sync=n.is_sync||!1,o.is_leading=n.is_leading||0,o.depends_on=n.depends_on||0,o.is_depended_on=n.is_depended_on||0,o.has_redundancy=n.has_redundancy||0,o.degradation_priority=n.degradation_priority||0,o.offset=0,o.subsamples=n.subsamples,d.samples.push(o),d.samples_size+=o.size,d.samples_duration+=o.duration,d.first_dts===void 0&&(d.first_dts=n.dts),this.processSamples();var u=this.createSingleSampleMoof(o);return this.addBox(u),u.computeSize(),u.trafs[0].truns[0].data_offset=u.size+8,this.add("mdat").data=new Uint8Array(e),o}},y.prototype.createSingleSampleMoof=function(t){var e=0;t.is_sync?e=1<<25:e=65536;var r=new s.moofBox;r.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var n=r.add("traf"),o=this.getTrackById(t.track_id);return n.add("tfhd").set("track_id",t.track_id).set("flags",s.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),n.add("tfdt").set("baseMediaDecodeTime",t.dts-(o.first_dts||0)),n.add("trun").set("flags",s.TRUN_FLAGS_DATA_OFFSET|s.TRUN_FLAGS_DURATION|s.TRUN_FLAGS_SIZE|s.TRUN_FLAGS_FLAGS|s.TRUN_FLAGS_CTS_OFFSET).set("data_offset",0).set("first_sample_flags",0).set("sample_count",1).set("sample_duration",[t.duration]).set("sample_size",[t.size]).set("sample_flags",[e]).set("sample_composition_time_offset",[t.cts-t.dts]),r},y.prototype.lastMoofIndex=0,y.prototype.samplesDataSize=0,y.prototype.resetTables=function(){var t,e,r,n,o,d,u,_;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,t=0;t<this.moov.traks.length;t++){e=this.moov.traks[t],e.tkhd.duration=0,e.mdia.mdhd.duration=0,r=e.mdia.minf.stbl.stco||e.mdia.minf.stbl.co64,r.chunk_offsets=[],n=e.mdia.minf.stbl.stsc,n.first_chunk=[],n.samples_per_chunk=[],n.sample_description_index=[],o=e.mdia.minf.stbl.stsz||e.mdia.minf.stbl.stz2,o.sample_sizes=[],d=e.mdia.minf.stbl.stts,d.sample_counts=[],d.sample_deltas=[],u=e.mdia.minf.stbl.ctts,u&&(u.sample_counts=[],u.sample_offsets=[]),_=e.mdia.minf.stbl.stss;var U=e.mdia.minf.stbl.boxes.indexOf(_);U!=-1&&(e.mdia.minf.stbl.boxes[U]=null)}},y.initSampleGroups=function(t,e,r,n,o){var d,u,_,U;function S(b,E,B){this.grouping_type=b,this.grouping_type_parameter=E,this.sbgp=B,this.last_sample_in_run=-1,this.entry_index=-1}for(e&&(e.sample_groups_info=[]),t.sample_groups_info||(t.sample_groups_info=[]),u=0;u<r.length;u++){for(U=r[u].grouping_type+"/"+r[u].grouping_type_parameter,_=new S(r[u].grouping_type,r[u].grouping_type_parameter,r[u]),e&&(e.sample_groups_info[U]=_),t.sample_groups_info[U]||(t.sample_groups_info[U]=_),d=0;d<n.length;d++)n[d].grouping_type===r[u].grouping_type&&(_.description=n[d],_.description.used=!0);if(o)for(d=0;d<o.length;d++)o[d].grouping_type===r[u].grouping_type&&(_.fragment_description=o[d],_.fragment_description.used=!0,_.is_fragment=!0)}if(e){if(o)for(u=0;u<o.length;u++)!o[u].used&&o[u].version>=2&&(U=o[u].grouping_type+"/0",_=new S(o[u].grouping_type,0),_.is_fragment=!0,e.sample_groups_info[U]||(e.sample_groups_info[U]=_))}else for(u=0;u<n.length;u++)!n[u].used&&n[u].version>=2&&(U=n[u].grouping_type+"/0",_=new S(n[u].grouping_type,0),t.sample_groups_info[U]||(t.sample_groups_info[U]=_))},y.setSampleGroupProperties=function(t,e,r,n){var o,d;e.sample_groups=[];for(o in n)if(e.sample_groups[o]={},e.sample_groups[o].grouping_type=n[o].grouping_type,e.sample_groups[o].grouping_type_parameter=n[o].grouping_type_parameter,r>=n[o].last_sample_in_run&&(n[o].last_sample_in_run<0&&(n[o].last_sample_in_run=0),n[o].entry_index++,n[o].entry_index<=n[o].sbgp.entries.length-1&&(n[o].last_sample_in_run+=n[o].sbgp.entries[n[o].entry_index].sample_count)),n[o].entry_index<=n[o].sbgp.entries.length-1?e.sample_groups[o].group_description_index=n[o].sbgp.entries[n[o].entry_index].group_description_index:e.sample_groups[o].group_description_index=-1,e.sample_groups[o].group_description_index!==0){var u;n[o].fragment_description?u=n[o].fragment_description:u=n[o].description,e.sample_groups[o].group_description_index>0?(e.sample_groups[o].group_description_index>65535?d=(e.sample_groups[o].group_description_index>>16)-1:d=e.sample_groups[o].group_description_index-1,u&&d>=0&&(e.sample_groups[o].description=u.entries[d])):u&&u.version>=2&&u.default_group_description_index>0&&(e.sample_groups[o].description=u.entries[u.default_group_description_index-1])}},y.process_sdtp=function(t,e,r){e&&(t?(e.is_leading=t.is_leading[r],e.depends_on=t.sample_depends_on[r],e.is_depended_on=t.sample_is_depended_on[r],e.has_redundancy=t.sample_has_redundancy[r]):(e.is_leading=0,e.depends_on=0,e.is_depended_on=0,e.has_redundancy=0))},y.prototype.buildSampleLists=function(){var t,e;for(t=0;t<this.moov.traks.length;t++)e=this.moov.traks[t],this.buildTrakSampleLists(e)},y.prototype.buildTrakSampleLists=function(t){var e,r,n,o,d,u,_,U,S,b,E,B,F,I,z,M,Y,k,L,O,V,K,R,G;if(t.samples=[],t.samples_duration=0,t.samples_size=0,r=t.mdia.minf.stbl.stco||t.mdia.minf.stbl.co64,n=t.mdia.minf.stbl.stsc,o=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2,d=t.mdia.minf.stbl.stts,u=t.mdia.minf.stbl.ctts,_=t.mdia.minf.stbl.stss,U=t.mdia.minf.stbl.stsd,S=t.mdia.minf.stbl.subs,B=t.mdia.minf.stbl.stdp,b=t.mdia.minf.stbl.sbgps,E=t.mdia.minf.stbl.sgpds,k=-1,L=-1,O=-1,V=-1,K=0,R=0,G=0,y.initSampleGroups(t,null,b,E),!(typeof o>"u")){for(e=0;e<o.sample_sizes.length;e++){var T={};T.number=e,T.track_id=t.tkhd.track_id,T.timescale=t.mdia.mdhd.timescale,T.alreadyRead=0,t.samples[e]=T,T.size=o.sample_sizes[e],t.samples_size+=T.size,e===0?(I=1,F=0,T.chunk_index=I,T.chunk_run_index=F,Y=n.samples_per_chunk[F],M=0,F+1<n.first_chunk.length?z=n.first_chunk[F+1]-1:z=1/0):e<Y?(T.chunk_index=I,T.chunk_run_index=F):(I++,T.chunk_index=I,M=0,I<=z||(F++,F+1<n.first_chunk.length?z=n.first_chunk[F+1]-1:z=1/0),T.chunk_run_index=F,Y+=n.samples_per_chunk[F]),T.description_index=n.sample_description_index[T.chunk_run_index]-1,T.description=U.entries[T.description_index],T.offset=r.chunk_offsets[T.chunk_index-1]+M,M+=T.size,e>k&&(L++,k<0&&(k=0),k+=d.sample_counts[L]),e>0?(t.samples[e-1].duration=d.sample_deltas[L],t.samples_duration+=t.samples[e-1].duration,T.dts=t.samples[e-1].dts+t.samples[e-1].duration):T.dts=0,u?(e>=O&&(V++,O<0&&(O=0),O+=u.sample_counts[V]),T.cts=t.samples[e].dts+u.sample_offsets[V]):T.cts=T.dts,_?(e==_.sample_numbers[K]-1?(T.is_sync=!0,K++):(T.is_sync=!1,T.degradation_priority=0),S&&S.entries[R].sample_delta+G==e+1&&(T.subsamples=S.entries[R].subsamples,G+=S.entries[R].sample_delta,R++)):T.is_sync=!0,y.process_sdtp(t.mdia.minf.stbl.sdtp,T,T.number),B?T.degradation_priority=B.priority[e]:T.degradation_priority=0,S&&S.entries[R].sample_delta+G==e&&(T.subsamples=S.entries[R].subsamples,G+=S.entries[R].sample_delta),(b.length>0||E.length>0)&&y.setSampleGroupProperties(t,T,e,t.sample_groups_info)}e>0&&(t.samples[e-1].duration=Math.max(t.mdia.mdhd.duration-t.samples[e-1].dts,0),t.samples_duration+=t.samples[e-1].duration)}},y.prototype.updateSampleLists=function(){var t,e,r,n,o,d,u,_,U,S,b,E,B,F,I;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(U=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,U.type=="moof")for(S=U,t=0;t<S.trafs.length;t++){for(b=S.trafs[t],E=this.getTrackById(b.tfhd.track_id),B=this.getTrexById(b.tfhd.track_id),b.tfhd.flags&s.TFHD_FLAG_SAMPLE_DESC?n=b.tfhd.default_sample_description_index:n=B?B.default_sample_description_index:1,b.tfhd.flags&s.TFHD_FLAG_SAMPLE_DUR?o=b.tfhd.default_sample_duration:o=B?B.default_sample_duration:0,b.tfhd.flags&s.TFHD_FLAG_SAMPLE_SIZE?d=b.tfhd.default_sample_size:d=B?B.default_sample_size:0,b.tfhd.flags&s.TFHD_FLAG_SAMPLE_FLAGS?u=b.tfhd.default_sample_flags:u=B?B.default_sample_flags:0,b.sample_number=0,b.sbgps.length>0&&y.initSampleGroups(E,b,b.sbgps,E.mdia.minf.stbl.sgpds,b.sgpds),e=0;e<b.truns.length;e++){var z=b.truns[e];for(r=0;r<z.sample_count;r++){F={},F.moof_number=this.lastMoofIndex,F.number_in_traf=b.sample_number,b.sample_number++,F.number=E.samples.length,b.first_sample_index=E.samples.length,E.samples.push(F),F.track_id=E.tkhd.track_id,F.timescale=E.mdia.mdhd.timescale,F.description_index=n-1,F.description=E.mdia.minf.stbl.stsd.entries[F.description_index],F.size=d,z.flags&s.TRUN_FLAGS_SIZE&&(F.size=z.sample_size[r]),E.samples_size+=F.size,F.duration=o,z.flags&s.TRUN_FLAGS_DURATION&&(F.duration=z.sample_duration[r]),E.samples_duration+=F.duration,E.first_traf_merged||r>0?F.dts=E.samples[E.samples.length-2].dts+E.samples[E.samples.length-2].duration:(b.tfdt?F.dts=b.tfdt.baseMediaDecodeTime:F.dts=0,E.first_traf_merged=!0),F.cts=F.dts,z.flags&s.TRUN_FLAGS_CTS_OFFSET&&(F.cts=F.dts+z.sample_composition_time_offset[r]),I=u,z.flags&s.TRUN_FLAGS_FLAGS?I=z.sample_flags[r]:r===0&&z.flags&s.TRUN_FLAGS_FIRST_FLAG&&(I=z.first_sample_flags),F.is_sync=!(I>>16&1),F.is_leading=I>>26&3,F.depends_on=I>>24&3,F.is_depended_on=I>>22&3,F.has_redundancy=I>>20&3,F.degradation_priority=I&65535;var M=!!(b.tfhd.flags&s.TFHD_FLAG_BASE_DATA_OFFSET),Y=!!(b.tfhd.flags&s.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),k=!!(z.flags&s.TRUN_FLAGS_DATA_OFFSET),L=0;M?L=b.tfhd.base_data_offset:Y||e===0?L=S.start:L=_,e===0&&r===0?k?F.offset=L+z.data_offset:F.offset=L:F.offset=_,_=F.offset+F.size,(b.sbgps.length>0||b.sgpds.length>0||E.mdia.minf.stbl.sbgps.length>0||E.mdia.minf.stbl.sgpds.length>0)&&y.setSampleGroupProperties(E,F,F.number_in_traf,b.sample_groups_info)}}if(b.subs){E.has_fragment_subsamples=!0;var O=b.first_sample_index;for(e=0;e<b.subs.entries.length;e++)O+=b.subs.entries[e].sample_delta,F=E.samples[O-1],F.subsamples=b.subs.entries[e].subsamples}}}},y.prototype.getSample=function(t,e){var r,n=t.samples[e];if(!this.moov)return null;if(!n.data)n.data=new Uint8Array(n.size),n.alreadyRead=0,this.samplesDataSize+=n.size,f.debug("ISOFile","Allocating sample #"+e+" on track #"+t.tkhd.track_id+" of size "+n.size+" (total: "+this.samplesDataSize+")");else if(n.alreadyRead==n.size)return n;for(;;){var o=this.stream.findPosition(!0,n.offset+n.alreadyRead,!1);if(o>-1){r=this.stream.buffers[o];var d=r.byteLength-(n.offset+n.alreadyRead-r.fileStart);if(n.size-n.alreadyRead<=d)return f.debug("ISOFile","Getting sample #"+e+" data (alreadyRead: "+n.alreadyRead+" offset: "+(n.offset+n.alreadyRead-r.fileStart)+" read size: "+(n.size-n.alreadyRead)+" full size: "+n.size+")"),a.memcpy(n.data.buffer,n.alreadyRead,r,n.offset+n.alreadyRead-r.fileStart,n.size-n.alreadyRead),r.usedBytes+=n.size-n.alreadyRead,this.stream.logBufferLevel(),n.alreadyRead=n.size,n;if(d===0)return null;f.debug("ISOFile","Getting sample #"+e+" partial data (alreadyRead: "+n.alreadyRead+" offset: "+(n.offset+n.alreadyRead-r.fileStart)+" read size: "+d+" full size: "+n.size+")"),a.memcpy(n.data.buffer,n.alreadyRead,r,n.offset+n.alreadyRead-r.fileStart,d),n.alreadyRead+=d,r.usedBytes+=d,this.stream.logBufferLevel()}else return null}},y.prototype.releaseSample=function(t,e){var r=t.samples[e];return r.data?(this.samplesDataSize-=r.size,r.data=null,r.alreadyRead=0,r.size):0},y.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},y.prototype.getCodecs=function(){var t,e="";for(t=0;t<this.moov.traks.length;t++){var r=this.moov.traks[t];t>0&&(e+=","),e+=r.mdia.minf.stbl.stsd.entries[0].getCodec()}return e},y.prototype.getTrexById=function(t){var e;if(!this.moov||!this.moov.mvex)return null;for(e=0;e<this.moov.mvex.trexs.length;e++){var r=this.moov.mvex.trexs[e];if(r.track_id==t)return r}return null},y.prototype.getTrackById=function(t){if(this.moov===void 0)return null;for(var e=0;e<this.moov.traks.length;e++){var r=this.moov.traks[e];if(r.tkhd.track_id==t)return r}return null},y.prototype.itemsDataSize=0,y.prototype.flattenItemInfo=function(){var t=this.items,e=this.entity_groups,r,n,o,d=this.meta;if(d!=null&&d.hdlr!==void 0&&d.iinf!==void 0){for(r=0;r<d.iinf.item_infos.length;r++)o={},o.id=d.iinf.item_infos[r].item_ID,t[o.id]=o,o.ref_to=[],o.name=d.iinf.item_infos[r].item_name,d.iinf.item_infos[r].protection_index>0&&(o.protection=d.ipro.protections[d.iinf.item_infos[r].protection_index-1]),d.iinf.item_infos[r].item_type?o.type=d.iinf.item_infos[r].item_type:o.type="mime",o.content_type=d.iinf.item_infos[r].content_type,o.content_encoding=d.iinf.item_infos[r].content_encoding;if(d.grpl)for(r=0;r<d.grpl.boxes.length;r++)entity_group={},entity_group.id=d.grpl.boxes[r].group_id,entity_group.entity_ids=d.grpl.boxes[r].entity_ids,entity_group.type=d.grpl.boxes[r].type,e[entity_group.id]=entity_group;if(d.iloc)for(r=0;r<d.iloc.items.length;r++){var u=d.iloc.items[r];switch(o=t[u.item_ID],u.data_reference_index!==0&&(f.warn("Item storage with reference to other files: not supported"),o.source=d.dinf.boxes[u.data_reference_index-1]),u.construction_method){case 0:break;case 1:break;case 2:f.warn("Item storage with construction_method : not supported");break}for(o.extents=[],o.size=0,n=0;n<u.extents.length;n++)o.extents[n]={},o.extents[n].offset=u.extents[n].extent_offset+u.base_offset,u.construction_method==1&&(o.extents[n].offset+=d.idat.start+d.idat.hdr_size),o.extents[n].length=u.extents[n].extent_length,o.extents[n].alreadyRead=0,o.size+=o.extents[n].length}if(d.pitm&&(t[d.pitm.item_id].primary=!0),d.iref)for(r=0;r<d.iref.references.length;r++){var _=d.iref.references[r];for(n=0;n<_.references.length;n++)t[_.from_item_ID].ref_to.push({type:_.type,id:_.references[n]})}if(d.iprp)for(var U=0;U<d.iprp.ipmas.length;U++){var S=d.iprp.ipmas[U];for(r=0;r<S.associations.length;r++){var b=S.associations[r];if(o=t[b.id],o||(o=e[b.id]),o)for(o.properties===void 0&&(o.properties={},o.properties.boxes=[]),n=0;n<b.props.length;n++){var E=b.props[n];if(E.property_index>0&&E.property_index-1<d.iprp.ipco.boxes.length){var B=d.iprp.ipco.boxes[E.property_index-1];o.properties[B.type]=B,o.properties.boxes.push(B)}}}}}},y.prototype.getItem=function(t){var e,r;if(!this.meta)return null;if(r=this.items[t],!r.data&&r.size)r.data=new Uint8Array(r.size),r.alreadyRead=0,this.itemsDataSize+=r.size,f.debug("ISOFile","Allocating item #"+t+" of size "+r.size+" (total: "+this.itemsDataSize+")");else if(r.alreadyRead===r.size)return r;for(var n=0;n<r.extents.length;n++){var o=r.extents[n];if(o.alreadyRead!==o.length){var d=this.stream.findPosition(!0,o.offset+o.alreadyRead,!1);if(d>-1){e=this.stream.buffers[d];var u=e.byteLength-(o.offset+o.alreadyRead-e.fileStart);if(o.length-o.alreadyRead<=u)f.debug("ISOFile","Getting item #"+t+" extent #"+n+" data (alreadyRead: "+o.alreadyRead+" offset: "+(o.offset+o.alreadyRead-e.fileStart)+" read size: "+(o.length-o.alreadyRead)+" full extent size: "+o.length+" full item size: "+r.size+")"),a.memcpy(r.data.buffer,r.alreadyRead,e,o.offset+o.alreadyRead-e.fileStart,o.length-o.alreadyRead),e.usedBytes+=o.length-o.alreadyRead,this.stream.logBufferLevel(),r.alreadyRead+=o.length-o.alreadyRead,o.alreadyRead=o.length;else return f.debug("ISOFile","Getting item #"+t+" extent #"+n+" partial data (alreadyRead: "+o.alreadyRead+" offset: "+(o.offset+o.alreadyRead-e.fileStart)+" read size: "+u+" full extent size: "+o.length+" full item size: "+r.size+")"),a.memcpy(r.data.buffer,r.alreadyRead,e,o.offset+o.alreadyRead-e.fileStart,u),o.alreadyRead+=u,r.alreadyRead+=u,e.usedBytes+=u,this.stream.logBufferLevel(),null}else return null}}return r.alreadyRead===r.size?r:null},y.prototype.releaseItem=function(t){var e=this.items[t];if(e.data){this.itemsDataSize-=e.size,e.data=null,e.alreadyRead=0;for(var r=0;r<e.extents.length;r++){var n=e.extents[r];n.alreadyRead=0}return e.size}else return 0},y.prototype.processItems=function(t){for(var e in this.items){var r=this.items[e];this.getItem(r.id),t&&!r.sent&&(t(r),r.sent=!0,r.data=null)}},y.prototype.hasItem=function(t){for(var e in this.items){var r=this.items[e];if(r.name===t)return r.id}return-1},y.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},y.prototype.getPrimaryItem=function(){return!this.meta||!this.meta.pitm?null:this.getItem(this.meta.pitm.item_id)},y.prototype.itemToFragmentedTrackFile=function(t){var e=t||{},r=null;if(e.itemId?r=this.getItem(e.itemId):r=this.getPrimaryItem(),r==null)return null;var n=new y;n.discardMdatData=!1;var o={type:r.type,description_boxes:r.properties.boxes};r.properties.ispe&&(o.width=r.properties.ispe.image_width,o.height=r.properties.ispe.image_height);var d=n.addTrack(o);return d?(n.addSample(d,r.data),n):null},y.prototype.write=function(t){for(var e=0;e<this.boxes.length;e++)this.boxes[e].write(t)},y.prototype.createFragment=function(t,e,r){var n=this.getTrackById(t),o=this.getSample(n,e);if(o==null)return this.setNextSeekPositionFromSample(n.samples[e]),null;var d=r||new a;d.endianness=a.BIG_ENDIAN;var u=this.createSingleSampleMoof(o);u.write(d),u.trafs[0].truns[0].data_offset=u.size+8,f.debug("MP4Box","Adjusting data_offset with new value "+u.trafs[0].truns[0].data_offset),d.adjustUint32(u.trafs[0].truns[0].data_offset_position,u.trafs[0].truns[0].data_offset);var _=new s.mdatBox;return _.data=o.data,_.write(d),d},y.writeInitializationSegment=function(t,e,r,n){var o;f.debug("ISOFile","Generating initialization segment");var d=new a;d.endianness=a.BIG_ENDIAN,t.write(d);var u=e.add("mvex");for(r&&u.add("mehd").set("fragment_duration",r),o=0;o<e.traks.length;o++)u.add("trex").set("track_id",e.traks[o].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",n).set("default_sample_size",0).set("default_sample_flags",65536);return e.write(d),d.buffer},y.prototype.save=function(t){var e=new a;e.endianness=a.BIG_ENDIAN,this.write(e),e.save(t)},y.prototype.getBuffer=function(){var t=new a;return t.endianness=a.BIG_ENDIAN,this.write(t),t.buffer},y.prototype.initializeSegmentation=function(){var t,e,r,n;for(this.onSegment===null&&f.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),e=[],t=0;t<this.fragmentedTracks.length;t++){var o=new s.moovBox;o.mvhd=this.moov.mvhd,o.boxes.push(o.mvhd),r=this.getTrackById(this.fragmentedTracks[t].id),o.boxes.push(r),o.traks.push(r),n={},n.id=r.tkhd.track_id,n.user=this.fragmentedTracks[t].user,n.buffer=y.writeInitializationSegment(this.ftyp,o,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[t].samples.length>0?this.moov.traks[t].samples[0].duration:0),e.push(n)}return e},s.Box.prototype.printHeader=function(t){this.size+=8,this.size>c&&(this.size+=8),this.type==="uuid"&&(this.size+=16),t.log(t.indent+"size:"+this.size),t.log(t.indent+"type:"+this.type)},s.FullBox.prototype.printHeader=function(t){this.size+=4,s.Box.prototype.printHeader.call(this,t),t.log(t.indent+"version:"+this.version),t.log(t.indent+"flags:"+this.flags)},s.Box.prototype.print=function(t){this.printHeader(t)},s.ContainerBox.prototype.print=function(t){this.printHeader(t);for(var e=0;e<this.boxes.length;e++)if(this.boxes[e]){var r=t.indent;t.indent+=" ",this.boxes[e].print(t),t.indent=r}},y.prototype.print=function(t){t.indent="";for(var e=0;e<this.boxes.length;e++)this.boxes[e]&&this.boxes[e].print(t)},s.mvhdBox.prototype.print=function(t){s.FullBox.prototype.printHeader.call(this,t),t.log(t.indent+"creation_time: "+this.creation_time),t.log(t.indent+"modification_time: "+this.modification_time),t.log(t.indent+"timescale: "+this.timescale),t.log(t.indent+"duration: "+this.duration),t.log(t.indent+"rate: "+this.rate),t.log(t.indent+"volume: "+(this.volume>>8)),t.log(t.indent+"matrix: "+this.matrix.join(", ")),t.log(t.indent+"next_track_id: "+this.next_track_id)},s.tkhdBox.prototype.print=function(t){s.FullBox.prototype.printHeader.call(this,t),t.log(t.indent+"creation_time: "+this.creation_time),t.log(t.indent+"modification_time: "+this.modification_time),t.log(t.indent+"track_id: "+this.track_id),t.log(t.indent+"duration: "+this.duration),t.log(t.indent+"volume: "+(this.volume>>8)),t.log(t.indent+"matrix: "+this.matrix.join(", ")),t.log(t.indent+"layer: "+this.layer),t.log(t.indent+"alternate_group: "+this.alternate_group),t.log(t.indent+"width: "+this.width),t.log(t.indent+"height: "+this.height)};var A={};A.createFile=function(t,e){var r=t!==void 0?t:!0,n=new y(e);return n.discardMdatData=!r,n},C.createFile=A.createFile}(W)),W}var J=st(),nt=tt(J),X={exports:{}},it;function ot(){return it||(it=1,function(C){var f={};C.exports=f,f.parse=function(h,a){for(var c=f.bin.readUshort,l=f.bin.readUint,v=0,p={},s=new Uint8Array(h),g=s.length-4;l(s,g)!=101010256;)g--;var v=g;v+=4,v+=4;var x=c(s,v);v+=2,c(s,v),v+=2;var m=l(s,v);v+=4;var w=l(s,v);v+=4,v=w;for(var y=0;y<x;y++){l(s,v),v+=4,v+=4,v+=4,v+=4,l(s,v),v+=4;var m=l(s,v);v+=4;var A=l(s,v);v+=4;var t=c(s,v),e=c(s,v+2),r=c(s,v+4);v+=6,v+=8;var n=l(s,v);v+=4,v+=t+e+r,f._readLocal(s,n,p,m,A,a)}return p},f._readLocal=function(h,a,c,l,p,s){var g=f.bin.readUshort,v=f.bin.readUint;v(h,a),a+=4,g(h,a),a+=2,g(h,a),a+=2;var x=g(h,a);a+=2,v(h,a),a+=4,v(h,a),a+=4,a+=8;var m=g(h,a);a+=2;var w=g(h,a);a+=2;var y=f.bin.readUTF8(h,a,m);if(a+=m,a+=w,s){c[y]={size:p,csize:l};return}var A=new Uint8Array(h.buffer,a);if(x==0)c[y]=new Uint8Array(A.buffer.slice(a,a+l));else if(x==8){var t=new Uint8Array(p);f.inflateRaw(A,t),c[y]=t}else throw"unknown compression method: "+x},f.inflateRaw=function(h,a){return f.F.inflate(h,a)},f.inflate=function(h,a){return h[0],h[1],f.inflateRaw(new Uint8Array(h.buffer,h.byteOffset+2,h.length-6),a)},f.deflate=function(h,a){a==null&&(a={level:6});var c=0,l=new Uint8Array(50+Math.floor(h.length*1.1));l[c]=120,l[c+1]=156,c+=2,c=f.F.deflateRaw(h,l,c,a.level);var p=f.adler(h,0,h.length);return l[c+0]=p>>>24&255,l[c+1]=p>>>16&255,l[c+2]=p>>>8&255,l[c+3]=p>>>0&255,new Uint8Array(l.buffer,0,c+4)},f.deflateRaw=function(h,a){a==null&&(a={level:6});var c=new Uint8Array(50+Math.floor(h.length*1.1)),l=f.F.deflateRaw(h,c,l,a.level);return new Uint8Array(c.buffer,0,l)},f.encode=function(h,a){a==null&&(a=!1);var c=0,l=f.bin.writeUint,p=f.bin.writeUshort,s={};for(var g in h){var v=!f._noNeed(g)&&!a,x=h[g],m=f.crc.crc(x,0,x.length);s[g]={cpr:v,usize:x.length,crc:m,file:v?f.deflateRaw(x):x}}for(var g in s)c+=s[g].file.length+30+46+2*f.bin.sizeUTF8(g);c+=22;var w=new Uint8Array(c),y=0,A=[];for(var g in s){var t=s[g];A.push(y),y=f._writeHeader(w,y,g,t,0)}var e=0,r=y;for(var g in s){var t=s[g];A.push(y),y=f._writeHeader(w,y,g,t,1,A[e++])}var n=y-r;return l(w,y,101010256),y+=4,y+=4,p(w,y,e),y+=2,p(w,y,e),y+=2,l(w,y,n),y+=4,l(w,y,r),y+=4,y+=2,w.buffer},f._noNeed=function(h){var a=h.split(".").pop().toLowerCase();return"png,jpg,jpeg,zip".indexOf(a)!=-1},f._writeHeader=function(h,a,c,l,p,s){var g=f.bin.writeUint,v=f.bin.writeUshort,x=l.file;g(h,a,p==0?67324752:33639248),a+=4,p==1&&(a+=2),v(h,a,20),a+=2,v(h,a,0),a+=2,v(h,a,l.cpr?8:0),a+=2,g(h,a,0),a+=4,g(h,a,l.crc),a+=4,g(h,a,x.length),a+=4,g(h,a,l.usize),a+=4,v(h,a,f.bin.sizeUTF8(c)),a+=2,v(h,a,0),a+=2,p==1&&(a+=2,a+=2,a+=6,g(h,a,s),a+=4);var m=f.bin.writeUTF8(h,a,c);return a+=m,p==0&&(h.set(x,a),a+=x.length),a},f.crc={table:function(){for(var h=new Uint32Array(256),a=0;a<256;a++){for(var c=a,l=0;l<8;l++)c&1?c=3988292384^c>>>1:c=c>>>1;h[a]=c}return h}(),update:function(h,a,c,l){for(var p=0;p<l;p++)h=f.crc.table[(h^a[c+p])&255]^h>>>8;return h},crc:function(h,a,c){return f.crc.update(4294967295,h,a,c)^4294967295}},f.adler=function(h,a,c){for(var l=1,p=0,s=a,g=a+c;s<g;){for(var v=Math.min(s+5552,g);s<v;)l+=h[s++],p+=l;l=l%65521,p=p%65521}return p<<16|l},f.bin={readUshort:function(h,a){return h[a]|h[a+1]<<8},writeUshort:function(h,a,c){h[a]=c&255,h[a+1]=c>>8&255},readUint:function(h,a){return h[a+3]*(256*256*256)+(h[a+2]<<16|h[a+1]<<8|h[a])},writeUint:function(h,a,c){h[a]=c&255,h[a+1]=c>>8&255,h[a+2]=c>>16&255,h[a+3]=c>>24&255},readASCII:function(h,a,c){for(var l="",p=0;p<c;p++)l+=String.fromCharCode(h[a+p]);return l},writeASCII:function(h,a,c){for(var l=0;l<c.length;l++)h[a+l]=c.charCodeAt(l)},pad:function(h){return h.length<2?"0"+h:h},readUTF8:function(h,a,c){for(var l="",p,s=0;s<c;s++)l+="%"+f.bin.pad(h[a+s].toString(16));try{p=decodeURIComponent(l)}catch{return f.bin.readASCII(h,a,c)}return p},writeUTF8:function(h,a,c){for(var l=c.length,p=0,s=0;s<l;s++){var g=c.charCodeAt(s);if(!(g&4294967168))h[a+p]=g,p++;else if(!(g&4294965248))h[a+p]=192|g>>6,h[a+p+1]=128|g>>0&63,p+=2;else if(!(g&4294901760))h[a+p]=224|g>>12,h[a+p+1]=128|g>>6&63,h[a+p+2]=128|g>>0&63,p+=3;else if(!(g&4294967295-(1<<21)+1))h[a+p]=240|g>>18,h[a+p+1]=128|g>>12&63,h[a+p+2]=128|g>>6&63,h[a+p+3]=128|g>>0&63,p+=4;else throw"e"}return p},sizeUTF8:function(h){for(var a=h.length,c=0,l=0;l<a;l++){var p=h.charCodeAt(l);if(!(p&4294967168))c++;else if(!(p&4294965248))c+=2;else if(!(p&4294901760))c+=3;else if(!(p&4294967295-(1<<21)+1))c+=4;else throw"e"}return c}},f.F={},f.F.deflateRaw=function(h,a,c,l){var p=[[0,0,0,0,0],[4,4,8,4,0],[4,5,16,8,0],[4,6,16,16,0],[4,10,16,32,0],[8,16,32,32,0],[8,16,128,128,0],[8,32,128,256,0],[32,128,258,1024,1],[32,258,258,4096,1]],s=p[l],g=f.F.U,v=f.F._goodIndex;f.F._hash;var x=f.F._putsE,m=0,w=c<<3,y=0,A=h.length;if(l==0){for(;m<A;){var t=Math.min(65535,A-m);x(a,w,m+t==A?1:0),w=f.F._copyExact(h,m,t,a,w+8),m+=t}return w>>>3}var e=g.lits,r=g.strt,n=g.prev,o=0,d=0,u=0,_=0,U=0,S=0;for(A>2&&(S=f.F._hash(h,0),r[S]=0),m=0;m<A;m++){if(U=S,m+1<A-2){S=f.F._hash(h,m+1);var b=m+1&32767;n[b]=r[S],r[S]=b}if(y<=m){(o>14e3||d>26697)&&A-m>100&&(y<m&&(e[o]=m-y,o+=2,y=m),w=f.F._writeBlock(m==A-1||y==A?1:0,e,o,_,h,u,m-u,a,w),o=d=_=0,u=m);var E=0;m<A-2&&(E=f.F._bestMatch(h,m,n,U,Math.min(s[2],A-m),s[3]));var t=E>>>16,B=E&65535;if(E!=0){var t=E>>>16,B=E&65535,F=v(t,g.of0);g.lhst[257+F]++;var I=v(B,g.df0);g.dhst[I]++,_+=g.exb[F]+g.dxb[I],e[o]=t<<23|m-y,e[o+1]=B<<16|F<<8|I,o+=2,y=m+t}else g.lhst[h[m]]++;d++}}for((u!=m||h.length==0)&&(y<m&&(e[o]=m-y,o+=2,y=m),w=f.F._writeBlock(1,e,o,_,h,u,m-u,a,w),o=0,d=0,o=d=_=0,u=m);w&7;)w++;return w>>>3},f.F._bestMatch=function(h,a,c,l,p,s){var g=a&32767,v=c[g],x=g-v+32768&32767;if(v==g||l!=f.F._hash(h,a-x))return 0;for(var m=0,w=0,y=Math.min(32767,a);x<=y&&--s!=0&&v!=g;){if(m==0||h[a+m]==h[a+m-x]){var A=f.F._howLong(h,a,x);if(A>m){if(m=A,w=x,m>=p)break;x+2<A&&(A=x+2);for(var t=0,e=0;e<A-2;e++){var r=a-x+e+32768&32767,n=c[r],o=r-n+32768&32767;o>t&&(t=o,v=r)}}}g=v,v=c[g],x+=g-v+32768&32767}return m<<16|w},f.F._howLong=function(h,a,c){if(h[a]!=h[a-c]||h[a+1]!=h[a+1-c]||h[a+2]!=h[a+2-c])return 0;var l=a,p=Math.min(h.length,a+258);for(a+=3;a<p&&h[a]==h[a-c];)a++;return a-l},f.F._hash=function(h,a){return(h[a]<<8|h[a+1])+(h[a+2]<<4)&65535},f.saved=0,f.F._writeBlock=function(h,a,c,l,p,s,g,v,x){var m=f.F.U,w=f.F._putsF,y=f.F._putsE,A,t,e,r,n,o,d,u,_;m.lhst[256]++,A=f.F.getTrees(),t=A[0],e=A[1],r=A[2],n=A[3],o=A[4],d=A[5],u=A[6],_=A[7];var U=(x+3&7?8-(x+3&7):0)+32+(g<<3),S=l+f.F.contSize(m.fltree,m.lhst)+f.F.contSize(m.fdtree,m.dhst),b=l+f.F.contSize(m.ltree,m.lhst)+f.F.contSize(m.dtree,m.dhst);b+=14+3*d+f.F.contSize(m.itree,m.ihst)+(m.ihst[16]*2+m.ihst[17]*3+m.ihst[18]*7);for(var E=0;E<286;E++)m.lhst[E]=0;for(var E=0;E<30;E++)m.dhst[E]=0;for(var E=0;E<19;E++)m.ihst[E]=0;var B=U<S&&U<b?0:S<b?1:2;if(w(v,x,h),w(v,x+1,B),x+=3,B==0){for(;x&7;)x++;x=f.F._copyExact(p,s,g,v,x)}else{var F,I;if(B==1&&(F=m.fltree,I=m.fdtree),B==2){f.F.makeCodes(m.ltree,t),f.F.revCodes(m.ltree,t),f.F.makeCodes(m.dtree,e),f.F.revCodes(m.dtree,e),f.F.makeCodes(m.itree,r),f.F.revCodes(m.itree,r),F=m.ltree,I=m.dtree,y(v,x,n-257),x+=5,y(v,x,o-1),x+=5,y(v,x,d-4),x+=4;for(var z=0;z<d;z++)y(v,x+z*3,m.itree[(m.ordr[z]<<1)+1]);x+=3*d,x=f.F._codeTiny(u,m.itree,v,x),x=f.F._codeTiny(_,m.itree,v,x)}for(var M=s,Y=0;Y<c;Y+=2){for(var k=a[Y],L=k>>>23,O=M+(k&(1<<23)-1);M<O;)x=f.F._writeLit(p[M++],F,v,x);if(L!=0){var V=a[Y+1],K=V>>16,R=V>>8&255,G=V&255;x=f.F._writeLit(257+R,F,v,x),y(v,x,L-m.of0[R]),x+=m.exb[R],x=f.F._writeLit(G,I,v,x),w(v,x,K-m.df0[G]),x+=m.dxb[G],M+=L}}x=f.F._writeLit(256,F,v,x)}return x},f.F._copyExact=function(h,a,c,l,p){var s=p>>>3;return l[s]=c,l[s+1]=c>>>8,l[s+2]=255-l[s],l[s+3]=255-l[s+1],s+=4,l.set(new Uint8Array(h.buffer,a,c),s),p+(c+4<<3)},f.F.getTrees=function(){for(var h=f.F.U,a=f.F._hufTree(h.lhst,h.ltree,15),c=f.F._hufTree(h.dhst,h.dtree,15),l=[],p=f.F._lenCodes(h.ltree,l),s=[],g=f.F._lenCodes(h.dtree,s),v=0;v<l.length;v+=2)h.ihst[l[v]]++;for(var v=0;v<s.length;v+=2)h.ihst[s[v]]++;for(var x=f.F._hufTree(h.ihst,h.itree,7),m=19;m>4&&h.itree[(h.ordr[m-1]<<1)+1]==0;)m--;return[a,c,x,p,g,m,l,s]},f.F.getSecond=function(h){for(var a=[],c=0;c<h.length;c+=2)a.push(h[c+1]);return a},f.F.nonZero=function(h){for(var a="",c=0;c<h.length;c+=2)h[c+1]!=0&&(a+=(c>>1)+",");return a},f.F.contSize=function(h,a){for(var c=0,l=0;l<a.length;l++)c+=a[l]*h[(l<<1)+1];return c},f.F._codeTiny=function(h,a,c,l){for(var p=0;p<h.length;p+=2){var s=h[p],g=h[p+1];l=f.F._writeLit(s,a,c,l);var v=s==16?2:s==17?3:7;s>15&&(f.F._putsE(c,l,g,v),l+=v)}return l},f.F._lenCodes=function(h,a){for(var c=h.length;c!=2&&h[c-1]==0;)c-=2;for(var l=0;l<c;l+=2){var p=h[l+1],s=l+3<c?h[l+3]:-1,g=l+5<c?h[l+5]:-1,v=l==0?-1:h[l-1];if(p==0&&s==p&&g==p){for(var x=l+5;x+2<c&&h[x+2]==p;)x+=2;var m=Math.min(x+1-l>>>1,138);m<11?a.push(17,m-3):a.push(18,m-11),l+=m*2-2}else if(p==v&&s==p&&g==p){for(var x=l+5;x+2<c&&h[x+2]==p;)x+=2;var m=Math.min(x+1-l>>>1,6);a.push(16,m-3),l+=m*2-2}else a.push(p,0)}return c>>>1},f.F._hufTree=function(h,a,c){var l=[],p=h.length,s=a.length,g=0;for(g=0;g<s;g+=2)a[g]=0,a[g+1]=0;for(g=0;g<p;g++)h[g]!=0&&l.push({lit:g,f:h[g]});var v=l.length,x=l.slice(0);if(v==0)return 0;if(v==1){var m=l[0].lit,x=m==0?1:0;return a[(m<<1)+1]=1,a[(x<<1)+1]=1,1}l.sort(function(n,o){return n.f-o.f});var w=l[0],y=l[1],A=0,t=1,e=2;for(l[0]={lit:-1,f:w.f+y.f,l:w,r:y,d:0};t!=v-1;)A!=t&&(e==v||l[A].f<l[e].f)?w=l[A++]:w=l[e++],A!=t&&(e==v||l[A].f<l[e].f)?y=l[A++]:y=l[e++],l[t++]={lit:-1,f:w.f+y.f,l:w,r:y};var r=f.F.setDepth(l[t-1],0);for(r>c&&(f.F.restrictDepth(x,c,r),r=c),g=0;g<v;g++)a[(x[g].lit<<1)+1]=x[g].d;return r},f.F.setDepth=function(h,a){return h.lit!=-1?(h.d=a,a):Math.max(f.F.setDepth(h.l,a+1),f.F.setDepth(h.r,a+1))},f.F.restrictDepth=function(h,a,c){var l=0,p=1<<c-a,s=0;for(h.sort(function(v,x){return x.d==v.d?v.f-x.f:x.d-v.d}),l=0;l<h.length&&h[l].d>a;l++){var g=h[l].d;h[l].d=a,s+=p-(1<<c-g)}for(s=s>>>c-a;s>0;){var g=h[l].d;g<a?(h[l].d++,s-=1<<a-g-1):l++}for(;l>=0;l--)h[l].d==a&&s<0&&(h[l].d--,s++);s!=0&&console.log("debt left")},f.F._goodIndex=function(h,a){var c=0;return a[c|16]<=h&&(c|=16),a[c|8]<=h&&(c|=8),a[c|4]<=h&&(c|=4),a[c|2]<=h&&(c|=2),a[c|1]<=h&&(c|=1),c},f.F._writeLit=function(h,a,c,l){return f.F._putsF(c,l,a[h<<1]),l+a[(h<<1)+1]},f.F.inflate=function(h,a){var c=Uint8Array;if(h[0]==3&&h[1]==0)return a||new c(0);var l=f.F,p=l._bitsF,s=l._bitsE,g=l._decodeTiny,v=l.makeCodes,x=l.codes2map,m=l._get17,w=l.U,y=a==null;y&&(a=new c(h.length>>>2<<3));for(var A=0,t=0,e=0,r=0,n=0,o=0,d=0,u=0,_=0,U,S;A==0;){if(A=p(h,_,1),t=p(h,_+1,2),_+=3,t==0){_&7&&(_+=8-(_&7));var b=(_>>>3)+4,E=h[b-4]|h[b-3]<<8;y&&(a=f.F._check(a,u+E)),a.set(new c(h.buffer,h.byteOffset+b,E),u),_=b+E<<3,u+=E;continue}if(y&&(a=f.F._check(a,u+(1<<17))),t==1&&(U=w.flmap,S=w.fdmap,o=511,d=31),t==2){e=s(h,_,5)+257,r=s(h,_+5,5)+1,n=s(h,_+10,4)+4,_+=14;for(var B=0;B<38;B+=2)w.itree[B]=0,w.itree[B+1]=0;for(var F=1,B=0;B<n;B++){var I=s(h,_+B*3,3);w.itree[(w.ordr[B]<<1)+1]=I,I>F&&(F=I)}_+=3*n,v(w.itree,F),x(w.itree,F,w.imap),U=w.lmap,S=w.dmap,_=g(w.imap,(1<<F)-1,e+r,h,_,w.ttree);var z=l._copyOut(w.ttree,0,e,w.ltree);o=(1<<z)-1;var M=l._copyOut(w.ttree,e,r,w.dtree);d=(1<<M)-1,v(w.ltree,z),x(w.ltree,z,U),v(w.dtree,M),x(w.dtree,M,S)}for(;;){var Y=U[m(h,_)&o];_+=Y&15;var k=Y>>>4;if(!(k>>>8))a[u++]=k;else{if(k==256)break;var L=u+k-254;if(k>264){var O=w.ldef[k-257];L=u+(O>>>3)+s(h,_,O&7),_+=O&7}var V=S[m(h,_)&d];_+=V&15;var K=V>>>4,R=w.ddef[K],G=(R>>>4)+p(h,_,R&15);for(_+=R&15,y&&(a=f.F._check(a,u+(1<<17)));u<L;)a[u]=a[u++-G],a[u]=a[u++-G],a[u]=a[u++-G],a[u]=a[u++-G];u=L}}}return a.length==u?a:a.slice(0,u)},f.F._check=function(h,a){var c=h.length;if(a<=c)return h;var l=new Uint8Array(Math.max(c<<1,a));return l.set(h,0),l},f.F._decodeTiny=function(h,a,c,l,p,s){for(var g=f.F._bitsE,v=f.F._get17,x=0;x<c;){var m=h[v(l,p)&a];p+=m&15;var w=m>>>4;if(w<=15)s[x]=w,x++;else{var y=0,A=0;w==16?(A=3+g(l,p,2),p+=2,y=s[x-1]):w==17?(A=3+g(l,p,3),p+=3):w==18&&(A=11+g(l,p,7),p+=7);for(var t=x+A;x<t;)s[x]=y,x++}}return p},f.F._copyOut=function(h,a,c,l){for(var p=0,s=0,g=l.length>>>1;s<c;){var v=h[s+a];l[s<<1]=0,l[(s<<1)+1]=v,v>p&&(p=v),s++}for(;s<g;)l[s<<1]=0,l[(s<<1)+1]=0,s++;return p},f.F.makeCodes=function(h,a){for(var c=f.F.U,l=h.length,p,s,g,v,x,m=c.bl_count,v=0;v<=a;v++)m[v]=0;for(v=1;v<l;v+=2)m[h[v]]++;var w=c.next_code;for(p=0,m[0]=0,s=1;s<=a;s++)p=p+m[s-1]<<1,w[s]=p;for(g=0;g<l;g+=2)x=h[g+1],x!=0&&(h[g]=w[x],w[x]++)},f.F.codes2map=function(h,a,c){for(var l=h.length,p=f.F.U,s=p.rev15,g=0;g<l;g+=2)if(h[g+1]!=0)for(var v=g>>1,x=h[g+1],m=v<<4|x,w=a-x,y=h[g]<<w,A=y+(1<<w);y!=A;){var t=s[y]>>>15-a;c[t]=m,y++}},f.F.revCodes=function(h,a){for(var c=f.F.U.rev15,l=15-a,p=0;p<h.length;p+=2){var s=h[p]<<a-h[p+1];h[p]=c[s]>>>l}},f.F._putsE=function(h,a,c){c=c<<(a&7);var l=a>>>3;h[l]|=c,h[l+1]|=c>>>8},f.F._putsF=function(h,a,c){c=c<<(a&7);var l=a>>>3;h[l]|=c,h[l+1]|=c>>>8,h[l+2]|=c>>>16},f.F._bitsE=function(h,a,c){return(h[a>>>3]|h[(a>>>3)+1]<<8)>>>(a&7)&(1<<c)-1},f.F._bitsF=function(h,a,c){return(h[a>>>3]|h[(a>>>3)+1]<<8|h[(a>>>3)+2]<<16)>>>(a&7)&(1<<c)-1},f.F._get17=function(h,a){return(h[a>>>3]|h[(a>>>3)+1]<<8|h[(a>>>3)+2]<<16)>>>(a&7)},f.F._get25=function(h,a){return(h[a>>>3]|h[(a>>>3)+1]<<8|h[(a>>>3)+2]<<16|h[(a>>>3)+3]<<24)>>>(a&7)},f.F.U=function(){var h=Uint16Array,a=Uint32Array;return{next_code:new h(16),bl_count:new h(16),ordr:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],of0:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],exb:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],ldef:new h(32),df0:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],dxb:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],ddef:new a(32),flmap:new h(512),fltree:[],fdmap:new h(32),fdtree:[],lmap:new h(32768),ltree:[],ttree:[],dmap:new h(32768),dtree:[],imap:new h(512),itree:[],rev15:new h(32768),lhst:new a(286),dhst:new a(30),ihst:new a(19),lits:new a(15e3),strt:new h(65536),prev:new h(32768)}}(),function(){for(var h=f.F.U,a=32768,c=0;c<a;c++){var l=c;l=(l&2863311530)>>>1|(l&1431655765)<<1,l=(l&3435973836)>>>2|(l&858993459)<<2,l=(l&4042322160)>>>4|(l&252645135)<<4,l=(l&4278255360)>>>8|(l&16711935)<<8,h.rev15[c]=(l>>>16|l<<16)>>>17}function p(s,g,v){for(;g--!=0;)s.push(0,v)}for(var c=0;c<32;c++)h.ldef[c]=h.of0[c]<<3|h.exb[c],h.ddef[c]=h.df0[c]<<4|h.dxb[c];p(h.fltree,144,8),p(h.fltree,112,9),p(h.fltree,24,7),p(h.fltree,8,8),f.F.makeCodes(h.fltree,9),f.F.codes2map(h.fltree,9,h.flmap),f.F.revCodes(h.fltree,9),p(h.fdtree,32,5),f.F.makeCodes(h.fdtree,5),f.F.codes2map(h.fdtree,5,h.fdmap),f.F.revCodes(h.fdtree,5),p(h.itree,19,0),p(h.ltree,286,0),p(h.dtree,30,0),p(h.ttree,320,0)}()}(X)),X.exports}var at=ot(),ht=tt(at);const P=class P{constructor(f,h,a,c,l){this.copy=()=>new P(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const p=":";let s=("0"+this.h).slice(-2)+p+("0"+this.m).slice(-2)+p+("0"+this.s).slice(-2)+p+("0"+this.f).slice(-2);return s+="."+(this.field?"1":"2"),s},this.toZipTimeCodeString=()=>{const p=this.copy();return p.f=0,p.s=p.s%2===0?p.s:p.s-1,p.field=0,P.toStr(p)},this.toFrames=p=>{let s=60,g=0;Math.floor(p)==60?(s=60,g=0):Math.floor(p)==59?(s=60,g=4):Math.floor(p)==30?(s=30,g=0):Math.floor(p)==29&&(s=30,g=2);let v=this.h,x=this.m,m=this.s,w=this.f,y=this.field;const A=v*60+x,e=(A-Math.floor(A/10))*g;return v*(s*3600)+x*(s*60)+m*s+(w*2+y)-e},this.addSeconds=p=>{let s=this.copy();return s.s+=p,s.s>=60&&(s.s=0,s.m++,s.m>=60&&(s.m=0,s.h++)),s},this.addFrames=(p,s)=>{let g=this.toFrames(s);return g+=p,P.fromFrames(g,s)},this.subtractFrames=(p,s)=>this.addFrames(-p,s),this.h=f||0,this.m=h||0,this.s=a||0,this.f=c||0,this.field=l||0}static compare(f,h){return f.h!==h.h?f.h<h.h?-1:1:f.m!==h.m?f.m<h.m?-1:1:f.s!==h.s?f.s<h.s?-1:1:f.f!==h.f?f.f<h.f?-1:1:f.field!==h.field?f.field<h.field?-1:1:0}static generateTimecodeRange(f,h,a){const c=[];let l=f;for(;P.compare(l,h)<=0;)c.push(l),l=l.addSeconds(a);return c}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(f){return this.toFrames(f)*1e3/f}};P.calculateCurrentTimeCode=f=>{var m;if(!f.video||!f.clocker||!f.gameParams)throw new Error("OTTPlayer is not initialized");const h=f.video,a=f.clocker,c=a.videoFPScalculator.getFPS(),s=(h.currentTime-a.syncPoint.playerTime)%(60*60*24)*c+a.syncPoint.frame;if(s===0||c===0)throw new Error("Current frame is 0 or fps is 0");const g=P.calculateCurrentOffset(s,(m=f.gameParams)==null?void 0:m.offsets);if(g===void 0)throw new Error("Offset is undefined");let v=Math.floor(s-g);return v<0&&(v+=5178816),v>=5178816&&(v-=5178816),P.fromFrames(v,c)},P.calculateCurrentOffset=(f,h)=>{for(let a=1;a<h.length;a++)if(f<h[a].frame)return h[a-1].offset;return h[h.length-1].offset},P.fromFrames=(f,h)=>{let a=60,c=0;Math.floor(h)==60?(a=60,c=0):Math.floor(h)==59?(a=60,c=4):Math.floor(h)==30?(a=30,c=0):Math.floor(h)==29&&(a=30,c=2);let l=Math.floor(h*60),p=Math.floor(h*60*10),s=p*6,g=f,v=Math.floor(g/s);g-=v*s;let x=Math.floor(g/p);g-=x*p,g>=a*60&&(g+=c*(Math.floor((g-a*60)/l)+1));let m=Math.floor(g/(a*60));g-=m*(a*60);let w=Math.floor(g/a);g-=w*a;let y=g;m+=x*10;let A=0;return A=y%2,y=Math.floor(y/2),new P(v,m,w,y,A)},P.toStr=f=>{const h="_";let a=("0"+f.h).slice(-2)+h+("0"+f.m).slice(-2)+h+("0"+f.s).slice(-2)+h+("0"+f.f).slice(-2);return f.field&&(a+="_1"),a},P.fromStr=f=>{const a=f.split("_").map(Number);if(a.length==4){const[c,l,p,s]=a;return new P(c,l,p,s,0)}else if(a.length==5){const[c,l,p,s,g]=a;return new P(c,l,p,s,g)}else throw new Error("Invalid timecode format: "+f)},P.fromMetadata=f=>{const h=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,a=f.timecode.match(h);if(!a)throw new Error("Invalid timecode format: "+f.timecode);const[,c,l,p,s,g]=a,v=Number(c),x=Number(l),m=Number(p),w=Number(s),y=g?Number(g):0;return new P(v,x,m,w,y)};let N=P;class Q{constructor(f,h,a){this.videoDecoder=null,this.reservedVideoDecoder=null,this.videoDecoderNeedsKeyFrame=!1,this.reservedVideoDecoderNeedsKeyFrame=!1,this.currentTimecode="",this.fps=0,this.unchunkedJobs=[],this.jobChunking=null,this.jobsQueue=[],this.chunksQueue=[],this.chunksForDecodingFrames=[],this.processedMetadata=[],this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.timecodeErrorCount=0,this.decoderStopped=!1,this.addJob=(c,l)=>{const{alphaMp4:p,metadataList:s}=this.parseZipAndMetadata(l);if(!p){this.options&&D(this.options,"Decoder")&&console.log("[Decoder] No alpha.mp4 found, no decoding needed.");return}const g={timeCode:c,alphaMp4:p,metadata:s,chunks:[],totalFrameCount:s.length,framesProcessed:0,framesSentToDecoder:0,useReserveDecoder:s.length<3};this.jobChunking?this.unchunkedJobs.push(g):(this.jobChunking=g,this.chunkJob(g)),this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Added job:",g)},this.clearOldJobsAndChunks=c=>{const p=N.fromStr(this.currentTimecode).totalMilliseconds(this.fps)-c;this.unchunkedJobs=this.unchunkedJobs.filter(s=>N.fromStr(s.timeCode).totalMilliseconds(this.fps)>p),this.jobsQueue=this.jobsQueue.filter(s=>N.fromStr(s.timeCode).totalMilliseconds(this.fps)>p),this.chunksQueue=this.chunksQueue.filter(s=>N.fromStr(s.timeCode).totalMilliseconds(this.fps)>p)},this.clearAllJobsAndChunks=()=>{this.unchunkedJobs=[],this.jobsQueue=[],this.chunksQueue=[]},this.updateCurrentTimecode=(c,l)=>{if(this.options){if(this.currentTimecode){const p=N.fromStr(c).totalMilliseconds(this.fps),s=N.fromStr(this.currentTimecode).totalMilliseconds(this.fps);if(p<s||p>s+this.options.DECODER_LEAD_TIME_MILLIS){this.timecodeErrorCount++,p<s&&this.options&&D(this.options,"Errors")&&console.error("[Decoder] Timecode is going backwards"),p>s+this.options.DECODER_LEAD_TIME_MILLIS&&this.options&&D(this.options,"Errors")&&console.error("[Decoder] Timecode is too far ahead"),this.timecodeErrorCount>5&&this.restartDecoder();return}}this.timecodeErrorCount=0,this.currentTimecode=c,this.fps=59.94,this.clearOldJobsAndChunks(2100),this.decodeUpcomingChunks()}},this.setupMP4Box=(c=!1)=>{const l=nt.createFile();return l.onError=p=>{this.options&&D(this.options,"Errors")&&console.error("[Decoder] MP4 parsing error:",p)},l.onReady=p=>{const s=p.tracks.find(g=>g.type==="video");if(s){if(!(c?this.reservedVideoDecoderConfigured:this.videoDecoderConfigured)){this.options&&D(this.options,"Decoder")&&console.error("[Decoder] Starting a new VideoDecoder");let v;c?(this.reservedVideoDecoder=new VideoDecoder({output:this.onFrameDecoded,error:this.onDecoderError}),v=this.reservedVideoDecoder):(this.videoDecoder=new VideoDecoder({output:this.onFrameDecoded,error:this.onDecoderError}),v=this.videoDecoder),v.configure({codec:s.codec,codedWidth:s.video.width,codedHeight:s.video.height,description:this.getDescription(l.getTrackById(s.id)),hardwareAcceleration:"prefer-hardware",optimizeForLatency:!0}),c?(this.reservedVideoDecoderConfigured=!0,this.reservedVideoDecoderNeedsKeyFrame=!0):(this.videoDecoderConfigured=!0,this.videoDecoderNeedsKeyFrame=!0)}l.setExtractionOptions(s.id),l.start()}},l.onSamples=async(p,s,g)=>{const v=[];for(const x of g){const m=new EncodedVideoChunk({type:x.is_sync?"key":"delta",timestamp:x.cts,data:new Uint8Array(x.data)});v.push(m)}this.storeChunks(v)},l},this.chunkJob=async c=>{this.mp4boxfile=this.setupMP4Box(c.useReserveDecoder);const p=await new Blob([c.alphaMp4],{type:"video/mp4"}).arrayBuffer();p.fileStart=0,this.mp4boxfile.appendBuffer(p)},this.storeChunks=c=>{this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Storing chunks:",c);const l=this.jobChunking;if(this.unchunkedJobs.length>0){const s=this.unchunkedJobs.shift();this.jobChunking=s,this.chunkJob(s)}else this.jobChunking=null;const p=l==null?void 0:l.metadata.map((s,g)=>({timeCode:s.timecode,chunk:c[g],metadata:s,job:l,cancelled:!1}));l.chunks=p,this.chunksQueue.push(...p),this.jobsQueue.push(l),this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Jobs Queue:",this.jobsQueue),this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Chunks Queue:",this.chunksQueue)},this.onFrameDecoded=c=>{this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Frame decoded:",c);const l=this.chunksForDecodingFrames.shift();if(!l){this.options&&D(this.options,"Errors")&&console.error("[Decoder] No current chunk for a processed frame");return}if(l.cancelled||this.decoderStopped){this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Skipping cancelled chunk:",l.timeCode),c.close();return}const p=l.metadata;l.job.framesProcessed++,p.alphaMask=c,this.processedMetadata.push(p),(this.processedMetadata.length>=this.options.DECODER_FRAME_BATCH_SIZE||l.job.framesProcessed>=l.job.totalFrameCount)&&(this.postBatchToRenderer(this.processedMetadata),this.processedMetadata.forEach(s=>s.alphaMask.close()),this.processedMetadata=[])},this.onDecoderError=c=>{var s,g;this.options&&D(this.options,"Errors")&&console.error("[Decoder] VideoDecoder error:",c),this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.videoDecoderNeedsKeyFrame=!0,this.reservedVideoDecoderNeedsKeyFrame=!0;const l=this.chunksForDecodingFrames.shift();if(!l){this.options&&D(this.options,"Errors")&&console.error("[Decoder] No broken chunk for an error");return}const p=l.job;p&&p.chunks.forEach(v=>v.cancelled=!0),(s=this.reservedVideoDecoder)==null||s.close(),(g=this.videoDecoder)==null||g.close()},this.parseZipAndMetadata=c=>{const l=ht.parse(c),p=l["alpha.mp4"]||null,s=Object.keys(l).filter(g=>g.endsWith(".json")).sort(this.numericFileComparator).map(g=>{const v=JSON.parse(new TextDecoder().decode(l[g]));return v.timecode=N.toStr(N.fromMetadata(v)),v}).filter(g=>g.placeholders);return{alphaMp4:p,metadataList:s}},this.numericFileComparator=(c,l)=>{const p=/^(\\d{2})_(\\d{2})_(\\d{2})_(\\d{2})(?:\\.(\\d+))?\\.(.+)$/,s=c.match(p),g=l.match(p);if(!s||!g)return 0;const[,v,x,m,w,y="0",A]=s,[,t,e,r,n,o="0",d]=g;return parseInt(v,10)-parseInt(t,10)||parseInt(x,10)-parseInt(e,10)||parseInt(m,10)-parseInt(r,10)||parseInt(w,10)-parseInt(n,10)||parseInt(y,10)-parseInt(o,10)||A.localeCompare(d)},this.getDescription=c=>{for(const l of c.mdia.minf.stbl.stsd.entries){const p=l.avcC||l.hvcC||l.vpcC||l.av1C;if(p){const s=new J.DataStream(void 0,0,J.DataStream.BIG_ENDIAN);return p.write(s),new Uint8Array(s.buffer,8)}}return null},this.postBatchToRenderer=f,this.restartDecoder=h,this.options=a,this.mp4boxfile=this.setupMP4Box()}decodeUpcomingChunks(){const f=N.fromStr(this.currentTimecode).totalMilliseconds(this.fps),h=f+this.options.DECODER_LEAD_TIME_MILLIS,a=this.chunksQueue.filter(l=>{const p=N.fromStr(l.timeCode).totalMilliseconds(this.fps);return p>=f&&p<=h&&!l.decoded});a.sort((l,p)=>{const s=N.fromStr(l.timeCode).totalMilliseconds(this.fps),g=N.fromStr(p.timeCode).totalMilliseconds(this.fps);return s-g});const c=a.slice(0,this.options.DECODER_FRAME_BATCH_SIZE);for(const l of c){if(l.cancelled){this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Skipping cancelled chunk:",l.timeCode);continue}const p=l.job.useReserveDecoder?this.reservedVideoDecoder:this.videoDecoder;if(!p||p.state==="closed"){this.options&&D(this.options,"Errors")&&console.error("[Decoder] No VideoDecoder available");continue}if((l.job.useReserveDecoder?this.reservedVideoDecoderNeedsKeyFrame:this.videoDecoderNeedsKeyFrame)&&l.chunk.type==="delta"){this.options&&D(this.options,"Errors")&&console.error("[Decoder] Decoder needs a key frame, skipping delta chunk:",l.timeCode),l.decoded=!0;continue}try{this.chunksForDecodingFrames.push(l),l.chunk.type==="key"&&(l.job.useReserveDecoder?this.reservedVideoDecoderNeedsKeyFrame=!1:this.videoDecoderNeedsKeyFrame=!1),p.decode(l.chunk)}catch(g){this.options&&D(this.options,"Errors")&&console.error("[Decoder] Error decoding chunk:",g),this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.videoDecoderNeedsKeyFrame=!0,this.reservedVideoDecoderNeedsKeyFrame=!0,l.job.chunks.forEach(x=>x.cancelled=!0),p.close()}finally{if(l.decoded=!0,l.job.framesSentToDecoder++,l.job.framesSentToDecoder>=l.job.totalFrameCount){p.flush(),l.job.useReserveDecoder;continue}}}}stop(){var f,h;this.decoderStopped=!0,this.clearAllJobsAndChunks();try{(f=this.videoDecoder)==null||f.close()}catch(a){this.options&&D(this.options,"Errors")&&console.error("[Decoder] Error closing main VideoDecoder:",a)}try{(h=this.reservedVideoDecoder)==null||h.close()}catch(a){this.options&&D(this.options,"Errors")&&console.error("[Decoder] Error closing reserved VideoDecoder:",a)}}}let rt=null,q=null,j,H;self.onmessage=async C=>{const{data:f}=C;if(f.type==="SET_DOWNLOADER_PORT"&&(rt=f.port,rt.onmessage=ft),f.type==="SET_RENDERER_PORT"&&(q=f.port,q.onmessage=lt),f.type==="SET_OPTIONS"&&(H=f.options,j=new Q($,Z,H)),f.type==="VIDEO_SEEKED"){if(!H)return;Z()}};function ft(C){const{data:f}=C;if(f.type==="DECODER_INPUT"){const{timeCode:h,arrayBuffer:a}=f;H&&D(H,"Decoder")&&console.log("[DecoderWorker] Received ArrayBuffer from Downloader, timeCode =",h),j.addJob(h,a)}}function lt(C){const{data:f}=C;if(f.type==="DECODER_REQUEST"){const{timeCode:h,fps:a}=f;H&&D(H,"Decoder")&&console.log("[DecoderWorker] Received TimeCode request from Renderer, timeCode =",h),j.updateCurrentTimecode(h,a)}}function Z(){H&&(j.stop(),j=new Q($,Z,H))}function $(C){if(!q)return;H&&D(H,"Decoder")&&console.log(\`[DecoderWorker] Posting a batch of \${C.length} frames to Renderer\`);const f=C.map(h=>h.alphaMask).filter(h=>h!==void 0);try{const h=new Set(f);q.postMessage({type:"RENDERER_INPUT",batch:C},[...h]),f.forEach(a=>a.close())}catch(h){console.error("[DecoderWorker] Error posting batch to Renderer:",h),f.forEach(a=>a.close());return}}self.onunhandledrejection=C=>{console.error("[Worker] Unhandled rejection:",C.reason),H&&(j.stop(),j=new Q($,Z,H))}})();
3
- `,O=typeof self<"u"&&self.Blob&&new Blob([z],{type:"text/javascript;charset=utf-8"});function Z(s){let t;try{if(t=O&&(self.URL||self.webkitURL).createObjectURL(O),!t)throw"";const e=new Worker(t,{name:s==null?void 0:s.name});return e.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(z),{name:s==null?void 0:s.name})}finally{t&&(self.URL||self.webkitURL).revokeObjectURL(t)}}const N=`(function(){"use strict";const m=(c,o)=>!c.debug||!c.debug.on?!1:c.debug[\`log\${o}\`],u=class u{constructor(o,a,e,t,i){this.copy=()=>new u(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const r=":";let s=("0"+this.h).slice(-2)+r+("0"+this.m).slice(-2)+r+("0"+this.s).slice(-2)+r+("0"+this.f).slice(-2);return s+="."+(this.field?"1":"2"),s},this.toZipTimeCodeString=()=>{const r=this.copy();return r.f=0,r.s=r.s%2===0?r.s:r.s-1,r.field=0,u.toStr(r)},this.toFrames=r=>{let s=60,n=0;Math.floor(r)==60?(s=60,n=0):Math.floor(r)==59?(s=60,n=4):Math.floor(r)==30?(s=30,n=0):Math.floor(r)==29&&(s=30,n=2);let l=this.h,h=this.m,d=this.s,R=this.f,p=this.field;const E=l*60+h,x=(E-Math.floor(E/10))*n;return l*(s*3600)+h*(s*60)+d*s+(R*2+p)-x},this.addSeconds=r=>{let s=this.copy();return s.s+=r,s.s>=60&&(s.s=0,s.m++,s.m>=60&&(s.m=0,s.h++)),s},this.addFrames=(r,s)=>{let n=this.toFrames(s);return n+=r,u.fromFrames(n,s)},this.subtractFrames=(r,s)=>this.addFrames(-r,s),this.h=o||0,this.m=a||0,this.s=e||0,this.f=t||0,this.field=i||0}static compare(o,a){return o.h!==a.h?o.h<a.h?-1:1:o.m!==a.m?o.m<a.m?-1:1:o.s!==a.s?o.s<a.s?-1:1:o.f!==a.f?o.f<a.f?-1:1:o.field!==a.field?o.field<a.field?-1:1:0}static generateTimecodeRange(o,a,e){const t=[];let i=o;for(;u.compare(i,a)<=0;)t.push(i),i=i.addSeconds(e);return t}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(o){return this.toFrames(o)*1e3/o}};u.calculateCurrentTimeCode=o=>{var d;if(!o.video||!o.clocker||!o.gameParams)throw new Error("OTTPlayer is not initialized");const a=o.video,e=o.clocker,t=e.videoFPScalculator.getFPS(),s=(a.currentTime-e.syncPoint.playerTime)%(60*60*24)*t+e.syncPoint.frame;if(s===0||t===0)throw new Error("Current frame is 0 or fps is 0");const n=u.calculateCurrentOffset(s,(d=o.gameParams)==null?void 0:d.offsets);if(n===void 0)throw new Error("Offset is undefined");let l=Math.floor(s-n);return l<0&&(l+=5178816),l>=5178816&&(l-=5178816),u.fromFrames(l,t)},u.calculateCurrentOffset=(o,a)=>{for(let e=1;e<a.length;e++)if(o<a[e].frame)return a[e-1].offset;return a[a.length-1].offset},u.fromFrames=(o,a)=>{let e=60,t=0;Math.floor(a)==60?(e=60,t=0):Math.floor(a)==59?(e=60,t=4):Math.floor(a)==30?(e=30,t=0):Math.floor(a)==29&&(e=30,t=2);let i=Math.floor(a*60),r=Math.floor(a*60*10),s=r*6,n=o,l=Math.floor(n/s);n-=l*s;let h=Math.floor(n/r);n-=h*r,n>=e*60&&(n+=t*(Math.floor((n-e*60)/i)+1));let d=Math.floor(n/(e*60));n-=d*(e*60);let R=Math.floor(n/e);n-=R*e;let p=n;d+=h*10;let E=0;return E=p%2,p=Math.floor(p/2),new u(l,d,R,p,E)},u.toStr=o=>{const a="_";let e=("0"+o.h).slice(-2)+a+("0"+o.m).slice(-2)+a+("0"+o.s).slice(-2)+a+("0"+o.f).slice(-2);return o.field&&(e+="_1"),e},u.fromStr=o=>{const e=o.split("_").map(Number);if(e.length==4){const[t,i,r,s]=e;return new u(t,i,r,s,0)}else if(e.length==5){const[t,i,r,s,n]=e;return new u(t,i,r,s,n)}else throw new Error("Invalid timecode format: "+o)},u.fromMetadata=o=>{const a=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,e=o.timecode.match(a);if(!e)throw new Error("Invalid timecode format: "+o.timecode);const[,t,i,r,s,n]=e,l=Number(t),h=Number(i),d=Number(r),R=Number(s),p=n?Number(n):0;return new u(l,h,d,R,p)};let D=u;const O=\`
4
- attribute vec2 a_position;
5
- attribute vec2 a_uv;
6
-
7
- uniform vec2 u_resolution;
8
-
9
- varying vec2 v_uv;
10
-
11
- void main() {
12
- v_uv = a_uv;
13
-
14
- vec2 clipSpace = 2.0 * (a_position / u_resolution) - 1.0;
15
- gl_Position = vec4(clipSpace, 0.0, 1.0);
16
- }
17
- \`,k=\`
18
- precision mediump float;
19
-
20
- uniform sampler2D u_alphaMask;
21
- varying vec2 v_uv;
22
-
23
- void main() {
24
- vec4 alphaColor = texture2D(u_alphaMask, v_uv);
25
-
26
- // Where the alpha map is white, make it transparent
27
- if (alphaColor.r > 0.5) {
28
- discard;
29
- } else {
30
- gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
31
- }
32
- }
33
- \`,G=\`
34
- uniform vec2 u_resolution;
35
- attribute vec2 a_position;
36
- attribute vec2 a_uv;
37
-
38
- varying vec2 v_uv;
39
-
40
- void main() {
41
- v_uv = a_uv;
42
-
43
- // convert the rectangle from pixels to 0.0 to 1.0
44
- vec2 clipSpace = 2.0 * (a_position / u_resolution) - 1.0;
45
-
46
- gl_Position = vec4(clipSpace, 0.0, 1.0);
47
- }
48
- \`,W=c=>\`
49
- #ifdef GL_FRAGMENT_PRECISION_HIGH
50
- precision highp float;
51
- #else
52
- precision mediump float;
53
- #endif
54
-
55
-
56
- uniform vec2 u_resolution;
57
- \${c.map((o,a)=>\`uniform sampler2D u_ad\${o};\`).join(\`
58
- \`)}
59
- uniform sampler2D u_alphaMask;
60
-
61
- varying vec2 v_uv;
62
-
63
- \${c.map((o,a)=>\`uniform int u_hasLogo\${o};\`).join(\`
64
- \`)}
65
- \${c.map((o,a)=>\`uniform mat3 u_matrix\${o};\`).join(\`
66
- \`)}
67
-
68
- uniform int u_hasDigitTex;
69
- uniform sampler2D u_digitTex;
70
- uniform vec2 u_digitTopLeft;
71
- uniform vec2 u_digitSize;
72
-
73
-
74
- const float Directions = 16.0; // BLUR DIRECTIONS (Default 16.0 - More is better but slower)
75
- const float QualityAd = 3.0; // BLUR QUALITY (Default 3.0 - More is better but slower)
76
- const float QualityAlpha = 5.0; // BLUR QUALITY (Default 3.0 - More is better but slower)
77
- const float BlurRadiusAd = 10.0;
78
- const float BlurRadiusAlpha = 10.0;
79
- const float Pi = 6.28318530718; // Pi*2
80
-
81
- vec4 BlurAd(sampler2D adTexture, vec2 adTexCoord) {
82
- vec2 Radius = BlurRadiusAd/u_resolution.xy;
83
- vec4 res = texture2D(adTexture, adTexCoord);
84
-
85
- for( float d=0.0; d<Pi; d+=Pi/Directions) {
86
- for(float i=1.0/QualityAd; i<=1.0; i+=1.0/QualityAd) {
87
- res += texture2D(adTexture, adTexCoord+vec2(cos(d),sin(d))*Radius*i);
88
- }
89
- }
90
-
91
- res /= QualityAd * Directions - 5.0;
92
-
93
- return res;
94
- }
95
-
96
- vec4 BlendLogo(vec2 curCoord, sampler2D ad, mat3 matrix) {
97
- vec2 texCoord;
98
- texCoord.x = (matrix[0][0]*curCoord.x + matrix[0][1]*curCoord.y + matrix[0][2]) / (matrix[2][0]*curCoord.x + matrix[2][1]*curCoord.y + 1.0);
99
- texCoord.y = (matrix[1][0]*curCoord.x + matrix[1][1]*curCoord.y + matrix[1][2]) / (matrix[2][0]*curCoord.x + matrix[2][1]*curCoord.y + 1.0);
100
- texCoord /= u_resolution;
101
-
102
- vec4 maskAlpha = texture2D(u_alphaMask, v_uv);
103
- vec4 adColor = BlurAd(ad, texCoord);
104
- float adAlpha = texture2D(ad, texCoord).a;
105
-
106
- float finalAlpha = maskAlpha.r;
107
- if (finalAlpha < 0.3)
108
- finalAlpha = 0.0;
109
- finalAlpha *= adColor.a;
110
- vec4 finalColor = vec4(adColor.rgb, finalAlpha);
111
- finalColor.rgb *= finalAlpha;
112
- return finalColor;
113
- }
114
-
115
- bool BlendDigit(vec2 curCoord) {
116
- vec2 digitCoord = (curCoord - u_digitTopLeft)/u_digitSize;//get the coordinate on the digit size
117
- if (digitCoord.x >= 0.0 && digitCoord.y >= 0.0 && digitCoord.x <= 1.0 && digitCoord.y <= 1.0) {
118
- gl_FragColor = texture2D(u_digitTex, digitCoord);
119
- return true;
120
- }
121
- return false;
122
- }
123
-
124
-
125
- void main() {
126
- vec2 curCoord = gl_FragCoord.xy;
127
- curCoord.y = u_resolution[1] - curCoord.y;
128
-
129
- if (u_hasDigitTex == 1 && (BlendDigit(curCoord))) return;
130
-
131
- \${c.map((o,a)=>\`
132
- if (u_hasLogo\${o} == 1) {
133
- gl_FragColor += BlendLogo(curCoord, u_ad\${o}, u_matrix\${o});
134
- }\`).join(\`
135
- \`)}
136
- }
137
- \`;class F{constructor(o,a){this.adTextures=new Map,this.allPlaceholders=[],this.setAllPlaceholders=e=>{this.allPlaceholders=e},this.initShadersAlphaMask=e=>{const t=this.compileShader(e,e.VERTEX_SHADER,O),i=this.compileShader(e,e.FRAGMENT_SHADER,k),r=e.createProgram();return e.attachShader(r,t),e.attachShader(r,i),e.linkProgram(r),e.getProgramParameter(r,e.LINK_STATUS)?r:(console.error("Could not link shaders:",e.getProgramInfoLog(r)),null)},this.initShadersAugmentation=e=>{const t=this.compileShader(e,e.VERTEX_SHADER,G),i=this.compileShader(e,e.FRAGMENT_SHADER,W(this.allPlaceholders)),r=e.createProgram();return e.attachShader(r,t),e.attachShader(r,i),e.linkProgram(r),e.getProgramParameter(r,e.LINK_STATUS)?r:(console.error("Could not link shaders:",e.getProgramInfoLog(r)),null)},this.compileShader=(e,t,i)=>{const r=e.createShader(t);return e.shaderSource(r,i),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS)?r:(console.error(\`Error compiling shader: \${e.getShaderInfoLog(r)}\`),e.deleteShader(r),null)},this.createTextureFromVideoFrame=e=>{const t=this.gl,i=t.createTexture();return t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.bindTexture(t.TEXTURE_2D,i),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.bindTexture(t.TEXTURE_2D,null),i},this.deleteTexture=e=>{this.gl.deleteTexture(e)},this.drawAlphaMask=e=>{if(!this.program){this.options&&m(this.options,"Errors")&&console.error("[Renderer] Program not initialized");return}(!this.positionBuffer||!this.uvBuffer)&&this.options&&m(this.options,"Errors")&&console.error("[Renderer] Buffers not initialized");const t=this.gl,i=this.program,r=t.getAttribLocation(i,"a_position"),s=t.getAttribLocation(i,"a_uv"),n=t.getUniformLocation(i,"u_alphaMask");t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e),t.uniform1i(n,0),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),t.enableVertexAttribArray(s),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0),t.clear(t.COLOR_BUFFER_BIT);let l=t.TRIANGLES;t.drawArrays(l,0,6)},this.drawAugmentation=(e,t)=>{if(!this.program){this.options&&m(this.options,"Errors")&&console.error("[Renderer] Program not initialized");return}const i=this.gl,r=this.program;if(!this.allPlaceholders){this.options&&m(this.options,"Errors")&&console.error("[Renderer] Placeholder names not initialized");return}i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,e);let s=i.getUniformLocation(r,"u_alphaMask");s&&i.uniform1i(s,0);let n=0;const l=Object.keys(t).map(g=>t[g]),h=l.map(g=>g.name);this.allPlaceholders.forEach(g=>{if(h.includes(g)&&this.adTextures.has(g)){const L=l.filter(Z=>Z.name===g)[0],C=this.adTextures.get(g);i.activeTexture(i.TEXTURE1+n),i.bindTexture(i.TEXTURE_2D,C);let N=i.getUniformLocation(r,"u_ad"+g);N&&i.uniform1i(N,n+1);let K="u_hasLogo"+g,Q=i.getUniformLocation(r,K);i.uniform1i(Q,1);let J="u_matrix"+g,q=i.getUniformLocation(r,J);i.uniformMatrix3fv(q,!1,L.tranform),n++}else{let L="u_hasLogo"+g,C=i.getUniformLocation(r,L);i.uniform1i(C,0)}});const d=i.getAttribLocation(r,"a_position"),R=i.getAttribLocation(r,"a_uv"),p=i.getUniformLocation(r,"u_resolution");i.uniform2f(p,i.canvas.width,i.canvas.height),i.bindBuffer(i.ARRAY_BUFFER,this.positionBuffer),i.enableVertexAttribArray(d),i.vertexAttribPointer(d,2,i.FLOAT,!1,0,0),i.bindBuffer(i.ARRAY_BUFFER,this.uvBuffer),i.enableVertexAttribArray(R),i.vertexAttribPointer(R,2,i.FLOAT,!1,0,0),i.viewport(0,0,i.canvas.width,i.canvas.height),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT);let E=i.TRIANGLES;i.drawArrays(E,0,6)},this.setRectangle=(e,t,i,r,s)=>{const n=t,l=i,h=t+r,d=i+s;e.bufferData(e.ARRAY_BUFFER,new Float32Array([n,l,h,l,n,d,n,d,h,l,h,d]),e.STATIC_DRAW)},this.generateAdTexture=(e,t,i)=>{const r=this.gl;if(!this.program){this.options&&m(this.options,"Errors")&&console.error("[Renderer] Program not initialized");return}r.pixelStorei(r.UNPACK_ALIGNMENT,4),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,i);const n=r.createTexture();if(r.bindTexture(r.TEXTURE_2D,n),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.bindTexture(r.TEXTURE_2D,null),!n){this.options&&m(this.options,"Errors")&&console.error("[Renderer] Failed to create texture");return}this.adTextures.set(e,n)},this.isPowerOf2=e=>(e&e-1)==0,this.setUVs=e=>{e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),e.STATIC_DRAW)},this.options=a,this.renderer=o,this.gl=o.glContext}init(){const o=this.gl;this.renderer.RENDER_ALPHAMASK?this.program=this.initShadersAlphaMask(o):this.program=this.initShadersAugmentation(o),o.useProgram(this.program);const a=o.getUniformLocation(this.program,"u_resolution");o.uniform2f(a,o.canvas.width,o.canvas.height),this.initGeometryBuffers()}initGeometryBuffers(){const o=this.gl;this.positionBuffer=o.createBuffer(),o.bindBuffer(o.ARRAY_BUFFER,this.positionBuffer),this.setRectangle(o,0,0,o.canvas.width,o.canvas.height),this.uvBuffer=o.createBuffer(),o.bindBuffer(o.ARRAY_BUFFER,this.uvBuffer),this.setUVs(o),o.bindBuffer(o.ARRAY_BUFFER,null)}updateGeometryBuffers(){const o=this.gl;if(!this.positionBuffer||!this.uvBuffer){this.options&&m(this.options,"Errors")&&console.error("[Renderer] Buffers not initialized");return}o.bindBuffer(o.ARRAY_BUFFER,this.positionBuffer),this.setRectangle(o,0,0,o.canvas.width,o.canvas.height),o.bindBuffer(o.ARRAY_BUFFER,this.uvBuffer),this.setUVs(o),o.bindBuffer(o.ARRAY_BUFFER,null)}cleanGL(){this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT)}}const S=["LeftTop","MidTopLeft","MidTopRight","RightTop","LeftBottom","MidBottomLeft","MidBottomRight","RightBottom"];class w{constructor(o,a){this.ads=[],this.getAds=async()=>{const t=await(await fetch("https://www.virtualott.com/ads/"+this.options.augmentation.channelName)).json(),i=t.filter(l=>l.name.indexOf(".json")>-1)[0].url,n=(await(await fetch(i)).json()).urls;for(const l of t){const h=await this.loadAdvImage(l);if(!h)continue;const d={name:l.name,imageUrl:l.url,image:h,adUrl:n[l.name]};this.ads.push(d)}this.setAd("LeftTop",3),this.setAd("RightBottom",4),this.uploadAdTextures()},this.loadAdvImage=async e=>{const t=\`#\${e.name}\`,i=e.url;if(t.indexOf(".json")>-1)return;const s=await(await fetch(i)).blob();return await createImageBitmap(s)},this.setAd=(e,t)=>{this.adMap.set(e,this.ads[t])},this.uploadAdTextures=()=>{this.adMap.forEach((e,t)=>{!e||!e.image||this.webgl.generateAdTexture(t,e.image,!0)})},this.getAdURLAtCoord=(e,t,i)=>{let r;return Object.keys(e).forEach(s=>{const n=e[s].corners.map(l=>({x:l.x/t.width,y:l.y/t.height}));if(this.isPointInPlaceholder(n,i)){const l=e[s].name,h=this.adMap.get(l);console.log("ad: ",h),h&&(console.log("ad.url: ",h.adUrl),r=h.adUrl)}}),r},this.isPointInPlaceholder=(e,t)=>{console.log("polygon: ",e),console.log("coord: ",t);let i=!1;const{x:r,y:s}=t,n=e.length;for(let l=0,h=n-1;l<n;h=l++){const d=e[l].x,R=e[l].y,p=e[h].x,E=e[h].y;R>s!=E>s&&r<(p-d)*(s-R)/(E-R)+d&&(i=!i)}return console.log("inside: ",i),i},this.placeholderNames=S,this.webgl=o,this.options=a,this.adMap=new Map,S.forEach(e=>{this.adMap.set(e,void 0)}),this.webgl.setAllPlaceholders(S),console.log("channelName: ",this.options.augmentation.channelName),this.getAds()}}class U{constructor(o,a){this.RENDER_ALPHAMASK=!1,this.renderDataMap=new Map,this.setWebGLEventListeners=()=>{const e=this.glContext.canvas;e.addEventListener("webglcontextlost",t=>{console.warn("Context lost:",t),t.preventDefault()}),e.addEventListener("webglcontextrestored",()=>{console.log("Context restored!"),this.webgl=new F(this,this.options),this.ads=new w(this.webgl,this.options),this.webgl.init()})},this.addMetadataBatch=e=>{e.forEach(t=>{if(!(!t.alphaMask||!t.isLive)){this.options&&m(this.options,"Renderer")&&console.log(\`[RendererWorker] Creating texture for timeCode=\${t.timecode}\`);try{const i=this.webgl.createTextureFromVideoFrame(t.alphaMask),r=t.timecode,s={width:t.processingWidth,height:t.processingHeight},n={alphaMask:i,placeholders:t.placeholders,processingSize:s};this.renderDataMap.set(r,n)}catch{this.options&&m(this.options,"Errors")&&console.error(\`[RendererWorker] Error creating texture for timeCode=\${t.timecode}\`)}finally{t.alphaMask.close()}}})},this.handleRenderDraw=(e,t)=>{var n,l,h,d,R;if(!this.streamData||this.streamData.ottActions&&!this.streamData.ottActions.toggle.web)return;const i=(n=this.renderDataMap.get(e))==null?void 0:n.alphaMask,r=(l=this.renderDataMap.get(e))==null?void 0:l.placeholders,s=(h=this.renderDataMap.get(e))==null?void 0:h.processingSize;if(!(!i||!r||!s||!this.streamData)){if((this.glContext.canvas.width!==s.width||this.glContext.canvas.height!==s.height)&&(this.glContext.canvas.width=s.width,this.glContext.canvas.height=s.height,this.webgl.updateGeometryBuffers()),t!=0)if(t>0){const p=D.fromStr(e).addFrames(1,this.streamData.fps),E=(d=this.renderDataMap.get(D.toStr(p)))==null?void 0:d.placeholders;E&&Object.keys(E).forEach(_=>{_ in r&&(r[_].tranform=r[_].tranform.map((x,g)=>x*(1-t)+E[_].tranform[g]*t))})}else{const p=Math.abs(t),E=D.fromStr(e).subtractFrames(1,this.streamData.fps),_=(R=this.renderDataMap.get(D.toStr(E)))==null?void 0:R.placeholders;_&&Object.keys(_).forEach(x=>{x in r&&(r[x].tranform=r[x].tranform.map((g,L)=>_[x].tranform[L]*(1-p)+g*p))})}this.options&&m(this.options,"Renderer")&&console.log(\`[Renderer] Render logic: binding texture for \${e}\`),this.RENDER_ALPHAMASK?this.webgl.drawAlphaMask(i):this.webgl.drawAugmentation(i,r)}},this.getAdURLByCoord=e=>{var n,l;if(!this.ads||!this.streamData||!this.streamData.timeCode||!this.renderDataMap)return null;const t=this.streamData.timeCode,i=(n=this.renderDataMap.get(t))==null?void 0:n.placeholders,r=(l=this.renderDataMap.get(t))==null?void 0:l.processingSize;if(!i||!r)return null;console.log("placeholders: ",i);const s=this.ads.getAdURLAtCoord(i,r,e);return console.log("url: ",s),s},this.deleteTexture=e=>{var i;const t=(i=this.renderDataMap.get(e))==null?void 0:i.alphaMask;t&&(this.webgl.deleteTexture(t),this.renderDataMap.delete(e))},this.deleteOldTextures=e=>{if(!this.streamData)return;const t=59.94,i=D.fromStr(e).totalMilliseconds(t);this.renderDataMap.forEach((r,s)=>{D.fromStr(s).totalMilliseconds(t)<i-100&&(this.options&&m(this.options,"Renderer")&&console.log(\`[Renderer] Deleting old texture for timeCode=\${s}\`),this.webgl.deleteTexture(r.alphaMask),this.renderDataMap.delete(s))})},this.deleteAllTextures=()=>{this.renderDataMap.forEach((e,t)=>{this.webgl.deleteTexture(e.alphaMask),this.renderDataMap.delete(t)})},this.cleanGL=()=>{this.webgl.cleanGL()},this.updateStreamData=e=>{this.streamData=e},this.glContext=o,this.webgl=new F(this,a),this.options=a,this.ads=new w(this.webgl,a),this.webgl.init()}stop(){this.cleanGL(),this.deleteAllTextures()}}let M=null,b=null,P=null,v=null,A=null,f;const T={timeCode:"",frameCorrection:0,fps:0,cloudFrontURL:"",bucketName:"",offsets:[]};let B=0,y=0;self.onmessage=c=>{const{data:o}=c;if(o.type==="INIT_OFFSCREEN"){const a=o.offscreen;if(f=o.options,v=a.getContext("webgl"),f&&m(f,"Renderer")&&console.log("[RendererWorker] Initializing OffscreenCanvas"),!v){f&&m(f,"Errors")&&console.error("[RendererWorker] Failed to acquire WebGL context");return}A=new U(v,f),f&&m(f,"Renderer")&&console.log("[RendererWorker] OffscreenCanvas initialized, gl context acquired")}if(o.type==="SET_DOWNLOADER_PORT"&&(M=o.port,M.onmessage=V),o.type==="SET_DECODER_PORT"&&(b=o.port,b.onmessage=z),o.type==="SET_ADAPTER_PORT"&&(P=o.port,P.onmessage=j),(o.type==="RENDERER_DRAW"||o.type==="RENDERER_CLEAR")&&I(o),o.type==="VIDEO_CLICK"&&A){const a=A.getAdURLByCoord(o.clickData);postMessage({type:"OPEN_URL",url:a})}if(o.type==="VIDEO_SEEKED"){if(!v||!f)return;A==null||A.stop(),A=new U(v,f)}};function X(){M&&M.postMessage({type:"DOWNLOADER_INPUT",streamData:T})}function Y(){b&&b.postMessage({type:"DECODER_REQUEST",timeCode:T.timeCode,fps:T.fps})}function I(c){H(c.streamData),A?(A.updateStreamData(T),A.cleanGL(),c.type==="RENDERER_DRAW"&&(A.handleRenderDraw(c.streamData.timeCode,c.streamData.frameCorrection),A.deleteOldTextures(c.streamData.timeCode))):f&&m(f,"Errors")&&console.error("[RendererWorker] WebGL context is not initialized."),$()}function $(){if(!f)return;const c=performance.now();c-B>f.DOWNLOADER_UPDATE_FREQUENCY&&(X(),B=c),c-y>f.DECODER_UPDATE_FREQUENCY&&(Y(),y=c)}function z(c){const{data:o}=c;if(o.type==="RENDERER_INPUT"){const a=o.batch;f&&m(f,"Renderer")&&console.log(\`[RendererWorker] Received a batch of \${a.length} frames\`),A&&A.addMetadataBatch(a)}}function V(c){const{data:o}=c;if(f&&m(f,"Renderer")&&console.log("[RendererWorker] Message from Downloader:",c.data),o.type==="OTT_ACTIONS"){const a=o.ottActions;T.ottActions=a}}function j(c){const{data:o}=c;(o.type==="RENDERER_DRAW"||o.type==="RENDERER_CLEAR")&&I(o)}function H(c){T.timeCode=c.timeCode,T.frameCorrection=c.frameCorrection,T.fps=c.fps,T.cloudFrontURL=c.cloudFrontURL,T.bucketName=c.bucketName,T.offsets=c.offsets}})();
138
- `,G=typeof self<"u"&&self.Blob&&new Blob([N],{type:"text/javascript;charset=utf-8"});function tt(s){let t;try{if(t=G&&(self.URL||self.webkitURL).createObjectURL(G),!t)throw"";const e=new Worker(t,{name:s==null?void 0:s.name});return e.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(N),{name:s==null?void 0:s.name})}finally{t&&(self.URL||self.webkitURL).revokeObjectURL(t)}}const V='(function(){"use strict";const E=(o,e)=>!o.debug||!o.debug.on?!1:o.debug[`log${e}`],b=o=>Math.abs(o-59.94005994005994)<20?59.94:Math.abs(o-29.97002997002997)<10?29.97:Math.abs(o-14.985014985014985)<8?14.98:0,T=(()=>{const o=()=>{const n=navigator.userAgent;return/windows/i.test(n)?"Windows":/android/i.test(n)?"Android":/iphone|ipad|ipod/i.test(n)?"iOS":/mac/i.test(n)?"Mac":/ipad/i.test(n)?"iPad":"Something else"},e=()=>o()==="Mac",r=()=>o()==="iPad",t=()=>o()==="iOS",l=()=>{const n=o();return n==="iOS"||n==="Mac"||n==="iPad"},c=()=>o()==="Windows",s=()=>o()==="Android",i=()=>{switch(o()){case"Windows":return"a Windows PC";case"Android":return"an Android phone";case"iOS":return"an iPhone";case"Mac":return"a Mac";case"iPad":return"an iPad";default:return"an Unknown device"}},a=()=>({header:[navigator.platform,navigator.userAgent,navigator.appVersion,navigator.vendor,window.opera],dataos:[{name:"Windows Phone",value:"Windows Phone",version:"OS"},{name:"Windows",value:"Win",version:"NT"},{name:"iPhone",value:"iPhone",version:"OS"},{name:"iPad",value:"iPad",version:"OS"},{name:"Kindle",value:"Silk",version:"Silk"},{name:"Android",value:"Android",version:"Android"},{name:"PlayBook",value:"PlayBook",version:"OS"},{name:"BlackBerry",value:"BlackBerry",version:"/"},{name:"Macintosh",value:"Mac",version:"OS X"},{name:"Linux",value:"Linux",version:"rv"},{name:"Palm",value:"Palm",version:"PalmOS"}],databrowser:[{name:"Chrome",value:"Chrome",version:"Chrome"},{name:"Firefox",value:"Firefox",version:"Firefox"},{name:"Safari",value:"Safari",version:"Version"},{name:"Internet Explorer",value:"MSIE",version:"MSIE"},{name:"Opera",value:"Opera",version:"Opera"},{name:"BlackBerry",value:"CLDC",version:"CLDC"},{name:"Mozilla",value:"Mozilla",version:"Mozilla"}],init(){const w=this.header.join(" ");return this.matchItem(w,this.dataos)},matchItem(w,M){for(let A=0;A<M.length;A+=1)if(new RegExp(M[A].value,"i").test(w))return M[A].name;return"unknown"}}).init(),m=()=>{const n=navigator.userAgent;return n.indexOf("Chrome")>-1&&n.indexOf("Edge")===-1?"Chrome":n.indexOf("Safari")>-1&&n.indexOf("Chrome")===-1?"Safari":n.indexOf("Firefox")>-1?"Firefox":n.indexOf("MSIE")>-1||n.indexOf("Trident")>-1?"Internet Explorer":n.indexOf("Edge")>-1?"Edge":"Unknown"};return{getCurrentPlatform:o,isMac:e,isiPad:r,isiPhone:t,isApple:l,isWindows:c,isAndroid:s,getDeviceDescription:i,getDeviceName:a,getBrowserName:m,isSafariMac:()=>e()&&m()==="Safari",isChromeMac:()=>e()&&m()==="Chrome",isChromeWin:()=>c()&&m()==="Chrome",isFirefoxMac:()=>e()&&m()==="Firefox",isFirefoxWin:()=>c()&&m()==="Firefox"}})(),f=class f{constructor(e,r,t,l,c){this.copy=()=>new f(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const s=":";let i=("0"+this.h).slice(-2)+s+("0"+this.m).slice(-2)+s+("0"+this.s).slice(-2)+s+("0"+this.f).slice(-2);return i+="."+(this.field?"1":"2"),i},this.toZipTimeCodeString=()=>{const s=this.copy();return s.f=0,s.s=s.s%2===0?s.s:s.s-1,s.field=0,f.toStr(s)},this.toFrames=s=>{let i=60,a=0;Math.floor(s)==60?(i=60,a=0):Math.floor(s)==59?(i=60,a=4):Math.floor(s)==30?(i=30,a=0):Math.floor(s)==29&&(i=30,a=2);let m=this.h,h=this.m,u=this.s,F=this.f,p=this.field;const v=m*60+h,n=(v-Math.floor(v/10))*a;return m*(i*3600)+h*(i*60)+u*i+(F*2+p)-n},this.addSeconds=s=>{let i=this.copy();return i.s+=s,i.s>=60&&(i.s=0,i.m++,i.m>=60&&(i.m=0,i.h++)),i},this.addFrames=(s,i)=>{let a=this.toFrames(i);return a+=s,f.fromFrames(a,i)},this.subtractFrames=(s,i)=>this.addFrames(-s,i),this.h=e||0,this.m=r||0,this.s=t||0,this.f=l||0,this.field=c||0}static compare(e,r){return e.h!==r.h?e.h<r.h?-1:1:e.m!==r.m?e.m<r.m?-1:1:e.s!==r.s?e.s<r.s?-1:1:e.f!==r.f?e.f<r.f?-1:1:e.field!==r.field?e.field<r.field?-1:1:0}static generateTimecodeRange(e,r,t){const l=[];let c=e;for(;f.compare(c,r)<=0;)l.push(c),c=c.addSeconds(t);return l}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(e){return this.toFrames(e)*1e3/e}};f.calculateCurrentTimeCode=e=>{var u;if(!e.video||!e.clocker||!e.gameParams)throw new Error("OTTPlayer is not initialized");const r=e.video,t=e.clocker,l=t.videoFPScalculator.getFPS(),i=(r.currentTime-t.syncPoint.playerTime)%(60*60*24)*l+t.syncPoint.frame;if(i===0||l===0)throw new Error("Current frame is 0 or fps is 0");const a=f.calculateCurrentOffset(i,(u=e.gameParams)==null?void 0:u.offsets);if(a===void 0)throw new Error("Offset is undefined");let m=Math.floor(i-a);return m<0&&(m+=5178816),m>=5178816&&(m-=5178816),f.fromFrames(m,l)},f.calculateCurrentOffset=(e,r)=>{for(let t=1;t<r.length;t++)if(e<r[t].frame)return r[t-1].offset;return r[r.length-1].offset},f.fromFrames=(e,r)=>{let t=60,l=0;Math.floor(r)==60?(t=60,l=0):Math.floor(r)==59?(t=60,l=4):Math.floor(r)==30?(t=30,l=0):Math.floor(r)==29&&(t=30,l=2);let c=Math.floor(r*60),s=Math.floor(r*60*10),i=s*6,a=e,m=Math.floor(a/i);a-=m*i;let h=Math.floor(a/s);a-=h*s,a>=t*60&&(a+=l*(Math.floor((a-t*60)/c)+1));let u=Math.floor(a/(t*60));a-=u*(t*60);let F=Math.floor(a/t);a-=F*t;let p=a;u+=h*10;let v=0;return v=p%2,p=Math.floor(p/2),new f(m,u,F,p,v)},f.toStr=e=>{const r="_";let t=("0"+e.h).slice(-2)+r+("0"+e.m).slice(-2)+r+("0"+e.s).slice(-2)+r+("0"+e.f).slice(-2);return e.field&&(t+="_1"),t},f.fromStr=e=>{const t=e.split("_").map(Number);if(t.length==4){const[l,c,s,i]=t;return new f(l,c,s,i,0)}else if(t.length==5){const[l,c,s,i,a]=t;return new f(l,c,s,i,a)}else throw new Error("Invalid timecode format: "+e)},f.fromMetadata=e=>{const r=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,t=e.timecode.match(r);if(!t)throw new Error("Invalid timecode format: "+e.timecode);const[,l,c,s,i,a]=t,m=Number(l),h=Number(c),u=Number(s),F=Number(i),p=a?Number(a):0;return new f(m,h,u,F,p)};let P=f;class W{constructor(){this.start=0,this.end=0,this.startTimeoutForSeconds=e=>{this.start=performance.now(),this.end=this.start+e*1e3},this.isTimeout=()=>{const e=performance.now()>=this.end;return e&&(this.start=0,this.end=0),!e}}}const C={lastRendererFrameSent:0,isRAFSeen:!1,isRVFCSeen:!1,RVFCmissed:!1,RVFCframeExpected:0,compensationMode:!1,compensationCounter:0,frameCorrection:0,lastMessageSent:""};let x=null,g,d,y=new W;self.onmessage=async o=>{const{data:e}=o;e.type==="SET_RENDERER_PORT"&&(x=e.port,x.onmessage=V),e.type==="ADAPTER_UPDATE_DATA"&&(d=e.data,O()),e.type==="SET_OPTIONS"&&(g=e.options)};function V(o){g&&E(g,"Adapter")&&console.log("[AdapterWorker] Message from Renderer:",o.data)}const O=()=>{!d||d.siData.isVideoPaused||(T.isChromeMac()?I():T.isSafariMac()&&L())},I=()=>{if(!d||d.siData.isVideoPaused||!d.vfcData.lastFrameMetadata)return;const{siData:o,vfcData:e,afData:r,debugControls:t}=d;if(!o.isRAFSeen){let l=4,c=-11,s=1,i=5;if(t){const n=parseInt(t["Window Start (ms)"],10);isNaN(n)||(l=n);const S=parseInt(t["Window End (ms)"],10);isNaN(S)||(c=S);const w=parseInt(t["Frame Correction"],10);isNaN(w)||(s=w);const M=parseInt(t["Timeout time"],10);isNaN(M)||(i=M)}const a=1e3/e.videoFPS;1e3/r.animationFPS;const m=r.lastTimestamp,h=e.storedMetadata.reduce((n,S)=>Math.abs(S.expectedDisplayTime-m)<Math.abs(n.expectedDisplayTime-m)?S:n),u=h.expectedDisplayTime-l,F=[];for(let n=-10;n<10;n++)F.push(u+n*a);const p=h.expectedDisplayTime-c,v=[];for(let n=-10;n<10;n++)v.push(p+n*a);let D=null;F.forEach((n,S)=>{m>n&&m<v[S]&&(D=S-10)}),D!==null?setTimeout(n=>R(e.lastCalculatedMediaTimeVideoFrame+n*Math.round(60/e.videoFPS)+s),i,D):R(C.lastRendererFrameSent)}},L=()=>{if(!d||d.siData.isVideoPaused||!d.vfcData.lastFrameMetadata)return;const{siData:o,vfcData:e,afData:r}=d;let t=r.lastCalculatedPlayerTimeFraction;const l=r.previousCalculatedPlayerTimeFraction;t<.3&&t>.1&&l<.3&&l>.1&&(t=Math.min(t,l));let c=0;t<.1?c=0:t>.1&&t<.3?c=(t-.1)/(.3-.1):c=1;let s=r.lastCalculatedPlayerTimeVideoFrame;c==1&&(s++,c=0),R(s,c)},R=(o,e)=>{if(!d)return;C.lastRendererFrameSent=o,d.siData.workingFps;const r=P.fromFrames(o,6e4/1001);if(y.isTimeout())N(r);else{const t=d.vfcData.videoFPS;if(t<=10||t>70){console.error("Video FPS is out of supported range: "+t),y.startTimeoutForSeconds(3),N(r);return}d.afData.animationFPS,B(r,e)}},B=(o,e)=>{const r=P.toStr(o);C.lastMessageSent=r,g&&E(g,"Adapter")&&console.log(`[AdapterWorker] Rendering augmentation for timecode: ${r} , ${o}`),k(r,e)},N=o=>{const e=P.toStr(o);g&&E(g,"Adapter")&&console.log("[AdapterWorker] Clearing augmentation"),k(e,0,!0)},k=(o,e,r)=>{if(!x||!d)return;const t=o;g&&E(g,"Adapter")&&console.log(`[AdapterWorker] Sending current time code to the Renderer: ${t}`);const l={timeCode:t,frameCorrection:e||0,fps:b(d.siData.workingFps),cloudFrontURL:d.cloudFrontURL,bucketName:d.bucketName,offsets:d.offsets},s={type:r?"RENDERER_CLEAR":"RENDERER_DRAW",streamData:l};x.postMessage(s)};setInterval(O,2)})();\n',H=typeof self<"u"&&self.Blob&&new Blob([V],{type:"text/javascript;charset=utf-8"});function et(s){let t;try{if(t=H&&(self.URL||self.webkitURL).createObjectURL(H),!t)throw"";const e=new Worker(t,{name:s==null?void 0:s.name});return e.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(V),{name:s==null?void 0:s.name})}finally{t&&(self.URL||self.webkitURL).revokeObjectURL(t)}}class it{constructor(t){this.canPlayListner=()=>this.setupCanvas(),this.clickListner=e=>{this.clicker.click(e)},this.mediaTime=0,this.timecodeChecker=new q(0),this.OTTPlayer=t,this.options=t.options,this.downloaderWorker=new Q,this.decoderWorker=new Z,this.rendererWorker=new tt,this.adapterWorker=new et,window.BB.workerInstances.push(this.downloaderWorker,this.decoderWorker,this.rendererWorker,this.adapterWorker),this.rendererToDownloader=new MessageChannel,this.downloaderToDecoder=new MessageChannel,this.decoderToRenderer=new MessageChannel,this.adapterToRenderer=new MessageChannel,this.setupWorkers(),this.canvas=document.createElement("canvas"),this.OTTPlayer.video.readyState>=3?this.setupCanvas():this.OTTPlayer.video.addEventListener("canplay",this.canPlayListner,{once:!0}),this.processedTimecodes=[],this.clicker=new J(this.OTTPlayer.video,this.rendererWorker),this.segmentFirstFrameTimecode=new g,this.syncPoint={frame:0,playerTime:0,stringTime:""},this.cacheStarted=!1,this.animationFPScalculator=new P(20),this.videoFPScalculator=new P(20),this.startAnimationFrameLoop(),this.startVideoFrameCallbackLoop()}onNewMetadata(t){const e=b(this.videoFPScalculator.getFPS());this.segmentFirstFrameTimecode=W(t),this.metadataReportedFrameTimecode=j(t),this.metadataReportedFrameTimecode&&e&&!this.cacheStarted&&(this.syncPoint=K(t,e,this.metadataReportedFrameTimecode),this.cacheStarted=!0)}async onNewSegment(t){const e=b(this.videoFPScalculator.getFPS());this.segmentFirstFrameTimecode&&e&&(this.syncPoint=$(t,e,this.segmentFirstFrameTimecode))}startAnimationFrameLoop(){const t=()=>{var e;this.animationFPScalculator.addTimestamp(performance.now()/1e3),(e=this.OTTPlayer.gameParams)!=null&&e.bucketName&&this.OTTPlayer.gameParams.offsets&&this.cacheStarted&&!this.OTTPlayer.RUN_ADAPTER&&this.callRendererWorker(),this.OTTPlayer.RUN_PIXEL_TICKERS&&this.OTTPlayer.pixelTickers.forEach(i=>{i.update()}),this.animationFPScalculator.getFPS(),this.animationFrameLoopId=requestAnimationFrame(t)};this.animationFrameLoopId=requestAnimationFrame(t)}startVideoFrameCallbackLoop(){const t=(e,i)=>{this.mediaTime=i.mediaTime,this.videoFPScalculator.addTimestamp(i.mediaTime),this.videoFrameCallbackLoopId=this.OTTPlayer.video.requestVideoFrameCallback(t)};this.videoFrameCallbackLoopId=this.OTTPlayer.video.requestVideoFrameCallback(t)}setupCanvas(){const t=this.OTTPlayer.video,e=t.parentElement;this.canvas.width=t.videoWidth,this.canvas.height=t.videoHeight,this.canvas.style.zIndex="3000",this.canvas.style.position="absolute",this.canvas.style.top="50%",this.canvas.style.transform="translateY(-50%)",this.canvas.style.left="0",this.canvas.style.width=e.style.width,this.canvas.style.height=e.style.height,this.canvas.style.pointerEvents="none",e.addEventListener("click",this.clickListner),e.style.position="relative",e.appendChild(this.canvas);const i=this.canvas.transferControlToOffscreen(),r={type:"INIT_OFFSCREEN",offscreen:i,options:this.options};this.rendererWorker.postMessage(r,[i]),t.onseeked=()=>{this.onVideoSeeked()},t.onseeking=()=>{this.onVideoSeeked()}}setupWorkers(){this.rendererWorker.postMessage({type:"SET_DOWNLOADER_PORT",port:this.rendererToDownloader.port1},[this.rendererToDownloader.port1]),this.downloaderWorker.postMessage({type:"SET_RENDERER_PORT",port:this.rendererToDownloader.port2},[this.rendererToDownloader.port2]),this.downloaderWorker.postMessage({type:"SET_DECODER_PORT",port:this.downloaderToDecoder.port1},[this.downloaderToDecoder.port1]),this.decoderWorker.postMessage({type:"SET_DOWNLOADER_PORT",port:this.downloaderToDecoder.port2},[this.downloaderToDecoder.port2]),this.decoderWorker.postMessage({type:"SET_RENDERER_PORT",port:this.decoderToRenderer.port1},[this.decoderToRenderer.port1]),this.rendererWorker.postMessage({type:"SET_DECODER_PORT",port:this.decoderToRenderer.port2},[this.decoderToRenderer.port2]),this.adapterWorker.postMessage({type:"SET_RENDERER_PORT",port:this.adapterToRenderer.port1},[this.adapterToRenderer.port1]),this.rendererWorker.postMessage({type:"SET_ADAPTER_PORT",port:this.adapterToRenderer.port2},[this.adapterToRenderer.port2]),this.downloaderWorker.postMessage({type:"SET_OPTIONS",options:this.options}),this.decoderWorker.postMessage({type:"SET_OPTIONS",options:this.options}),this.adapterWorker.postMessage({type:"SET_OPTIONS",options:this.options})}callAdapterWorker(t){this.adapterWorker.postMessage({type:"ADAPTER_UPDATE_DATA",data:t})}callRendererWorker(t,e,i){var h,l;let r=t;if(!r){const d=g.calculateCurrentTimeCode(this.OTTPlayer);r=g.toStr(d)}this.options&&y(this.options,"Clocker")&&console.log(`[Clocker] Sending current time code to the Renderer: ${r}`);const n={timeCode:r,frameCorrection:e||0,fps:b(this.videoFPScalculator.getFPS()),cloudFrontURL:this.OTTPlayer.options.cloudFrontURL,bucketName:((h=this.OTTPlayer.gameParams)==null?void 0:h.bucketName)||"",offsets:((l=this.OTTPlayer.gameParams)==null?void 0:l.offsets)||[]},o={type:i?"RENDERER_CLEAR":"RENDERER_DRAW",streamData:n};this.rendererWorker.postMessage(o)}onVideoSeeked(){this.downloaderWorker.postMessage({type:"VIDEO_SEEKED"}),this.decoderWorker.postMessage({type:"VIDEO_SEEKED"}),this.rendererWorker.postMessage({type:"VIDEO_SEEKED"})}delete(){const t=this.OTTPlayer.video,e=t.parentElement;e.removeChild(this.canvas),this.rendererWorker.terminate(),this.downloaderWorker.terminate(),this.decoderWorker.terminate(),this.adapterWorker.terminate(),this.animationFrameLoopId&&cancelAnimationFrame(this.animationFrameLoopId),this.videoFrameCallbackLoopId&&t.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),t.removeEventListener("canplay",this.canPlayListner),e.removeEventListener("click",this.clickListner)}}class rt{constructor(t){this.fetchGameParams=async(e,i)=>{const r=`${e}/${i}.json`;this.options&&y(this.options,"Fetcher")&&console.log(`[Fetcher] Fetching GameParams from ${r}`);const n=await fetch(r);if(!n.ok)throw new Error(`HTTP error! Status: ${n.status}`);const a=await n.json();return a.hasOwnProperty("bucketName")&&a.hasOwnProperty("offsets")?a:(this.options&&y(this.options,"Errors")&&console.error(`[Fetcher] Game params for ${i} not found in JSON.`),n)},this.fetchMetadata=async(e,i,r,n)=>{const o=`${`${e}/${i}`}/manifests/59.94/${n}.zip`;this.options&&y(this.options,"Fetcher")&&console.log(`[Fetcher] Fetching metadata from ${o}`);const h=await fetch(o),l=h.headers.get("x-tgi-ott-actions");let d;if(l?d=JSON.parse(l):d={toggle:{ios:!0,android:!0,web:!0}},!h.ok)throw new Error(`HTTP error! Status: ${h.status}`);return{arrayBuffer:await h.arrayBuffer(),ottActions:d}},this.options=t}}class st{constructor(){this.metrics=new Map,this.containers=[],this.createContainer=()=>{const t=document.createElement("div");t.style.display="flex",t.style.gap="10px",t.style.marginBottom="5px",t.style.fontSize="14px";const e={div:t,metrics:[]};return this.containers.push(e),document.body.appendChild(t),e},this.createMetric=(t,e)=>{const i=document.createElement("span"),r={name:t,value:"",span:i};return e.metrics.push(r),i.textContent=`${t}: ${r.value}`,e.div.appendChild(i),this.metrics.set(t,r),r},this.updateMetric=(t,e)=>{const i=this.metrics.get(t);if(!i){console.error("Metric does not exist");return}typeof e=="boolean"?i.value=e?"true":"false":i.value=e,i.span.textContent=`${t}: ${i.value}`}}delete(){this.containers.forEach(t=>{t.div.remove()})}}class nt{constructor(){this.controls=new Map,this.containers=[]}createContainer(t){const e=document.createElement("div");e.style.display="flex",e.style.flexWrap="wrap",e.style.gap="10px",e.style.padding="10px",e.style.marginBottom="10px",e.style.border="1px solid #ccc",e.style.fontSize="14px",e.style.backgroundColor="#f9f9f9";const i=document.createElement("button");i.textContent="Apply",i.style.cursor="pointer";const r={div:e,controls:[],button:i};return i.addEventListener("click",()=>{const n={};r.controls.forEach(a=>{(a.type==="input"||a.type==="select")&&(a.appliedValue=a.element.value),n[a.name]=a.appliedValue}),t&&t(n)}),e.appendChild(i),document.body.appendChild(e),this.containers.push(r),r}createInput(t,e="",i){const r=document.createElement("label");r.style.display="flex",r.style.flexDirection="column",r.style.fontWeight="bold";const n=document.createElement("span");n.textContent=t,n.style.marginBottom="3px";const a=document.createElement("input");a.type="text",a.value=String(e),a.style.minWidth="60px";const o={name:t,type:"input",element:a,container:i,appliedValue:String(e)};this.controls.set(t,o),i.controls.push(o),r.appendChild(n),r.appendChild(a),i.div.insertBefore(r,i.button)}createSelect(t,e,i="",r){const n=document.createElement("label");n.style.display="flex",n.style.flexDirection="column",n.style.fontWeight="bold";const a=document.createElement("span");a.textContent=t,a.style.marginBottom="3px";const o=document.createElement("select");o.style.minWidth="80px",Object.entries(e).forEach(([l,d])=>{const p=document.createElement("option");p.textContent=l,p.value=String(d),o.appendChild(p)}),o.value=String(i);const h={name:t,type:"select",element:o,container:r,appliedValue:String(i)};this.controls.set(t,h),r.controls.push(h),n.appendChild(a),n.appendChild(o),r.div.insertBefore(n,r.button)}exportData(){const t={};return this.controls.forEach(e=>{t[e.name]=e.appliedValue}),t}getValue(t){const e=this.controls.get(t);return e?e.appliedValue:(console.error(`No control found with name: ${t}`),"")}delete(){this.containers.forEach(t=>{t.div.remove()}),this.containers=[],this.controls.clear()}}const x=s=>s.toString().padStart(2,"0"),A=":",at=(s,t,e=!1)=>{let i="";return Array.isArray(s)?(i=[x(s[0]),x(s[1]),x(s[2]),x(s[3])].join(":"),e==!0?s[4]==1&&t?i+=".2":i+=".1":s[4]==1&&t&&(i+=".1")):(i=("0"+s.h).slice(-2)+A+("0"+s.m).slice(-2)+A+("0"+s.s).slice(-2)+A+("0"+s.f).slice(-2),i+="."+(s.field?"1":"2")),i},ot=(s,t,e)=>{let i=60,r=0;Math.floor(t)==60?(i=60,r=0):Math.floor(t)==59?(i=60,r=4):Math.floor(t)==30?(i=30,r=0):Math.floor(t)==29&&(i=30,r=2);let n=0,o=Math.floor(t*60*10)*6,h=s[0],l=s[1],d=s[2],p=s[3],_=s[4];return n+=h*o,n+=l*(i*60),n+=d*i,n+=p*2+_,n-=r*l,n+=r*Math.floor(l/10),n};class ht{constructor(){this.start=0,this.end=0,this.startTimeoutForSeconds=t=>{this.start=performance.now(),this.end=this.start+t*1e3},this.isTimeout=()=>{const t=performance.now()>=this.end;return t&&(this.start=0,this.end=0),!t}}}class lt{constructor(t){if(this.platformSupported=!0,this.firstFrameTimecode=[0,0,0,0,0],this.timeout=new ht,this.afData={counter:0,lastTimestamp:0,lastMetadataNow:0,timeFromLastRVFC:0,animationFPS:0,lastPlayerTimeFromSync:0,lastCalculatedPlayerTimeVideoFrame:0,lastCalculatedPlayerTimeFraction:0,previousCalculatedPlayerTimeFraction:2},this.vfcData={counter:0,lastTimestamp:0,timeFromLastRAF:0,videoFPS:0,lastFrameMetadata:null,lastFrameMetadataNow:0,storedMetadata:[],lastMediaTimeFromSync:0,lastCalculatedMediaTimeVideoFrame:0},this.siData={counter:0,lastTimestamp:0,timeFromLastRAF:0,timeFromLastRVFC:0,lastSeenRAFCount:0,lastSeenRVFCCount:0,isRAFSeen:!1,isRVFCSeen:!1,isVideoPaused:!0,workingFps:0,RVFCmissed:0,RVFCframeExpected:0,lastCallback:null,lastCalculatedFrame:0,lastRendererFrameSent:0,lastMessageSent:"",compensationMode:!1,compensationCounter:0,frameCorrection:0,determineFramesTimestamps:[],determineFramesIntervals:[]},this.tcTimeStamp=0,this.timecode_offset=0,this.onAnimationFrame=e=>{if(this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams){window.requestAnimationFrame(this.onAnimationFrame);return}this.afData.counter++,this.afData.lastTimestamp=performance.now(),this.afData.lastMetadataNow=e,this.afData.timeFromLastRVFC=this.afData.lastTimestamp-this.vfcData.lastTimestamp,this.afData.animationFPS=this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS(),this.siData.lastCallback=="RAF"&&this.siData.RVFCmissed++,this.siData.lastCallback="RAF";const i=(this.video.currentTime-this.syncPoint.playerTime)%(60*60*24)*(6e4/1001);this.afData.lastPlayerTimeFromSync=i;const r=Math.floor(i)+this.syncPoint.frame,n=g.calculateCurrentOffset(r,this.OTTPlayer.gameParams.offsets);let a=r-n;a<0&&(a+=5178816),a>=5178816&&(a-=5178816),a++,this.afData.lastCalculatedPlayerTimeVideoFrame=a,this.afData.previousCalculatedPlayerTimeFraction=this.afData.lastCalculatedPlayerTimeFraction,this.afData.lastCalculatedPlayerTimeFraction=i-Math.floor(i),this.metrics&&(this.metrics.updateMetric("RAF calls",this.afData.counter),this.metrics.updateMetric("Last player time",this.video.currentTime.toFixed(4)),this.metrics.updateMetric("Last player time frame",this.afData.lastCalculatedPlayerTimeVideoFrame),this.metrics.updateMetric("Last player time fraction",this.afData.lastCalculatedPlayerTimeFraction.toFixed(4)),this.metrics.updateMetric("Last player time double frame",this.afData.lastPlayerTimeFromSync.toFixed(5)),this.metrics.updateMetric("AF metadata now - perf.now()",(this.afData.lastTimestamp-this.afData.lastMetadataNow).toFixed(3)),this.metrics.updateMetric("VF ExpDispTime - AF metadata now",(this.afData.lastMetadataNow-this.vfcData.lastFrameMetadata.expectedDisplayTime).toFixed(3)),this.metrics.updateMetric("Last RAF call",this.afData.lastTimestamp.toFixed(2)),this.metrics.updateMetric("RAF - RVFC dif",this.afData.timeFromLastRVFC.toFixed(2)),this.metrics.updateMetric("Sync point to RAF time",(this.afData.lastTimestamp-this.syncPoint.lastUpdate).toFixed(2))),window.requestAnimationFrame(this.onAnimationFrame),this.determineFrameUpdate()},this.onVideoFrame=(e,i)=>{if(this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams){this.video.requestVideoFrameCallback(this.onVideoFrame);return}this.vfcData.counter++,this.vfcData.lastTimestamp=performance.now(),this.vfcData.timeFromLastRAF=this.vfcData.lastTimestamp-this.afData.lastTimestamp,this.siData.RVFCmissed=0,this.vfcData.videoFPS=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS(),this.siData.lastCallback="RVFC";const r=(i.mediaTime-this.syncPoint.playerTime)%(60*60*24)*(6e4/1001);this.vfcData.lastMediaTimeFromSync=r;const n=Math.floor(r+.1)+this.syncPoint.frame,a=g.calculateCurrentOffset(n,this.OTTPlayer.gameParams.offsets);let o=n-a;o<0&&(o+=5178816),o>=5178816&&(o-=5178816),o++,this.vfcData.lastCalculatedMediaTimeVideoFrame=o,this.vfcData.lastFrameMetadata=i,this.vfcData.storedMetadata.push(i),this.vfcData.storedMetadata.length>10&&this.vfcData.storedMetadata.shift(),this.vfcData.lastFrameMetadataNow=e,this.metrics&&(this.metrics.updateMetric("RVFC calls",this.vfcData.counter),this.metrics.updateMetric("Last metadata media time",i.mediaTime.toFixed(4)),this.metrics.updateMetric("Last metadata media time frame",this.vfcData.lastCalculatedMediaTimeVideoFrame),this.metrics.updateMetric("Time to presentation time",(i.presentationTime-e).toFixed(4)),this.metrics.updateMetric("Metadata presented frames",i.presentedFrames),this.metrics.updateMetric("Metadata processing duration",i.processingDuration),this.metrics.updateMetric("Last media time double frame",this.vfcData.lastMediaTimeFromSync.toFixed(5)),this.metrics.updateMetric("VF metadata now - perf.now()",(this.afData.lastTimestamp-this.afData.lastMetadataNow).toFixed(3)),this.metrics.updateMetric("Time to expected display time",(i.expectedDisplayTime-e).toFixed(4)),this.metrics.updateMetric("Last RVFC call",this.vfcData.lastTimestamp.toFixed(2)),this.metrics.updateMetric("Sync point to RVFC time",(i.mediaTime-this.syncPoint.playerTime).toFixed(2))),this.video.requestVideoFrameCallback(this.onVideoFrame),this.determineFrameUpdate()},this.determineFrameUpdate=()=>{var e,i,r;if(!(!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)){if(this.siData.counter++,this.siData.isVideoPaused=this.video.paused,this.siData.isRAFSeen=this.siData.lastSeenRAFCount==this.afData.counter,this.siData.isRVFCSeen=this.siData.lastSeenRVFCCount==this.vfcData.counter,this.siData.lastTimestamp=performance.now(),this.siData.timeFromLastRAF=this.siData.lastTimestamp-this.afData.lastTimestamp,this.siData.timeFromLastRVFC=this.siData.lastTimestamp-this.vfcData.lastTimestamp,this.siData.lastSeenRAFCount=this.afData.counter,this.siData.lastSeenRVFCCount=this.vfcData.counter,this.siData.workingFps=this.OTTPlayer.clocker.videoFPScalculator.getFPS(),this.metrics){const n=performance.now();if(this.siData.determineFramesTimestamps||(this.siData.determineFramesTimestamps=[]),this.siData.determineFramesTimestamps.length>0){const a=n-this.siData.determineFramesTimestamps[this.siData.determineFramesTimestamps.length-1];this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(a.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", "))}this.siData.determineFramesTimestamps.push(n),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed)}if(!this.OTTPlayer.options.ADAPTER_RUN_IN_WORKER)this.platformSpecificFrameUpdate();else{const n={siData:this.siData,vfcData:this.vfcData,afData:this.afData,debugControls:(e=this.debugControls)==null?void 0:e.exportData(),cloudFrontURL:this.OTTPlayer.options.cloudFrontURL,bucketName:((i=this.OTTPlayer.gameParams)==null?void 0:i.bucketName)||"",offsets:((r=this.OTTPlayer.gameParams)==null?void 0:r.offsets)||[]};this.OTTPlayer.clocker.callAdapterWorker(n)}}},this.determineFrameUpdateChromeMac=()=>{if(!(this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)&&!this.siData.isRAFSeen){let e=4,i=-11,r=1,n=5;if(this.debugControls){const f=parseInt(this.debugControls.getValue("Window Start (ms)"),10);isNaN(f)||(e=f);const v=parseInt(this.debugControls.getValue("Window End (ms)"),10);isNaN(v)||(i=v);const c=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(c)||(r=c);const E=parseInt(this.debugControls.getValue("Timeout time"),10);isNaN(E)||(n=E)}const a=1e3/this.vfcData.videoFPS;1e3/this.afData.animationFPS;const o=this.afData.lastTimestamp,h=this.vfcData.storedMetadata.reduce((f,v)=>Math.abs(v.expectedDisplayTime-o)<Math.abs(f.expectedDisplayTime-o)?v:f),l=h.expectedDisplayTime-e,d=[];for(let f=-10;f<10;f++)d.push(l+f*a);const p=h.expectedDisplayTime-i,_=[];for(let f=-10;f<10;f++)_.push(p+f*a);let m=null;d.forEach((f,v)=>{o>f&&o<_[v]&&(m=v-10)}),m!==null?setTimeout(f=>this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+f*Math.round(60/this.vfcData.videoFPS)+r),n,m):this.callRenderer(this.siData.lastRendererFrameSent)}},this.determineFrameUpdateSifariMac=()=>{if(this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;let e=this.afData.lastCalculatedPlayerTimeFraction;const i=this.afData.previousCalculatedPlayerTimeFraction;e<.3&&e>.1&&i<.3&&i>.1&&(e=Math.min(e,i));let r=0;e<.1?r=0:e>.1&&e<.3?r=(e-.1)/(.3-.1):r=1,this.metrics&&this.metrics.updateMetric("Compensation",r.toFixed(4));let n=this.afData.lastCalculatedPlayerTimeVideoFrame;r==1&&(n++,r=0),this.callRenderer(n)},this.callRenderer=(e,i)=>{if(!this.OTTPlayer.clocker||!this.OTTPlayer)return;this.siData.lastRendererFrameSent=e,this.metrics&&this.metrics.updateMetric("Last sent frame",e);const r=this.OTTPlayer.clocker.videoFPScalculator.getFPS();this.metrics&&this.metrics.updateMetric("FPS",r.toFixed(2));const n=g.fromFrames(e,6e4/1001);if(this.timeout.isTimeout())this.clearAugmentation(n);else{const a=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS();if(a<=10||a>70){console.error("Video FPS is out of supported range: "+a),this.timeout.startTimeoutForSeconds(3),this.clearAugmentation(n);return}this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS(),this.renderAugmentation(n,i)}},this.playbackTimeDelta=0,this.wallClockTimeDelta=0,this.dateTimeDelta=0,this.renderAugmentation=(e,i)=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const r=g.toStr(e);this.siData.lastMessageSent=r,this.playerOptions&&y(this.playerOptions,"Clocker")&&console.log(`Rendering augmentation for timecode: ${r} , ${e}`),this.metrics&&this.metrics.updateMetric("Last sent timecode",r),this.OTTPlayer.clocker.callRendererWorker(r,i)},this.clearAugmentation=e=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const i=g.toStr(e);this.playerOptions&&y(this.playerOptions,"Clocker")&&console.log("Clearing augmentation"),this.OTTPlayer.clocker.callRendererWorker(i,0,!0)},this.OTTPlayer=t,this.playerOptions=t.options,this.playerOptions&&y(this.playerOptions,"Clocker")&&console.log("Adapter is initialized",this.OTTPlayer),this.video=t.video,this.debug=this.playerOptions.debug?this.playerOptions.debug.on:!1,this.syncPoint={frame:0,playerTime:0,stringTime:"",lastUpdate:0},S.isChromeMac())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeMac;else if(S.isSafariMac(),S.isFirefoxMac())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeMac;else{this.platformSpecificFrameUpdate=()=>{};const e=S.getCurrentPlatform(),i=S.getBrowserName();console.error("Unsupported platform: "+e+" "+i),this.platformSupported=!1;return}if(this.debug){this.metrics=new st;const e=this.metrics.createContainer(),i=this.metrics.createContainer(),r=this.metrics.createContainer(),n=this.metrics.createContainer(),a=this.metrics.createContainer(),o=this.metrics.createContainer(),h=this.metrics.createContainer(),l=this.metrics.createContainer(),d=this.metrics.createContainer(),p=this.metrics.createContainer();this.metrics.createMetric("RAF calls",e),this.metrics.createMetric("RVFC calls",e),this.metrics.createMetric("RVFC missed",e),this.metrics.createMetric("Last sent frame",e),this.metrics.createMetric("Last sent timecode",e),this.metrics.createMetric("Last metadata media time",i),this.metrics.createMetric("Last player time",i),this.metrics.createMetric("Time to expected display time",i),this.metrics.createMetric("Last metadata media time frame",r),this.metrics.createMetric("Last player time frame",r),this.metrics.createMetric("Last player time fraction",r),this.metrics.createMetric("Last media time double frame",n),this.metrics.createMetric("Last player time double frame",n),this.metrics.createMetric("AF metadata now - perf.now()",a),this.metrics.createMetric("VF metadata now - perf.now()",a),this.metrics.createMetric("VF ExpDispTime - AF metadata now",a),this.metrics.createMetric("Time to presentation time",o),this.metrics.createMetric("Metadata presented frames",o),this.metrics.createMetric("Metadata processing duration",o),this.metrics.createMetric("Sync point frame",h),this.metrics.createMetric("Sync point player time",h),this.metrics.createMetric("Sync point to RVFC time",h),this.metrics.createMetric("Sync point to RAF time",h),this.metrics.createMetric("FPS",l),this.metrics.createMetric("Last RAF call",l),this.metrics.createMetric("Last RVFC call",l),this.metrics.createMetric("RAF - RVFC dif",l),this.metrics.createMetric("Determine frames intervals",d),this.metrics.createMetric("Compensation",p),this.metrics.createMetric("Drop frame compensation",p),this.debugControls=new nt;const _=this.debugControls.createContainer(),m=this.debugControls.createContainer();this.debugControls.createInput("Window Start (ms)",4,_),this.debugControls.createInput("Window End (ms)",-11,_),this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"1",m),this.debugControls.createSelect("Timeout time",{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,11:11,12:12,13:13,14:14,15:15,16:16,17:17,18:18,19:19,20:20},"5",m)}this.platformSupported&&(this.OTTPlayer.video.readyState>=3?this.setupAdapter():this.OTTPlayer.video.addEventListener("canplay",()=>this.setupAdapter(),{once:!0}))}setupAdapter(){const t=this.video;if(this.debug){const e=typeof wmcsdk<"u"?wmcsdk:wmcPlayer;console.log(e);const i=e.getAvailableVideoQualities(),r={};i.forEach(o=>{r[o.label]=o.id});const n=o=>{e.doSetVideoQuality(o.videoQuality)},a=this.debugControls.createContainer(n);this.debugControls.createSelect("videoQuality",r,i[0].id,a)}this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame),this.videoFrameCallbackLoopId=t.requestVideoFrameCallback(this.onVideoFrame)}onNewSegmentForMetadata(t){const e=ot(this.firstFrameTimecode,59.94005994005994);if(console.log(t),!t.mimeType.includes("video"))return;const i=at(this.firstFrameTimecode,!0,!0);this.playerOptions&&y(this.playerOptions,"Clocker")&&console.log("New segment ("+t.url+"): "+i+" ("+e+") playing at "+t.playbackTime);const r=t.playbackTime,n=r-this.playbackTimeDelta;this.playbackTimeDelta=r,console.log("Delta playback: ",n);const a=t.wallClockTime/1e3,o=a-this.wallClockTimeDelta;this.wallClockTimeDelta=a,console.log("Delta wallClock: ",o);const h=t.dateTime.getTime()/1e3,l=h-this.dateTimeDelta;this.dateTimeDelta=h,console.log("Delta dateTime: ",l);const d={frame:e,playerTime:r,stringTime:i,lastUpdate:performance.now()};this.syncPoint=d,this.metrics&&(this.metrics.updateMetric("Sync point frame",d.frame),this.metrics.updateMetric("Sync point player time",d.playerTime)),this.playerOptions&&y(this.playerOptions,"Clocker")&&console.log("url: "+t.url)}onNewMetadata(t){if(t&&t.metadata&&t.metadata.id==0||S.isSafariMac()){if(t.metadata.messageData)t.metadata.messageData=this.processTimedMetadata(t.metadata.messageData,t.metadata.presentationTime);else if(t.metadata.frames&&t.metadata.frames.length&&t.metadata.frames[0].key&&t.metadata.frames[0].key.toLowerCase()==="priv"){const e=t.metadata.frames.filter(i=>i.info&&i.info.toLowerCase().includes("ntc"));if(e.length){const i=`${e[e.length-1].info}\0${String.fromCharCode(...e[e.length-1].data)}`;t.metadata.messageData=this.processTimedMetadata(i,t.metadata.presentationTime)}}if(t.metadata.id==0||S.isSafariMac()&&this.timecode_offset==0){t.metadata.presentationTime*1e3;const e=new Date(this.tcTimeStamp-this.timecode_offset);let i=Math.round(e.getUTCMilliseconds()*30*2/1001)/2;const r=i%1;let n=1;r==.5&&(i=Math.floor(i),n=2),this.firstFrameTimecode=[e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),Math.floor(i),n==1?0:1],console.log("First frame timecode: ",this.firstFrameTimecode)}}}processTimedMetadata(t,e){let i="";if(t&&t.includes("www.mediakind.com/NTC")){const r=t.replace(/.*NTC./,"");let n=0;for(;n+8<=r.length;){const a=r.substring(n,n+4),o=((r.charCodeAt(n+4)*256+r.charCodeAt(n+5))*256+r.charCodeAt(n+6))*256+r.charCodeAt(n+7);if(n+8+o>r.length)break;const h=r.substring(n+8,n+8+o);a=="utc_"&&new Date(parseInt(h)).getTime()/1e3,a=="tc__"&&(this.tcTimeStamp=new Date(parseInt(h)).getTime()),a==="offs"&&(this.timecode_offset=parseInt(h)/90),n+=8+o}}return i}delete(){this.animationFrameLoopId&&cancelAnimationFrame(this.animationFrameLoopId),this.videoFrameCallbackLoopId&&this.video.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),this.intervalLoopId&&clearInterval(this.intervalLoopId),this.metrics&&this.metrics.delete(),this.debugControls&&this.debugControls.delete()}}class U{constructor(t,e){this.size=1,this.positionElement=()=>{let r=0,n=0;this.corner=="left-top"?(this.element.style.top=`${r}px`,this.element.style.left=`${n}px`):this.corner=="right-top"?(this.element.style.top=`${r}px`,this.element.style.left=`${n+this.video.offsetWidth-this.size}px`):this.corner=="right-bottom"?(this.element.style.top=`${r+this.video.offsetHeight-this.size}px`,this.element.style.left=`${n+this.video.offsetWidth-this.size}px`):this.corner=="left-bottom"&&(this.element.style.top=`${r+this.video.offsetHeight-this.size}px`,this.element.style.left=`${n}px`)},this.video=e,this.container=e.parentElement,this.corner=t;const i=document.createElement("div");i.style.position="absolute",i.style.width=`${this.size}px`,i.style.height=`${this.size}px`,i.style.transition="background-color 0s",i.style.zIndex="100000",this.element=i,this.container.appendChild(i),this.positionElement()}getRandomColor(){const i=Math.floor(Math.random()*11)+0;return`rgb(${i},${i},${i})`}update(){this.element.style.backgroundColor=this.getRandomColor(),this.positionElement()}delete(){this.container.removeChild(this.element)}static createInAllCorners(t){return[new U("left-top",t),new U("right-top",t),new U("right-bottom",t),new U("left-bottom",t)]}static updateAll(t){t.forEach(e=>e.update())}static deleteAll(t){t.forEach(e=>e.delete())}}class Y{constructor(t,e,i){this.RUN_ADAPTER=!0,this.RUN_PIXEL_TICKERS=!0,this.pixelTickers=[],this.fetchGameParams=async()=>{if(this.fetcher)try{y(this.options,"OTTPlayer")&&console.log("[OTTPlayer] GameId: ",this.options.gameId);const r=await this.fetcher.fetchGameParams(this.options.cloudFrontURL,this.options.gameId);if(r instanceof Response)throw console.log("gameParams: ",r),new Error("Error fetching game params:"+r.type);this.gameParams=r}catch(r){y(this.options,"Errors")&&console.error("[OTTPlayer] Error fetching game params:",r)}},this.video=t,this.options={...i,cloudFrontURL:"https://d1ze2lfw5ong7.cloudfront.net",augmentation:{channelName:"nba"},ADAPTER_RUN_IN_WORKER:!1,DOWNLOADER_UPDATE_FREQUENCY:1e3,DOWNLOADER_ZIP_START_OFFSET:2,DOWNLOADER_ZIP_END_OFFSET:4,DOWNLOADER_ZIP_LENGTH_SECONDS:2,DECODER_UPDATE_FREQUENCY:40,DECODER_FRAME_BATCH_SIZE:5,DECODER_LEAD_TIME_MILLIS:400},X(this.options).then(()=>{window.BB.playerInstances.length>0&&window.BB.playerInstances.forEach(r=>{r.delete()}),window.BB.workerInstances.length>0&&window.BB.workerInstances.forEach(r=>{r.terminate()}),this.clocker=new it(this),this.fetcher=new rt(this.options),this.RUN_ADAPTER&&(this.adapter=new lt(this)),this.RUN_PIXEL_TICKERS&&(this.pixelTickers=U.createInAllCorners(this.video)),this.fetchGameParams(),window.BB.playerInstances.push(this)})}onNewMetadata(t){if(this.RUN_ADAPTER){if(!this.adapter)return;this.adapter.onNewMetadata(t)}else{if(!this.clocker)return;this.clocker.onNewMetadata(t)}}onNewSegment(t){if(this.RUN_ADAPTER){if(!this.adapter)return;this.adapter.onNewSegmentForMetadata(t)}else{if(!this.clocker)return;this.clocker.onNewSegment(t)}}toggle(t){this.options.enabled=t}setFps(t){this.fps=t}delete(){var e;(e=this.clocker)==null||e.delete(),this.clocker=void 0,this.fetcher=void 0,this.adapter&&(this.adapter.delete(),this.adapter=void 0),U.deleteAll(this.pixelTickers),this.pixelTickers=[];const t=window.BB.playerInstances.indexOf(this);t>=0&&window.BB.playerInstances.splice(t,1)}}return window.BB={OTTPlayer:Y,playerInstances:[],workerInstances:[]},Y});
1
+ (function(z,fe){typeof exports=="object"&&typeof module<"u"?module.exports=fe():typeof define=="function"&&define.amd?define(fe):(z=typeof globalThis<"u"?globalThis:z||self,z.OTTPlayer=fe())})(this,function(){"use strict";const z=t=>Math.abs(t-59.94005994005994)<20?59.94:Math.abs(t-29.97002997002997)<10?29.97:Math.abs(t-14.985014985014985)<8?14.98:0,fe=t=>t>30&&t<70?59.94005994005994:t>15?29.97002997002997:t>7?14.985014985014985:0;class At{constructor(e){this.frameDurations=[],this.frameDurationsCapacity=e,this.lastTimestamp=null}addFrameDuration(e){return this.frameDurations.push(e),this.frameDurations.length>this.frameDurationsCapacity&&this.frameDurations.shift(),this.calculateAverage()}addTimestamp(e){if(this.lastTimestamp===null)return this.lastTimestamp=e,null;const n=e-this.lastTimestamp;return this.lastTimestamp=e,this.addFrameDuration(n)}calculateAverage(){if(this.frameDurations.length===0)return 0;const n=this.frameDurations.reduce((o,a)=>o+a,0)/this.frameDurations.length,r=this.frameDurations.filter(o=>Math.abs(o-n)<=n*.2);return r.reduce((o,a)=>o+a,0)/r.length||n}getFPS(){const e=this.calculateAverage();if(e===0)return 0;const n=1/e;return fe(n)}getPerciseFPS(){const e=this.calculateAverage();return e===0?0:1/e}}const U=(()=>{const t=()=>{const m=navigator.userAgent;return/windows/i.test(m)?"Windows":/android/i.test(m)?"Android":/iphone|ipad|ipod/i.test(m)?"iOS":/mac/i.test(m)?"Mac":/ipad/i.test(m)?"iPad":"Something else"},e=()=>t()==="Mac",n=()=>t()==="iPad",r=()=>t()==="iOS",s=()=>{const m=t();return m==="iOS"||m==="Mac"||m==="iPad"},i=()=>t()==="Windows",o=()=>t()==="Android",a=()=>{switch(t()){case"Windows":return"a Windows PC";case"Android":return"an Android phone";case"iOS":return"an iPhone";case"Mac":return"a Mac";case"iPad":return"an iPad";default:return"an Unknown device"}},c=()=>({header:[navigator.platform,navigator.userAgent,navigator.appVersion,navigator.vendor,window.opera],dataos:[{name:"Windows Phone",value:"Windows Phone",version:"OS"},{name:"Windows",value:"Win",version:"NT"},{name:"iPhone",value:"iPhone",version:"OS"},{name:"iPad",value:"iPad",version:"OS"},{name:"Kindle",value:"Silk",version:"Silk"},{name:"Android",value:"Android",version:"Android"},{name:"PlayBook",value:"PlayBook",version:"OS"},{name:"BlackBerry",value:"BlackBerry",version:"/"},{name:"Macintosh",value:"Mac",version:"OS X"},{name:"Linux",value:"Linux",version:"rv"},{name:"Palm",value:"Palm",version:"PalmOS"}],databrowser:[{name:"Chrome",value:"Chrome",version:"Chrome"},{name:"Firefox",value:"Firefox",version:"Firefox"},{name:"Safari",value:"Safari",version:"Version"},{name:"Internet Explorer",value:"MSIE",version:"MSIE"},{name:"Opera",value:"Opera",version:"Opera"},{name:"BlackBerry",value:"CLDC",version:"CLDC"},{name:"Mozilla",value:"Mozilla",version:"Mozilla"}],init(){const k=this.header.join(" ");return this.matchItem(k,this.dataos)},matchItem(k,le){for(let ue=0;ue<le.length;ue+=1)if(new RegExp(le[ue].value,"i").test(k))return le[ue].name;return"unknown"}}).init(),u=()=>{const m=navigator.userAgent;return m.indexOf("Chrome")>-1&&m.indexOf("Edge")===-1?"Chrome":m.indexOf("Safari")>-1&&m.indexOf("Chrome")===-1?"Safari":m.indexOf("Firefox")>-1?"Firefox":m.indexOf("MSIE")>-1||m.indexOf("Trident")>-1?"Internet Explorer":m.indexOf("Edge")>-1?"Edge":"Unknown"};return{getCurrentPlatform:t,isMac:e,isiPad:n,isiPhone:r,isApple:s,isWindows:i,isAndroid:o,getDeviceDescription:a,getDeviceName:c,getBrowserName:u,isSafariMac:()=>e()&&u()==="Safari",isChromeMac:()=>e()&&u()==="Chrome",isChromeWin:()=>i()&&u()==="Chrome",isFirefoxMac:()=>e()&&u()==="Firefox",isFirefoxWin:()=>i()&&u()==="Firefox"}})(),E=class E{constructor(e,n,r,s,i){this.copy=()=>new E(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const o=":";let a=("0"+this.h).slice(-2)+o+("0"+this.m).slice(-2)+o+("0"+this.s).slice(-2)+o+("0"+this.f).slice(-2);return a+="."+(this.field?"1":"2"),a},this.toZipTimeCodeString=()=>{const o=this.copy();return o.f=0,o.s=o.s%2===0?o.s:o.s-1,o.field=0,E.toStr(o)},this.toFrames=o=>{let a=60,c=0;Math.floor(o)==60?(a=60,c=0):Math.floor(o)==59?(a=60,c=4):Math.floor(o)==30?(a=30,c=0):Math.floor(o)==29&&(a=30,c=2);let u=this.h,l=this.m,d=this.s,f=this.f,h=this.field;const p=u*60+l,m=(p-Math.floor(p/10))*c;return u*(a*3600)+l*(a*60)+d*a+(f*2+h)-m},this.addSeconds=o=>{let a=this.copy();return a.s+=o,a.s>=60&&(a.s=0,a.m++,a.m>=60&&(a.m=0,a.h++)),a},this.addFrames=(o,a)=>{let c=this.toFrames(a);return c+=o,E.fromFrames(c,a)},this.subtractFrames=(o,a)=>this.addFrames(-o,a),this.h=e||0,this.m=n||0,this.s=r||0,this.f=s||0,this.field=i||0}static compare(e,n){return e.h!==n.h?e.h<n.h?-1:1:e.m!==n.m?e.m<n.m?-1:1:e.s!==n.s?e.s<n.s?-1:1:e.f!==n.f?e.f<n.f?-1:1:e.field!==n.field?e.field<n.field?-1:1:0}static generateTimecodeRange(e,n,r){const s=[];let i=e;for(;E.compare(i,n)<=0;)s.push(i),i=i.addSeconds(r);return s}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(e){return this.toFrames(e)*1e3/e}};E.calculateCurrentTimeCode=e=>{var d;if(!e.video||!e.clocker||!e.gameParams)throw new Error("OTTPlayer is not initialized");const n=e.video,r=e.clocker,s=r.videoFPScalculator.getFPS(),a=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*s+r.syncPoint.frame;if(a===0||s===0)throw new Error("Current frame is 0 or fps is 0");const c=E.calculateCurrentOffset(a,(d=e.gameParams)==null?void 0:d.offsets);if(c===void 0)throw new Error("Offset is undefined");let u=Math.floor(a-c);return u<0&&(u+=5178816),u>=5178816&&(u-=5178816),E.fromFrames(u,s)},E.calculateCurrentOffset=(e,n)=>{for(let r=1;r<n.length;r++)if(e<n[r].frame)return n[r-1].offset;return n[n.length-1].offset},E.fromFrames=(e,n)=>{let r=60,s=0;Math.floor(n)==60?(r=60,s=0):Math.floor(n)==59?(r=60,s=4):Math.floor(n)==30?(r=30,s=0):Math.floor(n)==29&&(r=30,s=2);let i=Math.floor(n*60),o=Math.floor(n*60*10),a=o*6,c=e,u=Math.floor(c/a);c-=u*a;let l=Math.floor(c/o);c-=l*o,c>=r*60&&(c+=s*(Math.floor((c-r*60)/i)+1));let d=Math.floor(c/(r*60));c-=d*(r*60);let f=Math.floor(c/r);c-=f*r;let h=c;d+=l*10;let p=0;return p=h%2,h=Math.floor(h/2),new E(u,d,f,h,p)},E.toStr=e=>{const n="_";let r=("0"+e.h).slice(-2)+n+("0"+e.m).slice(-2)+n+("0"+e.s).slice(-2)+n+("0"+e.f).slice(-2);return e.field&&(r+="_1"),r},E.fromStr=e=>{const r=e.split("_").map(Number);if(r.length==4){const[s,i,o,a]=r;return new E(s,i,o,a,0)}else if(r.length==5){const[s,i,o,a,c]=r;return new E(s,i,o,a,c)}else throw new Error("Invalid timecode format: "+e)},E.fromMetadata=e=>{const n=/^(\d{2}):(\d{2}):(\d{2}):(\d{2})(?:\.(\d))?$/,r=e.timecode.match(n);if(!r)throw new Error("Invalid timecode format: "+e.timecode);const[,s,i,o,a,c]=r,u=Number(s),l=Number(i),d=Number(o),f=Number(a),h=c?Number(c):0;return new E(u,l,d,f,h)};let x=E,Ot=0,Ze=0;const Lt=t=>{if(t.metadata.messageData){t.metadata.messageData=It(t.metadata.messageData,t.metadata.presentationTime);return}if(t.metadata.frames&&t.metadata.frames.length&&t.metadata.frames[0].key&&t.metadata.frames[0].key.toLowerCase()==="priv"){const e=t.metadata.frames.filter(n=>n.info&&n.info.toLowerCase().includes("ntc"));if(e.length){const n=e[e.length-1],r=`${n.info}\0${String.fromCharCode(...n.data)}`;t.metadata.messageData=It(r,t.metadata.presentationTime)}}},Dt=()=>{const t=new Date(Ot-Ze);let e=Math.round(t.getUTCMilliseconds()*30*2/1001)/2;const n=e%1;let r=1;return n===.5&&(e=Math.floor(e),r=2),new x(t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),Math.floor(e),r===1?0:1)},er=t=>{if((t&&t.metadata&&t.metadata.id==0||U.isSafariMac())&&(Lt(t),t.metadata.id==0||U.isSafariMac()&&Ze==0))return Dt()},tr=t=>(Lt(t),Dt()),It=(t,e)=>{let n="";if(t&&t.includes("www.mediakind.com/NTC")){const r=t.replace(/.*NTC./,"");let s=0;for(;s+8<=r.length;){const i=r.substring(s,s+4),o=((r.charCodeAt(s+4)*256+r.charCodeAt(s+5))*256+r.charCodeAt(s+6))*256+r.charCodeAt(s+7);if(s+8+o>r.length)break;const a=r.substring(s+8,s+8+o);i==="utc_"&&new Date(parseInt(a)).getTime()/1e3,i==="tc__"&&(Ot=new Date(parseInt(a)).getTime()),i==="offs"&&(Ze=parseInt(a)/90),s+=8+o}}return n},nr=(t,e,n)=>{const r=n.toFrames(e),s=n.print();console.log("New segment ("+t.url+"): "+s+" ("+r+") playing at "+t.playbackTime);const i=t.playbackTime;return{frame:r,playerTime:i,stringTime:s}},rr=(t,e,n)=>{const r=n.toFrames(e),s=n.print(),i=t.metadata.presentationTime;return{frame:r,playerTime:i,stringTime:s}},sr=async t=>{let e;typeof document>"u"?e=new URL(self.location.href):e=new URL(document.location.href);const n=e.searchParams.get("config");if(n){const s=await(await fetch(n)).json();Object.assign(t,s)}},A=(t,e)=>!t.debug||!t.debug.on?!1:t.debug[`log${e}`];class ir{constructor(e){this.last10=[],this.errorsInProgress=[],this.lastFrameTC=null,this.fps=e}setFPS(e){this.fps=e}timecodeRecieved(e){if(!e)return;const n=x.fromStr(e);if(this.last10.push(n),this.last10.length>10&&this.last10.shift(),this.lastFrameTC){const r=this.incrementInterlaced(this.lastFrameTC);x.compare(n,r)!==0&&(console.warn("Timecode sequence is invalid! Detected at:",e),this.errorsInProgress.push({preTCs:[...this.last10],postTCs:[],framesAfter:0,printed:!1}))}for(const r of this.errorsInProgress)r.printed||(r.postTCs.push(n),r.framesAfter++);for(const r of this.errorsInProgress)if(!r.printed&&r.framesAfter>=10){console.error("Full 20-frame sequence around error:");const s=[...r.preTCs,...r.postTCs];console.error(s.map(i=>x.toStr(i))),r.printed=!0}this.lastFrameTC=n}incrementInterlaced(e){const n=e.copy();return n.field===0?(n.field=1,n):(n.field=0,n.f++,n.f>=30&&(n.f=0,n.s++,n.s>=60&&(n.s=0,n.m++,n.m>=60&&(n.m=0,n.h++))),n)}}class or{constructor(e,n){this.click=async r=>{const s=this.video.getBoundingClientRect(),i=(r.clientX-s.left)/s.width,o=(r.clientY-s.top)/s.height,a={x:i,y:o};this.renderer.postMessage({type:"VIDEO_CLICK",clickData:a})},this.video=e,this.renderer=n,this.renderer.onmessage=r=>{if(r.data.type==="OPEN_URL"){const s=r.data.url;s&&window.open(s,"_blank")}}}}const Ft='(function(){"use strict";const v=(e,t)=>!e.debug||!e.debug.on?!1:e.debug[`log${t}`],E={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},L=console,G={};Object.keys(E).forEach(e=>{G[e]=L[e]});const ue="Datadog Browser SDK:",_={debug:G.debug.bind(L,ue),log:G.log.bind(L,ue),info:G.info.bind(L,ue),warn:G.warn.bind(L,ue),error:G.error.bind(L,ue)},We="https://docs.datadoghq.com",Rt=`${We}/real_user_monitoring/browser/troubleshooting`,we="More details:";function Ct(e,t){return(...n)=>{try{return e(...n)}catch(r){_.error(t,r)}}}function Oe(e){return e!==0&&Math.random()*100<=e}function Pn(e){return $n(e)&&e>=0&&e<=100}function $n(e){return typeof e=="number"}const le=1e3,j=60*le,vt=60*j,Un=365*(24*vt);function de(){return new Date().getTime()}function N(){return de()}function Re(){return performance.now()}function M(){return{relative:Re(),timeStamp:N()}}function Bn(){return{relative:0,timeStamp:Lt()}}function Fn(e,t){return t-e}function Gn(e,t){return e+t}function jn(e){return e-Lt()}let Ve;function Lt(){return Ve===void 0&&(Ve=performance.timing.navigationStart),Ve}const I=1024,xt=1024*I,Hn=/[^\\u0000-\\u007F]/;function Xe(e){return Hn.test(e)?window.TextEncoder!==void 0?new TextEncoder().encode(e).length:new Blob([e]).size:e.length}function zn(e){return{...e}}function It(e,t){return Object.keys(e).some(n=>e[n]===t)}function fe(e){return Object.keys(e).length===0}function P(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let e=_dd_temp_;return delete Object.prototype._dd_temp_,typeof e!="object"&&(typeof self=="object"?e=self:typeof window=="object"?e=window:e={}),e}function X(e,t){const n=P();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=e[n.Zone.__symbol__(t)]),r||(r=e[t]),r}let Ce,At=!1;function Jn(e){Ce=e}function Kn(e){At=e}function qn(e,t,n){const r=n.value;n.value=function(...o){return(Ce?b(r):r).apply(this,o)}}function b(e){return function(){return pe(e,this,arguments)}}function pe(e,t,n){try{return e.apply(t,n)}catch(r){Yn(r)}}function Yn(e){if(Ze(e),Ce)try{Ce(e)}catch(t){Ze(t)}}function Ze(...e){At&&_.error("[MONITOR]",...e)}function he(e,t){return X(P(),"setTimeout")(b(e),t)}function kt(e){X(P(),"clearTimeout")(e)}function Qe(e,t){return X(P(),"setInterval")(b(e),t)}function Dt(e){X(P(),"clearInterval")(e)}class T{constructor(t){this.onFirstSubscribe=t,this.observers=[]}subscribe(t){return this.observers.push(t),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(n=>t!==n),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(t){this.observers.forEach(n=>n(t))}}function Nt(...e){return new T(t=>{const n=e.map(r=>r.subscribe(o=>t.notify(o)));return()=>n.forEach(r=>r.unsubscribe())})}function Mt(e,t,n){let r=!1,o,s;return{throttled:(...i)=>{if(r){o=i;return}e(...i),r=!0,s=he(()=>{o&&e(...o),r=!1,o=void 0},t)},cancel:()=>{kt(s),r=!1,o=void 0}}}function $(){}function U(e){return e?(parseInt(e,10)^Math.random()*16>>parseInt(e,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,U)}const ve=/([\\w-]+)\\s*=\\s*([^;]+)/g;function Wn(e,t){for(ve.lastIndex=0;;){const n=ve.exec(e);if(n){if(n[1]===t)return n[2]}else break}}function Vn(e){const t=new Map;for(ve.lastIndex=0;;){const n=ve.exec(e);if(n)t.set(n[1],n[2]);else break}return t}function Xn(e,t,n=""){const r=e.charCodeAt(t-1),s=r>=55296&&r<=56319?t+1:t;return e.length<=s?e:`${e.slice(0,s)}${n}`}function Zn(){return Qn()===0}let Le;function Qn(){return Le??(Le=er())}function er(e=window){var t;const n=e.navigator.userAgent;return e.chrome||/HeadlessChrome/.test(n)?0:((t=e.navigator.vendor)===null||t===void 0?void 0:t.indexOf("Apple"))===0||/safari/i.test(n)&&!/chrome|android/i.test(n)?1:2}function ge(e,t,n=0,r){const o=new Date;o.setTime(o.getTime()+n);const s=`expires=${o.toUTCString()}`,i=r&&r.crossSite?"none":"strict",c=r&&r.domain?`;domain=${r.domain}`:"",a=r&&r.secure?";secure":"",l=r&&r.partitioned?";partitioned":"";document.cookie=`${e}=${t};${s};path=/;samesite=${i}${c}${a}${l}`}function et(e){return Wn(document.cookie,e)}let tt;function H(e){return tt||(tt=Vn(document.cookie)),tt.get(e)}function Pt(e,t){ge(e,"",0,t)}function tr(e){if(document.cookie===void 0||document.cookie===null)return!1;try{const t=`dd_cookie_test_${U()}`,n="test";ge(t,n,j,e);const r=et(t)===n;return Pt(t,e),r}catch(t){return _.error(t),!1}}let nt;function nr(){if(nt===void 0){const e=`dd_site_test_${U()}`,t="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!et(e);)r=`${n.pop()}.${r}`,ge(e,t,le,{domain:r});Pt(e,{domain:r}),nt=r}return nt}const Z="_dd_s";function xe(e){return Object.values(e)}function rr(e){return Object.entries(e)}const rt=4*vt,$t=15*j,or=Un,me={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},Ut=/^([a-zA-Z]+)=([a-z0-9-]+)$/,ot="&";function sr(e){return!!e&&(e.indexOf(ot)!==-1||Ut.test(e))}const ir="1";function z(e,t){const n={isExpired:ir};return t.trackAnonymousUser&&(e!=null&&e.anonymousId?n.anonymousId=e==null?void 0:e.anonymousId:n.anonymousId=U()),n}function Ie(e){return fe(e)}function Bt(e){return!Ie(e)}function Ae(e){return e.isExpired!==void 0||!cr(e)}function cr(e){return(e.created===void 0||de()-Number(e.created)<rt)&&(e.expire===void 0||de()<Number(e.expire))}function Ft(e){e.expire=String(de()+$t)}function st(e){return rr(e).map(([t,n])=>t==="anonymousId"?`aid=${n}`:`${t}=${n}`).join(ot)}function Gt(e){const t={};return sr(e)&&e.split(ot).forEach(n=>{const r=Ut.exec(n);if(r!==null){const[,o,s]=r;o==="aid"?t.anonymousId=s:t[o]=s}}),t}const ar="_dd",ur="_dd_r",lr="_dd_l",dr="rum",fr="logs";function pr(e){if(!H(Z)){const n=H(ar),r=H(ur),o=H(lr),s={};n&&(s.id=n),o&&/^[01]$/.test(o)&&(s[fr]=o),r&&/^[012]$/.test(r)&&(s[dr]=r),Bt(s)&&(Ft(s),e.persistSession(s))}}function jt(e){const t=Sr(e);return tr(t)?{type:me.COOKIE,cookieOptions:t}:void 0}function hr(e,t){const n={isLockEnabled:Zn(),persistSession:gr(t),retrieveSession:br,expireSession:r=>mr(t,r,e)};return pr(n),n}function gr(e){return t=>{ge(Z,st(t),$t,e)}}function mr(e,t,n){const r=z(t,n);ge(Z,st(r),n.trackAnonymousUser?or:rt,e)}function br(){const e=et(Z);return Gt(e)}function Sr(e){const t={};return t.secure=!!e.useSecureSessionCookie||!!e.usePartitionedCrossSiteSessionCookie,t.crossSite=!!e.usePartitionedCrossSiteSessionCookie,t.partitioned=!!e.usePartitionedCrossSiteSessionCookie,e.trackSessionAcrossSubdomains&&(t.domain=nr()),t}const yr="_dd_test_";function Ht(){try{const e=U(),t=`${yr}${e}`;localStorage.setItem(t,e);const n=localStorage.getItem(t);return localStorage.removeItem(t),e===n?{type:me.LOCAL_STORAGE}:void 0}catch{return}}function Er(e){return{isLockEnabled:!1,persistSession:zt,retrieveSession:_r,expireSession:t=>Tr(t,e)}}function zt(e){localStorage.setItem(Z,st(e))}function _r(){const e=localStorage.getItem(Z);return Gt(e)}function Tr(e,t){zt(z(e,t))}const wr=10,Or=100,Jt=[];let ke;function J(e,t,n=0){var r;const{isLockEnabled:o,persistSession:s,expireSession:i}=t,c=f=>s({...f,lock:l}),a=()=>{const f=t.retrieveSession(),h=f.lock;return f.lock&&delete f.lock,{session:f,lock:h}};if(ke||(ke=e),e!==ke){Jt.push(e);return}if(o&&n>=Or){Kt(t);return}let l,u=a();if(o){if(u.lock){De(e,t,n);return}if(l=U(),c(u.session),u=a(),u.lock!==l){De(e,t,n);return}}let d=e.process(u.session);if(o&&(u=a(),u.lock!==l)){De(e,t,n);return}if(d&&(Ae(d)?i(d):(Ft(d),o?c(d):s(d))),o&&!(d&&Ae(d))){if(u=a(),u.lock!==l){De(e,t,n);return}s(u.session),d=u.session}(r=e.after)===null||r===void 0||r.call(e,d||u.session),Kt(t)}function De(e,t,n){he(()=>{J(e,t,n+1)},wr)}function Kt(e){ke=void 0;const t=Jt.shift();t&&J(t,e)}const qt=le;function Rr(e){switch(e.sessionPersistence){case me.COOKIE:return jt(e);case me.LOCAL_STORAGE:return Ht();case void 0:{let t=jt(e);return!t&&e.allowFallbackToLocalStorage&&(t=Ht()),t}default:_.error(`Invalid session persistence \'${String(e.sessionPersistence)}\'`)}}function Cr(e,t,n,r){const o=new T,s=new T,i=new T,c=e.type===me.COOKIE?hr(t,e.cookieOptions):Er(t),{expireSession:a}=c,l=Qe(p,qt);let u;y();const{throttled:d,cancel:f}=Mt(()=>{J({process:m=>{if(Ie(m))return;const ae=S(m);return Te(ae),ae},after:m=>{Bt(m)&&!F()&&Di(m),u=m}},c)},qt);function h(){J({process:m=>F()?S(m):void 0},c)}function p(){J({process:m=>Ae(m)?z(m,t):void 0,after:S},c)}function S(m){return Ae(m)&&(m=z(m,t)),F()&&(Ai(m)?ki():(i.notify({previousState:u,newState:m}),u=m)),m}function y(){J({process:m=>{if(Ie(m))return z(m,t)},after:m=>{u=m}},c)}function Te(m){if(Ie(m))return!1;const{trackingType:ae,isTracked:Mi}=r(m[n]);m[n]=ae,delete m.isExpired,Mi&&!m.id&&(m.id=U(),m.created=String(de()))}function F(){return u[n]!==void 0}function Ai(m){return u.id!==m.id||u[n]!==m[n]}function ki(){u=z(u,t),s.notify()}function Di(m){u=m,o.notify()}function Ni(m){J({process:ae=>({...ae,...m}),after:S},c)}return{expandOrRenewSession:d,expandSession:h,getSession:()=>u,renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i,restartSession:y,expire:()=>{f(),a(u),S(z(u,t))},stop:()=>{Dt(l)},updateSessionState:Ni}}const it={GRANTED:"granted",NOT_GRANTED:"not-granted"};function vr(e){const t=new T;return{tryToInit(n){e||(e=n)},update(n){e=n,t.notify()},isGranted(){return e===it.GRANTED},observable:t}}function K(e,t,n){if(typeof e!="object"||e===null)return JSON.stringify(e);const r=Q(Object.prototype),o=Q(Array.prototype),s=Q(Object.getPrototypeOf(e)),i=Q(e);try{return JSON.stringify(e,t,n)}catch{return"<error: unable to serialize object>"}finally{r(),o(),s(),i()}}function Q(e){const t=e,n=t.toJSON;return n?(delete t.toJSON,()=>{t.toJSON=n}):$}function ct(e){return Lr(e,location.href).href}function Lr(e,t){const n=xr();if(n)try{return t!==void 0?new n(e,t):new n(e)}catch(s){throw new Error(`Failed to construct URL: ${String(s)} ${K({url:e,base:t})}`)}if(t===void 0&&!/:/.test(e))throw new Error(`Invalid URL: \'${e}\'`);let r=document;const o=r.createElement("a");if(t!==void 0){r=document.implementation.createHTMLDocument("");const s=r.createElement("base");s.href=t,r.head.appendChild(s),r.body.appendChild(o)}return o.href=e,o}const Yt=URL;let Ne;function xr(){if(Ne===void 0)try{Ne=new Yt("http://test/path").href==="http://test/path"}catch{Ne=!1}return Ne?Yt:void 0}const Ir="datad0g.com",Ar="dd0g-gov.com",ee="datadoghq.com",kr="ddog-gov.com",Dr="pci.browser-intake-datadoghq.com",Nr=["ddsource","ddtags"];function be(e,t,n){const r=Mr(e,t);return{build(o,s){const i=$r(e,t,n,o,s);return r(i)},urlPrefix:r(""),trackType:t}}function Mr(e,t){const n=`/api/v2/${t}`,r=e.proxy;if(typeof r=="string"){const s=ct(r);return i=>`${s}?ddforward=${encodeURIComponent(`${n}?${i}`)}`}if(typeof r=="function")return s=>r({path:n,parameters:s});const o=Pr(t,e);return s=>`https://${o}${n}?${s}`}function Pr(e,t){const{site:n=ee,internalAnalyticsSubdomain:r}=t;if(e==="logs"&&t.usePciIntake&&n===ee)return Dr;if(r&&n===ee)return`${r}.${ee}`;if(n===Ar)return`http-intake.logs.${n}`;const o=n.split("."),s=o.pop();return`browser-intake-${o.join("-")}.${s}`}function $r({clientToken:e,internalAnalyticsSubdomain:t},n,r,o,{retry:s,encoding:i}){const c=["sdk_version:6.5.0",`api:${o}`].concat(r);s&&c.push(`retry_count:${s.count}`,`retry_after:${s.lastFailureStatus}`);const a=["ddsource=browser",`ddtags=${encodeURIComponent(c.join(","))}`,`dd-api-key=${e}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${U()}`];return i&&a.push(`dd-evp-encoding=${i}`),n==="rum"&&a.push(`batch_time=${N()}`),t&&a.reverse(),a.join("&")}const Ur=200;function Br(e){const{env:t,service:n,version:r,datacenter:o}=e,s=[];return t&&s.push(Me("env",t)),n&&s.push(Me("service",n)),r&&s.push(Me("version",r)),o&&s.push(Me("datacenter",o)),s}function Me(e,t){const n=Ur-e.length-1;(t.length>n||Fr(t))&&_.warn(`${e} value doesn\'t meet tag requirements and will be sanitized. ${we} ${We}/getting_started/tagging/#defining-tags`);const r=t.replace(/,/g,"_");return`${e}:${r}`}function Fr(e){return Gr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(e):!1}function Gr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function jr(e){const t=e.site||ee,n=Br(e),r=Hr(e,n);return{replica:zr(e,n),site:t,...r}}function Hr(e,t){return{logsEndpointBuilder:be(e,"logs",t),rumEndpointBuilder:be(e,"rum",t),sessionReplayEndpointBuilder:be(e,"replay",t)}}function zr(e,t){if(!e.replica)return;const n={...e,site:ee,clientToken:e.replica.clientToken},r={logsEndpointBuilder:be(n,"logs",t),rumEndpointBuilder:be(n,"rum",t)};return{applicationId:e.replica.applicationId,...r}}function Jr(e){return Nr.every(t=>e.includes(t))}function at(e,t){return e!=null&&typeof e!="string"?(_.error(`${t} must be defined as a string`),!1):!0}function Kr(e){return e&&typeof e=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(e)?(_.error(`Site should be a valid Datadog site. ${we} ${We}/getting_started/site/.`),!1):!0}function Pe(e,t){return e!==void 0&&!Pn(e)?(_.error(`${t} Sample Rate should be a number between 0 and 100`),!1):!0}function qr(e){var t,n,r,o,s,i;if(!e||!e.clientToken){_.error("Client Token is not configured, we will not send any data.");return}if(!(!Kr(e.site)||!Pe(e.sessionSampleRate,"Session")||!Pe(e.telemetrySampleRate,"Telemetry")||!Pe(e.telemetryConfigurationSampleRate,"Telemetry Configuration")||!Pe(e.telemetryUsageSampleRate,"Telemetry Usage")||!at(e.version,"Version")||!at(e.env,"Env")||!at(e.service,"Service"))){if(e.trackingConsent!==void 0&&!It(it,e.trackingConsent)){_.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:e.beforeSend&&Ct(e.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:Rr(e),sessionSampleRate:(t=e.sessionSampleRate)!==null&&t!==void 0?t:100,telemetrySampleRate:(n=e.telemetrySampleRate)!==null&&n!==void 0?n:20,telemetryConfigurationSampleRate:(r=e.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(o=e.telemetryUsageSampleRate)!==null&&o!==void 0?o:5,service:e.service||void 0,silentMultipleInit:!!e.silentMultipleInit,allowUntrustedEvents:!!e.allowUntrustedEvents,trackingConsent:(s=e.trackingConsent)!==null&&s!==void 0?s:it.GRANTED,trackAnonymousUser:(i=e.trackAnonymousUser)!==null&&i!==void 0?i:!0,storeContextsAcrossPages:!!e.storeContextsAcrossPages,batchBytesLimit:16*I,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*le,batchMessagesLimit:50,messageBytesLimit:256*I,...jr(e)}}}function Yr(e){return{session_sample_rate:e.sessionSampleRate,telemetry_sample_rate:e.telemetrySampleRate,telemetry_configuration_sample_rate:e.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:e.telemetryUsageSampleRate,use_before_send:!!e.beforeSend,use_partitioned_cross_site_session_cookie:e.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:e.useSecureSessionCookie,use_proxy:!!e.proxy,silent_multiple_init:e.silentMultipleInit,track_session_across_subdomains:e.trackSessionAcrossSubdomains,track_anonymous_user:e.trackAnonymousUser,session_persistence:e.sessionPersistence,allow_fallback_to_local_storage:!!e.allowFallbackToLocalStorage,store_contexts_across_pages:!!e.storeContextsAcrossPages,allow_untrusted_events:!!e.allowUntrustedEvents,tracking_consent:e.trackingConsent}}var ut;(function(e){e.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",e.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(ut||(ut={}));const Wt=new Set;function Wr(e){Array.isArray(e)&&Vr(e.filter(t=>It(ut,t)))}function Vr(e){e.forEach(t=>{Wt.add(t)})}function Xr(){return Wt}const Se="?";function A(e){const t=[];let n=lt(e,"stack");const r=String(e);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`\n`).forEach(o=>{const s=eo(o)||no(o)||oo(o)||co(o);s&&(!s.func&&s.line&&(s.func=Se),t.push(s))}),{message:lt(e,"message"),name:lt(e,"name"),stack:t}}const Vt="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",te="(?::(\\\\d+))",Zr=new RegExp(`^\\\\s*at (.*?) ?\\\\(${Vt}${te}?${te}?\\\\)?\\\\s*$`,"i"),Qr=new RegExp(`\\\\((\\\\S*)${te}${te}\\\\)`);function eo(e){const t=Zr.exec(e);if(!t)return;const n=t[2]&&t[2].indexOf("native")===0,r=t[2]&&t[2].indexOf("eval")===0,o=Qr.exec(t[2]);return r&&o&&(t[2]=o[1],t[3]=o[2],t[4]=o[3]),{args:n?[t[2]]:[],column:t[4]?+t[4]:void 0,func:t[1]||Se,line:t[3]?+t[3]:void 0,url:n?void 0:t[2]}}const to=new RegExp(`^\\\\s*at ?${Vt}${te}?${te}??\\\\s*$`,"i");function no(e){const t=to.exec(e);if(t)return{args:[],column:t[3]?+t[3]:void 0,func:Se,line:t[2]?+t[2]:void 0,url:t[1]}}const ro=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function oo(e){const t=ro.exec(e);if(t)return{args:[],column:t[4]?+t[4]:void 0,func:t[1]||Se,line:+t[3],url:t[2]}}const so=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,io=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function co(e){const t=so.exec(e);if(!t)return;const n=t[3]&&t[3].indexOf(" > eval")>-1,r=io.exec(t[3]);return n&&r&&(t[3]=r[1],t[4]=r[2],t[5]=void 0),{args:t[2]?t[2].split(","):[],column:t[5]?+t[5]:void 0,func:t[1]||Se,line:t[4]?+t[4]:void 0,url:t[3]}}function lt(e,t){if(typeof e!="object"||!e||!(t in e))return;const n=e[t];return typeof n=="string"?n:void 0}function ao(e,t,n,r){const o=[{url:t,column:r,line:n}],{name:s,message:i}=lo(e);return{name:s,message:i,stack:o}}const uo=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function lo(e){let t,n;return{}.toString.call(e)==="[object String]"&&([,t,n]=uo.exec(e)),{name:t,message:n}}function $e(e){const n=new Error(e);n.name="HandlingStack";let r;return pe(()=>{const o=A(n);o.stack=o.stack.slice(2),r=q(o)}),r}function q(e){let t=Xt(e);return e.stack.forEach(n=>{const r=n.func==="?"?"<anonymous>":n.func,o=n.args&&n.args.length>0?`(${n.args.join(", ")})`:"",s=n.line?`:${n.line}`:"",i=n.line&&n.column?`:${n.column}`:"";t+=`\n at ${r}${o} @ ${n.url}${s}${i}`}),t}function Xt(e){return`${e.name||"Error"}: ${e.message}`}function Y(e,t,n,{computeHandlingStack:r}={}){let o=e[t];if(typeof o!="function")if(t in e&&t.startsWith("on"))o=$;else return{stop:$};let s=!1;const i=function(){if(s)return o.apply(this,arguments);const c=Array.from(arguments);let a;pe(n,null,[{target:this,parameters:c,onPostCall:u=>{a=u},handlingStack:r?$e("instrumented method"):void 0}]);const l=o.apply(this,c);return a&&pe(a,null,[l]),l};return e[t]=i,{stop:()=>{s=!0,e[t]===i&&(e[t]=o)}}}const fo=220*I,po="$",ho=3;function k(e,t=fo){const n=Q(Object.prototype),r=Q(Array.prototype),o=[],s=new WeakMap,i=dt(e,po,void 0,o,s),c=JSON.stringify(i);let a=c?c.length:0;if(a>t){pt(t,"discarded",e);return}for(;o.length>0&&a<t;){const l=o.shift();let u=0;if(Array.isArray(l.source))for(let d=0;d<l.source.length;d++){const f=dt(l.source[d],l.path,d,o,s);if(f!==void 0?a+=JSON.stringify(f).length:a+=4,a+=u,u=1,a>t){pt(t,"truncated",e);break}l.target[d]=f}else for(const d in l.source)if(Object.prototype.hasOwnProperty.call(l.source,d)){const f=dt(l.source[d],l.path,d,o,s);if(f!==void 0&&(a+=JSON.stringify(f).length+u+d.length+ho,u=1),a>t){pt(t,"truncated",e);break}l.target[d]=f}}return n(),r(),i}function dt(e,t,n,r,o){const s=bo(e);if(!s||typeof s!="object")return go(s);const i=ft(s);if(i!=="[Object]"&&i!=="[Array]"&&i!=="[Error]")return i;const c=e;if(o.has(c))return`[Reference seen at ${o.get(c)}]`;const a=n!==void 0?`${t}.${n}`:t,l=Array.isArray(s)?[]:{};return o.set(c,a),r.push({source:s,target:l,path:a}),l}function go(e){return typeof e=="bigint"?`[BigInt] ${e.toString()}`:typeof e=="function"?`[Function] ${e.name||"unknown"}`:typeof e=="symbol"?`[Symbol] ${e.description||e.toString()}`:e}function ft(e){try{if(e instanceof Event)return mo(e);if(e instanceof RegExp)return`[RegExp] ${e.toString()}`;const n=Object.prototype.toString.call(e).match(/\\[object (.*)\\]/);if(n&&n[1])return`[${n[1]}]`}catch{}return"[Unserializable]"}function mo(e){return{type:e.type,isTrusted:e.isTrusted,currentTarget:e.currentTarget?ft(e.currentTarget):null,target:e.target?ft(e.target):null}}function bo(e){const t=e;if(t&&typeof t.toJSON=="function")try{return t.toJSON()}catch{}return e}function pt(e,t,n){_.warn(`The data provided has been ${t} as it is over the limit of ${e} characters:`,n)}const Zt="No stack, consider using an instance of Error";function Qt({stackTrace:e,originalError:t,handlingStack:n,componentStack:r,startClocks:o,nonErrorPrefix:s,source:i,handling:c}){const a=B(t),l=So(e,a,s,t),u=yo(a,e)?q(e):Zt,d=a?nn(t,i):void 0,f=e?e.name:void 0,h=en(t),p=tn(t);return{startClocks:o,source:i,handling:c,handlingStack:n,componentStack:r,originalError:t,type:f,message:l,stack:u,causes:d,fingerprint:h,context:p}}function So(e,t,n,r){return e!=null&&e.message&&(e!=null&&e.name)?e.message:t?"Empty message":`${n} ${K(k(r))}`}function yo(e,t){return t===void 0?!1:e?!0:t.stack.length>0&&(t.stack.length>1||t.stack[0].url!==void 0)}function en(e){return B(e)&&"dd_fingerprint"in e?String(e.dd_fingerprint):void 0}function tn(e){if(e!==null&&typeof e=="object"&&"dd_context"in e)return e.dd_context}function Eo(e){var t;return(t=/@ (.+)/.exec(e))===null||t===void 0?void 0:t[1]}function B(e){return e instanceof Error||Object.prototype.toString.call(e)==="[object Error]"}function nn(e,t){let n=e;const r=[];for(;B(n==null?void 0:n.cause)&&r.length<10;){const o=A(n.cause);r.push({message:n.cause.message,source:t,type:o==null?void 0:o.name,stack:q(o)}),n=n.cause}return r.length?r:void 0}const R={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function _o(e){const t=(o,s)=>{const i=Qt({stackTrace:o,originalError:s,startClocks:M(),nonErrorPrefix:"Uncaught",source:R.SOURCE,handling:"unhandled"});e.notify(i)},{stop:n}=To(t),{stop:r}=wo(t);return{stop:()=>{n(),r()}}}function To(e){return Y(window,"onerror",({parameters:[t,n,r,o,s]})=>{let i;B(s)?i=A(s):i=ao(t,n,r,o),e(i,s??t)})}function wo(e){return Y(window,"onunhandledrejection",({parameters:[t]})=>{const n=t.reason||"Empty reason",r=A(n);e(r,n)})}function Oo(e){const t={version:"6.5.0",onReady(n){n()},...e};return Object.defineProperty(t,"_setDebug",{get(){return Kn},enumerable:!1}),t}function Ro(e,t,n){const r=e[t];r&&!r.q&&r.version&&_.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),e[t]=n,r&&r.q&&r.q.forEach(o=>Ct(o,"onReady callback threw an error:")())}function rn(e,t){t.silentMultipleInit||_.error(`${e} is already initialized.`)}function W(e,t,n,r,o){return ht(e,t,[n],r,o)}function ht(e,t,n,r,{once:o,capture:s,passive:i}={}){const c=b(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!e.allowUntrustedEvents||(o&&d(),r(f))}),a=i?{capture:s,passive:i}:s,l=window.EventTarget&&t instanceof EventTarget?window.EventTarget.prototype:t,u=X(l,"addEventListener");n.forEach(f=>u.call(t,f,c,a));function d(){const f=X(l,"removeEventListener");n.forEach(h=>f.call(t,h,c,a))}return{stop:d}}const Ue={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function Co(e,t){const n=[];t.includes(Ue.cspViolation)&&n.push(Lo(e));const r=t.filter(o=>o!==Ue.cspViolation);return r.length&&n.push(vo(r)),Nt(...n)}function vo(e){return new T(t=>{if(!window.ReportingObserver)return;const n=b((o,s)=>o.forEach(i=>t.notify(xo(i)))),r=new window.ReportingObserver(n,{types:e,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function Lo(e){return new T(t=>{const{stop:n}=W(e,document,"securitypolicyviolation",r=>{t.notify(Io(r))});return n})}function xo(e){const{type:t,body:n}=e;return on({type:n.id,message:`${t}: ${n.message}`,originalError:e,stack:sn(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function Io(e){const t=`\'${e.blockedURI}\' blocked by \'${e.effectiveDirective}\' directive`;return on({type:e.effectiveDirective,message:`${Ue.cspViolation}: ${t}`,originalError:e,csp:{disposition:e.disposition},stack:sn(e.effectiveDirective,e.originalPolicy?`${t} of the policy "${Xn(e.originalPolicy,100,"...")}"`:"no policy",e.sourceFile,e.lineNumber,e.columnNumber)})}function on(e){return{startClocks:M(),source:R.REPORT,handling:"unhandled",...e}}function sn(e,t,n,r,o){return n?q({name:e,message:t,stack:[{func:"?",url:n,line:r??void 0,column:o??void 0}]}):void 0}function cn(e,t){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:e,payload:t})}function an(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Be(e,t,n=Ao()){if(t===void 0)return e;if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=t.flags||[t.global?"g":"",t.ignoreCase?"i":"",t.multiline?"m":"",t.sticky?"y":"",t.unicode?"u":""].join("");return new RegExp(t.source,o)}if(n.hasAlreadyBeenSeen(t))return;if(Array.isArray(t)){const o=Array.isArray(e)?e:[];for(let s=0;s<t.length;++s)o[s]=Be(o[s],t[s],n);return o}const r=an(e)==="object"?e:{};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=Be(r[o],t[o],n));return r}function un(e){return Be(void 0,e)}function ne(...e){let t;for(const n of e)n!=null&&(t=Be(t,n));return t}function Ao(){if(typeof WeakSet<"u"){const t=new WeakSet;return{hasAlreadyBeenSeen(n){const r=t.has(n);return r||t.add(n),r}}}const e=[];return{hasAlreadyBeenSeen(t){const n=e.indexOf(t)>=0;return n||e.push(t),n}}}function ko(){var e;const t=window.navigator;return{status:t.onLine?"connected":"not_connected",interfaces:t.connection&&t.connection.type?[t.connection.type]:void 0,effective_type:(e=t.connection)===null||e===void 0?void 0:e.effectiveType}}function Do(e){const t=new Set;return e.forEach(n=>t.add(n)),Array.from(t)}function ln(e,t){const n=e.indexOf(t);n>=0&&e.splice(n,1)}const No=500;function dn(){const e=[];return{add:o=>{e.push(o)>No&&e.splice(0,1)},remove:o=>{ln(e,o)},drain:o=>{e.forEach(s=>s(o)),e.length=0}}}const V={log:"log",configuration:"configuration",usage:"usage"},Mo=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],Po=[kr];let fn=dn(),re=e=>{fn.add(()=>re(e))};function $o(e,t){let n;const r=new T,o=new Set,s=!Po.includes(t.site)&&Oe(t.telemetrySampleRate),i={[V.log]:s,[V.configuration]:s&&Oe(t.telemetryConfigurationSampleRate),[V.usage]:s&&Oe(t.telemetryUsageSampleRate)},c=Uo();re=l=>{const u=K(l);if(i[l.type]&&o.size<t.maxTelemetryEventsPerPage&&!o.has(u)){const d=a(e,l,c);r.notify(d),cn("telemetry",d),o.add(u)}},Jn(hn);function a(l,u,d){return ne({type:"telemetry",date:N(),service:l,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:ne(u,{runtime_env:d,connectivity:ko(),sdk_setup:"npm"}),experimental_features:Array.from(Xr())},n!==void 0?n():{})}return{setContextProvider:l=>{n=l},observable:r,enabled:s}}function Uo(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function Bo(){fn.drain()}function Fo(e){return e.site===Ir}function pn(e,t){Ze(E.debug,e,t),re({type:V.log,message:e,status:"debug",...t})}function hn(e,t){re({type:V.log,status:"error",...Ho(e),...t})}function Go(e){re({type:V.configuration,configuration:e})}function jo(e){re({type:V.usage,usage:e})}function Ho(e){if(B(e)){const t=A(e);return{error:{kind:t.name,stack:q(zo(t))},message:t.message}}return{error:{stack:Zt},message:`Uncaught ${K(e)}`}}function zo(e){return e.stack=e.stack.filter(t=>!t.url||Mo.some(n=>t.url.startsWith(n))),e}const ye=1/0,Jo=j;let Ee=null;const Fe=new Set;function Ko(){Fe.forEach(e=>e())}function qo({expireDelay:e,maxEntries:t}){let n=[];const r=[];Ee||(Ee=Qe(()=>Ko(),Jo));const o=()=>{const h=Re()-e;for(;n.length>0&&n[n.length-1].endTime<h;){const p=n.pop();p&&r.push(p.startTime)}};Fe.add(o);function s(h,p){const S={value:h,startTime:p,endTime:ye,remove:()=>{ln(n,S)},close:y=>{S.endTime=y}};return t&&n.length>=t&&n.pop(),n.unshift(S),S}function i(h=ye,p={returnInactive:!1}){for(const S of n)if(S.startTime<=h){if(p.returnInactive||h<=S.endTime)return S.value;break}}function c(h){const p=n[0];p&&p.endTime===ye&&p.close(h)}function a(h=ye,p=0){const S=Gn(h,p);return n.filter(y=>y.startTime<=S&&h<=y.endTime).map(y=>y.value)}function l(){return n.map(({startTime:h,endTime:p,value:S})=>({startTime:h,endTime:p===ye?"Infinity":p,value:S}))}function u(){return r}function d(){n=[]}function f(){Fe.delete(o),Fe.size===0&&Ee&&(Dt(Ee),Ee=null)}return{add:s,find:i,closeActive:c,findAll:a,reset:d,stop:f,getAllEntries:l,getDeletedEntries:u}}const Yo=j,Wo=rt;function Vo(e,t,n,r){const o=new T,s=new T,i=Cr(e.sessionStoreStrategyType,e,t,n),c=qo({expireDelay:Wo});i.renewObservable.subscribe(()=>{c.add(a(),Re()),o.notify()}),i.expireObservable.subscribe(()=>{s.notify(),c.closeActive(Re())}),i.expandOrRenewSession(),c.add(a(),Bn().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),Xo(e,()=>{r.isGranted()&&i.expandOrRenewSession()}),Zo(e,()=>i.expandSession()),Qo(e,()=>i.restartSession());function a(){return{id:i.getSession().id,trackingType:i.getSession()[t],isReplayForced:!!i.getSession().forcedReplay,anonymousId:i.getSession().anonymousId}}return{findSession:(l,u)=>c.find(l,u),renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i.sessionStateUpdateObservable,expire:i.expire,updateSessionState:i.updateSessionState}}function Xo(e,t){ht(e,window,["click","touchstart","keydown","scroll"],t,{capture:!0,passive:!0})}function Zo(e,t){const n=()=>{document.visibilityState==="visible"&&t()};W(e,document,"visibilitychange",n),Qe(n,Yo)}function Qo(e,t){W(e,window,"resume",t,{capture:!0})}function gn(e){return e>=500}function es(e){try{return e.clone()}catch{return}}const ts=80*I,ns=32,mn=3*xt,rs=j,bn=le;function Sn(e,t,n,r,o){t.transportStatus===0&&t.queuedPayloads.size()===0&&t.bandwidthMonitor.canHandle(e)?En(e,t,n,{onSuccess:()=>_n(0,t,n,r,o),onFailure:()=>{t.queuedPayloads.enqueue(e),yn(t,n,r,o)}}):t.queuedPayloads.enqueue(e)}function yn(e,t,n,r){e.transportStatus===2&&he(()=>{const o=e.queuedPayloads.first();En(o,e,t,{onSuccess:()=>{e.queuedPayloads.dequeue(),e.currentBackoffTime=bn,_n(1,e,t,n,r)},onFailure:()=>{e.currentBackoffTime=Math.min(rs,e.currentBackoffTime*2),yn(e,t,n,r)}})},e.currentBackoffTime)}function En(e,t,n,{onSuccess:r,onFailure:o}){t.bandwidthMonitor.add(e),n(e,s=>{t.bandwidthMonitor.remove(e),os(s)?(t.transportStatus=t.bandwidthMonitor.ongoingRequestCount>0?1:2,e.retry={count:e.retry?e.retry.count+1:1,lastFailureStatus:s.status},o()):(t.transportStatus=0,r())})}function _n(e,t,n,r,o){e===0&&t.queuedPayloads.isFull()&&!t.queueFullReported&&(o({message:`Reached max ${r} events size queued for upload: ${mn/xt}MiB`,source:R.AGENT,startClocks:M()}),t.queueFullReported=!0);const s=t.queuedPayloads;for(t.queuedPayloads=Tn();s.size()>0;)Sn(s.dequeue(),t,n,r,o)}function os(e){return e.type!=="opaque"&&(e.status===0&&!navigator.onLine||e.status===408||e.status===429||gn(e.status))}function ss(){return{transportStatus:0,currentBackoffTime:bn,bandwidthMonitor:is(),queuedPayloads:Tn(),queueFullReported:!1}}function Tn(){const e=[];return{bytesCount:0,enqueue(t){this.isFull()||(e.push(t),this.bytesCount+=t.bytesCount)},first(){return e[0]},dequeue(){const t=e.shift();return t&&(this.bytesCount-=t.bytesCount),t},size(){return e.length},isFull(){return this.bytesCount>=mn}}}function is(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(e){return this.ongoingRequestCount===0||this.ongoingByteCount+e.bytesCount<=ts&&this.ongoingRequestCount<ns},add(e){this.ongoingRequestCount+=1,this.ongoingByteCount+=e.bytesCount},remove(e){this.ongoingRequestCount-=1,this.ongoingByteCount-=e.bytesCount}}}function cs(e,t,n){const r=ss(),o=(s,i)=>ls(e,t,s,i);return{send:s=>{Sn(s,r,o,e.trackType,n)},sendOnExit:s=>{as(e,t,s)}}}function as(e,t,n){if(!!navigator.sendBeacon&&n.bytesCount<t)try{const s=e.build("beacon",n);if(navigator.sendBeacon(s,n.data))return}catch(s){us(s)}const o=e.build("xhr",n);gt(o,n.data)}let wn=!1;function us(e){wn||(wn=!0,hn(e))}function ls(e,t,n,r){if(ds()&&n.bytesCount<t){const s=e.build("fetch",n);fetch(s,{method:"POST",body:n.data,keepalive:!0,mode:"cors"}).then(b(i=>r==null?void 0:r({status:i.status,type:i.type})),b(()=>{const i=e.build("xhr",n);gt(i,n.data,r)}))}else{const s=e.build("xhr",n);gt(s,n.data,r)}}function ds(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function gt(e,t,n){const r=new XMLHttpRequest;r.open("POST",e,!0),t instanceof Blob&&r.setRequestHeader("Content-Type",t.type),W({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(t)}function mt(){const e=fs();if(e)return{getCapabilities(){var t;return JSON.parse(((t=e.getCapabilities)===null||t===void 0?void 0:t.call(e))||"[]")},getPrivacyLevel(){var t;return(t=e.getPrivacyLevel)===null||t===void 0?void 0:t.call(e)},getAllowedWebViewHosts(){return JSON.parse(e.getAllowedWebViewHosts())},send(t,n,r){const o=r?{id:r}:void 0;e.send(JSON.stringify({eventType:t,event:n,view:o}))}}}function Ge(e){var t;e===void 0&&(e=(t=P().location)===null||t===void 0?void 0:t.hostname);const n=mt();return!!n&&n.getAllowedWebViewHosts().some(r=>e===r||e.endsWith(`.${r}`))}function fs(){return P().DatadogEventBridge}const je={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function ps(e){return new T(t=>{const{stop:n}=ht(e,window,["visibilitychange","freeze"],o=>{o.type==="visibilitychange"&&document.visibilityState==="hidden"?t.notify({reason:je.HIDDEN}):o.type==="freeze"&&t.notify({reason:je.FROZEN})},{capture:!0}),r=W(e,window,"beforeunload",()=>{t.notify({reason:je.UNLOADING})}).stop;return()=>{n(),r()}})}function hs(e){return xe(je).includes(e)}function gs({encoder:e,request:t,flushController:n,messageBytesLimit:r}){let o={};const s=n.flushObservable.subscribe(d=>u(d));function i(d,f,h){n.notifyBeforeAddMessage(f),h!==void 0?(o[h]=d,n.notifyAfterAddMessage()):e.write(e.isEmpty?d:`\n${d}`,p=>{n.notifyAfterAddMessage(p-f)})}function c(d){return d!==void 0&&o[d]!==void 0}function a(d){const f=o[d];delete o[d];const h=e.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(h)}function l(d,f){const h=K(d),p=e.estimateEncodedBytesCount(h);if(p>=r){_.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${we} ${Rt}/#technical-limitations`);return}c(f)&&a(f),i(h,p,f)}function u(d){const f=xe(o).join(`\n`);o={};const h=hs(d.reason),p=h?t.sendOnExit:t.send;if(h&&e.isAsync){const S=e.finishSync();S.outputBytesCount&&p(On(S));const y=[S.pendingData,f].filter(Boolean).join(`\n`);y&&p({data:y,bytesCount:Xe(y)})}else f&&e.write(e.isEmpty?f:`\n${f}`),e.finish(S=>{p(On(S))})}return{flushController:n,add:l,upsert:l,stop:s.unsubscribe}}function On(e){let t;return typeof e.output=="string"?t=e.output:t=new Blob([e.output],{type:"text/plain"}),{data:t,bytesCount:e.outputBytesCount,encoding:e.encoding}}function ms({messagesLimit:e,bytesLimit:t,durationLimit:n,pageExitObservable:r,sessionExpireObservable:o}){const s=r.subscribe(p=>u(p.reason)),i=o.subscribe(()=>u("session_expire")),c=new T(()=>()=>{s.unsubscribe(),i.unsubscribe()});let a=0,l=0;function u(p){if(l===0)return;const S=l,y=a;l=0,a=0,h(),c.notify({reason:p,messagesCount:S,bytesCount:y})}let d;function f(){d===void 0&&(d=he(()=>{u("duration_limit")},n))}function h(){kt(d),d=void 0}return{flushObservable:c,get messagesCount(){return l},notifyBeforeAddMessage(p){a+p>=t&&u("bytes_limit"),l+=1,a+=p,f()},notifyAfterAddMessage(p=0){a+=p,l>=e?u("messages_limit"):a>=t&&u("bytes_limit")},notifyAfterRemoveMessage(p){a-=p,l-=1,l===0&&h()}}}function Rn(e,t,n,r,o,s,i=gs){const c=l(e,t),a=n&&l(e,n);function l(u,{endpoint:d,encoder:f}){return i({encoder:f,request:cs(d,u.batchBytesLimit,r),flushController:ms({messagesLimit:u.batchMessagesLimit,bytesLimit:u.batchBytesLimit,durationLimit:u.flushTimeout,pageExitObservable:o,sessionExpireObservable:s}),messageBytesLimit:u.messageBytesLimit})}return{flushObservable:c.flushController.flushObservable,add(u,d=!0){c.add(u),a&&d&&a.add(n.transformMessage?n.transformMessage(u):u)},upsert:(u,d)=>{c.upsert(u,d),a&&a.upsert(n.transformMessage?n.transformMessage(u):u,d)},stop:()=>{c.stop(),a&&a.stop()}}}function He(){let e="",t=0;return{isAsync:!1,get isEmpty(){return!e},write(n,r){const o=Xe(n);t+=o,e+=n,r&&r(o)},finish(n){n(this.finishSync())},finishSync(){const n={output:e,outputBytesCount:t,rawBytesCount:t,pendingData:""};return e="",t=0,n},estimateEncodedBytesCount(n){return n.length}}}class bs{constructor(){this.callbacks={}}notify(t,n){const r=this.callbacks[t];r&&r.forEach(o=>o(n))}subscribe(t,n){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(n),{unsubscribe:()=>{this.callbacks[t]=this.callbacks[t].filter(r=>n!==r)}}}}function Ss(e,t,n){let r=0,o=!1;return{isLimitReached(){if(r===0&&he(()=>{r=0},j),r+=1,r<=t||o)return o=!1,!1;if(r===t+1){o=!0;try{n({message:`Reached max number of ${e}s by minute: ${t}`,source:R.AGENT,startClocks:M()})}finally{o=!1}}return!0}}}let bt;const St=new WeakMap;function ys(e){return bt||(bt=Es(e)),bt}function Es(e){return new T(t=>{const{stop:n}=Y(XMLHttpRequest.prototype,"open",_s),{stop:r}=Y(XMLHttpRequest.prototype,"send",s=>{Ts(s,e,t)},{computeHandlingStack:!0}),{stop:o}=Y(XMLHttpRequest.prototype,"abort",ws);return()=>{n(),r(),o()}})}function _s({target:e,parameters:[t,n]}){St.set(e,{state:"open",method:String(t).toUpperCase(),url:ct(String(n))})}function Ts({target:e,handlingStack:t},n,r){const o=St.get(e);if(!o)return;const s=o;s.state="start",s.startClocks=M(),s.isAborted=!1,s.xhr=e,s.handlingStack=t;let i=!1;const{stop:c}=Y(e,"onreadystatechange",()=>{e.readyState===XMLHttpRequest.DONE&&a()}),a=()=>{if(l(),c(),i)return;i=!0;const u=o;u.state="complete",u.duration=Fn(s.startClocks.timeStamp,N()),u.status=e.status,r.notify(zn(u))},{stop:l}=W(n,e,"loadend",a);r.notify(s)}function ws({target:e}){const t=St.get(e);t&&(t.isAborted=!0)}let yt;function Cn(){return yt||(yt=Os()),yt}function Os(){return new T(e=>{if(!window.fetch)return;const{stop:t}=Y(window,"fetch",n=>Rs(n,e),{computeHandlingStack:!0});return t})}function Rs({parameters:e,onPostCall:t,handlingStack:n},r){const[o,s]=e;let i=s&&s.method;i===void 0&&o instanceof Request&&(i=o.method);const c=i!==void 0?String(i).toUpperCase():"GET",a=o instanceof Request?o.url:ct(String(o)),l=M(),u={state:"start",init:s,input:o,method:c,startClocks:l,url:a,handlingStack:n};r.notify(u),e[0]=u.input,e[1]=u.init,t(d=>Cs(r,d,u))}function Cs(e,t,n){const r=n;function o(s){r.state="resolve",Object.assign(r,s),e.notify(r)}t.then(b(s=>{o({response:s,responseType:s.type,status:s.status,isAborted:!1})}),b(s=>{var i,c;o({status:0,isAborted:((c=(i=r.init)===null||i===void 0?void 0:i.signal)===null||c===void 0?void 0:c.aborted)||s instanceof DOMException&&s.code===DOMException.ABORT_ERR,error:s})}))}let Et={};function vs(e){const t=e.map(n=>(Et[n]||(Et[n]=Ls(n)),Et[n]));return Nt(...t)}function Ls(e){return new T(t=>{const n=L[e];return L[e]=(...r)=>{n.apply(console,r);const o=$e("console error");pe(()=>{t.notify(xs(r,e,o))})},()=>{L[e]=n}})}function xs(e,t,n){const r=e.map(s=>Is(s)).join(" ");let o;if(t===E.error){const s=e.find(B);o={stack:s?q(A(s)):void 0,fingerprint:en(s),causes:s?nn(s,"console"):void 0,startClocks:M(),message:r,source:R.CONSOLE,handling:"handled",handlingStack:n,context:tn(s)}}return{api:t,message:r,error:o,handlingStack:n}}function Is(e){return typeof e=="string"?k(e):B(e)?Xt(A(e)):K(k(e),void 0,2)}function As(e){const t=an(e)==="object";return t||_.error("Unsupported context:",e),t}function _t(e,t,n){const r={...e};for(const[o,{required:s,type:i}]of Object.entries(t))i==="string"&&o in r&&(r[o]=String(r[o])),s&&!(o in e)&&_.warn(`The property ${o} of ${n} is required; context will not be sent to the intake.`);return r}function ze(e="",{customerDataTracker:t,propertiesConfig:n={}}={}){let r={};const o=new T,s={getContext:()=>un(r),setContext:i=>{As(i)?(r=k(_t(i,n,e)),t==null||t.updateCustomerData(r)):s.clearContext(),o.notify()},setContextProperty:(i,c)=>{r=k(_t({...r,[i]:c},n,e)),t==null||t.updateCustomerData(r),o.notify()},removeContextProperty:i=>{delete r[i],t==null||t.updateCustomerData(r),_t(r,n,e),o.notify()},clearContext:()=>{r={},t==null||t.resetCustomerData(),o.notify()},changeObservable:o};return s}const ks="_dd_c",Ds=[];function Tt(e,t,n,r){const o=Ns(n,r);Ds.push(W(e,window,"storage",({key:l})=>{o===l&&i()})),t.changeObservable.subscribe(c);const s=ne(a(),t.getContext());fe(s)||t.setContext(s);function i(){t.setContext(a())}function c(){localStorage.setItem(o,JSON.stringify(t.getContext()))}function a(){const l=localStorage.getItem(o);return l?JSON.parse(l):{}}}function Ns(e,t){return`${ks}_${e}_${t}`}const Ms=3*I,Ps=16*I,$s=200;function Us(e=2){const t=new Map;let n=!1;function r(o=0){if(n||e===0)return;const s=e===2?Ms:Ps;let i=o;t.forEach(c=>{i+=c.getBytesCount()}),i>s&&(Bs(s),n=!0)}return{createDetachedTracker:()=>{const o=vn(()=>r(o.getBytesCount()));return o},getOrCreateTracker:o=>(t.has(o)||t.set(o,vn(r)),t.get(o)),setCompressionStatus:o=>{e===0&&(e=o,r())},getCompressionStatus:()=>e,stop:()=>{t.forEach(o=>o.stop()),t.clear()}}}function vn(e){let t=0;const{throttled:n,cancel:r}=Mt(s=>{t=Xe(K(s)),e()},$s),o=()=>{r(),t=0};return{updateCustomerData:s=>{fe(s)?o():n(s)},resetCustomerData:o,getBytesCount:()=>t,stop:()=>{r()}}}function Bs(e){_.warn(`Customer data exceeds the recommended ${e/I}KiB threshold. ${we} ${Rt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function Fs(e,t,n){const r=e.getReader(),o=[];let s=0;i();function i(){r.read().then(b(a=>{if(a.done){c();return}o.push(a.value),s+=a.value.length,s>n.bytesLimit?c():i()}),b(a=>t(a)))}function c(){r.cancel().catch($);let a,l;{let u;if(o.length===1)u=o[0];else{u=new Uint8Array(s);let d=0;o.forEach(f=>{u.set(f,d),d+=f.length})}a=u.slice(0,n.bytesLimit),l=u.length>n.bytesLimit}t(void 0,a,l)}}const Gs="datadog-synthetics-public-id",js="datadog-synthetics-result-id",Hs="datadog-synthetics-injects-rum";function Ln(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||H(Hs))}function zs(){const e=window._DATADOG_SYNTHETICS_PUBLIC_ID||H(Gs);return typeof e=="string"?e:void 0}function Js(){const e=window._DATADOG_SYNTHETICS_RESULT_ID||H(js);return typeof e=="string"?e:void 0}function Je(e,t,n){const r=n.getHandler(),o=Array.isArray(r)?r:[r];return xn[e]>=xn[n.getLevel()]&&o.includes(t)}const g={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},xn={[g.ok]:0,[g.debug]:1,[g.info]:2,[g.notice]:4,[g.warn]:5,[g.error]:6,[g.critical]:7,[g.alert]:8,[g.emerg]:9};function Ke(e,{includeMessage:t=!1}={}){return{stack:e.stack,kind:e.type,message:t?e.message:void 0,causes:e.causes,fingerprint:e.fingerprint,handling:e.handling}}var Ks=function(e,t,n,r){var o=arguments.length,s=o<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,n,r);else for(var c=e.length-1;c>=0;c--)(i=e[c])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};const _e={console:"console",http:"http",silent:"silent"},qs=Object.keys(g);let C=class{constructor(t,n,r,o=_e.http,s=g.debug,i={}){this.handleLogStrategy=t,this.handlerType=o,this.level=s,this.contextManager=ze("logger",{customerDataTracker:n}),this.contextManager.setContext(i),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(t,n,r=g.info,o,s){const i=k(n);let c;if(o!=null){const a=Qt({stackTrace:B(o)?A(o):void 0,originalError:o,nonErrorPrefix:"Provided",source:R.LOGGER,handling:"handled",startClocks:M()});c=ne({error:Ke(a,{includeMessage:!0})},i)}else c=i;this.handleLogStrategy({message:k(t),context:c,status:r},this,s)}log(t,n,r=g.info,o){let s;Je(r,_e.http,this)&&(s=$e("log")),this.logImplementation(t,n,r,o,s)}setContext(t){this.contextManager.setContext(t)}getContext(){return this.contextManager.getContext()}setContextProperty(t,n){this.contextManager.setContextProperty(t,n)}removeContextProperty(t){this.contextManager.removeContextProperty(t)}clearContext(){this.contextManager.clearContext()}setHandler(t){this.handlerType=t}getHandler(){return this.handlerType}setLevel(t){this.level=t}getLevel(){return this.level}};Ks([qn],C.prototype,"logImplementation",null),C.prototype.ok=D(g.ok),C.prototype.debug=D(g.debug),C.prototype.info=D(g.info),C.prototype.notice=D(g.notice),C.prototype.warn=D(g.warn),C.prototype.error=D(g.error),C.prototype.critical=D(g.critical),C.prototype.alert=D(g.alert),C.prototype.emerg=D(g.emerg);function D(e){return function(t,n,r){let o;Je(e,_e.http,this)&&(o=$e("log")),this.logImplementation(t,n,e,r,o)}}function Ys(e,t,n){return{view:{referrer:document.referrer,url:window.location.href},context:e.getContext(),user:t.getContext(),account:n.getContext()}}const Ws=32*I;function Vs(e){e.usePciIntake===!0&&e.site&&e.site!=="datadoghq.com"&&_.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const t=qr(e),n=In(e.forwardConsoleLogs,xe(E),"Forward Console Logs"),r=In(e.forwardReports,xe(Ue),"Forward Reports");if(!(!t||!n||!r))return e.forwardErrorsToLogs&&!n.includes(E.error)&&n.push(E.error),{forwardErrorsToLogs:e.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:Ws,...t}}function In(e,t,n){if(e===void 0)return[];if(!(e==="all"||Array.isArray(e)&&e.every(r=>t.includes(r)))){_.error(`${n} should be "all" or an array with allowed values "${t.join(\'", "\')}"`);return}return e==="all"?t:Do(e)}function Xs(e){const t=Yr(e);return{forward_errors_to_logs:e.forwardErrorsToLogs,forward_console_logs:e.forwardConsoleLogs,forward_reports:e.forwardReports,use_pci_intake:e.usePciIntake,...t}}function Zs(e,t,n){const r=dn();let o,s;const i=t.observable.subscribe(c);function c(){if(!s||!o||!t.isGranted())return;i.unsubscribe();const a=n(o,s);r.drain(a)}return{init(a){if(!a){_.error("Missing configuration");return}if(Wr(a.enableExperimentalFeatures),Ge()&&(a=Qs(a)),o=a,s){rn("DD_LOGS",a);return}const l=Vs(a);l&&(s=l,Cn().subscribe($),t.tryToInit(l.trackingConsent),c())},get initConfiguration(){return o},getInternalContext:$,handleLog(a,l,u,d=e(),f=N()){r.add(h=>h.handleLog(a,l,u,d,f))}}}function Qs(e){return{...e,clientToken:"empty"}}const wt="logs";function ei(e){const t=Us(),n=ze("global context",{customerDataTracker:t.getOrCreateTracker(2)}),r=ze("user",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),o=ze("account",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),s=vr();function i(){return Ys(n,r,o)}let c=Zs(i,s,(u,d)=>{u.storeContextsAcrossPages&&(Tt(d,n,wt,2),Tt(d,r,wt,1),Tt(d,o,wt,4));const f=e(u,d,i,s);return c=ti(u,f),f});const a={},l=new C((...u)=>c.handleLog(...u),t.createDetachedTracker());return Oo({logger:l,init:b(u=>c.init(u)),setTrackingConsent:b(u=>{s.update(u),jo({feature:"set-tracking-consent",tracking_consent:u})}),getGlobalContext:b(()=>n.getContext()),setGlobalContext:b(u=>n.setContext(u)),setGlobalContextProperty:b((u,d)=>n.setContextProperty(u,d)),removeGlobalContextProperty:b(u=>n.removeContextProperty(u)),clearGlobalContext:b(()=>n.clearContext()),createLogger:b((u,d={})=>(a[u]=new C((...f)=>c.handleLog(...f),t.createDetachedTracker(),k(u),d.handler,d.level,k(d.context)),a[u])),getLogger:b(u=>a[u]),getInitConfiguration:b(()=>un(c.initConfiguration)),getInternalContext:b(u=>c.getInternalContext(u)),setUser:b(r.setContext),getUser:b(r.getContext),setUserProperty:b(r.setContextProperty),removeUserProperty:b(r.removeContextProperty),clearUser:b(r.clearContext),setAccount:b(o.setContext),getAccount:b(o.getContext),setAccountProperty:b(o.setContextProperty),removeAccountProperty:b(o.removeContextProperty),clearAccount:b(o.clearContext)})}function ti(e,t){return{init:n=>{rn("DD_LOGS",n)},initConfiguration:e,...t}}const ni="logs";function ri(e,t){const n=Vo(e,ni,r=>si(e,r),t);return{findTrackedSession:(r,o={returnInactive:!1})=>{const s=n.findSession(r,o);return s&&s.trackingType==="1"?{id:s.id,anonymousId:s.anonymousId}:void 0},expireObservable:n.expireObservable}}function oi(e){const n=An(e)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new T}}function An(e){return Oe(e.sessionSampleRate)?"1":"0"}function si(e,t){const n=ii(t)?t:An(e);return{trackingType:n,isTracked:n==="1"}}function ii(e){return e==="0"||e==="1"}let kn=!1;function qe(e){const t=window;if(Ln()){const r=n(t.DD_RUM_SYNTHETICS);return!r&&!kn&&(kn=!0,pn("Logs sent before RUM is injected by the synthetics worker",{testId:zs(),resultId:Js()})),r}return n(t.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(e)}}function ci(e,t,n,r,o){const s=qs.concat(["custom"]),i={};s.forEach(c=>{i[c]=Ss(c,t.eventRateLimiterThreshold,o)}),n.subscribe(0,({rawLogsEvent:c,messageContext:a=void 0,savedCommonContext:l=void 0,domainContext:u})=>{var d,f;const h=jn(c.date),p=e.findTrackedSession(h);if(!e.findTrackedSession(h,{returnInactive:!0}))return;const y=l||r();let Te;!fe(y.account)&&y.account.id&&(Te=y.account),p&&p.anonymousId&&!y.user.anonymous_id&&(y.user.anonymous_id=p.anonymousId);const F=ne({service:t.service,session_id:p?p.id:void 0,session:p?{id:p.id}:void 0,usr:fe(y.user)?void 0:y.user,account:Te,view:y.view},y.context,qe(h),c,a);((d=t.beforeSend)===null||d===void 0?void 0:d.call(t,F,u))===!1||F.origin!==R.AGENT&&((f=i[F.status])!==null&&f!==void 0?f:i.custom).isLimitReached()||n.notify(1,F)})}const ai={[E.log]:g.info,[E.debug]:g.debug,[E.info]:g.info,[E.warn]:g.warn,[E.error]:g.error};function ui(e,t){const n=vs(e.forwardConsoleLogs).subscribe(r=>{var o;const s={rawLogsEvent:{date:N(),message:r.message,origin:R.CONSOLE,error:r.error&&Ke(r.error),status:ai[r.api]},messageContext:(o=r.error)===null||o===void 0?void 0:o.context,domainContext:{handlingStack:r.handlingStack}};t.notify(0,s)});return{stop:()=>{n.unsubscribe()}}}function li(e,t){const n=Co(e,e.forwardReports).subscribe(r=>{let o=r.message,s;const i=r.originalError.type==="deprecation"?g.warn:g.error;i===g.error?s=Ke(r):r.stack&&(o+=` Found in ${Eo(r.stack)}`),t.notify(0,{rawLogsEvent:{date:N(),message:o,origin:R.REPORT,error:s,status:i}})});return{stop:()=>{n.unsubscribe()}}}function di(e,t){if(!e.forwardErrorsToLogs)return{stop:$};const n=ys(e).subscribe(s=>{s.state==="complete"&&o("xhr",s)}),r=Cn().subscribe(s=>{s.state==="resolve"&&o("fetch",s)});function o(s,i){!Jr(i.url)&&(gi(i)||gn(i.status))&&("xhr"in i?fi(i.xhr,e,c):i.response?hi(i.response,e,c):i.error&&pi(i.error,e,c));function c(a){const l={isAborted:i.isAborted,handlingStack:i.handlingStack};t.notify(0,{rawLogsEvent:{message:`${mi(s)} error ${i.method} ${i.url}`,date:i.startClocks.timeStamp,error:{stack:a||"Failed to load",handling:void 0},http:{method:i.method,status_code:i.status,url:i.url},status:g.error,origin:R.NETWORK},domainContext:l})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function fi(e,t,n){typeof e.response=="string"?n(Ot(e.response,t)):n(e.response)}function pi(e,t,n){n(Ot(q(A(e)),t))}function hi(e,t,n){const r=es(e);!r||!r.body?n():window.TextDecoder?bi(r.body,t.requestErrorResponseLengthLimit,(o,s)=>{n(o?`Unable to retrieve response: ${o}`:s)}):r.text().then(b(o=>n(Ot(o,t))),b(o=>n(`Unable to retrieve response: ${o}`)))}function gi(e){return e.status===0&&e.responseType!=="opaque"}function Ot(e,t){return e.length>t.requestErrorResponseLengthLimit?`${e.substring(0,t.requestErrorResponseLengthLimit)}...`:e}function mi(e){return e==="xhr"?"XHR":"Fetch"}function bi(e,t,n){Fs(e,(r,o,s)=>{if(r)n(r);else{let i=new TextDecoder().decode(o);s&&(i+="..."),n(void 0,i)}},{bytesLimit:t,collectStreamBody:!0})}function Si(e,t){if(!e.forwardErrorsToLogs)return{stop:$};const n=new T,{stop:r}=_o(n),o=n.subscribe(s=>{t.notify(0,{rawLogsEvent:{message:s.message,date:s.startClocks.timeStamp,error:Ke(s),origin:R.SOURCE,status:g.error},messageContext:s.context})});return{stop:()=>{r(),o.unsubscribe()}}}const yi=bs;function Ei(e){function t(n,r,o,s,i){const c=ne(r.getContext(),n.context);if(Je(n.status,_e.console,r)&&Ti(n,c),Je(n.status,_e.http,r)){const a={rawLogsEvent:{date:i||N(),message:n.message,status:n.status,origin:R.LOGGER},messageContext:c,savedCommonContext:s};o&&(a.domainContext={handlingStack:o}),e.notify(0,a)}}return{handleLog:t}}const _i={[g.ok]:E.debug,[g.debug]:E.debug,[g.info]:E.info,[g.notice]:E.info,[g.warn]:E.warn,[g.error]:E.error,[g.critical]:E.error,[g.alert]:E.error,[g.emerg]:E.error};function Ti({status:e,message:t},n){G[_i[e]].call(L,t,n)}function wi(e,t,n,r,o){const s=Rn(e,{endpoint:e.logsEndpointBuilder,encoder:He()},e.replica&&{endpoint:e.replica.logsEndpointBuilder,encoder:He()},n,r,o.expireObservable);return t.subscribe(1,i=>{s.add(i)}),s}function Oi(e){const t=mt();e.subscribe(1,n=>{t.send("log",n)})}function Ri(e){return{get:t=>{const n=e.findTrackedSession(t);if(n)return{session_id:n.id}}}}function Ci(e){return t=>{e.notify(0,{rawLogsEvent:{message:t.message,date:t.startClocks.timeStamp,origin:R.AGENT,status:g.error}}),pn("Error reported to customer",{"error.message":t.message})}}function vi(e,t,n,r,o){const s=$o("browser-logs-sdk",t);s.setContextProvider(()=>{var c,a,l,u,d,f;return{application:{id:(c=qe())===null||c===void 0?void 0:c.application_id},session:{id:(a=o.findTrackedSession())===null||a===void 0?void 0:a.id},view:{id:(u=(l=qe())===null||l===void 0?void 0:l.view)===null||u===void 0?void 0:u.id},action:{id:(f=(d=qe())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const i=[];if(Ge()){const c=mt(),a=s.observable.subscribe(l=>c.send("internal_telemetry",l));i.push(()=>a.unsubscribe())}else{const c=Rn(t,{endpoint:t.rumEndpointBuilder,encoder:He()},t.replica&&{endpoint:t.replica.rumEndpointBuilder,encoder:He()},n,r,o.expireObservable);i.push(()=>c.stop());const a=s.observable.subscribe(l=>c.add(l,Fo(t)));i.push(()=>a.unsubscribe())}return Bo(),Go(Xs(e)),{telemetry:s,stop:()=>{i.forEach(c=>c())}}}function Li(e,t,n,r){const o=new yi,s=[];o.subscribe(1,f=>cn("logs",f));const i=Ci(o),c=ps(t),a=t.sessionStoreStrategyType&&!Ge()&&!Ln()?ri(t,r):oi(t),{stop:l}=vi(e,t,i,c,a);s.push(()=>l()),di(t,o),Si(t,o),ui(t,o),li(t,o);const{handleLog:u}=Ei(o);if(ci(a,t,o,n,i),Ge())Oi(o);else{const{stop:f}=wi(t,o,i,c,a);s.push(()=>f())}const d=Ri(a);return{handleLog:u,getInternalContext:d.get,stop:()=>{s.forEach(f=>f())}}}const oe=ei(Li);Ro(P(),"DD_LOGS",oe);class O{constructor(t){this.isLoggingOn=t,oe.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!0,sessionSampleRate:100})}static setMessagePort(t){this.messagePort=t}static getMessagePort(){return this.messagePort}setLoggingOn(t){this.isLoggingOn=t}setAttributes(t){for(const n in t)oe.logger.setContextProperty(n,t[n])}info(t,n){this.isLoggingOn&&(oe.logger.info(t,n),console.log("[Logger] Sending info: ",t))}error(t,n){this.isLoggingOn&&(oe.logger.error(t,n),console.log("[Logger] Sending error: ",t))}warn(t,n){this.isLoggingOn&&(oe.logger.warn(t,n),console.log("[Logger] Sending warn: ",t))}handleMessageFromWorker(t){t.actionType==="INFO"?this.info(t.message,t.attributes):t.actionType==="ERROR"?this.error(t.message,t.attributes):t.actionType==="WARN"?this.warn(t.message,t.attributes):t.actionType==="SET_ATTRIBUTES"&&t.attributes&&this.setAttributes(t.attributes)}static setAttributes(t){O.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:t})}static info(t,n){O.messagePort.postMessage({type:"LOG",actionType:"INFO",message:t,attributes:n})}static error(t,n){O.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:t,attributes:n})}static warn(t,n){O.messagePort.postMessage({type:"LOG",actionType:"WARN",message:t,attributes:n})}}const w=class w{constructor(t,n,r,o,s){this.copy=()=>new w(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const i=":";let c=("0"+this.h).slice(-2)+i+("0"+this.m).slice(-2)+i+("0"+this.s).slice(-2)+i+("0"+this.f).slice(-2);return c+="."+(this.field?"1":"2"),c},this.toZipTimeCodeString=()=>{const i=this.copy();return i.f=0,i.s=i.s%2===0?i.s:i.s-1,i.field=0,w.toStr(i)},this.toFrames=i=>{let c=60,a=0;Math.floor(i)==60?(c=60,a=0):Math.floor(i)==59?(c=60,a=4):Math.floor(i)==30?(c=30,a=0):Math.floor(i)==29&&(c=30,a=2);let l=this.h,u=this.m,d=this.s,f=this.f,h=this.field;const p=l*60+u,y=(p-Math.floor(p/10))*a;return l*(c*3600)+u*(c*60)+d*c+(f*2+h)-y},this.addSeconds=i=>{let c=this.copy();return c.s+=i,c.s>=60&&(c.s=0,c.m++,c.m>=60&&(c.m=0,c.h++)),c},this.addFrames=(i,c)=>{let a=this.toFrames(c);return a+=i,w.fromFrames(a,c)},this.subtractFrames=(i,c)=>this.addFrames(-i,c),this.h=t||0,this.m=n||0,this.s=r||0,this.f=o||0,this.field=s||0}static compare(t,n){return t.h!==n.h?t.h<n.h?-1:1:t.m!==n.m?t.m<n.m?-1:1:t.s!==n.s?t.s<n.s?-1:1:t.f!==n.f?t.f<n.f?-1:1:t.field!==n.field?t.field<n.field?-1:1:0}static generateTimecodeRange(t,n,r){const o=[];let s=t;for(;w.compare(s,n)<=0;)o.push(s),s=s.addSeconds(r);return o}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(t){return this.toFrames(t)*1e3/t}};w.calculateCurrentTimeCode=t=>{var d;if(!t.video||!t.clocker||!t.gameParams)throw new Error("OTTPlayer is not initialized");const n=t.video,r=t.clocker,o=r.videoFPScalculator.getFPS(),c=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*o+r.syncPoint.frame;if(c===0||o===0)throw new Error("Current frame is 0 or fps is 0");const a=w.calculateCurrentOffset(c,(d=t.gameParams)==null?void 0:d.offsets);if(a===void 0)throw new Error("Offset is undefined");let l=Math.floor(c-a);return l<0&&(l+=5178816),l>=5178816&&(l-=5178816),w.fromFrames(l,o)},w.calculateCurrentOffset=(t,n)=>{for(let r=1;r<n.length;r++)if(t<n[r].frame)return n[r-1].offset;return n[n.length-1].offset},w.fromFrames=(t,n)=>{let r=60,o=0;Math.floor(n)==60?(r=60,o=0):Math.floor(n)==59?(r=60,o=4):Math.floor(n)==30?(r=30,o=0):Math.floor(n)==29&&(r=30,o=2);let s=Math.floor(n*60),i=Math.floor(n*60*10),c=i*6,a=t,l=Math.floor(a/c);a-=l*c;let u=Math.floor(a/i);a-=u*i,a>=r*60&&(a+=o*(Math.floor((a-r*60)/s)+1));let d=Math.floor(a/(r*60));a-=d*(r*60);let f=Math.floor(a/r);a-=f*r;let h=a;d+=u*10;let p=0;return p=h%2,h=Math.floor(h/2),new w(l,d,f,h,p)},w.toStr=t=>{const n="_";let r=("0"+t.h).slice(-2)+n+("0"+t.m).slice(-2)+n+("0"+t.s).slice(-2)+n+("0"+t.f).slice(-2);return t.field&&(r+="_1"),r},w.fromStr=t=>{const r=t.split("_").map(Number);if(r.length==4){const[o,s,i,c]=r;return new w(o,s,i,c,0)}else if(r.length==5){const[o,s,i,c,a]=r;return new w(o,s,i,c,a)}else throw new Error("Invalid timecode format: "+t)},w.fromMetadata=t=>{const n=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,r=t.timecode.match(n);if(!r)throw new Error("Invalid timecode format: "+t.timecode);const[,o,s,i,c,a]=r,l=Number(o),u=Number(s),d=Number(i),f=Number(c),h=a?Number(a):0;return new w(l,u,d,f,h)};let se=w;class Dn{constructor(t,n,r){this.jobsQueue=[],this.processedTimecodes=[],this.downloaderStopped=!1,this.fitstDownload=!0,this.updateStreamData=o=>{this.streamData=o,this.initiateJobs(this.options.DOWNLOADER_ZIP_START_OFFSET,this.options.DOWNLOADER_ZIP_END_OFFSET,this.options.DOWNLOADER_ZIP_LENGTH_SECONDS),this.clearOldJobs(1)},this.initiateJobs=(o,s,i)=>{if(!this.streamData){O.error("[Downloader] Stream data is not available"),this.options&&v(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}const c=se.fromStr(this.streamData.timeCode),a=c.addSeconds(o),l=c.addSeconds(s),u=se.generateTimecodeRange(a,l,i);for(const d of u){const f=d.toZipTimeCodeString();this.processedTimecodes.includes(f)||(this.processedTimecodes.push(f),this.addJob(f))}},this.clearOldJobs=o=>{if(!this.streamData){O.error("[Downloader] Stream data is not available"),this.options&&v(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}const i=se.fromStr(this.streamData.timeCode).totalSeconds()-o;this.processedTimecodes=this.processedTimecodes.filter(c=>se.fromStr(c).totalSeconds()>i)},this.clearAllJobs=()=>{this.jobsQueue=[],this.currentJob=void 0,this.processedTimecodes=[]},this.addJob=o=>{if(this.jobsQueue.some(s=>s===o)){this.options&&v(this.options,"Downloader")&&console.log(`[Downloader] Job already exists for timeCode=${o}`);return}this.jobsQueue.push(o),this.startNextJob()},this.startNextJob=()=>{!this.currentJob&&this.jobsQueue.length>0&&(this.currentJob=this.jobsQueue.shift(),this.options&&v(this.options,"Downloader")&&console.log(`[Downloader] Starting job timeCode=${this.currentJob}`),this.downloadZip(this.currentJob))},this.jobDone=()=>{this.currentJob=void 0,this.startNextJob()},this.downloadZip=async o=>{if(!this.streamData){O.error("[Downloader] Stream data is not available"),this.options&&v(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}this.fitstDownload&&(this.fitstDownload=!1,O.info("didStartAugmentationDownload",{timestamp:o}));const{fps:s,cloudFrontURL:i,bucketName:c}=this.streamData;try{this.options&&v(this.options,"Downloader")&&console.log(`[Downloader] Fetching zip for timeCode=${o}`);const{arrayBuffer:a,ottActions:l}=await this.fetchMetadata(i,c,s,o);if(this.downloaderStopped)return;this.postArrayBufferToDecoder(o,a),O.setAttributes({last_loading_zip:o}),(!this.ottActions||this.ottActions.toggle.web!==l.toggle.web)&&(this.ottActions&&O.info("didToggleGlobalAugmentationDrawing",{isEnabled:l.toggle.web}),this.ottActions=l,this.postOTTActionsToRenderer(l))}catch(a){O.error("[Downloader] Error fetching zip",a),this.options&&v(this.options,"Errors")&&console.error("[Downloader] Error fetching zip:",a)}this.jobDone()},this.fetchMetadata=async(o,s,i,c)=>{const l=`${`${o}/${s}`}/manifests/59.94/${c}.zip`;this.options&&v(this.options,"Fetcher")&&console.log(`[Fetcher] Fetching metadata from ${l}`);const u=performance.now(),d=await fetch(l),f=await d.arrayBuffer(),p=(performance.now()-u)/1e3,S=d.headers.get("x-tgi-ott-actions");let y;if(S?y=JSON.parse(S):y={toggle:{ios:!0,android:!0,web:!0}},!d.ok)throw new Error(`HTTP error! Status: ${d.status}`);return O.warn("didFetchZip",{downloadTaskURL:l,downloadTime:p}),{arrayBuffer:f,ottActions:y}},this.stop=()=>{this.downloaderStopped=!0,this.clearAllJobs()},this.postArrayBufferToDecoder=t,this.postOTTActionsToRenderer=n,this.options=r}}let ie=null,ce=null,Ye,x;self.onmessage=async e=>{const{data:t}=e;if(t.type==="SET_LOGGER_PORT"&&O.setMessagePort(t.port),t.type==="SET_RENDERER_PORT"&&(ie=t.port,ie.onmessage=xi),t.type==="SET_DECODER_PORT"&&(ce=t.port,ce.onmessage=Ii),t.type==="SET_OPTIONS"&&(x=t.options,O.setMessagePort(self),Ye=new Dn(Nn,Mn,x)),t.type==="VIDEO_SEEKED"){if(!x)return;Ye.stop(),Ye=new Dn(Nn,Mn,x)}};async function xi(e){const{data:t}=e;self.postMessage(t),t.type==="DOWNLOADER_INPUT"&&Ye.updateStreamData(t.streamData)}function Nn(e,t){if(!ce)return;x&&v(x,"Downloader")&&console.log(`[DownloaderWorker] Posting an ArrayBuffer to Decoder, timeCode=${e}`);const n={type:"DECODER_INPUT",timeCode:e,arrayBuffer:t};ce==null||ce.postMessage(n,{transfer:[t]})}function Mn(e){if(!ie)return;x&&v(x,"Downloader")&&console.log(`[DownloaderWorker] Posting OTTActions to Renderer, toggle=${e.toggle}`);const t={type:"OTT_ACTIONS",ottActions:e};ie==null||ie.postMessage(t)}function Ii(e){x&&v(x,"Downloader")&&console.log("[DownloaderWorker] Received message from Decoder:",e.data)}})();\n',Pt=typeof self<"u"&&self.Blob&&new Blob([Ft],{type:"text/javascript;charset=utf-8"});function ar(t){let e;try{if(e=Pt&&(self.URL||self.webkitURL).createObjectURL(Pt),!e)throw"";const n=new Worker(e,{name:t==null?void 0:t.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Ft),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const Mt='(function(){"use strict";const D=(a,n)=>!a.debug||!a.debug.on?!1:a.debug[`log${n}`];function Xt(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var gt={},Zt;function ln(){return Zt||(Zt=1,function(a){var n=function(){var e=new Date,t=4,r=3,l=2,c=1,_=t,y={setLogLevel:function(b){b==this.debug?_=c:b==this.info?_=l:b==this.warn?_=r:(b==this.error,_=t)},debug:function(b,x){console.debug===void 0&&(console.debug=console.log),c>=_&&console.debug("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)},log:function(b,x){this.debug(b.msg)},info:function(b,x){l>=_&&console.info("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)},warn:function(b,x){r>=_&&console.warn("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)},error:function(b,x){t>=_&&console.error("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)}};return y}();n.getDurationString=function(e,t){var r;function l(w,C){for(var T=""+w,I=T.split(".");I[0].length<C;)I[0]="0"+I[0];return I.join(".")}e<0?(r=!0,e=-e):r=!1;var c=t||1,_=e/c,y=Math.floor(_/3600);_-=y*3600;var b=Math.floor(_/60);_-=b*60;var x=_*1e3;return _=Math.floor(_),x-=_*1e3,x=Math.floor(x),(r?"-":"")+y+":"+l(b,2)+":"+l(_,2)+"."+l(x,3)},n.printRanges=function(e){var t=e.length;if(t>0){for(var r="",l=0;l<t;l++)l>0&&(r+=","),r+="["+n.getDurationString(e.start(l))+","+n.getDurationString(e.end(l))+"]";return r}else return"(empty)"},a.Log=n;var o=function(e){if(e instanceof ArrayBuffer)this.buffer=e,this.dataview=new DataView(e);else throw"Needs an array buffer";this.position=0};o.prototype.getPosition=function(){return this.position},o.prototype.getEndPosition=function(){return this.buffer.byteLength},o.prototype.getLength=function(){return this.buffer.byteLength},o.prototype.seek=function(e){var t=Math.max(0,Math.min(this.buffer.byteLength,e));return this.position=isNaN(t)||!isFinite(t)?0:t,!0},o.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},o.prototype.readAnyInt=function(e,t){var r=0;if(this.position+e<=this.buffer.byteLength){switch(e){case 1:t?r=this.dataview.getInt8(this.position):r=this.dataview.getUint8(this.position);break;case 2:t?r=this.dataview.getInt16(this.position):r=this.dataview.getUint16(this.position);break;case 3:if(t)throw"No method for reading signed 24 bits values";r=this.dataview.getUint8(this.position)<<16,r|=this.dataview.getUint8(this.position+1)<<8,r|=this.dataview.getUint8(this.position+2);break;case 4:t?r=this.dataview.getInt32(this.position):r=this.dataview.getUint32(this.position);break;case 8:if(t)throw"No method for reading signed 64 bits values";r=this.dataview.getUint32(this.position)<<32,r|=this.dataview.getUint32(this.position+4);break;default:throw"readInt method not implemented for size: "+e}return this.position+=e,r}else throw"Not enough bytes in buffer"},o.prototype.readUint8=function(){return this.readAnyInt(1,!1)},o.prototype.readUint16=function(){return this.readAnyInt(2,!1)},o.prototype.readUint24=function(){return this.readAnyInt(3,!1)},o.prototype.readUint32=function(){return this.readAnyInt(4,!1)},o.prototype.readUint64=function(){return this.readAnyInt(8,!1)},o.prototype.readString=function(e){if(this.position+e<=this.buffer.byteLength){for(var t="",r=0;r<e;r++)t+=String.fromCharCode(this.readUint8());return t}else throw"Not enough bytes in buffer"},o.prototype.readCString=function(){for(var e=[];;){var t=this.readUint8();if(t!==0)e.push(t);else break}return String.fromCharCode.apply(null,e)},o.prototype.readInt8=function(){return this.readAnyInt(1,!0)},o.prototype.readInt16=function(){return this.readAnyInt(2,!0)},o.prototype.readInt32=function(){return this.readAnyInt(4,!0)},o.prototype.readInt64=function(){return this.readAnyInt(8,!1)},o.prototype.readUint8Array=function(e){for(var t=new Uint8Array(e),r=0;r<e;r++)t[r]=this.readUint8();return t},o.prototype.readInt16Array=function(e){for(var t=new Int16Array(e),r=0;r<e;r++)t[r]=this.readInt16();return t},o.prototype.readUint16Array=function(e){for(var t=new Int16Array(e),r=0;r<e;r++)t[r]=this.readUint16();return t},o.prototype.readUint32Array=function(e){for(var t=new Uint32Array(e),r=0;r<e;r++)t[r]=this.readUint32();return t},o.prototype.readInt32Array=function(e){for(var t=new Int32Array(e),r=0;r<e;r++)t[r]=this.readInt32();return t},a.MP4BoxStream=o;var d=function(e,t,r){this._byteOffset=t||0,e instanceof ArrayBuffer?this.buffer=e:typeof e=="object"?(this.dataView=e,t&&(this._byteOffset+=t)):this.buffer=new ArrayBuffer(e||0),this.position=0,this.endianness=r??d.LITTLE_ENDIAN};d.prototype={},d.prototype.getPosition=function(){return this.position},d.prototype._realloc=function(e){if(this._dynamicSize){var t=this._byteOffset+this.position+e,r=this._buffer.byteLength;if(t<=r){t>this._byteLength&&(this._byteLength=t);return}for(r<1&&(r=1);t>r;)r*=2;var l=new ArrayBuffer(r),c=new Uint8Array(this._buffer),_=new Uint8Array(l,0,c.length);_.set(c),this.buffer=l,this._byteLength=t}},d.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var e=new ArrayBuffer(this._byteLength),t=new Uint8Array(e),r=new Uint8Array(this._buffer,0,t.length);t.set(r),this.buffer=e}},d.BIG_ENDIAN=!1,d.LITTLE_ENDIAN=!0,d.prototype._byteLength=0,Object.defineProperty(d.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(d.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(e){this._buffer=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(d.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(e){this._byteOffset=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(d.prototype,"dataView",{get:function(){return this._dataView},set:function(e){this._byteOffset=e.byteOffset,this._buffer=e.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+e.byteLength}}),d.prototype.seek=function(e){var t=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(t)||!isFinite(t)?0:t},d.prototype.isEof=function(){return this.position>=this._byteLength},d.prototype.mapUint8Array=function(e){this._realloc(e*1);var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e*1,t},d.prototype.readInt32Array=function(e,t){e=e??this.byteLength-this.position/4;var r=new Int32Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readInt16Array=function(e,t){e=e??this.byteLength-this.position/2;var r=new Int16Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readInt8Array=function(e){e=e??this.byteLength-this.position;var t=new Int8Array(e);return d.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t},d.prototype.readUint32Array=function(e,t){e=e??this.byteLength-this.position/4;var r=new Uint32Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readUint16Array=function(e,t){e=e??this.byteLength-this.position/2;var r=new Uint16Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readUint8Array=function(e){e=e??this.byteLength-this.position;var t=new Uint8Array(e);return d.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t},d.prototype.readFloat64Array=function(e,t){e=e??this.byteLength-this.position/8;var r=new Float64Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readFloat32Array=function(e,t){e=e??this.byteLength-this.position/4;var r=new Float32Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readInt32=function(e){var t=this._dataView.getInt32(this.position,e??this.endianness);return this.position+=4,t},d.prototype.readInt16=function(e){var t=this._dataView.getInt16(this.position,e??this.endianness);return this.position+=2,t},d.prototype.readInt8=function(){var e=this._dataView.getInt8(this.position);return this.position+=1,e},d.prototype.readUint32=function(e){var t=this._dataView.getUint32(this.position,e??this.endianness);return this.position+=4,t},d.prototype.readUint16=function(e){var t=this._dataView.getUint16(this.position,e??this.endianness);return this.position+=2,t},d.prototype.readUint8=function(){var e=this._dataView.getUint8(this.position);return this.position+=1,e},d.prototype.readFloat32=function(e){var t=this._dataView.getFloat32(this.position,e??this.endianness);return this.position+=4,t},d.prototype.readFloat64=function(e){var t=this._dataView.getFloat64(this.position,e??this.endianness);return this.position+=8,t},d.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,d.memcpy=function(e,t,r,l,c){var _=new Uint8Array(e,t,c),y=new Uint8Array(r,l,c);_.set(y)},d.arrayToNative=function(e,t){return t==this.endianness?e:this.flipArrayEndianness(e)},d.nativeToEndian=function(e,t){return this.endianness==t?e:this.flipArrayEndianness(e)},d.flipArrayEndianness=function(e){for(var t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=0;r<e.byteLength;r+=e.BYTES_PER_ELEMENT)for(var l=r+e.BYTES_PER_ELEMENT-1,c=r;l>c;l--,c++){var _=t[c];t[c]=t[l],t[l]=_}return e},d.prototype.failurePosition=0,String.fromCharCodeUint8=function(e){for(var t=[],r=0;r<e.length;r++)t[r]=e[r];return String.fromCharCode.apply(null,t)},d.prototype.readString=function(e,t){return t==null||t=="ASCII"?String.fromCharCodeUint8.apply(null,[this.mapUint8Array(e??this.byteLength-this.position)]):new TextDecoder(t).decode(this.mapUint8Array(e))},d.prototype.readCString=function(e){var t=this.byteLength-this.position,r=new Uint8Array(this._buffer,this._byteOffset+this.position),l=t;e!=null&&(l=Math.min(e,t));for(var c=0;c<l&&r[c]!==0;c++);var _=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(c)]);return e!=null?this.position+=l-c:c!=t&&(this.position+=1),_};var h=Math.pow(2,32);d.prototype.readInt64=function(){return this.readInt32()*h+this.readUint32()},d.prototype.readUint64=function(){return this.readUint32()*h+this.readUint32()},d.prototype.readInt64=function(){return this.readUint32()*h+this.readUint32()},d.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},a.DataStream=d,d.prototype.save=function(e){var t=new Blob([this.buffer]);if(window.URL&&URL.createObjectURL){var r=window.URL.createObjectURL(t),l=document.createElement("a");document.body.appendChild(l),l.setAttribute("href",r),l.setAttribute("download",e),l.setAttribute("target","_self"),l.click(),window.URL.revokeObjectURL(r)}else throw"DataStream.save: Can\'t create object URL."},d.prototype._dynamicSize=!0,Object.defineProperty(d.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(e){e||this._trimAlloc(),this._dynamicSize=e}}),d.prototype.shift=function(e){var t=new ArrayBuffer(this._byteLength-e),r=new Uint8Array(t),l=new Uint8Array(this._buffer,e,r.length);r.set(l),this.buffer=t,this.position-=e},d.prototype.writeInt32Array=function(e,t){if(this._realloc(e.length*4),e instanceof Int32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapInt32Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeInt32(e[r],t)},d.prototype.writeInt16Array=function(e,t){if(this._realloc(e.length*2),e instanceof Int16Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapInt16Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeInt16(e[r],t)},d.prototype.writeInt8Array=function(e){if(this._realloc(e.length*1),e instanceof Int8Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapInt8Array(e.length);else for(var t=0;t<e.length;t++)this.writeInt8(e[t])},d.prototype.writeUint32Array=function(e,t){if(this._realloc(e.length*4),e instanceof Uint32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapUint32Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeUint32(e[r],t)},d.prototype.writeUint16Array=function(e,t){if(this._realloc(e.length*2),e instanceof Uint16Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapUint16Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeUint16(e[r],t)},d.prototype.writeUint8Array=function(e){if(this._realloc(e.length*1),e instanceof Uint8Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapUint8Array(e.length);else for(var t=0;t<e.length;t++)this.writeUint8(e[t])},d.prototype.writeFloat64Array=function(e,t){if(this._realloc(e.length*8),e instanceof Float64Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapFloat64Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeFloat64(e[r],t)},d.prototype.writeFloat32Array=function(e,t){if(this._realloc(e.length*4),e instanceof Float32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapFloat32Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeFloat32(e[r],t)},d.prototype.writeInt32=function(e,t){this._realloc(4),this._dataView.setInt32(this.position,e,t??this.endianness),this.position+=4},d.prototype.writeInt16=function(e,t){this._realloc(2),this._dataView.setInt16(this.position,e,t??this.endianness),this.position+=2},d.prototype.writeInt8=function(e){this._realloc(1),this._dataView.setInt8(this.position,e),this.position+=1},d.prototype.writeUint32=function(e,t){this._realloc(4),this._dataView.setUint32(this.position,e,t??this.endianness),this.position+=4},d.prototype.writeUint16=function(e,t){this._realloc(2),this._dataView.setUint16(this.position,e,t??this.endianness),this.position+=2},d.prototype.writeUint8=function(e){this._realloc(1),this._dataView.setUint8(this.position,e),this.position+=1},d.prototype.writeFloat32=function(e,t){this._realloc(4),this._dataView.setFloat32(this.position,e,t??this.endianness),this.position+=4},d.prototype.writeFloat64=function(e,t){this._realloc(8),this._dataView.setFloat64(this.position,e,t??this.endianness),this.position+=8},d.prototype.writeUCS2String=function(e,t,r){r==null&&(r=e.length);for(var l=0;l<e.length&&l<r;l++)this.writeUint16(e.charCodeAt(l),t);for(;l<r;l++)this.writeUint16(0)},d.prototype.writeString=function(e,t,r){var l=0;if(t==null||t=="ASCII")if(r!=null){var c=Math.min(e.length,r);for(l=0;l<c;l++)this.writeUint8(e.charCodeAt(l));for(;l<r;l++)this.writeUint8(0)}else for(l=0;l<e.length;l++)this.writeUint8(e.charCodeAt(l));else this.writeUint8Array(new TextEncoder(t).encode(e.substring(0,r)))},d.prototype.writeCString=function(e,t){var r=0;if(t!=null){var l=Math.min(e.length,t);for(r=0;r<l;r++)this.writeUint8(e.charCodeAt(r));for(;r<t;r++)this.writeUint8(0)}else{for(r=0;r<e.length;r++)this.writeUint8(e.charCodeAt(r));this.writeUint8(0)}},d.prototype.writeStruct=function(e,t){for(var r=0;r<e.length;r+=2){var l=e[r+1];this.writeType(l,t[e[r]],t)}},d.prototype.writeType=function(e,t,r){var l;if(typeof e=="function")return e(this,t);if(typeof e=="object"&&!(e instanceof Array))return e.set(this,t,r);var c=null,_="ASCII",y=this.position;switch(typeof e=="string"&&/:/.test(e)&&(l=e.split(":"),e=l[0],c=parseInt(l[1])),typeof e=="string"&&/,/.test(e)&&(l=e.split(","),e=l[0],_=parseInt(l[1])),e){case"uint8":this.writeUint8(t);break;case"int8":this.writeInt8(t);break;case"uint16":this.writeUint16(t,this.endianness);break;case"int16":this.writeInt16(t,this.endianness);break;case"uint32":this.writeUint32(t,this.endianness);break;case"int32":this.writeInt32(t,this.endianness);break;case"float32":this.writeFloat32(t,this.endianness);break;case"float64":this.writeFloat64(t,this.endianness);break;case"uint16be":this.writeUint16(t,d.BIG_ENDIAN);break;case"int16be":this.writeInt16(t,d.BIG_ENDIAN);break;case"uint32be":this.writeUint32(t,d.BIG_ENDIAN);break;case"int32be":this.writeInt32(t,d.BIG_ENDIAN);break;case"float32be":this.writeFloat32(t,d.BIG_ENDIAN);break;case"float64be":this.writeFloat64(t,d.BIG_ENDIAN);break;case"uint16le":this.writeUint16(t,d.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(t,d.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(t,d.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(t,d.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(t,d.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(t,d.LITTLE_ENDIAN);break;case"cstring":this.writeCString(t,c);break;case"string":this.writeString(t,_,c);break;case"u16string":this.writeUCS2String(t,this.endianness,c);break;case"u16stringle":this.writeUCS2String(t,d.LITTLE_ENDIAN,c);break;case"u16stringbe":this.writeUCS2String(t,d.BIG_ENDIAN,c);break;default:if(e.length==3){for(var b=e[1],x=0;x<t.length;x++)this.writeType(b,t[x]);break}else{this.writeStruct(e,t);break}}c!=null&&(this.position=y,this._realloc(c),this.position=y+c)},d.prototype.writeUint64=function(e){var t=Math.floor(e/h);this.writeUint32(t),this.writeUint32(e&4294967295)},d.prototype.writeUint24=function(e){this.writeUint8((e&16711680)>>16),this.writeUint8((e&65280)>>8),this.writeUint8(e&255)},d.prototype.adjustUint32=function(e,t){var r=this.position;this.seek(e),this.writeUint32(t),this.seek(r)},d.prototype.mapInt32Array=function(e,t){this._realloc(e*4);var r=new Int32Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*4,r},d.prototype.mapInt16Array=function(e,t){this._realloc(e*2);var r=new Int16Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*2,r},d.prototype.mapInt8Array=function(e){this._realloc(e*1);var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e*1,t},d.prototype.mapUint32Array=function(e,t){this._realloc(e*4);var r=new Uint32Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*4,r},d.prototype.mapUint16Array=function(e,t){this._realloc(e*2);var r=new Uint16Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*2,r},d.prototype.mapFloat64Array=function(e,t){this._realloc(e*8);var r=new Float64Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*8,r},d.prototype.mapFloat32Array=function(e,t){this._realloc(e*4);var r=new Float32Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*4,r};var f=function(e){this.buffers=[],this.bufferIndex=-1,e&&(this.insertBuffer(e),this.bufferIndex=0)};f.prototype=new d(new ArrayBuffer,0,d.BIG_ENDIAN),f.prototype.initialized=function(){var e;return this.bufferIndex>-1?!0:this.buffers.length>0?(e=this.buffers[0],e.fileStart===0?(this.buffer=e,this.bufferIndex=0,n.debug("MultiBufferStream","Stream ready for parsing"),!0):(n.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)):(n.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1)},ArrayBuffer.concat=function(e,t){n.debug("ArrayBuffer","Trying to create a new buffer of size: "+(e.byteLength+t.byteLength));var r=new Uint8Array(e.byteLength+t.byteLength);return r.set(new Uint8Array(e),0),r.set(new Uint8Array(t),e.byteLength),r.buffer},f.prototype.reduceBuffer=function(e,t,r){var l;return l=new Uint8Array(r),l.set(new Uint8Array(e,t,r)),l.buffer.fileStart=e.fileStart+t,l.buffer.usedBytes=0,l.buffer},f.prototype.insertBuffer=function(e){for(var t=!0,r=0;r<this.buffers.length;r++){var l=this.buffers[r];if(e.fileStart<=l.fileStart){if(e.fileStart===l.fileStart)if(e.byteLength>l.byteLength){this.buffers.splice(r,1),r--;continue}else n.warn("MultiBufferStream","Buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+") already appended, ignoring");else e.fileStart+e.byteLength<=l.fileStart||(e=this.reduceBuffer(e,0,l.fileStart-e.fileStart)),n.debug("MultiBufferStream","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")"),this.buffers.splice(r,0,e),r===0&&(this.buffer=e);t=!1;break}else if(e.fileStart<l.fileStart+l.byteLength){var c=l.fileStart+l.byteLength-e.fileStart,_=e.byteLength-c;if(_>0)e=this.reduceBuffer(e,c,_);else{t=!1;break}}}t&&(n.debug("MultiBufferStream","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")"),this.buffers.push(e),r===0&&(this.buffer=e))},f.prototype.logBufferLevel=function(e){var t,r,l,c,_=[],y,b="";for(l=0,c=0,t=0;t<this.buffers.length;t++)r=this.buffers[t],t===0?(y={},_.push(y),y.start=r.fileStart,y.end=r.fileStart+r.byteLength,b+="["+y.start+"-"):y.end===r.fileStart?y.end=r.fileStart+r.byteLength:(y={},y.start=r.fileStart,b+=_[_.length-1].end-1+"], ["+y.start+"-",y.end=r.fileStart+r.byteLength,_.push(y)),l+=r.usedBytes,c+=r.byteLength;_.length>0&&(b+=y.end-1+"]");var x=e?n.info:n.debug;this.buffers.length===0?x("MultiBufferStream","No more buffer in memory"):x("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+l+"/"+c+" bytes), continuous ranges: "+b)},f.prototype.cleanBuffers=function(){var e,t;for(e=0;e<this.buffers.length;e++)t=this.buffers[e],t.usedBytes===t.byteLength&&(n.debug("MultiBufferStream","Removing buffer #"+e),this.buffers.splice(e,1),e--)},f.prototype.mergeNextBuffer=function(){var e;if(this.bufferIndex+1<this.buffers.length)if(e=this.buffers[this.bufferIndex+1],e.fileStart===this.buffer.fileStart+this.buffer.byteLength){var t=this.buffer.byteLength,r=this.buffer.usedBytes,l=this.buffer.fileStart;return this.buffers[this.bufferIndex]=ArrayBuffer.concat(this.buffer,e),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=r,this.buffer.fileStart=l,n.debug("ISOFile","Concatenating buffer for box parsing (length: "+t+"->"+this.buffer.byteLength+")"),!0}else return!1;else return!1},f.prototype.findPosition=function(e,t,r){var l,c=null,_=-1;for(e===!0?l=0:l=this.bufferIndex;l<this.buffers.length&&(c=this.buffers[l],c.fileStart<=t);){_=l,r&&(c.fileStart+c.byteLength<=t?c.usedBytes=c.byteLength:c.usedBytes=t-c.fileStart,this.logBufferLevel());l++}return _!==-1?(c=this.buffers[_],c.fileStart+c.byteLength>=t?(n.debug("MultiBufferStream","Found position in existing buffer #"+_),_):-1):-1},f.prototype.findEndContiguousBuf=function(e){var t,r,l,c=e!==void 0?e:this.bufferIndex;if(r=this.buffers[c],this.buffers.length>c+1)for(t=c+1;t<this.buffers.length&&(l=this.buffers[t],l.fileStart===r.fileStart+r.byteLength);t++)r=l;return r.fileStart+r.byteLength},f.prototype.getEndFilePositionAfter=function(e){var t=this.findPosition(!0,e,!1);return t!==-1?this.findEndContiguousBuf(t):e},f.prototype.addUsedBytes=function(e){this.buffer.usedBytes+=e,this.logBufferLevel()},f.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},f.prototype.seek=function(e,t,r){var l;return l=this.findPosition(t,e,r),l!==-1?(this.buffer=this.buffers[l],this.bufferIndex=l,this.position=e-this.buffer.fileStart,n.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(n.debug("MultiBufferStream","Position "+e+" not found in buffered data"),!1)},f.prototype.getPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.position},f.prototype.getLength=function(){return this.byteLength},f.prototype.getEndPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.byteLength},a.MultiBufferStream=f;var u=function(){var e=3,t=4,r=5,l=6,c=[];c[e]="ES_Descriptor",c[t]="DecoderConfigDescriptor",c[r]="DecoderSpecificInfo",c[l]="SLConfigDescriptor",this.getDescriptorName=function(b){return c[b]};var _=this,y={};return this.parseOneDescriptor=function(b){var x=0,w,C,T;for(w=b.readUint8(),T=b.readUint8();T&128;)x=(x<<7)+(T&127),T=b.readUint8();return x=(x<<7)+(T&127),n.debug("MPEG4DescriptorParser","Found "+(c[w]||"Descriptor "+w)+", size "+x+" at position "+b.getPosition()),c[w]?C=new y[c[w]](x):C=new y.Descriptor(x),C.parse(b),C},y.Descriptor=function(b,x){this.tag=b,this.size=x,this.descs=[]},y.Descriptor.prototype.parse=function(b){this.data=b.readUint8Array(this.size)},y.Descriptor.prototype.findDescriptor=function(b){for(var x=0;x<this.descs.length;x++)if(this.descs[x].tag==b)return this.descs[x];return null},y.Descriptor.prototype.parseRemainingDescriptors=function(b){for(var x=b.position;b.position<x+this.size;){var w=_.parseOneDescriptor(b);this.descs.push(w)}},y.ES_Descriptor=function(b){y.Descriptor.call(this,e,b)},y.ES_Descriptor.prototype=new y.Descriptor,y.ES_Descriptor.prototype.parse=function(b){if(this.ES_ID=b.readUint16(),this.flags=b.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=b.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){var x=b.readUint8();this.URL=b.readString(x),this.size-=x+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=b.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(b)},y.ES_Descriptor.prototype.getOTI=function(b){var x=this.findDescriptor(t);return x?x.oti:0},y.ES_Descriptor.prototype.getAudioConfig=function(b){var x=this.findDescriptor(t);if(!x)return null;var w=x.findDescriptor(r);if(w&&w.data){var C=(w.data[0]&248)>>3;return C===31&&w.data.length>=2&&(C=32+((w.data[0]&7)<<3)+((w.data[1]&224)>>5)),C}else return null},y.DecoderConfigDescriptor=function(b){y.Descriptor.call(this,t,b)},y.DecoderConfigDescriptor.prototype=new y.Descriptor,y.DecoderConfigDescriptor.prototype.parse=function(b){this.oti=b.readUint8(),this.streamType=b.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=b.readUint24(),this.maxBitrate=b.readUint32(),this.avgBitrate=b.readUint32(),this.size-=13,this.parseRemainingDescriptors(b)},y.DecoderSpecificInfo=function(b){y.Descriptor.call(this,r,b)},y.DecoderSpecificInfo.prototype=new y.Descriptor,y.SLConfigDescriptor=function(b){y.Descriptor.call(this,l,b)},y.SLConfigDescriptor.prototype=new y.Descriptor,this};a.MPEG4DescriptorParser=u;var s={ERR_INVALID_DATA:-1,ERR_NOT_ENOUGH_DATA:0,OK:1,BASIC_BOXES:["mdat","idat","free","skip","meco","strk"],FULL_BOXES:["hmhd","nmhd","iods","xml ","bxml","ipro","mere"],CONTAINER_BOXES:[["moov",["trak","pssh"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl",["sgpd","sbgp"]],["mvex",["trex"]],["moof",["traf"]],["traf",["trun","sgpd","sbgp"]],["vttc"],["tref"],["iref"],["mfra",["tfra"]],["meco"],["hnti"],["hinf"],["strk"],["strd"],["sinf"],["rinf"],["schi"],["trgr"],["udta",["kind"]],["iprp",["ipma"]],["ipco"],["grpl"],["j2kH"],["etyp",["tyco"]]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){s.FullBox.prototype=new s.Box,s.ContainerBox.prototype=new s.Box,s.SampleEntry.prototype=new s.Box,s.TrackGroupTypeBox.prototype=new s.FullBox,s.BASIC_BOXES.forEach(function(e){s.createBoxCtor(e)}),s.FULL_BOXES.forEach(function(e){s.createFullBoxCtor(e)}),s.CONTAINER_BOXES.forEach(function(e){s.createContainerBoxCtor(e[0],null,e[1])})},Box:function(e,t,r){this.type=e,this.size=t,this.uuid=r},FullBox:function(e,t,r){s.Box.call(this,e,t,r),this.flags=0,this.version=0},ContainerBox:function(e,t,r){s.Box.call(this,e,t,r),this.boxes=[]},SampleEntry:function(e,t,r,l){s.ContainerBox.call(this,e,t),this.hdr_size=r,this.start=l},SampleGroupEntry:function(e){this.grouping_type=e},TrackGroupTypeBox:function(e,t){s.FullBox.call(this,e,t)},createBoxCtor:function(e,t){s.boxCodes.push(e),s[e+"Box"]=function(r){s.Box.call(this,e,r)},s[e+"Box"].prototype=new s.Box,t&&(s[e+"Box"].prototype.parse=t)},createFullBoxCtor:function(e,t){s[e+"Box"]=function(r){s.FullBox.call(this,e,r)},s[e+"Box"].prototype=new s.FullBox,s[e+"Box"].prototype.parse=function(r){this.parseFullHeader(r),t&&t.call(this,r)}},addSubBoxArrays:function(e){if(e){this.subBoxNames=e;for(var t=e.length,r=0;r<t;r++)this[e[r]+"s"]=[]}},createContainerBoxCtor:function(e,t,r){s[e+"Box"]=function(l){s.ContainerBox.call(this,e,l),s.addSubBoxArrays.call(this,r)},s[e+"Box"].prototype=new s.ContainerBox,t&&(s[e+"Box"].prototype.parse=t)},createMediaSampleEntryCtor:function(e,t,r){s.sampleEntryCodes[e]=[],s[e+"SampleEntry"]=function(l,c){s.SampleEntry.call(this,l,c),s.addSubBoxArrays.call(this,r)},s[e+"SampleEntry"].prototype=new s.SampleEntry,t&&(s[e+"SampleEntry"].prototype.parse=t)},createSampleEntryCtor:function(e,t,r,l){s.sampleEntryCodes[e].push(t),s[t+"SampleEntry"]=function(c){s[e+"SampleEntry"].call(this,t,c),s.addSubBoxArrays.call(this,l)},s[t+"SampleEntry"].prototype=new s[e+"SampleEntry"],r&&(s[t+"SampleEntry"].prototype.parse=r)},createEncryptedSampleEntryCtor:function(e,t,r){s.createSampleEntryCtor.call(this,e,t,r,["sinf"])},createSampleGroupCtor:function(e,t){s[e+"SampleGroupEntry"]=function(r){s.SampleGroupEntry.call(this,e,r)},s[e+"SampleGroupEntry"].prototype=new s.SampleGroupEntry,t&&(s[e+"SampleGroupEntry"].prototype.parse=t)},createTrackGroupCtor:function(e,t){s[e+"TrackGroupTypeBox"]=function(r){s.TrackGroupTypeBox.call(this,e,r)},s[e+"TrackGroupTypeBox"].prototype=new s.TrackGroupTypeBox,t&&(s[e+"TrackGroupTypeBox"].prototype.parse=t)},createUUIDBox:function(e,t,r,l){s.UUIDs.push(e),s.UUIDBoxes[e]=function(c){t?s.FullBox.call(this,"uuid",c,e):r?s.ContainerBox.call(this,"uuid",c,e):s.Box.call(this,"uuid",c,e)},s.UUIDBoxes[e].prototype=t?new s.FullBox:r?new s.ContainerBox:new s.Box,l&&(t?s.UUIDBoxes[e].prototype.parse=function(c){this.parseFullHeader(c),l&&l.call(this,c)}:s.UUIDBoxes[e].prototype.parse=l)}};s.initialize(),s.TKHD_FLAG_ENABLED=1,s.TKHD_FLAG_IN_MOVIE=2,s.TKHD_FLAG_IN_PREVIEW=4,s.TFHD_FLAG_BASE_DATA_OFFSET=1,s.TFHD_FLAG_SAMPLE_DESC=2,s.TFHD_FLAG_SAMPLE_DUR=8,s.TFHD_FLAG_SAMPLE_SIZE=16,s.TFHD_FLAG_SAMPLE_FLAGS=32,s.TFHD_FLAG_DUR_EMPTY=65536,s.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,s.TRUN_FLAGS_DATA_OFFSET=1,s.TRUN_FLAGS_FIRST_FLAG=4,s.TRUN_FLAGS_DURATION=256,s.TRUN_FLAGS_SIZE=512,s.TRUN_FLAGS_FLAGS=1024,s.TRUN_FLAGS_CTS_OFFSET=2048,s.Box.prototype.add=function(e){return this.addBox(new s[e+"Box"])},s.Box.prototype.addBox=function(e){return this.boxes.push(e),this[e.type+"s"]?this[e.type+"s"].push(e):this[e.type]=e,e},s.Box.prototype.set=function(e,t){return this[e]=t,this},s.Box.prototype.addEntry=function(e,t){var r=t||"entries";return this[r]||(this[r]=[]),this[r].push(e),this},a.BoxParser=s,s.parseUUID=function(e){return s.parseHex16(e)},s.parseHex16=function(e){for(var t="",r=0;r<16;r++){var l=e.readUint8().toString(16);t+=l.length===1?"0"+l:l}return t},s.parseOneBox=function(e,t,r){var l,c=e.getPosition(),_=0,y,b;if(e.getEndPosition()-c<8)return n.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:s.ERR_NOT_ENOUGH_DATA};if(r&&r<8)return n.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:s.ERR_NOT_ENOUGH_DATA};var x=e.readUint32(),w=e.readString(4),C=w;if(n.debug("BoxParser","Found box of type \'"+w+"\' and size "+x+" at position "+c),_=8,w=="uuid"){if(e.getEndPosition()-e.getPosition()<16||r-_<16)return e.seek(c),n.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:s.ERR_NOT_ENOUGH_DATA};b=s.parseUUID(e),_+=16,C=b}if(x==1){if(e.getEndPosition()-e.getPosition()<8||r&&r-_<8)return e.seek(c),n.warn("BoxParser",\'Not enough data in stream to parse the extended size of the "\'+w+\'" box\'),{code:s.ERR_NOT_ENOUGH_DATA};x=e.readUint64(),_+=8}else if(x===0){if(r)x=r;else if(w!=="mdat")return n.error("BoxParser","Unlimited box size not supported for type: \'"+w+"\'"),l=new s.Box(w,x),{code:s.OK,box:l,size:l.size}}return x!==0&&x<_?(n.error("BoxParser","Box of type "+w+" has an invalid size "+x+" (too small to be a box)"),{code:s.ERR_NOT_ENOUGH_DATA,type:w,size:x,hdr_size:_,start:c}):x!==0&&r&&x>r?(n.error("BoxParser","Box of type \'"+w+"\' has a size "+x+" greater than its container size "+r),{code:s.ERR_NOT_ENOUGH_DATA,type:w,size:x,hdr_size:_,start:c}):x!==0&&c+x>e.getEndPosition()?(e.seek(c),n.info("BoxParser","Not enough data in stream to parse the entire \'"+w+"\' box"),{code:s.ERR_NOT_ENOUGH_DATA,type:w,size:x,hdr_size:_,start:c}):t?{code:s.OK,type:w,size:x,hdr_size:_,start:c}:(s[w+"Box"]?l=new s[w+"Box"](x):w!=="uuid"?(n.warn("BoxParser","Unknown box type: \'"+w+"\'"),l=new s.Box(w,x),l.has_unparsed_data=!0):s.UUIDBoxes[b]?l=new s.UUIDBoxes[b](x):(n.warn("BoxParser","Unknown uuid type: \'"+b+"\'"),l=new s.Box(w,x),l.uuid=b,l.has_unparsed_data=!0),l.hdr_size=_,l.start=c,l.write===s.Box.prototype.write&&l.type!=="mdat"&&(n.info("BoxParser","\'"+C+"\' box writing not yet implemented, keeping unparsed data in memory for later write"),l.parseDataAndRewind(e)),l.parse(e),y=e.getPosition()-(l.start+l.size),y<0?(n.warn("BoxParser","Parsing of box \'"+C+"\' did not read the entire indicated box data size (missing "+-y+" bytes), seeking forward"),e.seek(l.start+l.size)):y>0&&(n.error("BoxParser","Parsing of box \'"+C+"\' read "+y+" more bytes than the indicated box data size, seeking backwards"),l.size!==0&&e.seek(l.start+l.size)),{code:s.OK,box:l,size:l.size})},s.Box.prototype.parse=function(e){this.type!="mdat"?this.data=e.readUint8Array(this.size-this.hdr_size):this.size===0?e.seek(e.getEndPosition()):e.seek(this.start+this.size)},s.Box.prototype.parseDataAndRewind=function(e){this.data=e.readUint8Array(this.size-this.hdr_size),e.position-=this.size-this.hdr_size},s.FullBox.prototype.parseDataAndRewind=function(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,e.position-=this.size-this.hdr_size},s.FullBox.prototype.parseFullHeader=function(e){this.version=e.readUint8(),this.flags=e.readUint24(),this.hdr_size+=4},s.FullBox.prototype.parse=function(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)},s.ContainerBox.prototype.parse=function(e){for(var t,r;e.getPosition()<this.start+this.size;)if(t=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),t.code===s.OK)if(r=t.box,this.boxes.push(r),this.subBoxNames&&this.subBoxNames.indexOf(r.type)!=-1)this[this.subBoxNames[this.subBoxNames.indexOf(r.type)]+"s"].push(r);else{var l=r.type!=="uuid"?r.type:r.uuid;this[l]?n.warn("Box of type "+l+" already stored in field of this type"):this[l]=r}else return},s.Box.prototype.parseLanguage=function(e){this.language=e.readUint16();var t=[];t[0]=this.language>>10&31,t[1]=this.language>>5&31,t[2]=this.language&31,this.languageString=String.fromCharCode(t[0]+96,t[1]+96,t[2]+96)},s.SAMPLE_ENTRY_TYPE_VISUAL="Visual",s.SAMPLE_ENTRY_TYPE_AUDIO="Audio",s.SAMPLE_ENTRY_TYPE_HINT="Hint",s.SAMPLE_ENTRY_TYPE_METADATA="Metadata",s.SAMPLE_ENTRY_TYPE_SUBTITLE="Subtitle",s.SAMPLE_ENTRY_TYPE_SYSTEM="System",s.SAMPLE_ENTRY_TYPE_TEXT="Text",s.SampleEntry.prototype.parseHeader=function(e){e.readUint8Array(6),this.data_reference_index=e.readUint16(),this.hdr_size+=8},s.SampleEntry.prototype.parse=function(e){this.parseHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)},s.SampleEntry.prototype.parseDataAndRewind=function(e){this.parseHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,e.position-=this.size-this.hdr_size},s.SampleEntry.prototype.parseFooter=function(e){s.ContainerBox.prototype.parse.call(this,e)},s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_HINT),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SYSTEM),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_TEXT),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,function(e){var t;this.parseHeader(e),e.readUint16(),e.readUint16(),e.readUint32Array(3),this.width=e.readUint16(),this.height=e.readUint16(),this.horizresolution=e.readUint32(),this.vertresolution=e.readUint32(),e.readUint32(),this.frame_count=e.readUint16(),t=Math.min(31,e.readUint8()),this.compressorname=e.readString(t),t<31&&e.readString(31-t),this.depth=e.readUint16(),e.readUint16(),this.parseFooter(e)}),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,function(e){this.parseHeader(e),e.readUint32Array(2),this.channel_count=e.readUint16(),this.samplesize=e.readUint16(),e.readUint16(),e.readUint16(),this.samplerate=e.readUint32()/65536,this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc4"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"av01"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"dav1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"hvc1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"hev1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"hvt1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"lhe1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"dvh1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"dvhe"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvc1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvi1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvs1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvcN"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vp08"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vp09"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avs3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"j2ki"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"mjp2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"mjpg"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"uncv"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mp4a"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"ac-3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"ac-4"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"ec-3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"Opus"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mha1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mha2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mhm1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mhm2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"fLaC"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"encv"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"enca"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"encu"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SYSTEM,"encs"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_TEXT,"enct"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"encm"),s.createBoxCtor("a1lx",function(e){var t=e.readUint8()&1,r=((t&1)+1)*16;this.layer_size=[];for(var l=0;l<3;l++)r==16?this.layer_size[l]=e.readUint16():this.layer_size[l]=e.readUint32()}),s.createBoxCtor("a1op",function(e){this.op_index=e.readUint8()}),s.createFullBoxCtor("auxC",function(e){this.aux_type=e.readCString();var t=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=e.readUint8Array(t)}),s.createBoxCtor("av1C",function(e){var t=e.readUint8();if(t>>7&!1){n.error("av1C marker problem");return}if(this.version=t&127,this.version!==1){n.error("av1C version "+this.version+" not supported");return}if(t=e.readUint8(),this.seq_profile=t>>5&7,this.seq_level_idx_0=t&31,t=e.readUint8(),this.seq_tier_0=t>>7&1,this.high_bitdepth=t>>6&1,this.twelve_bit=t>>5&1,this.monochrome=t>>4&1,this.chroma_subsampling_x=t>>3&1,this.chroma_subsampling_y=t>>2&1,this.chroma_sample_position=t&3,t=e.readUint8(),this.reserved_1=t>>5&7,this.reserved_1!==0){n.error("av1C reserved_1 parsing problem");return}if(this.initial_presentation_delay_present=t>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=t&15;else if(this.reserved_2=t&15,this.reserved_2!==0){n.error("av1C reserved_2 parsing problem");return}var r=this.size-this.hdr_size-4;this.configOBUs=e.readUint8Array(r)}),s.createBoxCtor("avcC",function(e){var t,r;for(this.configurationVersion=e.readUint8(),this.AVCProfileIndication=e.readUint8(),this.profile_compatibility=e.readUint8(),this.AVCLevelIndication=e.readUint8(),this.lengthSizeMinusOne=e.readUint8()&3,this.nb_SPS_nalus=e.readUint8()&31,r=this.size-this.hdr_size-6,this.SPS=[],t=0;t<this.nb_SPS_nalus;t++)this.SPS[t]={},this.SPS[t].length=e.readUint16(),this.SPS[t].nalu=e.readUint8Array(this.SPS[t].length),r-=2+this.SPS[t].length;for(this.nb_PPS_nalus=e.readUint8(),r--,this.PPS=[],t=0;t<this.nb_PPS_nalus;t++)this.PPS[t]={},this.PPS[t].length=e.readUint16(),this.PPS[t].nalu=e.readUint8Array(this.PPS[t].length),r-=2+this.PPS[t].length;r>0&&(this.ext=e.readUint8Array(r))}),s.createBoxCtor("btrt",function(e){this.bufferSizeDB=e.readUint32(),this.maxBitrate=e.readUint32(),this.avgBitrate=e.readUint32()}),s.createFullBoxCtor("ccst",function(e){var t=e.readUint8();this.all_ref_pics_intra=(t&128)==128,this.intra_pred_used=(t&64)==64,this.max_ref_per_pic=(t&63)>>2,e.readUint24()}),s.createBoxCtor("cdef",function(e){var t;for(this.channel_count=e.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[],t=0;t<this.channel_count;t++)this.channel_indexes.push(e.readUint16()),this.channel_types.push(e.readUint16()),this.channel_associations.push(e.readUint16())}),s.createBoxCtor("clap",function(e){this.cleanApertureWidthN=e.readUint32(),this.cleanApertureWidthD=e.readUint32(),this.cleanApertureHeightN=e.readUint32(),this.cleanApertureHeightD=e.readUint32(),this.horizOffN=e.readUint32(),this.horizOffD=e.readUint32(),this.vertOffN=e.readUint32(),this.vertOffD=e.readUint32()}),s.createBoxCtor("clli",function(e){this.max_content_light_level=e.readUint16(),this.max_pic_average_light_level=e.readUint16()}),s.createFullBoxCtor("cmex",function(e){this.flags&1&&(this.pos_x=e.readInt32()),this.flags&2&&(this.pos_y=e.readInt32()),this.flags&4&&(this.pos_z=e.readInt32()),this.flags&8&&(this.version==0?this.flags&16?(this.quat_x=e.readInt32(),this.quat_y=e.readInt32(),this.quat_z=e.readInt32()):(this.quat_x=e.readInt16(),this.quat_y=e.readInt16(),this.quat_z=e.readInt16()):this.version==1),this.flags&32&&(this.id=e.readUint32())}),s.createFullBoxCtor("cmin",function(e){this.focal_length_x=e.readInt32(),this.principal_point_x=e.readInt32(),this.principal_point_y=e.readInt32(),this.flags&1&&(this.focal_length_y=e.readInt32(),this.skew_factor=e.readInt32())}),s.createBoxCtor("cmpd",function(e){for(this.component_count=e.readUint32(),this.component_types=[],this.component_type_urls=[],i=0;i<this.component_count;i++){var t=e.readUint16();this.component_types.push(t),t>=32768&&this.component_type_urls.push(e.readCString())}}),s.createFullBoxCtor("co64",function(e){var t,r;if(t=e.readUint32(),this.chunk_offsets=[],this.version===0)for(r=0;r<t;r++)this.chunk_offsets.push(e.readUint64())}),s.createFullBoxCtor("CoLL",function(e){this.maxCLL=e.readUint16(),this.maxFALL=e.readUint16()}),s.createBoxCtor("colr",function(e){if(this.colour_type=e.readString(4),this.colour_type==="nclx"){this.colour_primaries=e.readUint16(),this.transfer_characteristics=e.readUint16(),this.matrix_coefficients=e.readUint16();var t=e.readUint8();this.full_range_flag=t>>7}else this.colour_type==="rICC"?this.ICC_profile=e.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=e.readUint8Array(this.size-4))}),s.createFullBoxCtor("cprt",function(e){this.parseLanguage(e),this.notice=e.readCString()}),s.createFullBoxCtor("cslg",function(e){this.version===0&&(this.compositionToDTSShift=e.readInt32(),this.leastDecodeToDisplayDelta=e.readInt32(),this.greatestDecodeToDisplayDelta=e.readInt32(),this.compositionStartTime=e.readInt32(),this.compositionEndTime=e.readInt32())}),s.createFullBoxCtor("ctts",function(e){var t,r;if(t=e.readUint32(),this.sample_counts=[],this.sample_offsets=[],this.version===0)for(r=0;r<t;r++){this.sample_counts.push(e.readUint32());var l=e.readInt32();l<0&&n.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(l)}else if(this.version==1)for(r=0;r<t;r++)this.sample_counts.push(e.readUint32()),this.sample_offsets.push(e.readInt32())}),s.createBoxCtor("dac3",function(e){var t=e.readUint8(),r=e.readUint8(),l=e.readUint8();this.fscod=t>>6,this.bsid=t>>1&31,this.bsmod=(t&1)<<2|r>>6&3,this.acmod=r>>3&7,this.lfeon=r>>2&1,this.bit_rate_code=r&3|l>>5&7}),s.createBoxCtor("dec3",function(e){var t=e.readUint16();this.data_rate=t>>3,this.num_ind_sub=t&7,this.ind_subs=[];for(var r=0;r<this.num_ind_sub+1;r++){var l={};this.ind_subs.push(l);var c=e.readUint8(),_=e.readUint8(),y=e.readUint8();l.fscod=c>>6,l.bsid=c>>1&31,l.bsmod=(c&1)<<4|_>>4&15,l.acmod=_>>1&7,l.lfeon=_&1,l.num_dep_sub=y>>1&15,l.num_dep_sub>0&&(l.chan_loc=(y&1)<<8|e.readUint8())}}),s.createFullBoxCtor("dfLa",function(e){var t=127,r=128,l=[],c=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];do{var _=e.readUint8(),y=Math.min(_&t,c.length-1);if(y?e.readUint8Array(e.readUint24()):(e.readUint8Array(13),this.samplerate=e.readUint32()>>12,e.readUint8Array(20)),l.push(c[y]),_&r)break}while(!0);this.numMetadataBlocks=l.length+" ("+l.join(", ")+")"}),s.createBoxCtor("dimm",function(e){this.bytessent=e.readUint64()}),s.createBoxCtor("dmax",function(e){this.time=e.readUint32()}),s.createBoxCtor("dmed",function(e){this.bytessent=e.readUint64()}),s.createBoxCtor("dOps",function(e){if(this.Version=e.readUint8(),this.OutputChannelCount=e.readUint8(),this.PreSkip=e.readUint16(),this.InputSampleRate=e.readUint32(),this.OutputGain=e.readInt16(),this.ChannelMappingFamily=e.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=e.readUint8(),this.CoupledCount=e.readUint8(),this.ChannelMapping=[];for(var t=0;t<this.OutputChannelCount;t++)this.ChannelMapping[t]=e.readUint8()}}),s.createFullBoxCtor("dref",function(e){var t,r;this.entries=[];for(var l=e.readUint32(),c=0;c<l;c++)if(t=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),t.code===s.OK)r=t.box,this.entries.push(r);else return}),s.createBoxCtor("drep",function(e){this.bytessent=e.readUint64()}),s.createFullBoxCtor("elng",function(e){this.extended_language=e.readString(this.size-this.hdr_size)}),s.createFullBoxCtor("elst",function(e){this.entries=[];for(var t=e.readUint32(),r=0;r<t;r++){var l={};this.entries.push(l),this.version===1?(l.segment_duration=e.readUint64(),l.media_time=e.readInt64()):(l.segment_duration=e.readUint32(),l.media_time=e.readInt32()),l.media_rate_integer=e.readInt16(),l.media_rate_fraction=e.readInt16()}}),s.createFullBoxCtor("emsg",function(e){this.version==1?(this.timescale=e.readUint32(),this.presentation_time=e.readUint64(),this.event_duration=e.readUint32(),this.id=e.readUint32(),this.scheme_id_uri=e.readCString(),this.value=e.readCString()):(this.scheme_id_uri=e.readCString(),this.value=e.readCString(),this.timescale=e.readUint32(),this.presentation_time_delta=e.readUint32(),this.event_duration=e.readUint32(),this.id=e.readUint32());var t=this.size-this.hdr_size-(4*4+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version==1&&(t-=4),this.message_data=e.readUint8Array(t)}),s.createEntityToGroupCtor=function(e,t){s[e+"Box"]=function(r){s.FullBox.call(this,e,r)},s[e+"Box"].prototype=new s.FullBox,s[e+"Box"].prototype.parse=function(r){if(this.parseFullHeader(r),t)t.call(this,r);else for(this.group_id=r.readUint32(),this.num_entities_in_group=r.readUint32(),this.entity_ids=[],i=0;i<this.num_entities_in_group;i++){var l=r.readUint32();this.entity_ids.push(l)}}},s.createEntityToGroupCtor("aebr"),s.createEntityToGroupCtor("afbr"),s.createEntityToGroupCtor("albc"),s.createEntityToGroupCtor("altr"),s.createEntityToGroupCtor("brst"),s.createEntityToGroupCtor("dobr"),s.createEntityToGroupCtor("eqiv"),s.createEntityToGroupCtor("favc"),s.createEntityToGroupCtor("fobr"),s.createEntityToGroupCtor("iaug"),s.createEntityToGroupCtor("pano"),s.createEntityToGroupCtor("slid"),s.createEntityToGroupCtor("ster"),s.createEntityToGroupCtor("tsyn"),s.createEntityToGroupCtor("wbbr"),s.createEntityToGroupCtor("prgr"),s.createEntityToGroupCtor("pymd",function(e){this.group_id=e.readUint32(),this.num_entities_in_group=e.readUint32(),this.entity_ids=[];for(var t=0;t<this.num_entities_in_group;t++){var r=e.readUint32();this.entity_ids.push(r)}for(this.tile_size_x=e.readUint16(),this.tile_size_y=e.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[],t=0;t<this.num_entities_in_group;t++)this.layer_binning[t]=e.readUint16(),this.tiles_in_layer_row_minus1[t]=e.readUint16(),this.tiles_in_layer_column_minus1[t]=e.readUint16()}),s.createFullBoxCtor("esds",function(e){var t=e.readUint8Array(this.size-this.hdr_size);if(typeof u<"u"){var r=new u;this.esd=r.parseOneDescriptor(new d(t.buffer,0,d.BIG_ENDIAN))}}),s.createBoxCtor("fiel",function(e){this.fieldCount=e.readUint8(),this.fieldOrdering=e.readUint8()}),s.createBoxCtor("frma",function(e){this.data_format=e.readString(4)}),s.createBoxCtor("ftyp",function(e){var t=this.size-this.hdr_size;this.major_brand=e.readString(4),this.minor_version=e.readUint32(),t-=8,this.compatible_brands=[];for(var r=0;t>=4;)this.compatible_brands[r]=e.readString(4),t-=4,r++}),s.createFullBoxCtor("hdlr",function(e){this.version===0&&(e.readUint32(),this.handler=e.readString(4),e.readUint32Array(3),this.name=e.readString(this.size-this.hdr_size-20),this.name[this.name.length-1]==="\\0"&&(this.name=this.name.slice(0,-1)))}),s.createBoxCtor("hvcC",function(e){var t,r,l,c;this.configurationVersion=e.readUint8(),c=e.readUint8(),this.general_profile_space=c>>6,this.general_tier_flag=(c&32)>>5,this.general_profile_idc=c&31,this.general_profile_compatibility=e.readUint32(),this.general_constraint_indicator=e.readUint8Array(6),this.general_level_idc=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3,this.chroma_format_idc=e.readUint8()&3,this.bit_depth_luma_minus8=e.readUint8()&7,this.bit_depth_chroma_minus8=e.readUint8()&7,this.avgFrameRate=e.readUint16(),c=e.readUint8(),this.constantFrameRate=c>>6,this.numTemporalLayers=(c&13)>>3,this.temporalIdNested=(c&4)>>2,this.lengthSizeMinusOne=c&3,this.nalu_arrays=[];var _=e.readUint8();for(t=0;t<_;t++){var y=[];this.nalu_arrays.push(y),c=e.readUint8(),y.completeness=(c&128)>>7,y.nalu_type=c&63;var b=e.readUint16();for(r=0;r<b;r++){var x={};y.push(x),l=e.readUint16(),x.data=e.readUint8Array(l)}}}),s.createFullBoxCtor("iinf",function(e){var t;this.version===0?this.entry_count=e.readUint16():this.entry_count=e.readUint32(),this.item_infos=[];for(var r=0;r<this.entry_count;r++)if(t=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),t.code===s.OK)t.box.type!=="infe"&&n.error("BoxParser","Expected \'infe\' box, got "+t.box.type),this.item_infos[r]=t.box;else return}),s.createFullBoxCtor("iloc",function(e){var t;t=e.readUint8(),this.offset_size=t>>4&15,this.length_size=t&15,t=e.readUint8(),this.base_offset_size=t>>4&15,this.version===1||this.version===2?this.index_size=t&15:this.index_size=0,this.items=[];var r=0;if(this.version<2)r=e.readUint16();else if(this.version===2)r=e.readUint32();else throw"version of iloc box not supported";for(var l=0;l<r;l++){var c={};if(this.items.push(c),this.version<2)c.item_ID=e.readUint16();else if(this.version===2)c.item_ID=e.readUint32();else throw"version of iloc box not supported";switch(this.version===1||this.version===2?c.construction_method=e.readUint16()&15:c.construction_method=0,c.data_reference_index=e.readUint16(),this.base_offset_size){case 0:c.base_offset=0;break;case 4:c.base_offset=e.readUint32();break;case 8:c.base_offset=e.readUint64();break;default:throw"Error reading base offset size"}var _=e.readUint16();c.extents=[];for(var y=0;y<_;y++){var b={};if(c.extents.push(b),this.version===1||this.version===2)switch(this.index_size){case 0:b.extent_index=0;break;case 4:b.extent_index=e.readUint32();break;case 8:b.extent_index=e.readUint64();break;default:throw"Error reading extent index"}switch(this.offset_size){case 0:b.extent_offset=0;break;case 4:b.extent_offset=e.readUint32();break;case 8:b.extent_offset=e.readUint64();break;default:throw"Error reading extent index"}switch(this.length_size){case 0:b.extent_length=0;break;case 4:b.extent_length=e.readUint32();break;case 8:b.extent_length=e.readUint64();break;default:throw"Error reading extent index"}}}}),s.createBoxCtor("imir",function(e){var t=e.readUint8();this.reserved=t>>7,this.axis=t&1}),s.createFullBoxCtor("infe",function(e){if((this.version===0||this.version===1)&&(this.item_ID=e.readUint16(),this.item_protection_index=e.readUint16(),this.item_name=e.readCString(),this.content_type=e.readCString(),this.content_encoding=e.readCString()),this.version===1){this.extension_type=e.readString(4),n.warn("BoxParser","Cannot parse extension type"),e.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=e.readUint16():this.version===3&&(this.item_ID=e.readUint32()),this.item_protection_index=e.readUint16(),this.item_type=e.readString(4),this.item_name=e.readCString(),this.item_type==="mime"?(this.content_type=e.readCString(),this.content_encoding=e.readCString()):this.item_type==="uri "&&(this.item_uri_type=e.readCString()))}),s.createFullBoxCtor("ipma",function(e){var t,r;for(entry_count=e.readUint32(),this.associations=[],t=0;t<entry_count;t++){var l={};this.associations.push(l),this.version<1?l.id=e.readUint16():l.id=e.readUint32();var c=e.readUint8();for(l.props=[],r=0;r<c;r++){var _=e.readUint8(),y={};l.props.push(y),y.essential=(_&128)>>7===1,this.flags&1?y.property_index=(_&127)<<8|e.readUint8():y.property_index=_&127}}}),s.createFullBoxCtor("iref",function(e){var t,r;for(this.references=[];e.getPosition()<this.start+this.size;)if(t=s.parseOneBox(e,!0,this.size-(e.getPosition()-this.start)),t.code===s.OK)this.version===0?r=new s.SingleItemTypeReferenceBox(t.type,t.size,t.hdr_size,t.start):r=new s.SingleItemTypeReferenceBoxLarge(t.type,t.size,t.hdr_size,t.start),r.write===s.Box.prototype.write&&r.type!=="mdat"&&(n.warn("BoxParser",r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(e)),r.parse(e),this.references.push(r);else return}),s.createBoxCtor("irot",function(e){this.angle=e.readUint8()&3}),s.createFullBoxCtor("ispe",function(e){this.image_width=e.readUint32(),this.image_height=e.readUint32()}),s.createFullBoxCtor("kind",function(e){this.schemeURI=e.readCString(),this.value=e.readCString()}),s.createFullBoxCtor("leva",function(e){var t=e.readUint8();this.levels=[];for(var r=0;r<t;r++){var l={};this.levels[r]=l,l.track_ID=e.readUint32();var c=e.readUint8();switch(l.padding_flag=c>>7,l.assignment_type=c&127,l.assignment_type){case 0:l.grouping_type=e.readString(4);break;case 1:l.grouping_type=e.readString(4),l.grouping_type_parameter=e.readUint32();break;case 2:break;case 3:break;case 4:l.sub_track_id=e.readUint32();break;default:n.warn("BoxParser","Unknown leva assignement type")}}}),s.createBoxCtor("lhvC",function(e){var t,r,l;this.configurationVersion=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3,l=e.readUint8(),this.numTemporalLayers=(l&13)>>3,this.temporalIdNested=(l&4)>>2,this.lengthSizeMinusOne=l&3,this.nalu_arrays=[];var c=e.readUint8();for(t=0;t<c;t++){var _=[];this.nalu_arrays.push(_),l=e.readUint8(),_.completeness=(l&128)>>7,_.nalu_type=l&63;var y=e.readUint16();for(r=0;r<y;r++){var b={};_.push(b);var x=e.readUint16();b.data=e.readUint8Array(x)}}}),s.createBoxCtor("lsel",function(e){this.layer_id=e.readUint16()}),s.createBoxCtor("maxr",function(e){this.period=e.readUint32(),this.bytes=e.readUint32()});function p(e,t){this.x=e,this.y=t}p.prototype.toString=function(){return"("+this.x+","+this.y+")"},s.createBoxCtor("mdcv",function(e){this.display_primaries=[],this.display_primaries[0]=new p(e.readUint16(),e.readUint16()),this.display_primaries[1]=new p(e.readUint16(),e.readUint16()),this.display_primaries[2]=new p(e.readUint16(),e.readUint16()),this.white_point=new p(e.readUint16(),e.readUint16()),this.max_display_mastering_luminance=e.readUint32(),this.min_display_mastering_luminance=e.readUint32()}),s.createFullBoxCtor("mdhd",function(e){this.version==1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.timescale=e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.timescale=e.readUint32(),this.duration=e.readUint32()),this.parseLanguage(e),e.readUint16()}),s.createFullBoxCtor("mehd",function(e){this.flags&1&&(n.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version==1?this.fragment_duration=e.readUint64():this.fragment_duration=e.readUint32()}),s.createFullBoxCtor("meta",function(e){this.boxes=[],s.ContainerBox.prototype.parse.call(this,e)}),s.createFullBoxCtor("mfhd",function(e){this.sequence_number=e.readUint32()}),s.createFullBoxCtor("mfro",function(e){this._size=e.readUint32()}),s.createFullBoxCtor("mskC",function(e){this.bits_per_pixel=e.readUint8()}),s.createFullBoxCtor("mvhd",function(e){this.version==1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.timescale=e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.timescale=e.readUint32(),this.duration=e.readUint32()),this.rate=e.readUint32(),this.volume=e.readUint16()>>8,e.readUint16(),e.readUint32Array(2),this.matrix=e.readUint32Array(9),e.readUint32Array(6),this.next_track_id=e.readUint32()}),s.createBoxCtor("npck",function(e){this.packetssent=e.readUint32()}),s.createBoxCtor("nump",function(e){this.packetssent=e.readUint64()}),s.createFullBoxCtor("padb",function(e){var t=e.readUint32();this.padbits=[];for(var r=0;r<Math.floor((t+1)/2);r++)this.padbits=e.readUint8()}),s.createBoxCtor("pasp",function(e){this.hSpacing=e.readUint32(),this.vSpacing=e.readUint32()}),s.createBoxCtor("payl",function(e){this.text=e.readString(this.size-this.hdr_size)}),s.createBoxCtor("payt",function(e){this.payloadID=e.readUint32();var t=e.readUint8();this.rtpmap_string=e.readString(t)}),s.createFullBoxCtor("pdin",function(e){var t=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var r=0;r<t;r++)this.rate[r]=e.readUint32(),this.initial_delay[r]=e.readUint32()}),s.createFullBoxCtor("pitm",function(e){this.version===0?this.item_id=e.readUint16():this.item_id=e.readUint32()}),s.createFullBoxCtor("pixi",function(e){var t;for(this.num_channels=e.readUint8(),this.bits_per_channels=[],t=0;t<this.num_channels;t++)this.bits_per_channels[t]=e.readUint8()}),s.createBoxCtor("pmax",function(e){this.bytes=e.readUint32()}),s.createFullBoxCtor("prdi",function(e){if(this.step_count=e.readUint16(),this.item_count=[],this.flags&2)for(var t=0;t<this.step_count;t++)this.item_count[t]=e.readUint16()}),s.createFullBoxCtor("prft",function(e){this.ref_track_id=e.readUint32(),this.ntp_timestamp=e.readUint64(),this.version===0?this.media_time=e.readUint32():this.media_time=e.readUint64()}),s.createFullBoxCtor("pssh",function(e){if(this.system_id=s.parseHex16(e),this.version>0){var t=e.readUint32();this.kid=[];for(var r=0;r<t;r++)this.kid[r]=s.parseHex16(e)}var l=e.readUint32();l>0&&(this.data=e.readUint8Array(l))}),s.createFullBoxCtor("clef",function(e){this.width=e.readUint32(),this.height=e.readUint32()}),s.createFullBoxCtor("enof",function(e){this.width=e.readUint32(),this.height=e.readUint32()}),s.createFullBoxCtor("prof",function(e){this.width=e.readUint32(),this.height=e.readUint32()}),s.createContainerBoxCtor("tapt",null,["clef","prof","enof"]),s.createBoxCtor("rtp ",function(e){this.descriptionformat=e.readString(4),this.sdptext=e.readString(this.size-this.hdr_size-4)}),s.createFullBoxCtor("saio",function(e){this.flags&1&&(this.aux_info_type=e.readString(4),this.aux_info_type_parameter=e.readUint32());var t=e.readUint32();this.offset=[];for(var r=0;r<t;r++)this.version===0?this.offset[r]=e.readUint32():this.offset[r]=e.readUint64()}),s.createFullBoxCtor("saiz",function(e){if(this.flags&1&&(this.aux_info_type=e.readString(4),this.aux_info_type_parameter=e.readUint32()),this.default_sample_info_size=e.readUint8(),this.sample_count=e.readUint32(),this.sample_info_size=[],this.default_sample_info_size===0)for(var t=0;t<this.sample_count;t++)this.sample_info_size[t]=e.readUint8()}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"mett",function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"metx",function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.namespace=e.readCString(),this.schema_location=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"sbtt",function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"stpp",function(e){this.parseHeader(e),this.namespace=e.readCString(),this.schema_location=e.readCString(),this.auxiliary_mime_types=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"stxt",function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"tx3g",function(e){this.parseHeader(e),this.displayFlags=e.readUint32(),this.horizontal_justification=e.readInt8(),this.vertical_justification=e.readInt8(),this.bg_color_rgba=e.readUint8Array(4),this.box_record=e.readInt16Array(4),this.style_record=e.readUint8Array(12),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"wvtt",function(e){this.parseHeader(e),this.parseFooter(e)}),s.createSampleGroupCtor("alst",function(e){var t,r=e.readUint16();for(this.first_output_sample=e.readUint16(),this.sample_offset=[],t=0;t<r;t++)this.sample_offset[t]=e.readUint32();var l=this.description_length-4-4*r;for(this.num_output_samples=[],this.num_total_samples=[],t=0;t<l/4;t++)this.num_output_samples[t]=e.readUint16(),this.num_total_samples[t]=e.readUint16()}),s.createSampleGroupCtor("avll",function(e){this.layerNumber=e.readUint8(),this.accurateStatisticsFlag=e.readUint8(),this.avgBitRate=e.readUint16(),this.avgFrameRate=e.readUint16()}),s.createSampleGroupCtor("avss",function(e){this.subSequenceIdentifier=e.readUint16(),this.layerNumber=e.readUint8();var t=e.readUint8();this.durationFlag=t>>7,this.avgRateFlag=t>>6&1,this.durationFlag&&(this.duration=e.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=e.readUint8(),this.avgBitRate=e.readUint16(),this.avgFrameRate=e.readUint16()),this.dependency=[];for(var r=e.readUint8(),l=0;l<r;l++){var c={};this.dependency.push(c),c.subSeqDirectionFlag=e.readUint8(),c.layerNumber=e.readUint8(),c.subSequenceIdentifier=e.readUint16()}}),s.createSampleGroupCtor("dtrt",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("mvif",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("prol",function(e){this.roll_distance=e.readInt16()}),s.createSampleGroupCtor("rap ",function(e){var t=e.readUint8();this.num_leading_samples_known=t>>7,this.num_leading_samples=t&127}),s.createSampleGroupCtor("rash",function(e){if(this.operation_point_count=e.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)n.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=e.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=e.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(var t=0;t<this.operation_point_count;t++)this.available_bitrate[t]=e.readUint32(),this.target_rate_share[t]=e.readUint16()}this.maximum_bitrate=e.readUint32(),this.minimum_bitrate=e.readUint32(),this.discard_priority=e.readUint8()}}),s.createSampleGroupCtor("roll",function(e){this.roll_distance=e.readInt16()}),s.SampleGroupEntry.prototype.parse=function(e){n.warn("BoxParser","Unknown Sample Group type: "+this.grouping_type),this.data=e.readUint8Array(this.description_length)},s.createSampleGroupCtor("scif",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("scnm",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("seig",function(e){this.reserved=e.readUint8();var t=e.readUint8();this.crypt_byte_block=t>>4,this.skip_byte_block=t&15,this.isProtected=e.readUint8(),this.Per_Sample_IV_Size=e.readUint8(),this.KID=s.parseHex16(e),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=e.readUint8(),this.constant_IV=e.readUint8Array(this.constant_IV_size))}),s.createSampleGroupCtor("stsa",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("sync",function(e){var t=e.readUint8();this.NAL_unit_type=t&63}),s.createSampleGroupCtor("tele",function(e){var t=e.readUint8();this.level_independently_decodable=t>>7}),s.createSampleGroupCtor("tsas",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("tscl",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("vipr",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createFullBoxCtor("sbgp",function(e){this.grouping_type=e.readString(4),this.version===1?this.grouping_type_parameter=e.readUint32():this.grouping_type_parameter=0,this.entries=[];for(var t=e.readUint32(),r=0;r<t;r++){var l={};this.entries.push(l),l.sample_count=e.readInt32(),l.group_description_index=e.readInt32()}});function m(e,t){this.bad_pixel_row=e,this.bad_pixel_column=t}m.prototype.toString=function(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"},s.createFullBoxCtor("sbpm",function(e){var t;for(this.component_count=e.readUint16(),this.component_index=[],t=0;t<this.component_count;t++)this.component_index.push(e.readUint16());var r=e.readUint8();for(this.correction_applied=(r&128)==128,this.num_bad_rows=e.readUint32(),this.num_bad_cols=e.readUint32(),this.num_bad_pixels=e.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[],t=0;t<this.num_bad_rows;t++)this.bad_rows.push(e.readUint32());for(t=0;t<this.num_bad_cols;t++)this.bad_columns.push(e.readUint32());for(t=0;t<this.num_bad_pixels;t++){var l=e.readUint32(),c=e.readUint32();this.bad_pixels.push(new m(l,c))}}),s.createFullBoxCtor("schm",function(e){this.scheme_type=e.readString(4),this.scheme_version=e.readUint32(),this.flags&1&&(this.scheme_uri=e.readString(this.size-this.hdr_size-8))}),s.createBoxCtor("sdp ",function(e){this.sdptext=e.readString(this.size-this.hdr_size)}),s.createFullBoxCtor("sdtp",function(e){var t,r=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var l=0;l<r;l++)t=e.readUint8(),this.is_leading[l]=t>>6,this.sample_depends_on[l]=t>>4&3,this.sample_is_depended_on[l]=t>>2&3,this.sample_has_redundancy[l]=t&3}),s.createFullBoxCtor("senc"),s.createFullBoxCtor("sgpd",function(e){this.grouping_type=e.readString(4),n.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=e.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=e.readUint32()),this.entries=[];for(var t=e.readUint32(),r=0;r<t;r++){var l;s[this.grouping_type+"SampleGroupEntry"]?l=new s[this.grouping_type+"SampleGroupEntry"](this.grouping_type):l=new s.SampleGroupEntry(this.grouping_type),this.entries.push(l),this.version===1?this.default_length===0?l.description_length=e.readUint32():l.description_length=this.default_length:l.description_length=this.default_length,l.write===s.SampleGroupEntry.prototype.write&&(n.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),l.data=e.readUint8Array(l.description_length),e.position-=l.description_length),l.parse(e)}}),s.createFullBoxCtor("sidx",function(e){this.reference_ID=e.readUint32(),this.timescale=e.readUint32(),this.version===0?(this.earliest_presentation_time=e.readUint32(),this.first_offset=e.readUint32()):(this.earliest_presentation_time=e.readUint64(),this.first_offset=e.readUint64()),e.readUint16(),this.references=[];for(var t=e.readUint16(),r=0;r<t;r++){var l={};this.references.push(l);var c=e.readUint32();l.reference_type=c>>31&1,l.referenced_size=c&2147483647,l.subsegment_duration=e.readUint32(),c=e.readUint32(),l.starts_with_SAP=c>>31&1,l.SAP_type=c>>28&7,l.SAP_delta_time=c&268435455}}),s.SingleItemTypeReferenceBox=function(e,t,r,l){s.Box.call(this,e,t),this.hdr_size=r,this.start=l},s.SingleItemTypeReferenceBox.prototype=new s.Box,s.SingleItemTypeReferenceBox.prototype.parse=function(e){this.from_item_ID=e.readUint16();var t=e.readUint16();this.references=[];for(var r=0;r<t;r++)this.references[r]={},this.references[r].to_item_ID=e.readUint16()},s.SingleItemTypeReferenceBoxLarge=function(e,t,r,l){s.Box.call(this,e,t),this.hdr_size=r,this.start=l},s.SingleItemTypeReferenceBoxLarge.prototype=new s.Box,s.SingleItemTypeReferenceBoxLarge.prototype.parse=function(e){this.from_item_ID=e.readUint32();var t=e.readUint16();this.references=[];for(var r=0;r<t;r++)this.references[r]={},this.references[r].to_item_ID=e.readUint32()},s.createFullBoxCtor("SmDm",function(e){this.primaryRChromaticity_x=e.readUint16(),this.primaryRChromaticity_y=e.readUint16(),this.primaryGChromaticity_x=e.readUint16(),this.primaryGChromaticity_y=e.readUint16(),this.primaryBChromaticity_x=e.readUint16(),this.primaryBChromaticity_y=e.readUint16(),this.whitePointChromaticity_x=e.readUint16(),this.whitePointChromaticity_y=e.readUint16(),this.luminanceMax=e.readUint32(),this.luminanceMin=e.readUint32()}),s.createFullBoxCtor("smhd",function(e){this.balance=e.readUint16(),e.readUint16()}),s.createFullBoxCtor("ssix",function(e){this.subsegments=[];for(var t=e.readUint32(),r=0;r<t;r++){var l={};this.subsegments.push(l),l.ranges=[];for(var c=e.readUint32(),_=0;_<c;_++){var y={};l.ranges.push(y),y.level=e.readUint8(),y.range_size=e.readUint24()}}}),s.createFullBoxCtor("stco",function(e){var t;if(t=e.readUint32(),this.chunk_offsets=[],this.version===0)for(var r=0;r<t;r++)this.chunk_offsets.push(e.readUint32())}),s.createFullBoxCtor("stdp",function(e){var t=(this.size-this.hdr_size)/2;this.priority=[];for(var r=0;r<t;r++)this.priority[r]=e.readUint16()}),s.createFullBoxCtor("sthd"),s.createFullBoxCtor("stri",function(e){this.switch_group=e.readUint16(),this.alternate_group=e.readUint16(),this.sub_track_id=e.readUint32();var t=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(var r=0;r<t;r++)this.attribute_list[r]=e.readUint32()}),s.createFullBoxCtor("stsc",function(e){var t,r;if(t=e.readUint32(),this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(r=0;r<t;r++)this.first_chunk.push(e.readUint32()),this.samples_per_chunk.push(e.readUint32()),this.sample_description_index.push(e.readUint32())}),s.createFullBoxCtor("stsd",function(e){var t,r,l,c;for(this.entries=[],l=e.readUint32(),t=1;t<=l;t++)if(r=s.parseOneBox(e,!0,this.size-(e.getPosition()-this.start)),r.code===s.OK)s[r.type+"SampleEntry"]?(c=new s[r.type+"SampleEntry"](r.size),c.hdr_size=r.hdr_size,c.start=r.start):(n.warn("BoxParser","Unknown sample entry type: "+r.type),c=new s.SampleEntry(r.type,r.size,r.hdr_size,r.start)),c.write===s.SampleEntry.prototype.write&&(n.info("BoxParser","SampleEntry "+c.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),c.parseDataAndRewind(e)),c.parse(e),this.entries.push(c);else return}),s.createFullBoxCtor("stsg",function(e){this.grouping_type=e.readUint32();var t=e.readUint16();this.group_description_index=[];for(var r=0;r<t;r++)this.group_description_index[r]=e.readUint32()}),s.createFullBoxCtor("stsh",function(e){var t,r;if(t=e.readUint32(),this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(r=0;r<t;r++)this.shadowed_sample_numbers.push(e.readUint32()),this.sync_sample_numbers.push(e.readUint32())}),s.createFullBoxCtor("stss",function(e){var t,r;if(r=e.readUint32(),this.version===0)for(this.sample_numbers=[],t=0;t<r;t++)this.sample_numbers.push(e.readUint32())}),s.createFullBoxCtor("stsz",function(e){var t;if(this.sample_sizes=[],this.version===0)for(this.sample_size=e.readUint32(),this.sample_count=e.readUint32(),t=0;t<this.sample_count;t++)this.sample_size===0?this.sample_sizes.push(e.readUint32()):this.sample_sizes[t]=this.sample_size}),s.createFullBoxCtor("stts",function(e){var t,r,l;if(t=e.readUint32(),this.sample_counts=[],this.sample_deltas=[],this.version===0)for(r=0;r<t;r++)this.sample_counts.push(e.readUint32()),l=e.readInt32(),l<0&&(n.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),l=1),this.sample_deltas.push(l)}),s.createFullBoxCtor("stvi",function(e){var t=e.readUint32();this.single_view_allowed=t&3,this.stereo_scheme=e.readUint32();var r=e.readUint32();this.stereo_indication_type=e.readString(r);var l,c;for(this.boxes=[];e.getPosition()<this.start+this.size;)if(l=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),l.code===s.OK)c=l.box,this.boxes.push(c),this[c.type]=c;else return}),s.createBoxCtor("styp",function(e){s.ftypBox.prototype.parse.call(this,e)}),s.createFullBoxCtor("stz2",function(e){var t,r;if(this.sample_sizes=[],this.version===0)if(this.reserved=e.readUint24(),this.field_size=e.readUint8(),r=e.readUint32(),this.field_size===4)for(t=0;t<r;t+=2){var l=e.readUint8();this.sample_sizes[t]=l>>4&15,this.sample_sizes[t+1]=l&15}else if(this.field_size===8)for(t=0;t<r;t++)this.sample_sizes[t]=e.readUint8();else if(this.field_size===16)for(t=0;t<r;t++)this.sample_sizes[t]=e.readUint16();else n.error("BoxParser","Error in length field in stz2 box")}),s.createFullBoxCtor("subs",function(e){var t,r,l,c;for(l=e.readUint32(),this.entries=[],t=0;t<l;t++){var _={};if(this.entries[t]=_,_.sample_delta=e.readUint32(),_.subsamples=[],c=e.readUint16(),c>0)for(r=0;r<c;r++){var y={};_.subsamples.push(y),this.version==1?y.size=e.readUint32():y.size=e.readUint16(),y.priority=e.readUint8(),y.discardable=e.readUint8(),y.codec_specific_parameters=e.readUint32()}}}),s.createFullBoxCtor("tenc",function(e){if(e.readUint8(),this.version===0)e.readUint8();else{var t=e.readUint8();this.default_crypt_byte_block=t>>4&15,this.default_skip_byte_block=t&15}this.default_isProtected=e.readUint8(),this.default_Per_Sample_IV_Size=e.readUint8(),this.default_KID=s.parseHex16(e),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=e.readUint8(),this.default_constant_IV=e.readUint8Array(this.default_constant_IV_size))}),s.createFullBoxCtor("tfdt",function(e){this.version==1?this.baseMediaDecodeTime=e.readUint64():this.baseMediaDecodeTime=e.readUint32()}),s.createFullBoxCtor("tfhd",function(e){var t=0;this.track_id=e.readUint32(),this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=e.readUint64(),t+=8):this.base_data_offset=0,this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=e.readUint32(),t+=4):this.default_sample_description_index=0,this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=e.readUint32(),t+=4):this.default_sample_duration=0,this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=e.readUint32(),t+=4):this.default_sample_size=0,this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=e.readUint32(),t+=4):this.default_sample_flags=0}),s.createFullBoxCtor("tfra",function(e){this.track_ID=e.readUint32(),e.readUint24();var t=e.readUint8();this.length_size_of_traf_num=t>>4&3,this.length_size_of_trun_num=t>>2&3,this.length_size_of_sample_num=t&3,this.entries=[];for(var r=e.readUint32(),l=0;l<r;l++)this.version===1?(this.time=e.readUint64(),this.moof_offset=e.readUint64()):(this.time=e.readUint32(),this.moof_offset=e.readUint32()),this.traf_number=e["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=e["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=e["readUint"+8*(this.length_size_of_sample_num+1)]()}),s.createFullBoxCtor("tkhd",function(e){this.version==1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint32()),e.readUint32Array(2),this.layer=e.readInt16(),this.alternate_group=e.readInt16(),this.volume=e.readInt16()>>8,e.readUint16(),this.matrix=e.readInt32Array(9),this.width=e.readUint32(),this.height=e.readUint32()}),s.createBoxCtor("tmax",function(e){this.time=e.readUint32()}),s.createBoxCtor("tmin",function(e){this.time=e.readUint32()}),s.createBoxCtor("totl",function(e){this.bytessent=e.readUint32()}),s.createBoxCtor("tpay",function(e){this.bytessent=e.readUint32()}),s.createBoxCtor("tpyl",function(e){this.bytessent=e.readUint64()}),s.TrackGroupTypeBox.prototype.parse=function(e){this.parseFullHeader(e),this.track_group_id=e.readUint32()},s.createTrackGroupCtor("msrc"),s.TrackReferenceTypeBox=function(e,t,r,l){s.Box.call(this,e,t),this.hdr_size=r,this.start=l},s.TrackReferenceTypeBox.prototype=new s.Box,s.TrackReferenceTypeBox.prototype.parse=function(e){this.track_ids=e.readUint32Array((this.size-this.hdr_size)/4)},s.trefBox.prototype.parse=function(e){for(var t,r;e.getPosition()<this.start+this.size;)if(t=s.parseOneBox(e,!0,this.size-(e.getPosition()-this.start)),t.code===s.OK)r=new s.TrackReferenceTypeBox(t.type,t.size,t.hdr_size,t.start),r.write===s.Box.prototype.write&&r.type!=="mdat"&&(n.info("BoxParser","TrackReference "+r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(e)),r.parse(e),this.boxes.push(r);else return},s.createFullBoxCtor("trep",function(e){for(this.track_ID=e.readUint32(),this.boxes=[];e.getPosition()<this.start+this.size;)if(ret=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),ret.code===s.OK)box=ret.box,this.boxes.push(box);else return}),s.createFullBoxCtor("trex",function(e){this.track_id=e.readUint32(),this.default_sample_description_index=e.readUint32(),this.default_sample_duration=e.readUint32(),this.default_sample_size=e.readUint32(),this.default_sample_flags=e.readUint32()}),s.createBoxCtor("trpy",function(e){this.bytessent=e.readUint64()}),s.createFullBoxCtor("trun",function(e){var t=0;if(this.sample_count=e.readUint32(),t+=4,this.size-this.hdr_size>t&&this.flags&s.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=e.readInt32(),t+=4):this.data_offset=0,this.size-this.hdr_size>t&&this.flags&s.TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=e.readUint32(),t+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>t)for(var r=0;r<this.sample_count;r++)this.flags&s.TRUN_FLAGS_DURATION&&(this.sample_duration[r]=e.readUint32()),this.flags&s.TRUN_FLAGS_SIZE&&(this.sample_size[r]=e.readUint32()),this.flags&s.TRUN_FLAGS_FLAGS&&(this.sample_flags[r]=e.readUint32()),this.flags&s.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?this.sample_composition_time_offset[r]=e.readUint32():this.sample_composition_time_offset[r]=e.readInt32())}),s.createFullBoxCtor("tsel",function(e){this.switch_group=e.readUint32();var t=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var r=0;r<t;r++)this.attribute_list[r]=e.readUint32()}),s.createFullBoxCtor("txtC",function(e){this.config=e.readCString()}),s.createBoxCtor("tyco",function(e){var t=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(var r=0;r<t;r++)this.compatible_brands[r]=e.readString(4)}),s.createFullBoxCtor("udes",function(e){this.lang=e.readCString(),this.name=e.readCString(),this.description=e.readCString(),this.tags=e.readCString()}),s.createFullBoxCtor("uncC",function(e){var t;if(this.profile=e.readUint32(),this.version!=1){if(this.version==0){for(this.component_count=e.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[],t=0;t<this.component_count;t++)this.component_index.push(e.readUint16()),this.component_bit_depth_minus_one.push(e.readUint8()),this.component_format.push(e.readUint8()),this.component_align_size.push(e.readUint8());this.sampling_type=e.readUint8(),this.interleave_type=e.readUint8(),this.block_size=e.readUint8();var r=e.readUint8();this.component_little_endian=r>>7&1,this.block_pad_lsb=r>>6&1,this.block_little_endian=r>>5&1,this.block_reversed=r>>4&1,this.pad_unknown=r>>3&1,this.pixel_size=e.readUint32(),this.row_align_size=e.readUint32(),this.tile_align_size=e.readUint32(),this.num_tile_cols_minus_one=e.readUint32(),this.num_tile_rows_minus_one=e.readUint32()}}}),s.createFullBoxCtor("url ",function(e){this.flags!==1&&(this.location=e.readCString())}),s.createFullBoxCtor("urn ",function(e){this.name=e.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=e.readCString())}),s.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66",!0,!1,function(e){this.LiveServerManifest=e.readString(this.size-this.hdr_size).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\'/g,"&#039;")}),s.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3",!0,!1,function(e){this.system_id=s.parseHex16(e);var t=e.readUint32();t>0&&(this.data=e.readUint8Array(t))}),s.createUUIDBox("a2394f525a9b4f14a2446c427c648df4",!0,!1),s.createUUIDBox("8974dbce7be74c5184f97148f9882554",!0,!1,function(e){this.default_AlgorithmID=e.readUint24(),this.default_IV_size=e.readUint8(),this.default_KID=s.parseHex16(e)}),s.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f",!0,!1,function(e){this.fragment_count=e.readUint8(),this.entries=[];for(var t=0;t<this.fragment_count;t++){var r={},l=0,c=0;this.version===1?(l=e.readUint64(),c=e.readUint64()):(l=e.readUint32(),c=e.readUint32()),r.absolute_time=l,r.absolute_duration=c,this.entries.push(r)}}),s.createUUIDBox("6d1d9b0542d544e680e2141daff757b2",!0,!1,function(e){this.version===1?(this.absolute_time=e.readUint64(),this.duration=e.readUint64()):(this.absolute_time=e.readUint32(),this.duration=e.readUint32())}),s.createFullBoxCtor("vmhd",function(e){this.graphicsmode=e.readUint16(),this.opcolor=e.readUint16Array(3)}),s.createFullBoxCtor("vpcC",function(e){var t;this.version===1?(this.profile=e.readUint8(),this.level=e.readUint8(),t=e.readUint8(),this.bitDepth=t>>4,this.chromaSubsampling=t>>1&7,this.videoFullRangeFlag=t&1,this.colourPrimaries=e.readUint8(),this.transferCharacteristics=e.readUint8(),this.matrixCoefficients=e.readUint8(),this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize)):(this.profile=e.readUint8(),this.level=e.readUint8(),t=e.readUint8(),this.bitDepth=t>>4&15,this.colorSpace=t&15,t=e.readUint8(),this.chromaSubsampling=t>>4&15,this.transferFunction=t>>1&7,this.videoFullRangeFlag=t&1,this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize))}),s.createBoxCtor("vttC",function(e){this.text=e.readString(this.size-this.hdr_size)}),s.createFullBoxCtor("vvcC",function(e){var t,r,l={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(A){this.held_bits=A.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(A){this.held_bits=A.readUint16(),this.num_held_bits=16},extract_bits:function(A){var k=this.held_bits>>this.num_held_bits-A&(1<<A)-1;return this.num_held_bits-=A,k}};if(l.stream_read_1_bytes(e),l.extract_bits(5),this.lengthSizeMinusOne=l.extract_bits(2),this.ptl_present_flag=l.extract_bits(1),this.ptl_present_flag){l.stream_read_2_bytes(e),this.ols_idx=l.extract_bits(9),this.num_sublayers=l.extract_bits(3),this.constant_frame_rate=l.extract_bits(2),this.chroma_format_idc=l.extract_bits(2),l.stream_read_1_bytes(e),this.bit_depth_minus8=l.extract_bits(3),l.extract_bits(5);{if(l.stream_read_2_bytes(e),l.extract_bits(2),this.num_bytes_constraint_info=l.extract_bits(6),this.general_profile_idc=l.extract_bits(7),this.general_tier_flag=l.extract_bits(1),this.general_level_idc=e.readUint8(),l.stream_read_1_bytes(e),this.ptl_frame_only_constraint_flag=l.extract_bits(1),this.ptl_multilayer_enabled_flag=l.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(t=0;t<this.num_bytes_constraint_info-1;t++){var c=l.extract_bits(6);l.stream_read_1_bytes(e);var _=l.extract_bits(2);this.general_constraint_info[t]=c<<2|_}this.general_constraint_info[this.num_bytes_constraint_info-1]=l.extract_bits(6)}else l.extract_bits(6);if(this.num_sublayers>1){for(l.stream_read_1_bytes(e),this.ptl_sublayer_present_mask=0,r=this.num_sublayers-2;r>=0;--r){var y=l.extract_bits(1);this.ptl_sublayer_present_mask|=y<<r}for(r=this.num_sublayers;r<=8&&this.num_sublayers>1;++r)l.extract_bits(1);for(this.sublayer_level_idc=[],r=this.num_sublayers-2;r>=0;--r)this.ptl_sublayer_present_mask&1<<r&&(this.sublayer_level_idc[r]=e.readUint8())}if(this.ptl_num_sub_profiles=e.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(t=0;t<this.ptl_num_sub_profiles;t++)this.general_sub_profile_idc.push(e.readUint32())}this.max_picture_width=e.readUint16(),this.max_picture_height=e.readUint16(),this.avg_frame_rate=e.readUint16()}var b=12,x=13;this.nalu_arrays=[];var w=e.readUint8();for(t=0;t<w;t++){var C=[];this.nalu_arrays.push(C),l.stream_read_1_bytes(e),C.completeness=l.extract_bits(1),l.extract_bits(2),C.nalu_type=l.extract_bits(5);var T=1;for(C.nalu_type!=x&&C.nalu_type!=b&&(T=e.readUint16()),r=0;r<T;r++){var I=e.readUint16();C.push({data:e.readUint8Array(I),length:I})}}}),s.createFullBoxCtor("vvnC",function(e){var t=strm.readUint8();this.lengthSizeMinusOne=t&3}),s.SampleEntry.prototype.isVideo=function(){return!1},s.SampleEntry.prototype.isAudio=function(){return!1},s.SampleEntry.prototype.isSubtitle=function(){return!1},s.SampleEntry.prototype.isMetadata=function(){return!1},s.SampleEntry.prototype.isHint=function(){return!1},s.SampleEntry.prototype.getCodec=function(){return this.type.replace(".","")},s.SampleEntry.prototype.getWidth=function(){return""},s.SampleEntry.prototype.getHeight=function(){return""},s.SampleEntry.prototype.getChannelCount=function(){return""},s.SampleEntry.prototype.getSampleRate=function(){return""},s.SampleEntry.prototype.getSampleSize=function(){return""},s.VisualSampleEntry.prototype.isVideo=function(){return!0},s.VisualSampleEntry.prototype.getWidth=function(){return this.width},s.VisualSampleEntry.prototype.getHeight=function(){return this.height},s.AudioSampleEntry.prototype.isAudio=function(){return!0},s.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_count},s.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},s.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},s.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},s.MetadataSampleEntry.prototype.isMetadata=function(){return!0},s.decimalToHex=function(e,t){var r=Number(e).toString(16);for(t=typeof t>"u"||t===null?t=2:t;r.length<t;)r="0"+r;return r},s.avc1SampleEntry.prototype.getCodec=s.avc2SampleEntry.prototype.getCodec=s.avc3SampleEntry.prototype.getCodec=s.avc4SampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this);return this.avcC?e+"."+s.decimalToHex(this.avcC.AVCProfileIndication)+s.decimalToHex(this.avcC.profile_compatibility)+s.decimalToHex(this.avcC.AVCLevelIndication):e},s.hev1SampleEntry.prototype.getCodec=s.hvc1SampleEntry.prototype.getCodec=function(){var e,t=s.SampleEntry.prototype.getCodec.call(this);if(this.hvcC){switch(t+=".",this.hvcC.general_profile_space){case 0:t+="";break;case 1:t+="A";break;case 2:t+="B";break;case 3:t+="C";break}t+=this.hvcC.general_profile_idc,t+=".";var r=this.hvcC.general_profile_compatibility,l=0;for(e=0;e<32&&(l|=r&1,e!=31);e++)l<<=1,r>>=1;t+=s.decimalToHex(l,0),t+=".",this.hvcC.general_tier_flag===0?t+="L":t+="H",t+=this.hvcC.general_level_idc;var c=!1,_="";for(e=5;e>=0;e--)(this.hvcC.general_constraint_indicator[e]||c)&&(_="."+s.decimalToHex(this.hvcC.general_constraint_indicator[e],0)+_,c=!0);t+=_}return t},s.vvc1SampleEntry.prototype.getCodec=s.vvi1SampleEntry.prototype.getCodec=function(){var e,t=s.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){t+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?t+=".H":t+=".L",t+=this.vvcC.general_level_idc;var r="";if(this.vvcC.general_constraint_info){var l=[],c=0;c|=this.vvcC.ptl_frame_only_constraint<<7,c|=this.vvcC.ptl_multilayer_enabled<<6;var _;for(e=0;e<this.vvcC.general_constraint_info.length;++e)c|=this.vvcC.general_constraint_info[e]>>2&63,l.push(c),c&&(_=e),c=this.vvcC.general_constraint_info[e]>>2&3;if(_===void 0)r=".CA";else{r=".C";var y="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",b=0,x=0;for(e=0;e<=_;++e)for(b=b<<8|l[e],x+=8;x>=5;){var w=b>>x-5&31;r+=y[w],x-=5,b&=(1<<x)-1}x&&(b<<=5-x,r+=y[b&31])}}t+=r}return t},s.mp4aSampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var t=this.esds.esd.getOTI(),r=this.esds.esd.getAudioConfig();return e+"."+s.decimalToHex(t)+(r?"."+r:"")}else return e},s.stxtSampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this);return this.mime_format?e+"."+this.mime_format:e},s.vp08SampleEntry.prototype.getCodec=s.vp09SampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this),t=this.vpcC.level;t==0&&(t="00");var r=this.vpcC.bitDepth;return r==8&&(r="08"),e+".0"+this.vpcC.profile+"."+t+"."+r},s.av01SampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this),t=this.av1C.seq_level_idx_0;t<10&&(t="0"+t);var r;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?r=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(r=this.av1C.high_bitdepth===1?"10":"08"),e+"."+this.av1C.seq_profile+"."+t+(this.av1C.seq_tier_0?"H":"M")+"."+r},s.Box.prototype.writeHeader=function(e,t){this.size+=8,this.size>h&&(this.size+=8),this.type==="uuid"&&(this.size+=16),n.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+e.getPosition()+(t||"")),this.size>h?e.writeUint32(1):(this.sizePosition=e.getPosition(),e.writeUint32(this.size)),e.writeString(this.type,null,4),this.type==="uuid"&&e.writeUint8Array(this.uuid),this.size>h&&e.writeUint64(this.size)},s.FullBox.prototype.writeHeader=function(e){this.size+=4,s.Box.prototype.writeHeader.call(this,e," v="+this.version+" f="+this.flags),e.writeUint8(this.version),e.writeUint24(this.flags)},s.Box.prototype.write=function(e){this.type==="mdat"?this.data&&(this.size=this.data.length,this.writeHeader(e),e.writeUint8Array(this.data)):(this.size=this.data?this.data.length:0,this.writeHeader(e),this.data&&e.writeUint8Array(this.data))},s.ContainerBox.prototype.write=function(e){this.size=0,this.writeHeader(e);for(var t=0;t<this.boxes.length;t++)this.boxes[t]&&(this.boxes[t].write(e),this.size+=this.boxes[t].size);n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.TrackReferenceTypeBox.prototype.write=function(e){this.size=this.track_ids.length*4,this.writeHeader(e),e.writeUint32Array(this.track_ids)},s.avcCBox.prototype.write=function(e){var t;for(this.size=7,t=0;t<this.SPS.length;t++)this.size+=2+this.SPS[t].length;for(t=0;t<this.PPS.length;t++)this.size+=2+this.PPS[t].length;for(this.ext&&(this.size+=this.ext.length),this.writeHeader(e),e.writeUint8(this.configurationVersion),e.writeUint8(this.AVCProfileIndication),e.writeUint8(this.profile_compatibility),e.writeUint8(this.AVCLevelIndication),e.writeUint8(this.lengthSizeMinusOne+252),e.writeUint8(this.SPS.length+224),t=0;t<this.SPS.length;t++)e.writeUint16(this.SPS[t].length),e.writeUint8Array(this.SPS[t].nalu);for(e.writeUint8(this.PPS.length),t=0;t<this.PPS.length;t++)e.writeUint16(this.PPS[t].length),e.writeUint8Array(this.PPS[t].nalu);this.ext&&e.writeUint8Array(this.ext)},s.co64Box.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(e),e.writeUint32(this.chunk_offsets.length),t=0;t<this.chunk_offsets.length;t++)e.writeUint64(this.chunk_offsets[t])},s.cslgBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(e),e.writeInt32(this.compositionToDTSShift),e.writeInt32(this.leastDecodeToDisplayDelta),e.writeInt32(this.greatestDecodeToDisplayDelta),e.writeInt32(this.compositionStartTime),e.writeInt32(this.compositionEndTime)},s.cttsBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(e),e.writeUint32(this.sample_counts.length),t=0;t<this.sample_counts.length;t++)e.writeUint32(this.sample_counts[t]),this.version===1?e.writeInt32(this.sample_offsets[t]):e.writeUint32(this.sample_offsets[t])},s.drefBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.entries.length);for(var t=0;t<this.entries.length;t++)this.entries[t].write(e),this.size+=this.entries[t].size;n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.elngBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(e),e.writeString(this.extended_language)},s.elstBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4+12*this.entries.length,this.writeHeader(e),e.writeUint32(this.entries.length);for(var t=0;t<this.entries.length;t++){var r=this.entries[t];e.writeUint32(r.segment_duration),e.writeInt32(r.media_time),e.writeInt16(r.media_rate_integer),e.writeInt16(r.media_rate_fraction)}},s.emsgBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4*4+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(e),e.writeCString(this.scheme_id_uri),e.writeCString(this.value),e.writeUint32(this.timescale),e.writeUint32(this.presentation_time_delta),e.writeUint32(this.event_duration),e.writeUint32(this.id),e.writeUint8Array(this.message_data)},s.ftypBox.prototype.write=function(e){this.size=8+4*this.compatible_brands.length,this.writeHeader(e),e.writeString(this.major_brand,null,4),e.writeUint32(this.minor_version);for(var t=0;t<this.compatible_brands.length;t++)e.writeString(this.compatible_brands[t],null,4)},s.hdlrBox.prototype.write=function(e){this.size=5*4+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(e),e.writeUint32(0),e.writeString(this.handler,null,4),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeCString(this.name)},s.hvcCBox.prototype.write=function(e){var t,r;for(this.size=23,t=0;t<this.nalu_arrays.length;t++)for(this.size+=3,r=0;r<this.nalu_arrays[t].length;r++)this.size+=2+this.nalu_arrays[t][r].data.length;for(this.writeHeader(e),e.writeUint8(this.configurationVersion),e.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),e.writeUint32(this.general_profile_compatibility),e.writeUint8Array(this.general_constraint_indicator),e.writeUint8(this.general_level_idc),e.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),e.writeUint8(this.parallelismType+252),e.writeUint8(this.chroma_format_idc+252),e.writeUint8(this.bit_depth_luma_minus8+248),e.writeUint8(this.bit_depth_chroma_minus8+248),e.writeUint16(this.avgFrameRate),e.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),e.writeUint8(this.nalu_arrays.length),t=0;t<this.nalu_arrays.length;t++)for(e.writeUint8((this.nalu_arrays[t].completeness<<7)+this.nalu_arrays[t].nalu_type),e.writeUint16(this.nalu_arrays[t].length),r=0;r<this.nalu_arrays[t].length;r++)e.writeUint16(this.nalu_arrays[t][r].data.length),e.writeUint8Array(this.nalu_arrays[t][r].data)},s.kindBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value.length+1),this.writeHeader(e),e.writeCString(this.schemeURI),e.writeCString(this.value)},s.mdhdBox.prototype.write=function(e){this.size=4*4+2*2,this.flags=0,this.version=0,this.writeHeader(e),e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration),e.writeUint16(this.language),e.writeUint16(0)},s.mehdBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.fragment_duration)},s.mfhdBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.sequence_number)},s.mvhdBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=23*4+2*2,this.writeHeader(e),e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration),e.writeUint32(this.rate),e.writeUint16(this.volume<<8),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32Array(this.matrix),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(this.next_track_id)},s.SampleEntry.prototype.writeHeader=function(e){this.size=8,s.Box.prototype.writeHeader.call(this,e),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint16(this.data_reference_index)},s.SampleEntry.prototype.writeFooter=function(e){for(var t=0;t<this.boxes.length;t++)this.boxes[t].write(e),this.size+=this.boxes[t].size;n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.SampleEntry.prototype.write=function(e){this.writeHeader(e),e.writeUint8Array(this.data),this.size+=this.data.length,n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.VisualSampleEntry.prototype.write=function(e){this.writeHeader(e),this.size+=2*7+6*4+32,e.writeUint16(0),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.width),e.writeUint16(this.height),e.writeUint32(this.horizresolution),e.writeUint32(this.vertresolution),e.writeUint32(0),e.writeUint16(this.frame_count),e.writeUint8(Math.min(31,this.compressorname.length)),e.writeString(this.compressorname,null,31),e.writeUint16(this.depth),e.writeInt16(-1),this.writeFooter(e)},s.AudioSampleEntry.prototype.write=function(e){this.writeHeader(e),this.size+=2*4+3*4,e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.channel_count),e.writeUint16(this.samplesize),e.writeUint16(0),e.writeUint16(0),e.writeUint32(this.samplerate<<16),this.writeFooter(e)},s.stppSampleEntry.prototype.write=function(e){this.writeHeader(e),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,e.writeCString(this.namespace),e.writeCString(this.schema_location),e.writeCString(this.auxiliary_mime_types),this.writeFooter(e)},s.SampleGroupEntry.prototype.write=function(e){e.writeUint8Array(this.data)},s.sbgpBox.prototype.write=function(e){this.version=1,this.flags=0,this.size=12+8*this.entries.length,this.writeHeader(e),e.writeString(this.grouping_type,null,4),e.writeUint32(this.grouping_type_parameter),e.writeUint32(this.entries.length);for(var t=0;t<this.entries.length;t++){var r=this.entries[t];e.writeInt32(r.sample_count),e.writeInt32(r.group_description_index)}},s.sgpdBox.prototype.write=function(e){var t,r;for(this.flags=0,this.size=12,t=0;t<this.entries.length;t++)r=this.entries[t],this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=r.data.length);for(this.writeHeader(e),e.writeString(this.grouping_type,null,4),this.version===1&&e.writeUint32(this.default_length),this.version>=2&&e.writeUint32(this.default_sample_description_index),e.writeUint32(this.entries.length),t=0;t<this.entries.length;t++)r=this.entries[t],this.version===1&&this.default_length===0&&e.writeUint32(r.description_length),r.write(e)},s.sidxBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4*4+2+2+12*this.references.length,this.writeHeader(e),e.writeUint32(this.reference_ID),e.writeUint32(this.timescale),e.writeUint32(this.earliest_presentation_time),e.writeUint32(this.first_offset),e.writeUint16(0),e.writeUint16(this.references.length);for(var t=0;t<this.references.length;t++){var r=this.references[t];e.writeUint32(r.reference_type<<31|r.referenced_size),e.writeUint32(r.subsegment_duration),e.writeUint32(r.starts_with_SAP<<31|r.SAP_type<<28|r.SAP_delta_time)}},s.smhdBox.prototype.write=function(e){this.version=0,this.flags=1,this.size=4,this.writeHeader(e),e.writeUint16(this.balance),e.writeUint16(0)},s.stcoBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(e),e.writeUint32(this.chunk_offsets.length),e.writeUint32Array(this.chunk_offsets)},s.stscBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(e),e.writeUint32(this.first_chunk.length),t=0;t<this.first_chunk.length;t++)e.writeUint32(this.first_chunk[t]),e.writeUint32(this.samples_per_chunk[t]),e.writeUint32(this.sample_description_index[t])},s.stsdBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=0,this.writeHeader(e),e.writeUint32(this.entries.length),this.size+=4,t=0;t<this.entries.length;t++)this.entries[t].write(e),this.size+=this.entries[t].size;n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.stshBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(e),e.writeUint32(this.shadowed_sample_numbers.length),t=0;t<this.shadowed_sample_numbers.length;t++)e.writeUint32(this.shadowed_sample_numbers[t]),e.writeUint32(this.sync_sample_numbers[t])},s.stssBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(e),e.writeUint32(this.sample_numbers.length),e.writeUint32Array(this.sample_numbers)},s.stszBox.prototype.write=function(e){var t,r=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0)for(t=0;t+1<this.sample_sizes.length;)if(this.sample_sizes[t+1]!==this.sample_sizes[0]){r=!1;break}else t++;else r=!1;this.size=8,r||(this.size+=4*this.sample_sizes.length),this.writeHeader(e),r?e.writeUint32(this.sample_sizes[0]):e.writeUint32(0),e.writeUint32(this.sample_sizes.length),r||e.writeUint32Array(this.sample_sizes)},s.sttsBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(e),e.writeUint32(this.sample_counts.length),t=0;t<this.sample_counts.length;t++)e.writeUint32(this.sample_counts[t]),e.writeUint32(this.sample_deltas[t])},s.tfdtBox.prototype.write=function(e){var t=Math.pow(2,32)-1;this.version=this.baseMediaDecodeTime>t?1:0,this.flags=0,this.size=4,this.version===1&&(this.size+=4),this.writeHeader(e),this.version===1?e.writeUint64(this.baseMediaDecodeTime):e.writeUint32(this.baseMediaDecodeTime)},s.tfhdBox.prototype.write=function(e){this.version=0,this.size=4,this.flags&s.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&s.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&s.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&s.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&s.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(e),e.writeUint32(this.track_id),this.flags&s.TFHD_FLAG_BASE_DATA_OFFSET&&e.writeUint64(this.base_data_offset),this.flags&s.TFHD_FLAG_SAMPLE_DESC&&e.writeUint32(this.default_sample_description_index),this.flags&s.TFHD_FLAG_SAMPLE_DUR&&e.writeUint32(this.default_sample_duration),this.flags&s.TFHD_FLAG_SAMPLE_SIZE&&e.writeUint32(this.default_sample_size),this.flags&s.TFHD_FLAG_SAMPLE_FLAGS&&e.writeUint32(this.default_sample_flags)},s.tkhdBox.prototype.write=function(e){this.version=0,this.size=4*18+2*4,this.writeHeader(e),e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.track_id),e.writeUint32(0),e.writeUint32(this.duration),e.writeUint32(0),e.writeUint32(0),e.writeInt16(this.layer),e.writeInt16(this.alternate_group),e.writeInt16(this.volume<<8),e.writeUint16(0),e.writeInt32Array(this.matrix),e.writeUint32(this.width),e.writeUint32(this.height)},s.trexBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(e),e.writeUint32(this.track_id),e.writeUint32(this.default_sample_description_index),e.writeUint32(this.default_sample_duration),e.writeUint32(this.default_sample_size),e.writeUint32(this.default_sample_flags)},s.trunBox.prototype.write=function(e){this.version=0,this.size=4,this.flags&s.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&s.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&s.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&s.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&s.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&s.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(e),e.writeUint32(this.sample_count),this.flags&s.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=e.getPosition(),e.writeInt32(this.data_offset)),this.flags&s.TRUN_FLAGS_FIRST_FLAG&&e.writeUint32(this.first_sample_flags);for(var t=0;t<this.sample_count;t++)this.flags&s.TRUN_FLAGS_DURATION&&e.writeUint32(this.sample_duration[t]),this.flags&s.TRUN_FLAGS_SIZE&&e.writeUint32(this.sample_size[t]),this.flags&s.TRUN_FLAGS_FLAGS&&e.writeUint32(this.sample_flags[t]),this.flags&s.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?e.writeUint32(this.sample_composition_time_offset[t]):e.writeInt32(this.sample_composition_time_offset[t]))},s["url Box"].prototype.write=function(e){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(e),this.location&&e.writeCString(this.location)},s["urn Box"].prototype.write=function(e){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(e),e.writeCString(this.name),this.location&&e.writeCString(this.location)},s.vmhdBox.prototype.write=function(e){this.version=0,this.flags=1,this.size=8,this.writeHeader(e),e.writeUint16(this.graphicsmode),e.writeUint16Array(this.opcolor)},s.cttsBox.prototype.unpack=function(e){var t,r,l;for(l=0,t=0;t<this.sample_counts.length;t++)for(r=0;r<this.sample_counts[t];r++)e[l].pts=e[l].dts+this.sample_offsets[t],l++},s.sttsBox.prototype.unpack=function(e){var t,r,l;for(l=0,t=0;t<this.sample_counts.length;t++)for(r=0;r<this.sample_counts[t];r++)l===0?e[l].dts=0:e[l].dts=e[l-1].dts+this.sample_deltas[t],l++},s.stcoBox.prototype.unpack=function(e){var t;for(t=0;t<this.chunk_offsets.length;t++)e[t].offset=this.chunk_offsets[t]},s.stscBox.prototype.unpack=function(e){var t,r,l,c,_;for(c=0,_=0,t=0;t<this.first_chunk.length;t++)for(r=0;r<(t+1<this.first_chunk.length?this.first_chunk[t+1]:1/0);r++)for(_++,l=0;l<this.samples_per_chunk[t];l++){if(e[c])e[c].description_index=this.sample_description_index[t],e[c].chunk_index=_;else return;c++}},s.stszBox.prototype.unpack=function(e){var t;for(t=0;t<this.sample_sizes.length;t++)e[t].size=this.sample_sizes[t]},s.DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],s.DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"],s.boxEqualFields=function(e,t){if(e&&!t)return!1;var r;for(r in e)if(!(s.DIFF_BOXES_PROP_NAMES.indexOf(r)>-1)){if(e[r]instanceof s.Box||t[r]instanceof s.Box)continue;if(typeof e[r]>"u"||typeof t[r]>"u")continue;if(typeof e[r]=="function"||typeof t[r]=="function")continue;if(e.subBoxNames&&e.subBoxNames.indexOf(r.slice(0,4))>-1||t.subBoxNames&&t.subBoxNames.indexOf(r.slice(0,4))>-1)continue;if(r==="data"||r==="start"||r==="size"||r==="creation_time"||r==="modification_time")continue;if(s.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(r)>-1)continue;if(e[r]!==t[r])return!1}return!0},s.boxEqual=function(e,t){if(!s.boxEqualFields(e,t))return!1;for(var r=0;r<s.DIFF_BOXES_PROP_NAMES.length;r++){var l=s.DIFF_BOXES_PROP_NAMES[r];if(e[l]&&t[l]&&!s.boxEqual(e[l],t[l]))return!1}return!0};var g=function(){};g.prototype.parseSample=function(e){var t,r,l=new o(e.buffer);for(t=[];!l.isEos();)r=s.parseOneBox(l,!1),r.code===s.OK&&r.box.type==="vttc"&&t.push(r.box);return t},g.prototype.getText=function(e,t,r){function l(w,C,T){return T=T||"0",w=w+"",w.length>=C?w:new Array(C-w.length+1).join(T)+w}function c(w){var C=Math.floor(w/3600),T=Math.floor((w-C*3600)/60),I=Math.floor(w-C*3600-T*60),A=Math.floor((w-C*3600-T*60-I)*1e3);return""+l(C,2)+":"+l(T,2)+":"+l(I,2)+"."+l(A,3)}for(var _=this.parseSample(r),y="",b=0;b<_.length;b++){var x=_[b];y+=c(e)+" --> "+c(t)+`\\r\n`,y+=x.payl.text}return y};var v=function(){};v.prototype.parseSample=function(e){var t={},r;t.resources=[];var l=new o(e.data.buffer);if(!e.subsamples||e.subsamples.length===0)t.documentString=l.readString(e.data.length);else if(t.documentString=l.readString(e.subsamples[0].size),e.subsamples.length>1)for(r=1;r<e.subsamples.length;r++)t.resources[r]=l.readUint8Array(e.subsamples[r].size);return typeof DOMParser<"u"&&(t.document=new DOMParser().parseFromString(t.documentString,"application/xml")),t};var U=function(){};U.prototype.parseSample=function(e){var t,r=new o(e.data.buffer);return t=r.readString(e.data.length),t},U.prototype.parseConfig=function(e){var t,r=new o(e.buffer);return r.readUint32(),t=r.readCString(),t},a.VTTin4Parser=g,a.XMLSubtitlein4Parser=v,a.Textin4Parser=U;var S=function(e){this.stream=e||new f,this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.onMoovStart=null,this.moovStartSent=!1,this.onReady=null,this.readySent=!1,this.onSegment=null,this.onSamples=null,this.onError=null,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.items=[],this.entity_groups=[],this.onSidx=null,this.sidxSent=!1};S.prototype.setSegmentOptions=function(e,t,r){var l=this.getTrackById(e);if(l){var c={};this.fragmentedTracks.push(c),c.id=e,c.user=t,c.trak=l,l.nextSample=0,c.segmentStream=null,c.nb_samples=1e3,c.rapAlignement=!0,r&&(r.nbSamples&&(c.nb_samples=r.nbSamples),r.rapAlignement&&(c.rapAlignement=r.rapAlignement))}},S.prototype.unsetSegmentOptions=function(e){for(var t=-1,r=0;r<this.fragmentedTracks.length;r++){var l=this.fragmentedTracks[r];l.id==e&&(t=r)}t>-1&&this.fragmentedTracks.splice(t,1)},S.prototype.setExtractionOptions=function(e,t,r){var l=this.getTrackById(e);if(l){var c={};this.extractedTracks.push(c),c.id=e,c.user=t,c.trak=l,l.nextSample=0,c.nb_samples=1e3,c.samples=[],r&&r.nbSamples&&(c.nb_samples=r.nbSamples)}},S.prototype.unsetExtractionOptions=function(e){for(var t=-1,r=0;r<this.extractedTracks.length;r++){var l=this.extractedTracks[r];l.id==e&&(t=r)}t>-1&&this.extractedTracks.splice(t,1)},S.prototype.parse=function(){var e,t,r=!1;if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else if(this.saveParsePosition&&this.saveParsePosition(),e=s.parseOneBox(this.stream,r),e.code===s.ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(e))continue;return}else return;else{var l;switch(t=e.box,l=t.type!=="uuid"?t.type:t.uuid,this.boxes.push(t),l){case"mdat":this.mdats.push(t);break;case"moof":this.moofs.push(t);break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[l]!==void 0&&n.warn("ISOFile","Duplicate Box of type: "+l+", overriding previous occurrence"),this[l]=t;break}this.updateUsedBytes&&this.updateUsedBytes(t,e)}},S.prototype.checkBuffer=function(e){if(e==null)throw"Buffer must be defined and non empty";if(e.fileStart===void 0)throw"Buffer must have a fileStart property";return e.byteLength===0?(n.warn("ISOFile","Ignoring empty buffer (fileStart: "+e.fileStart+")"),this.stream.logBufferLevel(),!1):(n.info("ISOFile","Processing buffer (fileStart: "+e.fileStart+")"),e.usedBytes=0,this.stream.insertBuffer(e),this.stream.logBufferLevel(),this.stream.initialized()?!0:(n.warn("ISOFile","Not ready to start parsing"),!1))},S.prototype.appendBuffer=function(e,t){var r;if(this.checkBuffer(e))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(t),this.nextSeekPosition?(r=this.nextSeekPosition,this.nextSeekPosition=void 0):r=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(r=this.stream.getEndFilePositionAfter(r))):this.nextParsePosition?r=this.nextParsePosition:r=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(n.info("ISOFile","Done processing buffer (fileStart: "+e.fileStart+") - next buffer to fetch should have a fileStart position of "+r),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),n.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),r},S.prototype.getInfo=function(){var e,t,r={},l,c,_,y,b=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(r.hasMoov=!0,r.duration=this.moov.mvhd.duration,r.timescale=this.moov.mvhd.timescale,r.isFragmented=this.moov.mvex!=null,r.isFragmented&&this.moov.mvex.mehd&&(r.fragment_duration=this.moov.mvex.mehd.fragment_duration),r.isProgressive=this.isProgressive,r.hasIOD=this.moov.iods!=null,r.brands=[],r.brands.push(this.ftyp.major_brand),r.brands=r.brands.concat(this.ftyp.compatible_brands),r.created=new Date(b+this.moov.mvhd.creation_time*1e3),r.modified=new Date(b+this.moov.mvhd.modification_time*1e3),r.tracks=[],r.audioTracks=[],r.videoTracks=[],r.subtitleTracks=[],r.metadataTracks=[],r.hintTracks=[],r.otherTracks=[],e=0;e<this.moov.traks.length;e++){if(l=this.moov.traks[e],y=l.mdia.minf.stbl.stsd.entries[0],c={},r.tracks.push(c),c.id=l.tkhd.track_id,c.name=l.mdia.hdlr.name,c.references=[],l.tref)for(t=0;t<l.tref.boxes.length;t++)_={},c.references.push(_),_.type=l.tref.boxes[t].type,_.track_ids=l.tref.boxes[t].track_ids;l.edts&&(c.edits=l.edts.elst.entries),c.created=new Date(b+l.tkhd.creation_time*1e3),c.modified=new Date(b+l.tkhd.modification_time*1e3),c.movie_duration=l.tkhd.duration,c.movie_timescale=r.timescale,c.layer=l.tkhd.layer,c.alternate_group=l.tkhd.alternate_group,c.volume=l.tkhd.volume,c.matrix=l.tkhd.matrix,c.track_width=l.tkhd.width/65536,c.track_height=l.tkhd.height/65536,c.timescale=l.mdia.mdhd.timescale,c.cts_shift=l.mdia.minf.stbl.cslg,c.duration=l.mdia.mdhd.duration,c.samples_duration=l.samples_duration,c.codec=y.getCodec(),c.kind=l.udta&&l.udta.kinds.length?l.udta.kinds[0]:{schemeURI:"",value:""},c.language=l.mdia.elng?l.mdia.elng.extended_language:l.mdia.mdhd.languageString,c.nb_samples=l.samples.length,c.size=l.samples_size,c.bitrate=c.size*8*c.timescale/c.samples_duration,y.isAudio()?(c.type="audio",r.audioTracks.push(c),c.audio={},c.audio.sample_rate=y.getSampleRate(),c.audio.channel_count=y.getChannelCount(),c.audio.sample_size=y.getSampleSize()):y.isVideo()?(c.type="video",r.videoTracks.push(c),c.video={},c.video.width=y.getWidth(),c.video.height=y.getHeight()):y.isSubtitle()?(c.type="subtitles",r.subtitleTracks.push(c)):y.isHint()?(c.type="metadata",r.hintTracks.push(c)):y.isMetadata()?(c.type="metadata",r.metadataTracks.push(c)):(c.type="metadata",r.otherTracks.push(c))}else r.hasMoov=!1;if(r.mime="",r.hasMoov&&r.tracks){for(r.videoTracks&&r.videoTracks.length>0?r.mime+=\'video/mp4; codecs="\':r.audioTracks&&r.audioTracks.length>0?r.mime+=\'audio/mp4; codecs="\':r.mime+=\'application/mp4; codecs="\',e=0;e<r.tracks.length;e++)e!==0&&(r.mime+=","),r.mime+=r.tracks[e].codec;r.mime+=\'"; profiles="\',r.mime+=this.ftyp.compatible_brands.join(),r.mime+=\'"\'}return r},S.prototype.setNextSeekPositionFromSample=function(e){e&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(e.offset+e.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=e.offset+e.alreadyRead)},S.prototype.processSamples=function(e){var t,r;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==null)for(t=0;t<this.fragmentedTracks.length;t++){var l=this.fragmentedTracks[t];for(r=l.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){n.debug("ISOFile","Creating media fragment on track #"+l.id+" for sample "+r.nextSample);var c=this.createFragment(l.id,r.nextSample,l.segmentStream);if(c)l.segmentStream=c,r.nextSample++;else break;if((r.nextSample%l.nb_samples===0||e||r.nextSample>=r.samples.length)&&(n.info("ISOFile","Sending fragmented data on track #"+l.id+" for samples ["+Math.max(0,r.nextSample-l.nb_samples)+","+(r.nextSample-1)+"]"),n.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(l.id,l.user,l.segmentStream.buffer,r.nextSample,e||r.nextSample>=r.samples.length),l.segmentStream=null,l!==this.fragmentedTracks[t]))break}}if(this.onSamples!==null)for(t=0;t<this.extractedTracks.length;t++){var _=this.extractedTracks[t];for(r=_.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){n.debug("ISOFile","Exporting on track #"+_.id+" sample #"+r.nextSample);var y=this.getSample(r,r.nextSample);if(y)r.nextSample++,_.samples.push(y);else{this.setNextSeekPositionFromSample(r.samples[r.nextSample]);break}if((r.nextSample%_.nb_samples===0||r.nextSample>=r.samples.length)&&(n.debug("ISOFile","Sending samples on track #"+_.id+" for sample "+r.nextSample),this.onSamples&&this.onSamples(_.id,_.user,_.samples),_.samples=[],_!==this.extractedTracks[t]))break}}}},S.prototype.getBox=function(e){var t=this.getBoxes(e,!0);return t.length?t[0]:null},S.prototype.getBoxes=function(e,t){var r=[];return S._sweep.call(this,e,r,t),r},S._sweep=function(e,t,r){this.type&&this.type==e&&t.push(this);for(var l in this.boxes){if(t.length&&r)return;S._sweep.call(this.boxes[l],e,t,r)}},S.prototype.getTrackSamplesInfo=function(e){var t=this.getTrackById(e);if(t)return t.samples},S.prototype.getTrackSample=function(e,t){var r=this.getTrackById(e),l=this.getSample(r,t);return l},S.prototype.releaseUsedSamples=function(e,t){var r=0,l=this.getTrackById(e);l.lastValidSample||(l.lastValidSample=0);for(var c=l.lastValidSample;c<t;c++)r+=this.releaseSample(l,c);n.info("ISOFile","Track #"+e+" released samples up to "+t+" (released size: "+r+", remaining: "+this.samplesDataSize+")"),l.lastValidSample=t},S.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},S.prototype.stop=function(){this.sampleProcessingStarted=!1},S.prototype.flush=function(){n.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},S.prototype.seekTrack=function(e,t,r){var l,c,_=1/0,y=0,b=0,x;if(r.samples.length===0)return n.info("ISOFile","No sample in track, cannot seek! Using time "+n.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(l=0;l<r.samples.length;l++){if(c=r.samples[l],l===0)b=0,x=c.timescale;else if(c.cts>e*c.timescale){b=l-1;break}t&&c.is_sync&&(y=l)}for(t&&(b=y),e=r.samples[b].cts,r.nextSample=b;r.samples[b].alreadyRead===r.samples[b].size&&r.samples[b+1];)b++;return _=r.samples[b].offset+r.samples[b].alreadyRead,n.info("ISOFile","Seeking to "+(t?"RAP":"")+" sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+n.getDurationString(e,x)+" and offset: "+_),{offset:_,time:e/x}},S.prototype.getTrackDuration=function(e){var t;return e.samples?(t=e.samples[e.samples.length-1],(t.cts+t.duration)/t.timescale):1/0},S.prototype.seek=function(e,t){var r=this.moov,l,c,_,y={offset:1/0,time:1/0};if(this.moov){for(_=0;_<r.traks.length;_++)l=r.traks[_],!(e>this.getTrackDuration(l))&&(c=this.seekTrack(e,t,l),c.offset<y.offset&&(y.offset=c.offset),c.time<y.time&&(y.time=c.time));return n.info("ISOFile","Seeking at time "+n.getDurationString(y.time,1)+" needs a buffer with a fileStart position of "+y.offset),y.offset===1/0?y={offset:this.nextParsePosition,time:0}:y.offset=this.stream.getEndFilePositionAfter(y.offset),n.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+y.offset),y}else throw"Cannot seek: moov not received!"},S.prototype.equal=function(e){for(var t=0;t<this.boxes.length&&t<e.boxes.length;){var r=this.boxes[t],l=e.boxes[t];if(!s.boxEqual(r,l))return!1;t++}return!0},a.ISOFile=S,S.prototype.lastBoxStartPosition=0,S.prototype.parsingMdat=null,S.prototype.nextParsePosition=0,S.prototype.discardMdatData=!1,S.prototype.processIncompleteBox=function(e){var t,r,l;return e.type==="mdat"?(t=new s[e.type+"Box"](e.size),this.parsingMdat=t,this.boxes.push(t),this.mdats.push(t),t.start=e.start,t.hdr_size=e.hdr_size,this.stream.addUsedBytes(t.hdr_size),this.lastBoxStartPosition=t.start+t.size,l=this.stream.seek(t.start+t.size,!1,this.discardMdatData),l?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=t.start+t.size,!1)):(e.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),r=this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1,r?(this.nextParsePosition=this.stream.getEndPosition(),!0):(e.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+e.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},S.prototype.hasIncompleteMdat=function(){return this.parsingMdat!==null},S.prototype.processIncompleteMdat=function(){var e,t;return e=this.parsingMdat,t=this.stream.seek(e.start+e.size,!1,this.discardMdatData),t?(n.debug("ISOFile","Found \'mdat\' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},S.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},S.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},S.prototype.updateUsedBytes=function(e,t){this.stream.addUsedBytes&&(e.type==="mdat"?(this.stream.addUsedBytes(e.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(e.size-e.hdr_size)):this.stream.addUsedBytes(e.size))},S.prototype.add=s.Box.prototype.add,S.prototype.addBox=s.Box.prototype.addBox,S.prototype.init=function(e){var t=e||{};this.add("ftyp").set("major_brand",t.brands&&t.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",t.brands||["iso4"]);var r=this.add("moov");return r.add("mvhd").set("timescale",t.timescale||600).set("rate",t.rate||65536).set("creation_time",0).set("modification_time",0).set("duration",t.duration||0).set("volume",t.width?0:256).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("next_track_id",1),r.add("mvex"),this},S.prototype.addTrack=function(e){this.moov||this.init(e);var t=e||{};t.width=t.width||320,t.height=t.height||320,t.id=t.id||this.moov.mvhd.next_track_id,t.type=t.type||"avc1";var r=this.moov.add("trak");this.moov.mvhd.next_track_id=t.id+1,r.add("tkhd").set("flags",s.TKHD_FLAG_ENABLED|s.TKHD_FLAG_IN_MOVIE|s.TKHD_FLAG_IN_PREVIEW).set("creation_time",0).set("modification_time",0).set("track_id",t.id).set("duration",t.duration||0).set("layer",t.layer||0).set("alternate_group",0).set("volume",1).set("matrix",[0,0,0,0,0,0,0,0,0]).set("width",t.width<<16).set("height",t.height<<16);var l=r.add("mdia");l.add("mdhd").set("creation_time",0).set("modification_time",0).set("timescale",t.timescale||1).set("duration",t.media_duration||0).set("language",t.language||"und"),l.add("hdlr").set("handler",t.hdlr||"vide").set("name",t.name||"Track created with MP4Box.js"),l.add("elng").set("extended_language",t.language||"fr-FR");var c=l.add("minf");if(s[t.type+"SampleEntry"]!==void 0){var _=new s[t.type+"SampleEntry"];_.data_reference_index=1;var y="";for(var b in s.sampleEntryCodes)for(var x=s.sampleEntryCodes[b],w=0;w<x.length;w++)if(x.indexOf(t.type)>-1){y=b;break}switch(y){case"Visual":if(c.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),_.set("width",t.width).set("height",t.height).set("horizresolution",72<<16).set("vertresolution",72<<16).set("frame_count",1).set("compressorname",t.type+" Compressor").set("depth",24),t.avcDecoderConfigRecord){var C=new s.avcCBox;C.parse(new o(t.avcDecoderConfigRecord)),_.addBox(C)}else if(t.hevcDecoderConfigRecord){var T=new s.hvcCBox;T.parse(new o(t.hevcDecoderConfigRecord)),_.addBox(T)}break;case"Audio":c.add("smhd").set("balance",t.balance||0),_.set("channel_count",t.channel_count||2).set("samplesize",t.samplesize||16).set("samplerate",t.samplerate||65536);break;case"Hint":c.add("hmhd");break;case"Subtitle":switch(c.add("sthd"),t.type){case"stpp":_.set("namespace",t.namespace||"nonamespace").set("schema_location",t.schema_location||"").set("auxiliary_mime_types",t.auxiliary_mime_types||"");break}break;case"Metadata":c.add("nmhd");break;case"System":c.add("nmhd");break;default:c.add("nmhd");break}t.description&&_.addBox(t.description),t.description_boxes&&t.description_boxes.forEach(function(A){_.addBox(A)}),c.add("dinf").add("dref").addEntry(new s["url Box"]().set("flags",1));var I=c.add("stbl");return I.add("stsd").addEntry(_),I.add("stts").set("sample_counts",[]).set("sample_deltas",[]),I.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),I.add("stco").set("chunk_offsets",[]),I.add("stsz").set("sample_sizes",[]),this.moov.mvex.add("trex").set("track_id",t.id).set("default_sample_description_index",t.default_sample_description_index||1).set("default_sample_duration",t.default_sample_duration||0).set("default_sample_size",t.default_sample_size||0).set("default_sample_flags",t.default_sample_flags||0),this.buildTrakSampleLists(r),t.id}},s.Box.prototype.computeSize=function(e){var t=e||new d;t.endianness=d.BIG_ENDIAN,this.write(t)},S.prototype.addSample=function(e,t,r){var l=r||{},c={},_=this.getTrackById(e);if(_!==null){c.number=_.samples.length,c.track_id=_.tkhd.track_id,c.timescale=_.mdia.mdhd.timescale,c.description_index=l.sample_description_index?l.sample_description_index-1:0,c.description=_.mdia.minf.stbl.stsd.entries[c.description_index],c.data=t,c.size=t.byteLength,c.alreadyRead=c.size,c.duration=l.duration||1,c.cts=l.cts||0,c.dts=l.dts||0,c.is_sync=l.is_sync||!1,c.is_leading=l.is_leading||0,c.depends_on=l.depends_on||0,c.is_depended_on=l.is_depended_on||0,c.has_redundancy=l.has_redundancy||0,c.degradation_priority=l.degradation_priority||0,c.offset=0,c.subsamples=l.subsamples,_.samples.push(c),_.samples_size+=c.size,_.samples_duration+=c.duration,_.first_dts===void 0&&(_.first_dts=l.dts),this.processSamples();var y=this.createSingleSampleMoof(c);return this.addBox(y),y.computeSize(),y.trafs[0].truns[0].data_offset=y.size+8,this.add("mdat").data=new Uint8Array(t),c}},S.prototype.createSingleSampleMoof=function(e){var t=0;e.is_sync?t=1<<25:t=65536;var r=new s.moofBox;r.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var l=r.add("traf"),c=this.getTrackById(e.track_id);return l.add("tfhd").set("track_id",e.track_id).set("flags",s.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),l.add("tfdt").set("baseMediaDecodeTime",e.dts-(c.first_dts||0)),l.add("trun").set("flags",s.TRUN_FLAGS_DATA_OFFSET|s.TRUN_FLAGS_DURATION|s.TRUN_FLAGS_SIZE|s.TRUN_FLAGS_FLAGS|s.TRUN_FLAGS_CTS_OFFSET).set("data_offset",0).set("first_sample_flags",0).set("sample_count",1).set("sample_duration",[e.duration]).set("sample_size",[e.size]).set("sample_flags",[t]).set("sample_composition_time_offset",[e.cts-e.dts]),r},S.prototype.lastMoofIndex=0,S.prototype.samplesDataSize=0,S.prototype.resetTables=function(){var e,t,r,l,c,_,y,b;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,e=0;e<this.moov.traks.length;e++){t=this.moov.traks[e],t.tkhd.duration=0,t.mdia.mdhd.duration=0,r=t.mdia.minf.stbl.stco||t.mdia.minf.stbl.co64,r.chunk_offsets=[],l=t.mdia.minf.stbl.stsc,l.first_chunk=[],l.samples_per_chunk=[],l.sample_description_index=[],c=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2,c.sample_sizes=[],_=t.mdia.minf.stbl.stts,_.sample_counts=[],_.sample_deltas=[],y=t.mdia.minf.stbl.ctts,y&&(y.sample_counts=[],y.sample_offsets=[]),b=t.mdia.minf.stbl.stss;var x=t.mdia.minf.stbl.boxes.indexOf(b);x!=-1&&(t.mdia.minf.stbl.boxes[x]=null)}},S.initSampleGroups=function(e,t,r,l,c){var _,y,b,x;function w(C,T,I){this.grouping_type=C,this.grouping_type_parameter=T,this.sbgp=I,this.last_sample_in_run=-1,this.entry_index=-1}for(t&&(t.sample_groups_info=[]),e.sample_groups_info||(e.sample_groups_info=[]),y=0;y<r.length;y++){for(x=r[y].grouping_type+"/"+r[y].grouping_type_parameter,b=new w(r[y].grouping_type,r[y].grouping_type_parameter,r[y]),t&&(t.sample_groups_info[x]=b),e.sample_groups_info[x]||(e.sample_groups_info[x]=b),_=0;_<l.length;_++)l[_].grouping_type===r[y].grouping_type&&(b.description=l[_],b.description.used=!0);if(c)for(_=0;_<c.length;_++)c[_].grouping_type===r[y].grouping_type&&(b.fragment_description=c[_],b.fragment_description.used=!0,b.is_fragment=!0)}if(t){if(c)for(y=0;y<c.length;y++)!c[y].used&&c[y].version>=2&&(x=c[y].grouping_type+"/0",b=new w(c[y].grouping_type,0),b.is_fragment=!0,t.sample_groups_info[x]||(t.sample_groups_info[x]=b))}else for(y=0;y<l.length;y++)!l[y].used&&l[y].version>=2&&(x=l[y].grouping_type+"/0",b=new w(l[y].grouping_type,0),e.sample_groups_info[x]||(e.sample_groups_info[x]=b))},S.setSampleGroupProperties=function(e,t,r,l){var c,_;t.sample_groups=[];for(c in l)if(t.sample_groups[c]={},t.sample_groups[c].grouping_type=l[c].grouping_type,t.sample_groups[c].grouping_type_parameter=l[c].grouping_type_parameter,r>=l[c].last_sample_in_run&&(l[c].last_sample_in_run<0&&(l[c].last_sample_in_run=0),l[c].entry_index++,l[c].entry_index<=l[c].sbgp.entries.length-1&&(l[c].last_sample_in_run+=l[c].sbgp.entries[l[c].entry_index].sample_count)),l[c].entry_index<=l[c].sbgp.entries.length-1?t.sample_groups[c].group_description_index=l[c].sbgp.entries[l[c].entry_index].group_description_index:t.sample_groups[c].group_description_index=-1,t.sample_groups[c].group_description_index!==0){var y;l[c].fragment_description?y=l[c].fragment_description:y=l[c].description,t.sample_groups[c].group_description_index>0?(t.sample_groups[c].group_description_index>65535?_=(t.sample_groups[c].group_description_index>>16)-1:_=t.sample_groups[c].group_description_index-1,y&&_>=0&&(t.sample_groups[c].description=y.entries[_])):y&&y.version>=2&&y.default_group_description_index>0&&(t.sample_groups[c].description=y.entries[y.default_group_description_index-1])}},S.process_sdtp=function(e,t,r){t&&(e?(t.is_leading=e.is_leading[r],t.depends_on=e.sample_depends_on[r],t.is_depended_on=e.sample_is_depended_on[r],t.has_redundancy=e.sample_has_redundancy[r]):(t.is_leading=0,t.depends_on=0,t.is_depended_on=0,t.has_redundancy=0))},S.prototype.buildSampleLists=function(){var e,t;for(e=0;e<this.moov.traks.length;e++)t=this.moov.traks[e],this.buildTrakSampleLists(t)},S.prototype.buildTrakSampleLists=function(e){var t,r,l,c,_,y,b,x,w,C,T,I,A,k,R,V,J,H,O,j,Z,be,Y,K;if(e.samples=[],e.samples_duration=0,e.samples_size=0,r=e.mdia.minf.stbl.stco||e.mdia.minf.stbl.co64,l=e.mdia.minf.stbl.stsc,c=e.mdia.minf.stbl.stsz||e.mdia.minf.stbl.stz2,_=e.mdia.minf.stbl.stts,y=e.mdia.minf.stbl.ctts,b=e.mdia.minf.stbl.stss,x=e.mdia.minf.stbl.stsd,w=e.mdia.minf.stbl.subs,I=e.mdia.minf.stbl.stdp,C=e.mdia.minf.stbl.sbgps,T=e.mdia.minf.stbl.sgpds,H=-1,O=-1,j=-1,Z=-1,be=0,Y=0,K=0,S.initSampleGroups(e,null,C,T),!(typeof c>"u")){for(t=0;t<c.sample_sizes.length;t++){var B={};B.number=t,B.track_id=e.tkhd.track_id,B.timescale=e.mdia.mdhd.timescale,B.alreadyRead=0,e.samples[t]=B,B.size=c.sample_sizes[t],e.samples_size+=B.size,t===0?(k=1,A=0,B.chunk_index=k,B.chunk_run_index=A,J=l.samples_per_chunk[A],V=0,A+1<l.first_chunk.length?R=l.first_chunk[A+1]-1:R=1/0):t<J?(B.chunk_index=k,B.chunk_run_index=A):(k++,B.chunk_index=k,V=0,k<=R||(A++,A+1<l.first_chunk.length?R=l.first_chunk[A+1]-1:R=1/0),B.chunk_run_index=A,J+=l.samples_per_chunk[A]),B.description_index=l.sample_description_index[B.chunk_run_index]-1,B.description=x.entries[B.description_index],B.offset=r.chunk_offsets[B.chunk_index-1]+V,V+=B.size,t>H&&(O++,H<0&&(H=0),H+=_.sample_counts[O]),t>0?(e.samples[t-1].duration=_.sample_deltas[O],e.samples_duration+=e.samples[t-1].duration,B.dts=e.samples[t-1].dts+e.samples[t-1].duration):B.dts=0,y?(t>=j&&(Z++,j<0&&(j=0),j+=y.sample_counts[Z]),B.cts=e.samples[t].dts+y.sample_offsets[Z]):B.cts=B.dts,b?(t==b.sample_numbers[be]-1?(B.is_sync=!0,be++):(B.is_sync=!1,B.degradation_priority=0),w&&w.entries[Y].sample_delta+K==t+1&&(B.subsamples=w.entries[Y].subsamples,K+=w.entries[Y].sample_delta,Y++)):B.is_sync=!0,S.process_sdtp(e.mdia.minf.stbl.sdtp,B,B.number),I?B.degradation_priority=I.priority[t]:B.degradation_priority=0,w&&w.entries[Y].sample_delta+K==t&&(B.subsamples=w.entries[Y].subsamples,K+=w.entries[Y].sample_delta),(C.length>0||T.length>0)&&S.setSampleGroupProperties(e,B,t,e.sample_groups_info)}t>0&&(e.samples[t-1].duration=Math.max(e.mdia.mdhd.duration-e.samples[t-1].dts,0),e.samples_duration+=e.samples[t-1].duration)}},S.prototype.updateSampleLists=function(){var e,t,r,l,c,_,y,b,x,w,C,T,I,A,k;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(x=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,x.type=="moof")for(w=x,e=0;e<w.trafs.length;e++){for(C=w.trafs[e],T=this.getTrackById(C.tfhd.track_id),I=this.getTrexById(C.tfhd.track_id),C.tfhd.flags&s.TFHD_FLAG_SAMPLE_DESC?l=C.tfhd.default_sample_description_index:l=I?I.default_sample_description_index:1,C.tfhd.flags&s.TFHD_FLAG_SAMPLE_DUR?c=C.tfhd.default_sample_duration:c=I?I.default_sample_duration:0,C.tfhd.flags&s.TFHD_FLAG_SAMPLE_SIZE?_=C.tfhd.default_sample_size:_=I?I.default_sample_size:0,C.tfhd.flags&s.TFHD_FLAG_SAMPLE_FLAGS?y=C.tfhd.default_sample_flags:y=I?I.default_sample_flags:0,C.sample_number=0,C.sbgps.length>0&&S.initSampleGroups(T,C,C.sbgps,T.mdia.minf.stbl.sgpds,C.sgpds),t=0;t<C.truns.length;t++){var R=C.truns[t];for(r=0;r<R.sample_count;r++){A={},A.moof_number=this.lastMoofIndex,A.number_in_traf=C.sample_number,C.sample_number++,A.number=T.samples.length,C.first_sample_index=T.samples.length,T.samples.push(A),A.track_id=T.tkhd.track_id,A.timescale=T.mdia.mdhd.timescale,A.description_index=l-1,A.description=T.mdia.minf.stbl.stsd.entries[A.description_index],A.size=_,R.flags&s.TRUN_FLAGS_SIZE&&(A.size=R.sample_size[r]),T.samples_size+=A.size,A.duration=c,R.flags&s.TRUN_FLAGS_DURATION&&(A.duration=R.sample_duration[r]),T.samples_duration+=A.duration,T.first_traf_merged||r>0?A.dts=T.samples[T.samples.length-2].dts+T.samples[T.samples.length-2].duration:(C.tfdt?A.dts=C.tfdt.baseMediaDecodeTime:A.dts=0,T.first_traf_merged=!0),A.cts=A.dts,R.flags&s.TRUN_FLAGS_CTS_OFFSET&&(A.cts=A.dts+R.sample_composition_time_offset[r]),k=y,R.flags&s.TRUN_FLAGS_FLAGS?k=R.sample_flags[r]:r===0&&R.flags&s.TRUN_FLAGS_FIRST_FLAG&&(k=R.first_sample_flags),A.is_sync=!(k>>16&1),A.is_leading=k>>26&3,A.depends_on=k>>24&3,A.is_depended_on=k>>22&3,A.has_redundancy=k>>20&3,A.degradation_priority=k&65535;var V=!!(C.tfhd.flags&s.TFHD_FLAG_BASE_DATA_OFFSET),J=!!(C.tfhd.flags&s.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),H=!!(R.flags&s.TRUN_FLAGS_DATA_OFFSET),O=0;V?O=C.tfhd.base_data_offset:J||t===0?O=w.start:O=b,t===0&&r===0?H?A.offset=O+R.data_offset:A.offset=O:A.offset=b,b=A.offset+A.size,(C.sbgps.length>0||C.sgpds.length>0||T.mdia.minf.stbl.sbgps.length>0||T.mdia.minf.stbl.sgpds.length>0)&&S.setSampleGroupProperties(T,A,A.number_in_traf,C.sample_groups_info)}}if(C.subs){T.has_fragment_subsamples=!0;var j=C.first_sample_index;for(t=0;t<C.subs.entries.length;t++)j+=C.subs.entries[t].sample_delta,A=T.samples[j-1],A.subsamples=C.subs.entries[t].subsamples}}}},S.prototype.getSample=function(e,t){var r,l=e.samples[t];if(!this.moov)return null;if(!l.data)l.data=new Uint8Array(l.size),l.alreadyRead=0,this.samplesDataSize+=l.size,n.debug("ISOFile","Allocating sample #"+t+" on track #"+e.tkhd.track_id+" of size "+l.size+" (total: "+this.samplesDataSize+")");else if(l.alreadyRead==l.size)return l;for(;;){var c=this.stream.findPosition(!0,l.offset+l.alreadyRead,!1);if(c>-1){r=this.stream.buffers[c];var _=r.byteLength-(l.offset+l.alreadyRead-r.fileStart);if(l.size-l.alreadyRead<=_)return n.debug("ISOFile","Getting sample #"+t+" data (alreadyRead: "+l.alreadyRead+" offset: "+(l.offset+l.alreadyRead-r.fileStart)+" read size: "+(l.size-l.alreadyRead)+" full size: "+l.size+")"),d.memcpy(l.data.buffer,l.alreadyRead,r,l.offset+l.alreadyRead-r.fileStart,l.size-l.alreadyRead),r.usedBytes+=l.size-l.alreadyRead,this.stream.logBufferLevel(),l.alreadyRead=l.size,l;if(_===0)return null;n.debug("ISOFile","Getting sample #"+t+" partial data (alreadyRead: "+l.alreadyRead+" offset: "+(l.offset+l.alreadyRead-r.fileStart)+" read size: "+_+" full size: "+l.size+")"),d.memcpy(l.data.buffer,l.alreadyRead,r,l.offset+l.alreadyRead-r.fileStart,_),l.alreadyRead+=_,r.usedBytes+=_,this.stream.logBufferLevel()}else return null}},S.prototype.releaseSample=function(e,t){var r=e.samples[t];return r.data?(this.samplesDataSize-=r.size,r.data=null,r.alreadyRead=0,r.size):0},S.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},S.prototype.getCodecs=function(){var e,t="";for(e=0;e<this.moov.traks.length;e++){var r=this.moov.traks[e];e>0&&(t+=","),t+=r.mdia.minf.stbl.stsd.entries[0].getCodec()}return t},S.prototype.getTrexById=function(e){var t;if(!this.moov||!this.moov.mvex)return null;for(t=0;t<this.moov.mvex.trexs.length;t++){var r=this.moov.mvex.trexs[t];if(r.track_id==e)return r}return null},S.prototype.getTrackById=function(e){if(this.moov===void 0)return null;for(var t=0;t<this.moov.traks.length;t++){var r=this.moov.traks[t];if(r.tkhd.track_id==e)return r}return null},S.prototype.itemsDataSize=0,S.prototype.flattenItemInfo=function(){var e=this.items,t=this.entity_groups,r,l,c,_=this.meta;if(_!=null&&_.hdlr!==void 0&&_.iinf!==void 0){for(r=0;r<_.iinf.item_infos.length;r++)c={},c.id=_.iinf.item_infos[r].item_ID,e[c.id]=c,c.ref_to=[],c.name=_.iinf.item_infos[r].item_name,_.iinf.item_infos[r].protection_index>0&&(c.protection=_.ipro.protections[_.iinf.item_infos[r].protection_index-1]),_.iinf.item_infos[r].item_type?c.type=_.iinf.item_infos[r].item_type:c.type="mime",c.content_type=_.iinf.item_infos[r].content_type,c.content_encoding=_.iinf.item_infos[r].content_encoding;if(_.grpl)for(r=0;r<_.grpl.boxes.length;r++)entity_group={},entity_group.id=_.grpl.boxes[r].group_id,entity_group.entity_ids=_.grpl.boxes[r].entity_ids,entity_group.type=_.grpl.boxes[r].type,t[entity_group.id]=entity_group;if(_.iloc)for(r=0;r<_.iloc.items.length;r++){var y=_.iloc.items[r];switch(c=e[y.item_ID],y.data_reference_index!==0&&(n.warn("Item storage with reference to other files: not supported"),c.source=_.dinf.boxes[y.data_reference_index-1]),y.construction_method){case 0:break;case 1:break;case 2:n.warn("Item storage with construction_method : not supported");break}for(c.extents=[],c.size=0,l=0;l<y.extents.length;l++)c.extents[l]={},c.extents[l].offset=y.extents[l].extent_offset+y.base_offset,y.construction_method==1&&(c.extents[l].offset+=_.idat.start+_.idat.hdr_size),c.extents[l].length=y.extents[l].extent_length,c.extents[l].alreadyRead=0,c.size+=c.extents[l].length}if(_.pitm&&(e[_.pitm.item_id].primary=!0),_.iref)for(r=0;r<_.iref.references.length;r++){var b=_.iref.references[r];for(l=0;l<b.references.length;l++)e[b.from_item_ID].ref_to.push({type:b.type,id:b.references[l]})}if(_.iprp)for(var x=0;x<_.iprp.ipmas.length;x++){var w=_.iprp.ipmas[x];for(r=0;r<w.associations.length;r++){var C=w.associations[r];if(c=e[C.id],c||(c=t[C.id]),c)for(c.properties===void 0&&(c.properties={},c.properties.boxes=[]),l=0;l<C.props.length;l++){var T=C.props[l];if(T.property_index>0&&T.property_index-1<_.iprp.ipco.boxes.length){var I=_.iprp.ipco.boxes[T.property_index-1];c.properties[I.type]=I,c.properties.boxes.push(I)}}}}}},S.prototype.getItem=function(e){var t,r;if(!this.meta)return null;if(r=this.items[e],!r.data&&r.size)r.data=new Uint8Array(r.size),r.alreadyRead=0,this.itemsDataSize+=r.size,n.debug("ISOFile","Allocating item #"+e+" of size "+r.size+" (total: "+this.itemsDataSize+")");else if(r.alreadyRead===r.size)return r;for(var l=0;l<r.extents.length;l++){var c=r.extents[l];if(c.alreadyRead!==c.length){var _=this.stream.findPosition(!0,c.offset+c.alreadyRead,!1);if(_>-1){t=this.stream.buffers[_];var y=t.byteLength-(c.offset+c.alreadyRead-t.fileStart);if(c.length-c.alreadyRead<=y)n.debug("ISOFile","Getting item #"+e+" extent #"+l+" data (alreadyRead: "+c.alreadyRead+" offset: "+(c.offset+c.alreadyRead-t.fileStart)+" read size: "+(c.length-c.alreadyRead)+" full extent size: "+c.length+" full item size: "+r.size+")"),d.memcpy(r.data.buffer,r.alreadyRead,t,c.offset+c.alreadyRead-t.fileStart,c.length-c.alreadyRead),t.usedBytes+=c.length-c.alreadyRead,this.stream.logBufferLevel(),r.alreadyRead+=c.length-c.alreadyRead,c.alreadyRead=c.length;else return n.debug("ISOFile","Getting item #"+e+" extent #"+l+" partial data (alreadyRead: "+c.alreadyRead+" offset: "+(c.offset+c.alreadyRead-t.fileStart)+" read size: "+y+" full extent size: "+c.length+" full item size: "+r.size+")"),d.memcpy(r.data.buffer,r.alreadyRead,t,c.offset+c.alreadyRead-t.fileStart,y),c.alreadyRead+=y,r.alreadyRead+=y,t.usedBytes+=y,this.stream.logBufferLevel(),null}else return null}}return r.alreadyRead===r.size?r:null},S.prototype.releaseItem=function(e){var t=this.items[e];if(t.data){this.itemsDataSize-=t.size,t.data=null,t.alreadyRead=0;for(var r=0;r<t.extents.length;r++){var l=t.extents[r];l.alreadyRead=0}return t.size}else return 0},S.prototype.processItems=function(e){for(var t in this.items){var r=this.items[t];this.getItem(r.id),e&&!r.sent&&(e(r),r.sent=!0,r.data=null)}},S.prototype.hasItem=function(e){for(var t in this.items){var r=this.items[t];if(r.name===e)return r.id}return-1},S.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},S.prototype.getPrimaryItem=function(){return!this.meta||!this.meta.pitm?null:this.getItem(this.meta.pitm.item_id)},S.prototype.itemToFragmentedTrackFile=function(e){var t=e||{},r=null;if(t.itemId?r=this.getItem(t.itemId):r=this.getPrimaryItem(),r==null)return null;var l=new S;l.discardMdatData=!1;var c={type:r.type,description_boxes:r.properties.boxes};r.properties.ispe&&(c.width=r.properties.ispe.image_width,c.height=r.properties.ispe.image_height);var _=l.addTrack(c);return _?(l.addSample(_,r.data),l):null},S.prototype.write=function(e){for(var t=0;t<this.boxes.length;t++)this.boxes[t].write(e)},S.prototype.createFragment=function(e,t,r){var l=this.getTrackById(e),c=this.getSample(l,t);if(c==null)return this.setNextSeekPositionFromSample(l.samples[t]),null;var _=r||new d;_.endianness=d.BIG_ENDIAN;var y=this.createSingleSampleMoof(c);y.write(_),y.trafs[0].truns[0].data_offset=y.size+8,n.debug("MP4Box","Adjusting data_offset with new value "+y.trafs[0].truns[0].data_offset),_.adjustUint32(y.trafs[0].truns[0].data_offset_position,y.trafs[0].truns[0].data_offset);var b=new s.mdatBox;return b.data=c.data,b.write(_),_},S.writeInitializationSegment=function(e,t,r,l){var c;n.debug("ISOFile","Generating initialization segment");var _=new d;_.endianness=d.BIG_ENDIAN,e.write(_);var y=t.add("mvex");for(r&&y.add("mehd").set("fragment_duration",r),c=0;c<t.traks.length;c++)y.add("trex").set("track_id",t.traks[c].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",l).set("default_sample_size",0).set("default_sample_flags",65536);return t.write(_),_.buffer},S.prototype.save=function(e){var t=new d;t.endianness=d.BIG_ENDIAN,this.write(t),t.save(e)},S.prototype.getBuffer=function(){var e=new d;return e.endianness=d.BIG_ENDIAN,this.write(e),e.buffer},S.prototype.initializeSegmentation=function(){var e,t,r,l;for(this.onSegment===null&&n.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),t=[],e=0;e<this.fragmentedTracks.length;e++){var c=new s.moovBox;c.mvhd=this.moov.mvhd,c.boxes.push(c.mvhd),r=this.getTrackById(this.fragmentedTracks[e].id),c.boxes.push(r),c.traks.push(r),l={},l.id=r.tkhd.track_id,l.user=this.fragmentedTracks[e].user,l.buffer=S.writeInitializationSegment(this.ftyp,c,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[e].samples.length>0?this.moov.traks[e].samples[0].duration:0),t.push(l)}return t},s.Box.prototype.printHeader=function(e){this.size+=8,this.size>h&&(this.size+=8),this.type==="uuid"&&(this.size+=16),e.log(e.indent+"size:"+this.size),e.log(e.indent+"type:"+this.type)},s.FullBox.prototype.printHeader=function(e){this.size+=4,s.Box.prototype.printHeader.call(this,e),e.log(e.indent+"version:"+this.version),e.log(e.indent+"flags:"+this.flags)},s.Box.prototype.print=function(e){this.printHeader(e)},s.ContainerBox.prototype.print=function(e){this.printHeader(e);for(var t=0;t<this.boxes.length;t++)if(this.boxes[t]){var r=e.indent;e.indent+=" ",this.boxes[t].print(e),e.indent=r}},S.prototype.print=function(e){e.indent="";for(var t=0;t<this.boxes.length;t++)this.boxes[t]&&this.boxes[t].print(e)},s.mvhdBox.prototype.print=function(e){s.FullBox.prototype.printHeader.call(this,e),e.log(e.indent+"creation_time: "+this.creation_time),e.log(e.indent+"modification_time: "+this.modification_time),e.log(e.indent+"timescale: "+this.timescale),e.log(e.indent+"duration: "+this.duration),e.log(e.indent+"rate: "+this.rate),e.log(e.indent+"volume: "+(this.volume>>8)),e.log(e.indent+"matrix: "+this.matrix.join(", ")),e.log(e.indent+"next_track_id: "+this.next_track_id)},s.tkhdBox.prototype.print=function(e){s.FullBox.prototype.printHeader.call(this,e),e.log(e.indent+"creation_time: "+this.creation_time),e.log(e.indent+"modification_time: "+this.modification_time),e.log(e.indent+"track_id: "+this.track_id),e.log(e.indent+"duration: "+this.duration),e.log(e.indent+"volume: "+(this.volume>>8)),e.log(e.indent+"matrix: "+this.matrix.join(", ")),e.log(e.indent+"layer: "+this.layer),e.log(e.indent+"alternate_group: "+this.alternate_group),e.log(e.indent+"width: "+this.width),e.log(e.indent+"height: "+this.height)};var E={};E.createFile=function(e,t){var r=e!==void 0?e:!0,l=new S(t);return l.discardMdatData=!r,l},a.createFile=E.createFile}(gt)),gt}var yt=ln(),fn=Xt(yt),mt={exports:{}},Qt;function hn(){return Qt||(Qt=1,function(a){var n={};a.exports=n,n.parse=function(o,d){for(var h=n.bin.readUshort,f=n.bin.readUint,m=0,u={},s=new Uint8Array(o),p=s.length-4;f(s,p)!=101010256;)p--;var m=p;m+=4,m+=4;var g=h(s,m);m+=2,h(s,m),m+=2;var v=f(s,m);m+=4;var U=f(s,m);m+=4,m=U;for(var S=0;S<g;S++){f(s,m),m+=4,m+=4,m+=4,m+=4,f(s,m),m+=4;var v=f(s,m);m+=4;var E=f(s,m);m+=4;var e=h(s,m),t=h(s,m+2),r=h(s,m+4);m+=6,m+=8;var l=f(s,m);m+=4,m+=e+t+r,n._readLocal(s,l,u,v,E,d)}return u},n._readLocal=function(o,d,h,f,u,s){var p=n.bin.readUshort,m=n.bin.readUint;m(o,d),d+=4,p(o,d),d+=2,p(o,d),d+=2;var g=p(o,d);d+=2,m(o,d),d+=4,m(o,d),d+=4,d+=8;var v=p(o,d);d+=2;var U=p(o,d);d+=2;var S=n.bin.readUTF8(o,d,v);if(d+=v,d+=U,s){h[S]={size:u,csize:f};return}var E=new Uint8Array(o.buffer,d);if(g==0)h[S]=new Uint8Array(E.buffer.slice(d,d+f));else if(g==8){var e=new Uint8Array(u);n.inflateRaw(E,e),h[S]=e}else throw"unknown compression method: "+g},n.inflateRaw=function(o,d){return n.F.inflate(o,d)},n.inflate=function(o,d){return o[0],o[1],n.inflateRaw(new Uint8Array(o.buffer,o.byteOffset+2,o.length-6),d)},n.deflate=function(o,d){d==null&&(d={level:6});var h=0,f=new Uint8Array(50+Math.floor(o.length*1.1));f[h]=120,f[h+1]=156,h+=2,h=n.F.deflateRaw(o,f,h,d.level);var u=n.adler(o,0,o.length);return f[h+0]=u>>>24&255,f[h+1]=u>>>16&255,f[h+2]=u>>>8&255,f[h+3]=u>>>0&255,new Uint8Array(f.buffer,0,h+4)},n.deflateRaw=function(o,d){d==null&&(d={level:6});var h=new Uint8Array(50+Math.floor(o.length*1.1)),f=n.F.deflateRaw(o,h,f,d.level);return new Uint8Array(h.buffer,0,f)},n.encode=function(o,d){d==null&&(d=!1);var h=0,f=n.bin.writeUint,u=n.bin.writeUshort,s={};for(var p in o){var m=!n._noNeed(p)&&!d,g=o[p],v=n.crc.crc(g,0,g.length);s[p]={cpr:m,usize:g.length,crc:v,file:m?n.deflateRaw(g):g}}for(var p in s)h+=s[p].file.length+30+46+2*n.bin.sizeUTF8(p);h+=22;var U=new Uint8Array(h),S=0,E=[];for(var p in s){var e=s[p];E.push(S),S=n._writeHeader(U,S,p,e,0)}var t=0,r=S;for(var p in s){var e=s[p];E.push(S),S=n._writeHeader(U,S,p,e,1,E[t++])}var l=S-r;return f(U,S,101010256),S+=4,S+=4,u(U,S,t),S+=2,u(U,S,t),S+=2,f(U,S,l),S+=4,f(U,S,r),S+=4,S+=2,U.buffer},n._noNeed=function(o){var d=o.split(".").pop().toLowerCase();return"png,jpg,jpeg,zip".indexOf(d)!=-1},n._writeHeader=function(o,d,h,f,u,s){var p=n.bin.writeUint,m=n.bin.writeUshort,g=f.file;p(o,d,u==0?67324752:33639248),d+=4,u==1&&(d+=2),m(o,d,20),d+=2,m(o,d,0),d+=2,m(o,d,f.cpr?8:0),d+=2,p(o,d,0),d+=4,p(o,d,f.crc),d+=4,p(o,d,g.length),d+=4,p(o,d,f.usize),d+=4,m(o,d,n.bin.sizeUTF8(h)),d+=2,m(o,d,0),d+=2,u==1&&(d+=2,d+=2,d+=6,p(o,d,s),d+=4);var v=n.bin.writeUTF8(o,d,h);return d+=v,u==0&&(o.set(g,d),d+=g.length),d},n.crc={table:function(){for(var o=new Uint32Array(256),d=0;d<256;d++){for(var h=d,f=0;f<8;f++)h&1?h=3988292384^h>>>1:h=h>>>1;o[d]=h}return o}(),update:function(o,d,h,f){for(var u=0;u<f;u++)o=n.crc.table[(o^d[h+u])&255]^o>>>8;return o},crc:function(o,d,h){return n.crc.update(4294967295,o,d,h)^4294967295}},n.adler=function(o,d,h){for(var f=1,u=0,s=d,p=d+h;s<p;){for(var m=Math.min(s+5552,p);s<m;)f+=o[s++],u+=f;f=f%65521,u=u%65521}return u<<16|f},n.bin={readUshort:function(o,d){return o[d]|o[d+1]<<8},writeUshort:function(o,d,h){o[d]=h&255,o[d+1]=h>>8&255},readUint:function(o,d){return o[d+3]*(256*256*256)+(o[d+2]<<16|o[d+1]<<8|o[d])},writeUint:function(o,d,h){o[d]=h&255,o[d+1]=h>>8&255,o[d+2]=h>>16&255,o[d+3]=h>>24&255},readASCII:function(o,d,h){for(var f="",u=0;u<h;u++)f+=String.fromCharCode(o[d+u]);return f},writeASCII:function(o,d,h){for(var f=0;f<h.length;f++)o[d+f]=h.charCodeAt(f)},pad:function(o){return o.length<2?"0"+o:o},readUTF8:function(o,d,h){for(var f="",u,s=0;s<h;s++)f+="%"+n.bin.pad(o[d+s].toString(16));try{u=decodeURIComponent(f)}catch{return n.bin.readASCII(o,d,h)}return u},writeUTF8:function(o,d,h){for(var f=h.length,u=0,s=0;s<f;s++){var p=h.charCodeAt(s);if(!(p&4294967168))o[d+u]=p,u++;else if(!(p&4294965248))o[d+u]=192|p>>6,o[d+u+1]=128|p>>0&63,u+=2;else if(!(p&4294901760))o[d+u]=224|p>>12,o[d+u+1]=128|p>>6&63,o[d+u+2]=128|p>>0&63,u+=3;else if(!(p&4294967295-(1<<21)+1))o[d+u]=240|p>>18,o[d+u+1]=128|p>>12&63,o[d+u+2]=128|p>>6&63,o[d+u+3]=128|p>>0&63,u+=4;else throw"e"}return u},sizeUTF8:function(o){for(var d=o.length,h=0,f=0;f<d;f++){var u=o.charCodeAt(f);if(!(u&4294967168))h++;else if(!(u&4294965248))h+=2;else if(!(u&4294901760))h+=3;else if(!(u&4294967295-(1<<21)+1))h+=4;else throw"e"}return h}},n.F={},n.F.deflateRaw=function(o,d,h,f){var u=[[0,0,0,0,0],[4,4,8,4,0],[4,5,16,8,0],[4,6,16,16,0],[4,10,16,32,0],[8,16,32,32,0],[8,16,128,128,0],[8,32,128,256,0],[32,128,258,1024,1],[32,258,258,4096,1]],s=u[f],p=n.F.U,m=n.F._goodIndex;n.F._hash;var g=n.F._putsE,v=0,U=h<<3,S=0,E=o.length;if(f==0){for(;v<E;){var e=Math.min(65535,E-v);g(d,U,v+e==E?1:0),U=n.F._copyExact(o,v,e,d,U+8),v+=e}return U>>>3}var t=p.lits,r=p.strt,l=p.prev,c=0,_=0,y=0,b=0,x=0,w=0;for(E>2&&(w=n.F._hash(o,0),r[w]=0),v=0;v<E;v++){if(x=w,v+1<E-2){w=n.F._hash(o,v+1);var C=v+1&32767;l[C]=r[w],r[w]=C}if(S<=v){(c>14e3||_>26697)&&E-v>100&&(S<v&&(t[c]=v-S,c+=2,S=v),U=n.F._writeBlock(v==E-1||S==E?1:0,t,c,b,o,y,v-y,d,U),c=_=b=0,y=v);var T=0;v<E-2&&(T=n.F._bestMatch(o,v,l,x,Math.min(s[2],E-v),s[3]));var e=T>>>16,I=T&65535;if(T!=0){var e=T>>>16,I=T&65535,A=m(e,p.of0);p.lhst[257+A]++;var k=m(I,p.df0);p.dhst[k]++,b+=p.exb[A]+p.dxb[k],t[c]=e<<23|v-S,t[c+1]=I<<16|A<<8|k,c+=2,S=v+e}else p.lhst[o[v]]++;_++}}for((y!=v||o.length==0)&&(S<v&&(t[c]=v-S,c+=2,S=v),U=n.F._writeBlock(1,t,c,b,o,y,v-y,d,U),c=0,_=0,c=_=b=0,y=v);U&7;)U++;return U>>>3},n.F._bestMatch=function(o,d,h,f,u,s){var p=d&32767,m=h[p],g=p-m+32768&32767;if(m==p||f!=n.F._hash(o,d-g))return 0;for(var v=0,U=0,S=Math.min(32767,d);g<=S&&--s!=0&&m!=p;){if(v==0||o[d+v]==o[d+v-g]){var E=n.F._howLong(o,d,g);if(E>v){if(v=E,U=g,v>=u)break;g+2<E&&(E=g+2);for(var e=0,t=0;t<E-2;t++){var r=d-g+t+32768&32767,l=h[r],c=r-l+32768&32767;c>e&&(e=c,m=r)}}}p=m,m=h[p],g+=p-m+32768&32767}return v<<16|U},n.F._howLong=function(o,d,h){if(o[d]!=o[d-h]||o[d+1]!=o[d+1-h]||o[d+2]!=o[d+2-h])return 0;var f=d,u=Math.min(o.length,d+258);for(d+=3;d<u&&o[d]==o[d-h];)d++;return d-f},n.F._hash=function(o,d){return(o[d]<<8|o[d+1])+(o[d+2]<<4)&65535},n.saved=0,n.F._writeBlock=function(o,d,h,f,u,s,p,m,g){var v=n.F.U,U=n.F._putsF,S=n.F._putsE,E,e,t,r,l,c,_,y,b;v.lhst[256]++,E=n.F.getTrees(),e=E[0],t=E[1],r=E[2],l=E[3],c=E[4],_=E[5],y=E[6],b=E[7];var x=(g+3&7?8-(g+3&7):0)+32+(p<<3),w=f+n.F.contSize(v.fltree,v.lhst)+n.F.contSize(v.fdtree,v.dhst),C=f+n.F.contSize(v.ltree,v.lhst)+n.F.contSize(v.dtree,v.dhst);C+=14+3*_+n.F.contSize(v.itree,v.ihst)+(v.ihst[16]*2+v.ihst[17]*3+v.ihst[18]*7);for(var T=0;T<286;T++)v.lhst[T]=0;for(var T=0;T<30;T++)v.dhst[T]=0;for(var T=0;T<19;T++)v.ihst[T]=0;var I=x<w&&x<C?0:w<C?1:2;if(U(m,g,o),U(m,g+1,I),g+=3,I==0){for(;g&7;)g++;g=n.F._copyExact(u,s,p,m,g)}else{var A,k;if(I==1&&(A=v.fltree,k=v.fdtree),I==2){n.F.makeCodes(v.ltree,e),n.F.revCodes(v.ltree,e),n.F.makeCodes(v.dtree,t),n.F.revCodes(v.dtree,t),n.F.makeCodes(v.itree,r),n.F.revCodes(v.itree,r),A=v.ltree,k=v.dtree,S(m,g,l-257),g+=5,S(m,g,c-1),g+=5,S(m,g,_-4),g+=4;for(var R=0;R<_;R++)S(m,g+R*3,v.itree[(v.ordr[R]<<1)+1]);g+=3*_,g=n.F._codeTiny(y,v.itree,m,g),g=n.F._codeTiny(b,v.itree,m,g)}for(var V=s,J=0;J<h;J+=2){for(var H=d[J],O=H>>>23,j=V+(H&(1<<23)-1);V<j;)g=n.F._writeLit(u[V++],A,m,g);if(O!=0){var Z=d[J+1],be=Z>>16,Y=Z>>8&255,K=Z&255;g=n.F._writeLit(257+Y,A,m,g),S(m,g,O-v.of0[Y]),g+=v.exb[Y],g=n.F._writeLit(K,k,m,g),U(m,g,be-v.df0[K]),g+=v.dxb[K],V+=O}}g=n.F._writeLit(256,A,m,g)}return g},n.F._copyExact=function(o,d,h,f,u){var s=u>>>3;return f[s]=h,f[s+1]=h>>>8,f[s+2]=255-f[s],f[s+3]=255-f[s+1],s+=4,f.set(new Uint8Array(o.buffer,d,h),s),u+(h+4<<3)},n.F.getTrees=function(){for(var o=n.F.U,d=n.F._hufTree(o.lhst,o.ltree,15),h=n.F._hufTree(o.dhst,o.dtree,15),f=[],u=n.F._lenCodes(o.ltree,f),s=[],p=n.F._lenCodes(o.dtree,s),m=0;m<f.length;m+=2)o.ihst[f[m]]++;for(var m=0;m<s.length;m+=2)o.ihst[s[m]]++;for(var g=n.F._hufTree(o.ihst,o.itree,7),v=19;v>4&&o.itree[(o.ordr[v-1]<<1)+1]==0;)v--;return[d,h,g,u,p,v,f,s]},n.F.getSecond=function(o){for(var d=[],h=0;h<o.length;h+=2)d.push(o[h+1]);return d},n.F.nonZero=function(o){for(var d="",h=0;h<o.length;h+=2)o[h+1]!=0&&(d+=(h>>1)+",");return d},n.F.contSize=function(o,d){for(var h=0,f=0;f<d.length;f++)h+=d[f]*o[(f<<1)+1];return h},n.F._codeTiny=function(o,d,h,f){for(var u=0;u<o.length;u+=2){var s=o[u],p=o[u+1];f=n.F._writeLit(s,d,h,f);var m=s==16?2:s==17?3:7;s>15&&(n.F._putsE(h,f,p,m),f+=m)}return f},n.F._lenCodes=function(o,d){for(var h=o.length;h!=2&&o[h-1]==0;)h-=2;for(var f=0;f<h;f+=2){var u=o[f+1],s=f+3<h?o[f+3]:-1,p=f+5<h?o[f+5]:-1,m=f==0?-1:o[f-1];if(u==0&&s==u&&p==u){for(var g=f+5;g+2<h&&o[g+2]==u;)g+=2;var v=Math.min(g+1-f>>>1,138);v<11?d.push(17,v-3):d.push(18,v-11),f+=v*2-2}else if(u==m&&s==u&&p==u){for(var g=f+5;g+2<h&&o[g+2]==u;)g+=2;var v=Math.min(g+1-f>>>1,6);d.push(16,v-3),f+=v*2-2}else d.push(u,0)}return h>>>1},n.F._hufTree=function(o,d,h){var f=[],u=o.length,s=d.length,p=0;for(p=0;p<s;p+=2)d[p]=0,d[p+1]=0;for(p=0;p<u;p++)o[p]!=0&&f.push({lit:p,f:o[p]});var m=f.length,g=f.slice(0);if(m==0)return 0;if(m==1){var v=f[0].lit,g=v==0?1:0;return d[(v<<1)+1]=1,d[(g<<1)+1]=1,1}f.sort(function(l,c){return l.f-c.f});var U=f[0],S=f[1],E=0,e=1,t=2;for(f[0]={lit:-1,f:U.f+S.f,l:U,r:S,d:0};e!=m-1;)E!=e&&(t==m||f[E].f<f[t].f)?U=f[E++]:U=f[t++],E!=e&&(t==m||f[E].f<f[t].f)?S=f[E++]:S=f[t++],f[e++]={lit:-1,f:U.f+S.f,l:U,r:S};var r=n.F.setDepth(f[e-1],0);for(r>h&&(n.F.restrictDepth(g,h,r),r=h),p=0;p<m;p++)d[(g[p].lit<<1)+1]=g[p].d;return r},n.F.setDepth=function(o,d){return o.lit!=-1?(o.d=d,d):Math.max(n.F.setDepth(o.l,d+1),n.F.setDepth(o.r,d+1))},n.F.restrictDepth=function(o,d,h){var f=0,u=1<<h-d,s=0;for(o.sort(function(m,g){return g.d==m.d?m.f-g.f:g.d-m.d}),f=0;f<o.length&&o[f].d>d;f++){var p=o[f].d;o[f].d=d,s+=u-(1<<h-p)}for(s=s>>>h-d;s>0;){var p=o[f].d;p<d?(o[f].d++,s-=1<<d-p-1):f++}for(;f>=0;f--)o[f].d==d&&s<0&&(o[f].d--,s++);s!=0&&console.log("debt left")},n.F._goodIndex=function(o,d){var h=0;return d[h|16]<=o&&(h|=16),d[h|8]<=o&&(h|=8),d[h|4]<=o&&(h|=4),d[h|2]<=o&&(h|=2),d[h|1]<=o&&(h|=1),h},n.F._writeLit=function(o,d,h,f){return n.F._putsF(h,f,d[o<<1]),f+d[(o<<1)+1]},n.F.inflate=function(o,d){var h=Uint8Array;if(o[0]==3&&o[1]==0)return d||new h(0);var f=n.F,u=f._bitsF,s=f._bitsE,p=f._decodeTiny,m=f.makeCodes,g=f.codes2map,v=f._get17,U=f.U,S=d==null;S&&(d=new h(o.length>>>2<<3));for(var E=0,e=0,t=0,r=0,l=0,c=0,_=0,y=0,b=0,x,w;E==0;){if(E=u(o,b,1),e=u(o,b+1,2),b+=3,e==0){b&7&&(b+=8-(b&7));var C=(b>>>3)+4,T=o[C-4]|o[C-3]<<8;S&&(d=n.F._check(d,y+T)),d.set(new h(o.buffer,o.byteOffset+C,T),y),b=C+T<<3,y+=T;continue}if(S&&(d=n.F._check(d,y+(1<<17))),e==1&&(x=U.flmap,w=U.fdmap,c=511,_=31),e==2){t=s(o,b,5)+257,r=s(o,b+5,5)+1,l=s(o,b+10,4)+4,b+=14;for(var I=0;I<38;I+=2)U.itree[I]=0,U.itree[I+1]=0;for(var A=1,I=0;I<l;I++){var k=s(o,b+I*3,3);U.itree[(U.ordr[I]<<1)+1]=k,k>A&&(A=k)}b+=3*l,m(U.itree,A),g(U.itree,A,U.imap),x=U.lmap,w=U.dmap,b=p(U.imap,(1<<A)-1,t+r,o,b,U.ttree);var R=f._copyOut(U.ttree,0,t,U.ltree);c=(1<<R)-1;var V=f._copyOut(U.ttree,t,r,U.dtree);_=(1<<V)-1,m(U.ltree,R),g(U.ltree,R,x),m(U.dtree,V),g(U.dtree,V,w)}for(;;){var J=x[v(o,b)&c];b+=J&15;var H=J>>>4;if(!(H>>>8))d[y++]=H;else{if(H==256)break;var O=y+H-254;if(H>264){var j=U.ldef[H-257];O=y+(j>>>3)+s(o,b,j&7),b+=j&7}var Z=w[v(o,b)&_];b+=Z&15;var be=Z>>>4,Y=U.ddef[be],K=(Y>>>4)+u(o,b,Y&15);for(b+=Y&15,S&&(d=n.F._check(d,y+(1<<17)));y<O;)d[y]=d[y++-K],d[y]=d[y++-K],d[y]=d[y++-K],d[y]=d[y++-K];y=O}}}return d.length==y?d:d.slice(0,y)},n.F._check=function(o,d){var h=o.length;if(d<=h)return o;var f=new Uint8Array(Math.max(h<<1,d));return f.set(o,0),f},n.F._decodeTiny=function(o,d,h,f,u,s){for(var p=n.F._bitsE,m=n.F._get17,g=0;g<h;){var v=o[m(f,u)&d];u+=v&15;var U=v>>>4;if(U<=15)s[g]=U,g++;else{var S=0,E=0;U==16?(E=3+p(f,u,2),u+=2,S=s[g-1]):U==17?(E=3+p(f,u,3),u+=3):U==18&&(E=11+p(f,u,7),u+=7);for(var e=g+E;g<e;)s[g]=S,g++}}return u},n.F._copyOut=function(o,d,h,f){for(var u=0,s=0,p=f.length>>>1;s<h;){var m=o[s+d];f[s<<1]=0,f[(s<<1)+1]=m,m>u&&(u=m),s++}for(;s<p;)f[s<<1]=0,f[(s<<1)+1]=0,s++;return u},n.F.makeCodes=function(o,d){for(var h=n.F.U,f=o.length,u,s,p,m,g,v=h.bl_count,m=0;m<=d;m++)v[m]=0;for(m=1;m<f;m+=2)v[o[m]]++;var U=h.next_code;for(u=0,v[0]=0,s=1;s<=d;s++)u=u+v[s-1]<<1,U[s]=u;for(p=0;p<f;p+=2)g=o[p+1],g!=0&&(o[p]=U[g],U[g]++)},n.F.codes2map=function(o,d,h){for(var f=o.length,u=n.F.U,s=u.rev15,p=0;p<f;p+=2)if(o[p+1]!=0)for(var m=p>>1,g=o[p+1],v=m<<4|g,U=d-g,S=o[p]<<U,E=S+(1<<U);S!=E;){var e=s[S]>>>15-d;h[e]=v,S++}},n.F.revCodes=function(o,d){for(var h=n.F.U.rev15,f=15-d,u=0;u<o.length;u+=2){var s=o[u]<<d-o[u+1];o[u]=h[s]>>>f}},n.F._putsE=function(o,d,h){h=h<<(d&7);var f=d>>>3;o[f]|=h,o[f+1]|=h>>>8},n.F._putsF=function(o,d,h){h=h<<(d&7);var f=d>>>3;o[f]|=h,o[f+1]|=h>>>8,o[f+2]|=h>>>16},n.F._bitsE=function(o,d,h){return(o[d>>>3]|o[(d>>>3)+1]<<8)>>>(d&7)&(1<<h)-1},n.F._bitsF=function(o,d,h){return(o[d>>>3]|o[(d>>>3)+1]<<8|o[(d>>>3)+2]<<16)>>>(d&7)&(1<<h)-1},n.F._get17=function(o,d){return(o[d>>>3]|o[(d>>>3)+1]<<8|o[(d>>>3)+2]<<16)>>>(d&7)},n.F._get25=function(o,d){return(o[d>>>3]|o[(d>>>3)+1]<<8|o[(d>>>3)+2]<<16|o[(d>>>3)+3]<<24)>>>(d&7)},n.F.U=function(){var o=Uint16Array,d=Uint32Array;return{next_code:new o(16),bl_count:new o(16),ordr:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],of0:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],exb:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],ldef:new o(32),df0:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],dxb:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],ddef:new d(32),flmap:new o(512),fltree:[],fdmap:new o(32),fdtree:[],lmap:new o(32768),ltree:[],ttree:[],dmap:new o(32768),dtree:[],imap:new o(512),itree:[],rev15:new o(32768),lhst:new d(286),dhst:new d(30),ihst:new d(19),lits:new d(15e3),strt:new o(65536),prev:new o(32768)}}(),function(){for(var o=n.F.U,d=32768,h=0;h<d;h++){var f=h;f=(f&2863311530)>>>1|(f&1431655765)<<1,f=(f&3435973836)>>>2|(f&858993459)<<2,f=(f&4042322160)>>>4|(f&252645135)<<4,f=(f&4278255360)>>>8|(f&16711935)<<8,o.rev15[h]=(f>>>16|f<<16)>>>17}function u(s,p,m){for(;p--!=0;)s.push(0,m)}for(var h=0;h<32;h++)o.ldef[h]=o.of0[h]<<3|o.exb[h],o.ddef[h]=o.df0[h]<<4|o.dxb[h];u(o.fltree,144,8),u(o.fltree,112,9),u(o.fltree,24,7),u(o.fltree,8,8),n.F.makeCodes(o.fltree,9),n.F.codes2map(o.fltree,9,o.flmap),n.F.revCodes(o.fltree,9),u(o.fdtree,32,5),n.F.makeCodes(o.fdtree,5),n.F.codes2map(o.fdtree,5,o.fdmap),n.F.revCodes(o.fdtree,5),u(o.itree,19,0),u(o.ltree,286,0),u(o.dtree,30,0),u(o.ttree,320,0)}()}(mt)),mt.exports}var cn=hn(),un=Xt(cn);const G=class G{constructor(n,o,d,h,f){this.copy=()=>new G(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const u=":";let s=("0"+this.h).slice(-2)+u+("0"+this.m).slice(-2)+u+("0"+this.s).slice(-2)+u+("0"+this.f).slice(-2);return s+="."+(this.field?"1":"2"),s},this.toZipTimeCodeString=()=>{const u=this.copy();return u.f=0,u.s=u.s%2===0?u.s:u.s-1,u.field=0,G.toStr(u)},this.toFrames=u=>{let s=60,p=0;Math.floor(u)==60?(s=60,p=0):Math.floor(u)==59?(s=60,p=4):Math.floor(u)==30?(s=30,p=0):Math.floor(u)==29&&(s=30,p=2);let m=this.h,g=this.m,v=this.s,U=this.f,S=this.field;const E=m*60+g,t=(E-Math.floor(E/10))*p;return m*(s*3600)+g*(s*60)+v*s+(U*2+S)-t},this.addSeconds=u=>{let s=this.copy();return s.s+=u,s.s>=60&&(s.s=0,s.m++,s.m>=60&&(s.m=0,s.h++)),s},this.addFrames=(u,s)=>{let p=this.toFrames(s);return p+=u,G.fromFrames(p,s)},this.subtractFrames=(u,s)=>this.addFrames(-u,s),this.h=n||0,this.m=o||0,this.s=d||0,this.f=h||0,this.field=f||0}static compare(n,o){return n.h!==o.h?n.h<o.h?-1:1:n.m!==o.m?n.m<o.m?-1:1:n.s!==o.s?n.s<o.s?-1:1:n.f!==o.f?n.f<o.f?-1:1:n.field!==o.field?n.field<o.field?-1:1:0}static generateTimecodeRange(n,o,d){const h=[];let f=n;for(;G.compare(f,o)<=0;)h.push(f),f=f.addSeconds(d);return h}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(n){return this.toFrames(n)*1e3/n}};G.calculateCurrentTimeCode=n=>{var v;if(!n.video||!n.clocker||!n.gameParams)throw new Error("OTTPlayer is not initialized");const o=n.video,d=n.clocker,h=d.videoFPScalculator.getFPS(),s=(o.currentTime-d.syncPoint.playerTime)%(60*60*24)*h+d.syncPoint.frame;if(s===0||h===0)throw new Error("Current frame is 0 or fps is 0");const p=G.calculateCurrentOffset(s,(v=n.gameParams)==null?void 0:v.offsets);if(p===void 0)throw new Error("Offset is undefined");let m=Math.floor(s-p);return m<0&&(m+=5178816),m>=5178816&&(m-=5178816),G.fromFrames(m,h)},G.calculateCurrentOffset=(n,o)=>{for(let d=1;d<o.length;d++)if(n<o[d].frame)return o[d-1].offset;return o[o.length-1].offset},G.fromFrames=(n,o)=>{let d=60,h=0;Math.floor(o)==60?(d=60,h=0):Math.floor(o)==59?(d=60,h=4):Math.floor(o)==30?(d=30,h=0):Math.floor(o)==29&&(d=30,h=2);let f=Math.floor(o*60),u=Math.floor(o*60*10),s=u*6,p=n,m=Math.floor(p/s);p-=m*s;let g=Math.floor(p/u);p-=g*u,p>=d*60&&(p+=h*(Math.floor((p-d*60)/f)+1));let v=Math.floor(p/(d*60));p-=v*(d*60);let U=Math.floor(p/d);p-=U*d;let S=p;v+=g*10;let E=0;return E=S%2,S=Math.floor(S/2),new G(m,v,U,S,E)},G.toStr=n=>{const o="_";let d=("0"+n.h).slice(-2)+o+("0"+n.m).slice(-2)+o+("0"+n.s).slice(-2)+o+("0"+n.f).slice(-2);return n.field&&(d+="_1"),d},G.fromStr=n=>{const d=n.split("_").map(Number);if(d.length==4){const[h,f,u,s]=d;return new G(h,f,u,s,0)}else if(d.length==5){const[h,f,u,s,p]=d;return new G(h,f,u,s,p)}else throw new Error("Invalid timecode format: "+n)},G.fromMetadata=n=>{const o=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,d=n.timecode.match(o);if(!d)throw new Error("Invalid timecode format: "+n.timecode);const[,h,f,u,s,p]=d,m=Number(h),g=Number(f),v=Number(u),U=Number(s),S=p?Number(p):0;return new G(m,g,v,U,S)};let $=G;const P={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},Q=console,fe={};Object.keys(P).forEach(a=>{fe[a]=Q[a]});const Fe="Datadog Browser SDK:",z={debug:fe.debug.bind(Q,Fe),log:fe.log.bind(Q,Fe),info:fe.info.bind(Q,Fe),warn:fe.warn.bind(Q,Fe),error:fe.error.bind(Q,Fe)},vt="https://docs.datadoghq.com",ei=`${vt}/real_user_monitoring/browser/troubleshooting`,Ye="More details:";function ti(a,n){return(...o)=>{try{return a(...o)}catch(d){z.error(n,d)}}}function Ve(a){return a!==0&&Math.random()*100<=a}function pn(a){return _n(a)&&a>=0&&a<=100}function _n(a){return typeof a=="number"}const Be=1e3,he=60*Be,ii=60*he,gn=365*(24*ii);function Le(){return new Date().getTime()}function re(){return Le()}function $e(){return performance.now()}function se(){return{relative:$e(),timeStamp:re()}}function yn(){return{relative:0,timeStamp:ni()}}function mn(a,n){return n-a}function vn(a,n){return a+n}function Sn(a){return a-ni()}let St;function ni(){return St===void 0&&(St=performance.timing.navigationStart),St}const ee=1024,ri=1024*ee,bn=/[^\\u0000-\\u007F]/;function bt(a){return bn.test(a)?window.TextEncoder!==void 0?new TextEncoder().encode(a).length:new Blob([a]).size:a.length}function xn(a){return{...a}}function si(a,n){return Object.keys(a).some(o=>a[o]===n)}function ke(a){return Object.keys(a).length===0}function oe(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let a=_dd_temp_;return delete Object.prototype._dd_temp_,typeof a!="object"&&(typeof self=="object"?a=self:typeof window=="object"?a=window:a={}),a}function xe(a,n){const o=oe();let d;return o.Zone&&typeof o.Zone.__symbol__=="function"&&(d=a[o.Zone.__symbol__(n)]),d||(d=a[n]),d}let je,oi=!1;function Un(a){je=a}function En(a){oi=a}function wn(a,n,o){const d=o.value;o.value=function(...h){return(je?L(d):d).apply(this,h)}}function L(a){return function(){return Re(a,this,arguments)}}function Re(a,n,o){try{return a.apply(n,o)}catch(d){Cn(d)}}function Cn(a){if(xt(a),je)try{je(a)}catch(n){xt(n)}}function xt(...a){oi&&z.error("[MONITOR]",...a)}function De(a,n){return xe(oe(),"setTimeout")(L(a),n)}function ai(a){xe(oe(),"clearTimeout")(a)}function Ut(a,n){return xe(oe(),"setInterval")(L(a),n)}function di(a){xe(oe(),"clearInterval")(a)}class M{constructor(n){this.onFirstSubscribe=n,this.observers=[]}subscribe(n){return this.observers.push(n),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(o=>n!==o),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(n){this.observers.forEach(o=>o(n))}}function li(...a){return new M(n=>{const o=a.map(d=>d.subscribe(h=>n.notify(h)));return()=>o.forEach(d=>d.unsubscribe())})}function fi(a,n,o){let d=!1,h,f;return{throttled:(...u)=>{if(d){h=u;return}a(...u),d=!0,f=De(()=>{h&&a(...h),d=!1,h=void 0},n)},cancel:()=>{ai(f),d=!1,h=void 0}}}function ae(){}function de(a){return a?(parseInt(a,10)^Math.random()*16>>parseInt(a,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,de)}const Ke=/([\\w-]+)\\s*=\\s*([^;]+)/g;function Tn(a,n){for(Ke.lastIndex=0;;){const o=Ke.exec(a);if(o){if(o[1]===n)return o[2]}else break}}function An(a){const n=new Map;for(Ke.lastIndex=0;;){const o=Ke.exec(a);if(o)n.set(o[1],o[2]);else break}return n}function In(a,n,o=""){const d=a.charCodeAt(n-1),f=d>=55296&&d<=56319?n+1:n;return a.length<=f?a:`${a.slice(0,f)}${o}`}function Fn(){return Bn()===0}let qe;function Bn(){return qe??(qe=Ln())}function Ln(a=window){var n;const o=a.navigator.userAgent;return a.chrome||/HeadlessChrome/.test(o)?0:((n=a.navigator.vendor)===null||n===void 0?void 0:n.indexOf("Apple"))===0||/safari/i.test(o)&&!/chrome|android/i.test(o)?1:2}function Pe(a,n,o=0,d){const h=new Date;h.setTime(h.getTime()+o);const f=`expires=${h.toUTCString()}`,u=d&&d.crossSite?"none":"strict",s=d&&d.domain?`;domain=${d.domain}`:"",p=d&&d.secure?";secure":"",m=d&&d.partitioned?";partitioned":"";document.cookie=`${a}=${n};${f};path=/;samesite=${u}${s}${p}${m}`}function Et(a){return Tn(document.cookie,a)}let wt;function ce(a){return wt||(wt=An(document.cookie)),wt.get(a)}function hi(a,n){Pe(a,"",0,n)}function kn(a){if(document.cookie===void 0||document.cookie===null)return!1;try{const n=`dd_cookie_test_${de()}`,o="test";Pe(n,o,he,a);const d=Et(n)===o;return hi(n,a),d}catch(n){return z.error(n),!1}}let Ct;function Rn(){if(Ct===void 0){const a=`dd_site_test_${de()}`,n="test",o=window.location.hostname.split(".");let d=o.pop();for(;o.length&&!Et(a);)d=`${o.pop()}.${d}`,Pe(a,n,Be,{domain:d});hi(a,{domain:d}),Ct=d}return Ct}const Ue="_dd_s";function We(a){return Object.values(a)}function Dn(a){return Object.entries(a)}const Tt=4*ii,ci=15*he,Pn=gn,ze={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},ui=/^([a-zA-Z]+)=([a-z0-9-]+)$/,At="&";function zn(a){return!!a&&(a.indexOf(At)!==-1||ui.test(a))}const On="1";function ue(a,n){const o={isExpired:On};return n.trackAnonymousUser&&(a!=null&&a.anonymousId?o.anonymousId=a==null?void 0:a.anonymousId:o.anonymousId=de()),o}function Je(a){return ke(a)}function pi(a){return!Je(a)}function Xe(a){return a.isExpired!==void 0||!Mn(a)}function Mn(a){return(a.created===void 0||Le()-Number(a.created)<Tt)&&(a.expire===void 0||Le()<Number(a.expire))}function _i(a){a.expire=String(Le()+ci)}function It(a){return Dn(a).map(([n,o])=>n==="anonymousId"?`aid=${o}`:`${n}=${o}`).join(At)}function gi(a){const n={};return zn(a)&&a.split(At).forEach(o=>{const d=ui.exec(o);if(d!==null){const[,h,f]=d;h==="aid"?n.anonymousId=f:n[h]=f}}),n}const Nn="_dd",Gn="_dd_r",Hn="_dd_l",Yn="rum",Vn="logs";function $n(a){if(!ce(Ue)){const o=ce(Nn),d=ce(Gn),h=ce(Hn),f={};o&&(f.id=o),h&&/^[01]$/.test(h)&&(f[Vn]=h),d&&/^[012]$/.test(d)&&(f[Yn]=d),pi(f)&&(_i(f),a.persistSession(f))}}function yi(a){const n=Jn(a);return kn(n)?{type:ze.COOKIE,cookieOptions:n}:void 0}function jn(a,n){const o={isLockEnabled:Fn(),persistSession:Kn(n),retrieveSession:Wn,expireSession:d=>qn(n,d,a)};return $n(o),o}function Kn(a){return n=>{Pe(Ue,It(n),ci,a)}}function qn(a,n,o){const d=ue(n,o);Pe(Ue,It(d),o.trackAnonymousUser?Pn:Tt,a)}function Wn(){const a=Et(Ue);return gi(a)}function Jn(a){const n={};return n.secure=!!a.useSecureSessionCookie||!!a.usePartitionedCrossSiteSessionCookie,n.crossSite=!!a.usePartitionedCrossSiteSessionCookie,n.partitioned=!!a.usePartitionedCrossSiteSessionCookie,a.trackSessionAcrossSubdomains&&(n.domain=Rn()),n}const Xn="_dd_test_";function mi(){try{const a=de(),n=`${Xn}${a}`;localStorage.setItem(n,a);const o=localStorage.getItem(n);return localStorage.removeItem(n),a===o?{type:ze.LOCAL_STORAGE}:void 0}catch{return}}function Zn(a){return{isLockEnabled:!1,persistSession:vi,retrieveSession:Qn,expireSession:n=>er(n,a)}}function vi(a){localStorage.setItem(Ue,It(a))}function Qn(){const a=localStorage.getItem(Ue);return gi(a)}function er(a,n){vi(ue(a,n))}const tr=10,ir=100,Si=[];let Ze;function pe(a,n,o=0){var d;const{isLockEnabled:h,persistSession:f,expireSession:u}=n,s=U=>f({...U,lock:m}),p=()=>{const U=n.retrieveSession(),S=U.lock;return U.lock&&delete U.lock,{session:U,lock:S}};if(Ze||(Ze=a),a!==Ze){Si.push(a);return}if(h&&o>=ir){bi(n);return}let m,g=p();if(h){if(g.lock){Qe(a,n,o);return}if(m=de(),s(g.session),g=p(),g.lock!==m){Qe(a,n,o);return}}let v=a.process(g.session);if(h&&(g=p(),g.lock!==m)){Qe(a,n,o);return}if(v&&(Xe(v)?u(v):(_i(v),h?s(v):f(v))),h&&!(v&&Xe(v))){if(g=p(),g.lock!==m){Qe(a,n,o);return}f(g.session),v=g.session}(d=a.after)===null||d===void 0||d.call(a,v||g.session),bi(n)}function Qe(a,n,o){De(()=>{pe(a,n,o+1)},tr)}function bi(a){Ze=void 0;const n=Si.shift();n&&pe(n,a)}const xi=Be;function nr(a){switch(a.sessionPersistence){case ze.COOKIE:return yi(a);case ze.LOCAL_STORAGE:return mi();case void 0:{let n=yi(a);return!n&&a.allowFallbackToLocalStorage&&(n=mi()),n}default:z.error(`Invalid session persistence \'${String(a.sessionPersistence)}\'`)}}function rr(a,n,o,d){const h=new M,f=new M,u=new M,s=a.type===ze.COOKIE?jn(n,a.cookieOptions):Zn(n),{expireSession:p}=s,m=Ut(E,xi);let g;t();const{throttled:v,cancel:U}=fi(()=>{pe({process:x=>{if(Je(x))return;const w=e(x);return r(w),w},after:x=>{pi(x)&&!l()&&y(x),g=x}},s)},xi);function S(){pe({process:x=>l()?e(x):void 0},s)}function E(){pe({process:x=>Xe(x)?ue(x,n):void 0,after:e},s)}function e(x){return Xe(x)&&(x=ue(x,n)),l()&&(c(x)?_():(u.notify({previousState:g,newState:x}),g=x)),x}function t(){pe({process:x=>{if(Je(x))return ue(x,n)},after:x=>{g=x}},s)}function r(x){if(Je(x))return!1;const{trackingType:w,isTracked:C}=d(x[o]);x[o]=w,delete x.isExpired,C&&!x.id&&(x.id=de(),x.created=String(Le()))}function l(){return g[o]!==void 0}function c(x){return g.id!==x.id||g[o]!==x[o]}function _(){g=ue(g,n),f.notify()}function y(x){g=x,h.notify()}function b(x){pe({process:w=>({...w,...x}),after:e},s)}return{expandOrRenewSession:v,expandSession:S,getSession:()=>g,renewObservable:h,expireObservable:f,sessionStateUpdateObservable:u,restartSession:t,expire:()=>{U(),p(g),e(ue(g,n))},stop:()=>{di(m)},updateSessionState:b}}const Ft={GRANTED:"granted",NOT_GRANTED:"not-granted"};function sr(a){const n=new M;return{tryToInit(o){a||(a=o)},update(o){a=o,n.notify()},isGranted(){return a===Ft.GRANTED},observable:n}}function _e(a,n,o){if(typeof a!="object"||a===null)return JSON.stringify(a);const d=Ee(Object.prototype),h=Ee(Array.prototype),f=Ee(Object.getPrototypeOf(a)),u=Ee(a);try{return JSON.stringify(a,n,o)}catch{return"<error: unable to serialize object>"}finally{d(),h(),f(),u()}}function Ee(a){const n=a,o=n.toJSON;return o?(delete n.toJSON,()=>{n.toJSON=o}):ae}function Bt(a){return or(a,location.href).href}function or(a,n){const o=ar();if(o)try{return n!==void 0?new o(a,n):new o(a)}catch(f){throw new Error(`Failed to construct URL: ${String(f)} ${_e({url:a,base:n})}`)}if(n===void 0&&!/:/.test(a))throw new Error(`Invalid URL: \'${a}\'`);let d=document;const h=d.createElement("a");if(n!==void 0){d=document.implementation.createHTMLDocument("");const f=d.createElement("base");f.href=n,d.head.appendChild(f),d.body.appendChild(h)}return h.href=a,h}const Ui=URL;let et;function ar(){if(et===void 0)try{et=new Ui("http://test/path").href==="http://test/path"}catch{et=!1}return et?Ui:void 0}const dr="datad0g.com",lr="dd0g-gov.com",we="datadoghq.com",fr="ddog-gov.com",hr="pci.browser-intake-datadoghq.com",cr=["ddsource","ddtags"];function Oe(a,n,o){const d=ur(a,n);return{build(h,f){const u=_r(a,n,o,h,f);return d(u)},urlPrefix:d(""),trackType:n}}function ur(a,n){const o=`/api/v2/${n}`,d=a.proxy;if(typeof d=="string"){const f=Bt(d);return u=>`${f}?ddforward=${encodeURIComponent(`${o}?${u}`)}`}if(typeof d=="function")return f=>d({path:o,parameters:f});const h=pr(n,a);return f=>`https://${h}${o}?${f}`}function pr(a,n){const{site:o=we,internalAnalyticsSubdomain:d}=n;if(a==="logs"&&n.usePciIntake&&o===we)return hr;if(d&&o===we)return`${d}.${we}`;if(o===lr)return`http-intake.logs.${o}`;const h=o.split("."),f=h.pop();return`browser-intake-${h.join("-")}.${f}`}function _r({clientToken:a,internalAnalyticsSubdomain:n},o,d,h,{retry:f,encoding:u}){const s=["sdk_version:6.5.0",`api:${h}`].concat(d);f&&s.push(`retry_count:${f.count}`,`retry_after:${f.lastFailureStatus}`);const p=["ddsource=browser",`ddtags=${encodeURIComponent(s.join(","))}`,`dd-api-key=${a}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${de()}`];return u&&p.push(`dd-evp-encoding=${u}`),o==="rum"&&p.push(`batch_time=${re()}`),n&&p.reverse(),p.join("&")}const gr=200;function yr(a){const{env:n,service:o,version:d,datacenter:h}=a,f=[];return n&&f.push(tt("env",n)),o&&f.push(tt("service",o)),d&&f.push(tt("version",d)),h&&f.push(tt("datacenter",h)),f}function tt(a,n){const o=gr-a.length-1;(n.length>o||mr(n))&&z.warn(`${a} value doesn\'t meet tag requirements and will be sanitized. ${Ye} ${vt}/getting_started/tagging/#defining-tags`);const d=n.replace(/,/g,"_");return`${a}:${d}`}function mr(a){return vr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(a):!1}function vr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function Sr(a){const n=a.site||we,o=yr(a),d=br(a,o);return{replica:xr(a,o),site:n,...d}}function br(a,n){return{logsEndpointBuilder:Oe(a,"logs",n),rumEndpointBuilder:Oe(a,"rum",n),sessionReplayEndpointBuilder:Oe(a,"replay",n)}}function xr(a,n){if(!a.replica)return;const o={...a,site:we,clientToken:a.replica.clientToken},d={logsEndpointBuilder:Oe(o,"logs",n),rumEndpointBuilder:Oe(o,"rum",n)};return{applicationId:a.replica.applicationId,...d}}function Ur(a){return cr.every(n=>a.includes(n))}function Lt(a,n){return a!=null&&typeof a!="string"?(z.error(`${n} must be defined as a string`),!1):!0}function Er(a){return a&&typeof a=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(a)?(z.error(`Site should be a valid Datadog site. ${Ye} ${vt}/getting_started/site/.`),!1):!0}function it(a,n){return a!==void 0&&!pn(a)?(z.error(`${n} Sample Rate should be a number between 0 and 100`),!1):!0}function wr(a){var n,o,d,h,f,u;if(!a||!a.clientToken){z.error("Client Token is not configured, we will not send any data.");return}if(!(!Er(a.site)||!it(a.sessionSampleRate,"Session")||!it(a.telemetrySampleRate,"Telemetry")||!it(a.telemetryConfigurationSampleRate,"Telemetry Configuration")||!it(a.telemetryUsageSampleRate,"Telemetry Usage")||!Lt(a.version,"Version")||!Lt(a.env,"Env")||!Lt(a.service,"Service"))){if(a.trackingConsent!==void 0&&!si(Ft,a.trackingConsent)){z.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:a.beforeSend&&ti(a.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:nr(a),sessionSampleRate:(n=a.sessionSampleRate)!==null&&n!==void 0?n:100,telemetrySampleRate:(o=a.telemetrySampleRate)!==null&&o!==void 0?o:20,telemetryConfigurationSampleRate:(d=a.telemetryConfigurationSampleRate)!==null&&d!==void 0?d:5,telemetryUsageSampleRate:(h=a.telemetryUsageSampleRate)!==null&&h!==void 0?h:5,service:a.service||void 0,silentMultipleInit:!!a.silentMultipleInit,allowUntrustedEvents:!!a.allowUntrustedEvents,trackingConsent:(f=a.trackingConsent)!==null&&f!==void 0?f:Ft.GRANTED,trackAnonymousUser:(u=a.trackAnonymousUser)!==null&&u!==void 0?u:!0,storeContextsAcrossPages:!!a.storeContextsAcrossPages,batchBytesLimit:16*ee,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*Be,batchMessagesLimit:50,messageBytesLimit:256*ee,...Sr(a)}}}function Cr(a){return{session_sample_rate:a.sessionSampleRate,telemetry_sample_rate:a.telemetrySampleRate,telemetry_configuration_sample_rate:a.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:a.telemetryUsageSampleRate,use_before_send:!!a.beforeSend,use_partitioned_cross_site_session_cookie:a.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:a.useSecureSessionCookie,use_proxy:!!a.proxy,silent_multiple_init:a.silentMultipleInit,track_session_across_subdomains:a.trackSessionAcrossSubdomains,track_anonymous_user:a.trackAnonymousUser,session_persistence:a.sessionPersistence,allow_fallback_to_local_storage:!!a.allowFallbackToLocalStorage,store_contexts_across_pages:!!a.storeContextsAcrossPages,allow_untrusted_events:!!a.allowUntrustedEvents,tracking_consent:a.trackingConsent}}var kt;(function(a){a.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",a.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(kt||(kt={}));const Ei=new Set;function Tr(a){Array.isArray(a)&&Ar(a.filter(n=>si(kt,n)))}function Ar(a){a.forEach(n=>{Ei.add(n)})}function Ir(){return Ei}const Me="?";function te(a){const n=[];let o=Rt(a,"stack");const d=String(a);return o&&o.startsWith(d)&&(o=o.slice(d.length)),o&&o.split(`\n`).forEach(h=>{const f=Lr(h)||Rr(h)||Pr(h)||Mr(h);f&&(!f.func&&f.line&&(f.func=Me),n.push(f))}),{message:Rt(a,"message"),name:Rt(a,"name"),stack:n}}const wi="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",Ce="(?::(\\\\d+))",Fr=new RegExp(`^\\\\s*at (.*?) ?\\\\(${wi}${Ce}?${Ce}?\\\\)?\\\\s*$`,"i"),Br=new RegExp(`\\\\((\\\\S*)${Ce}${Ce}\\\\)`);function Lr(a){const n=Fr.exec(a);if(!n)return;const o=n[2]&&n[2].indexOf("native")===0,d=n[2]&&n[2].indexOf("eval")===0,h=Br.exec(n[2]);return d&&h&&(n[2]=h[1],n[3]=h[2],n[4]=h[3]),{args:o?[n[2]]:[],column:n[4]?+n[4]:void 0,func:n[1]||Me,line:n[3]?+n[3]:void 0,url:o?void 0:n[2]}}const kr=new RegExp(`^\\\\s*at ?${wi}${Ce}?${Ce}??\\\\s*$`,"i");function Rr(a){const n=kr.exec(a);if(n)return{args:[],column:n[3]?+n[3]:void 0,func:Me,line:n[2]?+n[2]:void 0,url:n[1]}}const Dr=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function Pr(a){const n=Dr.exec(a);if(n)return{args:[],column:n[4]?+n[4]:void 0,func:n[1]||Me,line:+n[3],url:n[2]}}const zr=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,Or=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function Mr(a){const n=zr.exec(a);if(!n)return;const o=n[3]&&n[3].indexOf(" > eval")>-1,d=Or.exec(n[3]);return o&&d&&(n[3]=d[1],n[4]=d[2],n[5]=void 0),{args:n[2]?n[2].split(","):[],column:n[5]?+n[5]:void 0,func:n[1]||Me,line:n[4]?+n[4]:void 0,url:n[3]}}function Rt(a,n){if(typeof a!="object"||!a||!(n in a))return;const o=a[n];return typeof o=="string"?o:void 0}function Nr(a,n,o,d){const h=[{url:n,column:d,line:o}],{name:f,message:u}=Hr(a);return{name:f,message:u,stack:h}}const Gr=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function Hr(a){let n,o;return{}.toString.call(a)==="[object String]"&&([,n,o]=Gr.exec(a)),{name:n,message:o}}function nt(a){const o=new Error(a);o.name="HandlingStack";let d;return Re(()=>{const h=te(o);h.stack=h.stack.slice(2),d=ge(h)}),d}function ge(a){let n=Ci(a);return a.stack.forEach(o=>{const d=o.func==="?"?"<anonymous>":o.func,h=o.args&&o.args.length>0?`(${o.args.join(", ")})`:"",f=o.line?`:${o.line}`:"",u=o.line&&o.column?`:${o.column}`:"";n+=`\n at ${d}${h} @ ${o.url}${f}${u}`}),n}function Ci(a){return`${a.name||"Error"}: ${a.message}`}function ye(a,n,o,{computeHandlingStack:d}={}){let h=a[n];if(typeof h!="function")if(n in a&&n.startsWith("on"))h=ae;else return{stop:ae};let f=!1;const u=function(){if(f)return h.apply(this,arguments);const s=Array.from(arguments);let p;Re(o,null,[{target:this,parameters:s,onPostCall:g=>{p=g},handlingStack:d?nt("instrumented method"):void 0}]);const m=h.apply(this,s);return p&&Re(p,null,[m]),m};return a[n]=u,{stop:()=>{f=!0,a[n]===u&&(a[n]=h)}}}const Yr=220*ee,Vr="$",$r=3;function ie(a,n=Yr){const o=Ee(Object.prototype),d=Ee(Array.prototype),h=[],f=new WeakMap,u=Dt(a,Vr,void 0,h,f),s=JSON.stringify(u);let p=s?s.length:0;if(p>n){zt(n,"discarded",a);return}for(;h.length>0&&p<n;){const m=h.shift();let g=0;if(Array.isArray(m.source))for(let v=0;v<m.source.length;v++){const U=Dt(m.source[v],m.path,v,h,f);if(U!==void 0?p+=JSON.stringify(U).length:p+=4,p+=g,g=1,p>n){zt(n,"truncated",a);break}m.target[v]=U}else for(const v in m.source)if(Object.prototype.hasOwnProperty.call(m.source,v)){const U=Dt(m.source[v],m.path,v,h,f);if(U!==void 0&&(p+=JSON.stringify(U).length+g+v.length+$r,g=1),p>n){zt(n,"truncated",a);break}m.target[v]=U}}return o(),d(),u}function Dt(a,n,o,d,h){const f=qr(a);if(!f||typeof f!="object")return jr(f);const u=Pt(f);if(u!=="[Object]"&&u!=="[Array]"&&u!=="[Error]")return u;const s=a;if(h.has(s))return`[Reference seen at ${h.get(s)}]`;const p=o!==void 0?`${n}.${o}`:n,m=Array.isArray(f)?[]:{};return h.set(s,p),d.push({source:f,target:m,path:p}),m}function jr(a){return typeof a=="bigint"?`[BigInt] ${a.toString()}`:typeof a=="function"?`[Function] ${a.name||"unknown"}`:typeof a=="symbol"?`[Symbol] ${a.description||a.toString()}`:a}function Pt(a){try{if(a instanceof Event)return Kr(a);if(a instanceof RegExp)return`[RegExp] ${a.toString()}`;const o=Object.prototype.toString.call(a).match(/\\[object (.*)\\]/);if(o&&o[1])return`[${o[1]}]`}catch{}return"[Unserializable]"}function Kr(a){return{type:a.type,isTrusted:a.isTrusted,currentTarget:a.currentTarget?Pt(a.currentTarget):null,target:a.target?Pt(a.target):null}}function qr(a){const n=a;if(n&&typeof n.toJSON=="function")try{return n.toJSON()}catch{}return a}function zt(a,n,o){z.warn(`The data provided has been ${n} as it is over the limit of ${a} characters:`,o)}const Ti="No stack, consider using an instance of Error";function Ai({stackTrace:a,originalError:n,handlingStack:o,componentStack:d,startClocks:h,nonErrorPrefix:f,source:u,handling:s}){const p=le(n),m=Wr(a,p,f,n),g=Jr(p,a)?ge(a):Ti,v=p?Bi(n,u):void 0,U=a?a.name:void 0,S=Ii(n),E=Fi(n);return{startClocks:h,source:u,handling:s,handlingStack:o,componentStack:d,originalError:n,type:U,message:m,stack:g,causes:v,fingerprint:S,context:E}}function Wr(a,n,o,d){return a!=null&&a.message&&(a!=null&&a.name)?a.message:n?"Empty message":`${o} ${_e(ie(d))}`}function Jr(a,n){return n===void 0?!1:a?!0:n.stack.length>0&&(n.stack.length>1||n.stack[0].url!==void 0)}function Ii(a){return le(a)&&"dd_fingerprint"in a?String(a.dd_fingerprint):void 0}function Fi(a){if(a!==null&&typeof a=="object"&&"dd_context"in a)return a.dd_context}function Xr(a){var n;return(n=/@ (.+)/.exec(a))===null||n===void 0?void 0:n[1]}function le(a){return a instanceof Error||Object.prototype.toString.call(a)==="[object Error]"}function Bi(a,n){let o=a;const d=[];for(;le(o==null?void 0:o.cause)&&d.length<10;){const h=te(o.cause);d.push({message:o.cause.message,source:n,type:h==null?void 0:h.name,stack:ge(h)}),o=o.cause}return d.length?d:void 0}const q={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function Zr(a){const n=(h,f)=>{const u=Ai({stackTrace:h,originalError:f,startClocks:se(),nonErrorPrefix:"Uncaught",source:q.SOURCE,handling:"unhandled"});a.notify(u)},{stop:o}=Qr(n),{stop:d}=es(n);return{stop:()=>{o(),d()}}}function Qr(a){return ye(window,"onerror",({parameters:[n,o,d,h,f]})=>{let u;le(f)?u=te(f):u=Nr(n,o,d,h),a(u,f??n)})}function es(a){return ye(window,"onunhandledrejection",({parameters:[n]})=>{const o=n.reason||"Empty reason",d=te(o);a(d,o)})}function ts(a){const n={version:"6.5.0",onReady(o){o()},...a};return Object.defineProperty(n,"_setDebug",{get(){return En},enumerable:!1}),n}function is(a,n,o){const d=a[n];d&&!d.q&&d.version&&z.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),a[n]=o,d&&d.q&&d.q.forEach(h=>ti(h,"onReady callback threw an error:")())}function Li(a,n){n.silentMultipleInit||z.error(`${a} is already initialized.`)}function me(a,n,o,d,h){return Ot(a,n,[o],d,h)}function Ot(a,n,o,d,{once:h,capture:f,passive:u}={}){const s=L(U=>{!U.isTrusted&&!U.__ddIsTrusted&&!a.allowUntrustedEvents||(h&&v(),d(U))}),p=u?{capture:f,passive:u}:f,m=window.EventTarget&&n instanceof EventTarget?window.EventTarget.prototype:n,g=xe(m,"addEventListener");o.forEach(U=>g.call(n,U,s,p));function v(){const U=xe(m,"removeEventListener");o.forEach(S=>U.call(n,S,s,p))}return{stop:v}}const rt={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function ns(a,n){const o=[];n.includes(rt.cspViolation)&&o.push(ss(a));const d=n.filter(h=>h!==rt.cspViolation);return d.length&&o.push(rs(d)),li(...o)}function rs(a){return new M(n=>{if(!window.ReportingObserver)return;const o=L((h,f)=>h.forEach(u=>n.notify(os(u)))),d=new window.ReportingObserver(o,{types:a,buffered:!0});return d.observe(),()=>{d.disconnect()}})}function ss(a){return new M(n=>{const{stop:o}=me(a,document,"securitypolicyviolation",d=>{n.notify(as(d))});return o})}function os(a){const{type:n,body:o}=a;return ki({type:o.id,message:`${n}: ${o.message}`,originalError:a,stack:Ri(o.id,o.message,o.sourceFile,o.lineNumber,o.columnNumber)})}function as(a){const n=`\'${a.blockedURI}\' blocked by \'${a.effectiveDirective}\' directive`;return ki({type:a.effectiveDirective,message:`${rt.cspViolation}: ${n}`,originalError:a,csp:{disposition:a.disposition},stack:Ri(a.effectiveDirective,a.originalPolicy?`${n} of the policy "${In(a.originalPolicy,100,"...")}"`:"no policy",a.sourceFile,a.lineNumber,a.columnNumber)})}function ki(a){return{startClocks:se(),source:q.REPORT,handling:"unhandled",...a}}function Ri(a,n,o,d,h){return o?ge({name:a,message:n,stack:[{func:"?",url:o,line:d??void 0,column:h??void 0}]}):void 0}function Di(a,n){const o=window.__ddBrowserSdkExtensionCallback;o&&o({type:a,payload:n})}function Pi(a){return a===null?"null":Array.isArray(a)?"array":typeof a}function st(a,n,o=ds()){if(n===void 0)return a;if(typeof n!="object"||n===null)return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp){const h=n.flags||[n.global?"g":"",n.ignoreCase?"i":"",n.multiline?"m":"",n.sticky?"y":"",n.unicode?"u":""].join("");return new RegExp(n.source,h)}if(o.hasAlreadyBeenSeen(n))return;if(Array.isArray(n)){const h=Array.isArray(a)?a:[];for(let f=0;f<n.length;++f)h[f]=st(h[f],n[f],o);return h}const d=Pi(a)==="object"?a:{};for(const h in n)Object.prototype.hasOwnProperty.call(n,h)&&(d[h]=st(d[h],n[h],o));return d}function zi(a){return st(void 0,a)}function Te(...a){let n;for(const o of a)o!=null&&(n=st(n,o));return n}function ds(){if(typeof WeakSet<"u"){const n=new WeakSet;return{hasAlreadyBeenSeen(o){const d=n.has(o);return d||n.add(o),d}}}const a=[];return{hasAlreadyBeenSeen(n){const o=a.indexOf(n)>=0;return o||a.push(n),o}}}function ls(){var a;const n=window.navigator;return{status:n.onLine?"connected":"not_connected",interfaces:n.connection&&n.connection.type?[n.connection.type]:void 0,effective_type:(a=n.connection)===null||a===void 0?void 0:a.effectiveType}}function fs(a){const n=new Set;return a.forEach(o=>n.add(o)),Array.from(n)}function Oi(a,n){const o=a.indexOf(n);o>=0&&a.splice(o,1)}const hs=500;function Mi(){const a=[];return{add:h=>{a.push(h)>hs&&a.splice(0,1)},remove:h=>{Oi(a,h)},drain:h=>{a.forEach(f=>f(h)),a.length=0}}}const ve={log:"log",configuration:"configuration",usage:"usage"},cs=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],us=[fr];let Ni=Mi(),Ae=a=>{Ni.add(()=>Ae(a))};function ps(a,n){let o;const d=new M,h=new Set,f=!us.includes(n.site)&&Ve(n.telemetrySampleRate),u={[ve.log]:f,[ve.configuration]:f&&Ve(n.telemetryConfigurationSampleRate),[ve.usage]:f&&Ve(n.telemetryUsageSampleRate)},s=_s();Ae=m=>{const g=_e(m);if(u[m.type]&&h.size<n.maxTelemetryEventsPerPage&&!h.has(g)){const v=p(a,m,s);d.notify(v),Di("telemetry",v),h.add(g)}},Un(Hi);function p(m,g,v){return Te({type:"telemetry",date:re(),service:m,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:Te(g,{runtime_env:v,connectivity:ls(),sdk_setup:"npm"}),experimental_features:Array.from(Ir())},o!==void 0?o():{})}return{setContextProvider:m=>{o=m},observable:d,enabled:f}}function _s(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function gs(){Ni.drain()}function ys(a){return a.site===dr}function Gi(a,n){xt(P.debug,a,n),Ae({type:ve.log,message:a,status:"debug",...n})}function Hi(a,n){Ae({type:ve.log,status:"error",...Ss(a),...n})}function ms(a){Ae({type:ve.configuration,configuration:a})}function vs(a){Ae({type:ve.usage,usage:a})}function Ss(a){if(le(a)){const n=te(a);return{error:{kind:n.name,stack:ge(bs(n))},message:n.message}}return{error:{stack:Ti},message:`Uncaught ${_e(a)}`}}function bs(a){return a.stack=a.stack.filter(n=>!n.url||cs.some(o=>n.url.startsWith(o))),a}const Ne=1/0,xs=he;let Ge=null;const ot=new Set;function Us(){ot.forEach(a=>a())}function Es({expireDelay:a,maxEntries:n}){let o=[];const d=[];Ge||(Ge=Ut(()=>Us(),xs));const h=()=>{const S=$e()-a;for(;o.length>0&&o[o.length-1].endTime<S;){const E=o.pop();E&&d.push(E.startTime)}};ot.add(h);function f(S,E){const e={value:S,startTime:E,endTime:Ne,remove:()=>{Oi(o,e)},close:t=>{e.endTime=t}};return n&&o.length>=n&&o.pop(),o.unshift(e),e}function u(S=Ne,E={returnInactive:!1}){for(const e of o)if(e.startTime<=S){if(E.returnInactive||S<=e.endTime)return e.value;break}}function s(S){const E=o[0];E&&E.endTime===Ne&&E.close(S)}function p(S=Ne,E=0){const e=vn(S,E);return o.filter(t=>t.startTime<=e&&S<=t.endTime).map(t=>t.value)}function m(){return o.map(({startTime:S,endTime:E,value:e})=>({startTime:S,endTime:E===Ne?"Infinity":E,value:e}))}function g(){return d}function v(){o=[]}function U(){ot.delete(h),ot.size===0&&Ge&&(di(Ge),Ge=null)}return{add:f,find:u,closeActive:s,findAll:p,reset:v,stop:U,getAllEntries:m,getDeletedEntries:g}}const ws=he,Cs=Tt;function Ts(a,n,o,d){const h=new M,f=new M,u=rr(a.sessionStoreStrategyType,a,n,o),s=Es({expireDelay:Cs});u.renewObservable.subscribe(()=>{s.add(p(),$e()),h.notify()}),u.expireObservable.subscribe(()=>{f.notify(),s.closeActive($e())}),u.expandOrRenewSession(),s.add(p(),yn().relative),d.observable.subscribe(()=>{d.isGranted()?u.expandOrRenewSession():u.expire()}),As(a,()=>{d.isGranted()&&u.expandOrRenewSession()}),Is(a,()=>u.expandSession()),Fs(a,()=>u.restartSession());function p(){return{id:u.getSession().id,trackingType:u.getSession()[n],isReplayForced:!!u.getSession().forcedReplay,anonymousId:u.getSession().anonymousId}}return{findSession:(m,g)=>s.find(m,g),renewObservable:h,expireObservable:f,sessionStateUpdateObservable:u.sessionStateUpdateObservable,expire:u.expire,updateSessionState:u.updateSessionState}}function As(a,n){Ot(a,window,["click","touchstart","keydown","scroll"],n,{capture:!0,passive:!0})}function Is(a,n){const o=()=>{document.visibilityState==="visible"&&n()};me(a,document,"visibilitychange",o),Ut(o,ws)}function Fs(a,n){me(a,window,"resume",n,{capture:!0})}function Yi(a){return a>=500}function Bs(a){try{return a.clone()}catch{return}}const Ls=80*ee,ks=32,Vi=3*ri,Rs=he,$i=Be;function ji(a,n,o,d,h){n.transportStatus===0&&n.queuedPayloads.size()===0&&n.bandwidthMonitor.canHandle(a)?qi(a,n,o,{onSuccess:()=>Wi(0,n,o,d,h),onFailure:()=>{n.queuedPayloads.enqueue(a),Ki(n,o,d,h)}}):n.queuedPayloads.enqueue(a)}function Ki(a,n,o,d){a.transportStatus===2&&De(()=>{const h=a.queuedPayloads.first();qi(h,a,n,{onSuccess:()=>{a.queuedPayloads.dequeue(),a.currentBackoffTime=$i,Wi(1,a,n,o,d)},onFailure:()=>{a.currentBackoffTime=Math.min(Rs,a.currentBackoffTime*2),Ki(a,n,o,d)}})},a.currentBackoffTime)}function qi(a,n,o,{onSuccess:d,onFailure:h}){n.bandwidthMonitor.add(a),o(a,f=>{n.bandwidthMonitor.remove(a),Ds(f)?(n.transportStatus=n.bandwidthMonitor.ongoingRequestCount>0?1:2,a.retry={count:a.retry?a.retry.count+1:1,lastFailureStatus:f.status},h()):(n.transportStatus=0,d())})}function Wi(a,n,o,d,h){a===0&&n.queuedPayloads.isFull()&&!n.queueFullReported&&(h({message:`Reached max ${d} events size queued for upload: ${Vi/ri}MiB`,source:q.AGENT,startClocks:se()}),n.queueFullReported=!0);const f=n.queuedPayloads;for(n.queuedPayloads=Ji();f.size()>0;)ji(f.dequeue(),n,o,d,h)}function Ds(a){return a.type!=="opaque"&&(a.status===0&&!navigator.onLine||a.status===408||a.status===429||Yi(a.status))}function Ps(){return{transportStatus:0,currentBackoffTime:$i,bandwidthMonitor:zs(),queuedPayloads:Ji(),queueFullReported:!1}}function Ji(){const a=[];return{bytesCount:0,enqueue(n){this.isFull()||(a.push(n),this.bytesCount+=n.bytesCount)},first(){return a[0]},dequeue(){const n=a.shift();return n&&(this.bytesCount-=n.bytesCount),n},size(){return a.length},isFull(){return this.bytesCount>=Vi}}}function zs(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(a){return this.ongoingRequestCount===0||this.ongoingByteCount+a.bytesCount<=Ls&&this.ongoingRequestCount<ks},add(a){this.ongoingRequestCount+=1,this.ongoingByteCount+=a.bytesCount},remove(a){this.ongoingRequestCount-=1,this.ongoingByteCount-=a.bytesCount}}}function Os(a,n,o){const d=Ps(),h=(f,u)=>Gs(a,n,f,u);return{send:f=>{ji(f,d,h,a.trackType,o)},sendOnExit:f=>{Ms(a,n,f)}}}function Ms(a,n,o){if(!!navigator.sendBeacon&&o.bytesCount<n)try{const f=a.build("beacon",o);if(navigator.sendBeacon(f,o.data))return}catch(f){Ns(f)}const h=a.build("xhr",o);Mt(h,o.data)}let Xi=!1;function Ns(a){Xi||(Xi=!0,Hi(a))}function Gs(a,n,o,d){if(Hs()&&o.bytesCount<n){const f=a.build("fetch",o);fetch(f,{method:"POST",body:o.data,keepalive:!0,mode:"cors"}).then(L(u=>d==null?void 0:d({status:u.status,type:u.type})),L(()=>{const u=a.build("xhr",o);Mt(u,o.data,d)}))}else{const f=a.build("xhr",o);Mt(f,o.data,d)}}function Hs(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function Mt(a,n,o){const d=new XMLHttpRequest;d.open("POST",a,!0),n instanceof Blob&&d.setRequestHeader("Content-Type",n.type),me({allowUntrustedEvents:!0},d,"loadend",()=>{o==null||o({status:d.status})},{once:!0}),d.send(n)}function Nt(){const a=Ys();if(a)return{getCapabilities(){var n;return JSON.parse(((n=a.getCapabilities)===null||n===void 0?void 0:n.call(a))||"[]")},getPrivacyLevel(){var n;return(n=a.getPrivacyLevel)===null||n===void 0?void 0:n.call(a)},getAllowedWebViewHosts(){return JSON.parse(a.getAllowedWebViewHosts())},send(n,o,d){const h=d?{id:d}:void 0;a.send(JSON.stringify({eventType:n,event:o,view:h}))}}}function at(a){var n;a===void 0&&(a=(n=oe().location)===null||n===void 0?void 0:n.hostname);const o=Nt();return!!o&&o.getAllowedWebViewHosts().some(d=>a===d||a.endsWith(`.${d}`))}function Ys(){return oe().DatadogEventBridge}const dt={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function Vs(a){return new M(n=>{const{stop:o}=Ot(a,window,["visibilitychange","freeze"],h=>{h.type==="visibilitychange"&&document.visibilityState==="hidden"?n.notify({reason:dt.HIDDEN}):h.type==="freeze"&&n.notify({reason:dt.FROZEN})},{capture:!0}),d=me(a,window,"beforeunload",()=>{n.notify({reason:dt.UNLOADING})}).stop;return()=>{o(),d()}})}function $s(a){return We(dt).includes(a)}function js({encoder:a,request:n,flushController:o,messageBytesLimit:d}){let h={};const f=o.flushObservable.subscribe(v=>g(v));function u(v,U,S){o.notifyBeforeAddMessage(U),S!==void 0?(h[S]=v,o.notifyAfterAddMessage()):a.write(a.isEmpty?v:`\n${v}`,E=>{o.notifyAfterAddMessage(E-U)})}function s(v){return v!==void 0&&h[v]!==void 0}function p(v){const U=h[v];delete h[v];const S=a.estimateEncodedBytesCount(U);o.notifyAfterRemoveMessage(S)}function m(v,U){const S=_e(v),E=a.estimateEncodedBytesCount(S);if(E>=d){z.warn(`Discarded a message whose size was bigger than the maximum allowed size ${d}KB. ${Ye} ${ei}/#technical-limitations`);return}s(U)&&p(U),u(S,E,U)}function g(v){const U=We(h).join(`\n`);h={};const S=$s(v.reason),E=S?n.sendOnExit:n.send;if(S&&a.isAsync){const e=a.finishSync();e.outputBytesCount&&E(Zi(e));const t=[e.pendingData,U].filter(Boolean).join(`\n`);t&&E({data:t,bytesCount:bt(t)})}else U&&a.write(a.isEmpty?U:`\n${U}`),a.finish(e=>{E(Zi(e))})}return{flushController:o,add:m,upsert:m,stop:f.unsubscribe}}function Zi(a){let n;return typeof a.output=="string"?n=a.output:n=new Blob([a.output],{type:"text/plain"}),{data:n,bytesCount:a.outputBytesCount,encoding:a.encoding}}function Ks({messagesLimit:a,bytesLimit:n,durationLimit:o,pageExitObservable:d,sessionExpireObservable:h}){const f=d.subscribe(E=>g(E.reason)),u=h.subscribe(()=>g("session_expire")),s=new M(()=>()=>{f.unsubscribe(),u.unsubscribe()});let p=0,m=0;function g(E){if(m===0)return;const e=m,t=p;m=0,p=0,S(),s.notify({reason:E,messagesCount:e,bytesCount:t})}let v;function U(){v===void 0&&(v=De(()=>{g("duration_limit")},o))}function S(){ai(v),v=void 0}return{flushObservable:s,get messagesCount(){return m},notifyBeforeAddMessage(E){p+E>=n&&g("bytes_limit"),m+=1,p+=E,U()},notifyAfterAddMessage(E=0){p+=E,m>=a?g("messages_limit"):p>=n&&g("bytes_limit")},notifyAfterRemoveMessage(E){p-=E,m-=1,m===0&&S()}}}function Qi(a,n,o,d,h,f,u=js){const s=m(a,n),p=o&&m(a,o);function m(g,{endpoint:v,encoder:U}){return u({encoder:U,request:Os(v,g.batchBytesLimit,d),flushController:Ks({messagesLimit:g.batchMessagesLimit,bytesLimit:g.batchBytesLimit,durationLimit:g.flushTimeout,pageExitObservable:h,sessionExpireObservable:f}),messageBytesLimit:g.messageBytesLimit})}return{flushObservable:s.flushController.flushObservable,add(g,v=!0){s.add(g),p&&v&&p.add(o.transformMessage?o.transformMessage(g):g)},upsert:(g,v)=>{s.upsert(g,v),p&&p.upsert(o.transformMessage?o.transformMessage(g):g,v)},stop:()=>{s.stop(),p&&p.stop()}}}function lt(){let a="",n=0;return{isAsync:!1,get isEmpty(){return!a},write(o,d){const h=bt(o);n+=h,a+=o,d&&d(h)},finish(o){o(this.finishSync())},finishSync(){const o={output:a,outputBytesCount:n,rawBytesCount:n,pendingData:""};return a="",n=0,o},estimateEncodedBytesCount(o){return o.length}}}class qs{constructor(){this.callbacks={}}notify(n,o){const d=this.callbacks[n];d&&d.forEach(h=>h(o))}subscribe(n,o){return this.callbacks[n]||(this.callbacks[n]=[]),this.callbacks[n].push(o),{unsubscribe:()=>{this.callbacks[n]=this.callbacks[n].filter(d=>o!==d)}}}}function Ws(a,n,o){let d=0,h=!1;return{isLimitReached(){if(d===0&&De(()=>{d=0},he),d+=1,d<=n||h)return h=!1,!1;if(d===n+1){h=!0;try{o({message:`Reached max number of ${a}s by minute: ${n}`,source:q.AGENT,startClocks:se()})}finally{h=!1}}return!0}}}let Gt;const Ht=new WeakMap;function Js(a){return Gt||(Gt=Xs(a)),Gt}function Xs(a){return new M(n=>{const{stop:o}=ye(XMLHttpRequest.prototype,"open",Zs),{stop:d}=ye(XMLHttpRequest.prototype,"send",f=>{Qs(f,a,n)},{computeHandlingStack:!0}),{stop:h}=ye(XMLHttpRequest.prototype,"abort",eo);return()=>{o(),d(),h()}})}function Zs({target:a,parameters:[n,o]}){Ht.set(a,{state:"open",method:String(n).toUpperCase(),url:Bt(String(o))})}function Qs({target:a,handlingStack:n},o,d){const h=Ht.get(a);if(!h)return;const f=h;f.state="start",f.startClocks=se(),f.isAborted=!1,f.xhr=a,f.handlingStack=n;let u=!1;const{stop:s}=ye(a,"onreadystatechange",()=>{a.readyState===XMLHttpRequest.DONE&&p()}),p=()=>{if(m(),s(),u)return;u=!0;const g=h;g.state="complete",g.duration=mn(f.startClocks.timeStamp,re()),g.status=a.status,d.notify(xn(g))},{stop:m}=me(o,a,"loadend",p);d.notify(f)}function eo({target:a}){const n=Ht.get(a);n&&(n.isAborted=!0)}let Yt;function en(){return Yt||(Yt=to()),Yt}function to(){return new M(a=>{if(!window.fetch)return;const{stop:n}=ye(window,"fetch",o=>io(o,a),{computeHandlingStack:!0});return n})}function io({parameters:a,onPostCall:n,handlingStack:o},d){const[h,f]=a;let u=f&&f.method;u===void 0&&h instanceof Request&&(u=h.method);const s=u!==void 0?String(u).toUpperCase():"GET",p=h instanceof Request?h.url:Bt(String(h)),m=se(),g={state:"start",init:f,input:h,method:s,startClocks:m,url:p,handlingStack:o};d.notify(g),a[0]=g.input,a[1]=g.init,n(v=>no(d,v,g))}function no(a,n,o){const d=o;function h(f){d.state="resolve",Object.assign(d,f),a.notify(d)}n.then(L(f=>{h({response:f,responseType:f.type,status:f.status,isAborted:!1})}),L(f=>{var u,s;h({status:0,isAborted:((s=(u=d.init)===null||u===void 0?void 0:u.signal)===null||s===void 0?void 0:s.aborted)||f instanceof DOMException&&f.code===DOMException.ABORT_ERR,error:f})}))}let Vt={};function ro(a){const n=a.map(o=>(Vt[o]||(Vt[o]=so(o)),Vt[o]));return li(...n)}function so(a){return new M(n=>{const o=Q[a];return Q[a]=(...d)=>{o.apply(console,d);const h=nt("console error");Re(()=>{n.notify(oo(d,a,h))})},()=>{Q[a]=o}})}function oo(a,n,o){const d=a.map(f=>ao(f)).join(" ");let h;if(n===P.error){const f=a.find(le);h={stack:f?ge(te(f)):void 0,fingerprint:Ii(f),causes:f?Bi(f,"console"):void 0,startClocks:se(),message:d,source:q.CONSOLE,handling:"handled",handlingStack:o,context:Fi(f)}}return{api:n,message:d,error:h,handlingStack:o}}function ao(a){return typeof a=="string"?ie(a):le(a)?Ci(te(a)):_e(ie(a),void 0,2)}function lo(a){const n=Pi(a)==="object";return n||z.error("Unsupported context:",a),n}function $t(a,n,o){const d={...a};for(const[h,{required:f,type:u}]of Object.entries(n))u==="string"&&h in d&&(d[h]=String(d[h])),f&&!(h in a)&&z.warn(`The property ${h} of ${o} is required; context will not be sent to the intake.`);return d}function ft(a="",{customerDataTracker:n,propertiesConfig:o={}}={}){let d={};const h=new M,f={getContext:()=>zi(d),setContext:u=>{lo(u)?(d=ie($t(u,o,a)),n==null||n.updateCustomerData(d)):f.clearContext(),h.notify()},setContextProperty:(u,s)=>{d=ie($t({...d,[u]:s},o,a)),n==null||n.updateCustomerData(d),h.notify()},removeContextProperty:u=>{delete d[u],n==null||n.updateCustomerData(d),$t(d,o,a),h.notify()},clearContext:()=>{d={},n==null||n.resetCustomerData(),h.notify()},changeObservable:h};return f}const fo="_dd_c",ho=[];function jt(a,n,o,d){const h=co(o,d);ho.push(me(a,window,"storage",({key:m})=>{h===m&&u()})),n.changeObservable.subscribe(s);const f=Te(p(),n.getContext());ke(f)||n.setContext(f);function u(){n.setContext(p())}function s(){localStorage.setItem(h,JSON.stringify(n.getContext()))}function p(){const m=localStorage.getItem(h);return m?JSON.parse(m):{}}}function co(a,n){return`${fo}_${a}_${n}`}const uo=3*ee,po=16*ee,_o=200;function go(a=2){const n=new Map;let o=!1;function d(h=0){if(o||a===0)return;const f=a===2?uo:po;let u=h;n.forEach(s=>{u+=s.getBytesCount()}),u>f&&(yo(f),o=!0)}return{createDetachedTracker:()=>{const h=tn(()=>d(h.getBytesCount()));return h},getOrCreateTracker:h=>(n.has(h)||n.set(h,tn(d)),n.get(h)),setCompressionStatus:h=>{a===0&&(a=h,d())},getCompressionStatus:()=>a,stop:()=>{n.forEach(h=>h.stop()),n.clear()}}}function tn(a){let n=0;const{throttled:o,cancel:d}=fi(f=>{n=bt(_e(f)),a()},_o),h=()=>{d(),n=0};return{updateCustomerData:f=>{ke(f)?h():o(f)},resetCustomerData:h,getBytesCount:()=>n,stop:()=>{d()}}}function yo(a){z.warn(`Customer data exceeds the recommended ${a/ee}KiB threshold. ${Ye} ${ei}/#customer-data-exceeds-the-recommended-threshold-warning`)}function mo(a,n,o){const d=a.getReader(),h=[];let f=0;u();function u(){d.read().then(L(p=>{if(p.done){s();return}h.push(p.value),f+=p.value.length,f>o.bytesLimit?s():u()}),L(p=>n(p)))}function s(){d.cancel().catch(ae);let p,m;{let g;if(h.length===1)g=h[0];else{g=new Uint8Array(f);let v=0;h.forEach(U=>{g.set(U,v),v+=U.length})}p=g.slice(0,o.bytesLimit),m=g.length>o.bytesLimit}n(void 0,p,m)}}const vo="datadog-synthetics-public-id",So="datadog-synthetics-result-id",bo="datadog-synthetics-injects-rum";function nn(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||ce(bo))}function xo(){const a=window._DATADOG_SYNTHETICS_PUBLIC_ID||ce(vo);return typeof a=="string"?a:void 0}function Uo(){const a=window._DATADOG_SYNTHETICS_RESULT_ID||ce(So);return typeof a=="string"?a:void 0}function ht(a,n,o){const d=o.getHandler(),h=Array.isArray(d)?d:[d];return rn[a]>=rn[o.getLevel()]&&h.includes(n)}const F={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},rn={[F.ok]:0,[F.debug]:1,[F.info]:2,[F.notice]:4,[F.warn]:5,[F.error]:6,[F.critical]:7,[F.alert]:8,[F.emerg]:9};function ct(a,{includeMessage:n=!1}={}){return{stack:a.stack,kind:a.type,message:n?a.message:void 0,causes:a.causes,fingerprint:a.fingerprint,handling:a.handling}}var Eo=function(a,n,o,d){var h=arguments.length,f=h<3?n:d===null?d=Object.getOwnPropertyDescriptor(n,o):d,u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")f=Reflect.decorate(a,n,o,d);else for(var s=a.length-1;s>=0;s--)(u=a[s])&&(f=(h<3?u(f):h>3?u(n,o,f):u(n,o))||f);return h>3&&f&&Object.defineProperty(n,o,f),f};const He={console:"console",http:"http",silent:"silent"},wo=Object.keys(F);let X=class{constructor(n,o,d,h=He.http,f=F.debug,u={}){this.handleLogStrategy=n,this.handlerType=h,this.level=f,this.contextManager=ft("logger",{customerDataTracker:o}),this.contextManager.setContext(u),d&&this.contextManager.setContextProperty("logger",{name:d})}logImplementation(n,o,d=F.info,h,f){const u=ie(o);let s;if(h!=null){const p=Ai({stackTrace:le(h)?te(h):void 0,originalError:h,nonErrorPrefix:"Provided",source:q.LOGGER,handling:"handled",startClocks:se()});s=Te({error:ct(p,{includeMessage:!0})},u)}else s=u;this.handleLogStrategy({message:ie(n),context:s,status:d},this,f)}log(n,o,d=F.info,h){let f;ht(d,He.http,this)&&(f=nt("log")),this.logImplementation(n,o,d,h,f)}setContext(n){this.contextManager.setContext(n)}getContext(){return this.contextManager.getContext()}setContextProperty(n,o){this.contextManager.setContextProperty(n,o)}removeContextProperty(n){this.contextManager.removeContextProperty(n)}clearContext(){this.contextManager.clearContext()}setHandler(n){this.handlerType=n}getHandler(){return this.handlerType}setLevel(n){this.level=n}getLevel(){return this.level}};Eo([wn],X.prototype,"logImplementation",null),X.prototype.ok=ne(F.ok),X.prototype.debug=ne(F.debug),X.prototype.info=ne(F.info),X.prototype.notice=ne(F.notice),X.prototype.warn=ne(F.warn),X.prototype.error=ne(F.error),X.prototype.critical=ne(F.critical),X.prototype.alert=ne(F.alert),X.prototype.emerg=ne(F.emerg);function ne(a){return function(n,o,d){let h;ht(a,He.http,this)&&(h=nt("log")),this.logImplementation(n,o,a,d,h)}}function Co(a,n,o){return{view:{referrer:document.referrer,url:window.location.href},context:a.getContext(),user:n.getContext(),account:o.getContext()}}const To=32*ee;function Ao(a){a.usePciIntake===!0&&a.site&&a.site!=="datadoghq.com"&&z.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const n=wr(a),o=sn(a.forwardConsoleLogs,We(P),"Forward Console Logs"),d=sn(a.forwardReports,We(rt),"Forward Reports");if(!(!n||!o||!d))return a.forwardErrorsToLogs&&!o.includes(P.error)&&o.push(P.error),{forwardErrorsToLogs:a.forwardErrorsToLogs!==!1,forwardConsoleLogs:o,forwardReports:d,requestErrorResponseLengthLimit:To,...n}}function sn(a,n,o){if(a===void 0)return[];if(!(a==="all"||Array.isArray(a)&&a.every(d=>n.includes(d)))){z.error(`${o} should be "all" or an array with allowed values "${n.join(\'", "\')}"`);return}return a==="all"?n:fs(a)}function Io(a){const n=Cr(a);return{forward_errors_to_logs:a.forwardErrorsToLogs,forward_console_logs:a.forwardConsoleLogs,forward_reports:a.forwardReports,use_pci_intake:a.usePciIntake,...n}}function Fo(a,n,o){const d=Mi();let h,f;const u=n.observable.subscribe(s);function s(){if(!f||!h||!n.isGranted())return;u.unsubscribe();const p=o(h,f);d.drain(p)}return{init(p){if(!p){z.error("Missing configuration");return}if(Tr(p.enableExperimentalFeatures),at()&&(p=Bo(p)),h=p,f){Li("DD_LOGS",p);return}const m=Ao(p);m&&(f=m,en().subscribe(ae),n.tryToInit(m.trackingConsent),s())},get initConfiguration(){return h},getInternalContext:ae,handleLog(p,m,g,v=a(),U=re()){d.add(S=>S.handleLog(p,m,g,v,U))}}}function Bo(a){return{...a,clientToken:"empty"}}const Kt="logs";function Lo(a){const n=go(),o=ft("global context",{customerDataTracker:n.getOrCreateTracker(2)}),d=ft("user",{customerDataTracker:n.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),h=ft("account",{customerDataTracker:n.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),f=sr();function u(){return Co(o,d,h)}let s=Fo(u,f,(g,v)=>{g.storeContextsAcrossPages&&(jt(v,o,Kt,2),jt(v,d,Kt,1),jt(v,h,Kt,4));const U=a(g,v,u,f);return s=ko(g,U),U});const p={},m=new X((...g)=>s.handleLog(...g),n.createDetachedTracker());return ts({logger:m,init:L(g=>s.init(g)),setTrackingConsent:L(g=>{f.update(g),vs({feature:"set-tracking-consent",tracking_consent:g})}),getGlobalContext:L(()=>o.getContext()),setGlobalContext:L(g=>o.setContext(g)),setGlobalContextProperty:L((g,v)=>o.setContextProperty(g,v)),removeGlobalContextProperty:L(g=>o.removeContextProperty(g)),clearGlobalContext:L(()=>o.clearContext()),createLogger:L((g,v={})=>(p[g]=new X((...U)=>s.handleLog(...U),n.createDetachedTracker(),ie(g),v.handler,v.level,ie(v.context)),p[g])),getLogger:L(g=>p[g]),getInitConfiguration:L(()=>zi(s.initConfiguration)),getInternalContext:L(g=>s.getInternalContext(g)),setUser:L(d.setContext),getUser:L(d.getContext),setUserProperty:L(d.setContextProperty),removeUserProperty:L(d.removeContextProperty),clearUser:L(d.clearContext),setAccount:L(h.setContext),getAccount:L(h.getContext),setAccountProperty:L(h.setContextProperty),removeAccountProperty:L(h.removeContextProperty),clearAccount:L(h.clearContext)})}function ko(a,n){return{init:o=>{Li("DD_LOGS",o)},initConfiguration:a,...n}}const Ro="logs";function Do(a,n){const o=Ts(a,Ro,d=>zo(a,d),n);return{findTrackedSession:(d,h={returnInactive:!1})=>{const f=o.findSession(d,h);return f&&f.trackingType==="1"?{id:f.id,anonymousId:f.anonymousId}:void 0},expireObservable:o.expireObservable}}function Po(a){const o=on(a)==="1"?{}:void 0;return{findTrackedSession:()=>o,expireObservable:new M}}function on(a){return Ve(a.sessionSampleRate)?"1":"0"}function zo(a,n){const o=Oo(n)?n:on(a);return{trackingType:o,isTracked:o==="1"}}function Oo(a){return a==="0"||a==="1"}let an=!1;function ut(a){const n=window;if(nn()){const d=o(n.DD_RUM_SYNTHETICS);return!d&&!an&&(an=!0,Gi("Logs sent before RUM is injected by the synthetics worker",{testId:xo(),resultId:Uo()})),d}return o(n.DD_RUM);function o(d){if(d&&d.getInternalContext)return d.getInternalContext(a)}}function Mo(a,n,o,d,h){const f=wo.concat(["custom"]),u={};f.forEach(s=>{u[s]=Ws(s,n.eventRateLimiterThreshold,h)}),o.subscribe(0,({rawLogsEvent:s,messageContext:p=void 0,savedCommonContext:m=void 0,domainContext:g})=>{var v,U;const S=Sn(s.date),E=a.findTrackedSession(S);if(!a.findTrackedSession(S,{returnInactive:!0}))return;const t=m||d();let r;!ke(t.account)&&t.account.id&&(r=t.account),E&&E.anonymousId&&!t.user.anonymous_id&&(t.user.anonymous_id=E.anonymousId);const l=Te({service:n.service,session_id:E?E.id:void 0,session:E?{id:E.id}:void 0,usr:ke(t.user)?void 0:t.user,account:r,view:t.view},t.context,ut(S),s,p);((v=n.beforeSend)===null||v===void 0?void 0:v.call(n,l,g))===!1||l.origin!==q.AGENT&&((U=u[l.status])!==null&&U!==void 0?U:u.custom).isLimitReached()||o.notify(1,l)})}const No={[P.log]:F.info,[P.debug]:F.debug,[P.info]:F.info,[P.warn]:F.warn,[P.error]:F.error};function Go(a,n){const o=ro(a.forwardConsoleLogs).subscribe(d=>{var h;const f={rawLogsEvent:{date:re(),message:d.message,origin:q.CONSOLE,error:d.error&&ct(d.error),status:No[d.api]},messageContext:(h=d.error)===null||h===void 0?void 0:h.context,domainContext:{handlingStack:d.handlingStack}};n.notify(0,f)});return{stop:()=>{o.unsubscribe()}}}function Ho(a,n){const o=ns(a,a.forwardReports).subscribe(d=>{let h=d.message,f;const u=d.originalError.type==="deprecation"?F.warn:F.error;u===F.error?f=ct(d):d.stack&&(h+=` Found in ${Xr(d.stack)}`),n.notify(0,{rawLogsEvent:{date:re(),message:h,origin:q.REPORT,error:f,status:u}})});return{stop:()=>{o.unsubscribe()}}}function Yo(a,n){if(!a.forwardErrorsToLogs)return{stop:ae};const o=Js(a).subscribe(f=>{f.state==="complete"&&h("xhr",f)}),d=en().subscribe(f=>{f.state==="resolve"&&h("fetch",f)});function h(f,u){!Ur(u.url)&&(Ko(u)||Yi(u.status))&&("xhr"in u?Vo(u.xhr,a,s):u.response?jo(u.response,a,s):u.error&&$o(u.error,a,s));function s(p){const m={isAborted:u.isAborted,handlingStack:u.handlingStack};n.notify(0,{rawLogsEvent:{message:`${qo(f)} error ${u.method} ${u.url}`,date:u.startClocks.timeStamp,error:{stack:p||"Failed to load",handling:void 0},http:{method:u.method,status_code:u.status,url:u.url},status:F.error,origin:q.NETWORK},domainContext:m})}}return{stop:()=>{o.unsubscribe(),d.unsubscribe()}}}function Vo(a,n,o){typeof a.response=="string"?o(qt(a.response,n)):o(a.response)}function $o(a,n,o){o(qt(ge(te(a)),n))}function jo(a,n,o){const d=Bs(a);!d||!d.body?o():window.TextDecoder?Wo(d.body,n.requestErrorResponseLengthLimit,(h,f)=>{o(h?`Unable to retrieve response: ${h}`:f)}):d.text().then(L(h=>o(qt(h,n))),L(h=>o(`Unable to retrieve response: ${h}`)))}function Ko(a){return a.status===0&&a.responseType!=="opaque"}function qt(a,n){return a.length>n.requestErrorResponseLengthLimit?`${a.substring(0,n.requestErrorResponseLengthLimit)}...`:a}function qo(a){return a==="xhr"?"XHR":"Fetch"}function Wo(a,n,o){mo(a,(d,h,f)=>{if(d)o(d);else{let u=new TextDecoder().decode(h);f&&(u+="..."),o(void 0,u)}},{bytesLimit:n,collectStreamBody:!0})}function Jo(a,n){if(!a.forwardErrorsToLogs)return{stop:ae};const o=new M,{stop:d}=Zr(o),h=o.subscribe(f=>{n.notify(0,{rawLogsEvent:{message:f.message,date:f.startClocks.timeStamp,error:ct(f),origin:q.SOURCE,status:F.error},messageContext:f.context})});return{stop:()=>{d(),h.unsubscribe()}}}const Xo=qs;function Zo(a){function n(o,d,h,f,u){const s=Te(d.getContext(),o.context);if(ht(o.status,He.console,d)&&ea(o,s),ht(o.status,He.http,d)){const p={rawLogsEvent:{date:u||re(),message:o.message,status:o.status,origin:q.LOGGER},messageContext:s,savedCommonContext:f};h&&(p.domainContext={handlingStack:h}),a.notify(0,p)}}return{handleLog:n}}const Qo={[F.ok]:P.debug,[F.debug]:P.debug,[F.info]:P.info,[F.notice]:P.info,[F.warn]:P.warn,[F.error]:P.error,[F.critical]:P.error,[F.alert]:P.error,[F.emerg]:P.error};function ea({status:a,message:n},o){fe[Qo[a]].call(Q,n,o)}function ta(a,n,o,d,h){const f=Qi(a,{endpoint:a.logsEndpointBuilder,encoder:lt()},a.replica&&{endpoint:a.replica.logsEndpointBuilder,encoder:lt()},o,d,h.expireObservable);return n.subscribe(1,u=>{f.add(u)}),f}function ia(a){const n=Nt();a.subscribe(1,o=>{n.send("log",o)})}function na(a){return{get:n=>{const o=a.findTrackedSession(n);if(o)return{session_id:o.id}}}}function ra(a){return n=>{a.notify(0,{rawLogsEvent:{message:n.message,date:n.startClocks.timeStamp,origin:q.AGENT,status:F.error}}),Gi("Error reported to customer",{"error.message":n.message})}}function sa(a,n,o,d,h){const f=ps("browser-logs-sdk",n);f.setContextProvider(()=>{var s,p,m,g,v,U;return{application:{id:(s=ut())===null||s===void 0?void 0:s.application_id},session:{id:(p=h.findTrackedSession())===null||p===void 0?void 0:p.id},view:{id:(g=(m=ut())===null||m===void 0?void 0:m.view)===null||g===void 0?void 0:g.id},action:{id:(U=(v=ut())===null||v===void 0?void 0:v.user_action)===null||U===void 0?void 0:U.id}}});const u=[];if(at()){const s=Nt(),p=f.observable.subscribe(m=>s.send("internal_telemetry",m));u.push(()=>p.unsubscribe())}else{const s=Qi(n,{endpoint:n.rumEndpointBuilder,encoder:lt()},n.replica&&{endpoint:n.replica.rumEndpointBuilder,encoder:lt()},o,d,h.expireObservable);u.push(()=>s.stop());const p=f.observable.subscribe(m=>s.add(m,ys(n)));u.push(()=>p.unsubscribe())}return gs(),ms(Io(a)),{telemetry:f,stop:()=>{u.forEach(s=>s())}}}function oa(a,n,o,d){const h=new Xo,f=[];h.subscribe(1,U=>Di("logs",U));const u=ra(h),s=Vs(n),p=n.sessionStoreStrategyType&&!at()&&!nn()?Do(n,d):Po(n),{stop:m}=sa(a,n,u,s,p);f.push(()=>m()),Yo(n,h),Jo(n,h),Go(n,h),Ho(n,h);const{handleLog:g}=Zo(h);if(Mo(p,n,h,o,u),at())ia(h);else{const{stop:U}=ta(n,h,u,s,p);f.push(()=>U())}const v=na(p);return{handleLog:g,getInternalContext:v.get,stop:()=>{f.forEach(U=>U())}}}const Ie=Lo(oa);is(oe(),"DD_LOGS",Ie);class N{constructor(n){this.isLoggingOn=n,Ie.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!0,sessionSampleRate:100})}static setMessagePort(n){this.messagePort=n}static getMessagePort(){return this.messagePort}setLoggingOn(n){this.isLoggingOn=n}setAttributes(n){for(const o in n)Ie.logger.setContextProperty(o,n[o])}info(n,o){this.isLoggingOn&&(Ie.logger.info(n,o),console.log("[Logger] Sending info: ",n))}error(n,o){this.isLoggingOn&&(Ie.logger.error(n,o),console.log("[Logger] Sending error: ",n))}warn(n,o){this.isLoggingOn&&(Ie.logger.warn(n,o),console.log("[Logger] Sending warn: ",n))}handleMessageFromWorker(n){n.actionType==="INFO"?this.info(n.message,n.attributes):n.actionType==="ERROR"?this.error(n.message,n.attributes):n.actionType==="WARN"?this.warn(n.message,n.attributes):n.actionType==="SET_ATTRIBUTES"&&n.attributes&&this.setAttributes(n.attributes)}static setAttributes(n){N.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:n})}static info(n,o){N.messagePort.postMessage({type:"LOG",actionType:"INFO",message:n,attributes:o})}static error(n,o){N.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:n,attributes:o})}static warn(n,o){N.messagePort.postMessage({type:"LOG",actionType:"WARN",message:n,attributes:o})}}class Wt{constructor(n,o,d){this.videoDecoder=null,this.reservedVideoDecoder=null,this.videoDecoderNeedsKeyFrame=!1,this.reservedVideoDecoderNeedsKeyFrame=!1,this.currentTimecode="",this.fps=0,this.unchunkedJobs=[],this.jobChunking=null,this.jobsQueue=[],this.chunksQueue=[],this.chunksForDecodingFrames=[],this.processedMetadata=[],this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.timecodeErrorCount=0,this.decoderStopped=!1,this.addJob=(h,f)=>{const{alphaMp4:u,metadataList:s}=this.parseZipAndMetadata(f);if(!u){this.options&&D(this.options,"Decoder")&&console.log("[Decoder] No alpha.mp4 found, no decoding needed.");return}const p={timeCode:h,alphaMp4:u,metadata:s,chunks:[],totalFrameCount:s.length,framesProcessed:0,framesSentToDecoder:0,useReserveDecoder:s.length<3};this.jobChunking?this.unchunkedJobs.push(p):(this.jobChunking=p,this.chunkJob(p)),this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Added job:",p)},this.clearOldJobsAndChunks=h=>{const u=$.fromStr(this.currentTimecode).totalMilliseconds(this.fps)-h;this.unchunkedJobs=this.unchunkedJobs.filter(s=>$.fromStr(s.timeCode).totalMilliseconds(this.fps)>u),this.jobsQueue=this.jobsQueue.filter(s=>$.fromStr(s.timeCode).totalMilliseconds(this.fps)>u),this.chunksQueue=this.chunksQueue.filter(s=>$.fromStr(s.timeCode).totalMilliseconds(this.fps)>u)},this.clearAllJobsAndChunks=()=>{this.unchunkedJobs=[],this.jobsQueue=[],this.chunksQueue=[]},this.updateCurrentTimecode=(h,f)=>{if(this.options){if(this.currentTimecode){const u=$.fromStr(h).totalMilliseconds(this.fps),s=$.fromStr(this.currentTimecode).totalMilliseconds(this.fps);if(u<s||u>s+this.options.DECODER_LEAD_TIME_MILLIS){this.timecodeErrorCount++,u<s&&(N.error("[Decoder] Timecode is going backwards"),this.options&&D(this.options,"Errors")&&console.error("[Decoder] Timecode is going backwards")),u>s+this.options.DECODER_LEAD_TIME_MILLIS&&(N.error("[Decoder] Timecode is too far ahead"),this.options&&D(this.options,"Errors")&&console.error("[Decoder] Timecode is too far ahead")),this.timecodeErrorCount>5&&this.restartDecoder();return}}this.timecodeErrorCount=0,this.currentTimecode=h,this.fps=59.94,this.clearOldJobsAndChunks(2100),this.decodeUpcomingChunks()}},this.setupMP4Box=(h=!1)=>{const f=fn.createFile();return f.onError=u=>{N.error("[Decoder] MP4 parsing error",u),this.options&&D(this.options,"Errors")&&console.error("[Decoder] MP4 parsing error:",u)},f.onReady=u=>{const s=u.tracks.find(p=>p.type==="video");if(s){if(!(h?this.reservedVideoDecoderConfigured:this.videoDecoderConfigured)){this.options&&D(this.options,"Decoder")&&console.error("[Decoder] Starting a new VideoDecoder");let m;h?(this.reservedVideoDecoder=new VideoDecoder({output:this.onFrameDecoded,error:this.onDecoderError}),m=this.reservedVideoDecoder):(this.videoDecoder=new VideoDecoder({output:this.onFrameDecoded,error:this.onDecoderError}),m=this.videoDecoder),m.configure({codec:s.codec,codedWidth:s.video.width,codedHeight:s.video.height,description:this.getDescription(f.getTrackById(s.id)),hardwareAcceleration:"prefer-hardware",optimizeForLatency:!0}),h?(this.reservedVideoDecoderConfigured=!0,this.reservedVideoDecoderNeedsKeyFrame=!0):(this.videoDecoderConfigured=!0,this.videoDecoderNeedsKeyFrame=!0)}f.setExtractionOptions(s.id),f.start()}},f.onSamples=async(u,s,p)=>{const m=[];for(const g of p){const v=new EncodedVideoChunk({type:g.is_sync?"key":"delta",timestamp:g.cts,data:new Uint8Array(g.data)});m.push(v)}this.storeChunks(m)},f},this.chunkJob=async h=>{this.mp4boxfile=this.setupMP4Box(h.useReserveDecoder);const u=await new Blob([h.alphaMp4],{type:"video/mp4"}).arrayBuffer();u.fileStart=0,this.mp4boxfile.appendBuffer(u)},this.storeChunks=h=>{this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Storing chunks:",h);const f=this.jobChunking;if(this.unchunkedJobs.length>0){const s=this.unchunkedJobs.shift();this.jobChunking=s,this.chunkJob(s)}else this.jobChunking=null;const u=f==null?void 0:f.metadata.map((s,p)=>({timeCode:s.timecode,chunk:h[p],metadata:s,job:f,cancelled:!1}));f.chunks=u,this.chunksQueue.push(...u),this.jobsQueue.push(f),this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Jobs Queue:",this.jobsQueue),this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Chunks Queue:",this.chunksQueue)},this.onFrameDecoded=h=>{this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Frame decoded:",h);const f=this.chunksForDecodingFrames.shift();if(!f){N.error("[Decoder] No current chunk for a processed frame"),this.options&&D(this.options,"Errors")&&console.error("[Decoder] No current chunk for a processed frame");return}if(f.cancelled||this.decoderStopped){this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Skipping cancelled chunk:",f.timeCode),h.close();return}const u=f.metadata;f.job.framesProcessed++,u.alphaMask=h,this.processedMetadata.push(u),(this.processedMetadata.length>=this.options.DECODER_FRAME_BATCH_SIZE||f.job.framesProcessed>=f.job.totalFrameCount)&&(this.postBatchToRenderer(this.processedMetadata),this.processedMetadata.forEach(s=>s.alphaMask.close()),this.processedMetadata=[])},this.onDecoderError=h=>{var s,p;N.error("[Decoder] VideoDecoder error",h),this.options&&D(this.options,"Errors")&&console.error("[Decoder] VideoDecoder error:",h),this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.videoDecoderNeedsKeyFrame=!0,this.reservedVideoDecoderNeedsKeyFrame=!0;const f=this.chunksForDecodingFrames.shift();if(!f){N.error("[Decoder] No broken chunk for an error"),this.options&&D(this.options,"Errors")&&console.error("[Decoder] No broken chunk for an error");return}const u=f.job;u&&u.chunks.forEach(m=>m.cancelled=!0),(s=this.reservedVideoDecoder)==null||s.close(),(p=this.videoDecoder)==null||p.close()},this.parseZipAndMetadata=h=>{const f=un.parse(h),u=f["alpha.mp4"]||null,s=Object.keys(f).filter(p=>p.endsWith(".json")).sort(this.numericFileComparator).map(p=>{const m=JSON.parse(new TextDecoder().decode(f[p]));return m.timecode=$.toStr($.fromMetadata(m)),m}).filter(p=>p.placeholders);return{alphaMp4:u,metadataList:s}},this.numericFileComparator=(h,f)=>{const u=/^(\\d{2})_(\\d{2})_(\\d{2})_(\\d{2})(?:\\.(\\d+))?\\.(.+)$/,s=h.match(u),p=f.match(u);if(!s||!p)return 0;const[,m,g,v,U,S="0",E]=s,[,e,t,r,l,c="0",_]=p;return parseInt(m,10)-parseInt(e,10)||parseInt(g,10)-parseInt(t,10)||parseInt(v,10)-parseInt(r,10)||parseInt(U,10)-parseInt(l,10)||parseInt(S,10)-parseInt(c,10)||E.localeCompare(_)},this.getDescription=h=>{for(const f of h.mdia.minf.stbl.stsd.entries){const u=f.avcC||f.hvcC||f.vpcC||f.av1C;if(u){const s=new yt.DataStream(void 0,0,yt.DataStream.BIG_ENDIAN);return u.write(s),new Uint8Array(s.buffer,8)}}return null},this.postBatchToRenderer=n,this.restartDecoder=o,this.options=d,this.mp4boxfile=this.setupMP4Box()}decodeUpcomingChunks(){const n=$.fromStr(this.currentTimecode).totalMilliseconds(this.fps),o=n+this.options.DECODER_LEAD_TIME_MILLIS,d=this.chunksQueue.filter(f=>{const u=$.fromStr(f.timeCode).totalMilliseconds(this.fps);return u>=n&&u<=o&&!f.decoded});d.sort((f,u)=>{const s=$.fromStr(f.timeCode).totalMilliseconds(this.fps),p=$.fromStr(u.timeCode).totalMilliseconds(this.fps);return s-p});const h=d.slice(0,this.options.DECODER_FRAME_BATCH_SIZE);for(const f of h){if(f.cancelled){this.options&&D(this.options,"Decoder")&&console.log("[Decoder] Skipping cancelled chunk:",f.timeCode);continue}const u=f.job.useReserveDecoder?this.reservedVideoDecoder:this.videoDecoder;if(!u||u.state==="closed"){N.error("[Decoder] No VideoDecoder available"),this.options&&D(this.options,"Errors")&&console.error("[Decoder] No VideoDecoder available");continue}if((f.job.useReserveDecoder?this.reservedVideoDecoderNeedsKeyFrame:this.videoDecoderNeedsKeyFrame)&&f.chunk.type==="delta"){N.error("[Decoder] Decoder needs a key frame, skipping delta chunk",{chunkTimeCode:f.timeCode}),this.options&&D(this.options,"Errors")&&console.error("[Decoder] Decoder needs a key frame, skipping delta chunk:",f.timeCode),f.decoded=!0;continue}try{this.chunksForDecodingFrames.push(f),f.chunk.type==="key"&&(f.job.useReserveDecoder?this.reservedVideoDecoderNeedsKeyFrame=!1:this.videoDecoderNeedsKeyFrame=!1),u.decode(f.chunk)}catch(p){N.error("[Decoder] Error decoding chunk",p),this.options&&D(this.options,"Errors")&&console.error("[Decoder] Error decoding chunk:",p),this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.videoDecoderNeedsKeyFrame=!0,this.reservedVideoDecoderNeedsKeyFrame=!0,f.job.chunks.forEach(g=>g.cancelled=!0),u.close()}finally{if(f.decoded=!0,f.job.framesSentToDecoder++,f.job.framesSentToDecoder>=f.job.totalFrameCount){u.flush(),f.job.useReserveDecoder;continue}}}}stop(){var n,o;this.decoderStopped=!0,this.clearAllJobsAndChunks();try{(n=this.videoDecoder)==null||n.close()}catch(d){N.error("[Decoder] Error closing main VideoDecoder",d),this.options&&D(this.options,"Errors")&&console.error("[Decoder] Error closing main VideoDecoder:",d)}try{(o=this.reservedVideoDecoder)==null||o.close()}catch(d){N.error("[Decoder] Error closing reserved VideoDecoder",d),this.options&&D(this.options,"Errors")&&console.error("[Decoder] Error closing reserved VideoDecoder:",d)}}}let dn=null,pt=null,Se,W;self.onmessage=async a=>{const{data:n}=a;if(n.type==="SET_LOGGER_PORT"&&N.setMessagePort(n.port),n.type==="SET_DOWNLOADER_PORT"&&(dn=n.port,dn.onmessage=aa),n.type==="SET_RENDERER_PORT"&&(pt=n.port,pt.onmessage=da),n.type==="SET_OPTIONS"&&(W=n.options,N.setMessagePort(self),Se=new Wt(Jt,_t,W)),n.type==="VIDEO_SEEKED"){if(!W)return;_t()}};function aa(a){const{data:n}=a;if(n.type==="DECODER_INPUT"){const{timeCode:o,arrayBuffer:d}=n;W&&D(W,"Decoder")&&console.log("[DecoderWorker] Received ArrayBuffer from Downloader, timeCode =",o),Se.addJob(o,d)}}function da(a){const{data:n}=a;if(n.type==="DECODER_REQUEST"){const{timeCode:o,fps:d}=n;W&&D(W,"Decoder")&&console.log("[DecoderWorker] Received TimeCode request from Renderer, timeCode =",o),Se.updateCurrentTimecode(o,d)}}function _t(){W&&(Se.stop(),Se=new Wt(Jt,_t,W))}function Jt(a){if(!pt)return;W&&D(W,"Decoder")&&console.log(`[DecoderWorker] Posting a batch of ${a.length} frames to Renderer`);const n=a.map(o=>o.alphaMask).filter(o=>o!==void 0);try{const o=new Set(n);pt.postMessage({type:"RENDERER_INPUT",batch:a},[...o]),n.forEach(d=>d.close())}catch(o){console.error("[DecoderWorker] Error posting batch to Renderer:",o),n.forEach(d=>d.close());return}}self.onunhandledrejection=a=>{console.error("[Worker] Unhandled rejection:",a.reason),W&&(Se.stop(),Se=new Wt(Jt,_t,W))}})();\n',Bt=typeof self<"u"&&self.Blob&&new Blob([Mt],{type:"text/javascript;charset=utf-8"});function cr(t){let e;try{if(e=Bt&&(self.URL||self.webkitURL).createObjectURL(Bt),!e)throw"";const n=new Worker(e,{name:t==null?void 0:t.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Mt),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const Nt='(function(){"use strict";const C=(e,t)=>!e.debug||!e.debug.on?!1:e.debug[`log${t}`],y={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},D=console,Y={};Object.keys(y).forEach(e=>{Y[e]=D[e]});const de="Datadog Browser SDK:",_={debug:Y.debug.bind(D,de),log:Y.log.bind(D,de),info:Y.info.bind(D,de),warn:Y.warn.bind(D,de),error:Y.error.bind(D,de)},tt="https://docs.datadoghq.com",kt=`${tt}/real_user_monitoring/browser/troubleshooting`,we="More details:";function Mt(e,t){return(...n)=>{try{return e(...n)}catch(r){_.error(t,r)}}}function ve(e){return e!==0&&Math.random()*100<=e}function Kn(e){return Vn(e)&&e>=0&&e<=100}function Vn(e){return typeof e=="number"}const fe=1e3,X=60*fe,Ut=60*X,qn=365*(24*Ut);function he(){return new Date().getTime()}function B(){return he()}function Le(){return performance.now()}function F(){return{relative:Le(),timeStamp:B()}}function Jn(){return{relative:0,timeStamp:Pt()}}function Qn(e,t){return t-e}function Zn(e,t){return e+t}function er(e){return e-Pt()}let nt;function Pt(){return nt===void 0&&(nt=performance.timing.navigationStart),nt}const k=1024,Nt=1024*k,tr=/[^\\u0000-\\u007F]/;function rt(e){return tr.test(e)?window.TextEncoder!==void 0?new TextEncoder().encode(e).length:new Blob([e]).size:e.length}function nr(e){return{...e}}function Bt(e,t){return Object.keys(e).some(n=>e[n]===t)}function pe(e){return Object.keys(e).length===0}function $(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let e=_dd_temp_;return delete Object.prototype._dd_temp_,typeof e!="object"&&(typeof self=="object"?e=self:typeof window=="object"?e=window:e={}),e}function ne(e,t){const n=$();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=e[n.Zone.__symbol__(t)]),r||(r=e[t]),r}let Oe,Ft=!1;function rr(e){Oe=e}function or(e){Ft=e}function sr(e,t,n){const r=n.value;n.value=function(...o){return(Oe?b(r):r).apply(this,o)}}function b(e){return function(){return me(e,this,arguments)}}function me(e,t,n){try{return e.apply(t,n)}catch(r){ir(r)}}function ir(e){if(ot(e),Oe)try{Oe(e)}catch(t){ot(t)}}function ot(...e){Ft&&_.error("[MONITOR]",...e)}function ge(e,t){return ne($(),"setTimeout")(b(e),t)}function $t(e){ne($(),"clearTimeout")(e)}function st(e,t){return ne($(),"setInterval")(b(e),t)}function Gt(e){ne($(),"clearInterval")(e)}class T{constructor(t){this.onFirstSubscribe=t,this.observers=[]}subscribe(t){return this.observers.push(t),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(n=>t!==n),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(t){this.observers.forEach(n=>n(t))}}function jt(...e){return new T(t=>{const n=e.map(r=>r.subscribe(o=>t.notify(o)));return()=>n.forEach(r=>r.unsubscribe())})}function Ht(e,t,n){let r=!1,o,i;return{throttled:(...s)=>{if(r){o=s;return}e(...s),r=!0,i=ge(()=>{o&&e(...o),r=!1,o=void 0},t)},cancel:()=>{$t(i),r=!1,o=void 0}}}function G(){}function j(e){return e?(parseInt(e,10)^Math.random()*16>>parseInt(e,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,j)}const Ie=/([\\w-]+)\\s*=\\s*([^;]+)/g;function ar(e,t){for(Ie.lastIndex=0;;){const n=Ie.exec(e);if(n){if(n[1]===t)return n[2]}else break}}function cr(e){const t=new Map;for(Ie.lastIndex=0;;){const n=Ie.exec(e);if(n)t.set(n[1],n[2]);else break}return t}function ur(e,t,n=""){const r=e.charCodeAt(t-1),i=r>=55296&&r<=56319?t+1:t;return e.length<=i?e:`${e.slice(0,i)}${n}`}function lr(){return dr()===0}let De;function dr(){return De??(De=fr())}function fr(e=window){var t;const n=e.navigator.userAgent;return e.chrome||/HeadlessChrome/.test(n)?0:((t=e.navigator.vendor)===null||t===void 0?void 0:t.indexOf("Apple"))===0||/safari/i.test(n)&&!/chrome|android/i.test(n)?1:2}function Ee(e,t,n=0,r){const o=new Date;o.setTime(o.getTime()+n);const i=`expires=${o.toUTCString()}`,s=r&&r.crossSite?"none":"strict",a=r&&r.domain?`;domain=${r.domain}`:"",c=r&&r.secure?";secure":"",l=r&&r.partitioned?";partitioned":"";document.cookie=`${e}=${t};${i};path=/;samesite=${s}${a}${c}${l}`}function it(e){return ar(document.cookie,e)}let at;function K(e){return at||(at=cr(document.cookie)),at.get(e)}function zt(e,t){Ee(e,"",0,t)}function hr(e){if(document.cookie===void 0||document.cookie===null)return!1;try{const t=`dd_cookie_test_${j()}`,n="test";Ee(t,n,X,e);const r=it(t)===n;return zt(t,e),r}catch(t){return _.error(t),!1}}let ct;function pr(){if(ct===void 0){const e=`dd_site_test_${j()}`,t="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!it(e);)r=`${n.pop()}.${r}`,Ee(e,t,fe,{domain:r});zt(e,{domain:r}),ct=r}return ct}const re="_dd_s";function ke(e){return Object.values(e)}function mr(e){return Object.entries(e)}const ut=4*Ut,Wt=15*X,gr=qn,be={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},Yt=/^([a-zA-Z]+)=([a-z0-9-]+)$/,lt="&";function Er(e){return!!e&&(e.indexOf(lt)!==-1||Yt.test(e))}const br="1";function V(e,t){const n={isExpired:br};return t.trackAnonymousUser&&(e!=null&&e.anonymousId?n.anonymousId=e==null?void 0:e.anonymousId:n.anonymousId=j()),n}function Me(e){return pe(e)}function Xt(e){return!Me(e)}function Ue(e){return e.isExpired!==void 0||!Sr(e)}function Sr(e){return(e.created===void 0||he()-Number(e.created)<ut)&&(e.expire===void 0||he()<Number(e.expire))}function Kt(e){e.expire=String(he()+Wt)}function dt(e){return mr(e).map(([t,n])=>t==="anonymousId"?`aid=${n}`:`${t}=${n}`).join(lt)}function Vt(e){const t={};return Er(e)&&e.split(lt).forEach(n=>{const r=Yt.exec(n);if(r!==null){const[,o,i]=r;o==="aid"?t.anonymousId=i:t[o]=i}}),t}const yr="_dd",_r="_dd_r",Rr="_dd_l",Tr="rum",Ar="logs";function Cr(e){if(!K(re)){const n=K(yr),r=K(_r),o=K(Rr),i={};n&&(i.id=n),o&&/^[01]$/.test(o)&&(i[Ar]=o),r&&/^[012]$/.test(r)&&(i[Tr]=r),Xt(i)&&(Kt(i),e.persistSession(i))}}function qt(e){const t=Or(e);return hr(t)?{type:be.COOKIE,cookieOptions:t}:void 0}function xr(e,t){const n={isLockEnabled:lr(),persistSession:wr(t),retrieveSession:Lr,expireSession:r=>vr(t,r,e)};return Cr(n),n}function wr(e){return t=>{Ee(re,dt(t),Wt,e)}}function vr(e,t,n){const r=V(t,n);Ee(re,dt(r),n.trackAnonymousUser?gr:ut,e)}function Lr(){const e=it(re);return Vt(e)}function Or(e){const t={};return t.secure=!!e.useSecureSessionCookie||!!e.usePartitionedCrossSiteSessionCookie,t.crossSite=!!e.usePartitionedCrossSiteSessionCookie,t.partitioned=!!e.usePartitionedCrossSiteSessionCookie,e.trackSessionAcrossSubdomains&&(t.domain=pr()),t}const Ir="_dd_test_";function Jt(){try{const e=j(),t=`${Ir}${e}`;localStorage.setItem(t,e);const n=localStorage.getItem(t);return localStorage.removeItem(t),e===n?{type:be.LOCAL_STORAGE}:void 0}catch{return}}function Dr(e){return{isLockEnabled:!1,persistSession:Qt,retrieveSession:kr,expireSession:t=>Mr(t,e)}}function Qt(e){localStorage.setItem(re,dt(e))}function kr(){const e=localStorage.getItem(re);return Vt(e)}function Mr(e,t){Qt(V(e,t))}const Ur=10,Pr=100,Zt=[];let Pe;function q(e,t,n=0){var r;const{isLockEnabled:o,persistSession:i,expireSession:s}=t,a=f=>i({...f,lock:l}),c=()=>{const f=t.retrieveSession(),p=f.lock;return f.lock&&delete f.lock,{session:f,lock:p}};if(Pe||(Pe=e),e!==Pe){Zt.push(e);return}if(o&&n>=Pr){en(t);return}let l,u=c();if(o){if(u.lock){Ne(e,t,n);return}if(l=j(),a(u.session),u=c(),u.lock!==l){Ne(e,t,n);return}}let d=e.process(u.session);if(o&&(u=c(),u.lock!==l)){Ne(e,t,n);return}if(d&&(Ue(d)?s(d):(Kt(d),o?a(d):i(d))),o&&!(d&&Ue(d))){if(u=c(),u.lock!==l){Ne(e,t,n);return}i(u.session),d=u.session}(r=e.after)===null||r===void 0||r.call(e,d||u.session),en(t)}function Ne(e,t,n){ge(()=>{q(e,t,n+1)},Ur)}function en(e){Pe=void 0;const t=Zt.shift();t&&q(t,e)}const tn=fe;function Nr(e){switch(e.sessionPersistence){case be.COOKIE:return qt(e);case be.LOCAL_STORAGE:return Jt();case void 0:{let t=qt(e);return!t&&e.allowFallbackToLocalStorage&&(t=Jt()),t}default:_.error(`Invalid session persistence \'${String(e.sessionPersistence)}\'`)}}function Br(e,t,n,r){const o=new T,i=new T,s=new T,a=e.type===be.COOKIE?xr(t,e.cookieOptions):Dr(t),{expireSession:c}=a,l=st(h,tn);let u;S();const{throttled:d,cancel:f}=Ht(()=>{q({process:g=>{if(Me(g))return;const W=E(g);return le(W),W},after:g=>{Xt(g)&&!N()&&xe(g),u=g}},a)},tn);function p(){q({process:g=>N()?E(g):void 0},a)}function h(){q({process:g=>Ue(g)?V(g,t):void 0,after:E},a)}function E(g){return Ue(g)&&(g=V(g,t)),N()&&(v(g)?Ce():(s.notify({previousState:u,newState:g}),u=g)),g}function S(){q({process:g=>{if(Me(g))return V(g,t)},after:g=>{u=g}},a)}function le(g){if(Me(g))return!1;const{trackingType:W,isTracked:Dt}=r(g[n]);g[n]=W,delete g.isExpired,Dt&&!g.id&&(g.id=j(),g.created=String(he()))}function N(){return u[n]!==void 0}function v(g){return u.id!==g.id||u[n]!==g[n]}function Ce(){u=V(u,t),i.notify()}function xe(g){u=g,o.notify()}function et(g){q({process:W=>({...W,...g}),after:E},a)}return{expandOrRenewSession:d,expandSession:p,getSession:()=>u,renewObservable:o,expireObservable:i,sessionStateUpdateObservable:s,restartSession:S,expire:()=>{f(),c(u),E(V(u,t))},stop:()=>{Gt(l)},updateSessionState:et}}const ft={GRANTED:"granted",NOT_GRANTED:"not-granted"};function Fr(e){const t=new T;return{tryToInit(n){e||(e=n)},update(n){e=n,t.notify()},isGranted(){return e===ft.GRANTED},observable:t}}function J(e,t,n){if(typeof e!="object"||e===null)return JSON.stringify(e);const r=oe(Object.prototype),o=oe(Array.prototype),i=oe(Object.getPrototypeOf(e)),s=oe(e);try{return JSON.stringify(e,t,n)}catch{return"<error: unable to serialize object>"}finally{r(),o(),i(),s()}}function oe(e){const t=e,n=t.toJSON;return n?(delete t.toJSON,()=>{t.toJSON=n}):G}function ht(e){return $r(e,location.href).href}function $r(e,t){const n=Gr();if(n)try{return t!==void 0?new n(e,t):new n(e)}catch(i){throw new Error(`Failed to construct URL: ${String(i)} ${J({url:e,base:t})}`)}if(t===void 0&&!/:/.test(e))throw new Error(`Invalid URL: \'${e}\'`);let r=document;const o=r.createElement("a");if(t!==void 0){r=document.implementation.createHTMLDocument("");const i=r.createElement("base");i.href=t,r.head.appendChild(i),r.body.appendChild(o)}return o.href=e,o}const nn=URL;let Be;function Gr(){if(Be===void 0)try{Be=new nn("http://test/path").href==="http://test/path"}catch{Be=!1}return Be?nn:void 0}const jr="datad0g.com",Hr="dd0g-gov.com",se="datadoghq.com",zr="ddog-gov.com",Wr="pci.browser-intake-datadoghq.com",Yr=["ddsource","ddtags"];function Se(e,t,n){const r=Xr(e,t);return{build(o,i){const s=Vr(e,t,n,o,i);return r(s)},urlPrefix:r(""),trackType:t}}function Xr(e,t){const n=`/api/v2/${t}`,r=e.proxy;if(typeof r=="string"){const i=ht(r);return s=>`${i}?ddforward=${encodeURIComponent(`${n}?${s}`)}`}if(typeof r=="function")return i=>r({path:n,parameters:i});const o=Kr(t,e);return i=>`https://${o}${n}?${i}`}function Kr(e,t){const{site:n=se,internalAnalyticsSubdomain:r}=t;if(e==="logs"&&t.usePciIntake&&n===se)return Wr;if(r&&n===se)return`${r}.${se}`;if(n===Hr)return`http-intake.logs.${n}`;const o=n.split("."),i=o.pop();return`browser-intake-${o.join("-")}.${i}`}function Vr({clientToken:e,internalAnalyticsSubdomain:t},n,r,o,{retry:i,encoding:s}){const a=["sdk_version:6.5.0",`api:${o}`].concat(r);i&&a.push(`retry_count:${i.count}`,`retry_after:${i.lastFailureStatus}`);const c=["ddsource=browser",`ddtags=${encodeURIComponent(a.join(","))}`,`dd-api-key=${e}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${j()}`];return s&&c.push(`dd-evp-encoding=${s}`),n==="rum"&&c.push(`batch_time=${B()}`),t&&c.reverse(),c.join("&")}const qr=200;function Jr(e){const{env:t,service:n,version:r,datacenter:o}=e,i=[];return t&&i.push(Fe("env",t)),n&&i.push(Fe("service",n)),r&&i.push(Fe("version",r)),o&&i.push(Fe("datacenter",o)),i}function Fe(e,t){const n=qr-e.length-1;(t.length>n||Qr(t))&&_.warn(`${e} value doesn\'t meet tag requirements and will be sanitized. ${we} ${tt}/getting_started/tagging/#defining-tags`);const r=t.replace(/,/g,"_");return`${e}:${r}`}function Qr(e){return Zr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(e):!1}function Zr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function eo(e){const t=e.site||se,n=Jr(e),r=to(e,n);return{replica:no(e,n),site:t,...r}}function to(e,t){return{logsEndpointBuilder:Se(e,"logs",t),rumEndpointBuilder:Se(e,"rum",t),sessionReplayEndpointBuilder:Se(e,"replay",t)}}function no(e,t){if(!e.replica)return;const n={...e,site:se,clientToken:e.replica.clientToken},r={logsEndpointBuilder:Se(n,"logs",t),rumEndpointBuilder:Se(n,"rum",t)};return{applicationId:e.replica.applicationId,...r}}function ro(e){return Yr.every(t=>e.includes(t))}function pt(e,t){return e!=null&&typeof e!="string"?(_.error(`${t} must be defined as a string`),!1):!0}function oo(e){return e&&typeof e=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(e)?(_.error(`Site should be a valid Datadog site. ${we} ${tt}/getting_started/site/.`),!1):!0}function $e(e,t){return e!==void 0&&!Kn(e)?(_.error(`${t} Sample Rate should be a number between 0 and 100`),!1):!0}function so(e){var t,n,r,o,i,s;if(!e||!e.clientToken){_.error("Client Token is not configured, we will not send any data.");return}if(!(!oo(e.site)||!$e(e.sessionSampleRate,"Session")||!$e(e.telemetrySampleRate,"Telemetry")||!$e(e.telemetryConfigurationSampleRate,"Telemetry Configuration")||!$e(e.telemetryUsageSampleRate,"Telemetry Usage")||!pt(e.version,"Version")||!pt(e.env,"Env")||!pt(e.service,"Service"))){if(e.trackingConsent!==void 0&&!Bt(ft,e.trackingConsent)){_.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:e.beforeSend&&Mt(e.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:Nr(e),sessionSampleRate:(t=e.sessionSampleRate)!==null&&t!==void 0?t:100,telemetrySampleRate:(n=e.telemetrySampleRate)!==null&&n!==void 0?n:20,telemetryConfigurationSampleRate:(r=e.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(o=e.telemetryUsageSampleRate)!==null&&o!==void 0?o:5,service:e.service||void 0,silentMultipleInit:!!e.silentMultipleInit,allowUntrustedEvents:!!e.allowUntrustedEvents,trackingConsent:(i=e.trackingConsent)!==null&&i!==void 0?i:ft.GRANTED,trackAnonymousUser:(s=e.trackAnonymousUser)!==null&&s!==void 0?s:!0,storeContextsAcrossPages:!!e.storeContextsAcrossPages,batchBytesLimit:16*k,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*fe,batchMessagesLimit:50,messageBytesLimit:256*k,...eo(e)}}}function io(e){return{session_sample_rate:e.sessionSampleRate,telemetry_sample_rate:e.telemetrySampleRate,telemetry_configuration_sample_rate:e.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:e.telemetryUsageSampleRate,use_before_send:!!e.beforeSend,use_partitioned_cross_site_session_cookie:e.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:e.useSecureSessionCookie,use_proxy:!!e.proxy,silent_multiple_init:e.silentMultipleInit,track_session_across_subdomains:e.trackSessionAcrossSubdomains,track_anonymous_user:e.trackAnonymousUser,session_persistence:e.sessionPersistence,allow_fallback_to_local_storage:!!e.allowFallbackToLocalStorage,store_contexts_across_pages:!!e.storeContextsAcrossPages,allow_untrusted_events:!!e.allowUntrustedEvents,tracking_consent:e.trackingConsent}}var mt;(function(e){e.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",e.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(mt||(mt={}));const rn=new Set;function ao(e){Array.isArray(e)&&co(e.filter(t=>Bt(mt,t)))}function co(e){e.forEach(t=>{rn.add(t)})}function uo(){return rn}const ye="?";function M(e){const t=[];let n=gt(e,"stack");const r=String(e);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`\n`).forEach(o=>{const i=ho(o)||mo(o)||Eo(o)||yo(o);i&&(!i.func&&i.line&&(i.func=ye),t.push(i))}),{message:gt(e,"message"),name:gt(e,"name"),stack:t}}const on="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",ie="(?::(\\\\d+))",lo=new RegExp(`^\\\\s*at (.*?) ?\\\\(${on}${ie}?${ie}?\\\\)?\\\\s*$`,"i"),fo=new RegExp(`\\\\((\\\\S*)${ie}${ie}\\\\)`);function ho(e){const t=lo.exec(e);if(!t)return;const n=t[2]&&t[2].indexOf("native")===0,r=t[2]&&t[2].indexOf("eval")===0,o=fo.exec(t[2]);return r&&o&&(t[2]=o[1],t[3]=o[2],t[4]=o[3]),{args:n?[t[2]]:[],column:t[4]?+t[4]:void 0,func:t[1]||ye,line:t[3]?+t[3]:void 0,url:n?void 0:t[2]}}const po=new RegExp(`^\\\\s*at ?${on}${ie}?${ie}??\\\\s*$`,"i");function mo(e){const t=po.exec(e);if(t)return{args:[],column:t[3]?+t[3]:void 0,func:ye,line:t[2]?+t[2]:void 0,url:t[1]}}const go=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function Eo(e){const t=go.exec(e);if(t)return{args:[],column:t[4]?+t[4]:void 0,func:t[1]||ye,line:+t[3],url:t[2]}}const bo=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,So=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function yo(e){const t=bo.exec(e);if(!t)return;const n=t[3]&&t[3].indexOf(" > eval")>-1,r=So.exec(t[3]);return n&&r&&(t[3]=r[1],t[4]=r[2],t[5]=void 0),{args:t[2]?t[2].split(","):[],column:t[5]?+t[5]:void 0,func:t[1]||ye,line:t[4]?+t[4]:void 0,url:t[3]}}function gt(e,t){if(typeof e!="object"||!e||!(t in e))return;const n=e[t];return typeof n=="string"?n:void 0}function _o(e,t,n,r){const o=[{url:t,column:r,line:n}],{name:i,message:s}=To(e);return{name:i,message:s,stack:o}}const Ro=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function To(e){let t,n;return{}.toString.call(e)==="[object String]"&&([,t,n]=Ro.exec(e)),{name:t,message:n}}function Ge(e){const n=new Error(e);n.name="HandlingStack";let r;return me(()=>{const o=M(n);o.stack=o.stack.slice(2),r=Q(o)}),r}function Q(e){let t=sn(e);return e.stack.forEach(n=>{const r=n.func==="?"?"<anonymous>":n.func,o=n.args&&n.args.length>0?`(${n.args.join(", ")})`:"",i=n.line?`:${n.line}`:"",s=n.line&&n.column?`:${n.column}`:"";t+=`\n at ${r}${o} @ ${n.url}${i}${s}`}),t}function sn(e){return`${e.name||"Error"}: ${e.message}`}function Z(e,t,n,{computeHandlingStack:r}={}){let o=e[t];if(typeof o!="function")if(t in e&&t.startsWith("on"))o=G;else return{stop:G};let i=!1;const s=function(){if(i)return o.apply(this,arguments);const a=Array.from(arguments);let c;me(n,null,[{target:this,parameters:a,onPostCall:u=>{c=u},handlingStack:r?Ge("instrumented method"):void 0}]);const l=o.apply(this,a);return c&&me(c,null,[l]),l};return e[t]=s,{stop:()=>{i=!0,e[t]===s&&(e[t]=o)}}}const Ao=220*k,Co="$",xo=3;function U(e,t=Ao){const n=oe(Object.prototype),r=oe(Array.prototype),o=[],i=new WeakMap,s=Et(e,Co,void 0,o,i),a=JSON.stringify(s);let c=a?a.length:0;if(c>t){St(t,"discarded",e);return}for(;o.length>0&&c<t;){const l=o.shift();let u=0;if(Array.isArray(l.source))for(let d=0;d<l.source.length;d++){const f=Et(l.source[d],l.path,d,o,i);if(f!==void 0?c+=JSON.stringify(f).length:c+=4,c+=u,u=1,c>t){St(t,"truncated",e);break}l.target[d]=f}else for(const d in l.source)if(Object.prototype.hasOwnProperty.call(l.source,d)){const f=Et(l.source[d],l.path,d,o,i);if(f!==void 0&&(c+=JSON.stringify(f).length+u+d.length+xo,u=1),c>t){St(t,"truncated",e);break}l.target[d]=f}}return n(),r(),s}function Et(e,t,n,r,o){const i=Lo(e);if(!i||typeof i!="object")return wo(i);const s=bt(i);if(s!=="[Object]"&&s!=="[Array]"&&s!=="[Error]")return s;const a=e;if(o.has(a))return`[Reference seen at ${o.get(a)}]`;const c=n!==void 0?`${t}.${n}`:t,l=Array.isArray(i)?[]:{};return o.set(a,c),r.push({source:i,target:l,path:c}),l}function wo(e){return typeof e=="bigint"?`[BigInt] ${e.toString()}`:typeof e=="function"?`[Function] ${e.name||"unknown"}`:typeof e=="symbol"?`[Symbol] ${e.description||e.toString()}`:e}function bt(e){try{if(e instanceof Event)return vo(e);if(e instanceof RegExp)return`[RegExp] ${e.toString()}`;const n=Object.prototype.toString.call(e).match(/\\[object (.*)\\]/);if(n&&n[1])return`[${n[1]}]`}catch{}return"[Unserializable]"}function vo(e){return{type:e.type,isTrusted:e.isTrusted,currentTarget:e.currentTarget?bt(e.currentTarget):null,target:e.target?bt(e.target):null}}function Lo(e){const t=e;if(t&&typeof t.toJSON=="function")try{return t.toJSON()}catch{}return e}function St(e,t,n){_.warn(`The data provided has been ${t} as it is over the limit of ${e} characters:`,n)}const an="No stack, consider using an instance of Error";function cn({stackTrace:e,originalError:t,handlingStack:n,componentStack:r,startClocks:o,nonErrorPrefix:i,source:s,handling:a}){const c=H(t),l=Oo(e,c,i,t),u=Io(c,e)?Q(e):an,d=c?dn(t,s):void 0,f=e?e.name:void 0,p=un(t),h=ln(t);return{startClocks:o,source:s,handling:a,handlingStack:n,componentStack:r,originalError:t,type:f,message:l,stack:u,causes:d,fingerprint:p,context:h}}function Oo(e,t,n,r){return e!=null&&e.message&&(e!=null&&e.name)?e.message:t?"Empty message":`${n} ${J(U(r))}`}function Io(e,t){return t===void 0?!1:e?!0:t.stack.length>0&&(t.stack.length>1||t.stack[0].url!==void 0)}function un(e){return H(e)&&"dd_fingerprint"in e?String(e.dd_fingerprint):void 0}function ln(e){if(e!==null&&typeof e=="object"&&"dd_context"in e)return e.dd_context}function Do(e){var t;return(t=/@ (.+)/.exec(e))===null||t===void 0?void 0:t[1]}function H(e){return e instanceof Error||Object.prototype.toString.call(e)==="[object Error]"}function dn(e,t){let n=e;const r=[];for(;H(n==null?void 0:n.cause)&&r.length<10;){const o=M(n.cause);r.push({message:n.cause.message,source:t,type:o==null?void 0:o.name,stack:Q(o)}),n=n.cause}return r.length?r:void 0}const L={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function ko(e){const t=(o,i)=>{const s=cn({stackTrace:o,originalError:i,startClocks:F(),nonErrorPrefix:"Uncaught",source:L.SOURCE,handling:"unhandled"});e.notify(s)},{stop:n}=Mo(t),{stop:r}=Uo(t);return{stop:()=>{n(),r()}}}function Mo(e){return Z(window,"onerror",({parameters:[t,n,r,o,i]})=>{let s;H(i)?s=M(i):s=_o(t,n,r,o),e(s,i??t)})}function Uo(e){return Z(window,"onunhandledrejection",({parameters:[t]})=>{const n=t.reason||"Empty reason",r=M(n);e(r,n)})}function Po(e){const t={version:"6.5.0",onReady(n){n()},...e};return Object.defineProperty(t,"_setDebug",{get(){return or},enumerable:!1}),t}function No(e,t,n){const r=e[t];r&&!r.q&&r.version&&_.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),e[t]=n,r&&r.q&&r.q.forEach(o=>Mt(o,"onReady callback threw an error:")())}function fn(e,t){t.silentMultipleInit||_.error(`${e} is already initialized.`)}function ee(e,t,n,r,o){return yt(e,t,[n],r,o)}function yt(e,t,n,r,{once:o,capture:i,passive:s}={}){const a=b(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!e.allowUntrustedEvents||(o&&d(),r(f))}),c=s?{capture:i,passive:s}:i,l=window.EventTarget&&t instanceof EventTarget?window.EventTarget.prototype:t,u=ne(l,"addEventListener");n.forEach(f=>u.call(t,f,a,c));function d(){const f=ne(l,"removeEventListener");n.forEach(p=>f.call(t,p,a,c))}return{stop:d}}const je={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function Bo(e,t){const n=[];t.includes(je.cspViolation)&&n.push($o(e));const r=t.filter(o=>o!==je.cspViolation);return r.length&&n.push(Fo(r)),jt(...n)}function Fo(e){return new T(t=>{if(!window.ReportingObserver)return;const n=b((o,i)=>o.forEach(s=>t.notify(Go(s)))),r=new window.ReportingObserver(n,{types:e,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function $o(e){return new T(t=>{const{stop:n}=ee(e,document,"securitypolicyviolation",r=>{t.notify(jo(r))});return n})}function Go(e){const{type:t,body:n}=e;return hn({type:n.id,message:`${t}: ${n.message}`,originalError:e,stack:pn(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function jo(e){const t=`\'${e.blockedURI}\' blocked by \'${e.effectiveDirective}\' directive`;return hn({type:e.effectiveDirective,message:`${je.cspViolation}: ${t}`,originalError:e,csp:{disposition:e.disposition},stack:pn(e.effectiveDirective,e.originalPolicy?`${t} of the policy "${ur(e.originalPolicy,100,"...")}"`:"no policy",e.sourceFile,e.lineNumber,e.columnNumber)})}function hn(e){return{startClocks:F(),source:L.REPORT,handling:"unhandled",...e}}function pn(e,t,n,r,o){return n?Q({name:e,message:t,stack:[{func:"?",url:n,line:r??void 0,column:o??void 0}]}):void 0}function mn(e,t){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:e,payload:t})}function gn(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function He(e,t,n=Ho()){if(t===void 0)return e;if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=t.flags||[t.global?"g":"",t.ignoreCase?"i":"",t.multiline?"m":"",t.sticky?"y":"",t.unicode?"u":""].join("");return new RegExp(t.source,o)}if(n.hasAlreadyBeenSeen(t))return;if(Array.isArray(t)){const o=Array.isArray(e)?e:[];for(let i=0;i<t.length;++i)o[i]=He(o[i],t[i],n);return o}const r=gn(e)==="object"?e:{};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=He(r[o],t[o],n));return r}function En(e){return He(void 0,e)}function ae(...e){let t;for(const n of e)n!=null&&(t=He(t,n));return t}function Ho(){if(typeof WeakSet<"u"){const t=new WeakSet;return{hasAlreadyBeenSeen(n){const r=t.has(n);return r||t.add(n),r}}}const e=[];return{hasAlreadyBeenSeen(t){const n=e.indexOf(t)>=0;return n||e.push(t),n}}}function zo(){var e;const t=window.navigator;return{status:t.onLine?"connected":"not_connected",interfaces:t.connection&&t.connection.type?[t.connection.type]:void 0,effective_type:(e=t.connection)===null||e===void 0?void 0:e.effectiveType}}function Wo(e){const t=new Set;return e.forEach(n=>t.add(n)),Array.from(t)}function bn(e,t){const n=e.indexOf(t);n>=0&&e.splice(n,1)}const Yo=500;function Sn(){const e=[];return{add:o=>{e.push(o)>Yo&&e.splice(0,1)},remove:o=>{bn(e,o)},drain:o=>{e.forEach(i=>i(o)),e.length=0}}}const te={log:"log",configuration:"configuration",usage:"usage"},Xo=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],Ko=[zr];let yn=Sn(),ce=e=>{yn.add(()=>ce(e))};function Vo(e,t){let n;const r=new T,o=new Set,i=!Ko.includes(t.site)&&ve(t.telemetrySampleRate),s={[te.log]:i,[te.configuration]:i&&ve(t.telemetryConfigurationSampleRate),[te.usage]:i&&ve(t.telemetryUsageSampleRate)},a=qo();ce=l=>{const u=J(l);if(s[l.type]&&o.size<t.maxTelemetryEventsPerPage&&!o.has(u)){const d=c(e,l,a);r.notify(d),mn("telemetry",d),o.add(u)}},rr(Rn);function c(l,u,d){return ae({type:"telemetry",date:B(),service:l,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:ae(u,{runtime_env:d,connectivity:zo(),sdk_setup:"npm"}),experimental_features:Array.from(uo())},n!==void 0?n():{})}return{setContextProvider:l=>{n=l},observable:r,enabled:i}}function qo(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function Jo(){yn.drain()}function Qo(e){return e.site===jr}function _n(e,t){ot(y.debug,e,t),ce({type:te.log,message:e,status:"debug",...t})}function Rn(e,t){ce({type:te.log,status:"error",...ts(e),...t})}function Zo(e){ce({type:te.configuration,configuration:e})}function es(e){ce({type:te.usage,usage:e})}function ts(e){if(H(e)){const t=M(e);return{error:{kind:t.name,stack:Q(ns(t))},message:t.message}}return{error:{stack:an},message:`Uncaught ${J(e)}`}}function ns(e){return e.stack=e.stack.filter(t=>!t.url||Xo.some(n=>t.url.startsWith(n))),e}const _e=1/0,rs=X;let Re=null;const ze=new Set;function os(){ze.forEach(e=>e())}function ss({expireDelay:e,maxEntries:t}){let n=[];const r=[];Re||(Re=st(()=>os(),rs));const o=()=>{const p=Le()-e;for(;n.length>0&&n[n.length-1].endTime<p;){const h=n.pop();h&&r.push(h.startTime)}};ze.add(o);function i(p,h){const E={value:p,startTime:h,endTime:_e,remove:()=>{bn(n,E)},close:S=>{E.endTime=S}};return t&&n.length>=t&&n.pop(),n.unshift(E),E}function s(p=_e,h={returnInactive:!1}){for(const E of n)if(E.startTime<=p){if(h.returnInactive||p<=E.endTime)return E.value;break}}function a(p){const h=n[0];h&&h.endTime===_e&&h.close(p)}function c(p=_e,h=0){const E=Zn(p,h);return n.filter(S=>S.startTime<=E&&p<=S.endTime).map(S=>S.value)}function l(){return n.map(({startTime:p,endTime:h,value:E})=>({startTime:p,endTime:h===_e?"Infinity":h,value:E}))}function u(){return r}function d(){n=[]}function f(){ze.delete(o),ze.size===0&&Re&&(Gt(Re),Re=null)}return{add:i,find:s,closeActive:a,findAll:c,reset:d,stop:f,getAllEntries:l,getDeletedEntries:u}}const is=X,as=ut;function cs(e,t,n,r){const o=new T,i=new T,s=Br(e.sessionStoreStrategyType,e,t,n),a=ss({expireDelay:as});s.renewObservable.subscribe(()=>{a.add(c(),Le()),o.notify()}),s.expireObservable.subscribe(()=>{i.notify(),a.closeActive(Le())}),s.expandOrRenewSession(),a.add(c(),Jn().relative),r.observable.subscribe(()=>{r.isGranted()?s.expandOrRenewSession():s.expire()}),us(e,()=>{r.isGranted()&&s.expandOrRenewSession()}),ls(e,()=>s.expandSession()),ds(e,()=>s.restartSession());function c(){return{id:s.getSession().id,trackingType:s.getSession()[t],isReplayForced:!!s.getSession().forcedReplay,anonymousId:s.getSession().anonymousId}}return{findSession:(l,u)=>a.find(l,u),renewObservable:o,expireObservable:i,sessionStateUpdateObservable:s.sessionStateUpdateObservable,expire:s.expire,updateSessionState:s.updateSessionState}}function us(e,t){yt(e,window,["click","touchstart","keydown","scroll"],t,{capture:!0,passive:!0})}function ls(e,t){const n=()=>{document.visibilityState==="visible"&&t()};ee(e,document,"visibilitychange",n),st(n,is)}function ds(e,t){ee(e,window,"resume",t,{capture:!0})}function Tn(e){return e>=500}function fs(e){try{return e.clone()}catch{return}}const hs=80*k,ps=32,An=3*Nt,ms=X,Cn=fe;function xn(e,t,n,r,o){t.transportStatus===0&&t.queuedPayloads.size()===0&&t.bandwidthMonitor.canHandle(e)?vn(e,t,n,{onSuccess:()=>Ln(0,t,n,r,o),onFailure:()=>{t.queuedPayloads.enqueue(e),wn(t,n,r,o)}}):t.queuedPayloads.enqueue(e)}function wn(e,t,n,r){e.transportStatus===2&&ge(()=>{const o=e.queuedPayloads.first();vn(o,e,t,{onSuccess:()=>{e.queuedPayloads.dequeue(),e.currentBackoffTime=Cn,Ln(1,e,t,n,r)},onFailure:()=>{e.currentBackoffTime=Math.min(ms,e.currentBackoffTime*2),wn(e,t,n,r)}})},e.currentBackoffTime)}function vn(e,t,n,{onSuccess:r,onFailure:o}){t.bandwidthMonitor.add(e),n(e,i=>{t.bandwidthMonitor.remove(e),gs(i)?(t.transportStatus=t.bandwidthMonitor.ongoingRequestCount>0?1:2,e.retry={count:e.retry?e.retry.count+1:1,lastFailureStatus:i.status},o()):(t.transportStatus=0,r())})}function Ln(e,t,n,r,o){e===0&&t.queuedPayloads.isFull()&&!t.queueFullReported&&(o({message:`Reached max ${r} events size queued for upload: ${An/Nt}MiB`,source:L.AGENT,startClocks:F()}),t.queueFullReported=!0);const i=t.queuedPayloads;for(t.queuedPayloads=On();i.size()>0;)xn(i.dequeue(),t,n,r,o)}function gs(e){return e.type!=="opaque"&&(e.status===0&&!navigator.onLine||e.status===408||e.status===429||Tn(e.status))}function Es(){return{transportStatus:0,currentBackoffTime:Cn,bandwidthMonitor:bs(),queuedPayloads:On(),queueFullReported:!1}}function On(){const e=[];return{bytesCount:0,enqueue(t){this.isFull()||(e.push(t),this.bytesCount+=t.bytesCount)},first(){return e[0]},dequeue(){const t=e.shift();return t&&(this.bytesCount-=t.bytesCount),t},size(){return e.length},isFull(){return this.bytesCount>=An}}}function bs(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(e){return this.ongoingRequestCount===0||this.ongoingByteCount+e.bytesCount<=hs&&this.ongoingRequestCount<ps},add(e){this.ongoingRequestCount+=1,this.ongoingByteCount+=e.bytesCount},remove(e){this.ongoingRequestCount-=1,this.ongoingByteCount-=e.bytesCount}}}function Ss(e,t,n){const r=Es(),o=(i,s)=>Rs(e,t,i,s);return{send:i=>{xn(i,r,o,e.trackType,n)},sendOnExit:i=>{ys(e,t,i)}}}function ys(e,t,n){if(!!navigator.sendBeacon&&n.bytesCount<t)try{const i=e.build("beacon",n);if(navigator.sendBeacon(i,n.data))return}catch(i){_s(i)}const o=e.build("xhr",n);_t(o,n.data)}let In=!1;function _s(e){In||(In=!0,Rn(e))}function Rs(e,t,n,r){if(Ts()&&n.bytesCount<t){const i=e.build("fetch",n);fetch(i,{method:"POST",body:n.data,keepalive:!0,mode:"cors"}).then(b(s=>r==null?void 0:r({status:s.status,type:s.type})),b(()=>{const s=e.build("xhr",n);_t(s,n.data,r)}))}else{const i=e.build("xhr",n);_t(i,n.data,r)}}function Ts(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function _t(e,t,n){const r=new XMLHttpRequest;r.open("POST",e,!0),t instanceof Blob&&r.setRequestHeader("Content-Type",t.type),ee({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(t)}function Rt(){const e=As();if(e)return{getCapabilities(){var t;return JSON.parse(((t=e.getCapabilities)===null||t===void 0?void 0:t.call(e))||"[]")},getPrivacyLevel(){var t;return(t=e.getPrivacyLevel)===null||t===void 0?void 0:t.call(e)},getAllowedWebViewHosts(){return JSON.parse(e.getAllowedWebViewHosts())},send(t,n,r){const o=r?{id:r}:void 0;e.send(JSON.stringify({eventType:t,event:n,view:o}))}}}function We(e){var t;e===void 0&&(e=(t=$().location)===null||t===void 0?void 0:t.hostname);const n=Rt();return!!n&&n.getAllowedWebViewHosts().some(r=>e===r||e.endsWith(`.${r}`))}function As(){return $().DatadogEventBridge}const Ye={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function Cs(e){return new T(t=>{const{stop:n}=yt(e,window,["visibilitychange","freeze"],o=>{o.type==="visibilitychange"&&document.visibilityState==="hidden"?t.notify({reason:Ye.HIDDEN}):o.type==="freeze"&&t.notify({reason:Ye.FROZEN})},{capture:!0}),r=ee(e,window,"beforeunload",()=>{t.notify({reason:Ye.UNLOADING})}).stop;return()=>{n(),r()}})}function xs(e){return ke(Ye).includes(e)}function ws({encoder:e,request:t,flushController:n,messageBytesLimit:r}){let o={};const i=n.flushObservable.subscribe(d=>u(d));function s(d,f,p){n.notifyBeforeAddMessage(f),p!==void 0?(o[p]=d,n.notifyAfterAddMessage()):e.write(e.isEmpty?d:`\n${d}`,h=>{n.notifyAfterAddMessage(h-f)})}function a(d){return d!==void 0&&o[d]!==void 0}function c(d){const f=o[d];delete o[d];const p=e.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(p)}function l(d,f){const p=J(d),h=e.estimateEncodedBytesCount(p);if(h>=r){_.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${we} ${kt}/#technical-limitations`);return}a(f)&&c(f),s(p,h,f)}function u(d){const f=ke(o).join(`\n`);o={};const p=xs(d.reason),h=p?t.sendOnExit:t.send;if(p&&e.isAsync){const E=e.finishSync();E.outputBytesCount&&h(Dn(E));const S=[E.pendingData,f].filter(Boolean).join(`\n`);S&&h({data:S,bytesCount:rt(S)})}else f&&e.write(e.isEmpty?f:`\n${f}`),e.finish(E=>{h(Dn(E))})}return{flushController:n,add:l,upsert:l,stop:i.unsubscribe}}function Dn(e){let t;return typeof e.output=="string"?t=e.output:t=new Blob([e.output],{type:"text/plain"}),{data:t,bytesCount:e.outputBytesCount,encoding:e.encoding}}function vs({messagesLimit:e,bytesLimit:t,durationLimit:n,pageExitObservable:r,sessionExpireObservable:o}){const i=r.subscribe(h=>u(h.reason)),s=o.subscribe(()=>u("session_expire")),a=new T(()=>()=>{i.unsubscribe(),s.unsubscribe()});let c=0,l=0;function u(h){if(l===0)return;const E=l,S=c;l=0,c=0,p(),a.notify({reason:h,messagesCount:E,bytesCount:S})}let d;function f(){d===void 0&&(d=ge(()=>{u("duration_limit")},n))}function p(){$t(d),d=void 0}return{flushObservable:a,get messagesCount(){return l},notifyBeforeAddMessage(h){c+h>=t&&u("bytes_limit"),l+=1,c+=h,f()},notifyAfterAddMessage(h=0){c+=h,l>=e?u("messages_limit"):c>=t&&u("bytes_limit")},notifyAfterRemoveMessage(h){c-=h,l-=1,l===0&&p()}}}function kn(e,t,n,r,o,i,s=ws){const a=l(e,t),c=n&&l(e,n);function l(u,{endpoint:d,encoder:f}){return s({encoder:f,request:Ss(d,u.batchBytesLimit,r),flushController:vs({messagesLimit:u.batchMessagesLimit,bytesLimit:u.batchBytesLimit,durationLimit:u.flushTimeout,pageExitObservable:o,sessionExpireObservable:i}),messageBytesLimit:u.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(u,d=!0){a.add(u),c&&d&&c.add(n.transformMessage?n.transformMessage(u):u)},upsert:(u,d)=>{a.upsert(u,d),c&&c.upsert(n.transformMessage?n.transformMessage(u):u,d)},stop:()=>{a.stop(),c&&c.stop()}}}function Xe(){let e="",t=0;return{isAsync:!1,get isEmpty(){return!e},write(n,r){const o=rt(n);t+=o,e+=n,r&&r(o)},finish(n){n(this.finishSync())},finishSync(){const n={output:e,outputBytesCount:t,rawBytesCount:t,pendingData:""};return e="",t=0,n},estimateEncodedBytesCount(n){return n.length}}}class Ls{constructor(){this.callbacks={}}notify(t,n){const r=this.callbacks[t];r&&r.forEach(o=>o(n))}subscribe(t,n){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(n),{unsubscribe:()=>{this.callbacks[t]=this.callbacks[t].filter(r=>n!==r)}}}}function Os(e,t,n){let r=0,o=!1;return{isLimitReached(){if(r===0&&ge(()=>{r=0},X),r+=1,r<=t||o)return o=!1,!1;if(r===t+1){o=!0;try{n({message:`Reached max number of ${e}s by minute: ${t}`,source:L.AGENT,startClocks:F()})}finally{o=!1}}return!0}}}let Tt;const At=new WeakMap;function Is(e){return Tt||(Tt=Ds(e)),Tt}function Ds(e){return new T(t=>{const{stop:n}=Z(XMLHttpRequest.prototype,"open",ks),{stop:r}=Z(XMLHttpRequest.prototype,"send",i=>{Ms(i,e,t)},{computeHandlingStack:!0}),{stop:o}=Z(XMLHttpRequest.prototype,"abort",Us);return()=>{n(),r(),o()}})}function ks({target:e,parameters:[t,n]}){At.set(e,{state:"open",method:String(t).toUpperCase(),url:ht(String(n))})}function Ms({target:e,handlingStack:t},n,r){const o=At.get(e);if(!o)return;const i=o;i.state="start",i.startClocks=F(),i.isAborted=!1,i.xhr=e,i.handlingStack=t;let s=!1;const{stop:a}=Z(e,"onreadystatechange",()=>{e.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(l(),a(),s)return;s=!0;const u=o;u.state="complete",u.duration=Qn(i.startClocks.timeStamp,B()),u.status=e.status,r.notify(nr(u))},{stop:l}=ee(n,e,"loadend",c);r.notify(i)}function Us({target:e}){const t=At.get(e);t&&(t.isAborted=!0)}let Ct;function Mn(){return Ct||(Ct=Ps()),Ct}function Ps(){return new T(e=>{if(!window.fetch)return;const{stop:t}=Z(window,"fetch",n=>Ns(n,e),{computeHandlingStack:!0});return t})}function Ns({parameters:e,onPostCall:t,handlingStack:n},r){const[o,i]=e;let s=i&&i.method;s===void 0&&o instanceof Request&&(s=o.method);const a=s!==void 0?String(s).toUpperCase():"GET",c=o instanceof Request?o.url:ht(String(o)),l=F(),u={state:"start",init:i,input:o,method:a,startClocks:l,url:c,handlingStack:n};r.notify(u),e[0]=u.input,e[1]=u.init,t(d=>Bs(r,d,u))}function Bs(e,t,n){const r=n;function o(i){r.state="resolve",Object.assign(r,i),e.notify(r)}t.then(b(i=>{o({response:i,responseType:i.type,status:i.status,isAborted:!1})}),b(i=>{var s,a;o({status:0,isAborted:((a=(s=r.init)===null||s===void 0?void 0:s.signal)===null||a===void 0?void 0:a.aborted)||i instanceof DOMException&&i.code===DOMException.ABORT_ERR,error:i})}))}let xt={};function Fs(e){const t=e.map(n=>(xt[n]||(xt[n]=$s(n)),xt[n]));return jt(...t)}function $s(e){return new T(t=>{const n=D[e];return D[e]=(...r)=>{n.apply(console,r);const o=Ge("console error");me(()=>{t.notify(Gs(r,e,o))})},()=>{D[e]=n}})}function Gs(e,t,n){const r=e.map(i=>js(i)).join(" ");let o;if(t===y.error){const i=e.find(H);o={stack:i?Q(M(i)):void 0,fingerprint:un(i),causes:i?dn(i,"console"):void 0,startClocks:F(),message:r,source:L.CONSOLE,handling:"handled",handlingStack:n,context:ln(i)}}return{api:t,message:r,error:o,handlingStack:n}}function js(e){return typeof e=="string"?U(e):H(e)?sn(M(e)):J(U(e),void 0,2)}function Hs(e){const t=gn(e)==="object";return t||_.error("Unsupported context:",e),t}function wt(e,t,n){const r={...e};for(const[o,{required:i,type:s}]of Object.entries(t))s==="string"&&o in r&&(r[o]=String(r[o])),i&&!(o in e)&&_.warn(`The property ${o} of ${n} is required; context will not be sent to the intake.`);return r}function Ke(e="",{customerDataTracker:t,propertiesConfig:n={}}={}){let r={};const o=new T,i={getContext:()=>En(r),setContext:s=>{Hs(s)?(r=U(wt(s,n,e)),t==null||t.updateCustomerData(r)):i.clearContext(),o.notify()},setContextProperty:(s,a)=>{r=U(wt({...r,[s]:a},n,e)),t==null||t.updateCustomerData(r),o.notify()},removeContextProperty:s=>{delete r[s],t==null||t.updateCustomerData(r),wt(r,n,e),o.notify()},clearContext:()=>{r={},t==null||t.resetCustomerData(),o.notify()},changeObservable:o};return i}const zs="_dd_c",Ws=[];function vt(e,t,n,r){const o=Ys(n,r);Ws.push(ee(e,window,"storage",({key:l})=>{o===l&&s()})),t.changeObservable.subscribe(a);const i=ae(c(),t.getContext());pe(i)||t.setContext(i);function s(){t.setContext(c())}function a(){localStorage.setItem(o,JSON.stringify(t.getContext()))}function c(){const l=localStorage.getItem(o);return l?JSON.parse(l):{}}}function Ys(e,t){return`${zs}_${e}_${t}`}const Xs=3*k,Ks=16*k,Vs=200;function qs(e=2){const t=new Map;let n=!1;function r(o=0){if(n||e===0)return;const i=e===2?Xs:Ks;let s=o;t.forEach(a=>{s+=a.getBytesCount()}),s>i&&(Js(i),n=!0)}return{createDetachedTracker:()=>{const o=Un(()=>r(o.getBytesCount()));return o},getOrCreateTracker:o=>(t.has(o)||t.set(o,Un(r)),t.get(o)),setCompressionStatus:o=>{e===0&&(e=o,r())},getCompressionStatus:()=>e,stop:()=>{t.forEach(o=>o.stop()),t.clear()}}}function Un(e){let t=0;const{throttled:n,cancel:r}=Ht(i=>{t=rt(J(i)),e()},Vs),o=()=>{r(),t=0};return{updateCustomerData:i=>{pe(i)?o():n(i)},resetCustomerData:o,getBytesCount:()=>t,stop:()=>{r()}}}function Js(e){_.warn(`Customer data exceeds the recommended ${e/k}KiB threshold. ${we} ${kt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function Qs(e,t,n){const r=e.getReader(),o=[];let i=0;s();function s(){r.read().then(b(c=>{if(c.done){a();return}o.push(c.value),i+=c.value.length,i>n.bytesLimit?a():s()}),b(c=>t(c)))}function a(){r.cancel().catch(G);let c,l;{let u;if(o.length===1)u=o[0];else{u=new Uint8Array(i);let d=0;o.forEach(f=>{u.set(f,d),d+=f.length})}c=u.slice(0,n.bytesLimit),l=u.length>n.bytesLimit}t(void 0,c,l)}}const Zs="datadog-synthetics-public-id",ei="datadog-synthetics-result-id",ti="datadog-synthetics-injects-rum";function Pn(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||K(ti))}function ni(){const e=window._DATADOG_SYNTHETICS_PUBLIC_ID||K(Zs);return typeof e=="string"?e:void 0}function ri(){const e=window._DATADOG_SYNTHETICS_RESULT_ID||K(ei);return typeof e=="string"?e:void 0}function Ve(e,t,n){const r=n.getHandler(),o=Array.isArray(r)?r:[r];return Nn[e]>=Nn[n.getLevel()]&&o.includes(t)}const m={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},Nn={[m.ok]:0,[m.debug]:1,[m.info]:2,[m.notice]:4,[m.warn]:5,[m.error]:6,[m.critical]:7,[m.alert]:8,[m.emerg]:9};function qe(e,{includeMessage:t=!1}={}){return{stack:e.stack,kind:e.type,message:t?e.message:void 0,causes:e.causes,fingerprint:e.fingerprint,handling:e.handling}}var oi=function(e,t,n,r){var o=arguments.length,i=o<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(s=e[a])&&(i=(o<3?s(i):o>3?s(t,n,i):s(t,n))||i);return o>3&&i&&Object.defineProperty(t,n,i),i};const Te={console:"console",http:"http",silent:"silent"},si=Object.keys(m);let O=class{constructor(t,n,r,o=Te.http,i=m.debug,s={}){this.handleLogStrategy=t,this.handlerType=o,this.level=i,this.contextManager=Ke("logger",{customerDataTracker:n}),this.contextManager.setContext(s),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(t,n,r=m.info,o,i){const s=U(n);let a;if(o!=null){const c=cn({stackTrace:H(o)?M(o):void 0,originalError:o,nonErrorPrefix:"Provided",source:L.LOGGER,handling:"handled",startClocks:F()});a=ae({error:qe(c,{includeMessage:!0})},s)}else a=s;this.handleLogStrategy({message:U(t),context:a,status:r},this,i)}log(t,n,r=m.info,o){let i;Ve(r,Te.http,this)&&(i=Ge("log")),this.logImplementation(t,n,r,o,i)}setContext(t){this.contextManager.setContext(t)}getContext(){return this.contextManager.getContext()}setContextProperty(t,n){this.contextManager.setContextProperty(t,n)}removeContextProperty(t){this.contextManager.removeContextProperty(t)}clearContext(){this.contextManager.clearContext()}setHandler(t){this.handlerType=t}getHandler(){return this.handlerType}setLevel(t){this.level=t}getLevel(){return this.level}};oi([sr],O.prototype,"logImplementation",null),O.prototype.ok=P(m.ok),O.prototype.debug=P(m.debug),O.prototype.info=P(m.info),O.prototype.notice=P(m.notice),O.prototype.warn=P(m.warn),O.prototype.error=P(m.error),O.prototype.critical=P(m.critical),O.prototype.alert=P(m.alert),O.prototype.emerg=P(m.emerg);function P(e){return function(t,n,r){let o;Ve(e,Te.http,this)&&(o=Ge("log")),this.logImplementation(t,n,e,r,o)}}function ii(e,t,n){return{view:{referrer:document.referrer,url:window.location.href},context:e.getContext(),user:t.getContext(),account:n.getContext()}}const ai=32*k;function ci(e){e.usePciIntake===!0&&e.site&&e.site!=="datadoghq.com"&&_.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const t=so(e),n=Bn(e.forwardConsoleLogs,ke(y),"Forward Console Logs"),r=Bn(e.forwardReports,ke(je),"Forward Reports");if(!(!t||!n||!r))return e.forwardErrorsToLogs&&!n.includes(y.error)&&n.push(y.error),{forwardErrorsToLogs:e.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:ai,...t}}function Bn(e,t,n){if(e===void 0)return[];if(!(e==="all"||Array.isArray(e)&&e.every(r=>t.includes(r)))){_.error(`${n} should be "all" or an array with allowed values "${t.join(\'", "\')}"`);return}return e==="all"?t:Wo(e)}function ui(e){const t=io(e);return{forward_errors_to_logs:e.forwardErrorsToLogs,forward_console_logs:e.forwardConsoleLogs,forward_reports:e.forwardReports,use_pci_intake:e.usePciIntake,...t}}function li(e,t,n){const r=Sn();let o,i;const s=t.observable.subscribe(a);function a(){if(!i||!o||!t.isGranted())return;s.unsubscribe();const c=n(o,i);r.drain(c)}return{init(c){if(!c){_.error("Missing configuration");return}if(ao(c.enableExperimentalFeatures),We()&&(c=di(c)),o=c,i){fn("DD_LOGS",c);return}const l=ci(c);l&&(i=l,Mn().subscribe(G),t.tryToInit(l.trackingConsent),a())},get initConfiguration(){return o},getInternalContext:G,handleLog(c,l,u,d=e(),f=B()){r.add(p=>p.handleLog(c,l,u,d,f))}}}function di(e){return{...e,clientToken:"empty"}}const Lt="logs";function fi(e){const t=qs(),n=Ke("global context",{customerDataTracker:t.getOrCreateTracker(2)}),r=Ke("user",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),o=Ke("account",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),i=Fr();function s(){return ii(n,r,o)}let a=li(s,i,(u,d)=>{u.storeContextsAcrossPages&&(vt(d,n,Lt,2),vt(d,r,Lt,1),vt(d,o,Lt,4));const f=e(u,d,s,i);return a=hi(u,f),f});const c={},l=new O((...u)=>a.handleLog(...u),t.createDetachedTracker());return Po({logger:l,init:b(u=>a.init(u)),setTrackingConsent:b(u=>{i.update(u),es({feature:"set-tracking-consent",tracking_consent:u})}),getGlobalContext:b(()=>n.getContext()),setGlobalContext:b(u=>n.setContext(u)),setGlobalContextProperty:b((u,d)=>n.setContextProperty(u,d)),removeGlobalContextProperty:b(u=>n.removeContextProperty(u)),clearGlobalContext:b(()=>n.clearContext()),createLogger:b((u,d={})=>(c[u]=new O((...f)=>a.handleLog(...f),t.createDetachedTracker(),U(u),d.handler,d.level,U(d.context)),c[u])),getLogger:b(u=>c[u]),getInitConfiguration:b(()=>En(a.initConfiguration)),getInternalContext:b(u=>a.getInternalContext(u)),setUser:b(r.setContext),getUser:b(r.getContext),setUserProperty:b(r.setContextProperty),removeUserProperty:b(r.removeContextProperty),clearUser:b(r.clearContext),setAccount:b(o.setContext),getAccount:b(o.getContext),setAccountProperty:b(o.setContextProperty),removeAccountProperty:b(o.removeContextProperty),clearAccount:b(o.clearContext)})}function hi(e,t){return{init:n=>{fn("DD_LOGS",n)},initConfiguration:e,...t}}const pi="logs";function mi(e,t){const n=cs(e,pi,r=>Ei(e,r),t);return{findTrackedSession:(r,o={returnInactive:!1})=>{const i=n.findSession(r,o);return i&&i.trackingType==="1"?{id:i.id,anonymousId:i.anonymousId}:void 0},expireObservable:n.expireObservable}}function gi(e){const n=Fn(e)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new T}}function Fn(e){return ve(e.sessionSampleRate)?"1":"0"}function Ei(e,t){const n=bi(t)?t:Fn(e);return{trackingType:n,isTracked:n==="1"}}function bi(e){return e==="0"||e==="1"}let $n=!1;function Je(e){const t=window;if(Pn()){const r=n(t.DD_RUM_SYNTHETICS);return!r&&!$n&&($n=!0,_n("Logs sent before RUM is injected by the synthetics worker",{testId:ni(),resultId:ri()})),r}return n(t.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(e)}}function Si(e,t,n,r,o){const i=si.concat(["custom"]),s={};i.forEach(a=>{s[a]=Os(a,t.eventRateLimiterThreshold,o)}),n.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:l=void 0,domainContext:u})=>{var d,f;const p=er(a.date),h=e.findTrackedSession(p);if(!e.findTrackedSession(p,{returnInactive:!0}))return;const S=l||r();let le;!pe(S.account)&&S.account.id&&(le=S.account),h&&h.anonymousId&&!S.user.anonymous_id&&(S.user.anonymous_id=h.anonymousId);const N=ae({service:t.service,session_id:h?h.id:void 0,session:h?{id:h.id}:void 0,usr:pe(S.user)?void 0:S.user,account:le,view:S.view},S.context,Je(p),a,c);((d=t.beforeSend)===null||d===void 0?void 0:d.call(t,N,u))===!1||N.origin!==L.AGENT&&((f=s[N.status])!==null&&f!==void 0?f:s.custom).isLimitReached()||n.notify(1,N)})}const yi={[y.log]:m.info,[y.debug]:m.debug,[y.info]:m.info,[y.warn]:m.warn,[y.error]:m.error};function _i(e,t){const n=Fs(e.forwardConsoleLogs).subscribe(r=>{var o;const i={rawLogsEvent:{date:B(),message:r.message,origin:L.CONSOLE,error:r.error&&qe(r.error),status:yi[r.api]},messageContext:(o=r.error)===null||o===void 0?void 0:o.context,domainContext:{handlingStack:r.handlingStack}};t.notify(0,i)});return{stop:()=>{n.unsubscribe()}}}function Ri(e,t){const n=Bo(e,e.forwardReports).subscribe(r=>{let o=r.message,i;const s=r.originalError.type==="deprecation"?m.warn:m.error;s===m.error?i=qe(r):r.stack&&(o+=` Found in ${Do(r.stack)}`),t.notify(0,{rawLogsEvent:{date:B(),message:o,origin:L.REPORT,error:i,status:s}})});return{stop:()=>{n.unsubscribe()}}}function Ti(e,t){if(!e.forwardErrorsToLogs)return{stop:G};const n=Is(e).subscribe(i=>{i.state==="complete"&&o("xhr",i)}),r=Mn().subscribe(i=>{i.state==="resolve"&&o("fetch",i)});function o(i,s){!ro(s.url)&&(wi(s)||Tn(s.status))&&("xhr"in s?Ai(s.xhr,e,a):s.response?xi(s.response,e,a):s.error&&Ci(s.error,e,a));function a(c){const l={isAborted:s.isAborted,handlingStack:s.handlingStack};t.notify(0,{rawLogsEvent:{message:`${vi(i)} error ${s.method} ${s.url}`,date:s.startClocks.timeStamp,error:{stack:c||"Failed to load",handling:void 0},http:{method:s.method,status_code:s.status,url:s.url},status:m.error,origin:L.NETWORK},domainContext:l})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function Ai(e,t,n){typeof e.response=="string"?n(Ot(e.response,t)):n(e.response)}function Ci(e,t,n){n(Ot(Q(M(e)),t))}function xi(e,t,n){const r=fs(e);!r||!r.body?n():window.TextDecoder?Li(r.body,t.requestErrorResponseLengthLimit,(o,i)=>{n(o?`Unable to retrieve response: ${o}`:i)}):r.text().then(b(o=>n(Ot(o,t))),b(o=>n(`Unable to retrieve response: ${o}`)))}function wi(e){return e.status===0&&e.responseType!=="opaque"}function Ot(e,t){return e.length>t.requestErrorResponseLengthLimit?`${e.substring(0,t.requestErrorResponseLengthLimit)}...`:e}function vi(e){return e==="xhr"?"XHR":"Fetch"}function Li(e,t,n){Qs(e,(r,o,i)=>{if(r)n(r);else{let s=new TextDecoder().decode(o);i&&(s+="..."),n(void 0,s)}},{bytesLimit:t,collectStreamBody:!0})}function Oi(e,t){if(!e.forwardErrorsToLogs)return{stop:G};const n=new T,{stop:r}=ko(n),o=n.subscribe(i=>{t.notify(0,{rawLogsEvent:{message:i.message,date:i.startClocks.timeStamp,error:qe(i),origin:L.SOURCE,status:m.error},messageContext:i.context})});return{stop:()=>{r(),o.unsubscribe()}}}const Ii=Ls;function Di(e){function t(n,r,o,i,s){const a=ae(r.getContext(),n.context);if(Ve(n.status,Te.console,r)&&Mi(n,a),Ve(n.status,Te.http,r)){const c={rawLogsEvent:{date:s||B(),message:n.message,status:n.status,origin:L.LOGGER},messageContext:a,savedCommonContext:i};o&&(c.domainContext={handlingStack:o}),e.notify(0,c)}}return{handleLog:t}}const ki={[m.ok]:y.debug,[m.debug]:y.debug,[m.info]:y.info,[m.notice]:y.info,[m.warn]:y.warn,[m.error]:y.error,[m.critical]:y.error,[m.alert]:y.error,[m.emerg]:y.error};function Mi({status:e,message:t},n){Y[ki[e]].call(D,t,n)}function Ui(e,t,n,r,o){const i=kn(e,{endpoint:e.logsEndpointBuilder,encoder:Xe()},e.replica&&{endpoint:e.replica.logsEndpointBuilder,encoder:Xe()},n,r,o.expireObservable);return t.subscribe(1,s=>{i.add(s)}),i}function Pi(e){const t=Rt();e.subscribe(1,n=>{t.send("log",n)})}function Ni(e){return{get:t=>{const n=e.findTrackedSession(t);if(n)return{session_id:n.id}}}}function Bi(e){return t=>{e.notify(0,{rawLogsEvent:{message:t.message,date:t.startClocks.timeStamp,origin:L.AGENT,status:m.error}}),_n("Error reported to customer",{"error.message":t.message})}}function Fi(e,t,n,r,o){const i=Vo("browser-logs-sdk",t);i.setContextProvider(()=>{var a,c,l,u,d,f;return{application:{id:(a=Je())===null||a===void 0?void 0:a.application_id},session:{id:(c=o.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(u=(l=Je())===null||l===void 0?void 0:l.view)===null||u===void 0?void 0:u.id},action:{id:(f=(d=Je())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const s=[];if(We()){const a=Rt(),c=i.observable.subscribe(l=>a.send("internal_telemetry",l));s.push(()=>c.unsubscribe())}else{const a=kn(t,{endpoint:t.rumEndpointBuilder,encoder:Xe()},t.replica&&{endpoint:t.replica.rumEndpointBuilder,encoder:Xe()},n,r,o.expireObservable);s.push(()=>a.stop());const c=i.observable.subscribe(l=>a.add(l,Qo(t)));s.push(()=>c.unsubscribe())}return Jo(),Zo(ui(e)),{telemetry:i,stop:()=>{s.forEach(a=>a())}}}function $i(e,t,n,r){const o=new Ii,i=[];o.subscribe(1,f=>mn("logs",f));const s=Bi(o),a=Cs(t),c=t.sessionStoreStrategyType&&!We()&&!Pn()?mi(t,r):gi(t),{stop:l}=Fi(e,t,s,a,c);i.push(()=>l()),Ti(t,o),Oi(t,o),_i(t,o),Ri(t,o);const{handleLog:u}=Di(o);if(Si(c,t,o,n,s),We())Pi(o);else{const{stop:f}=Ui(t,o,s,a,c);i.push(()=>f())}const d=Ni(c);return{handleLog:u,getInternalContext:d.get,stop:()=>{i.forEach(f=>f())}}}const ue=fi($i);No($(),"DD_LOGS",ue);class w{constructor(t){this.isLoggingOn=t,ue.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!0,sessionSampleRate:100})}static setMessagePort(t){this.messagePort=t}static getMessagePort(){return this.messagePort}setLoggingOn(t){this.isLoggingOn=t}setAttributes(t){for(const n in t)ue.logger.setContextProperty(n,t[n])}info(t,n){this.isLoggingOn&&(ue.logger.info(t,n),console.log("[Logger] Sending info: ",t))}error(t,n){this.isLoggingOn&&(ue.logger.error(t,n),console.log("[Logger] Sending error: ",t))}warn(t,n){this.isLoggingOn&&(ue.logger.warn(t,n),console.log("[Logger] Sending warn: ",t))}handleMessageFromWorker(t){t.actionType==="INFO"?this.info(t.message,t.attributes):t.actionType==="ERROR"?this.error(t.message,t.attributes):t.actionType==="WARN"?this.warn(t.message,t.attributes):t.actionType==="SET_ATTRIBUTES"&&t.attributes&&this.setAttributes(t.attributes)}static setAttributes(t){w.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:t})}static info(t,n){w.messagePort.postMessage({type:"LOG",actionType:"INFO",message:t,attributes:n})}static error(t,n){w.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:t,attributes:n})}static warn(t,n){w.messagePort.postMessage({type:"LOG",actionType:"WARN",message:t,attributes:n})}}const A=class A{constructor(t,n,r,o,i){this.copy=()=>new A(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const s=":";let a=("0"+this.h).slice(-2)+s+("0"+this.m).slice(-2)+s+("0"+this.s).slice(-2)+s+("0"+this.f).slice(-2);return a+="."+(this.field?"1":"2"),a},this.toZipTimeCodeString=()=>{const s=this.copy();return s.f=0,s.s=s.s%2===0?s.s:s.s-1,s.field=0,A.toStr(s)},this.toFrames=s=>{let a=60,c=0;Math.floor(s)==60?(a=60,c=0):Math.floor(s)==59?(a=60,c=4):Math.floor(s)==30?(a=30,c=0):Math.floor(s)==29&&(a=30,c=2);let l=this.h,u=this.m,d=this.s,f=this.f,p=this.field;const h=l*60+u,S=(h-Math.floor(h/10))*c;return l*(a*3600)+u*(a*60)+d*a+(f*2+p)-S},this.addSeconds=s=>{let a=this.copy();return a.s+=s,a.s>=60&&(a.s=0,a.m++,a.m>=60&&(a.m=0,a.h++)),a},this.addFrames=(s,a)=>{let c=this.toFrames(a);return c+=s,A.fromFrames(c,a)},this.subtractFrames=(s,a)=>this.addFrames(-s,a),this.h=t||0,this.m=n||0,this.s=r||0,this.f=o||0,this.field=i||0}static compare(t,n){return t.h!==n.h?t.h<n.h?-1:1:t.m!==n.m?t.m<n.m?-1:1:t.s!==n.s?t.s<n.s?-1:1:t.f!==n.f?t.f<n.f?-1:1:t.field!==n.field?t.field<n.field?-1:1:0}static generateTimecodeRange(t,n,r){const o=[];let i=t;for(;A.compare(i,n)<=0;)o.push(i),i=i.addSeconds(r);return o}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(t){return this.toFrames(t)*1e3/t}};A.calculateCurrentTimeCode=t=>{var d;if(!t.video||!t.clocker||!t.gameParams)throw new Error("OTTPlayer is not initialized");const n=t.video,r=t.clocker,o=r.videoFPScalculator.getFPS(),a=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*o+r.syncPoint.frame;if(a===0||o===0)throw new Error("Current frame is 0 or fps is 0");const c=A.calculateCurrentOffset(a,(d=t.gameParams)==null?void 0:d.offsets);if(c===void 0)throw new Error("Offset is undefined");let l=Math.floor(a-c);return l<0&&(l+=5178816),l>=5178816&&(l-=5178816),A.fromFrames(l,o)},A.calculateCurrentOffset=(t,n)=>{for(let r=1;r<n.length;r++)if(t<n[r].frame)return n[r-1].offset;return n[n.length-1].offset},A.fromFrames=(t,n)=>{let r=60,o=0;Math.floor(n)==60?(r=60,o=0):Math.floor(n)==59?(r=60,o=4):Math.floor(n)==30?(r=30,o=0):Math.floor(n)==29&&(r=30,o=2);let i=Math.floor(n*60),s=Math.floor(n*60*10),a=s*6,c=t,l=Math.floor(c/a);c-=l*a;let u=Math.floor(c/s);c-=u*s,c>=r*60&&(c+=o*(Math.floor((c-r*60)/i)+1));let d=Math.floor(c/(r*60));c-=d*(r*60);let f=Math.floor(c/r);c-=f*r;let p=c;d+=u*10;let h=0;return h=p%2,p=Math.floor(p/2),new A(l,d,f,p,h)},A.toStr=t=>{const n="_";let r=("0"+t.h).slice(-2)+n+("0"+t.m).slice(-2)+n+("0"+t.s).slice(-2)+n+("0"+t.f).slice(-2);return t.field&&(r+="_1"),r},A.fromStr=t=>{const r=t.split("_").map(Number);if(r.length==4){const[o,i,s,a]=r;return new A(o,i,s,a,0)}else if(r.length==5){const[o,i,s,a,c]=r;return new A(o,i,s,a,c)}else throw new Error("Invalid timecode format: "+t)},A.fromMetadata=t=>{const n=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,r=t.timecode.match(n);if(!r)throw new Error("Invalid timecode format: "+t.timecode);const[,o,i,s,a,c]=r,l=Number(o),u=Number(i),d=Number(s),f=Number(a),p=c?Number(c):0;return new A(l,u,d,f,p)};let z=A;const Gi=`\nattribute vec2 a_position;\nattribute vec2 a_uv;\n\nuniform vec2 u_resolution;\n\nvarying vec2 v_uv;\n\nvoid main() {\n v_uv = a_uv;\n\n vec2 clipSpace = 2.0 * (a_position / u_resolution) - 1.0;\n gl_Position = vec4(clipSpace, 0.0, 1.0);\n}\n`,ji=`\nprecision mediump float;\n\nuniform sampler2D u_alphaMask;\nvarying vec2 v_uv;\n\nvoid main() {\n vec4 alphaColor = texture2D(u_alphaMask, v_uv);\n\n // Where the alpha map is white, make it transparent\n if (alphaColor.r > 0.5) {\n discard;\n } else {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n}\n`,Hi=`\nuniform vec2 u_resolution;\nattribute vec2 a_position;\nattribute vec2 a_uv;\n\nvarying vec2 v_uv;\n\nvoid main() {\n v_uv = a_uv;\n\n // convert the rectangle from pixels to 0.0 to 1.0\n vec2 clipSpace = 2.0 * (a_position / u_resolution) - 1.0;\n\n gl_Position = vec4(clipSpace, 0.0, 1.0);\n}\n`,zi=e=>`\n#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\n\nuniform vec2 u_resolution;\n${e.map((t,n)=>`uniform sampler2D u_ad${t};`).join(`\n`)}\nuniform sampler2D u_alphaMask;\nuniform float u_augmentationAlpha;\n\nvarying vec2 v_uv;\n\n${e.map((t,n)=>`uniform int u_hasLogo${t};`).join(`\n`)}\n${e.map((t,n)=>`uniform mat3 u_matrix${t};`).join(`\n`)}\n\nuniform int u_hasDigitTex;\nuniform sampler2D u_digitTex;\nuniform vec2 u_digitTopLeft;\nuniform vec2 u_digitSize;\n\n\nconst float Directions = 16.0; // BLUR DIRECTIONS (Default 16.0 - More is better but slower)\nconst float QualityAd = 3.0; // BLUR QUALITY (Default 3.0 - More is better but slower)\nconst float QualityAlpha = 5.0; // BLUR QUALITY (Default 3.0 - More is better but slower)\nconst float BlurRadiusAd = 10.0;\nconst float BlurRadiusAlpha = 10.0;\nconst float Pi = 6.28318530718; // Pi*2\n\nvec4 BlurAd(sampler2D adTexture, vec2 adTexCoord) {\n vec2 Radius = BlurRadiusAd/u_resolution.xy;\n vec4 res = texture2D(adTexture, adTexCoord);\n \n for( float d=0.0; d<Pi; d+=Pi/Directions) {\n for(float i=1.0/QualityAd; i<=1.0; i+=1.0/QualityAd) {\n res += texture2D(adTexture, adTexCoord+vec2(cos(d),sin(d))*Radius*i);\n }\n }\n\n res /= QualityAd * Directions - 5.0;\n\n return res;\n}\n\nvec4 BlendLogo(vec2 curCoord, sampler2D ad, mat3 matrix) {\n vec2 texCoord;\n texCoord.x = (matrix[0][0]*curCoord.x + matrix[0][1]*curCoord.y + matrix[0][2]) / (matrix[2][0]*curCoord.x + matrix[2][1]*curCoord.y + 1.0);\n texCoord.y = (matrix[1][0]*curCoord.x + matrix[1][1]*curCoord.y + matrix[1][2]) / (matrix[2][0]*curCoord.x + matrix[2][1]*curCoord.y + 1.0);\n texCoord /= u_resolution;\n\n vec4 maskAlpha = texture2D(u_alphaMask, v_uv);\n vec4 adColor = BlurAd(ad, texCoord);\n float adAlpha = texture2D(ad, texCoord).a;\n\n float finalAlpha = maskAlpha.r;\n if (finalAlpha < 0.3) \n finalAlpha = 0.0;\n finalAlpha *= adColor.a;\n vec4 finalColor = vec4(adColor.rgb, finalAlpha);\n finalColor.rgb *= finalAlpha;\n return finalColor;\n}\n\nbool BlendDigit(vec2 curCoord) {\n vec2 digitCoord = (curCoord - u_digitTopLeft)/u_digitSize;//get the coordinate on the digit size\n if (digitCoord.x >= 0.0 && digitCoord.y >= 0.0 && digitCoord.x <= 1.0 && digitCoord.y <= 1.0) {\n gl_FragColor = texture2D(u_digitTex, digitCoord);\n return true;\n }\n return false;\n}\n\n\nvoid main() { \n vec2 curCoord = gl_FragCoord.xy;\n curCoord.y = u_resolution[1] - curCoord.y;\n\n if (u_hasDigitTex == 1 && (BlendDigit(curCoord))) return;\n\n ${e.map((t,n)=>`\n if (u_hasLogo${t} == 1) {\n gl_FragColor += BlendLogo(curCoord, u_ad${t}, u_matrix${t});\n }`).join(`\n`)}\n gl_FragColor.a *= u_augmentationAlpha;\n}\n`;class Gn{constructor(t,n){this.adTextures=new Map,this.allPlaceholders=[],this.setAllPlaceholders=r=>{this.allPlaceholders=r},this.initShadersAlphaMask=r=>{const o=this.compileShader(r,r.VERTEX_SHADER,Gi),i=this.compileShader(r,r.FRAGMENT_SHADER,ji),s=r.createProgram();return r.attachShader(s,o),r.attachShader(s,i),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)?s:(console.error("Could not link shaders:",r.getProgramInfoLog(s)),null)},this.initShadersAugmentation=r=>{const o=this.compileShader(r,r.VERTEX_SHADER,Hi),i=this.compileShader(r,r.FRAGMENT_SHADER,zi(this.allPlaceholders)),s=r.createProgram();return r.attachShader(s,o),r.attachShader(s,i),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)?s:(console.error("Could not link shaders:",r.getProgramInfoLog(s)),null)},this.compileShader=(r,o,i)=>{const s=r.createShader(o);return r.shaderSource(s,i),r.compileShader(s),r.getShaderParameter(s,r.COMPILE_STATUS)?s:(console.error(`Error compiling shader: ${r.getShaderInfoLog(s)}`),r.deleteShader(s),null)},this.createTextureFromVideoFrame=r=>{const o=this.gl,i=o.createTexture();return o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,!0),o.bindTexture(o.TEXTURE_2D,i),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,r),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.bindTexture(o.TEXTURE_2D,null),i},this.deleteTexture=r=>{this.gl.deleteTexture(r)},this.drawAlphaMask=r=>{if(!this.program){this.options&&C(this.options,"Errors")&&console.error("[Renderer] Program not initialized");return}(!this.positionBuffer||!this.uvBuffer)&&this.options&&C(this.options,"Errors")&&console.error("[Renderer] Buffers not initialized");const o=this.gl,i=this.program,s=o.getAttribLocation(i,"a_position"),a=o.getAttribLocation(i,"a_uv"),c=o.getUniformLocation(i,"u_alphaMask");o.activeTexture(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,r),o.uniform1i(c,0),o.bindBuffer(o.ARRAY_BUFFER,this.positionBuffer),o.enableVertexAttribArray(s),o.vertexAttribPointer(s,2,o.FLOAT,!1,0,0),o.bindBuffer(o.ARRAY_BUFFER,this.uvBuffer),o.enableVertexAttribArray(a),o.vertexAttribPointer(a,2,o.FLOAT,!1,0,0),o.clear(o.COLOR_BUFFER_BIT);let l=o.TRIANGLES;o.drawArrays(l,0,6)},this.drawAugmentation=(r,o,i=1)=>{if(!this.program){w.error("[Renderer] Program not initialized"),this.options&&C(this.options,"Errors")&&console.error("[Renderer] Program not initialized");return}const s=this.gl,a=this.program;if(!this.allPlaceholders){w.error("[Renderer] Placeholder names not initialized"),this.options&&C(this.options,"Errors")&&console.error("[Renderer] Placeholder names not initialized");return}s.enable(s.BLEND),s.blendFunc(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA),s.activeTexture(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,r);const c=s.getUniformLocation(a,"u_alphaMask");c&&s.uniform1i(c,0);const l=s.getUniformLocation(a,"u_augmentationAlpha");l&&s.uniform1f(l,i);let u=0;const d=Object.keys(o).map(v=>o[v]),f=d.map(v=>v.name);this.allPlaceholders.forEach(v=>{if(f.includes(v)&&this.adTextures.has(v)){const Ce=d.filter(Zi=>Zi.name===v)[0],xe=this.adTextures.get(v);s.activeTexture(s.TEXTURE1+u),s.bindTexture(s.TEXTURE_2D,xe);let et=s.getUniformLocation(a,"u_ad"+v);et&&s.uniform1i(et,u+1);let g="u_hasLogo"+v,W=s.getUniformLocation(a,g);s.uniform1i(W,1);let Dt="u_matrix"+v,Qi=s.getUniformLocation(a,Dt);s.uniformMatrix3fv(Qi,!1,Ce.tranform),u++}else{let Ce="u_hasLogo"+v,xe=s.getUniformLocation(a,Ce);s.uniform1i(xe,0)}});const p=s.getAttribLocation(a,"a_position"),h=s.getAttribLocation(a,"a_uv"),E=s.getUniformLocation(a,"u_resolution");s.uniform2f(E,s.canvas.width,s.canvas.height),s.bindBuffer(s.ARRAY_BUFFER,this.positionBuffer),s.enableVertexAttribArray(p),s.vertexAttribPointer(p,2,s.FLOAT,!1,0,0),s.bindBuffer(s.ARRAY_BUFFER,this.uvBuffer),s.enableVertexAttribArray(h),s.vertexAttribPointer(h,2,s.FLOAT,!1,0,0),s.viewport(0,0,s.canvas.width,s.canvas.height),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT);let S=s.TRIANGLES;s.drawArrays(S,0,6)},this.setRectangle=(r,o,i,s,a)=>{const c=o,l=i,u=o+s,d=i+a;r.bufferData(r.ARRAY_BUFFER,new Float32Array([c,l,u,l,c,d,c,d,u,l,u,d]),r.STATIC_DRAW)},this.generateAdTexture=(r,o,i)=>{const s=this.gl;if(!this.program){w.error("[Renderer] Program not initialized"),this.options&&C(this.options,"Errors")&&console.error("[Renderer] Program not initialized");return}s.pixelStorei(s.UNPACK_ALIGNMENT,4),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,i);const c=s.createTexture();if(s.bindTexture(s.TEXTURE_2D,c),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.bindTexture(s.TEXTURE_2D,null),!c){w.error("[Renderer] Failed to create texture"),this.options&&C(this.options,"Errors")&&console.error("[Renderer] Failed to create texture");return}this.adTextures.set(r,c)},this.isPowerOf2=r=>(r&r-1)==0,this.setUVs=r=>{r.bufferData(r.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),r.STATIC_DRAW)},this.options=n,this.renderer=t,this.gl=t.glContext}init(){const t=this.gl;this.renderer.RENDER_ALPHAMASK?this.program=this.initShadersAlphaMask(t):this.program=this.initShadersAugmentation(t),t.useProgram(this.program);const n=t.getUniformLocation(this.program,"u_resolution");t.uniform2f(n,t.canvas.width,t.canvas.height),this.initGeometryBuffers()}initGeometryBuffers(){const t=this.gl;this.positionBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),this.setRectangle(t,0,0,t.canvas.width,t.canvas.height),this.uvBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.setUVs(t),t.bindBuffer(t.ARRAY_BUFFER,null)}updateGeometryBuffers(){const t=this.gl;if(!this.positionBuffer||!this.uvBuffer){w.error("[Renderer] Buffers not initialized"),this.options&&C(this.options,"Errors")&&console.error("[Renderer] Buffers not initialized");return}t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),this.setRectangle(t,0,0,t.canvas.width,t.canvas.height),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.setUVs(t),t.bindBuffer(t.ARRAY_BUFFER,null)}cleanGL(){this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT)}}const It=["LeftTop","MidTopLeft","MidTopRight","RightTop","LeftBottom","MidBottomLeft","MidBottomRight","RightBottom"];class jn{constructor(t,n){this.ads=[],this.getAds=async()=>{const o=await(await fetch("https://www.virtualott.com/ads/"+this.options.augmentation.channelName)).json(),i=o.filter(l=>l.name.indexOf(".json")>-1)[0].url,c=(await(await fetch(i)).json()).urls;for(const l of o){const u=await this.loadAdvImage(l);if(!u)continue;const d={name:l.name,imageUrl:l.url,image:u,adUrl:c[l.name]};this.ads.push(d)}this.setAd("LeftTop",3),this.setAd("RightBottom",4),this.uploadAdTextures()},this.loadAdvImage=async r=>{const o=`#${r.name}`,i=r.url;if(o.indexOf(".json")>-1)return;const a=await(await fetch(i)).blob();return await createImageBitmap(a)},this.setAd=(r,o)=>{this.adMap.set(r,this.ads[o])},this.uploadAdTextures=()=>{this.adMap.forEach((r,o)=>{!r||!r.image||this.webgl.generateAdTexture(o,r.image,!0)})},this.getAdURLAtCoord=(r,o,i)=>{let s;return Object.keys(r).forEach(a=>{const c=r[a].corners.map(l=>({x:l.x/o.width,y:l.y/o.height}));if(this.isPointInPlaceholder(c,i)){const l=r[a].name,u=this.adMap.get(l);console.log("ad: ",u),u&&(console.log("ad.url: ",u.adUrl),s=u.adUrl)}}),s},this.isPointInPlaceholder=(r,o)=>{console.log("polygon: ",r),console.log("coord: ",o);let i=!1;const{x:s,y:a}=o,c=r.length;for(let l=0,u=c-1;l<c;u=l++){const d=r[l].x,f=r[l].y,p=r[u].x,h=r[u].y;f>a!=h>a&&s<(p-d)*(a-f)/(h-f)+d&&(i=!i)}return console.log("inside: ",i),i},this.placeholderNames=It,this.webgl=t,this.options=n,this.adMap=new Map,It.forEach(r=>{this.adMap.set(r,void 0)}),this.webgl.setAllPlaceholders(It),console.log("channelName: ",this.options.augmentation.channelName),this.getAds()}}class Hn{constructor(t,n){this.RENDER_ALPHAMASK=!1,this.renderDataMap=new Map,this.isRenderData=!1,this.state="OFF",this.opacity=0,this.lastStateUpdate=0,this.stateUpdateInterval=500,this.setWebGLEventListeners=()=>{const r=this.glContext.canvas;r.addEventListener("webglcontextlost",o=>{console.warn("Context lost:",o),o.preventDefault()}),r.addEventListener("webglcontextrestored",()=>{console.log("Context restored!"),this.webgl=new Gn(this,this.options),this.ads=new jn(this.webgl,this.options),this.webgl.init()})},this.addMetadataBatch=r=>{r.forEach(o=>{if(!(!o.alphaMask||!o.isLive)){this.options&&C(this.options,"Renderer")&&console.log(`[RendererWorker] Creating texture for timeCode=${o.timecode}`);try{const i=this.webgl.createTextureFromVideoFrame(o.alphaMask),s=o.timecode,a={width:o.processingWidth,height:o.processingHeight},c={alphaMask:i,placeholders:o.placeholders,processingSize:a};this.renderDataMap.set(s,c)}catch(i){w.error(`[RendererWorker] Error creating texture for timeCode=${o.timecode}`,{error:i}),this.options&&C(this.options,"Errors")&&console.error(`[RendererWorker] Error creating texture for timeCode=${o.timecode}`)}finally{o.alphaMask.close()}}})},this.handleRenderDraw=(r,o)=>{var l,u;if(!this.streamData)return;this.streamData.ottActions&&!this.streamData.ottActions.toggle.web?(this.state==="ON"||this.state==="FADE_IN")&&(this.state="FADE_OUT"):(this.state==="OFF"||this.state==="FADE_OUT")&&(this.state="FADE_IN");const i=this.renderDataMap.get(r);if(!!i!==this.isRenderData&&(i?w.info("didStartDrawingAugmentationMedia",{timecode:r}):w.info("didEndDrawingAugmentationMedia",{timecode:r}),this.isRenderData=!!i),!i)return;const s=i.alphaMask,a=i.placeholders,c=i.processingSize;if(!(!s||!a||!c)){if((this.glContext.canvas.width!==c.width||this.glContext.canvas.height!==c.height)&&(this.glContext.canvas.width=c.width,this.glContext.canvas.height=c.height,this.webgl.updateGeometryBuffers()),o!=0)if(o>0){const d=z.fromStr(r).addFrames(1,this.streamData.fps),f=(l=this.renderDataMap.get(z.toStr(d)))==null?void 0:l.placeholders;f&&Object.keys(f).forEach(p=>{p in a&&(a[p].tranform=a[p].tranform.map((h,E)=>h*(1-o)+f[p].tranform[E]*o))})}else{const d=Math.abs(o),f=z.fromStr(r).subtractFrames(1,this.streamData.fps),p=(u=this.renderDataMap.get(z.toStr(f)))==null?void 0:u.placeholders;p&&Object.keys(p).forEach(h=>{h in a&&(a[h].tranform=a[h].tranform.map((E,S)=>p[h].tranform[S]*(1-d)+E*d))})}this.options&&C(this.options,"Renderer")&&console.log(`[Renderer] Render logic: binding texture for ${r}`),this.state==="FADE_IN"?(this.opacity===0&&(this.lastStateUpdate=performance.now()),this.opacity=Math.min(1,this.opacity+(performance.now()-this.lastStateUpdate)/this.stateUpdateInterval),this.lastStateUpdate=performance.now(),this.opacity===1&&(this.state="ON")):this.state==="FADE_OUT"&&(this.opacity===1&&(this.lastStateUpdate=performance.now()),this.opacity=Math.max(0,this.opacity-(performance.now()-this.lastStateUpdate)/this.stateUpdateInterval),this.lastStateUpdate=performance.now(),this.opacity===0&&(this.state="OFF")),this.RENDER_ALPHAMASK?this.webgl.drawAlphaMask(s):this.webgl.drawAugmentation(s,a,this.opacity)}},this.handleRenderClear=()=>{this.opacity=0,this.state="OFF"},this.getAdURLByCoord=r=>{var c,l;if(!this.ads||!this.streamData||!this.streamData.timeCode||!this.renderDataMap)return null;const o=this.streamData.timeCode,i=(c=this.renderDataMap.get(o))==null?void 0:c.placeholders,s=(l=this.renderDataMap.get(o))==null?void 0:l.processingSize;if(!i||!s)return null;console.log("placeholders: ",i);const a=this.ads.getAdURLAtCoord(i,s,r);return console.log("url: ",a),a},this.deleteTexture=r=>{var i;const o=(i=this.renderDataMap.get(r))==null?void 0:i.alphaMask;o&&(this.webgl.deleteTexture(o),this.renderDataMap.delete(r))},this.deleteOldTextures=r=>{if(!this.streamData)return;const o=59.94,i=z.fromStr(r).totalMilliseconds(o);this.renderDataMap.forEach((s,a)=>{z.fromStr(a).totalMilliseconds(o)<i-100&&(this.options&&C(this.options,"Renderer")&&console.log(`[Renderer] Deleting old texture for timeCode=${a}`),this.webgl.deleteTexture(s.alphaMask),this.renderDataMap.delete(a))})},this.deleteAllTextures=()=>{this.renderDataMap.forEach((r,o)=>{this.webgl.deleteTexture(r.alphaMask),this.renderDataMap.delete(o)})},this.cleanGL=()=>{this.webgl.cleanGL()},this.updateStreamData=r=>{this.streamData=r},this.glContext=t,this.webgl=new Gn(this,n),this.options=n,this.ads=new jn(this.webgl,n),this.webgl.init()}stop(){this.cleanGL(),this.deleteAllTextures()}}let Qe=null,Ze=null,zn=null,Ae=null,x=null,R;const I={timeCode:"",frameCorrection:0,fps:0,cloudFrontURL:"",bucketName:"",offsets:[]};let Wn=0,Yn=0;self.onmessage=e=>{const{data:t}=e;if(t.type==="SET_LOGGER_PORT"&&w.setMessagePort(t.port),t.type==="INIT_OFFSCREEN"){const n=t.offscreen;if(R=t.options,Ae=n.getContext("webgl"),R&&C(R,"Renderer")&&console.log("[RendererWorker] Initializing OffscreenCanvas"),!Ae){R&&C(R,"Errors")&&console.error("[RendererWorker] Failed to acquire WebGL context");return}x=new Hn(Ae,R),R&&C(R,"Renderer")&&console.log("[RendererWorker] OffscreenCanvas initialized, gl context acquired")}if(t.type==="SET_DOWNLOADER_PORT"&&(Qe=t.port,Qe.onmessage=Vi),t.type==="SET_DECODER_PORT"&&(Ze=t.port,Ze.onmessage=Ki),t.type==="SET_ADAPTER_PORT"&&(zn=t.port,zn.onmessage=qi),(t.type==="RENDERER_DRAW"||t.type==="RENDERER_CLEAR")&&Xn(t),t.type==="VIDEO_CLICK"&&x){const n=x.getAdURLByCoord(t.clickData);postMessage({type:"OPEN_URL",url:n})}if(t.type==="VIDEO_SEEKED"){if(!Ae||!R)return;x==null||x.stop(),x=new Hn(Ae,R)}};function Wi(){Qe&&Qe.postMessage({type:"DOWNLOADER_INPUT",streamData:I})}function Yi(){Ze&&Ze.postMessage({type:"DECODER_REQUEST",timeCode:I.timeCode,fps:I.fps})}function Xn(e){Ji(e.streamData),x?(x.updateStreamData(I),x.cleanGL(),e.type==="RENDERER_CLEAR"&&x.handleRenderClear(),e.type==="RENDERER_DRAW"&&(x.handleRenderDraw(e.streamData.timeCode,e.streamData.frameCorrection),x.deleteOldTextures(e.streamData.timeCode))):R&&C(R,"Errors")&&console.error("[RendererWorker] WebGL context is not initialized."),Xi()}function Xi(){if(!R)return;const e=performance.now();e-Wn>R.DOWNLOADER_UPDATE_FREQUENCY&&(Wi(),Wn=e),e-Yn>R.DECODER_UPDATE_FREQUENCY&&(Yi(),Yn=e)}function Ki(e){const{data:t}=e;if(t.type==="RENDERER_INPUT"){const n=t.batch;R&&C(R,"Renderer")&&console.log(`[RendererWorker] Received a batch of ${n.length} frames`),x&&x.addMetadataBatch(n)}}function Vi(e){const{data:t}=e;R&&C(R,"Renderer")&&console.log("[RendererWorker] Message from Downloader:",e.data),t.type==="OTT_ACTIONS"&&(I.ottActions=t.ottActions)}function qi(e){const{data:t}=e;(t.type==="RENDERER_DRAW"||t.type==="RENDERER_CLEAR")&&Xn(t)}function Ji(e){I.timeCode=e.timeCode,I.frameCorrection=e.frameCorrection,I.fps=e.fps,I.cloudFrontURL=e.cloudFrontURL,I.bucketName=e.bucketName,I.offsets=e.offsets}})();\n',$t=typeof self<"u"&&self.Blob&&new Blob([Nt],{type:"text/javascript;charset=utf-8"});function lr(t){let e;try{if(e=$t&&(self.URL||self.webkitURL).createObjectURL($t),!e)throw"";const n=new Worker(e,{name:t==null?void 0:t.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Nt),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const zt='(function(){"use strict";const we=(e,t)=>!e.debug||!e.debug.on?!1:e.debug[`log${t}`],Wn=e=>Math.abs(e-59.94005994005994)<20?59.94:Math.abs(e-29.97002997002997)<10?29.97:Math.abs(e-14.985014985014985)<8?14.98:0,E={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},A=console,j={};Object.keys(E).forEach(e=>{j[e]=A[e]});const ue="Datadog Browser SDK:",_={debug:j.debug.bind(A,ue),log:j.log.bind(A,ue),info:j.info.bind(A,ue),warn:j.warn.bind(A,ue),error:j.error.bind(A,ue)},Xe="https://docs.datadoghq.com",xt=`${Xe}/real_user_monitoring/browser/troubleshooting`,Ce="More details:";function At(e,t){return(...n)=>{try{return e(...n)}catch(r){_.error(t,r)}}}function Oe(e){return e!==0&&Math.random()*100<=e}function Hn(e){return zn(e)&&e>=0&&e<=100}function zn(e){return typeof e=="number"}const le=1e3,W=60*le,Lt=60*W,Kn=365*(24*Lt);function de(){return new Date().getTime()}function F(){return de()}function ve(){return performance.now()}function D(){return{relative:ve(),timeStamp:F()}}function Vn(){return{relative:0,timeStamp:It()}}function qn(e,t){return t-e}function Yn(e,t){return e+t}function Xn(e){return e-It()}let Je;function It(){return Je===void 0&&(Je=performance.timing.navigationStart),Je}const L=1024,kt=1024*L,Jn=/[^\\u0000-\\u007F]/;function Qe(e){return Jn.test(e)?window.TextEncoder!==void 0?new TextEncoder().encode(e).length:new Blob([e]).size:e.length}function Qn(e){return{...e}}function Mt(e,t){return Object.keys(e).some(n=>e[n]===t)}function fe(e){return Object.keys(e).length===0}function $(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let e=_dd_temp_;return delete Object.prototype._dd_temp_,typeof e!="object"&&(typeof self=="object"?e=self:typeof window=="object"?e=window:e={}),e}function Z(e,t){const n=$();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=e[n.Zone.__symbol__(t)]),r||(r=e[t]),r}let Re,Pt=!1;function Zn(e){Re=e}function er(e){Pt=e}function tr(e,t,n){const r=n.value;n.value=function(...o){return(Re?b(r):r).apply(this,o)}}function b(e){return function(){return pe(e,this,arguments)}}function pe(e,t,n){try{return e.apply(t,n)}catch(r){nr(r)}}function nr(e){if(Ze(e),Re)try{Re(e)}catch(t){Ze(t)}}function Ze(...e){Pt&&_.error("[MONITOR]",...e)}function me(e,t){return Z($(),"setTimeout")(b(e),t)}function Nt(e){Z($(),"clearTimeout")(e)}function et(e,t){return Z($(),"setInterval")(b(e),t)}function Ft(e){Z($(),"clearInterval")(e)}class w{constructor(t){this.onFirstSubscribe=t,this.observers=[]}subscribe(t){return this.observers.push(t),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(n=>t!==n),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(t){this.observers.forEach(n=>n(t))}}function Dt(...e){return new w(t=>{const n=e.map(r=>r.subscribe(o=>t.notify(o)));return()=>n.forEach(r=>r.unsubscribe())})}function $t(e,t,n){let r=!1,o,s;return{throttled:(...i)=>{if(r){o=i;return}e(...i),r=!0,s=me(()=>{o&&e(...o),r=!1,o=void 0},t)},cancel:()=>{Nt(s),r=!1,o=void 0}}}function U(){}function B(e){return e?(parseInt(e,10)^Math.random()*16>>parseInt(e,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,B)}const xe=/([\\w-]+)\\s*=\\s*([^;]+)/g;function rr(e,t){for(xe.lastIndex=0;;){const n=xe.exec(e);if(n){if(n[1]===t)return n[2]}else break}}function or(e){const t=new Map;for(xe.lastIndex=0;;){const n=xe.exec(e);if(n)t.set(n[1],n[2]);else break}return t}function sr(e,t,n=""){const r=e.charCodeAt(t-1),s=r>=55296&&r<=56319?t+1:t;return e.length<=s?e:`${e.slice(0,s)}${n}`}function ir(){return ar()===0}let Ae;function ar(){return Ae??(Ae=cr())}function cr(e=window){var t;const n=e.navigator.userAgent;return e.chrome||/HeadlessChrome/.test(n)?0:((t=e.navigator.vendor)===null||t===void 0?void 0:t.indexOf("Apple"))===0||/safari/i.test(n)&&!/chrome|android/i.test(n)?1:2}function ge(e,t,n=0,r){const o=new Date;o.setTime(o.getTime()+n);const s=`expires=${o.toUTCString()}`,i=r&&r.crossSite?"none":"strict",a=r&&r.domain?`;domain=${r.domain}`:"",c=r&&r.secure?";secure":"",l=r&&r.partitioned?";partitioned":"";document.cookie=`${e}=${t};${s};path=/;samesite=${i}${a}${c}${l}`}function tt(e){return rr(document.cookie,e)}let nt;function H(e){return nt||(nt=or(document.cookie)),nt.get(e)}function Ut(e,t){ge(e,"",0,t)}function ur(e){if(document.cookie===void 0||document.cookie===null)return!1;try{const t=`dd_cookie_test_${B()}`,n="test";ge(t,n,W,e);const r=tt(t)===n;return Ut(t,e),r}catch(t){return _.error(t),!1}}let rt;function lr(){if(rt===void 0){const e=`dd_site_test_${B()}`,t="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!tt(e);)r=`${n.pop()}.${r}`,ge(e,t,le,{domain:r});Ut(e,{domain:r}),rt=r}return rt}const ee="_dd_s";function Le(e){return Object.values(e)}function dr(e){return Object.entries(e)}const ot=4*Lt,Bt=15*W,fr=Kn,he={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},Gt=/^([a-zA-Z]+)=([a-z0-9-]+)$/,st="&";function pr(e){return!!e&&(e.indexOf(st)!==-1||Gt.test(e))}const mr="1";function z(e,t){const n={isExpired:mr};return t.trackAnonymousUser&&(e!=null&&e.anonymousId?n.anonymousId=e==null?void 0:e.anonymousId:n.anonymousId=B()),n}function Ie(e){return fe(e)}function jt(e){return!Ie(e)}function ke(e){return e.isExpired!==void 0||!gr(e)}function gr(e){return(e.created===void 0||de()-Number(e.created)<ot)&&(e.expire===void 0||de()<Number(e.expire))}function Wt(e){e.expire=String(de()+Bt)}function it(e){return dr(e).map(([t,n])=>t==="anonymousId"?`aid=${n}`:`${t}=${n}`).join(st)}function Ht(e){const t={};return pr(e)&&e.split(st).forEach(n=>{const r=Gt.exec(n);if(r!==null){const[,o,s]=r;o==="aid"?t.anonymousId=s:t[o]=s}}),t}const hr="_dd",Sr="_dd_r",br="_dd_l",yr="rum",Er="logs";function _r(e){if(!H(ee)){const n=H(hr),r=H(Sr),o=H(br),s={};n&&(s.id=n),o&&/^[01]$/.test(o)&&(s[Er]=o),r&&/^[012]$/.test(r)&&(s[yr]=r),jt(s)&&(Wt(s),e.persistSession(s))}}function zt(e){const t=vr(e);return ur(t)?{type:he.COOKIE,cookieOptions:t}:void 0}function Tr(e,t){const n={isLockEnabled:ir(),persistSession:wr(t),retrieveSession:Or,expireSession:r=>Cr(t,r,e)};return _r(n),n}function wr(e){return t=>{ge(ee,it(t),Bt,e)}}function Cr(e,t,n){const r=z(t,n);ge(ee,it(r),n.trackAnonymousUser?fr:ot,e)}function Or(){const e=tt(ee);return Ht(e)}function vr(e){const t={};return t.secure=!!e.useSecureSessionCookie||!!e.usePartitionedCrossSiteSessionCookie,t.crossSite=!!e.usePartitionedCrossSiteSessionCookie,t.partitioned=!!e.usePartitionedCrossSiteSessionCookie,e.trackSessionAcrossSubdomains&&(t.domain=lr()),t}const Rr="_dd_test_";function Kt(){try{const e=B(),t=`${Rr}${e}`;localStorage.setItem(t,e);const n=localStorage.getItem(t);return localStorage.removeItem(t),e===n?{type:he.LOCAL_STORAGE}:void 0}catch{return}}function xr(e){return{isLockEnabled:!1,persistSession:Vt,retrieveSession:Ar,expireSession:t=>Lr(t,e)}}function Vt(e){localStorage.setItem(ee,it(e))}function Ar(){const e=localStorage.getItem(ee);return Ht(e)}function Lr(e,t){Vt(z(e,t))}const Ir=10,kr=100,qt=[];let Me;function K(e,t,n=0){var r;const{isLockEnabled:o,persistSession:s,expireSession:i}=t,a=f=>s({...f,lock:l}),c=()=>{const f=t.retrieveSession(),g=f.lock;return f.lock&&delete f.lock,{session:f,lock:g}};if(Me||(Me=e),e!==Me){qt.push(e);return}if(o&&n>=kr){Yt(t);return}let l,u=c();if(o){if(u.lock){Pe(e,t,n);return}if(l=B(),a(u.session),u=c(),u.lock!==l){Pe(e,t,n);return}}let d=e.process(u.session);if(o&&(u=c(),u.lock!==l)){Pe(e,t,n);return}if(d&&(ke(d)?i(d):(Wt(d),o?a(d):s(d))),o&&!(d&&ke(d))){if(u=c(),u.lock!==l){Pe(e,t,n);return}s(u.session),d=u.session}(r=e.after)===null||r===void 0||r.call(e,d||u.session),Yt(t)}function Pe(e,t,n){me(()=>{K(e,t,n+1)},Ir)}function Yt(e){Me=void 0;const t=qt.shift();t&&K(t,e)}const Xt=le;function Mr(e){switch(e.sessionPersistence){case he.COOKIE:return zt(e);case he.LOCAL_STORAGE:return Kt();case void 0:{let t=zt(e);return!t&&e.allowFallbackToLocalStorage&&(t=Kt()),t}default:_.error(`Invalid session persistence \'${String(e.sessionPersistence)}\'`)}}function Pr(e,t,n,r){const o=new w,s=new w,i=new w,a=e.type===he.COOKIE?Tr(t,e.cookieOptions):xr(t),{expireSession:c}=a,l=et(m,Xt);let u;p();const{throttled:d,cancel:f}=$t(()=>{K({process:S=>{if(Ie(S))return;const ce=y(S);return O(ce),ce},after:S=>{jt(S)&&!v()&&Gn(S),u=S}},a)},Xt);function g(){K({process:S=>v()?y(S):void 0},a)}function m(){K({process:S=>ke(S)?z(S,t):void 0,after:y},a)}function y(S){return ke(S)&&(S=z(S,t)),v()&&(N(S)?ae():(i.notify({previousState:u,newState:S}),u=S)),S}function p(){K({process:S=>{if(Ie(S))return z(S,t)},after:S=>{u=S}},a)}function O(S){if(Ie(S))return!1;const{trackingType:ce,isTracked:ji}=r(S[n]);S[n]=ce,delete S.isExpired,ji&&!S.id&&(S.id=B(),S.created=String(de()))}function v(){return u[n]!==void 0}function N(S){return u.id!==S.id||u[n]!==S[n]}function ae(){u=z(u,t),s.notify()}function Gn(S){u=S,o.notify()}function jn(S){K({process:ce=>({...ce,...S}),after:y},a)}return{expandOrRenewSession:d,expandSession:g,getSession:()=>u,renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i,restartSession:p,expire:()=>{f(),c(u),y(z(u,t))},stop:()=>{Ft(l)},updateSessionState:jn}}const at={GRANTED:"granted",NOT_GRANTED:"not-granted"};function Nr(e){const t=new w;return{tryToInit(n){e||(e=n)},update(n){e=n,t.notify()},isGranted(){return e===at.GRANTED},observable:t}}function V(e,t,n){if(typeof e!="object"||e===null)return JSON.stringify(e);const r=te(Object.prototype),o=te(Array.prototype),s=te(Object.getPrototypeOf(e)),i=te(e);try{return JSON.stringify(e,t,n)}catch{return"<error: unable to serialize object>"}finally{r(),o(),s(),i()}}function te(e){const t=e,n=t.toJSON;return n?(delete t.toJSON,()=>{t.toJSON=n}):U}function ct(e){return Fr(e,location.href).href}function Fr(e,t){const n=Dr();if(n)try{return t!==void 0?new n(e,t):new n(e)}catch(s){throw new Error(`Failed to construct URL: ${String(s)} ${V({url:e,base:t})}`)}if(t===void 0&&!/:/.test(e))throw new Error(`Invalid URL: \'${e}\'`);let r=document;const o=r.createElement("a");if(t!==void 0){r=document.implementation.createHTMLDocument("");const s=r.createElement("base");s.href=t,r.head.appendChild(s),r.body.appendChild(o)}return o.href=e,o}const Jt=URL;let Ne;function Dr(){if(Ne===void 0)try{Ne=new Jt("http://test/path").href==="http://test/path"}catch{Ne=!1}return Ne?Jt:void 0}const $r="datad0g.com",Ur="dd0g-gov.com",ne="datadoghq.com",Br="ddog-gov.com",Gr="pci.browser-intake-datadoghq.com",jr=["ddsource","ddtags"];function Se(e,t,n){const r=Wr(e,t);return{build(o,s){const i=zr(e,t,n,o,s);return r(i)},urlPrefix:r(""),trackType:t}}function Wr(e,t){const n=`/api/v2/${t}`,r=e.proxy;if(typeof r=="string"){const s=ct(r);return i=>`${s}?ddforward=${encodeURIComponent(`${n}?${i}`)}`}if(typeof r=="function")return s=>r({path:n,parameters:s});const o=Hr(t,e);return s=>`https://${o}${n}?${s}`}function Hr(e,t){const{site:n=ne,internalAnalyticsSubdomain:r}=t;if(e==="logs"&&t.usePciIntake&&n===ne)return Gr;if(r&&n===ne)return`${r}.${ne}`;if(n===Ur)return`http-intake.logs.${n}`;const o=n.split("."),s=o.pop();return`browser-intake-${o.join("-")}.${s}`}function zr({clientToken:e,internalAnalyticsSubdomain:t},n,r,o,{retry:s,encoding:i}){const a=["sdk_version:6.5.0",`api:${o}`].concat(r);s&&a.push(`retry_count:${s.count}`,`retry_after:${s.lastFailureStatus}`);const c=["ddsource=browser",`ddtags=${encodeURIComponent(a.join(","))}`,`dd-api-key=${e}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${B()}`];return i&&c.push(`dd-evp-encoding=${i}`),n==="rum"&&c.push(`batch_time=${F()}`),t&&c.reverse(),c.join("&")}const Kr=200;function Vr(e){const{env:t,service:n,version:r,datacenter:o}=e,s=[];return t&&s.push(Fe("env",t)),n&&s.push(Fe("service",n)),r&&s.push(Fe("version",r)),o&&s.push(Fe("datacenter",o)),s}function Fe(e,t){const n=Kr-e.length-1;(t.length>n||qr(t))&&_.warn(`${e} value doesn\'t meet tag requirements and will be sanitized. ${Ce} ${Xe}/getting_started/tagging/#defining-tags`);const r=t.replace(/,/g,"_");return`${e}:${r}`}function qr(e){return Yr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(e):!1}function Yr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function Xr(e){const t=e.site||ne,n=Vr(e),r=Jr(e,n);return{replica:Qr(e,n),site:t,...r}}function Jr(e,t){return{logsEndpointBuilder:Se(e,"logs",t),rumEndpointBuilder:Se(e,"rum",t),sessionReplayEndpointBuilder:Se(e,"replay",t)}}function Qr(e,t){if(!e.replica)return;const n={...e,site:ne,clientToken:e.replica.clientToken},r={logsEndpointBuilder:Se(n,"logs",t),rumEndpointBuilder:Se(n,"rum",t)};return{applicationId:e.replica.applicationId,...r}}function Zr(e){return jr.every(t=>e.includes(t))}function ut(e,t){return e!=null&&typeof e!="string"?(_.error(`${t} must be defined as a string`),!1):!0}function eo(e){return e&&typeof e=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(e)?(_.error(`Site should be a valid Datadog site. ${Ce} ${Xe}/getting_started/site/.`),!1):!0}function De(e,t){return e!==void 0&&!Hn(e)?(_.error(`${t} Sample Rate should be a number between 0 and 100`),!1):!0}function to(e){var t,n,r,o,s,i;if(!e||!e.clientToken){_.error("Client Token is not configured, we will not send any data.");return}if(!(!eo(e.site)||!De(e.sessionSampleRate,"Session")||!De(e.telemetrySampleRate,"Telemetry")||!De(e.telemetryConfigurationSampleRate,"Telemetry Configuration")||!De(e.telemetryUsageSampleRate,"Telemetry Usage")||!ut(e.version,"Version")||!ut(e.env,"Env")||!ut(e.service,"Service"))){if(e.trackingConsent!==void 0&&!Mt(at,e.trackingConsent)){_.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:e.beforeSend&&At(e.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:Mr(e),sessionSampleRate:(t=e.sessionSampleRate)!==null&&t!==void 0?t:100,telemetrySampleRate:(n=e.telemetrySampleRate)!==null&&n!==void 0?n:20,telemetryConfigurationSampleRate:(r=e.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(o=e.telemetryUsageSampleRate)!==null&&o!==void 0?o:5,service:e.service||void 0,silentMultipleInit:!!e.silentMultipleInit,allowUntrustedEvents:!!e.allowUntrustedEvents,trackingConsent:(s=e.trackingConsent)!==null&&s!==void 0?s:at.GRANTED,trackAnonymousUser:(i=e.trackAnonymousUser)!==null&&i!==void 0?i:!0,storeContextsAcrossPages:!!e.storeContextsAcrossPages,batchBytesLimit:16*L,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*le,batchMessagesLimit:50,messageBytesLimit:256*L,...Xr(e)}}}function no(e){return{session_sample_rate:e.sessionSampleRate,telemetry_sample_rate:e.telemetrySampleRate,telemetry_configuration_sample_rate:e.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:e.telemetryUsageSampleRate,use_before_send:!!e.beforeSend,use_partitioned_cross_site_session_cookie:e.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:e.useSecureSessionCookie,use_proxy:!!e.proxy,silent_multiple_init:e.silentMultipleInit,track_session_across_subdomains:e.trackSessionAcrossSubdomains,track_anonymous_user:e.trackAnonymousUser,session_persistence:e.sessionPersistence,allow_fallback_to_local_storage:!!e.allowFallbackToLocalStorage,store_contexts_across_pages:!!e.storeContextsAcrossPages,allow_untrusted_events:!!e.allowUntrustedEvents,tracking_consent:e.trackingConsent}}var lt;(function(e){e.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",e.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(lt||(lt={}));const Qt=new Set;function ro(e){Array.isArray(e)&&oo(e.filter(t=>Mt(lt,t)))}function oo(e){e.forEach(t=>{Qt.add(t)})}function so(){return Qt}const be="?";function I(e){const t=[];let n=dt(e,"stack");const r=String(e);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`\n`).forEach(o=>{const s=co(o)||lo(o)||po(o)||ho(o);s&&(!s.func&&s.line&&(s.func=be),t.push(s))}),{message:dt(e,"message"),name:dt(e,"name"),stack:t}}const Zt="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",re="(?::(\\\\d+))",io=new RegExp(`^\\\\s*at (.*?) ?\\\\(${Zt}${re}?${re}?\\\\)?\\\\s*$`,"i"),ao=new RegExp(`\\\\((\\\\S*)${re}${re}\\\\)`);function co(e){const t=io.exec(e);if(!t)return;const n=t[2]&&t[2].indexOf("native")===0,r=t[2]&&t[2].indexOf("eval")===0,o=ao.exec(t[2]);return r&&o&&(t[2]=o[1],t[3]=o[2],t[4]=o[3]),{args:n?[t[2]]:[],column:t[4]?+t[4]:void 0,func:t[1]||be,line:t[3]?+t[3]:void 0,url:n?void 0:t[2]}}const uo=new RegExp(`^\\\\s*at ?${Zt}${re}?${re}??\\\\s*$`,"i");function lo(e){const t=uo.exec(e);if(t)return{args:[],column:t[3]?+t[3]:void 0,func:be,line:t[2]?+t[2]:void 0,url:t[1]}}const fo=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function po(e){const t=fo.exec(e);if(t)return{args:[],column:t[4]?+t[4]:void 0,func:t[1]||be,line:+t[3],url:t[2]}}const mo=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,go=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function ho(e){const t=mo.exec(e);if(!t)return;const n=t[3]&&t[3].indexOf(" > eval")>-1,r=go.exec(t[3]);return n&&r&&(t[3]=r[1],t[4]=r[2],t[5]=void 0),{args:t[2]?t[2].split(","):[],column:t[5]?+t[5]:void 0,func:t[1]||be,line:t[4]?+t[4]:void 0,url:t[3]}}function dt(e,t){if(typeof e!="object"||!e||!(t in e))return;const n=e[t];return typeof n=="string"?n:void 0}function So(e,t,n,r){const o=[{url:t,column:r,line:n}],{name:s,message:i}=yo(e);return{name:s,message:i,stack:o}}const bo=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function yo(e){let t,n;return{}.toString.call(e)==="[object String]"&&([,t,n]=bo.exec(e)),{name:t,message:n}}function $e(e){const n=new Error(e);n.name="HandlingStack";let r;return pe(()=>{const o=I(n);o.stack=o.stack.slice(2),r=q(o)}),r}function q(e){let t=en(e);return e.stack.forEach(n=>{const r=n.func==="?"?"<anonymous>":n.func,o=n.args&&n.args.length>0?`(${n.args.join(", ")})`:"",s=n.line?`:${n.line}`:"",i=n.line&&n.column?`:${n.column}`:"";t+=`\n at ${r}${o} @ ${n.url}${s}${i}`}),t}function en(e){return`${e.name||"Error"}: ${e.message}`}function Y(e,t,n,{computeHandlingStack:r}={}){let o=e[t];if(typeof o!="function")if(t in e&&t.startsWith("on"))o=U;else return{stop:U};let s=!1;const i=function(){if(s)return o.apply(this,arguments);const a=Array.from(arguments);let c;pe(n,null,[{target:this,parameters:a,onPostCall:u=>{c=u},handlingStack:r?$e("instrumented method"):void 0}]);const l=o.apply(this,a);return c&&pe(c,null,[l]),l};return e[t]=i,{stop:()=>{s=!0,e[t]===i&&(e[t]=o)}}}const Eo=220*L,_o="$",To=3;function k(e,t=Eo){const n=te(Object.prototype),r=te(Array.prototype),o=[],s=new WeakMap,i=ft(e,_o,void 0,o,s),a=JSON.stringify(i);let c=a?a.length:0;if(c>t){mt(t,"discarded",e);return}for(;o.length>0&&c<t;){const l=o.shift();let u=0;if(Array.isArray(l.source))for(let d=0;d<l.source.length;d++){const f=ft(l.source[d],l.path,d,o,s);if(f!==void 0?c+=JSON.stringify(f).length:c+=4,c+=u,u=1,c>t){mt(t,"truncated",e);break}l.target[d]=f}else for(const d in l.source)if(Object.prototype.hasOwnProperty.call(l.source,d)){const f=ft(l.source[d],l.path,d,o,s);if(f!==void 0&&(c+=JSON.stringify(f).length+u+d.length+To,u=1),c>t){mt(t,"truncated",e);break}l.target[d]=f}}return n(),r(),i}function ft(e,t,n,r,o){const s=Oo(e);if(!s||typeof s!="object")return wo(s);const i=pt(s);if(i!=="[Object]"&&i!=="[Array]"&&i!=="[Error]")return i;const a=e;if(o.has(a))return`[Reference seen at ${o.get(a)}]`;const c=n!==void 0?`${t}.${n}`:t,l=Array.isArray(s)?[]:{};return o.set(a,c),r.push({source:s,target:l,path:c}),l}function wo(e){return typeof e=="bigint"?`[BigInt] ${e.toString()}`:typeof e=="function"?`[Function] ${e.name||"unknown"}`:typeof e=="symbol"?`[Symbol] ${e.description||e.toString()}`:e}function pt(e){try{if(e instanceof Event)return Co(e);if(e instanceof RegExp)return`[RegExp] ${e.toString()}`;const n=Object.prototype.toString.call(e).match(/\\[object (.*)\\]/);if(n&&n[1])return`[${n[1]}]`}catch{}return"[Unserializable]"}function Co(e){return{type:e.type,isTrusted:e.isTrusted,currentTarget:e.currentTarget?pt(e.currentTarget):null,target:e.target?pt(e.target):null}}function Oo(e){const t=e;if(t&&typeof t.toJSON=="function")try{return t.toJSON()}catch{}return e}function mt(e,t,n){_.warn(`The data provided has been ${t} as it is over the limit of ${e} characters:`,n)}const tn="No stack, consider using an instance of Error";function nn({stackTrace:e,originalError:t,handlingStack:n,componentStack:r,startClocks:o,nonErrorPrefix:s,source:i,handling:a}){const c=G(t),l=vo(e,c,s,t),u=Ro(c,e)?q(e):tn,d=c?sn(t,i):void 0,f=e?e.name:void 0,g=rn(t),m=on(t);return{startClocks:o,source:i,handling:a,handlingStack:n,componentStack:r,originalError:t,type:f,message:l,stack:u,causes:d,fingerprint:g,context:m}}function vo(e,t,n,r){return e!=null&&e.message&&(e!=null&&e.name)?e.message:t?"Empty message":`${n} ${V(k(r))}`}function Ro(e,t){return t===void 0?!1:e?!0:t.stack.length>0&&(t.stack.length>1||t.stack[0].url!==void 0)}function rn(e){return G(e)&&"dd_fingerprint"in e?String(e.dd_fingerprint):void 0}function on(e){if(e!==null&&typeof e=="object"&&"dd_context"in e)return e.dd_context}function xo(e){var t;return(t=/@ (.+)/.exec(e))===null||t===void 0?void 0:t[1]}function G(e){return e instanceof Error||Object.prototype.toString.call(e)==="[object Error]"}function sn(e,t){let n=e;const r=[];for(;G(n==null?void 0:n.cause)&&r.length<10;){const o=I(n.cause);r.push({message:n.cause.message,source:t,type:o==null?void 0:o.name,stack:q(o)}),n=n.cause}return r.length?r:void 0}const R={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function Ao(e){const t=(o,s)=>{const i=nn({stackTrace:o,originalError:s,startClocks:D(),nonErrorPrefix:"Uncaught",source:R.SOURCE,handling:"unhandled"});e.notify(i)},{stop:n}=Lo(t),{stop:r}=Io(t);return{stop:()=>{n(),r()}}}function Lo(e){return Y(window,"onerror",({parameters:[t,n,r,o,s]})=>{let i;G(s)?i=I(s):i=So(t,n,r,o),e(i,s??t)})}function Io(e){return Y(window,"onunhandledrejection",({parameters:[t]})=>{const n=t.reason||"Empty reason",r=I(n);e(r,n)})}function ko(e){const t={version:"6.5.0",onReady(n){n()},...e};return Object.defineProperty(t,"_setDebug",{get(){return er},enumerable:!1}),t}function Mo(e,t,n){const r=e[t];r&&!r.q&&r.version&&_.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),e[t]=n,r&&r.q&&r.q.forEach(o=>At(o,"onReady callback threw an error:")())}function an(e,t){t.silentMultipleInit||_.error(`${e} is already initialized.`)}function X(e,t,n,r,o){return gt(e,t,[n],r,o)}function gt(e,t,n,r,{once:o,capture:s,passive:i}={}){const a=b(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!e.allowUntrustedEvents||(o&&d(),r(f))}),c=i?{capture:s,passive:i}:s,l=window.EventTarget&&t instanceof EventTarget?window.EventTarget.prototype:t,u=Z(l,"addEventListener");n.forEach(f=>u.call(t,f,a,c));function d(){const f=Z(l,"removeEventListener");n.forEach(g=>f.call(t,g,a,c))}return{stop:d}}const Ue={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function Po(e,t){const n=[];t.includes(Ue.cspViolation)&&n.push(Fo(e));const r=t.filter(o=>o!==Ue.cspViolation);return r.length&&n.push(No(r)),Dt(...n)}function No(e){return new w(t=>{if(!window.ReportingObserver)return;const n=b((o,s)=>o.forEach(i=>t.notify(Do(i)))),r=new window.ReportingObserver(n,{types:e,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function Fo(e){return new w(t=>{const{stop:n}=X(e,document,"securitypolicyviolation",r=>{t.notify($o(r))});return n})}function Do(e){const{type:t,body:n}=e;return cn({type:n.id,message:`${t}: ${n.message}`,originalError:e,stack:un(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function $o(e){const t=`\'${e.blockedURI}\' blocked by \'${e.effectiveDirective}\' directive`;return cn({type:e.effectiveDirective,message:`${Ue.cspViolation}: ${t}`,originalError:e,csp:{disposition:e.disposition},stack:un(e.effectiveDirective,e.originalPolicy?`${t} of the policy "${sr(e.originalPolicy,100,"...")}"`:"no policy",e.sourceFile,e.lineNumber,e.columnNumber)})}function cn(e){return{startClocks:D(),source:R.REPORT,handling:"unhandled",...e}}function un(e,t,n,r,o){return n?q({name:e,message:t,stack:[{func:"?",url:n,line:r??void 0,column:o??void 0}]}):void 0}function ln(e,t){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:e,payload:t})}function dn(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Be(e,t,n=Uo()){if(t===void 0)return e;if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=t.flags||[t.global?"g":"",t.ignoreCase?"i":"",t.multiline?"m":"",t.sticky?"y":"",t.unicode?"u":""].join("");return new RegExp(t.source,o)}if(n.hasAlreadyBeenSeen(t))return;if(Array.isArray(t)){const o=Array.isArray(e)?e:[];for(let s=0;s<t.length;++s)o[s]=Be(o[s],t[s],n);return o}const r=dn(e)==="object"?e:{};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=Be(r[o],t[o],n));return r}function fn(e){return Be(void 0,e)}function oe(...e){let t;for(const n of e)n!=null&&(t=Be(t,n));return t}function Uo(){if(typeof WeakSet<"u"){const t=new WeakSet;return{hasAlreadyBeenSeen(n){const r=t.has(n);return r||t.add(n),r}}}const e=[];return{hasAlreadyBeenSeen(t){const n=e.indexOf(t)>=0;return n||e.push(t),n}}}function Bo(){var e;const t=window.navigator;return{status:t.onLine?"connected":"not_connected",interfaces:t.connection&&t.connection.type?[t.connection.type]:void 0,effective_type:(e=t.connection)===null||e===void 0?void 0:e.effectiveType}}function Go(e){const t=new Set;return e.forEach(n=>t.add(n)),Array.from(t)}function pn(e,t){const n=e.indexOf(t);n>=0&&e.splice(n,1)}const jo=500;function mn(){const e=[];return{add:o=>{e.push(o)>jo&&e.splice(0,1)},remove:o=>{pn(e,o)},drain:o=>{e.forEach(s=>s(o)),e.length=0}}}const J={log:"log",configuration:"configuration",usage:"usage"},Wo=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],Ho=[Br];let gn=mn(),se=e=>{gn.add(()=>se(e))};function zo(e,t){let n;const r=new w,o=new Set,s=!Ho.includes(t.site)&&Oe(t.telemetrySampleRate),i={[J.log]:s,[J.configuration]:s&&Oe(t.telemetryConfigurationSampleRate),[J.usage]:s&&Oe(t.telemetryUsageSampleRate)},a=Ko();se=l=>{const u=V(l);if(i[l.type]&&o.size<t.maxTelemetryEventsPerPage&&!o.has(u)){const d=c(e,l,a);r.notify(d),ln("telemetry",d),o.add(u)}},Zn(Sn);function c(l,u,d){return oe({type:"telemetry",date:F(),service:l,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:oe(u,{runtime_env:d,connectivity:Bo(),sdk_setup:"npm"}),experimental_features:Array.from(so())},n!==void 0?n():{})}return{setContextProvider:l=>{n=l},observable:r,enabled:s}}function Ko(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function Vo(){gn.drain()}function qo(e){return e.site===$r}function hn(e,t){Ze(E.debug,e,t),se({type:J.log,message:e,status:"debug",...t})}function Sn(e,t){se({type:J.log,status:"error",...Jo(e),...t})}function Yo(e){se({type:J.configuration,configuration:e})}function Xo(e){se({type:J.usage,usage:e})}function Jo(e){if(G(e)){const t=I(e);return{error:{kind:t.name,stack:q(Qo(t))},message:t.message}}return{error:{stack:tn},message:`Uncaught ${V(e)}`}}function Qo(e){return e.stack=e.stack.filter(t=>!t.url||Wo.some(n=>t.url.startsWith(n))),e}const ye=1/0,Zo=W;let Ee=null;const Ge=new Set;function es(){Ge.forEach(e=>e())}function ts({expireDelay:e,maxEntries:t}){let n=[];const r=[];Ee||(Ee=et(()=>es(),Zo));const o=()=>{const g=ve()-e;for(;n.length>0&&n[n.length-1].endTime<g;){const m=n.pop();m&&r.push(m.startTime)}};Ge.add(o);function s(g,m){const y={value:g,startTime:m,endTime:ye,remove:()=>{pn(n,y)},close:p=>{y.endTime=p}};return t&&n.length>=t&&n.pop(),n.unshift(y),y}function i(g=ye,m={returnInactive:!1}){for(const y of n)if(y.startTime<=g){if(m.returnInactive||g<=y.endTime)return y.value;break}}function a(g){const m=n[0];m&&m.endTime===ye&&m.close(g)}function c(g=ye,m=0){const y=Yn(g,m);return n.filter(p=>p.startTime<=y&&g<=p.endTime).map(p=>p.value)}function l(){return n.map(({startTime:g,endTime:m,value:y})=>({startTime:g,endTime:m===ye?"Infinity":m,value:y}))}function u(){return r}function d(){n=[]}function f(){Ge.delete(o),Ge.size===0&&Ee&&(Ft(Ee),Ee=null)}return{add:s,find:i,closeActive:a,findAll:c,reset:d,stop:f,getAllEntries:l,getDeletedEntries:u}}const ns=W,rs=ot;function os(e,t,n,r){const o=new w,s=new w,i=Pr(e.sessionStoreStrategyType,e,t,n),a=ts({expireDelay:rs});i.renewObservable.subscribe(()=>{a.add(c(),ve()),o.notify()}),i.expireObservable.subscribe(()=>{s.notify(),a.closeActive(ve())}),i.expandOrRenewSession(),a.add(c(),Vn().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),ss(e,()=>{r.isGranted()&&i.expandOrRenewSession()}),is(e,()=>i.expandSession()),as(e,()=>i.restartSession());function c(){return{id:i.getSession().id,trackingType:i.getSession()[t],isReplayForced:!!i.getSession().forcedReplay,anonymousId:i.getSession().anonymousId}}return{findSession:(l,u)=>a.find(l,u),renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i.sessionStateUpdateObservable,expire:i.expire,updateSessionState:i.updateSessionState}}function ss(e,t){gt(e,window,["click","touchstart","keydown","scroll"],t,{capture:!0,passive:!0})}function is(e,t){const n=()=>{document.visibilityState==="visible"&&t()};X(e,document,"visibilitychange",n),et(n,ns)}function as(e,t){X(e,window,"resume",t,{capture:!0})}function bn(e){return e>=500}function cs(e){try{return e.clone()}catch{return}}const us=80*L,ls=32,yn=3*kt,ds=W,En=le;function _n(e,t,n,r,o){t.transportStatus===0&&t.queuedPayloads.size()===0&&t.bandwidthMonitor.canHandle(e)?wn(e,t,n,{onSuccess:()=>Cn(0,t,n,r,o),onFailure:()=>{t.queuedPayloads.enqueue(e),Tn(t,n,r,o)}}):t.queuedPayloads.enqueue(e)}function Tn(e,t,n,r){e.transportStatus===2&&me(()=>{const o=e.queuedPayloads.first();wn(o,e,t,{onSuccess:()=>{e.queuedPayloads.dequeue(),e.currentBackoffTime=En,Cn(1,e,t,n,r)},onFailure:()=>{e.currentBackoffTime=Math.min(ds,e.currentBackoffTime*2),Tn(e,t,n,r)}})},e.currentBackoffTime)}function wn(e,t,n,{onSuccess:r,onFailure:o}){t.bandwidthMonitor.add(e),n(e,s=>{t.bandwidthMonitor.remove(e),fs(s)?(t.transportStatus=t.bandwidthMonitor.ongoingRequestCount>0?1:2,e.retry={count:e.retry?e.retry.count+1:1,lastFailureStatus:s.status},o()):(t.transportStatus=0,r())})}function Cn(e,t,n,r,o){e===0&&t.queuedPayloads.isFull()&&!t.queueFullReported&&(o({message:`Reached max ${r} events size queued for upload: ${yn/kt}MiB`,source:R.AGENT,startClocks:D()}),t.queueFullReported=!0);const s=t.queuedPayloads;for(t.queuedPayloads=On();s.size()>0;)_n(s.dequeue(),t,n,r,o)}function fs(e){return e.type!=="opaque"&&(e.status===0&&!navigator.onLine||e.status===408||e.status===429||bn(e.status))}function ps(){return{transportStatus:0,currentBackoffTime:En,bandwidthMonitor:ms(),queuedPayloads:On(),queueFullReported:!1}}function On(){const e=[];return{bytesCount:0,enqueue(t){this.isFull()||(e.push(t),this.bytesCount+=t.bytesCount)},first(){return e[0]},dequeue(){const t=e.shift();return t&&(this.bytesCount-=t.bytesCount),t},size(){return e.length},isFull(){return this.bytesCount>=yn}}}function ms(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(e){return this.ongoingRequestCount===0||this.ongoingByteCount+e.bytesCount<=us&&this.ongoingRequestCount<ls},add(e){this.ongoingRequestCount+=1,this.ongoingByteCount+=e.bytesCount},remove(e){this.ongoingRequestCount-=1,this.ongoingByteCount-=e.bytesCount}}}function gs(e,t,n){const r=ps(),o=(s,i)=>bs(e,t,s,i);return{send:s=>{_n(s,r,o,e.trackType,n)},sendOnExit:s=>{hs(e,t,s)}}}function hs(e,t,n){if(!!navigator.sendBeacon&&n.bytesCount<t)try{const s=e.build("beacon",n);if(navigator.sendBeacon(s,n.data))return}catch(s){Ss(s)}const o=e.build("xhr",n);ht(o,n.data)}let vn=!1;function Ss(e){vn||(vn=!0,Sn(e))}function bs(e,t,n,r){if(ys()&&n.bytesCount<t){const s=e.build("fetch",n);fetch(s,{method:"POST",body:n.data,keepalive:!0,mode:"cors"}).then(b(i=>r==null?void 0:r({status:i.status,type:i.type})),b(()=>{const i=e.build("xhr",n);ht(i,n.data,r)}))}else{const s=e.build("xhr",n);ht(s,n.data,r)}}function ys(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function ht(e,t,n){const r=new XMLHttpRequest;r.open("POST",e,!0),t instanceof Blob&&r.setRequestHeader("Content-Type",t.type),X({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(t)}function St(){const e=Es();if(e)return{getCapabilities(){var t;return JSON.parse(((t=e.getCapabilities)===null||t===void 0?void 0:t.call(e))||"[]")},getPrivacyLevel(){var t;return(t=e.getPrivacyLevel)===null||t===void 0?void 0:t.call(e)},getAllowedWebViewHosts(){return JSON.parse(e.getAllowedWebViewHosts())},send(t,n,r){const o=r?{id:r}:void 0;e.send(JSON.stringify({eventType:t,event:n,view:o}))}}}function je(e){var t;e===void 0&&(e=(t=$().location)===null||t===void 0?void 0:t.hostname);const n=St();return!!n&&n.getAllowedWebViewHosts().some(r=>e===r||e.endsWith(`.${r}`))}function Es(){return $().DatadogEventBridge}const We={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function _s(e){return new w(t=>{const{stop:n}=gt(e,window,["visibilitychange","freeze"],o=>{o.type==="visibilitychange"&&document.visibilityState==="hidden"?t.notify({reason:We.HIDDEN}):o.type==="freeze"&&t.notify({reason:We.FROZEN})},{capture:!0}),r=X(e,window,"beforeunload",()=>{t.notify({reason:We.UNLOADING})}).stop;return()=>{n(),r()}})}function Ts(e){return Le(We).includes(e)}function ws({encoder:e,request:t,flushController:n,messageBytesLimit:r}){let o={};const s=n.flushObservable.subscribe(d=>u(d));function i(d,f,g){n.notifyBeforeAddMessage(f),g!==void 0?(o[g]=d,n.notifyAfterAddMessage()):e.write(e.isEmpty?d:`\n${d}`,m=>{n.notifyAfterAddMessage(m-f)})}function a(d){return d!==void 0&&o[d]!==void 0}function c(d){const f=o[d];delete o[d];const g=e.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(g)}function l(d,f){const g=V(d),m=e.estimateEncodedBytesCount(g);if(m>=r){_.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${Ce} ${xt}/#technical-limitations`);return}a(f)&&c(f),i(g,m,f)}function u(d){const f=Le(o).join(`\n`);o={};const g=Ts(d.reason),m=g?t.sendOnExit:t.send;if(g&&e.isAsync){const y=e.finishSync();y.outputBytesCount&&m(Rn(y));const p=[y.pendingData,f].filter(Boolean).join(`\n`);p&&m({data:p,bytesCount:Qe(p)})}else f&&e.write(e.isEmpty?f:`\n${f}`),e.finish(y=>{m(Rn(y))})}return{flushController:n,add:l,upsert:l,stop:s.unsubscribe}}function Rn(e){let t;return typeof e.output=="string"?t=e.output:t=new Blob([e.output],{type:"text/plain"}),{data:t,bytesCount:e.outputBytesCount,encoding:e.encoding}}function Cs({messagesLimit:e,bytesLimit:t,durationLimit:n,pageExitObservable:r,sessionExpireObservable:o}){const s=r.subscribe(m=>u(m.reason)),i=o.subscribe(()=>u("session_expire")),a=new w(()=>()=>{s.unsubscribe(),i.unsubscribe()});let c=0,l=0;function u(m){if(l===0)return;const y=l,p=c;l=0,c=0,g(),a.notify({reason:m,messagesCount:y,bytesCount:p})}let d;function f(){d===void 0&&(d=me(()=>{u("duration_limit")},n))}function g(){Nt(d),d=void 0}return{flushObservable:a,get messagesCount(){return l},notifyBeforeAddMessage(m){c+m>=t&&u("bytes_limit"),l+=1,c+=m,f()},notifyAfterAddMessage(m=0){c+=m,l>=e?u("messages_limit"):c>=t&&u("bytes_limit")},notifyAfterRemoveMessage(m){c-=m,l-=1,l===0&&g()}}}function xn(e,t,n,r,o,s,i=ws){const a=l(e,t),c=n&&l(e,n);function l(u,{endpoint:d,encoder:f}){return i({encoder:f,request:gs(d,u.batchBytesLimit,r),flushController:Cs({messagesLimit:u.batchMessagesLimit,bytesLimit:u.batchBytesLimit,durationLimit:u.flushTimeout,pageExitObservable:o,sessionExpireObservable:s}),messageBytesLimit:u.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(u,d=!0){a.add(u),c&&d&&c.add(n.transformMessage?n.transformMessage(u):u)},upsert:(u,d)=>{a.upsert(u,d),c&&c.upsert(n.transformMessage?n.transformMessage(u):u,d)},stop:()=>{a.stop(),c&&c.stop()}}}function He(){let e="",t=0;return{isAsync:!1,get isEmpty(){return!e},write(n,r){const o=Qe(n);t+=o,e+=n,r&&r(o)},finish(n){n(this.finishSync())},finishSync(){const n={output:e,outputBytesCount:t,rawBytesCount:t,pendingData:""};return e="",t=0,n},estimateEncodedBytesCount(n){return n.length}}}class Os{constructor(){this.callbacks={}}notify(t,n){const r=this.callbacks[t];r&&r.forEach(o=>o(n))}subscribe(t,n){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(n),{unsubscribe:()=>{this.callbacks[t]=this.callbacks[t].filter(r=>n!==r)}}}}function vs(e,t,n){let r=0,o=!1;return{isLimitReached(){if(r===0&&me(()=>{r=0},W),r+=1,r<=t||o)return o=!1,!1;if(r===t+1){o=!0;try{n({message:`Reached max number of ${e}s by minute: ${t}`,source:R.AGENT,startClocks:D()})}finally{o=!1}}return!0}}}let bt;const yt=new WeakMap;function Rs(e){return bt||(bt=xs(e)),bt}function xs(e){return new w(t=>{const{stop:n}=Y(XMLHttpRequest.prototype,"open",As),{stop:r}=Y(XMLHttpRequest.prototype,"send",s=>{Ls(s,e,t)},{computeHandlingStack:!0}),{stop:o}=Y(XMLHttpRequest.prototype,"abort",Is);return()=>{n(),r(),o()}})}function As({target:e,parameters:[t,n]}){yt.set(e,{state:"open",method:String(t).toUpperCase(),url:ct(String(n))})}function Ls({target:e,handlingStack:t},n,r){const o=yt.get(e);if(!o)return;const s=o;s.state="start",s.startClocks=D(),s.isAborted=!1,s.xhr=e,s.handlingStack=t;let i=!1;const{stop:a}=Y(e,"onreadystatechange",()=>{e.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(l(),a(),i)return;i=!0;const u=o;u.state="complete",u.duration=qn(s.startClocks.timeStamp,F()),u.status=e.status,r.notify(Qn(u))},{stop:l}=X(n,e,"loadend",c);r.notify(s)}function Is({target:e}){const t=yt.get(e);t&&(t.isAborted=!0)}let Et;function An(){return Et||(Et=ks()),Et}function ks(){return new w(e=>{if(!window.fetch)return;const{stop:t}=Y(window,"fetch",n=>Ms(n,e),{computeHandlingStack:!0});return t})}function Ms({parameters:e,onPostCall:t,handlingStack:n},r){const[o,s]=e;let i=s&&s.method;i===void 0&&o instanceof Request&&(i=o.method);const a=i!==void 0?String(i).toUpperCase():"GET",c=o instanceof Request?o.url:ct(String(o)),l=D(),u={state:"start",init:s,input:o,method:a,startClocks:l,url:c,handlingStack:n};r.notify(u),e[0]=u.input,e[1]=u.init,t(d=>Ps(r,d,u))}function Ps(e,t,n){const r=n;function o(s){r.state="resolve",Object.assign(r,s),e.notify(r)}t.then(b(s=>{o({response:s,responseType:s.type,status:s.status,isAborted:!1})}),b(s=>{var i,a;o({status:0,isAborted:((a=(i=r.init)===null||i===void 0?void 0:i.signal)===null||a===void 0?void 0:a.aborted)||s instanceof DOMException&&s.code===DOMException.ABORT_ERR,error:s})}))}let _t={};function Ns(e){const t=e.map(n=>(_t[n]||(_t[n]=Fs(n)),_t[n]));return Dt(...t)}function Fs(e){return new w(t=>{const n=A[e];return A[e]=(...r)=>{n.apply(console,r);const o=$e("console error");pe(()=>{t.notify(Ds(r,e,o))})},()=>{A[e]=n}})}function Ds(e,t,n){const r=e.map(s=>$s(s)).join(" ");let o;if(t===E.error){const s=e.find(G);o={stack:s?q(I(s)):void 0,fingerprint:rn(s),causes:s?sn(s,"console"):void 0,startClocks:D(),message:r,source:R.CONSOLE,handling:"handled",handlingStack:n,context:on(s)}}return{api:t,message:r,error:o,handlingStack:n}}function $s(e){return typeof e=="string"?k(e):G(e)?en(I(e)):V(k(e),void 0,2)}function Us(e){const t=dn(e)==="object";return t||_.error("Unsupported context:",e),t}function Tt(e,t,n){const r={...e};for(const[o,{required:s,type:i}]of Object.entries(t))i==="string"&&o in r&&(r[o]=String(r[o])),s&&!(o in e)&&_.warn(`The property ${o} of ${n} is required; context will not be sent to the intake.`);return r}function ze(e="",{customerDataTracker:t,propertiesConfig:n={}}={}){let r={};const o=new w,s={getContext:()=>fn(r),setContext:i=>{Us(i)?(r=k(Tt(i,n,e)),t==null||t.updateCustomerData(r)):s.clearContext(),o.notify()},setContextProperty:(i,a)=>{r=k(Tt({...r,[i]:a},n,e)),t==null||t.updateCustomerData(r),o.notify()},removeContextProperty:i=>{delete r[i],t==null||t.updateCustomerData(r),Tt(r,n,e),o.notify()},clearContext:()=>{r={},t==null||t.resetCustomerData(),o.notify()},changeObservable:o};return s}const Bs="_dd_c",Gs=[];function wt(e,t,n,r){const o=js(n,r);Gs.push(X(e,window,"storage",({key:l})=>{o===l&&i()})),t.changeObservable.subscribe(a);const s=oe(c(),t.getContext());fe(s)||t.setContext(s);function i(){t.setContext(c())}function a(){localStorage.setItem(o,JSON.stringify(t.getContext()))}function c(){const l=localStorage.getItem(o);return l?JSON.parse(l):{}}}function js(e,t){return`${Bs}_${e}_${t}`}const Ws=3*L,Hs=16*L,zs=200;function Ks(e=2){const t=new Map;let n=!1;function r(o=0){if(n||e===0)return;const s=e===2?Ws:Hs;let i=o;t.forEach(a=>{i+=a.getBytesCount()}),i>s&&(Vs(s),n=!0)}return{createDetachedTracker:()=>{const o=Ln(()=>r(o.getBytesCount()));return o},getOrCreateTracker:o=>(t.has(o)||t.set(o,Ln(r)),t.get(o)),setCompressionStatus:o=>{e===0&&(e=o,r())},getCompressionStatus:()=>e,stop:()=>{t.forEach(o=>o.stop()),t.clear()}}}function Ln(e){let t=0;const{throttled:n,cancel:r}=$t(s=>{t=Qe(V(s)),e()},zs),o=()=>{r(),t=0};return{updateCustomerData:s=>{fe(s)?o():n(s)},resetCustomerData:o,getBytesCount:()=>t,stop:()=>{r()}}}function Vs(e){_.warn(`Customer data exceeds the recommended ${e/L}KiB threshold. ${Ce} ${xt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function qs(e,t,n){const r=e.getReader(),o=[];let s=0;i();function i(){r.read().then(b(c=>{if(c.done){a();return}o.push(c.value),s+=c.value.length,s>n.bytesLimit?a():i()}),b(c=>t(c)))}function a(){r.cancel().catch(U);let c,l;{let u;if(o.length===1)u=o[0];else{u=new Uint8Array(s);let d=0;o.forEach(f=>{u.set(f,d),d+=f.length})}c=u.slice(0,n.bytesLimit),l=u.length>n.bytesLimit}t(void 0,c,l)}}const Ys="datadog-synthetics-public-id",Xs="datadog-synthetics-result-id",Js="datadog-synthetics-injects-rum";function In(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||H(Js))}function Qs(){const e=window._DATADOG_SYNTHETICS_PUBLIC_ID||H(Ys);return typeof e=="string"?e:void 0}function Zs(){const e=window._DATADOG_SYNTHETICS_RESULT_ID||H(Xs);return typeof e=="string"?e:void 0}function Ke(e,t,n){const r=n.getHandler(),o=Array.isArray(r)?r:[r];return kn[e]>=kn[n.getLevel()]&&o.includes(t)}const h={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},kn={[h.ok]:0,[h.debug]:1,[h.info]:2,[h.notice]:4,[h.warn]:5,[h.error]:6,[h.critical]:7,[h.alert]:8,[h.emerg]:9};function Ve(e,{includeMessage:t=!1}={}){return{stack:e.stack,kind:e.type,message:t?e.message:void 0,causes:e.causes,fingerprint:e.fingerprint,handling:e.handling}}var ei=function(e,t,n,r){var o=arguments.length,s=o<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};const _e={console:"console",http:"http",silent:"silent"},ti=Object.keys(h);let x=class{constructor(t,n,r,o=_e.http,s=h.debug,i={}){this.handleLogStrategy=t,this.handlerType=o,this.level=s,this.contextManager=ze("logger",{customerDataTracker:n}),this.contextManager.setContext(i),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(t,n,r=h.info,o,s){const i=k(n);let a;if(o!=null){const c=nn({stackTrace:G(o)?I(o):void 0,originalError:o,nonErrorPrefix:"Provided",source:R.LOGGER,handling:"handled",startClocks:D()});a=oe({error:Ve(c,{includeMessage:!0})},i)}else a=i;this.handleLogStrategy({message:k(t),context:a,status:r},this,s)}log(t,n,r=h.info,o){let s;Ke(r,_e.http,this)&&(s=$e("log")),this.logImplementation(t,n,r,o,s)}setContext(t){this.contextManager.setContext(t)}getContext(){return this.contextManager.getContext()}setContextProperty(t,n){this.contextManager.setContextProperty(t,n)}removeContextProperty(t){this.contextManager.removeContextProperty(t)}clearContext(){this.contextManager.clearContext()}setHandler(t){this.handlerType=t}getHandler(){return this.handlerType}setLevel(t){this.level=t}getLevel(){return this.level}};ei([tr],x.prototype,"logImplementation",null),x.prototype.ok=M(h.ok),x.prototype.debug=M(h.debug),x.prototype.info=M(h.info),x.prototype.notice=M(h.notice),x.prototype.warn=M(h.warn),x.prototype.error=M(h.error),x.prototype.critical=M(h.critical),x.prototype.alert=M(h.alert),x.prototype.emerg=M(h.emerg);function M(e){return function(t,n,r){let o;Ke(e,_e.http,this)&&(o=$e("log")),this.logImplementation(t,n,e,r,o)}}function ni(e,t,n){return{view:{referrer:document.referrer,url:window.location.href},context:e.getContext(),user:t.getContext(),account:n.getContext()}}const ri=32*L;function oi(e){e.usePciIntake===!0&&e.site&&e.site!=="datadoghq.com"&&_.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const t=to(e),n=Mn(e.forwardConsoleLogs,Le(E),"Forward Console Logs"),r=Mn(e.forwardReports,Le(Ue),"Forward Reports");if(!(!t||!n||!r))return e.forwardErrorsToLogs&&!n.includes(E.error)&&n.push(E.error),{forwardErrorsToLogs:e.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:ri,...t}}function Mn(e,t,n){if(e===void 0)return[];if(!(e==="all"||Array.isArray(e)&&e.every(r=>t.includes(r)))){_.error(`${n} should be "all" or an array with allowed values "${t.join(\'", "\')}"`);return}return e==="all"?t:Go(e)}function si(e){const t=no(e);return{forward_errors_to_logs:e.forwardErrorsToLogs,forward_console_logs:e.forwardConsoleLogs,forward_reports:e.forwardReports,use_pci_intake:e.usePciIntake,...t}}function ii(e,t,n){const r=mn();let o,s;const i=t.observable.subscribe(a);function a(){if(!s||!o||!t.isGranted())return;i.unsubscribe();const c=n(o,s);r.drain(c)}return{init(c){if(!c){_.error("Missing configuration");return}if(ro(c.enableExperimentalFeatures),je()&&(c=ai(c)),o=c,s){an("DD_LOGS",c);return}const l=oi(c);l&&(s=l,An().subscribe(U),t.tryToInit(l.trackingConsent),a())},get initConfiguration(){return o},getInternalContext:U,handleLog(c,l,u,d=e(),f=F()){r.add(g=>g.handleLog(c,l,u,d,f))}}}function ai(e){return{...e,clientToken:"empty"}}const Ct="logs";function ci(e){const t=Ks(),n=ze("global context",{customerDataTracker:t.getOrCreateTracker(2)}),r=ze("user",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),o=ze("account",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),s=Nr();function i(){return ni(n,r,o)}let a=ii(i,s,(u,d)=>{u.storeContextsAcrossPages&&(wt(d,n,Ct,2),wt(d,r,Ct,1),wt(d,o,Ct,4));const f=e(u,d,i,s);return a=ui(u,f),f});const c={},l=new x((...u)=>a.handleLog(...u),t.createDetachedTracker());return ko({logger:l,init:b(u=>a.init(u)),setTrackingConsent:b(u=>{s.update(u),Xo({feature:"set-tracking-consent",tracking_consent:u})}),getGlobalContext:b(()=>n.getContext()),setGlobalContext:b(u=>n.setContext(u)),setGlobalContextProperty:b((u,d)=>n.setContextProperty(u,d)),removeGlobalContextProperty:b(u=>n.removeContextProperty(u)),clearGlobalContext:b(()=>n.clearContext()),createLogger:b((u,d={})=>(c[u]=new x((...f)=>a.handleLog(...f),t.createDetachedTracker(),k(u),d.handler,d.level,k(d.context)),c[u])),getLogger:b(u=>c[u]),getInitConfiguration:b(()=>fn(a.initConfiguration)),getInternalContext:b(u=>a.getInternalContext(u)),setUser:b(r.setContext),getUser:b(r.getContext),setUserProperty:b(r.setContextProperty),removeUserProperty:b(r.removeContextProperty),clearUser:b(r.clearContext),setAccount:b(o.setContext),getAccount:b(o.getContext),setAccountProperty:b(o.setContextProperty),removeAccountProperty:b(o.removeContextProperty),clearAccount:b(o.clearContext)})}function ui(e,t){return{init:n=>{an("DD_LOGS",n)},initConfiguration:e,...t}}const li="logs";function di(e,t){const n=os(e,li,r=>pi(e,r),t);return{findTrackedSession:(r,o={returnInactive:!1})=>{const s=n.findSession(r,o);return s&&s.trackingType==="1"?{id:s.id,anonymousId:s.anonymousId}:void 0},expireObservable:n.expireObservable}}function fi(e){const n=Pn(e)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new w}}function Pn(e){return Oe(e.sessionSampleRate)?"1":"0"}function pi(e,t){const n=mi(t)?t:Pn(e);return{trackingType:n,isTracked:n==="1"}}function mi(e){return e==="0"||e==="1"}let Nn=!1;function qe(e){const t=window;if(In()){const r=n(t.DD_RUM_SYNTHETICS);return!r&&!Nn&&(Nn=!0,hn("Logs sent before RUM is injected by the synthetics worker",{testId:Qs(),resultId:Zs()})),r}return n(t.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(e)}}function gi(e,t,n,r,o){const s=ti.concat(["custom"]),i={};s.forEach(a=>{i[a]=vs(a,t.eventRateLimiterThreshold,o)}),n.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:l=void 0,domainContext:u})=>{var d,f;const g=Xn(a.date),m=e.findTrackedSession(g);if(!e.findTrackedSession(g,{returnInactive:!0}))return;const p=l||r();let O;!fe(p.account)&&p.account.id&&(O=p.account),m&&m.anonymousId&&!p.user.anonymous_id&&(p.user.anonymous_id=m.anonymousId);const v=oe({service:t.service,session_id:m?m.id:void 0,session:m?{id:m.id}:void 0,usr:fe(p.user)?void 0:p.user,account:O,view:p.view},p.context,qe(g),a,c);((d=t.beforeSend)===null||d===void 0?void 0:d.call(t,v,u))===!1||v.origin!==R.AGENT&&((f=i[v.status])!==null&&f!==void 0?f:i.custom).isLimitReached()||n.notify(1,v)})}const hi={[E.log]:h.info,[E.debug]:h.debug,[E.info]:h.info,[E.warn]:h.warn,[E.error]:h.error};function Si(e,t){const n=Ns(e.forwardConsoleLogs).subscribe(r=>{var o;const s={rawLogsEvent:{date:F(),message:r.message,origin:R.CONSOLE,error:r.error&&Ve(r.error),status:hi[r.api]},messageContext:(o=r.error)===null||o===void 0?void 0:o.context,domainContext:{handlingStack:r.handlingStack}};t.notify(0,s)});return{stop:()=>{n.unsubscribe()}}}function bi(e,t){const n=Po(e,e.forwardReports).subscribe(r=>{let o=r.message,s;const i=r.originalError.type==="deprecation"?h.warn:h.error;i===h.error?s=Ve(r):r.stack&&(o+=` Found in ${xo(r.stack)}`),t.notify(0,{rawLogsEvent:{date:F(),message:o,origin:R.REPORT,error:s,status:i}})});return{stop:()=>{n.unsubscribe()}}}function yi(e,t){if(!e.forwardErrorsToLogs)return{stop:U};const n=Rs(e).subscribe(s=>{s.state==="complete"&&o("xhr",s)}),r=An().subscribe(s=>{s.state==="resolve"&&o("fetch",s)});function o(s,i){!Zr(i.url)&&(wi(i)||bn(i.status))&&("xhr"in i?Ei(i.xhr,e,a):i.response?Ti(i.response,e,a):i.error&&_i(i.error,e,a));function a(c){const l={isAborted:i.isAborted,handlingStack:i.handlingStack};t.notify(0,{rawLogsEvent:{message:`${Ci(s)} error ${i.method} ${i.url}`,date:i.startClocks.timeStamp,error:{stack:c||"Failed to load",handling:void 0},http:{method:i.method,status_code:i.status,url:i.url},status:h.error,origin:R.NETWORK},domainContext:l})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function Ei(e,t,n){typeof e.response=="string"?n(Ot(e.response,t)):n(e.response)}function _i(e,t,n){n(Ot(q(I(e)),t))}function Ti(e,t,n){const r=cs(e);!r||!r.body?n():window.TextDecoder?Oi(r.body,t.requestErrorResponseLengthLimit,(o,s)=>{n(o?`Unable to retrieve response: ${o}`:s)}):r.text().then(b(o=>n(Ot(o,t))),b(o=>n(`Unable to retrieve response: ${o}`)))}function wi(e){return e.status===0&&e.responseType!=="opaque"}function Ot(e,t){return e.length>t.requestErrorResponseLengthLimit?`${e.substring(0,t.requestErrorResponseLengthLimit)}...`:e}function Ci(e){return e==="xhr"?"XHR":"Fetch"}function Oi(e,t,n){qs(e,(r,o,s)=>{if(r)n(r);else{let i=new TextDecoder().decode(o);s&&(i+="..."),n(void 0,i)}},{bytesLimit:t,collectStreamBody:!0})}function vi(e,t){if(!e.forwardErrorsToLogs)return{stop:U};const n=new w,{stop:r}=Ao(n),o=n.subscribe(s=>{t.notify(0,{rawLogsEvent:{message:s.message,date:s.startClocks.timeStamp,error:Ve(s),origin:R.SOURCE,status:h.error},messageContext:s.context})});return{stop:()=>{r(),o.unsubscribe()}}}const Ri=Os;function xi(e){function t(n,r,o,s,i){const a=oe(r.getContext(),n.context);if(Ke(n.status,_e.console,r)&&Li(n,a),Ke(n.status,_e.http,r)){const c={rawLogsEvent:{date:i||F(),message:n.message,status:n.status,origin:R.LOGGER},messageContext:a,savedCommonContext:s};o&&(c.domainContext={handlingStack:o}),e.notify(0,c)}}return{handleLog:t}}const Ai={[h.ok]:E.debug,[h.debug]:E.debug,[h.info]:E.info,[h.notice]:E.info,[h.warn]:E.warn,[h.error]:E.error,[h.critical]:E.error,[h.alert]:E.error,[h.emerg]:E.error};function Li({status:e,message:t},n){j[Ai[e]].call(A,t,n)}function Ii(e,t,n,r,o){const s=xn(e,{endpoint:e.logsEndpointBuilder,encoder:He()},e.replica&&{endpoint:e.replica.logsEndpointBuilder,encoder:He()},n,r,o.expireObservable);return t.subscribe(1,i=>{s.add(i)}),s}function ki(e){const t=St();e.subscribe(1,n=>{t.send("log",n)})}function Mi(e){return{get:t=>{const n=e.findTrackedSession(t);if(n)return{session_id:n.id}}}}function Pi(e){return t=>{e.notify(0,{rawLogsEvent:{message:t.message,date:t.startClocks.timeStamp,origin:R.AGENT,status:h.error}}),hn("Error reported to customer",{"error.message":t.message})}}function Ni(e,t,n,r,o){const s=zo("browser-logs-sdk",t);s.setContextProvider(()=>{var a,c,l,u,d,f;return{application:{id:(a=qe())===null||a===void 0?void 0:a.application_id},session:{id:(c=o.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(u=(l=qe())===null||l===void 0?void 0:l.view)===null||u===void 0?void 0:u.id},action:{id:(f=(d=qe())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const i=[];if(je()){const a=St(),c=s.observable.subscribe(l=>a.send("internal_telemetry",l));i.push(()=>c.unsubscribe())}else{const a=xn(t,{endpoint:t.rumEndpointBuilder,encoder:He()},t.replica&&{endpoint:t.replica.rumEndpointBuilder,encoder:He()},n,r,o.expireObservable);i.push(()=>a.stop());const c=s.observable.subscribe(l=>a.add(l,qo(t)));i.push(()=>c.unsubscribe())}return Vo(),Yo(si(e)),{telemetry:s,stop:()=>{i.forEach(a=>a())}}}function Fi(e,t,n,r){const o=new Ri,s=[];o.subscribe(1,f=>ln("logs",f));const i=Pi(o),a=_s(t),c=t.sessionStoreStrategyType&&!je()&&!In()?di(t,r):fi(t),{stop:l}=Ni(e,t,i,a,c);s.push(()=>l()),yi(t,o),vi(t,o),Si(t,o),bi(t,o);const{handleLog:u}=xi(o);if(gi(c,t,o,n,i),je())ki(o);else{const{stop:f}=Ii(t,o,i,a,c);s.push(()=>f())}const d=Mi(c);return{handleLog:u,getInternalContext:d.get,stop:()=>{s.forEach(f=>f())}}}const ie=ci(Fi);Mo($(),"DD_LOGS",ie);class Q{constructor(t){this.isLoggingOn=t,ie.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!0,sessionSampleRate:100})}static setMessagePort(t){this.messagePort=t}static getMessagePort(){return this.messagePort}setLoggingOn(t){this.isLoggingOn=t}setAttributes(t){for(const n in t)ie.logger.setContextProperty(n,t[n])}info(t,n){this.isLoggingOn&&(ie.logger.info(t,n),console.log("[Logger] Sending info: ",t))}error(t,n){this.isLoggingOn&&(ie.logger.error(t,n),console.log("[Logger] Sending error: ",t))}warn(t,n){this.isLoggingOn&&(ie.logger.warn(t,n),console.log("[Logger] Sending warn: ",t))}handleMessageFromWorker(t){t.actionType==="INFO"?this.info(t.message,t.attributes):t.actionType==="ERROR"?this.error(t.message,t.attributes):t.actionType==="WARN"?this.warn(t.message,t.attributes):t.actionType==="SET_ATTRIBUTES"&&t.attributes&&this.setAttributes(t.attributes)}static setAttributes(t){Q.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:t})}static info(t,n){Q.messagePort.postMessage({type:"LOG",actionType:"INFO",message:t,attributes:n})}static error(t,n){Q.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:t,attributes:n})}static warn(t,n){Q.messagePort.postMessage({type:"LOG",actionType:"WARN",message:t,attributes:n})}}const Fn=(()=>{const e=()=>{const p=navigator.userAgent;return/windows/i.test(p)?"Windows":/android/i.test(p)?"Android":/iphone|ipad|ipod/i.test(p)?"iOS":/mac/i.test(p)?"Mac":/ipad/i.test(p)?"iPad":"Something else"},t=()=>e()==="Mac",n=()=>e()==="iPad",r=()=>e()==="iOS",o=()=>{const p=e();return p==="iOS"||p==="Mac"||p==="iPad"},s=()=>e()==="Windows",i=()=>e()==="Android",a=()=>{switch(e()){case"Windows":return"a Windows PC";case"Android":return"an Android phone";case"iOS":return"an iPhone";case"Mac":return"a Mac";case"iPad":return"an iPad";default:return"an Unknown device"}},c=()=>({header:[navigator.platform,navigator.userAgent,navigator.appVersion,navigator.vendor,window.opera],dataos:[{name:"Windows Phone",value:"Windows Phone",version:"OS"},{name:"Windows",value:"Win",version:"NT"},{name:"iPhone",value:"iPhone",version:"OS"},{name:"iPad",value:"iPad",version:"OS"},{name:"Kindle",value:"Silk",version:"Silk"},{name:"Android",value:"Android",version:"Android"},{name:"PlayBook",value:"PlayBook",version:"OS"},{name:"BlackBerry",value:"BlackBerry",version:"/"},{name:"Macintosh",value:"Mac",version:"OS X"},{name:"Linux",value:"Linux",version:"rv"},{name:"Palm",value:"Palm",version:"PalmOS"}],databrowser:[{name:"Chrome",value:"Chrome",version:"Chrome"},{name:"Firefox",value:"Firefox",version:"Firefox"},{name:"Safari",value:"Safari",version:"Version"},{name:"Internet Explorer",value:"MSIE",version:"MSIE"},{name:"Opera",value:"Opera",version:"Opera"},{name:"BlackBerry",value:"CLDC",version:"CLDC"},{name:"Mozilla",value:"Mozilla",version:"Mozilla"}],init(){const v=this.header.join(" ");return this.matchItem(v,this.dataos)},matchItem(v,N){for(let ae=0;ae<N.length;ae+=1)if(new RegExp(N[ae].value,"i").test(v))return N[ae].name;return"unknown"}}).init(),l=()=>{const p=navigator.userAgent;return p.indexOf("Chrome")>-1&&p.indexOf("Edge")===-1?"Chrome":p.indexOf("Safari")>-1&&p.indexOf("Chrome")===-1?"Safari":p.indexOf("Firefox")>-1?"Firefox":p.indexOf("MSIE")>-1||p.indexOf("Trident")>-1?"Internet Explorer":p.indexOf("Edge")>-1?"Edge":"Unknown"};return{getCurrentPlatform:e,isMac:t,isiPad:n,isiPhone:r,isApple:o,isWindows:s,isAndroid:i,getDeviceDescription:a,getDeviceName:c,getBrowserName:l,isSafariMac:()=>t()&&l()==="Safari",isChromeMac:()=>t()&&l()==="Chrome",isChromeWin:()=>s()&&l()==="Chrome",isFirefoxMac:()=>t()&&l()==="Firefox",isFirefoxWin:()=>s()&&l()==="Firefox"}})(),C=class C{constructor(t,n,r,o,s){this.copy=()=>new C(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const i=":";let a=("0"+this.h).slice(-2)+i+("0"+this.m).slice(-2)+i+("0"+this.s).slice(-2)+i+("0"+this.f).slice(-2);return a+="."+(this.field?"1":"2"),a},this.toZipTimeCodeString=()=>{const i=this.copy();return i.f=0,i.s=i.s%2===0?i.s:i.s-1,i.field=0,C.toStr(i)},this.toFrames=i=>{let a=60,c=0;Math.floor(i)==60?(a=60,c=0):Math.floor(i)==59?(a=60,c=4):Math.floor(i)==30?(a=30,c=0):Math.floor(i)==29&&(a=30,c=2);let l=this.h,u=this.m,d=this.s,f=this.f,g=this.field;const m=l*60+u,p=(m-Math.floor(m/10))*c;return l*(a*3600)+u*(a*60)+d*a+(f*2+g)-p},this.addSeconds=i=>{let a=this.copy();return a.s+=i,a.s>=60&&(a.s=0,a.m++,a.m>=60&&(a.m=0,a.h++)),a},this.addFrames=(i,a)=>{let c=this.toFrames(a);return c+=i,C.fromFrames(c,a)},this.subtractFrames=(i,a)=>this.addFrames(-i,a),this.h=t||0,this.m=n||0,this.s=r||0,this.f=o||0,this.field=s||0}static compare(t,n){return t.h!==n.h?t.h<n.h?-1:1:t.m!==n.m?t.m<n.m?-1:1:t.s!==n.s?t.s<n.s?-1:1:t.f!==n.f?t.f<n.f?-1:1:t.field!==n.field?t.field<n.field?-1:1:0}static generateTimecodeRange(t,n,r){const o=[];let s=t;for(;C.compare(s,n)<=0;)o.push(s),s=s.addSeconds(r);return o}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(t){return this.toFrames(t)*1e3/t}};C.calculateCurrentTimeCode=t=>{var d;if(!t.video||!t.clocker||!t.gameParams)throw new Error("OTTPlayer is not initialized");const n=t.video,r=t.clocker,o=r.videoFPScalculator.getFPS(),a=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*o+r.syncPoint.frame;if(a===0||o===0)throw new Error("Current frame is 0 or fps is 0");const c=C.calculateCurrentOffset(a,(d=t.gameParams)==null?void 0:d.offsets);if(c===void 0)throw new Error("Offset is undefined");let l=Math.floor(a-c);return l<0&&(l+=5178816),l>=5178816&&(l-=5178816),C.fromFrames(l,o)},C.calculateCurrentOffset=(t,n)=>{for(let r=1;r<n.length;r++)if(t<n[r].frame)return n[r-1].offset;return n[n.length-1].offset},C.fromFrames=(t,n)=>{let r=60,o=0;Math.floor(n)==60?(r=60,o=0):Math.floor(n)==59?(r=60,o=4):Math.floor(n)==30?(r=30,o=0):Math.floor(n)==29&&(r=30,o=2);let s=Math.floor(n*60),i=Math.floor(n*60*10),a=i*6,c=t,l=Math.floor(c/a);c-=l*a;let u=Math.floor(c/i);c-=u*i,c>=r*60&&(c+=o*(Math.floor((c-r*60)/s)+1));let d=Math.floor(c/(r*60));c-=d*(r*60);let f=Math.floor(c/r);c-=f*r;let g=c;d+=u*10;let m=0;return m=g%2,g=Math.floor(g/2),new C(l,d,f,g,m)},C.toStr=t=>{const n="_";let r=("0"+t.h).slice(-2)+n+("0"+t.m).slice(-2)+n+("0"+t.s).slice(-2)+n+("0"+t.f).slice(-2);return t.field&&(r+="_1"),r},C.fromStr=t=>{const r=t.split("_").map(Number);if(r.length==4){const[o,s,i,a]=r;return new C(o,s,i,a,0)}else if(r.length==5){const[o,s,i,a,c]=r;return new C(o,s,i,a,c)}else throw new Error("Invalid timecode format: "+t)},C.fromMetadata=t=>{const n=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,r=t.timecode.match(n);if(!r)throw new Error("Invalid timecode format: "+t.timecode);const[,o,s,i,a,c]=r,l=Number(o),u=Number(s),d=Number(i),f=Number(a),g=c?Number(c):0;return new C(l,u,d,f,g)};let Te=C;class Di{constructor(){this.start=0,this.end=0,this.startTimeoutForSeconds=t=>{this.start=performance.now(),this.end=this.start+t*1e3},this.isTimeout=()=>{const t=performance.now()>=this.end;return t&&(this.start=0,this.end=0),!t}}}const vt={lastRendererFrameSent:0,isRAFSeen:!1,isRVFCSeen:!1,RVFCmissed:!1,RVFCframeExpected:0,compensationMode:!1,compensationCounter:0,frameCorrection:0,lastMessageSent:""};let Ye=null,P,T,Dn=new Di;self.onmessage=async e=>{const{data:t}=e;t.type==="SET_LOGGER_PORT"&&Q.setMessagePort(t.port),t.type==="SET_RENDERER_PORT"&&(Ye=t.port,Ye.onmessage=$i),t.type==="ADAPTER_UPDATE_DATA"&&(T=t.data,$n()),t.type==="SET_OPTIONS"&&(P=t.options,Q.setMessagePort(self))};function $i(e){P&&we(P,"Adapter")&&console.log("[AdapterWorker] Message from Renderer:",e.data)}const $n=()=>{!T||T.siData.isVideoPaused||(Fn.isChromeMac()?Ui():Fn.isSafariMac()&&Bi())},Ui=()=>{if(!T||T.siData.isVideoPaused||!T.vfcData.lastFrameMetadata)return;const{siData:e,vfcData:t,afData:n,debugControls:r}=T;if(!e.isRAFSeen){let o=4,s=-11,i=1,a=5;if(r){const p=parseInt(r["Window Start (ms)"],10);isNaN(p)||(o=p);const O=parseInt(r["Window End (ms)"],10);isNaN(O)||(s=O);const v=parseInt(r["Frame Correction"],10);isNaN(v)||(i=v);const N=parseInt(r["Timeout time"],10);isNaN(N)||(a=N)}const c=1e3/t.videoFPS;1e3/n.animationFPS;const l=n.lastTimestamp,u=t.storedMetadata.reduce((p,O)=>Math.abs(O.expectedDisplayTime-l)<Math.abs(p.expectedDisplayTime-l)?O:p),d=u.expectedDisplayTime-o,f=[];for(let p=-10;p<10;p++)f.push(d+p*c);const g=u.expectedDisplayTime-s,m=[];for(let p=-10;p<10;p++)m.push(g+p*c);let y=null;f.forEach((p,O)=>{l>p&&l<m[O]&&(y=O-10)}),y!==null?setTimeout(p=>Rt(t.lastCalculatedMediaTimeVideoFrame+p*Math.round(60/t.videoFPS)+i),a,y):Rt(vt.lastRendererFrameSent)}},Bi=()=>{if(!T||T.siData.isVideoPaused||!T.vfcData.lastFrameMetadata)return;const{siData:e,vfcData:t,afData:n}=T;let r=n.lastCalculatedPlayerTimeFraction;const o=n.previousCalculatedPlayerTimeFraction;r<.3&&r>.1&&o<.3&&o>.1&&(r=Math.min(r,o));let s=0;r<.1?s=0:r>.1&&r<.3?s=(r-.1)/(.3-.1):s=1;let i=n.lastCalculatedPlayerTimeVideoFrame;s==1&&(i++,s=0),Rt(i,s)},Rt=(e,t)=>{if(!T)return;vt.lastRendererFrameSent=e,T.siData.workingFps;const n=Te.fromFrames(e,6e4/1001);if(Dn.isTimeout())Un(n);else{const r=T.vfcData.videoFPS;if(r<=10||r>70){console.error("Video FPS is out of supported range: "+r),Dn.startTimeoutForSeconds(3),Un(n);return}T.afData.animationFPS,Gi(n,t)}},Gi=(e,t)=>{const n=Te.toStr(e);vt.lastMessageSent=n,P&&we(P,"Adapter")&&console.log(`[AdapterWorker] Rendering augmentation for timecode: ${n} , ${e}`),Bn(n,t)},Un=e=>{const t=Te.toStr(e);P&&we(P,"Adapter")&&console.log("[AdapterWorker] Clearing augmentation"),Bn(t,0,!0)},Bn=(e,t,n)=>{if(!Ye||!T)return;const r=e;P&&we(P,"Adapter")&&console.log(`[AdapterWorker] Sending current time code to the Renderer: ${r}`);const o={timeCode:r,frameCorrection:t||0,fps:Wn(T.siData.workingFps),cloudFrontURL:T.cloudFrontURL,bucketName:T.bucketName,offsets:T.offsets},i={type:n?"RENDERER_CLEAR":"RENDERER_DRAW",streamData:o};Ye.postMessage(i)};setInterval($n,2)})();\n',Gt=typeof self<"u"&&self.Blob&&new Blob([zt],{type:"text/javascript;charset=utf-8"});function ur(t){let e;try{if(e=Gt&&(self.URL||self.webkitURL).createObjectURL(Gt),!e)throw"";const n=new Worker(e,{name:t==null?void 0:t.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(zt),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}class dr{constructor(e){this.canPlayListner=()=>this.setupCanvas(),this.clickListner=n=>{this.clicker.click(n)},this.mediaTime=0,this.timecodeChecker=new ir(0),this.logger=e.logger,this.OTTPlayer=e,this.options=e.options,this.downloaderWorker=new ar,this.decoderWorker=new cr,this.rendererWorker=new lr,this.adapterWorker=new ur,window.BB.workerInstances.push(this.downloaderWorker,this.decoderWorker,this.rendererWorker,this.adapterWorker),this.rendererToDownloader=new MessageChannel,this.rendererToMain=new MessageChannel,this.downloaderToDecoder=new MessageChannel,this.decoderToRenderer=new MessageChannel,this.adapterToRenderer=new MessageChannel,this.setupWorkers(),this.canvas=document.createElement("canvas"),this.OTTPlayer.video.readyState>=3?this.setupCanvas():this.OTTPlayer.video.addEventListener("canplay",this.canPlayListner,{once:!0}),this.processedTimecodes=[],this.clicker=new or(this.OTTPlayer.video,this.rendererWorker),this.segmentFirstFrameTimecode=new x,this.syncPoint={frame:0,playerTime:0,stringTime:""},this.cacheStarted=!1,this.animationFPScalculator=new At(20),this.videoFPScalculator=new At(20),this.startAnimationFrameLoop(),this.startVideoFrameCallbackLoop()}onNewMetadata(e){const n=z(this.videoFPScalculator.getFPS());this.segmentFirstFrameTimecode=er(e),this.metadataReportedFrameTimecode=tr(e),this.metadataReportedFrameTimecode&&n&&!this.cacheStarted&&(this.syncPoint=rr(e,n,this.metadataReportedFrameTimecode),this.cacheStarted=!0)}async onNewSegment(e){const n=z(this.videoFPScalculator.getFPS());this.segmentFirstFrameTimecode&&n&&(this.syncPoint=nr(e,n,this.segmentFirstFrameTimecode))}startAnimationFrameLoop(){const e=()=>{var n;this.animationFPScalculator.addTimestamp(performance.now()/1e3),(n=this.OTTPlayer.gameParams)!=null&&n.bucketName&&this.OTTPlayer.gameParams.offsets&&this.cacheStarted&&!this.OTTPlayer.RUN_ADAPTER&&this.callRendererWorker(),this.OTTPlayer.RUN_PIXEL_TICKERS&&this.OTTPlayer.pixelTickers.forEach(r=>{r.update()}),this.animationFPScalculator.getFPS(),this.animationFrameLoopId=requestAnimationFrame(e)};this.animationFrameLoopId=requestAnimationFrame(e)}startVideoFrameCallbackLoop(){const e=(n,r)=>{this.mediaTime=r.mediaTime,this.videoFPScalculator.addTimestamp(r.mediaTime),this.videoFrameCallbackLoopId=this.OTTPlayer.video.requestVideoFrameCallback(e)};this.videoFrameCallbackLoopId=this.OTTPlayer.video.requestVideoFrameCallback(e)}setupCanvas(){const e=this.OTTPlayer.video,n=e.parentElement;this.canvas.width=e.videoWidth,this.canvas.height=e.videoHeight,this.canvas.style.zIndex="3000",this.canvas.style.position="absolute",this.canvas.style.top="50%",this.canvas.style.transform="translateY(-50%)",this.canvas.style.left="0",this.canvas.style.width=n.style.width,this.canvas.style.height=n.style.height,this.canvas.style.pointerEvents="none",n.addEventListener("click",this.clickListner),n.style.position="relative",n.appendChild(this.canvas);const r=this.canvas.transferControlToOffscreen(),s={type:"INIT_OFFSCREEN",offscreen:r,options:this.options};this.rendererWorker.postMessage(s,[r]),e.onseeked=()=>{this.onVideoSeeked()},e.onseeking=()=>{this.onVideoSeeked()}}setupWorkers(){this.downloaderWorker.onmessage=e=>{e.data.type==="LOG"&&this.logger.handleMessageFromWorker(e.data)},this.decoderWorker.onmessage=e=>{e.data.type==="LOG"&&this.logger.handleMessageFromWorker(e.data)},this.rendererWorker.onmessage=e=>{e.data.type==="LOG"&&this.logger.handleMessageFromWorker(e.data)},this.adapterWorker.onmessage=e=>{e.data.type==="LOG"&&this.logger.handleMessageFromWorker(e.data)},this.rendererWorker.postMessage({type:"SET_DOWNLOADER_PORT",port:this.rendererToDownloader.port1},[this.rendererToDownloader.port1]),this.downloaderWorker.postMessage({type:"SET_RENDERER_PORT",port:this.rendererToDownloader.port2},[this.rendererToDownloader.port2]),this.downloaderWorker.postMessage({type:"SET_DECODER_PORT",port:this.downloaderToDecoder.port1},[this.downloaderToDecoder.port1]),this.decoderWorker.postMessage({type:"SET_DOWNLOADER_PORT",port:this.downloaderToDecoder.port2},[this.downloaderToDecoder.port2]),this.decoderWorker.postMessage({type:"SET_RENDERER_PORT",port:this.decoderToRenderer.port1},[this.decoderToRenderer.port1]),this.rendererWorker.postMessage({type:"SET_DECODER_PORT",port:this.decoderToRenderer.port2},[this.decoderToRenderer.port2]),this.adapterWorker.postMessage({type:"SET_RENDERER_PORT",port:this.adapterToRenderer.port1},[this.adapterToRenderer.port1]),this.rendererWorker.postMessage({type:"SET_ADAPTER_PORT",port:this.adapterToRenderer.port2},[this.adapterToRenderer.port2]),this.rendererWorker.postMessage({type:"SET_LOGGER_PORT",port:this.rendererToMain.port1},[this.rendererToMain.port1]),this.rendererToMain.port2.onmessage=e=>{e.data.type==="LOG"&&this.logger.handleMessageFromWorker(e.data)},this.downloaderWorker.postMessage({type:"SET_OPTIONS",options:this.options}),this.decoderWorker.postMessage({type:"SET_OPTIONS",options:this.options}),this.adapterWorker.postMessage({type:"SET_OPTIONS",options:this.options}),this.rendererWorker.postMessage({type:"SET_OPTIONS",options:this.options})}callAdapterWorker(e){this.adapterWorker.postMessage({type:"ADAPTER_UPDATE_DATA",data:e})}callRendererWorker(e,n,r){var c,u;let s=e;if(!s){const l=x.calculateCurrentTimeCode(this.OTTPlayer);s=x.toStr(l)}this.options&&A(this.options,"Clocker")&&console.log(`[Clocker] Sending current time code to the Renderer: ${s}`);const i={timeCode:s,frameCorrection:n||0,fps:z(this.videoFPScalculator.getFPS()),cloudFrontURL:this.OTTPlayer.options.cloudFrontURL,bucketName:((c=this.OTTPlayer.gameParams)==null?void 0:c.bucketName)||"",offsets:((u=this.OTTPlayer.gameParams)==null?void 0:u.offsets)||[]},a={type:r?"RENDERER_CLEAR":"RENDERER_DRAW",streamData:i};this.rendererWorker.postMessage(a),r||this.logger.setAttributes({last_timecode:s})}onVideoSeeked(){this.downloaderWorker.postMessage({type:"VIDEO_SEEKED"}),this.decoderWorker.postMessage({type:"VIDEO_SEEKED"}),this.rendererWorker.postMessage({type:"VIDEO_SEEKED"}),this.logger.info("didSeek")}delete(){const e=this.OTTPlayer.video,n=e.parentElement;n.removeChild(this.canvas),this.rendererWorker.terminate(),this.downloaderWorker.terminate(),this.decoderWorker.terminate(),this.adapterWorker.terminate(),this.animationFrameLoopId&&cancelAnimationFrame(this.animationFrameLoopId),this.videoFrameCallbackLoopId&&e.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),e.removeEventListener("canplay",this.canPlayListner),n.removeEventListener("click",this.clickListner)}}class fr{constructor(){this.metrics=new Map,this.containers=[],this.createContainer=()=>{const e=document.createElement("div");e.style.display="flex",e.style.gap="10px",e.style.marginBottom="5px",e.style.fontSize="14px";const n={div:e,metrics:[]};return this.containers.push(n),document.body.appendChild(e),n},this.createMetric=(e,n)=>{const r=document.createElement("span"),s={name:e,value:"",span:r};return n.metrics.push(s),r.textContent=`${e}: ${s.value}`,n.div.appendChild(r),this.metrics.set(e,s),s},this.updateMetric=(e,n)=>{const r=this.metrics.get(e);if(!r){console.error("Metric does not exist");return}typeof n=="boolean"?r.value=n?"true":"false":r.value=n,r.span.textContent=`${e}: ${r.value}`}}delete(){this.containers.forEach(e=>{e.div.remove()})}}class hr{constructor(){this.controls=new Map,this.containers=[]}createContainer(e){const n=document.createElement("div");n.style.display="flex",n.style.flexWrap="wrap",n.style.gap="10px",n.style.padding="10px",n.style.marginBottom="10px",n.style.border="1px solid #ccc",n.style.fontSize="14px",n.style.backgroundColor="#f9f9f9";const r=document.createElement("button");r.textContent="Apply",r.style.cursor="pointer";const s={div:n,controls:[],button:r};return r.addEventListener("click",()=>{const i={};s.controls.forEach(o=>{(o.type==="input"||o.type==="select")&&(o.appliedValue=o.element.value),i[o.name]=o.appliedValue}),e&&e(i)}),n.appendChild(r),document.body.appendChild(n),this.containers.push(s),s}createInput(e,n="",r){const s=document.createElement("label");s.style.display="flex",s.style.flexDirection="column",s.style.fontWeight="bold";const i=document.createElement("span");i.textContent=e,i.style.marginBottom="3px";const o=document.createElement("input");o.type="text",o.value=String(n),o.style.minWidth="60px";const a={name:e,type:"input",element:o,container:r,appliedValue:String(n)};this.controls.set(e,a),r.controls.push(a),s.appendChild(i),s.appendChild(o),r.div.insertBefore(s,r.button)}createSelect(e,n,r="",s){const i=document.createElement("label");i.style.display="flex",i.style.flexDirection="column",i.style.fontWeight="bold";const o=document.createElement("span");o.textContent=e,o.style.marginBottom="3px";const a=document.createElement("select");a.style.minWidth="80px",Object.entries(n).forEach(([u,l])=>{const d=document.createElement("option");d.textContent=u,d.value=String(l),a.appendChild(d)}),a.value=String(r);const c={name:e,type:"select",element:a,container:s,appliedValue:String(r)};this.controls.set(e,c),s.controls.push(c),i.appendChild(o),i.appendChild(a),s.div.insertBefore(i,s.button)}exportData(){const e={};return this.controls.forEach(n=>{e[n.name]=n.appliedValue}),e}getValue(e){const n=this.controls.get(e);return n?n.appliedValue:(console.error(`No control found with name: ${e}`),"")}delete(){this.containers.forEach(e=>{e.div.remove()}),this.containers=[],this.controls.clear()}}const Ce=t=>t.toString().padStart(2,"0"),Qe=":",pr=(t,e,n=!1)=>{let r="";return Array.isArray(t)?(r=[Ce(t[0]),Ce(t[1]),Ce(t[2]),Ce(t[3])].join(":"),n==!0?t[4]==1&&e?r+=".2":r+=".1":t[4]==1&&e&&(r+=".1")):(r=("0"+t.h).slice(-2)+Qe+("0"+t.m).slice(-2)+Qe+("0"+t.s).slice(-2)+Qe+("0"+t.f).slice(-2),r+="."+(t.field?"1":"2")),r},mr=(t,e,n)=>{let r=60,s=0;Math.floor(e)==60?(r=60,s=0):Math.floor(e)==59?(r=60,s=4):Math.floor(e)==30?(r=30,s=0):Math.floor(e)==29&&(r=30,s=2);let i=0,a=Math.floor(e*60*10)*6,c=t[0],u=t[1],l=t[2],d=t[3],f=t[4];return i+=c*a,i+=u*(r*60),i+=l*r,i+=d*2+f,i-=s*u,i+=s*Math.floor(u/10),i};class gr{constructor(){this.start=0,this.end=0,this.startTimeoutForSeconds=e=>{this.start=performance.now(),this.end=this.start+e*1e3},this.isTimeout=()=>{const e=performance.now()>=this.end;return e&&(this.start=0,this.end=0),!e}}}class yr{constructor(e){if(this.platformSupported=!0,this.firstFrameTimecode=[0,0,0,0,0],this.timeout=new gr,this.afData={counter:0,lastTimestamp:0,lastMetadataNow:0,timeFromLastRVFC:0,animationFPS:0,playerTimeOffset:0,lastPlayerTimeFromSync:0,lastCalculatedPlayerTimeVideoFrame:0,lastCalculatedPlayerTimeFraction:0,previousCalculatedPlayerTimeFraction:2},this.vfcData={counter:0,lastTimestamp:0,timeFromLastRAF:0,videoFPS:0,lastFrameMetadata:null,lastFrameMetadataNow:0,storedMetadata:[],timeToExpectedDisplayTime:0,mediaTimeOffset:0,lastMediaTimeFromSync:0,lastCalculatedMediaTimeVideoFrame:0},this.siData={counter:0,lastTimestamp:0,lastOffset:0,timeFromLastRAF:0,timeFromLastRVFC:0,lastSeenRAFCount:0,lastSeenRVFCCount:0,isRAFSeen:!1,isRVFCSeen:!1,isVideoPaused:!0,workingFps:0,refreshRate:0,RVFCmissed:0,RVFCframeExpected:0,expectedRefreshRate:0,newRefreshRateFrames:0,RVFCpattern:[],isRVFCpatternDetected:!1,patternTracking:[],patternTrackingIndex:-1,patternNextValue:-1,lastCallback:null,lastCalculatedFrame:0,lastRendererFrameSent:0,lastMessageSent:"",compensationMode:!1,compensationCounter:0,frameCorrection:0,determineFramesTimestamps:[],determineFramesIntervals:[]},this.tcTimeStamp=0,this.timecode_offset=0,this.onAnimationFrame=n=>{if(this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams){window.requestAnimationFrame(this.onAnimationFrame);return}this.afData.counter++,this.afData.lastTimestamp=performance.now(),this.afData.lastMetadataNow=n,this.afData.timeFromLastRVFC=this.afData.lastTimestamp-this.vfcData.lastTimestamp,this.afData.animationFPS=this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS(),this.siData.lastCallback=="RAF"&&this.siData.RVFCmissed++,this.siData.lastCallback="RAF";const r=(this.video.currentTime-this.syncPoint.playerTime)%(60*60*24)*(6e4/1001);this.afData.lastPlayerTimeFromSync=r;const s=Math.floor(r)+this.syncPoint.frame;this.afData.playerTimeOffset=x.calculateCurrentOffset(s,this.OTTPlayer.gameParams.offsets);let i=s-this.afData.playerTimeOffset;if(i<0&&(i+=5178816),i>=5178816&&(i-=5178816),i++,this.afData.lastCalculatedPlayerTimeVideoFrame=i,this.afData.previousCalculatedPlayerTimeFraction=this.afData.lastCalculatedPlayerTimeFraction,this.afData.lastCalculatedPlayerTimeFraction=r-Math.floor(r),this.metrics)try{this.metrics.updateMetric("RAF calls",this.afData.counter),this.metrics.updateMetric("Last player time",this.video.currentTime.toFixed(4)),this.metrics.updateMetric("Last player time frame",this.afData.lastCalculatedPlayerTimeVideoFrame),this.metrics.updateMetric("Last player time fraction",this.afData.lastCalculatedPlayerTimeFraction.toFixed(4)),this.metrics.updateMetric("Last player time double frame",this.afData.lastPlayerTimeFromSync.toFixed(5)),this.metrics.updateMetric("AF metadata now - perf.now()",(this.afData.lastTimestamp-this.afData.lastMetadataNow).toFixed(3)),this.metrics.updateMetric("VF ExpDispTime - AF metadata now",(this.afData.lastMetadataNow-this.vfcData.lastFrameMetadata.expectedDisplayTime).toFixed(3)),this.metrics.updateMetric("Last RAF call",this.afData.lastTimestamp.toFixed(2)),this.metrics.updateMetric("RAF - RVFC dif",this.afData.timeFromLastRVFC.toFixed(2)),this.metrics.updateMetric("Sync point to RAF time",(this.afData.lastTimestamp-this.syncPoint.lastUpdate).toFixed(2))}catch(o){console.error(o)}window.requestAnimationFrame(this.onAnimationFrame),this.determineFrameUpdate()},this.onVideoFrame=(n,r)=>{if(this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams){this.video.requestVideoFrameCallback(this.onVideoFrame);return}this.vfcData.counter++,this.vfcData.lastTimestamp=performance.now(),this.vfcData.timeFromLastRAF=this.vfcData.lastTimestamp-this.afData.lastTimestamp,this.siData.RVFCmissed=0,this.vfcData.videoFPS=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS(),this.siData.lastCallback="RVFC";const s=(r.mediaTime-this.syncPoint.playerTime)%(60*60*24)*(6e4/1001);this.vfcData.lastMediaTimeFromSync=s;const i=Math.floor(s+.1)+this.syncPoint.frame;this.vfcData.mediaTimeOffset=x.calculateCurrentOffset(i,this.OTTPlayer.gameParams.offsets);let o=i-this.vfcData.mediaTimeOffset;o<0&&(o+=5178816),o>=5178816&&(o-=5178816),o++,this.vfcData.lastCalculatedMediaTimeVideoFrame=o,this.vfcData.lastFrameMetadata=r,this.vfcData.storedMetadata.push(r),this.vfcData.storedMetadata.length>10&&this.vfcData.storedMetadata.shift(),this.vfcData.timeToExpectedDisplayTime=r.expectedDisplayTime-n,this.vfcData.lastFrameMetadataNow=n,this.metrics&&(this.metrics.updateMetric("RVFC calls",this.vfcData.counter),this.metrics.updateMetric("Last metadata media time",r.mediaTime.toFixed(4)),this.metrics.updateMetric("Last metadata media time frame",this.vfcData.lastCalculatedMediaTimeVideoFrame),this.metrics.updateMetric("Time to presentation time",(r.presentationTime-n).toFixed(4)),this.metrics.updateMetric("Metadata presented frames",r.presentedFrames),this.metrics.updateMetric("Metadata processing duration",r.processingDuration),this.metrics.updateMetric("Last media time double frame",this.vfcData.lastMediaTimeFromSync.toFixed(5)),this.metrics.updateMetric("VF metadata now - perf.now()",(this.afData.lastTimestamp-this.afData.lastMetadataNow).toFixed(3)),this.metrics.updateMetric("Time to expected display time",this.vfcData.timeToExpectedDisplayTime.toFixed(4)),this.metrics.updateMetric("Last RVFC call",this.vfcData.lastTimestamp.toFixed(2)),this.metrics.updateMetric("Sync point to RVFC time",(r.mediaTime-this.syncPoint.playerTime).toFixed(2))),this.video.requestVideoFrameCallback(this.onVideoFrame),this.determineFrameUpdate()},this.determineFrameUpdate=()=>{var n,r,s;if(!(!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata))if(this.siData.counter===0&&this.logger.info("didStartAugmentation"),this.siData.counter++,this.siData.isVideoPaused=this.video.paused,this.siData.isRAFSeen=this.siData.lastSeenRAFCount==this.afData.counter,this.siData.isRVFCSeen=this.siData.lastSeenRVFCCount==this.vfcData.counter,this.siData.lastTimestamp=performance.now(),this.siData.timeFromLastRAF=this.siData.lastTimestamp-this.afData.lastTimestamp,this.siData.timeFromLastRVFC=this.siData.lastTimestamp-this.vfcData.lastTimestamp,this.siData.lastSeenRAFCount=this.afData.counter,this.siData.lastSeenRVFCCount=this.vfcData.counter,this.siData.workingFps=this.OTTPlayer.clocker.videoFPScalculator.getFPS(),this.siData.refreshRate=this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS(),!this.OTTPlayer.options.ADAPTER_RUN_IN_WORKER)this.platformSpecificFrameUpdate();else{const i={siData:this.siData,vfcData:this.vfcData,afData:this.afData,debugControls:(n=this.debugControls)==null?void 0:n.exportData(),cloudFrontURL:this.OTTPlayer.options.cloudFrontURL,bucketName:((r=this.OTTPlayer.gameParams)==null?void 0:r.bucketName)||"",offsets:((s=this.OTTPlayer.gameParams)==null?void 0:s.offsets)||[]};this.OTTPlayer.clocker.callAdapterWorker(i)}},this.determineFrameUpdateChromeMac=()=>{const n=Math.round(1e3/this.vfcData.timeToExpectedDisplayTime);if(n>0&&n<500&&(Math.abs(this.siData.expectedRefreshRate-n)>3?this.siData.newRefreshRateFrames++:this.siData.expectedRefreshRate=n,this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const r=20,s=1e3;if(!this.siData.isRVFCSeen){const i=Math.round(this.vfcData.timeToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(i<=0&&this.siData.patternTracking.length<=1-i){this.siData.patternTracking=[!0];for(let o=0;o<1-i;o++)this.siData.patternTracking.push(!1)}else i<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+i]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>s&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const i=this.siData.patternTracking;for(let o=1;o*r<=i.length;o++){for(let a=0;a+o*r<=i.length;a++){let c=!0;for(let u=0;u<r-1;u++){const l=i.slice(a+u*o,a+(u+1)*o),d=i.slice(a+(u+1)*o,a+(u+2)*o);if(!l.every((f,h)=>f===d[h])){c=!1;break}}if(c){const u=i.slice(a,a+o),l=u.every(h=>!h),d=u.every(h=>h),f=this.afData.animationFPS-this.vfcData.videoFPS;if(l||d&&f>5)continue;this.siData.RVFCpattern=u,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const i=this.siData.RVFCpattern,o=this.siData.patternTracking;let a=-1;for(let c=o.length-i.length;c>=0;c--){let u=!0;for(let l=0;l<i.length;l++)if(i[l]!==o[c+l]){u=!1;break}if(u){a=c;break}}if(a>=0){const c=(o.length-a)%i.length,u=i[c];this.siData.patternTrackingIndex=c,this.siData.patternNextValue=u?1:0}if(o.length>=i.length*5){o.slice(o.length-i.length*5);let c=0,u=0;for(let l=0;l+i.length<=o.length;l++)o.slice(l,l+i.length).every((f,h)=>f===i[h])?(c++,u=Math.max(u,c),l+=i.length-1):c=0;u<6&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.expectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){const i=performance.now();if(this.siData.determineFramesTimestamps||(this.siData.determineFramesTimestamps=[]),this.siData.determineFramesTimestamps.length>0){const o=i-this.siData.determineFramesTimestamps[this.siData.determineFramesTimestamps.length-1];this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(o.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", "))}this.siData.determineFramesTimestamps.push(i),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(o=>o?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).map(o=>o?1:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let i=0,o=1,a=5;if(this.debugControls){const c=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(c)||(i=c);const u=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(u)||(o=u);const l=parseInt(this.debugControls.getValue("Timeout time"),10);isNaN(l)||(a=l)}this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset})),this.siData.RVFCpattern[(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+i)%this.siData.RVFCpattern.length]?setTimeout(()=>this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+o),a):this.callRenderer(this.siData.lastRendererFrameSent)}else this.siData.isRVFCpatternDetected||this.clearAugmentation(new x(0,0,0,0,0))},this.determineFrameUpdateSifariMac=()=>{if(this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;let n=this.afData.lastCalculatedPlayerTimeFraction;const r=this.afData.previousCalculatedPlayerTimeFraction;n<.3&&n>.1&&r<.3&&r>.1&&(n=Math.min(n,r));let s=0;n<.1?s=0:n>.1&&n<.3?s=(n-.1)/(.3-.1):s=1,this.metrics&&this.metrics.updateMetric("Compensation",s.toFixed(4));let i=this.afData.lastCalculatedPlayerTimeVideoFrame;s==1&&(i++,s=0),this.callRenderer(i)},this.callRenderer=(n,r)=>{if(!this.OTTPlayer.clocker||!this.OTTPlayer)return;this.siData.lastRendererFrameSent=n,this.metrics&&this.metrics.updateMetric("Last sent frame",n);const s=this.OTTPlayer.clocker.videoFPScalculator.getFPS();this.metrics&&this.metrics.updateMetric("FPS",s.toFixed(2));const i=x.fromFrames(n,6e4/1001);if(this.timeout.isTimeout())this.clearAugmentation(i);else{const o=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS();if(o<=10||o>70){console.error("Video FPS is out of supported range: "+o),this.timeout.startTimeoutForSeconds(3),this.clearAugmentation(i);return}this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS(),this.renderAugmentation(i,r)}},this.playbackTimeDelta=0,this.wallClockTimeDelta=0,this.dateTimeDelta=0,this.renderAugmentation=(n,r)=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const s=x.toStr(n);this.siData.lastMessageSent=s,this.options&&A(this.options,"Clocker")&&console.log(`Rendering augmentation for timecode: ${s} , ${n}`),this.metrics&&this.metrics.updateMetric("Last sent timecode",s),this.OTTPlayer.clocker.callRendererWorker(s,r)},this.clearAugmentation=n=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const r=x.toStr(n);this.options&&A(this.options,"Clocker")&&console.log("Clearing augmentation"),this.OTTPlayer.clocker.callRendererWorker(r,0,!0)},this.logger=e.logger,this.OTTPlayer=e,this.options=e.options,this.options&&A(this.options,"Clocker")&&console.log("Adapter is initialized",this.OTTPlayer),this.video=e.video,this.debug=this.options.debug?this.options.debug.on:!1,this.syncPoint={frame:0,playerTime:0,stringTime:"",lastUpdate:0},U.isChromeMac())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeMac;else if(U.isChromeWin())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeMac;else{U.isSafariMac(),U.isFirefoxMac();{this.platformSpecificFrameUpdate=()=>{};const n=U.getCurrentPlatform(),r=U.getBrowserName();console.error("Unsupported platform: "+n+" "+r),this.platformSupported=!1;return}}if(this.debug){this.metrics=new fr;const n=this.metrics.createContainer(),r=this.metrics.createContainer(),s=this.metrics.createContainer(),i=this.metrics.createContainer(),o=this.metrics.createContainer(),a=this.metrics.createContainer(),c=this.metrics.createContainer(),u=this.metrics.createContainer(),l=this.metrics.createContainer(),d=this.metrics.createContainer(),f=this.metrics.createContainer();this.metrics.createMetric("RAF calls",n),this.metrics.createMetric("RVFC calls",n),this.metrics.createMetric("RVFC missed",n),this.metrics.createMetric("Last sent frame",n),this.metrics.createMetric("Last sent timecode",n),this.metrics.createMetric("Last metadata media time",r),this.metrics.createMetric("Last player time",r),this.metrics.createMetric("Time to expected display time",r),this.metrics.createMetric("Last metadata media time frame",s),this.metrics.createMetric("Last player time frame",s),this.metrics.createMetric("Last player time fraction",s),this.metrics.createMetric("Last media time double frame",i),this.metrics.createMetric("Last player time double frame",i),this.metrics.createMetric("AF metadata now - perf.now()",o),this.metrics.createMetric("VF metadata now - perf.now()",o),this.metrics.createMetric("VF ExpDispTime - AF metadata now",o),this.metrics.createMetric("Time to presentation time",a),this.metrics.createMetric("Metadata presented frames",a),this.metrics.createMetric("Metadata processing duration",a),this.metrics.createMetric("Sync point frame",c),this.metrics.createMetric("Sync point player time",c),this.metrics.createMetric("Sync point to RVFC time",c),this.metrics.createMetric("Sync point to RAF time",c),this.metrics.createMetric("FPS",u),this.metrics.createMetric("Refresh rate",u),this.metrics.createMetric("Last RAF call",u),this.metrics.createMetric("Last RVFC call",u),this.metrics.createMetric("RAF - RVFC dif",u),this.metrics.createMetric("Determine frames intervals",l),this.metrics.createMetric("Expected Refresh Rate",d),this.metrics.createMetric("New Refresh Rate Frames",d),this.metrics.createMetric("Pattern found",f),this.metrics.createMetric("Pattern array",f),this.metrics.createMetric("Pattern tracking",f),this.metrics.createMetric("Pattern next index",f),this.metrics.createMetric("Pattern next value",f),this.debugControls=new hr;const h=this.debugControls.createContainer(),p=this.debugControls.createContainer();this.debugControls.createInput("Window Start (ms)",4,h),this.debugControls.createInput("Window End (ms)",-11,h),this.debugControls.createSelect("Pattern offset",{"-5":-5,"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4,5:5},"0",h),this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"1",p),this.debugControls.createSelect("Timeout time",{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,11:11,12:12,13:13,14:14,15:15,16:16,17:17,18:18,19:19,20:20},"5",p)}this.platformSupported&&(this.OTTPlayer.video.readyState>=3?this.setupAdapter():this.OTTPlayer.video.addEventListener("canplay",()=>this.setupAdapter(),{once:!0}))}setupAdapter(){const e=this.video;if(this.debug){const n=typeof wmcsdk<"u"?wmcsdk:wmcPlayer;console.log(n);const r=n.getAvailableVideoQualities(),s={};r.forEach(a=>{s[a.label]=a.id});const i=a=>{n.doSetVideoQuality(a.videoQuality)},o=this.debugControls.createContainer(i);this.debugControls.createSelect("videoQuality",s,r[0].id,o)}this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame),this.videoFrameCallbackLoopId=e.requestVideoFrameCallback(this.onVideoFrame)}onNewSegmentForMetadata(e){const n=mr(this.firstFrameTimecode,59.94005994005994);if(console.log(e),!e.mimeType.includes("video"))return;const r=pr(this.firstFrameTimecode,!0,!0);this.options&&A(this.options,"Clocker")&&console.log("New segment ("+e.url+"): "+r+" ("+n+") playing at "+e.playbackTime);const s=e.playbackTime,i=s-this.playbackTimeDelta;this.playbackTimeDelta=s,console.log("Delta playback: ",i);const o=e.wallClockTime/1e3,a=o-this.wallClockTimeDelta;this.wallClockTimeDelta=o,console.log("Delta wallClock: ",a);const c=e.dateTime.getTime()/1e3,u=c-this.dateTimeDelta;this.dateTimeDelta=c,console.log("Delta dateTime: ",u);const l={frame:n,playerTime:s,stringTime:r,lastUpdate:performance.now()};this.syncPoint=l,this.metrics&&(this.metrics.updateMetric("Sync point frame",l.frame),this.metrics.updateMetric("Sync point player time",l.playerTime)),this.options&&A(this.options,"Clocker")&&console.log("url: "+e.url)}onNewMetadata(e){if(e&&e.metadata&&e.metadata.id==0||U.isSafariMac()){if(e.metadata.messageData)e.metadata.messageData=this.processTimedMetadata(e.metadata.messageData,e.metadata.presentationTime);else if(e.metadata.frames&&e.metadata.frames.length&&e.metadata.frames[0].key&&e.metadata.frames[0].key.toLowerCase()==="priv"){const n=e.metadata.frames.filter(r=>r.info&&r.info.toLowerCase().includes("ntc"));if(n.length){const r=`${n[n.length-1].info}\0${String.fromCharCode(...n[n.length-1].data)}`;e.metadata.messageData=this.processTimedMetadata(r,e.metadata.presentationTime)}}if(e.metadata.id==0||U.isSafariMac()&&this.timecode_offset==0){e.metadata.presentationTime*1e3;const n=new Date(this.tcTimeStamp-this.timecode_offset);let r=Math.round(n.getUTCMilliseconds()*30*2/1001)/2;const s=r%1;let i=1;s==.5&&(r=Math.floor(r),i=2),this.firstFrameTimecode=[n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),Math.floor(r),i==1?0:1],console.log("First frame timecode: ",this.firstFrameTimecode)}}}processTimedMetadata(e,n){let r="";if(e&&e.includes("www.mediakind.com/NTC")){const s=e.replace(/.*NTC./,"");let i=0;for(;i+8<=s.length;){const o=s.substring(i,i+4),a=((s.charCodeAt(i+4)*256+s.charCodeAt(i+5))*256+s.charCodeAt(i+6))*256+s.charCodeAt(i+7);if(i+8+a>s.length)break;const c=s.substring(i+8,i+8+a);o=="utc_"&&new Date(parseInt(c)).getTime()/1e3,o=="tc__"&&(this.tcTimeStamp=new Date(parseInt(c)).getTime()),o==="offs"&&(this.timecode_offset=parseInt(c)/90),i+=8+a}}return r}delete(){this.animationFrameLoopId&&cancelAnimationFrame(this.animationFrameLoopId),this.videoFrameCallbackLoopId&&this.video.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),this.intervalLoopId&&clearInterval(this.intervalLoopId),this.metrics&&this.metrics.delete(),this.debugControls&&this.debugControls.delete()}}class G{constructor(e,n){this.size=1,this.positionElement=()=>{let s=0,i=0;this.corner=="left-top"?(this.element.style.top=`${s}px`,this.element.style.left=`${i}px`):this.corner=="right-top"?(this.element.style.top=`${s}px`,this.element.style.left=`${i+this.video.offsetWidth-this.size}px`):this.corner=="right-bottom"?(this.element.style.top=`${s+this.video.offsetHeight-this.size}px`,this.element.style.left=`${i+this.video.offsetWidth-this.size}px`):this.corner=="left-bottom"&&(this.element.style.top=`${s+this.video.offsetHeight-this.size}px`,this.element.style.left=`${i}px`)},this.video=n,this.container=n.parentElement,this.corner=e;const r=document.createElement("div");r.style.position="absolute",r.style.width=`${this.size}px`,r.style.height=`${this.size}px`,r.style.transition="background-color 0s",r.style.zIndex="100000",this.element=r,this.container.appendChild(r),this.positionElement()}getRandomColor(){const r=Math.floor(Math.random()*11)+0;return`rgb(${r},${r},${r})`}update(){this.element.style.backgroundColor=this.getRandomColor(),this.positionElement()}delete(){this.container.removeChild(this.element)}static createInAllCorners(e){return[new G("left-top",e),new G("right-top",e),new G("right-bottom",e),new G("left-bottom",e)]}static updateAll(e){e.forEach(n=>n.update())}static deleteAll(e){e.forEach(n=>n.delete())}}const v={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},R=console,j={};Object.keys(v).forEach(t=>{j[t]=R[t]});const he="Datadog Browser SDK:",S={debug:j.debug.bind(R,he),log:j.log.bind(R,he),info:j.info.bind(R,he),warn:j.warn.bind(R,he),error:j.error.bind(R,he)},et="https://docs.datadoghq.com",jt=`${et}/real_user_monitoring/browser/troubleshooting`,ke="More details:";function Ht(t,e){return(...n)=>{try{return t(...n)}catch(r){S.error(e,r)}}}function Ue(t){return t!==0&&Math.random()*100<=t}function _r(t){return br(t)&&t>=0&&t<=100}function br(t){return typeof t=="number"}const pe=1e3,H=60*pe,Vt=60*H,vr=365*(24*Vt);function me(){return new Date().getTime()}function F(){return me()}function Re(){return performance.now()}function P(){return{relative:Re(),timeStamp:F()}}function Sr(){return{relative:0,timeStamp:qt()}}function wr(t,e){return e-t}function Er(t,e){return t+e}function xr(t){return t-qt()}let tt;function qt(){return tt===void 0&&(tt=performance.timing.navigationStart),tt}const O=1024,Wt=1024*O,Tr=/[^\u0000-\u007F]/;function nt(t){return Tr.test(t)?window.TextEncoder!==void 0?new TextEncoder().encode(t).length:new Blob([t]).size:t.length}function Cr(t){return{...t}}function Yt(t,e){return Object.keys(t).some(n=>t[n]===e)}function ge(t){return Object.keys(t).length===0}function M(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let t=_dd_temp_;return delete Object.prototype._dd_temp_,typeof t!="object"&&(typeof self=="object"?t=self:typeof window=="object"?t=window:t={}),t}function Q(t,e){const n=M();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=t[n.Zone.__symbol__(e)]),r||(r=t[e]),r}let Ae,Kt=!1;function kr(t){Ae=t}function Ur(t){Kt=t}function Rr(t,e,n){const r=n.value;n.value=function(...s){return(Ae?_(r):r).apply(this,s)}}function _(t){return function(){return ye(t,this,arguments)}}function ye(t,e,n){try{return t.apply(e,n)}catch(r){Ar(r)}}function Ar(t){if(rt(t),Ae)try{Ae(t)}catch(e){rt(e)}}function rt(...t){Kt&&S.error("[MONITOR]",...t)}function _e(t,e){return Q(M(),"setTimeout")(_(t),e)}function Jt(t){Q(M(),"clearTimeout")(t)}function st(t,e){return Q(M(),"setInterval")(_(t),e)}function Xt(t){Q(M(),"clearInterval")(t)}class w{constructor(e){this.onFirstSubscribe=e,this.observers=[]}subscribe(e){return this.observers.push(e),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(n=>e!==n),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(e){this.observers.forEach(n=>n(e))}}function Zt(...t){return new w(e=>{const n=t.map(r=>r.subscribe(s=>e.notify(s)));return()=>n.forEach(r=>r.unsubscribe())})}function Qt(t,e,n){let r=!1,s,i;return{throttled:(...o)=>{if(r){s=o;return}t(...o),r=!0,i=_e(()=>{s&&t(...s),r=!1,s=void 0},e)},cancel:()=>{Jt(i),r=!1,s=void 0}}}function B(){}function N(t){return t?(parseInt(t,10)^Math.random()*16>>parseInt(t,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,N)}const Oe=/([\w-]+)\s*=\s*([^;]+)/g;function Or(t,e){for(Oe.lastIndex=0;;){const n=Oe.exec(t);if(n){if(n[1]===e)return n[2]}else break}}function Lr(t){const e=new Map;for(Oe.lastIndex=0;;){const n=Oe.exec(t);if(n)e.set(n[1],n[2]);else break}return e}function Dr(t,e,n=""){const r=t.charCodeAt(e-1),i=r>=55296&&r<=56319?e+1:e;return t.length<=i?t:`${t.slice(0,i)}${n}`}function Ir(){return Fr()===0}let Le;function Fr(){return Le??(Le=Pr())}function Pr(t=window){var e;const n=t.navigator.userAgent;return t.chrome||/HeadlessChrome/.test(n)?0:((e=t.navigator.vendor)===null||e===void 0?void 0:e.indexOf("Apple"))===0||/safari/i.test(n)&&!/chrome|android/i.test(n)?1:2}function be(t,e,n=0,r){const s=new Date;s.setTime(s.getTime()+n);const i=`expires=${s.toUTCString()}`,o=r&&r.crossSite?"none":"strict",a=r&&r.domain?`;domain=${r.domain}`:"",c=r&&r.secure?";secure":"",u=r&&r.partitioned?";partitioned":"";document.cookie=`${t}=${e};${i};path=/;samesite=${o}${a}${c}${u}`}function it(t){return Or(document.cookie,t)}let ot;function V(t){return ot||(ot=Lr(document.cookie)),ot.get(t)}function en(t,e){be(t,"",0,e)}function Mr(t){if(document.cookie===void 0||document.cookie===null)return!1;try{const e=`dd_cookie_test_${N()}`,n="test";be(e,n,H,t);const r=it(e)===n;return en(e,t),r}catch(e){return S.error(e),!1}}let at;function Br(){if(at===void 0){const t=`dd_site_test_${N()}`,e="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!it(t);)r=`${n.pop()}.${r}`,be(t,e,pe,{domain:r});en(t,{domain:r}),at=r}return at}const ee="_dd_s";function De(t){return Object.values(t)}function Nr(t){return Object.entries(t)}const ct=4*Vt,tn=15*H,$r=vr,ve={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},nn=/^([a-zA-Z]+)=([a-z0-9-]+)$/,lt="&";function zr(t){return!!t&&(t.indexOf(lt)!==-1||nn.test(t))}const Gr="1";function q(t,e){const n={isExpired:Gr};return e.trackAnonymousUser&&(t!=null&&t.anonymousId?n.anonymousId=t==null?void 0:t.anonymousId:n.anonymousId=N()),n}function Ie(t){return ge(t)}function rn(t){return!Ie(t)}function Fe(t){return t.isExpired!==void 0||!jr(t)}function jr(t){return(t.created===void 0||me()-Number(t.created)<ct)&&(t.expire===void 0||me()<Number(t.expire))}function sn(t){t.expire=String(me()+tn)}function ut(t){return Nr(t).map(([e,n])=>e==="anonymousId"?`aid=${n}`:`${e}=${n}`).join(lt)}function on(t){const e={};return zr(t)&&t.split(lt).forEach(n=>{const r=nn.exec(n);if(r!==null){const[,s,i]=r;s==="aid"?e.anonymousId=i:e[s]=i}}),e}const Hr="_dd",Vr="_dd_r",qr="_dd_l",Wr="rum",Yr="logs";function Kr(t){if(!V(ee)){const n=V(Hr),r=V(Vr),s=V(qr),i={};n&&(i.id=n),s&&/^[01]$/.test(s)&&(i[Yr]=s),r&&/^[012]$/.test(r)&&(i[Wr]=r),rn(i)&&(sn(i),t.persistSession(i))}}function an(t){const e=es(t);return Mr(e)?{type:ve.COOKIE,cookieOptions:e}:void 0}function Jr(t,e){const n={isLockEnabled:Ir(),persistSession:Xr(e),retrieveSession:Qr,expireSession:r=>Zr(e,r,t)};return Kr(n),n}function Xr(t){return e=>{be(ee,ut(e),tn,t)}}function Zr(t,e,n){const r=q(e,n);be(ee,ut(r),n.trackAnonymousUser?$r:ct,t)}function Qr(){const t=it(ee);return on(t)}function es(t){const e={};return e.secure=!!t.useSecureSessionCookie||!!t.usePartitionedCrossSiteSessionCookie,e.crossSite=!!t.usePartitionedCrossSiteSessionCookie,e.partitioned=!!t.usePartitionedCrossSiteSessionCookie,t.trackSessionAcrossSubdomains&&(e.domain=Br()),e}const ts="_dd_test_";function cn(){try{const t=N(),e=`${ts}${t}`;localStorage.setItem(e,t);const n=localStorage.getItem(e);return localStorage.removeItem(e),t===n?{type:ve.LOCAL_STORAGE}:void 0}catch{return}}function ns(t){return{isLockEnabled:!1,persistSession:ln,retrieveSession:rs,expireSession:e=>ss(e,t)}}function ln(t){localStorage.setItem(ee,ut(t))}function rs(){const t=localStorage.getItem(ee);return on(t)}function ss(t,e){ln(q(t,e))}const is=10,os=100,un=[];let Pe;function W(t,e,n=0){var r;const{isLockEnabled:s,persistSession:i,expireSession:o}=e,a=f=>i({...f,lock:u}),c=()=>{const f=e.retrieveSession(),h=f.lock;return f.lock&&delete f.lock,{session:f,lock:h}};if(Pe||(Pe=t),t!==Pe){un.push(t);return}if(s&&n>=os){dn(e);return}let u,l=c();if(s){if(l.lock){Me(t,e,n);return}if(u=N(),a(l.session),l=c(),l.lock!==u){Me(t,e,n);return}}let d=t.process(l.session);if(s&&(l=c(),l.lock!==u)){Me(t,e,n);return}if(d&&(Fe(d)?o(d):(sn(d),s?a(d):i(d))),s&&!(d&&Fe(d))){if(l=c(),l.lock!==u){Me(t,e,n);return}i(l.session),d=l.session}(r=t.after)===null||r===void 0||r.call(t,d||l.session),dn(e)}function Me(t,e,n){_e(()=>{W(t,e,n+1)},is)}function dn(t){Pe=void 0;const e=un.shift();e&&W(e,t)}const fn=pe;function as(t){switch(t.sessionPersistence){case ve.COOKIE:return an(t);case ve.LOCAL_STORAGE:return cn();case void 0:{let e=an(t);return!e&&t.allowFallbackToLocalStorage&&(e=cn()),e}default:S.error(`Invalid session persistence '${String(t.sessionPersistence)}'`)}}function cs(t,e,n,r){const s=new w,i=new w,o=new w,a=t.type===ve.COOKIE?Jr(e,t.cookieOptions):ns(e),{expireSession:c}=a,u=st(p,fn);let l;m();const{throttled:d,cancel:f}=Qt(()=>{W({process:y=>{if(Ie(y))return;const de=b(y);return ce(de),de},after:y=>{rn(y)&&!k()&&Zn(y),l=y}},a)},fn);function h(){W({process:y=>k()?b(y):void 0},a)}function p(){W({process:y=>Fe(y)?q(y,e):void 0,after:b},a)}function b(y){return Fe(y)&&(y=q(y,e)),k()&&(le(y)?ue():(o.notify({previousState:l,newState:y}),l=y)),y}function m(){W({process:y=>{if(Ie(y))return q(y,e)},after:y=>{l=y}},a)}function ce(y){if(Ie(y))return!1;const{trackingType:de,isTracked:da}=r(y[n]);y[n]=de,delete y.isExpired,da&&!y.id&&(y.id=N(),y.created=String(me()))}function k(){return l[n]!==void 0}function le(y){return l.id!==y.id||l[n]!==y[n]}function ue(){l=q(l,e),i.notify()}function Zn(y){l=y,s.notify()}function Qn(y){W({process:de=>({...de,...y}),after:b},a)}return{expandOrRenewSession:d,expandSession:h,getSession:()=>l,renewObservable:s,expireObservable:i,sessionStateUpdateObservable:o,restartSession:m,expire:()=>{f(),c(l),b(q(l,e))},stop:()=>{Xt(u)},updateSessionState:Qn}}const dt={GRANTED:"granted",NOT_GRANTED:"not-granted"};function ls(t){const e=new w;return{tryToInit(n){t||(t=n)},update(n){t=n,e.notify()},isGranted(){return t===dt.GRANTED},observable:e}}function Y(t,e,n){if(typeof t!="object"||t===null)return JSON.stringify(t);const r=te(Object.prototype),s=te(Array.prototype),i=te(Object.getPrototypeOf(t)),o=te(t);try{return JSON.stringify(t,e,n)}catch{return"<error: unable to serialize object>"}finally{r(),s(),i(),o()}}function te(t){const e=t,n=e.toJSON;return n?(delete e.toJSON,()=>{e.toJSON=n}):B}function ft(t){return us(t,location.href).href}function us(t,e){const n=ds();if(n)try{return e!==void 0?new n(t,e):new n(t)}catch(i){throw new Error(`Failed to construct URL: ${String(i)} ${Y({url:t,base:e})}`)}if(e===void 0&&!/:/.test(t))throw new Error(`Invalid URL: '${t}'`);let r=document;const s=r.createElement("a");if(e!==void 0){r=document.implementation.createHTMLDocument("");const i=r.createElement("base");i.href=e,r.head.appendChild(i),r.body.appendChild(s)}return s.href=t,s}const hn=URL;let Be;function ds(){if(Be===void 0)try{Be=new hn("http://test/path").href==="http://test/path"}catch{Be=!1}return Be?hn:void 0}const fs="datad0g.com",hs="dd0g-gov.com",ne="datadoghq.com",ps="ddog-gov.com",ms="pci.browser-intake-datadoghq.com",gs=["ddsource","ddtags"];function Se(t,e,n){const r=ys(t,e);return{build(s,i){const o=bs(t,e,n,s,i);return r(o)},urlPrefix:r(""),trackType:e}}function ys(t,e){const n=`/api/v2/${e}`,r=t.proxy;if(typeof r=="string"){const i=ft(r);return o=>`${i}?ddforward=${encodeURIComponent(`${n}?${o}`)}`}if(typeof r=="function")return i=>r({path:n,parameters:i});const s=_s(e,t);return i=>`https://${s}${n}?${i}`}function _s(t,e){const{site:n=ne,internalAnalyticsSubdomain:r}=e;if(t==="logs"&&e.usePciIntake&&n===ne)return ms;if(r&&n===ne)return`${r}.${ne}`;if(n===hs)return`http-intake.logs.${n}`;const s=n.split("."),i=s.pop();return`browser-intake-${s.join("-")}.${i}`}function bs({clientToken:t,internalAnalyticsSubdomain:e},n,r,s,{retry:i,encoding:o}){const a=["sdk_version:6.5.0",`api:${s}`].concat(r);i&&a.push(`retry_count:${i.count}`,`retry_after:${i.lastFailureStatus}`);const c=["ddsource=browser",`ddtags=${encodeURIComponent(a.join(","))}`,`dd-api-key=${t}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${N()}`];return o&&c.push(`dd-evp-encoding=${o}`),n==="rum"&&c.push(`batch_time=${F()}`),e&&c.reverse(),c.join("&")}const vs=200;function Ss(t){const{env:e,service:n,version:r,datacenter:s}=t,i=[];return e&&i.push(Ne("env",e)),n&&i.push(Ne("service",n)),r&&i.push(Ne("version",r)),s&&i.push(Ne("datacenter",s)),i}function Ne(t,e){const n=vs-t.length-1;(e.length>n||ws(e))&&S.warn(`${t} value doesn't meet tag requirements and will be sanitized. ${ke} ${et}/getting_started/tagging/#defining-tags`);const r=e.replace(/,/g,"_");return`${t}:${r}`}function ws(t){return Es()?new RegExp("[^\\p{Ll}\\p{Lo}0-9_:./-]","u").test(t):!1}function Es(){try{return new RegExp("[\\p{Ll}]","u"),!0}catch{return!1}}function xs(t){const e=t.site||ne,n=Ss(t),r=Ts(t,n);return{replica:Cs(t,n),site:e,...r}}function Ts(t,e){return{logsEndpointBuilder:Se(t,"logs",e),rumEndpointBuilder:Se(t,"rum",e),sessionReplayEndpointBuilder:Se(t,"replay",e)}}function Cs(t,e){if(!t.replica)return;const n={...t,site:ne,clientToken:t.replica.clientToken},r={logsEndpointBuilder:Se(n,"logs",e),rumEndpointBuilder:Se(n,"rum",e)};return{applicationId:t.replica.applicationId,...r}}function ks(t){return gs.every(e=>t.includes(e))}function ht(t,e){return t!=null&&typeof t!="string"?(S.error(`${e} must be defined as a string`),!1):!0}function Us(t){return t&&typeof t=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(t)?(S.error(`Site should be a valid Datadog site. ${ke} ${et}/getting_started/site/.`),!1):!0}function $e(t,e){return t!==void 0&&!_r(t)?(S.error(`${e} Sample Rate should be a number between 0 and 100`),!1):!0}function Rs(t){var e,n,r,s,i,o;if(!t||!t.clientToken){S.error("Client Token is not configured, we will not send any data.");return}if(!(!Us(t.site)||!$e(t.sessionSampleRate,"Session")||!$e(t.telemetrySampleRate,"Telemetry")||!$e(t.telemetryConfigurationSampleRate,"Telemetry Configuration")||!$e(t.telemetryUsageSampleRate,"Telemetry Usage")||!ht(t.version,"Version")||!ht(t.env,"Env")||!ht(t.service,"Service"))){if(t.trackingConsent!==void 0&&!Yt(dt,t.trackingConsent)){S.error('Tracking Consent should be either "granted" or "not-granted"');return}return{beforeSend:t.beforeSend&&Ht(t.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:as(t),sessionSampleRate:(e=t.sessionSampleRate)!==null&&e!==void 0?e:100,telemetrySampleRate:(n=t.telemetrySampleRate)!==null&&n!==void 0?n:20,telemetryConfigurationSampleRate:(r=t.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(s=t.telemetryUsageSampleRate)!==null&&s!==void 0?s:5,service:t.service||void 0,silentMultipleInit:!!t.silentMultipleInit,allowUntrustedEvents:!!t.allowUntrustedEvents,trackingConsent:(i=t.trackingConsent)!==null&&i!==void 0?i:dt.GRANTED,trackAnonymousUser:(o=t.trackAnonymousUser)!==null&&o!==void 0?o:!0,storeContextsAcrossPages:!!t.storeContextsAcrossPages,batchBytesLimit:16*O,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*pe,batchMessagesLimit:50,messageBytesLimit:256*O,...xs(t)}}}function As(t){return{session_sample_rate:t.sessionSampleRate,telemetry_sample_rate:t.telemetrySampleRate,telemetry_configuration_sample_rate:t.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:t.telemetryUsageSampleRate,use_before_send:!!t.beforeSend,use_partitioned_cross_site_session_cookie:t.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:t.useSecureSessionCookie,use_proxy:!!t.proxy,silent_multiple_init:t.silentMultipleInit,track_session_across_subdomains:t.trackSessionAcrossSubdomains,track_anonymous_user:t.trackAnonymousUser,session_persistence:t.sessionPersistence,allow_fallback_to_local_storage:!!t.allowFallbackToLocalStorage,store_contexts_across_pages:!!t.storeContextsAcrossPages,allow_untrusted_events:!!t.allowUntrustedEvents,tracking_consent:t.trackingConsent}}var pt;(function(t){t.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",t.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(pt||(pt={}));const pn=new Set;function Os(t){Array.isArray(t)&&Ls(t.filter(e=>Yt(pt,e)))}function Ls(t){t.forEach(e=>{pn.add(e)})}function Ds(){return pn}const we="?";function L(t){const e=[];let n=mt(t,"stack");const r=String(t);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`
2
+ `).forEach(s=>{const i=Ps(s)||Bs(s)||$s(s)||js(s);i&&(!i.func&&i.line&&(i.func=we),e.push(i))}),{message:mt(t,"message"),name:mt(t,"name"),stack:e}}const mn="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\w+\\.|\\/).*?)",re="(?::(\\d+))",Is=new RegExp(`^\\s*at (.*?) ?\\(${mn}${re}?${re}?\\)?\\s*$`,"i"),Fs=new RegExp(`\\((\\S*)${re}${re}\\)`);function Ps(t){const e=Is.exec(t);if(!e)return;const n=e[2]&&e[2].indexOf("native")===0,r=e[2]&&e[2].indexOf("eval")===0,s=Fs.exec(e[2]);return r&&s&&(e[2]=s[1],e[3]=s[2],e[4]=s[3]),{args:n?[e[2]]:[],column:e[4]?+e[4]:void 0,func:e[1]||we,line:e[3]?+e[3]:void 0,url:n?void 0:e[2]}}const Ms=new RegExp(`^\\s*at ?${mn}${re}?${re}??\\s*$`,"i");function Bs(t){const e=Ms.exec(t);if(e)return{args:[],column:e[3]?+e[3]:void 0,func:we,line:e[2]?+e[2]:void 0,url:e[1]}}const Ns=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;function $s(t){const e=Ns.exec(t);if(e)return{args:[],column:e[4]?+e[4]:void 0,func:e[1]||we,line:+e[3],url:e[2]}}const zs=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,Gs=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;function js(t){const e=zs.exec(t);if(!e)return;const n=e[3]&&e[3].indexOf(" > eval")>-1,r=Gs.exec(e[3]);return n&&r&&(e[3]=r[1],e[4]=r[2],e[5]=void 0),{args:e[2]?e[2].split(","):[],column:e[5]?+e[5]:void 0,func:e[1]||we,line:e[4]?+e[4]:void 0,url:e[3]}}function mt(t,e){if(typeof t!="object"||!t||!(e in t))return;const n=t[e];return typeof n=="string"?n:void 0}function Hs(t,e,n,r){const s=[{url:e,column:r,line:n}],{name:i,message:o}=qs(t);return{name:i,message:o,stack:s}}const Vs=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\s\S]*)$/;function qs(t){let e,n;return{}.toString.call(t)==="[object String]"&&([,e,n]=Vs.exec(t)),{name:e,message:n}}function ze(t){const n=new Error(t);n.name="HandlingStack";let r;return ye(()=>{const s=L(n);s.stack=s.stack.slice(2),r=K(s)}),r}function K(t){let e=gn(t);return t.stack.forEach(n=>{const r=n.func==="?"?"<anonymous>":n.func,s=n.args&&n.args.length>0?`(${n.args.join(", ")})`:"",i=n.line?`:${n.line}`:"",o=n.line&&n.column?`:${n.column}`:"";e+=`
3
+ at ${r}${s} @ ${n.url}${i}${o}`}),e}function gn(t){return`${t.name||"Error"}: ${t.message}`}function J(t,e,n,{computeHandlingStack:r}={}){let s=t[e];if(typeof s!="function")if(e in t&&e.startsWith("on"))s=B;else return{stop:B};let i=!1;const o=function(){if(i)return s.apply(this,arguments);const a=Array.from(arguments);let c;ye(n,null,[{target:this,parameters:a,onPostCall:l=>{c=l},handlingStack:r?ze("instrumented method"):void 0}]);const u=s.apply(this,a);return c&&ye(c,null,[u]),u};return t[e]=o,{stop:()=>{i=!0,t[e]===o&&(t[e]=s)}}}const Ws=220*O,Ys="$",Ks=3;function D(t,e=Ws){const n=te(Object.prototype),r=te(Array.prototype),s=[],i=new WeakMap,o=gt(t,Ys,void 0,s,i),a=JSON.stringify(o);let c=a?a.length:0;if(c>e){_t(e,"discarded",t);return}for(;s.length>0&&c<e;){const u=s.shift();let l=0;if(Array.isArray(u.source))for(let d=0;d<u.source.length;d++){const f=gt(u.source[d],u.path,d,s,i);if(f!==void 0?c+=JSON.stringify(f).length:c+=4,c+=l,l=1,c>e){_t(e,"truncated",t);break}u.target[d]=f}else for(const d in u.source)if(Object.prototype.hasOwnProperty.call(u.source,d)){const f=gt(u.source[d],u.path,d,s,i);if(f!==void 0&&(c+=JSON.stringify(f).length+l+d.length+Ks,l=1),c>e){_t(e,"truncated",t);break}u.target[d]=f}}return n(),r(),o}function gt(t,e,n,r,s){const i=Zs(t);if(!i||typeof i!="object")return Js(i);const o=yt(i);if(o!=="[Object]"&&o!=="[Array]"&&o!=="[Error]")return o;const a=t;if(s.has(a))return`[Reference seen at ${s.get(a)}]`;const c=n!==void 0?`${e}.${n}`:e,u=Array.isArray(i)?[]:{};return s.set(a,c),r.push({source:i,target:u,path:c}),u}function Js(t){return typeof t=="bigint"?`[BigInt] ${t.toString()}`:typeof t=="function"?`[Function] ${t.name||"unknown"}`:typeof t=="symbol"?`[Symbol] ${t.description||t.toString()}`:t}function yt(t){try{if(t instanceof Event)return Xs(t);if(t instanceof RegExp)return`[RegExp] ${t.toString()}`;const n=Object.prototype.toString.call(t).match(/\[object (.*)\]/);if(n&&n[1])return`[${n[1]}]`}catch{}return"[Unserializable]"}function Xs(t){return{type:t.type,isTrusted:t.isTrusted,currentTarget:t.currentTarget?yt(t.currentTarget):null,target:t.target?yt(t.target):null}}function Zs(t){const e=t;if(e&&typeof e.toJSON=="function")try{return e.toJSON()}catch{}return t}function _t(t,e,n){S.warn(`The data provided has been ${e} as it is over the limit of ${t} characters:`,n)}const yn="No stack, consider using an instance of Error";function _n({stackTrace:t,originalError:e,handlingStack:n,componentStack:r,startClocks:s,nonErrorPrefix:i,source:o,handling:a}){const c=$(e),u=Qs(t,c,i,e),l=ei(c,t)?K(t):yn,d=c?Sn(e,o):void 0,f=t?t.name:void 0,h=bn(e),p=vn(e);return{startClocks:s,source:o,handling:a,handlingStack:n,componentStack:r,originalError:e,type:f,message:u,stack:l,causes:d,fingerprint:h,context:p}}function Qs(t,e,n,r){return t!=null&&t.message&&(t!=null&&t.name)?t.message:e?"Empty message":`${n} ${Y(D(r))}`}function ei(t,e){return e===void 0?!1:t?!0:e.stack.length>0&&(e.stack.length>1||e.stack[0].url!==void 0)}function bn(t){return $(t)&&"dd_fingerprint"in t?String(t.dd_fingerprint):void 0}function vn(t){if(t!==null&&typeof t=="object"&&"dd_context"in t)return t.dd_context}function ti(t){var e;return(e=/@ (.+)/.exec(t))===null||e===void 0?void 0:e[1]}function $(t){return t instanceof Error||Object.prototype.toString.call(t)==="[object Error]"}function Sn(t,e){let n=t;const r=[];for(;$(n==null?void 0:n.cause)&&r.length<10;){const s=L(n.cause);r.push({message:n.cause.message,source:e,type:s==null?void 0:s.name,stack:K(s)}),n=n.cause}return r.length?r:void 0}const T={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function ni(t){const e=(s,i)=>{const o=_n({stackTrace:s,originalError:i,startClocks:P(),nonErrorPrefix:"Uncaught",source:T.SOURCE,handling:"unhandled"});t.notify(o)},{stop:n}=ri(e),{stop:r}=si(e);return{stop:()=>{n(),r()}}}function ri(t){return J(window,"onerror",({parameters:[e,n,r,s,i]})=>{let o;$(i)?o=L(i):o=Hs(e,n,r,s),t(o,i??e)})}function si(t){return J(window,"onunhandledrejection",({parameters:[e]})=>{const n=e.reason||"Empty reason",r=L(n);t(r,n)})}function ii(t){const e={version:"6.5.0",onReady(n){n()},...t};return Object.defineProperty(e,"_setDebug",{get(){return Ur},enumerable:!1}),e}function oi(t,e,n){const r=t[e];r&&!r.q&&r.version&&S.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),t[e]=n,r&&r.q&&r.q.forEach(s=>Ht(s,"onReady callback threw an error:")())}function wn(t,e){e.silentMultipleInit||S.error(`${t} is already initialized.`)}function X(t,e,n,r,s){return bt(t,e,[n],r,s)}function bt(t,e,n,r,{once:s,capture:i,passive:o}={}){const a=_(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!t.allowUntrustedEvents||(s&&d(),r(f))}),c=o?{capture:i,passive:o}:i,u=window.EventTarget&&e instanceof EventTarget?window.EventTarget.prototype:e,l=Q(u,"addEventListener");n.forEach(f=>l.call(e,f,a,c));function d(){const f=Q(u,"removeEventListener");n.forEach(h=>f.call(e,h,a,c))}return{stop:d}}const Ge={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function ai(t,e){const n=[];e.includes(Ge.cspViolation)&&n.push(li(t));const r=e.filter(s=>s!==Ge.cspViolation);return r.length&&n.push(ci(r)),Zt(...n)}function ci(t){return new w(e=>{if(!window.ReportingObserver)return;const n=_((s,i)=>s.forEach(o=>e.notify(ui(o)))),r=new window.ReportingObserver(n,{types:t,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function li(t){return new w(e=>{const{stop:n}=X(t,document,"securitypolicyviolation",r=>{e.notify(di(r))});return n})}function ui(t){const{type:e,body:n}=t;return En({type:n.id,message:`${e}: ${n.message}`,originalError:t,stack:xn(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function di(t){const e=`'${t.blockedURI}' blocked by '${t.effectiveDirective}' directive`;return En({type:t.effectiveDirective,message:`${Ge.cspViolation}: ${e}`,originalError:t,csp:{disposition:t.disposition},stack:xn(t.effectiveDirective,t.originalPolicy?`${e} of the policy "${Dr(t.originalPolicy,100,"...")}"`:"no policy",t.sourceFile,t.lineNumber,t.columnNumber)})}function En(t){return{startClocks:P(),source:T.REPORT,handling:"unhandled",...t}}function xn(t,e,n,r,s){return n?K({name:t,message:e,stack:[{func:"?",url:n,line:r??void 0,column:s??void 0}]}):void 0}function Tn(t,e){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:t,payload:e})}function Cn(t){return t===null?"null":Array.isArray(t)?"array":typeof t}function je(t,e,n=fi()){if(e===void 0)return t;if(typeof e!="object"||e===null)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const s=e.flags||[e.global?"g":"",e.ignoreCase?"i":"",e.multiline?"m":"",e.sticky?"y":"",e.unicode?"u":""].join("");return new RegExp(e.source,s)}if(n.hasAlreadyBeenSeen(e))return;if(Array.isArray(e)){const s=Array.isArray(t)?t:[];for(let i=0;i<e.length;++i)s[i]=je(s[i],e[i],n);return s}const r=Cn(t)==="object"?t:{};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(r[s]=je(r[s],e[s],n));return r}function kn(t){return je(void 0,t)}function se(...t){let e;for(const n of t)n!=null&&(e=je(e,n));return e}function fi(){if(typeof WeakSet<"u"){const e=new WeakSet;return{hasAlreadyBeenSeen(n){const r=e.has(n);return r||e.add(n),r}}}const t=[];return{hasAlreadyBeenSeen(e){const n=t.indexOf(e)>=0;return n||t.push(e),n}}}function hi(){var t;const e=window.navigator;return{status:e.onLine?"connected":"not_connected",interfaces:e.connection&&e.connection.type?[e.connection.type]:void 0,effective_type:(t=e.connection)===null||t===void 0?void 0:t.effectiveType}}function pi(t){const e=new Set;return t.forEach(n=>e.add(n)),Array.from(e)}function Un(t,e){const n=t.indexOf(e);n>=0&&t.splice(n,1)}const mi=500;function Rn(){const t=[];return{add:s=>{t.push(s)>mi&&t.splice(0,1)},remove:s=>{Un(t,s)},drain:s=>{t.forEach(i=>i(s)),t.length=0}}}const Z={log:"log",configuration:"configuration",usage:"usage"},gi=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],yi=[ps];let An=Rn(),ie=t=>{An.add(()=>ie(t))};function _i(t,e){let n;const r=new w,s=new Set,i=!yi.includes(e.site)&&Ue(e.telemetrySampleRate),o={[Z.log]:i,[Z.configuration]:i&&Ue(e.telemetryConfigurationSampleRate),[Z.usage]:i&&Ue(e.telemetryUsageSampleRate)},a=bi();ie=u=>{const l=Y(u);if(o[u.type]&&s.size<e.maxTelemetryEventsPerPage&&!s.has(l)){const d=c(t,u,a);r.notify(d),Tn("telemetry",d),s.add(l)}},kr(Ln);function c(u,l,d){return se({type:"telemetry",date:F(),service:u,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:se(l,{runtime_env:d,connectivity:hi(),sdk_setup:"npm"}),experimental_features:Array.from(Ds())},n!==void 0?n():{})}return{setContextProvider:u=>{n=u},observable:r,enabled:i}}function bi(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function vi(){An.drain()}function Si(t){return t.site===fs}function On(t,e){rt(v.debug,t,e),ie({type:Z.log,message:t,status:"debug",...e})}function Ln(t,e){ie({type:Z.log,status:"error",...xi(t),...e})}function wi(t){ie({type:Z.configuration,configuration:t})}function Ei(t){ie({type:Z.usage,usage:t})}function xi(t){if($(t)){const e=L(t);return{error:{kind:e.name,stack:K(Ti(e))},message:e.message}}return{error:{stack:yn},message:`Uncaught ${Y(t)}`}}function Ti(t){return t.stack=t.stack.filter(e=>!e.url||gi.some(n=>e.url.startsWith(n))),t}const Ee=1/0,Ci=H;let xe=null;const He=new Set;function ki(){He.forEach(t=>t())}function Ui({expireDelay:t,maxEntries:e}){let n=[];const r=[];xe||(xe=st(()=>ki(),Ci));const s=()=>{const h=Re()-t;for(;n.length>0&&n[n.length-1].endTime<h;){const p=n.pop();p&&r.push(p.startTime)}};He.add(s);function i(h,p){const b={value:h,startTime:p,endTime:Ee,remove:()=>{Un(n,b)},close:m=>{b.endTime=m}};return e&&n.length>=e&&n.pop(),n.unshift(b),b}function o(h=Ee,p={returnInactive:!1}){for(const b of n)if(b.startTime<=h){if(p.returnInactive||h<=b.endTime)return b.value;break}}function a(h){const p=n[0];p&&p.endTime===Ee&&p.close(h)}function c(h=Ee,p=0){const b=Er(h,p);return n.filter(m=>m.startTime<=b&&h<=m.endTime).map(m=>m.value)}function u(){return n.map(({startTime:h,endTime:p,value:b})=>({startTime:h,endTime:p===Ee?"Infinity":p,value:b}))}function l(){return r}function d(){n=[]}function f(){He.delete(s),He.size===0&&xe&&(Xt(xe),xe=null)}return{add:i,find:o,closeActive:a,findAll:c,reset:d,stop:f,getAllEntries:u,getDeletedEntries:l}}const Ri=H,Ai=ct;function Oi(t,e,n,r){const s=new w,i=new w,o=cs(t.sessionStoreStrategyType,t,e,n),a=Ui({expireDelay:Ai});o.renewObservable.subscribe(()=>{a.add(c(),Re()),s.notify()}),o.expireObservable.subscribe(()=>{i.notify(),a.closeActive(Re())}),o.expandOrRenewSession(),a.add(c(),Sr().relative),r.observable.subscribe(()=>{r.isGranted()?o.expandOrRenewSession():o.expire()}),Li(t,()=>{r.isGranted()&&o.expandOrRenewSession()}),Di(t,()=>o.expandSession()),Ii(t,()=>o.restartSession());function c(){return{id:o.getSession().id,trackingType:o.getSession()[e],isReplayForced:!!o.getSession().forcedReplay,anonymousId:o.getSession().anonymousId}}return{findSession:(u,l)=>a.find(u,l),renewObservable:s,expireObservable:i,sessionStateUpdateObservable:o.sessionStateUpdateObservable,expire:o.expire,updateSessionState:o.updateSessionState}}function Li(t,e){bt(t,window,["click","touchstart","keydown","scroll"],e,{capture:!0,passive:!0})}function Di(t,e){const n=()=>{document.visibilityState==="visible"&&e()};X(t,document,"visibilitychange",n),st(n,Ri)}function Ii(t,e){X(t,window,"resume",e,{capture:!0})}function Dn(t){return t>=500}function Fi(t){try{return t.clone()}catch{return}}const Pi=80*O,Mi=32,In=3*Wt,Bi=H,Fn=pe;function Pn(t,e,n,r,s){e.transportStatus===0&&e.queuedPayloads.size()===0&&e.bandwidthMonitor.canHandle(t)?Bn(t,e,n,{onSuccess:()=>Nn(0,e,n,r,s),onFailure:()=>{e.queuedPayloads.enqueue(t),Mn(e,n,r,s)}}):e.queuedPayloads.enqueue(t)}function Mn(t,e,n,r){t.transportStatus===2&&_e(()=>{const s=t.queuedPayloads.first();Bn(s,t,e,{onSuccess:()=>{t.queuedPayloads.dequeue(),t.currentBackoffTime=Fn,Nn(1,t,e,n,r)},onFailure:()=>{t.currentBackoffTime=Math.min(Bi,t.currentBackoffTime*2),Mn(t,e,n,r)}})},t.currentBackoffTime)}function Bn(t,e,n,{onSuccess:r,onFailure:s}){e.bandwidthMonitor.add(t),n(t,i=>{e.bandwidthMonitor.remove(t),Ni(i)?(e.transportStatus=e.bandwidthMonitor.ongoingRequestCount>0?1:2,t.retry={count:t.retry?t.retry.count+1:1,lastFailureStatus:i.status},s()):(e.transportStatus=0,r())})}function Nn(t,e,n,r,s){t===0&&e.queuedPayloads.isFull()&&!e.queueFullReported&&(s({message:`Reached max ${r} events size queued for upload: ${In/Wt}MiB`,source:T.AGENT,startClocks:P()}),e.queueFullReported=!0);const i=e.queuedPayloads;for(e.queuedPayloads=$n();i.size()>0;)Pn(i.dequeue(),e,n,r,s)}function Ni(t){return t.type!=="opaque"&&(t.status===0&&!navigator.onLine||t.status===408||t.status===429||Dn(t.status))}function $i(){return{transportStatus:0,currentBackoffTime:Fn,bandwidthMonitor:zi(),queuedPayloads:$n(),queueFullReported:!1}}function $n(){const t=[];return{bytesCount:0,enqueue(e){this.isFull()||(t.push(e),this.bytesCount+=e.bytesCount)},first(){return t[0]},dequeue(){const e=t.shift();return e&&(this.bytesCount-=e.bytesCount),e},size(){return t.length},isFull(){return this.bytesCount>=In}}}function zi(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(t){return this.ongoingRequestCount===0||this.ongoingByteCount+t.bytesCount<=Pi&&this.ongoingRequestCount<Mi},add(t){this.ongoingRequestCount+=1,this.ongoingByteCount+=t.bytesCount},remove(t){this.ongoingRequestCount-=1,this.ongoingByteCount-=t.bytesCount}}}function Gi(t,e,n){const r=$i(),s=(i,o)=>Vi(t,e,i,o);return{send:i=>{Pn(i,r,s,t.trackType,n)},sendOnExit:i=>{ji(t,e,i)}}}function ji(t,e,n){if(!!navigator.sendBeacon&&n.bytesCount<e)try{const i=t.build("beacon",n);if(navigator.sendBeacon(i,n.data))return}catch(i){Hi(i)}const s=t.build("xhr",n);vt(s,n.data)}let zn=!1;function Hi(t){zn||(zn=!0,Ln(t))}function Vi(t,e,n,r){if(qi()&&n.bytesCount<e){const i=t.build("fetch",n);fetch(i,{method:"POST",body:n.data,keepalive:!0,mode:"cors"}).then(_(o=>r==null?void 0:r({status:o.status,type:o.type})),_(()=>{const o=t.build("xhr",n);vt(o,n.data,r)}))}else{const i=t.build("xhr",n);vt(i,n.data,r)}}function qi(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function vt(t,e,n){const r=new XMLHttpRequest;r.open("POST",t,!0),e instanceof Blob&&r.setRequestHeader("Content-Type",e.type),X({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(e)}function St(){const t=Wi();if(t)return{getCapabilities(){var e;return JSON.parse(((e=t.getCapabilities)===null||e===void 0?void 0:e.call(t))||"[]")},getPrivacyLevel(){var e;return(e=t.getPrivacyLevel)===null||e===void 0?void 0:e.call(t)},getAllowedWebViewHosts(){return JSON.parse(t.getAllowedWebViewHosts())},send(e,n,r){const s=r?{id:r}:void 0;t.send(JSON.stringify({eventType:e,event:n,view:s}))}}}function Ve(t){var e;t===void 0&&(t=(e=M().location)===null||e===void 0?void 0:e.hostname);const n=St();return!!n&&n.getAllowedWebViewHosts().some(r=>t===r||t.endsWith(`.${r}`))}function Wi(){return M().DatadogEventBridge}const qe={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function Yi(t){return new w(e=>{const{stop:n}=bt(t,window,["visibilitychange","freeze"],s=>{s.type==="visibilitychange"&&document.visibilityState==="hidden"?e.notify({reason:qe.HIDDEN}):s.type==="freeze"&&e.notify({reason:qe.FROZEN})},{capture:!0}),r=X(t,window,"beforeunload",()=>{e.notify({reason:qe.UNLOADING})}).stop;return()=>{n(),r()}})}function Ki(t){return De(qe).includes(t)}function Ji({encoder:t,request:e,flushController:n,messageBytesLimit:r}){let s={};const i=n.flushObservable.subscribe(d=>l(d));function o(d,f,h){n.notifyBeforeAddMessage(f),h!==void 0?(s[h]=d,n.notifyAfterAddMessage()):t.write(t.isEmpty?d:`
4
+ ${d}`,p=>{n.notifyAfterAddMessage(p-f)})}function a(d){return d!==void 0&&s[d]!==void 0}function c(d){const f=s[d];delete s[d];const h=t.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(h)}function u(d,f){const h=Y(d),p=t.estimateEncodedBytesCount(h);if(p>=r){S.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${ke} ${jt}/#technical-limitations`);return}a(f)&&c(f),o(h,p,f)}function l(d){const f=De(s).join(`
5
+ `);s={};const h=Ki(d.reason),p=h?e.sendOnExit:e.send;if(h&&t.isAsync){const b=t.finishSync();b.outputBytesCount&&p(Gn(b));const m=[b.pendingData,f].filter(Boolean).join(`
6
+ `);m&&p({data:m,bytesCount:nt(m)})}else f&&t.write(t.isEmpty?f:`
7
+ ${f}`),t.finish(b=>{p(Gn(b))})}return{flushController:n,add:u,upsert:u,stop:i.unsubscribe}}function Gn(t){let e;return typeof t.output=="string"?e=t.output:e=new Blob([t.output],{type:"text/plain"}),{data:e,bytesCount:t.outputBytesCount,encoding:t.encoding}}function Xi({messagesLimit:t,bytesLimit:e,durationLimit:n,pageExitObservable:r,sessionExpireObservable:s}){const i=r.subscribe(p=>l(p.reason)),o=s.subscribe(()=>l("session_expire")),a=new w(()=>()=>{i.unsubscribe(),o.unsubscribe()});let c=0,u=0;function l(p){if(u===0)return;const b=u,m=c;u=0,c=0,h(),a.notify({reason:p,messagesCount:b,bytesCount:m})}let d;function f(){d===void 0&&(d=_e(()=>{l("duration_limit")},n))}function h(){Jt(d),d=void 0}return{flushObservable:a,get messagesCount(){return u},notifyBeforeAddMessage(p){c+p>=e&&l("bytes_limit"),u+=1,c+=p,f()},notifyAfterAddMessage(p=0){c+=p,u>=t?l("messages_limit"):c>=e&&l("bytes_limit")},notifyAfterRemoveMessage(p){c-=p,u-=1,u===0&&h()}}}function jn(t,e,n,r,s,i,o=Ji){const a=u(t,e),c=n&&u(t,n);function u(l,{endpoint:d,encoder:f}){return o({encoder:f,request:Gi(d,l.batchBytesLimit,r),flushController:Xi({messagesLimit:l.batchMessagesLimit,bytesLimit:l.batchBytesLimit,durationLimit:l.flushTimeout,pageExitObservable:s,sessionExpireObservable:i}),messageBytesLimit:l.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(l,d=!0){a.add(l),c&&d&&c.add(n.transformMessage?n.transformMessage(l):l)},upsert:(l,d)=>{a.upsert(l,d),c&&c.upsert(n.transformMessage?n.transformMessage(l):l,d)},stop:()=>{a.stop(),c&&c.stop()}}}function We(){let t="",e=0;return{isAsync:!1,get isEmpty(){return!t},write(n,r){const s=nt(n);e+=s,t+=n,r&&r(s)},finish(n){n(this.finishSync())},finishSync(){const n={output:t,outputBytesCount:e,rawBytesCount:e,pendingData:""};return t="",e=0,n},estimateEncodedBytesCount(n){return n.length}}}class Zi{constructor(){this.callbacks={}}notify(e,n){const r=this.callbacks[e];r&&r.forEach(s=>s(n))}subscribe(e,n){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(n),{unsubscribe:()=>{this.callbacks[e]=this.callbacks[e].filter(r=>n!==r)}}}}function Qi(t,e,n){let r=0,s=!1;return{isLimitReached(){if(r===0&&_e(()=>{r=0},H),r+=1,r<=e||s)return s=!1,!1;if(r===e+1){s=!0;try{n({message:`Reached max number of ${t}s by minute: ${e}`,source:T.AGENT,startClocks:P()})}finally{s=!1}}return!0}}}let wt;const Et=new WeakMap;function eo(t){return wt||(wt=to(t)),wt}function to(t){return new w(e=>{const{stop:n}=J(XMLHttpRequest.prototype,"open",no),{stop:r}=J(XMLHttpRequest.prototype,"send",i=>{ro(i,t,e)},{computeHandlingStack:!0}),{stop:s}=J(XMLHttpRequest.prototype,"abort",so);return()=>{n(),r(),s()}})}function no({target:t,parameters:[e,n]}){Et.set(t,{state:"open",method:String(e).toUpperCase(),url:ft(String(n))})}function ro({target:t,handlingStack:e},n,r){const s=Et.get(t);if(!s)return;const i=s;i.state="start",i.startClocks=P(),i.isAborted=!1,i.xhr=t,i.handlingStack=e;let o=!1;const{stop:a}=J(t,"onreadystatechange",()=>{t.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(u(),a(),o)return;o=!0;const l=s;l.state="complete",l.duration=wr(i.startClocks.timeStamp,F()),l.status=t.status,r.notify(Cr(l))},{stop:u}=X(n,t,"loadend",c);r.notify(i)}function so({target:t}){const e=Et.get(t);e&&(e.isAborted=!0)}let xt;function Hn(){return xt||(xt=io()),xt}function io(){return new w(t=>{if(!window.fetch)return;const{stop:e}=J(window,"fetch",n=>oo(n,t),{computeHandlingStack:!0});return e})}function oo({parameters:t,onPostCall:e,handlingStack:n},r){const[s,i]=t;let o=i&&i.method;o===void 0&&s instanceof Request&&(o=s.method);const a=o!==void 0?String(o).toUpperCase():"GET",c=s instanceof Request?s.url:ft(String(s)),u=P(),l={state:"start",init:i,input:s,method:a,startClocks:u,url:c,handlingStack:n};r.notify(l),t[0]=l.input,t[1]=l.init,e(d=>ao(r,d,l))}function ao(t,e,n){const r=n;function s(i){r.state="resolve",Object.assign(r,i),t.notify(r)}e.then(_(i=>{s({response:i,responseType:i.type,status:i.status,isAborted:!1})}),_(i=>{var o,a;s({status:0,isAborted:((a=(o=r.init)===null||o===void 0?void 0:o.signal)===null||a===void 0?void 0:a.aborted)||i instanceof DOMException&&i.code===DOMException.ABORT_ERR,error:i})}))}let Tt={};function co(t){const e=t.map(n=>(Tt[n]||(Tt[n]=lo(n)),Tt[n]));return Zt(...e)}function lo(t){return new w(e=>{const n=R[t];return R[t]=(...r)=>{n.apply(console,r);const s=ze("console error");ye(()=>{e.notify(uo(r,t,s))})},()=>{R[t]=n}})}function uo(t,e,n){const r=t.map(i=>fo(i)).join(" ");let s;if(e===v.error){const i=t.find($);s={stack:i?K(L(i)):void 0,fingerprint:bn(i),causes:i?Sn(i,"console"):void 0,startClocks:P(),message:r,source:T.CONSOLE,handling:"handled",handlingStack:n,context:vn(i)}}return{api:e,message:r,error:s,handlingStack:n}}function fo(t){return typeof t=="string"?D(t):$(t)?gn(L(t)):Y(D(t),void 0,2)}function ho(t){const e=Cn(t)==="object";return e||S.error("Unsupported context:",t),e}function Ct(t,e,n){const r={...t};for(const[s,{required:i,type:o}]of Object.entries(e))o==="string"&&s in r&&(r[s]=String(r[s])),i&&!(s in t)&&S.warn(`The property ${s} of ${n} is required; context will not be sent to the intake.`);return r}function Ye(t="",{customerDataTracker:e,propertiesConfig:n={}}={}){let r={};const s=new w,i={getContext:()=>kn(r),setContext:o=>{ho(o)?(r=D(Ct(o,n,t)),e==null||e.updateCustomerData(r)):i.clearContext(),s.notify()},setContextProperty:(o,a)=>{r=D(Ct({...r,[o]:a},n,t)),e==null||e.updateCustomerData(r),s.notify()},removeContextProperty:o=>{delete r[o],e==null||e.updateCustomerData(r),Ct(r,n,t),s.notify()},clearContext:()=>{r={},e==null||e.resetCustomerData(),s.notify()},changeObservable:s};return i}const po="_dd_c",mo=[];function kt(t,e,n,r){const s=go(n,r);mo.push(X(t,window,"storage",({key:u})=>{s===u&&o()})),e.changeObservable.subscribe(a);const i=se(c(),e.getContext());ge(i)||e.setContext(i);function o(){e.setContext(c())}function a(){localStorage.setItem(s,JSON.stringify(e.getContext()))}function c(){const u=localStorage.getItem(s);return u?JSON.parse(u):{}}}function go(t,e){return`${po}_${t}_${e}`}const yo=3*O,_o=16*O,bo=200;function vo(t=2){const e=new Map;let n=!1;function r(s=0){if(n||t===0)return;const i=t===2?yo:_o;let o=s;e.forEach(a=>{o+=a.getBytesCount()}),o>i&&(So(i),n=!0)}return{createDetachedTracker:()=>{const s=Vn(()=>r(s.getBytesCount()));return s},getOrCreateTracker:s=>(e.has(s)||e.set(s,Vn(r)),e.get(s)),setCompressionStatus:s=>{t===0&&(t=s,r())},getCompressionStatus:()=>t,stop:()=>{e.forEach(s=>s.stop()),e.clear()}}}function Vn(t){let e=0;const{throttled:n,cancel:r}=Qt(i=>{e=nt(Y(i)),t()},bo),s=()=>{r(),e=0};return{updateCustomerData:i=>{ge(i)?s():n(i)},resetCustomerData:s,getBytesCount:()=>e,stop:()=>{r()}}}function So(t){S.warn(`Customer data exceeds the recommended ${t/O}KiB threshold. ${ke} ${jt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function wo(t,e,n){const r=t.getReader(),s=[];let i=0;o();function o(){r.read().then(_(c=>{if(c.done){a();return}s.push(c.value),i+=c.value.length,i>n.bytesLimit?a():o()}),_(c=>e(c)))}function a(){r.cancel().catch(B);let c,u;{let l;if(s.length===1)l=s[0];else{l=new Uint8Array(i);let d=0;s.forEach(f=>{l.set(f,d),d+=f.length})}c=l.slice(0,n.bytesLimit),u=l.length>n.bytesLimit}e(void 0,c,u)}}const Eo="datadog-synthetics-public-id",xo="datadog-synthetics-result-id",To="datadog-synthetics-injects-rum";function qn(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||V(To))}function Co(){const t=window._DATADOG_SYNTHETICS_PUBLIC_ID||V(Eo);return typeof t=="string"?t:void 0}function ko(){const t=window._DATADOG_SYNTHETICS_RESULT_ID||V(xo);return typeof t=="string"?t:void 0}function Ke(t,e,n){const r=n.getHandler(),s=Array.isArray(r)?r:[r];return Wn[t]>=Wn[n.getLevel()]&&s.includes(e)}const g={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},Wn={[g.ok]:0,[g.debug]:1,[g.info]:2,[g.notice]:4,[g.warn]:5,[g.error]:6,[g.critical]:7,[g.alert]:8,[g.emerg]:9};function Je(t,{includeMessage:e=!1}={}){return{stack:t.stack,kind:t.type,message:e?t.message:void 0,causes:t.causes,fingerprint:t.fingerprint,handling:t.handling}}var Uo=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const Te={console:"console",http:"http",silent:"silent"},Ro=Object.keys(g);let C=class{constructor(e,n,r,s=Te.http,i=g.debug,o={}){this.handleLogStrategy=e,this.handlerType=s,this.level=i,this.contextManager=Ye("logger",{customerDataTracker:n}),this.contextManager.setContext(o),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(e,n,r=g.info,s,i){const o=D(n);let a;if(s!=null){const c=_n({stackTrace:$(s)?L(s):void 0,originalError:s,nonErrorPrefix:"Provided",source:T.LOGGER,handling:"handled",startClocks:P()});a=se({error:Je(c,{includeMessage:!0})},o)}else a=o;this.handleLogStrategy({message:D(e),context:a,status:r},this,i)}log(e,n,r=g.info,s){let i;Ke(r,Te.http,this)&&(i=ze("log")),this.logImplementation(e,n,r,s,i)}setContext(e){this.contextManager.setContext(e)}getContext(){return this.contextManager.getContext()}setContextProperty(e,n){this.contextManager.setContextProperty(e,n)}removeContextProperty(e){this.contextManager.removeContextProperty(e)}clearContext(){this.contextManager.clearContext()}setHandler(e){this.handlerType=e}getHandler(){return this.handlerType}setLevel(e){this.level=e}getLevel(){return this.level}};Uo([Rr],C.prototype,"logImplementation",null),C.prototype.ok=I(g.ok),C.prototype.debug=I(g.debug),C.prototype.info=I(g.info),C.prototype.notice=I(g.notice),C.prototype.warn=I(g.warn),C.prototype.error=I(g.error),C.prototype.critical=I(g.critical),C.prototype.alert=I(g.alert),C.prototype.emerg=I(g.emerg);function I(t){return function(e,n,r){let s;Ke(t,Te.http,this)&&(s=ze("log")),this.logImplementation(e,n,t,r,s)}}function Ao(t,e,n){return{view:{referrer:document.referrer,url:window.location.href},context:t.getContext(),user:e.getContext(),account:n.getContext()}}const Oo=32*O;function Lo(t){t.usePciIntake===!0&&t.site&&t.site!=="datadoghq.com"&&S.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const e=Rs(t),n=Yn(t.forwardConsoleLogs,De(v),"Forward Console Logs"),r=Yn(t.forwardReports,De(Ge),"Forward Reports");if(!(!e||!n||!r))return t.forwardErrorsToLogs&&!n.includes(v.error)&&n.push(v.error),{forwardErrorsToLogs:t.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:Oo,...e}}function Yn(t,e,n){if(t===void 0)return[];if(!(t==="all"||Array.isArray(t)&&t.every(r=>e.includes(r)))){S.error(`${n} should be "all" or an array with allowed values "${e.join('", "')}"`);return}return t==="all"?e:pi(t)}function Do(t){const e=As(t);return{forward_errors_to_logs:t.forwardErrorsToLogs,forward_console_logs:t.forwardConsoleLogs,forward_reports:t.forwardReports,use_pci_intake:t.usePciIntake,...e}}function Io(t,e,n){const r=Rn();let s,i;const o=e.observable.subscribe(a);function a(){if(!i||!s||!e.isGranted())return;o.unsubscribe();const c=n(s,i);r.drain(c)}return{init(c){if(!c){S.error("Missing configuration");return}if(Os(c.enableExperimentalFeatures),Ve()&&(c=Fo(c)),s=c,i){wn("DD_LOGS",c);return}const u=Lo(c);u&&(i=u,Hn().subscribe(B),e.tryToInit(u.trackingConsent),a())},get initConfiguration(){return s},getInternalContext:B,handleLog(c,u,l,d=t(),f=F()){r.add(h=>h.handleLog(c,u,l,d,f))}}}function Fo(t){return{...t,clientToken:"empty"}}const Ut="logs";function Po(t){const e=vo(),n=Ye("global context",{customerDataTracker:e.getOrCreateTracker(2)}),r=Ye("user",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),s=Ye("account",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),i=ls();function o(){return Ao(n,r,s)}let a=Io(o,i,(l,d)=>{l.storeContextsAcrossPages&&(kt(d,n,Ut,2),kt(d,r,Ut,1),kt(d,s,Ut,4));const f=t(l,d,o,i);return a=Mo(l,f),f});const c={},u=new C((...l)=>a.handleLog(...l),e.createDetachedTracker());return ii({logger:u,init:_(l=>a.init(l)),setTrackingConsent:_(l=>{i.update(l),Ei({feature:"set-tracking-consent",tracking_consent:l})}),getGlobalContext:_(()=>n.getContext()),setGlobalContext:_(l=>n.setContext(l)),setGlobalContextProperty:_((l,d)=>n.setContextProperty(l,d)),removeGlobalContextProperty:_(l=>n.removeContextProperty(l)),clearGlobalContext:_(()=>n.clearContext()),createLogger:_((l,d={})=>(c[l]=new C((...f)=>a.handleLog(...f),e.createDetachedTracker(),D(l),d.handler,d.level,D(d.context)),c[l])),getLogger:_(l=>c[l]),getInitConfiguration:_(()=>kn(a.initConfiguration)),getInternalContext:_(l=>a.getInternalContext(l)),setUser:_(r.setContext),getUser:_(r.getContext),setUserProperty:_(r.setContextProperty),removeUserProperty:_(r.removeContextProperty),clearUser:_(r.clearContext),setAccount:_(s.setContext),getAccount:_(s.getContext),setAccountProperty:_(s.setContextProperty),removeAccountProperty:_(s.removeContextProperty),clearAccount:_(s.clearContext)})}function Mo(t,e){return{init:n=>{wn("DD_LOGS",n)},initConfiguration:t,...e}}const Bo="logs";function No(t,e){const n=Oi(t,Bo,r=>zo(t,r),e);return{findTrackedSession:(r,s={returnInactive:!1})=>{const i=n.findSession(r,s);return i&&i.trackingType==="1"?{id:i.id,anonymousId:i.anonymousId}:void 0},expireObservable:n.expireObservable}}function $o(t){const n=Kn(t)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new w}}function Kn(t){return Ue(t.sessionSampleRate)?"1":"0"}function zo(t,e){const n=Go(e)?e:Kn(t);return{trackingType:n,isTracked:n==="1"}}function Go(t){return t==="0"||t==="1"}let Jn=!1;function Xe(t){const e=window;if(qn()){const r=n(e.DD_RUM_SYNTHETICS);return!r&&!Jn&&(Jn=!0,On("Logs sent before RUM is injected by the synthetics worker",{testId:Co(),resultId:ko()})),r}return n(e.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(t)}}function jo(t,e,n,r,s){const i=Ro.concat(["custom"]),o={};i.forEach(a=>{o[a]=Qi(a,e.eventRateLimiterThreshold,s)}),n.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:u=void 0,domainContext:l})=>{var d,f;const h=xr(a.date),p=t.findTrackedSession(h);if(!t.findTrackedSession(h,{returnInactive:!0}))return;const m=u||r();let ce;!ge(m.account)&&m.account.id&&(ce=m.account),p&&p.anonymousId&&!m.user.anonymous_id&&(m.user.anonymous_id=p.anonymousId);const k=se({service:e.service,session_id:p?p.id:void 0,session:p?{id:p.id}:void 0,usr:ge(m.user)?void 0:m.user,account:ce,view:m.view},m.context,Xe(h),a,c);((d=e.beforeSend)===null||d===void 0?void 0:d.call(e,k,l))===!1||k.origin!==T.AGENT&&((f=o[k.status])!==null&&f!==void 0?f:o.custom).isLimitReached()||n.notify(1,k)})}const Ho={[v.log]:g.info,[v.debug]:g.debug,[v.info]:g.info,[v.warn]:g.warn,[v.error]:g.error};function Vo(t,e){const n=co(t.forwardConsoleLogs).subscribe(r=>{var s;const i={rawLogsEvent:{date:F(),message:r.message,origin:T.CONSOLE,error:r.error&&Je(r.error),status:Ho[r.api]},messageContext:(s=r.error)===null||s===void 0?void 0:s.context,domainContext:{handlingStack:r.handlingStack}};e.notify(0,i)});return{stop:()=>{n.unsubscribe()}}}function qo(t,e){const n=ai(t,t.forwardReports).subscribe(r=>{let s=r.message,i;const o=r.originalError.type==="deprecation"?g.warn:g.error;o===g.error?i=Je(r):r.stack&&(s+=` Found in ${ti(r.stack)}`),e.notify(0,{rawLogsEvent:{date:F(),message:s,origin:T.REPORT,error:i,status:o}})});return{stop:()=>{n.unsubscribe()}}}function Wo(t,e){if(!t.forwardErrorsToLogs)return{stop:B};const n=eo(t).subscribe(i=>{i.state==="complete"&&s("xhr",i)}),r=Hn().subscribe(i=>{i.state==="resolve"&&s("fetch",i)});function s(i,o){!ks(o.url)&&(Xo(o)||Dn(o.status))&&("xhr"in o?Yo(o.xhr,t,a):o.response?Jo(o.response,t,a):o.error&&Ko(o.error,t,a));function a(c){const u={isAborted:o.isAborted,handlingStack:o.handlingStack};e.notify(0,{rawLogsEvent:{message:`${Zo(i)} error ${o.method} ${o.url}`,date:o.startClocks.timeStamp,error:{stack:c||"Failed to load",handling:void 0},http:{method:o.method,status_code:o.status,url:o.url},status:g.error,origin:T.NETWORK},domainContext:u})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function Yo(t,e,n){typeof t.response=="string"?n(Rt(t.response,e)):n(t.response)}function Ko(t,e,n){n(Rt(K(L(t)),e))}function Jo(t,e,n){const r=Fi(t);!r||!r.body?n():window.TextDecoder?Qo(r.body,e.requestErrorResponseLengthLimit,(s,i)=>{n(s?`Unable to retrieve response: ${s}`:i)}):r.text().then(_(s=>n(Rt(s,e))),_(s=>n(`Unable to retrieve response: ${s}`)))}function Xo(t){return t.status===0&&t.responseType!=="opaque"}function Rt(t,e){return t.length>e.requestErrorResponseLengthLimit?`${t.substring(0,e.requestErrorResponseLengthLimit)}...`:t}function Zo(t){return t==="xhr"?"XHR":"Fetch"}function Qo(t,e,n){wo(t,(r,s,i)=>{if(r)n(r);else{let o=new TextDecoder().decode(s);i&&(o+="..."),n(void 0,o)}},{bytesLimit:e,collectStreamBody:!0})}function ea(t,e){if(!t.forwardErrorsToLogs)return{stop:B};const n=new w,{stop:r}=ni(n),s=n.subscribe(i=>{e.notify(0,{rawLogsEvent:{message:i.message,date:i.startClocks.timeStamp,error:Je(i),origin:T.SOURCE,status:g.error},messageContext:i.context})});return{stop:()=>{r(),s.unsubscribe()}}}const ta=Zi;function na(t){function e(n,r,s,i,o){const a=se(r.getContext(),n.context);if(Ke(n.status,Te.console,r)&&sa(n,a),Ke(n.status,Te.http,r)){const c={rawLogsEvent:{date:o||F(),message:n.message,status:n.status,origin:T.LOGGER},messageContext:a,savedCommonContext:i};s&&(c.domainContext={handlingStack:s}),t.notify(0,c)}}return{handleLog:e}}const ra={[g.ok]:v.debug,[g.debug]:v.debug,[g.info]:v.info,[g.notice]:v.info,[g.warn]:v.warn,[g.error]:v.error,[g.critical]:v.error,[g.alert]:v.error,[g.emerg]:v.error};function sa({status:t,message:e},n){j[ra[t]].call(R,e,n)}function ia(t,e,n,r,s){const i=jn(t,{endpoint:t.logsEndpointBuilder,encoder:We()},t.replica&&{endpoint:t.replica.logsEndpointBuilder,encoder:We()},n,r,s.expireObservable);return e.subscribe(1,o=>{i.add(o)}),i}function oa(t){const e=St();t.subscribe(1,n=>{e.send("log",n)})}function aa(t){return{get:e=>{const n=t.findTrackedSession(e);if(n)return{session_id:n.id}}}}function ca(t){return e=>{t.notify(0,{rawLogsEvent:{message:e.message,date:e.startClocks.timeStamp,origin:T.AGENT,status:g.error}}),On("Error reported to customer",{"error.message":e.message})}}function la(t,e,n,r,s){const i=_i("browser-logs-sdk",e);i.setContextProvider(()=>{var a,c,u,l,d,f;return{application:{id:(a=Xe())===null||a===void 0?void 0:a.application_id},session:{id:(c=s.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(l=(u=Xe())===null||u===void 0?void 0:u.view)===null||l===void 0?void 0:l.id},action:{id:(f=(d=Xe())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const o=[];if(Ve()){const a=St(),c=i.observable.subscribe(u=>a.send("internal_telemetry",u));o.push(()=>c.unsubscribe())}else{const a=jn(e,{endpoint:e.rumEndpointBuilder,encoder:We()},e.replica&&{endpoint:e.replica.rumEndpointBuilder,encoder:We()},n,r,s.expireObservable);o.push(()=>a.stop());const c=i.observable.subscribe(u=>a.add(u,Si(e)));o.push(()=>c.unsubscribe())}return vi(),wi(Do(t)),{telemetry:i,stop:()=>{o.forEach(a=>a())}}}function ua(t,e,n,r){const s=new ta,i=[];s.subscribe(1,f=>Tn("logs",f));const o=ca(s),a=Yi(e),c=e.sessionStoreStrategyType&&!Ve()&&!qn()?No(e,r):$o(e),{stop:u}=la(t,e,o,a,c);i.push(()=>u()),Wo(e,s),ea(e,s),Vo(e,s),qo(e,s);const{handleLog:l}=na(s);if(jo(c,e,s,n,o),Ve())oa(s);else{const{stop:f}=ia(e,s,o,a,c);i.push(()=>f())}const d=aa(c);return{handleLog:l,getInternalContext:d.get,stop:()=>{i.forEach(f=>f())}}}const oe=Po(ua);oi(M(),"DD_LOGS",oe);class ae{constructor(e){this.isLoggingOn=e,oe.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!0,sessionSampleRate:100})}static setMessagePort(e){this.messagePort=e}static getMessagePort(){return this.messagePort}setLoggingOn(e){this.isLoggingOn=e}setAttributes(e){for(const n in e)oe.logger.setContextProperty(n,e[n])}info(e,n){this.isLoggingOn&&(oe.logger.info(e,n),console.log("[Logger] Sending info: ",e))}error(e,n){this.isLoggingOn&&(oe.logger.error(e,n),console.log("[Logger] Sending error: ",e))}warn(e,n){this.isLoggingOn&&(oe.logger.warn(e,n),console.log("[Logger] Sending warn: ",e))}handleMessageFromWorker(e){e.actionType==="INFO"?this.info(e.message,e.attributes):e.actionType==="ERROR"?this.error(e.message,e.attributes):e.actionType==="WARN"?this.warn(e.message,e.attributes):e.actionType==="SET_ATTRIBUTES"&&e.attributes&&this.setAttributes(e.attributes)}static setAttributes(e){ae.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:e})}static info(e,n){ae.messagePort.postMessage({type:"LOG",actionType:"INFO",message:e,attributes:n})}static error(e,n){ae.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:e,attributes:n})}static warn(e,n){ae.messagePort.postMessage({type:"LOG",actionType:"WARN",message:e,attributes:n})}}class Xn{constructor(e,n,r){this.RUN_ADAPTER=!0,this.RUN_PIXEL_TICKERS=!0,this.pixelTickers=[],this.fetchGameParams=async()=>{try{A(this.options,"OTTPlayer")&&console.log("[OTTPlayer] GameId: ",this.options.gameId);let s;const i=`${this.options.cloudFrontURL}/${this.options.gameId}.json`;if(console.log(`[Fetcher] Fetching GameParams from ${i}`),s=await fetch(i),!s.ok)throw new Error(`HTTP error! Status: ${s.status}`);const o=await s.json();if(o.hasOwnProperty("bucketName")&&o.hasOwnProperty("offsets")?s=o:(this.logger.error(`[Fetcher] Game params for ${this.options.gameId} not found in JSON.`),this.options&&A(this.options,"Errors")&&console.error(`[Fetcher] Game params for ${this.options.gameId} not found in JSON.`)),s instanceof Response)throw console.log("gameParams: ",s),new Error("Error fetching game params:"+s.type);this.gameParams=s,this.logger.setAttributes({game_id:this.gameParams.bucketName,customer_name:this.gameParams.customerName,customer_id:this.gameParams.customerId}),this.logger.info("didFetchGameInfo",this.gameParams)}catch(s){this.logger.error("[OTTPlayer] Error fetching game params",{error:s}),A(this.options,"Errors")&&console.error("[OTTPlayer] Error fetching game params:",s)}},console.log("OTTPlayer v1.0.55"),this.video=e,this.options={...r,cloudFrontURL:"https://d1ze2lfw5ong7.cloudfront.net",augmentation:{channelName:"nba"},LOG_TO_DATADOG:!1,ADAPTER_RUN_IN_WORKER:!1,DOWNLOADER_UPDATE_FREQUENCY:1e3,DOWNLOADER_ZIP_START_OFFSET:2,DOWNLOADER_ZIP_END_OFFSET:4,DOWNLOADER_ZIP_LENGTH_SECONDS:2,DECODER_UPDATE_FREQUENCY:40,DECODER_FRAME_BATCH_SIZE:5,DECODER_LEAD_TIME_MILLIS:400},this.logger=new ae(this.options.LOG_TO_DATADOG),this.logger.setAttributes({bb_session_id:crypto.randomUUID(),media_id:r.gameId}),this.logger.info("didGetConfiguration",{...r,fps:n}),sr(this.options).then(()=>{window.BB.playerInstances.length>0&&window.BB.playerInstances.forEach(s=>{s.delete()}),window.BB.workerInstances.length>0&&window.BB.workerInstances.forEach(s=>{s.terminate()}),this.clocker=new dr(this),this.RUN_ADAPTER&&(this.adapter=new yr(this)),this.RUN_PIXEL_TICKERS&&(this.pixelTickers=G.createInAllCorners(this.video)),this.fetchGameParams(),window.BB.playerInstances.push(this)})}onNewMetadata(e){if(this.RUN_ADAPTER){if(!this.adapter)return;this.adapter.onNewMetadata(e)}else{if(!this.clocker)return;this.clocker.onNewMetadata(e)}}onNewSegment(e){if(this.RUN_ADAPTER){if(!this.adapter)return;this.adapter.onNewSegmentForMetadata(e)}else{if(!this.clocker)return;this.clocker.onNewSegment(e)}}toggle(e){this.options.enabled=e}setFps(e){this.fps=e}delete(){var n;(n=this.clocker)==null||n.delete(),this.clocker=void 0,this.adapter&&(this.adapter.delete(),this.adapter=void 0),G.deleteAll(this.pixelTickers),this.pixelTickers=[];const e=window.BB.playerInstances.indexOf(this);e>=0&&window.BB.playerInstances.splice(e,1)}}return window.BB={OTTPlayer:Xn,playerInstances:[],workerInstances:[]},Xn});