Файловый менеджер - Редактировать - /home/jogoso94/public_html/jogos/virtu_piano/scripts/main.js
�азад
'use strict';{window.DOMHandler=class DOMHandler{constructor(iRuntime,componentId){this._iRuntime=iRuntime;this._componentId=componentId;this._hasTickCallback=false;this._tickCallback=()=>this.Tick()}Attach(){}PostToRuntime(handler,data,dispatchOpts,transferables){this._iRuntime.PostToRuntimeComponent(this._componentId,handler,data,dispatchOpts,transferables)}PostToRuntimeAsync(handler,data,dispatchOpts,transferables){return this._iRuntime.PostToRuntimeComponentAsync(this._componentId,handler,data, dispatchOpts,transferables)}_PostToRuntimeMaybeSync(name,data,dispatchOpts){if(this._iRuntime.UsesWorker())this.PostToRuntime(name,data,dispatchOpts);else this._iRuntime._GetLocalRuntime()["_OnMessageFromDOM"]({"type":"event","component":this._componentId,"handler":name,"dispatchOpts":dispatchOpts||null,"data":data,"responseId":null})}AddRuntimeMessageHandler(handler,func){this._iRuntime.AddRuntimeComponentMessageHandler(this._componentId,handler,func)}AddRuntimeMessageHandlers(list){for(const [handler, func]of list)this.AddRuntimeMessageHandler(handler,func)}GetRuntimeInterface(){return this._iRuntime}GetComponentID(){return this._componentId}_StartTicking(){if(this._hasTickCallback)return;this._iRuntime._AddRAFCallback(this._tickCallback);this._hasTickCallback=true}_StopTicking(){if(!this._hasTickCallback)return;this._iRuntime._RemoveRAFCallback(this._tickCallback);this._hasTickCallback=false}Tick(){}};window.RateLimiter=class RateLimiter{constructor(callback,interval){this._callback=callback; this._interval=interval;this._timerId=-1;this._lastCallTime=-Infinity;this._timerCallFunc=()=>this._OnTimer();this._ignoreReset=false;this._canRunImmediate=false}SetCanRunImmediate(c){this._canRunImmediate=!!c}Call(){if(this._timerId!==-1)return;const nowTime=Date.now();const timeSinceLastCall=nowTime-this._lastCallTime;const interval=this._interval;if(timeSinceLastCall>=interval&&this._canRunImmediate){this._lastCallTime=nowTime;this._RunCallback()}else this._timerId=self.setTimeout(this._timerCallFunc, Math.max(interval-timeSinceLastCall,4))}_RunCallback(){this._ignoreReset=true;this._callback();this._ignoreReset=false}Reset(){if(this._ignoreReset)return;this._CancelTimer();this._lastCallTime=Date.now()}_OnTimer(){this._timerId=-1;this._lastCallTime=Date.now();this._RunCallback()}_CancelTimer(){if(this._timerId!==-1){self.clearTimeout(this._timerId);this._timerId=-1}}Release(){this._CancelTimer();this._callback=null;this._timerCallFunc=null}}}; 'use strict';{class ElementState{constructor(elem){this._elem=elem;this._hadFirstUpdate=false;this._isVisibleFlag=true;this._wantHtmlIndex=-1;this._actualHtmlIndex=-1;this._htmlZIndex=-1}SetVisibleFlag(f){this._isVisibleFlag=!!f}GetVisibleFlag(){return this._isVisibleFlag}HadFirstUpdate(){return this._hadFirstUpdate}SetHadFirstUpdate(){this._hadFirstUpdate=true}GetWantHTMLIndex(){return this._wantHtmlIndex}SetWantHTMLIndex(i){this._wantHtmlIndex=i}GetActualHTMLIndex(){return this._actualHtmlIndex}SetActualHTMLIndex(i){this._actualHtmlIndex= i}SetHTMLZIndex(z){this._htmlZIndex=z}GetHTMLZIndex(){return this._htmlZIndex}GetElement(){return this._elem}}window.DOMElementHandler=class DOMElementHandler extends self.DOMHandler{constructor(iRuntime,componentId){super(iRuntime,componentId);this._elementMap=new Map;this._autoAttach=true;this.AddRuntimeMessageHandlers([["create",e=>this._OnCreate(e)],["destroy",e=>this._OnDestroy(e)],["set-visible",e=>this._OnSetVisible(e)],["update-position",e=>this._OnUpdatePosition(e)],["update-state",e=>this._OnUpdateState(e)], ["focus",e=>this._OnSetFocus(e)],["set-css-style",e=>this._OnSetCssStyle(e)],["set-attribute",e=>this._OnSetAttribute(e)],["remove-attribute",e=>this._OnRemoveAttribute(e)]]);this.AddDOMElementMessageHandler("get-element",elem=>elem)}SetAutoAttach(e){this._autoAttach=!!e}AddDOMElementMessageHandler(handler,func){this.AddRuntimeMessageHandler(handler,e=>{const elementId=e["elementId"];const elem=this.GetElementById(elementId);return func(elem,e)})}_OnCreate(e){const elementId=e["elementId"];const elem= this.CreateElement(elementId,e);const elementState=new ElementState(elem);this._elementMap.set(elementId,elementState);elem.style.boxSizing="border-box";elem.style.display="none";elementState.SetVisibleFlag(e["isVisible"]);const focusElem=this._GetFocusElement(elem);focusElem.addEventListener("focus",e=>this._OnFocus(elementId));focusElem.addEventListener("blur",e=>this._OnBlur(elementId));const wantHtmlIndex=e["htmlIndex"];elementState.SetWantHTMLIndex(wantHtmlIndex);elementState.SetHTMLZIndex(e["htmlZIndex"]); if(this._autoAttach){const actualHtmlIndex=this.GetRuntimeInterface().GetAvailableHTMLIndex(wantHtmlIndex);elementState.SetActualHTMLIndex(actualHtmlIndex);const parent=this.GetRuntimeInterface().GetHTMLWrapElement(actualHtmlIndex);parent.appendChild(elem)}}CreateElement(elementId,e){throw new Error("required override");}DestroyElement(elem){}_OnDestroy(e){const elementId=e["elementId"];const elem=this.GetElementById(elementId);this.DestroyElement(elem);if(this._autoAttach)elem.parentElement.removeChild(elem); this._elementMap.delete(elementId)}PostToRuntimeElement(handler,elementId,data){if(!data)data={};data["elementId"]=elementId;this.PostToRuntime(handler,data)}_PostToRuntimeElementMaybeSync(handler,elementId,data){if(!data)data={};data["elementId"]=elementId;this._PostToRuntimeMaybeSync(handler,data)}_OnSetVisible(e){if(!this._autoAttach)return;const elemState=this._elementMap.get(e["elementId"]);const elem=elemState.GetElement();if(elemState.HadFirstUpdate())elem.style.display=e["isVisible"]?"":"none"; else elemState.SetVisibleFlag(e["isVisible"])}_OnUpdatePosition(e){if(!this._autoAttach)return;const elemState=this._elementMap.get(e["elementId"]);const elem=elemState.GetElement();const iRuntime=this.GetRuntimeInterface();elem.style.left=e["left"]+"px";elem.style.top=e["top"]+"px";elem.style.width=e["width"]+"px";elem.style.height=e["height"]+"px";const fontSize=e["fontSize"];if(fontSize!==null)elem.style.fontSize=fontSize+"em";const wantHtmlIndex=e["htmlIndex"];elemState.SetWantHTMLIndex(wantHtmlIndex); const actualHtmlIndex=iRuntime.GetAvailableHTMLIndex(wantHtmlIndex);if(actualHtmlIndex!==elemState.GetActualHTMLIndex()){elem.remove();const parent=iRuntime.GetHTMLWrapElement(actualHtmlIndex);parent.appendChild(elem);elemState.SetActualHTMLIndex(actualHtmlIndex);iRuntime._UpdateHTMLElementsZOrder()}const htmlZIndex=e["htmlZIndex"];if(htmlZIndex!==elemState.GetHTMLZIndex()){elemState.SetHTMLZIndex(htmlZIndex);iRuntime._UpdateHTMLElementsZOrder()}if(!elemState.HadFirstUpdate()){elemState.SetHadFirstUpdate(); if(elemState.GetVisibleFlag())elem.style.display=""}}_OnHTMLLayersChanged(){if(!this._autoAttach)return;for(const elemState of this._elementMap.values()){const wantHtmlIndex=this.GetRuntimeInterface().GetAvailableHTMLIndex(elemState.GetWantHTMLIndex());const actualHtmlIndex=elemState.GetActualHTMLIndex();if(wantHtmlIndex!==-1&&actualHtmlIndex!==-1&&wantHtmlIndex!==actualHtmlIndex){const elem=elemState.GetElement();elem.remove();const parent=this.GetRuntimeInterface().GetHTMLWrapElement(wantHtmlIndex); parent.appendChild(elem);elemState.SetActualHTMLIndex(wantHtmlIndex)}}}_GetAllElementStatesForZOrderUpdate(){if(!this._autoAttach)return null;return[...this._elementMap.values()]}_OnUpdateState(e){const elem=this.GetElementById(e["elementId"]);this.UpdateState(elem,e)}UpdateState(elem,e){throw new Error("required override");}_GetFocusElement(elem){return elem}_OnFocus(elementId){this.PostToRuntimeElement("elem-focused",elementId)}_OnBlur(elementId){this.PostToRuntimeElement("elem-blurred",elementId)}_OnSetFocus(e){const elem= this._GetFocusElement(this.GetElementById(e["elementId"]));if(e["focus"])elem.focus();else elem.blur()}_OnSetCssStyle(e){const elem=this.GetElementById(e["elementId"]);const prop=e["prop"];const val=e["val"];if(prop.startsWith("--"))elem.style.setProperty(prop,val);else elem.style[prop]=val}_OnSetAttribute(e){const elem=this.GetElementById(e["elementId"]);elem.setAttribute(e["name"],e["val"])}_OnRemoveAttribute(e){const elem=this.GetElementById(e["elementId"]);elem.removeAttribute(e["name"])}GetElementById(elementId){const elementState= this._elementMap.get(elementId);if(!elementState)throw new Error(`no element with id ${elementId}`);return elementState.GetElement()}}}; 'use strict';{const isiOSLike=/(iphone|ipod|ipad|macos|macintosh|mac os x)/i.test(navigator.userAgent);const isAndroid=/android/i.test(navigator.userAgent);const isSafari=/safari/i.test(navigator.userAgent)&&!/(chrome|chromium|edg\/|OPR\/|nwjs)/i.test(navigator.userAgent);let resolveCounter=0;function AddScript(url){const elem=document.createElement("script");elem.async=false;elem.type="module";if(url.isStringSrc)return new Promise(resolve=>{const resolveName="c3_resolve_"+resolveCounter;++resolveCounter; self[resolveName]=resolve;elem.textContent=url.str+`\n\nself["${resolveName}"]();`;document.head.appendChild(elem)});else return new Promise((resolve,reject)=>{elem.onload=resolve;elem.onerror=reject;elem.src=url;document.head.appendChild(elem)})}async function CheckSupportsWorkerMode(){if(!navigator["userActivation"]||typeof OffscreenCanvas==="undefined")return false;try{const workerScript=` self.addEventListener("message", () => { try { const offscreenCanvas = new OffscreenCanvas(32, 32); const gl = offscreenCanvas.getContext("webgl"); self.postMessage(!!gl); } catch (err) { console.warn("Feature detection worker error:", err); self.postMessage(false); } });`;let isWorkerModuleSupported=false;const workerScriptBlob=new Blob([workerScript],{"type":"text/javascript"});const w=new Worker(URL.createObjectURL(workerScriptBlob),{get type(){isWorkerModuleSupported=true}});const result=await new Promise(resolve=>{w.addEventListener("message",e=>{w.terminate();resolve(e.data)});w.postMessage("")});return isWorkerModuleSupported&&result}catch(err){console.warn("Error feature detecting worker mode: ",err);return false}}let tmpAudio=new Audio;const supportedAudioFormats= {"audio/webm; codecs=opus":!!tmpAudio.canPlayType("audio/webm; codecs=opus"),"audio/ogg; codecs=opus":!!tmpAudio.canPlayType("audio/ogg; codecs=opus"),"audio/webm; codecs=vorbis":!!tmpAudio.canPlayType("audio/webm; codecs=vorbis"),"audio/ogg; codecs=vorbis":!!tmpAudio.canPlayType("audio/ogg; codecs=vorbis"),"audio/mp4":!!tmpAudio.canPlayType("audio/mp4"),"audio/mpeg":!!tmpAudio.canPlayType("audio/mpeg")};tmpAudio=null;async function BlobToString(blob){const arrayBuffer=await BlobToArrayBuffer(blob); const textDecoder=new TextDecoder("utf-8");return textDecoder.decode(arrayBuffer)}function BlobToArrayBuffer(blob){return new Promise((resolve,reject)=>{const fileReader=new FileReader;fileReader.onload=e=>resolve(e.target.result);fileReader.onerror=err=>reject(err);fileReader.readAsArrayBuffer(blob)})}const queuedArrayBufferReads=[];let activeArrayBufferReads=0;const MAX_ARRAYBUFFER_READS=8;window["RealFile"]=window["File"];const domHandlerClasses=[];const runtimeEventHandlers=new Map;const pendingResponsePromises= new Map;let nextResponseId=0;const runOnStartupFunctions=[];self.runOnStartup=function runOnStartup(f){if(typeof f!=="function")throw new Error("runOnStartup called without a function");runOnStartupFunctions.push(f)};const WEBVIEW_EXPORT_TYPES=new Set(["cordova","playable-ad","instant-games"]);function IsWebViewExportType(exportType){return WEBVIEW_EXPORT_TYPES.has(exportType)}let isWrapperFullscreen=false;window.RuntimeInterface=class RuntimeInterface{constructor(opts){this._useWorker=opts.useWorker; this._messageChannelPort=null;this._runtimeBaseUrl="";this._scriptFolder=opts.scriptFolder;this._workerScriptURLs={};this._worker=null;this._localRuntime=null;this._domHandlers=[];this._runtimeDomHandler=null;this._isFirstSizeUpdate=true;this._canvasLayers=[];this._pendingRemoveElements=[];this._pendingUpdateHTMLZOrder=false;this._updateHTMLZOrderRAFCallback=()=>this._DoUpdateHTMLElementsZOrder();this._isExportingToVideo=false;this._exportToVideoDuration=0;this._jobScheduler=null;this._rafId=-1;this._rafFunc= ()=>this._OnRAFCallback();this._rafCallbacks=new Set;this._wrapperInitResolve=null;this._wrapperComponentIds=[];this._exportType=opts.exportType;this._isFileProtocol=location.protocol.substr(0,4)==="file";if(this._exportType==="playable-ad"||this._exportType==="instant-games")this._useWorker=false;if(isSafari)this._useWorker=false;if(this._exportType==="cordova"&&this._useWorker)if(isAndroid){const chromeVer=/Chrome\/(\d+)/i.exec(navigator.userAgent);if(!chromeVer||!(parseInt(chromeVer[1],10)>=90))this._useWorker= false}if(this.IsAnyWebView2Wrapper())self["chrome"]["webview"].addEventListener("message",e=>this._OnWrapperMessage(e.data));else if(this._exportType==="macos-wkwebview")self["C3WrapperOnMessage"]=msg=>this._OnWrapperMessage(msg);this._localFileBlobs=null;this._localFileStrings=null;if(this._exportType==="html5"&&!window.isSecureContext)console.warn("[Construct] Warning: the browser indicates this is not a secure context. Some features may be unavailable. Use secure (HTTPS) hosting to ensure all features are available."); this.AddRuntimeComponentMessageHandler("canvas","update-size",e=>this._OnUpdateCanvasSize(e));this.AddRuntimeComponentMessageHandler("canvas","set-html-layer-count",e=>this["_OnSetHTMLLayerCount"](e));this.AddRuntimeComponentMessageHandler("canvas","cleanup-html-layers",()=>this._OnCleanUpHTMLLayers());this.AddRuntimeComponentMessageHandler("runtime","cordova-fetch-local-file",e=>this._OnCordovaFetchLocalFile(e));this.AddRuntimeComponentMessageHandler("runtime","create-job-worker",e=>this._OnCreateJobWorker(e)); this.AddRuntimeComponentMessageHandler("runtime","send-wrapper-extension-message",e=>this._OnSendWrapperExtensionMessage(e));if(this._exportType==="cordova")document.addEventListener("deviceready",()=>this._Init(opts));else this._Init(opts)}Release(){this._CancelAnimationFrame();if(this._messageChannelPort){this._messageChannelPort.onmessage=null;this._messageChannelPort=null}if(this._worker){this._worker.terminate();this._worker=null}if(this._localRuntime){this._localRuntime.Release();this._localRuntime= null}for(const {canvas,htmlWrap}of this._canvasLayers){canvas.remove();htmlWrap.remove()}this._canvasLayers.length=0}GetMainCanvas(){return this._canvasLayers[0].canvas}GetAvailableHTMLIndex(index){return Math.min(index,this._canvasLayers.length-1)}GetHTMLWrapElement(index){if(index<0||index>=this._canvasLayers.length)throw new RangeError("invalid canvas layer");return this._canvasLayers[index].htmlWrap}GetRuntimeBaseURL(){return this._runtimeBaseUrl}UsesWorker(){return this._useWorker}GetExportType(){return this._exportType}IsFileProtocol(){return this._isFileProtocol}GetScriptFolder(){return this._scriptFolder}IsiOSCordova(){return isiOSLike&& this._exportType==="cordova"}IsiOSWebView(){const ua=navigator.userAgent;return isiOSLike&&IsWebViewExportType(this._exportType)||navigator["standalone"]||/crios\/|fxios\/|edgios\//i.test(ua)}IsAndroid(){return isAndroid}IsAndroidWebView(){return isAndroid&&IsWebViewExportType(this._exportType)}IsWindowsWebView2(){return this._exportType==="windows-webview2"||!!(this._exportType==="preview"&&window["chrome"]&&window["chrome"]["webview"]&&window["chrome"]["webview"]["postMessage"])}IsAnyWebView2Wrapper(){return this.IsWindowsWebView2()|| this._exportType==="xbox-uwp-webview2"}async _Init(opts){if(this._useWorker){const isWorkerModeSupported=await CheckSupportsWorkerMode();if(!isWorkerModeSupported)this._useWorker=false}if(this._exportType==="macos-wkwebview")this._SendWrapperMessage({"type":"ready"});else if(this.IsAnyWebView2Wrapper()){this._SetupWebView2Polyfills();const result=await this._InitWrapper();this._wrapperComponentIds=result["registeredComponentIds"]}if(this._exportType==="playable-ad"){this._localFileBlobs=self["c3_base64files"]; this._localFileStrings={};await this._ConvertDataUrisToBlobs();for(let i=0,len=opts.engineScripts.length;i<len;++i){const src=opts.engineScripts[i];if(this._localFileStrings.hasOwnProperty(src))opts.engineScripts[i]={isStringSrc:true,str:this._localFileStrings[src]};else if(this._localFileBlobs.hasOwnProperty(src))opts.engineScripts[i]=URL.createObjectURL(this._localFileBlobs[src])}opts.workerDependencyScripts=[]}if(this._exportType==="nwjs"&&self["nw"]&&self["nw"]["App"]["manifest"]["c3-steam-mode"]){let frameNum= 0;this._AddRAFCallback(()=>{frameNum++;document.body.style.opacity=frameNum%2===0?"1":"0.999"})}if(opts.runtimeBaseUrl)this._runtimeBaseUrl=opts.runtimeBaseUrl;else{const origin=location.origin;this._runtimeBaseUrl=(origin==="null"?"file:///":origin)+location.pathname;const i=this._runtimeBaseUrl.lastIndexOf("/");if(i!==-1)this._runtimeBaseUrl=this._runtimeBaseUrl.substr(0,i+1)}if(opts.workerScripts)this._workerScriptURLs=opts.workerScripts;const messageChannel=new MessageChannel;this._messageChannelPort= messageChannel.port1;this._messageChannelPort.onmessage=e=>this["_OnMessageFromRuntime"](e.data);if(window["c3_addPortMessageHandler"])window["c3_addPortMessageHandler"](e=>this._OnMessageFromDebugger(e));this._jobScheduler=new self.JobSchedulerDOM(this);await this._jobScheduler.Init();if(typeof window["StatusBar"]==="object")window["StatusBar"]["hide"]();if(typeof window["AndroidFullScreen"]==="object")try{await new Promise((resolve,reject)=>{window["AndroidFullScreen"]["immersiveMode"](resolve, reject)})}catch(err){console.error("Failed to enter Android immersive mode: ",err)}if(this._useWorker)await this._InitWorker(opts,messageChannel.port2);else await this._InitDOM(opts,messageChannel.port2)}_GetWorkerURL(url){let ret;if(this._workerScriptURLs.hasOwnProperty(url))ret=this._workerScriptURLs[url];else if(url.endsWith("/workermain.js")&&this._workerScriptURLs.hasOwnProperty("workermain.js"))ret=this._workerScriptURLs["workermain.js"];else if(this._exportType==="playable-ad"&&this._localFileBlobs.hasOwnProperty(url))ret= this._localFileBlobs[url];else ret=url;if(ret instanceof Blob)ret=URL.createObjectURL(ret);return ret}async CreateWorker(url,baseUrl,workerOpts){if(url.startsWith("blob:"))return new Worker(url,workerOpts);if(this._exportType==="cordova"&&this._isFileProtocol){let filePath="";if(workerOpts.isC3MainWorker)filePath=url;else filePath=this._scriptFolder+url;const arrayBuffer=await this.CordovaFetchLocalFileAsArrayBuffer(filePath);const blob=new Blob([arrayBuffer],{type:"application/javascript"});return new Worker(URL.createObjectURL(blob), workerOpts)}const absUrl=new URL(url,baseUrl);const isCrossOrigin=location.origin!==absUrl.origin;if(isCrossOrigin){const response=await fetch(absUrl);if(!response.ok)throw new Error("failed to fetch worker script");const blob=await response.blob();return new Worker(URL.createObjectURL(blob),workerOpts)}else return new Worker(absUrl,workerOpts)}_GetWindowInnerWidth(){return Math.max(window.innerWidth,1)}_GetWindowInnerHeight(){return Math.max(window.innerHeight,1)}GetCssDisplayMode(){if(this.IsAnyWebView2Wrapper())return"standalone"; const exportType=this.GetExportType();const standaloneExportTypes=new Set(["cordova","nwjs","macos-wkwebview"]);if(standaloneExportTypes.has(exportType))return"standalone";if(window.matchMedia("(display-mode: fullscreen)").matches)return"fullscreen";else if(window.matchMedia("(display-mode: standalone)").matches)return"standalone";else if(window.matchMedia("(display-mode: minimal-ui)").matches)return"minimal-ui";else if(navigator["standalone"])return"standalone";else return"browser"}_GetCommonRuntimeOptions(opts){return{"runtimeBaseUrl":this._runtimeBaseUrl, "previewUrl":location.href,"windowInnerWidth":this._GetWindowInnerWidth(),"windowInnerHeight":this._GetWindowInnerHeight(),"cssDisplayMode":this.GetCssDisplayMode(),"devicePixelRatio":window.devicePixelRatio,"isFullscreen":RuntimeInterface.IsDocumentFullscreen(),"projectData":opts.projectData,"previewImageBlobs":window["cr_previewImageBlobs"]||this._localFileBlobs,"previewProjectFileBlobs":window["cr_previewProjectFileBlobs"],"previewProjectFileSWUrls":window["cr_previewProjectFiles"],"swClientId":window["cr_swClientId"]|| "","exportType":opts.exportType,"isDebug":(new URLSearchParams(self.location.search)).has("debug"),"ife":!!self.ife,"jobScheduler":this._jobScheduler.GetPortData(),"supportedAudioFormats":supportedAudioFormats,"opusWasmScriptUrl":window["cr_opusWasmScriptUrl"]||this._scriptFolder+"opus.wasm.js","opusWasmBinaryUrl":window["cr_opusWasmBinaryUrl"]||this._scriptFolder+"opus.wasm.wasm","isFileProtocol":this._isFileProtocol,"isiOSCordova":this.IsiOSCordova(),"isiOSWebView":this.IsiOSWebView(),"isWindowsWebView2":this.IsWindowsWebView2(), "isAnyWebView2Wrapper":this.IsAnyWebView2Wrapper(),"wrapperComponentIds":this._wrapperComponentIds,"isFBInstantAvailable":typeof self["FBInstant"]!=="undefined"}}async _InitWorker(opts,port2){const workerMainUrl=this._GetWorkerURL(opts.workerMainUrl);if(this._exportType==="preview"){this._worker=new Worker("previewworker.js",{type:"module",name:"Runtime"});await new Promise((resolve,reject)=>{const messageHandler=e=>{this._worker.removeEventListener("message",messageHandler);if(e.data&&e.data["type"]=== "ok")resolve();else reject()};this._worker.addEventListener("message",messageHandler);this._worker.postMessage({"type":"construct-worker-init","import":(new URL(workerMainUrl,this._runtimeBaseUrl)).toString()})})}else this._worker=await this.CreateWorker(workerMainUrl,this._runtimeBaseUrl,{type:"module",name:"Runtime",isC3MainWorker:true});const canvas=document.createElement("canvas");canvas.style.display="none";const offscreenCanvas=canvas["transferControlToOffscreen"]();document.body.appendChild(canvas); const htmlWrap=document.createElement("div");htmlWrap.className="c3htmlwrap";document.body.appendChild(htmlWrap);this._canvasLayers.push({canvas,htmlWrap});window["c3canvas"]=canvas;if(self["C3_InsertHTMLPlaceholders"])self["C3_InsertHTMLPlaceholders"]();let workerDependencyScripts=opts.workerDependencyScripts||[];let engineScripts=opts.engineScripts;workerDependencyScripts=await Promise.all(workerDependencyScripts.map(url=>this._MaybeGetCordovaScriptURL(url)));engineScripts=await Promise.all(engineScripts.map(url=> this._MaybeGetCordovaScriptURL(url)));if(this._exportType==="cordova")for(let i=0,len=opts.projectScripts.length;i<len;++i){const info=opts.projectScripts[i];const originalUrl=info[0];if(originalUrl===opts.mainProjectScript||(originalUrl==="scriptsInEvents.js"||originalUrl.endsWith("/scriptsInEvents.js")))info[1]=await this._MaybeGetCordovaScriptURL(originalUrl)}this._worker.postMessage(Object.assign(this._GetCommonRuntimeOptions(opts),{"type":"init-runtime","isInWorker":true,"messagePort":port2, "canvas":offscreenCanvas,"workerDependencyScripts":workerDependencyScripts,"engineScripts":engineScripts,"projectScripts":opts.projectScripts,"mainProjectScript":opts.mainProjectScript,"projectScriptsStatus":self["C3_ProjectScriptsStatus"]}),[port2,offscreenCanvas,...this._jobScheduler.GetPortTransferables()]);this._domHandlers=domHandlerClasses.map(C=>new C(this));this._FindRuntimeDOMHandler();this._runtimeDomHandler._AddDefaultCanvasEventHandlers(canvas);this._runtimeDomHandler._AddDefaultHTMLWrapEventHandlers(htmlWrap); this._runtimeDomHandler._EnableWindowResizeEvent();self["c3_callFunction"]=(name,params)=>this._runtimeDomHandler._InvokeFunctionFromJS(name,params);if(this._exportType==="preview")self["goToLastErrorScript"]=()=>this.PostToRuntimeComponent("runtime","go-to-last-error-script")}async _InitDOM(opts,port2){const canvas=document.createElement("canvas");canvas.style.display="none";document.body.appendChild(canvas);const htmlWrap=document.createElement("div");htmlWrap.className="c3htmlwrap";document.body.appendChild(htmlWrap); this._canvasLayers.push({canvas,htmlWrap});window["c3canvas"]=canvas;if(self["C3_InsertHTMLPlaceholders"])self["C3_InsertHTMLPlaceholders"]();this._domHandlers=domHandlerClasses.map(C=>new C(this));this._FindRuntimeDOMHandler();this._runtimeDomHandler._AddDefaultCanvasEventHandlers(canvas);this._runtimeDomHandler._AddDefaultHTMLWrapEventHandlers(htmlWrap);let engineScripts=opts.engineScripts.map(url=>typeof url==="string"?(new URL(url,this._runtimeBaseUrl)).toString():url);if(Array.isArray(opts.workerDependencyScripts)){const workerDependencyScripts= [...opts.workerDependencyScripts].map(s=>s instanceof Blob?URL.createObjectURL(s):s);engineScripts.unshift(...workerDependencyScripts)}engineScripts=await Promise.all(engineScripts.map(url=>this._MaybeGetCordovaScriptURL(url)));await Promise.all(engineScripts.map(url=>AddScript(url)));const scriptsStatus=self["C3_ProjectScriptsStatus"];const mainProjectScript=opts.mainProjectScript;const allProjectScripts=opts.projectScripts;for(let [originalUrl,loadUrl]of allProjectScripts){if(!loadUrl)loadUrl=originalUrl; if(originalUrl===mainProjectScript)try{loadUrl=await this._MaybeGetCordovaScriptURL(loadUrl);await AddScript(loadUrl);if(this._exportType==="preview"&&!scriptsStatus[originalUrl])this._ReportProjectMainScriptError(originalUrl,"main script did not run to completion")}catch(err){this._ReportProjectMainScriptError(originalUrl,err)}else if(originalUrl==="scriptsInEvents.js"||originalUrl.endsWith("/scriptsInEvents.js")){loadUrl=await this._MaybeGetCordovaScriptURL(loadUrl);await AddScript(loadUrl)}}if(this._exportType=== "preview"&&typeof self.C3.ScriptsInEvents!=="object"){this._RemoveLoadingMessage();const msg="Failed to load JavaScript code used in events. Check all your JavaScript code has valid syntax.";console.error("[C3 runtime] "+msg);alert(msg);return}const runtimeOpts=Object.assign(this._GetCommonRuntimeOptions(opts),{"isInWorker":false,"messagePort":port2,"canvas":canvas,"runOnStartupFunctions":runOnStartupFunctions});this._runtimeDomHandler._EnableWindowResizeEvent();this._OnBeforeCreateRuntime();this._localRuntime= self["C3_CreateRuntime"](runtimeOpts);await self["C3_InitRuntime"](this._localRuntime,runtimeOpts)}_ReportProjectMainScriptError(url,err){this._RemoveLoadingMessage();console.error(`[Preview] Failed to load project main script (${url}): `,err);alert(`Failed to load project main script (${url}). Check all your JavaScript code has valid syntax. Press F12 and check the console for error details.`)}_OnBeforeCreateRuntime(){this._RemoveLoadingMessage()}_RemoveLoadingMessage(){const loadingElem=window["cr_previewLoadingElem"]; if(loadingElem){loadingElem.parentElement.removeChild(loadingElem);window["cr_previewLoadingElem"]=null}}async _OnCreateJobWorker(e){const outputPort=await this._jobScheduler._CreateJobWorker();return{"outputPort":outputPort,"transferables":[outputPort]}}_OnUpdateCanvasSize(e){if(this.IsExportingToVideo())return;const widthPx=e["styleWidth"]+"px";const heightPx=e["styleHeight"]+"px";const leftPx=e["marginLeft"]+"px";const topPx=e["marginTop"]+"px";for(const {canvas,htmlWrap}of this._canvasLayers){canvas.style.width= widthPx;canvas.style.height=heightPx;canvas.style.marginLeft=leftPx;canvas.style.marginTop=topPx;htmlWrap.style.width=widthPx;htmlWrap.style.height=heightPx;htmlWrap.style.marginLeft=leftPx;htmlWrap.style.marginTop=topPx;if(this._isFirstSizeUpdate){canvas.style.display="";htmlWrap.style.display=""}}document.documentElement.style.setProperty("--construct-scale",e["displayScale"]);this._isFirstSizeUpdate=false}["_OnSetHTMLLayerCount"](e){const count=e["count"];const immediate=e["immediate"];const widthPx= e["styleWidth"]+"px";const heightPx=e["styleHeight"]+"px";const leftPx=e["marginLeft"]+"px";const topPx=e["marginTop"]+"px";const addedCanvases=[];const transferables=[];if(count<this._canvasLayers.length)while(this._canvasLayers.length>count){const {canvas,htmlWrap}=this._canvasLayers.pop();htmlWrap.remove();if(this._useWorker&&!immediate)this._pendingRemoveElements.push(canvas);else canvas.remove()}else if(count>this._canvasLayers.length)for(let i=0,len=count-this._canvasLayers.length;i<len;++i){const canvas= document.createElement("canvas");canvas.classList.add("c3overlay");if(this._useWorker){const offscreenCanvas=canvas["transferControlToOffscreen"]();addedCanvases.push(offscreenCanvas);transferables.push(offscreenCanvas)}else addedCanvases.push(canvas);document.body.appendChild(canvas);const htmlWrap=document.createElement("div");htmlWrap.classList.add("c3htmlwrap","c3overlay");document.body.appendChild(htmlWrap);canvas.style.width=widthPx;canvas.style.height=heightPx;canvas.style.marginLeft=leftPx; canvas.style.marginTop=topPx;htmlWrap.style.width=widthPx;htmlWrap.style.height=heightPx;htmlWrap.style.marginLeft=leftPx;htmlWrap.style.marginTop=topPx;this._runtimeDomHandler._AddDefaultCanvasEventHandlers(canvas);this._runtimeDomHandler._AddDefaultHTMLWrapEventHandlers(htmlWrap);this._canvasLayers.push({canvas,htmlWrap})}for(const domHandler of this._domHandlers)if(domHandler instanceof window.DOMElementHandler)domHandler._OnHTMLLayersChanged();this._UpdateHTMLElementsZOrder();return{"addedCanvases":addedCanvases, "transferables":transferables}}_OnCleanUpHTMLLayers(){for(const elem of this._pendingRemoveElements)elem.remove();this._pendingRemoveElements.length=0}_UpdateHTMLElementsZOrder(){if(this._pendingUpdateHTMLZOrder)return;this._pendingUpdateHTMLZOrder=true;this._AddRAFCallback(this._updateHTMLZOrderRAFCallback)}_DoUpdateHTMLElementsZOrder(){this._RemoveRAFCallback(this._updateHTMLZOrderRAFCallback);this._pendingUpdateHTMLZOrder=false;let allElementStates=[];for(const domHandler of this._domHandlers)if(domHandler instanceof window.DOMElementHandler){const elemStates=domHandler._GetAllElementStatesForZOrderUpdate();if(elemStates)allElementStates.push(...elemStates)}allElementStates.sort((a,b)=>{const a1=a.GetActualHTMLIndex();const b1=b.GetActualHTMLIndex();if(a1!==b1)return a1-b1;const a2=a.GetHTMLZIndex();const b2=b.GetHTMLZIndex();return a2-b2});let curHtmlIndex=0;let s=0,i=0,len=allElementStates.length;for(;i<len;++i){const es=allElementStates[i];if(es.GetActualHTMLIndex()!==curHtmlIndex){this._DoUpdateHTMLElementsZOrderOnHTMLLayer(curHtmlIndex, allElementStates.slice(s,i));curHtmlIndex=es.GetActualHTMLIndex();s=i}}if(s<i)this._DoUpdateHTMLElementsZOrderOnHTMLLayer(curHtmlIndex,allElementStates.slice(s,i))}_DoUpdateHTMLElementsZOrderOnHTMLLayer(htmlIndex,arr){if(arr.length<=1)return;if(htmlIndex>=this._canvasLayers.length)return;const newChildren=arr.map(es=>es.GetElement());const newChildrenSet=new Set(newChildren);const htmlWrap=this.GetHTMLWrapElement(htmlIndex);const existingChildren=Array.from(htmlWrap.children).filter(elem=>newChildrenSet.has(elem)); let i=0,len=Math.min(newChildren.length,existingChildren.length);for(;i<len;++i)if(newChildren[i]!==existingChildren[i])break;let j=i;for(;j<len;++j)existingChildren[j].remove();j=i;for(;j<len;++j)htmlWrap.appendChild(newChildren[j])}_GetLocalRuntime(){if(this._useWorker)throw new Error("not available in worker mode");return this._localRuntime}PostToRuntimeComponent(component,handler,data,dispatchOpts,transferables){this._messageChannelPort.postMessage({"type":"event","component":component,"handler":handler, "dispatchOpts":dispatchOpts||null,"data":data,"responseId":null},transferables)}PostToRuntimeComponentAsync(component,handler,data,dispatchOpts,transferables){const responseId=nextResponseId++;const ret=new Promise((resolve,reject)=>{pendingResponsePromises.set(responseId,{resolve,reject})});this._messageChannelPort.postMessage({"type":"event","component":component,"handler":handler,"dispatchOpts":dispatchOpts||null,"data":data,"responseId":responseId},transferables);return ret}["_OnMessageFromRuntime"](data){const type= data["type"];if(type==="event")return this._OnEventFromRuntime(data);else if(type==="result")this._OnResultFromRuntime(data);else if(type==="runtime-ready")this._OnRuntimeReady();else if(type==="alert-error"){this._RemoveLoadingMessage();alert(data["message"])}else if(type==="creating-runtime")this._OnBeforeCreateRuntime();else throw new Error(`unknown message '${type}'`);}_OnEventFromRuntime(e){const component=e["component"];const handler=e["handler"];const data=e["data"];const responseId=e["responseId"]; const handlerMap=runtimeEventHandlers.get(component);if(!handlerMap){console.warn(`[DOM] No event handlers for component '${component}'`);return}const func=handlerMap.get(handler);if(!func){console.warn(`[DOM] No handler '${handler}' for component '${component}'`);return}let ret=null;try{ret=func(data)}catch(err){console.error(`Exception in '${component}' handler '${handler}':`,err);if(responseId!==null)this._PostResultToRuntime(responseId,false,""+err);return}if(responseId===null)return ret;else if(ret&& ret.then)ret.then(result=>this._PostResultToRuntime(responseId,true,result)).catch(err=>{console.error(`Rejection from '${component}' handler '${handler}':`,err);this._PostResultToRuntime(responseId,false,""+err)});else this._PostResultToRuntime(responseId,true,ret)}_PostResultToRuntime(responseId,isOk,result){let transferables;if(result&&result["transferables"])transferables=result["transferables"];this._messageChannelPort.postMessage({"type":"result","responseId":responseId,"isOk":isOk,"result":result}, transferables)}_OnResultFromRuntime(data){const responseId=data["responseId"];const isOk=data["isOk"];const result=data["result"];const pendingPromise=pendingResponsePromises.get(responseId);if(isOk)pendingPromise.resolve(result);else pendingPromise.reject(result);pendingResponsePromises.delete(responseId)}AddRuntimeComponentMessageHandler(component,handler,func){let handlerMap=runtimeEventHandlers.get(component);if(!handlerMap){handlerMap=new Map;runtimeEventHandlers.set(component,handlerMap)}if(handlerMap.has(handler))throw new Error(`[DOM] Component '${component}' already has handler '${handler}'`); handlerMap.set(handler,func)}static AddDOMHandlerClass(Class){if(domHandlerClasses.includes(Class))throw new Error("DOM handler already added");domHandlerClasses.push(Class)}_FindRuntimeDOMHandler(){for(const dh of this._domHandlers)if(dh.GetComponentID()==="runtime"){this._runtimeDomHandler=dh;return}throw new Error("cannot find runtime DOM handler");}_OnMessageFromDebugger(e){this.PostToRuntimeComponent("debugger","message",e)}_OnRuntimeReady(){for(const h of this._domHandlers)h.Attach()}static IsDocumentFullscreen(){return!!(document["fullscreenElement"]|| document["webkitFullscreenElement"]||document["mozFullScreenElement"]||isWrapperFullscreen)}static _SetWrapperIsFullscreenFlag(f){isWrapperFullscreen=!!f}async GetRemotePreviewStatusInfo(){return await this.PostToRuntimeComponentAsync("runtime","get-remote-preview-status-info")}_AddRAFCallback(f){this._rafCallbacks.add(f);this._RequestAnimationFrame()}_RemoveRAFCallback(f){this._rafCallbacks.delete(f);if(this._rafCallbacks.size===0)this._CancelAnimationFrame()}_RequestAnimationFrame(){if(this._rafId=== -1&&this._rafCallbacks.size>0)this._rafId=requestAnimationFrame(this._rafFunc)}_CancelAnimationFrame(){if(this._rafId!==-1){cancelAnimationFrame(this._rafId);this._rafId=-1}}_OnRAFCallback(){this._rafId=-1;for(const f of this._rafCallbacks)f();this._RequestAnimationFrame()}TryPlayMedia(mediaElem){this._runtimeDomHandler.TryPlayMedia(mediaElem)}RemovePendingPlay(mediaElem){this._runtimeDomHandler.RemovePendingPlay(mediaElem)}_PlayPendingMedia(){this._runtimeDomHandler._PlayPendingMedia()}SetSilent(s){this._runtimeDomHandler.SetSilent(s)}IsAudioFormatSupported(typeStr){return!!supportedAudioFormats[typeStr]}async _WasmDecodeWebMOpus(arrayBuffer){const result= await this.PostToRuntimeComponentAsync("runtime","opus-decode",{"arrayBuffer":arrayBuffer},null,[arrayBuffer]);return new Float32Array(result)}SetIsExportingToVideo(duration){this._isExportingToVideo=true;this._exportToVideoDuration=duration}IsExportingToVideo(){return this._isExportingToVideo}GetExportToVideoDuration(){return this._exportToVideoDuration}IsAbsoluteURL(url){return/^(?:[a-z\-]+:)?\/\//.test(url)||url.substr(0,5)==="data:"||url.substr(0,5)==="blob:"}IsRelativeURL(url){return!this.IsAbsoluteURL(url)}async _MaybeGetCordovaScriptURL(url){if(this._exportType=== "cordova"&&(url.startsWith("file:")||this._isFileProtocol&&this.IsRelativeURL(url))){let filename=url;if(filename.startsWith(this._runtimeBaseUrl))filename=filename.substr(this._runtimeBaseUrl.length);const arrayBuffer=await this.CordovaFetchLocalFileAsArrayBuffer(filename);const blob=new Blob([arrayBuffer],{type:"application/javascript"});return URL.createObjectURL(blob)}else return url}async _OnCordovaFetchLocalFile(e){const filename=e["filename"];switch(e["as"]){case "text":return await this.CordovaFetchLocalFileAsText(filename); case "buffer":return await this.CordovaFetchLocalFileAsArrayBuffer(filename);default:throw new Error("unsupported type");}}_GetPermissionAPI(){const api=window["cordova"]&&window["cordova"]["plugins"]&&window["cordova"]["plugins"]["permissions"];if(typeof api!=="object")throw new Error("Permission API is not loaded");return api}_MapPermissionID(api,permission){const permissionID=api[permission];if(typeof permissionID!=="string")throw new Error("Invalid permission name");return permissionID}_HasPermission(id){const api= this._GetPermissionAPI();return new Promise((resolve,reject)=>api["checkPermission"](this._MapPermissionID(api,id),status=>resolve(!!status["hasPermission"]),reject))}_RequestPermission(id){const api=this._GetPermissionAPI();return new Promise((resolve,reject)=>api["requestPermission"](this._MapPermissionID(api,id),status=>resolve(!!status["hasPermission"]),reject))}async RequestPermissions(permissions){if(this.GetExportType()!=="cordova")return true;if(this.IsiOSCordova())return true;for(const id of permissions){const alreadyGranted= await this._HasPermission(id);if(alreadyGranted)continue;const granted=await this._RequestPermission(id);if(granted===false)return false}return true}async RequirePermissions(...permissions){if(await this.RequestPermissions(permissions)===false)throw new Error("Permission not granted");}CordovaFetchLocalFile(filename){const path=window["cordova"]["file"]["applicationDirectory"]+"www/"+filename;return new Promise((resolve,reject)=>{window["resolveLocalFileSystemURL"](path,entry=>{entry["file"](resolve, reject)},reject)})}async CordovaFetchLocalFileAsText(filename){const file=await this.CordovaFetchLocalFile(filename);return await BlobToString(file)}_CordovaMaybeStartNextArrayBufferRead(){if(!queuedArrayBufferReads.length)return;if(activeArrayBufferReads>=MAX_ARRAYBUFFER_READS)return;activeArrayBufferReads++;const job=queuedArrayBufferReads.shift();this._CordovaDoFetchLocalFileAsAsArrayBuffer(job.filename,job.successCallback,job.errorCallback)}CordovaFetchLocalFileAsArrayBuffer(filename){return new Promise((resolve, reject)=>{queuedArrayBufferReads.push({filename:filename,successCallback:result=>{activeArrayBufferReads--;this._CordovaMaybeStartNextArrayBufferRead();resolve(result)},errorCallback:err=>{activeArrayBufferReads--;this._CordovaMaybeStartNextArrayBufferRead();reject(err)}});this._CordovaMaybeStartNextArrayBufferRead()})}async _CordovaDoFetchLocalFileAsAsArrayBuffer(filename,successCallback,errorCallback){try{const file=await this.CordovaFetchLocalFile(filename);const arrayBuffer=await BlobToArrayBuffer(file); successCallback(arrayBuffer)}catch(err){errorCallback(err)}}_OnWrapperMessage(msg){if(msg==="entered-fullscreen"){RuntimeInterface._SetWrapperIsFullscreenFlag(true);this._runtimeDomHandler._OnFullscreenChange()}else if(msg==="exited-fullscreen"){RuntimeInterface._SetWrapperIsFullscreenFlag(false);this._runtimeDomHandler._OnFullscreenChange()}else if(typeof msg==="object"){const type=msg["type"];if(type==="wrapper-init-response"){this._wrapperInitResolve(msg);this._wrapperInitResolve=null}else if(type=== "extension-message")this.PostToRuntimeComponent("runtime","wrapper-extension-message",msg);else console.warn("Unknown wrapper message: ",msg)}else console.warn("Unknown wrapper message: ",msg)}_OnSendWrapperExtensionMessage(data){this._SendWrapperMessage({"type":"extension-message","componentId":data["componentId"],"messageId":data["messageId"],"params":data["params"]||[],"asyncId":data["asyncId"]})}_SendWrapperMessage(o){if(this.IsAnyWebView2Wrapper())window["chrome"]["webview"]["postMessage"](JSON.stringify(o)); else if(this._exportType==="macos-wkwebview")window["webkit"]["messageHandlers"]["C3Wrapper"]["postMessage"](JSON.stringify(o));else;}_SetupWebView2Polyfills(){window.moveTo=(x,y)=>{this._SendWrapperMessage({"type":"set-window-position","windowX":Math.ceil(x),"windowY":Math.ceil(y)})};window.resizeTo=(w,h)=>{this._SendWrapperMessage({"type":"set-window-size","windowWidth":Math.ceil(w),"windowHeight":Math.ceil(h)})}}_InitWrapper(){if(!this.IsAnyWebView2Wrapper())return Promise.resolve();return new Promise(resolve=> {this._wrapperInitResolve=resolve;this._SendWrapperMessage({"type":"wrapper-init"})})}async _ConvertDataUrisToBlobs(){const promises=[];for(const [filename,data]of Object.entries(this._localFileBlobs))promises.push(this._ConvertDataUriToBlobs(filename,data));await Promise.all(promises)}async _ConvertDataUriToBlobs(filename,data){if(typeof data==="object"){this._localFileBlobs[filename]=new Blob([data["str"]],{"type":data["type"]});this._localFileStrings[filename]=data["str"]}else{let blob=await this._FetchDataUri(data); if(!blob)blob=this._DataURIToBinaryBlobSync(data);this._localFileBlobs[filename]=blob}}async _FetchDataUri(dataUri){try{const response=await fetch(dataUri);return await response.blob()}catch(err){console.warn("Failed to fetch a data: URI. Falling back to a slower workaround. This is probably because the Content Security Policy unnecessarily blocked it. Allow data: URIs in your CSP to avoid this.",err);return null}}_DataURIToBinaryBlobSync(datauri){const o=this._ParseDataURI(datauri);return this._BinaryStringToBlob(o.data, o.mime_type)}_ParseDataURI(datauri){const comma=datauri.indexOf(",");if(comma<0)throw new URIError("expected comma in data: uri");const typepart=datauri.substring(5,comma);const datapart=datauri.substring(comma+1);const typearr=typepart.split(";");const mimetype=typearr[0]||"";const encoding1=typearr[1];const encoding2=typearr[2];let decodeddata;if(encoding1==="base64"||encoding2==="base64")decodeddata=atob(datapart);else decodeddata=decodeURIComponent(datapart);return{mime_type:mimetype,data:decodeddata}}_BinaryStringToBlob(binstr, mime_type){let len=binstr.length;let len32=len>>2;let a8=new Uint8Array(len);let a32=new Uint32Array(a8.buffer,0,len32);let i,j;for(i=0,j=0;i<len32;++i)a32[i]=binstr.charCodeAt(j++)|binstr.charCodeAt(j++)<<8|binstr.charCodeAt(j++)<<16|binstr.charCodeAt(j++)<<24;let tailLength=len&3;while(tailLength--){a8[j]=binstr.charCodeAt(j);++j}return new Blob([a8],{"type":mime_type})}}}; 'use strict';{const RuntimeInterface=self.RuntimeInterface;function IsCompatibilityMouseEvent(e){return e["sourceCapabilities"]&&e["sourceCapabilities"]["firesTouchEvents"]||e["originalEvent"]&&e["originalEvent"]["sourceCapabilities"]&&e["originalEvent"]["sourceCapabilities"]["firesTouchEvents"]}const KEY_CODE_ALIASES=new Map([["OSLeft","MetaLeft"],["OSRight","MetaRight"]]);const DISPATCH_RUNTIME_AND_SCRIPT={"dispatchRuntimeEvent":true,"dispatchUserScriptEvent":true};const DISPATCH_SCRIPT_ONLY={"dispatchUserScriptEvent":true}; const DISPATCH_RUNTIME_ONLY={"dispatchRuntimeEvent":true};function AddStyleSheet(cssUrl){return new Promise((resolve,reject)=>{const styleLink=document.createElement("link");styleLink.onload=()=>resolve(styleLink);styleLink.onerror=err=>reject(err);styleLink.rel="stylesheet";styleLink.href=cssUrl;document.head.appendChild(styleLink)})}function FetchImage(url){return new Promise((resolve,reject)=>{const img=new Image;img.onload=()=>resolve(img);img.onerror=err=>reject(err);img.src=url})}async function BlobToImage(blob){const blobUrl= URL.createObjectURL(blob);try{return await FetchImage(blobUrl)}finally{URL.revokeObjectURL(blobUrl)}}function BlobToString(blob){return new Promise((resolve,reject)=>{let fileReader=new FileReader;fileReader.onload=e=>resolve(e.target.result);fileReader.onerror=err=>reject(err);fileReader.readAsText(blob)})}function IsInContentEditable(el){do{if(el.parentNode&&el.hasAttribute("contenteditable"))return true;el=el.parentNode}while(el);return false}const keyboardInputElementTagNames=new Set(["input", "textarea","datalist","select"]);function IsKeyboardInputElement(elem){return keyboardInputElementTagNames.has(elem.tagName.toLowerCase())||IsInContentEditable(elem)}const canvasOrDocTags=new Set(["canvas","body","html"]);function PreventDefaultOnCanvasOrDoc(e){if(!e.target.tagName)return;const tagName=e.target.tagName.toLowerCase();if(canvasOrDocTags.has(tagName))e.preventDefault()}function PreventDefaultOnHTMLWrap(e){if(!e.target.tagName)return;if(e.target.classList.contains("c3htmlwrap"))e.preventDefault()} function BlockWheelZoom(e){if(e.metaKey||e.ctrlKey)e.preventDefault()}self["C3_GetSvgImageSize"]=async function(blob){const img=await BlobToImage(blob);if(img.width>0&&img.height>0)return[img.width,img.height];else{img.style.position="absolute";img.style.left="0px";img.style.top="0px";img.style.visibility="hidden";document.body.appendChild(img);const rc=img.getBoundingClientRect();document.body.removeChild(img);return[rc.width,rc.height]}};self["C3_RasterSvgImageBlob"]=async function(blob,imageWidth, imageHeight,surfaceWidth,surfaceHeight){const img=await BlobToImage(blob);const canvas=document.createElement("canvas");canvas.width=surfaceWidth;canvas.height=surfaceHeight;const ctx=canvas.getContext("2d");ctx.drawImage(img,0,0,imageWidth,imageHeight);return canvas};let isCordovaPaused=false;document.addEventListener("pause",()=>isCordovaPaused=true);document.addEventListener("resume",()=>isCordovaPaused=false);function ParentHasFocus(){try{return window.parent&&window.parent.document.hasFocus()}catch(err){return false}} const DOM_COMPONENT_ID="runtime";const HANDLER_CLASS=class RuntimeDOMHandler extends self.DOMHandler{constructor(iRuntime){super(iRuntime,DOM_COMPONENT_ID);this._enableWindowResizeEvent=false;this._simulatedResizeTimerId=-1;this._targetOrientation="any";this._attachedDeviceOrientationEvent=false;this._attachedDeviceMotionEvent=false;this._pageVisibilityIsHidden=false;this._screenReaderTextWrap=document.createElement("div");this._screenReaderTextWrap.className="c3-screen-reader-text";this._screenReaderTextWrap.setAttribute("aria-live", "polite");document.body.appendChild(this._screenReaderTextWrap);this._debugHighlightElem=null;this._isExportToVideo=false;this._exportVideoProgressMessage="";this._exportVideoUpdateTimerId=-1;this._enableAndroidVKDetection=false;this._lastWindowWidth=iRuntime._GetWindowInnerWidth();this._lastWindowHeight=iRuntime._GetWindowInnerHeight();this._virtualKeyboardHeight=0;this._vkTranslateYOffset=0;iRuntime.AddRuntimeComponentMessageHandler("runtime","invoke-download",e=>this._OnInvokeDownload(e));iRuntime.AddRuntimeComponentMessageHandler("runtime", "load-webfonts",e=>this._OnLoadWebFonts(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","raster-svg-image",e=>this._OnRasterSvgImage(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","get-svg-image-size",e=>this._OnGetSvgImageSize(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","set-target-orientation",e=>this._OnSetTargetOrientation(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","register-sw",()=>this._OnRegisterSW());iRuntime.AddRuntimeComponentMessageHandler("runtime", "post-to-debugger",e=>this._OnPostToDebugger(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","go-to-script",e=>this._OnPostToDebugger(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","before-start-ticking",()=>this._OnBeforeStartTicking());iRuntime.AddRuntimeComponentMessageHandler("runtime","debug-highlight",e=>this._OnDebugHighlight(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","enable-device-orientation",()=>this._AttachDeviceOrientationEvent());iRuntime.AddRuntimeComponentMessageHandler("runtime", "enable-device-motion",()=>this._AttachDeviceMotionEvent());iRuntime.AddRuntimeComponentMessageHandler("runtime","add-stylesheet",e=>this._OnAddStylesheet(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","script-create-worker",e=>this._OnScriptCreateWorker(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","alert",e=>this._OnAlert(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","screen-reader-text",e=>this._OnScreenReaderTextEvent(e));iRuntime.AddRuntimeComponentMessageHandler("runtime", "hide-cordova-splash",()=>this._OnHideCordovaSplash());iRuntime.AddRuntimeComponentMessageHandler("runtime","set-exporting-to-video",e=>this._SetExportingToVideo(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","export-to-video-progress",e=>this._OnExportVideoProgress(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","exported-to-video",e=>this._OnExportedToVideo(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","exported-to-image-sequence",e=>this._OnExportedToImageSequence(e)); const allowDefaultContextMenuTagNames=new Set(["input","textarea","datalist"]);window.addEventListener("contextmenu",e=>{const t=e.target;const name=t.tagName.toLowerCase();if(!allowDefaultContextMenuTagNames.has(name)&&!IsInContentEditable(t))e.preventDefault()});window.addEventListener("selectstart",PreventDefaultOnCanvasOrDoc);window.addEventListener("gesturehold",PreventDefaultOnCanvasOrDoc);window.addEventListener("touchstart",PreventDefaultOnCanvasOrDoc,{"passive":false});window.addEventListener("pointerdown", PreventDefaultOnCanvasOrDoc,{"passive":false});this._mousePointerLastButtons=0;window.addEventListener("mousedown",e=>{if(e.button===1)e.preventDefault()});window.addEventListener("mousewheel",BlockWheelZoom,{"passive":false});window.addEventListener("wheel",BlockWheelZoom,{"passive":false});window.addEventListener("resize",()=>this._OnWindowResize());window.addEventListener("fullscreenchange",()=>this._OnFullscreenChange());window.addEventListener("webkitfullscreenchange",()=>this._OnFullscreenChange()); window.addEventListener("mozfullscreenchange",()=>this._OnFullscreenChange());window.addEventListener("fullscreenerror",e=>this._OnFullscreenError(e));window.addEventListener("webkitfullscreenerror",e=>this._OnFullscreenError(e));window.addEventListener("mozfullscreenerror",e=>this._OnFullscreenError(e));if(iRuntime.IsiOSWebView()){let lastVisualViewportHeight=Infinity;window["visualViewport"].addEventListener("resize",()=>{const curVisualViewportHeight=window["visualViewport"].height;if(curVisualViewportHeight> lastVisualViewportHeight){document.scrollingElement.scrollTop=0;document.scrollingElement.scrollLeft=0}lastVisualViewportHeight=curVisualViewportHeight});document.documentElement.setAttribute("ioswebview","")}this._mediaPendingPlay=new Set;this._mediaRemovedPendingPlay=new WeakSet;this._isSilent=false}_AddDefaultCanvasEventHandlers(canvas){canvas.addEventListener("selectstart",PreventDefaultOnCanvasOrDoc);canvas.addEventListener("gesturehold",PreventDefaultOnCanvasOrDoc);canvas.addEventListener("pointerdown", PreventDefaultOnCanvasOrDoc)}_AddDefaultHTMLWrapEventHandlers(htmlwrap){htmlwrap.addEventListener("selectstart",PreventDefaultOnHTMLWrap);htmlwrap.addEventListener("gesturehold",PreventDefaultOnHTMLWrap);htmlwrap.addEventListener("touchstart",PreventDefaultOnHTMLWrap)}_OnBeforeStartTicking(){self.setTimeout(()=>{this._enableAndroidVKDetection=true},1E3);if(this._iRuntime.GetExportType()==="cordova"){document.addEventListener("pause",()=>this._OnVisibilityChange(true));document.addEventListener("resume", ()=>this._OnVisibilityChange(false))}else document.addEventListener("visibilitychange",()=>this._OnVisibilityChange(document.visibilityState==="hidden"));this._pageVisibilityIsHidden=!!(document.visibilityState==="hidden"||isCordovaPaused);return{"isSuspended":this._pageVisibilityIsHidden}}Attach(){window.addEventListener("focus",()=>this._PostRuntimeEvent("window-focus"));window.addEventListener("blur",()=>{this._PostRuntimeEvent("window-blur",{"parentHasFocus":ParentHasFocus()});this._mousePointerLastButtons= 0});window.addEventListener("focusin",e=>{if(IsKeyboardInputElement(e.target))this._PostRuntimeEvent("keyboard-blur")});window.addEventListener("keydown",e=>this._OnKeyEvent("keydown",e));window.addEventListener("keyup",e=>this._OnKeyEvent("keyup",e));window.addEventListener("mousedown",e=>this._OnMouseEvent("mousedown",e,DISPATCH_SCRIPT_ONLY));window.addEventListener("mousemove",e=>this._OnMouseEvent("mousemove",e,DISPATCH_SCRIPT_ONLY));window.addEventListener("mouseup",e=>this._OnMouseEvent("mouseup", e,DISPATCH_SCRIPT_ONLY));window.addEventListener("dblclick",e=>this._OnMouseEvent("dblclick",e,DISPATCH_RUNTIME_AND_SCRIPT));window.addEventListener("wheel",e=>this._OnMouseWheelEvent("wheel",e,DISPATCH_RUNTIME_AND_SCRIPT));window.addEventListener("pointerdown",e=>{this._HandlePointerDownFocus(e);this._OnPointerEvent("pointerdown",e)});if(this._iRuntime.UsesWorker()&&typeof window["onpointerrawupdate"]!=="undefined"&&self===self.top)window.addEventListener("pointerrawupdate",e=>this._OnPointerRawUpdate(e)); else window.addEventListener("pointermove",e=>this._OnPointerEvent("pointermove",e));window.addEventListener("pointerup",e=>this._OnPointerEvent("pointerup",e));window.addEventListener("pointercancel",e=>this._OnPointerEvent("pointercancel",e));const playFunc=()=>this._PlayPendingMedia();window.addEventListener("pointerup",playFunc,true);window.addEventListener("touchend",playFunc,true);window.addEventListener("click",playFunc,true);window.addEventListener("keydown",playFunc,true);window.addEventListener("gamepadconnected", playFunc,true);if(this._iRuntime.IsAndroid()&&!this._iRuntime.IsAndroidWebView()&&navigator["virtualKeyboard"]){navigator["virtualKeyboard"]["overlaysContent"]=true;navigator["virtualKeyboard"].addEventListener("geometrychange",()=>{this._OnAndroidVirtualKeyboardChange(this._GetWindowInnerHeight(),navigator["virtualKeyboard"]["boundingRect"]["height"])})}if(this._iRuntime.IsiOSWebView()){document.scrollingElement.scrollTop=0;document.scrollingElement.scrollLeft=0}}_OnAndroidVirtualKeyboardChange(windowHeight, vkHeight){document.body.style.position="";document.body.style.overflow="";document.body.style.transform="";this._vkTranslateYOffset=0;if(vkHeight>0){const activeElement=document.activeElement;if(activeElement){const rc=activeElement.getBoundingClientRect();const rcMidY=(rc.top+rc.bottom)/2;const targetY=(windowHeight-vkHeight)/2;let shiftY=rcMidY-targetY;if(shiftY>vkHeight)shiftY=vkHeight;if(shiftY<0)shiftY=0;if(shiftY>0){document.body.style.position="absolute";document.body.style.overflow="visible"; document.body.style.transform=`translateY(${-shiftY}px)`;this._vkTranslateYOffset=shiftY}}}}_PostRuntimeEvent(name,data){this.PostToRuntime(name,data||null,DISPATCH_RUNTIME_ONLY)}_GetWindowInnerWidth(){return this._iRuntime._GetWindowInnerWidth()}_GetWindowInnerHeight(){return this._iRuntime._GetWindowInnerHeight()}_EnableWindowResizeEvent(){this._enableWindowResizeEvent=true;this._lastWindowWidth=this._iRuntime._GetWindowInnerWidth();this._lastWindowHeight=this._iRuntime._GetWindowInnerHeight()}_OnWindowResize(){if(this._isExportToVideo)return; if(!this._enableWindowResizeEvent)return;const width=this._GetWindowInnerWidth();const height=this._GetWindowInnerHeight();if(this._iRuntime.IsAndroidWebView())if(this._enableAndroidVKDetection)if(this._lastWindowWidth===width&&height<this._lastWindowHeight){this._virtualKeyboardHeight=this._lastWindowHeight-height;this._OnAndroidVirtualKeyboardChange(this._lastWindowHeight,this._virtualKeyboardHeight);return}else{if(this._virtualKeyboardHeight>0){this._virtualKeyboardHeight=0;this._OnAndroidVirtualKeyboardChange(height, this._virtualKeyboardHeight)}this._lastWindowWidth=width;this._lastWindowHeight=height}else{this._lastWindowWidth=width;this._lastWindowHeight=height}this.PostToRuntime("window-resize",{"innerWidth":width,"innerHeight":height,"devicePixelRatio":window.devicePixelRatio,"isFullscreen":RuntimeInterface.IsDocumentFullscreen(),"cssDisplayMode":this._iRuntime.GetCssDisplayMode()});if(this._iRuntime.IsiOSWebView()){if(this._simulatedResizeTimerId!==-1)clearTimeout(this._simulatedResizeTimerId);this._OnSimulatedResize(width, height,0)}}_ScheduleSimulatedResize(width,height,count){if(this._simulatedResizeTimerId!==-1)clearTimeout(this._simulatedResizeTimerId);this._simulatedResizeTimerId=setTimeout(()=>this._OnSimulatedResize(width,height,count),48)}_OnSimulatedResize(originalWidth,originalHeight,count){const width=this._GetWindowInnerWidth();const height=this._GetWindowInnerHeight();this._simulatedResizeTimerId=-1;if(width!=originalWidth||height!=originalHeight)this.PostToRuntime("window-resize",{"innerWidth":width,"innerHeight":height, "devicePixelRatio":window.devicePixelRatio,"isFullscreen":RuntimeInterface.IsDocumentFullscreen(),"cssDisplayMode":this._iRuntime.GetCssDisplayMode()});else if(count<10)this._ScheduleSimulatedResize(width,height,count+1)}_OnSetTargetOrientation(e){this._targetOrientation=e["targetOrientation"]}_TrySetTargetOrientation(){const orientation=this._targetOrientation;if(screen["orientation"]&&screen["orientation"]["lock"])screen["orientation"]["lock"](orientation).catch(err=>console.warn("[Construct] Failed to lock orientation: ", err));else try{let result=false;if(screen["lockOrientation"])result=screen["lockOrientation"](orientation);else if(screen["webkitLockOrientation"])result=screen["webkitLockOrientation"](orientation);else if(screen["mozLockOrientation"])result=screen["mozLockOrientation"](orientation);else if(screen["msLockOrientation"])result=screen["msLockOrientation"](orientation);if(!result)console.warn("[Construct] Failed to lock orientation")}catch(err){console.warn("[Construct] Failed to lock orientation: ", err)}}_OnFullscreenChange(){if(this._isExportToVideo)return;const isDocFullscreen=RuntimeInterface.IsDocumentFullscreen();if(isDocFullscreen&&this._targetOrientation!=="any")this._TrySetTargetOrientation();this.PostToRuntime("fullscreenchange",{"isFullscreen":isDocFullscreen,"innerWidth":this._GetWindowInnerWidth(),"innerHeight":this._GetWindowInnerHeight()})}_OnFullscreenError(e){console.warn("[Construct] Fullscreen request failed: ",e);this.PostToRuntime("fullscreenerror",{"isFullscreen":RuntimeInterface.IsDocumentFullscreen(), "innerWidth":this._GetWindowInnerWidth(),"innerHeight":this._GetWindowInnerHeight()})}_OnVisibilityChange(isHidden){if(this._pageVisibilityIsHidden===isHidden)return;this._pageVisibilityIsHidden=isHidden;if(isHidden)this._iRuntime._CancelAnimationFrame();else this._iRuntime._RequestAnimationFrame();this.PostToRuntime("visibilitychange",{"hidden":isHidden});if(!isHidden&&this._iRuntime.IsiOSWebView()){const resetScrollFunc=()=>{document.scrollingElement.scrollTop=0;document.scrollingElement.scrollLeft= 0};setTimeout(resetScrollFunc,50);setTimeout(resetScrollFunc,100);setTimeout(resetScrollFunc,250);setTimeout(resetScrollFunc,500)}}_OnKeyEvent(name,e){if(e.key==="Backspace")PreventDefaultOnCanvasOrDoc(e);if(this._iRuntime.GetExportType()==="nwjs"&&e.key==="u"&&(e.ctrlKey||e.metaKey))e.preventDefault();if(this._isExportToVideo)return;const code=KEY_CODE_ALIASES.get(e.code)||e.code;this._PostToRuntimeMaybeSync(name,{"code":code,"key":e.key,"which":e.which,"repeat":e.repeat,"altKey":e.altKey,"ctrlKey":e.ctrlKey, "metaKey":e.metaKey,"shiftKey":e.shiftKey,"timeStamp":e.timeStamp},DISPATCH_RUNTIME_AND_SCRIPT)}_OnMouseWheelEvent(name,e,opts){if(this._isExportToVideo)return;this.PostToRuntime(name,{"clientX":e.clientX,"clientY":e.clientY+this._vkTranslateYOffset,"pageX":e.pageX,"pageY":e.pageY+this._vkTranslateYOffset,"deltaX":e.deltaX,"deltaY":e.deltaY,"deltaZ":e.deltaZ,"deltaMode":e.deltaMode,"timeStamp":e.timeStamp},opts)}_OnMouseEvent(name,e,opts){if(this._isExportToVideo)return;if(IsCompatibilityMouseEvent(e))return; this._PostToRuntimeMaybeSync(name,{"button":e.button,"buttons":e.buttons,"clientX":e.clientX,"clientY":e.clientY+this._vkTranslateYOffset,"pageX":e.pageX,"pageY":e.pageY+this._vkTranslateYOffset,"movementX":e.movementX||0,"movementY":e.movementY||0,"timeStamp":e.timeStamp},opts)}_OnPointerEvent(name,e){if(this._isExportToVideo)return;let lastButtons=0;if(e.pointerType==="mouse")lastButtons=this._mousePointerLastButtons;this._PostToRuntimeMaybeSync(name,{"pointerId":e.pointerId,"pointerType":e.pointerType, "button":e.button,"buttons":e.buttons,"lastButtons":lastButtons,"clientX":e.clientX,"clientY":e.clientY+this._vkTranslateYOffset,"pageX":e.pageX,"pageY":e.pageY+this._vkTranslateYOffset,"movementX":e.movementX||0,"movementY":e.movementY||0,"width":e.width||0,"height":e.height||0,"pressure":e.pressure||0,"tangentialPressure":e["tangentialPressure"]||0,"tiltX":e.tiltX||0,"tiltY":e.tiltY||0,"twist":e["twist"]||0,"timeStamp":e.timeStamp},DISPATCH_RUNTIME_AND_SCRIPT);if(e.pointerType==="mouse")this._mousePointerLastButtons= e.buttons}_OnPointerRawUpdate(e){this._OnPointerEvent("pointermove",e)}_OnTouchEvent(fireName,e){if(this._isExportToVideo)return;for(let i=0,len=e.changedTouches.length;i<len;++i){const t=e.changedTouches[i];this._PostToRuntimeMaybeSync(fireName,{"pointerId":t.identifier,"pointerType":"touch","button":0,"buttons":0,"lastButtons":0,"clientX":t.clientX,"clientY":t.clientY+this._vkTranslateYOffset,"pageX":t.pageX,"pageY":t.pageY+this._vkTranslateYOffset,"movementX":e.movementX||0,"movementY":e.movementY|| 0,"width":(t["radiusX"]||t["webkitRadiusX"]||0)*2,"height":(t["radiusY"]||t["webkitRadiusY"]||0)*2,"pressure":t["force"]||t["webkitForce"]||0,"tangentialPressure":0,"tiltX":0,"tiltY":0,"twist":t["rotationAngle"]||0,"timeStamp":e.timeStamp},DISPATCH_RUNTIME_AND_SCRIPT)}}_HandlePointerDownFocus(e){if(window!==window.top)window.focus();if(this._IsElementCanvasOrDocument(e.target)&&document.activeElement&&!this._IsElementCanvasOrDocument(document.activeElement))document.activeElement.blur()}_IsElementCanvasOrDocument(elem){return!elem|| elem===document||elem===window||elem===document.body||elem.tagName.toLowerCase()==="canvas"}_AttachDeviceOrientationEvent(){if(this._attachedDeviceOrientationEvent)return;this._attachedDeviceOrientationEvent=true;window.addEventListener("deviceorientation",e=>this._OnDeviceOrientation(e));window.addEventListener("deviceorientationabsolute",e=>this._OnDeviceOrientationAbsolute(e))}_AttachDeviceMotionEvent(){if(this._attachedDeviceMotionEvent)return;this._attachedDeviceMotionEvent=true;window.addEventListener("devicemotion", e=>this._OnDeviceMotion(e))}_OnDeviceOrientation(e){if(this._isExportToVideo)return;this.PostToRuntime("deviceorientation",{"absolute":!!e["absolute"],"alpha":e["alpha"]||0,"beta":e["beta"]||0,"gamma":e["gamma"]||0,"timeStamp":e.timeStamp,"webkitCompassHeading":e["webkitCompassHeading"],"webkitCompassAccuracy":e["webkitCompassAccuracy"]},DISPATCH_RUNTIME_AND_SCRIPT)}_OnDeviceOrientationAbsolute(e){if(this._isExportToVideo)return;this.PostToRuntime("deviceorientationabsolute",{"absolute":!!e["absolute"], "alpha":e["alpha"]||0,"beta":e["beta"]||0,"gamma":e["gamma"]||0,"timeStamp":e.timeStamp},DISPATCH_RUNTIME_AND_SCRIPT)}_OnDeviceMotion(e){if(this._isExportToVideo)return;let accProp=null;const acc=e["acceleration"];if(acc)accProp={"x":acc["x"]||0,"y":acc["y"]||0,"z":acc["z"]||0};let withGProp=null;const withG=e["accelerationIncludingGravity"];if(withG)withGProp={"x":withG["x"]||0,"y":withG["y"]||0,"z":withG["z"]||0};let rotationRateProp=null;const rotationRate=e["rotationRate"];if(rotationRate)rotationRateProp= {"alpha":rotationRate["alpha"]||0,"beta":rotationRate["beta"]||0,"gamma":rotationRate["gamma"]||0};this.PostToRuntime("devicemotion",{"acceleration":accProp,"accelerationIncludingGravity":withGProp,"rotationRate":rotationRateProp,"interval":e["interval"],"timeStamp":e.timeStamp},DISPATCH_RUNTIME_AND_SCRIPT)}_OnInvokeDownload(e){const url=e["url"];const filename=e["filename"];const a=document.createElement("a");const body=document.body;a.textContent=filename;a.href=url;a.download=filename;body.appendChild(a); a.click();body.removeChild(a)}async _OnLoadWebFonts(e){const webfonts=e["webfonts"];await Promise.all(webfonts.map(async info=>{const fontFace=new FontFace(info.name,`url('${info.url}')`);document.fonts.add(fontFace);await fontFace.load()}))}async _OnRasterSvgImage(e){const blob=e["blob"];const imageWidth=e["imageWidth"];const imageHeight=e["imageHeight"];const surfaceWidth=e["surfaceWidth"];const surfaceHeight=e["surfaceHeight"];const imageBitmapOpts=e["imageBitmapOpts"];const canvas=await self["C3_RasterSvgImageBlob"](blob, imageWidth,imageHeight,surfaceWidth,surfaceHeight);let ret;if(imageBitmapOpts)ret=await createImageBitmap(canvas,imageBitmapOpts);else ret=await createImageBitmap(canvas);return{"imageBitmap":ret,"transferables":[ret]}}async _OnGetSvgImageSize(e){return await self["C3_GetSvgImageSize"](e["blob"])}async _OnAddStylesheet(e){await AddStyleSheet(e["url"])}_PlayPendingMedia(){const mediaToTryPlay=[...this._mediaPendingPlay];this._mediaPendingPlay.clear();if(!this._isSilent)for(const mediaElem of mediaToTryPlay){const playRet= mediaElem.play();if(playRet)playRet.catch(err=>{if(!this._mediaRemovedPendingPlay.has(mediaElem))this._mediaPendingPlay.add(mediaElem)})}}TryPlayMedia(mediaElem){if(typeof mediaElem.play!=="function")throw new Error("missing play function");this._mediaRemovedPendingPlay.delete(mediaElem);let playRet;try{playRet=mediaElem.play()}catch(err){this._mediaPendingPlay.add(mediaElem);return}if(playRet)playRet.catch(err=>{if(!this._mediaRemovedPendingPlay.has(mediaElem))this._mediaPendingPlay.add(mediaElem)})}RemovePendingPlay(mediaElem){this._mediaPendingPlay.delete(mediaElem); this._mediaRemovedPendingPlay.add(mediaElem)}SetSilent(s){this._isSilent=!!s}_OnHideCordovaSplash(){if(navigator["splashscreen"]&&navigator["splashscreen"]["hide"])navigator["splashscreen"]["hide"]()}_OnDebugHighlight(e){const show=e["show"];if(!show){if(this._debugHighlightElem)this._debugHighlightElem.style.display="none";return}if(!this._debugHighlightElem){this._debugHighlightElem=document.createElement("div");this._debugHighlightElem.id="inspectOutline";document.body.appendChild(this._debugHighlightElem)}const elem= this._debugHighlightElem;elem.style.display="";elem.style.left=e["left"]-1+"px";elem.style.top=e["top"]-1+"px";elem.style.width=e["width"]+2+"px";elem.style.height=e["height"]+2+"px";elem.textContent=e["name"]}_OnRegisterSW(){if(window["C3_RegisterSW"])window["C3_RegisterSW"]()}_OnPostToDebugger(data){if(!window["c3_postToMessagePort"])return;data["from"]="runtime";window["c3_postToMessagePort"](data)}_InvokeFunctionFromJS(name,params){return this.PostToRuntimeAsync("js-invoke-function",{"name":name, "params":params})}_OnScriptCreateWorker(e){const url=e["url"];const opts=e["opts"];const port2=e["port2"];const worker=new Worker(url,opts);worker.postMessage({"type":"construct-worker-init","port2":port2},[port2])}_OnAlert(e){alert(e["message"])}_OnScreenReaderTextEvent(e){const type=e["type"];if(type==="create"){const p=document.createElement("p");p.id="c3-sr-"+e["id"];p.textContent=e["text"];this._screenReaderTextWrap.appendChild(p)}else if(type==="update"){const p=document.getElementById("c3-sr-"+ e["id"]);if(p)p.textContent=e["text"];else console.warn(`[Construct] Missing screen reader text with id ${e["id"]}`)}else if(type==="release"){const p=document.getElementById("c3-sr-"+e["id"]);if(p)p.remove();else console.warn(`[Construct] Missing screen reader text with id ${e["id"]}`)}else console.warn(`[Construct] Unknown screen reader text update '${type}'`)}_SetExportingToVideo(e){this._isExportToVideo=true;const headerElem=document.createElement("h1");headerElem.id="exportToVideoMessage";headerElem.textContent= e["message"];document.body.prepend(headerElem);document.body.classList.add("exportingToVideo");this.GetRuntimeInterface().GetMainCanvas().style.display="";this._iRuntime.SetIsExportingToVideo(e["duration"])}_OnExportVideoProgress(e){this._exportVideoProgressMessage=e["message"];if(this._exportVideoUpdateTimerId===-1)this._exportVideoUpdateTimerId=setTimeout(()=>this._DoUpdateExportVideoProgressMessage(),250)}_DoUpdateExportVideoProgressMessage(){this._exportVideoUpdateTimerId=-1;const headerElem= document.getElementById("exportToVideoMessage");if(headerElem)headerElem.textContent=this._exportVideoProgressMessage}_OnExportedToVideo(e){window.c3_postToMessagePort({"type":"exported-video","arrayBuffer":e["arrayBuffer"],"contentType":e["contentType"],"time":e["time"]})}_OnExportedToImageSequence(e){window.c3_postToMessagePort({"type":"exported-image-sequence","blobArr":e["blobArr"],"time":e["time"],"gif":e["gif"]})}};RuntimeInterface.AddDOMHandlerClass(HANDLER_CLASS)}; 'use strict';{const DISPATCH_WORKER_SCRIPT_NAME="dispatchworker.js";const JOB_WORKER_SCRIPT_NAME="jobworker.js";self.JobSchedulerDOM=class JobSchedulerDOM{constructor(runtimeInterface){this._runtimeInterface=runtimeInterface;this._baseUrl=runtimeInterface.GetRuntimeBaseURL();if(runtimeInterface.GetExportType()==="preview")this._baseUrl+="workers/";else this._baseUrl+=runtimeInterface.GetScriptFolder();this._maxNumWorkers=Math.min(navigator.hardwareConcurrency||2,16);this._dispatchWorker=null;this._jobWorkers= [];this._inputPort=null;this._outputPort=null}_GetWorkerScriptFolder(){if(this._runtimeInterface.GetExportType()==="playable-ad")return this._runtimeInterface.GetScriptFolder();else return""}async Init(){if(this._hasInitialised)throw new Error("already initialised");this._hasInitialised=true;const dispatchWorkerScriptUrl=this._runtimeInterface._GetWorkerURL(this._GetWorkerScriptFolder()+DISPATCH_WORKER_SCRIPT_NAME);this._dispatchWorker=await this._runtimeInterface.CreateWorker(dispatchWorkerScriptUrl, this._baseUrl,{name:"DispatchWorker"});const messageChannel=new MessageChannel;this._inputPort=messageChannel.port1;this._dispatchWorker.postMessage({"type":"_init","in-port":messageChannel.port2},[messageChannel.port2]);this._outputPort=await this._CreateJobWorker()}async _CreateJobWorker(){const number=this._jobWorkers.length;const jobWorkerScriptUrl=this._runtimeInterface._GetWorkerURL(this._GetWorkerScriptFolder()+JOB_WORKER_SCRIPT_NAME);const jobWorker=await this._runtimeInterface.CreateWorker(jobWorkerScriptUrl, this._baseUrl,{name:"JobWorker"+number});const dispatchChannel=new MessageChannel;const outputChannel=new MessageChannel;this._dispatchWorker.postMessage({"type":"_addJobWorker","port":dispatchChannel.port1},[dispatchChannel.port1]);jobWorker.postMessage({"type":"init","number":number,"dispatch-port":dispatchChannel.port2,"output-port":outputChannel.port2},[dispatchChannel.port2,outputChannel.port2]);this._jobWorkers.push(jobWorker);return outputChannel.port1}GetPortData(){return{"inputPort":this._inputPort, "outputPort":this._outputPort,"maxNumWorkers":this._maxNumWorkers}}GetPortTransferables(){return[this._inputPort,this._outputPort]}}}; 'use strict';{if(window["C3_Is_Supported"]){const enableWorker=false;window["c3_runtimeInterface"]=new self.RuntimeInterface({useWorker:enableWorker,workerMainUrl:"workermain.js",engineScripts:["scripts/c3runtime.js"],projectScripts:[],mainProjectScript:"",scriptFolder:"scripts/",workerDependencyScripts:[],exportType:"html5"})}}; 'use strict';{const DOM_COMPONENT_ID="mouse";const HANDLER_CLASS=class MouseDOMHandler extends self.DOMHandler{constructor(iRuntime){super(iRuntime,DOM_COMPONENT_ID);this.AddRuntimeMessageHandlers([["cursor",e=>this._OnChangeCursorStyle(e)],["request-pointer-lock",()=>this._OnRequestPointerLock()],["release-pointer-lock",()=>this._OnReleasePointerLock()]]);document.addEventListener("pointerlockchange",e=>this._OnPointerLockChange());document.addEventListener("pointerlockerror",e=>this._OnPointerLockError())}_OnChangeCursorStyle(e){document.documentElement.style.cursor= e}_OnRequestPointerLock(){this._iRuntime.GetMainCanvas().requestPointerLock()}_OnReleasePointerLock(){document.exitPointerLock()}_OnPointerLockChange(){this.PostToRuntime("pointer-lock-change",{"has-pointer-lock":!!document.pointerLockElement})}_OnPointerLockError(){this.PostToRuntime("pointer-lock-error",{"has-pointer-lock":!!document.pointerLockElement})}};self.RuntimeInterface.AddDOMHandlerClass(HANDLER_CLASS)}; 'use strict';{const R_TO_D=180/Math.PI;const DOM_COMPONENT_ID="audio";self.AudioDOMHandler=class AudioDOMHandler extends self.DOMHandler{constructor(iRuntime){super(iRuntime,DOM_COMPONENT_ID);this._audioContext=null;this._destinationNode=null;this._hasUnblocked=false;this._hasAttachedUnblockEvents=false;this._unblockFunc=()=>this._UnblockAudioContext();this._audioBuffers=[];this._audioInstances=[];this._lastAudioInstance=null;this._lastPlayedTags=[];this._loadedAudioUrls=new Set;this._lastTickCount= -1;this._pendingTags=new Map;this._masterVolume=1;this._isSilent=false;this._timeScaleMode=0;this._timeScale=1;this._gameTime=0;this._panningModel="HRTF";this._distanceModel="inverse";this._refDistance=600;this._maxDistance=1E4;this._rolloffFactor=1;this._lastListenerPos=[0,0,0];this._lastListenerOrientation=[0,0,-1,0,1,0];this._playMusicAsSound=false;this._hasAnySoftwareDecodedMusic=false;this._supportsWebMOpus=this._iRuntime.IsAudioFormatSupported("audio/webm; codecs=opus");this._effects=new Map; this._analysers=new Set;this._isPendingPostFxState=false;this._hasStartedOfflineRender=false;this._microphoneTag="";this._microphoneSource=null;self["C3Audio_OnMicrophoneStream"]=(localMediaStream,tag)=>this._OnMicrophoneStream(localMediaStream,tag);this._destMediaStreamNode=null;self["C3Audio_GetOutputStream"]=()=>this._OnGetOutputStream();self["C3Audio_DOMInterface"]=this;this.AddRuntimeMessageHandlers([["create-audio-context",e=>this._CreateAudioContext(e)],["play",e=>this._Play(e)],["stop",e=> this._Stop(e)],["stop-all",()=>this._StopAll()],["set-paused",e=>this._SetPaused(e)],["set-volume",e=>this._SetVolume(e)],["fade-volume",e=>this._FadeVolume(e)],["set-master-volume",e=>this._SetMasterVolume(e)],["set-muted",e=>this._SetMuted(e)],["set-silent",e=>this._SetSilent(e)],["set-looping",e=>this._SetLooping(e)],["set-playback-rate",e=>this._SetPlaybackRate(e)],["set-stereo-pan",e=>this._SetStereoPan(e)],["seek",e=>this._Seek(e)],["preload",e=>this._Preload(e)],["unload",e=>this._Unload(e)], ["unload-all",()=>this._UnloadAll()],["set-suspended",e=>this._SetSuspended(e)],["add-effect",e=>this._AddEffect(e)],["set-effect-param",e=>this._SetEffectParam(e)],["remove-effects",e=>this._RemoveEffects(e)],["tick",e=>this._OnTick(e)],["load-state",e=>this._OnLoadState(e)],["offline-render-audio",e=>this._OnOfflineRenderAudio(e)],["offline-render-finish",()=>this._OnOfflineRenderFinish()]])}async _CreateAudioContext(e){if(e["isiOSCordova"]||e["isSafari"])this._playMusicAsSound=true;this._timeScaleMode= e["timeScaleMode"];this._panningModel=["equalpower","HRTF","soundfield"][e["panningModel"]];this._distanceModel=["linear","inverse","exponential"][e["distanceModel"]];this._refDistance=e["refDistance"];this._maxDistance=e["maxDistance"];this._rolloffFactor=e["rolloffFactor"];if(this._iRuntime.IsExportingToVideo()){this._playMusicAsSound=true;const sampleRate=48E3;this._audioContext=new OfflineAudioContext({"numberOfChannels":2,"sampleRate":sampleRate,"length":Math.ceil(this._iRuntime.GetExportToVideoDuration()* sampleRate)})}else{const opts={"latencyHint":e["latencyHint"]};if(!this.SupportsWebMOpus())opts["sampleRate"]=48E3;if(typeof AudioContext!=="undefined")this._audioContext=new AudioContext(opts);else if(typeof webkitAudioContext!=="undefined")this._audioContext=new webkitAudioContext(opts);else throw new Error("Web Audio API not supported");this._AttachUnblockEvents();this._audioContext.onstatechange=()=>{if(this._audioContext.state!=="running")this._AttachUnblockEvents();this.PostToRuntime("audiocontext-state", {"audioContextState":this._audioContext.state})}}this._destinationNode=this._audioContext["createGain"]();this._destinationNode["connect"](this._audioContext["destination"]);const listenerPos=e["listenerPos"];this._lastListenerPos[0]=listenerPos[0];this._lastListenerPos[1]=listenerPos[1];this._lastListenerPos[2]=listenerPos[2];this._audioContext["listener"]["setPosition"](listenerPos[0],listenerPos[1],listenerPos[2]);this._audioContext["listener"]["setOrientation"](...this._lastListenerOrientation); self["C3_GetAudioContextCurrentTime"]=()=>this.GetAudioCurrentTime();try{await Promise.all(e["preloadList"].map(o=>this._GetAudioBuffer(o["originalUrl"],o["url"],o["type"],false)))}catch(err){console.error("[Construct] Preloading sounds failed: ",err)}return{"sampleRate":this._audioContext["sampleRate"],"audioContextState":this._audioContext.state,"outputLatency":this._audioContext["outputLatency"]||0}}_AttachUnblockEvents(){if(this._hasAttachedUnblockEvents)return;this._hasUnblocked=false;window.addEventListener("pointerup", this._unblockFunc,true);window.addEventListener("touchend",this._unblockFunc,true);window.addEventListener("click",this._unblockFunc,true);window.addEventListener("keydown",this._unblockFunc,true);this._hasAttachedUnblockEvents=true}_DetachUnblockEvents(){if(!this._hasAttachedUnblockEvents)return;this._hasUnblocked=true;window.removeEventListener("pointerup",this._unblockFunc,true);window.removeEventListener("touchend",this._unblockFunc,true);window.removeEventListener("click",this._unblockFunc,true); window.removeEventListener("keydown",this._unblockFunc,true);this._hasAttachedUnblockEvents=false}_UnblockAudioContext(){if(this._hasUnblocked)return;const audioContext=this._audioContext;if(audioContext["state"]==="suspended"&&audioContext["resume"])audioContext["resume"]();const buffer=audioContext["createBuffer"](1,220,22050);const source=audioContext["createBufferSource"]();source["buffer"]=buffer;source["connect"](audioContext["destination"]);source["start"](0);if(audioContext["state"]==="running")this._DetachUnblockEvents()}_MatchTagLists(tagArr1, tagArr2){for(const t2 of tagArr2){let found=false;for(const t1 of tagArr1)if(self.AudioDOMHandler.EqualsNoCase(t1,t2)){found=true;break}if(!found)return false}return true}GetAudioContext(){return this._audioContext}GetAudioCurrentTime(){return this._audioContext["currentTime"]}GetDestinationNode(){return this._destinationNode}["GetAudioContextExtern"](){return this.GetAudioContext()}["GetDestinationNodeExtern"](){return this.GetDestinationNode()}GetDestinationForTag(tag){const fxChain=this._effects.get(tag.toLowerCase()); if(fxChain)return fxChain[0].GetInputNode();else return this.GetDestinationNode()}AddEffectForTag(tag,effect){tag=tag.toLowerCase();let fxChain=this._effects.get(tag);if(!fxChain){fxChain=[];this._effects.set(tag,fxChain)}effect._SetIndex(fxChain.length);effect._SetTag(tag);fxChain.push(effect);this._ReconnectEffects(tag)}_ReconnectEffects(tag){tag=tag.toLowerCase();let destNode=this.GetDestinationNode();const fxChain=this._effects.get(tag);if(fxChain&&fxChain.length){destNode=fxChain[0].GetInputNode(); for(let i=0,len=fxChain.length;i<len;++i){const n=fxChain[i];if(i+1===len)n.ConnectTo(this.GetDestinationNode());else n.ConnectTo(fxChain[i+1].GetInputNode())}}for(const ai of this.audioInstancesByEffectTag(tag))ai.Reconnect(destNode);if(this._microphoneSource&&this._microphoneTag===tag){this._microphoneSource["disconnect"]();this._microphoneSource["connect"](destNode)}}GetMasterVolume(){return this._masterVolume}IsSilent(){return this._isSilent}GetTimeScaleMode(){return this._timeScaleMode}GetTimeScale(){return this._timeScale}GetGameTime(){return this._gameTime}IsPlayMusicAsSound(){return this._playMusicAsSound}SupportsWebMOpus(){return this._supportsWebMOpus}_SetHasAnySoftwareDecodedMusic(){this._hasAnySoftwareDecodedMusic= true}GetPanningModel(){return this._panningModel}GetDistanceModel(){return this._distanceModel}GetReferenceDistance(){return this._refDistance}GetMaxDistance(){return this._maxDistance}GetRolloffFactor(){return this._rolloffFactor}DecodeAudioData(audioData,needsSoftwareDecode){if(needsSoftwareDecode)return this._iRuntime._WasmDecodeWebMOpus(audioData).then(rawAudio=>{const audioBuffer=this._audioContext["createBuffer"](1,rawAudio.length,48E3);const channelBuffer=audioBuffer["getChannelData"](0);channelBuffer.set(rawAudio); return audioBuffer});else return new Promise((resolve,reject)=>{this._audioContext["decodeAudioData"](audioData,resolve,reject)})}TryPlayMedia(mediaElem){this._iRuntime.TryPlayMedia(mediaElem)}RemovePendingPlay(mediaElem){this._iRuntime.RemovePendingPlay(mediaElem)}ReleaseInstancesForBuffer(buffer){let j=0;for(let i=0,len=this._audioInstances.length;i<len;++i){const a=this._audioInstances[i];this._audioInstances[j]=a;if(a.GetBuffer()===buffer)a.Release();else++j}this._audioInstances.length=j}ReleaseAllMusicBuffers(){let j= 0;for(let i=0,len=this._audioBuffers.length;i<len;++i){const b=this._audioBuffers[i];this._audioBuffers[j]=b;if(b.IsMusic())b.Release();else++j}this._audioBuffers.length=j}*audioInstancesMatchingTags(tags){if(tags.length>0)for(const ai of this._audioInstances){if(this._MatchTagLists(ai.GetTags(),tags))yield ai}else if(this._lastAudioInstance&&!this._lastAudioInstance.HasEnded())yield this._lastAudioInstance}*audioInstancesByEffectTag(tag){if(tag)for(const ai of this._audioInstances){if(self.AudioDOMHandler.EqualsNoCase(ai.GetEffectTag(), tag))yield ai}else if(this._lastAudioInstance&&!this._lastAudioInstance.HasEnded())yield this._lastAudioInstance}async _GetAudioBuffer(originalUrl,url,type,isMusic,dontCreate){for(const ab of this._audioBuffers)if(ab.GetUrl()===url){await ab.Load();return ab}if(dontCreate)return null;if(isMusic&&(this._playMusicAsSound||this._hasAnySoftwareDecodedMusic))this.ReleaseAllMusicBuffers();const ret=self.C3AudioBuffer.Create(this,originalUrl,url,type,isMusic);this._audioBuffers.push(ret);await ret.Load(); if(!this._loadedAudioUrls.has(originalUrl)){this.PostToRuntime("buffer-metadata",{"originalUrl":originalUrl,"duration":ret.GetDuration()});this._loadedAudioUrls.add(originalUrl)}return ret}async _GetAudioInstance(originalUrl,url,type,tags,isMusic){for(const ai of this._audioInstances)if(ai.GetUrl()===url&&(ai.CanBeRecycled()||isMusic)){ai.SetTags(tags);return ai}const buffer=await this._GetAudioBuffer(originalUrl,url,type,isMusic);const ret=buffer.CreateInstance(tags);this._audioInstances.push(ret); return ret}_AddPendingTags(tags){const tagStr=tags.join(" ");let info=this._pendingTags.get(tagStr);if(!info){let resolve=null;const promise=new Promise(r=>resolve=r);info={pendingCount:0,promise,resolve};this._pendingTags.set(tagStr,info)}info.pendingCount++}_RemovePendingTags(tags){const tagStr=tags.join(" ");const info=this._pendingTags.get(tagStr);if(!info)throw new Error("expected pending tag");info.pendingCount--;if(info.pendingCount===0){info.resolve();this._pendingTags.delete(tagStr)}}TagsReady(tags){const tagStr= (tags.length===0?this._lastPlayedTags:tags).join(" ");const info=this._pendingTags.get(tagStr);if(info)return info.promise;else return Promise.resolve()}_MaybeStartTicking(){if(this._analysers.size>0){this._StartTicking();return}for(const ai of this._audioInstances)if(ai.IsActive()){this._StartTicking();return}}Tick(){for(const a of this._analysers)a.Tick();const currentTime=this.GetAudioCurrentTime();for(const ai of this._audioInstances)ai.Tick(currentTime);const instStates=this._audioInstances.filter(a=> a.IsActive()).map(a=>a.GetState());this.PostToRuntime("state",{"tickCount":this._lastTickCount,"outputLatency":this._audioContext["outputLatency"]||0,"audioInstances":instStates,"analysers":[...this._analysers].map(a=>a.GetData())});if(instStates.length===0&&this._analysers.size===0)this._StopTicking()}PostTrigger(type,tags,aiid){this.PostToRuntime("trigger",{"type":type,"tags":tags,"aiid":aiid})}async _Play(e){const originalUrl=e["originalUrl"];const url=e["url"];const type=e["type"];const isMusic= e["isMusic"];const tags=e["tags"];const isLooping=e["isLooping"];const volume=e["vol"];const position=e["pos"];const panning=e["panning"];const stereoPan=e["stereoPan"];let startTime=e["off"];if(startTime>0&&!e["trueClock"])if(this._audioContext["getOutputTimestamp"]){const outputTimestamp=this._audioContext["getOutputTimestamp"]();startTime=startTime-outputTimestamp["performanceTime"]/1E3+outputTimestamp["contextTime"]}else startTime=startTime-performance.now()/1E3+this._audioContext["currentTime"]; this._lastPlayedTags=tags.slice(0);this._AddPendingTags(tags);try{this._lastAudioInstance=await this._GetAudioInstance(originalUrl,url,type,tags,isMusic);if(panning){this._lastAudioInstance.SetPannerEnabled(true);this._lastAudioInstance.SetPan(panning["x"],panning["y"],panning["z"],panning["angle"],panning["innerAngle"],panning["outerAngle"],panning["outerGain"]);if(panning.hasOwnProperty("uid"))this._lastAudioInstance.SetUID(panning["uid"])}else if(typeof stereoPan==="number"&&stereoPan!==0){this._lastAudioInstance.SetStereoPannerEnabled(true); this._lastAudioInstance.SetStereoPan(stereoPan)}else{this._lastAudioInstance.SetPannerEnabled(false);this._lastAudioInstance.SetStereoPannerEnabled(false)}this._lastAudioInstance.Play(isLooping,volume,position,startTime)}catch(err){console.error("[Construct] Audio: error starting playback: ",err);return}finally{this._RemovePendingTags(tags)}this._StartTicking()}_Stop(e){const tags=e["tags"];for(const ai of this.audioInstancesMatchingTags(tags))ai.Stop()}_StopAll(){for(const ai of this._audioInstances)ai.Stop()}_SetPaused(e){const tags= e["tags"];const paused=e["paused"];for(const ai of this.audioInstancesMatchingTags(tags))if(paused)ai.Pause();else ai.Resume();this._MaybeStartTicking()}_SetVolume(e){const tags=e["tags"];const vol=e["vol"];for(const ai of this.audioInstancesMatchingTags(tags))ai.SetVolume(vol)}_SetStereoPan(e){const tags=e["tags"];const p=e["p"];for(const ai of this.audioInstancesMatchingTags(tags)){ai.SetStereoPannerEnabled(true);ai.SetStereoPan(p)}}async _FadeVolume(e){const tags=e["tags"];const vol=e["vol"];const duration= e["duration"];const stopOnEnd=e["stopOnEnd"];await this.TagsReady(tags);for(const ai of this.audioInstancesMatchingTags(tags))ai.FadeVolume(vol,duration,stopOnEnd);this._MaybeStartTicking()}_SetMasterVolume(e){this._masterVolume=e["vol"];this._destinationNode["gain"]["value"]=this._masterVolume}_SetMuted(e){const tags=e["tags"];const isMuted=e["isMuted"];for(const ai of this.audioInstancesMatchingTags(tags))ai.SetMuted(isMuted)}_SetSilent(e){this._isSilent=e["isSilent"];this._iRuntime.SetSilent(this._isSilent); for(const ai of this._audioInstances)ai._UpdateMuted()}_SetLooping(e){const tags=e["tags"];const isLooping=e["isLooping"];for(const ai of this.audioInstancesMatchingTags(tags))ai.SetLooping(isLooping)}async _SetPlaybackRate(e){const tags=e["tags"];const rate=e["rate"];await this.TagsReady(tags);for(const ai of this.audioInstancesMatchingTags(tags))ai.SetPlaybackRate(rate)}async _Seek(e){const tags=e["tags"];const pos=e["pos"];await this.TagsReady(tags);for(const ai of this.audioInstancesMatchingTags(tags))ai.Seek(pos)}async _Preload(e){const originalUrl= e["originalUrl"];const url=e["url"];const type=e["type"];const isMusic=e["isMusic"];try{await this._GetAudioInstance(originalUrl,url,type,"",isMusic)}catch(err){console.error("[Construct] Audio: error preloading: ",err)}}async _Unload(e){const url=e["url"];const type=e["type"];const isMusic=e["isMusic"];const buffer=await this._GetAudioBuffer("",url,type,isMusic,true);if(!buffer)return;buffer.Release();const i=this._audioBuffers.indexOf(buffer);if(i!==-1)this._audioBuffers.splice(i,1)}_UnloadAll(){for(const buffer of this._audioBuffers)buffer.Release(); this._audioBuffers.length=0}_SetSuspended(e){const isSuspended=e["isSuspended"];if(!isSuspended&&this._audioContext["resume"])this._audioContext["resume"]();for(const ai of this._audioInstances)ai.SetSuspended(isSuspended);if(isSuspended&&this._audioContext["suspend"])this._audioContext["suspend"]()}_OnTick(e){this._timeScale=e["timeScale"];this._gameTime=e["gameTime"];this._lastTickCount=e["tickCount"];if(this._timeScaleMode!==0)for(const ai of this._audioInstances)ai._UpdatePlaybackRate();const listenerPos= e["listenerPos"];if(listenerPos&&(this._lastListenerPos[0]!==listenerPos[0]||this._lastListenerPos[1]!==listenerPos[1]||this._lastListenerPos[2]!==listenerPos[2])){this._lastListenerPos[0]=listenerPos[0];this._lastListenerPos[1]=listenerPos[1];this._lastListenerPos[2]=listenerPos[2];this._audioContext["listener"]["setPosition"](listenerPos[0],listenerPos[1],listenerPos[2])}const listenerOrientation=e["listenerOrientation"];if(listenerOrientation&&(this._lastListenerOrientation[0]!==listenerOrientation[0]|| this._lastListenerOrientation[1]!==listenerOrientation[1]||this._lastListenerOrientation[2]!==listenerOrientation[2]||this._lastListenerOrientation[3]!==listenerOrientation[3]||this._lastListenerOrientation[4]!==listenerOrientation[4]||this._lastListenerOrientation[5]!==listenerOrientation[5])){for(let i=0;i<6;++i)this._lastListenerOrientation[i]=listenerOrientation[i];this._audioContext["listener"]["setOrientation"](...this._lastListenerOrientation)}for(const instPan of e["instPans"]){const uid= instPan["uid"];for(const ai of this._audioInstances)if(ai.GetUID()===uid)ai.SetPanXYZA(instPan["x"],instPan["y"],instPan["z"],instPan["angle"])}}async _AddEffect(e){const type=e["type"];const tags=e.hasOwnProperty("tags")?e["tags"]:[e["tag"]];const params=e["params"];let effect;let convolutionBuffer;if(type==="convolution")try{convolutionBuffer=await this._GetAudioBuffer(e["bufferOriginalUrl"],e["bufferUrl"],e["bufferType"],false)}catch(err){console.log("[Construct] Audio: error loading convolution: ", err);return}for(const tag of tags){if(type==="filter")effect=new self.C3AudioFilterFX(this,...params);else if(type==="delay")effect=new self.C3AudioDelayFX(this,...params);else if(type==="convolution"){effect=new self.C3AudioConvolveFX(this,convolutionBuffer.GetAudioBuffer(),...params);effect._SetBufferInfo(e["bufferOriginalUrl"],e["bufferUrl"],e["bufferType"])}else if(type==="flanger")effect=new self.C3AudioFlangerFX(this,...params);else if(type==="phaser")effect=new self.C3AudioPhaserFX(this,...params); else if(type==="gain")effect=new self.C3AudioGainFX(this,...params);else if(type==="stereopan")effect=new self.C3AudioStereoPanFX(this,...params);else if(type==="tremolo")effect=new self.C3AudioTremoloFX(this,...params);else if(type==="ringmod")effect=new self.C3AudioRingModFX(this,...params);else if(type==="distortion")effect=new self.C3AudioDistortionFX(this,...params);else if(type==="compressor")effect=new self.C3AudioCompressorFX(this,...params);else if(type==="analyser")effect=new self.C3AudioAnalyserFX(this, ...params);else throw new Error("invalid effect type");this.AddEffectForTag(tag,effect)}this._PostUpdatedFxState()}_SetEffectParam(e){const tags=e["tags"];const index=e["index"];const param=e["param"];const value=e["value"];const ramp=e["ramp"];const time=e["time"];for(const tag of tags){const fxChain=this._effects.get(tag.toLowerCase());if(!fxChain||index<0||index>=fxChain.length)continue;fxChain[index].SetParam(param,value,ramp,time)}this._PostUpdatedFxState()}_RemoveEffects(e){const tags=e["tags"]; for(const tag of tags){const lowerTag=tag.toLowerCase();const fxChain=this._effects.get(lowerTag);if(!fxChain||!fxChain.length)return;for(const effect of fxChain)effect.Release();this._effects.delete(lowerTag);this._ReconnectEffects(lowerTag)}}_AddAnalyser(analyser){this._analysers.add(analyser);this._MaybeStartTicking()}_RemoveAnalyser(analyser){this._analysers.delete(analyser)}_PostUpdatedFxState(){if(this._isPendingPostFxState)return;this._isPendingPostFxState=true;Promise.resolve().then(()=>this._DoPostUpdatedFxState())}_DoPostUpdatedFxState(){const fxstate= {};for(const [tag,fxChain]of this._effects)fxstate[tag]=fxChain.map(e=>e.GetState());this.PostToRuntime("fxstate",{"fxstate":fxstate});this._isPendingPostFxState=false}async _OnLoadState(e){const saveLoadMode=e["saveLoadMode"];if(saveLoadMode!==3){const keepAudioInstances=[];for(const ai of this._audioInstances)if(ai.IsMusic()&&saveLoadMode===1||!ai.IsMusic()&&saveLoadMode===2)keepAudioInstances.push(ai);else ai.Release();this._audioInstances=keepAudioInstances}for(const fxChain of this._effects.values())for(const effect of fxChain)effect.Release(); this._effects.clear();this._timeScale=e["timeScale"];this._gameTime=e["gameTime"];const listenerPos=e["listenerPos"];this._lastListenerPos[0]=listenerPos[0];this._lastListenerPos[1]=listenerPos[1];this._lastListenerPos[2]=listenerPos[2];this._audioContext["listener"]["setPosition"](listenerPos[0],listenerPos[1],listenerPos[2]);const listenerOrientation=e["listenerOrientation"];if(Array.isArray(listenerOrientation)){for(let i=0;i<6;++i)this._lastListenerOrientation[i]=listenerOrientation[i];this._audioContext["listener"]["setOrientation"](...this._lastListenerOrientation)}this._isSilent= e["isSilent"];this._iRuntime.SetSilent(this._isSilent);this._masterVolume=e["masterVolume"];this._destinationNode["gain"]["value"]=this._masterVolume;const promises=[];for(const fxChainData of Object.values(e["effects"]))promises.push(Promise.all(fxChainData.map(d=>this._AddEffect(d))));await Promise.all(promises);await Promise.all(e["playing"].map(d=>this._LoadAudioInstance(d,saveLoadMode)));this._MaybeStartTicking()}async _LoadAudioInstance(d,saveLoadMode){if(saveLoadMode===3)return;const originalUrl= d["bufferOriginalUrl"];const url=d["bufferUrl"];const type=d["bufferType"];const isMusic=d["isMusic"];const tags=d["tags"];const isLooping=d["isLooping"];const volume=d["volume"];const position=d["playbackTime"];if(isMusic&&saveLoadMode===1)return;if(!isMusic&&saveLoadMode===2)return;let ai=null;try{ai=await this._GetAudioInstance(originalUrl,url,type,tags,isMusic)}catch(err){console.error("[Construct] Audio: error loading audio state: ",err);return}ai.LoadPanState(d["pan"]);ai.LoadStereoPanState(d["stereoPan"]); ai.Play(isLooping,volume,position,0);if(!d["isPlaying"])ai.Pause();ai._LoadAdditionalState(d)}_OnMicrophoneStream(localMediaStream,tag){if(this._microphoneSource)this._microphoneSource["disconnect"]();this._microphoneTag=tag.toLowerCase();this._microphoneSource=this._audioContext["createMediaStreamSource"](localMediaStream);this._microphoneSource["connect"](this.GetDestinationForTag(this._microphoneTag))}_OnGetOutputStream(){if(!this._destMediaStreamNode){this._destMediaStreamNode=this._audioContext["createMediaStreamDestination"](); this._destinationNode["connect"](this._destMediaStreamNode)}return this._destMediaStreamNode["stream"]}async _OnOfflineRenderAudio(e){try{const time=e["time"];const suspendPromise=this._audioContext["suspend"](time);if(!this._hasStartedOfflineRender){this._audioContext["startRendering"]().then(buffer=>this._OnOfflineRenderCompleted(buffer)).catch(err=>this._OnOfflineRenderError(err));this._hasStartedOfflineRender=true}else this._audioContext["resume"]();await suspendPromise}catch(err){this._OnOfflineRenderError(err)}}_OnOfflineRenderFinish(){this._audioContext["resume"]()}_OnOfflineRenderCompleted(buffer){const channelArrayBuffers= [];for(let i=0,len=buffer["numberOfChannels"];i<len;++i){const f32arr=buffer["getChannelData"](i);channelArrayBuffers.push(f32arr.buffer)}this._iRuntime.PostToRuntimeComponent("runtime","offline-audio-render-completed",{"duration":buffer["duration"],"length":buffer["length"],"numberOfChannels":buffer["numberOfChannels"],"sampleRate":buffer["sampleRate"],"channelData":channelArrayBuffers},null,channelArrayBuffers)}_OnOfflineRenderError(err){console.error(`[Audio] Offline rendering error: `,err)}static EqualsNoCase(a, b){return a===b||a.normalize().toLowerCase()===b.normalize().toLowerCase()}static ToDegrees(x){return x*R_TO_D}static DbToLinearNoCap(x){return Math.pow(10,x/20)}static DbToLinear(x){return Math.max(Math.min(self.AudioDOMHandler.DbToLinearNoCap(x),1),0)}static LinearToDbNoCap(x){return Math.log(x)/Math.log(10)*20}static LinearToDb(x){return self.AudioDOMHandler.LinearToDbNoCap(Math.max(Math.min(x,1),0))}static e4(x,k){return 1-Math.exp(-k*x)}};self.RuntimeInterface.AddDOMHandlerClass(self.AudioDOMHandler)}; 'use strict';{self.C3AudioBuffer=class C3AudioBuffer{constructor(audioDomHandler,originalUrl,url,type,isMusic){this._audioDomHandler=audioDomHandler;this._originalUrl=originalUrl;this._url=url;this._type=type;this._isMusic=isMusic;this._api="";this._loadState="not-loaded";this._loadPromise=null}Release(){this._loadState="not-loaded";this._audioDomHandler=null;this._loadPromise=null}static Create(audioDomHandler,originalUrl,url,type,isMusic){const needsSoftwareDecode=type==="audio/webm; codecs=opus"&& !audioDomHandler.SupportsWebMOpus();if(isMusic&&needsSoftwareDecode)audioDomHandler._SetHasAnySoftwareDecodedMusic();if(!isMusic||audioDomHandler.IsPlayMusicAsSound()||needsSoftwareDecode)return new self.C3WebAudioBuffer(audioDomHandler,originalUrl,url,type,isMusic,needsSoftwareDecode);else return new self.C3Html5AudioBuffer(audioDomHandler,originalUrl,url,type,isMusic)}CreateInstance(tags){if(this._api==="html5")return new self.C3Html5AudioInstance(this._audioDomHandler,this,tags);else return new self.C3WebAudioInstance(this._audioDomHandler, this,tags)}_Load(){}Load(){if(!this._loadPromise)this._loadPromise=this._Load();return this._loadPromise}IsLoaded(){}IsLoadedAndDecoded(){}HasFailedToLoad(){return this._loadState==="failed"}GetAudioContext(){return this._audioDomHandler.GetAudioContext()}GetApi(){return this._api}GetOriginalUrl(){return this._originalUrl}GetUrl(){return this._url}GetContentType(){return this._type}IsMusic(){return this._isMusic}GetDuration(){}}}; 'use strict';{self.C3Html5AudioBuffer=class C3Html5AudioBuffer extends self.C3AudioBuffer{constructor(audioDomHandler,originalUrl,url,type,isMusic){super(audioDomHandler,originalUrl,url,type,isMusic);this._api="html5";this._audioElem=new Audio;this._audioElem.crossOrigin="anonymous";this._audioElem.autoplay=false;this._audioElem.preload="auto";this._loadResolve=null;this._loadReject=null;this._reachedCanPlayThrough=false;this._audioElem.addEventListener("canplaythrough",()=>this._reachedCanPlayThrough= true);this._outNode=this.GetAudioContext()["createGain"]();this._mediaSourceNode=null;this._audioElem.addEventListener("canplay",()=>{if(this._loadResolve){this._loadState="loaded";this._loadResolve();this._loadResolve=null;this._loadReject=null}if(this._mediaSourceNode||!this._audioElem)return;this._mediaSourceNode=this.GetAudioContext()["createMediaElementSource"](this._audioElem);this._mediaSourceNode["connect"](this._outNode)});this.onended=null;this._audioElem.addEventListener("ended",()=>{if(this.onended)this.onended()}); this._audioElem.addEventListener("error",e=>this._OnError(e))}Release(){this._audioDomHandler.ReleaseInstancesForBuffer(this);this._outNode["disconnect"]();this._outNode=null;this._mediaSourceNode["disconnect"]();this._mediaSourceNode=null;if(this._audioElem&&!this._audioElem.paused)this._audioElem.pause();this.onended=null;this._audioElem=null;super.Release()}_Load(){this._loadState="loading";return new Promise((resolve,reject)=>{this._loadResolve=resolve;this._loadReject=reject;this._audioElem.src= this._url})}_OnError(e){console.error(`[Construct] Audio '${this._url}' error: `,e);if(this._loadReject){this._loadState="failed";this._loadReject(e);this._loadResolve=null;this._loadReject=null}}IsLoaded(){const ret=this._audioElem["readyState"]>=4;if(ret)this._reachedCanPlayThrough=true;return ret||this._reachedCanPlayThrough}IsLoadedAndDecoded(){return this.IsLoaded()}GetAudioElement(){return this._audioElem}GetOutputNode(){return this._outNode}GetDuration(){return this._audioElem["duration"]}}}; 'use strict';{self.C3WebAudioBuffer=class C3WebAudioBuffer extends self.C3AudioBuffer{constructor(audioDomHandler,originalUrl,url,type,isMusic,needsSoftwareDecode){super(audioDomHandler,originalUrl,url,type,isMusic);this._api="webaudio";this._audioData=null;this._audioBuffer=null;this._needsSoftwareDecode=!!needsSoftwareDecode}Release(){this._audioDomHandler.ReleaseInstancesForBuffer(this);this._audioData=null;this._audioBuffer=null;super.Release()}async _Fetch(){if(this._audioData)return this._audioData; const iRuntime=this._audioDomHandler.GetRuntimeInterface();if(iRuntime.GetExportType()==="cordova"&&iRuntime.IsRelativeURL(this._url)&&iRuntime.IsFileProtocol())this._audioData=await iRuntime.CordovaFetchLocalFileAsArrayBuffer(this._url);else{const response=await fetch(this._url);if(!response.ok)throw new Error(`error fetching audio data: ${response.status} ${response.statusText}`);this._audioData=await response.arrayBuffer()}}async _Decode(){if(this._audioBuffer)return this._audioBuffer;this._audioBuffer= await this._audioDomHandler.DecodeAudioData(this._audioData,this._needsSoftwareDecode);this._audioData=null}async _Load(){try{this._loadState="loading";await this._Fetch();await this._Decode();this._loadState="loaded"}catch(err){this._loadState="failed";console.error(`[Construct] Failed to load audio '${this._url}': `,err)}}IsLoaded(){return!!(this._audioData||this._audioBuffer)}IsLoadedAndDecoded(){return!!this._audioBuffer}GetAudioBuffer(){return this._audioBuffer}GetDuration(){return this._audioBuffer? this._audioBuffer["duration"]:0}}}; 'use strict';{let nextAiId=0;self.C3AudioInstance=class C3AudioInstance{constructor(audioDomHandler,buffer,tags){this._audioDomHandler=audioDomHandler;this._buffer=buffer;this._tags=tags;this._aiId=nextAiId++;this._gainNode=this.GetAudioContext()["createGain"]();this._gainNode["connect"](this.GetDestinationNode());this._pannerNode=null;this._isPannerEnabled=false;this._pannerPosition=[0,0,0];this._pannerOrientation=[0,0,0];this._pannerConeParams=[0,0,0];this._stereoPannerNode=null;this._isStereoPannerEnabled= false;this._stereoPan=0;this._isStopped=true;this._isPaused=false;this._resumeMe=false;this._isLooping=false;this._volume=1;this._isMuted=false;this._playbackRate=1;const timeScaleMode=this._audioDomHandler.GetTimeScaleMode();this._isTimescaled=timeScaleMode===1&&!this.IsMusic()||timeScaleMode===2;this._instUid=-1;this._fadeEndTime=-1;this._stopOnFadeEnd=false}Release(){this._audioDomHandler=null;this._buffer=null;if(this._pannerNode){this._pannerNode["disconnect"]();this._pannerNode=null}if(this._stereoPannerNode){this._stereoPannerNode["disconnect"](); this._stereoPannerNode=null}this._gainNode["disconnect"]();this._gainNode=null}GetAudioContext(){return this._audioDomHandler.GetAudioContext()}SetTags(tags){this._tags=tags}GetTags(){return this._tags}GetEffectTag(){return this._tags.length>0?this._tags[0]:""}GetDestinationNode(){return this._audioDomHandler.GetDestinationForTag(this.GetEffectTag())}GetCurrentTime(){if(this._isTimescaled)return this._audioDomHandler.GetGameTime();else return performance.now()/1E3}GetOriginalUrl(){return this._buffer.GetOriginalUrl()}GetUrl(){return this._buffer.GetUrl()}GetContentType(){return this._buffer.GetContentType()}GetBuffer(){return this._buffer}IsMusic(){return this._buffer.IsMusic()}GetAiId(){return this._aiId}HasEnded(){}CanBeRecycled(){}IsPlaying(){return!this._isStopped&& !this._isPaused&&!this.HasEnded()}IsActive(){return!this._isStopped&&!this.HasEnded()}GetPlaybackTime(){}GetDuration(applyPlaybackRate){let ret=this._buffer.GetDuration();if(applyPlaybackRate)ret/=this._playbackRate||.001;return ret}Play(isLooping,vol,seekPos,scheduledTime){}Stop(){}Pause(){}IsPaused(){return this._isPaused}Resume(){}SetVolume(v){this._volume=v;this._gainNode["gain"]["cancelScheduledValues"](0);this._fadeEndTime=-1;this._gainNode["gain"]["value"]=this.GetOutputVolume()}FadeVolume(vol, duration,stopOnEnd){if(this.IsMuted())return;const gainParam=this._gainNode["gain"];gainParam["cancelScheduledValues"](0);const currentTime=this._audioDomHandler.GetAudioCurrentTime();const endTime=currentTime+duration;gainParam["setValueAtTime"](gainParam["value"],currentTime);gainParam["linearRampToValueAtTime"](vol,endTime);this._volume=vol;this._fadeEndTime=endTime;this._stopOnFadeEnd=stopOnEnd}_UpdateVolume(){this.SetVolume(this._volume)}Tick(currentTime){if(this._fadeEndTime!==-1&¤tTime>= this._fadeEndTime){this._fadeEndTime=-1;if(this._stopOnFadeEnd)this.Stop();this._audioDomHandler.PostTrigger("fade-ended",this._tags,this._aiId)}}GetOutputVolume(){const ret=this._volume;return isFinite(ret)?ret:0}SetMuted(m){m=!!m;if(this._isMuted===m)return;this._isMuted=m;this._UpdateMuted()}IsMuted(){return this._isMuted}IsSilent(){return this._audioDomHandler.IsSilent()}_UpdateMuted(){}SetLooping(l){}IsLooping(){return this._isLooping}SetPlaybackRate(r){if(this._playbackRate===r)return;this._playbackRate= r;this._UpdatePlaybackRate()}_UpdatePlaybackRate(){}GetPlaybackRate(){return this._playbackRate}Seek(pos){}SetSuspended(s){}SetPannerEnabled(e){e=!!e;if(this._isPannerEnabled===e)return;this._isPannerEnabled=e;if(this._isPannerEnabled){this.SetStereoPannerEnabled(false);if(!this._pannerNode){this._pannerNode=this.GetAudioContext()["createPanner"]();this._pannerNode["panningModel"]=this._audioDomHandler.GetPanningModel();this._pannerNode["distanceModel"]=this._audioDomHandler.GetDistanceModel();this._pannerNode["refDistance"]= this._audioDomHandler.GetReferenceDistance();this._pannerNode["maxDistance"]=this._audioDomHandler.GetMaxDistance();this._pannerNode["rolloffFactor"]=this._audioDomHandler.GetRolloffFactor()}this._gainNode["disconnect"]();this._gainNode["connect"](this._pannerNode);this._pannerNode["connect"](this.GetDestinationNode())}else{this._pannerNode["disconnect"]();this._gainNode["disconnect"]();this._gainNode["connect"](this.GetDestinationNode())}}SetPan(x,y,z,angle,innerAngle,outerAngle,outerGain){if(!this._isPannerEnabled)return; this.SetPanXYZA(x,y,z,angle);const toDegrees=self.AudioDOMHandler.ToDegrees;if(this._pannerConeParams[0]!==toDegrees(innerAngle)){this._pannerConeParams[0]=toDegrees(innerAngle);this._pannerNode["coneInnerAngle"]=toDegrees(innerAngle)}if(this._pannerConeParams[1]!==toDegrees(outerAngle)){this._pannerConeParams[1]=toDegrees(outerAngle);this._pannerNode["coneOuterAngle"]=toDegrees(outerAngle)}if(this._pannerConeParams[2]!==outerGain){this._pannerConeParams[2]=outerGain;this._pannerNode["coneOuterGain"]= outerGain}}SetPanXYZA(x,y,z,angle){if(!this._isPannerEnabled)return;const pos=this._pannerPosition;const orient=this._pannerOrientation;const cosa=Math.cos(angle);const sina=Math.sin(angle);if(pos[0]!==x||pos[1]!==y||pos[2]!==z){pos[0]=x;pos[1]=y;pos[2]=z;this._pannerNode["setPosition"](...pos)}if(orient[0]!==cosa||orient[1]!==sina||orient[2]!==0){orient[0]=cosa;orient[1]=sina;orient[2]=0;this._pannerNode["setOrientation"](...orient)}}SetStereoPannerEnabled(e){e=!!e;if(this._isStereoPannerEnabled=== e)return;this._isStereoPannerEnabled=e;if(this._isStereoPannerEnabled){this.SetPannerEnabled(false);this._stereoPannerNode=this.GetAudioContext()["createStereoPanner"]();this._gainNode["disconnect"]();this._gainNode["connect"](this._stereoPannerNode);this._stereoPannerNode["connect"](this.GetDestinationNode())}else{this._stereoPannerNode["disconnect"]();this._stereoPannerNode=null;this._gainNode["disconnect"]();this._gainNode["connect"](this.GetDestinationNode())}}SetStereoPan(p){if(!this._isStereoPannerEnabled)return; if(this._stereoPan===p)return;this._stereoPannerNode["pan"]["value"]=p;this._stereoPan=p}SetUID(uid){this._instUid=uid}GetUID(){return this._instUid}GetResumePosition(){}Reconnect(toNode){const outNode=this._stereoPannerNode||this._pannerNode||this._gainNode;outNode["disconnect"]();outNode["connect"](toNode)}GetState(){return{"aiid":this.GetAiId(),"tags":this._tags,"duration":this.GetDuration(),"volume":this._fadeEndTime===-1?this._volume:this._gainNode["gain"]["value"],"isPlaying":this.IsPlaying(), "playbackTime":this.GetPlaybackTime(),"playbackRate":this.GetPlaybackRate(),"uid":this._instUid,"bufferOriginalUrl":this.GetOriginalUrl(),"bufferUrl":"","bufferType":this.GetContentType(),"isMusic":this.IsMusic(),"isLooping":this.IsLooping(),"isMuted":this.IsMuted(),"resumePosition":this.GetResumePosition(),"pan":this.GetPanState(),"stereoPan":this.GetStereoPanState()}}_LoadAdditionalState(d){this.SetPlaybackRate(d["playbackRate"]);this.SetMuted(d["isMuted"])}GetPanState(){if(!this._pannerNode)return null; const pn=this._pannerNode;return{"pos":this._pannerPosition,"orient":this._pannerOrientation,"cia":pn["coneInnerAngle"],"coa":pn["coneOuterAngle"],"cog":pn["coneOuterGain"],"uid":this._instUid}}LoadPanState(d){if(!d){this.SetPannerEnabled(false);return}this.SetPannerEnabled(true);const pn=this._pannerNode;const panPos=d["pos"];this._pannerPosition[0]=panPos[0];this._pannerPosition[1]=panPos[1];this._pannerPosition[2]=panPos[2];const panOrient=d["orient"];this._pannerOrientation[0]=panOrient[0];this._pannerOrientation[1]= panOrient[1];this._pannerOrientation[2]=panOrient[2];pn["setPosition"](...this._pannerPosition);pn["setOrientation"](...this._pannerOrientation);this._pannerConeParams[0]=d["cia"];this._pannerConeParams[1]=d["coa"];this._pannerConeParams[2]=d["cog"];pn["coneInnerAngle"]=d["cia"];pn["coneOuterAngle"]=d["coa"];pn["coneOuterGain"]=d["cog"];this._instUid=d["uid"]}GetStereoPanState(){if(this._stereoPannerNode)return this._stereoPan;else return null}LoadStereoPanState(p){if(typeof p!=="number"){this.SetStereoPannerEnabled(false); return}this.SetStereoPannerEnabled(true);this.SetStereoPan(p)}}}; 'use strict';{self.C3Html5AudioInstance=class C3Html5AudioInstance extends self.C3AudioInstance{constructor(audioDomHandler,buffer,tags){super(audioDomHandler,buffer,tags);this._buffer.GetOutputNode()["connect"](this._gainNode);this._buffer.onended=()=>this._OnEnded()}Release(){this.Stop();this._buffer.GetOutputNode()["disconnect"]();super.Release()}GetAudioElement(){return this._buffer.GetAudioElement()}_OnEnded(){this._isStopped=true;this._instUid=-1;this._audioDomHandler.PostTrigger("ended",this._tags, this._aiId)}HasEnded(){return this.GetAudioElement()["ended"]}CanBeRecycled(){if(this._isStopped)return true;return this.HasEnded()}GetPlaybackTime(){let ret=this.GetAudioElement()["currentTime"];if(!this._isLooping)ret=Math.min(ret,this.GetDuration());return ret}Play(isLooping,vol,seekPos,scheduledTime){const audioElem=this.GetAudioElement();if(audioElem.playbackRate!==1)audioElem.playbackRate=1;if(audioElem.loop!==isLooping)audioElem.loop=isLooping;this.SetVolume(vol);this._isMuted=false;if(audioElem.muted)audioElem.muted= false;if(audioElem.currentTime!==seekPos)try{audioElem.currentTime=seekPos}catch(err){console.warn(`[Construct] Exception seeking audio '${this._buffer.GetUrl()}' to position '${seekPos}': `,err)}this._audioDomHandler.TryPlayMedia(audioElem);this._isStopped=false;this._isPaused=false;this._isLooping=isLooping;this._playbackRate=1}Stop(){const audioElem=this.GetAudioElement();if(!audioElem.paused)audioElem.pause();this._audioDomHandler.RemovePendingPlay(audioElem);this._isStopped=true;this._isPaused= false;this._instUid=-1}Pause(){if(this._isPaused||this._isStopped||this.HasEnded())return;const audioElem=this.GetAudioElement();if(!audioElem.paused)audioElem.pause();this._audioDomHandler.RemovePendingPlay(audioElem);this._isPaused=true}Resume(){if(!this._isPaused||this._isStopped||this.HasEnded())return;this._audioDomHandler.TryPlayMedia(this.GetAudioElement());this._isPaused=false}_UpdateMuted(){this.GetAudioElement().muted=this._isMuted||this.IsSilent()}SetLooping(l){l=!!l;if(this._isLooping=== l)return;this._isLooping=l;this.GetAudioElement().loop=l}_UpdatePlaybackRate(){let r=this._playbackRate;if(this._isTimescaled)r*=this._audioDomHandler.GetTimeScale();try{this.GetAudioElement()["playbackRate"]=r}catch(err){console.warn(`[Construct] Unable to set playback rate '${r}':`,err)}}Seek(pos){if(this._isStopped||this.HasEnded())return;try{this.GetAudioElement()["currentTime"]=pos}catch(err){console.warn(`[Construct] Error seeking audio to '${pos}': `,err)}}GetResumePosition(){return this.GetPlaybackTime()}SetSuspended(s){if(s)if(this.IsPlaying()){this.GetAudioElement()["pause"](); this._resumeMe=true}else this._resumeMe=false;else if(this._resumeMe){this._audioDomHandler.TryPlayMedia(this.GetAudioElement());this._resumeMe=false}}}}; 'use strict';{self.C3WebAudioInstance=class C3WebAudioInstance extends self.C3AudioInstance{constructor(audioDomHandler,buffer,tags){super(audioDomHandler,buffer,tags);this._bufferSource=null;this._onended_handler=e=>this._OnEnded(e);this._hasPlaybackEnded=true;this._activeSource=null;this._playStartTime=0;this._playFromSeekPos=0;this._resumePosition=0;this._muteVol=1}Release(){this.Stop();this._ReleaseBufferSource();this._onended_handler=null;super.Release()}_ReleaseBufferSource(){if(this._bufferSource){this._bufferSource["onended"]= null;this._bufferSource["disconnect"]();this._bufferSource["buffer"]=null}this._bufferSource=null;this._activeSource=null}_OnEnded(e){if(this._isPaused||this._resumeMe)return;if(e.target!==this._activeSource)return;this._hasPlaybackEnded=true;this._isStopped=true;this._instUid=-1;this._ReleaseBufferSource();this._audioDomHandler.PostTrigger("ended",this._tags,this._aiId)}HasEnded(){if(!this._isStopped&&this._bufferSource&&this._bufferSource["loop"])return false;if(this._isPaused)return false;return this._hasPlaybackEnded}CanBeRecycled(){if(!this._bufferSource|| this._isStopped)return true;return this.HasEnded()}GetPlaybackTime(){let ret=0;if(this._isPaused)ret=this._resumePosition;else ret=this._playFromSeekPos+(this.GetCurrentTime()-this._playStartTime)*this._playbackRate;if(!this._isLooping)ret=Math.min(ret,this.GetDuration());return ret}Play(isLooping,vol,seekPos,scheduledTime){this._isMuted=false;this._muteVol=1;this.SetVolume(vol);this._ReleaseBufferSource();this._bufferSource=this.GetAudioContext()["createBufferSource"]();this._bufferSource["buffer"]= this._buffer.GetAudioBuffer();this._bufferSource["connect"](this._gainNode);this._activeSource=this._bufferSource;this._bufferSource["onended"]=this._onended_handler;this._bufferSource["loop"]=isLooping;this._bufferSource["start"](scheduledTime,seekPos);this._hasPlaybackEnded=false;this._isStopped=false;this._isPaused=false;this._isLooping=isLooping;this._playbackRate=1;this._playStartTime=this.GetCurrentTime();this._playFromSeekPos=seekPos}Stop(){if(this._bufferSource)try{this._bufferSource["stop"](0)}catch(err){}this._isStopped= true;this._isPaused=false;this._instUid=-1}Pause(){if(this._isPaused||this._isStopped||this.HasEnded())return;this._resumePosition=this.GetPlaybackTime();if(this._isLooping)this._resumePosition%=this.GetDuration();this._isPaused=true;this._bufferSource["stop"](0)}Resume(){if(!this._isPaused||this._isStopped||this.HasEnded())return;this._ReleaseBufferSource();this._bufferSource=this.GetAudioContext()["createBufferSource"]();this._bufferSource["buffer"]=this._buffer.GetAudioBuffer();this._bufferSource["connect"](this._gainNode); this._activeSource=this._bufferSource;this._bufferSource["onended"]=this._onended_handler;this._bufferSource["loop"]=this._isLooping;this._UpdateVolume();this._UpdatePlaybackRate();this._bufferSource["start"](0,this._resumePosition);this._playStartTime=this.GetCurrentTime();this._playFromSeekPos=this._resumePosition;this._isPaused=false}GetOutputVolume(){return super.GetOutputVolume()*this._muteVol}_UpdateMuted(){this._muteVol=this._isMuted||this.IsSilent()?0:1;this._UpdateVolume()}SetLooping(l){l= !!l;if(this._isLooping===l)return;this._isLooping=l;if(this._bufferSource)this._bufferSource["loop"]=l}_UpdatePlaybackRate(){let r=this._playbackRate;if(this._isTimescaled)r*=this._audioDomHandler.GetTimeScale();if(this._bufferSource)this._bufferSource["playbackRate"]["value"]=r}Seek(pos){if(this._isStopped||this.HasEnded())return;if(this._isPaused)this._resumePosition=pos;else{this.Pause();this._resumePosition=pos;this.Resume()}}GetResumePosition(){return this._resumePosition}SetSuspended(s){if(s)if(this.IsPlaying()){this._resumeMe= true;this._resumePosition=this.GetPlaybackTime();if(this._isLooping)this._resumePosition%=this.GetDuration();this._bufferSource["stop"](0)}else this._resumeMe=false;else if(this._resumeMe){this._ReleaseBufferSource();this._bufferSource=this.GetAudioContext()["createBufferSource"]();this._bufferSource["buffer"]=this._buffer.GetAudioBuffer();this._bufferSource["connect"](this._gainNode);this._activeSource=this._bufferSource;this._bufferSource["onended"]=this._onended_handler;this._bufferSource["loop"]= this._isLooping;this._UpdateVolume();this._UpdatePlaybackRate();this._bufferSource["start"](0,this._resumePosition);this._playStartTime=this.GetCurrentTime();this._playFromSeekPos=this._resumePosition;this._resumeMe=false}}_LoadAdditionalState(d){super._LoadAdditionalState(d);this._resumePosition=d["resumePosition"]}}}; 'use strict';{class AudioFXBase{constructor(audioDomHandler){this._audioDomHandler=audioDomHandler;this._audioContext=audioDomHandler.GetAudioContext();this._index=-1;this._tag="";this._type="";this._params=null}Release(){this._audioContext=null}_SetIndex(i){this._index=i}GetIndex(){return this._index}_SetTag(t){this._tag=t}GetTag(){return this._tag}CreateGain(){return this._audioContext["createGain"]()}GetInputNode(){}ConnectTo(node){}SetAudioParam(ap,value,ramp,time){ap["cancelScheduledValues"](0); if(time===0){ap["value"]=value;return}const curTime=this._audioContext["currentTime"];time+=curTime;switch(ramp){case 0:ap["setValueAtTime"](value,time);break;case 1:ap["setValueAtTime"](ap["value"],curTime);ap["linearRampToValueAtTime"](value,time);break;case 2:ap["setValueAtTime"](ap["value"],curTime);ap["exponentialRampToValueAtTime"](value,time);break}}GetState(){return{"type":this._type,"tag":this._tag,"params":this._params}}}self.C3AudioFilterFX=class C3AudioFilterFX extends AudioFXBase{constructor(audioDomHandler, type,freq,detune,q,gain,mix){super(audioDomHandler);this._type="filter";this._params=[type,freq,detune,q,gain,mix];this._inputNode=this.CreateGain();this._wetNode=this.CreateGain();this._wetNode["gain"]["value"]=mix;this._dryNode=this.CreateGain();this._dryNode["gain"]["value"]=1-mix;this._filterNode=this._audioContext["createBiquadFilter"]();this._filterNode["type"]=type;this._filterNode["frequency"]["value"]=freq;this._filterNode["detune"]["value"]=detune;this._filterNode["Q"]["value"]=q;this._filterNode["gain"]["vlaue"]= gain;this._inputNode["connect"](this._filterNode);this._inputNode["connect"](this._dryNode);this._filterNode["connect"](this._wetNode)}Release(){this._inputNode["disconnect"]();this._filterNode["disconnect"]();this._wetNode["disconnect"]();this._dryNode["disconnect"]();super.Release()}ConnectTo(node){this._wetNode["disconnect"]();this._wetNode["connect"](node);this._dryNode["disconnect"]();this._dryNode["connect"](node)}GetInputNode(){return this._inputNode}SetParam(param,value,ramp,time){switch(param){case 0:value= Math.max(Math.min(value/100,1),0);this._params[5]=value;this.SetAudioParam(this._wetNode["gain"],value,ramp,time);this.SetAudioParam(this._dryNode["gain"],1-value,ramp,time);break;case 1:this._params[1]=value;this.SetAudioParam(this._filterNode["frequency"],value,ramp,time);break;case 2:this._params[2]=value;this.SetAudioParam(this._filterNode["detune"],value,ramp,time);break;case 3:this._params[3]=value;this.SetAudioParam(this._filterNode["Q"],value,ramp,time);break;case 4:this._params[4]=value; this.SetAudioParam(this._filterNode["gain"],value,ramp,time);break}}};self.C3AudioDelayFX=class C3AudioDelayFX extends AudioFXBase{constructor(audioDomHandler,delayTime,delayGain,mix){super(audioDomHandler);this._type="delay";this._params=[delayTime,delayGain,mix];this._inputNode=this.CreateGain();this._wetNode=this.CreateGain();this._wetNode["gain"]["value"]=mix;this._dryNode=this.CreateGain();this._dryNode["gain"]["value"]=1-mix;this._mainNode=this.CreateGain();this._delayNode=this._audioContext["createDelay"](delayTime); this._delayNode["delayTime"]["value"]=delayTime;this._delayGainNode=this.CreateGain();this._delayGainNode["gain"]["value"]=delayGain;this._inputNode["connect"](this._mainNode);this._inputNode["connect"](this._dryNode);this._mainNode["connect"](this._wetNode);this._mainNode["connect"](this._delayNode);this._delayNode["connect"](this._delayGainNode);this._delayGainNode["connect"](this._mainNode)}Release(){this._inputNode["disconnect"]();this._wetNode["disconnect"]();this._dryNode["disconnect"]();this._mainNode["disconnect"](); this._delayNode["disconnect"]();this._delayGainNode["disconnect"]();super.Release()}ConnectTo(node){this._wetNode["disconnect"]();this._wetNode["connect"](node);this._dryNode["disconnect"]();this._dryNode["connect"](node)}GetInputNode(){return this._inputNode}SetParam(param,value,ramp,time){const DbToLinear=self.AudioDOMHandler.DbToLinear;switch(param){case 0:value=Math.max(Math.min(value/100,1),0);this._params[2]=value;this.SetAudioParam(this._wetNode["gain"],value,ramp,time);this.SetAudioParam(this._dryNode["gain"], 1-value,ramp,time);break;case 4:this._params[1]=DbToLinear(value);this.SetAudioParam(this._delayGainNode["gain"],DbToLinear(value),ramp,time);break;case 5:this._params[0]=value;this.SetAudioParam(this._delayNode["delayTime"],value,ramp,time);break}}};self.C3AudioConvolveFX=class C3AudioConvolveFX extends AudioFXBase{constructor(audioDomHandler,buffer,normalize,mix){super(audioDomHandler);this._type="convolution";this._params=[normalize,mix];this._bufferOriginalUrl="";this._bufferUrl="";this._bufferType= "";this._inputNode=this.CreateGain();this._wetNode=this.CreateGain();this._wetNode["gain"]["value"]=mix;this._dryNode=this.CreateGain();this._dryNode["gain"]["value"]=1-mix;this._convolveNode=this._audioContext["createConvolver"]();this._convolveNode["normalize"]=normalize;this._convolveNode["buffer"]=buffer;this._inputNode["connect"](this._convolveNode);this._inputNode["connect"](this._dryNode);this._convolveNode["connect"](this._wetNode)}Release(){this._inputNode["disconnect"]();this._convolveNode["disconnect"](); this._wetNode["disconnect"]();this._dryNode["disconnect"]();super.Release()}ConnectTo(node){this._wetNode["disconnect"]();this._wetNode["connect"](node);this._dryNode["disconnect"]();this._dryNode["connect"](node)}GetInputNode(){return this._inputNode}SetParam(param,value,ramp,time){switch(param){case 0:value=Math.max(Math.min(value/100,1),0);this._params[1]=value;this.SetAudioParam(this._wetNode["gain"],value,ramp,time);this.SetAudioParam(this._dryNode["gain"],1-value,ramp,time);break}}_SetBufferInfo(bufferOriginalUrl, bufferUrl,bufferType){this._bufferOriginalUrl=bufferOriginalUrl;this._bufferUrl=bufferUrl;this._bufferType=bufferType}GetState(){const ret=super.GetState();ret["bufferOriginalUrl"]=this._bufferOriginalUrl;ret["bufferUrl"]="";ret["bufferType"]=this._bufferType;return ret}};self.C3AudioFlangerFX=class C3AudioFlangerFX extends AudioFXBase{constructor(audioDomHandler,delay,modulation,freq,feedback,mix){super(audioDomHandler);this._type="flanger";this._params=[delay,modulation,freq,feedback,mix];this._inputNode= this.CreateGain();this._dryNode=this.CreateGain();this._dryNode["gain"]["value"]=1-mix/2;this._wetNode=this.CreateGain();this._wetNode["gain"]["value"]=mix/2;this._feedbackNode=this.CreateGain();this._feedbackNode["gain"]["value"]=feedback;this._delayNode=this._audioContext["createDelay"](delay+modulation);this._delayNode["delayTime"]["value"]=delay;this._oscNode=this._audioContext["createOscillator"]();this._oscNode["frequency"]["value"]=freq;this._oscGainNode=this.CreateGain();this._oscGainNode["gain"]["value"]= modulation;this._inputNode["connect"](this._delayNode);this._inputNode["connect"](this._dryNode);this._delayNode["connect"](this._wetNode);this._delayNode["connect"](this._feedbackNode);this._feedbackNode["connect"](this._delayNode);this._oscNode["connect"](this._oscGainNode);this._oscGainNode["connect"](this._delayNode["delayTime"]);this._oscNode["start"](0)}Release(){this._oscNode["stop"](0);this._inputNode["disconnect"]();this._delayNode["disconnect"]();this._oscNode["disconnect"]();this._oscGainNode["disconnect"](); this._dryNode["disconnect"]();this._wetNode["disconnect"]();this._feedbackNode["disconnect"]();super.Release()}ConnectTo(node){this._wetNode["disconnect"]();this._wetNode["connect"](node);this._dryNode["disconnect"]();this._dryNode["connect"](node)}GetInputNode(){return this._inputNode}SetParam(param,value,ramp,time){switch(param){case 0:value=Math.max(Math.min(value/100,1),0);this._params[4]=value;this.SetAudioParam(this._wetNode["gain"],value/2,ramp,time);this.SetAudioParam(this._dryNode["gain"], 1-value/2,ramp,time);break;case 6:this._params[1]=value/1E3;this.SetAudioParam(this._oscGainNode["gain"],value/1E3,ramp,time);break;case 7:this._params[2]=value;this.SetAudioParam(this._oscNode["frequency"],value,ramp,time);break;case 8:this._params[3]=value/100;this.SetAudioParam(this._feedbackNode["gain"],value/100,ramp,time);break}}};self.C3AudioPhaserFX=class C3AudioPhaserFX extends AudioFXBase{constructor(audioDomHandler,freq,detune,q,modulation,modfreq,mix){super(audioDomHandler);this._type= "phaser";this._params=[freq,detune,q,modulation,modfreq,mix];this._inputNode=this.CreateGain();this._dryNode=this.CreateGain();this._dryNode["gain"]["value"]=1-mix/2;this._wetNode=this.CreateGain();this._wetNode["gain"]["value"]=mix/2;this._filterNode=this._audioContext["createBiquadFilter"]();this._filterNode["type"]="allpass";this._filterNode["frequency"]["value"]=freq;this._filterNode["detune"]["value"]=detune;this._filterNode["Q"]["value"]=q;this._oscNode=this._audioContext["createOscillator"](); this._oscNode["frequency"]["value"]=modfreq;this._oscGainNode=this.CreateGain();this._oscGainNode["gain"]["value"]=modulation;this._inputNode["connect"](this._filterNode);this._inputNode["connect"](this._dryNode);this._filterNode["connect"](this._wetNode);this._oscNode["connect"](this._oscGainNode);this._oscGainNode["connect"](this._filterNode["frequency"]);this._oscNode["start"](0)}Release(){this._oscNode["stop"](0);this._inputNode["disconnect"]();this._filterNode["disconnect"]();this._oscNode["disconnect"](); this._oscGainNode["disconnect"]();this._dryNode["disconnect"]();this._wetNode["disconnect"]();super.Release()}ConnectTo(node){this._wetNode["disconnect"]();this._wetNode["connect"](node);this._dryNode["disconnect"]();this._dryNode["connect"](node)}GetInputNode(){return this._inputNode}SetParam(param,value,ramp,time){switch(param){case 0:value=Math.max(Math.min(value/100,1),0);this._params[5]=value;this.SetAudioParam(this._wetNode["gain"],value/2,ramp,time);this.SetAudioParam(this._dryNode["gain"], 1-value/2,ramp,time);break;case 1:this._params[0]=value;this.SetAudioParam(this._filterNode["frequency"],value,ramp,time);break;case 2:this._params[1]=value;this.SetAudioParam(this._filterNode["detune"],value,ramp,time);break;case 3:this._params[2]=value;this.SetAudioParam(this._filterNode["Q"],value,ramp,time);break;case 6:this._params[3]=value;this.SetAudioParam(this._oscGainNode["gain"],value,ramp,time);break;case 7:this._params[4]=value;this.SetAudioParam(this._oscNode["frequency"],value,ramp, time);break}}};self.C3AudioGainFX=class C3AudioGainFX extends AudioFXBase{constructor(audioDomHandler,g){super(audioDomHandler);this._type="gain";this._params=[g];this._node=this.CreateGain();this._node["gain"]["value"]=g}Release(){this._node["disconnect"]();super.Release()}ConnectTo(node){this._node["disconnect"]();this._node["connect"](node)}GetInputNode(){return this._node}SetParam(param,value,ramp,time){const DbToLinear=self.AudioDOMHandler.DbToLinear;switch(param){case 4:this._params[0]=DbToLinear(value); this.SetAudioParam(this._node["gain"],DbToLinear(value),ramp,time);break}}};self.C3AudioStereoPanFX=class C3AudioStereoPanFX extends AudioFXBase{constructor(audioDomHandler,p){super(audioDomHandler);this._type="stereopan";this._params=[p];this._node=this._audioContext["createStereoPanner"]();this._node["pan"]["value"]=p}Release(){this._node["disconnect"]();super.Release()}ConnectTo(node){this._node["disconnect"]();this._node["connect"](node)}GetInputNode(){return this._node}SetParam(param,value,ramp, time){value=Math.min(Math.max(value/100,-1),1);switch(param){case 9:this._params[0]=value;this.SetAudioParam(this._node["pan"],value,ramp,time);break}}};self.C3AudioTremoloFX=class C3AudioTremoloFX extends AudioFXBase{constructor(audioDomHandler,freq,mix){super(audioDomHandler);this._type="tremolo";this._params=[freq,mix];this._node=this.CreateGain();this._node["gain"]["value"]=1-mix/2;this._oscNode=this._audioContext["createOscillator"]();this._oscNode["frequency"]["value"]=freq;this._oscGainNode= this.CreateGain();this._oscGainNode["gain"]["value"]=mix/2;this._oscNode["connect"](this._oscGainNode);this._oscGainNode["connect"](this._node["gain"]);this._oscNode["start"](0)}Release(){this._oscNode["stop"](0);this._oscNode["disconnect"]();this._oscGainNode["disconnect"]();this._node["disconnect"]();super.Release()}ConnectTo(node){this._node["disconnect"]();this._node["connect"](node)}GetInputNode(){return this._node}SetParam(param,value,ramp,time){switch(param){case 0:value=Math.max(Math.min(value/ 100,1),0);this._params[1]=value;this.SetAudioParam(this._node["gain"],1-value/2,ramp,time);this.SetAudioParam(this._oscGainNode["gain"],value/2,ramp,time);break;case 7:this._params[0]=value;this.SetAudioParam(this._oscNode["frequency"],value,ramp,time);break}}};self.C3AudioRingModFX=class C3AudioRingModFX extends AudioFXBase{constructor(audioDomHandler,freq,mix){super(audioDomHandler);this._type="ringmod";this._params=[freq,mix];this._inputNode=this.CreateGain();this._wetNode=this.CreateGain();this._wetNode["gain"]["value"]= mix;this._dryNode=this.CreateGain();this._dryNode["gain"]["value"]=1-mix;this._ringNode=this.CreateGain();this._ringNode["gain"]["value"]=0;this._oscNode=this._audioContext["createOscillator"]();this._oscNode["frequency"]["value"]=freq;this._oscNode["connect"](this._ringNode["gain"]);this._oscNode["start"](0);this._inputNode["connect"](this._ringNode);this._inputNode["connect"](this._dryNode);this._ringNode["connect"](this._wetNode)}Release(){this._oscNode["stop"](0);this._oscNode["disconnect"](); this._ringNode["disconnect"]();this._inputNode["disconnect"]();this._wetNode["disconnect"]();this._dryNode["disconnect"]();super.Release()}ConnectTo(node){this._wetNode["disconnect"]();this._wetNode["connect"](node);this._dryNode["disconnect"]();this._dryNode["connect"](node)}GetInputNode(){return this._inputNode}SetParam(param,value,ramp,time){switch(param){case 0:value=Math.max(Math.min(value/100,1),0);this._params[1]=value;this.SetAudioParam(this._wetNode["gain"],value,ramp,time);this.SetAudioParam(this._dryNode["gain"], 1-value,ramp,time);break;case 7:this._params[0]=value;this.SetAudioParam(this._oscNode["frequency"],value,ramp,time);break}}};self.C3AudioDistortionFX=class C3AudioDistortionFX extends AudioFXBase{constructor(audioDomHandler,threshold,headroom,drive,makeupgain,mix){super(audioDomHandler);this._type="distortion";this._params=[threshold,headroom,drive,makeupgain,mix];this._inputNode=this.CreateGain();this._preGain=this.CreateGain();this._postGain=this.CreateGain();this._SetDrive(drive,makeupgain);this._wetNode= this.CreateGain();this._wetNode["gain"]["value"]=mix;this._dryNode=this.CreateGain();this._dryNode["gain"]["value"]=1-mix;this._waveShaper=this._audioContext["createWaveShaper"]();this._curve=new Float32Array(65536);this._GenerateColortouchCurve(threshold,headroom);this._waveShaper.curve=this._curve;this._inputNode["connect"](this._preGain);this._inputNode["connect"](this._dryNode);this._preGain["connect"](this._waveShaper);this._waveShaper["connect"](this._postGain);this._postGain["connect"](this._wetNode)}Release(){this._inputNode["disconnect"](); this._preGain["disconnect"]();this._waveShaper["disconnect"]();this._postGain["disconnect"]();this._wetNode["disconnect"]();this._dryNode["disconnect"]();super.Release()}_SetDrive(drive,makeupgain){if(drive<.01)drive=.01;this._preGain["gain"]["value"]=drive;this._postGain["gain"]["value"]=Math.pow(1/drive,.6)*makeupgain}_GenerateColortouchCurve(threshold,headroom){const n=65536;const n2=n/2;for(let i=0;i<n2;++i){let x=i/n2;x=this._Shape(x,threshold,headroom);this._curve[n2+i]=x;this._curve[n2-i-1]= -x}}_Shape(x,threshold,headroom){const maximum=1.05*headroom*threshold;const kk=maximum-threshold;const sign=x<0?-1:+1;const absx=x<0?-x:x;let shapedInput=absx<threshold?absx:threshold+kk*self.AudioDOMHandler.e4(absx-threshold,1/kk);shapedInput*=sign;return shapedInput}ConnectTo(node){this._wetNode["disconnect"]();this._wetNode["connect"](node);this._dryNode["disconnect"]();this._dryNode["connect"](node)}GetInputNode(){return this._inputNode}SetParam(param,value,ramp,time){switch(param){case 0:value= Math.max(Math.min(value/100,1),0);this._params[4]=value;this.SetAudioParam(this._wetNode["gain"],value,ramp,time);this.SetAudioParam(this._dryNode["gain"],1-value,ramp,time);break}}};self.C3AudioCompressorFX=class C3AudioCompressorFX extends AudioFXBase{constructor(audioDomHandler,threshold,knee,ratio,attack,release){super(audioDomHandler);this._type="compressor";this._params=[threshold,knee,ratio,attack,release];this._node=this._audioContext["createDynamicsCompressor"]();this._node["threshold"]["value"]= threshold;this._node["knee"]["value"]=knee;this._node["ratio"]["value"]=ratio;this._node["attack"]["value"]=attack;this._node["release"]["value"]=release}Release(){this._node["disconnect"]();super.Release()}ConnectTo(node){this._node["disconnect"]();this._node["connect"](node)}GetInputNode(){return this._node}SetParam(param,value,ramp,time){}};self.C3AudioAnalyserFX=class C3AudioAnalyserFX extends AudioFXBase{constructor(audioDomHandler,fftSize,smoothing){super(audioDomHandler);this._type="analyser"; this._params=[fftSize,smoothing];this._node=this._audioContext["createAnalyser"]();this._node["fftSize"]=fftSize;this._node["smoothingTimeConstant"]=smoothing;this._freqBins=new Float32Array(this._node["frequencyBinCount"]);this._signal=new Uint8Array(fftSize);this._peak=0;this._rms=0;this._audioDomHandler._AddAnalyser(this)}Release(){this._audioDomHandler._RemoveAnalyser(this);this._node["disconnect"]();super.Release()}Tick(){this._node["getFloatFrequencyData"](this._freqBins);this._node["getByteTimeDomainData"](this._signal); const fftSize=this._node["fftSize"];this._peak=0;let rmsSquaredSum=0;for(let i=0;i<fftSize;++i){let s=(this._signal[i]-128)/128;if(s<0)s=-s;if(this._peak<s)this._peak=s;rmsSquaredSum+=s*s}const LinearToDb=self.AudioDOMHandler.LinearToDb;this._peak=LinearToDb(this._peak);this._rms=LinearToDb(Math.sqrt(rmsSquaredSum/fftSize))}ConnectTo(node){this._node["disconnect"]();this._node["connect"](node)}GetInputNode(){return this._node}SetParam(param,value,ramp,time){}GetData(){return{"tag":this.GetTag(),"index":this.GetIndex(), "peak":this._peak,"rms":this._rms,"binCount":this._node["frequencyBinCount"],"freqBins":this._freqBins}}}}; 'use strict';{const DOM_COMPONENT_ID="touch";const HANDLER_CLASS=class TouchDOMHandler extends self.DOMHandler{constructor(iRuntime){super(iRuntime,DOM_COMPONENT_ID);this.AddRuntimeMessageHandler("request-permission",e=>this._OnRequestPermission(e))}async _OnRequestPermission(e){const type=e["type"];let result=true;if(type===0)result=await this._RequestOrientationPermission();else if(type===1)result=await this._RequestMotionPermission();this.PostToRuntime("permission-result",{"type":type,"result":result})}async _RequestOrientationPermission(){if(!self["DeviceOrientationEvent"]|| !self["DeviceOrientationEvent"]["requestPermission"])return true;try{const state=await self["DeviceOrientationEvent"]["requestPermission"]();return state==="granted"}catch(err){console.warn("[Touch] Failed to request orientation permission: ",err);return false}}async _RequestMotionPermission(){if(!self["DeviceMotionEvent"]||!self["DeviceMotionEvent"]["requestPermission"])return true;try{const state=await self["DeviceMotionEvent"]["requestPermission"]();return state==="granted"}catch(err){console.warn("[Touch] Failed to request motion permission: ", err);return false}}};self.RuntimeInterface.AddDOMHandlerClass(HANDLER_CLASS)}; 'use strict';{const DOM_COMPONENT_ID="localstorage";const HANDLER_CLASS=class LocalStorageDOMHandler extends self.DOMHandler{constructor(iRuntime){super(iRuntime,DOM_COMPONENT_ID);this.AddRuntimeMessageHandlers([["init",()=>this._Init()],["request-persistent",()=>this._OnRequestPersistent()]])}async _Init(){let isPersistent=false;try{isPersistent=await navigator["storage"]["persisted"]()}catch(err){isPersistent=false;console.warn("[Construct] Error checking storage persisted state: ",err)}return{"isPersistent":isPersistent}}async _OnRequestPersistent(){try{const isPersistent= await navigator["storage"]["persist"]();return{"isOk":true,"isPersistent":isPersistent}}catch(err){console.error("[Construct] Error requesting persistent storage: ",err);return{"isOk":false}}}};self.RuntimeInterface.AddDOMHandlerClass(HANDLER_CLASS)}; 'use strict';{let deferredInstallPromptEvent=null;let browserDomHandler=null;window.addEventListener("beforeinstallprompt",e=>{e.preventDefault();deferredInstallPromptEvent=e;if(browserDomHandler)browserDomHandler._OnBeforeInstallPrompt();return false});function elemsForSelector(selector,isAll){if(!selector)return[document.documentElement];else if(isAll)return Array.from(document.querySelectorAll(selector));else{const e=document.querySelector(selector);return e?[e]:[]}}function noop(){}const DOM_COMPONENT_ID= "browser";const HANDLER_CLASS=class BrowserDOMHandler extends self.DOMHandler{constructor(iRuntime){super(iRuntime,DOM_COMPONENT_ID);this._exportType="";this.AddRuntimeMessageHandlers([["get-initial-state",e=>this._OnGetInitialState(e)],["ready-for-sw-messages",()=>this._OnReadyForSWMessages()],["alert",e=>this._OnAlert(e)],["close",()=>this._OnClose()],["set-focus",e=>this._OnSetFocus(e)],["vibrate",e=>this._OnVibrate(e)],["lock-orientation",e=>this._OnLockOrientation(e)],["unlock-orientation",()=> this._OnUnlockOrientation()],["navigate",e=>this._OnNavigate(e)],["request-fullscreen",e=>this._OnRequestFullscreen(e)],["exit-fullscreen",()=>this._OnExitFullscreen()],["set-hash",e=>this._OnSetHash(e)],["set-document-css-style",e=>this._OnSetDocumentCSSStyle(e)],["get-document-css-style",e=>this._OnGetDocumentCSSStyle(e)],["set-window-size",e=>this._OnSetWindowSize(e)],["set-window-position",e=>this._OnSetWindowPosition(e)],["request-install",()=>this._OnRequestInstall()]]);window.addEventListener("online", ()=>this._OnOnlineStateChanged(true));window.addEventListener("offline",()=>this._OnOnlineStateChanged(false));window.addEventListener("hashchange",()=>this._OnHashChange());document.addEventListener("backbutton",()=>this._OnCordovaBackButton())}Attach(){if(deferredInstallPromptEvent)this._OnBeforeInstallPrompt();else browserDomHandler=this;window.addEventListener("appinstalled",()=>this._OnAppInstalled())}_OnGetInitialState(e){this._exportType=e["exportType"];return{"location":location.toString(), "isOnline":!!navigator.onLine,"referrer":document.referrer,"title":document.title,"isCookieEnabled":!!navigator.cookieEnabled,"screenWidth":screen.width,"screenHeight":screen.height,"windowOuterWidth":window.outerWidth,"windowOuterHeight":window.outerHeight,"isConstructArcade":typeof window["is_scirra_arcade"]!=="undefined"}}_OnReadyForSWMessages(){if(!window["C3_RegisterSW"]||!window["OfflineClientInfo"])return;window["OfflineClientInfo"]["SetMessageCallback"](e=>this.PostToRuntime("sw-message", e["data"]))}_OnBeforeInstallPrompt(){this.PostToRuntime("install-available")}async _OnRequestInstall(){if(!deferredInstallPromptEvent)return{"result":"unavailable"};try{deferredInstallPromptEvent["prompt"]();const result=await deferredInstallPromptEvent["userChoice"];return{"result":result["outcome"]}}catch(err){console.error("[Construct] Requesting install failed: ",err);return{"result":"failed"}}}_OnAppInstalled(){this.PostToRuntime("app-installed")}_OnOnlineStateChanged(isOnline){this.PostToRuntime("online-state", {"isOnline":isOnline})}_OnCordovaBackButton(){this.PostToRuntime("backbutton")}GetNWjsWindow(){if(this._exportType==="nwjs")return nw["Window"]["get"]();else return null}_OnAlert(e){alert(e["message"])}_OnClose(){if(navigator["app"]&&navigator["app"]["exitApp"])navigator["app"]["exitApp"]();else if(navigator["device"]&&navigator["device"]["exitApp"])navigator["device"]["exitApp"]();else window.close()}_OnSetFocus(e){const isFocus=e["isFocus"];if(this._exportType==="nwjs"){const win=this.GetNWjsWindow(); if(isFocus)win["focus"]();else win["blur"]()}else if(isFocus)window.focus();else window.blur()}_OnVibrate(e){if(navigator["vibrate"])navigator["vibrate"](e["pattern"])}_OnLockOrientation(e){const orientation=e["orientation"];if(screen["orientation"]&&screen["orientation"]["lock"])screen["orientation"]["lock"](orientation).catch(err=>console.warn("[Construct] Failed to lock orientation: ",err));else try{let result=false;if(screen["lockOrientation"])result=screen["lockOrientation"](orientation);else if(screen["webkitLockOrientation"])result= screen["webkitLockOrientation"](orientation);else if(screen["mozLockOrientation"])result=screen["mozLockOrientation"](orientation);else if(screen["msLockOrientation"])result=screen["msLockOrientation"](orientation);if(!result)console.warn("[Construct] Failed to lock orientation")}catch(err){console.warn("[Construct] Failed to lock orientation: ",err)}}_OnUnlockOrientation(){try{if(screen["orientation"]&&screen["orientation"]["unlock"])screen["orientation"]["unlock"]();else if(screen["unlockOrientation"])screen["unlockOrientation"](); else if(screen["webkitUnlockOrientation"])screen["webkitUnlockOrientation"]();else if(screen["mozUnlockOrientation"])screen["mozUnlockOrientation"]();else if(screen["msUnlockOrientation"])screen["msUnlockOrientation"]()}catch(err){}}_OnNavigate(e){const type=e["type"];if(type==="back")if(navigator["app"]&&navigator["app"]["backHistory"])navigator["app"]["backHistory"]();else window.history.back();else if(type==="forward")window.history.forward();else if(type==="reload")location.reload();else if(type=== "url"){const url=e["url"];const target=e["target"];const exportType=e["exportType"];if(self["cordova"]&&self["cordova"]["InAppBrowser"])self["cordova"]["InAppBrowser"]["open"](url,"_system");else if(exportType==="preview"||this._iRuntime.IsAnyWebView2Wrapper())window.open(url,"_blank");else if(!this._isConstructArcade)if(target===2)window.top.location=url;else if(target===1)window.parent.location=url;else window.location=url}else if(type==="new-window"){const url=e["url"];const tag=e["tag"];if(self["cordova"]&& self["cordova"]["InAppBrowser"])self["cordova"]["InAppBrowser"]["open"](url,"_system");else window.open(url,tag)}}_OnRequestFullscreen(e){if(this._iRuntime.IsAnyWebView2Wrapper()||this._exportType==="macos-wkwebview"){self.RuntimeInterface._SetWrapperIsFullscreenFlag(true);this._iRuntime._SendWrapperMessage({"type":"set-fullscreen","fullscreen":true})}else{const opts={"navigationUI":"auto"};const navUI=e["navUI"];if(navUI===1)opts["navigationUI"]="hide";else if(navUI===2)opts["navigationUI"]="show"; const elem=document.documentElement;let ret;if(elem["requestFullscreen"])ret=elem["requestFullscreen"](opts);else if(elem["mozRequestFullScreen"])ret=elem["mozRequestFullScreen"](opts);else if(elem["msRequestFullscreen"])ret=elem["msRequestFullscreen"](opts);else if(elem["webkitRequestFullScreen"])if(typeof Element["ALLOW_KEYBOARD_INPUT"]!=="undefined")ret=elem["webkitRequestFullScreen"](Element["ALLOW_KEYBOARD_INPUT"]);else ret=elem["webkitRequestFullScreen"]();if(ret instanceof Promise)ret.catch(noop)}}_OnExitFullscreen(){if(this._iRuntime.IsAnyWebView2Wrapper()|| this._exportType==="macos-wkwebview"){self.RuntimeInterface._SetWrapperIsFullscreenFlag(false);this._iRuntime._SendWrapperMessage({"type":"set-fullscreen","fullscreen":false})}else{let ret;if(document["exitFullscreen"])ret=document["exitFullscreen"]();else if(document["mozCancelFullScreen"])ret=document["mozCancelFullScreen"]();else if(document["msExitFullscreen"])ret=document["msExitFullscreen"]();else if(document["webkitCancelFullScreen"])ret=document["webkitCancelFullScreen"]();if(ret instanceof Promise)ret.catch(noop)}}_OnSetHash(e){location.hash=e["hash"]}_OnHashChange(){this.PostToRuntime("hashchange",{"location":location.toString()})}_OnSetDocumentCSSStyle(e){const prop=e["prop"];const value=e["value"];const selector=e["selector"];const isAll=e["is-all"];try{const arr=elemsForSelector(selector,isAll);for(const e of arr)if(prop.startsWith("--"))e.style.setProperty(prop,value);else e.style[prop]=value}catch(err){console.warn("[Browser] Failed to set style: ",err)}}_OnGetDocumentCSSStyle(e){const prop= e["prop"];const selector=e["selector"];try{const elem=document.querySelector(selector);if(elem){const computedStyle=window.getComputedStyle(elem);return{"isOk":true,"result":computedStyle.getPropertyValue(prop)}}else return{"isOk":false}}catch(err){console.warn("[Browser] Failed to get style: ",err);return{"isOk":false}}}_OnSetWindowSize(e){window.resizeTo(e["windowWidth"],e["windowHeight"])}_OnSetWindowPosition(e){window.moveTo(e["windowX"],e["windowY"])}};self.RuntimeInterface.AddDOMHandlerClass(HANDLER_CLASS)}; /* The buffer module from node.js, for the browser. @author Feross Aboukhadijeh <https://feross.org> @license MIT ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */ 'use strict';(function(f){if(typeof exports==="object"&&typeof module!=="undefined")module.exports=f();else if(typeof define==="function"&&define.amd)define([],f);else{var g;if(typeof window!=="undefined")g=window;else if(typeof global!=="undefined")g=global;else if(typeof self!=="undefined")g=self;else g=this;g.EBML=f()}})(function(){var define,module,exports;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0); if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a;}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:true})},{}],2:[function(require,module,exports){Object.defineProperty(exports,"__esModule", {value:true});var tools_1=require("./tools");var int64_buffer_1=require("int64-buffer");var tools=require("./tools");var schema=require("matroska/lib/schema");var byEbmlID=schema.byEbmlID;var State;(function(State){State[State["STATE_TAG"]=1]="STATE_TAG";State[State["STATE_SIZE"]=2]="STATE_SIZE";State[State["STATE_CONTENT"]=3]="STATE_CONTENT"})(State||(State={}));var EBMLDecoder=function(){function EBMLDecoder(){this._buffer=new tools_1.Buffer(0);this._tag_stack=[];this._state=State.STATE_TAG;this._cursor= 0;this._total=0;this._schema=byEbmlID;this._result=[]}EBMLDecoder.prototype.decode=function(chunk){this.readChunk(chunk);var diff=this._result;this._result=[];return diff};EBMLDecoder.prototype.readChunk=function(chunk){this._buffer=tools.concat([this._buffer,new tools_1.Buffer(chunk)]);while(this._cursor<this._buffer.length){if(this._state===State.STATE_TAG&&!this.readTag())break;if(this._state===State.STATE_SIZE&&!this.readSize())break;if(this._state===State.STATE_CONTENT&&!this.readContent())break}}; EBMLDecoder.prototype.getSchemaInfo=function(tagNum){return this._schema[tagNum]||{name:"unknown",level:-1,type:"unknown",description:"unknown"}};EBMLDecoder.prototype.readTag=function(){if(this._cursor>=this._buffer.length)return false;var tag=tools_1.readVint(this._buffer,this._cursor);if(tag==null)return false;var buf=this._buffer.slice(this._cursor,this._cursor+tag.length);var tagNum=buf.reduce(function(o,v,i,arr){return o+v*Math.pow(16,2*(arr.length-1-i))},0);var schema=this.getSchemaInfo(tagNum); var tagObj={EBML_ID:tagNum.toString(16),schema:schema,type:schema.type,name:schema.name,level:schema.level,tagStart:this._total,tagEnd:this._total+tag.length,sizeStart:this._total+tag.length,sizeEnd:null,dataStart:null,dataEnd:null,dataSize:null,data:null};this._tag_stack.push(tagObj);this._cursor+=tag.length;this._total+=tag.length;this._state=State.STATE_SIZE;return true};EBMLDecoder.prototype.readSize=function(){if(this._cursor>=this._buffer.length)return false;var size=tools_1.readVint(this._buffer, this._cursor);if(size==null)return false;var tagObj=this._tag_stack[this._tag_stack.length-1];tagObj.sizeEnd=tagObj.sizeStart+size.length;tagObj.dataStart=tagObj.sizeEnd;tagObj.dataSize=size.value;if(size.value===-1){tagObj.dataEnd=-1;if(tagObj.type==="m")tagObj.unknownSize=true}else tagObj.dataEnd=tagObj.sizeEnd+size.value;this._cursor+=size.length;this._total+=size.length;this._state=State.STATE_CONTENT;return true};EBMLDecoder.prototype.readContent=function(){var tagObj=this._tag_stack[this._tag_stack.length- 1];if(tagObj.type==="m"){tagObj.isEnd=false;this._result.push(tagObj);this._state=State.STATE_TAG;if(tagObj.dataSize===0){var elm=Object.assign({},tagObj,{isEnd:true});this._result.push(elm);this._tag_stack.pop()}return true}if(this._buffer.length<this._cursor+tagObj.dataSize)return false;var data=this._buffer.slice(this._cursor,this._cursor+tagObj.dataSize);this._buffer=this._buffer.slice(this._cursor+tagObj.dataSize);tagObj.data=data;switch(tagObj.type){case "u":tagObj.value=data.readUIntBE(0,data.length); break;case "i":tagObj.value=data.readIntBE(0,data.length);break;case "f":tagObj.value=tagObj.dataSize===4?data.readFloatBE(0):tagObj.dataSize===8?data.readDoubleBE(0):(console.warn("cannot read "+tagObj.dataSize+" octets float. failback to 0"),0);break;case "s":tagObj.value=data.toString("ascii");break;case "8":tagObj.value=data.toString("utf8");break;case "b":tagObj.value=data;break;case "d":tagObj.value=tools_1.convertEBMLDateToJSDate((new int64_buffer_1.Int64BE(data)).toNumber());break}if(tagObj.value=== null)throw new Error("unknown tag type:"+tagObj.type);this._result.push(tagObj);this._total+=tagObj.dataSize;this._state=State.STATE_TAG;this._cursor=0;this._tag_stack.pop();while(this._tag_stack.length>0){var topEle=this._tag_stack[this._tag_stack.length-1];if(topEle.dataEnd<0){this._tag_stack.pop();return true}if(this._total<topEle.dataEnd)break;if(topEle.type!=="m")throw new Error("parent element is not master element");var elm=Object.assign({},topEle,{isEnd:true});this._result.push(elm);this._tag_stack.pop()}return true}; return EBMLDecoder}();exports.default=EBMLDecoder},{"./tools":6,"int64-buffer":14,"matroska/lib/schema":15}],3:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:true});var tools=require("./tools");var tools_1=require("./tools");var schema=require("matroska/lib/schema");var byEbmlID=schema.byEbmlID;var EBMLEncoder=function(){function EBMLEncoder(){this._schema=byEbmlID;this._buffers=[];this._stack=[]}EBMLEncoder.prototype.encode=function(elms){var _this=this;return tools.concat(elms.reduce(function(lst, elm){return lst.concat(_this.encodeChunk(elm))},[])).buffer};EBMLEncoder.prototype.encodeChunk=function(elm){if(elm.type==="m")if(!elm.isEnd)this.startTag(elm);else this.endTag(elm);else{elm.data=tools_1.Buffer.from(elm.data);this.writeTag(elm)}return this.flush()};EBMLEncoder.prototype.flush=function(){var ret=this._buffers;this._buffers=[];return ret};EBMLEncoder.prototype.getSchemaInfo=function(tagName){var tagNums=Object.keys(this._schema).map(Number);for(var i=0;i<tagNums.length;i++){var tagNum= tagNums[i];if(this._schema[tagNum].name===tagName)return new tools_1.Buffer(tagNum.toString(16),"hex")}return null};EBMLEncoder.prototype.writeTag=function(elm){var tagName=elm.name;var tagId=this.getSchemaInfo(tagName);var tagData=elm.data;if(tagId==null)throw new Error("No schema entry found for "+tagName);var data=tools.encodeTag(tagId,tagData);if(this._stack.length>0){var last=this._stack[this._stack.length-1];last.children.push({tagId:tagId,elm:elm,children:[],data:data});return}this._buffers= this._buffers.concat(data);return};EBMLEncoder.prototype.startTag=function(elm){var tagName=elm.name;var tagId=this.getSchemaInfo(tagName);if(tagId==null)throw new Error("No schema entry found for "+tagName);if(elm.unknownSize){var data=tools.encodeTag(tagId,new tools_1.Buffer(0),elm.unknownSize);this._buffers=this._buffers.concat(data);return}var tag={tagId:tagId,elm:elm,children:[],data:null};if(this._stack.length>0)this._stack[this._stack.length-1].children.push(tag);this._stack.push(tag)};EBMLEncoder.prototype.endTag= function(elm){var tagName=elm.name;var tag=this._stack.pop();if(tag==null)throw new Error("EBML structure is broken");if(tag.elm.name!==elm.name)throw new Error("EBML structure is broken");var childTagDataBuffers=tag.children.reduce(function(lst,child){if(child.data===null)throw new Error("EBML structure is broken");return lst.concat(child.data)},[]);var childTagDataBuffer=tools.concat(childTagDataBuffers);if(tag.elm.type==="m")tag.data=tools.encodeTag(tag.tagId,childTagDataBuffer,tag.elm.unknownSize); else tag.data=tools.encodeTag(tag.tagId,childTagDataBuffer);if(this._stack.length<1)this._buffers=this._buffers.concat(tag.data)};return EBMLEncoder}();exports.default=EBMLEncoder},{"./tools":6,"matroska/lib/schema":15}],4:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p]};return extendStatics(d, b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();Object.defineProperty(exports,"__esModule",{value:true});var events_1=require("events");var tools=require("./tools");var EBMLReader=function(_super){__extends(EBMLReader,_super);function EBMLReader(){var _this=_super.call(this)||this;_this.logGroup="";_this.hasLoggingStarted=false;_this.metadataloaded=false;_this.chunks=[];_this.stack=[];_this.segmentOffset= 0;_this.last2SimpleBlockVideoTrackTimecode=[0,0];_this.last2SimpleBlockAudioTrackTimecode=[0,0];_this.lastClusterTimecode=0;_this.lastClusterPosition=0;_this.timecodeScale=1E6;_this.metadataSize=0;_this.metadatas=[];_this.cues=[];_this.firstVideoBlockRead=false;_this.firstAudioBlockRead=false;_this.currentTrack={TrackNumber:-1,TrackType:-1,DefaultDuration:null,CodecDelay:null};_this.trackTypes=[];_this.trackDefaultDuration=[];_this.trackCodecDelay=[];_this.trackInfo={type:"nothing"};_this.ended=false; _this.logging=false;_this.use_duration_every_simpleblock=false;_this.use_webp=false;_this.use_segment_info=true;_this.drop_default_duration=true;return _this}EBMLReader.prototype.stop=function(){this.ended=true;this.emit_segment_info();while(this.stack.length){this.stack.pop();if(this.logging)console.groupEnd()}if(this.logging&&this.hasLoggingStarted&&this.logGroup)console.groupEnd()};EBMLReader.prototype.emit_segment_info=function(){var data=this.chunks;this.chunks=[];if(!this.metadataloaded){this.metadataloaded= true;this.metadatas=data;var videoTrackNum=this.trackTypes.indexOf(1);var audioTrackNum=this.trackTypes.indexOf(2);this.trackInfo=videoTrackNum>=0&&audioTrackNum>=0?{type:"both",trackNumber:videoTrackNum}:videoTrackNum>=0?{type:"video",trackNumber:videoTrackNum}:audioTrackNum>=0?{type:"audio",trackNumber:audioTrackNum}:{type:"nothing"};if(!this.use_segment_info)return;this.emit("metadata",{data:data,metadataSize:this.metadataSize})}else{if(!this.use_segment_info)return;var timecode=this.lastClusterTimecode; var duration=this.duration;var timecodeScale=this.timecodeScale;this.emit("cluster",{timecode:timecode,data:data});this.emit("duration",{timecodeScale:timecodeScale,duration:duration})}};EBMLReader.prototype.read=function(elm){var _this=this;var drop=false;if(this.ended)return;if(elm.type==="m")if(elm.isEnd)this.stack.pop();else{var parent_1=this.stack[this.stack.length-1];if(parent_1!=null&&parent_1.level>=elm.level){this.stack.pop();if(this.logging)console.groupEnd();parent_1.dataEnd=elm.dataEnd; parent_1.dataSize=elm.dataEnd-parent_1.dataStart;parent_1.unknownSize=false;var o=Object.assign({},parent_1,{name:parent_1.name,type:parent_1.type,isEnd:true});this.chunks.push(o)}this.stack.push(elm)}if(elm.type==="m"&&elm.name=="Segment"){if(this.segmentOffset!=0)console.warn("Multiple segments detected!");this.segmentOffset=elm.dataStart;this.emit("segment_offset",this.segmentOffset)}else if(elm.type==="b"&&elm.name==="SimpleBlock"){var _a=tools.ebmlBlock(elm.data),timecode=_a.timecode,trackNumber= _a.trackNumber,frames_1=_a.frames;if(this.trackTypes[trackNumber]===1){if(!this.firstVideoBlockRead){this.firstVideoBlockRead=true;if(this.trackInfo.type==="both"||this.trackInfo.type==="video"){var CueTime=this.lastClusterTimecode+timecode;this.cues.push({CueTrack:trackNumber,CueClusterPosition:this.lastClusterPosition,CueTime:CueTime});this.emit("cue_info",{CueTrack:trackNumber,CueClusterPosition:this.lastClusterPosition,CueTime:this.lastClusterTimecode});this.emit("cue",{CueTrack:trackNumber,CueClusterPosition:this.lastClusterPosition, CueTime:CueTime})}}this.last2SimpleBlockVideoTrackTimecode=[this.last2SimpleBlockVideoTrackTimecode[1],timecode]}else if(this.trackTypes[trackNumber]===2){if(!this.firstAudioBlockRead){this.firstAudioBlockRead=true;if(this.trackInfo.type==="audio"){var CueTime=this.lastClusterTimecode+timecode;this.cues.push({CueTrack:trackNumber,CueClusterPosition:this.lastClusterPosition,CueTime:CueTime});this.emit("cue_info",{CueTrack:trackNumber,CueClusterPosition:this.lastClusterPosition,CueTime:this.lastClusterTimecode}); this.emit("cue",{CueTrack:trackNumber,CueClusterPosition:this.lastClusterPosition,CueTime:CueTime})}}this.last2SimpleBlockAudioTrackTimecode=[this.last2SimpleBlockAudioTrackTimecode[1],timecode]}if(this.use_duration_every_simpleblock)this.emit("duration",{timecodeScale:this.timecodeScale,duration:this.duration});if(this.use_webp)frames_1.forEach(function(frame){var startcode=frame.slice(3,6).toString("hex");if(startcode!=="9d012a")return;var webpBuf=tools.VP8BitStreamToRiffWebPBuffer(frame);var webp= new Blob([webpBuf],{type:"image/webp"});var currentTime=_this.duration;_this.emit("webp",{currentTime:currentTime,webp:webp})})}else if(elm.type==="m"&&elm.name==="Cluster"&&elm.isEnd===false){this.firstVideoBlockRead=false;this.firstAudioBlockRead=false;this.emit_segment_info();this.emit("cluster_ptr",elm.tagStart);this.lastClusterPosition=elm.tagStart}else if(elm.type==="u"&&elm.name==="Timecode")this.lastClusterTimecode=elm.value;else if(elm.type==="u"&&elm.name==="TimecodeScale")this.timecodeScale= elm.value;else if(elm.type==="m"&&elm.name==="TrackEntry")if(elm.isEnd){this.trackTypes[this.currentTrack.TrackNumber]=this.currentTrack.TrackType;this.trackDefaultDuration[this.currentTrack.TrackNumber]=this.currentTrack.DefaultDuration;this.trackCodecDelay[this.currentTrack.TrackNumber]=this.currentTrack.CodecDelay}else this.currentTrack={TrackNumber:-1,TrackType:-1,DefaultDuration:null,CodecDelay:null};else if(elm.type==="u"&&elm.name==="TrackType")this.currentTrack.TrackType=elm.value;else if(elm.type=== "u"&&elm.name==="TrackNumber")this.currentTrack.TrackNumber=elm.value;else if(elm.type==="u"&&elm.name==="CodecDelay")this.currentTrack.CodecDelay=elm.value;else if(elm.type==="u"&&elm.name==="DefaultDuration")if(this.drop_default_duration){console.warn("DefaultDuration detected!, remove it");drop=true}else this.currentTrack.DefaultDuration=elm.value;else if(elm.name==="unknown")console.warn(elm);if(!this.metadataloaded&&elm.dataEnd>0)this.metadataSize=elm.dataEnd;if(!drop)this.chunks.push(elm);if(this.logging)this.put(elm)}; Object.defineProperty(EBMLReader.prototype,"duration",{get:function(){if(this.trackInfo.type==="nothing"){console.warn("no video, no audio track");return 0}var defaultDuration=0;var codecDelay=0;var lastTimecode=0;var _defaultDuration=this.trackDefaultDuration[this.trackInfo.trackNumber];if(typeof _defaultDuration==="number")defaultDuration=_defaultDuration;else if(this.trackInfo.type==="both")if(this.last2SimpleBlockAudioTrackTimecode[1]>this.last2SimpleBlockVideoTrackTimecode[1]){defaultDuration= (this.last2SimpleBlockAudioTrackTimecode[1]-this.last2SimpleBlockAudioTrackTimecode[0])*this.timecodeScale;var delay=this.trackCodecDelay[this.trackTypes.indexOf(2)];if(typeof delay==="number")codecDelay=delay;lastTimecode=this.last2SimpleBlockAudioTrackTimecode[1]}else{defaultDuration=(this.last2SimpleBlockVideoTrackTimecode[1]-this.last2SimpleBlockVideoTrackTimecode[0])*this.timecodeScale;var delay=this.trackCodecDelay[this.trackTypes.indexOf(1)];if(typeof delay==="number")codecDelay=delay;lastTimecode= this.last2SimpleBlockVideoTrackTimecode[1]}else if(this.trackInfo.type==="video"){defaultDuration=(this.last2SimpleBlockVideoTrackTimecode[1]-this.last2SimpleBlockVideoTrackTimecode[0])*this.timecodeScale;var delay=this.trackCodecDelay[this.trackInfo.trackNumber];if(typeof delay==="number")codecDelay=delay;lastTimecode=this.last2SimpleBlockVideoTrackTimecode[1]}else if(this.trackInfo.type==="audio"){defaultDuration=(this.last2SimpleBlockAudioTrackTimecode[1]-this.last2SimpleBlockAudioTrackTimecode[0])* this.timecodeScale;var delay=this.trackCodecDelay[this.trackInfo.trackNumber];if(typeof delay==="number")codecDelay=delay;lastTimecode=this.last2SimpleBlockAudioTrackTimecode[1]}var duration_nanosec=(this.lastClusterTimecode+lastTimecode)*this.timecodeScale+defaultDuration-codecDelay;var duration=duration_nanosec/this.timecodeScale;return Math.floor(duration)},enumerable:false,configurable:true});EBMLReader.prototype.addListener=function(event,listener){return _super.prototype.addListener.call(this, event,listener)};EBMLReader.prototype.put=function(elm){if(!this.hasLoggingStarted){this.hasLoggingStarted=true;if(this.logging&&this.logGroup)console.groupCollapsed(this.logGroup)}if(elm.type==="m")if(elm.isEnd)console.groupEnd();else console.group(elm.name+":"+elm.tagStart);else if(elm.type==="b")console.log(elm.name,elm.type);else console.log(elm.name,elm.tagStart,elm.type,elm.value)};return EBMLReader}(events_1.EventEmitter);exports.default=EBMLReader},{"./tools":6,"events":19}],5:[function(require, module,exports){var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!exports.hasOwnProperty(p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});exports.tools=exports.Reader=exports.Encoder= exports.Decoder=exports.version=void 0;__exportStar(require("./EBML"),exports);var EBMLDecoder_1=require("./EBMLDecoder");exports.Decoder=EBMLDecoder_1.default;var EBMLEncoder_1=require("./EBMLEncoder");exports.Encoder=EBMLEncoder_1.default;var EBMLReader_1=require("./EBMLReader");exports.Reader=EBMLReader_1.default;var tools=require("./tools");exports.tools=tools;var version=require("../package.json").version;exports.version=version},{"../package.json":16,"./EBML":1,"./EBMLDecoder":2,"./EBMLEncoder":3, "./EBMLReader":4,"./tools":6}],6:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:true});exports.convertEBMLDateToJSDate=exports.createFloatBuffer=exports.createIntBuffer=exports.createUIntBuffer=exports.encodeValueToBuffer=exports.concat=exports.putRefinedMetaData=exports.extractElement=exports.removeElement=exports.makeMetadataSeekable=exports.createRIFFChunk=exports.VP8BitStreamToRiffWebPBuffer=exports.WebPBlockFilter=exports.WebPFrameFilter=exports.encodeTag= exports.readBlock=exports.ebmlBlock=exports.writeVint=exports.readVint=exports.Buffer=void 0;var int64_buffer_1=require("int64-buffer");var EBMLEncoder_1=require("./EBMLEncoder");var _Buffer=require("buffer/");var _tools=require("ebml/lib/ebml/tools");var _block=require("ebml-block");exports.Buffer=_Buffer.Buffer;exports.readVint=_tools.readVint;exports.writeVint=_tools.writeVint;exports.ebmlBlock=_block;function readBlock(buf){return exports.ebmlBlock(new exports.Buffer(buf))}exports.readBlock=readBlock; function encodeTag(tagId,tagData,unknownSize){if(unknownSize===void 0)unknownSize=false;return concat([tagId,unknownSize?new exports.Buffer("01ffffffffffffff","hex"):exports.writeVint(tagData.length),tagData])}exports.encodeTag=encodeTag;function WebPFrameFilter(elms){return WebPBlockFilter(elms).reduce(function(lst,elm){var o=exports.ebmlBlock(elm.data);return o.frames.reduce(function(lst,frame){var webpBuf=VP8BitStreamToRiffWebPBuffer(frame);var webp=new Blob([webpBuf],{type:"image/webp"});return lst.concat(webp)}, lst)},[])}exports.WebPFrameFilter=WebPFrameFilter;function WebPBlockFilter(elms){return elms.reduce(function(lst,elm){if(elm.type!=="b")return lst;if(elm.name!=="SimpleBlock")return lst;var o=exports.ebmlBlock(elm.data);var hasWebP=o.frames.some(function(frame){var startcode=frame.slice(3,6).toString("hex");return startcode==="9d012a"});if(!hasWebP)return lst;return lst.concat(elm)},[])}exports.WebPBlockFilter=WebPBlockFilter;function VP8BitStreamToRiffWebPBuffer(frame){var VP8Chunk=createRIFFChunk("VP8 ", frame);var WebPChunk=concat([new exports.Buffer("WEBP","ascii"),VP8Chunk]);return createRIFFChunk("RIFF",WebPChunk)}exports.VP8BitStreamToRiffWebPBuffer=VP8BitStreamToRiffWebPBuffer;function createRIFFChunk(FourCC,chunk){var chunkSize=new exports.Buffer(4);chunkSize.writeUInt32LE(chunk.byteLength,0);return concat([new exports.Buffer(FourCC.substr(0,4),"ascii"),chunkSize,chunk,new exports.Buffer(chunk.byteLength%2===0?0:1)])}exports.createRIFFChunk=createRIFFChunk;function makeMetadataSeekable(originalMetadata, duration,cuesInfo){var header=extractElement("EBML",originalMetadata);var headerSize=encodedSizeOfEbml(header);var segmentContentStartPos=headerSize+12;var originalMetadataSize=originalMetadata[originalMetadata.length-1].dataEnd-segmentContentStartPos;var info=extractElement("Info",originalMetadata);removeElement("Duration",info);info.splice(1,0,{name:"Duration",type:"f",data:createFloatBuffer(duration,8)});var infoSize=encodedSizeOfEbml(info);var tracks=extractElement("Tracks",originalMetadata); var tracksSize=encodedSizeOfEbml(tracks);var seekHeadSize=47;var seekHead=[];var cuesSize=5+cuesInfo.length*15;var cues=[];var lastSizeDifference=-1;var maxIterations=10;var _loop_1=function(i){var infoStart=seekHeadSize;var tracksStart=infoStart+infoSize;var cuesStart=tracksStart+tracksSize;var newMetadataSize=cuesStart+cuesSize;var sizeDifference=newMetadataSize-originalMetadataSize;seekHead=[];seekHead.push({name:"SeekHead",type:"m",isEnd:false});seekHead.push({name:"Seek",type:"m",isEnd:false}); seekHead.push({name:"SeekID",type:"b",data:new exports.Buffer([21,73,169,102])});seekHead.push({name:"SeekPosition",type:"u",data:createUIntBuffer(infoStart)});seekHead.push({name:"Seek",type:"m",isEnd:true});seekHead.push({name:"Seek",type:"m",isEnd:false});seekHead.push({name:"SeekID",type:"b",data:new exports.Buffer([22,84,174,107])});seekHead.push({name:"SeekPosition",type:"u",data:createUIntBuffer(tracksStart)});seekHead.push({name:"Seek",type:"m",isEnd:true});seekHead.push({name:"Seek",type:"m", isEnd:false});seekHead.push({name:"SeekID",type:"b",data:new exports.Buffer([28,83,187,107])});seekHead.push({name:"SeekPosition",type:"u",data:createUIntBuffer(cuesStart)});seekHead.push({name:"Seek",type:"m",isEnd:true});seekHead.push({name:"SeekHead",type:"m",isEnd:true});seekHeadSize=encodedSizeOfEbml(seekHead);cues=[];cues.push({name:"Cues",type:"m",isEnd:false});cuesInfo.forEach(function(_a){var CueTrack=_a.CueTrack,CueClusterPosition=_a.CueClusterPosition,CueTime=_a.CueTime;cues.push({name:"CuePoint", type:"m",isEnd:false});cues.push({name:"CueTime",type:"u",data:createUIntBuffer(CueTime)});cues.push({name:"CueTrackPositions",type:"m",isEnd:false});cues.push({name:"CueTrack",type:"u",data:createUIntBuffer(CueTrack)});CueClusterPosition-=segmentContentStartPos;CueClusterPosition+=sizeDifference;cues.push({name:"CueClusterPosition",type:"u",data:createUIntBuffer(CueClusterPosition)});cues.push({name:"CueTrackPositions",type:"m",isEnd:true});cues.push({name:"CuePoint",type:"m",isEnd:true})});cues.push({name:"Cues", type:"m",isEnd:true});cuesSize=encodedSizeOfEbml(cues);if(lastSizeDifference!==sizeDifference){lastSizeDifference=sizeDifference;if(i===maxIterations-1)throw new Error("Failed to converge to a stable metadata size");}else return"break"};for(var i=0;i<maxIterations;i++){var state_1=_loop_1(i);if(state_1==="break")break}var finalMetadata=[].concat.apply([],[header,{name:"Segment",type:"m",isEnd:false,unknownSize:true},seekHead,info,tracks,cues]);var result=(new EBMLEncoder_1.default).encode(finalMetadata); return result}exports.makeMetadataSeekable=makeMetadataSeekable;function removeElement(idName,metadata){var result=[];var start=-1;for(var i=0;i<metadata.length;i++){var element=metadata[i];if(element.name===idName)if(element.type==="m")if(!element.isEnd)start=i;else{if(start==-1)throw new Error("Detected "+idName+" closing element before finding the start");metadata.splice(start,i-start+1);return}else{metadata.splice(i,1);return}}}exports.removeElement=removeElement;function extractElement(idName, metadata){var result=[];var start=-1;for(var i=0;i<metadata.length;i++){var element=metadata[i];if(element.name===idName)if(element.type==="m")if(!element.isEnd)start=i;else{if(start==-1)throw new Error("Detected "+idName+" closing element before finding the start");result=metadata.slice(start,i+1);break}else{result.push(metadata[i]);break}}return result}exports.extractElement=extractElement;function putRefinedMetaData(metadata,info){if(Array.isArray(info.cueInfos)&&!Array.isArray(info.cues)){console.warn("putRefinedMetaData: info.cueInfos property is deprecated. please use info.cues"); info.cues=info.cueInfos}var ebml=[];var payload=[];for(var i_1=0;i_1<metadata.length;i_1++){var elm=metadata[i_1];if(elm.type==="m"&&elm.name==="Segment"){ebml=metadata.slice(0,i_1);payload=metadata.slice(i_1);if(elm.unknownSize){payload.shift();break}throw new Error("this metadata is not streaming webm file");}}if(!(payload[payload.length-1].dataEnd>0))throw new Error("metadata dataEnd has wrong number");var originalPayloadOffsetEnd=payload[payload.length-1].dataEnd;var ebmlSize=ebml[ebml.length- 1].dataEnd;var refinedEBMLSize=(new EBMLEncoder_1.default).encode(ebml).byteLength;var offsetDiff=refinedEBMLSize-ebmlSize;var payloadSize=originalPayloadOffsetEnd-payload[0].tagStart;var segmentSize=payload[0].tagStart-ebmlSize;var segmentOffset=payload[0].tagStart;var segmentTagBuf=new exports.Buffer([24,83,128,103]);var segmentSizeBuf=new exports.Buffer("01ffffffffffffff","hex");var _segmentSize=segmentTagBuf.byteLength+segmentSizeBuf.byteLength;var newPayloadSize=payloadSize;var i;for(i=1;i<20;i++){var newPayloadOffsetEnd= ebmlSize+_segmentSize+newPayloadSize;var offsetEndDiff=newPayloadOffsetEnd-originalPayloadOffsetEnd;var sizeDiff=offsetDiff+offsetEndDiff;var refined=refineMetadata(payload,sizeDiff,info);var newNewRefinedSize=(new EBMLEncoder_1.default).encode(refined).byteLength;if(newNewRefinedSize===newPayloadSize)return(new EBMLEncoder_1.default).encode([].concat(ebml,[{type:"m",name:"Segment",isEnd:false,unknownSize:true}],refined));newPayloadSize=newNewRefinedSize}throw new Error("unable to refine metadata, stable size could not be found in "+ i+" iterations!");}exports.putRefinedMetaData=putRefinedMetaData;function encodedSizeOfEbml(refinedMetaData){var encorder=new EBMLEncoder_1.default;return refinedMetaData.reduce(function(lst,elm){return lst.concat(encorder.encode([elm]))},[]).reduce(function(o,buf){return o+buf.byteLength},0)}function refineMetadata(mesetadata,sizeDiff,info){var duration=info.duration,clusterPtrs=info.clusterPtrs,cues=info.cues;var _metadata=mesetadata.slice(0);if(typeof duration==="number"){var overwrited_1=false; _metadata.forEach(function(elm){if(elm.type==="f"&&elm.name==="Duration"){overwrited_1=true;elm.data=createFloatBuffer(duration,8)}});if(!overwrited_1)insertTag(_metadata,"Info",[{name:"Duration",type:"f",data:createFloatBuffer(duration,8)}])}if(Array.isArray(cues))insertTag(_metadata,"Cues",create_cue(cues,sizeDiff));var seekhead_children=[];if(Array.isArray(clusterPtrs)){console.warn("append cluster pointers to seekhead is deprecated. please use cues");seekhead_children=create_seek_from_clusters(clusterPtrs, sizeDiff)}insertTag(_metadata,"SeekHead",seekhead_children,true);return _metadata}function create_seekhead(metadata,sizeDiff){var seeks=[];["Info","Tracks","Cues"].forEach(function(tagName){var tagStarts=metadata.filter(function(elm){return elm.type==="m"&&elm.name===tagName&&elm.isEnd===false}).map(function(elm){return elm["tagStart"]});var tagStart=tagStarts[0];if(typeof tagStart!=="number")return;seeks.push({name:"Seek",type:"m",isEnd:false});switch(tagName){case "Info":seeks.push({name:"SeekID", type:"b",data:new exports.Buffer([21,73,169,102])});break;case "Tracks":seeks.push({name:"SeekID",type:"b",data:new exports.Buffer([22,84,174,107])});break;case "Cues":seeks.push({name:"SeekID",type:"b",data:new exports.Buffer([28,83,187,107])});break}seeks.push({name:"SeekPosition",type:"u",data:createUIntBuffer(tagStart+sizeDiff)});seeks.push({name:"Seek",type:"m",isEnd:true})});return seeks}function create_seek_from_clusters(clusterPtrs,sizeDiff){var seeks=[];clusterPtrs.forEach(function(start){seeks.push({name:"Seek", type:"m",isEnd:false});seeks.push({name:"SeekID",type:"b",data:new exports.Buffer([31,67,182,117])});seeks.push({name:"SeekPosition",type:"u",data:createUIntBuffer(start+sizeDiff)});seeks.push({name:"Seek",type:"m",isEnd:true})});return seeks}function create_cue(cueInfos,sizeDiff){var cues=[];cueInfos.forEach(function(_a){var CueTrack=_a.CueTrack,CueClusterPosition=_a.CueClusterPosition,CueTime=_a.CueTime;cues.push({name:"CuePoint",type:"m",isEnd:false});cues.push({name:"CueTime",type:"u",data:createUIntBuffer(CueTime)}); cues.push({name:"CueTrackPositions",type:"m",isEnd:false});cues.push({name:"CueTrack",type:"u",data:createUIntBuffer(CueTrack)});cues.push({name:"CueClusterPosition",type:"u",data:createUIntBuffer(CueClusterPosition+sizeDiff)});cues.push({name:"CueTrackPositions",type:"m",isEnd:true});cues.push({name:"CuePoint",type:"m",isEnd:true})});return cues}function insertTag(_metadata,tagName,children,insertHead){if(insertHead===void 0)insertHead=false;var idx=-1;for(var i=0;i<_metadata.length;i++){var elm= _metadata[i];if(elm.type==="m"&&elm.name===tagName&&elm.isEnd===false){idx=i;break}}if(idx>=0)Array.prototype.splice.apply(_metadata,[idx+1,0].concat(children));else if(insertHead)[].concat([{name:tagName,type:"m",isEnd:false}],children,[{name:tagName,type:"m",isEnd:true}]).reverse().forEach(function(elm){_metadata.unshift(elm)});else{_metadata.push({name:tagName,type:"m",isEnd:false});children.forEach(function(elm){_metadata.push(elm)});_metadata.push({name:tagName,type:"m",isEnd:true})}}function concat(list){return exports.Buffer.concat(list)} exports.concat=concat;function encodeValueToBuffer(elm){var data=new exports.Buffer(0);if(elm.type==="m")return elm;switch(elm.type){case "u":data=createUIntBuffer(elm.value);break;case "i":data=createIntBuffer(elm.value);break;case "f":data=createFloatBuffer(elm.value);break;case "s":data=new exports.Buffer(elm.value,"ascii");break;case "8":data=new exports.Buffer(elm.value,"utf8");break;case "b":data=elm.value;break;case "d":data=(new int64_buffer_1.Int64BE(elm.value.getTime().toString())).toBuffer(); break}return Object.assign({},elm,{data:data})}exports.encodeValueToBuffer=encodeValueToBuffer;function createUIntBuffer(value){var bytes=1;for(;value>=Math.pow(2,8*bytes);bytes++);if(bytes>=7){console.warn("7bit or more bigger uint not supported.");return(new int64_buffer_1.Uint64BE(value)).toBuffer()}var data=new exports.Buffer(bytes);data.writeUIntBE(value,0,bytes);return data}exports.createUIntBuffer=createUIntBuffer;function createIntBuffer(value){var bytes=1;for(;value>=Math.pow(2,8*bytes);bytes++); if(bytes>=7){console.warn("7bit or more bigger uint not supported.");return(new int64_buffer_1.Int64BE(value)).toBuffer()}var data=new exports.Buffer(bytes);data.writeIntBE(value,0,bytes);return data}exports.createIntBuffer=createIntBuffer;function createFloatBuffer(value,bytes){if(bytes===void 0)bytes=8;if(bytes===8){var data=new exports.Buffer(8);data.writeDoubleBE(value,0);return data}else if(bytes===4){var data=new exports.Buffer(4);data.writeFloatBE(value,0);return data}else throw new Error("float type bits must 4bytes or 8bytes"); }exports.createFloatBuffer=createFloatBuffer;function convertEBMLDateToJSDate(int64str){if(int64str instanceof Date)return int64str;return new Date((new Date("2001-01-01T00:00:00.000Z")).getTime()+Number(int64str)/1E3/1E3)}exports.convertEBMLDateToJSDate=convertEBMLDateToJSDate},{"./EBMLEncoder":3,"buffer/":8,"ebml-block":9,"ebml/lib/ebml/tools":12,"int64-buffer":14}],7:[function(require,module,exports){exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray; var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i<len;++i){lookup[i]=code[i];revLookup[code.charCodeAt(i)]=i}revLookup["-".charCodeAt(0)]=62;revLookup["_".charCodeAt(0)]=63;function getLens(b64){var len=b64.length;if(len%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");if(validLen===-1)validLen=len;var placeHoldersLen= validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;var len= placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i<len;i+=4){tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)];arr[curByte++]=tmp>>16&255;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&255}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+ 2)]>>2;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;i<end;i+=3){tmp=(uint8[i]<<16&16711680)+(uint8[i+1]<<8&65280)+(uint8[i+2]&255);output.push(tripletToBase64(tmp))}return output.join("")}function fromByteArray(uint8){var tmp;var len=uint8.length;var extraBytes=len%3;var parts=[];var maxChunkLength=16383; for(var i=0,len2=len-extraBytes;i<len2;i+=maxChunkLength)parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength));if(extraBytes===1){tmp=uint8[len-1];parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")}return parts.join("")}},{}],8:[function(require,module,exports){(function(Buffer){(function(){var base64=require("base64-js");var ieee754=require("ieee754"); var customInspectSymbol=typeof Symbol==="function"&&typeof Symbol["for"]==="function"?Symbol["for"]("nodejs.util.inspect.custom"):null;exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;var K_MAX_LENGTH=2147483647;exports.kMaxLength=K_MAX_LENGTH;Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport();if(!Buffer.TYPED_ARRAY_SUPPORT&&typeof console!=="undefined"&&typeof console.error==="function")console.error("This browser lacks typed array (Uint8Array) support which is required by "+ "`buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function typedArraySupport(){try{var arr=new Uint8Array(1);var proto={foo:function(){return 42}};Object.setPrototypeOf(proto,Uint8Array.prototype);Object.setPrototypeOf(arr,proto);return arr.foo()===42}catch(e){return false}}Object.defineProperty(Buffer.prototype,"parent",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.buffer}});Object.defineProperty(Buffer.prototype,"offset",{enumerable:true, get:function(){if(!Buffer.isBuffer(this))return undefined;return this.byteOffset}});function createBuffer(length){if(length>K_MAX_LENGTH)throw new RangeError('The value "'+length+'" is invalid for option "size"');var buf=new Uint8Array(length);Object.setPrototypeOf(buf,Buffer.prototype);return buf}function Buffer(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string")throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(arg)}return from(arg, encodingOrOffset,length)}Buffer.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="string")return fromString(value,encodingOrOffset);if(ArrayBuffer.isView(value))return fromArrayView(value);if(value==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value);if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer))return fromArrayBuffer(value,encodingOrOffset, length);if(typeof SharedArrayBuffer!=="undefined"&&(isInstance(value,SharedArrayBuffer)||value&&isInstance(value.buffer,SharedArrayBuffer)))return fromArrayBuffer(value,encodingOrOffset,length);if(typeof value==="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var valueOf=value.valueOf&&value.valueOf();if(valueOf!=null&&valueOf!==value)return Buffer.from(valueOf,encodingOrOffset,length);var b=fromObject(value);if(b)return b;if(typeof Symbol!=="undefined"&& Symbol.toPrimitive!=null&&typeof value[Symbol.toPrimitive]==="function")return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value);}Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Object.setPrototypeOf(Buffer.prototype,Uint8Array.prototype);Object.setPrototypeOf(Buffer,Uint8Array); function assertSize(size){if(typeof size!=="number")throw new TypeError('"size" argument must be of type number');else if(size<0)throw new RangeError('The value "'+size+'" is invalid for option "size"');}function alloc(size,fill,encoding){assertSize(size);if(size<=0)return createBuffer(size);if(fill!==undefined)return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill);return createBuffer(size)}Buffer.alloc=function(size,fill,encoding){return alloc(size, fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer.allocUnsafe=function(size){return allocUnsafe(size)};Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding==="")encoding="utf8";if(!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string, encoding);if(actual!==length)buf=buf.slice(0,actual);return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i<length;i+=1)buf[i]=array[i]&255;return buf}function fromArrayView(arrayView){if(isInstance(arrayView,Uint8Array)){var copy=new Uint8Array(arrayView);return fromArrayBuffer(copy.buffer,copy.byteOffset,copy.byteLength)}return fromArrayLike(arrayView)}function fromArrayBuffer(array,byteOffset,length){if(byteOffset< 0||array.byteLength<byteOffset)throw new RangeError('"offset" is outside of buffer bounds');if(array.byteLength<byteOffset+(length||0))throw new RangeError('"length" is outside of buffer bounds');var buf;if(byteOffset===undefined&&length===undefined)buf=new Uint8Array(array);else if(length===undefined)buf=new Uint8Array(array,byteOffset);else buf=new Uint8Array(array,byteOffset,length);Object.setPrototypeOf(buf,Buffer.prototype);return buf}function fromObject(obj){if(Buffer.isBuffer(obj)){var len= checked(obj.length)|0;var buf=createBuffer(len);if(buf.length===0)return buf;obj.copy(buf,0,0,len);return buf}if(obj.length!==undefined){if(typeof obj.length!=="number"||numberIsNaN(obj.length))return createBuffer(0);return fromArrayLike(obj)}if(obj.type==="Buffer"&&Array.isArray(obj.data))return fromArrayLike(obj.data)}function checked(length){if(length>=K_MAX_LENGTH)throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+K_MAX_LENGTH.toString(16)+" bytes");return length| 0}function SlowBuffer(length){if(+length!=length)length=0;return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true&&b!==Buffer.prototype};Buffer.compare=function compare(a,b){if(isInstance(a,Uint8Array))a=Buffer.from(a,a.offset,a.byteLength);if(isInstance(b,Uint8Array))b=Buffer.from(b,b.offset,b.byteLength);if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(a===b)return 0; var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len;++i)if(a[i]!==b[i]){x=a[i];y=b[i];break}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function isEncoding(encoding){switch(String(encoding).toLowerCase()){case "hex":case "utf8":case "utf-8":case "ascii":case "latin1":case "binary":case "base64":case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return true;default:return false}};Buffer.concat=function concat(list,length){if(!Array.isArray(list))throw new TypeError('"list" argument must be an Array of Buffers'); if(list.length===0)return Buffer.alloc(0);var i;if(length===undefined){length=0;for(i=0;i<list.length;++i)length+=list[i].length}var buffer=Buffer.allocUnsafe(length);var pos=0;for(i=0;i<list.length;++i){var buf=list[i];if(isInstance(buf,Uint8Array))if(pos+buf.length>buffer.length)Buffer.from(buf).copy(buffer,pos);else Uint8Array.prototype.set.call(buffer,buf,pos);else if(!Buffer.isBuffer(buf))throw new TypeError('"list" argument must be an Array of Buffers');else buf.copy(buffer,pos);pos+=buf.length}return buffer}; function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer))return string.byteLength;if(typeof string!=="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. '+"Received type "+typeof string);var len=string.length;var mustMatch=arguments.length>2&&arguments[2]===true;if(!mustMatch&&len===0)return 0;var loweredCase=false;for(;;)switch(encoding){case "ascii":case "latin1":case "binary":return len; case "utf8":case "utf-8":return utf8ToBytes(string).length;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return len*2;case "hex":return len>>>1;case "base64":return base64ToBytes(string).length;default:if(loweredCase)return mustMatch?-1:utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0)start=0;if(start>this.length)return"";if(end===undefined|| end>this.length)end=this.length;if(end<=0)return"";end>>>=0;start>>>=0;if(end<=start)return"";if(!encoding)encoding="utf8";while(true)switch(encoding){case "hex":return hexSlice(this,start,end);case "utf8":case "utf-8":return utf8Slice(this,start,end);case "ascii":return asciiSlice(this,start,end);case "latin1":case "binary":return latin1Slice(this,start,end);case "base64":return base64Slice(this,start,end);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return utf16leSlice(this,start,end); default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var i=0;i<len;i+=2)swap(this,i,i+1);return this};Buffer.prototype.swap32=function swap32(){var len=this.length;if(len%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits"); for(var i=0;i<len;i+=4){swap(this,i,i+3);swap(this,i+1,i+2)}return this};Buffer.prototype.swap64=function swap64(){var len=this.length;if(len%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var i=0;i<len;i+=8){swap(this,i,i+7);swap(this,i+1,i+6);swap(this,i+2,i+5);swap(this,i+3,i+4)}return this};Buffer.prototype.toString=function toString(){var length=this.length;if(length===0)return"";if(arguments.length===0)return utf8Slice(this,0,length);return slowToString.apply(this, arguments)};Buffer.prototype.toLocaleString=Buffer.prototype.toString;Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return true;return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function inspect(){var str="";var max=exports.INSPECT_MAX_BYTES;str=this.toString("hex",0,max).replace(/(.{2})/g,"$1 ").trim();if(this.length>max)str+=" ... ";return"<Buffer "+str+">"};if(customInspectSymbol)Buffer.prototype[customInspectSymbol]= Buffer.prototype.inspect;Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array))target=Buffer.from(target,target.offset,target.byteLength);if(!Buffer.isBuffer(target))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. '+"Received type "+typeof target);if(start===undefined)start=0;if(end===undefined)end=target?target.length:0;if(thisStart===undefined)thisStart=0;if(thisEnd===undefined)thisEnd=this.length;if(start< 0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i<len;++i)if(thisCopy[i]!==targetCopy[i]){x=thisCopy[i];y=targetCopy[i];break}if(x< y)return-1;if(y<x)return 1;return 0};function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(buffer.length===0)return-1;if(typeof byteOffset==="string"){encoding=byteOffset;byteOffset=0}else if(byteOffset>2147483647)byteOffset=2147483647;else if(byteOffset<-2147483648)byteOffset=-2147483648;byteOffset=+byteOffset;if(numberIsNaN(byteOffset))byteOffset=dir?0:buffer.length-1;if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length)if(dir)return-1;else byteOffset= buffer.length-1;else if(byteOffset<0)if(dir)byteOffset=0;else return-1;if(typeof val==="string")val=Buffer.from(val,encoding);if(Buffer.isBuffer(val)){if(val.length===0)return-1;return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function")if(dir)return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset);else return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset);return arrayIndexOf(buffer,[val], byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer");}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2)return-1;indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1)return buf[i]; else return buf.readUInt16BE(i*indexSize)}var i;if(dir){var foundIndex=-1;for(i=byteOffset;i<arrLength;i++)if(read(arr,i)===read(val,foundIndex===-1?0:i-foundIndex)){if(foundIndex===-1)foundIndex=i;if(i-foundIndex+1===valLength)return foundIndex*indexSize}else{if(foundIndex!==-1)i-=i-foundIndex;foundIndex=-1}}else{if(byteOffset+valLength>arrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;j<valLength;j++)if(read(arr,i+j)!==read(val,j)){found=false;break}if(found)return i}}return-1} Buffer.prototype.includes=function includes(val,byteOffset,encoding){return this.indexOf(val,byteOffset,encoding)!==-1};Buffer.prototype.indexOf=function indexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,true)};Buffer.prototype.lastIndexOf=function lastIndexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,false)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length)length= remaining;else{length=Number(length);if(length>remaining)length=remaining}var strLen=string.length;if(length>strLen/2)length=strLen/2;for(var i=0;i<length;++i){var parsed=parseInt(string.substr(i*2,2),16);if(numberIsNaN(parsed))return i;buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function base64Write(buf, string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}Buffer.prototype.write=function write(string,offset,length,encoding){if(offset===undefined){encoding="utf8";length=this.length;offset=0}else if(length===undefined&&typeof offset==="string"){encoding=offset;length=this.length;offset=0}else if(isFinite(offset)){offset=offset>>>0;if(isFinite(length)){length= length>>>0;if(encoding===undefined)encoding="utf8"}else{encoding=length;length=undefined}}else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");if(!encoding)encoding="utf8";var loweredCase=false;for(;;)switch(encoding){case "hex":return hexWrite(this, string,offset,length);case "utf8":case "utf-8":return utf8Write(this,string,offset,length);case "ascii":case "latin1":case "binary":return asciiWrite(this,string,offset,length);case "base64":return base64Write(this,string,offset,length);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer", data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length)return base64.fromByteArray(buf);else return base64.fromByteArray(buf.slice(start,end))}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i<end){var firstByte=buf[i];var codePoint=null;var bytesPerSequence=firstByte>239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte< 128)codePoint=firstByte;break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127)codePoint=tempCodePoint}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343))codePoint=tempCodePoint}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+ 3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112)codePoint=tempCodePoint}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096; function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);var res="";var i=0;while(i<len)res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH));return res}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i)ret+=String.fromCharCode(buf[i]&127);return ret}function latin1Slice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i= start;i<end;++i)ret+=String.fromCharCode(buf[i]);return ret}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;++i)out+=hexSliceLookupTable[buf[i]];return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length-1;i+=2)res+=String.fromCharCode(bytes[i]+bytes[i+1]*256);return res}Buffer.prototype.slice=function slice(start,end){var len=this.length;start= ~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len)start=len;if(end<0){end+=len;if(end<0)end=0}else if(end>len)end=len;if(end<start)end=start;var newBuf=this.subarray(start,end);Object.setPrototypeOf(newBuf,Buffer.prototype);return newBuf};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length");}Buffer.prototype.readUintLE= Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256))val+=this[offset+i]*mul;return val};Buffer.prototype.readUintBE=Buffer.prototype.readUIntBE=function readUIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset+ --byteLength];var mul=1;while(byteLength>0&&(mul*=256))val+=this[offset+--byteLength]*mul;return val};Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUint16BE= Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function readUInt32BE(offset, noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256))val+=this[offset+i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE= function readIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256))val+=this[offset+--i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+ 1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>> 0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true, 23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this, offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||value<min)throw new RangeError('"value" argument is out of bounds');if(offset+ext>buf.length)throw new RangeError("Index out of range");}Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes= Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256))this[offset+i]=value/mul&255;return offset+byteLength};Buffer.prototype.writeUintBE=Buffer.prototype.writeUIntBE=function writeUIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1;var mul= 1;this[offset+i]=value&255;while(--i>=0&&(mul*=256))this[offset+i]=value/mul&255;return offset+byteLength};Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset, 2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value, offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value, offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){if(value<0&&sub===0&&this[offset+i-1]!==0)sub=1;this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2, 8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0)sub=1;this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE= function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value= +value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+ 3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range");}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkIEEE754(buf,value,offset,4,3.4028234663852886E38,-3.4028234663852886E38);ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value, offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkIEEE754(buf,value,offset,8,1.7976931348623157E308,-1.7976931348623157E308);ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value, offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end<start)end= start;if(end===start)return 0;if(target.length===0||this.length===0)return 0;if(targetStart<0)throw new RangeError("targetStart out of bounds");if(start<0||start>=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart<end-start)end=target.length-targetStart+start;var len=end-start;if(this===target&&typeof Uint8Array.prototype.copyWithin==="function")this.copyWithin(targetStart, start,end);else Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart);return len};Buffer.prototype.fill=function fill(val,start,end,encoding){if(typeof val==="string"){if(typeof start==="string"){encoding=start;start=0;end=this.length}else if(typeof end==="string"){encoding=end;end=this.length}if(encoding!==undefined&&typeof encoding!=="string")throw new TypeError("encoding must be a string");if(typeof encoding==="string"&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+ encoding);if(val.length===1){var code=val.charCodeAt(0);if(encoding==="utf8"&&code<128||encoding==="latin1")val=code}}else if(typeof val==="number")val=val&255;else if(typeof val==="boolean")val=Number(val);if(start<0||this.length<start||this.length<end)throw new RangeError("Out of range index");if(end<=start)return this;start=start>>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number")for(i=start;i<end;++i)this[i]=val;else{var bytes=Buffer.isBuffer(val)?val:Buffer.from(val, encoding);var len=bytes.length;if(len===0)throw new TypeError('The value "'+val+'" is invalid for argument "value"');for(i=0;i<end-start;++i)this[i+start]=bytes[i%len]}return this};var INVALID_BASE64_RE=/[^+/0-9A-Za-z-_]/g;function base64clean(str){str=str.split("=")[0];str=str.trim().replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0)str=str+"=";return str}function utf8ToBytes(string,units){units=units||Infinity;var codePoint;var length=string.length;var leadSurrogate= null;var bytes=[];for(var i=0;i<length;++i){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate)if((units-=3)>-1)bytes.push(239, 191,189);leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else throw new Error("Invalid code point");}return bytes}function asciiToBytes(str){var byteArray= [];for(var i=0;i<str.length;++i)byteArray.push(str.charCodeAt(i)&255);return byteArray}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;++i){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;++i){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i} function isInstance(obj,type){return obj instanceof type||obj!=null&&obj.constructor!=null&&obj.constructor.name!=null&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}var hexSliceLookupTable=function(){var alphabet="0123456789abcdef";var table=new Array(256);for(var i=0;i<16;++i){var i16=i*16;for(var j=0;j<16;++j)table[i16+j]=alphabet[i]+alphabet[j]}return table}()}).call(this)}).call(this,require("buffer").Buffer)},{"base64-js":7,"buffer":18,"ieee754":13}],9:[function(require, module,exports){var BufferReader=require("./lib/buffer-reader");var XIPH_LACING=1;var EBML_LACING=3;var FIXED_SIZE_LACING=2;module.exports=function(buffer){var block={};var reader=new BufferReader(buffer);block.trackNumber=reader.nextUIntV();block.timecode=reader.nextInt16BE();var flags=reader.nextUInt8();block.invisible=!!(flags&8);block.keyframe=!!(flags&128);block.discardable=!!(flags&1);var lacing=(flags&6)>>1;block.frames=readLacedData(reader,lacing);return block};function readLacedData(reader, lacing){if(!lacing)return[reader.nextBuffer()];var i,frameSize;var frames=[];var framesNum=reader.nextUInt8()+1;if(lacing===FIXED_SIZE_LACING){if(reader.length%framesNum!==0)throw new Error("Fixed-Size Lacing Error");frameSize=reader.length/framesNum;for(i=0;i<framesNum;i++)frames.push(reader.nextBuffer(frameSize));return frames}var frameSizes=[];if(lacing===XIPH_LACING)for(i=0;i<framesNum-1;i++){var val;frameSize=0;do{val=reader.nextUInt8();frameSize+=val}while(val===255);frameSizes.push(frameSize)}else if(lacing=== EBML_LACING){frameSize=reader.nextUIntV();frameSizes.push(frameSize);for(i=1;i<framesNum-1;i++){frameSize+=reader.nextIntV();frameSizes.push(frameSize)}}for(i=0;i<framesNum-1;i++)frames.push(reader.nextBuffer(frameSizes[i]));frames.push(reader.nextBuffer());return frames}},{"./lib/buffer-reader":10}],10:[function(require,module,exports){var vint=require("./vint");function BufferReader(buffer){this.buffer=buffer;this.offset=0}BufferReader.prototype.nextInt16BE=function(){var value=this.buffer.readInt16BE(this.offset); this.offset+=2;return value};BufferReader.prototype.nextUInt8=function(){var value=this.buffer.readUInt8(this.offset);this.offset+=1;return value};BufferReader.prototype.nextUIntV=function(){var v=vint(this.buffer,this.offset);this.offset+=v.length;return v.value};BufferReader.prototype.nextIntV=function(){var v=vint(this.buffer,this.offset,true);this.offset+=v.length;return v.value};BufferReader.prototype.nextBuffer=function(length){var buffer=length?this.buffer.slice(this.offset,this.offset+length): this.buffer.slice(this.offset);this.offset+=length||this.length;return buffer};Object.defineProperty(BufferReader.prototype,"length",{get:function(){return this.buffer.length-this.offset}});module.exports=BufferReader},{"./vint":11}],11:[function(require,module,exports){module.exports=function(buffer,start,signed){start=start||0;for(var length=1;length<=8;length++)if(buffer[start]>=Math.pow(2,8-length))break;if(length>8)throw new Error("Unrepresentable length: "+length+" "+buffer.toString("hex",start, start+length));if(start+length>buffer.length)return null;var i;var value=buffer[start]&(1<<8-length)-1;for(i=1;i<length;i++){if(i===7)if(value>=Math.pow(2,53-8)&&buffer[start+7]>0)return{length:length,value:-1};value*=Math.pow(2,8);value+=buffer[start+i]}if(signed)value-=Math.pow(2,length*7-1)-1;return{length:length,value:value}}},{}],12:[function(require,module,exports){(function(Buffer){(function(){var tools={readVint:function(buffer,start){start=start||0;for(var length=1;length<=8;length++)if(buffer[start]>= Math.pow(2,8-length))break;if(length>8)throw new Error("Unrepresentable length: "+length+" "+buffer.toString("hex",start,start+length));if(start+length>buffer.length)return null;var value=buffer[start]&(1<<8-length)-1;for(var i=1;i<length;i++){if(i===7)if(value>=Math.pow(2,53-8)&&buffer[start+7]>0)return{length:length,value:-1};value*=Math.pow(2,8);value+=buffer[start+i]}return{length:length,value:value}},writeVint:function(value){if(value<0||value>Math.pow(2,53))throw new Error("Unrepresentable value: "+ value);for(var length=1;length<=8;length++)if(value<Math.pow(2,7*length)-1)break;var buffer=new Buffer(length);for(var i=1;i<=length;i++){var b=value&255;buffer[length-i]=b;value-=b;value/=Math.pow(2,8)}buffer[0]=buffer[0]|1<<8-length;return buffer}};module.exports=tools}).call(this)}).call(this,require("buffer").Buffer)},{"buffer":18}],13:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1; var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0)e=1-eBias;else if(e===eMax)return m?NaN:(s?-1:1)*Infinity;else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen- 1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1)value+=rt/c;else value+=rt*Math.pow(2,1-eBias);if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen); e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],14:[function(require,module,exports){(function(Buffer){(function(){var Uint64BE,Int64BE,Uint64LE,Int64LE;!function(exports){var UNDEFINED="undefined";var BUFFER=UNDEFINED!==typeof Buffer&&Buffer;var UINT8ARRAY=UNDEFINED!==typeof Uint8Array&&Uint8Array;var ARRAYBUFFER= UNDEFINED!==typeof ArrayBuffer&&ArrayBuffer;var ZERO=[0,0,0,0,0,0,0,0];var isArray=Array.isArray||_isArray;var BIT32=4294967296;var BIT24=16777216;var storage;Uint64BE=factory("Uint64BE",true,true);Int64BE=factory("Int64BE",true,false);Uint64LE=factory("Uint64LE",false,true);Int64LE=factory("Int64LE",false,false);function factory(name,bigendian,unsigned){var posH=bigendian?0:4;var posL=bigendian?4:0;var pos0=bigendian?0:3;var pos1=bigendian?1:2;var pos2=bigendian?2:1;var pos3=bigendian?3:0;var fromPositive= bigendian?fromPositiveBE:fromPositiveLE;var fromNegative=bigendian?fromNegativeBE:fromNegativeLE;var proto=Int64.prototype;var isName="is"+name;var _isInt64="_"+isName;proto.buffer=void 0;proto.offset=0;proto[_isInt64]=true;proto.toNumber=toNumber;proto.toString=toString;proto.toJSON=toNumber;proto.toArray=toArray;if(BUFFER)proto.toBuffer=toBuffer;if(UINT8ARRAY)proto.toArrayBuffer=toArrayBuffer;Int64[isName]=isInt64;exports[name]=Int64;return Int64;function Int64(buffer,offset,value,raddix){if(!(this instanceof Int64))return new Int64(buffer,offset,value,raddix);return init(this,buffer,offset,value,raddix)}function isInt64(b){return!!(b&&b[_isInt64])}function init(that,buffer,offset,value,raddix){if(UINT8ARRAY&&ARRAYBUFFER){if(buffer instanceof ARRAYBUFFER)buffer=new UINT8ARRAY(buffer);if(value instanceof ARRAYBUFFER)value=new UINT8ARRAY(value)}if(!buffer&&!offset&&!value&&!storage){that.buffer=newArray(ZERO,0);return}if(!isValidBuffer(buffer,offset)){var _storage=storage||Array;raddix=offset;value=buffer; offset=0;buffer=new _storage(8)}that.buffer=buffer;that.offset=offset|=0;if(UNDEFINED===typeof value)return;if("string"===typeof value)fromString(buffer,offset,value,raddix||10);else if(isValidBuffer(value,raddix))fromArray(buffer,offset,value,raddix);else if("number"===typeof raddix){writeInt32(buffer,offset+posH,value);writeInt32(buffer,offset+posL,raddix)}else if(value>0)fromPositive(buffer,offset,value);else if(value<0)fromNegative(buffer,offset,value);else fromArray(buffer,offset,ZERO,0)}function fromString(buffer, offset,str,raddix){var pos=0;var len=str.length;var high=0;var low=0;if(str[0]==="-")pos++;var sign=pos;while(pos<len){var chr=parseInt(str[pos++],raddix);if(!(chr>=0))break;low=low*raddix+chr;high=high*raddix+Math.floor(low/BIT32);low%=BIT32}if(sign){high=~high;if(low)low=BIT32-low;else high++}writeInt32(buffer,offset+posH,high);writeInt32(buffer,offset+posL,low)}function toNumber(){var buffer=this.buffer;var offset=this.offset;var high=readInt32(buffer,offset+posH);var low=readInt32(buffer,offset+ posL);if(!unsigned)high|=0;return high?high*BIT32+low:low}function toString(radix){var buffer=this.buffer;var offset=this.offset;var high=readInt32(buffer,offset+posH);var low=readInt32(buffer,offset+posL);var str="";var sign=!unsigned&&high&2147483648;if(sign){high=~high;low=BIT32-low}radix=radix||10;while(1){var mod=high%radix*BIT32+low;high=Math.floor(high/radix);low=Math.floor(mod/radix);str=(mod%radix).toString(radix)+str;if(!high&&!low)break}if(sign)str="-"+str;return str}function writeInt32(buffer, offset,value){buffer[offset+pos3]=value&255;value=value>>8;buffer[offset+pos2]=value&255;value=value>>8;buffer[offset+pos1]=value&255;value=value>>8;buffer[offset+pos0]=value&255}function readInt32(buffer,offset){return buffer[offset+pos0]*BIT24+(buffer[offset+pos1]<<16)+(buffer[offset+pos2]<<8)+buffer[offset+pos3]}}function toArray(raw){var buffer=this.buffer;var offset=this.offset;storage=null;if(raw!==false&&offset===0&&buffer.length===8&&isArray(buffer))return buffer;return newArray(buffer,offset)} function toBuffer(raw){var buffer=this.buffer;var offset=this.offset;storage=BUFFER;if(raw!==false&&offset===0&&buffer.length===8&&Buffer.isBuffer(buffer))return buffer;var dest=new BUFFER(8);fromArray(dest,0,buffer,offset);return dest}function toArrayBuffer(raw){var buffer=this.buffer;var offset=this.offset;var arrbuf=buffer.buffer;storage=UINT8ARRAY;if(raw!==false&&offset===0&&arrbuf instanceof ARRAYBUFFER&&arrbuf.byteLength===8)return arrbuf;var dest=new UINT8ARRAY(8);fromArray(dest,0,buffer,offset); return dest.buffer}function isValidBuffer(buffer,offset){var len=buffer&&buffer.length;offset|=0;return len&&offset+8<=len&&"string"!==typeof buffer[offset]}function fromArray(destbuf,destoff,srcbuf,srcoff){destoff|=0;srcoff|=0;for(var i=0;i<8;i++)destbuf[destoff++]=srcbuf[srcoff++]&255}function newArray(buffer,offset){return Array.prototype.slice.call(buffer,offset,offset+8)}function fromPositiveBE(buffer,offset,value){var pos=offset+8;while(pos>offset){buffer[--pos]=value&255;value/=256}}function fromNegativeBE(buffer, offset,value){var pos=offset+8;value++;while(pos>offset){buffer[--pos]=-value&255^255;value/=256}}function fromPositiveLE(buffer,offset,value){var end=offset+8;while(offset<end){buffer[offset++]=value&255;value/=256}}function fromNegativeLE(buffer,offset,value){var end=offset+8;value++;while(offset<end){buffer[offset++]=-value&255^255;value/=256}}function _isArray(val){return!!val&&"[object Array]"==Object.prototype.toString.call(val)}}(typeof exports==="object"&&typeof exports.nodeName!=="string"? exports:this||{})}).call(this)}).call(this,require("buffer").Buffer)},{"buffer":18}],15:[function(require,module,exports){var byEbmlID={128:{name:"ChapterDisplay",level:4,type:"m",multiple:true,minver:1,webm:true,description:"Contains all possible strings to use for the chapter display."},131:{name:"TrackType",level:3,type:"u",mandatory:true,minver:1,range:"1-254",description:"A set of track types coded on 8 bits (1: video, 2: audio, 3: complex, 0x10: logo, 0x11: subtitle, 0x12: buttons, 0x20: control)."}, 133:{name:"ChapString",cppname:"ChapterString",level:5,type:"8",mandatory:true,minver:1,webm:true,description:"Contains the string to use as the chapter atom."},134:{name:"CodecID",level:3,type:"s",mandatory:true,minver:1,description:"An ID corresponding to the codec, see the codec page for more info."},136:{name:"FlagDefault",cppname:"TrackFlagDefault",level:3,type:"u",mandatory:true,minver:1,"default":1,range:"0-1",description:"Set if that track (audio, video or subs) SHOULD be active if no language found matches the user preference. (1 bit)"}, 137:{name:"ChapterTrackNumber",level:5,type:"u",mandatory:true,multiple:true,minver:1,webm:false,range:"not 0",description:"UID of the Track to apply this chapter too. In the absense of a control track, choosing this chapter will select the listed Tracks and deselect unlisted tracks. Absense of this element indicates that the Chapter should be applied to any currently used Tracks."},145:{name:"ChapterTimeStart",level:4,type:"u",mandatory:true,minver:1,webm:true,description:"Timestamp of the start of Chapter (not scaled)."}, 146:{name:"ChapterTimeEnd",level:4,type:"u",minver:1,webm:false,description:"Timestamp of the end of Chapter (timestamp excluded, not scaled)."},150:{name:"CueRefTime",level:5,type:"u",mandatory:true,minver:2,webm:false,description:"Timestamp of the referenced Block."},151:{name:"CueRefCluster",level:5,type:"u",mandatory:true,webm:false,description:"The Position of the Cluster containing the referenced Block."},152:{name:"ChapterFlagHidden",level:4,type:"u",mandatory:true,minver:1,webm:false,"default":0, range:"0-1",description:"If a chapter is hidden (1), it should not be available to the user interface (but still to Control Tracks; see flag notes). (1 bit)"},16980:{name:"ContentCompAlgo",level:6,type:"u",mandatory:true,minver:1,webm:false,"default":0,description:"The compression algorithm used. Algorithms that have been specified so far are: 0 - zlib, 3 - Header Stripping"},16981:{name:"ContentCompSettings",level:6,type:"b",minver:1,webm:false,description:"Settings that might be needed by the decompressor. For Header Stripping (ContentCompAlgo=3), the bytes that were removed from the beggining of each frames of the track."}, 17026:{name:"DocType",level:1,type:"s",mandatory:true,"default":"matroska",minver:1,description:"A string that describes the type of document that follows this EBML header. 'matroska' in our case or 'webm' for webm files."},17029:{name:"DocTypeReadVersion",level:1,type:"u",mandatory:true,"default":1,minver:1,description:"The minimum DocType version an interpreter has to support to read this file."},17030:{name:"EBMLVersion",level:1,type:"u",mandatory:true,"default":1,minver:1,description:"The version of EBML parser used to create the file."}, 17031:{name:"DocTypeVersion",level:1,type:"u",mandatory:true,"default":1,minver:1,description:"The version of DocType interpreter used to create the file."},17476:{name:"SegmentFamily",level:2,type:"b",multiple:true,minver:1,webm:false,bytesize:16,description:"A randomly generated unique ID that all segments related to each other must use (128 bits)."},17505:{name:"DateUTC",level:2,type:"d",minver:1,description:"Date of the origin of timestamp (value 0), i.e. production date."},17540:{name:"TagDefault", level:4,type:"u",mandatory:true,minver:1,webm:false,"default":1,range:"0-1",description:"Indication to know if this is the default/original language to use for the given tag. (1 bit)"},17541:{name:"TagBinary",level:4,type:"b",minver:1,webm:false,description:"The values of the Tag if it is binary. Note that this cannot be used in the same SimpleTag as TagString."},17543:{name:"TagString",level:4,type:"8",minver:1,webm:false,description:"The value of the Element."},17545:{name:"Duration",level:2,type:"f", minver:1,range:"> 0",description:"Duration of the segment (based on TimecodeScale)."},17816:{name:"ChapterFlagEnabled",level:4,type:"u",mandatory:true,minver:1,webm:false,"default":1,range:"0-1",description:"Specify wether the chapter is enabled. It can be enabled/disabled by a Control Track. When disabled, the movie should skip all the content between the TimeStart and TimeEnd of this chapter (see flag notes). (1 bit)"},18016:{name:"FileMimeType",level:3,type:"s",mandatory:true,minver:1,webm:false, description:"MIME type of the file."},18017:{name:"FileUsedStartTime",level:3,type:"u",divx:true,description:"DivX font extension"},18018:{name:"FileUsedEndTime",level:3,type:"u",divx:true,description:"DivX font extension"},18037:{name:"FileReferral",level:3,type:"b",webm:false,description:"A binary value that a track/codec can refer to when the attachment is needed."},20529:{name:"ContentEncodingOrder",level:5,type:"u",mandatory:true,minver:1,webm:false,"default":0,description:"Tells when this modification was used during encoding/muxing starting with 0 and counting upwards. The decoder/demuxer has to start with the highest order number it finds and work its way down. This value has to be unique over all ContentEncodingOrder elements in the segment."}, 20530:{name:"ContentEncodingScope",level:5,type:"u",mandatory:true,minver:1,webm:false,"default":1,range:"not 0",description:"A bit field that describes which elements have been modified in this way. Values (big endian) can be OR'ed. Possible values: 1 - all frame contents, 2 - the track's private data, 4 - the next ContentEncoding (next ContentEncodingOrder. Either the data inside ContentCompression and/or ContentEncryption)"},20531:{name:"ContentEncodingType",level:5,type:"u",mandatory:true,minver:1, webm:false,"default":0,description:"A value describing what kind of transformation has been done. Possible values: 0 - compression, 1 - encryption"},20532:{name:"ContentCompression",level:5,type:"m",minver:1,webm:false,description:"Settings describing the compression used. Must be present if the value of ContentEncodingType is 0 and absent otherwise. Each block must be decompressable even if no previous block is available in order not to prevent seeking."},20533:{name:"ContentEncryption",level:5, type:"m",minver:1,webm:false,description:"Settings describing the encryption used. Must be present if the value of ContentEncodingType is 1 and absent otherwise."},21368:{name:"CueBlockNumber",level:4,type:"u",minver:1,"default":1,range:"not 0",description:"Number of the Block in the specified Cluster."},22100:{name:"ChapterStringUID",level:4,type:"8",mandatory:false,minver:3,webm:true,description:"A unique string ID to identify the Chapter. Use for WebVTT cue identifier storage."},22337:{name:"WritingApp", level:2,type:"8",mandatory:true,minver:1,description:'Writing application ("mkvmerge-0.3.3").'},22612:{name:"SilentTracks",cppname:"ClusterSilentTracks",level:2,type:"m",minver:1,webm:false,description:"The list of tracks that are not used in that part of the stream. It is useful when using overlay tracks on seeking. Then you should decide what track to use."},25152:{name:"ContentEncoding",level:4,type:"m",mandatory:true,multiple:true,minver:1,webm:false,description:"Settings for one content encoding like compression or encryption."}, 25188:{name:"BitDepth",cppname:"AudioBitDepth",level:4,type:"u",minver:1,range:"not 0",description:"Bits per sample, mostly used for PCM."},25906:{name:"SignedElement",level:3,type:"b",multiple:true,webm:false,description:"An element ID whose data will be used to compute the signature."},26148:{name:"TrackTranslate",level:3,type:"m",multiple:true,minver:1,webm:false,description:"The track identification for the given Chapter Codec."},26897:{name:"ChapProcessCommand",cppname:"ChapterProcessCommand", level:5,type:"m",multiple:true,minver:1,webm:false,description:"Contains all the commands associated to the Atom."},26914:{name:"ChapProcessTime",cppname:"ChapterProcessTime",level:6,type:"u",mandatory:true,minver:1,webm:false,description:"Defines when the process command should be handled (0: during the whole chapter, 1: before starting playback, 2: after playback of the chapter)."},26916:{name:"ChapterTranslate",level:2,type:"m",multiple:true,minver:1,webm:false,description:"A tuple of corresponding ID used by chapter codecs to represent this segment."}, 26931:{name:"ChapProcessData",cppname:"ChapterProcessData",level:6,type:"b",mandatory:true,minver:1,webm:false,description:"Contains the command information. The data should be interpreted depending on the ChapProcessCodecID value. For ChapProcessCodecID = 1, the data correspond to the binary DVD cell pre/post commands."},26948:{name:"ChapProcess",cppname:"ChapterProcess",level:4,type:"m",multiple:true,minver:1,webm:false,description:"Contains all the commands associated to the Atom."},26965:{name:"ChapProcessCodecID", cppname:"ChapterProcessCodecID",level:5,type:"u",mandatory:true,minver:1,webm:false,"default":0,description:"Contains the type of the codec used for the processing. A value of 0 means native Matroska processing (to be defined), a value of 1 means the DVD command set is used. More codec IDs can be added later."},29555:{name:"Tag",level:2,type:"m",mandatory:true,multiple:true,minver:1,webm:false,description:"Element containing elements specific to Tracks/Chapters."},29572:{name:"SegmentFilename",level:2, type:"8",minver:1,webm:false,description:"A filename corresponding to this segment."},29766:{name:"AttachmentLink",cppname:"TrackAttachmentLink",level:3,type:"u",minver:1,webm:false,range:"not 0",description:"The UID of an attachment that is used by this codec."},2459272:{name:"CodecName",level:3,type:"8",minver:1,description:"A human-readable string specifying the codec."},408125543:{name:"Segment",level:"0",type:"m",mandatory:true,multiple:true,minver:1,description:"This element contains all other top-level (level 1) elements. Typically a Matroska file is composed of 1 segment."}, 17530:{name:"TagLanguage",level:4,type:"s",mandatory:true,minver:1,webm:false,"default":"und",description:"Specifies the language of the tag specified, in the Matroska languages form."},17827:{name:"TagName",level:4,type:"8",mandatory:true,minver:1,webm:false,description:"The name of the Tag that is going to be stored."},26568:{name:"SimpleTag",cppname:"TagSimple",level:3,"recursive":"1",type:"m",mandatory:true,multiple:true,minver:1,webm:false,description:"Contains general information about the target."}, 25542:{name:"TagAttachmentUID",level:4,type:"u",multiple:true,minver:1,webm:false,"default":0,description:"A unique ID to identify the Attachment(s) the tags belong to. If the value is 0 at this level, the tags apply to all the attachments in the Segment."},25540:{name:"TagChapterUID",level:4,type:"u",multiple:true,minver:1,webm:false,"default":0,description:"A unique ID to identify the Chapter(s) the tags belong to. If the value is 0 at this level, the tags apply to all chapters in the Segment."}, 25545:{name:"TagEditionUID",level:4,type:"u",multiple:true,minver:1,webm:false,"default":0,description:"A unique ID to identify the EditionEntry(s) the tags belong to. If the value is 0 at this level, the tags apply to all editions in the Segment."},25541:{name:"TagTrackUID",level:4,type:"u",multiple:true,minver:1,webm:false,"default":0,description:"A unique ID to identify the Track(s) the tags belong to. If the value is 0 at this level, the tags apply to all tracks in the Segment."},25546:{name:"TargetType", cppname:"TagTargetType",level:4,type:"s",minver:1,webm:false,"strong":"informational",description:'An string that can be used to display the logical level of the target like "ALBUM", "TRACK", "MOVIE", "CHAPTER", etc (see TargetType).'},26826:{name:"TargetTypeValue",cppname:"TagTargetTypeValue",level:4,type:"u",minver:1,webm:false,"default":50,description:"A number to indicate the logical level of the target (see TargetType)."},25536:{name:"Targets",cppname:"TagTargets",level:3,type:"m",mandatory:true, minver:1,webm:false,description:"Contain all UIDs where the specified meta data apply. It is empty to describe everything in the segment."},307544935:{name:"Tags",level:1,type:"m",multiple:true,minver:1,webm:false,description:"Element containing elements specific to Tracks/Chapters. A list of valid tags can be found here."},17677:{name:"ChapProcessPrivate",cppname:"ChapterProcessPrivate",level:5,type:"b",minver:1,webm:false,description:'Some optional data attached to the ChapProcessCodecID information. For ChapProcessCodecID = 1, it is the "DVD level" equivalent.'}, 17278:{name:"ChapCountry",cppname:"ChapterCountry",level:5,type:"s",multiple:true,minver:1,webm:false,description:"The countries corresponding to the string, same 2 octets as in Internet domains."},17276:{name:"ChapLanguage",cppname:"ChapterLanguage",level:5,type:"s",mandatory:true,multiple:true,minver:1,webm:true,"default":"eng",description:"The languages corresponding to the string, in the bibliographic ISO-639-2 form."},143:{name:"ChapterTrack",level:4,type:"m",minver:1,webm:false,description:"List of tracks on which the chapter applies. If this element is not present, all tracks apply"}, 25539:{name:"ChapterPhysicalEquiv",level:4,type:"u",minver:1,webm:false,description:'Specify the physical equivalent of this ChapterAtom like "DVD" (60) or "SIDE" (50), see complete list of values.'},28348:{name:"ChapterSegmentEditionUID",level:4,type:"u",minver:1,webm:false,range:"not 0",description:"The EditionUID to play from the segment linked in ChapterSegmentUID."},28263:{name:"ChapterSegmentUID",level:4,type:"b",minver:1,webm:false,range:">0",bytesize:16,description:"A segment to play in place of this chapter. Edition ChapterSegmentEditionUID should be used for this segment, otherwise no edition is used."}, 29636:{name:"ChapterUID",level:4,type:"u",mandatory:true,minver:1,webm:true,range:"not 0",description:"A unique ID to identify the Chapter."},182:{name:"ChapterAtom",level:3,"recursive":"1",type:"m",mandatory:true,multiple:true,minver:1,webm:true,description:"Contains the atom information to use as the chapter atom (apply to all tracks)."},17885:{name:"EditionFlagOrdered",level:3,type:"u",minver:1,webm:false,"default":0,range:"0-1",description:"Specify if the chapters can be defined multiple times and the order to play them is enforced. (1 bit)"}, 17883:{name:"EditionFlagDefault",level:3,type:"u",mandatory:true,minver:1,webm:false,"default":0,range:"0-1",description:"If a flag is set (1) the edition should be used as the default one. (1 bit)"},17853:{name:"EditionFlagHidden",level:3,type:"u",mandatory:true,minver:1,webm:false,"default":0,range:"0-1",description:"If an edition is hidden (1), it should not be available to the user interface (but still to Control Tracks; see flag notes). (1 bit)"},17852:{name:"EditionUID",level:3,type:"u",minver:1, webm:false,range:"not 0",description:"A unique ID to identify the edition. It's useful for tagging an edition."},17849:{name:"EditionEntry",level:2,type:"m",mandatory:true,multiple:true,minver:1,webm:true,description:"Contains all information about a segment edition."},272869232:{name:"Chapters",level:1,type:"m",minver:1,webm:true,description:"A system to define basic menus and partition data. For more detailed information, look at the Chapters Explanation."},18094:{name:"FileUID",level:3,type:"u", mandatory:true,minver:1,webm:false,range:"not 0",description:"Unique ID representing the file, as random as possible."},18012:{name:"FileData",level:3,type:"b",mandatory:true,minver:1,webm:false,description:"The data of the file."},18030:{name:"FileName",level:3,type:"8",mandatory:true,minver:1,webm:false,description:"Filename of the attached file."},18046:{name:"FileDescription",level:3,type:"8",minver:1,webm:false,description:"A human-friendly name for the attached file."},24999:{name:"AttachedFile", level:2,type:"m",mandatory:true,multiple:true,minver:1,webm:false,description:"An attached file."},423732329:{name:"Attachments",level:1,type:"m",minver:1,webm:false,description:"Contain attached files."},235:{name:"CueRefCodecState",level:5,type:"u",webm:false,"default":0,description:"The position of the Codec State corresponding to this referenced element. 0 means that the data is taken from the initial Track Entry."},21343:{name:"CueRefNumber",level:5,type:"u",webm:false,"default":1,range:"not 0", description:"Number of the referenced Block of Track X in the specified Cluster."},219:{name:"CueReference",level:4,type:"m",multiple:true,minver:2,webm:false,description:"The Clusters containing the required referenced Blocks."},234:{name:"CueCodecState",level:4,type:"u",minver:2,webm:false,"default":0,description:"The position of the Codec State corresponding to this Cue element. 0 means that the data is taken from the initial Track Entry."},178:{name:"CueDuration",level:4,type:"u",mandatory:false, minver:4,webm:false,description:"The duration of the block according to the segment time base. If missing the track's DefaultDuration does not apply and no duration information is available in terms of the cues."},240:{name:"CueRelativePosition",level:4,type:"u",mandatory:false,minver:4,webm:false,description:"The relative position of the referenced block inside the cluster with 0 being the first possible position for an element inside that cluster.",position:"clusterRelative"},241:{name:"CueClusterPosition", level:4,type:"u",mandatory:true,minver:1,description:"The position of the Cluster containing the required Block.",position:"segment"},247:{name:"CueTrack",level:4,type:"u",mandatory:true,minver:1,range:"not 0",description:"The track for which a position is given."},183:{name:"CueTrackPositions",level:3,type:"m",mandatory:true,multiple:true,minver:1,description:"Contain positions for different tracks corresponding to the timestamp."},179:{name:"CueTime",level:3,type:"u",mandatory:true,minver:1,description:"Absolute timestamp according to the segment time base."}, 187:{name:"CuePoint",level:2,type:"m",mandatory:true,multiple:true,minver:1,description:"Contains all information relative to a seek point in the segment."},475249515:{name:"Cues",level:1,type:"m",minver:1,description:'A top-level element to speed seeking access. All entries are local to the segment. Should be mandatory for non "live" streams.'},18406:{name:"ContentSigHashAlgo",level:6,type:"u",minver:1,webm:false,"default":0,description:"The hash algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values: 1 - SHA1-160 2 - MD5"}, 18405:{name:"ContentSigAlgo",level:6,type:"u",minver:1,webm:false,"default":0,description:"The algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values: 1 - RSA"},18404:{name:"ContentSigKeyID",level:6,type:"b",minver:1,webm:false,description:"This is the ID of the private key the data was signed with."},18403:{name:"ContentSignature",level:6,type:"b",minver:1,webm:false,description:"A cryptographic signature of the contents."}, 18402:{name:"ContentEncKeyID",level:6,type:"b",minver:1,webm:false,description:"For public key algorithms this is the ID of the public key the the data was encrypted with."},18401:{name:"ContentEncAlgo",level:6,type:"u",minver:1,webm:false,"default":0,description:"The encryption algorithm used. The value '0' means that the contents have not been encrypted but only signed. Predefined values: 1 - DES, 2 - 3DES, 3 - Twofish, 4 - Blowfish, 5 - AES"},28032:{name:"ContentEncodings",level:3,type:"m",minver:1, webm:false,description:"Settings for several content encoding mechanisms like compression or encryption."},196:{name:"TrickMasterTrackSegmentUID",level:3,type:"b",divx:true,bytesize:16,description:"DivX trick track extenstions"},199:{name:"TrickMasterTrackUID",level:3,type:"u",divx:true,description:"DivX trick track extenstions"},198:{name:"TrickTrackFlag",level:3,type:"u",divx:true,"default":0,description:"DivX trick track extenstions"},193:{name:"TrickTrackSegmentUID",level:3,type:"b",divx:true, bytesize:16,description:"DivX trick track extenstions"},192:{name:"TrickTrackUID",level:3,type:"u",divx:true,description:"DivX trick track extenstions"},237:{name:"TrackJoinUID",level:5,type:"u",mandatory:true,multiple:true,minver:3,webm:false,range:"not 0",description:"The trackUID number of a track whose blocks are used to create this virtual track."},233:{name:"TrackJoinBlocks",level:4,type:"m",minver:3,webm:false,description:"Contains the list of all tracks whose Blocks need to be combined to create this virtual track"}, 230:{name:"TrackPlaneType",level:6,type:"u",mandatory:true,minver:3,webm:false,description:"The kind of plane this track corresponds to (0: left eye, 1: right eye, 2: background)."},229:{name:"TrackPlaneUID",level:6,type:"u",mandatory:true,minver:3,webm:false,range:"not 0",description:"The trackUID number of the track representing the plane."},228:{name:"TrackPlane",level:5,type:"m",mandatory:true,multiple:true,minver:3,webm:false,description:"Contains a video plane track that need to be combined to create this 3D track"}, 227:{name:"TrackCombinePlanes",level:4,type:"m",minver:3,webm:false,description:"Contains the list of all video plane tracks that need to be combined to create this 3D track"},226:{name:"TrackOperation",level:3,type:"m",minver:3,webm:false,description:"Operation that needs to be applied on tracks to create this virtual track. For more details look at the Specification Notes on the subject."},32123:{name:"ChannelPositions",cppname:"AudioPosition",level:4,type:"b",webm:false,description:"Table of horizontal angles for each successive channel, see appendix."}, 159:{name:"Channels",cppname:"AudioChannels",level:4,type:"u",mandatory:true,minver:1,"default":1,range:"not 0",description:"Numbers of channels in the track."},30901:{name:"OutputSamplingFrequency",cppname:"AudioOutputSamplingFreq",level:4,type:"f",minver:1,"default":"Sampling Frequency",range:"> 0",description:"Real output sampling frequency in Hz (used for SBR techniques)."},181:{name:"SamplingFrequency",cppname:"AudioSamplingFreq",level:4,type:"f",mandatory:true,minver:1,"default":8E3,range:"> 0", description:"Sampling frequency in Hz."},225:{name:"Audio",cppname:"TrackAudio",level:3,type:"m",minver:1,description:"Audio settings."},2327523:{name:"FrameRate",cppname:"VideoFrameRate",level:4,type:"f",range:"> 0","strong":"Informational",description:"Number of frames per second. only."},3126563:{name:"GammaValue",cppname:"VideoGamma",level:4,type:"f",webm:false,range:"> 0",description:"Gamma Value."},3061028:{name:"ColourSpace",cppname:"VideoColourSpace",level:4,type:"b",minver:1,webm:false, bytesize:4,description:"Same value as in AVI (32 bits)."},21683:{name:"AspectRatioType",cppname:"VideoAspectRatio",level:4,type:"u",minver:1,"default":0,description:"Specify the possible modifications to the aspect ratio (0: free resizing, 1: keep aspect ratio, 2: fixed)."},21682:{name:"DisplayUnit",cppname:"VideoDisplayUnit",level:4,type:"u",minver:1,"default":0,description:"How DisplayWidth & DisplayHeight should be interpreted (0: pixels, 1: centimeters, 2: inches, 3: Display Aspect Ratio)."}, 21690:{name:"DisplayHeight",cppname:"VideoDisplayHeight",level:4,type:"u",minver:1,"default":"PixelHeight",range:"not 0",description:"Height of the video frames to display. The default value is only valid when DisplayUnit is 0."},21680:{name:"DisplayWidth",cppname:"VideoDisplayWidth",level:4,type:"u",minver:1,"default":"PixelWidth",range:"not 0",description:"Width of the video frames to display. The default value is only valid when DisplayUnit is 0."},21725:{name:"PixelCropRight",cppname:"VideoPixelCropRight", level:4,type:"u",minver:1,"default":0,description:"The number of video pixels to remove on the right of the image."},21708:{name:"PixelCropLeft",cppname:"VideoPixelCropLeft",level:4,type:"u",minver:1,"default":0,description:"The number of video pixels to remove on the left of the image."},21691:{name:"PixelCropTop",cppname:"VideoPixelCropTop",level:4,type:"u",minver:1,"default":0,description:"The number of video pixels to remove at the top of the image."},21674:{name:"PixelCropBottom",cppname:"VideoPixelCropBottom", level:4,type:"u",minver:1,"default":0,description:"The number of video pixels to remove at the bottom of the image (for HDTV content)."},186:{name:"PixelHeight",cppname:"VideoPixelHeight",level:4,type:"u",mandatory:true,minver:1,range:"not 0",description:"Height of the encoded video frames in pixels."},176:{name:"PixelWidth",cppname:"VideoPixelWidth",level:4,type:"u",mandatory:true,minver:1,range:"not 0",description:"Width of the encoded video frames in pixels."},21433:{name:"OldStereoMode",level:4, type:"u","maxver":"0",webm:false,divx:false,description:"DEPRECATED, DO NOT USE. Bogus StereoMode value used in old versions of libmatroska. (0: mono, 1: right eye, 2: left eye, 3: both eyes)."},21440:{name:"AlphaMode",cppname:"VideoAlphaMode",level:4,type:"u",minver:3,webm:true,"default":0,description:"Alpha Video Mode. Presence of this element indicates that the BlockAdditional element could contain Alpha data."},21432:{name:"StereoMode",cppname:"VideoStereoMode",level:4,type:"u",minver:3,webm:true, "default":0,description:"Stereo-3D video mode (0: mono, 1: side by side (left eye is first), 2: top-bottom (right eye is first), 3: top-bottom (left eye is first), 4: checkboard (right is first), 5: checkboard (left is first), 6: row interleaved (right is first), 7: row interleaved (left is first), 8: column interleaved (right is first), 9: column interleaved (left is first), 10: anaglyph (cyan/red), 11: side by side (right eye is first), 12: anaglyph (green/magenta), 13 both eyes laced in one Block (left eye is first), 14 both eyes laced in one Block (right eye is first)) . There are some more details on 3D support in the Specification Notes."}, 154:{name:"FlagInterlaced",cppname:"VideoFlagInterlaced",level:4,type:"u",mandatory:true,minver:2,webm:true,"default":0,range:"0-1",description:"Set if the video is interlaced. (1 bit)"},224:{name:"Video",cppname:"TrackVideo",level:3,type:"m",minver:1,description:"Video settings."},26277:{name:"TrackTranslateTrackID",level:4,type:"b",mandatory:true,minver:1,webm:false,description:"The binary value used to represent this track in the chapter codec data. The format depends on the ChapProcessCodecID used."}, 26303:{name:"TrackTranslateCodec",level:4,type:"u",mandatory:true,minver:1,webm:false,description:"The chapter codec using this ID (0: Matroska Script, 1: DVD-menu)."},26364:{name:"TrackTranslateEditionUID",level:4,type:"u",multiple:true,minver:1,webm:false,description:"Specify an edition UID on which this translation applies. When not specified, it means for all editions found in the segment."},22203:{name:"SeekPreRoll",level:3,type:"u",mandatory:true,multiple:false,"default":0,minver:4,webm:true, description:"After a discontinuity, SeekPreRoll is the duration in nanoseconds of the data the decoder must decode before the decoded data is valid."},22186:{name:"CodecDelay",level:3,type:"u",multiple:false,"default":0,minver:4,webm:true,description:"CodecDelay is The codec-built-in delay in nanoseconds. This value must be subtracted from each block timestamp in order to get the actual timestamp. The value should be small so the muxing of tracks with the same actual timestamp are in the same Cluster."}, 28587:{name:"TrackOverlay",level:3,type:"u",multiple:true,minver:1,webm:false,description:"Specify that this track is an overlay track for the Track specified (in the u-integer). That means when this track has a gap (see SilentTracks) the overlay track should be used instead. The order of multiple TrackOverlay matters, the first one is the one that should be used. If not found it should be the second, etc."},170:{name:"CodecDecodeAll",level:3,type:"u",mandatory:true,minver:2,webm:false,"default":1, range:"0-1",description:"The codec can decode potentially damaged data (1 bit)."},2536E3:{name:"CodecDownloadURL",level:3,type:"s",multiple:true,webm:false,description:"A URL to download about the codec used."},3883072:{name:"CodecInfoURL",level:3,type:"s",multiple:true,webm:false,description:"A URL to find information about the codec used."},3839639:{name:"CodecSettings",level:3,type:"8",webm:false,description:"A string describing the encoding setting used."},25506:{name:"CodecPrivate",level:3,type:"b", minver:1,description:"Private data only known to the codec."},2274716:{name:"Language",cppname:"TrackLanguage",level:3,type:"s",minver:1,"default":"eng",description:"Specifies the language of the track in the Matroska languages form."},21358:{name:"Name",cppname:"TrackName",level:3,type:"8",minver:1,description:"A human-readable track name."},21998:{name:"MaxBlockAdditionID",level:3,type:"u",mandatory:true,minver:1,webm:false,"default":0,description:"The maximum value of BlockAdditions for this track."}, 21375:{name:"TrackOffset",level:3,type:"i",webm:false,"default":0,description:"A value to add to the Block's Timestamp. This can be used to adjust the playback offset of a track."},2306383:{name:"TrackTimecodeScale",level:3,type:"f",mandatory:true,minver:1,"maxver":"3",webm:false,"default":1,range:"> 0",description:"DEPRECATED, DO NOT USE. The scale to apply on this track to work at normal speed in relation with other tracks (mostly used to adjust video speed when the audio length differs)."},2313850:{name:"DefaultDecodedFieldDuration", cppname:"TrackDefaultDecodedFieldDuration",level:3,type:"u",minver:4,range:"not 0",description:"The period in nanoseconds (not scaled by TimcodeScale)\nbetween two successive fields at the output of the decoding process (see the notes)"},2352003:{name:"DefaultDuration",cppname:"TrackDefaultDuration",level:3,type:"u",minver:1,range:"not 0",description:"Number of nanoseconds (not scaled via TimecodeScale) per frame ('frame' in the Matroska sense -- one element put into a (Simple)Block)."},28152:{name:"MaxCache", cppname:"TrackMaxCache",level:3,type:"u",minver:1,webm:false,description:"The maximum cache size required to store referenced frames in and the current frame. 0 means no cache is needed."},28135:{name:"MinCache",cppname:"TrackMinCache",level:3,type:"u",mandatory:true,minver:1,webm:false,"default":0,description:"The minimum number of frames a player should be able to cache during playback. If set to 0, the reference pseudo-cache system is not used."},156:{name:"FlagLacing",cppname:"TrackFlagLacing", level:3,type:"u",mandatory:true,minver:1,"default":1,range:"0-1",description:"Set if the track may contain blocks using lacing. (1 bit)"},21930:{name:"FlagForced",cppname:"TrackFlagForced",level:3,type:"u",mandatory:true,minver:1,"default":0,range:"0-1",description:"Set if that track MUST be active during playback. There can be many forced track for a kind (audio, video or subs), the player should select the one which language matches the user preference or the default + forced track. Overlay MAY happen between a forced and non-forced track of the same kind. (1 bit)"}, 185:{name:"FlagEnabled",cppname:"TrackFlagEnabled",level:3,type:"u",mandatory:true,minver:2,webm:true,"default":1,range:"0-1",description:"Set if the track is usable. (1 bit)"},29637:{name:"TrackUID",level:3,type:"u",mandatory:true,minver:1,range:"not 0",description:"A unique ID to identify the Track. This should be kept the same when making a direct stream copy of the Track to another file."},215:{name:"TrackNumber",level:3,type:"u",mandatory:true,minver:1,range:"not 0",description:"The track number as used in the Block Header (using more than 127 tracks is not encouraged, though the design allows an unlimited number)."}, 174:{name:"TrackEntry",level:2,type:"m",mandatory:true,multiple:true,minver:1,description:"Describes a track with all elements."},374648427:{name:"Tracks",level:1,type:"m",multiple:true,minver:1,description:"A top-level block of information with many tracks described."},175:{name:"EncryptedBlock",level:2,type:"b",multiple:true,webm:false,description:"Similar to EncryptedBlock Structure)"},202:{name:"ReferenceTimeCode",level:4,type:"u",multiple:false,mandatory:true,minver:0,webm:false,divx:true,description:"DivX trick track extenstions"}, 201:{name:"ReferenceOffset",level:4,type:"u",multiple:false,mandatory:true,minver:0,webm:false,divx:true,description:"DivX trick track extenstions"},200:{name:"ReferenceFrame",level:3,type:"m",multiple:false,minver:0,webm:false,divx:true,description:"DivX trick track extenstions"},207:{name:"SliceDuration",level:5,type:"u","default":0,description:"The (scaled) duration to apply to the element."},206:{name:"Delay",cppname:"SliceDelay",level:5,type:"u","default":0,description:"The (scaled) delay to apply to the element."}, 203:{name:"BlockAdditionID",cppname:"SliceBlockAddID",level:5,type:"u","default":0,description:"The ID of the BlockAdditional element (0 is the main Block)."},205:{name:"FrameNumber",cppname:"SliceFrameNumber",level:5,type:"u","default":0,description:"The number of the frame to generate from this lace with this delay (allow you to generate many frames from the same Block/Frame)."},204:{name:"LaceNumber",cppname:"SliceLaceNumber",level:5,type:"u",minver:1,"default":0,divx:false,description:"The reverse number of the frame in the lace (0 is the last frame, 1 is the next to last, etc). While there are a few files in the wild with this element, it is no longer in use and has been deprecated. Being able to interpret this element is not required for playback."}, 232:{name:"TimeSlice",level:4,type:"m",multiple:true,minver:1,divx:false,description:"Contains extra time information about the data contained in the Block. While there are a few files in the wild with this element, it is no longer in use and has been deprecated. Being able to interpret this element is not required for playback."},142:{name:"Slices",level:3,type:"m",minver:1,divx:false,description:"Contains slices description."},30114:{name:"DiscardPadding",level:3,type:"i",minver:4,webm:true,description:"Duration in nanoseconds of the silent data added to the Block (padding at the end of the Block for positive value, at the beginning of the Block for negative value). The duration of DiscardPadding is not calculated in the duration of the TrackEntry and should be discarded during playback."}, 164:{name:"CodecState",level:3,type:"b",minver:2,webm:false,description:"The new codec state to use. Data interpretation is private to the codec. This information should always be referenced by a seek entry."},253:{name:"ReferenceVirtual",level:3,type:"i",webm:false,description:"Relative position of the data that should be in position of the virtual block."},251:{name:"ReferenceBlock",level:3,type:"i",multiple:true,minver:1,description:"Timestamp of another frame used as a reference (ie: B or P frame). The timestamp is relative to the block it's attached to."}, 250:{name:"ReferencePriority",cppname:"FlagReferenced",level:3,type:"u",mandatory:true,minver:1,webm:false,"default":0,description:"This frame is referenced and has the specified cache priority. In cache only a frame of the same or higher priority can replace this frame. A value of 0 means the frame is not referenced."},155:{name:"BlockDuration",level:3,type:"u",minver:1,"default":"TrackDuration",description:'The duration of the Block (based on TimecodeScale). This element is mandatory when DefaultDuration is set for the track (but can be omitted as other default values). When not written and with no DefaultDuration, the value is assumed to be the difference between the timestamp of this Block and the timestamp of the next Block in "display" order (not coding order). This element can be useful at the end of a Track (as there is not other Block available), or when there is a break in a track like for subtitle tracks. When set to 0 that means the frame is not a keyframe.'}, 165:{name:"BlockAdditional",level:5,type:"b",mandatory:true,minver:1,webm:false,description:"Interpreted by the codec as it wishes (using the BlockAddID)."},238:{name:"BlockAddID",level:5,type:"u",mandatory:true,minver:1,webm:false,"default":1,range:"not 0",description:"An ID to identify the BlockAdditional level."},166:{name:"BlockMore",level:4,type:"m",mandatory:true,multiple:true,minver:1,webm:false,description:"Contain the BlockAdditional and some parameters."},30113:{name:"BlockAdditions",level:3, type:"m",minver:1,webm:false,description:"Contain additional blocks to complete the main one. An EBML parser that has no knowledge of the Block structure could still see and use/skip these data."},162:{name:"BlockVirtual",level:3,type:"b",webm:false,description:"A Block with no data. It must be stored in the stream at the place the real Block should be in display order. (see Block Virtual)"},161:{name:"Block",level:3,type:"b",mandatory:true,minver:1,description:"Block containing the actual data to be rendered and a timestamp relative to the Cluster Timecode. (see Block Structure)"}, 160:{name:"BlockGroup",level:2,type:"m",multiple:true,minver:1,description:"Basic container of information containing a single Block or BlockVirtual, and information specific to that Block/VirtualBlock."},163:{name:"SimpleBlock",level:2,type:"b",multiple:true,minver:2,webm:true,divx:true,description:"Similar to SimpleBlock Structure"},171:{name:"PrevSize",cppname:"ClusterPrevSize",level:2,type:"u",minver:1,description:"Size of the previous Cluster, in octets. Can be useful for backward playing.", position:"prevCluster"},167:{name:"Position",cppname:"ClusterPosition",level:2,type:"u",minver:1,webm:false,description:"The Position of the Cluster in the segment (0 in live broadcast streams). It might help to resynchronise offset on damaged streams.",position:"segment"},22743:{name:"SilentTrackNumber",cppname:"ClusterSilentTrackNumber",level:3,type:"u",multiple:true,minver:1,webm:false,description:"One of the track number that are not used from now on in the stream. It could change later if not specified as silent in a further Cluster."}, 231:{name:"Timecode",cppname:"ClusterTimecode",level:2,type:"u",mandatory:true,minver:1,description:"Absolute timestamp of the cluster (based on TimecodeScale)."},524531317:{name:"Cluster",level:1,type:"m",multiple:true,minver:1,description:"The lower level element containing the (monolithic) Block structure."},19840:{name:"MuxingApp",level:2,type:"8",mandatory:true,minver:1,description:'Muxing application or library ("libmatroska-0.4.3").'},31657:{name:"Title",level:2,type:"8",minver:1,webm:false, description:"General name of the segment."},2807730:{name:"TimecodeScaleDenominator",level:2,type:"u",mandatory:true,minver:4,"default":"1000000000",description:"Timestamp scale numerator, see TimecodeScale."},2807729:{name:"TimecodeScale",level:2,type:"u",mandatory:true,minver:1,"default":"1000000",description:"Timestamp scale in nanoseconds (1.000.000 means all timestamps in the segment are expressed in milliseconds)."},27045:{name:"ChapterTranslateID",level:3,type:"b",mandatory:true,minver:1,webm:false, description:"The binary value used to represent this segment in the chapter codec data. The format depends on the ChapProcessCodecID used."},27071:{name:"ChapterTranslateCodec",level:3,type:"u",mandatory:true,minver:1,webm:false,description:"The chapter codec using this ID (0: Matroska Script, 1: DVD-menu)."},27132:{name:"ChapterTranslateEditionUID",level:3,type:"u",multiple:true,minver:1,webm:false,description:"Specify an edition UID on which this correspondance applies. When not specified, it means for all editions found in the segment."}, 4096955:{name:"NextFilename",level:2,type:"8",minver:1,webm:false,description:"An escaped filename corresponding to the next segment."},4110627:{name:"NextUID",level:2,type:"b",minver:1,webm:false,bytesize:16,description:"A unique ID to identify the next chained segment (128 bits)."},3965867:{name:"PrevFilename",level:2,type:"8",minver:1,webm:false,description:"An escaped filename corresponding to the previous segment."},3979555:{name:"PrevUID",level:2,type:"b",minver:1,webm:false,bytesize:16,description:"A unique ID to identify the previous chained segment (128 bits)."}, 29604:{name:"SegmentUID",level:2,type:"b",minver:1,webm:false,range:"not 0",bytesize:16,description:"A randomly generated unique ID to identify the current segment between many others (128 bits)."},357149030:{name:"Info",level:1,type:"m",mandatory:true,multiple:true,minver:1,description:"Contains miscellaneous general information and statistics on the file."},21420:{name:"SeekPosition",level:3,type:"u",mandatory:true,minver:1,description:"The position of the element in the segment in octets (0 = first level 1 element).", position:"segment"},21419:{name:"SeekID",level:3,type:"b",mandatory:true,minver:1,description:"The binary ID corresponding to the element name.",type2:"ebmlID"},19899:{name:"Seek",cppname:"SeekPoint",level:2,type:"m",mandatory:true,multiple:true,minver:1,description:"Contains a single seek entry to an EBML element."},290298740:{name:"SeekHead",cppname:"SeekHeader",level:1,type:"m",multiple:true,minver:1,description:"Contains the position of other level 1 elements."},32379:{name:"SignatureElementList", level:2,type:"m",multiple:true,webm:false,i:"Cluster|Block|BlockAdditional",description:"A list consists of a number of consecutive elements that represent one case where data is used in signature. Ex: means that the BlockAdditional of all Blocks in all Clusters is used for encryption."},32347:{name:"SignatureElements",level:1,type:"m",webm:false,description:"Contains elements that will be used to compute the signature."},32437:{name:"Signature",level:1,type:"b",webm:false,description:"The signature of the data (until a new."}, 32421:{name:"SignaturePublicKey",level:1,type:"b",webm:false,description:"The public key to use with the algorithm (in the case of a PKI-based signature)."},32410:{name:"SignatureHash",level:1,type:"u",webm:false,description:"Hash algorithm used (1=SHA1-160, 2=MD5)."},32394:{name:"SignatureAlgo",level:1,type:"u",webm:false,description:"Signature algorithm used (1=RSA, 2=elliptic)."},458458727:{name:"SignatureSlot",level:-1,type:"m",multiple:true,webm:false,description:"Contain signature of some (coming) elements in the stream."}, 191:{name:"CRC-32",level:-1,type:"b",minver:1,webm:false,description:"The CRC is computed on all the data of the Master element it's in. The CRC element should be the first in it's parent master for easier reading. All level 1 elements should include a CRC-32. The CRC in use is the IEEE CRC32 Little Endian",crc:true},236:{name:"Void",level:-1,type:"b",minver:1,description:"Used to void damaged data, to avoid unexpected behaviors when using damaged data. The content is discarded. Also used to reserve space in a sub-element for later use."}, 17139:{name:"EBMLMaxSizeLength",level:1,type:"u",mandatory:true,"default":8,minver:1,description:"The maximum length of the sizes you'll find in this file (8 or less in Matroska). This does not override the element size indicated at the beginning of an element. Elements that have an indicated size which is larger than what is allowed by EBMLMaxSizeLength shall be considered invalid."},17138:{name:"EBMLMaxIDLength",level:1,type:"u",mandatory:true,"default":4,minver:1,description:"The maximum length of the IDs you'll find in this file (4 or less in Matroska)."}, 17143:{name:"EBMLReadVersion",level:1,type:"u",mandatory:true,"default":1,minver:1,description:"The minimum EBML version a parser has to support to read this file."},440786851:{name:"EBML",level:"0",type:"m",mandatory:true,multiple:true,minver:1,description:"Set the EBML characteristics of the data to follow. Each EBML document has to start with this."}};var byName={};var schema={byEbmlID:byEbmlID,byName:byName};for(var ebmlID in byEbmlID){var desc=byEbmlID[ebmlID];byName[desc.name.replace("-","_")]= parseInt(ebmlID,10)}module.exports=schema},{}],16:[function(require,module,exports){module.exports={"name":"ts-ebml","version":"2.0.2","description":"ebml decoder and encoder","scripts":{"setup":"npm install -g http-server;","init":"npm run update; npm run mkdir; npm run build","update":"npm run reset; npm update","reset":"rm -rf node_modules","mkdir":"mkdir lib dist 2>/dev/null","clean":"rm -rf lib/* dist/* test/*.js; mkdir -p dist","build":"npm run clean && tsc -p .; npm run browserify","start":"http-server . -s & tsc -w -p .& watchify lib/example_seekable.js -o test/example_seekable.js", "stop":"killall -- node */tsc -w -p","browserify":"browserify lib/index.js --standalone EBML -o dist/EBML.js","watchify":"watchify lib/index.js --standalone EBML -o dist/EBMl.js -v","test":"tsc; espower lib/test.js > lib/test.tmp; mv -f lib/test.tmp lib/test.js; browserify lib/test.js -o test/test.js","example":"tsc; browserify lib/example_seekable.js -o test/example_seekable.js","examples":"tsc; for file in `find lib -name 'example_*.js' -type f -printf '%f\\n'`; do browserify lib/$file -o test/$file; done", "examples_bsd":"tsc; for file in `find lib -name 'example_*.js' -type f -print`; do browserify lib/$(basename $file) -o test/$(basename $file); done","check":"tsc -w --noEmit -p ./","lint":"tslint -c ./tslint.json --project ./tsconfig.json --type-check","doc":"typedoc --mode modules --out doc --disableOutputCheck"},"repository":{"type":"git","url":"git+https://github.com/legokichi/ts-ebml.git"},"keywords":["ebml","webm","mkv","matrosika","webp"],"author":"legokichi duckscallion","license":"MIT","bugs":{"url":"https://github.com/legokichi/ts-ebml/issues"}, "homepage":"https://github.com/legokichi/ts-ebml#readme","dependencies":{"buffer":"^5.0.7","commander":"^2.11.0","ebml":"^2.2.1","ebml-block":"^1.1.0","events":"^1.1.1","int64-buffer":"^0.1.9","matroska":"^2.2.3"},"devDependencies":{"@types/commander":"^2.9.1","@types/qunit":"^2.0.31","browserify":"^13.1.0","empower":"^1.2.3","espower-cli":"^1.1.0","power-assert":"^1.4.4","power-assert-formatter":"^1.4.1","qunit-tap":"^1.5.1","qunitjs":"^2.4.0","tslint":"^5.13.1","typedoc":"^0.14.2","typescript":"^3.9.10", "watchify":"^3.7.0"},"bin":"./lib/cli.js","main":"./lib/index.js","typings":"./lib/index.d.ts"}},{}],17:[function(require,module,exports){arguments[4][7][0].apply(exports,arguments)},{"dup":7}],18:[function(require,module,exports){(function(Buffer){(function(){var base64=require("base64-js");var ieee754=require("ieee754");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;var K_MAX_LENGTH=2147483647;exports.kMaxLength=K_MAX_LENGTH;Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport(); if(!Buffer.TYPED_ARRAY_SUPPORT&&typeof console!=="undefined"&&typeof console.error==="function")console.error("This browser lacks typed array (Uint8Array) support which is required by "+"`buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42}catch(e){return false}}Object.defineProperty(Buffer.prototype,"parent",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined; return this.buffer}});Object.defineProperty(Buffer.prototype,"offset",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.byteOffset}});function createBuffer(length){if(length>K_MAX_LENGTH)throw new RangeError('The value "'+length+'" is invalid for option "size"');var buf=new Uint8Array(length);buf.__proto__=Buffer.prototype;return buf}function Buffer(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string")throw new TypeError('The "string" argument must be of type string. Received type number'); return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species!=null&&Buffer[Symbol.species]===Buffer)Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false});Buffer.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="string")return fromString(value,encodingOrOffset);if(ArrayBuffer.isView(value))return fromArrayLike(value);if(value==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+ "or Array-like Object. Received type "+typeof value);if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer))return fromArrayBuffer(value,encodingOrOffset,length);if(typeof value==="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var valueOf=value.valueOf&&value.valueOf();if(valueOf!=null&&valueOf!==value)return Buffer.from(valueOf,encodingOrOffset,length);var b=fromObject(value);if(b)return b;if(typeof Symbol!=="undefined"&& Symbol.toPrimitive!=null&&typeof value[Symbol.toPrimitive]==="function")return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value);}Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array;function assertSize(size){if(typeof size!== "number")throw new TypeError('"size" argument must be of type number');else if(size<0)throw new RangeError('The value "'+size+'" is invalid for option "size"');}function alloc(size,fill,encoding){assertSize(size);if(size<=0)return createBuffer(size);if(fill!==undefined)return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill);return createBuffer(size)}Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size); return createBuffer(size<0?0:checked(size)|0)}Buffer.allocUnsafe=function(size){return allocUnsafe(size)};Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding==="")encoding="utf8";if(!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length)buf=buf.slice(0,actual); return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i<length;i+=1)buf[i]=array[i]&255;return buf}function fromArrayBuffer(array,byteOffset,length){if(byteOffset<0||array.byteLength<byteOffset)throw new RangeError('"offset" is outside of buffer bounds');if(array.byteLength<byteOffset+(length||0))throw new RangeError('"length" is outside of buffer bounds');var buf;if(byteOffset===undefined&&length===undefined)buf=new Uint8Array(array); else if(length===undefined)buf=new Uint8Array(array,byteOffset);else buf=new Uint8Array(array,byteOffset,length);buf.__proto__=Buffer.prototype;return buf}function fromObject(obj){if(Buffer.isBuffer(obj)){var len=checked(obj.length)|0;var buf=createBuffer(len);if(buf.length===0)return buf;obj.copy(buf,0,0,len);return buf}if(obj.length!==undefined){if(typeof obj.length!=="number"||numberIsNaN(obj.length))return createBuffer(0);return fromArrayLike(obj)}if(obj.type==="Buffer"&&Array.isArray(obj.data))return fromArrayLike(obj.data)} function checked(length){if(length>=K_MAX_LENGTH)throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+K_MAX_LENGTH.toString(16)+" bytes");return length|0}function SlowBuffer(length){if(+length!=length)length=0;return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true&&b!==Buffer.prototype};Buffer.compare=function compare(a,b){if(isInstance(a,Uint8Array))a=Buffer.from(a,a.offset,a.byteLength);if(isInstance(b,Uint8Array))b=Buffer.from(b, b.offset,b.byteLength);if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len;++i)if(a[i]!==b[i]){x=a[i];y=b[i];break}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function isEncoding(encoding){switch(String(encoding).toLowerCase()){case "hex":case "utf8":case "utf-8":case "ascii":case "latin1":case "binary":case "base64":case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return true; default:return false}};Buffer.concat=function concat(list,length){if(!Array.isArray(list))throw new TypeError('"list" argument must be an Array of Buffers');if(list.length===0)return Buffer.alloc(0);var i;if(length===undefined){length=0;for(i=0;i<list.length;++i)length+=list[i].length}var buffer=Buffer.allocUnsafe(length);var pos=0;for(i=0;i<list.length;++i){var buf=list[i];if(isInstance(buf,Uint8Array))buf=Buffer.from(buf);if(!Buffer.isBuffer(buf))throw new TypeError('"list" argument must be an Array of Buffers'); buf.copy(buffer,pos);pos+=buf.length}return buffer};function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer))return string.byteLength;if(typeof string!=="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. '+"Received type "+typeof string);var len=string.length;var mustMatch=arguments.length>2&&arguments[2]===true;if(!mustMatch&&len===0)return 0;var loweredCase= false;for(;;)switch(encoding){case "ascii":case "latin1":case "binary":return len;case "utf8":case "utf-8":return utf8ToBytes(string).length;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return len*2;case "hex":return len>>>1;case "base64":return base64ToBytes(string).length;default:if(loweredCase)return mustMatch?-1:utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false; if(start===undefined||start<0)start=0;if(start>this.length)return"";if(end===undefined||end>this.length)end=this.length;if(end<=0)return"";end>>>=0;start>>>=0;if(end<=start)return"";if(!encoding)encoding="utf8";while(true)switch(encoding){case "hex":return hexSlice(this,start,end);case "utf8":case "utf-8":return utf8Slice(this,start,end);case "ascii":return asciiSlice(this,start,end);case "latin1":case "binary":return latin1Slice(this,start,end);case "base64":return base64Slice(this,start,end);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return utf16leSlice(this, start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var i=0;i<len;i+=2)swap(this,i,i+1);return this};Buffer.prototype.swap32=function swap32(){var len=this.length;if(len%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits"); for(var i=0;i<len;i+=4){swap(this,i,i+3);swap(this,i+1,i+2)}return this};Buffer.prototype.swap64=function swap64(){var len=this.length;if(len%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var i=0;i<len;i+=8){swap(this,i,i+7);swap(this,i+1,i+6);swap(this,i+2,i+5);swap(this,i+3,i+4)}return this};Buffer.prototype.toString=function toString(){var length=this.length;if(length===0)return"";if(arguments.length===0)return utf8Slice(this,0,length);return slowToString.apply(this, arguments)};Buffer.prototype.toLocaleString=Buffer.prototype.toString;Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return true;return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function inspect(){var str="";var max=exports.INSPECT_MAX_BYTES;str=this.toString("hex",0,max).replace(/(.{2})/g,"$1 ").trim();if(this.length>max)str+=" ... ";return"<Buffer "+str+">"};Buffer.prototype.compare=function compare(target, start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array))target=Buffer.from(target,target.offset,target.byteLength);if(!Buffer.isBuffer(target))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. '+"Received type "+typeof target);if(start===undefined)start=0;if(end===undefined)end=target?target.length:0;if(thisStart===undefined)thisStart=0;if(thisEnd===undefined)thisEnd=this.length;if(start<0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index"); if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i<len;++i)if(thisCopy[i]!==targetCopy[i]){x=thisCopy[i];y=targetCopy[i];break}if(x<y)return-1;if(y<x)return 1;return 0};function bidirectionalIndexOf(buffer,val,byteOffset,encoding, dir){if(buffer.length===0)return-1;if(typeof byteOffset==="string"){encoding=byteOffset;byteOffset=0}else if(byteOffset>2147483647)byteOffset=2147483647;else if(byteOffset<-2147483648)byteOffset=-2147483648;byteOffset=+byteOffset;if(numberIsNaN(byteOffset))byteOffset=dir?0:buffer.length-1;if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length)if(dir)return-1;else byteOffset=buffer.length-1;else if(byteOffset<0)if(dir)byteOffset=0;else return-1;if(typeof val==="string")val= Buffer.from(val,encoding);if(Buffer.isBuffer(val)){if(val.length===0)return-1;return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function")if(dir)return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset);else return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset);return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer");}function arrayIndexOf(arr, val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2)return-1;indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1)return buf[i];else return buf.readUInt16BE(i*indexSize)}var i;if(dir){var foundIndex=-1;for(i=byteOffset;i<arrLength;i++)if(read(arr, i)===read(val,foundIndex===-1?0:i-foundIndex)){if(foundIndex===-1)foundIndex=i;if(i-foundIndex+1===valLength)return foundIndex*indexSize}else{if(foundIndex!==-1)i-=i-foundIndex;foundIndex=-1}}else{if(byteOffset+valLength>arrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;j<valLength;j++)if(read(arr,i+j)!==read(val,j)){found=false;break}if(found)return i}}return-1}Buffer.prototype.includes=function includes(val,byteOffset,encoding){return this.indexOf(val, byteOffset,encoding)!==-1};Buffer.prototype.indexOf=function indexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,true)};Buffer.prototype.lastIndexOf=function lastIndexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,false)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length)length=remaining;else{length=Number(length);if(length>remaining)length=remaining}var strLen= string.length;if(length>strLen/2)length=strLen/2;for(var i=0;i<length;++i){var parsed=parseInt(string.substr(i*2,2),16);if(numberIsNaN(parsed))return i;buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function latin1Write(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf, string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}Buffer.prototype.write=function write(string,offset,length,encoding){if(offset===undefined){encoding="utf8";length=this.length;offset=0}else if(length===undefined&&typeof offset==="string"){encoding=offset;length=this.length;offset=0}else if(isFinite(offset)){offset=offset>>>0;if(isFinite(length)){length= length>>>0;if(encoding===undefined)encoding="utf8"}else{encoding=length;length=undefined}}else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");if(!encoding)encoding="utf8";var loweredCase=false;for(;;)switch(encoding){case "hex":return hexWrite(this, string,offset,length);case "utf8":case "utf-8":return utf8Write(this,string,offset,length);case "ascii":return asciiWrite(this,string,offset,length);case "latin1":case "binary":return latin1Write(this,string,offset,length);case "base64":return base64Write(this,string,offset,length);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase= true}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length)return base64.fromByteArray(buf);else return base64.fromByteArray(buf.slice(start,end))}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i<end){var firstByte=buf[i];var codePoint=null;var bytesPerSequence=firstByte>239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<= end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128)codePoint=firstByte;break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127)codePoint=tempCodePoint}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint> 57343))codePoint=tempCodePoint}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112)codePoint=tempCodePoint}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint); i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);var res="";var i=0;while(i<len)res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH));return res}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i)ret+=String.fromCharCode(buf[i]&127);return ret} function latin1Slice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i)ret+=String.fromCharCode(buf[i]);return ret}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;++i)out+=toHex(buf[i]);return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2)res+=String.fromCharCode(bytes[i]+bytes[i+1]*256);return res}Buffer.prototype.slice= function slice(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len)start=len;if(end<0){end+=len;if(end<0)end=0}else if(end>len)end=len;if(end<start)end=start;var newBuf=this.subarray(start,end);newBuf.__proto__=Buffer.prototype;return newBuf};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length"); }Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256))val+=this[offset+i]*mul;return val};Buffer.prototype.readUIntBE=function readUIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset+--byteLength];var mul= 1;while(byteLength>0&&(mul*=256))val+=this[offset+--byteLength]*mul;return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset, 2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE= function readIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256))val+=this[offset+i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul= 1;var val=this[offset+--i];while(i>0&&(mul*=256))val+=this[offset+--i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+ 1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset, noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23, 4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance'); if(value>max||value<min)throw new RangeError('"value" argument is out of bounds');if(offset+ext>buf.length)throw new RangeError("Index out of range");}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256))this[offset+i]=value/mul&255;return offset+ byteLength};Buffer.prototype.writeUIntBE=function writeUIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256))this[offset+i]=value/mul&255;return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this, value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+ 2};Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+ 2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){if(value<0&&sub===0&&this[offset+i-1]!==0)sub=1;this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value, offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0)sub=1;this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset, 1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+ 1]=value&255;return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value= 4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range");}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkIEEE754(buf,value,offset,4,3.4028234663852886E38,-3.4028234663852886E38);ieee754.write(buf, value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkIEEE754(buf,value,offset,8,1.7976931348623157E308,-1.7976931348623157E308);ieee754.write(buf, value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(!start)start=0;if(!end&&end!==0)end=this.length; if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end<start)end=start;if(end===start)return 0;if(target.length===0||this.length===0)return 0;if(targetStart<0)throw new RangeError("targetStart out of bounds");if(start<0||start>=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart<end-start)end=target.length-targetStart+start;var len= end-start;if(this===target&&typeof Uint8Array.prototype.copyWithin==="function")this.copyWithin(targetStart,start,end);else if(this===target&&start<targetStart&&targetStart<end)for(var i=len-1;i>=0;--i)target[i+targetStart]=this[i+start];else Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart);return len};Buffer.prototype.fill=function fill(val,start,end,encoding){if(typeof val==="string"){if(typeof start==="string"){encoding=start;start=0;end=this.length}else if(typeof end=== "string"){encoding=end;end=this.length}if(encoding!==undefined&&typeof encoding!=="string")throw new TypeError("encoding must be a string");if(typeof encoding==="string"&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);if(val.length===1){var code=val.charCodeAt(0);if(encoding==="utf8"&&code<128||encoding==="latin1")val=code}}else if(typeof val==="number")val=val&255;if(start<0||this.length<start||this.length<end)throw new RangeError("Out of range index");if(end<=start)return this; start=start>>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number")for(i=start;i<end;++i)this[i]=val;else{var bytes=Buffer.isBuffer(val)?val:Buffer.from(val,encoding);var len=bytes.length;if(len===0)throw new TypeError('The value "'+val+'" is invalid for argument "value"');for(i=0;i<end-start;++i)this[i+start]=bytes[i%len]}return this};var INVALID_BASE64_RE=/[^+/0-9A-Za-z-_]/g;function base64clean(str){str=str.split("=")[0];str=str.trim().replace(INVALID_BASE64_RE, "");if(str.length<2)return"";while(str.length%4!==0)str=str+"=";return str}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(string,units){units=units||Infinity;var codePoint;var length=string.length;var leadSurrogate=null;var bytes=[];for(var i=0;i<length;++i){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239, 191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate)if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>> 12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else throw new Error("Invalid code point");}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;++i)byteArray.push(str.charCodeAt(i)&255);return byteArray}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;++i){if((units-=2)<0)break;c=str.charCodeAt(i); hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;++i){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isInstance(obj,type){return obj instanceof type||obj!=null&&obj.constructor!=null&&obj.constructor.name!=null&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}}).call(this)}).call(this, require("buffer").Buffer)},{"base64-js":17,"buffer":18,"ieee754":20}],19:[function(require,module,exports){var R=typeof Reflect==="object"?Reflect:null;var ReflectApply=R&&typeof R.apply==="function"?R.apply:function ReflectApply(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)};var ReflectOwnKeys;if(R&&typeof R.ownKeys==="function")ReflectOwnKeys=R.ownKeys;else if(Object.getOwnPropertySymbols)ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}; else ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target)};function ProcessEmitWarning(warning){if(console&&console.warn)console.warn(warning)}var NumberIsNaN=Number.isNaN||function NumberIsNaN(value){return value!==value};function EventEmitter(){EventEmitter.init.call(this)}module.exports=EventEmitter;module.exports.once=once;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._eventsCount=0;EventEmitter.prototype._maxListeners= undefined;var defaultMaxListeners=10;function checkListener(listener){if(typeof listener!=="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof listener);}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:true,get:function(){return defaultMaxListeners},set:function(arg){if(typeof arg!=="number"||arg<0||NumberIsNaN(arg))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+ arg+".");defaultMaxListeners=arg}});EventEmitter.init=function(){if(this._events===undefined||this._events===Object.getPrototypeOf(this)._events){this._events=Object.create(null);this._eventsCount=0}this._maxListeners=this._maxListeners||undefined};EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if(typeof n!=="number"||n<0||NumberIsNaN(n))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+n+".");this._maxListeners=n;return this}; function _getMaxListeners(that){if(that._maxListeners===undefined)return EventEmitter.defaultMaxListeners;return that._maxListeners}EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)};EventEmitter.prototype.emit=function emit(type){var args=[];for(var i=1;i<arguments.length;i++)args.push(arguments[i]);var doError=type==="error";var events=this._events;if(events!==undefined)doError=doError&&events.error===undefined;else if(!doError)return false;if(doError){var er; if(args.length>0)er=args[0];if(er instanceof Error)throw er;var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));err.context=er;throw err;}var handler=events[type];if(handler===undefined)return false;if(typeof handler==="function")ReflectApply(handler,this,args);else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i)ReflectApply(listeners[i],this,args)}return true};function _addListener(target,type,listener,prepend){var m;var events;var existing;checkListener(listener); events=target._events;if(events===undefined){events=target._events=Object.create(null);target._eventsCount=0}else{if(events.newListener!==undefined){target.emit("newListener",type,listener.listener?listener.listener:listener);events=target._events}existing=events[type]}if(existing===undefined){existing=events[type]=listener;++target._eventsCount}else{if(typeof existing==="function")existing=events[type]=prepend?[listener,existing]:[existing,listener];else if(prepend)existing.unshift(listener);else existing.push(listener); m=_getMaxListeners(target);if(m>0&&existing.length>m&&!existing.warned){existing.warned=true;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners "+"added. Use emitter.setMaxListeners() to "+"increase limit");w.name="MaxListenersExceededWarning";w.emitter=target;w.type=type;w.count=existing.length;ProcessEmitWarning(w)}}return target}EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener, false)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,true)};function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=true;if(arguments.length===0)return this.listener.call(this.target);return this.listener.apply(this.target,arguments)}}function _onceWrap(target,type,listener){var state={fired:false,wrapFn:undefined,target:target, type:type,listener:listener};var wrapped=onceWrapper.bind(state);wrapped.listener=listener;state.wrapFn=wrapped;return wrapped}EventEmitter.prototype.once=function once(type,listener){checkListener(listener);this.on(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){checkListener(listener);this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.removeListener=function removeListener(type, listener){var list,events,position,i,originalListener;checkListener(listener);events=this._events;if(events===undefined)return this;list=events[type];if(list===undefined)return this;if(list===listener||list.listener===listener)if(--this._eventsCount===0)this._events=Object.create(null);else{delete events[type];if(events.removeListener)this.emit("removeListener",type,list.listener||listener)}else if(typeof list!=="function"){position=-1;for(i=list.length-1;i>=0;i--)if(list[i]===listener||list[i].listener=== listener){originalListener=list[i].listener;position=i;break}if(position<0)return this;if(position===0)list.shift();else spliceOne(list,position);if(list.length===1)events[type]=list[0];if(events.removeListener!==undefined)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;events=this._events;if(events===undefined)return this; if(events.removeListener===undefined){if(arguments.length===0){this._events=Object.create(null);this._eventsCount=0}else if(events[type]!==undefined)if(--this._eventsCount===0)this._events=Object.create(null);else delete events[type];return this}if(arguments.length===0){var keys=Object.keys(events);var key;for(i=0;i<keys.length;++i){key=keys[i];if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events=Object.create(null);this._eventsCount= 0;return this}listeners=events[type];if(typeof listeners==="function")this.removeListener(type,listeners);else if(listeners!==undefined)for(i=listeners.length-1;i>=0;i--)this.removeListener(type,listeners[i]);return this};function _listeners(target,type,unwrap){var events=target._events;if(events===undefined)return[];var evlistener=events[type];if(evlistener===undefined)return[];if(typeof evlistener==="function")return unwrap?[evlistener.listener||evlistener]:[evlistener];return unwrap?unwrapListeners(evlistener): arrayClone(evlistener,evlistener.length)}EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,true)};EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,false)};EventEmitter.listenerCount=function(emitter,type){if(typeof emitter.listenerCount==="function")return emitter.listenerCount(type);else return listenerCount.call(emitter,type)};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(type){var events= this._events;if(events!==undefined){var evlistener=events[type];if(typeof evlistener==="function")return 1;else if(evlistener!==undefined)return evlistener.length}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(arr,n){var copy=new Array(n);for(var i=0;i<n;++i)copy[i]=arr[i];return copy}function spliceOne(list,index){for(;index+1<list.length;index++)list[index]=list[index+1];list.pop()}function unwrapListeners(arr){var ret= new Array(arr.length);for(var i=0;i<ret.length;++i)ret[i]=arr[i].listener||arr[i];return ret}function once(emitter,name){return new Promise(function(resolve,reject){function errorListener(err){emitter.removeListener(name,resolver);reject(err)}function resolver(){if(typeof emitter.removeListener==="function")emitter.removeListener("error",errorListener);resolve([].slice.call(arguments))}eventTargetAgnosticAddListener(emitter,name,resolver,{once:true});if(name!=="error")addErrorHandlerIfEventEmitter(emitter, errorListener,{once:true})})}function addErrorHandlerIfEventEmitter(emitter,handler,flags){if(typeof emitter.on==="function")eventTargetAgnosticAddListener(emitter,"error",handler,flags)}function eventTargetAgnosticAddListener(emitter,name,listener,flags){if(typeof emitter.on==="function")if(flags.once)emitter.once(name,listener);else emitter.on(name,listener);else if(typeof emitter.addEventListener==="function")emitter.addEventListener(name,function wrapListener(arg){if(flags.once)emitter.removeEventListener(name, wrapListener);listener(arg)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof emitter);}},{}],20:[function(require,module,exports){arguments[4][13][0].apply(exports,arguments)},{"dup":13}]},{},[5])(5)}); 'use strict';{const DOM_COMPONENT_ID="game-recorder";function BlobToArrayBuffer(blob){return new Promise((resolve,reject)=>{const fileReader=new FileReader;fileReader.onload=()=>resolve(fileReader["result"]);fileReader.onerror=()=>reject(fileReader["error"]);fileReader.readAsArrayBuffer(blob)})}async function MakeWebMSeekable(webMBlob){try{const EBML=self.EBML;const arrayBuffer=await BlobToArrayBuffer(webMBlob);const decoder=new EBML.Decoder;const reader=new EBML.Reader;const elms=decoder.decode(arrayBuffer); elms.forEach(elm=>reader.read(elm));const refinedMetadataBuf=EBML.tools.makeMetadataSeekable(reader.metadatas,reader.duration,reader.cues);const body=arrayBuffer.slice(reader.metadataSize);return new Blob([refinedMetadataBuf,body],{type:webMBlob.type})}catch(err){console.error("Error making WebM seekable, returning original: ",err);return webMBlob}}const HANDLER_CLASS=class GameRecorderDOMHandler extends self.DOMHandler{constructor(iRuntime){super(iRuntime,DOM_COMPONENT_ID);this._mediaRecorder=null; this._mediaStream=null;this._stopStreamOnEnd=true;this._recordedChunks=[];this._lastRecordingUrl="";this.AddRuntimeMessageHandler("get-supported-formats",()=>this._OnGetSupportedFormats());this.AddRuntimeMessageHandler("start-recording",e=>this._OnStartRecording(e));this.AddRuntimeMessageHandler("start-screen-recording",e=>this._OnStartScreenRecording(e));this.AddRuntimeMessageHandler("start-user-media-recording",e=>this._OnStartUserMediaRecording(e));this.AddRuntimeMessageHandler("stop-recording", ()=>this._OnStopRecording())}_OnGetSupportedFormats(){const canvas=this._iRuntime.GetMainCanvas();const isMediaRecorderSupported=typeof MediaRecorder!=="undefined";const isSupported=!!(canvas["captureStream"]&&isMediaRecorderSupported);const supportedVideoFormats=[];const supportedAudioFormats=[];if(isSupported){const containerFormats=["mp4","webm"];const videoCodecs=["avc1.420034","vp9","vp8"];const audioCodecs=["mp4a.40.2","opus"];for(const containerFormat of containerFormats){for(const videoCodec of videoCodecs){const typeStr= `video/${containerFormat};codecs=${videoCodec}`;if(MediaRecorder.isTypeSupported(typeStr))supportedVideoFormats.push(typeStr)}for(const audioCodec of audioCodecs){const typeStr=`audio/${containerFormat};codecs=${audioCodec}`;if(MediaRecorder.isTypeSupported(typeStr))supportedAudioFormats.push(typeStr)}}}return{"isSupported":isSupported,"isMediaRecorderSupported":isMediaRecorderSupported,"isScreenRecordingSupported":!!(navigator["mediaDevices"]&&navigator["mediaDevices"]["getDisplayMedia"]&&typeof MediaRecorder!== "undefined"),"supportedVideoFormats":supportedVideoFormats,"supportedAudioFormats":supportedAudioFormats}}_GetMimeTypeFromParts(containerPart,videoCodecStr,audioCodecStr){if(!containerPart)return"";const codecArr=[];if(videoCodecStr)codecArr.push(videoCodecStr);if(audioCodecStr)codecArr.push(audioCodecStr);return`${containerPart};codecs=${codecArr.join(",")}`}_StopStreamVideoTracks(stream){const tracks=stream["getTracks"]();for(let i=0,len=tracks.length;i<len;++i){const track=tracks[i];if(track["kind"]=== "video")track["stop"]()}}_StopAnyPriorRecording(){this._OnStopRecording();this._recordedChunks.length=0;if(this._lastRecordingUrl){URL.revokeObjectURL(this._lastRecordingUrl);this._lastRecordingUrl=""}}_OnStartRecording(e){const containerPart=e["containerPart"];const videoPart=e["videoPart"];let audioPart=e["audioPart"];const bitsPerSecond=e["bitsPerSecond"];const framerate=e["framerate"];this._StopAnyPriorRecording();let videoTracks=[];let audioTracks=[];try{if(videoPart){const canvas=this._iRuntime.GetMainCanvas(); let videoStream;if(framerate>0)videoStream=canvas["captureStream"](framerate);else videoStream=canvas["captureStream"]();videoTracks=videoStream["getVideoTracks"]()}if(audioPart&&self["C3Audio_GetOutputStream"]){const audioStream=self["C3Audio_GetOutputStream"]();audioTracks=audioStream["getAudioTracks"]()}if(audioTracks.length===0)audioPart="";const mimeType=this._GetMimeTypeFromParts(containerPart,videoPart,audioPart);console.log(`[Video recorder] Recording with MIME type '${mimeType}'`);this._mediaStream= new MediaStream([...videoTracks,...audioTracks]);this._stopStreamOnEnd=true;this._mediaRecorder=new MediaRecorder(this._mediaStream,{"mimeType":mimeType,"bitsPerSecond":bitsPerSecond});this._StartMediaRecorder(mimeType)}catch(err){console.error("[Video Recorder] Failed to start recording: ",err);this.PostToRuntime("error")}}async _OnStartScreenRecording(e){const containerPart=e["containerPart"];const videoPart=e["videoPart"];let audioPart=e["audioPart"];const systemAudio=e["systemAudio"]&&audioPart; const bitsPerSecond=e["bitsPerSecond"];this._StopAnyPriorRecording();let videoTracks=[];let audioTracks=[];try{if(videoPart){const videoStream=await navigator["mediaDevices"]["getDisplayMedia"]({"video":true,"selfBrowserSurface":"include","audio":systemAudio?{"channelCount":2}:false,"systemAudio":systemAudio?"include":"exclude"});videoTracks=videoStream["getVideoTracks"]();if(systemAudio)audioTracks=videoStream["getAudioTracks"]()}if(audioPart&&audioTracks.length===0&&self["C3Audio_GetOutputStream"]){const audioStream= self["C3Audio_GetOutputStream"]();audioTracks=audioStream["getAudioTracks"]()}if(audioTracks.length===0)audioPart="";const mimeType=this._GetMimeTypeFromParts(containerPart,videoPart,audioPart);console.log(`[Video recorder] Recording with MIME type '${mimeType}'`);this._mediaStream=new MediaStream([...videoTracks,...audioTracks]);this._stopStreamOnEnd=true;this._mediaStream.addEventListener("inactive",()=>this._OnMediaStreamInactive());this._mediaRecorder=new MediaRecorder(this._mediaStream,{"mimeType":mimeType, "bitsPerSecond":bitsPerSecond});this._StartMediaRecorder(mimeType)}catch(err){console.error("[Video Recorder] Failed to start recording: ",err);this.PostToRuntime("error")}}async _OnStartUserMediaRecording(e){const containerPart=e["containerPart"];const videoPart=e["videoPart"];const audioPart=e["audioPart"];const bitsPerSecond=e["bitsPerSecond"];this._StopAnyPriorRecording();if(!self["C3UserMedia_GetLastMediaStream"])return;const mediaStream=self["C3UserMedia_GetLastMediaStream"]();if(!mediaStream)return; try{this._mediaStream=mediaStream;this._stopStreamOnEnd=false;const mimeType=this._GetMimeTypeFromParts(containerPart,videoPart,audioPart);console.log(`[Video recorder] Recording with MIME type '${mimeType}'`);this._mediaRecorder=new MediaRecorder(this._mediaStream,{"mimeType":mimeType,"bitsPerSecond":bitsPerSecond});this._StartMediaRecorder(mimeType)}catch(err){console.error("[Video Recorder] Failed to start recording: ",err);this.PostToRuntime("error")}}_StartMediaRecorder(mimeType){this._mediaRecorder["ondataavailable"]= e=>{this._recordedChunks.push(e.data)};this._mediaRecorder["onerror"]=err=>{console.error("[Video Recorder] Error recording: ",err);this.PostToRuntime("error")};this._mediaRecorder["onwarning"]=e=>{console.warn("[Video Recorder] Recording warning: ",e)};this._mediaRecorder["onstop"]=async e=>{let blob=new Blob(this._recordedChunks,{"type":mimeType});if(mimeType.toLowerCase().includes("/webm"))blob=await MakeWebMSeekable(blob);this._lastRecordingUrl=URL.createObjectURL(blob);this.PostToRuntime("recording-ready", {"url":this._lastRecordingUrl})};this._mediaRecorder["start"]()}_OnMediaStreamInactive(){this.PostToRuntime("screen-recording-stopped");this._OnStopRecording()}_OnStopRecording(){if(this._mediaRecorder){this._mediaRecorder.stop();this._mediaRecorder=null}if(this._mediaStream){if(this._stopStreamOnEnd)this._StopStreamVideoTracks(this._mediaStream);this._mediaStream=null}}};self.RuntimeInterface.AddDOMHandlerClass(HANDLER_CLASS)};
| ver. 1.4 |
Github
|
.
| PHP 8.2.29 | Генераци� �траницы: 0.01 |
proxy
|
phpinfo
|
�а�тройка