krono-flow 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,4 +1,4 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).kronoFlow=t()}(this,function(){"use strict";var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)};function t(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function i(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(i.prototype=r.prototype,new i)}var r=function(){return r=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++)for(var a in t=arguments[r])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},r.apply(this,arguments)};function i(e,t,r,i){return new(r||(r=Promise))(function(a,n){function s(e){try{c(i.next(e))}catch(e){n(e)}}function o(e){try{c(i.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,o)}c((i=i.apply(e,t||[])).next())})}function a(e,t){var r,i,a,n={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=o(0),s.throw=o(1),s.return=o(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(c){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(n=0)),n;)try{if(r=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,i=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if(!(a=n.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){n=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){n.label=o[1];break}if(6===o[0]&&n.label<a[1]){n.label=a[1],a=o;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(o);break}a[2]&&n.ops.pop(),n.trys.pop();continue}o=t.call(e,n)}catch(e){o=[6,e],i=0}finally{r=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,c])}}}function n(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],i=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function s(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=n(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=e[r]&&function(t){return new Promise(function(i,a){(function(e,t,r,i){Promise.resolve(i).then(function(t){e({value:t,done:r})},t)})(i,a,(t=e[r](t)).done,t.value)})}}}let o;"function"==typeof SuppressedError&&SuppressedError;const c=new Uint8Array(16);function l(){if(!o&&(o="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!o))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return o(c)}const u=[];for(let e=0;e<256;++e)u.push((e+256).toString(16).slice(1));var h={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function d(e,t,r){if(h.randomUUID&&!e)return h.randomUUID();const i=(e=e||{}).random||(e.rng||l)();return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return u[e[t+0]]+u[e[t+1]]+u[e[t+2]]+u[e[t+3]]+"-"+u[e[t+4]]+u[e[t+5]]+"-"+u[e[t+6]]+u[e[t+7]]+"-"+u[e[t+8]]+u[e[t+9]]+"-"+u[e[t+10]]+u[e[t+11]]+u[e[t+12]]+u[e[t+13]]+u[e[t+14]]+u[e[t+15]]}(i)}var f={}.toString;function m(e){return function(t){return f.call(t)==="[object "+e+"]"}}var p,g=m("Object"),v=m("String"),y=(p=["Function","AsyncFunction","GeneratorFunction"],function(e){for(var t=f.call(e),r=0,i=p.length;r<i;r++)if(t==="[object "+p[r]+"]")return!0;return!1}),b=m("Number"),k=m("Boolean"),T=m("Date"),w={}.hasOwnProperty,S=w.toString,x=S.call(Object);function C(e){return null==e}function E(e){if(!e||"[object Object]"!==f.call(e))return!1;var t=Object.getPrototypeOf(e);if(!t)return!0;var r=w.call(t,"constructor")&&t.constructor;return"function"==typeof r&&S.call(r)===x}function A(e){if(C(e)||"object"!=typeof e)return e;if(T(e))return new Date(e);if(!E(e)&&!Array.isArray(e))return e;var t=Array.isArray(e)?[]:{};return Object.keys(e).forEach(function(r){t[r]=A(e[r])}),t}function P(e,t,r){if(e===t)return!0;if(g(e)&&g(t)){for(var i={},a=r||Object.keys(e),n=0,s=a.length;n<s;n++){var o=a[n];if(!t.hasOwnProperty(o)||!P(e[o],t[o]))return!1;i[o]=!0}for(n=0,s=(a=r||Object.keys(t)).length;n<s;n++){o=a[n];if(!i.hasOwnProperty(o))return!1}return!0}if(T(e)&&T(t))return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(n=0,s=e.length;n<s;n++)if(!P(e[n],t[n]))return!1;return!0}return e===t}var I={isNil:C,isString:v,isNumber:b,isObject:g,isBoolean:k,isDate:T,isFunction:y,isPlainObject:E,equal:P,extend:function(e,t,r){if(null===t||"object"!=typeof t)return e;r||(r=Object.keys(t));for(var i=0,a=r.length;i<a;){var n=r[i];e[n]=t[n],i++}return e},clone:A},R=function(){function e(){this.__eHash={}}return e.prototype.on=function(e,t){if(y(t))if(Array.isArray(e))for(var r=0,i=e.length;r<i;r++)this.on(e[r],t);else{this.__eHash.hasOwnProperty(e)||(this.__eHash[e]=[]);r=0;var a=this.__eHash[e];for(i=a.length;r<i;r++)if(a[r]===t)return;this.__eHash[e].push(t)}},e.prototype.once=function(e,t){var r=this;if(y(t))if(Array.isArray(e))for(var i=0,a=e.length;i<a;i++)this.once(e[i],t);else{var n=function(){t.apply(r,Array.prototype.slice.call(arguments)),r.off(e,n)};if(n.__eventCb=t,Array.isArray(e))for(i=0,a=e.length;i<a;i++)this.once(e[i],t);else this.on(e,n)}},e.prototype.off=function(e,t){if(Array.isArray(e))for(var r=0,i=e.length;r<i;r++)this.off(e[r],t);else if(this.__eHash.hasOwnProperty(e))if(t){r=0;var a=this.__eHash[e];for(i=a.length;r<i;r++)if(a[r]===t||a[r].__eventCb===t){a.splice(r,1);break}}else delete this.__eHash[e]},e.prototype.emit=function(e){for(var t=this,r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];if(Array.isArray(e))e.forEach(function(e){if(e&&t.__eHash.hasOwnProperty(e)){var i=t.__eHash[e];if(i.length)for(var a=0,n=(i=i.slice()).length;a<n;a++){var s=i[a];y(s)&&s.apply(t,r)}}});else if(e){var a=this.__eHash[e];if(a&&a.length)for(var n=0,s=(a=a.slice()).length;n<s;n++){var o=a[n];y(o)&&o.apply(this,r)}}},e}(),O={left:"auto",top:"auto",right:"auto",bottom:"auto",width:"auto",height:"auto",lineHeight:"normal",fontFamily:"Arial",fontSize:16,fontWeight:400,fontStyle:"normal",letterSpacing:0,paragraphSpacing:0,textAlign:"left",textVerticalAlign:"top",textDecoration:[],textShadow:"none",color:[0,0,0,1],visibility:"visible",opacity:1,backgroundColor:"transparent",fill:[],fillOpacity:[],fillEnable:[],fillMode:[],fillRule:"nonzero",stroke:[],strokeEnable:[],strokeWidth:[],strokePosition:[],strokeMode:[],strokeDasharray:[],strokeLinecap:"butt",strokeLinejoin:"miter",strokeMiterlimit:0,translateX:0,translateY:0,scaleX:1,scaleY:1,rotateZ:0,transformOrigin:["center","center"],mixBlendMode:"normal",objectFit:"fill",borderTopLeftRadius:0,borderTopRightRadius:0,borderBottomLeftRadius:0,borderBottomRightRadius:0};var M=2048,_=!1,D=M,B=!1,F={debug:!1,offscreenCanvas:!1,get maxTextureSize(){return M},set maxTextureSize(e){M=B?Math.min(e,D):e,_=!0},get MAX_TEXTURE_SIZE(){return D},MAX_TEXTURE_UNITS:8,MAX_VARYING_VECTORS:15,init:function(e,t,r){_?e<M&&(M=e):M=Math.min(M,e),B=!0,D=e,this.MAX_TEXTURE_UNITS=t,this.MAX_VARYING_VECTORS=r},historyTime:1e3,decoderWorker:"",decoderWorkerStr:"",encoderWorker:"",encoderWorkerStr:"",decodeNextDuration:0,releasePrevDuration:0,gopMinDuration:0,preloadAll:!1,singleSample:!1,mute:!1,indexedDB:!1},N=1e3/60,L={},U="function"==typeof OffscreenCanvas&&OffscreenCanvas.prototype.getContext;var z,W,V,H,j,X,q,G,K,Y,$,Q,Z,J,ee,te,re,ie,ae={},ne={requestAnimationFrame:function(e){return e?("undefined"!=typeof requestAnimationFrame?(ne.requestAnimationFrame=requestAnimationFrame.bind(null),t=requestAnimationFrame(e)):(t=setTimeout(e,N),ne.requestAnimationFrame=function(e){return setTimeout(e,N)}),t):-1;var t},cancelAnimationFrame:function(e){var t;return"undefined"!=typeof cancelAnimationFrame?(ne.cancelAnimationFrame=cancelAnimationFrame.bind(null),t=cancelAnimationFrame(e)):(t=clearTimeout(e),ne.cancelAnimationFrame=function(e){return clearTimeout(e)}),t},now:function(){return"undefined"!=typeof performance?(ne.now=function(){return Math.floor(performance.now())},Math.floor(performance.now())):(ne.now=Date.now.bind(Date),Date.now())},hasOffscreenCanvas:function(e){return e&&L.hasOwnProperty(e)},getOffscreenCanvas:function(e,t,r,i){return function(e,t,r,i){var a;a=r?L[r]?L[r]:L[r]=!F.debug&&F.offscreenCanvas&&U?new OffscreenCanvas(e,t):document.createElement("canvas"):!F.debug&&F.offscreenCanvas&&U?new OffscreenCanvas(e,t):document.createElement("canvas"),e=Math.ceil(e),t=Math.ceil(t),a.width=e,a.height=t,a.style.position="fixed",a.style.left="9999px",a.style.top="0px",a.style.webkitFontSmoothing="antialiased",a.style.mozOsxFontSmoothing="grayscale",F.debug&&(a.style.width=e+"px",a.style.height=t+"px"),a instanceof HTMLCanvasElement&&(document.body.appendChild(a),r&&a.setAttribute("key",r));var n=a.getContext("2d",i);return n||ne.error("Total canvas memory use exceeds the maximum limit"),{canvas:a,ctx:n,available:!0,release:function(){this.available&&!F.debug&&(this.available=!1,n.globalAlpha=1,n.globalCompositeOperation="source-over",n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,e,t),a.width=a.height=0,a instanceof HTMLCanvasElement&&document.body.removeChild(a),a=null)}}}(e,t,r,i)},isWebGLTexture:function(e){if(e&&"undefined"!=typeof WebGLTexture)return e instanceof WebGLTexture},defaultFontFamily:"Arial",defaultFontSize:16,getFontCanvas:function(){return ne.getOffscreenCanvas(16,16,"__$$CHECK_SUPPORT_FONT_FAMILY$$__",{willReadFrequently:!0})},checkSupportFontFamily:function(e){if(e===this.defaultFontFamily)return!0;if(ae.hasOwnProperty(e))return ae[e];var t=ne.getFontCanvas().ctx;t.textAlign="center",t.fillStyle="#000",t.textBaseline="middle",z||(t.clearRect(0,0,16,16),t.font="16px "+this.defaultFontFamily,t.fillText("a",8,8),z=t.getImageData(0,0,16,16).data),t.clearRect(0,0,16,16),/\s/.test(e)&&(e='"'+e.replace(/"/g,'\\"')+'"'),t.font="16px "+e+","+this.defaultFontFamily,t.fillText("a",8,8);for(var r=t.getImageData(0,0,16,16).data,i=0,a=r.length;i<a;i++)if(z[i]!==r[i])return ae[e]=!0;return ae[e]=!1},addArrayBufferFont:function(e,t){return i(this,void 0,void 0,function(){var r;return a(this,function(i){switch(i.label){case 0:return"undefined"==typeof document||"undefined"==typeof FontFace?[3,2]:[4,(r=new FontFace(e,t)).load()];case 1:i.sent(),document.fonts.add(r),i.label=2;case 2:return[2]}})})},addLocalFont:function(e){return i(this,void 0,void 0,function(){var t;return a(this,function(r){switch(r.label){case 0:return"undefined"==typeof document||"undefined"==typeof FontFace?[3,2]:[4,(t=new FontFace(e,"local(".concat(e))).load()];case 1:r.sent(),document.fonts.add(t),r.label=2;case 2:return[2]}})})},loadArrayBufferImg:function(e){return i(this,void 0,void 0,function(){var t,r;return a(this,function(i){return t=new Blob([e]),r=new Image,[2,new Promise(function(e,i){r.onload=function(){e(r)},r.onerror=function(e){i(e)},r.src=URL.createObjectURL(t)})]})})},pdfjsLibWorkerSrc:"https://gw.alipayobjects.com/os/lib/pdfjs-dist/3.11.174/build/pdf.worker.min.js",loadArrayBufferPdf:function(e){return i(this,void 0,void 0,function(){var t,r,i,n,s,o,c,l,u;return a(this,function(a){switch(a.label){case 0:return(t=window.pdfjsLib).GlobalWorkerOptions.workerSrc=ne.pdfjsLibWorkerSrc,r=new Blob([e]),i=URL.createObjectURL(r),[4,t.getDocument(i).promise];case 1:return[4,a.sent().getPage(1)];case 2:return n=a.sent(),s=n.getViewport({scale:1}),(o=document.createElement("canvas")).width=s.width,o.height=s.height,c=o.getContext("2d"),[4,n.render({viewport:s,canvasContext:c,background:"transparent"}).promise];case 3:return a.sent(),[4,new Promise(function(e,t){o.toBlob(function(r){r?e(r):t("")})})];case 4:return l=a.sent(),u=new Image,[2,new Promise(function(e,t){u.onload=function(){e(u)},u.onerror=function(e){t(e)},u.src=URL.createObjectURL(l)})]}})})},loadLocalFonts:function(){return i(this,void 0,void 0,function(){var e;return a(this,function(t){switch(t.label){case 0:if("undefined"==typeof navigator)return[3,5];t.label=1;case 1:return t.trys.push([1,4,,5]),[4,navigator.permissions.query({name:"local-fonts"})];case 2:return"denied"===t.sent().state?(ne.error("No Permission."),[2,[]]):[4,window.queryLocalFonts()];case 3:return[2,t.sent()];case 4:return e=t.sent(),ne.error(e),[2,[]];case 5:return[2,[]]}})})},uploadBlobImgSrc:function(e){return i(this,void 0,void 0,function(){return a(this,function(e){return[2]})})},log:function(e){console.log(e)},warn:function(e){console.warn(e)},error:function(e){console.error(e)}};function se(e,t){if(void 0===t&&(t=!1),"auto"===e)return{v:0,u:W.AUTO};var r=parseFloat(e)||0;return/%$/.test(e)?{v:r,u:W.PERCENT}:/px$/i.test(e)?{v:r,u:W.PX}:/deg$/i.test(e)?{v:r,u:t?W.PX:W.DEG}:{v:r,u:t?W.PX:W.NUMBER}}!function(e){e[e.AUTO=0]="AUTO",e[e.PX=1]="PX",e[e.PERCENT=2]="PERCENT",e[e.NUMBER=3]="NUMBER",e[e.DEG=4]="DEG",e[e.RGBA=5]="RGBA",e[e.BOOLEAN=6]="BOOLEAN",e[e.STRING=7]="STRING",e[e.GRADIENT=8]="GRADIENT",e[e.BLUR=9]="BLUR",e[e.PATTERN=10]="PATTERN",e[e.SHADOW=11]="SHADOW",e[e.MATRIX=12]="MATRIX"}(W||(W={})),function(e){e[e.LEFT=0]="LEFT",e[e.RIGHT=1]="RIGHT",e[e.CENTER=2]="CENTER",e[e.JUSTIFY=3]="JUSTIFY"}(V||(V={})),function(e){e[e.TOP=0]="TOP",e[e.MIDDLE=1]="MIDDLE",e[e.BOTTOM=2]="BOTTOM"}(H||(H={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.MULTIPLY=1]="MULTIPLY",e[e.SCREEN=2]="SCREEN",e[e.OVERLAY=3]="OVERLAY",e[e.DARKEN=4]="DARKEN",e[e.LIGHTEN=5]="LIGHTEN",e[e.COLOR_DODGE=6]="COLOR_DODGE",e[e.COLOR_BURN=7]="COLOR_BURN",e[e.HARD_LIGHT=8]="HARD_LIGHT",e[e.SOFT_LIGHT=9]="SOFT_LIGHT",e[e.DIFFERENCE=10]="DIFFERENCE",e[e.EXCLUSION=11]="EXCLUSION",e[e.HUE=12]="HUE",e[e.SATURATION=13]="SATURATION",e[e.COLOR=14]="COLOR",e[e.LUMINOSITY=15]="LUMINOSITY"}(j||(j={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.ITALIC=1]="ITALIC",e[e.OBLIQUE=2]="OBLIQUE"}(X||(X={})),function(e){e[e.LINEAR=0]="LINEAR",e[e.RADIAL=1]="RADIAL",e[e.CONIC=2]="CONIC"}(q||(q={})),function(e){e[e.NONE=0]="NONE",e[e.UNION=1]="UNION",e[e.SUBTRACT=2]="SUBTRACT",e[e.INTERSECT=3]="INTERSECT",e[e.XOR=4]="XOR"}(G||(G={})),function(e){e[e.NON_ZERO=0]="NON_ZERO",e[e.EVEN_ODD=1]="EVEN_ODD"}(K||(K={})),function(e){e[e.NONE=0]="NONE",e[e.OUTLINE=1]="OUTLINE",e[e.ALPHA=2]="ALPHA",e[e.GRAY=3]="GRAY",e[e.ALPHA_WITH=4]="ALPHA_WITH",e[e.GRAY_WITH=5]="GRAY_WITH"}(Y||(Y={})),function(e){e[e.BUTT=0]="BUTT",e[e.ROUND=1]="ROUND",e[e.SQUARE=2]="SQUARE"}($||($={})),function(e){e[e.MITER=0]="MITER",e[e.ROUND=1]="ROUND",e[e.BEVEL=2]="BEVEL"}(Q||(Q={})),function(e){e[e.CENTER=0]="CENTER",e[e.INSIDE=1]="INSIDE",e[e.OUTSIDE=2]="OUTSIDE"}(Z||(Z={})),function(e){e[e.TILE=0]="TILE",e[e.FILL=1]="FILL",e[e.STRETCH=2]="STRETCH",e[e.FIT=3]="FIT"}(J||(J={})),function(e){e[e.VISIBLE=0]="VISIBLE",e[e.HIDDEN=1]="HIDDEN"}(ee||(ee={})),function(e){e[e.NONE=0]="NONE",e[e.UNDERLINE=1]="UNDERLINE",e[e.LINE_THROUGH=2]="LINE_THROUGH"}(te||(te={})),function(e){e[e.VISIBLE=0]="VISIBLE",e[e.HIDDEN=1]="HIDDEN"}(re||(re={})),function(e){e[e.FILL=0]="FILL",e[e.CONTAIN=1]="CONTAIN",e[e.COVER=2]="COVER"}(ie||(ie={}));var oe=["fontFamily","fontSize","fontWeight","lineHeight","letterSpacing","paragraphSpacing","fontStyle","textAlign","textDecoration","color","textShadow","stroke","strokeWidth","strokeEnable"],ce={StyleUnit:W,TEXT_ALIGN:V,TEXT_VERTICAL_ALIGN:H,MIX_BLEND_MODE:j,FONT_STYLE:X,GRADIENT:q,FILL_RULE:K,MASK:Y,STROKE_LINE_CAP:$,STROKE_LINE_JOIN:Q,STROKE_POSITION:Z,PATTERN_FILL_TYPE:J,VISIBILITY:ee,TEXT_DECORATION:te,OVERFLOW:re,calUnit:se,RICH_KEYS:oe},le={position:/(([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?[pxremvwhina%]*)|(left|top|right|bottom|center)){1,2}/gi,gradient:/\b(\w+)-?gradient\s*\((.+)\)/i,img:/(?:\burl\((['"]?)(.*?)\1\))|(?:\b((data:)))/i,shadow:/([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:px)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:px)?)\s+((?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:px)?)\s+((?:#[a-f\d]{3,8})|(?:rgba?\s*\(.+?\)))/i};function ue(e){if(Array.isArray(e))return e;var t=[];if(!e||/transparent/i.test(e))t=[0,0,0,0];else if(/^#?[a-f\d]{3,8}$/i.test(e))3===(e=e.replace("#","")).length||4===e.length?(t.push(parseInt(e.charAt(0)+e.charAt(0),16)),t.push(parseInt(e.charAt(1)+e.charAt(1),16)),t.push(parseInt(e.charAt(2)+e.charAt(2),16)),4===e.length?t[3]=parseInt(e.charAt(3)+e.charAt(3),16):t[3]=1):6===e.length?(t.push(parseInt(e.slice(0,2),16)),t.push(parseInt(e.slice(2,4),16)),t.push(parseInt(e.slice(4),16)),t[3]=1):8===e.length?(t.push(parseInt(e.slice(0,2),16)),t.push(parseInt(e.slice(2,4),16)),t.push(parseInt(e.slice(4,6),16)),t.push(parseInt(e.slice(6),16)/255)):(t[0]=t[1]=t[2]=0,t[3]=1);else{var r=e.match(/rgba?\s*\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)/i);r?(t=[parseInt(r[1]),parseInt(r[2]),parseInt(r[3])],C(r[4])?t[3]=1:t[3]=parseFloat(r[4])):t=[0,0,0,0]}return t}function he(e){var t=ue(e);if(Array.isArray(t)){var r=Math.min(255,Math.max(Math.round(t[0]),0)),i=Math.min(255,Math.max(Math.round(t[1]),0)),a=Math.min(255,Math.max(Math.round(t[2]),0));if(3===t.length||4===t.length){if(4===t.length){var n=Math.min(1,Math.max(t[3],0));if(n<1)return"rgba("+r+","+i+","+a+","+n+")"}return"rgba("+r+","+i+","+a+",1)"}}return e||"rgba(0,0,0,0)"}function de(e){var t=e.toString(16).toUpperCase();return 1===t.length&&(t="0"+t),t}var fe={color2rgbaInt:ue,color2rgbaStr:he,color2hexStr:function(e){var t=ue(e);if(Array.isArray(t)){var r=Math.min(255,Math.max(Math.round(t[0]),0)),i=Math.min(255,Math.max(Math.round(t[1]),0)),a=Math.min(255,Math.max(Math.round(t[2]),0));if(3===t.length||4===t.length){if(4===t.length){var n=Math.min(1,Math.max(t[3],0));if(n<1)return"#"+de(r)+de(i)+de(a)+de(Math.floor(255*n))}return"#"+de(r)+de(i)+de(a)}}return e||"#000"},color2gl:function(e){return Array.isArray(e)||(e=ue(e)),[e[0]/255,e[1]/255,e[2]/255,3===e.length?1:e[3]]},clampColor:function(e){var t=Math.min(255,Math.max(Math.round(e[0]),0)),r=Math.min(255,Math.max(Math.round(e[1]),0)),i=Math.min(255,Math.max(Math.round(e[2]),0));return e.length>3?[t,r,i,Math.min(1,Math.max(0,e[3]))]:[t,r,i]}},me=function(){function e(){this.table=new Uint16Array(16),this.trans=new Uint16Array(288)}function t(t,r){this.source=t,this.sourceIndex=0,this.tag=0,this.bitcount=0,this.dest=r,this.destLen=0,this.ltree=new e,this.dtree=new e}var r=new e,i=new e,a=new Uint8Array(30),n=new Uint16Array(30),s=new Uint8Array(30),o=new Uint16Array(30),c=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),l=new e,u=new Uint8Array(320);function h(e,t,r,i){var a,n;for(a=0;a<r;++a)e[a]=0;for(a=0;a<30-r;++a)e[a+r]=a/r|0;for(n=i,a=0;a<30;++a)t[a]=n,n+=1<<e[a]}var d=new Uint16Array(16);function f(e,t,r,i){var a,n;for(a=0;a<16;++a)e.table[a]=0;for(a=0;a<i;++a)e.table[t[r+a]]++;for(e.table[0]=0,n=0,a=0;a<16;++a)d[a]=n,n+=e.table[a];for(a=0;a<i;++a)t[r+a]&&(e.trans[d[t[r+a]]++]=a)}function m(e){e.bitcount--||(e.tag=e.source[e.sourceIndex++],e.bitcount=7);var t=1&e.tag;return e.tag>>>=1,t}function p(e,t,r){if(!t)return r;for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<<e.bitcount,e.bitcount+=8;var i=e.tag&65535>>>16-t;return e.tag>>>=t,e.bitcount-=t,i+r}function g(e,t){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<<e.bitcount,e.bitcount+=8;var r=0,i=0,a=0,n=e.tag;do{i=2*i+(1&n),n>>>=1,++a,r+=t.table[a],i-=t.table[a]}while(i>=0);return e.tag=n,e.bitcount-=a,t.trans[r+i]}function v(e,t,r){var i,a,n,s,o,h;for(i=p(e,5,257),a=p(e,5,1),n=p(e,4,4),s=0;s<19;++s)u[s]=0;for(s=0;s<n;++s){var d=p(e,3,0);u[c[s]]=d}for(f(l,u,0,19),o=0;o<i+a;){var m=g(e,l),v=void 0;switch(m){case 16:for(v=u[o-1],h=p(e,2,3);h;--h)u[o++]=v;break;case 17:for(h=p(e,3,3);h;--h)u[o++]=0;break;case 18:for(h=p(e,7,11);h;--h)u[o++]=0;break;default:u[o++]=m}}f(t,u,0,i),f(r,u,i,a)}function y(e,t,r){for(;;){var i=g(e,t);if(256===i)return 0;if(i<256)e.dest[e.destLen++]=i;else{var c,l,u,h=void 0;for(c=p(e,a[i-=257],n[i]),l=g(e,r),h=u=e.destLen-p(e,s[l],o[l]);h<u+c;++h)e.dest[e.destLen++]=e.dest[h]}}}function b(e){for(var t,r;e.bitcount>8;)e.sourceIndex--,e.bitcount-=8;if((t=256*(t=e.source[e.sourceIndex+1])+e.source[e.sourceIndex])!==(65535&~(256*e.source[e.sourceIndex+3]+e.source[e.sourceIndex+2])))return-3;for(e.sourceIndex+=4,r=t;r;--r)e.dest[e.destLen++]=e.source[e.sourceIndex++];return e.bitcount=0,0}return function(e,t){var r;for(r=0;r<7;++r)e.table[r]=0;for(e.table[7]=24,e.table[8]=152,e.table[9]=112,r=0;r<24;++r)e.trans[r]=256+r;for(r=0;r<144;++r)e.trans[24+r]=r;for(r=0;r<8;++r)e.trans[168+r]=280+r;for(r=0;r<112;++r)e.trans[176+r]=144+r;for(r=0;r<5;++r)t.table[r]=0;for(t.table[5]=32,r=0;r<32;++r)t.trans[r]=r}(r,i),h(a,n,4,3),h(s,o,2,1),a[28]=0,n[28]=258,function(e,a){var n,s,o=new t(e,a);do{switch(n=m(o),p(o,2,0)){case 0:s=b(o);break;case 1:s=y(o,r,i);break;case 2:v(o,o.ltree,o.dtree),s=y(o,o.ltree,o.dtree);break;default:s=-3}if(0!==s)throw new Error("Data error")}while(!n);return o.destLen<o.dest.length?"function"==typeof o.dest.slice?o.dest.slice(0,o.destLen):o.dest.subarray(0,o.destLen):o.dest}}(),pe={UTF16:function(e,t,r){for(var i=[],a=r/2,n=0;n<a;n++,t+=2)i[n]=e.getUint16(t);return String.fromCharCode.apply(null,i)}},ge={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};function ve(e,t){for(var r="",i=t;i<t+4;i++)r+=String.fromCharCode(e.getInt8(i));return r}function ye(e,t){return e.getUint16(t,!1)}function be(e,t){return e.getUint32(t,!1)}pe.MACSTRING=function(e,t,r,i){var a=ge[i];if(void 0!==a){for(var n="",s=0;s<r;s++){var o=e.getUint8(t+s);n+=o<=127?String.fromCharCode(o):a[127&o]}return n}};var ke={byte:1,uShort:2,short:2,uLong:4,fixed:4,longDateTime:8,tag:4};function Te(e,t){for(var r=[],i=12,a=0;a<t;a+=1){var n=ve(e,i),s=be(e,i+4),o=be(e,i+8),c=be(e,i+12);r.push({tag:n,checksum:s,offset:o,length:c,compression:!1}),i+=16}return r}function we(e,t){if("WOFF"===t.compression){var r=new Uint8Array(e.buffer,t.offset+2,t.compressedLength-2),i=new Uint8Array(t.length);return me(r,i),i.byteLength!==t.length&&ne.error("Decompression error: "+t.tag+" decompressed length doesn't match recorded length"),{data:new DataView(i.buffer,0),offset:0}}return{data:e,offset:t.offset}}var Se=function(){function e(e,t){this.data=e,this.offset=t,this.relativeOffset=0}return e.prototype.parseByte=function(){var e=this.data.getUint8(this.offset+this.relativeOffset);return this.relativeOffset+=1,e},e.prototype.parseUShort=function(){var e=this.data.getUint16(this.offset+this.relativeOffset);return this.relativeOffset+=2,e},e.prototype.parseULong=function(){var e=be(this.data,this.offset+this.relativeOffset);return this.relativeOffset+=4,e},e.prototype.parseShort=function(){var e=this.data.getInt16(this.offset+this.relativeOffset);return this.relativeOffset+=2,e},e.prototype.parseFixed=function(){var e,t,r=(e=this.data,t=this.offset+this.relativeOffset,e.getInt16(t,!1)+e.getUint16(t+2,!1)/65535);return this.relativeOffset+=4,r},e.prototype.parseVersion=function(e){var t=ye(this.data,this.offset+this.relativeOffset),r=ye(this.data,this.offset+this.relativeOffset+2);return this.relativeOffset+=4,void 0===e&&(e=4096),t+r/e/10},e.prototype.skip=function(e,t){void 0===t&&(t=1),this.relativeOffset+=ke[e]*t},e}(),xe=["copyright","fontFamily","fontSubfamily","uniqueID","fullName","version","postScriptName","trademark","manufacturer","designer","description","manufacturerURL","designerURL","license","licenseURL","reserved","preferredFamily","preferredSubfamily","compatibleFullName","sampleText","postScriptFindFontName","wwsFamily","wwsSubfamily"],Ce={0:"en",1:"fr",2:"de",3:"it",4:"nl",5:"sv",6:"es",7:"da",8:"pt",9:"no",10:"he",11:"ja",12:"ar",13:"fi",14:"el",15:"is",16:"mt",17:"tr",18:"hr",19:"zh-Hant",20:"ur",21:"hi",22:"th",23:"ko",24:"lt",25:"pl",26:"hu",27:"es",28:"lv",29:"se",30:"fo",31:"fa",32:"ru",33:"zh",34:"nl-BE",35:"ga",36:"sq",37:"ro",38:"cz",39:"sk",40:"si",41:"yi",42:"sr",43:"mk",44:"bg",45:"uk",46:"be",47:"uz",48:"kk",49:"az-Cyrl",50:"az-Arab",51:"hy",52:"ka",53:"mo",54:"ky",55:"tg",56:"tk",57:"mn-CN",58:"mn",59:"ps",60:"ks",61:"ku",62:"sd",63:"bo",64:"ne",65:"sa",66:"mr",67:"bn",68:"as",69:"gu",70:"pa",71:"or",72:"ml",73:"kn",74:"ta",75:"te",76:"si",77:"my",78:"km",79:"lo",80:"vi",81:"id",82:"tl",83:"ms",84:"ms-Arab",85:"am",86:"ti",87:"om",88:"so",89:"sw",90:"rw",91:"rn",92:"ny",93:"mg",94:"eo",128:"cy",129:"eu",130:"ca",131:"la",132:"qu",133:"gn",134:"ay",135:"tt",136:"ug",137:"dz",138:"jv",139:"su",140:"gl",141:"af",142:"br",143:"iu",144:"gd",145:"gv",146:"ga",147:"to",148:"el-polyton",149:"kl",150:"az",151:"nn"},Ee={1078:"af",1052:"sq",1156:"gsw",1118:"am",5121:"ar-DZ",15361:"ar-BH",3073:"ar",2049:"ar-IQ",11265:"ar-JO",13313:"ar-KW",12289:"ar-LB",4097:"ar-LY",6145:"ary",8193:"ar-OM",16385:"ar-QA",1025:"ar-SA",10241:"ar-SY",7169:"aeb",14337:"ar-AE",9217:"ar-YE",1067:"hy",1101:"as",2092:"az-Cyrl",1068:"az",1133:"ba",1069:"eu",1059:"be",2117:"bn",1093:"bn-IN",8218:"bs-Cyrl",5146:"bs",1150:"br",1026:"bg",1027:"ca",3076:"zh-HK",5124:"zh-MO",2052:"zh",4100:"zh-SG",1028:"zh-TW",1155:"co",1050:"hr",4122:"hr-BA",1029:"cs",1030:"da",1164:"prs",1125:"dv",2067:"nl-BE",1043:"nl",3081:"en-AU",10249:"en-BZ",4105:"en-CA",9225:"en-029",16393:"en-IN",6153:"en-IE",8201:"en-JM",17417:"en-MY",5129:"en-NZ",13321:"en-PH",18441:"en-SG",7177:"en-ZA",11273:"en-TT",2057:"en-GB",1033:"en",12297:"en-ZW",1061:"et",1080:"fo",1124:"fil",1035:"fi",2060:"fr-BE",3084:"fr-CA",1036:"fr",5132:"fr-LU",6156:"fr-MC",4108:"fr-CH",1122:"fy",1110:"gl",1079:"ka",3079:"de-AT",1031:"de",5127:"de-LI",4103:"de-LU",2055:"de-CH",1032:"el",1135:"kl",1095:"gu",1128:"ha",1037:"he",1081:"hi",1038:"hu",1039:"is",1136:"ig",1057:"id",1117:"iu",2141:"iu-Latn",2108:"ga",1076:"xh",1077:"zu",1040:"it",2064:"it-CH",1041:"ja",1099:"kn",1087:"kk",1107:"km",1158:"quc",1159:"rw",1089:"sw",1111:"kok",1042:"ko",1088:"ky",1108:"lo",1062:"lv",1063:"lt",2094:"dsb",1134:"lb",1071:"mk",2110:"ms-BN",1086:"ms",1100:"ml",1082:"mt",1153:"mi",1146:"arn",1102:"mr",1148:"moh",1104:"mn",2128:"mn-CN",1121:"ne",1044:"nb",2068:"nn",1154:"oc",1096:"or",1123:"ps",1045:"pl",1046:"pt",2070:"pt-PT",1094:"pa",1131:"qu-BO",2155:"qu-EC",3179:"qu",1048:"ro",1047:"rm",1049:"ru",9275:"smn",4155:"smj-NO",5179:"smj",3131:"se-FI",1083:"se",2107:"se-SE",8251:"sms",6203:"sma-NO",7227:"sms",1103:"sa",7194:"sr-Cyrl-BA",3098:"sr",6170:"sr-Latn-BA",2074:"sr-Latn",1132:"nso",1074:"tn",1115:"si",1051:"sk",1060:"sl",11274:"es-AR",16394:"es-BO",13322:"es-CL",9226:"es-CO",5130:"es-CR",7178:"es-DO",12298:"es-EC",17418:"es-SV",4106:"es-GT",18442:"es-HN",2058:"es-MX",19466:"es-NI",6154:"es-PA",15370:"es-PY",10250:"es-PE",20490:"es-PR",3082:"es",1034:"es",21514:"es-US",14346:"es-UY",8202:"es-VE",2077:"sv-FI",1053:"sv",1114:"syr",1064:"tg",2143:"tzm",1097:"ta",1092:"tt",1098:"te",1054:"th",1105:"bo",1055:"tr",1090:"tk",1152:"ug",1058:"uk",1070:"hsb",1056:"ur",2115:"uz-Cyrl",1091:"uz",1066:"vi",1106:"cy",1160:"wo",1157:"sah",1144:"ii",1130:"yo"},Ae={0:"macintosh",1:"x-mac-japanese",2:"x-mac-chinesetrad",3:"x-mac-korean",6:"x-mac-greek",7:"x-mac-cyrillic",9:"x-mac-devanagai",10:"x-mac-gurmukhi",11:"x-mac-gujarati",12:"x-mac-oriya",13:"x-mac-bengali",14:"x-mac-tamil",15:"x-mac-telugu",16:"x-mac-kannada",17:"x-mac-malayalam",18:"x-mac-sinhalese",19:"x-mac-burmese",20:"x-mac-khmer",21:"x-mac-thai",22:"x-mac-lao",23:"x-mac-georgian",24:"x-mac-armenian",25:"x-mac-chinesesimp",26:"x-mac-tibetan",27:"x-mac-mongolian",28:"x-mac-ethiopic",29:"x-mac-ce",30:"x-mac-vietnamese",31:"x-mac-extarabic"},Pe={15:"x-mac-icelandic",17:"x-mac-turkish",18:"x-mac-croatian",24:"x-mac-ce",25:"x-mac-ce",26:"x-mac-ce",27:"x-mac-ce",28:"x-mac-ce",30:"x-mac-icelandic",37:"x-mac-romanian",38:"x-mac-ce",39:"x-mac-ce",40:"x-mac-ce",143:"x-mac-inuit",146:"x-mac-gaelic"};function Ie(e,t,r){switch(e){case 0:if(65535===t)return"und";if(r)return r[t];break;case 1:return Ce[t];case 3:return Ee[t]}}var Re="utf-16";function Oe(e,t,r){switch(e){case 0:return Re;case 1:return Pe[r]||Ae[t];case 3:if(1===t||10===t)return Re}}var Me={0:"unicode",1:"macintosh",2:"reserved",3:"windows"};function _e(e){return Me[e]}function De(e,t){var r,i=new Se(e,t),a=i.parseULong();r="Unsupported ltag table version.",1===a||fail(r),i.skip("uLong",1);for(var n=i.parseULong(),s=[],o=0;o<n;o++){for(var c="",l=t+i.parseUShort(),u=i.parseUShort(),h=l;h<l+u;++h)c+=String.fromCharCode(e.getInt8(h));s.push(c)}return s}var Be={parse:function(e){var t,r,i=new DataView(e,0),a=ve(i,0),n=!1;if(a===String.fromCharCode(0,1,0,0)||"true"===a||"typ1"===a)r=Te(i,t=ye(i,4));else if("OTTO"===a)r=Te(i,t=ye(i,4)),n=!0;else if("wOFF"===a){var s=ve(i,4);if(s===String.fromCharCode(0,1,0,0));else if("OTTO"!==s)return void ne.error("Unsupported OpenType flavor "+a);r=function(e,t){for(var r=[],i=44,a=0;a<t;a+=1){var n=ve(e,i),s=be(e,i+4),o=be(e,i+8),c=be(e,i+12),l=void 0;l=o<c&&"WOFF",r.push({tag:n,offset:s,compression:l,compressedLength:o,length:c}),i+=20}return r}(i,t=ye(i,12))}else if("wOF2"===a){ne.error("WOFF2 require an external decompressor library, see examples at: https://github.com/opentypejs/opentype.js/issues/183#issuecomment-1147228025")}else ne.error("Unsupported OpenType signature "+a);for(var o,c,l,u,h=2048,d=0,f=!1,m=0;m<t;m++){var p=r[m];if("head"===p.tag){var g=we(i,p);(v=new Se(g.data,g.offset)).parseVersion(),v.parseFixed(),v.parseULong(),v.parseULong(),v.parseUShort(),h=v.parseUShort()}else if("hhea"===p.tag){if(!f){g=we(i,p);(v=new Se(g.data,g.offset)).parseVersion(),o=Math.abs(v.parseShort()),c=Math.abs(v.parseShort()),d=Math.abs(v.parseShort()||0)}}else if("ltag"===p.tag){u=De((g=we(i,p)).data,g.offset)}else if("name"===p.tag)l=we(i,p);else if("OS/2"===p.tag){g=we(i,p);var v,y=(v=new Se(g.data,g.offset)).parseUShort();v.parseShort(),v.parseUShort(),v.parseUShort(),v.parseUShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort();for(var b=0;b<10;b++)v.parseByte();v.parseULong(),v.parseULong(),v.parseULong(),v.parseULong(),v.parseByte(),v.parseByte(),v.parseByte(),v.parseByte();var k=v.parseUShort(),T=y>=4&&(128&k||n);(T||void 0===o)&&(v.parseUShort(),v.parseUShort(),o=Math.abs(v.parseShort()),c=Math.abs(v.parseShort()),d=Math.abs(v.parseShort()||0),T&&(f=!0))}}var w=l?function(e,t,r){for(var i={},a=new Se(e,t),n=a.parseUShort(),s=a.parseUShort(),o=a.offset+a.parseUShort(),c=0;c<s;c++){var l=a.parseUShort(),u=a.parseUShort(),h=a.parseUShort(),d=a.parseUShort(),f=xe[d]||d,m=a.parseUShort(),p=a.parseUShort(),g=Ie(l,h,r),v=Oe(l,u,h),y=_e(l);if(void 0!==v&&void 0!==g&&void 0!==y){var b=void 0;if(b=v===Re?pe.UTF16(e,o+p,m):pe.MACSTRING(e,o+p,m,v)){var k=i[y];void 0===k&&(k=i[y]={});var T=k[f];void 0===T&&(T=k[f]={}),T[g]=b}}}return 1===n&&a.parseUShort(),i}(l.data,l.offset,u):{},S={};return w.macintosh&&Object.assign(S,w.macintosh),w.windows&&Object.assign(S,w.windows),{name:S,emSquare:h,ascent:o,descent:c,lineGap:d}}},Fe={name:"Arial",family:"Arial",lhr:1.14990234375,car:1.1171875,blr:.9052734375,lgr:.03271484375,list:[{style:"Regular",postscriptName:"Arial"}]},Ne="localFonts",Le="undefined"!=typeof navigator&&/win/i.test(navigator.platform),Ue={Arial:Fe},ze={Arial:Fe},We={},Ve={KEY_INFO:Ne,info:Ue,data:ze,hasRegister:function(e){return ze.hasOwnProperty(e)},registerLocalFonts:function(e){return i(this,void 0,void 0,function(){var t,r,i,n,s,o,c,l,u,h,d,f,m,p,g,v;return a(this,function(a){switch(a.label){case 0:return e?[3,2]:[4,ne.loadLocalFonts()];case 1:e=a.sent()||[],a.label=2;case 2:if(t={},"undefined"!=typeof localStorage)try{t=JSON.parse(localStorage.getItem(Ne)||"{}")}catch(e){}r=t.data||{},(!t.version||t.version<2)&&(r={}),i=0,n=e.length,a.label=3;case 3:return i<n?(s=e[i],o=s.postscriptName,c=s.family,l=s.style,Le?[4,ne.addLocalFont(o)]:[3,5]):[3,10];case 4:a.sent(),a.label=5;case 5:return r.hasOwnProperty(c)&&(u=r[c],Ue[c]=Ue[c]||{name:u.name,family:c,lhr:u.lhr,car:u.car,blr:u.blr,lgr:u.lgr,list:[]}),Ue.hasOwnProperty(c)?[3,8]:(h=Ue[c]={name:"",family:"",lhr:0,car:0,blr:0,lgr:0,list:[]},[4,s.blob()]);case 6:return[4,a.sent().arrayBuffer()];case 7:d=a.sent(),(f=Be.parse(d))&&f.name&&(h.name=(null===(p=f.name.preferredFamily)||void 0===p?void 0:p.zh)||(null===(g=f.name.preferredFamily)||void 0===g?void 0:g.en)||(null===(v=f.name.fontFamily)||void 0===v?void 0:v.zh)),h.name=h.name||c,h.family=c,m=this._cal(c,f),Object.assign(h,m),a.label=8;case 8:this._register(c,l,o),He(c),o!==c&&He(o),a.label=9;case 9:return i++,[3,3];case 10:return this.updateLocalStorage(),[2]}})})},registerAb:function(e,t){return i(this,void 0,void 0,function(){var r,i,n,s,o,c,l,u,h,d,f,m,p,g;return a(this,function(a){switch(a.label){case 0:return t&&ze.hasOwnProperty(t)?[2]:(r={},(i=Be.parse(e))&&i.name&&(r.family=(null===(l=i.name.preferredFamily)||void 0===l?void 0:l.en)||(null===(u=i.name.fontFamily)||void 0===u?void 0:u.en),r.name=(null===(h=i.name.preferredFamily)||void 0===h?void 0:h.zh)||(null===(d=i.name.preferredFamily)||void 0===d?void 0:d.en)||(null===(f=i.name.fontFamily)||void 0===f?void 0:f.zh)||r.family),n=r.family,s=(null===(m=i.name.preferredSubfamily)||void 0===m?void 0:m.en)||(null===(p=i.name.fontSubfamily)||void 0===p?void 0:p.en),o=null===(g=i.name.postScriptName)||void 0===g?void 0:g.en,n&&s&&o?[4,ne.addArrayBufferFont(n,e)]:[2]);case 1:return a.sent(),o===n?[3,3]:[4,ne.addArrayBufferFont(o,e)];case 2:a.sent(),a.label=3;case 3:return t&&t!==n&&t!==o?[4,ne.addArrayBufferFont(t,e)]:[3,5];case 4:a.sent(),a.label=5;case 5:return Ue.hasOwnProperty(n)||(c=this._cal(n,i),Object.assign(r,c),r.list=[],Ue[n]=ze[n]=r),this._register(n,s,o),t&&t!==n&&t!==o&&(Ue[t]=ze[t]=ze[n]),He(n),o!==n&&He(o),t&&t!==n&&t!==o&&He(t),[2,ze[n]]}})})},_cal:function(e,t){var r=0;return["times","helvetica","courier"].indexOf(e.toLowerCase())>-1&&(r=Math.round(.15*(t.ascent+t.descent))),{lhr:(t.ascent+r+t.descent+t.lineGap)/t.emSquare,car:(t.ascent+r+t.descent)/t.emSquare,blr:(t.ascent+r)/t.emSquare,lgr:t.lineGap/t.emSquare}},_register:function(e,t,r){for(var i=Ue[e],a=i.list=i.list||[],n=!1,s=0,o=a.length;s<o;s++){if(a[s].postscriptName===r){n=!0;break}}return n||a.push({style:t,postscriptName:r}),{family:e,postscriptName:r,data:ze[e]=ze[r]=i}},waitIfNotRegister:function(e,t){ze[e]||(We[e]=We[e]||[]).push(t)},updateLocalStorage:function(){var e={};for(var t in Ue)if(Ue.hasOwnProperty(t)){var r=Ue[t];e[t]={name:r.name,lhr:r.lhr,car:r.car,blr:r.blr,lgr:r.lgr}}"undefined"!=typeof localStorage&&localStorage.setItem(Ne,JSON.stringify({version:2,data:e}))}};function He(e){We.hasOwnProperty(e)&&(We[e].slice(0).forEach(function(e){e()}),delete We[e])}function je(e,t,r,i){return e*i-r*t}function Xe(){return new Float64Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}function qe(e){return!e||!e.length||1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}function Ge(e,t){if(qe(e))return new Float64Array(t);if(qe(t))return new Float64Array(e);for(var r=Xe(),i=0;i<4;i++){var a=e[i],n=e[i+4],s=e[i+8],o=e[i+12];r[i]=a*t[0]+n*t[1]+s*t[2]+o*t[3],r[i+4]=a*t[4]+n*t[5]+s*t[6]+o*t[7],r[i+8]=a*t[8]+n*t[9]+s*t[10]+o*t[11],r[i+12]=a*t[12]+n*t[13]+s*t[14]+o*t[15]}return r}function Ke(e){if(qe(e))return Xe();var t=new Float64Array(16);t[0]=e[5]*e[10]*e[15]-e[5]*e[11]*e[14]-e[9]*e[6]*e[15]+e[9]*e[7]*e[14]+e[13]*e[6]*e[11]-e[13]*e[7]*e[10],t[4]=-e[4]*e[10]*e[15]+e[4]*e[11]*e[14]+e[8]*e[6]*e[15]-e[8]*e[7]*e[14]-e[12]*e[6]*e[11]+e[12]*e[7]*e[10],t[8]=e[4]*e[9]*e[15]-e[4]*e[11]*e[13]-e[8]*e[5]*e[15]+e[8]*e[7]*e[13]+e[12]*e[5]*e[11]-e[12]*e[7]*e[9],t[12]=-e[4]*e[9]*e[14]+e[4]*e[10]*e[13]+e[8]*e[5]*e[14]-e[8]*e[6]*e[13]-e[12]*e[5]*e[10]+e[12]*e[6]*e[9],t[1]=-e[1]*e[10]*e[15]+e[1]*e[11]*e[14]+e[9]*e[2]*e[15]-e[9]*e[3]*e[14]-e[13]*e[2]*e[11]+e[13]*e[3]*e[10],t[5]=e[0]*e[10]*e[15]-e[0]*e[11]*e[14]-e[8]*e[2]*e[15]+e[8]*e[3]*e[14]+e[12]*e[2]*e[11]-e[12]*e[3]*e[10],t[9]=-e[0]*e[9]*e[15]+e[0]*e[11]*e[13]+e[8]*e[1]*e[15]-e[8]*e[3]*e[13]-e[12]*e[1]*e[11]+e[12]*e[3]*e[9],t[13]=e[0]*e[9]*e[14]-e[0]*e[10]*e[13]-e[8]*e[1]*e[14]+e[8]*e[2]*e[13]+e[12]*e[1]*e[10]-e[12]*e[2]*e[9],t[2]=e[1]*e[6]*e[15]-e[1]*e[7]*e[14]-e[5]*e[2]*e[15]+e[5]*e[3]*e[14]+e[13]*e[2]*e[7]-e[13]*e[3]*e[6],t[6]=-e[0]*e[6]*e[15]+e[0]*e[7]*e[14]+e[4]*e[2]*e[15]-e[4]*e[3]*e[14]-e[12]*e[2]*e[7]+e[12]*e[3]*e[6],t[10]=e[0]*e[5]*e[15]-e[0]*e[7]*e[13]-e[4]*e[1]*e[15]+e[4]*e[3]*e[13]+e[12]*e[1]*e[7]-e[12]*e[3]*e[5],t[14]=-e[0]*e[5]*e[14]+e[0]*e[6]*e[13]+e[4]*e[1]*e[14]-e[4]*e[2]*e[13]-e[12]*e[1]*e[6]+e[12]*e[2]*e[5],t[3]=-e[1]*e[6]*e[11]+e[1]*e[7]*e[10]+e[5]*e[2]*e[11]-e[5]*e[3]*e[10]-e[9]*e[2]*e[7]+e[9]*e[3]*e[6],t[7]=e[0]*e[6]*e[11]-e[0]*e[7]*e[10]-e[4]*e[2]*e[11]+e[4]*e[3]*e[10]+e[8]*e[2]*e[7]-e[8]*e[3]*e[6],t[11]=-e[0]*e[5]*e[11]+e[0]*e[7]*e[9]+e[4]*e[1]*e[11]-e[4]*e[3]*e[9]-e[8]*e[1]*e[7]+e[8]*e[3]*e[5],t[15]=e[0]*e[5]*e[10]-e[0]*e[6]*e[9]-e[4]*e[1]*e[10]+e[4]*e[2]*e[9]+e[8]*e[1]*e[6]-e[8]*e[2]*e[5];var r=e[0]*t[0]+e[1]*t[4]+e[2]*t[8]+e[3]*t[12];if(0===r)return Xe();r=1/r;for(var i=new Float64Array(16),a=0;a<16;a++)i[a]=t[a]*r;return i}function Ye(e,t){return e&&t&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e}function $e(e,t,r){return t||r?(e[12]+=e[0]*t+e[4]*r,e[13]+=e[1]*t+e[5]*r,e[14]+=e[2]*t+e[6]*r,e[15]+=e[3]*t+e[7]*r,e):e}function Qe(e,t,r){if(!e&&!t)return r;var i=r[3],a=r[7],n=r[11],s=r[15];return r[0]+=i*e,r[1]+=i*t,r[4]+=a*e,r[5]+=a*t,r[8]+=n*e,r[9]+=n*t,r[12]+=s*e,r[13]+=s*t,r}function Ze(e,t){if(!t)return e;var r=Math.sin(t),i=Math.cos(t),a=e[0],n=e[1],s=e[2],o=e[3],c=e[4],l=e[5],u=e[6],h=e[7];return e[0]=a*i+c*r,e[1]=n*i+l*r,e[2]=s*i+u*r,e[3]=o*i+h*r,e[4]=a*-r+c*i,e[5]=n*-r+l*i,e[6]=s*-r+u*i,e[7]=o*-r+h*i,e}function Je(e,t){return 1===t||(e[0]*=t,e[1]*=t,e[2]*=t,e[3]*=t),e}function et(e,t){return 1===t||(e[4]*=t,e[5]*=t,e[6]*=t,e[7]*=t),e}function tt(e,t){if(t&&!qe(t)){var r=e.x,i=e.y,a=t[0],n=t[1],s=t[4],o=t[5];return{x:(1===a?r:r*a)+(s?i*s:0)+t[12],y:(1===n?r:r*n)+(o?i*o:0)+t[13]}}return e}function rt(e,t,r,i,a){var n,s,o,c,l=tt({x:e,y:t},a),u=l.x,h=l.y,d=tt({x:r,y:i},a),f=d.x,m=d.y;if(a&&a.length&&(a[1]||a[2]||a[4]||a[6]||a[7]||a[8])){var p=tt({x:r,y:t},a);n=p.x,s=p.y,o=(p=tt({x:e,y:i},a)).x,c=p.y}else n=f,s=h,o=u,c=m;return{x1:u,y1:h,x2:n,y2:s,x3:f,y3:m,x4:o,y4:c}}function it(e){return e*Math.PI/180}function at(e){return 180*e/Math.PI}function nt(e,t,r,i,a,n,s,o){var c,l;if(void 0===o&&(o=!1),r>=a&&(r=(c=[a,r])[0],a=c[1]),i>=n&&(i=(l=[n,i])[0],n=l[1]),s&&!qe(s)){var u=tt({x:r,y:i},s),h=tt({x:a,y:i},s),d=tt({x:a,y:n},s),f=tt({x:r,y:n},s);return function(e,t,r,i){void 0===i&&(i=!1);for(var a,n=r[0],s=n.x,o=n.y,c=r[0],l=c.x,u=c.y,h=r.length,d=1;d<h;d++){var f=r[d],m=f.x,p=f.y;s=Math.max(s,m),o=Math.max(o,p),l=Math.min(l,m),u=Math.min(u,p)}if(e<l||t<u||e>s||t>o)return!1;if((e<=l||t<=u||e>=s||t>=o)&&!i)return!1;d=0;for(var g=r.length;d<g;d++){var v=r[d],y=v.x,b=v.y,k=r[(d+1)%g],T=k.x,w=k.y,S=je(T-y,w-b,e-y,t-b);if(0!==S){if(S=S>0?1:0,void 0===a)a=S;else if(a^S)return!1}else if(i){if(e===y&&t===b||e===T&&t===w)return!0;var x=e-y,C=T-e,E=t-b,A=w-t;if(0===x||0===C){if(E^A)return!0}else if(0===E||0===A){if(x^C)return!0}else if(x^C&&E^A)return!0}}return!0}(e,t,[{x:u.x,y:u.y},{x:h.x,y:h.y},{x:d.x,y:d.y},{x:f.x,y:f.y}])}return o?e>=r&&t>=i&&e<=a&&t<=n:e>r&&t>i&&e<a&&t<n}function st(e,t,r){var i=(Math.pow(t,2)+Math.pow(r,2)-Math.pow(e,2))/(2*t*r);return Math.acos(i)||0}var ot=4*(Math.sqrt(2)-1)/3;function ct(e,t){return lt(e,it(t))}function lt(e,t){var r=Math.sin(t),i=Math.cos(t);return e[0]=e[5]=i,e[1]=r,e[4]=-r,e}function ut(e,t,r){var i=e.slice(0);return 0===t&&0===r||qe(e)?i:i=$e(i=Qe(t,r,i),-t,-r)}var ht={calRotateZ:ct,calRotateZRadian:lt,calMatrix:function(e,t,r){void 0===t&&(t=0),void 0===r&&(r=0);var i=Xe();i[12]=e.translateX?Rt(e.translateX,t):0,i[13]=e.translateY?Rt(e.translateY,r):0;var a=e.rotateZ?e.rotateZ.v:0,n=e.scaleX?e.scaleX.v:1,s=e.scaleY?e.scaleY.v:1;return qe(i)?ct(i,a):a&&Ze(i,it(a)),1!==n&&(qe(i)?i[0]=n:Je(i,n)),1!==s&&(qe(i)?i[5]=s:et(i,s)),i},calMatrixByOrigin:ut,calTransformByMatrixAndOrigin:function(e,t,r){var i=e.slice(0);return i=Qe(-t,-r,i=$e(i,t,r))}};function dt(e){var t=function(e){if(e<=0)return 0;var t=Math.floor(3*e*Math.sqrt(2*Math.PI)/4+.5);return t<2&&(t=2),t%2==0&&t++,t}(e);return function(e){return 3*Math.floor(.5*e)}(t)}function ft(e,t){void 0===t&&(t=2);var r=Math.pow(10,t);return Math.round(e*r)/r}function mt(e,t,r){void 0===r&&(r=!1);for(var i=[],a=e[0].color,n=0,s=e.length;n<s;n++)i.push(e[n]);(1===i.length&&i.push(A(i[0])),void 0===i[0].offset&&(i[0].offset=0),i.length>1)&&(void 0===i[n=i.length-1].offset&&(i[n].offset=1));var o=i[0].offset;for(n=1,s=i.length;n<s-1;n++){if(void 0!==(b=i[n]).offset)o=b.offset;else{for(var c=n+1,l=i[i.length-1].offset;c<s-1;c++){var u=i[c];if(void 0!==u.offset){l=u.offset;break}}for(var h=(l-o)/(c-n+1),d=n;d<c;d++){i[d].offset=o+h*(d+1-n)}n=c}}i.sort(function(e,t){return e.offset-t.offset});for(n=0,s=i.length;n<s;n++){if((b=i[n]).offset>1){i.splice(n);var f=i[n-1];if(f&&f.offset<1){var m=b.color[0]-f.color[0],p=b.color[1]-f.color[1],g=b.color[2]-f.color[2],v=b.color[3]-f.color[3],y=(1-f.offset)/(b.offset-f.offset);i.push({color:[b.color[0]+m*y,b.color[1]+p*y,b.color[2]+g*y,b.color[3]+v*y],offset:1})}break}}for(n=i.length-1;n>=0;n--){var b;if((b=i[n]).offset<0){i.splice(0,n+1);var k=i[n];if(k&&k.offset>0){m=k.color[0]-b.color[0],p=k.color[1]-b.color[1],g=k.color[2]-b.color[2],v=k.color[3]-b.color[3],y=-b.offset/(k.offset-b.offset);i.unshift({color:[b.color[0]+m*y,b.color[1]+p*y,b.color[2]+g*y,b.color[3]+v*y],offset:0})}break}}if(i.forEach(function(e){e.offset<0?e.offset=0:e.offset>1&&(e.offset=1)}),i.length||i.push({color:a,offset:0},{color:a,offset:1}),r){var T=i[0],w=i[i.length-1];if(T.offset>0||w.offset<1){m=w.color[0]-T.color[0],p=w.color[1]-T.color[1],g=w.color[2]-T.color[2],v=w.color[3]-T.color[3];var S=T.offset+(1-w.offset);if(T.offset>0){y=T.offset/S;i.unshift({color:[T.color[0]+m*y,T.color[1]+p*y,T.color[2]+g*y,T.color[3]+v*y],offset:0})}if(w.offset<1){y=(1-w.offset)/S;i.push({color:[w.color[0]-m*y,w.color[1]-p*y,w.color[2]-g*y,w.color[3]-v*y],offset:1})}}}return i}function pt(e){if(le.gradient.test(e)){var t=le.gradient.exec(e);if(t&&["linear","radial","conic"].indexOf(t[1].toLowerCase())>-1)return!0}return!1}function gt(e){var t=le.gradient.exec(e);if(t){var r={linear:q.LINEAR,radial:q.RADIAL,conic:q.CONIC}[t[1].toLowerCase()],i=void 0;if(r===q.LINEAR)if(n=/([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)/.exec(t[2]))i=[parseFloat(n[1]),parseFloat(n[2]),parseFloat(n[3]),parseFloat(n[4])];else{var a=/([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)/.exec(t[2]);i=a?[it(parseFloat(a[1]))]:[]}else if(r===q.RADIAL){var n;i=(n=/([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)(\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?))?/.exec(t[2]))?[parseFloat(n[1]),parseFloat(n[2]),parseFloat(n[3]),parseFloat(n[4]),parseFloat(n[5])||0]:[.5,.5,1,1]}else r===q.CONIC&&(i=[]);var s=t[2].match(/(([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?[pxremvwhina%]*)?\s*((#[0-9a-f]{3,8})|(rgba?\s*\(.+?\)))\s*([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?[pxremvwhina%]*)?)|(transparent)/gi)||[],o=s.map(function(e,t){var r,i=/(?:#[0-9a-f]{3,8})|(?:rgba?\s*\(.+?\))|(?:transparent)/i.exec(e),a=/[-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?(?:(?:px)|%)?/.exec(e.replace(i[0],""));if(a){var n=se(a[0]);n.u!==W.PERCENT&&(n.v*=100,n.u=W.PERCENT),r=n}else t?t===s.length-1&&(r={v:100,u:W.PERCENT}):r={v:0,u:W.PERCENT};return{color:{v:i?ue(i[0]):[0,0,0,1],u:W.RGBA},offset:r}});o.sort(function(e,t){return e.offset&&t.offset?e.offset.v-t.offset.v:0});for(var c=o.length-2;c>0;c--){if(!o[c].offset){for(var l=o[c+1].offset.v,u=o[0].offset.v,h=c,d=c-1;d>=0;d--){if(0===d){c=d;break}if(o[d].offset){c=d,u=o[d].offset.v;break}}for(var f=(l-u)/(h-c+1),m=c+1;m<=h;m++)o[c].offset={v:u+(m-c)*f,u:W.PERCENT}}}return{t:r,d:i,stops:o}}}function vt(e,t,r,i,a,n){var s,o,c,l,u;if(t.length<=1){var h=function(e,t,r,i,a){var n,s,o,c;if(e%(2*Math.PI)==0)n=o=.5*i,s=0,c=a;else if(e%Math.PI===0)n=o=.5*i,s=a,c=0;else if(e%(.5*Math.PI)==0)n=0,o=i,s=c=.5*a;else if(e%(1.5*Math.PI)==0)n=i,o=0,s=c=.5*a;else{var l=.5*i,u=.5*a,h=Math.min(l,u),d=Math.sin(e%360),f=Math.cos(e%360);n=l-h*d,s=u-h*f,o=l+h*d,c=u+h*f}return{x1:n+=t,y1:s+=r,x2:o+=t,y2:c+=r}}(null!==(s=t[0])&&void 0!==s?s:Math.PI,r,i,a,n);o=h.x1,c=h.y1,l=h.x2,u=h.y2}else o=r+t[0]*a,c=i+t[1]*n,l=r+t[2]*a,u=i+t[3]*n;var d=Math.sqrt(Math.pow(l-o,2)+Math.pow(u-c,2));return{x1:o,y1:c,x2:l,y2:u,total:d,stop:mt(e,0,!1)}}function yt(e,t,r,i,a,n){var s,o=r+t[0]*a,c=i+t[1]*n,l=r+t[2]*a,u=i+t[3]*n,h=t[4],d=Math.sqrt(Math.pow(l-o,2)+Math.pow(u-c,2)),f=mt(e,0,!1);if(h&&1!==h){if(s=Xe(),u!==c)if(l===o)Ze(s,it(u>=c?90:270));else Ze(s,Math.atan((u-c)/(l-o)));et(s,h),s=ut(s,o,c)}return{cx:o,cy:c,tx:l,ty:u,ellipseLength:h,matrix:s,total:d,stop:f}}function bt(e,t,r,i,a,n){var s=Math.floor(r+.5*a),o=Math.floor(i+.5*n),c=Math.floor(r+.5*a)-s,l=Math.floor(i+.5*n)-o,u=0;u=0===c?l>=0?0:Math.PI:Math.atan(l/c);Math.sqrt(Math.pow(c,2)+Math.pow(l,2));return{angle:u,cx:s,cy:o,stop:mt(e,0,!0)}}function kt(e){var t={};if(["left","top","right","bottom","width","height","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"].forEach(function(r){var i=e[r];if(void 0!==i){var a=se(i||0,!0);"width"!==r&&"height"!==r||a.v<0&&(a.v=0),t[r]=a}}),void 0!==e.lineHeight){var r=e.lineHeight;if(C(r)||"normal"===r)t.lineHeight={v:0,u:W.AUTO};else(I=se(r||0,!0)).v<=0&&(I={v:0,u:W.AUTO}),t.lineHeight=I}(e.fontFamily&&(t.fontFamily={v:e.fontFamily.trim().replace(/['"]/g,"").replace(/\s*,\s*/g,","),u:W.STRING}),void 0!==e.fontSize)&&((I=se(e.fontSize||ne.defaultFontSize,!0)).v<=0&&(I.v=ne.defaultFontSize),t.fontSize=I);if(void 0!==e.fontWeight){var i=e.fontWeight;v(i)?/thin/i.test(i)?t.fontWeight={v:100,u:W.NUMBER}:/lighter/i.test(i)?t.fontWeight={v:200,u:W.NUMBER}:/light/i.test(i)?t.fontWeight={v:300,u:W.NUMBER}:/medium/i.test(i)?t.fontWeight={v:500,u:W.NUMBER}:/semiBold/i.test(i)?t.fontWeight={v:600,u:W.NUMBER}:/bold/i.test(i)?t.fontWeight={v:700,u:W.NUMBER}:/extraBold/i.test(i)?t.fontWeight={v:800,u:W.NUMBER}:/black/i.test(i)?t.fontWeight={v:900,u:W.NUMBER}:t.fontWeight={v:400,u:W.NUMBER}:t.fontWeight={v:Math.min(900,Math.max(100,parseInt(i)||400)),u:W.NUMBER}}if(e.fontStyle){var a=e.fontStyle,n=X.NORMAL;a&&/italic/i.test(a)?n=X.ITALIC:a&&/oblique/i.test(a)&&(n=X.OBLIQUE),t.fontStyle={v:n,u:W.NUMBER}}if(void 0!==e.letterSpacing&&(t.letterSpacing=se(e.letterSpacing||0,!0)),void 0!==e.paragraphSpacing&&(t.paragraphSpacing=se(e.paragraphSpacing||0,!0)),e.textAlign){var s=e.textAlign,n=V.LEFT;"center"===s?n=V.CENTER:"right"===s?n=V.RIGHT:"justify"===s&&(n=V.JUSTIFY),t.textAlign={v:n,u:W.NUMBER}}if(e.textVerticalAlign){var o=e.textVerticalAlign;n=H.TOP;"middle"===o?n=H.MIDDLE:"bottom"===o&&(n=H.BOTTOM),t.textVerticalAlign={v:n,u:W.NUMBER}}if(e.textDecoration){var c=e.textDecoration;Array.isArray(c)?t.textDecoration=c.map(function(e){var t=te.NONE;return"underline"===e?t=te.UNDERLINE:"line-through"!==e&&"lineThrough"!==e||(t=te.LINE_THROUGH),{v:t,u:W.NUMBER}}):t.textDecoration=[]}e.textShadow&&(le.shadow.test(e.textShadow)?(n=le.shadow.exec(e.textShadow))&&(t.textShadow={v:{x:parseFloat(n[1]),y:parseFloat(n[2]),blur:parseFloat(n[3]),color:ue(n[4])},u:W.SHADOW}):t.textShadow={u:W.SHADOW});if(e.color&&(t.color={v:ue(e.color),u:W.RGBA}),e.visibility&&(t.visibility={v:/hidden/i.test(e.visibility)?ee.HIDDEN:ee.VISIBLE,u:W.NUMBER}),void 0!==e.opacity&&(t.opacity={v:Math.max(0,Math.min(1,e.opacity)),u:W.NUMBER}),e.backgroundColor&&(t.backgroundColor={v:ue(e.backgroundColor),u:W.RGBA}),e.fill){var l=e.fill;Array.isArray(l)?t.fill=l.map(function(e){if(v(e)&&pt(e)){var t=gt(e);if(t)return{v:t,u:W.GRADIENT}}return{v:ue(e),u:W.RGBA}}):t.fill=[]}if(e.fillEnable){var u=e.fillEnable;Array.isArray(u)?t.fillEnable=u.map(function(e){return{v:e,u:W.BOOLEAN}}):t.fillEnable=t.fill.map(function(){return{v:!0,u:W.BOOLEAN}})}if(e.fillOpacity){var h=e.fillOpacity;Array.isArray(h)?t.fillOpacity=h.map(function(e){return{v:Math.max(0,Math.min(1,e)),u:W.NUMBER}}):t.fillOpacity=t.fill.map(function(){return{v:1,u:W.NUMBER}})}if(e.fillMode){var d=e.fillMode;Array.isArray(d)?t.fillMode=d.map(function(e){return{v:Et(e),u:W.NUMBER}}):t.fillMode=t.fill.map(function(){return{v:j.NORMAL,u:W.NUMBER}})}if(e.fillRule){var f=e.fillRule;t.fillRule={v:"evenodd"===f?K.EVEN_ODD:K.NON_ZERO,u:W.NUMBER}}if(e.stroke){var m=e.stroke;Array.isArray(m)?t.stroke=m.map(function(e){if(v(e))if(pt(e)){if(t=gt(e))return{v:t,u:W.GRADIENT}}else if(le.img.test(e)){var t;if(t=le.img.exec(e)){var r=J.TILE,i=e.replace(t[0],"");i.indexOf("fill")>-1?r=J.FILL:i.indexOf("stretch")>-1?r=J.STRETCH:i.indexOf("fit")>-1&&(r=J.FIT);var a=void 0,n=/([\d.]+)%/.exec(i);return n&&(a={v:parseFloat(n[1]),u:W.PERCENT}),{v:{url:t[2],type:r,scale:a},u:W.PATTERN}}}return{v:ue(e),u:W.RGBA}}):t.stroke=[]}if(e.strokeEnable){var p=e.strokeEnable;Array.isArray(p)?t.strokeEnable=p.map(function(e){return{v:e,u:W.BOOLEAN}}):t.strokeEnable=t.stroke.map(function(){return{v:!0,u:W.BOOLEAN}})}if(e.strokeWidth){var g=e.strokeWidth;Array.isArray(g)?t.strokeWidth=g.map(function(e){return{v:Math.max(0,e),u:W.PX}}):t.strokeWidth=t.stroke.map(function(){return{v:1,u:W.NUMBER}})}if(e.strokePosition){var y=e.strokePosition;Array.isArray(y)?t.strokePosition=y.map(function(e){var t=Z.CENTER;return"inside"===e?t=Z.INSIDE:"outside"===e&&(t=Z.OUTSIDE),{v:t,u:W.NUMBER}}):t.strokePosition=t.stroke.map(function(){return{v:Z.CENTER,u:W.NUMBER}})}if(e.strokeMode){var b=e.strokeMode;Array.isArray(b)?t.strokeMode=b.map(function(e){return{v:Et(e),u:W.NUMBER}}):t.strokeMode=t.stroke.map(function(){return{v:j.NORMAL,u:W.NUMBER}})}if(e.strokeDasharray){var k=e.strokeDasharray;Array.isArray(k)?t.strokeDasharray=k.map(function(e){return{v:Math.max(0,e),u:W.PX}}):t.strokeDasharray=[]}if(e.strokeLinecap){var T=e.strokeLinecap;n=$.BUTT;"round"===T?n=$.ROUND:"square"===T&&(n=$.SQUARE),t.strokeLinecap={v:n,u:W.NUMBER}}if(e.strokeLinejoin){var w=e.strokeLinejoin;n=Q.MITER;"round"===w?n=Q.ROUND:"bevel"===w&&(n=Q.BEVEL),t.strokeLinejoin={v:n,u:W.NUMBER}}if(void 0!==e.strokeMiterlimit&&(t.strokeMiterlimit={v:e.strokeMiterlimit,u:W.NUMBER}),["translateX","translateY","scaleX","scaleY","rotateZ"].forEach(function(r){var i=e[r];if(void 0!==i){var a=se(i);!function(e,t){"scaleX"===e||"scaleY"===e?t.u=W.NUMBER:"translateX"===e||"translateY"===e?t.u===W.NUMBER&&(t.u=W.PX):"rotateZ"===e&&t.u===W.NUMBER&&(t.u=W.DEG)}(r,a),t[r]=a}}),e.transformOrigin){var S=e.transformOrigin,x=void 0;(x=Array.isArray(S)?S:(S||"").toString().match(le.position))&&x.length?1===x.length&&(x[1]=x[0]):x=[50,50];for(var E=[],A=0;A<2;A++){var P=x[A];if(/^[-+]?[\d.]/.test(P)){var I=se(P);E.push(I)}else E.push({v:{top:0,left:0,center:50,right:100,bottom:100}[P],u:W.PERCENT}),C(E[A].v)&&(E[A].v=50)}t.transformOrigin=E}return e.mixBlendMode&&(t.mixBlendMode={v:Et(e.mixBlendMode),u:W.NUMBER}),e.objectFit&&(t.objectFit={v:At(e.objectFit),u:W.NUMBER}),t}function Tt(e){var t=e.fontSize||ne.defaultFontSize,r=e.fontFamily||ne.defaultFontFamily;/[\s.,/\\]/.test(r)&&(r='"'+r.replace(/"/g,'\\"')+'"');var i="";e.fontStyle===X.ITALIC&&(i="italic ");var a="";return 400!==e.fontWeight&&(a=e.fontWeight+" "),i+a+t+"px "+r}function wt(e){for(var t=e.split(/\s*,\s*/),r=0,i=t.length;r<i;r++){var a=t[r].replace(/^['"]/,"").replace(/['"]$/,"");if(Ve.hasRegister(a)||ne.checkSupportFontFamily(a))return a}return ne.defaultFontFamily}function St(e,t){t||(t=wt(e.fontFamily));var r=(Ve.data[t]||Ve.data[ne.defaultFontFamily]||Ve.data.Arial||{}).lhr;return e.fontSize*r}function xt(e,t){var r=e.fontSize,i=wt(e.fontFamily),a=St(e,i),n=(Ve.data[i]||Ve.data[ne.defaultFontFamily]||Ve.data.Arial||{}).blr||1;return.5*((null!=t?t:e.lineHeight)-a)+r*n}function Ct(e,t){var r=e.fontSize,i=wt(e.fontFamily),a=St(e,i),n=(Ve.data[i]||Ve.data[ne.defaultFontFamily]||Ve.data.Arial||{}).car||1;return.5*((null!=t?t:e.lineHeight)-a)+r*n}function Et(e){var t=j.NORMAL;return/multiply/i.test(e)?t=j.MULTIPLY:/screen/i.test(e)?t=j.SCREEN:/overlay/i.test(e)?t=j.OVERLAY:/darken/i.test(e)?t=j.DARKEN:/lighten/i.test(e)?t=j.LIGHTEN:/color[-\s]dodge/i.test(e)||/colorDodge/.test(e)?t=j.COLOR_DODGE:/color[-\s]burn/i.test(e)||/colorBurn/.test(e)?t=j.COLOR_BURN:/hard[\-\s]light/i.test(e)||/hardLight/.test(e)?t=j.HARD_LIGHT:/soft[-\s]light/i.test(e)||/softLight/.test(e)?t=j.SOFT_LIGHT:/difference/i.test(e)?t=j.DIFFERENCE:/exclusion/i.test(e)?t=j.EXCLUSION:/hue/i.test(e)?t=j.HUE:/saturation/i.test(e)?t=j.SATURATION:/color/i.test(e)?t=j.COLOR:/luminosity/i.test(e)&&(t=j.LUMINOSITY),t}function At(e){var t=ie.FILL;return"contain"===e?t=ie.CONTAIN:"cover"===e&&(t=ie.COVER),t}function Pt(e,t,r){if(e===t)return!0;var i=e[r],a=t[r];return"transformOrigin"===r?i[0].v===a[0].v&&i[0].u===a[0].u&&i[1].v===a[1].v&&i[1].u===a[1].u:"color"===r||"backgroundColor"===r?i.v[0]===a.v[0]&&i.v[1]===a.v[1]&&i.v[2]===a.v[2]&&i.v[3]===a.v[3]:i.v===a.v&&i.u===a.u}function It(e,t){t?Array.isArray(t)||(t=[t]):t=Object.keys(e);for(var r={},i=0,a=t.length;i<a;i++){var n=t[i],s=e[n];s&&(r[n]="transformOrigin"===n?[Object.assign({},s[0]),Object.assign({},s[1])]:Object.assign({},s))}return r}function Rt(e,t){return e.u===W.PX?e.v:e.u===W.PERCENT?e.v*t*.01:0}function Ot(e,t){var i={};return oe.forEach(function(e){var r=t[e];void 0!==r&&(i[e]=r)}),r(r({location:e.location,length:e.length},i),kt(e))}function Mt(e){return["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"][e]}function _t(e,t,r,i){return void 0===i&&(i=!1),Array.isArray(e)?he(e):function(e,t,r,i){var a,n,s,o;void 0===t&&(t=100),void 0===r&&(r=100),void 0===i&&(i=!1);var c=e.t,l=e.d,u=e.stops,h=l[0],d=l[1],f=l[2],m=l[3];h*=t,f*=t,d*=r,m*=r;var p=0;1===l.length?p=l[0]:h===f?d<m&&(p=180):p=f>h?m>=d?90+at(Math.atan((m-d)/(f-h))):at(Math.atan((f-h)/(d-m))):m>=d?180+at(Math.atan((h-f)/(m-d))):360-at(Math.atan((h-f)/(d-m)));var g=u.slice(0);if(g.sort(function(e,t){return e.offset-t.offset}),c===q.LINEAR){var v=void 0,y=void 0;p<=90?(v={x:0,y:r},y={x:t,y:0}):p<=180?(v={x:0,y:0},y={x:t,y:r}):p<=270?(v={x:t,y:0},y={x:0,y:r}):(v={x:t,y:r},y={x:0,y:0});var b=A(g).sort(function(e,t){return e.offset-t.offset});if(i){var k=Math.sqrt(Math.pow(m-v.y,2)+Math.pow(f-v.x,2)),T=Math.sqrt(Math.pow(d-v.y,2)+Math.pow(h-v.x,2)),w=Math.sqrt(Math.pow(m-d,2)+Math.pow(f-h,2)),S=st(k,T,w),x=S?T*Math.cos(S):T,C=(S=st(k=Math.sqrt(Math.pow(d-y.y,2)+Math.pow(h-y.x,2)),T=Math.sqrt(Math.pow(m-y.y,2)+Math.pow(f-y.x,2)),w))?T*Math.cos(S):T;if(b[0].offset>0&&b.unshift({color:b[0].color.slice(0),offset:0}),b[b.length-1].offset<1&&b.push({color:b[b.length-1].color.slice(0),offset:1}),x>1e-9)for(var E=x/w,P=function(e,t){var r=b[e];if(r.offset>=E){var i=b[e-1]||{color:r.color,offset:0};if(b.splice(0,e),r.offset>E){var a=w*(r.offset-i.offset),n=(x-i.offset*w)/a,s=i.color.map(function(e,t){return 3===t?e+(r.color[t]-e)*n:e+Math.floor((r.color[t]-e)*n)}),o={color:s,offset:0};b.unshift(o)}return"break"}},I=0,R=b.length;I<R&&"break"!==P(I);I++);else x<-1e-9&&b.forEach(function(e){e.offset=(e.offset*w-x)/(w-x)});if(C>1e-9){E=(w-C)/w;var O=function(e){var t=b[e];if(t.offset<=E){var r=b[e+1]||{color:t.color,offset:1};if(b.splice(e+1),t.offset<E){var i=w*(r.offset-t.offset),a=(C-(1-r.offset)*w)/i,n=r.color.map(function(e,r){return 3===r?e+(t.color[r]-e)*a:e+Math.floor((t.color[r]-e)*a)}),s={color:n,offset:1};b.push(s)}return"break"}};for(I=b.length-1;I>=0&&"break"!==O(I);I--);}else C<-1e-9&&b.forEach(function(e){e.offset=e.offset*(w-x)/(w-x-C)})}var M="linear-gradient(";return M+=i?ft(p)+"deg":l.join(" "),b.forEach(function(e){M+=", ",e.color[3]=ft(e.color[3]),M+=he(e.color)+" "+ft(100*e.offset)+"%"}),M+")"}if(c===q.RADIAL){var _=1;if(i){var D=Math.sqrt(Math.pow(f-h,2)+Math.pow(m-d,2)),B=Math.sqrt(Math.pow(h,2)+Math.pow(d,2)),F=Math.sqrt(Math.pow(h-t,2)+Math.pow(d,2)),N=Math.sqrt(Math.pow(h-t,2)+Math.pow(d-r,2)),L=Math.sqrt(Math.pow(h,2)+Math.pow(d-r,2)),U=Math.max(B,F,N,L);_=U/D}var z="radial-gradient(";return z+=i?"circle at ".concat(100*ft(l[0]),"% ").concat(100*ft(l[1]),"%, "):l.join(" ")+", ",g.forEach(function(e,t){t&&(z+=", ");var r=e.color.map(function(e,t){return 3===t?ft(e):Math.min(255,Math.floor(e*_))});z+=he(r)+" "+ft(100*e.offset)+"%"}),z+")"}if(c===q.CONIC){var W="conic-gradient(";i&&(W+="from 90deg, ");var V=g[0],H=g[g.length-1];if(i&&(V.offset>0||H.offset<1)){var j=null!==(a=V.color[3])&&void 0!==a?a:1,X=null!==(n=H.color[3])&&void 0!==n?n:1,G=[V.color[0]-H.color[0],V.color[1]-H.color[1],V.color[2]-H.color[2],j-X],K=1-H.offset+V.offset;if(V.offset>0){var Y=V.offset/K;g.unshift({color:[Math.min(255,Math.max(0,Math.round(V.color[0]-G[0]*Y))),Math.min(255,Math.max(0,Math.round(V.color[1]-G[1]*Y))),Math.min(255,Math.max(0,Math.round(V.color[2]-G[2]*Y))),Math.min(1,Math.max(0,null!==(s=V.color[3])&&void 0!==s?s:1-G[3]*Y))],offset:0})}H.offset<1&&(Y=(1-H.offset)/K,g.push({color:[Math.min(255,Math.max(0,Math.round(H.color[0]+G[0]*Y))),Math.min(255,Math.max(0,Math.round(H.color[1]+G[1]*Y))),Math.min(255,Math.max(0,Math.round(H.color[2]+G[2]*Y))),Math.min(1,Math.max(0,null!==(o=H.color[3])&&void 0!==o?o:1+G[3]*Y))],offset:1}))}return g.forEach(function(e,t){t&&(W+=", "),e.color[3]=ft(e.color[3]),W+=he(e.color)+" "+ft(100*e.offset)+"%"}),W+")"}return""}(e,t,r,i)}function Dt(e){return["center","inside","outside"][e]||"inside"}var Bt,Ft,Nt,Lt,Ut={normalize:kt,equalStyle:Pt,cloneStyle:It,calSize:Rt,normalizeRich:Ot,getCssMbm:Mt,getCssFillStroke:_t,getCssStrokePosition:Dt};function zt(e){return"pointerEvents"===e||"constrainProportions"===e||"isLocked"===e||"isSelected"===e||"resizesContent"===e||"isRectangle"===e?Bt.NONE:"translateX"===e?Bt.TRANSLATE_X:"translateY"===e?Bt.TRANSLATE_Y:"rotateZ"===e?Bt.ROTATE_Z:"scaleX"===e?Bt.SCALE_X:"scaleY"===e?Bt.SCALE_Y:"transformOrigin"===e||"matrix"===e?Bt.TRANSFORM:"opacity"===e?Bt.OPACITY:"blur"===e||"shadow"===e||"shadowEnable"===e||"hueRotate"===e||"saturate"===e||"brightness"===e||"contrast"===e?Bt.FILTER:"mixBlendMode"===e?Bt.MIX_BLEND_MODE:"maskMode"===e?Bt.MASK:"breakMask"===e?Bt.BREAK_MASK:function(e){return"width"===e||"height"===e||"letterSpacing"===e||"paragraphSpacing"===e||"textAlign"===e||"textVerticalAlign"===e||"fontFamily"===e||"fontSize"===e||"fontWeight"===e||"fontStyle"===e||"lineHeight"===e||"left"===e||"top"===e||"right"===e||"bottom"===e}(e)?Bt.REFLOW:Bt.REPAINT}function Wt(e,t,r){var i=function(e,t,r){var i=Vt(e,e.VERTEX_SHADER,t),a=Vt(e,e.FRAGMENT_SHADER,r);if(!i||!a)return null;var n=e.createProgram();if(!n)return null;n.vertexShader=i,n.fragmentShader=a,e.attachShader(n,i),e.attachShader(n,a),e.linkProgram(n);var s=e.getProgramParameter(n,e.LINK_STATUS);if(!s){var o=e.getProgramInfoLog(n);throw e.deleteProgram(n),e.deleteShader(a),e.deleteShader(i),new Error("Failed to link program: "+o)}return n}(e,t,r);if(!i)throw new Error("Failed to create program");return e.enable(e.BLEND),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA),i}function Vt(e,t,r){var i=e.createShader(t);if(null===i)throw new Error("unable to create shader");if(e.shaderSource(i,r),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){var a=e.getShaderInfoLog(i);throw e.deleteShader(i),new Error("Failed to compile shader: "+a)}return i}function Ht(e,t,r,i,a){var n=e.createTexture();if(jt(e,n,t),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),!r)throw new Error("Missing texImageSource or w/h");return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),n}function jt(e,t,r){e.activeTexture(e["TEXTURE"+r]),e.bindTexture(e.TEXTURE_2D,t)}function Xt(e,t,r,i,a,n,s,o,c,l,u,h){void 0===c&&(c=-1),void 0===l&&(l=-1),void 0===u&&(u=1),void 0===h&&(h=1);var d=a.length;if(d){var f,m,p,g=1===d,v=g?8:12*d,y=g?4:6*d;f=Ft&&Ft.length===v?Ft:Ft=new Float32Array(v),m=Nt&&Nt.length===v?Nt:Nt=new Float32Array(v),p=Lt&&Lt.length===y?Lt:Lt=new Float32Array(y);for(var b=0,k=a.length;b<k;b++){var T=a[b],w=T.opacity,S=T.matrix,x=T.bbox,C=T.coords,E=T.tc;jt(e,T.texture,0);var A=C?Kt(C):Gt(x,t,r,n,s,o,S),P=A.t1,I=A.t2,R=A.t3,O=A.t4,M=12*b;f[M]=P.x,f[M+1]=P.y,f[M+2]=O.x,f[M+3]=O.y,f[M+4]=I.x,f[M+5]=I.y,g?(f[M+6]=R.x,f[M+7]=R.y):(f[M+6]=O.x,f[M+7]=O.y,f[M+8]=I.x,f[M+9]=I.y,f[M+10]=R.x,f[M+11]=R.y),E?(m[M]=E.x1,m[M+1]=E.y1,m[M+2]=E.x1,m[M+3]=E.y3,m[M+4]=E.x3,m[M+5]=E.y1,g?(m[M+6]=E.x3,m[M+7]=E.y3):(m[M+6]=E.x1,m[M+7]=E.y3,m[M+8]=E.x3,m[M+9]=E.y1,m[M+10]=E.x3,m[M+11]=E.y3)):(m[M]=0,m[M+1]=0,m[M+2]=0,m[M+3]=1,m[M+4]=1,m[M+5]=0,g?(m[M+6]=1,m[M+7]=1):(m[M+6]=0,m[M+7]=1,m[M+8]=1,m[M+9]=0,m[M+10]=1,m[M+11]=1)),p[M=6*b]=w,p[M+1]=w,p[M+2]=w,p[M+3]=w,g||(p[M+4]=w,p[M+5]=w)}var _=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,_),e.bufferData(e.ARRAY_BUFFER,f,e.STATIC_DRAW);var D=e.getAttribLocation(i,"a_position");e.vertexAttribPointer(D,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(D);var B=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,B),e.bufferData(e.ARRAY_BUFFER,m,e.STATIC_DRAW);var F=e.getAttribLocation(i,"a_texCoords");e.vertexAttribPointer(F,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(F);var N=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,N),e.bufferData(e.ARRAY_BUFFER,p,e.STATIC_DRAW);var L=e.getAttribLocation(i,"a_opacity");e.vertexAttribPointer(L,1,e.FLOAT,!1,0,0),e.enableVertexAttribArray(L);var U=e.getUniformLocation(i,"u_texture");e.uniform1i(U,0);var z=e.getUniformLocation(i,"x1");e.uniform1f(z,c);var W=e.getUniformLocation(i,"y1");e.uniform1f(W,l);var V=e.getUniformLocation(i,"x2");e.uniform1f(V,u);var H=e.getUniformLocation(i,"y2");e.uniform1f(H,h),e.drawArrays(g?e.TRIANGLE_STRIP:e.TRIANGLES,0,y),e.deleteBuffer(_),e.deleteBuffer(B),e.deleteBuffer(N),e.disableVertexAttribArray(D),e.disableVertexAttribArray(F),e.disableVertexAttribArray(L)}}function qt(e,t,r,i,a){return{x:e=e===r?0:(e-r)/r,y:t=t===i?0:(i-t)/i}}function Gt(e,t,r,i,a,n,s){var o=rt(e[0],e[1],e[2],e[3],s),c=o.x1,l=o.y1,u=o.x2,h=o.y2,d=o.x3,f=o.y3,m=o.x4,p=o.y4;return{t1:qt(c+i,l+a,t,r),t2:qt(u+i,h+a,t,r),t3:qt(d+i,f+a,t,r),t4:qt(m+i,p+a,t,r)}}function Kt(e,t,r){return e}!function(e){e[e.NONE=0]="NONE",e[e.CACHE=1]="CACHE",e[e.TRANSLATE_X=2]="TRANSLATE_X",e[e.TRANSLATE_Y=4]="TRANSLATE_Y",e[e.TRANSLATE=6]="TRANSLATE",e[e.ROTATE_Z=8]="ROTATE_Z",e[e.SCALE_X=16]="SCALE_X",e[e.SCALE_Y=32]="SCALE_Y",e[e.SCALE=48]="SCALE",e[e.TRANSFORM=64]="TRANSFORM",e[e.TRANSFORM_ALL=126]="TRANSFORM_ALL",e[e.OPACITY=128]="OPACITY",e[e.FILTER=256]="FILTER",e[e.MIX_BLEND_MODE=512]="MIX_BLEND_MODE",e[e.MASK=1024]="MASK",e[e.BREAK_MASK=2048]="BREAK_MASK",e[e.TINT=4096]="TINT",e[e.REPAINT=8192]="REPAINT",e[e.REFLOW=16384]="REFLOW",e[e.REFLOW_REPAINT=24576]="REFLOW_REPAINT",e[e.REFLOW_TRANSFORM=16638]="REFLOW_TRANSFORM",e[e.REFLOW_OPACITY=16512]="REFLOW_OPACITY",e[e.REFLOW_FILTER=16640]="REFLOW_FILTER",e[e.ADD_DOM=32768]="ADD_DOM",e[e.REMOVE_DOM=65536]="REMOVE_DOM"}(Bt||(Bt={}));var Yt={},$t=new WeakMap,Qt=new WeakMap,Zt=function(){function e(e,t,r,i){void 0===r&&(r=0),void 0===i&&(i=0),this.available=!1,this.w=e,this.h=t,this.dx=r,this.dy=i,this.list=[];for(var a=F.maxTextureSize,n=0,s=Math.ceil(t/a);n<s;n++)for(var o=0,c=Math.ceil(e/a);o<c;o++){var l=o===c-1?e-o*a:a,u=n===s-1?t-n*a:a;this.list.push({x:o*a-r,y:n*a-i,w:l,h:u,os:ne.getOffscreenCanvas(l,u)})}}return e.prototype.release=function(){return this.url?this.releaseImg(this.url):this.videoFrame?this.releaseVideoFrame(this.videoFrame):this.canvas?this.releaseCanvas(this.canvas):!!this.available&&(this.available=!1,this.list.splice(0).forEach(function(e){return e.os.release()}),!0)},e.prototype.releaseImg=function(e){if(!this.available)return!1;this.available=!1;var t=Yt[e];return t&&(t.count--,t.count||(delete Yt[e],this.list.splice(0).forEach(function(e){return e.os.release()}))),!0},e.prototype.releaseVideoFrame=function(e){if(!this.available)return!1;this.available=!1;var t=Qt.get(e);return t&&(t.count--,t.count||(Qt.delete(e),this.list.splice(0).forEach(function(e){return e.os.release()}))),!0},e.prototype.releaseCanvas=function(e){if(!this.available)return!1;this.available=!1;var t=$t.get(e);return t&&(t.count--,t.count||($t.delete(e),this.list.splice(0).forEach(function(e){return e.os.release()}))),!0},e.prototype.getCount=function(){var e,t;return this.url?null===(e=Yt[this.url])||void 0===e?void 0:e.count:this.videoFrame?null===(t=Qt.get(this.videoFrame))||void 0===t?void 0:t.count:void 0},e.getImgInstance=function(t,r,i,a,n){void 0===a&&(a=0),void 0===n&&(n=0);var s=Yt[i];if(s)return s.count++,s.value;var o=new e(t,r,a,n);return o.url=i,Yt[i]={value:o,count:1},o},e.getVideoFrameInstance=function(t,r,i,a,n){void 0===a&&(a=0),void 0===n&&(n=0);var s=Qt.get(i);if(s)return s.count++,s.value;var o=new e(t,r,a,n);return o.videoFrame=i,Qt.set(i,{value:o,count:1}),o},e.getCanvasInstance=function(t,r,i,a,n){void 0===a&&(a=0),void 0===n&&(n=0);var s=$t.get(i);if(s)return s.count++,s.value;var o=new e(t,r,a,n);return o.canvas=i,$t.set(i,{value:o,count:1}),o},e}(),Jt=new WeakMap,er=new WeakMap,tr=new WeakMap,rr=new WeakMap,ir=function(){function e(e,t,r,i){this.gl=e,this.bbox=t.slice(0);var a=t[2],n=t[3];if(this.list=[],r)if(this.available=!0,r instanceof Zt){this.canvasCache=r;for(var s=r.list,o=r.w,c=r.h,l=s.length,u=(t[2]-t[0])/o,h=(t[3]-t[1])/c,d=0;d<l;d++){var f=s[d],m=Ht(e,0,f.os.canvas);this.list.push({bbox:new Float64Array([f.x*u,f.y*h,Math.min(a,(f.x+f.w)*u),Math.min(n,(f.y+f.h)*h)]),w:f.w,h:f.h,t:m,tc:i})}}else{m=Ht(e,0,r);r instanceof HTMLImageElement?(this.image=r,this.list.push({bbox:new Float64Array(t),w:r.width,h:r.height,t:m,tc:i})):r instanceof VideoFrame?(this.videoFrame=r,this.list.push({bbox:new Float64Array(t),w:r.codedWidth,h:r.codedHeight,t:m,tc:i})):r instanceof HTMLCanvasElement&&(this.canvas=r,this.list.push({bbox:new Float64Array(t),w:r.width,h:r.height,t:m,tc:i}))}else this.available=!1}return e.prototype.release=function(){var e=this;return this.image?this.releaseImg(this.image):this.videoFrame?this.releaseVideoFrame(this.videoFrame):this.canvasCache?this.releaseCanvasCache(this.canvasCache):!!this.available&&(this.available=!1,this.list.splice(0).forEach(function(t){t.t&&e.gl.deleteTexture(t.t)}),!0)},e.prototype.releaseImg=function(e){var t=this;if(!this.available)return!1;this.available=!1;var r=er.get(e);return!!r&&(r.count--,r.count||(er.delete(e),this.list.splice(0).forEach(function(e){e.t&&t.gl.deleteTexture(e.t)})),!0)},e.prototype.releaseVideoFrame=function(e){var t=this;if(!this.available)return!1;this.available=!1;var r=tr.get(e);return!!r&&(r.count--,r.count||(tr.delete(e),this.list.splice(0).forEach(function(e){e.t&&t.gl.deleteTexture(e.t)})),!0)},e.prototype.releaseCanvasCache=function(e){var t=this;if(!this.available)return!1;this.available=!1;var r=Jt.get(e);return!!r&&(r.count--,r.count||(Jt.delete(e),this.list.splice(0).forEach(function(e){e.t&&t.gl.deleteTexture(e.t)})),!0)},e.hasCanvasCacheInstance=function(e){return Jt.has(e)},e.getCanvasCacheInstance=function(t,r,i){var a=Jt.get(r);if(a){a.count++;var n=new e(t,i);n.available=!0,n.canvasCache=r;for(var s=i[2]-i[0],o=i[3]-i[1],c=s/a.w,l=o/a.h,u=i[2],h=i[3],d=a.value,f=d.length,m=0;m<f;m++){var p=d[m];n.list.push({bbox:new Float64Array([p.x*c,p.y*l,Math.min(u,(p.x+p.w)*c),Math.min(h,(p.y+p.h)*l)]),w:p.w,h:p.h,t:p.t})}return n}var g=new e(t,i,r);return Jt.set(r,{value:g.list.map(function(e,t){return{x:r.list[t].x,y:r.list[t].y,w:e.w,h:e.h,t:e.t}}),w:r.w,h:r.h,count:1}),g},e.hasImageCache=function(e){return er.has(e)},e.getImgInstance=function(t,r,i,a){var n=er.get(r);if(n){n.count++;var s=new e(t,i);return s.available=!0,s.image=r,s.list=[{bbox:i.slice(0),w:r.width,h:r.height,t:n.t,tc:a}],s}var o=new e(t,i,r,a);return er.set(r,{t:o.list[0].t,count:1}),o},e.hasVideoFrameInstance=function(e){return tr.has(e)},e.getVideoFrameInstance=function(t,r,i,a){var n=tr.get(r);if(n){n.count++;var s=new e(t,i);return s.available=!0,s.videoFrame=r,s.list=[{bbox:i.slice(0),w:r.codedWidth,h:r.codedHeight,t:n.t,tc:a}],s}var o=new e(t,i,r,a);return tr.set(r,{t:o.list[0].t,count:1}),o},e.getCanvasInstance=function(t,r,i,a){var n=rr.get(r);if(n){n.count++;var s=new e(t,i);return s.available=!0,s.canvas=r,s.list=[{bbox:i.slice(0),w:r.width,h:r.height,t:n.t,tc:a}],s}var o=new e(t,i,r,a);return rr.set(r,{t:o.list[0].t,count:1}),o},e}(),ar=.1,nr="function"==typeof Float32Array;function sr(e,t){return 1-3*t+3*e}function or(e,t){return 3*t-6*e}function cr(e){return 3*e}function lr(e,t,r){return((sr(t,r)*e+or(t,r))*e+cr(t))*e}function ur(e,t,r){return 3*sr(t,r)*e*e+2*or(t,r)*e+cr(t)}function hr(e){return e}function dr(e,t,r,i){if(!(0<=e&&e<=1&&0<=r&&r<=1))throw new Error("bezier x values must be in [0, 1] range");if(e===t&&r===i)return hr;for(var a=nr?new Float32Array(11):new Array(11),n=0;n<11;++n)a[n]=lr(n*ar,e,r);function s(t){for(var i=0,n=1;10!==n&&a[n]<=t;++n)i+=ar;--n;var s=i+(t-a[n])/(a[n+1]-a[n])*ar,o=ur(s,e,r);return o>=.001?function(e,t,r,i){for(var a=0;a<4;++a){var n=ur(t,r,i);if(0===n)return t;t-=(lr(t,r,i)-e)/n}return t}(t,s,e,r):0===o?s:function(e,t,r,i,a){var n,s,o=0;do{(n=lr(s=t+(r-t)/2,i,a)-e)>0?r=s:t=s}while(Math.abs(n)>1e-7&&++o<10);return s}(t,i,i+ar,e,r)}return function(e){return 0===e||1===e?e:lr(s(e),t,i)}}var fr={linear:dr(1,1,0,0),easeIn:dr(.42,0,1,1),easeOut:dr(0,0,.58,1),ease:dr(.25,.1,.25,1),easeInOut:dr(.42,0,.58,1),cubicBezier:dr,getEasing:function(e,t,r,i){if(4===arguments.length)return dr(e,t,r,i);if(Array.isArray(e)&&4===e.length)return dr(e[0],e[1],e[2],e[3]);if(e){var a=e.toString(),n=void 0;if(/^\s*(?:cubic-bezier\s*)?\(\s*[\d.]+\s*,\s*[-\d.]+\s*,\s*[\d.]+\s*,\s*[-\d.]+\s*\)\s*$/i.test(a)){var s=a.match(/[\d.]+/g);n=dr(parseFloat(s[0]),parseFloat(s[1]),parseFloat(s[2]),parseFloat(s[3]))}return n}}},mr=function(e){function r(t,r){var i=e.call(this)||this;return i.node=t,i.duration=r.duration||0,i.direction=r.direction||"forwards",i.fill=r.fill||"none",i.delay=Math.max(0,r.delay||0),i.endDelay=Math.max(0,r.endDelay||0),r.easing&&(y(r.easing)?i.easing=r.easing:Array.isArray(r.easing)?i.easing=fr.getEasing(r.easing):i.easing=fr[r.easing]),i.iterations=r.iterations||1,i.playbackRate=r.playbackRate||1,i._currentTime=0,i.time=0,i._playCount=r.iterationStart||0,i._playState="idle",i.isBegin=0===i._playCount&&!i.delay,i.isEnd=!1,i.isFirstInDelay=!0,i}return t(r,e),r.prototype.play=function(){var e,t=this._playState;"running"!==t&&("finished"!==t&&"idle"!==t||(this._playCount=0,this._currentTime=0,this.time=0,this.isBegin=!this.delay,this.isEnd=!1,this.isFirstInDelay=!0),this._playState="running",null===(e=this.node.root)||void 0===e||e.addAnimation(this))},r.prototype.pause=function(){var e;"paused"!==this._playState&&(this._playState="paused",null===(e=this.node.root)||void 0===e||e.removeAnimation(this))},r.prototype.resume=function(){var e;"paused"===this._playState&&(this._playState="running",null===(e=this.node.root)||void 0===e||e.addAnimation(this))},r.prototype.finish=function(){var e;"finished"!==this._playState&&(this._playCount=this.iterations,this._currentTime=this.delay+this.duration*this._playCount+this.endDelay,this.time=this.duration+this.endDelay,this._playState="finished",null===(e=this.node.root)||void 0===e||e.removeAnimation(this))},r.prototype.cancel=function(){var e;"idle"!==this._playState&&(this._playCount=0,this._currentTime=0,this.time=0,this._playState="idle",null===(e=this.node.root)||void 0===e||e.removeAnimation(this))},r.prototype.remove=function(){var e;this.cancel();var t=this.node.animationList,r=t.indexOf(this);r>-1&&t.splice(r,1),null===(e=this.node.root)||void 0===e||e.aniController.removeAni(this)},r.prototype.gotoAndPlay=function(e){if(this._currentTime!==e||"running"!==this._playState){this.play();var t=this._currentTime;this.currentTime=e,this.onRunning(0,t)}},r.prototype.gotoAndStop=function(e){if(this._currentTime!==e||"paused"!==this._playState){this.pause();var t=this._currentTime;this.currentTime=e,this.onRunning(0,t)}},r.prototype.onRunning=function(e,t){var r=this,i=r.playbackRate,a=r.delay,n=r.endDelay,s=r.duration,o=r.iterations;i>0&&1!==i&&(e*=i),t=null!=t?t:this._currentTime;var c=this._currentTime+=e;if(a&&c<a)this.isFirstInDelay&&this.onFirstInDelay();else{a&&t<a&&c>=a&&(this.isBegin=!0),c-=a;var l=Math.min(o-1,Math.floor(c/s));c-=s*l,this.time=c,this._playCount<l&&(this._playCount=l,this.onChangePlayCount(),this.isBegin=!0),this._playCount>=o-1&&(t-=a,t-=s*l,n&&t<s&&c>=s&&c<s+n&&this.onFirstInEndDelay(),t<s&&c>=s&&(this.isEnd=!0),c>=s+n&&this.finish())}},r.prototype.afterRunning=function(){this.emit("frame"),this.isFirstInDelay&&(this.isFirstInDelay=!1),this.isBegin&&(this.isBegin=!1,this.emit("begin",this._playCount,this.time)),this.isEnd&&(this.isEnd=!1,this.emit("end"))},Object.defineProperty(r.prototype,"currentTime",{get:function(){return this._currentTime},set:function(e){var t=this._currentTime;if(e!==t){var r=this.delay;this._currentTime=e;var i=t-r;this.time=i-this.duration*Math.floor(i/this.duration),e<=r&&(this.isBegin=!0),t>=r&&e<r&&(this.isFirstInDelay=!0)}},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"playCount",{get:function(){return this._playCount},set:function(e){if(e!==this._playCount){var t=this._currentTime,r=this.delay;if(t>=r){var i=(t-r)%this.duration;this.currentTime=i+r+e*this.duration,this.time=i}this._playCount=e}},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"playState",{get:function(){return this._playState},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"pending",{get:function(){return"running"!==this._playState},enumerable:!1,configurable:!0}),r}(R),pr=function(e){function r(t,r,i){var a=e.call(this,t,i)||this;return a._keyFrames=[],a._keyFramesR=[],a.currentKeyFrames=a._keyFrames,a.originStyle={},a.initKeyFrames(r),a.setCurrentFrames(),a}return t(r,e),r.prototype.initKeyFrames=function(e){var t=function(e,t,r,i){for(var a=[],n=0,s=0,o=t.length;s<o;s++){var c=t[s];if(b(c.offset)){var l=c.offset;if(l<0||l>1)continue;if(l<=n&&s)continue;n=l}a.push(Object.assign({},c))}if(1===a.length){a.push(Object.assign({},a[0]));var u=Object.assign({},a[0]);1===a[0].offset?(u.offset=0,a.unshift(u)):(u.offset=1,a.push(u))}var h=a[0];h.offset&&h.offset>0?a.unshift({offset:0}):h.offset=0;var d=a[a.length-1];d.offset&&d.offset<1?a.push({offset:1}):d.offset=1;for(s=1,o=a.length;s<o;s++){c=a[s];if(!b(c.offset)){for(var f=void 0,m=s+1;m<o&&!(f=a[m]).offset;m++);for(var p=m-s+1,g=a[s-1],k=(f.offset-g.offset)/p,T=s;T<m;T++)a[T].offset=g.offset+k*(T+1-s);s=m}}var w=[],S={},x=[];for(s=0,o=a.length;s<o;s++){c=a[s];var C=Ut.normalize(c);Object.keys(C).forEach(function(e){S.hasOwnProperty(e)||(S[e]=!0,x.push(e))});var E={style:C,time:c.offset*r,easing:i,transition:[],fixed:[]};c.easing&&(y(c.easing)?E.easing=c.easing:Array.isArray(c.easing)?E.easing=fr.getEasing(c.easing):v(c.easing)&&(E.easing=fr[c.easing])),w.push(E)}w.forEach(function(t){var r=t.style;x.forEach(function(t){r.hasOwnProperty(t)||Object.assign(r,It(e.style,[t]))})});var A=w.map(function(e){return Object.assign({},e,{transition:[],fixed:[]})}).reverse();A.forEach(function(e){e.time=r-e.time});var P=It(e.style,x);return{keys:x,keyFrames:w,keyFramesR:A,originStyle:P}}(this.node,e,this.duration,this.easing),r=t.keys,i=t.keyFrames,a=t.keyFramesR,n=t.originStyle;this._keyFrames=i,this._keyFramesR=a,gr(this.node,this._keyFrames,r),gr(this.node,this._keyFramesR,r),this.originStyle=n},r.prototype.finish=function(){"finished"!==this._playState&&(e.prototype.finish.call(this),this.onFirstInEndDelay())},r.prototype.cancel=function(){"idle"!==this._playState&&(e.prototype.cancel.call(this),this.node.updateFormatStyle(this.originStyle))},r.prototype.setCurrentFrames=function(){var e=this,t=e.direction,r=e._keyFrames,i=e._keyFramesR,a=e._playCount;this.currentKeyFrames="backwards"===t?i:"alternate"===t?a%2==0?r:i:"alternateReverse"===t&&a%2==0?i:r},r.prototype.onRunning=function(t,r){e.prototype.onRunning.call(this,t,r);var i=this,a=i.duration,n=i.delay,s=i.iterations,o=i.time;if(!(this._currentTime<n)){var c,l=this._playCount>=s-1,u=this.currentKeyFrames,h=u.length;c=2===h?o<a?0:1:function(e,t,r,i){for(;e<t;){if(e===t-1)return i[t].time<=r?t:e;var a=e+(t-e>>1),n=i[a].time;if(n===r)return a;n>r?t=Math.max(a-1,e):e=Math.min(a,t)}return e}(0,h-1,o,u);var d=u[c],f=l&&c===h-1,m=0;if(f);else if(2===h)m=o/a;else{var p=d.time,g=u[c+1].time-p;m=(o-p)/g}if(f);else{d.easing?m=d.easing(m):this.easing&&(m=this.easing(m));var v=d.transition,y=d.fixed,b=d.style,k={};v.forEach(function(e){var t=e.key,r=e.diff;if("opacity"===t||"translateX"===t||"translateY"===t||"scaleX"===t||"scaleY"===t||"rotateZ"===t){var i=Object.assign({},b[t]);i.v+=r*m,k[t]=i}}),y.forEach(function(e){k[e]=Object.assign({},b[e])}),this.node.updateFormatStyle(k)}}},r.prototype.onFirstInDelay=function(){var e=this.fill,t=this.node;"backwards"!==e&&"both"!==e||t.updateFormatStyle(this.currentKeyFrames[0].style)},r.prototype.onFirstInEndDelay=function(){var e=this.fill,t=this.node;if("forwards"===e||"both"===e){var r=this.currentKeyFrames;t.updateFormatStyle(r[r.length-1].style)}else t.updateFormatStyle(this.originStyle)},r.prototype.onChangePlayCount=function(){this.setCurrentFrames()},r}(mr);function gr(e,t,r){for(var i=function(i,a){var n=t[i-1],s=t[i],o=n.style,c=s.style;r.forEach(function(t){var r=o[t],a=c[t];if("opacity"===t||"scaleX"===t||"scaleY"===t||"rotateZ"===t)n.transition.push({key:t,diff:a.v-r.v});else if("translateX"===t||"translateY"===t)if(r.u===a.u)n.transition.push({key:t,diff:a.v-r.v});else{var l=0;"translateX"===t?l=e.computedStyle.width:"translateY"===t&&(l=e.computedStyle.height),n.transition.push({key:t,diff:vr(r,a,l)})}else"visibility"===t&&(s.fixed.push(t),1===i&&n.fixed.push(t))})},a=1,n=t.length;a<n;a++)i(a)}function vr(e,t,r){if(e.u===W.PX){if(t.u===W.PERCENT)return.01*t.v*r-e.v}else if(e.u===W.PERCENT&&t.u===W.PX)return 100*t.v/r-e.v;return 0}function yr(e){return e.map(function(e){if(Array.isArray(e.v))return e.v.slice(0);var t=e.v;return{t:t.t,d:t.d.slice(0),stops:t.stops.map(function(e){var t=.01*e.offset.v;return{color:e.color.v.slice(0),offset:t}})}})}function br(e){return e.map(function(e){if(Array.isArray(e.v))return e.v.slice(0);var t=e.v;return{t:t.t,d:t.d.slice(0),stops:t.stops.map(function(e){var t=e.offset?.01*e.offset.v:void 0;return{color:e.color.v.slice(0),offset:t}})}})}var kr,Tr=0,wr=function(e){function r(t){var r,i=e.call(this)||this;return i.id=Tr++,i.props=t,i.uuid=t.uuid||d(),i.name=t.name,i.style=kt((r=t.style,Object.assign({},O,r))),i.computedStyle={},i.struct={node:i,num:0,total:0,lv:0},i.isMounted=!1,i.isDestroyed=!1,i.refreshLevel=Bt.REFLOW,i._opacity=0,i.hasCacheOp=!1,i.localOpId=0,i.parentOpId=0,i.transform=Xe(),i.matrix=Xe(),i._matrixWorld=Xe(),i.hasCacheMw=!1,i.localMwId=0,i.parentMwId=0,i.hasContent=!1,i.animationList=[],i.contentLoadingNum=0,i}return t(r,e),r.prototype.didMount=function(){var e=this;this.isMounted=!0;var t=this.parent;if(t){this.parentOpId=t.localOpId,this.parentMwId=t.localMwId;var r=this.root=t.root,i=this.uuid;r&&i&&(r.refs[i]=this),this.animationList.forEach(function(t){e.root.aniController.addAni(t)})}},r.prototype.didUnmount=function(){this.clearTexCache(!0),this.isMounted=!1;var e=this.root,t=this.uuid;e&&t&&delete e.refs[t],this.animationList.forEach(function(t){t.cancel(),e.aniController.removeAni(t)}),this.prev=this.next=void 0,this.parent=this.root=void 0},r.prototype.structure=function(e){var t=this.struct;return t.lv=e,[t]},r.prototype.lay=function(e){var t=this.style,r=this.computedStyle,i=t.left,a=t.top,n=t.right,s=t.bottom,o=t.width,c=t.height,l=!1,u=!1,h=!1,d=!1;i.u!==W.AUTO&&(l=!0,r.left=Rt(i,e.w)),n.u!==W.AUTO&&(h=!0,r.right=Rt(n,e.w)),a.u!==W.AUTO&&(u=!0,r.top=Rt(a,e.h)),s.u!==W.AUTO&&(d=!0,r.bottom=Rt(s,e.h)),l&&h?r.width=Math.max(0,e.w-r.left-r.right):l?(o.u!==W.AUTO?r.width=Math.max(0,Rt(o,e.w)):r.width=0,r.right=e.w-r.left-r.width):h?(o.u!==W.AUTO?r.width=Math.max(0,Rt(o,e.w)):r.width=0,r.left=e.w-r.right-r.width):(o.u!==W.AUTO?r.width=Math.max(0,Rt(o,e.w)):r.width=0,r.left=0,r.right=e.w-r.width),u&&d?r.height=Math.max(0,e.h-r.top-r.bottom):u?(c.u!==W.AUTO?r.height=Math.max(0,Rt(c,e.h)):r.height=0,r.bottom=e.w-r.top-r.height):d?(c.u!==W.AUTO?r.height=Math.max(0,Rt(c,e.h)):r.height=0,r.top=e.w-r.bottom-r.height):(c.u!==W.AUTO?r.height=Math.max(0,Rt(c,e.h)):r.height=0,r.top=0,r.bottom=e.w-r.height)},r.prototype.layout=function(e){if(this.isDestroyed)throw new Error("Node is destroyed");this.refreshLevel=Bt.REFLOW,this.calReflowStyle(),this.lay(e),this.calRepaintStyle(Bt.REFLOW),this._rect=void 0},r.prototype.calReflowStyle=function(){var e=this,t=e.style,r=e.computedStyle,i=e.parent;r.fontFamily=t.fontFamily.v,r.fontSize=t.fontSize.v,r.fontWeight=t.fontWeight.v,r.fontStyle=t.fontStyle.v;var a=t.lineHeight;a.u===W.AUTO?r.lineHeight=St(r):r.lineHeight=a.v,r.width=r.height=0;var n=t.width,s=t.height;i?(n.u!==W.AUTO&&(r.width=Math.max(0,Rt(n,i.width))),s.u!==W.AUTO&&(r.height=Math.max(0,Rt(s,i.height)))):(n.u===W.PX&&(r.width=Math.max(0,n.v)),s.u===W.PX&&(r.height=Math.max(0,s.v))),r.letterSpacing=t.letterSpacing.v,r.paragraphSpacing=t.paragraphSpacing.v,r.textAlign=t.textAlign.v,r.textVerticalAlign=t.textVerticalAlign.v},r.prototype.calRepaintStyle=function(e){var t=this.style,r=this.computedStyle;r.visibility=t.visibility.v,r.textDecoration=t.textDecoration.map(function(e){return e.v}),r.textShadow=t.textShadow.v,r.color=t.color.v,r.backgroundColor=t.backgroundColor.v,r.fill=yr(t.fill),r.fillEnable=t.fillEnable.map(function(e){return e.v}),r.fillOpacity=t.fillOpacity.map(function(e){return e.v}),r.fillMode=t.fillMode.map(function(e){return e.v}),r.fillRule=t.fillRule.v,r.stroke=br(t.stroke),r.strokeEnable=t.strokeEnable.map(function(e){return e.v}),r.strokeWidth=t.strokeWidth.map(function(e){return e.v}),r.strokePosition=t.strokePosition.map(function(e){return e.v}),r.strokeMode=t.strokeMode.map(function(e){return e.v}),r.strokeDasharray=t.strokeDasharray.map(function(e){return e.v}),r.strokeLinecap=t.strokeLinecap.v,r.strokeLinejoin=t.strokeLinejoin.v,r.strokeMiterlimit=t.strokeMiterlimit.v,r.mixBlendMode=t.mixBlendMode.v,r.objectFit=t.objectFit.v,r.borderTopLeftRadius=t.borderTopLeftRadius.v,r.borderTopRightRadius=t.borderTopRightRadius.v,r.borderBottomLeftRadius=t.borderBottomLeftRadius.v,r.borderBottomRightRadius=t.borderBottomRightRadius.v,this.clearTexCache(!0),e&Bt.REFLOW_TRANSFORM&&this.calMatrix(e),e&Bt.REFLOW_OPACITY&&this.calOpacity(),this._bbox=void 0,this._bboxInt=void 0,this._filterBbox=void 0,this._filterBboxInt=void 0},r.prototype.calMatrix=function(e){var t=this,r=this,i=r.style,a=r.computedStyle,n=r.matrix,s=r.transform;!this.hasCacheMw&&this.localMwId||(this.hasCacheMw=!1,this.localMwId++);var o,c=!0;if((e>=Bt.REFLOW||e&Bt.TRANSFORM||e&Bt.SCALE_X&&!a.scaleX||e&Bt.SCALE_Y&&!a.scaleY)&&(c=!1),c){if(e&Bt.TRANSLATE_X){var l=(u=Rt(i.translateX,this.computedStyle.width))-a.translateX;a.translateX=u,s[12]+=l,n[12]+=l}if(e&Bt.TRANSLATE_Y){l=(u=Rt(i.translateY,this.computedStyle.height))-a.translateY;a.translateY=u,s[13]+=l,n[13]+=l}if(e&Bt.ROTATE_Z){var u=i.rotateZ.v;a.rotateZ=u;var h=it(u),d=Math.sin(h),f=Math.cos(h),m=a.scaleX,p=a.scaleY;n[0]=s[0]=f*m,n[1]=s[1]=d*p,n[4]=s[4]=-d*m,n[5]=s[5]=f*p;var g=(b=a.transformOrigin)[0],v=b[1];n[12]=s[12]+g-s[0]*g-v*s[4],n[13]=s[13]+v-s[1]*g-v*s[5]}if(e&Bt.SCALE){if(e&Bt.SCALE_X){m=(u=i.scaleX.v)/a.scaleX;a.scaleX=u,s[0]*=m,s[4]*=m,n[0]*=m,n[4]*=m}if(e&Bt.SCALE_Y){p=(u=i.scaleY.v)/a.scaleY;a.scaleY=u,s[1]*=p,s[5]*=p,n[1]*=p,n[5]*=p}g=(b=a.transformOrigin)[0],v=b[1];n[12]=s[12]+g-s[0]*g-s[4]*v,n[13]=s[13]+v-s[1]*g-s[5]*v,n[14]=s[14]-s[2]*g-s[6]*v}}else{(o=s)[0]=1,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=1,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=1,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1;var y=i.transformOrigin.map(function(e,r){return Rt(e,r?t.computedStyle.height:t.computedStyle.width)});a.transformOrigin=y,a.translateX=Rt(i.translateX,this.computedStyle.width),s[12]=a.left+a.translateX,a.translateY=Rt(i.translateY,this.computedStyle.height),s[13]=a.top+a.translateY;var b,k=i.rotateZ?i.rotateZ.v:0,T=i.scaleX?i.scaleX.v:1,w=i.scaleY?i.scaleY.v:1;a.rotateZ=k,a.scaleX=T,a.scaleY=w,qe(s)&&k?ct(s,k):k&&Ze(s,it(k)),1!==T&&(qe(s)?s[0]=T:Je(s,T)),1!==w&&(qe(s)?s[5]=w:et(s,w)),Ye(n,b=ut(s,y[0],y[1]))}},r.prototype.calOpacity=function(){var e=this.style,t=this.computedStyle;!this.hasCacheOp&&this.localOpId||(this.hasCacheOp=!1,this.localOpId++),t.opacity=e.opacity.v},r.prototype.calContent=function(){return this.hasContent=!1},r.prototype.calContentLoading=function(){var e=this.computedStyle;return e.opacity<=0||e.visibility===ee.HIDDEN||!e.width||!e.height?0:this.contentLoadingNum},r.prototype.renderCanvas=function(){var e=this.canvasCache;e&&e.available&&e.release()},r.prototype.genTexture=function(e){var t;this.renderCanvas(),null===(t=this.textureCache)||void 0===t||t.release();var r=this.canvasCache;(null==r?void 0:r.available)?(this.textureTarget=this.textureCache=new ir(e,this._bboxInt||this.bboxInt,r),r.release()):this.textureTarget=this.textureCache=void 0},r.prototype.resetTextureTarget=function(){var e=this,t=e.textureCache,r=e.textureTotal,i=e.textureFilter;(null==i?void 0:i.available)&&(this.textureTarget=i),(null==r?void 0:r.available)&&(this.textureTarget=r),(null==t?void 0:t.available)&&(this.textureTarget=t)},r.prototype.updateStyle=function(e,t){var r=kt(e);return this.updateFormatStyle(r,t)},r.prototype.updateFormatStyle=function(e,t){var r,i=this.updateFormatStyleData(e);return i.length||t&&t(!0),null===(r=this.root)||void 0===r?void 0:r.addUpdate(this,i,void 0,t)},r.prototype.updateFormatStyleData=function(e){var t=[];for(var r in e)if(e.hasOwnProperty(r)){var i=e[r];Pt(e,this.style,r)||(this.style[r]=i,t.push(r))}return t},r.prototype.clearTexCache=function(e){var t,r,i;void 0===e&&(e=!1),e&&(null===(t=this.textureCache)||void 0===t||t.release()),null===(r=this.textureTotal)||void 0===r||r.release(),null===(i=this.textureFilter)||void 0===i||i.release()},r.prototype.clearTexCacheUpward=function(e){void 0===e&&(e=!1);for(var t=this.parent;t;)t.clearTexCache(e),t=t.parent},r.prototype.refresh=function(e,t){var r;void 0===e&&(e=Bt.REPAINT),null===(r=this.root)||void 0===r||r.addUpdate(this,[],e,t)},r.prototype.getBackgroundCoords=function(e,t){void 0===e&&(e=0),void 0===t&&(t=0);var r=this.computedStyle,i=r.borderTopLeftRadius,a=r.borderTopRightRadius,n=r.borderBottomLeftRadius,s=r.borderBottomRightRadius,o=Math.min(.5*r.width,.5*r.height),c=Math.min(o,i),l=Math.min(o,a),u=Math.min(o,n),h=Math.min(o,s);return 0===c&&0===l&&0===u&&0===h?[[e,t],[r.width,t],[r.width,r.height],[e,r.height],[e,t]]:[[c,t],[r.width-l,t],[r.width-l+l*ot,t,r.width,l*ot,r.width,l],[r.width,r.height-h],[r.width,r.height-h+h*ot,r.width-h+h*ot,r.height,r.width-h,r.height],[u,r.height],[u*ot,r.height,e,r.height-u+u*ot,e,r.height-u],[e,c],[e,c-c*ot,c-c*ot,t,c,t]]},r.prototype.getStyle=function(){return A(this.style)},r.prototype.getComputedStyle=function(){var e=Object.assign({},this.computedStyle);return this.isMounted&&(e.color=e.color.slice(0),e.backgroundColor=e.backgroundColor.slice(0),e.fill=A(e.fill),e.stroke=A(e.stroke),e.fillOpacity=e.fillOpacity.slice(0),e.fillEnable=e.fillEnable.slice(0),e.fillMode=e.fillMode.slice(0),e.strokeEnable=e.strokeEnable.slice(0),e.strokeWidth=e.strokeWidth.slice(0),e.transformOrigin=e.transformOrigin.slice(0),e.strokeDasharray=e.strokeDasharray.slice(0)),e},r.prototype.getCssStyle=function(e){var t=this;void 0===e&&(e=!1);var r=this.style,i=this.computedStyle,a={};return["top","right","bottom","left","width","height","translateX","translateY","scaleX","scaleY","rotateZ","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"].forEach(function(e){var t=r[e];t.u===W.AUTO?a[e]="auto":t.u===W.PERCENT?a[e]=t.v+"%":t.u!==W.PX&&t.u!==W.NUMBER&&t.u!==W.DEG||(a[e]=t.v)}),a.opacity=r.opacity.v,a.visibility=r.visibility.v===ee.VISIBLE?"visible":"hidden",a.color=he(r.color.v),a.backgroundColor=he(r.backgroundColor.v),a.fontStyle=["normal","italic","oblique"][r.fontStyle.v],a.textAlign=["left","right","center","justify"][r.textAlign.v],a.textVerticalAlign=["top","middle","bottom"][r.textVerticalAlign.v],a.mixBlendMode=Mt(r.mixBlendMode.v),a.objectFit=["fill","contain","cover"][r.objectFit.v],["strokeEnable","fillEnable","fillOpacity","strokeWidth"].forEach(function(e){a[e]=r[e].map(function(e){return e.v})}),e?this.isMounted?a.fill=i.fill.map(function(e){return _t(e,t.width,t.height,!0)}):ne.error("Can not get CSS standard fill unmounted"):a.fill=yr(r.fill).map(function(e){return _t(e)}),a.fillRule=["nonzero","evenodd"][r.fillRule.v],a.fillMode=r.fillMode.map(function(e){return Mt(e.v)}),e?this.isMounted?a.stroke=i.stroke.map(function(e){return _t(e,t.width,t.height,!0)}):ne.error("Can not get CSS standard stroke unmounted"):a.stroke=br(r.stroke).map(function(e){return _t(e,t.width,t.height)}),a.strokeLinecap=["butt","round","square"][r.strokeLinecap.v],a.strokeLinejoin=["miter","round","bevel"][r.strokeLinejoin.v],a.strokePosition=r.strokePosition.map(function(e){return Dt(e.v)}),a.strokeMiterlimit=r.strokeMiterlimit.v,a.strokeDasharray=r.strokeDasharray.map(function(e){return e.v}),a.strokeMode=r.strokeMode.map(function(e){return Mt(e.v)}),a.transformOrigin=r.transformOrigin.map(function(e){return e.u===W.PERCENT?e.v+"%":e}),a},r.prototype.isParent=function(e){for(var t=this.parent;t;){if(t===e)return!0;t=t.parent}return!1},r.prototype.isChild=function(e){return e.isParent(this)},r.prototype.insertAfter=function(e,t){e.remove();var r=this.root,i=this.parent;if(!i)throw new Error("Can not appendSelf without parent");e.parent=i,e.prev=this,this.next&&(this.next.prev=e),e.next=this.next,this.next=e,e.root=r;var a=i.children,n=a.indexOf(this);a.splice(n+1,0,e),i.isDestroyed?t&&t(!0):(i.insertStruct(e,n+1),r.addUpdate(e,[],Bt.ADD_DOM,t))},r.prototype.insertBefore=function(e,t){e.remove();var r=this.root,i=this.parent;if(!i)throw new Error("Can not prependBefore without parent");e.parent=i,e.prev=this.prev,this.prev&&(this.prev.next=e),e.next=this,this.prev=e,e.root=r;var a=i.children,n=a.indexOf(this);a.splice(n,0,e),i.isDestroyed?t&&t(!0):(i.insertStruct(e,n),r.addUpdate(e,[],Bt.ADD_DOM,t))},r.prototype.remove=function(e){var t=this.root,r=this.parent;if(r){var i=r.children.indexOf(this);if(-1===i)throw new Error("Invalid index of remove()");r.children.splice(i,1);var a=this.prev,n=this.next;a&&(a.next=n),n&&(n.prev=a),r.deleteStruct(this)}t&&this.isMounted?t.addUpdate(this,[],Bt.REMOVE_DOM,e):e&&e(!0)},r.prototype.getBoundingClientRect=function(e){var t=(null==e?void 0:e.includeBbox)?this._bbox||this.bbox:this._rect||this.rect,r=rt(t[0],t[1],t[2],t[3],this.matrixWorld),i=r.x1,a=r.y1,n=r.x2,s=r.y2,o=r.x3,c=r.y3,l=r.x4,u=r.y4,h=Math.min(i,n,o,l),d=Math.min(a,s,c,u),f=Math.max(i,n,o,l),m=Math.max(a,s,c,u);return{left:h,top:d,right:f,bottom:m,width:f-h,height:m-d,points:[{x:i,y:a},{x:n,y:s},{x:o,y:c},{x:l,y:u}]}},r.prototype.getOffsetRect=function(){var e=this.computedStyle,t=e.left+e.translateX,r=e.top+e.translateY;return{left:t,top:r,right:t+this.width,bottom:r+this.height}},r.prototype.startSizeChange=function(){var e=this,t=e.width,r=e.height,i=e.style,a=e.computedStyle,n=e.parent;if(e.isDestroyed||!n)throw new Error("Can not resize a destroyed Node or Root");var s=i.left,o=i.right,c=i.top,l=i.bottom,u=i.translateX,h=i.translateY,d=n.width,f=n.height;if(u.v&&u.u===W.PERCENT){var m=u.v*t*.01;s.u===W.PERCENT?s.v+=100*m/d:s.u===W.PX&&(s.v+=m),a.left+=m,o.u===W.PERCENT?o.v-=100*m/d:o.u===W.PX&&(o.v-=m),a.right-=m,u.v=0}if(h.v&&h.u===W.PERCENT){m=h.v*r*.01;c.u===W.PERCENT?c.v+=100*m/f:c.u===W.PX&&(c.v+=m),a.top+=m,l.u===W.PERCENT?l.v-=100*m/f:l.u===W.PX&&(l.v-=m),a.bottom-=m,h.v=0}},r.prototype.endSizeChange=function(e){var t=e.translateX,r=e.translateY,i=this,a=i.style,n=i.computedStyle,s=i.parent,o=i.width,c=i.height,l=a.left,u=a.right,h=a.top,d=a.bottom,f=s,m=f.width,p=f.height;if(t.v&&t.u===W.PERCENT){var g=t.v*o*.01;l.u===W.PX?l.v-=g:l.u===W.PERCENT&&(l.v-=100*g/m),n.left-=g,u.u===W.PX?u.v+=g:u.u===W.PERCENT&&(u.v+=100*g/m),n.right+=g,n.translateX+=g}if(r.v&&r.u===W.PERCENT){g=r.v*c*.01;h.u===W.PX?h.v-=g:a.top.u===W.PERCENT&&(h.v-=100*g/p),n.top-=g,d.u===W.PX?d.v+=g:d.u===W.PERCENT&&(d.v+=100*g/p),n.bottom+=g,n.translateY+=g}a.translateX.v=t.v,a.translateX.u=t.u,a.translateY.v=r.v,a.translateY.u=r.u},r.prototype.endPosChange=function(e,t,r){var i=this,a=i.style,n=i.computedStyle,s=i.parent;if(s){var o=e.translateX,c=e.translateY,l=a.top,u=a.right,h=a.bottom,d=a.left,f=s.width,m=s.height;t&&(d.u===W.PX?d.v+=t:d.u===W.PERCENT&&(d.v+=100*t/f),n.left+=t,u.u===W.PX?u.v-=t:u.u===W.PERCENT&&(u.v-=100*t/f),n.right-=t,n.translateX-=t),r&&(l.u===W.PX?l.v+=r:l.u===W.PERCENT&&(l.v+=100*r/m),n.top+=r,h.u===W.PX?h.v-=r:h.u===W.PERCENT&&(h.v-=100*r/m),n.bottom-=r,n.translateY-=r),a.translateX.v=o.v,a.translateX.u=o.u,a.translateY.v=c.v,a.translateY.u=c.u}},r.prototype.adjustPosAndSizeSelf=function(e,t,r,i){var a=this,n=a.style,s=a.computedStyle,o=a.parent,c=a.root;if(o&&c&&(e||t||r||i)){var l=o.width,u=o.height,h=n.top,d=n.right,f=n.bottom,m=n.left,p=n.width,g=n.height,v=n.translateX,y=n.translateY,b=(e||r)&&v.u===W.PERCENT&&v.v;if(b){var k=.01*b*this.width;m.u===W.PX?m.v+=k:m.u===W.PERCENT&&(m.v+=100*k/l),s.left+=k,d.u===W.PX?d.v-=k:d.u===W.PERCENT&&(d.v-=100*k/l),s.right-=k}if(e&&(m.u===W.PX?m.v+=e:m.u===W.PERCENT&&(m.v+=100*e/l),s.left+=e),r&&(d.u===W.PX?d.v-=r:d.u===W.PERCENT&&(d.v-=100*r/l),s.right-=r),r-e&&(p.u===W.PX?p.v=r+this.width-e:p.u===W.PERCENT&&(p.v=100*(r+this.width-e)/o.width),s.width=o.width-s.left-s.right),this.width<0){s.width=-this.width;var T=s.left,w=s.right;s.left=l-w,m.u===W.PX?m.v=s.left:m.u===W.PERCENT&&(m.v=100*s.left/l),s.right=l-T,d.u===W.PX?d.v=s.right:d.u===W.PERCENT&&(d.v=100*s.right/l)}if(b){k=.01*b*this.width;m.u===W.PX?m.v-=k:m.u===W.PERCENT&&(m.v-=100*k/l),s.left-=k,d.u===W.PX?d.v+=k:d.u===W.PERCENT&&(d.v+=100*k/l),s.right+=k}var S=(t||i)&&y.u===W.PERCENT&&y.v;if(S){k=.01*S*this.height;h.u===W.PX?h.v+=k:h.u===W.PERCENT&&(h.v+=100*k/u),s.top+=k,f.u===W.PX?f.v-=k:f.u===W.PERCENT&&(f.v-=100*k/u),s.bottom-=k}if(t&&(h.u===W.PX?h.v+=t:h.u===W.PERCENT&&(h.v+=100*t/u),s.top+=t),i&&(f.u===W.PX?f.v-=i:f.u===W.PERCENT&&(f.v-=100*i/u),s.bottom-=i),i-t&&(g.u===W.PX?g.v=i+this.height-t:g.u===W.PERCENT&&(g.v=100*(i+this.height-t)/o.height),s.height=o.height-s.top-s.bottom),this.height<0){s.height=-this.height;var x=s.top,C=s.bottom;s.top=u-x,h.u===W.PX?h.v=s.top:h.u===W.PERCENT&&(h.v=100*s.top/u),s.bottom=u-C,f.u===W.PX?f.v=s.bottom:f.u===W.PERCENT&&(f.v=100*s.bottom/u)}if(S){k=.01*S*this.height;h.u===W.PX?h.v-=k:h.u===W.PERCENT&&(h.v-=100*k/u),s.top-=k,f.u===W.PX?f.v+=k:f.u===W.PERCENT&&(f.v+=100*k/u),s.bottom+=k}this.refreshLevel|=Bt.TRANSFORM,c.rl|=Bt.TRANSFORM,this.calMatrix(Bt.TRANSFORM),this._rect=void 0,this._bbox=void 0,this._bboxInt=void 0,this._filterBbox=void 0,this._filterBboxInt=void 0}},r.prototype.checkPosSizeUpward=function(){for(var e=this.root,t=this.parent;t&&t!==e&&t.adjustPosAndSize();)t=t.parent},r.prototype.adjustPosAndSize=function(){return!1},r.prototype.initAnimate=function(e,t){this.animationList.push(e);var r=this.root;return this.isDestroyed||!r?(e.cancel(),e):(r.aniController.addAni(e),t.autoPlay&&e.play(),e)},r.prototype.animate=function(e,t){var r=new pr(this,e,t);return this.initAnimate(r,t)},r.prototype.release=function(){this.remove(),this.animationList.splice(0).forEach(function(e){return e.remove()}),this.clearTexCache()},Object.defineProperty(r.prototype,"width",{get:function(){return this.computedStyle.width||0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"height",{get:function(){return this.computedStyle.height||0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"matrixWorld",{get:function(){var e,t=this.root,r=this._matrixWorld;if(!t)return r;for(var i=this,a=this.hasCacheMw,n=i.parent,s=-1,o=[];n;)o.push(n),n.hasCacheMw&&n.localMwId===i.parentMwId||(a=!1,s=o.length),i=n,n=n.parent;if(!a){if(s>-1){o.splice(s),o.reverse();for(var c=0,l=o.length;c<l;c++){var u=o[c];if(u.hasCacheMw&&u.parentMwId!==(null===(e=u.parent)||void 0===e?void 0:e.localMwId)&&u.localMwId++,u.hasCacheMw=!0,u===t)Ye(u._matrixWorld,u.matrix);else{var h=Ge(u.parent._matrixWorld,u.matrix);Ye(u._matrixWorld,h),u.parentMwId=u.parent.localMwId}}}if(this.hasCacheMw&&this.localMwId++,this.hasCacheMw=!0,n=this.parent)Ye(r,h=Ge(n._matrixWorld,this.matrix)),this.parentMwId=n.localMwId;else Ye(r,this.matrix)}return r},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"rect",{get:function(){var e=this._rect;return e||((e=this._rect=new Float64Array(4))[0]=0,e[1]=0,e[2]=this.computedStyle.width,e[3]=this.computedStyle.height),e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"bbox",{get:function(){var e=this._bbox;if(!e){var t=this._rect||this.rect;e=this._bbox=t.slice(0)}return e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"filterBbox",{get:function(){var e=this._filterBbox;if(!e){var t=this._bbox||this.bbox;e=this._filterBbox=t.slice(0)}return e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"bboxInt",{get:function(){var e=this._bboxInt;return e||((e=this._bboxInt=(this._bbox||this.bbox).slice(0))[0]=Math.floor(e[0]),e[1]=Math.floor(e[1]),e[2]=Math.ceil(e[2]),e[3]=Math.ceil(e[3])),e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"filterBboxInt",{get:function(){var e=this._filterBboxInt;return e||((e=this._filterBboxInt=(this._filterBbox||this.filterBbox).slice(0))[0]=Math.floor(e[0]),e[1]=Math.floor(e[1]),e[2]=Math.ceil(e[2]),e[3]=Math.ceil(e[3])),e},enumerable:!1,configurable:!0}),r}(R);!function(e){e[e.NONE=0]="NONE",e[e.LOADING=1]="LOADING",e[e.LOADED=2]="LOADED"}(kr||(kr={}));var Sr={};function xr(e,t){return i(this,void 0,void 0,function(){var r,i,n,s,o,c,l,u,h;return a(this,function(a){switch(a.label){case 0:if(r=Sr[e]){if(r.count++,r.state===kr.LOADED)return[2,r.res];if(r.state===kr.LOADING)return[2,new Promise(function(e){r.list.push(e)})]}return r=Sr[e]={state:kr.LOADING,list:[],count:0,res:{success:!1,frames:[],width:0,height:0,release:function(){r.count--,r.count<=0&&(r.res.source&&URL.revokeObjectURL(r.res.source.src),r.res.frames.forEach(function(e){return e.close()}),delete Sr[e])}}},[4,fetch(e,Object.assign({mode:"cors"},t))];case 1:return 200!==(i=a.sent()).status&&304!==i.status?(r.state=kr.LOADED,[2,r.res]):[4,i.arrayBuffer()];case 2:return n=a.sent(),"undefined"==typeof ImageDecoder?[3,9]:function(e){var t=[71,73,70,56,55,97];return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&(e[4]===t[4]||57===e[4])&&e[5]===t[5]}(new Uint8Array(n))?[4,(s=new ImageDecoder({data:n,type:"image/gif"})).tracks.ready]:[3,9];case 3:if(a.sent(),!(o=s.tracks.selectedTrack))return[3,8];c=0,a.label=4;case 4:return c<o.frameCount?[4,s.decode({frameIndex:c})]:[3,7];case 5:l=a.sent(),r.res.frames.push(l.image),a.label=6;case 6:return c++,[3,4];case 7:return r.state=kr.LOADED,r.res.success=!0,r.res.width=r.res.frames[0].codedWidth,r.res.height=r.res.frames[0].codedHeight,r.count++,r.list.splice(0).forEach(function(e){r.count++,e(r.res)}),s.close(),[2,r.res];case 8:s.close(),a.label=9;case 9:return u=new Blob([n]),(h=new Image).src=URL.createObjectURL(u),r.count++,[2,new Promise(function(e){h.onload=function(){r.state=kr.LOADED,r.res.success=!0,r.res.source=h,r.res.width=h.width,r.res.height=h.height,e(r.res),r.list.splice(0).forEach(function(e){r.count++,e(r.res)})},h.onerror=function(){r.state=kr.LOADED,e(r.res),r.list.splice(0).forEach(function(e){r.count++,e(r.res)})}})]}})})}var Cr=function(e){function r(t,r,i){var a=e.call(this,t,i)||this;return a.node=t,a._frameArea=r,a._frameAreaR=r.slice(0).reverse(),a.currentFrameArea=a._frameArea,a.originFrameIndex=t.frameIndex,a.setCurrentFrameArea(),a}return t(r,e),r.prototype.setCurrentFrameArea=function(){var e=this.direction,t=this._playCount;this.currentFrameArea="backwards"===e?this._frameAreaR:"alternate"===e?t%2==0?this._frameArea:this._frameAreaR:"alternateReverse"===e&&t%2==0?this._frameAreaR:this._frameArea},r.prototype.finish=function(){"finished"!==this._playState&&(e.prototype.finish.call(this),this.onFirstInEndDelay())},r.prototype.cancel=function(){"idle"!==this._playState&&(e.prototype.cancel.call(this),this.node.frameIndex=this.originFrameIndex)},r.prototype.onRunning=function(t){e.prototype.onRunning.call(this,t);var r=this,i=r.node,a=r.duration,n=r.delay,s=r.iterations,o=r.currentFrameArea,c=r.time;if(!(this._currentTime<n)){var l=this._playCount>=s-1,u=c/a;this.easing&&(u=this.easing(u)),l&&u>=1||(i.frameIndex=Math.floor(o[0]+(o[1]-o[0])*u))}},r.prototype.onFirstInDelay=function(){var e=this,t=e.fill,r=e.currentFrameArea,i=e.node;"backwards"!==t&&"both"!==t||(i.frameIndex=r[0])},r.prototype.onFirstInEndDelay=function(){var e=this.fill,t=this.node;if("forwards"===e||"both"===e){var r=this.currentFrameArea;t.frameIndex=r[r.length-1]}else t.frameIndex=this.originFrameIndex},r.prototype.onChangePlayCount=function(){this.setCurrentFrameArea()},r}(mr);function Er(e,t,r,i,a){if(void 0===i&&(i=0),void 0===a&&(a=0),t&&t.length){for(var n=-1,s=0,o=t.length;s<o;s++){var c=t[s];if(Array.isArray(c)&&c.length){n=s;break}}if(-1!==n){var l=t[n];4===l.length?e.moveTo(l[2]*r+i,l[3]*r+a):6===l.length?e.moveTo(l[4]*r+i,l[5]*r+a):e.moveTo(l[0]*r+i,l[1]*r+a);for(s=n+1,o=t.length;s<o;s++){c=t[s];Array.isArray(c)&&(2===c.length?e.lineTo(c[0]*r+i,c[1]*r+a):4===c.length?e.quadraticCurveTo(c[0]*r+i,c[1]*r+a,c[2]*r+i,c[3]*r+a):6===c.length&&e.bezierCurveTo(c[0]*r+i,c[1]*r+a,c[2]*r+i,c[3]*r+a,c[4]*r+i,c[5]*r+a))}}}}var Ar="refresh_complete",Pr="waiting",Ir="can_play",Rr="meta",Or="error",Mr="load",_r=function(e){function r(t){var r=e.call(this,t)||this;t.onLoad&&(r.onLoad=t.onLoad),r._frameIndex=t.frameIndex||0,r.isPure=!0;var i=r._src=t.src||"";return i&&(r.contentLoadingNum=1,xr(i).then(function(e){if(r.loader=e,r.contentLoadingNum=0,e.success){if(r.isMounted){var t=r.style,i=t.left,a=t.top,n=t.right,s=t.bottom,o=t.width,c=t.height;(i.u===W.AUTO||n.u===W.AUTO)&&o.u===W.AUTO||(a.u===W.AUTO||s.u===W.AUTO)&&c.u===W.AUTO?r.refresh(Bt.REFLOW):r.refresh()}r.onLoad&&r.onLoad(),r.emit(Mr)}})),r}return t(r,e),r.prototype.lay=function(t){e.prototype.lay.call(this,t);var r=this,i=r.style,a=r.computedStyle,n=r.loader,s=i.left,o=i.top,c=i.right,l=i.bottom,u=i.width,h=i.height;if(n){var d=(s.u===W.AUTO||c.u===W.AUTO)&&u.u===W.AUTO,f=(o.u===W.AUTO||l.u===W.AUTO)&&h.u===W.AUTO;d&&(a.width=f?n.width:n.width*a.height/n.height,s.u===W.AUTO&&c.u===W.AUTO?(a.left=0,a.right=t.w-a.width):s.u===W.AUTO?a.left=t.w-a.right-a.width:c.u===W.AUTO&&(a.right=t.w-a.left-a.width)),f&&(a.height=d?n.height:n.height*a.width/n.width,o.u===W.AUTO&&l.u===W.AUTO?(a.top=0,a.bottom=t.h-a.height):o.u===W.AUTO?a.top=t.h-a.bottom-a.height:l.u===W.AUTO&&(a.bottom=t.h-a.top-a.height))}},r.prototype.calRepaintStyle=function(t){e.prototype.calRepaintStyle.call(this,t);var r=this.computedStyle,i=this.loader;if(this.isPure=r.backgroundColor[3]<=0,this.isPure&&(null==i?void 0:i.success)){var a=r.objectFit,n=r.borderTopLeftRadius,s=r.borderTopRightRadius,o=r.borderBottomLeftRadius,c=r.borderBottomRightRadius;if(a!==ie.COVER&&a!==ie.FILL||!(n||s||o||c)){if(a===ie.CONTAIN&&(n||s||o||c)){var l=i.width/i.height,u=r.width/r.height;if(u>l){var h=r.height*l,d=.5*(r.width-h);(n>d||s>d||o>d||c>d)&&(this.isPure=!1)}else if(u<l){var f=r.width/l,m=.5*(r.height-f);(n>m||s>m||o>m||c>m)&&(this.isPure=!1)}else this.isPure=!1}}else this.isPure=!1}},r.prototype.calContent=function(){if(this.hasContent=!1,this.computedStyle.visibility===ee.HIDDEN||0===this.computedStyle.opacity)return this.hasContent;var e=this.loader;return(null==e?void 0:e.success)?e.frames.length?this._frameIndex>=0&&this._frameIndex<e.frames.length&&(this.hasContent=!0):e.source&&(this.hasContent=!0):this.hasContent=this.computedStyle.backgroundColor[3]>0,this.hasContent},r.prototype.renderCanvas=function(){var t,r=this,i=r.isPure,a=r.loader,n=r.computedStyle;if(i){if(null===(t=this.canvasCache)||void 0===t||t.release(),null==a?void 0:a.success){var s=a.width,o=a.height;if(a.frames.length){var c=Math.min(a.frames.length-1,Math.max(0,this._frameIndex));if((Q=a.frames[c])&&(s>F.maxTextureSize||o>F.maxTextureSize))if((R=this.canvasCache=Zt.getVideoFrameInstance(s,o,Q)).available=!0,1===R.getCount()){var l=n.width,u=n.height,h=n.objectFit,d=0,f=0,m=a.width/a.height,p=l/u;if(h===ie.CONTAIN){if(p>m){var g=u*m;d=.5*(l-g),l=g}else if(p<m){var v=l/m;f=.5*(u-v),u=v}}else if(h===ie.COVER)if(p>m){var y=l/m;f=.5*(u-y),u=y}else if(p<m){var b=u*m;d=.5*(l-b),l=b}for(var k=0,T=(L=R.list).length;k<T;k++){var w=L[k],S=w.x,x=w.y;w.os.ctx.drawImage(Q,-S+d,-x+f,l,u)}}}else if(a.source&&(a.width>F.maxTextureSize||a.height>F.maxTextureSize)){if((R=this.canvasCache=Zt.getImgInstance(s,o,this._src)).available=!0,1===R.getCount()){l=n.width,u=n.height,h=n.objectFit,d=0,f=0,m=a.width/a.height,p=l/u;if(h===ie.CONTAIN){if(p>m){var C=u*m;d=.5*(l-C),l=C}else if(p<m){var E=l/m;f=.5*(u-E),u=E}}else if(h===ie.COVER)if(p>m){var A=l/m;f=.5*(u-A),u=A}else if(p<m){var P=u*m;d=.5*(l-P),l=P}for(k=0,T=(L=R.list).length;k<T;k++){var I=L[k];S=I.x,x=I.y;I.os.ctx.drawImage(a.source,-S+d,-x+f,l,u)}}}}}else{e.prototype.renderCanvas.call(this);var R,O=this.computedStyle,M=this._bboxInt||this.bboxInt;S=M[0],x=M[1],s=M[2]-S,o=M[3]-x,l=O.width,u=O.height,h=O.objectFit,d=0,f=0;if(null==a?void 0:a.success){m=a.width/a.height,p=l/u;if(h===ie.CONTAIN){if(p>m){var _=u*m;d=.5*(l-_),l=_}else if(p<m){var D=l/m;f=.5*(u-D),u=D}}else if(h===ie.COVER)if(p>m){var B=l/m;f=.5*(u-B),u=B}else if(p<m){var N=u*m;d=.5*(l-N),l=N}}(R=this.canvasCache=new Zt(s,o,-S,-x)).available=!0;var L=R.list;if(O.backgroundColor[3]>0){var U=this.getBackgroundCoords(S,x);L.forEach(function(e){var t=e.x,r=e.y,i=e.os.ctx;i.fillStyle=he(O.backgroundColor),i.beginPath(),Er(i,U,1,-t,-r),i.closePath(),i.fill()})}for(k=0,T=L.length;k<T;k++){var z=L[k],W=z.x,V=z.y,H=z.os.ctx,j=-W,X=-V;if(null==a?void 0:a.success){var q=O.borderTopLeftRadius,G=O.borderTopRightRadius,K=O.borderBottomLeftRadius,Y=O.borderBottomRightRadius;if(q||G||K||Y){var $=this.getBackgroundCoords(W,V);H.save(),H.beginPath(),Er(H,$,1,-W,-V),H.closePath(),H.clip()}if(a.frames.length){var Q;c=Math.min(a.frames.length-1,Math.max(0,this._frameIndex));(Q=a.frames[c])&&H.drawImage(Q,j+d,X+f,l,u)}else a.source&&H.drawImage(a.source,j+d,X+f,l,u);(q||G||K||Y)&&H.restore()}}}},r.prototype.genTexture=function(t){var r=this,i=r.isPure,a=r.loader,n=r.canvasCache;if(i){if(null==a?void 0:a.success)if(a.width>F.maxTextureSize||a.height>F.maxTextureSize)if((null==n?void 0:n.available)&&ir.hasCanvasCacheInstance(n)){var s=ir.getCanvasCacheInstance(t,n,this._rect||this.rect);this.textureTarget=this.textureCache=s}else{this.renderCanvas();s=ir.getCanvasCacheInstance(t,this.canvasCache,this._rect||this.rect);this.textureTarget=this.textureCache=s,this.canvasCache.release()}else{var o=this.computedStyle,c=o.width,l=o.height,u=o.objectFit,h=this._rect||this.rect,d=(s=void 0,a.width/a.height),f=c/l;if(u===ie.CONTAIN){if(f>d){var m=.5*(c-(v=l*d));(h=h.slice(0))[0]+=m,h[2]-=m}else if(f<d){m=.5*(l-(p=c/d));(h=h.slice(0))[1]+=m,h[3]-=m}}else if(u===ie.COVER)if(f>d){var p=c/d;s={x1:0,y1:g=(m=.5*Math.abs(l-p))/p,x3:1,y3:1-g}}else if(f<d){var g,v=l*d;s={x1:g=(m=.5*Math.abs(c-v))/v,y1:0,x3:1-g,y3:1}}if(a.frames.length){var y=Math.min(a.frames.length-1,Math.max(0,this._frameIndex)),b=a.frames[y];if(b){var k=ir.getVideoFrameInstance(t,b,h,s);this.textureTarget=this.textureCache=k}}else if(a.source){k=ir.getImgInstance(t,a.source,h,s);this.textureTarget=this.textureCache=k}}}else e.prototype.genTexture.call(this,t)},r.prototype.release=function(){e.prototype.release.call(this);var t=this.loader;(null==t?void 0:t.success)&&t.release()},r.prototype.frameAnimate=function(e,t){var r=new Cr(this,e,t);return this.initAnimate(r,t)},Object.defineProperty(r.prototype,"src",{get:function(){return this._src},set:function(e){this._src!==e&&(this._src=e,this.refresh())},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"frameIndex",{get:function(){return this._frameIndex},set:function(e){this._frameIndex!==e&&(this._frameIndex=e,this.refresh())},enumerable:!1,configurable:!0}),r}(wr);var Dr,Br={parseJSON:function(e){var t=e.tagName,r=e.props,i=void 0===r?{}:r,a=e.children,n=void 0===a?[]:a,s=e.animation,o=void 0===s?[]:s;if(!t)throw new Error("Missing tagName");if(!Array.isArray(n))throw new Error("Children must be an array");if(!Array.isArray(o))throw new Error("Animation must be an array");if("img"!==t)throw new Error("Unknown tagName");return new _r(i)}},Fr=function(e){function r(t,r){void 0===r&&(r=[]);var i=e.call(this,t)||this;return i.children=r,i}return t(r,e),r.prototype.didMount=function(){e.prototype.didMount.call(this);var t=this.children,r=t.length;if(r){var i=t[0];i.parent=this,i.didMount();for(var a=i,n=1;n<r;n++){var s=t[n];s.didMount(),s.parent=this,a.next=s,s.prev=a,a=s}}},r.prototype.didUnmount=function(){e.prototype.didUnmount.call(this),this.children.forEach(function(e){e.didUnmount()})},r.prototype.layout=function(t){e.prototype.layout.call(this,t);for(var r=this.children,i=0,a=r.length;i<a;i++){r[i].layout({w:this.computedStyle.width,h:this.computedStyle.height})}},r.prototype.structure=function(t){var r=e.prototype.structure.call(this,t);return this.children.forEach(function(e){r=r.concat(e.structure(t+1))}),r[0].num=this.children.length,r[0].total=r.length-1,r},r.prototype.insertStruct=function(e,t){var r,i=this.struct,a=this.root,n=e.structure(i.lv+1),s=a.structs;if(t){var o=this.children[t-1].struct,c=o.total;r=s.indexOf(o)+c+1}else r=s.indexOf(i)+1;s.splice.apply(s,function(e,t,r){if(r||2===arguments.length)for(var i,a=0,n=t.length;a<n;a++)!i&&a in t||(i||(i=Array.prototype.slice.call(t,0,a)),i[a]=t[a]);return e.concat(i||Array.prototype.slice.call(t))}([r,0],n,!1));var l=n[0].total+1;i.num++,i.total+=l;for(var u=this.parent;u;)u.struct.total+=l,u=u.parent},r.prototype.deleteStruct=function(e){var t=e.struct,r=t.total+1,i=this.root.structs,a=i.indexOf(t);i.splice(a,r);var n=this.struct;n.num--,n.total-=r;for(var s=this.parent;s;)s.struct.total-=r,s=s.parent},r.prototype.appendChild=function(e,t){e.remove();var r=this.root,i=this.children,a=i.length;if(a){var n=i[i.length-1];n.next=e,e.prev=n}e.parent=this,e.root=r,i.push(e),r&&this.isMounted?(this.insertStruct(e,a),r.addUpdate(e,[],Bt.ADD_DOM,t)):t&&t(!0)},r.prototype.prependChild=function(e,t){e.remove();var r=this.root,i=this.children;if(i.length){var a=i[0];a.next=e,e.prev=a}e.parent=this,e.root=r,i.push(e),r&&!this.isDestroyed?(this.insertStruct(e,0),r.addUpdate(e,[],Bt.ADD_DOM,t)):t&&t(!0)},r.prototype.removeChild=function(e,t){e.parent===this?e.remove(t):ne.error("Invalid parameter of removeChild()")},r}(wr),Nr={alpha:!0,antialias:!0,premultipliedAlpha:!0,preserveDrawingBuffer:!0,depth:!0,stencil:!0};function Lr(e){return e.visibility===ee.HIDDEN||e.opacity<=0}function Ur(e,t,r,i){return function(e,t,r,i,a,n){var s,o,c=rt(e[0],e[1],e[2],e[3],t),l=c.x1,u=c.y1,h=c.x2,d=c.y2,f=c.x3,m=c.y3,p=c.x4,g=c.y4;if(l===p&&u===d&&h===f&&m===g)return l>h&&(l=(s=[f,l])[0],f=s[1]),d>m&&(u=(o=[m,u])[0],m=o[1]),function(e,t,r,i,a,n,s,o,c){if(void 0===c&&(c=!1),c){if(e>s||t>o||a>r||n>i)return!1;if((r===a||e===s)&&(i<n||t>o))return!1;if((i===t||t===i)&&(r<a||e>s))return!1}else if(e>=s||t>=o||a>=r||n>=i)return!1;return!0}(r,i,r+a,i+n,l,u,f,m,!1);return function(e,t,r,i,a,n){var s,o;void 0===n&&(n=!1),e>r&&(e=(s=[r,e])[0],r=s[1]),t>i&&(t=(o=[i,t])[0],i=o[1]);for(var c=0,l=0,u=0,h=0,d=0,f=a.length;d<f;d++){var m=a[d],p=m.x,g=m.y;if(d?(c=Math.min(c,p),l=Math.min(l,g),u=Math.max(u,p),h=Math.max(h,g)):(c=p,l=g,u=p,h=g),n){if(p>=e&&p<=r&&g>=t&&g<=i)return!0}else if(p>e&&p<r&&g>t&&g<i)return!0;var v=a[(d+1)%f],y=v.x,b=v.y;if(p===y){if(p>=e&&p<=r)if(g>=b){if(g>=i&&b<=t)return!0}else if(g<=t&&b>=i)return!0}else if(g===b){if(g>=t&&g<=i)if(p>=y){if(p>=r&&y<=e)return!0}else if(p<=e&&y>=r)return!0}else{var k=y-p,T=b-g,w=(e-p)/k;if(w>=0&&w<=1){var S=g+w*T;if(n&&S>=t&&S<=i||!n&&S>t&&S<i)return!0}var x=(r-p)/k;if(x>=0&&x<=1&&(S=g+x*T,n&&S>=t&&S<=i||!n&&S>t&&S<i))return!0}}return c<=e&&l<=t&&u>=r&&h>=i}(r,i,r+a,i+n,[{x:l,y:u},{x:h,y:d},{x:f,y:m},{x:p,y:g}],!1)}(e,t,0,0,r,i)}function zr(e,t){var r=t.structs,i=t.width,a=t.height;!function(e,t){var r=t.structs;t.contentLoadingCount=0;for(var i=0,a=r.length;i<a;i++){var n=r[i].node,s=n.refreshLevel;n.refreshLevel=Bt.NONE,s>=Bt.REPAINT&&n.calContent(),t.contentLoadingCount+=n.calContentLoading()}}(0,t);var n=.5*i,s=.5*a,o=t.programs.program;e.useProgram(o);for(var c=0,l=r.length;c<l;c++){var u=r[c],h=u.node,d=u.total;if(Lr(h.computedStyle)){for(var f=c+1;f<c+d;f++){var m=r[f].node;Wr(m,f,m.parent)}c+=d}else{Wr(h,c,h.parent);var p=h._opacity,g=h._matrixWorld,v=h.textureTarget,y=!1;if((null==v?void 0:v.available)?y=Ur(v.bbox,g,i,a):(y=Ur(h._filterBbox||h.filterBbox,g,i,a))&&h.hasContent&&(h.genTexture(e),v=h.textureTarget),y&&(null==v?void 0:v.available))for(var b=v.list,k=0,T=b.length;k<T;k++){var w=b[k],S=w.bbox,x=w.t,C=w.tc;x&&Xt(e,n,s,o,[{opacity:p,matrix:g,bbox:S,texture:x,tc:C}],0,0,!0)}(null==v?void 0:v.available)&&v!==h.textureCache&&(c+=d)}}}function Wr(e,t,r){var i=!1,a=!1;t?(i=e.hasCacheOp&&e.parentOpId===r.localOpId,a=e.hasCacheMw&&e.parentMwId===r.localMwId):(i=e.hasCacheOp,a=e.hasCacheMw),i||(e._opacity=r?r._opacity*e.computedStyle.opacity:e.computedStyle.opacity,r&&(e.parentOpId=r.localOpId),e.hasCacheOp=!0),a||(Ye(e._matrixWorld,r?Ge(r._matrixWorld,e.matrix):e.matrix),r&&(e.parentMwId=r.localMwId),e.hasCacheMw&&e.localMwId++,e.hasCacheMw=!0)}var Vr=function(){function e(){this.task=[],this.now=ne.now(),this.id=0}return e.prototype.init=function(){var e=this,t=this.task;ne.cancelAnimationFrame(this.id);var r=this.now=ne.now(),i=function(){ne.cancelAnimationFrame(e.id),e.id=ne.requestAnimationFrame(function(){var a=e.now=ne.now();if(!Dr&&t.length){var n=a-r;n=Math.max(n,0),r=a,t.slice(0).forEach(function(e){e(n)}),t.length&&i()}})};i()},e.prototype.onFrame=function(e){var t=this.task;t.length||this.init(),t.push(e)},e.prototype.offFrame=function(e){var t=this.task,r=t.indexOf(e);r>-1&&t.splice(r,1),t.length||(ne.cancelAnimationFrame(this.id),this.now=0)},e.prototype.nextFrame=function(e){var t=this,r=function(i){e(i),t.offFrame(r)};return this.onFrame(r),r},e.prototype.pause=function(){Dr=!0},e.prototype.resume=function(){Dr&&(this.init(),Dr=!1)},e}(),Hr=new Vr;
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).kronoFlow=t()}(this,function(){"use strict";var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)};function t(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function i(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(i.prototype=r.prototype,new i)}var r=function(){return r=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++)for(var a in t=arguments[r])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},r.apply(this,arguments)};function i(e,t,r,i){return new(r||(r=Promise))(function(a,n){function o(e){try{c(i.next(e))}catch(e){n(e)}}function s(e){try{c(i.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,s)}c((i=i.apply(e,t||[])).next())})}function a(e,t){var r,i,a,n={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,s[0]&&(n=0)),n;)try{if(r=1,i&&(a=2&s[0]?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,i=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if(!(a=n.trys,(a=a.length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){n=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(6===s[0]&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(e){s=[6,e],i=0}finally{r=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}function n(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],i=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function o(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=n(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=e[r]&&function(t){return new Promise(function(i,a){(function(e,t,r,i){Promise.resolve(i).then(function(t){e({value:t,done:r})},t)})(i,a,(t=e[r](t)).done,t.value)})}}}"function"==typeof SuppressedError&&SuppressedError;const s=[];for(let e=0;e<256;++e)s.push((e+256).toString(16).slice(1));let c;const u=new Uint8Array(16);var l={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function h(e,t,r){const i=(e=e||{}).random??e.rng?.()??function(){if(!c){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");c=crypto.getRandomValues.bind(crypto)}return c(u)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return(s[e[t+0]]+s[e[t+1]]+s[e[t+2]]+s[e[t+3]]+"-"+s[e[t+4]]+s[e[t+5]]+"-"+s[e[t+6]]+s[e[t+7]]+"-"+s[e[t+8]]+s[e[t+9]]+"-"+s[e[t+10]]+s[e[t+11]]+s[e[t+12]]+s[e[t+13]]+s[e[t+14]]+s[e[t+15]]).toLowerCase()}(i)}var d={}.toString;function f(e){return function(t){return d.call(t)==="[object "+e+"]"}}var m,p=f("Object"),g=f("String"),v=(m=["Function","AsyncFunction","GeneratorFunction"],function(e){for(var t=d.call(e),r=0,i=m.length;r<i;r++)if(t==="[object "+m[r]+"]")return!0;return!1}),y=f("Number"),b=f("Boolean"),x=f("Date"),T={}.hasOwnProperty,w=T.toString,k=w.call(Object);function S(e){return null==e}function E(e){if(!e||"[object Object]"!==d.call(e))return!1;var t=Object.getPrototypeOf(e);if(!t)return!0;var r=T.call(t,"constructor")&&t.constructor;return"function"==typeof r&&w.call(r)===k}function C(e){if(S(e)||"object"!=typeof e)return e;if(x(e))return new Date(e);if(!E(e)&&!Array.isArray(e))return e;var t=Array.isArray(e)?[]:{};return Object.keys(e).forEach(function(r){t[r]=C(e[r])}),t}function A(e,t,r){if(e===t)return!0;if(p(e)&&p(t)){for(var i={},a=r||Object.keys(e),n=0,o=a.length;n<o;n++){var s=a[n];if(!t.hasOwnProperty(s)||!A(e[s],t[s]))return!1;i[s]=!0}for(n=0,o=(a=r||Object.keys(t)).length;n<o;n++){s=a[n];if(!i.hasOwnProperty(s))return!1}return!0}if(x(e)&&x(t))return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(n=0,o=e.length;n<o;n++)if(!A(e[n],t[n]))return!1;return!0}return e===t}var _={isNil:S,isString:g,isNumber:y,isObject:p,isBoolean:b,isDate:x,isFunction:v,isPlainObject:E,equal:A,extend:function(e,t,r){if(null===t||"object"!=typeof t)return e;r||(r=Object.keys(t));for(var i=0,a=r.length;i<a;){var n=r[i];e[n]=t[n],i++}return e},clone:C},M=function(){function e(){this.__eHash={}}return e.prototype.on=function(e,t){if(v(t))if(Array.isArray(e))for(var r=0,i=e.length;r<i;r++)this.on(e[r],t);else{this.__eHash.hasOwnProperty(e)||(this.__eHash[e]=[]);r=0;var a=this.__eHash[e];for(i=a.length;r<i;r++)if(a[r]===t)return;this.__eHash[e].push(t)}},e.prototype.once=function(e,t){var r=this;if(v(t))if(Array.isArray(e))for(var i=0,a=e.length;i<a;i++)this.once(e[i],t);else{var n=function(){t.apply(r,Array.prototype.slice.call(arguments)),r.off(e,n)};if(n.__eventCb=t,Array.isArray(e))for(i=0,a=e.length;i<a;i++)this.once(e[i],t);else this.on(e,n)}},e.prototype.off=function(e,t){if(Array.isArray(e))for(var r=0,i=e.length;r<i;r++)this.off(e[r],t);else if(this.__eHash.hasOwnProperty(e))if(t){r=0;var a=this.__eHash[e];for(i=a.length;r<i;r++)if(a[r]===t||a[r].__eventCb===t){a.splice(r,1);break}}else delete this.__eHash[e]},e.prototype.emit=function(e){for(var t=this,r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];if(Array.isArray(e))e.forEach(function(e){if(e&&t.__eHash.hasOwnProperty(e)){var i=t.__eHash[e];if(i.length)for(var a=0,n=(i=i.slice()).length;a<n;a++){var o=i[a];v(o)&&o.apply(t,r)}}});else if(e){var a=this.__eHash[e];if(a&&a.length)for(var n=0,o=(a=a.slice()).length;n<o;n++){var s=a[n];v(s)&&s.apply(this,r)}}},e}(),I={left:"auto",top:"auto",right:"auto",bottom:"auto",width:"auto",height:"auto",lineHeight:"normal",fontFamily:"Arial",fontSize:16,fontWeight:400,fontStyle:"normal",letterSpacing:0,paragraphSpacing:0,textAlign:"left",textVerticalAlign:"top",textDecoration:[],textShadow:"none",color:[0,0,0,1],visibility:"visible",opacity:1,backgroundColor:"transparent",fill:[],fillOpacity:[],fillEnable:[],fillMode:[],fillRule:"nonzero",stroke:[],strokeEnable:[],strokeWidth:[],strokePosition:[],strokeMode:[],strokeDasharray:[],strokeLinecap:"butt",strokeLinejoin:"miter",strokeMiterlimit:4,translateX:0,translateY:0,translateZ:0,skewX:0,skewY:0,scaleX:1,scaleY:1,rotateX:0,rotateY:0,rotateZ:0,transformOrigin:["center","center"],perspective:0,perspectiveOrigin:["center","center"],perspectiveSelf:0,mixBlendMode:"normal",pointerEvents:!0,maskMode:"none",breakMask:!1,objectFit:"fill",borderTopLeftRadius:0,borderTopRightRadius:0,borderBottomLeftRadius:0,borderBottomRightRadius:0,overflow:"visible",filter:[]};function R(e){var t=Object.assign({},I);return["transformOrigin","perspectiveOrigin","color","strokeDasharray","filter"].forEach(function(e){t[e]=t[e].slice(0)}),Object.assign(t,e)}var P={getDefaultStyle:R},O=2048,D=!1,B=O,F=!1,L={debug:!1,offscreenCanvas:!1,get maxTextureSize(){return O},set maxTextureSize(e){O=F?Math.min(e,B):e,D=!0},get MAX_TEXTURE_SIZE(){return B},MAX_TEXTURE_IMAGE_UNITS:8,MAX_VARYING_VECTORS:15,init:function(e,t,r){D?e<O&&(O=e):O=Math.min(O,e),F=!0,B=e,this.MAX_TEXTURE_IMAGE_UNITS=t,this.MAX_VARYING_VECTORS=r},defaultFontFamily:"Arial",defaultFontSize:16,historyTime:1e3,decoderWorker:"",decoderWorkerStr:"",encoderWorker:"",encoderWorkerStr:"",decodeNextDuration:0,releasePrevDuration:0,gopMinDuration:0,preloadAll:!1,mute:!1,indexedDB:!1,encoderFrameQue:0},N=1e3/60,U={},z="function"==typeof OffscreenCanvas&&OffscreenCanvas.prototype.getContext;var W,V,H,X,j,G,Y,q,K,$,Q,Z,J,ee,te,re,ie,ae,ne={},oe={requestAnimationFrame:function(e){return e?("undefined"!=typeof requestAnimationFrame?(oe.requestAnimationFrame=requestAnimationFrame.bind(null),t=requestAnimationFrame(e)):(t=setTimeout(e,N),oe.requestAnimationFrame=function(e){return setTimeout(e,N)}),t):-1;var t},cancelAnimationFrame:function(e){var t;return"undefined"!=typeof cancelAnimationFrame?(oe.cancelAnimationFrame=cancelAnimationFrame.bind(null),t=cancelAnimationFrame(e)):(t=clearTimeout(e),oe.cancelAnimationFrame=function(e){return clearTimeout(e)}),t},now:function(){return"undefined"!=typeof performance?(oe.now=function(){return Math.floor(performance.now())},Math.floor(performance.now())):(oe.now=Date.now.bind(Date),Date.now())},hasOffscreenCanvas:function(e){return e&&U.hasOwnProperty(e)},getOffscreenCanvas:function(e,t,r,i){return function(e,t,r,i){var a;a=r?U[r]?U[r]:U[r]=!L.debug&&L.offscreenCanvas&&z?new OffscreenCanvas(e,t):document.createElement("canvas"):!L.debug&&L.offscreenCanvas&&z?new OffscreenCanvas(e,t):document.createElement("canvas"),e=Math.ceil(e),t=Math.ceil(t),a.width=e,a.height=t,a.style.position="fixed",a.style.left="9999px",a.style.top="0px",a.style.webkitFontSmoothing="antialiased",a.style.mozOsxFontSmoothing="grayscale",L.debug&&(a.style.width=e+"px",a.style.height=t+"px"),a instanceof HTMLCanvasElement&&(document.body.appendChild(a),r&&a.setAttribute("key",r));var n=a.getContext("2d",i);return n||oe.error("Total canvas memory use exceeds the maximum limit"),{canvas:a,ctx:n,width:e,height:t,available:!0,release:function(){this.available&&!L.debug&&(this.available=!1,n.globalAlpha=1,n.globalCompositeOperation="source-over",n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,e,t),a.width=a.height=0,a instanceof HTMLCanvasElement&&document.body.removeChild(a),a=null)}}}(e,t,r,i)},isWebGLTexture:function(e){if(e&&"undefined"!=typeof WebGLTexture)return e instanceof WebGLTexture},getFontCanvas:function(){return oe.getOffscreenCanvas(16,16,"__$$CHECK_SUPPORT_FONT_FAMILY$$__",{willReadFrequently:!0})},checkSupportFontFamily:function(e){if(e===L.defaultFontFamily)return!0;if(ne.hasOwnProperty(e))return ne[e];var t=oe.getFontCanvas().ctx;t.textAlign="center",t.fillStyle="#000",t.textBaseline="middle",W||(t.clearRect(0,0,16,16),t.font="16px "+L.defaultFontFamily,t.fillText("a",8,8),W=t.getImageData(0,0,16,16).data),t.clearRect(0,0,16,16),/\s/.test(e)&&(e='"'+e.replace(/"/g,'\\"')+'"'),t.font="16px "+e+","+L.defaultFontFamily,t.fillText("a",8,8);for(var r=t.getImageData(0,0,16,16).data,i=0,a=r.length;i<a;i++)if(W[i]!==r[i])return ne[e]=!0;return ne[e]=!1},addArrayBufferFont:function(e,t){return i(this,void 0,void 0,function(){var r;return a(this,function(i){switch(i.label){case 0:return"undefined"==typeof document||"undefined"==typeof FontFace?[3,2]:[4,(r=new FontFace(e,t)).load()];case 1:i.sent(),document.fonts.add(r),i.label=2;case 2:return[2]}})})},addLocalFont:function(e){return i(this,void 0,void 0,function(){var t;return a(this,function(r){switch(r.label){case 0:return"undefined"==typeof document||"undefined"==typeof FontFace?[3,2]:[4,(t=new FontFace(e,"local(".concat(e))).load()];case 1:r.sent(),document.fonts.add(t),r.label=2;case 2:return[2]}})})},loadArrayBufferImg:function(e){return i(this,void 0,void 0,function(){var t,r;return a(this,function(i){return t=new Blob([e]),r=new Image,[2,new Promise(function(e,i){r.onload=function(){e(r)},r.onerror=function(e){i(e)},r.src=URL.createObjectURL(t)})]})})},pdfjsLibWorkerSrc:"https://gw.alipayobjects.com/os/lib/pdfjs-dist/3.11.174/build/pdf.worker.min.js",loadArrayBufferPdf:function(e){return i(this,void 0,void 0,function(){var t,r,i,n,o,s,c,u,l;return a(this,function(a){switch(a.label){case 0:return(t=window.pdfjsLib).GlobalWorkerOptions.workerSrc=oe.pdfjsLibWorkerSrc,r=new Blob([e]),i=URL.createObjectURL(r),[4,t.getDocument(i).promise];case 1:return[4,a.sent().getPage(1)];case 2:return n=a.sent(),o=n.getViewport({scale:1}),(s=document.createElement("canvas")).width=o.width,s.height=o.height,c=s.getContext("2d"),[4,n.render({viewport:o,canvasContext:c,background:"transparent"}).promise];case 3:return a.sent(),[4,new Promise(function(e,t){s.toBlob(function(r){r?e(r):t("")})})];case 4:return u=a.sent(),l=new Image,[2,new Promise(function(e,t){l.onload=function(){e(l)},l.onerror=function(e){t(e)},l.src=URL.createObjectURL(u)})]}})})},loadLocalFonts:function(){return i(this,void 0,void 0,function(){var e;return a(this,function(t){switch(t.label){case 0:if("undefined"==typeof navigator)return[3,5];t.label=1;case 1:return t.trys.push([1,4,,5]),[4,navigator.permissions.query({name:"local-fonts"})];case 2:return"denied"===t.sent().state?(oe.error("No Permission."),[2,[]]):[4,window.queryLocalFonts()];case 3:return[2,t.sent()];case 4:return e=t.sent(),oe.error(e),[2,[]];case 5:return[2,[]]}})})},uploadBlobImgSrc:function(e){return i(this,void 0,void 0,function(){return a(this,function(e){return[2]})})},log:function(e){console.log(e)},warn:function(e){console.warn(e)},error:function(e){console.error(e)}};function se(e,t){if(void 0===t&&(t=!1),"auto"===e)return{v:0,u:V.AUTO};var r=parseFloat(e)||0;return/%$/.test(e)?{v:r,u:V.PERCENT}:/px$/i.test(e)?{v:r,u:V.PX}:/deg$/i.test(e)?{v:r,u:t?V.PX:V.DEG}:{v:r,u:t?V.PX:V.NUMBER}}!function(e){e[e.AUTO=0]="AUTO",e[e.PX=1]="PX",e[e.PERCENT=2]="PERCENT",e[e.NUMBER=3]="NUMBER",e[e.DEG=4]="DEG",e[e.RGBA=5]="RGBA",e[e.BOOLEAN=6]="BOOLEAN",e[e.STRING=7]="STRING",e[e.GRADIENT=8]="GRADIENT",e[e.MATRIX=9]="MATRIX",e[e.SHADOW=10]="SHADOW",e[e.PATTERN=11]="PATTERN",e[e.GAUSS_BLUR=12]="GAUSS_BLUR",e[e.MOTION_BLUR=13]="MOTION_BLUR",e[e.RADIAL_BLUR=14]="RADIAL_BLUR",e[e.BLOOM=15]="BLOOM",e[e.LIGHT_DARK=16]="LIGHT_DARK",e[e.HUE_ROTATE=17]="HUE_ROTATE",e[e.SATURATE=18]="SATURATE",e[e.BRIGHTNESS=19]="BRIGHTNESS",e[e.CONTRAST=20]="CONTRAST",e[e.SEPIA=21]="SEPIA"}(V||(V={})),function(e){e[e.LEFT=0]="LEFT",e[e.RIGHT=1]="RIGHT",e[e.CENTER=2]="CENTER",e[e.JUSTIFY=3]="JUSTIFY"}(H||(H={})),function(e){e[e.TOP=0]="TOP",e[e.MIDDLE=1]="MIDDLE",e[e.BOTTOM=2]="BOTTOM"}(X||(X={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.MULTIPLY=1]="MULTIPLY",e[e.SCREEN=2]="SCREEN",e[e.OVERLAY=3]="OVERLAY",e[e.DARKEN=4]="DARKEN",e[e.LIGHTEN=5]="LIGHTEN",e[e.COLOR_DODGE=6]="COLOR_DODGE",e[e.COLOR_BURN=7]="COLOR_BURN",e[e.HARD_LIGHT=8]="HARD_LIGHT",e[e.SOFT_LIGHT=9]="SOFT_LIGHT",e[e.DIFFERENCE=10]="DIFFERENCE",e[e.EXCLUSION=11]="EXCLUSION",e[e.HUE=12]="HUE",e[e.SATURATION=13]="SATURATION",e[e.COLOR=14]="COLOR",e[e.LUMINOSITY=15]="LUMINOSITY"}(j||(j={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.ITALIC=1]="ITALIC",e[e.OBLIQUE=2]="OBLIQUE"}(G||(G={})),function(e){e[e.LINEAR=0]="LINEAR",e[e.RADIAL=1]="RADIAL",e[e.CONIC=2]="CONIC"}(Y||(Y={})),function(e){e[e.NONE=0]="NONE",e[e.UNION=1]="UNION",e[e.SUBTRACT=2]="SUBTRACT",e[e.INTERSECT=3]="INTERSECT",e[e.XOR=4]="XOR"}(q||(q={})),function(e){e[e.NON_ZERO=0]="NON_ZERO",e[e.EVEN_ODD=1]="EVEN_ODD"}(K||(K={})),function(e){e[e.NONE=0]="NONE",e[e.OUTLINE=1]="OUTLINE",e[e.ALPHA=2]="ALPHA",e[e.GRAY=3]="GRAY",e[e.ALPHA_WITH=4]="ALPHA_WITH",e[e.GRAY_WITH=5]="GRAY_WITH"}($||($={})),function(e){e[e.BUTT=0]="BUTT",e[e.ROUND=1]="ROUND",e[e.SQUARE=2]="SQUARE"}(Q||(Q={})),function(e){e[e.MITER=0]="MITER",e[e.ROUND=1]="ROUND",e[e.BEVEL=2]="BEVEL"}(Z||(Z={})),function(e){e[e.CENTER=0]="CENTER",e[e.INSIDE=1]="INSIDE",e[e.OUTSIDE=2]="OUTSIDE"}(J||(J={})),function(e){e[e.TILE=0]="TILE",e[e.FILL=1]="FILL",e[e.STRETCH=2]="STRETCH",e[e.FIT=3]="FIT"}(ee||(ee={})),function(e){e[e.VISIBLE=0]="VISIBLE",e[e.HIDDEN=1]="HIDDEN"}(te||(te={})),function(e){e[e.NONE=0]="NONE",e[e.UNDERLINE=1]="UNDERLINE",e[e.LINE_THROUGH=2]="LINE_THROUGH"}(re||(re={})),function(e){e[e.VISIBLE=0]="VISIBLE",e[e.HIDDEN=1]="HIDDEN",e[e.CLIP=2]="CLIP"}(ie||(ie={})),function(e){e[e.FILL=0]="FILL",e[e.CONTAIN=1]="CONTAIN",e[e.COVER=2]="COVER"}(ae||(ae={}));var ce,ue=["fontFamily","fontSize","fontWeight","lineHeight","letterSpacing","paragraphSpacing","fontStyle","textAlign","textDecoration","color","textShadow","stroke","strokeWidth","strokeEnable"];!function(e){e[e.NONE=0]="NONE",e[e.STRAIGHT=1]="STRAIGHT",e[e.MIRRORED=2]="MIRRORED",e[e.ASYMMETRIC=3]="ASYMMETRIC",e[e.DISCONNECTED=4]="DISCONNECTED"}(ce||(ce={}));var le={StyleUnit:V,TEXT_ALIGN:H,TEXT_VERTICAL_ALIGN:X,MIX_BLEND_MODE:j,FONT_STYLE:G,GRADIENT:Y,FILL_RULE:K,MASK:$,STROKE_LINE_CAP:Q,STROKE_LINE_JOIN:Z,STROKE_POSITION:J,PATTERN_FILL_TYPE:ee,VISIBILITY:te,TEXT_DECORATION:re,OVERFLOW:ie,calUnit:se,RICH_KEYS:ue},he={position:/(([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?[pxremvwhina%]*)|(left|top|right|bottom|center)){1,2}/gi,gradient:/\b(\w+)-?gradient\s*\((.+)\)/i,img:/(?:\burl\((['"]?)(.*?)\1\))|(?:\b((data:)))/i,shadow:/([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:px)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:px)?)\s+((?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:px)?)\s+((?:#[a-f\d]{3,8})|(?:rgba?\s*\(.+?\)))/i};function de(e){if(Array.isArray(e))return e;var t=[];if(!e||/transparent/i.test(e))t=[0,0,0,0];else if(/^#?[a-f\d]{3,8}$/i.test(e))3===(e=e.replace("#","")).length||4===e.length?(t.push(parseInt(e.charAt(0)+e.charAt(0),16)),t.push(parseInt(e.charAt(1)+e.charAt(1),16)),t.push(parseInt(e.charAt(2)+e.charAt(2),16)),4===e.length?t[3]=parseInt(e.charAt(3)+e.charAt(3),16):t[3]=1):6===e.length?(t.push(parseInt(e.slice(0,2),16)),t.push(parseInt(e.slice(2,4),16)),t.push(parseInt(e.slice(4),16)),t[3]=1):8===e.length?(t.push(parseInt(e.slice(0,2),16)),t.push(parseInt(e.slice(2,4),16)),t.push(parseInt(e.slice(4,6),16)),t.push(parseInt(e.slice(6),16)/255)):(t[0]=t[1]=t[2]=0,t[3]=1);else{var r=e.match(/rgba?\s*\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)/i);r?(t=[parseInt(r[1]),parseInt(r[2]),parseInt(r[3])],S(r[4])?t[3]=1:t[3]=parseFloat(r[4])):t=[0,0,0,0]}return t}function fe(e){var t=de(e);if(Array.isArray(t)){var r=Math.min(255,Math.max(Math.round(t[0]),0)),i=Math.min(255,Math.max(Math.round(t[1]),0)),a=Math.min(255,Math.max(Math.round(t[2]),0));if(3===t.length||4===t.length){if(4===t.length){var n=Math.min(1,Math.max(t[3],0));if(n<1)return"rgba("+r+","+i+","+a+","+n+")"}return"rgba("+r+","+i+","+a+",1)"}}return e||"rgba(0,0,0,0)"}function me(e){var t=e.toString(16).toUpperCase();return 1===t.length&&(t="0"+t),t}var pe={color2rgbaInt:de,color2rgbaStr:fe,color2hexStr:function(e){var t=de(e);if(Array.isArray(t)){var r=Math.min(255,Math.max(Math.round(t[0]),0)),i=Math.min(255,Math.max(Math.round(t[1]),0)),a=Math.min(255,Math.max(Math.round(t[2]),0));if(3===t.length||4===t.length){if(4===t.length){var n=Math.min(1,Math.max(t[3],0));if(n<1)return"#"+me(r)+me(i)+me(a)+me(Math.floor(255*n))}return"#"+me(r)+me(i)+me(a)}}return e||"#000"},color2gl:function(e){return Array.isArray(e)||(e=de(e)),[e[0]/255,e[1]/255,e[2]/255,3===e.length?1:e[3]]},clampColor:function(e){var t=Math.min(255,Math.max(Math.round(e[0]),0)),r=Math.min(255,Math.max(Math.round(e[1]),0)),i=Math.min(255,Math.max(Math.round(e[2]),0));return e.length>3?[t,r,i,Math.min(1,Math.max(0,e[3]))]:[t,r,i]}},ge=function(){function e(){this.table=new Uint16Array(16),this.trans=new Uint16Array(288)}function t(t,r){this.source=t,this.sourceIndex=0,this.tag=0,this.bitcount=0,this.dest=r,this.destLen=0,this.ltree=new e,this.dtree=new e}var r=new e,i=new e,a=new Uint8Array(30),n=new Uint16Array(30),o=new Uint8Array(30),s=new Uint16Array(30),c=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),u=new e,l=new Uint8Array(320);function h(e,t,r,i){var a,n;for(a=0;a<r;++a)e[a]=0;for(a=0;a<30-r;++a)e[a+r]=a/r|0;for(n=i,a=0;a<30;++a)t[a]=n,n+=1<<e[a]}var d=new Uint16Array(16);function f(e,t,r,i){var a,n;for(a=0;a<16;++a)e.table[a]=0;for(a=0;a<i;++a)e.table[t[r+a]]++;for(e.table[0]=0,n=0,a=0;a<16;++a)d[a]=n,n+=e.table[a];for(a=0;a<i;++a)t[r+a]&&(e.trans[d[t[r+a]]++]=a)}function m(e){e.bitcount--||(e.tag=e.source[e.sourceIndex++],e.bitcount=7);var t=1&e.tag;return e.tag>>>=1,t}function p(e,t,r){if(!t)return r;for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<<e.bitcount,e.bitcount+=8;var i=e.tag&65535>>>16-t;return e.tag>>>=t,e.bitcount-=t,i+r}function g(e,t){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<<e.bitcount,e.bitcount+=8;var r=0,i=0,a=0,n=e.tag;do{i=2*i+(1&n),n>>>=1,++a,r+=t.table[a],i-=t.table[a]}while(i>=0);return e.tag=n,e.bitcount-=a,t.trans[r+i]}function v(e,t,r){var i,a,n,o,s,h;for(i=p(e,5,257),a=p(e,5,1),n=p(e,4,4),o=0;o<19;++o)l[o]=0;for(o=0;o<n;++o){var d=p(e,3,0);l[c[o]]=d}for(f(u,l,0,19),s=0;s<i+a;){var m=g(e,u),v=void 0;switch(m){case 16:for(v=l[s-1],h=p(e,2,3);h;--h)l[s++]=v;break;case 17:for(h=p(e,3,3);h;--h)l[s++]=0;break;case 18:for(h=p(e,7,11);h;--h)l[s++]=0;break;default:l[s++]=m}}f(t,l,0,i),f(r,l,i,a)}function y(e,t,r){for(;;){var i=g(e,t);if(256===i)return 0;if(i<256)e.dest[e.destLen++]=i;else{var c,u,l,h=void 0;for(c=p(e,a[i-=257],n[i]),u=g(e,r),h=l=e.destLen-p(e,o[u],s[u]);h<l+c;++h)e.dest[e.destLen++]=e.dest[h]}}}function b(e){for(var t,r;e.bitcount>8;)e.sourceIndex--,e.bitcount-=8;if((t=256*(t=e.source[e.sourceIndex+1])+e.source[e.sourceIndex])!==(65535&~(256*e.source[e.sourceIndex+3]+e.source[e.sourceIndex+2])))return-3;for(e.sourceIndex+=4,r=t;r;--r)e.dest[e.destLen++]=e.source[e.sourceIndex++];return e.bitcount=0,0}return function(e,t){var r;for(r=0;r<7;++r)e.table[r]=0;for(e.table[7]=24,e.table[8]=152,e.table[9]=112,r=0;r<24;++r)e.trans[r]=256+r;for(r=0;r<144;++r)e.trans[24+r]=r;for(r=0;r<8;++r)e.trans[168+r]=280+r;for(r=0;r<112;++r)e.trans[176+r]=144+r;for(r=0;r<5;++r)t.table[r]=0;for(t.table[5]=32,r=0;r<32;++r)t.trans[r]=r}(r,i),h(a,n,4,3),h(o,s,2,1),a[28]=0,n[28]=258,function(e,a){var n,o,s=new t(e,a);do{switch(n=m(s),p(s,2,0)){case 0:o=b(s);break;case 1:o=y(s,r,i);break;case 2:v(s,s.ltree,s.dtree),o=y(s,s.ltree,s.dtree);break;default:o=-3}if(0!==o)throw new Error("Data error")}while(!n);return s.destLen<s.dest.length?"function"==typeof s.dest.slice?s.dest.slice(0,s.destLen):s.dest.subarray(0,s.destLen):s.dest}}(),ve={UTF16:function(e,t,r){for(var i=[],a=r/2,n=0;n<a;n++,t+=2)i[n]=e.getUint16(t);return String.fromCharCode.apply(null,i)}},ye={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};function be(e,t){for(var r="",i=t;i<t+4;i++)r+=String.fromCharCode(e.getInt8(i));return r}function xe(e,t){return e.getUint16(t,!1)}function Te(e,t){return e.getUint32(t,!1)}ve.MACSTRING=function(e,t,r,i){var a=ye[i];if(void 0!==a){for(var n="",o=0;o<r;o++){var s=e.getUint8(t+o);n+=s<=127?String.fromCharCode(s):a[127&s]}return n}};var we={byte:1,uShort:2,short:2,uLong:4,fixed:4,longDateTime:8,tag:4};function ke(e,t){for(var r=[],i=12,a=0;a<t;a+=1){var n=be(e,i),o=Te(e,i+4),s=Te(e,i+8),c=Te(e,i+12);r.push({tag:n,checksum:o,offset:s,length:c,compression:!1}),i+=16}return r}function Se(e,t){if("WOFF"===t.compression){var r=new Uint8Array(e.buffer,t.offset+2,t.compressedLength-2),i=new Uint8Array(t.length);return ge(r,i),i.byteLength!==t.length&&oe.error("Decompression error: "+t.tag+" decompressed length doesn't match recorded length"),{data:new DataView(i.buffer,0),offset:0}}return{data:e,offset:t.offset}}var Ee=function(){function e(e,t){this.data=e,this.offset=t,this.relativeOffset=0}return e.prototype.parseByte=function(){var e=this.data.getUint8(this.offset+this.relativeOffset);return this.relativeOffset+=1,e},e.prototype.parseUShort=function(){var e=this.data.getUint16(this.offset+this.relativeOffset);return this.relativeOffset+=2,e},e.prototype.parseULong=function(){var e=Te(this.data,this.offset+this.relativeOffset);return this.relativeOffset+=4,e},e.prototype.parseShort=function(){var e=this.data.getInt16(this.offset+this.relativeOffset);return this.relativeOffset+=2,e},e.prototype.parseFixed=function(){var e,t,r=(e=this.data,t=this.offset+this.relativeOffset,e.getInt16(t,!1)+e.getUint16(t+2,!1)/65535);return this.relativeOffset+=4,r},e.prototype.parseVersion=function(e){var t=xe(this.data,this.offset+this.relativeOffset),r=xe(this.data,this.offset+this.relativeOffset+2);return this.relativeOffset+=4,void 0===e&&(e=4096),t+r/e/10},e.prototype.skip=function(e,t){void 0===t&&(t=1),this.relativeOffset+=we[e]*t},e}(),Ce=["copyright","fontFamily","fontSubfamily","uniqueID","fullName","version","postScriptName","trademark","manufacturer","designer","description","manufacturerURL","designerURL","license","licenseURL","reserved","preferredFamily","preferredSubfamily","compatibleFullName","sampleText","postScriptFindFontName","wwsFamily","wwsSubfamily"],Ae={0:"en",1:"fr",2:"de",3:"it",4:"nl",5:"sv",6:"es",7:"da",8:"pt",9:"no",10:"he",11:"ja",12:"ar",13:"fi",14:"el",15:"is",16:"mt",17:"tr",18:"hr",19:"zh-Hant",20:"ur",21:"hi",22:"th",23:"ko",24:"lt",25:"pl",26:"hu",27:"es",28:"lv",29:"se",30:"fo",31:"fa",32:"ru",33:"zh",34:"nl-BE",35:"ga",36:"sq",37:"ro",38:"cz",39:"sk",40:"si",41:"yi",42:"sr",43:"mk",44:"bg",45:"uk",46:"be",47:"uz",48:"kk",49:"az-Cyrl",50:"az-Arab",51:"hy",52:"ka",53:"mo",54:"ky",55:"tg",56:"tk",57:"mn-CN",58:"mn",59:"ps",60:"ks",61:"ku",62:"sd",63:"bo",64:"ne",65:"sa",66:"mr",67:"bn",68:"as",69:"gu",70:"pa",71:"or",72:"ml",73:"kn",74:"ta",75:"te",76:"si",77:"my",78:"km",79:"lo",80:"vi",81:"id",82:"tl",83:"ms",84:"ms-Arab",85:"am",86:"ti",87:"om",88:"so",89:"sw",90:"rw",91:"rn",92:"ny",93:"mg",94:"eo",128:"cy",129:"eu",130:"ca",131:"la",132:"qu",133:"gn",134:"ay",135:"tt",136:"ug",137:"dz",138:"jv",139:"su",140:"gl",141:"af",142:"br",143:"iu",144:"gd",145:"gv",146:"ga",147:"to",148:"el-polyton",149:"kl",150:"az",151:"nn"},_e={1078:"af",1052:"sq",1156:"gsw",1118:"am",5121:"ar-DZ",15361:"ar-BH",3073:"ar",2049:"ar-IQ",11265:"ar-JO",13313:"ar-KW",12289:"ar-LB",4097:"ar-LY",6145:"ary",8193:"ar-OM",16385:"ar-QA",1025:"ar-SA",10241:"ar-SY",7169:"aeb",14337:"ar-AE",9217:"ar-YE",1067:"hy",1101:"as",2092:"az-Cyrl",1068:"az",1133:"ba",1069:"eu",1059:"be",2117:"bn",1093:"bn-IN",8218:"bs-Cyrl",5146:"bs",1150:"br",1026:"bg",1027:"ca",3076:"zh-HK",5124:"zh-MO",2052:"zh",4100:"zh-SG",1028:"zh-TW",1155:"co",1050:"hr",4122:"hr-BA",1029:"cs",1030:"da",1164:"prs",1125:"dv",2067:"nl-BE",1043:"nl",3081:"en-AU",10249:"en-BZ",4105:"en-CA",9225:"en-029",16393:"en-IN",6153:"en-IE",8201:"en-JM",17417:"en-MY",5129:"en-NZ",13321:"en-PH",18441:"en-SG",7177:"en-ZA",11273:"en-TT",2057:"en-GB",1033:"en",12297:"en-ZW",1061:"et",1080:"fo",1124:"fil",1035:"fi",2060:"fr-BE",3084:"fr-CA",1036:"fr",5132:"fr-LU",6156:"fr-MC",4108:"fr-CH",1122:"fy",1110:"gl",1079:"ka",3079:"de-AT",1031:"de",5127:"de-LI",4103:"de-LU",2055:"de-CH",1032:"el",1135:"kl",1095:"gu",1128:"ha",1037:"he",1081:"hi",1038:"hu",1039:"is",1136:"ig",1057:"id",1117:"iu",2141:"iu-Latn",2108:"ga",1076:"xh",1077:"zu",1040:"it",2064:"it-CH",1041:"ja",1099:"kn",1087:"kk",1107:"km",1158:"quc",1159:"rw",1089:"sw",1111:"kok",1042:"ko",1088:"ky",1108:"lo",1062:"lv",1063:"lt",2094:"dsb",1134:"lb",1071:"mk",2110:"ms-BN",1086:"ms",1100:"ml",1082:"mt",1153:"mi",1146:"arn",1102:"mr",1148:"moh",1104:"mn",2128:"mn-CN",1121:"ne",1044:"nb",2068:"nn",1154:"oc",1096:"or",1123:"ps",1045:"pl",1046:"pt",2070:"pt-PT",1094:"pa",1131:"qu-BO",2155:"qu-EC",3179:"qu",1048:"ro",1047:"rm",1049:"ru",9275:"smn",4155:"smj-NO",5179:"smj",3131:"se-FI",1083:"se",2107:"se-SE",8251:"sms",6203:"sma-NO",7227:"sms",1103:"sa",7194:"sr-Cyrl-BA",3098:"sr",6170:"sr-Latn-BA",2074:"sr-Latn",1132:"nso",1074:"tn",1115:"si",1051:"sk",1060:"sl",11274:"es-AR",16394:"es-BO",13322:"es-CL",9226:"es-CO",5130:"es-CR",7178:"es-DO",12298:"es-EC",17418:"es-SV",4106:"es-GT",18442:"es-HN",2058:"es-MX",19466:"es-NI",6154:"es-PA",15370:"es-PY",10250:"es-PE",20490:"es-PR",3082:"es",1034:"es",21514:"es-US",14346:"es-UY",8202:"es-VE",2077:"sv-FI",1053:"sv",1114:"syr",1064:"tg",2143:"tzm",1097:"ta",1092:"tt",1098:"te",1054:"th",1105:"bo",1055:"tr",1090:"tk",1152:"ug",1058:"uk",1070:"hsb",1056:"ur",2115:"uz-Cyrl",1091:"uz",1066:"vi",1106:"cy",1160:"wo",1157:"sah",1144:"ii",1130:"yo"},Me={0:"macintosh",1:"x-mac-japanese",2:"x-mac-chinesetrad",3:"x-mac-korean",6:"x-mac-greek",7:"x-mac-cyrillic",9:"x-mac-devanagai",10:"x-mac-gurmukhi",11:"x-mac-gujarati",12:"x-mac-oriya",13:"x-mac-bengali",14:"x-mac-tamil",15:"x-mac-telugu",16:"x-mac-kannada",17:"x-mac-malayalam",18:"x-mac-sinhalese",19:"x-mac-burmese",20:"x-mac-khmer",21:"x-mac-thai",22:"x-mac-lao",23:"x-mac-georgian",24:"x-mac-armenian",25:"x-mac-chinesesimp",26:"x-mac-tibetan",27:"x-mac-mongolian",28:"x-mac-ethiopic",29:"x-mac-ce",30:"x-mac-vietnamese",31:"x-mac-extarabic"},Ie={15:"x-mac-icelandic",17:"x-mac-turkish",18:"x-mac-croatian",24:"x-mac-ce",25:"x-mac-ce",26:"x-mac-ce",27:"x-mac-ce",28:"x-mac-ce",30:"x-mac-icelandic",37:"x-mac-romanian",38:"x-mac-ce",39:"x-mac-ce",40:"x-mac-ce",143:"x-mac-inuit",146:"x-mac-gaelic"};function Re(e,t,r){switch(e){case 0:if(65535===t)return"und";if(r)return r[t];break;case 1:return Ae[t];case 3:return _e[t]}}var Pe="utf-16";function Oe(e,t,r){switch(e){case 0:return Pe;case 1:return Ie[r]||Me[t];case 3:if(1===t||10===t)return Pe}}var De={0:"unicode",1:"macintosh",2:"reserved",3:"windows"};function Be(e){return De[e]}function Fe(e,t){var r,i=new Ee(e,t),a=i.parseULong();r="Unsupported ltag table version.",1===a||fail(r),i.skip("uLong",1);for(var n=i.parseULong(),o=[],s=0;s<n;s++){for(var c="",u=t+i.parseUShort(),l=i.parseUShort(),h=u;h<u+l;++h)c+=String.fromCharCode(e.getInt8(h));o.push(c)}return o}var Le={parse:function(e){var t,r,i=new DataView(e,0),a=be(i,0),n=!1;if(a===String.fromCharCode(0,1,0,0)||"true"===a||"typ1"===a)r=ke(i,t=xe(i,4));else if("OTTO"===a)r=ke(i,t=xe(i,4)),n=!0;else if("wOFF"===a){var o=be(i,4);if(o===String.fromCharCode(0,1,0,0));else if("OTTO"!==o)return void oe.error("Unsupported OpenType flavor "+a);r=function(e,t){for(var r=[],i=44,a=0;a<t;a+=1){var n=be(e,i),o=Te(e,i+4),s=Te(e,i+8),c=Te(e,i+12),u=void 0;u=s<c&&"WOFF",r.push({tag:n,offset:o,compression:u,compressedLength:s,length:c}),i+=20}return r}(i,t=xe(i,12))}else if("wOF2"===a){oe.error("WOFF2 require an external decompressor library, see examples at: https://github.com/opentypejs/opentype.js/issues/183#issuecomment-1147228025")}else oe.error("Unsupported OpenType signature "+a);for(var s,c,u,l,h=2048,d=0,f=!1,m=0;m<t;m++){var p=r[m];if("head"===p.tag){var g=Se(i,p);(v=new Ee(g.data,g.offset)).parseVersion(),v.parseFixed(),v.parseULong(),v.parseULong(),v.parseUShort(),h=v.parseUShort()}else if("hhea"===p.tag){if(!f){g=Se(i,p);(v=new Ee(g.data,g.offset)).parseVersion(),s=Math.abs(v.parseShort()),c=Math.abs(v.parseShort()),d=Math.abs(v.parseShort()||0)}}else if("ltag"===p.tag){l=Fe((g=Se(i,p)).data,g.offset)}else if("name"===p.tag)u=Se(i,p);else if("OS/2"===p.tag){g=Se(i,p);var v,y=(v=new Ee(g.data,g.offset)).parseUShort();v.parseShort(),v.parseUShort(),v.parseUShort(),v.parseUShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort(),v.parseShort();for(var b=0;b<10;b++)v.parseByte();v.parseULong(),v.parseULong(),v.parseULong(),v.parseULong(),v.parseByte(),v.parseByte(),v.parseByte(),v.parseByte();var x=v.parseUShort(),T=y>=4&&(128&x||n);(T||void 0===s)&&(v.parseUShort(),v.parseUShort(),s=Math.abs(v.parseShort()),c=Math.abs(v.parseShort()),d=Math.abs(v.parseShort()||0),T&&(f=!0))}}var w=u?function(e,t,r){for(var i={},a=new Ee(e,t),n=a.parseUShort(),o=a.parseUShort(),s=a.offset+a.parseUShort(),c=0;c<o;c++){var u=a.parseUShort(),l=a.parseUShort(),h=a.parseUShort(),d=a.parseUShort(),f=Ce[d]||d,m=a.parseUShort(),p=a.parseUShort(),g=Re(u,h,r),v=Oe(u,l,h),y=Be(u);if(void 0!==v&&void 0!==g&&void 0!==y){var b=void 0;if(b=v===Pe?ve.UTF16(e,s+p,m):ve.MACSTRING(e,s+p,m,v)){var x=i[y];void 0===x&&(x=i[y]={});var T=x[f];void 0===T&&(T=x[f]={}),T[g]=b}}}return 1===n&&a.parseUShort(),i}(u.data,u.offset,l):{},k={};return w.macintosh&&Object.assign(k,w.macintosh),w.windows&&Object.assign(k,w.windows),{name:k,emSquare:h,ascent:s,descent:c,lineGap:d}}},Ne={name:"Arial",family:"Arial",lhr:1.14990234375,car:1.1171875,blr:.9052734375,lgr:.03271484375,list:[{style:"Regular",postscriptName:"Arial"}]},Ue="localFonts",ze="undefined"!=typeof navigator&&/win/i.test(navigator.platform),We={Arial:Ne},Ve={Arial:Ne},He={},Xe={KEY_INFO:Ue,info:We,data:Ve,hasRegister:function(e){return Ve.hasOwnProperty(e)},registerLocalFonts:function(e){return i(this,void 0,void 0,function(){var t,r,i,n,o,s,c,u,l,h,d,f,m,p,g,v;return a(this,function(a){switch(a.label){case 0:return e?[3,2]:[4,oe.loadLocalFonts()];case 1:e=a.sent()||[],a.label=2;case 2:if(t={},"undefined"!=typeof localStorage)try{t=JSON.parse(localStorage.getItem(Ue)||"{}")}catch(e){}r=t.data||{},(!t.version||t.version<2)&&(r={}),i=0,n=e.length,a.label=3;case 3:return i<n?(o=e[i],s=o.postscriptName,c=o.family,u=o.style,ze?[4,oe.addLocalFont(s)]:[3,5]):[3,10];case 4:a.sent(),a.label=5;case 5:return r.hasOwnProperty(c)&&(l=r[c],We[c]=We[c]||{name:l.name,family:c,lhr:l.lhr,car:l.car,blr:l.blr,lgr:l.lgr,list:[]}),We.hasOwnProperty(c)?[3,8]:(h=We[c]={name:"",family:"",lhr:0,car:0,blr:0,lgr:0,list:[]},[4,o.blob()]);case 6:return[4,a.sent().arrayBuffer()];case 7:d=a.sent(),(f=Le.parse(d))&&f.name&&(h.name=(null===(p=f.name.preferredFamily)||void 0===p?void 0:p.zh)||(null===(g=f.name.preferredFamily)||void 0===g?void 0:g.en)||(null===(v=f.name.fontFamily)||void 0===v?void 0:v.zh)),h.name=h.name||c,h.family=c,m=this._cal(c,f),Object.assign(h,m),a.label=8;case 8:this._register(c,u,s),je(c),s!==c&&je(s),a.label=9;case 9:return i++,[3,3];case 10:return this.updateLocalStorage(),[2]}})})},registerAb:function(e,t){return i(this,void 0,void 0,function(){var r,i,n,o,s,c,u,l,h,d,f,m,p,g;return a(this,function(a){switch(a.label){case 0:return t&&Ve.hasOwnProperty(t)?[2]:(r={},(i=Le.parse(e))&&i.name&&(r.family=(null===(u=i.name.preferredFamily)||void 0===u?void 0:u.en)||(null===(l=i.name.fontFamily)||void 0===l?void 0:l.en),r.name=(null===(h=i.name.preferredFamily)||void 0===h?void 0:h.zh)||(null===(d=i.name.preferredFamily)||void 0===d?void 0:d.en)||(null===(f=i.name.fontFamily)||void 0===f?void 0:f.zh)||r.family),n=r.family,o=(null===(m=i.name.preferredSubfamily)||void 0===m?void 0:m.en)||(null===(p=i.name.fontSubfamily)||void 0===p?void 0:p.en),s=null===(g=i.name.postScriptName)||void 0===g?void 0:g.en,n&&o&&s?[4,oe.addArrayBufferFont(n,e)]:[2]);case 1:return a.sent(),s===n?[3,3]:[4,oe.addArrayBufferFont(s,e)];case 2:a.sent(),a.label=3;case 3:return t&&t!==n&&t!==s?[4,oe.addArrayBufferFont(t,e)]:[3,5];case 4:a.sent(),a.label=5;case 5:return We.hasOwnProperty(n)||(c=this._cal(n,i),Object.assign(r,c),r.list=[],We[n]=Ve[n]=r),this._register(n,o,s),t&&t!==n&&t!==s&&(We[t]=Ve[t]=Ve[n]),je(n),s!==n&&je(s),t&&t!==n&&t!==s&&je(t),[2,Ve[n]]}})})},_cal:function(e,t){var r=0;return["times","helvetica","courier"].indexOf(e.toLowerCase())>-1&&(r=Math.round(.15*(t.ascent+t.descent))),{lhr:(t.ascent+r+t.descent+t.lineGap)/t.emSquare,car:(t.ascent+r+t.descent)/t.emSquare,blr:(t.ascent+r)/t.emSquare,lgr:t.lineGap/t.emSquare}},_register:function(e,t,r){for(var i=We[e],a=i.list=i.list||[],n=!1,o=0,s=a.length;o<s;o++){if(a[o].postscriptName===r){n=!0;break}}return n||a.push({style:t,postscriptName:r}),{family:e,postscriptName:r,data:Ve[e]=Ve[r]=i}},waitIfNotRegister:function(e,t){Ve[e]||(He[e]=He[e]||[]).push(t)},updateLocalStorage:function(){var e={};for(var t in We)if(We.hasOwnProperty(t)){var r=We[t];e[t]={name:r.name,lhr:r.lhr,car:r.car,blr:r.blr,lgr:r.lgr}}"undefined"!=typeof localStorage&&localStorage.setItem(Ue,JSON.stringify({version:2,data:e}))}};function je(e){He.hasOwnProperty(e)&&(He[e].slice(0).forEach(function(e){e()}),delete He[e])}function Ge(e,t,r,i){return e*r+t*i}function Ye(e,t,r,i,a,n){return e*i+t*a+r*n}function qe(e,t,r,i){return e*i-r*t}function Ke(e,t,r,i,a){void 0===a&&(a=!1);var n=0;return n=e===r&&t===i?1:t===i&&0===t?e>0&&r>0||e<0&&r<0?1:-1:e===r&&0===e?t>0&&i>0||t<0&&i<0?1:-1:Ge(e,t,r,i)/($e(e,t)*$e(r,i)),a?n:Math.acos(n)||0}function $e(e,t){return Math.sqrt(Math.pow(e,2)+Math.pow(t,2))}function Qe(e,t,r){return Math.sqrt(Math.pow(e,2)+Math.pow(t,2)+Math.pow(r,2))}function Ze(e,t){var r=$e(e,t);return{x:e/r,y:t/r}}function Je(e,t,r,i){return Math.abs(e)<1e-9&&Math.abs(t)<1e-9&&Math.abs(r)<1e-9&&Math.abs(i)<1e-9}function et(e,t,r,i,a,n){return Math.abs(e)<1e-9&&Math.abs(t)<1e-9&&Math.abs(r)<1e-9&&Math.abs(i)<1e-9&&Math.abs(a)<1e-9&&Math.abs(n)<1e-9}function tt(e,t,r,i){var a=Ge(e,t,r,i)/($e(e,t)*$e(r,i));return a<-1?a=-1:a>1&&(a=1),Math.acos(a)}function rt(e,t,r,i,a,n){var o=Ye(e,t,r,i,a,n)/(Qe(e,t,r)*Qe(i,a,n));return o<-1?o=-1:o>1&&(o=1),Math.acos(o)}var it={dotProduct:Ge,dotProduct3:Ye,crossProduct:qe,crossProduct3:function(e,t,r,i,a,n){return{x:t*n-a*r,y:r*i-n*e,z:e*a-i*t}},projection:function(e,t,r,i){var a=Ge(e,t,r,i),n=Math.pow(r,2)+Math.pow(i,2);return{x:a*r/n,y:a*i/n}},includedAngle:Ke,length:$e,length3:Qe,unitize:Ze,unitize3:function(e,t,r){var i=Qe(e,t,r);return{x:e/i,y:t/i,z:r/i}},angle:tt,angle3:rt,isParallel:function(e,t,r,i){if(Je(e,t,r,i))return!0;var a=tt(e,t,r,i);return Math.abs(a)<1e-9||Math.PI-Math.abs(a)<1e-9},isParallel3:function(e,t,r,i,a,n){if(et(e,t,r,i,a,n))return!0;var o=rt(e,t,r,i,a,n);return Math.abs(o)<1e-9||Math.PI-Math.abs(o)<1e-9},isZero:Je,isZero3:et};function at(){return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}function nt(e){return!e||!e.length||1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}function ot(e,t){if(nt(e))return new Float32Array(t);if(nt(t))return new Float32Array(e);for(var r=at(),i=0;i<4;i++){var a=e[i],n=e[i+4],o=e[i+8],s=e[i+12];r[i]=a*t[0]+n*t[1]+o*t[2]+s*t[3],r[i+4]=a*t[4]+n*t[5]+o*t[6]+s*t[7],r[i+8]=a*t[8]+n*t[9]+o*t[10]+s*t[11],r[i+12]=a*t[12]+n*t[13]+o*t[14]+s*t[15]}return r}function st(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function ct(e){if(nt(e))return at();var t=new Float32Array(16);t[0]=e[5]*e[10]*e[15]-e[5]*e[11]*e[14]-e[9]*e[6]*e[15]+e[9]*e[7]*e[14]+e[13]*e[6]*e[11]-e[13]*e[7]*e[10],t[4]=-e[4]*e[10]*e[15]+e[4]*e[11]*e[14]+e[8]*e[6]*e[15]-e[8]*e[7]*e[14]-e[12]*e[6]*e[11]+e[12]*e[7]*e[10],t[8]=e[4]*e[9]*e[15]-e[4]*e[11]*e[13]-e[8]*e[5]*e[15]+e[8]*e[7]*e[13]+e[12]*e[5]*e[11]-e[12]*e[7]*e[9],t[12]=-e[4]*e[9]*e[14]+e[4]*e[10]*e[13]+e[8]*e[5]*e[14]-e[8]*e[6]*e[13]-e[12]*e[5]*e[10]+e[12]*e[6]*e[9],t[1]=-e[1]*e[10]*e[15]+e[1]*e[11]*e[14]+e[9]*e[2]*e[15]-e[9]*e[3]*e[14]-e[13]*e[2]*e[11]+e[13]*e[3]*e[10],t[5]=e[0]*e[10]*e[15]-e[0]*e[11]*e[14]-e[8]*e[2]*e[15]+e[8]*e[3]*e[14]+e[12]*e[2]*e[11]-e[12]*e[3]*e[10],t[9]=-e[0]*e[9]*e[15]+e[0]*e[11]*e[13]+e[8]*e[1]*e[15]-e[8]*e[3]*e[13]-e[12]*e[1]*e[11]+e[12]*e[3]*e[9],t[13]=e[0]*e[9]*e[14]-e[0]*e[10]*e[13]-e[8]*e[1]*e[14]+e[8]*e[2]*e[13]+e[12]*e[1]*e[10]-e[12]*e[2]*e[9],t[2]=e[1]*e[6]*e[15]-e[1]*e[7]*e[14]-e[5]*e[2]*e[15]+e[5]*e[3]*e[14]+e[13]*e[2]*e[7]-e[13]*e[3]*e[6],t[6]=-e[0]*e[6]*e[15]+e[0]*e[7]*e[14]+e[4]*e[2]*e[15]-e[4]*e[3]*e[14]-e[12]*e[2]*e[7]+e[12]*e[3]*e[6],t[10]=e[0]*e[5]*e[15]-e[0]*e[7]*e[13]-e[4]*e[1]*e[15]+e[4]*e[3]*e[13]+e[12]*e[1]*e[7]-e[12]*e[3]*e[5],t[14]=-e[0]*e[5]*e[14]+e[0]*e[6]*e[13]+e[4]*e[1]*e[14]-e[4]*e[2]*e[13]-e[12]*e[1]*e[6]+e[12]*e[2]*e[5],t[3]=-e[1]*e[6]*e[11]+e[1]*e[7]*e[10]+e[5]*e[2]*e[11]-e[5]*e[3]*e[10]-e[9]*e[2]*e[7]+e[9]*e[3]*e[6],t[7]=e[0]*e[6]*e[11]-e[0]*e[7]*e[10]-e[4]*e[2]*e[11]+e[4]*e[3]*e[10]+e[8]*e[2]*e[7]-e[8]*e[3]*e[6],t[11]=-e[0]*e[5]*e[11]+e[0]*e[7]*e[9]+e[4]*e[1]*e[11]-e[4]*e[3]*e[9]-e[8]*e[1]*e[7]+e[8]*e[3]*e[5],t[15]=e[0]*e[5]*e[10]-e[0]*e[6]*e[9]-e[4]*e[1]*e[10]+e[4]*e[2]*e[9]+e[8]*e[1]*e[6]-e[8]*e[2]*e[5];var r=e[0]*t[0]+e[1]*t[4]+e[2]*t[8]+e[3]*t[12];if(0===r)return at();r=1/r;for(var i=new Float32Array(16),a=0;a<16;a++)i[a]=t[a]*r;return i}function ut(e,t){return e&&t&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e}function lt(e,t,r){return t||r?(e[12]+=e[0]*t+e[4]*r,e[13]+=e[1]*t+e[5]*r,e[14]+=e[2]*t+e[6]*r,e[15]+=e[3]*t+e[7]*r,e):e}function ht(e,t,r){if(!e&&!t)return r;var i=r[3],a=r[7],n=r[11],o=r[15];return r[0]+=i*e,r[1]+=i*t,r[4]+=a*e,r[5]+=a*t,r[8]+=n*e,r[9]+=n*t,r[12]+=o*e,r[13]+=o*t,r}function dt(e,t){if(!t)return e;var r=Math.tan(t);return e[4]+=e[0]*r,e[5]+=e[1]*r,e[6]+=e[2]*r,e[7]+=e[3]*r,e}function ft(e,t){if(!t)return e;var r=Math.tan(t);return e[0]+=e[4]*r,e[1]+=e[5]*r,e[2]+=e[6]*r,e[3]+=e[7]*r,e}function mt(e,t){if(!t)return e;var r=Math.sin(t),i=Math.cos(t),a=e[4],n=e[5],o=e[6],s=e[7],c=e[8],u=e[10],l=e[11];return e[4]=a*i+c*r,e[5]=n*i+o*r,e[6]=o*i+u*r,e[7]=s*i+l*r,e[8]=a*-r+c*i,e[9]=n*-r+o*i,e[10]=o*-r+u*i,e[11]=s*-r+l*i,e}function pt(e,t){if(!t)return e;var r=Math.sin(t),i=Math.cos(t),a=e[0],n=e[1],o=e[2],s=e[3],c=e[8],u=e[9],l=e[10],h=e[11];return e[0]=a*i+c*-r,e[1]=n*i+u*-r,e[2]=o*i+l*-r,e[3]=s*i+h*-r,e[8]=a*r+c*i,e[9]=n*r+u*i,e[10]=o*r+l*i,e[11]=s*r+h*i,e}function gt(e,t){if(!t)return e;var r=Math.sin(t),i=Math.cos(t),a=e[0],n=e[1],o=e[2],s=e[3],c=e[4],u=e[5],l=e[6],h=e[7];return e[0]=a*i+c*r,e[1]=n*i+u*r,e[2]=o*i+l*r,e[3]=s*i+h*r,e[4]=a*-r+c*i,e[5]=n*-r+u*i,e[6]=o*-r+l*i,e[7]=s*-r+h*i,e}function vt(e,t){return 1===t||(e[0]*=t,e[1]*=t,e[2]*=t,e[3]*=t),e}function yt(e,t){return 1===t||(e[4]*=t,e[5]*=t,e[6]*=t,e[7]*=t),e}function bt(e,t){if(t&&!nt(t)){var r=e.x,i=e.y,a=e.z,n=void 0===a?0:a,o=e.w,s=void 0===o?1:o,c=t[0],u=t[1],l=t[2],h=t[3],d=t[4],f=t[5],m=t[6],p=t[7],g=t[8],v=t[9],y=t[10],b=t[11],x=t[12],T=t[13],w=t[14],k=t[15],S={x:(1===c?r:r*c)+(d?i*d:0)+(1===s?x:x*s),y:(1===u?r:r*u)+(f?i*f:0)+(1===s?T:T*s),z:n,w:s};return h||p||b?S.w=r*h+i*p+n*b+k*s:1!==k&&(S.w*=k),n?(S.x+=n*g,S.y+=n*v,S.z=r*l+i*m+w+n*y):(l||m||w)&&(S.z=r*l+i*m+w),S}return e}function xt(e){if(16===e.length)return ct(e);var t=e[0],r=e[1],i=e[2],a=e[3],n=e[4],o=e[5];if(1===t&&0===r&&0===i&&1===a&&0===n&&0===o)return e;var s=t*a-r*i;return 0===s?e:new Float32Array([a/s,-r/s,-i/s,t/s,(i*o-a*n)/s,(r*n-t*o)/s])}function Tt(e,t,r,i,a){var n,o,s,c,u,l,h,d,f=bt({x:e,y:t},a),m=f.x,p=f.y,g=f.z,v=f.w,y=bt({x:r,y:i},a),b=y.x,x=y.y,T=y.z,w=y.w;if(a&&a.length&&(a[1]||a[2]||a[4]||a[6]||a[7]||a[8])){var k=bt({x:r,y:t},a);n=k.x,o=k.y,s=k.z,c=k.w,u=(k=bt({x:e,y:i},a)).x,l=k.y,h=k.z,d=k.w}else n=b,o=p,u=m,l=x;return{x1:m,y1:p,z1:g,w1:v,x2:n,y2:o,z2:s,w2:c,x3:b,y3:x,z3:T,w3:w,x4:u,y4:l,z4:h,w4:d}}var wt={identity:at,isE:nt,toE:st,assignMatrix:ut,inverse:xt,inverse4:ct,calPoint:bt,calRectPoints:Tt,tfoMultiply:ht,multiplyTfo:lt,multiply:ot,multiplyRef:function(e,t){if(nt(e))return t;if(nt(t))return ut(t,e),t;for(var r=t[0],i=t[1],a=t[2],n=t[3],o=t[4],s=t[5],c=t[6],u=t[7],l=t[8],h=t[9],d=t[10],f=t[11],m=t[12],p=t[13],g=t[14],v=t[15],y=0;y<4;y++){var b=e[y],x=e[y+4],T=e[y+8],w=e[y+12];t[y]=b*r+x*i+T*a+w*n,t[y+4]=b*o+x*s+T*c+w*u,t[y+8]=b*l+x*h+T*d+w*f,t[y+12]=b*m+x*p+T*g+w*v}return t},multiplyTranslate:function(e,t,r){return t||r?(e[12]+=e[0]*t+e[4]*r,e[13]+=e[1]*t+e[5]*r,e[14]+=e[2]*t+e[6]*r,e[15]+=e[3]*t+e[7]*r,e):e},multiplyTranslateX:function(e,t){return t?(e[12]+=e[0]*t,e[13]+=e[1]*t,e[14]+=e[2]*t,e[15]+=e[3]*t,e):e},multiplyTranslateY:function(e,t){return t?(e[12]+=e[4]*t,e[13]+=e[5]*t,e[14]+=e[6]*t,e[15]+=e[7]*t,e):e},multiplyTranslateZ:function(e,t){return t?(e[12]+=e[8]*t,e[13]+=e[9]*t,e[14]+=e[10]*t,e[15]+=e[11]*t,e):e},multiplyRotateX:mt,multiplyRotateY:pt,multiplyRotateZ:gt,multiplySkewX:dt,multiplySkewY:ft,multiplyScale:function(e,t){return 1===t||(e[0]*=t,e[1]*=t,e[2]*=t,e[3]*=t,e[4]*=t,e[5]*=t,e[6]*=t,e[7]*=t),e},multiplyScaleX:vt,multiplyScaleY:yt},kt=1e-9;function St(e){var t=[],r=e[3],i=e[2]/r,a=e[1]/r,n=(3*a-i*i)/3,o=(2*i*i*i-9*a*i+27*(e[0]/r))/27,s=i/3,c=o*o/4+n*n*n/27,u=o/2;if(Math.abs(c)<=kt&&(c=0),c>0){var l=Math.sqrt(c),h=void 0,d=void 0;d=(h=-u+l)>=0?Math.pow(h,1/3):-Math.pow(-h,1/3),(h=-u-l)>=0?d+=Math.pow(h,1/3):d-=Math.pow(-h,1/3),t.push(d-s)}else if(c<0){var f=Math.sqrt(-n/3),m=Math.atan2(Math.sqrt(-c),-u)/3,p=Math.cos(m),g=Math.sin(m),v=Math.sqrt(3);t.push(2*f*p-s),t.push(-f*(p+v*g)-s),t.push(-f*(p-v*g)-s)}else{h=void 0;h=u>=0?-Math.pow(u,1/3):Math.pow(-u,1/3),t.push(2*h-s),t.push(-h-s)}return t}function Et(e){for(var t=e.length-1,r=t;r>=0&&0===e[r];r--)t--;var i=[];switch(t){case 1:i=function(e){var t=[],r=e[1];return 0!==r&&t.push(-e[0]/r),t}(e);break;case 2:i=function(e){var t=[],r=e[2],i=e[1]/r,a=i*i-e[0]/r*4;if(a>0){var n=Math.sqrt(a);t.push(.5*(-i+n)),t.push(.5*(-i-n))}else 0===a&&t.push(.5*-i);return t}(e);break;case 3:i=St(e);break;case 4:i=function(e){var t=[],r=e[4],i=e[3]/r,a=e[2]/r,n=e[1]/r,o=e[0]/r,s=St([1,-a,i*n-4*o,-i*i*o+4*a*o-n*n].reverse())[0],c=i*i/4-a+s;if(Math.abs(c)<=kt&&(c=0),c>0){var u=Math.sqrt(c),l=(m=3*i*i/4-u*u-2*a)+(f=(4*i*a-8*n-i*i*i)/(4*u)),h=m-f;if(Math.abs(l)<=kt&&(l=0),Math.abs(h)<=kt&&(h=0),l>=0){var d=Math.sqrt(l);t.push(-i/4+(u+d)/2),t.push(-i/4+(u-d)/2)}h>=0&&(d=Math.sqrt(h),t.push(-i/4+(d-u)/2),t.push(-i/4-(d+u)/2))}else if(c<0);else{var f;if((f=s*s-4*o)>=-1e-9){var m;if(f<0&&(f=0),(m=3*i*i/4-2*a)+(f=2*Math.sqrt(f))>=kt){var p=Math.sqrt(m+f);t.push(-i/4+p/2),t.push(-i/4-p/2)}m-f>=kt&&(p=Math.sqrt(m-f),t.push(-i/4+p/2),t.push(-i/4-p/2))}}return t}(e)}return i}function Ct(e,t,r){return[r,-1,t-r*e]}function At(e,t,r,i,a,n){var o=Math.min(e,a),s=Math.min(t,n),c=Math.max(e,a),u=Math.max(t,n);if(r<o||i<s||r>c||i>u){var l=(e-r)/(e-2*r+a);isNaN(l)||l<0?l=0:l>1&&(l=1);var h=(t-i)/(t-2*i+n);isNaN(h)||h<0?h=0:h>1&&(h=1);var d=1-l,f=1-h,m=d*d*e+2*d*l*r+l*l*a,p=f*f*t+2*f*h*i+h*h*n;o=Math.min(o,m),s=Math.min(s,p),c=Math.max(c,m),u=Math.max(u,p)}return[o,s,c,u]}function _t(e,t,r,i,a,n,o,s){Array.isArray(e)&&(o=e[3].x,s=e[3].y,a=e[2].x,n=e[2].y,r=e[1].x,i=e[1].y,t=e[0].y,e=e[0].x);var c=Math.min(e,o),u=Math.min(t,s),l=Math.max(e,o),h=Math.max(t,s);(r<c||i<u||r>l||i>h||a<c||n<u||a>l||n>h)&&Ht(e,t,r,i,a,n,o,s).forEach(function(d){var f=Ft([{x:e,y:t},{x:r,y:i},{x:a,y:n},{x:o,y:s}],d);c=Math.min(c,f.x),u=Math.min(u,f.y),l=Math.max(l,f.x),h=Math.max(h,f.y)});return[c,u,l,h]}function Mt(e,t,r,i,a,n,o,s){var c=arguments.length;if(Array.isArray(e)){if((c=e.length)<2||c>4)throw new Error("Unsupported order");return 4===c?_t(e[0].x,e[0].y,e[1].x,e[1].y,e[2].x,e[2].y,e[3].x,e[3].y):3===c?At(e[0].x,e[0].y,e[1].x,e[1].y,e[2].x,e[2].y):[Math.min(e[0].x,e[1].x),Math.min(e[0].y,e[1].y),Math.max(e[0].x,e[1].x),Math.max(e[0].y,e[1].y)]}if(4===c||void 0===a||void 0===n)return[Math.min(e,r),Math.min(t,i),Math.max(e,r),Math.max(t,i)];if(6===c||void 0===o||void 0===s)return At(e,t,r,i,a,n);if(8===c)return _t(e,t,r,i,a,n,o,s);throw new Error("Unsupported order")}function It(e,t,r){var i=e,a=(2*t+r)/3,n=(t+2*r)/3;return(i(t)+3*i(a)+3*i(n)+i(r))*(r-t)/8}function Rt(e,t,r,i){void 0===i&&(i=1e-9);var a=e,n=(t+r)/2,o=It(a,t,r),s=It(a,t,n),c=It(a,n,r),u=s+c-o;return Math.abs(u)<=15*i?s+c+u/15:Rt(a,t,n,i/2)+Rt(a,n,r,i/2)}function Pt(e,t,r){if(void 0===t&&(t=0),void 0===r&&(r=1),2===e.length){var i=e[0],a=i.x,n=i.y,o=e[1],s=o.x,c=o.y;return Math.sqrt(Math.pow(s-a,2)+Math.pow(c-n,2))}if(e.length>4)throw new Error("Unsupported order");return Rt(function(t){var r=Ot(t,e);return Math.sqrt(Math.pow(r.x,2)+Math.pow(r.y,2))},t,r)}function Ot(e,t,r){if(void 0===r&&(r=1),4===t.length)return function(e,t,r){void 0===r&&(r=1);var i=t[0],a=i.x,n=i.y,o=t[1],s=o.x,c=o.y,u=t[2],l=u.x,h=u.y,d=t[3],f=d.x,m=d.y,p=0,g=0;return 0===r?(p=Math.pow(1-e,3)*a+3*e*Math.pow(1-e,2)*s+3*(1-e)*Math.pow(e,2)*l+Math.pow(e,3)*f,g=Math.pow(1-e,3)*n+3*e*Math.pow(1-e,2)*c+3*(1-e)*Math.pow(e,2)*h+Math.pow(e,3)*m):1===r?(p=3*((1-e)*(1-e)*(s-a)+2*(1-e)*e*(l-s)+e*e*(f-l)),g=3*((1-e)*(1-e)*(c-n)+2*(1-e)*e*(h-c)+e*e*(m-h))):2===r?(p=6*(l-2*s+a)*(1-e)+6*(f-2*l+s)*e,g=6*(h-2*c+n)*(1-e)+6*(m-2*h+c)*e):3===r&&(p=6*(f-3*l+3*s-a),g=6*(m-3*h+3*c-n)),{x:p,y:g}}(e,t,r);if(3===t.length)return function(e,t,r){void 0===r&&(r=1);var i=t[0],a=i.x,n=i.y,o=t[1],s=o.x,c=o.y,u=t[2],l=u.x,h=u.y,d=0,f=0;return 0===r?(d=Math.pow(1-e,2)*a+2*e*(1-e)*s+Math.pow(e,2)*l,f=Math.pow(1-e,2)*n+2*e*(1-e)*c+Math.pow(e,2)*h):1===r?(d=2*(1-e)*(s-a)+2*e*(l-s),f=2*(1-e)*(c-n)+2*e*(h-c)):2===r&&(d=2*(l-2*s+a),f=2*(h-2*c+n)),{x:d,y:f}}(e,t,r);throw new Error("Unsupported order")}function Dt(e,t){var r=e[0],i=r.x,a=r.y,n=e[1],o=n.x,s=n.y,c=(o-i)*t+i,u=(s-a)*t+a;if(2===e.length)return[{x:i,y:a},{x:c,y:u}];var l=e[2],h=l.x,d=l.y,f=(h-o)*t+o,m=(d-s)*t+s,p=(f-c)*t+c,g=(m-u)*t+u;if(4===e.length){var v=e[3];return[{x:i,y:a},{x:c,y:u},{x:p,y:g},{x:(((v.x-h)*t+h-f)*t+f-p)*t+p,y:(((v.y-d)*t+d-m)*t+m-g)*t+g}]}if(3===e.length)return[{x:i,y:a},{x:c,y:u},{x:p,y:g}];throw new Error("Unsupported order")}function Bt(e,t,r){var i;void 0===t&&(t=0),void 0===r&&(r=1),t=Math.max(t,0),t=Math.min(t,1),r=Math.max(r,0),r=Math.min(r,1);var a=e.slice(0);if(0===t&&1===r)return a;var n=r<t;return n&&(t=(i=[r,t])[0],r=i[1]),r<1&&(a=Dt(e,r)),t>0&&(r<1&&(t/=r),a=Dt(a.reverse(),1-t).reverse()),n&&a.reverse(),a}function Ft(e,t){if(void 0===t&&(t=0),0===t)return e[0];if(1===t)return e[e.length-1];if(4===e.length)return Nt(e,t);if(3===e.length)return Lt(e,t);if(2===e.length)return{x:e[0].x+(e[1].x-e[0].x)*t,y:e[0].y+(e[1].y-e[0].y)*t};throw new Error("Unsupported order")}function Lt(e,t){return{x:e[0].x*(1-t)*(1-t)+2*e[1].x*t*(1-t)+e[2].x*t*t,y:e[0].y*(1-t)*(1-t)+2*e[1].y*t*(1-t)+e[2].y*t*t}}function Nt(e,t){return{x:e[0].x*(1-t)*(1-t)*(1-t)+3*e[1].x*t*(1-t)*(1-t)+3*e[2].x*t*t*(1-t)+e[3].x*t*t*t,y:e[0].y*(1-t)*(1-t)*(1-t)+3*e[1].y*t*(1-t)*(1-t)+3*e[2].y*t*t*(1-t)+e[3].y*t*t*t}}function Ut(e,t,r,i){if(void 0===i&&(i=1e-9),4===e.length)return function(e,t,r,i){void 0===i&&(i=1e-9);for(var a=Qt(e,t,!0),n=Qt(e,r,!1),o=[],s=0,c=a.length;s<c;s++)for(var u=a[s],l=0,h=n.length;l<h;l++){var d=n[l],f=Math.abs(u-d);f<=i&&o.push({x:u,y:d,diff:f})}o.sort(function(e,t){return e.diff-t.diff}),o.length>3&&o.splice(3);o=o.map(function(e){return.5*(e.x+e.y)});var m=[];return o.forEach(function(a){var n=$t(e,a,!0),o=$t(e,a,!1);Math.abs(n-t)<=i&&Math.abs(o-r)<=i&&m.push(a)}),m}(e,t,r,i);if(3===e.length)return function(e,t,r,i){void 0===i&&(i=1e-9);for(var a=Qt(e,t,!0),n=Qt(e,r,!1),o=[],s=0,c=a.length;s<c;s++)for(var u=a[s],l=0,h=n.length;l<h;l++){var d=n[l],f=Math.abs(u-d);f<=i&&o.push({x:u,y:d,diff:f})}o.sort(function(e,t){return e.diff-t.diff}),o.length>2&&o.splice(2);o=o.map(function(e){return.5*(e.x+e.y)});var m=[];return o.forEach(function(a){var n=$t(e,a,!0),o=$t(e,a,!1);Math.abs(n-t)<=i&&Math.abs(o-r)<=i&&m.push(a)}),m}(e,t,r,i);if(2===e.length)return function(e,t,r,i){void 0===i&&(i=1e-9);var a=(t-e[0].x)/(e[1].x-e[0].x),n=(r-e[0].y)/(e[1].y-e[0].y);if(Math.abs(a-n)<=i)return[.5*(a+n)];return[]}(e,t,r,i);throw new Error("Unsupported order")}function zt(e,t){if(void 0===t&&(t=0),2===e.length){var r=e[0],i=r.x,a=r.y,n=e[1];return function(e,t,r,i){return t===i?0:e===r?i>t?1/0:-1/0:(i-t)/(r-e)}(i,a,n.x,n.y)}if(3===e.length)return Wt(e,t);if(4===e.length)return Vt(e,t);throw new Error("Unsupported order")}function Wt(e,t){void 0===t&&(t=0);var r=qt(e,t,!0);return 0===r?1/0:qt(e,t,!1)/r}function Vt(e,t){var r=qt(e,t,!0);return 0===r?1/0:qt(e,t,!1)/r}function Ht(e,t,r,i,a,n,o,s){var c=arguments.length;if(4===c)return[0,1];if(6===c)return function(e,t,r,i,a,n){var o=(e-r)/(e-2*r+a);isNaN(o)||o<0?o=0:o>1&&(o=1);var s=(t-i)/(t-2*i+n);isNaN(s)||s<0?s=0:s>1&&(s=1);var c=[o];return s!==o&&c.push(s),c.sort(function(e,t){return e-t}),c[0]>0&&c.unshift(0),c[c.length-1]<1&&c.push(1),c}(e,t,r,i,a,n);if(8===c)return function(e,t,r,i,a,n,o,s){var c=-3*t+3*i,u=6*t-12*i+6*n,l=-3*t+9*i-9*n+3*s,h=Et([-3*e+3*r,6*e-12*r+6*a,-3*e+9*r-9*a+3*o]).filter(function(e){return e>=0&&e<=1}),d=Et([c,u,l]).filter(function(e){return e>=0&&e<=1}),f=h.concat(d);f.sort(function(e,t){return e-t});for(var m=f.length-1;m>0;m--)f[m]===f[m-1]&&f.splice(m,1);return f}(e,t,r,i,a,n,o,s);throw new Error("Unsupported order")}function Xt(e,t,r){if(void 0===t&&(t=!0),void 0===r&&(r=1e-9),e.length<3||e.length>4)throw new Error("Unsupported order");var i=t?e[0].x:e[0].y,a=t?e[1].x:e[1].y,n=t?e[2].x:e[2].y;if(4===e.length){var o=Et([3*a-3*i,2*(3*i-6*a+3*n),3*(3*a-i-3*n+(t?e[3].x:e[3].y))]).filter(function(e){return e>r&&e<1-r});return o.sort(function(e,t){return e-t})}if(3===e.length){o=Et([2*(a-i),2*(i-2*a+n)]).filter(function(e){return e>r&&e<1-r});return o}}function jt(e,t,r){if(void 0===t&&(t=!0),void 0===r&&(r=1e-9),e.length<3||e.length>4)throw new Error("Unsupported order");var i=t?e[0].x:e[0].y,a=t?e[1].x:e[1].y,n=t?e[2].x:e[2].y;if(4===e.length){var o=Et([2*(3*i-6*a+3*n),6*(3*a-i-3*n+(t?e[3].x:e[3].y))]).filter(function(e){return e>r&&e<1-r});return o.sort(function(e,t){return e-t})}if(3===e.length)return(o=2*(i-2*a+n))>r&&o<1-r?[o]:[]}function Gt(e,t,r,i,a,n,o,s){void 0===n&&(n=1e-9),void 0===o&&(o=3),void 0===s&&(s=30);var c=[],u=Yt(e,t,r,t,i,a,n,o,s);if(u&&c.push(u),1===r){var l=Yt(e,t,r,r,i,a,n,o,s);l&&c.push(l)}var h=Yt(e,t,r,.5*(t+r),i,a,n,o,s);if(h&&c.push(h),c.length)return c.sort(function(e,t){return e.d-t.d}),c[0]}function Yt(e,t,r,i,a,n,o,s,c){void 0===o&&(o=1e-9),void 0===s&&(s=5),void 0===c&&(c=30);for(var u=i,l=0;l++<c;){var h=$t(e,i,!0)-a,d=$t(e,i,!1)-n,f=qt(e,i,!0),m=qt(e,i,!1),p=Kt(e,i,!0),g=Kt(e,i,!1),v=h*f+d*m,y=Math.pow(f,2)+h*p+Math.pow(m,2)+d*g;if(y<0)return;if((i-=v/y)>r?i=r:i<t&&(i=t),l>s){var b=$t(e,i,!0),x=$t(e,i,!1),T=$t(e,u,!0),w=$t(e,u,!1),k=Math.sqrt(Math.pow(b-T,2)+Math.pow(x-w,2));if(Math.abs(k)<o)break}u=i}var S=$t(e,i,!0),E=$t(e,i,!1);return{x:S,y:E,t:i,d:Math.sqrt(Math.pow(a-S,2)+Math.pow(n-E,2))}}function qt(e,t,r){if(void 0===r&&(r=!0),e.length<3||e.length>4)throw new Error("Unsupported order");var i=r?e[0].x:e[0].y,a=r?e[1].x:e[1].y,n=r?e[2].x:e[2].y;return 3===e.length?2*(i-2*a+n)*t+2*(a-i):4===e.length?3*(3*a-i-3*n+(r?e[3].x:e[3].y))*t*t+2*(3*i-6*a+3*n)*t+3*a-3*i:void 0}function Kt(e,t,r){if(void 0===r&&(r=!0),e.length<2||e.length>4)throw new Error("Unsupported order");if(2===e.length)return 0;var i=r?e[0].x:e[0].y,a=r?e[1].x:e[1].y,n=r?e[2].x:e[2].y;return 3===e.length?2*(i-2*a+n):4===e.length?6*(3*a-i-3*n+(r?e[3].x:e[3].y))*t+2*(3*i-6*a+3*n):void 0}function $t(e,t,r){if(void 0===r&&(r=!0),e.length<2||e.length>4)throw new Error("Unsupported order");var i=r?e[0].x:e[0].y,a=r?e[1].x:e[1].y;if(2===e.length)return i+(a-i)*t;var n=r?e[2].x:e[2].y;if(3===e.length)return Math.pow(1-t,2)*i+2*t*(1-t)*a+Math.pow(t,2)*n;if(4===e.length){var o=r?e[3].x:e[3].y;return Math.pow(1-t,3)*i+3*Math.pow(1-t,2)*t*a+3*Math.pow(t,2)*(1-t)*n+Math.pow(t,3)*o}}function Qt(e,t,r){void 0===r&&(r=!0);var i=r?e[0].x:e[0].y,a=r?e[1].x:e[1].y,n=r?e[2].x:e[2].y;return 4===e.length?Et([i-t,3*(a-i),3*(n+i-2*a),(r?e[3].x:e[3].y)-i+3*a-3*n]).filter(function(e){return e>=0&&e<=1}):Et([i-t,2*(a-i),n+i-2*a]).filter(function(e){return e>=0&&e<=1})}var Zt={bboxBezier:Mt,bezierLength:Pt,bezierAt:Ot,sliceBezier:Bt,getPointByT:Ft,getT:Qt,getPointT:Ut,getPointWithDByApprox:function(e,t,r,i){if(void 0===i&&(i=1e-9),e.length<2||e.length>4)throw new Error("Unsupported order");if(2===e.length){var a=e[1].x-e[0].x,n=e[1].y-e[0].y,o=t-e[0].x,s=r-e[0].y,c=Math.sqrt(Math.pow(a,2)+Math.pow(n,2)),u=Math.sqrt(Math.pow(o,2)+Math.pow(s,2))*Ke(a,n,o,s,!0)/c,l=a*u,h=n*u;return{x:l+=e[0].x,y:h+=e[0].y,d:Math.sqrt(Math.pow(l-t,2)+Math.pow(h-r,2)),t:u}}var d=Xt(e,!0),f=Xt(e,!1),m=jt(e,!0),p=jt(e,!1),g=[];d&&g.push.apply(g,d),f&&f.forEach(function(e){g.includes(e)||g.push(e)}),m&&m.forEach(function(e){g.includes(e)||g.push(e)}),p&&p.forEach(function(e){g.includes(e)||g.push(e)}),g.sort(function(e,t){return e-t});var v=[];if(g.forEach(function(a,n){if(!n){var o=Gt(e,0,a,t,r,i);void 0!==o&&v.push(o)}var s=Gt(e,a,g[n+1]||1,t,r,i);void 0!==s&&v.push(s)}),!g.length){var y=Gt(e,0,1,t,r,i);void 0!==y&&v.push(y)}if(v.sort(function(e,t){return e.d-t.d}),v.length)return{x:v[0].x,y:v[0].y,t:v[0].t,d:v[0].d}},bezierSlope:zt,bezierExtremaT:Ht,bezierTangent:function(e,t){if(void 0===t&&(t=0),2===e.length)return r=e[0].x,i=e[0].y,a=e[1].x,[(n=e[1].y)-i,r-a,i*(a-r)-r*(n-i)];var r,i,a,n;if(3===e.length)return function(e,t){void 0===t&&(t=0);var r=Wt(e,t),i=Lt(e,t);return Ct(i.x,i.y,r)}(e,t);if(4===e.length)return function(e,t){void 0===t&&(t=0);var r=Vt(e,t),i=Nt(e,t);return Ct(i.x,i.y,r)}(e,t);throw new Error("Unsupported order")},splitBezierT:function(e,t,r,i){if(void 0===r&&(r=5),t<2)return[];if(e.length>4||e.length<2)throw new Error("Unsupported order");for(var a=e[0],n=e[e.length-1],o=[{x:a.x,y:a.y,t:0}],s=1/t,c=1;c<t;c++){var u=s*c,l=Ft(e,u);o.push({x:l.x,y:l.y,t:u})}if(o.push({x:n.x,y:n.y,t:1}),2===e.length)return o;var h=(i=i||Pt(e))/t;for(c=0;c<r;c++){for(var d=[0],f=1;f<t;f++)d[f]=Math.sqrt(Math.pow(o[f].x-o[f-1].x,2)+Math.pow(o[f].y-o[f-1].y,2));var m=0;for(f=1;f<t;f++){m+=d[f]-h;var p=o[f],g=Ot(p.t,e,1),v=Math.sqrt(Math.pow(g.x,2)+Math.pow(g.y,2)),y=Ot(p.t,e,2),b=m*v,x=m*Math.sqrt(Math.pow(y.x,2)+Math.pow(y.y,2))+v*v;p.t=p.t-b/x;l=Ft(e,p.t);p.x=l.x,p.y=l.y}}return o},getBezierMonotonicityT:Xt,getBezierMonotonicityT2:jt,bezierDerivative:qt,bezierDerivative2:Kt,bezierValue:$t},Jt=it.unitize3,er=it.crossProduct3,tr=it.dotProduct3,rr=it.isParallel3,ir=it.length3;function ar(e){var t=e[0],r=e[e.length-1];return[Math.min(t.x,r.x),Math.min(t.y,r.y),Math.max(t.x,r.x),Math.max(t.y,r.y)]}function nr(e,t,r,i,a,n){var o,s,c,u,l,h,d,f,m=[{a:e,b:t,t1:0,t2:1,t3:0,t4:1}],p=e.length,g=t.length;if(2===p&&2===g){var v=cr(e[0].x,e[0].y,e[1].x,e[1].y,t[0].x,t[0].y,t[1].x,t[1].y,!0,r);return v&&n.push({x:v.x,y:v.y,t1:v.toSource,t2:v.toClip}),n}for(var y=function(){var e=m.pop(),t=e.a,i=e.b,v=e.t1,y=e.t2,b=e.t3,x=e.t4,T=a?ar(t):Mt(t[0].x,t[0].y,t[1].x,t[1].y,null===(o=t[2])||void 0===o?void 0:o.x,null===(s=t[2])||void 0===s?void 0:s.y,null===(c=t[3])||void 0===c?void 0:c.x,null===(u=t[3])||void 0===u?void 0:u.y),w=a?ar(i):Mt(i[0].x,i[0].y,i[1].x,i[1].y,null===(l=i[2])||void 0===l?void 0:l.x,null===(h=i[2])||void 0===h?void 0:h.y,null===(d=i[3])||void 0===d?void 0:d.x,null===(f=i[3])||void 0===f?void 0:f.y);if(a){if(t[0].x===i[0].x&&t[0].y===i[0].y)return n.push({x:t[0].x,y:t[0].y,t1:v,t2:b}),"continue";if(t[0].x===i[g-1].x&&t[0].y===i[g-1].y)return n.push({x:t[0].x,y:t[0].y,t1:v,t2:x}),"continue";if(t[p-1].x===i[0].x&&t[p-1].y===i[0].y)return n.push({x:i[0].x,y:i[0].y,t1:y,t2:b}),"continue";if(t[p-1].x===i[g-1].x&&t[p-1].y===i[g-1].y)return n.push({x:t[p-1].x,y:t[p-1].y,t1:y,t2:x}),"continue";if((T[0]===w[2]||T[2]===w[0])&&T[1]<=w[3]&&T[3]>=w[1]){var k=T[2]===w[0];if(2===p){if(C=sr(t,i,T,k)){var S=v+C.tl*(y-v),E=b+C.tb*(x-b);n.push({x:C.x,y:C.y,t1:S,t2:E})}}else if(2===g){if(C=sr(i,t,w,!k)){S=b+C.tl*(x-b),E=v+C.tb*(y-v);n.push({x:C.x,y:C.y,t1:E,t2:S})}}else{var C=function(e,t,r,i){var a,n,o,s,c,u;void 0===i&&(i=!0);var l=e.length,h=t.length,d=i?r[2]:r[0];if(e[0].x===d||e[l-1].x===d)if(t[0].x===d||t[h-1].x===d){if(e[0].x===d&&t[0].x===d&&e[0].y===t[0].y)return{x:d,y:e[0].y,ta:0,tb:0};if(e[0].x===d&&t[h-1].x===d&&e[0].y===t[h-1].y)return{x:d,y:e[0].y,ta:0,tb:1};if(e[l-1].x===d&&t[h-1].x===d&&e[l-1].y===t[h-1].y)return{x:d,y:e[l-1].y,ta:1,tb:1};if(e[l-1].x===d&&t[0].x===d&&e[l-1].y===t[0].y)return{x:d,y:e[l-1].y,ta:1,tb:0}}else{var f=Ht(t[0].x,t[0].y,t[1].x,t[1].y,t[2].x,t[2].y,null===(a=t[3])||void 0===a?void 0:a.x,null===(n=t[3])||void 0===n?void 0:n.y).filter(function(e){return e>0&&e<1}),m=Ft(t,f[0]);if(e[0].x===d&&e[0].y===m.y)return{x:d,y:m.y,ta:0,tb:f[0]};if(e[l-1].x===d&&e[l-1].y===m.y)return{x:d,y:m.y,ta:1,tb:f[0]}}else{var p=Ht(e[0].x,e[0].y,e[1].x,e[1].y,e[2].x,e[2].y,null===(o=e[3])||void 0===o?void 0:o.x,null===(s=e[3])||void 0===s?void 0:s.y).filter(function(e){return e>0&&e<1}),g=Ft(e,p[0]);if(t[0].x===d||t[h-1].x===d){if(t[0].x===d&&t[0].y===g.y)return{x:d,y:g.y,ta:p[0],tb:0};if(t[h-1].x===d&&t[h-1].y===g.y)return{x:d,y:g.y,ta:p[0],tb:1}}else{var v=Ht(t[0].x,t[0].y,t[1].x,t[1].y,t[2].x,t[2].y,null===(c=t[3])||void 0===c?void 0:c.x,null===(u=t[3])||void 0===u?void 0:u.y).filter(function(e){return e>0&&e<1}),y=Ft(t,v[0]);if(g.y===y.y)return{x:d,y:g.y,ta:p[0],tb:v[0]}}}}(t,i,T,k);if(C){var A=v+C.ta*(y-v);E=b+C.tb*(x-b);n.push({x:C.x,y:C.y,t1:A,t2:E})}}return"continue"}if((T[1]===w[3]||T[3]===w[1])&&T[0]<=w[2]&&T[2]>=w[0]){var _=T[3]===w[1];if(2===p){if(C=or(t,i,T,_)){S=v+C.tl*(y-v),E=b+C.tb*(x-b);n.push({x:C.x,y:C.y,t1:S,t2:E})}}else if(2===g){if(C=or(i,t,w,!_)){S=b+C.tl*(x-b),E=v+C.tb*(y-v);n.push({x:C.x,y:C.y,t1:E,t2:S})}}else{C=function(e,t,r,i){var a,n,o,s,c,u;void 0===i&&(i=!0);var l=e.length,h=t.length,d=i?r[3]:r[1];if(e[0].y===d||e[l-1].y===d)if(t[0].y===d||t[h-1].y===d){if(e[0].y===d&&t[0].y===d&&e[0].x===t[0].x)return{x:e[0].x,y:d,ta:0,tb:0};if(e[0].y===d&&t[h-1].y===d&&e[0].x===t[h-1].x)return{x:e[0].x,y:d,ta:0,tb:1};if(e[l-1].y===d&&t[h-1].y===d&&e[l-1].x===t[h-1].x)return{x:e[l-1].x,y:d,ta:1,tb:1};if(e[l-1].y===d&&t[0].y===d&&e[l-1].x===t[0].x)return{x:e[l-1].x,y:d,ta:1,tb:0}}else{var f=Ht(t[0].x,t[0].y,t[1].x,t[1].y,t[2].x,t[2].y,null===(a=t[3])||void 0===a?void 0:a.x,null===(n=t[3])||void 0===n?void 0:n.y).filter(function(e){return e>0&&e<1}),m=Ft(t,f[0]);if(e[0].y===d&&e[0].x===m.x)return{x:m.x,y:d,ta:0,tb:f[0]};if(e[l-1].y===d&&e[l-1].x===m.x)return{x:m.x,y:d,ta:1,tb:f[0]}}else{var p=Ht(e[0].x,e[0].y,e[1].x,e[1].y,e[2].x,e[2].y,null===(o=e[3])||void 0===o?void 0:o.x,null===(s=e[3])||void 0===s?void 0:s.y).filter(function(e){return e>0&&e<1}),g=Ft(e,p[0]);if(t[0].y===d||t[h-1].y===d){if(t[0].y===d&&t[0].x===g.x)return{x:g.x,y:d,ta:p[0],tb:0};if(t[h-1].y===d&&t[h-1].x===g.x)return{x:g.x,y:d,ta:p[0],tb:1}}else{var v=Ht(t[0].x,t[0].y,t[1].x,t[1].y,t[2].x,t[2].y,null===(c=t[3])||void 0===c?void 0:c.x,null===(u=t[3])||void 0===u?void 0:u.y).filter(function(e){return e>0&&e<1}),y=Ft(t,v[0]);if(g.x===y.x)return{x:g.x,y:d,ta:p[0],tb:v[0]}}}}(t,i,T,_);if(C){A=v+C.ta*(y-v),E=b+C.tb*(x-b);n.push({x:C.x,y:C.y,t1:A,t2:E})}}return"continue"}if(2===p){if(t[0].x===t[1].x)return Qt(i,t[0].x,!0).forEach(function(e){if(!(e<0||e>1)){var r=Ft(i,e),a=(r.y-t[0].y)/(t[1].y-t[0].y);a>=0&&a<=1&&n.push({x:r.x,y:r.y,t1:a,t2:e})}}),"continue";if(t[0].y===t[1].y)return Qt(i,t[0].y,!1).forEach(function(e){if(!(e<0||e>1)){var r=Ft(i,e),a=(r.x-t[0].x)/(t[1].x-t[0].x);a>=0&&a<=1&&n.push({x:r.x,y:r.y,t1:a,t2:e})}}),"continue"}else if(2===g){if(i[0].x===i[1].x)return Qt(t,i[0].x,!0).forEach(function(e){if(!(e<0||e>1)){var r=Ft(t,e),a=(r.y-i[0].y)/(i[1].y-i[0].y);a>=0&&a<=1&&n.push({x:r.x,y:r.y,t1:e,t2:a})}}),"continue";if(i[0].y===i[1].y)return Qt(t,i[0].y,!1).forEach(function(e){if(!(e<0||e>1)){var r=Ft(t,e),a=(r.x-i[0].x)/(i[1].x-i[0].x);a>=0&&a<=1&&n.push({x:r.x,y:r.y,t1:e,t2:a})}}),"continue"}}if(function(e,t,r,i,a){if(e[0]>t[2]||e[1]>t[3]||t[0]>e[2]||t[1]>e[3])return!1;if((e[2]===t[0]||e[0]===t[2])&&(t[3]<e[1]||e[1]>t[3]))return!1;if((e[3]===t[1]||e[1]===t[3])&&(t[2]<e[0]||e[0]>t[2]))return!1;var n=r.length,o=i.length;if(a){if(n===o){for(var s=r[0].x-i[0].x,c=r[0].y-i[0].y,u=!0,l=!0,h=0;h<n&&(r[h].x-i[h].x!==s&&(u=!1),r[h].y-i[h].y!==c&&(l=!1),u||l);h++);if(u&&l)return!1;if(u){for(var d=r[0].y-i[0].y,f=jt(r.map(function(e,t){return{x:e.x-i[t].x,y:e.y-i[t].y}}),!1)||[],m=(h=0,f.length);h<m;h++){var p=Ft(r,f[h]),g=Ft(i,f[h]);if(d>0&&p.y-g.y<=0||d<0&&p.y-g.y>=0)return!0}return!1}if(l){for(d=r[0].x-i[0].x,f=jt(r.map(function(e,t){return{x:e.x-i[t].x,y:e.y-i[t].y}}),!0)||[],h=0,m=f.length;h<m;h++){p=Ft(r,f[h]),g=Ft(i,f[h]);if(d>0&&p.x-g.x<=0||d<0&&p.x-g.x>=0)return!0}return!1}}}else{if(e[1]===t[3]||e[3]===t[1]){var v=e[1]===t[3]?e[1]:e[3];return 2===n?e[1]===e[3]||(i[1].y===v||i[o-2].y===v):2===o?t[1]===t[3]||(r[1].y===v||r[n-2].y===v):r[1].y===v||r[n-2].y===v||i[1].y===v||i[o-2].y===v}if(e[0]===t[2]||e[2]===t[0]){var y=e[0]===t[2]?e[0]:e[2];return 2===n?e[0]===e[2]||(i[1].x===y||i[o-2].y===y):2===o?t[0]===t[2]||(r[1].x===y||r[n-2].x===y):r[1].x===y||r[n-2].x===y||i[1].x===y||i[o-2].x===y}}return!0}(T,w,t,i,a)){if(p===g){for(var M=!0,I=0;I<p;I++)if(Math.abs(t[I].x-i[I].x)>.1*r||Math.abs(t[I].y-i[I].y)>.1*r){M=!1;break}if(M)return n.push({x:.5*(t[0].x+i[0].x),y:.5*(t[0].y+i[0].y),t1:v,t2:b}),n.push({x:.5*(t[p-1].x+i[g-1].x),y:.5*(t[p-1].y+i[g-1].y),t1:y,t2:x}),"continue"}var R=T[2]-T[0]||Number.EPSILON,P=T[3]-T[1]||Number.EPSILON,O=w[2]-w[0]||Number.EPSILON,D=w[3]-w[1]||Number.EPSILON;if(R<=r&&P<=r&&O<=r&&D<=r){A=.5*(v+y),E=.5*(b+x);if(0===v)((B=t[0]).x===i[0].x&&B.y===i[0].y||B.x===i[g-1].x&&B.y===i[g-1].y)&&(A=0);else if(1===y){((B=t[p-1]).x===i[0].x&&B.y===i[0].y||B.x===i[g-1].x&&B.y===i[g-1].y)&&(A=1)}if(0===b)((B=i[0]).x===t[0].x&&B.y===t[0].y||B.x===t[p-1].x&&B.y===t[p-1].y)&&(E=0);else if(1===x){var B;((B=i[g-1]).x===t[0].x&&B.y===t[0].y||B.x===t[p-1].x&&B.y===t[p-1].y)&&(E=1)}var F=Ft(t,A),L=Ft(i,E);n.push({x:.5*(F.x+L.x),y:.5*(F.y+L.y),t1:A,t2:E})}else if((R>r||P>r)&&(O>r||D>r)){var N=Bt(t,0,.5),U=Bt(t,.5,1),z=Bt(i,0,.5),W=Bt(i,.5,1);m.push({a:N,b:z,t1:v,t2:v+.5*(y-v),t3:b,t4:b+.5*(x-b)}),m.push({a:N,b:W,t1:v,t2:v+.5*(y-v),t3:b+.5*(x-b),t4:x}),m.push({a:U,b:z,t1:v+.5*(y-v),t2:y,t3:b,t4:b+.5*(x-b)}),m.push({a:U,b:W,t1:v+.5*(y-v),t2:y,t3:b+.5*(x-b),t4:x})}else if(R>r||P>r){N=Bt(t,0,.5),U=Bt(t,.5,1);m.push({a:N,b:i,t1:v,t2:v+.5*(y-v),t3:b,t4:x}),m.push({a:U,b:i,t1:v+.5*(y-v),t2:y,t3:b,t4:x})}else if(O>r||D>r){z=Bt(i,0,.5),W=Bt(i,.5,1);m.push({a:t,b:z,t1:v,t2:y,t3:b,t4:b+.5*(x-b)}),m.push({a:t,b:W,t1:v,t2:y,t3:b+.5*(x-b),t4:x})}}};m.length;)y();n.sort(function(e,t){return e.t1===t.t1?e.t2-t.t2:e.t1-t.t1});for(var b=n.length-1;b>0;b--){var x=n[b],T=n[b-1];if(Math.abs(x.x-T.x)<=i&&Math.abs(x.y-T.y)<=i)if(1===b)0===x.t1||1===x.t1||0===x.t2||1===x.t2?n.shift():n.splice(1,1);else for(var w=b-1;w>0;w--){var k=n[w],S=n[w-1],E=Math.abs(k.x-S.x)>i&&Math.abs(k.y-S.y)>i;if(E||1===w){var C=E?w:w-1,A=n[C];if(Math.abs(x.x-A.x)<=i&&Math.abs(x.y-A.y)<=i)if(0===x.t1||1===x.t1||0===x.t2||1===x.t2)n.splice(C,b-C);else if(0===A.t1||1===A.t1||0===A.t2||1===A.t2)n.splice(C+1,b-C);else{var _=n[C+b>>1];n.splice(C,b-C+1,_)}else n.splice(C+1,b-C-1);b=C;break}}}return n}function or(e,t,r,i){var a,n,o,s;void 0===i&&(i=!0);var c=t.length,u=i?r[3]:r[1];if(r[1]===r[3])if(t[0].y===u||t[c-1].y===u){if((l=((d=t[0].y===u?t[0].x:t[c-1].x)-r[0])/(r[2]-r[0]))>=0&&l<=1)return{x:d,y:u,tl:l,tb:t[0].y===u?0:1}}else{var l,h=Ht(t[0].x,t[0].y,t[1].x,t[1].y,t[2].x,t[2].y,null===(a=t[3])||void 0===a?void 0:a.x,null===(n=t[3])||void 0===n?void 0:n.y).filter(function(e){return e>0&&e<1});if((l=((f=Ft(t,h[0])).x-r[0])/(r[2]-r[0]))>=0&&l<=1)return{x:f.x,y:u,tl:l,tb:h[0]}}else if(t[0].y===u||t[c-1].y===u){var d=t[0].y===u?t[0].x:t[c-1].x;if(e[0].x===d&&e[0].y===u||e[1].x===d&&e[1].y===u)return{x:d,y:u,tl:e[0].y===u?0:1,tb:t[0].y===u?0:1}}else{var f;h=Ht(t[0].x,t[0].y,t[1].x,t[1].y,t[2].x,t[2].y,null===(o=t[3])||void 0===o?void 0:o.x,null===(s=t[3])||void 0===s?void 0:s.y).filter(function(e){return e>0&&e<1});if((f=Ft(t,h[0])).x===e[0].x&&e[0].y===u||f.x===e[1].x&&e[1].y===u)return{x:f.x,y:u,tl:f.x===e[0].x?0:1,tb:h[0]}}}function sr(e,t,r,i){var a,n,o,s;void 0===i&&(i=!0);var c=t.length,u=i?r[2]:r[0];if(r[0]===r[2])if(t[0].x===u||t[c-1].x===u){if((l=((d=t[0].x===u?t[0].y:t[c-1].y)-r[1])/(r[3]-r[1]))>=0&&l<=1)return{x:u,y:d,tl:l,tb:t[0].x===u?0:1}}else{var l,h=Ht(t[0].x,t[0].y,t[1].x,t[1].y,t[2].x,t[2].y,null===(a=t[3])||void 0===a?void 0:a.x,null===(n=t[3])||void 0===n?void 0:n.y).filter(function(e){return e>0&&e<1});if((l=((f=Ft(t,h[0])).y-r[1])/(r[3]-r[1]))>=0&&l<=1)return{x:u,y:f.y,tl:(f.y-r[1])/(r[3]-r[1]),tb:h[0]}}else if(t[0].x===u||t[c-1].x===u){var d=t[0].x===u?t[0].x:t[c-1].x;if(e[0].x===u&&e[0].y===d||e[1].x===u&&e[1].y===d)return{x:u,y:d,tl:e[0].x===u?0:1,tb:t[0].x===u?0:1}}else{var f;h=Ht(t[0].x,t[0].y,t[1].x,t[1].y,t[2].x,t[2].y,null===(o=t[3])||void 0===o?void 0:o.x,null===(s=t[3])||void 0===s?void 0:s.y).filter(function(e){return e>0&&e<1});if((f=Ft(t,h[0])).y===e[0].y&&e[0].x===u||f.y===e[1].y&&e[1].x===u)return{x:u,y:f.y,tl:f.y===e[0].y?0:1,tb:h[0]}}}function cr(e,t,r,i,a,n,o,s,c,u){void 0===c&&(c=!0),void 0===u&&(u=0);var l=(s-n)*(r-e)-(o-a)*(i-t);if(0!==l){var h=((o-a)*(t-n)-(s-n)*(e-a))/l,d=((r-e)*(t-n)-(i-t)*(e-a))/l,f=1-u;if(c&&(h<u||h>f||d<u||d>f))return;return{x:e+h*(r-e),y:t+h*(i-t),toSource:h,toClip:d}}}function ur(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}function lr(e,t){return{x:e.x+t.x,y:e.y+t.y,z:e.z+t.z}}function hr(e,t,r){var i=ur(e,t),a=ur(r,t),n=tr(a.x,a.y,a.z,a.x,a.y,a.z);return tr(a.x,a.y,a.z,i.x,i.y,i.z)/n}var dr={intersectLineLine:cr,intersectBezier2Line:function(e,t,r,i,a,n,o,s,c,u,l,h,d){void 0===l&&(l=.1),void 0===h&&(h=.5),void 0===d&&(d=!1);var f=[];return nr([{x:e,y:t},{x:r,y:i},{x:a,y:n}],[{x:o,y:s},{x:c,y:u}],l,h,d,f),f},intersectBezier3Line:function(e,t,r,i,a,n,o,s,c,u,l,h,d,f,m){void 0===d&&(d=.1),void 0===f&&(f=.5),void 0===m&&(m=!1);var p=[];return nr([{x:e,y:t},{x:r,y:i},{x:a,y:n},{x:o,y:s}],[{x:c,y:u},{x:l,y:h}],d,f,m,p),p},intersectBezier2Bezier2:function(e,t,r,i,a,n,o,s,c,u,l,h,d,f,m){void 0===d&&(d=.1),void 0===f&&(f=.5),void 0===m&&(m=!1);var p=[];return nr([{x:e,y:t},{x:r,y:i},{x:a,y:n}],[{x:o,y:s},{x:c,y:u},{x:l,y:h}],d,f,m,p),p},intersectBezier3Bezier3:function(e,t,r,i,a,n,o,s,c,u,l,h,d,f,m,p,g,v,y){void 0===g&&(g=.1),void 0===v&&(v=.5),void 0===y&&(y=!1);var b=[];return nr([{x:e,y:t},{x:r,y:i},{x:a,y:n},{x:o,y:s}],[{x:c,y:u},{x:l,y:h},{x:d,y:f},{x:m,y:p}],g,v,y,b),b},intersectBezier2Bezier3:function(e,t,r,i,a,n,o,s,c,u,l,h,d,f,m,p,g){void 0===m&&(m=.1),void 0===p&&(p=.5),void 0===g&&(g=!1);var v=[];return nr([{x:e,y:t},{x:r,y:i},{x:a,y:n}],[{x:o,y:s},{x:c,y:u},{x:l,y:h},{x:d,y:f}],m,p,g,v),v},intersectLineLine3:function(e,t,r,i,a,n){void 0===a&&(a=0),void 0===n&&(n=1e-9);var o=ur(e,r),s=ur(i,r),c=ur(t,e),u=o.x*s.x+o.y*s.y+o.z*s.z,l=s.x*c.x+s.y*c.y+s.z*c.z,h=o.x*c.x+o.y*c.y+o.z*c.z,d=s.x*s.x+s.y*s.y+s.z*s.z,f=(c.x*c.x+c.y*c.y+c.z*c.z)*d-l*l;if(!(Math.abs(f)<n)){var m,p,g=(u*l-h*d)/f,v=(u+l*g)/d,y={x:e.x+g*c.x,y:e.y+g*c.y,z:e.z+g*c.z},b={x:r.x+v*s.x,y:r.y+v*s.y,z:r.z+v*s.z};if(!((m=y,p=b,Math.sqrt(Math.pow(m.x-p.x,2)+Math.pow(m.y-p.y,2)+Math.pow(m.z-p.z,2)))>n)){var x=function(e,t){var r=1/t;return{x:e.x*r,y:e.y*r,z:e.z*r}}(lr(y,b),2);if(!a)return x;var T=hr(x,e,t),w=hr(x,r,i);return T<0&&Math.abs(T)<1e-9?T=0:T>1&&T-1<1e-9&&(T=1),w<0&&Math.abs(w)<1e-9?w=0:w>1&&w-1<1e-9&&(w=1),x.pa=T,x.pb=w,1===a&&T>=0&&T<=1||2===a&&w>=0&&w<=1||3===a&&T>=0&&T<=1&&w>=0&&w<=1?x:void 0}}},intersectPlanePlane:function(e,t,r,i,a,n){var o=Jt(t.x-e.x,t.y-e.y,t.z-e.z),s=Jt(r.x-e.x,r.y-e.y,r.z-e.z),c=Jt(a.x-i.x,a.y-i.y,a.z-i.z),u=Jt(n.x-i.x,n.y-i.y,n.z-i.z),l=er(o.x,o.y,o.z,s.x,s.y,s.z),h=Jt(l.x,l.y,l.z),d=er(c.x,c.y,c.z,u.x,u.y,u.z),f=Jt(d.x,d.y,d.z);if(rr(h.x,h.y,h.z,f.x,f.y,f.z))return null;var m=er(f.x,f.y,f.z,h.x,h.y,h.z),p=lr(o,c),g=Jt(m.x,m.y,m.z),v=h.x,y=h.y,b=h.z,x=-v*e.x-y*e.y-b*e.z,T=f.x,w=f.y,k=f.z,S=-T*i.x-w*i.y-k*i.z,E=g.x,C=g.y,A=g.z,_=[-x,-S,-(-E*p.x-C*p.y-A*p.z)],M=v*(w*A-k*C)-y*(T*A-k*E)+b*(T*C-w*E);if(Math.abs(M)<1e-9)return null;var I=1/M,R={x:I*(w*A-k*C)*_[0]+I*(b*C-y*A)*_[1]+I*(y*k-b*w)*_[2],y:I*(k*E-T*A)*_[0]+I*(v*A-b*E)*_[1]+I*(b*T-v*k)*_[2],z:I*(T*C-w*E)*_[0]+I*(y*E-v*C)*_[1]+I*(v*w-y*T)*_[2]};return[R,lr(R,g)]},pointOnLine3:function(e,t,r,i){void 0===i&&(i=1e-9);var a=t.x-e.x,n=t.y-e.y,o=t.z-e.z,s=r.x-e.x,c=r.y-e.y,u=r.z-e.z,l=er(a,n,o,s,c,u);return ir(l.x,l.y,l.z)<i}};function fr(e){return e*Math.PI/180}function mr(e){return 180*e/Math.PI}function pr(e,t,r,i){void 0===i&&(i=!1);for(var a,n=r[0],o=n.x,s=n.y,c=r[0],u=c.x,l=c.y,h=r.length,d=1;d<h;d++){var f=r[d],m=f.x,p=f.y;o=Math.max(o,m),s=Math.max(s,p),u=Math.min(u,m),l=Math.min(l,p)}if(e<u||t<l||e>o||t>s)return!1;if((e<=u||t<=l||e>=o||t>=s)&&!i)return!1;d=0;for(var g=r.length;d<g;d++){var v=r[d],y=v.x,b=v.y,x=r[(d+1)%g],T=x.x,w=x.y,k=qe(T-y,w-b,e-y,t-b);if(0!==k){if(k=k>0?1:0,void 0===a)a=k;else if(a^k)return!1}else if(i){if(e===y&&t===b||e===T&&t===w)return!0;var S=e-y,E=T-e,C=t-b,A=w-t;if(0===S||0===E){if(C^A)return!0}else if(0===C||0===A){if(S^E)return!0}else if(S^E&&C^A)return!0}}return!0}function gr(e,t,r,i,a,n,o,s){var c,u;if(void 0===s&&(s=!1),r>=a&&(r=(c=[a,r])[0],a=c[1]),i>=n&&(i=(u=[n,i])[0],n=u[1]),o&&!nt(o)){var l=bt({x:r,y:i},o),h=bt({x:a,y:i},o),d=bt({x:a,y:n},o),f=bt({x:r,y:n},o);return pr(e,t,[{x:l.x,y:l.y},{x:h.x,y:h.y},{x:d.x,y:d.y},{x:f.x,y:f.y}])}return s?e>=r&&t>=i&&e<=a&&t<=n:e>r&&t>i&&e<a&&t<n}function vr(e,t,r,i){return Math.sqrt(Math.pow(r-e,2)+Math.pow(i-t,2))}function yr(e,t,r){var i=(Math.pow(t,2)+Math.pow(r,2)-Math.pow(e,2))/(2*t*r);return Math.acos(i)||0}var br=4*(Math.sqrt(2)-1)/3;function xr(e,t,r,i,a,n,o,s,c){if(void 0===c&&(c=!1),c){if(e>o||t>s||a>r||n>i)return!1;if((r===a||e===o)&&(i<n||t>s))return!1;if((i===t||t===i)&&(r<a||e>o))return!1}else if(e>=o||t>=s||a>=r||n>=i)return!1;return!0}function Tr(e,t,r,i,a,n){var o,s;void 0===n&&(n=!1),e>r&&(e=(o=[r,e])[0],r=o[1]),t>i&&(t=(s=[i,t])[0],i=s[1]);for(var c=0,u=0,l=0,h=0,d=0,f=a.length;d<f;d++){var m=a[d],p=m.x,g=m.y;if(d?(c=Math.min(c,p),u=Math.min(u,g),l=Math.max(l,p),h=Math.max(h,g)):(c=p,u=g,l=p,h=g),n){if(p>=e&&p<=r&&g>=t&&g<=i)return!0}else if(p>e&&p<r&&g>t&&g<i)return!0;var v=a[(d+1)%f],y=v.x,b=v.y,x=cr(e,t,r,t,p,g,y,b);if(x){if(x.toSource>0&&x.toSource<1&&x.toClip>0&&x.toClip<1)return!0;if(n&&x.toSource>=0&&x.toSource<=1&&x.toClip>=0&&x.toClip<=1)return!0}if(x=cr(e,t,e,i,p,g,y,b)){if(x.toSource>0&&x.toSource<1&&x.toClip>0&&x.toClip<1)return!0;if(n&&x.toSource>=0&&x.toSource<=1&&x.toClip>=0&&x.toClip<=1)return!0}if(x=cr(r,t,r,i,p,g,y,b)){if(x.toSource>0&&x.toSource<1&&x.toClip>0&&x.toClip<1)return!0;if(n&&x.toSource>=0&&x.toSource<=1&&x.toClip>=0&&x.toClip<=1)return!0}if(x=cr(e,i,r,i,p,g,y,b)){if(x.toSource>0&&x.toSource<1&&x.toClip>0&&x.toClip<1)return!0;if(n&&x.toSource>=0&&x.toSource<=1&&x.toClip>=0&&x.toClip<=1)return!0}}return c<=e&&u<=t&&l>=r&&h>=i}var wr={d2r:fr,r2d:mr,H:br,h:function(e){return e*=.5,(1-Math.cos(e))/Math.sin(e)*4/3},pointInConvexPolygon:pr,pointInRect:gr,pointsDistance:vr,angleBySides:yr,isRectsOverlap:xr,isRectsInside:function(e,t,r,i,a,n,o,s,c){if(void 0===c&&(c=!1),c){if(e<=a&&t<=n&&r>=o&&i>=s)return!0}else if(e<a&&t<n&&r>o&&i>s)return!0;return!1},isConvexPolygonsOverlap:function(e,t,r){void 0===r&&(r=!1);for(var i=0,a=0,n=0,o=0,s=0,c=e.length;s<c;s++){var u=e[s],l=u.x,h=u.y;s?(i=Math.min(i,l),a=Math.min(a,h),n=Math.max(n,l),o=Math.max(o,h)):(i=l,a=h,n=l,o=h)}var d=0,f=0,m=0,p=0;for(s=0,c=t.length;s<c;s++){var g=t[s];l=g.x,h=g.y;s?(d=Math.min(d,l),f=Math.min(f,h),m=Math.max(m,l),p=Math.max(p,h)):(d=l,f=h,m=l,p=h)}if(r){if(i>m||a>p||n<d||o<f)return!1}else if(i>=m||a>=p||n<=d||o<=f)return!1;for(s=0,c=e.length;s<c;s++)if(pr(e[s].x,e[s].y,t,r))return!0;for(s=0,c=t.length;s<c;s++)if(pr(t[s].x,t[s].y,e,r))return!0;for(s=0,c=e.length;s<c;s++)for(var v=[e[s].x,e[s].y,e[(s+1)%c].x,e[(s+1)%c].y],y=0,b=t.length;y<b;y++){var x=[t[y].x,t[y].y,t[(y+1)%b].x,t[(y+1)%b].y],T=cr(v[0],v[1],v[2],v[3],x[0],x[1],x[2],x[3]);if(T){if(r)return!0;if(T.toSource||T.toClip)return!0}}return!1},isConvexPolygonOverlapRect:Tr,isConvexPolygonInAnother:function(e,t,r){void 0===r&&(r=!1);for(var i=0,a=e.length;i<a;i++)if(!pr(e[i].x,e[i].y,t,r))return!1;return!0}};function kr(e,t){return Sr(e,fr(t))}function Sr(e,t){var r=Math.sin(t),i=Math.cos(t);return e[5]=e[10]=i,e[6]=r,e[9]=-r,e}function Er(e,t){return function(e,t){var r=Math.sin(t),i=Math.cos(t);return e[0]=e[10]=i,e[8]=r,e[2]=-r,e}(e,fr(t))}function Cr(e,t){return Ar(e,fr(t))}function Ar(e,t){var r=Math.sin(t),i=Math.cos(t);return e[0]=e[5]=i,e[1]=r,e[4]=-r,e}function _r(e,t,r){var i=e.slice(0);return 0===t&&0===r||nt(e)?i:i=lt(i=ht(t,r,i),-t,-r)}function Mr(e,t,r){var i=at();return e>=1&&(i[11]=-1/e,(t||r)&&(i=lt(i=ht(t,r,i),-t,-r))),i}function Ir(e,t){t||(t=at());var r=e.translateX,i=e.translateY,a=e.translateZ,n=e.rotateX,o=e.rotateY,s=e.rotateZ,c=e.scaleX,u=e.scaleY,l=e.skewX,h=e.skewY;return t[12]=r||0,t[13]=i||0,t[14]=a||0,n&&(nt(t)?kr(t,n):mt(t,fr(n))),o&&(nt(t)?Er(t,o):pt(t,fr(o))),s&&(nt(t)?Cr(t,s):gt(t,fr(s))),l&&(nt(t)?t[4]=Math.tan(fr(l)):dt(t,fr(l))),h&&(nt(t)?t[1]=Math.tan(fr(h)):ft(t,fr(h))),void 0!==c&&1!==c&&(nt(t)?t[0]=c:vt(t,c)),void 0!==u&&1!==u&&(nt(t)?t[5]=u:yt(t,u)),t}var Rr={calRotateX:kr,calRotateXRadian:Sr,calRotateZ:Cr,calRotateZRadian:Ar,calMatrixByOrigin:_r,calTransform:Ir,calTransformByMatrixAndOrigin:function(e,t,r){var i=e.slice(0);return i=ht(-t,-r,i=lt(i,t,r))},calPerspectiveMatrix:Mr};function Pr(e){if(e<=0)return 0;var t=Math.floor(3*e*Math.sqrt(2*Math.PI)/4+.5);return t<2&&(t=2),t%2==0&&t++,t}function Or(e){return Dr(Pr(e))}function Dr(e){return 3*Math.floor(.5*e)}function Br(e,t){void 0===t&&(t=3);var r=Math.sqrt(12*e*e/t+1),i=Math.floor(r);i%2==0&&i--;for(var a=i+2,n=(12*e*e-t*i*i-4*t*i-3*t)/(-4*i-4),o=Math.round(n),s=[],c=0;c<t;c++)s.push(c<o?i:a);return s}function Fr(e){var t,r=Math.abs(e);if(r>=1.5)return 0;if(r<.5)t=.75-e*e;else{var i=1.5-r;t=.5*i*i}return t*(4/3)}var Lr={gaussKernel:Pr,gaussSize:Or,gaussSizeByD:Dr,gaussianWeight:function(e,t){if(e<=0||t<=0)return[1];for(var r=[],i=Math.floor(.5*t),a=0,n=i;n>=0;n--){var o=Math.pow(Math.E,-Math.pow(n,2)/(2*Math.pow(e,2)))/(e*Math.sqrt(2*Math.PI));r.push(o),a+=o}for(n=1;n<=i;n++){o=r[i-n];r.push(o),a+=o}if(1!==a)for(n=0;n<t;n++)r[n]/=a;return r},boxesForGauss:Br,dualKawase:function(e){var t=Math.max(1,Math.round(4/3*Math.log(e)));return{passes:t,distance:Math.pow(.4538,t)*e}},n2Kernel:Fr,n2Size:function(e){return e<1?0:(e%2==0&&e++,2*(e>>1)+1)},n2Weight:function(e){if(e<1)return[];e%2==0&&e++;for(var t=e>>1,r=t/1.5,i=[],a=0,n=-t;n<=t;n++){var o=Fr(Math.abs(n)/r);i.push(o),a+=o}return i.map(function(e){return e/a})}};function Nr(e,t){void 0===t&&(t=2);var r=Math.pow(10,t);return Math.round(e*r)/r}var Ur={geom:wr,matrix:wt,vector:it,isec:dr,bezier:Zt,toPrecision:Nr,blur:Lr};function zr(e,t,r){void 0===r&&(r=!1);for(var i=[],a=e[0].color,n=0,o=e.length;n<o;n++)i.push(e[n]);(1===i.length&&i.push(C(i[0])),void 0===i[0].offset&&(i[0].offset=0),i.length>1)&&(void 0===i[n=i.length-1].offset&&(i[n].offset=1));var s=i[0].offset;for(n=1,o=i.length;n<o-1;n++){if(void 0!==(b=i[n]).offset)s=b.offset;else{for(var c=n+1,u=i[i.length-1].offset;c<o-1;c++){var l=i[c];if(void 0!==l.offset){u=l.offset;break}}for(var h=(u-s)/(c-n+1),d=n;d<c;d++){i[d].offset=s+h*(d+1-n)}n=c}}i.sort(function(e,t){return e.offset-t.offset});for(n=0,o=i.length;n<o;n++){if((b=i[n]).offset>1){i.splice(n);var f=i[n-1];if(f&&f.offset<1){var m=b.color[0]-f.color[0],p=b.color[1]-f.color[1],g=b.color[2]-f.color[2],v=b.color[3]-f.color[3],y=(1-f.offset)/(b.offset-f.offset);i.push({color:[b.color[0]+m*y,b.color[1]+p*y,b.color[2]+g*y,b.color[3]+v*y],offset:1})}break}}for(n=i.length-1;n>=0;n--){var b;if((b=i[n]).offset<0){i.splice(0,n+1);var x=i[n];if(x&&x.offset>0){m=x.color[0]-b.color[0],p=x.color[1]-b.color[1],g=x.color[2]-b.color[2],v=x.color[3]-b.color[3],y=-b.offset/(x.offset-b.offset);i.unshift({color:[b.color[0]+m*y,b.color[1]+p*y,b.color[2]+g*y,b.color[3]+v*y],offset:0})}break}}if(i.forEach(function(e){e.offset<0?e.offset=0:e.offset>1&&(e.offset=1)}),i.length||i.push({color:a,offset:0},{color:a,offset:1}),r){var T=i[0],w=i[i.length-1];if(T.offset>0||w.offset<1){m=w.color[0]-T.color[0],p=w.color[1]-T.color[1],g=w.color[2]-T.color[2],v=w.color[3]-T.color[3];var k=T.offset+(1-w.offset);if(T.offset>0){y=T.offset/k;i.unshift({color:[T.color[0]+m*y,T.color[1]+p*y,T.color[2]+g*y,T.color[3]+v*y],offset:0})}if(w.offset<1){y=(1-w.offset)/k;i.push({color:[w.color[0]-m*y,w.color[1]-p*y,w.color[2]-g*y,w.color[3]-v*y],offset:1})}}}return i}function Wr(e){if(he.gradient.test(e)){var t=he.gradient.exec(e);if(t&&["linear","radial","conic"].indexOf(t[1].toLowerCase())>-1)return!0}return!1}function Vr(e){var t=he.gradient.exec(e);if(t){var r={linear:Y.LINEAR,radial:Y.RADIAL,conic:Y.CONIC}[t[1].toLowerCase()],i=void 0;if(r===Y.LINEAR)if(n=/([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)/.exec(t[2]))i=[parseFloat(n[1]),parseFloat(n[2]),parseFloat(n[3]),parseFloat(n[4])];else{var a=/([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)/.exec(t[2]);i=a?[fr(parseFloat(a[1]))]:[]}else if(r===Y.RADIAL){var n;i=(n=/([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?)(\s+([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?))?/.exec(t[2]))?[parseFloat(n[1]),parseFloat(n[2]),parseFloat(n[3]),parseFloat(n[4]),parseFloat(n[5])||0]:[.5,.5,1,1]}else r===Y.CONIC&&(i=[]);var o=t[2].match(/(([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?[pxremvwhina%]*)?\s*((#[0-9a-f]{3,8})|(rgba?\s*\(.+?\)))\s*([-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?[pxremvwhina%]*)?)|(transparent)/gi)||[],s=o.map(function(e,t){var r,i=/(?:#[0-9a-f]{3,8})|(?:rgba?\s*\(.+?\))|(?:transparent)/i.exec(e),a=/[-+]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[-+]?\d+)?(?:(?:px)|%)?/.exec(e.replace(i[0],""));if(a){var n=se(a[0]);n.u!==V.PERCENT&&(n.v*=100,n.u=V.PERCENT),r=n}else t?t===o.length-1&&(r={v:100,u:V.PERCENT}):r={v:0,u:V.PERCENT};return{color:{v:i?de(i[0]):[0,0,0,1],u:V.RGBA},offset:r}});s.sort(function(e,t){return e.offset&&t.offset?e.offset.v-t.offset.v:0});for(var c=s.length-2;c>0;c--){if(!s[c].offset){for(var u=s[c+1].offset.v,l=s[0].offset.v,h=c,d=c-1;d>=0;d--){if(0===d){c=d;break}if(s[d].offset){c=d,l=s[d].offset.v;break}}for(var f=(u-l)/(h-c+1),m=c+1;m<=h;m++)s[c].offset={v:l+(m-c)*f,u:V.PERCENT}}}return{t:r,d:i,stops:s}}}function Hr(e,t,r,i,a,n){var o,s,c,u,l;if(t.length<=1){var h=function(e,t,r,i,a){var n,o,s,c;if(e%(2*Math.PI)==0)n=s=.5*i,o=0,c=a;else if(e%Math.PI===0)n=s=.5*i,o=a,c=0;else if(e%(.5*Math.PI)==0)n=0,s=i,o=c=.5*a;else if(e%(1.5*Math.PI)==0)n=i,s=0,o=c=.5*a;else{var u=.5*i,l=.5*a,h=Math.min(u,l),d=Math.sin(e%360),f=Math.cos(e%360);n=u-h*d,o=l-h*f,s=u+h*d,c=l+h*f}return{x1:n+=t,y1:o+=r,x2:s+=t,y2:c+=r}}(null!==(o=t[0])&&void 0!==o?o:Math.PI,r,i,a,n);s=h.x1,c=h.y1,u=h.x2,l=h.y2}else s=r+t[0]*a,c=i+t[1]*n,u=r+t[2]*a,l=i+t[3]*n;var d=Math.sqrt(Math.pow(u-s,2)+Math.pow(l-c,2));return{x1:s,y1:c,x2:u,y2:l,total:d,stop:zr(e,0,!1)}}function Xr(e,t,r,i,a,n){var o,s=r+t[0]*a,c=i+t[1]*n,u=r+t[2]*a,l=i+t[3]*n,h=t[4],d=Math.sqrt(Math.pow(u-s,2)+Math.pow(l-c,2)),f=zr(e,0,!1);if(h&&1!==h){if(o=at(),l!==c)if(u===s)gt(o,fr(l>=c?90:270));else gt(o,Math.atan((l-c)/(u-s)));yt(o,h),o=_r(o,s,c)}return{cx:s,cy:c,tx:u,ty:l,ellipseLength:h,matrix:o,total:d,stop:f}}function jr(e,t,r,i,a,n){var o=Math.floor(r+.5*a),s=Math.floor(i+.5*n),c=Math.floor(r+.5*a)-o,u=Math.floor(i+.5*n)-s,l=0;l=0===c?u>=0?0:Math.PI:Math.atan(u/c);Math.sqrt(Math.pow(c,2)+Math.pow(u,2));return{angle:l,cx:o,cy:s,stop:zr(e,0,!0)}}function Gr(e){var t={};if(["left","top","right","bottom","width","height","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"].forEach(function(r){var i=e[r];if(void 0!==i){var a=se(i||0,!0);"width"!==r&&"height"!==r||a.v<0&&(a.v=0),t[r]=a}}),void 0!==e.lineHeight){var r,i=e.lineHeight;if(S(i)||"normal"===i)t.lineHeight={v:0,u:V.AUTO};else(r=se(i||0,!0)).v<=0&&(r={v:0,u:V.AUTO}),t.lineHeight=r}(void 0!==e.fontFamily&&(t.fontFamily={v:e.fontFamily.trim().replace(/['"]/g,"").replace(/\s*,\s*/g,","),u:V.STRING}),void 0!==e.fontSize)&&((r=se(e.fontSize||L.defaultFontSize,!0)).v<=0&&(r.v=L.defaultFontSize),t.fontSize=r);if(void 0!==e.fontWeight){var a=e.fontWeight;g(a)?/thin/i.test(a)?t.fontWeight={v:100,u:V.NUMBER}:/lighter/i.test(a)?t.fontWeight={v:200,u:V.NUMBER}:/light/i.test(a)?t.fontWeight={v:300,u:V.NUMBER}:/medium/i.test(a)?t.fontWeight={v:500,u:V.NUMBER}:/semiBold/i.test(a)?t.fontWeight={v:600,u:V.NUMBER}:/bold/i.test(a)?t.fontWeight={v:700,u:V.NUMBER}:/extraBold/i.test(a)?t.fontWeight={v:800,u:V.NUMBER}:/black/i.test(a)?t.fontWeight={v:900,u:V.NUMBER}:t.fontWeight={v:400,u:V.NUMBER}:t.fontWeight={v:Math.min(900,Math.max(100,parseInt(a)||400)),u:V.NUMBER}}if(void 0!==e.fontStyle){var n=e.fontStyle,o=G.NORMAL;n&&/italic/i.test(n)?o=G.ITALIC:n&&/oblique/i.test(n)&&(o=G.OBLIQUE),t.fontStyle={v:o,u:V.NUMBER}}if(void 0!==e.letterSpacing&&(t.letterSpacing=se(e.letterSpacing||0,!0)),void 0!==e.paragraphSpacing&&(t.paragraphSpacing=se(e.paragraphSpacing||0,!0)),void 0!==e.textAlign){var s=e.textAlign,o=H.LEFT;"center"===s?o=H.CENTER:"right"===s?o=H.RIGHT:"justify"===s&&(o=H.JUSTIFY),t.textAlign={v:o,u:V.NUMBER}}if(void 0!==e.textVerticalAlign){var c=e.textVerticalAlign;o=X.TOP;"middle"===c?o=X.MIDDLE:"bottom"===c&&(o=X.BOTTOM),t.textVerticalAlign={v:o,u:V.NUMBER}}if(void 0!==e.textDecoration){var u=e.textDecoration;Array.isArray(u)?t.textDecoration=u.map(function(e){var t=re.NONE;return"underline"===e?t=re.UNDERLINE:"line-through"!==e&&"lineThrough"!==e||(t=re.LINE_THROUGH),{v:t,u:V.NUMBER}}):t.textDecoration=[]}void 0!==e.textShadow&&(he.shadow.test(e.textShadow)?(o=he.shadow.exec(e.textShadow))&&(t.textShadow={v:{x:parseFloat(o[1]),y:parseFloat(o[2]),blur:parseFloat(o[3]),color:de(o[4])},u:V.SHADOW}):t.textShadow={u:V.SHADOW});if(void 0!==e.color&&(t.color={v:de(e.color),u:V.RGBA}),void 0!==e.visibility&&(t.visibility={v:/hidden/i.test(e.visibility)?te.HIDDEN:te.VISIBLE,u:V.NUMBER}),void 0!==e.opacity&&(t.opacity={v:Math.max(0,Math.min(1,e.opacity)),u:V.NUMBER}),void 0!==e.backgroundColor&&(t.backgroundColor={v:de(e.backgroundColor),u:V.RGBA}),void 0!==e.fill){var l=e.fill;Array.isArray(l)?t.fill=l.map(function(e){if(g(e)&&Wr(e)){var t=Vr(e);if(t)return{v:t,u:V.GRADIENT}}return{v:de(e),u:V.RGBA}}):t.fill=[]}if(void 0!==e.fillEnable){var h=e.fillEnable;Array.isArray(h)?t.fillEnable=h.map(function(e){return{v:e,u:V.BOOLEAN}}):t.fillEnable=t.fill.map(function(){return{v:!0,u:V.BOOLEAN}})}if(void 0!==e.fillOpacity){var d=e.fillOpacity;Array.isArray(d)?t.fillOpacity=d.map(function(e){return{v:Math.max(0,Math.min(1,e)),u:V.NUMBER}}):t.fillOpacity=t.fill.map(function(){return{v:1,u:V.NUMBER}})}if(void 0!==e.fillMode){var f=e.fillMode;Array.isArray(f)?t.fillMode=f.map(function(e){return{v:Zr(e),u:V.NUMBER}}):t.fillMode=t.fill.map(function(){return{v:j.NORMAL,u:V.NUMBER}})}if(void 0!==e.fillRule){var m=e.fillRule;t.fillRule={v:"evenodd"===m?K.EVEN_ODD:K.NON_ZERO,u:V.NUMBER}}if(void 0!==e.stroke){var p=e.stroke;Array.isArray(p)?t.stroke=p.map(function(e){if(g(e))if(Wr(e)){if(t=Vr(e))return{v:t,u:V.GRADIENT}}else if(he.img.test(e)){var t;if(t=he.img.exec(e)){var r=ee.TILE,i=e.replace(t[0],"");i.indexOf("fill")>-1?r=ee.FILL:i.indexOf("stretch")>-1?r=ee.STRETCH:i.indexOf("fit")>-1&&(r=ee.FIT);var a=void 0,n=/([\d.]+)%/.exec(i);return n&&(a={v:parseFloat(n[1]),u:V.PERCENT}),{v:{url:t[2],type:r,scale:a},u:V.PATTERN}}}return{v:de(e),u:V.RGBA}}):t.stroke=[]}if(void 0!==e.strokeEnable){var v=e.strokeEnable;Array.isArray(v)?t.strokeEnable=v.map(function(e){return{v:e,u:V.BOOLEAN}}):t.strokeEnable=t.stroke.map(function(){return{v:!0,u:V.BOOLEAN}})}if(void 0!==e.strokeWidth){var y=e.strokeWidth;Array.isArray(y)?t.strokeWidth=y.map(function(e){return{v:Math.max(0,e),u:V.PX}}):t.strokeWidth=t.stroke.map(function(){return{v:1,u:V.NUMBER}})}if(void 0!==e.strokePosition){var b=e.strokePosition;Array.isArray(b)?t.strokePosition=b.map(function(e){var t=J.CENTER;return"inside"===e?t=J.INSIDE:"outside"===e&&(t=J.OUTSIDE),{v:t,u:V.NUMBER}}):t.strokePosition=t.stroke.map(function(){return{v:J.CENTER,u:V.NUMBER}})}if(void 0!==e.strokeMode){var x=e.strokeMode;Array.isArray(x)?t.strokeMode=x.map(function(e){return{v:Zr(e),u:V.NUMBER}}):t.strokeMode=t.stroke.map(function(){return{v:j.NORMAL,u:V.NUMBER}})}if(void 0!==e.strokeDasharray){var T=e.strokeDasharray;Array.isArray(T)?t.strokeDasharray=T.map(function(e){return{v:Math.max(0,e),u:V.PX}}):t.strokeDasharray=[]}if(void 0!==e.strokeLinecap){var w=e.strokeLinecap;o=Q.BUTT;"round"===w?o=Q.ROUND:"square"===w&&(o=Q.SQUARE),t.strokeLinecap={v:o,u:V.NUMBER}}if(void 0!==e.strokeLinejoin){var k=e.strokeLinejoin;o=Z.MITER;"round"===k?o=Z.ROUND:"bevel"===k&&(o=Z.BEVEL),t.strokeLinejoin={v:o,u:V.NUMBER}}if(void 0!==e.strokeMiterlimit&&(t.strokeMiterlimit={v:e.strokeMiterlimit,u:V.NUMBER}),["translateX","translateY","translateZ","skewX","skewY","scaleX","scaleY","rotateX","rotateY","rotateZ","perspective","perspectiveSelf"].forEach(function(r){var i=e[r];if(void 0!==i){var a=se(i);!function(e,t){"scaleX"===e||"scaleY"===e?t.u=V.NUMBER:"translateX"===e||"translateY"===e||"translateZ"===e||"perspective"===e||"perspectiveSelf"===e?t.u===V.NUMBER&&(t.u=V.PX):"rotateX"!==e&&"rotateY"!==e&&"rotateZ"!==e||t.u===V.NUMBER&&(t.u=V.DEG)}(r,a),t[r]=a}}),["transformOrigin","perspectiveOrigin"].forEach(function(r){var i=e[r];if(void 0!==i){var a;(a=Array.isArray(i)?i:(i||"").toString().match(he.position))&&a.length?1===a.length&&(a[1]=a[0]):a=[50,50];for(var n=[],o=0;o<2;o++){var s=a[o];if(/^[-+]?[\d.]/.test(s)){var c=se(s,!0);n.push(c)}else n.push({v:{top:0,left:0,center:50,right:100,bottom:100}[s],u:V.PERCENT}),S(n[o].v)&&(n[o].v=50)}t[r]=n}}),void 0!==e.mixBlendMode&&(t.mixBlendMode={v:Zr(e.mixBlendMode),u:V.NUMBER}),void 0!==e.pointerEvents&&(t.pointerEvents={v:e.pointerEvents,u:V.BOOLEAN}),e.hasOwnProperty("maskMode")){var E=e.maskMode;o=$.NONE;"alpha"===E?o=$.ALPHA:"gray"===E?o=$.GRAY:"alpha-with"===E?o=$.ALPHA_WITH:"gray-with"===E&&(o=$.GRAY_WITH),t.maskMode={v:o,u:V.NUMBER}}if(e.hasOwnProperty("breakMask")&&(t.breakMask={v:!!e.breakMask,u:V.BOOLEAN}),void 0!==e.objectFit&&(t.objectFit={v:Jr(e.objectFit),u:V.NUMBER}),void 0!==e.overflow){var C=e.overflow;o=ie.VISIBLE;"hidden"===C&&(o=ie.HIDDEN),t.overflow={v:o,u:V.NUMBER}}if(void 0!==e.filter){var A=Array.isArray(e.filter)?e.filter:[e.filter],_=[];A.forEach(function(e){var t=/([\w-]+)\s*\((\s*.+\s*)\)/i.exec(e);if(t){var r=t[1],i=t[2];if("gaussBlur"===r){var a=parseFloat(i)||0;_.push({v:{radius:{v:Math.max(a,0),u:V.PX}},u:V.GAUSS_BLUR})}else if("radiaBlur"===r){a=parseFloat(i)||0;var n=/,\s*(.+)\s*(?:,\s*(.+))?/.exec(i),o=[{v:50,u:V.PERCENT},{v:50,u:V.PERCENT}];if(n)if((h=se(n[1])).u!==V.PX&&h.u!==V.PERCENT&&(h.u=V.PX),o[0]=h,n[2]){var s=se(n[2]);s.u!==V.PX&&s.u!==V.PERCENT&&(s.u=V.PX),o[1]=s}else o[1]={v:h.v,u:h.u};_.push({v:{radius:{v:Math.max(a,0),u:V.PX},center:o},u:V.RADIAL_BLUR})}else if("motionBlur"===r){a=parseFloat(i)||0;var c={v:0,u:V.DEG},u={v:0,u:V.DEG};if(p=/,\s*(.+)\s*(?:,\s*(.+))?/.exec(i)){var l=parseFloat(p[1]);if(c.v=l||0,p[2]){var h=se(p[2]);u.v=h.v}}_.push({v:{radius:{v:Math.max(a,0),u:V.PX},angle:c,offset:u},u:V.MOTION_BLUR})}else if("bloom"===r){a=parseFloat(i)||0;var d=/,\s*([^,]+)/.exec(i),f={v:.5,u:V.NUMBER};if(d){var m=se(d[1]);f.v=Math.max(0,m.v)}_.push({v:{threshold:{v:Math.max(a,0),u:V.NUMBER},knee:f},u:V.BLOOM})}else if("lightDark"===r){var p;a=parseFloat(i)||0,c={v:0,u:V.DEG};if(p=/,\s*(.+)\s*(?:,\s*(.+))?/.exec(i)){l=parseFloat(p[1]);c.v=l||0}_.push({v:{radius:{v:Math.max(a,0),u:V.PX},angle:c},u:V.LIGHT_DARK})}else if("hueRotate"===r){a=parseFloat(i)||0;_.push({v:{radius:{v:a,u:V.DEG}},u:V.HUE_ROTATE})}else if("saturate"===r){a=parseFloat(i)||0;_.push({v:{radius:{v:.01*a,u:V.PERCENT}},u:V.SATURATE})}else if("brightness"===r){a=parseFloat(i)||0;_.push({v:{radius:{v:.01*a,u:V.PERCENT}},u:V.BRIGHTNESS})}else if("contrast"===r){a=parseFloat(i)||0;_.push({v:{radius:{v:.01*a,u:V.PERCENT}},u:V.CONTRAST})}else if("sepia"===r){a=parseFloat(i)||0;_.push({v:{radius:{v:.01*a,u:V.PERCENT}},u:V.SEPIA})}}}),t.filter=_}return t}function Yr(e){var t=e.fontSize||L.defaultFontSize,r=e.fontFamily||L.defaultFontFamily;/[\s.,/\\]/.test(r)&&(r='"'+r.replace(/"/g,'\\"')+'"');var i="";e.fontStyle===G.ITALIC&&(i="italic ");var a="";return 400!==e.fontWeight&&(a=e.fontWeight+" "),i+a+t+"px "+r}function qr(e){for(var t=e.split(/\s*,\s*/),r=0,i=t.length;r<i;r++){var a=t[r].replace(/^['"]/,"").replace(/['"]$/,"");if(Xe.hasRegister(a)||oe.checkSupportFontFamily(a))return a}return L.defaultFontFamily}function Kr(e,t){t||(t=qr(e.fontFamily));var r=(Xe.data[t]||Xe.data[L.defaultFontFamily]||Xe.data.Arial||{}).lhr;return e.fontSize*r}function $r(e,t){var r=e.fontSize,i=qr(e.fontFamily),a=Kr(e,i),n=(Xe.data[i]||Xe.data[L.defaultFontFamily]||Xe.data.Arial||{}).blr||1;return.5*((null!=t?t:e.lineHeight)-a)+r*n}function Qr(e,t){var r=e.fontSize,i=qr(e.fontFamily),a=Kr(e,i),n=(Xe.data[i]||Xe.data[L.defaultFontFamily]||Xe.data.Arial||{}).car||1;return.5*((null!=t?t:e.lineHeight)-a)+r*n}function Zr(e){var t=j.NORMAL;return/multiply/i.test(e)?t=j.MULTIPLY:/screen/i.test(e)?t=j.SCREEN:/overlay/i.test(e)?t=j.OVERLAY:/darken/i.test(e)?t=j.DARKEN:/lighten/i.test(e)?t=j.LIGHTEN:/color[-\s]dodge/i.test(e)||/colorDodge/.test(e)?t=j.COLOR_DODGE:/color[-\s]burn/i.test(e)||/colorBurn/.test(e)?t=j.COLOR_BURN:/hard[\-\s]light/i.test(e)||/hardLight/.test(e)?t=j.HARD_LIGHT:/soft[-\s]light/i.test(e)||/softLight/.test(e)?t=j.SOFT_LIGHT:/difference/i.test(e)?t=j.DIFFERENCE:/exclusion/i.test(e)?t=j.EXCLUSION:/hue/i.test(e)?t=j.HUE:/saturation/i.test(e)?t=j.SATURATION:/color/i.test(e)?t=j.COLOR:/luminosity/i.test(e)&&(t=j.LUMINOSITY),t}function Jr(e){var t=ae.FILL;return"contain"===e?t=ae.CONTAIN:"cover"===e&&(t=ae.COVER),t}function ei(e,t,r){if(e===t)return!0;var i=e[r],a=t[r];if(void 0===i&&void 0===a)return!0;if(void 0===i||void 0===a)return!1;if("transformOrigin"===r||"perspectiveOrigin"===r)return i[0].v===a[0].v&&i[0].u===a[0].u&&i[1].v===a[1].v&&i[1].u===a[1].u;if("color"===r||"backgroundColor"===r)return i.v[0]===a.v[0]&&i.v[1]===a.v[1]&&i.v[2]===a.v[2]&&i.v[3]===a.v[3];if("fill"===r||"stroke"===r){if(i.length!==a.length)return!1;for(var n=0,o=i.length;n<o;n++){var s=i[n],c=a[n];if(s.u!==c.u)return!1;if(s.u===V.RGBA){if(s.v[0]!==c.v[0]||s.v[1]!==c.v[1]||s.v[2]!==c.v[2]||s.v[3]!==c.v[3])return!1}else if(s.u===V.GRADIENT){if(s.v.t!==c.v.t)return!1;if(s.v.d.length!==c.v.d.length)return!1;for(var u=0,l=s.v.d.length;u<l;u++)if(s.v.d[u]!==c.v.d[u])return!1;if(s.v.stops.length!==c.v.stops.length)return!1;for(var h=0,d=s.v.stops.length;h<d;h++){var f=s.v.stops[h],m=c.v.stops[h];if(f.color.v[0]!==m.color.v[0]||f.color.v[1]!==m.color.v[1]||f.color.v[2]!==m.color.v[2]||f.color.v[3]!==m.color.v[3])return!1;if(f.offset&&!m.offset||!f.offset&&m.offset)return!1;if(f.offset.u!==m.offset.u||f.offset.v!==m.offset.v)return!1}}}return!0}if("filter"===r){if(i.length!==a.length)return!1;for(n=0,o=i.length;n<o;n++){s=i[n],c=a[n];if(s.u!==c.u)return!1;if(s.u===V.GAUSS_BLUR){if(s.v.radius.v!==c.v.radius.v)return!1}else if(s.u===V.RADIAL_BLUR){if(s.v.radius.v!==c.v.radius.v)return!1;if(s.v.center[0].v!==c.v.center[0].v||s.v.center[1].v!==c.v.center[1].v)return!1}else if(s.u===V.MOTION_BLUR){if(s.v.radius.v!==c.v.radius.v)return!1;if(s.v.angle.v!==c.v.angle.v||s.v.offset.v!==c.v.offset.v)return!1}else if(s.u===V.BLOOM){if(s.v.threshold.v!==c.v.threshold.v||s.v.knee.v!==c.v.knee.v)return!1}else if(s.u===V.LIGHT_DARK){if(s.v.radius.v!==c.v.radius.v||s.v.angle.v!==c.v.angle.v)return!1}else if((s.u===V.HUE_ROTATE||s.u===V.SATURATE||s.u===V.BRIGHTNESS||s.u===V.CONTRAST||s.u===V.SEPIA)&&s.v.radius.v!==c.v.radius.v)return!1}return!0}if("fillEnable"===r||"fillRule"===r||"fillOpacity"===r||"strokeEnable"===r||"strokeWidth"===r||"strokePosition"===r||"strokeDasharray"===r){if(i.length!==a.length)return!1;for(n=0,o=i.length;n<o;n++){s=i[n],c=a[n];if(s.u!==c.u||s.v!==c.v)return!1}return!0}return i.v===a.v&&i.u===a.u}function ti(e,t){t?Array.isArray(t)||(t=[t]):t=Object.keys(e);for(var r={},i=0,a=t.length;i<a;i++){var n=t[i],o=e[n];o&&(r[n]="transformOrigin"===n||"perspectiveOrigin"===n?[Object.assign({},o[0]),Object.assign({},o[1])]:"color"===n||"backgroundColor"===n?{v:o.v.slice(0),u:o.u}:"fill"===n||"stroke"===n||"filter"===n?o.map(function(e){return C(e)}):"filter"===n?o.map(function(e){var t={};return e.u===V.RADIAL_BLUR?(t.radius=Object.assign({},e.v.radius),t.center=e.v.center.map(function(e){return Object.assign({},e)})):e.u===V.MOTION_BLUR?(t.radius=Object.assign({},e.v.radius),t.angle=Object.assign({},e.v.angle),t.offset=Object.assign({},e.v.offset)):e.u===V.BLOOM&&(t.threshold=Object.assign({},e.v.threshold),t.knee=Object.assign({},e.v.knee)),{v:t,u:e.u}}):"fillEnable"===n||"fillRule"===n||"fillOpacity"===n||"strokeEnable"===n||"strokeWidth"===n||"strokePosition"===n||"strokeDasharray"===n?o.map(function(e){return Object.assign({},e)}):Object.assign({},o))}return r}function ri(e,t){return e.u===V.PX?e.v:e.u===V.PERCENT?e.v*t*.01:0}function ii(e,t){var i={};return ue.forEach(function(e){var r=t[e];void 0!==r&&(i[e]=r)}),r(r({location:e.location,length:e.length},i),Gr(e))}function ai(e){return["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"][e]}function ni(e,t,r,i){return void 0===i&&(i=!1),Array.isArray(e)?fe(e):function(e,t,r,i){var a,n,o,s;void 0===t&&(t=100),void 0===r&&(r=100),void 0===i&&(i=!1);var c=e.t,u=e.d,l=e.stops,h=u[0],d=u[1],f=u[2],m=u[3];h*=t,f*=t,d*=r,m*=r;var p=0;1===u.length?p=u[0]:h===f?d<m&&(p=180):p=f>h?m>=d?90+mr(Math.atan((m-d)/(f-h))):mr(Math.atan((f-h)/(d-m))):m>=d?180+mr(Math.atan((h-f)/(m-d))):360-mr(Math.atan((h-f)/(d-m)));var g=l.slice(0);if(g.sort(function(e,t){return e.offset-t.offset}),c===Y.LINEAR){var v=void 0,y=void 0;p<=90?(v={x:0,y:r},y={x:t,y:0}):p<=180?(v={x:0,y:0},y={x:t,y:r}):p<=270?(v={x:t,y:0},y={x:0,y:r}):(v={x:t,y:r},y={x:0,y:0});var b=C(g).sort(function(e,t){return e.offset-t.offset});if(i){var x=Math.sqrt(Math.pow(m-v.y,2)+Math.pow(f-v.x,2)),T=Math.sqrt(Math.pow(d-v.y,2)+Math.pow(h-v.x,2)),w=Math.sqrt(Math.pow(m-d,2)+Math.pow(f-h,2)),k=yr(x,T,w),S=k?T*Math.cos(k):T,E=(k=yr(x=Math.sqrt(Math.pow(d-y.y,2)+Math.pow(h-y.x,2)),T=Math.sqrt(Math.pow(m-y.y,2)+Math.pow(f-y.x,2)),w))?T*Math.cos(k):T;if(b[0].offset>0&&b.unshift({color:b[0].color.slice(0),offset:0}),b[b.length-1].offset<1&&b.push({color:b[b.length-1].color.slice(0),offset:1}),S>1e-9)for(var A=S/w,_=function(e,t){var r=b[e];if(r.offset>=A){var i=b[e-1]||{color:r.color,offset:0};if(b.splice(0,e),r.offset>A){var a=w*(r.offset-i.offset),n=(S-i.offset*w)/a,o=i.color.map(function(e,t){return 3===t?e+(r.color[t]-e)*n:e+Math.floor((r.color[t]-e)*n)}),s={color:o,offset:0};b.unshift(s)}return"break"}},M=0,I=b.length;M<I&&"break"!==_(M);M++);else S<-1e-9&&b.forEach(function(e){e.offset=(e.offset*w-S)/(w-S)});if(E>1e-9){A=(w-E)/w;var R=function(e){var t=b[e];if(t.offset<=A){var r=b[e+1]||{color:t.color,offset:1};if(b.splice(e+1),t.offset<A){var i=w*(r.offset-t.offset),a=(E-(1-r.offset)*w)/i,n=r.color.map(function(e,r){return 3===r?e+(t.color[r]-e)*a:e+Math.floor((t.color[r]-e)*a)}),o={color:n,offset:1};b.push(o)}return"break"}};for(M=b.length-1;M>=0&&"break"!==R(M);M--);}else E<-1e-9&&b.forEach(function(e){e.offset=e.offset*(w-S)/(w-S-E)})}var P="linear-gradient(";return P+=i?Nr(p)+"deg":u.join(" "),b.forEach(function(e){P+=", ",e.color[3]=Nr(e.color[3]),P+=fe(e.color)+" "+Nr(100*e.offset)+"%"}),P+")"}if(c===Y.RADIAL){var O=1;if(i){var D=Math.sqrt(Math.pow(f-h,2)+Math.pow(m-d,2)),B=Math.sqrt(Math.pow(h,2)+Math.pow(d,2)),F=Math.sqrt(Math.pow(h-t,2)+Math.pow(d,2)),L=Math.sqrt(Math.pow(h-t,2)+Math.pow(d-r,2)),N=Math.sqrt(Math.pow(h,2)+Math.pow(d-r,2)),U=Math.max(B,F,L,N);O=U/D}var z="radial-gradient(";return z+=i?"circle at ".concat(100*Nr(u[0]),"% ").concat(100*Nr(u[1]),"%, "):u.join(" ")+", ",g.forEach(function(e,t){t&&(z+=", ");var r=e.color.map(function(e,t){return 3===t?Nr(e):Math.min(255,Math.floor(e*O))});z+=fe(r)+" "+Nr(100*e.offset)+"%"}),z+")"}if(c===Y.CONIC){var W="conic-gradient(";i&&(W+="from 90deg, ");var V=g[0],H=g[g.length-1];if(i&&(V.offset>0||H.offset<1)){var X=null!==(a=V.color[3])&&void 0!==a?a:1,j=null!==(n=H.color[3])&&void 0!==n?n:1,G=[V.color[0]-H.color[0],V.color[1]-H.color[1],V.color[2]-H.color[2],X-j],q=1-H.offset+V.offset;if(V.offset>0){var K=V.offset/q;g.unshift({color:[Math.min(255,Math.max(0,Math.round(V.color[0]-G[0]*K))),Math.min(255,Math.max(0,Math.round(V.color[1]-G[1]*K))),Math.min(255,Math.max(0,Math.round(V.color[2]-G[2]*K))),Math.min(1,Math.max(0,null!==(o=V.color[3])&&void 0!==o?o:1-G[3]*K))],offset:0})}H.offset<1&&(K=(1-H.offset)/q,g.push({color:[Math.min(255,Math.max(0,Math.round(H.color[0]+G[0]*K))),Math.min(255,Math.max(0,Math.round(H.color[1]+G[1]*K))),Math.min(255,Math.max(0,Math.round(H.color[2]+G[2]*K))),Math.min(1,Math.max(0,null!==(s=H.color[3])&&void 0!==s?s:1+G[3]*K))],offset:1}))}return g.forEach(function(e,t){t&&(W+=", "),e.color[3]=Nr(e.color[3]),W+=fe(e.color)+" "+Nr(100*e.offset)+"%"}),W+")"}return""}(e,t,r,i)}function oi(e){return["center","inside","outside"][e]||"inside"}function si(e){var t,r,i,a;return{x:e.x,y:e.y,cornerRadius:e.cornerRadius||0,fx:null!==(t=e.fx)&&void 0!==t?t:e.x,fy:null!==(r=e.fy)&&void 0!==r?r:e.y,tx:null!==(i=e.tx)&&void 0!==i?i:e.x,ty:null!==(a=e.ty)&&void 0!==a?a:e.y,hasCurveFrom:e.hasCurveFrom||!1,hasCurveTo:e.hasCurveTo||!1,curveMode:{none:ce.NONE,straight:ce.STRAIGHT,mirrored:ce.MIRRORED,asymmetric:ce.ASYMMETRIC,disconnected:ce.DISCONNECTED}[e.curveMode||"none"]||ce.NONE,absX:0,absY:0,absFx:0,absFy:0,absTx:0,absTy:0,dspX:0,dspY:0,dspFx:0,dspFy:0,dspTx:0,dspTy:0}}var ci,ui={normalize:Gr,equalStyle:ei,cloneStyle:ti,calSize:ri,normalizeRich:ii,getCssMbm:ai,getCssFillStroke:ni,getCssStrokePosition:oi,normalizePoints:si,getPropsRich:function(e){return r(r({},e),{textAlign:["left","right","center","justify"][e.textAlign]||"left",textDecoration:e.textDecoration.map(function(e){return["none","underline","lineThrough"][e]||"none"}),color:fe(e.color)})}};function li(e){return"pointerEvents"===e||"constrainProportions"===e||"isLocked"===e||"isSelected"===e||"resizesContent"===e||"isRectangle"===e?ci.NONE:"translateX"===e?ci.TRANSLATE_X:"translateY"===e?ci.TRANSLATE_Y:"translateZ"===e?ci.TRANSLATE_Z:"rotateX"===e?ci.ROTATE_X:"rotateY"===e?ci.ROTATE_Y:"rotateZ"===e?ci.ROTATE_Z:"scaleX"===e?ci.SCALE_X:"scaleY"===e?ci.SCALE_Y:"matrix"===e?ci.MATRIX:"transformOrigin"===e?ci.TRANSFORM_ORIGIN:"opacity"===e?ci.OPACITY:"perspective"===e||"perspectiveOrigin"===e?ci.PERSPECTIVE:"perspectiveSelf"===e?ci.PERSPECTIVE_SELF:"filter"===e?ci.FILTER:"mixBlendMode"===e?ci.MIX_BLEND_MODE:"maskMode"===e?ci.MASK:"breakMask"===e?ci.BREAK_MASK:function(e){return"width"===e||"height"===e||"letterSpacing"===e||"paragraphSpacing"===e||"textAlign"===e||"textVerticalAlign"===e||"fontFamily"===e||"fontSize"===e||"fontWeight"===e||"fontStyle"===e||"lineHeight"===e||"left"===e||"top"===e||"right"===e||"bottom"===e}(e)?ci.REFLOW:ci.REPAINT}function hi(e,t,r,i,a){if(3===arguments.length){var n=t,o=n[0],s=n[1],c=n[2],u=n[3];if(!nt(r)){var l=bt({x:o,y:s},r),h=bt({x:o,y:u},r),d=bt({x:c,y:s},r),f=bt({x:c,y:u},r);l.w&&1!==l.w&&(l.x/=l.w,l.y/=l.w),h.w&&1!==h.w&&(h.x/=h.w,h.y/=h.w),d.w&&1!==d.w&&(d.x/=d.w,d.y/=d.w),f.w&&1!==f.w&&(f.x/=f.w,f.y/=f.w),o=Math.min(l.x,h.x,d.x,f.x),s=Math.min(l.y,h.y,d.y,f.y),c=Math.max(l.x,h.x,d.x,f.x),u=Math.max(l.y,h.y,d.y,f.y)}e[0]=Math.min(e[0],o),e[1]=Math.min(e[1],s),e[2]=Math.max(e[2],c),e[3]=Math.max(e[3],u)}else 2===arguments.length?(e[0]=Math.min(e[0],t[0]),e[1]=Math.min(e[1],t[1]),e[2]=Math.max(e[2],t[2]),e[3]=Math.max(e[3],t[3])):5===arguments.length&&(e[0]=Math.min(e[0],t),e[1]=Math.min(e[1],r),e[2]=Math.max(e[2],i),e[3]=Math.max(e[3],a))}function di(e,t){var r,i;if(6===e.length)r=e[4],i=e[5];else if(4===e.length)r=e[2],i=e[3];else{if(2!==e.length)return void oe.error("Unsupported point data: "+e.join(","));r=e[0],i=e[1]}return t[0]=r,t[1]=i,t[2]=r,t[3]=i,{x:r,y:i}}function fi(e,t,r,i){var a,n;if(4===e.length)a=e[2],n=e[3],hi(i,(o=Zt.bboxBezier(t,r,e[0],e[1],a,n))[0],o[1],o[2],o[3]);else if(6===e.length){var o;a=e[4],n=e[5],hi(i,(o=Zt.bboxBezier(t,r,e[0],e[1],e[2],e[3],a,n))[0],o[1],o[2],o[3])}else{if(2!==e.length)return void oe.error("Unsupported point data: "+e.join(","));hi(i,a=e[0],n=e[1],a,n)}return{x:a,y:n}}function mi(e){e[0]=Math.floor(e[0]),e[1]=Math.floor(e[1]),e[2]=Math.ceil(e[2]),e[3]=Math.ceil(e[3])}!function(e){e[e.NONE=0]="NONE",e[e.CACHE=1]="CACHE",e[e.TRANSLATE_X=2]="TRANSLATE_X",e[e.TRANSLATE_Y=4]="TRANSLATE_Y",e[e.TRANSLATE=6]="TRANSLATE",e[e.TRANSLATE_Z=8]="TRANSLATE_Z",e[e.ROTATE_X=16]="ROTATE_X",e[e.ROTATE_Y=32]="ROTATE_Y",e[e.ROTATE_Z=64]="ROTATE_Z",e[e.SCALE_X=128]="SCALE_X",e[e.SCALE_Y=256]="SCALE_Y",e[e.SCALE=384]="SCALE",e[e.MATRIX=512]="MATRIX",e[e.TRANSFORM_ORIGIN=1024]="TRANSFORM_ORIGIN",e[e.TRANSFORM_ALL=2046]="TRANSFORM_ALL",e[e.PERSPECTIVE=2048]="PERSPECTIVE",e[e.PERSPECTIVE_SELF=4096]="PERSPECTIVE_SELF",e[e.OPACITY=8192]="OPACITY",e[e.FILTER=16384]="FILTER",e[e.MIX_BLEND_MODE=32768]="MIX_BLEND_MODE",e[e.MASK=65536]="MASK",e[e.BREAK_MASK=131072]="BREAK_MASK",e[e.MASK_OPACITY=139264]="MASK_OPACITY",e[e.HOOK=262144]="HOOK",e[e.REPAINT=524288]="REPAINT",e[e.REFLOW=1048576]="REFLOW",e[e.REFLOW_REPAINT=1572864]="REFLOW_REPAINT",e[e.REFLOW_REPAINT_MASK=1638400]="REFLOW_REPAINT_MASK",e[e.REFLOW_REPAINT_HOOK=1835008]="REFLOW_REPAINT_HOOK",e[e.REFLOW_TRANSFORM=1050622]="REFLOW_TRANSFORM",e[e.REFLOW_PERSPECTIVE=1050624]="REFLOW_PERSPECTIVE",e[e.REFLOW_PERSPECTIVE_SELF=1052672]="REFLOW_PERSPECTIVE_SELF",e[e.REFLOW_OPACITY=1056768]="REFLOW_OPACITY",e[e.REFLOW_FILTER=1064960]="REFLOW_FILTER",e[e.ADD_DOM=2097152]="ADD_DOM",e[e.REMOVE_DOM=4194304]="REMOVE_DOM",e[e.FULL=8388607]="FULL"}(ci||(ci={}));var pi,gi,vi={},yi=new WeakMap,bi=new WeakMap,xi=function(){function e(e,t,r,i){void 0===r&&(r=0),void 0===i&&(i=0),this.available=!1,this.w=e,this.h=t,this.dx=r,this.dy=i,this.list=[];for(var a=L.maxTextureSize,n=0,o=Math.ceil(t/a);n<o;n++)for(var s=0,c=Math.ceil(e/a);s<c;s++){var u=s===c-1?e-s*a:a,l=n===o-1?t-n*a:a;this.list.push({x:s*a-r,y:n*a-i,w:u,h:l,os:oe.getOffscreenCanvas(u,l)})}}return e.prototype.release=function(){return this.url?this.releaseImg(this.url):this.videoFrame?this.releaseVideoFrame(this.videoFrame):this.canvas?this.releaseCanvas(this.canvas):!!this.available&&(this.available=!1,this.list.splice(0).forEach(function(e){return e.os.release()}),!0)},e.prototype.releaseImg=function(e){if(!this.available)return!1;this.available=!1;var t=vi[e];return t&&(t.count--,t.count||(delete vi[e],this.list.splice(0).forEach(function(e){return e.os.release()}))),!0},e.prototype.releaseVideoFrame=function(e){if(!this.available)return!1;this.available=!1;var t=bi.get(e);return t&&(t.count--,t.count||(bi.delete(e),this.list.splice(0).forEach(function(e){return e.os.release()}))),!0},e.prototype.releaseCanvas=function(e){if(!this.available)return!1;this.available=!1;var t=yi.get(e);return t&&(t.count--,t.count||(yi.delete(e),this.list.splice(0).forEach(function(e){return e.os.release()}))),!0},e.prototype.getCount=function(){var e,t;return this.url?null===(e=vi[this.url])||void 0===e?void 0:e.count:this.videoFrame?null===(t=bi.get(this.videoFrame))||void 0===t?void 0:t.count:void 0},e.getImgInstance=function(t,r,i,a,n){void 0===a&&(a=0),void 0===n&&(n=0);var o=vi[i];if(o)return o.count++,o.value;var s=new e(t,r,a,n);return s.url=i,vi[i]={value:s,count:1},s},e.getVideoFrameInstance=function(t,r,i,a,n){void 0===a&&(a=0),void 0===n&&(n=0);var o=bi.get(i);if(o)return o.count++,o.value;var s=new e(t,r,a,n);return s.videoFrame=i,bi.set(i,{value:s,count:1}),s},e.getCanvasInstance=function(t,r,i,a,n){void 0===a&&(a=0),void 0===n&&(n=0);var o=yi.get(i);if(o)return o.count++,o.value;var s=new e(t,r,a,n);return s.canvas=i,yi.set(i,{value:s,count:1}),s},e}();function Ti(e,t,r){var i=function(e,t,r){var i=wi(e,e.VERTEX_SHADER,t),a=wi(e,e.FRAGMENT_SHADER,r);if(!i||!a)return null;var n=e.createProgram();if(!n)return null;n.vertexShader=i,n.fragmentShader=a,e.attachShader(n,i),e.attachShader(n,a),e.linkProgram(n);var o=e.getProgramParameter(n,e.LINK_STATUS);if(!o){var s=e.getProgramInfoLog(n);throw e.deleteProgram(n),e.deleteShader(a),e.deleteShader(i),new Error("Failed to link program: "+s)}return n}(e,t,r);if(!i)throw new Error("Failed to create program");return e.enable(e.BLEND),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA),i}function wi(e,t,r){var i=e.createShader(t);if(null===i)throw new Error("unable to create shader");if(e.shaderSource(i,r),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){var a=e.getShaderInfoLog(i);throw e.deleteShader(i),new Error("Failed to compile shader: "+a)}return i}function ki(e,t,r,i,a){var n=e.createTexture();if(Si(e,n,t),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),r)e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r);else{if(!i||!a)throw new Error("Missing texImageSource or w/h");e.texImage2D(e.TEXTURE_2D,0,e.RGBA,i,a,0,e.RGBA,e.UNSIGNED_BYTE,null)}return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),n}function Si(e,t,r){e.activeTexture(e["TEXTURE"+r]),e.bindTexture(e.TEXTURE_2D,t)}function Ei(e,t,r,i,a){var n,o;n=pi||(pi=new Float32Array(12)),o=gi||(gi=new Float32Array(8));var s=a.matrix,c=a.bbox,u=a.tc,l=a.t,h=a.dx,d=void 0===h?0:h,f=a.dy,m=void 0===f?0:f;Si(e,l,0);var p=Gi(c,t,r,d,m,s),g=p.t1,v=p.t2,y=p.t3,b=p.t4;n[0]=g.x,n[1]=g.y,n[2]=g.w||1,n[3]=b.x,n[4]=b.y,n[5]=b.w||1,n[6]=v.x,n[7]=v.y,n[8]=v.w||1,n[9]=y.x,n[10]=y.y,n[11]=y.w||1,u?(o[0]=u.x1,o[1]=u.y3,o[2]=u.x1,o[3]=u.y1,o[4]=u.x3,o[5]=u.y3,o[6]=u.x3,o[7]=u.y1):(o[0]=0,o[1]=1,o[2]=0,o[3]=0,o[4]=1,o[5]=1,o[6]=1,o[7]=0);var x=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,x),e.bufferData(e.ARRAY_BUFFER,n,e.STATIC_DRAW);var T=i.attrib.a_position;e.vertexAttribPointer(T,3,e.FLOAT,!1,0,0),e.enableVertexAttribArray(T);var w=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,w),e.bufferData(e.ARRAY_BUFFER,o,e.STATIC_DRAW);var k=i.attrib.a_texCoords;e.vertexAttribPointer(k,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(k);var S=i.uniformValue;if(S.u_opacity!==a.opacity){S.u_opacity=a.opacity;var E=i.uniform.u_opacity;e.uniform1f(E,a.opacity)}if(0!==S.u_texture){S.u_texture=0;var C=i.uniform.u_texture;e.uniform1i(C,0)}e.drawArrays(e.TRIANGLE_STRIP,0,4),e.deleteBuffer(x),e.deleteBuffer(w),e.disableVertexAttribArray(T),e.disableVertexAttribArray(k)}for(var Ci=16,Ai=new Float32Array(192),_i=new Float32Array(128),Mi=new Float32Array(64),Ii=new Uint16Array(64),Ri=new Uint16Array(Ci),Pi=0;Pi<Ci;Pi++)Ri[Pi]=Pi;var Oi=new Uint16Array(79);for(Pi=0;Pi<Oi.length;Pi++){var Di=(Pi+1)%5;if(Di){var Bi=Math.floor(Pi/5);Oi[Pi]=4*Bi+Di-1}else Oi[Pi]=65535}function Fi(e,t,r,i,a){var n=a.length;if(n>Ci)throw new Error("DrawData size is "+n+", max is "+Ci);for(var o=0;o<n;o++){var s=a[o],c=s.opacity,u=s.matrix,l=s.bbox,h=s.tc,d=s.t,f=s.dx,m=void 0===f?0:f,p=s.dy,g=void 0===p?0:p;Si(e,d,o);var v=Gi(l,t,r,m,g,u),y=v.t1,b=v.t2,x=v.t3,T=v.t4;Ai[12*o]=y.x,Ai[12*o+1]=y.y,Ai[12*o+2]=y.w||1,Ai[12*o+3]=T.x,Ai[12*o+4]=T.y,Ai[12*o+5]=T.w||1,Ai[12*o+6]=b.x,Ai[12*o+7]=b.y,Ai[12*o+8]=b.w||1,Ai[12*o+9]=x.x,Ai[12*o+10]=x.y,Ai[12*o+11]=x.w||1,h?(_i[8*o]=h.x1,_i[8*o+1]=h.y1,_i[8*o+2]=h.x1,_i[8*o+3]=h.y3,_i[8*o+4]=h.x3,_i[8*o+5]=h.y1,_i[8*o+6]=h.x3,_i[8*o+7]=h.y3):(_i[8*o]=0,_i[8*o+1]=1,_i[8*o+2]=0,_i[8*o+3]=0,_i[8*o+4]=1,_i[8*o+5]=1,_i[8*o+6]=1,_i[8*o+7]=0),Mi[4*o]=c,Mi[4*o+1]=c,Mi[4*o+2]=c,Mi[4*o+3]=c,Ii[4*o]=o,Ii[4*o+1]=o,Ii[4*o+2]=o,Ii[4*o+3]=o}var w=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,w),e.bufferData(e.ARRAY_BUFFER,Ai,e.STATIC_DRAW);var k=i.attrib.a_position;e.vertexAttribPointer(k,3,e.FLOAT,!1,0,0),e.enableVertexAttribArray(k);var S=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,S),e.bufferData(e.ARRAY_BUFFER,_i,e.STATIC_DRAW);var E=i.attrib.a_texCoords;e.vertexAttribPointer(E,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(E);var C=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,C),e.bufferData(e.ARRAY_BUFFER,Mi,e.STATIC_DRAW);var A=i.attrib.a_opacity;e.vertexAttribPointer(A,1,e.FLOAT,!1,0,0),e.enableVertexAttribArray(A);var _=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,_),e.bufferData(e.ARRAY_BUFFER,Ii,e.STATIC_DRAW);var M=i.attrib.a_textureIndex;e.vertexAttribPointer(M,1,e.UNSIGNED_SHORT,!1,0,0),e.enableVertexAttribArray(M);var I=i.uniformValue;Ri.forEach(function(t){var r="u_texture["+t+"]";if(I[r]!==t){I[r]=t;var a=i.uniform[r];e.uniform1i(a,t)}});var R=e.createBuffer();e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,R),e.bufferData(e.ELEMENT_ARRAY_BUFFER,Oi,e.STATIC_DRAW),e.drawElements(e.TRIANGLE_STRIP,5*n-1,e.UNSIGNED_SHORT,0)}function Li(e,t){var r=function(){var e=new Float32Array(8),t=new Float32Array(8);return e[0]=-1,e[1]=-1,e[2]=-1,e[3]=1,e[4]=1,e[5]=-1,e[6]=1,e[7]=1,t[0]=0,t[1]=0,t[2]=0,t[3]=1,t[4]=1,t[5]=0,t[6]=1,t[7]=1,{vtPoint:e,vtTex:t}}(),i=r.vtPoint,a=r.vtTex,n=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,n),e.bufferData(e.ARRAY_BUFFER,i,e.STATIC_DRAW);var o=t.attrib.a_position;e.vertexAttribPointer(o,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(o);var s=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,s),e.bufferData(e.ARRAY_BUFFER,a,e.STATIC_DRAW);var c=t.attrib.a_texCoords;return e.vertexAttribPointer(c,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(c),{pointBuffer:n,a_position:o,texBuffer:s,a_texCoords:c}}function Ni(e,t,r,i,a,n){void 0===a&&(a=0),void 0===n&&(n=0);var o=Li(e,t),s=o.pointBuffer,c=o.a_position,u=o.texBuffer,l=o.a_texCoords;Si(e,r,0),Si(e,i,1);var h=t.uniform.u_texture1;e.uniform1i(h,0);var d=t.uniform.u_texture2;e.uniform1i(d,1);var f=t.uniform.u_d;void 0!==f&&e.uniform2f(f,a,n),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.deleteBuffer(s),e.deleteBuffer(u),e.disableVertexAttribArray(c),e.disableVertexAttribArray(l)}function Ui(e,t,r,i,a,n,o,s){void 0===s&&(s=1);var c=Li(e,t),u=c.pointBuffer,l=c.a_position,h=c.texBuffer,d=c.a_texCoords,f=t.uniform.u_xy;e.uniform2f(f,s/i,s/a);var m=ki(e,0,void 0,n,o),p=t.uniform.u_texture;return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,m,0),Si(e,r,0),e.uniform1i(p,0),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.deleteBuffer(u),e.deleteBuffer(h),e.disableVertexAttribArray(l),e.disableVertexAttribArray(d),m}function zi(e,t,r,i,a,n,o,s,c){void 0===c&&(c=!1);var u=Li(e,t),l=u.pointBuffer,h=u.a_position,d=u.texBuffer,f=u.a_texCoords;if(Math.floor(i)!==t.uniformValue.u_kernel){var m=t.uniform.u_kernel;e.uniform1i(m,Math.floor(i))}if(c!==t.uniformValue.u_limit){var p=t.uniform.u_limit;e.uniform1i(p,c?1:0)}var g=Math.sin(a)*i/s,v=Math.cos(a)*i/o,y=Math.sin(a)*n/s,b=Math.cos(a)*n/o,x=t.uniform.u_velocity;e.uniform4f(x,v,g,b,y);for(var T=t.uniform.u_texture,w=r,k=ki(e,0,void 0,o,s),S=ki(e,0,void 0,o,s),E=0;E<3;E++)e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,[k,S,k][E],0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),Si(e,[w,k,S][E],0),e.uniform1i(T,0),e.drawArrays(e.TRIANGLE_STRIP,0,4);return e.deleteBuffer(l),e.deleteBuffer(d),e.disableVertexAttribArray(h),e.disableVertexAttribArray(f),e.deleteTexture(S),k}function Wi(e,t,r,i,a,n,o,s){var c=Li(e,t),u=c.pointBuffer,l=c.a_position,h=c.texBuffer,d=c.a_texCoords,f=t.uniform.u_kernel;e.uniform1i(f,a);var m=t.uniform.u_center;e.uniform2f(m,n[0],n[1]);var p=t.uniform.u_ratio;e.uniform1f(p,i);for(var g=r,v=[],y=0;y<1;y++){var b=ki(e,0,void 0,o,s);e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,b,0),Si(e,g,0);var x=t.uniform.u_texture;e.uniform1i(x,0),e.drawArrays(e.TRIANGLE_STRIP,0,4),v.push(g),g=b}return e.deleteBuffer(u),e.deleteBuffer(h),e.disableVertexAttribArray(l),e.disableVertexAttribArray(d),v.forEach(function(t){t!==r&&e.deleteTexture(t)}),g}var Vi=Ni;function Hi(e,t,r,i){var a=Li(e,t),n=a.pointBuffer,o=a.a_position,s=a.texBuffer,c=a.a_texCoords;Si(e,r,0);var u=t.uniform.u_texture;e.uniform1i(u,0);var l=t.uniform["u_m[0]"];e.uniform1fv(l,new Float32Array(i)),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.deleteBuffer(n),e.deleteBuffer(s),e.disableVertexAttribArray(o),e.disableVertexAttribArray(c)}function Xi(e,t,r,i,a,n,o){var s=Li(e,t),c=s.pointBuffer,u=s.a_position,l=s.texBuffer,h=s.a_texCoords,d=Math.sin(a)/o,f=Math.cos(a)/n,m=t.uniform.u_velocity;e.uniform2f(m,d,f);var p=Math.floor(i);if(p!==t.uniformValue.u_radius){var g=t.uniform.u_radius;e.uniform1i(g,p)}Si(e,r,0);var v=t.uniform.u_texture;e.uniform1i(v,0),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.deleteBuffer(c),e.deleteBuffer(l),e.disableVertexAttribArray(u),e.disableVertexAttribArray(h)}function ji(e,t,r,i,a,n,o,s){return void 0===s&&(s=!0),i&&1!==i&&(e/=i,t/=i,r/=i),o&&(r/=-o),{x:(e=e===a?0:(e-a)/a)*i,y:(t=t===n?0:s?(n-t)/n:(t-n)/n)*i,z:r*i,w:i}}function Gi(e,t,r,i,a,n,o,s){void 0===i&&(i=0),void 0===a&&(a=0),void 0===o&&(o=0),void 0===s&&(s=0);var c=Tt(e[0]+i,e[1]+a,e[2]+i,e[3]+a,n),u=c.x1,l=c.y1,h=c.z1,d=c.w1,f=c.x2,m=c.y2,p=c.z2,g=c.w2,v=c.x3,y=c.y3,b=c.z3,x=c.w3,T=c.x4,w=c.y4,k=c.z4,S=c.w4,E=Math.max(h||0,p||0,b||0,k||0,Math.sqrt(t*t+r*r));return{t1:ji(u+o,l+s,h||0,d||1,t,r,E),t2:ji(f+o,m+s,p||0,g||1,t,r,E),t3:ji(v+o,y+s,b||0,x||1,t,r,E),t4:ji(T+o,w+s,k||0,S||1,t,r,E)}}var Yi=new WeakMap,qi=new WeakMap,Ki=new WeakMap,$i=new WeakMap,Qi=0,Zi=function(){function e(e,t,r,i){this.id=Qi++,this.gl=e,this.bbox=t.slice(0);var a=t[2],n=t[3];if(this.list=[],r)if(this.available=!0,r instanceof xi){this.canvasCache=r;for(var o=r.list,s=r.w,c=r.h,u=o.length,l=(t[2]-t[0])/s,h=(t[3]-t[1])/c,d=0;d<u;d++){var f=o[d],m=ki(e,0,f.os.canvas);this.list.push({bbox:new Float32Array([f.x*l,f.y*h,Math.min(a,(f.x+f.w)*l),Math.min(n,(f.y+f.h)*h)]),w:f.w,h:f.h,t:m,tc:i})}}else{m=ki(e,0,r);r instanceof HTMLImageElement?(this.image=r,this.list.push({bbox:new Float32Array(t),w:r.width,h:r.height,t:m,tc:i})):r instanceof VideoFrame?(this.videoFrame=r,this.list.push({bbox:new Float32Array(t),w:r.codedWidth,h:r.codedHeight,t:m,tc:i})):r instanceof HTMLCanvasElement&&(this.canvas=r,this.list.push({bbox:new Float32Array(t),w:r.width,h:r.height,t:m,tc:i}))}else this.available=!1}return e.prototype.release=function(){var e=this;return this.image?this.releaseImg(this.image):this.videoFrame?this.releaseVideoFrame(this.videoFrame):this.canvasCache?this.releaseCanvasCache(this.canvasCache):!!this.available&&(this.available=!1,this.list.splice(0).forEach(function(t){t.t&&e.gl.deleteTexture(t.t)}),!0)},e.prototype.releaseImg=function(e){var t=this;if(!this.available)return!1;this.available=!1;var r=qi.get(e);return!!r&&(r.count--,r.count||(qi.delete(e),this.list.splice(0).forEach(function(e){e.t&&t.gl.deleteTexture(e.t)})),!0)},e.prototype.releaseVideoFrame=function(e){var t=this;if(!this.available)return!1;this.available=!1;var r=Ki.get(e);return!!r&&(r.count--,r.count||(Ki.delete(e),this.list.splice(0).forEach(function(e){e.t&&t.gl.deleteTexture(e.t)})),!0)},e.prototype.releaseCanvasCache=function(e){var t=this;if(!this.available)return!1;this.available=!1;var r=Yi.get(e);return!!r&&(r.count--,r.count||(Yi.delete(e),this.list.splice(0).forEach(function(e){e.t&&t.gl.deleteTexture(e.t)})),!0)},e.hasCanvasCacheInstance=function(e){return Yi.has(e)},e.getCanvasCacheInstance=function(t,r,i){var a=Yi.get(r);if(a){a.count++;var n=new e(t,i);n.available=!0,n.canvasCache=r;for(var o=i[2]-i[0],s=i[3]-i[1],c=o/a.w,u=s/a.h,l=i[2],h=i[3],d=a.value,f=d.length,m=0;m<f;m++){var p=d[m];n.list.push({bbox:new Float32Array([p.x*c,p.y*u,Math.min(l,(p.x+p.w)*c),Math.min(h,(p.y+p.h)*u)]),w:p.w,h:p.h,t:p.t})}return n}var g=new e(t,i,r);return Yi.set(r,{value:g.list.map(function(e,t){return{x:r.list[t].x,y:r.list[t].y,w:e.w,h:e.h,t:e.t}}),w:r.w,h:r.h,count:1}),g},e.hasImageCache=function(e){return qi.has(e)},e.getImgInstance=function(t,r,i,a){var n=qi.get(r);if(n){n.count++;var o=new e(t,i);return o.available=!0,o.image=r,o.list=[{bbox:i.slice(0),w:r.width,h:r.height,t:n.t,tc:a}],o}var s=new e(t,i,r,a);return qi.set(r,{t:s.list[0].t,count:1}),s},e.hasVideoFrameInstance=function(e){return Ki.has(e)},e.getVideoFrameInstance=function(t,r,i,a){var n=Ki.get(r);if(n){n.count++;var o=new e(t,i);return o.available=!0,o.videoFrame=r,o.list=[{bbox:i.slice(0),w:r.codedWidth,h:r.codedHeight,t:n.t,tc:a}],o}var s=new e(t,i,r,a);return Ki.set(r,{t:s.list[0].t,count:1}),s},e.getCanvasInstance=function(t,r,i,a){var n=$i.get(r);if(n){n.count++;var o=new e(t,i);return o.available=!0,o.canvas=r,o.list=[{bbox:i.slice(0),w:r.width,h:r.height,t:n.t,tc:a}],o}var s=new e(t,i,r,a);return $i.set(r,{t:s.list[0].t,count:1}),s},e.getEmptyInstance=function(t,r){return new e(t,r)},e}(),Ji=.1,ea="function"==typeof Float32Array;function ta(e,t){return 1-3*t+3*e}function ra(e,t){return 3*t-6*e}function ia(e){return 3*e}function aa(e,t,r){return((ta(t,r)*e+ra(t,r))*e+ia(t))*e}function na(e,t,r){return 3*ta(t,r)*e*e+2*ra(t,r)*e+ia(t)}function oa(e){return e}function sa(e,t,r,i){if(!(0<=e&&e<=1&&0<=r&&r<=1))throw new Error("bezier x values must be in [0, 1] range");if(e===t&&r===i)return oa;for(var a=ea?new Float32Array(11):new Array(11),n=0;n<11;++n)a[n]=aa(n*Ji,e,r);function o(t){for(var i=0,n=1;10!==n&&a[n]<=t;++n)i+=Ji;--n;var o=i+(t-a[n])/(a[n+1]-a[n])*Ji,s=na(o,e,r);return s>=.001?function(e,t,r,i){for(var a=0;a<4;++a){var n=na(t,r,i);if(0===n)return t;t-=(aa(t,r,i)-e)/n}return t}(t,o,e,r):0===s?o:function(e,t,r,i,a){var n,o,s=0;do{(n=aa(o=t+(r-t)/2,i,a)-e)>0?r=o:t=o}while(Math.abs(n)>1e-7&&++s<10);return o}(t,i,i+Ji,e,r)}return function(e){return 0===e||1===e?e:aa(o(e),t,i)}}var ca={linear:sa(1,1,0,0),easeIn:sa(.42,0,1,1),easeOut:sa(0,0,.58,1),ease:sa(.25,.1,.25,1),easeInOut:sa(.42,0,.58,1),cubicBezier:sa,getEasing:function(e,t,r,i){if(4===arguments.length)return sa(e,t,r,i);if(Array.isArray(e)&&4===e.length)return sa(e[0],e[1],e[2],e[3]);if(e){var a=e.toString(),n=void 0;if(/^\s*(?:cubic-bezier\s*)?\(\s*[\d.]+\s*,\s*[-\d.]+\s*,\s*[\d.]+\s*,\s*[-\d.]+\s*\)\s*$/i.test(a)){var o=a.match(/[\d.]+/g);n=sa(parseFloat(o[0]),parseFloat(o[1]),parseFloat(o[2]),parseFloat(o[3]))}return n}}},ua="frame",la="begin",ha={FRAME:ua,BEGIN:la,END:"end"},da=function(e){function r(t,r){var i=e.call(this)||this;return i.node=t,i.duration=r.duration||0,i.direction=r.direction||"forwards",i.fill=r.fill||"none",i.delay=Math.max(0,r.delay||0),i.endDelay=Math.max(0,r.endDelay||0),r.easing&&(v(r.easing)?i.easing=r.easing:Array.isArray(r.easing)?i.easing=ca.getEasing(r.easing):i.easing=ca[r.easing]),i.iterations=r.iterations||1,i.playbackRate=r.playbackRate||1,i._currentTime=0,i.time=0,i._playCount=r.iterationStart||0,i._playState="idle",i.isBegin=0===i._playCount&&!i.delay,i.isEnd=!1,i.isFirstInDelay=!0,i}return t(r,e),r.prototype.play=function(){var e,t=this._playState;"running"!==t&&("finished"!==t&&"idle"!==t||(this._playCount=0,this._currentTime=0,this.time=0,this.isBegin=!this.delay,this.isEnd=!1,this.isFirstInDelay=!0),this._playState="running",null===(e=this.node.root)||void 0===e||e.addAnimation(this))},r.prototype.pause=function(){var e;"paused"!==this._playState&&(this._playState="paused",null===(e=this.node.root)||void 0===e||e.removeAnimation(this))},r.prototype.resume=function(){var e;"paused"===this._playState&&(this._playState="running",null===(e=this.node.root)||void 0===e||e.addAnimation(this))},r.prototype.finish=function(){var e;"finished"!==this._playState&&(this._playCount=this.iterations,this._currentTime=this.delay+this.duration*this._playCount+this.endDelay,this.time=this.duration+this.endDelay,this._playState="finished",null===(e=this.node.root)||void 0===e||e.removeAnimation(this))},r.prototype.cancel=function(){var e;"idle"!==this._playState&&(this._playCount=0,this._currentTime=0,this.time=0,this._playState="idle",null===(e=this.node.root)||void 0===e||e.removeAnimation(this))},r.prototype.remove=function(){var e;this.cancel();var t=this.node.animationList,r=t.indexOf(this);r>-1&&t.splice(r,1),null===(e=this.node.root)||void 0===e||e.aniController.removeAni(this)},r.prototype.gotoAndPlay=function(e){if(this._currentTime!==e||"running"!==this._playState){this.play();var t=this._currentTime;this.currentTime=e,this.onRunning(0,t)}},r.prototype.gotoAndStop=function(e){if(this._currentTime!==e||"paused"!==this._playState){this.pause();var t=this._currentTime;this.currentTime=e,this.onRunning(0,t)}},r.prototype.onRunning=function(e,t){var r=this,i=r.playbackRate,a=r.delay,n=r.endDelay,o=r.duration,s=r.iterations;i>0&&1!==i&&(e*=i),t=null!=t?t:this._currentTime;var c=this._currentTime+=e;if(a&&c<a)this.isFirstInDelay&&this.onFirstInDelay();else{this.isFirstInDelay=!1,a&&t<a&&c>=a&&(this.isBegin=!0),c-=a;var u=Math.min(s-1,Math.floor(c/o));c-=o*u,this.time=c,this._playCount<u&&(this._playCount=u,this.onChangePlayCount(),this.isBegin=!0),this._playCount>=s-1&&(t-=a,t-=o*u,n&&t<o&&c>=o&&c<o+n&&this.onFirstInEndDelay(),t<o&&c>=o&&(this.isEnd=!0),c>=o+n&&this.finish())}},r.prototype.afterRunning=function(){this.emit(ua),this.isFirstInDelay&&(this.isFirstInDelay=!1),this.isBegin&&(this.isBegin=!1,this.emit(la,this._playCount,this.time)),this.isEnd&&(this.isEnd=!1,this.emit("end"))},Object.defineProperty(r.prototype,"currentTime",{get:function(){return this._currentTime},set:function(e){var t=this._currentTime;if(e!==t){var r=this.delay;this._currentTime=e;var i=t-r;this.time=i%this.duration,e<=r&&(this.isBegin=!0),t>=r&&e<r&&(this.isFirstInDelay=!0)}},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"playCount",{get:function(){return this._playCount},set:function(e){if(e!==this._playCount){var t=this._currentTime,r=this.delay;if(t>=r){var i=(t-r)%this.duration;this.currentTime=i+r+e*this.duration,this.time=i}this._playCount=e}},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"playState",{get:function(){return this._playState},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"pending",{get:function(){return"running"!==this._playState},enumerable:!1,configurable:!0}),r}(M),fa=function(e){function r(t,r,i){var a=e.call(this,t,i)||this;return a._keyFrames=[],a._keyFramesR=[],a.currentKeyFrames=a._keyFrames,a.originStyle={},a.initKeyFrames(r),a.setCurrentFrames(),a}return t(r,e),r.prototype.initKeyFrames=function(e){var t=function(e,t,r,i){for(var a=[],n=0,o=0,s=t.length;o<s;o++){var c=t[o];if(y(c.offset)){var u=c.offset;if(u<0||u>1)continue;if(u<=n&&o)continue;n=u}a.push(Object.assign({},c))}if(1===a.length){a.push(Object.assign({},a[0]));var l=Object.assign({},a[0]);1===a[0].offset?(l.offset=0,a.unshift(l)):(l.offset=1,a.push(l))}var h=a[0];h.offset&&h.offset>0?a.unshift({offset:0}):h.offset=0;var d=a[a.length-1];d.offset&&d.offset<1?a.push({offset:1}):d.offset=1;for(o=1,s=a.length;o<s;o++){c=a[o];if(!y(c.offset)){for(var f=void 0,m=o+1;m<s&&!(f=a[m]).offset;m++);for(var p=m-o+1,b=a[o-1],x=(f.offset-b.offset)/p,T=o;T<m;T++)a[T].offset=b.offset+x*(T+1-o);o=m}}var w=[],k={},S=[];for(o=0,s=a.length;o<s;o++){c=a[o];var E=ui.normalize(c);Object.keys(E).forEach(function(e){k.hasOwnProperty(e)||(k[e]=!0,S.push(e))});var C={style:E,time:c.offset*r,easing:i,transition:[],fixed:[]};c.easing&&(v(c.easing)?C.easing=c.easing:Array.isArray(c.easing)?C.easing=ca.getEasing(c.easing):g(c.easing)&&(C.easing=ca[c.easing])),w.push(C)}w.forEach(function(t){var r=t.style;S.forEach(function(t){r.hasOwnProperty(t)||Object.assign(r,ti(e.style,[t]))})});var A=w.map(function(e){return Object.assign({},e,{transition:[],fixed:[]})}).reverse();A.forEach(function(e){e.time=r-e.time});var _=ti(e.style,S);return{keys:S,keyFrames:w,keyFramesR:A,originStyle:_}}(this.node,e,this.duration,this.easing),r=t.keys,i=t.keyFrames,a=t.keyFramesR,n=t.originStyle;this._keyFrames=i,this._keyFramesR=a,ma(this.node,this._keyFrames,r),ma(this.node,this._keyFramesR,r),this.originStyle=n},r.prototype.finish=function(){"finished"!==this._playState&&(e.prototype.finish.call(this),this.onFirstInEndDelay())},r.prototype.cancel=function(){"idle"!==this._playState&&(e.prototype.cancel.call(this),this.node.updateFormatStyle(this.originStyle))},r.prototype.setCurrentFrames=function(){var e=this,t=e.direction,r=e._keyFrames,i=e._keyFramesR,a=e._playCount;this.currentKeyFrames="backwards"===t?i:"alternate"===t?a%2==0?r:i:"alternateReverse"===t&&a%2==0?i:r},r.prototype.onRunning=function(t,r){e.prototype.onRunning.call(this,t,r);var i=this,a=i.duration,n=i.delay,o=i.iterations,s=i.time;if(!(this._currentTime<n)){var c,u=this._playCount>=o-1,l=this.currentKeyFrames,h=l.length;c=2===h?s<a?0:1:function(e,t,r,i){for(;e<t;){if(e===t-1)return i[t].time<=r?t:e;var a=e+(t-e>>1),n=i[a].time;if(n===r)return a;n>r?t=Math.max(a-1,e):e=Math.min(a,t)}return e}(0,h-1,s,l);var d=l[c],f=u&&c===h-1,m=0;if(f);else if(2===h)m=s/a;else{var p=d.time,g=l[c+1].time-p;m=(s-p)/g}if(f);else{d.easing?m=d.easing(m):this.easing&&(m=this.easing(m));var v=d.transition,y=d.fixed,b=d.style,x={};v.forEach(function(e){var t=e.key,r=e.diff;if("opacity"===t||"translateX"===t||"translateY"===t||"translateZ"===t||"scaleX"===t||"scaleY"===t||"rotateX"===t||"rotateY"===t||"rotateZ"===t||"perspective"===t||"perspectiveSelf"===t)(a=Object.assign({},b[t])).v+=r*m,x[t]=a;else if("transformOrigin"===t||"perspectiveOrigin"===t){var i=b[t];(a=[Object.assign({},i[0]),Object.assign({},i[1])])[0].v+=r[0]*m,a[1].v+=r[1]*m,x[t]=a}else if("filter"===t){var a;(a=ti(b,t).filter).forEach(function(e,t){var i=r[t];i&&(e.u===V.GAUSS_BLUR&&(e.v.radius.v+=i.radius*m),e.u===V.RADIAL_BLUR?(e.v.radius.v+=i.radius*m,e.v.center[0].v+=i.center[0]*m,e.v.center[1].v+=i.center[1]*m):e.u===V.MOTION_BLUR?(e.v.radius.v+=i.radius*m,e.v.angle.v+=i.angle*m,e.v.offset.v+=i.offset*m):e.u===V.BLOOM?(e.v.threshold.v+=i.threshold*m,e.v.knee.v+=i.knee*m):e.u===V.LIGHT_DARK?(e.v.radius.v+=i.radius*m,e.v.angle.v+=i.angle*m):e.u!==V.HUE_ROTATE&&e.u!==V.SATURATE&&e.u!==V.BRIGHTNESS&&e.u!==V.CONTRAST&&e.u!==V.SEPIA||(e.v.radius.v+=i.radius*m))}),x[t]=a}}),y.forEach(function(e){x[e]=Object.assign({},b[e])}),this.node.updateFormatStyle(x)}}},r.prototype.onFirstInDelay=function(){var e=this.fill,t=this.node;"backwards"===e||"both"===e?t.updateFormatStyle(this.currentKeyFrames[0].style):t.updateFormatStyle(this.originStyle)},r.prototype.onFirstInEndDelay=function(){var e=this.fill,t=this.node;if("forwards"===e||"both"===e){var r=this.currentKeyFrames;t.updateFormatStyle(r[r.length-1].style)}else t.updateFormatStyle(this.originStyle)},r.prototype.onChangePlayCount=function(){this.setCurrentFrames()},r}(da);function ma(e,t,r){for(var i=function(i,a){var n=t[i-1],o=t[i],s=n.style,c=o.style;r.forEach(function(t){var r=s[t],a=c[t];if("opacity"===t||"scaleX"===t||"scaleY"===t||"rotateX"===t||"rotateY"===t||"rotateZ"===t)n.transition.push({key:t,diff:a.v-r.v});else if("translateX"===t||"translateY"===t||"translateZ"===t||"perspective"===t||"perspectiveSelf"===t)if(r.u===a.u)n.transition.push({key:t,diff:a.v-r.v});else{var u=0;"translateX"===t||"translateZ"===t||"perspective"===t||"perspectiveSelf"===t?u=e.computedStyle.width:"translateY"===t&&(u=e.computedStyle.height),n.transition.push({key:t,diff:pa(r,a,u)})}else if("transformOrigin"===t||"perspectiveOrigin"===t){for(var l=r,h=a,d=[0,0],f=0;f<2;f++)if(l[f].u===h[f].u)d.push(h[f].v-l[f].v);else{u=f?e.computedStyle.height:e.computedStyle.width;n.transition.push({key:t,diff:pa(h[f],l[f],u)})}n.transition.push({key:t,diff:d})}else if("visibility"===t||"overflow"===t)o.fixed.push(t),1===i&&n.fixed.push(t);else if("filter"===t){for(var m=r,p=a,g=!0,v=0,y=Math.min(m.length,p.length);v<y;v++)if(m[v].u!==p[v].u){g=!1;break}if(g){d=[];for(var b=0,x=Math.min(m.length,p.length);b<x;b++){var T=m[b],w=p[b],k={};T.u===V.GAUSS_BLUR?k.radius=w.v.radius.v-T.v.radius.v:T.u===V.RADIAL_BLUR?(k.radius=w.v.radius.v-T.v.radius.v,k.center=[pa(w.v.center[0],T.v.center[0],e.computedStyle.width),pa(w.v.center[1],T.v.center[1],e.computedStyle.height)]):T.u===V.MOTION_BLUR?(k.radius=w.v.radius.v-T.v.radius.v,k.angle=w.v.angle.v-T.v.angle.v,k.offset=w.v.offset.v-T.v.offset.v):T.u===V.BLOOM?(k.threshold=w.v.threshold.v-T.v.threshold.v,k.knee=w.v.knee.v-T.v.knee.v):T.u===V.LIGHT_DARK?(k.radius=w.v.radius.v-T.v.radius.v,k.angle=w.v.angle.v-T.v.angle.v):T.u!==V.HUE_ROTATE&&T.u!==V.SATURATE&&T.u!==V.BRIGHTNESS&&T.u!==V.CONTRAST&&T.u!==V.SEPIA||(k.radius=w.v.radius.v-T.v.radius.v),d.push(k)}n.transition.push({key:t,diff:d})}else o.fixed.push(t),1===i&&n.fixed.push(t)}})},a=1,n=t.length;a<n;a++)i(a)}function pa(e,t,r){if(e.u===V.PX){if(t.u===V.PERCENT)return.01*t.v*r-e.v}else if(e.u===V.PERCENT&&t.u===V.PX)return 100*t.v/r-e.v;return 0}function ga(e){return e.map(function(e){if(Array.isArray(e.v))return e.v.slice(0);var t=e.v;return{t:t.t,d:t.d.slice(0),stops:t.stops.map(function(e){var t=.01*e.offset.v;return{color:e.color.v.slice(0),offset:t}})}})}function va(e){return e.map(function(e){if(Array.isArray(e.v))return e.v.slice(0);var t=e.v;return{t:t.t,d:t.d.slice(0),stops:t.stops.map(function(e){var t=e.offset?.01*e.offset.v:void 0;return{color:e.color.v.slice(0),offset:t}})}})}function ya(e,t,r){return e.map(function(e){var i=e.v,a=e.u;if(a===V.GAUSS_BLUR)return{radius:n=i.radius.u===V.PERCENT?i.radius.v*t*.01:i.radius.v,u:a};if(a===V.RADIAL_BLUR){var n=i.radius.u===V.PERCENT?i.radius.v*t*.01:i.radius.v,o=i.center.map(function(e,i){return e.u===V.PERCENT?e.v*(i?r:t)*.01:e.v});return{radius:n,center:o,u:a}}return a===V.MOTION_BLUR?{radius:n=i.radius.u===V.PERCENT?i.radius.v*t*.01:i.radius.v,angle:i.angle.v,offset:i.offset.v,u:a}:a===V.BLOOM?{threshold:i.threshold.v,knee:i.knee.v,u:a}:a===V.LIGHT_DARK?{radius:i.radius.v,angle:i.angle.v,u:a}:a===V.HUE_ROTATE||a===V.SATURATE||a===V.BRIGHTNESS||a===V.CONTRAST||a===V.SEPIA?{radius:i.radius.v,u:a}:void 0})}function ba(e,t,r,i){if(void 0===r&&(r=0),void 0===i&&(i=0),t&&t.length){for(var a=-1,n=0,o=t.length;n<o;n++){var s=t[n];if(Array.isArray(s)&&s.length){a=n;break}}if(-1!==a){var c=t[a];4===c.length?e.moveTo(c[2]+r,c[3]+i):6===c.length?e.moveTo(c[4]+r,c[5]+i):e.moveTo(c[0]+r,c[1]+i);for(n=a+1,o=t.length;n<o;n++){s=t[n];Array.isArray(s)&&(2===s.length?e.lineTo(s[0]+r,s[1]+i):4===s.length?e.quadraticCurveTo(s[0]+r,s[1]+i,s[2]+r,s[3]+i):6===s.length&&e.bezierCurveTo(s[0]+r,s[1]+i,s[2]+r,s[3]+i,s[4]+r,s[5]+i))}}}}function xa(e){switch(e){case j.MULTIPLY:return"multiply";case j.SCREEN:return"screen";case j.OVERLAY:return"overlay";case j.DARKEN:return"darken";case j.LIGHTEN:return"lighten";case j.COLOR_DODGE:return"color-dodge";case j.COLOR_BURN:return"color-burn";case j.HARD_LIGHT:return"hard-light";case j.SOFT_LIGHT:return"soft-light";case j.DIFFERENCE:return"difference";case j.EXCLUSION:return"exclusion";case j.HUE:return"hue";case j.SATURATION:return"saturation";case j.COLOR:return"color";case j.LUMINOSITY:return"luminosity";default:return"source-over"}}var Ta,wa=0,ka=function(e){function r(t){var r,i=e.call(this)||this;return i.id=wa++,i.props=t,i.uuid=t.uuid||(l.randomUUID&&!r?l.randomUUID():h(r)),i.name=t.name,i.isLocked=!!t.isLocked,i.style=Gr(R(t.style)),i.computedStyle={},i.struct={node:i,num:0,total:0,lv:0,next:0},i.isMounted=!1,i.isDestroyed=!1,i.refreshLevel=ci.REFLOW,i._opacity=0,i.hasCacheOp=!1,i.localOpId=0,i.parentOpId=0,i.transform=at(),i.matrix=at(),i._matrixWorld=at(),i.hasCacheMw=!1,i.localMwId=0,i.parentMwId=0,i.hasContent=!1,i.animationList=[],i.contentLoadingNum=0,i.tempOpacity=1,i.tempMatrix=at(),i}return t(r,e),r.prototype.didMount=function(){var e=this;this.isMounted=!0;var t=this.parent;if(t){this.parentOpId=t.localOpId,this.parentMwId=t.localMwId;var r=this.root=t.root,i=this.uuid;r&&i&&(r.refs[i]=this),this.animationList.forEach(function(t){e.root.aniController.addAni(t)})}},r.prototype.didUnmount=function(){this.clearTexCache(!0),this.isMounted=!1;var e=this.root,t=this.uuid;e&&t&&delete e.refs[t],this.animationList.forEach(function(t){t.cancel(),e.aniController.removeAni(t)}),this.prev=this.next=void 0,this.parent=this.root=void 0},r.prototype.structure=function(e){var t=this.struct;return t.lv=e,[t]},r.prototype.lay=function(e){var t=this.style,r=this.computedStyle,i=t.left,a=t.top,n=t.right,o=t.bottom,s=t.width,c=t.height,u=!1,l=!1,h=!1,d=!1;i.u!==V.AUTO&&(u=!0,r.left=ri(i,e.w)),n.u!==V.AUTO&&(h=!0,r.right=ri(n,e.w)),a.u!==V.AUTO&&(l=!0,r.top=ri(a,e.h)),o.u!==V.AUTO&&(d=!0,r.bottom=ri(o,e.h)),u&&h?r.width=Math.max(0,e.w-r.left-r.right):u?(s.u!==V.AUTO?r.width=Math.max(0,ri(s,e.w)):r.width=0,r.right=e.w-r.left-r.width):h?(s.u!==V.AUTO?r.width=Math.max(0,ri(s,e.w)):r.width=0,r.left=e.w-r.right-r.width):(s.u!==V.AUTO?r.width=Math.max(0,ri(s,e.w)):r.width=0,r.left=0,r.right=e.w-r.width),l&&d?r.height=Math.max(0,e.h-r.top-r.bottom):l?(c.u!==V.AUTO?r.height=Math.max(0,ri(c,e.h)):r.height=0,r.bottom=e.h-r.top-r.height):d?(c.u!==V.AUTO?r.height=Math.max(0,ri(c,e.h)):r.height=0,r.top=e.h-r.bottom-r.height):(c.u!==V.AUTO?r.height=Math.max(0,ri(c,e.h)):r.height=0,r.top=0,r.bottom=e.h-r.height)},r.prototype.layout=function(e){if(this.isDestroyed)throw new Error("Node is destroyed");this.refreshLevel=ci.REFLOW,this.calReflowStyle(),this.lay(e),this.calRepaintStyle(ci.REFLOW),this._rect=void 0},r.prototype.calReflowStyle=function(){var e=this,t=e.style,r=e.computedStyle,i=e.parent;r.fontFamily=t.fontFamily.v,r.fontSize=t.fontSize.v,r.fontWeight=t.fontWeight.v,r.fontStyle=t.fontStyle.v;var a=t.lineHeight;a.u===V.AUTO?r.lineHeight=Kr(r):r.lineHeight=a.v,r.width=r.height=0;var n=t.width,o=t.height;i?(n.u!==V.AUTO&&(r.width=Math.max(0,ri(n,i.width))),o.u!==V.AUTO&&(r.height=Math.max(0,ri(o,i.height)))):(n.u===V.PX&&(r.width=Math.max(0,n.v)),o.u===V.PX&&(r.height=Math.max(0,o.v))),r.letterSpacing=t.letterSpacing.v,r.paragraphSpacing=t.paragraphSpacing.v,r.textAlign=t.textAlign.v,r.textVerticalAlign=t.textVerticalAlign.v},r.prototype.calRepaintStyle=function(e){var t=this.style,r=this.computedStyle;r.visibility=t.visibility.v,r.textDecoration=t.textDecoration.map(function(e){return e.v}),r.textShadow=t.textShadow.v,r.color=t.color.v,r.backgroundColor=t.backgroundColor.v,r.fill=ga(t.fill),r.fillEnable=t.fillEnable.map(function(e){return e.v}),r.fillOpacity=t.fillOpacity.map(function(e){return e.v}),r.fillMode=t.fillMode.map(function(e){return e.v}),r.fillRule=t.fillRule.v,r.stroke=va(t.stroke),r.strokeEnable=t.strokeEnable.map(function(e){return e.v}),r.strokeWidth=t.strokeWidth.map(function(e){return e.v}),r.strokePosition=t.strokePosition.map(function(e){return e.v}),r.strokeMode=t.strokeMode.map(function(e){return e.v}),r.strokeDasharray=t.strokeDasharray.map(function(e){return e.v}),r.strokeLinecap=t.strokeLinecap.v,r.strokeLinejoin=t.strokeLinejoin.v,r.strokeMiterlimit=t.strokeMiterlimit.v,r.mixBlendMode=t.mixBlendMode.v,r.pointerEvents=t.pointerEvents.v,r.objectFit=t.objectFit.v,r.borderTopLeftRadius=t.borderTopLeftRadius.v,r.borderTopRightRadius=t.borderTopRightRadius.v,r.borderBottomLeftRadius=t.borderBottomLeftRadius.v,r.borderBottomRightRadius=t.borderBottomRightRadius.v,r.overflow=t.overflow.v,this.clearTexCache(!0),e&ci.REFLOW_TRANSFORM&&this.calMatrix(e),e&ci.REFLOW_PERSPECTIVE&&this.calPerspective(),e&ci.REFLOW_PERSPECTIVE_SELF&&this.calPerspectiveSelf(),e&ci.REFLOW_OPACITY&&this.calOpacity(),e&ci.REFLOW_FILTER&&this.calFilter(e),e&ci.REFLOW_REPAINT_MASK&&this.calMask(),this._bbox=void 0,this._bboxInt=void 0,this._filterBbox=void 0,this._filterBboxInt=void 0,this.tempBbox=void 0},r.prototype.calMask=function(){var e=this.style,t=this.computedStyle;t.maskMode=e.maskMode.v,t.breakMask=e.breakMask.v;var r=this.prev;if(r&&!t.breakMask&&(r.computedStyle.maskMode?this.mask=r:r.mask&&(this.mask=r.mask)),t.maskMode){this.mask=void 0;for(var i=this.next;i;){if(i.computedStyle.maskMode){i.mask=this;break}if(i.computedStyle.breakMask)break;i.mask=this,i=i.next}}else{var a=t.breakMask?void 0:this.mask;this.mask=a;for(i=this.next;i;){if(i.computedStyle.maskMode){i.mask=a;break}if(i.computedStyle.breakMask)break;i.mask=a,i=i.next}}this.clearMask()},r.prototype.calFilter=function(e){var t,r=this.style,i=this.computedStyle;i.filter=ya(r.filter,i.width,i.height),e<ci.REPAINT&&(this._filterBbox=void 0,this._filterBboxInt=void 0,this.tempBbox=void 0,null===(t=this.textureFilter)||void 0===t||t.release(),this.resetTextureTarget())},r.prototype.calMatrix=function(e){var t=this,r=this,i=r.style,a=r.computedStyle,n=r.matrix,o=r.transform;!this.hasCacheMw&&this.localMwId||(this.hasCacheMw=!1,this.localMwId++);var s=!0;if((e>=ci.REFLOW||e&ci.SCALE_X&&!a.scaleX||e&ci.SCALE_Y&&!a.scaleY||e&ci.ROTATE_Z&&(a.rotateX||a.rotateY||a.skewX||a.skewY)||e&ci.ROTATE_X||e&ci.ROTATE_Y)&&(s=!1),s){if(e&ci.TRANSLATE_X){var c=(u=ri(i.translateX,this.computedStyle.width))-a.translateX;a.translateX=u,o[12]+=c,n[12]+=c}if(e&ci.TRANSLATE_Y){c=(u=ri(i.translateY,this.computedStyle.height))-a.translateY;a.translateY=u,o[13]+=c,n[13]+=c}if(e&ci.ROTATE_Z){var u=i.rotateZ.v;a.rotateZ=u;var l=fr(u),h=Math.sin(l),d=Math.cos(l),f=a.scaleX,m=a.scaleY;n[0]=o[0]=d*f,n[1]=o[1]=h*m,n[4]=o[4]=-h*f,n[5]=o[5]=d*m;var p=(y=a.transformOrigin)[0],g=y[1];n[12]=o[12]+p-o[0]*p-g*o[4],n[13]=o[13]+g-o[1]*p-g*o[5]}if(e&ci.SCALE){if(e&ci.SCALE_X){f=(u=i.scaleX.v)/a.scaleX;a.scaleX=u,o[0]*=f,o[4]*=f,n[0]*=f,n[4]*=f}if(e&ci.SCALE_Y){m=(u=i.scaleY.v)/a.scaleY;a.scaleY=u,o[1]*=m,o[5]*=m,n[1]*=m,n[5]*=m}p=(y=a.transformOrigin)[0],g=y[1];n[12]=o[12]+p-o[0]*p-o[4]*g,n[13]=o[13]+g-o[1]*p-o[5]*g,n[14]=o[14]-o[2]*p-o[6]*g}if(e&ci.TRANSFORM_ORIGIN){var v=i.transformOrigin.map(function(e,r){return ri(e,r?t.computedStyle.height:t.computedStyle.width)});ut(n,y=_r(o,v[0],v[1]))}}else{st(o);v=i.transformOrigin.map(function(e,r){return ri(e,r?t.computedStyle.height:t.computedStyle.width)});a.transformOrigin=v,a.translateX=ri(i.translateX,this.computedStyle.width),a.translateY=ri(i.translateY,this.computedStyle.height),a.translateZ=ri(i.translateZ,this.computedStyle.width);var y,b=i.rotateX?i.rotateX.v:0,x=i.rotateY?i.rotateY.v:0,T=i.rotateZ?i.rotateZ.v:0,w=i.skewX?i.skewX.v:0,k=i.skewY?i.skewY.v:0,S=i.scaleX?i.scaleX.v:1,E=i.scaleY?i.scaleY.v:1;a.rotateX=b,a.rotateY=x,a.rotateZ=T,a.skewX=w,a.skewY=k,a.scaleX=S,a.scaleY=E,Ir({translateX:a.left+a.translateX,translateY:a.top+a.translateY,translateZ:a.translateZ,rotateX:b,rotateY:x,rotateZ:T,skewX:w,skewY:k,scaleX:S,scaleY:E},o),ut(n,y=_r(o,v[0],v[1]))}},r.prototype.calPerspective=function(){var e=this,t=this.style,r=this.computedStyle;!this.hasCacheMw&&this.localMwId||(this.hasCacheMw=!1,this.localMwId++);var i=t.perspectiveOrigin.map(function(t,r){return ri(t,r?e.computedStyle.height:e.computedStyle.width)});r.perspectiveOrigin=i,r.perspective=ri(t.perspective,this.computedStyle.width),r.perspective>=1?this.perspectiveMatrix=Mr(r.perspective,i[0],i[1]):this.perspectiveMatrix=void 0},r.prototype.calPerspectiveSelf=function(){var e=this,t=e.style,r=e.computedStyle,i=e.transform;if(!this.hasCacheMw&&this.localMwId||(this.hasCacheMw=!1,this.localMwId++),r.perspectiveSelf=ri(t.perspectiveSelf,this.computedStyle.width),r.perspectiveSelf>=1){var a=r.transformOrigin;this.perspectiveMatrixSelf=Mr(r.perspectiveSelf,a[0]+i[12],a[1]+i[13])}else this.perspectiveMatrixSelf=void 0},r.prototype.calOpacity=function(){var e=this.style,t=this.computedStyle;!this.hasCacheOp&&this.localOpId||(this.hasCacheOp=!1,this.localOpId++),t.opacity=e.opacity.v},r.prototype.calContent=function(){var e=this.computedStyle;return this.hasContent=e.backgroundColor[3]>0,this.hasContent},r.prototype.calContentLoading=function(){var e=this.computedStyle;return e.width&&e.height?this.contentLoadingNum:0},r.prototype.renderCanvas=function(){var e=this.canvasCache;if(e&&e.available&&e.release(),this.hasContent){var t=this._bboxInt||this.bboxInt,r=t[0],i=t[1],a=t[2]-r,n=t[3]-i;(e=this.canvasCache=new xi(a,n,-r,-i)).available=!0,this.renderCanvasBgc(e)}},r.prototype.renderCanvasBgc=function(e){var t=this.computedStyle.backgroundColor;if(t[3]>0){var r=this.getBackgroundCoords(-e.dx,-e.dy);e.list.forEach(function(e){var i=e.x,a=e.y,n=e.os.ctx;n.fillStyle=fe(t),n.beginPath(),ba(n,r,-i,-a),n.closePath(),n.fill()})}},r.prototype.renderFillStroke=function(e,t,r){var i;if(void 0===t&&(t=!0),void 0===r&&(r=this.computedStyle),e.length){var a=this._bboxInt||this.bboxInt,n=a[0],o=a[1],s=a[2]-n,c=a[3]-o,u=-n,l=-o,h=r.fill,d=r.fillOpacity,f=r.fillRule,m=r.fillEnable,p=r.fillMode,g=r.stroke,v=r.strokeEnable,y=r.strokeWidth,b=r.strokePosition,x=r.strokeMode,T=r.strokeDasharray,w=r.strokeLinecap,k=r.strokeLinejoin,S=r.strokeMiterlimit,E=(null===(i=this.canvasCache)||void 0===i?void 0:i.available)?this.canvasCache:new xi(s,c,u,l);E.available=!0;for(var C=E.list,A=function(r,i){var a=C[r],n=a.x,o=a.y,E=a.os.ctx,A=-n,_=-o;E.setLineDash(T),E.beginPath(),e.forEach(function(e){ba(E,e,A,_)}),t&&E.closePath();for(var M=function(r,i){if(!m[r]||!d[r])return"continue";var a=h[r],n=void 0,o=p[r];if(E.globalAlpha=d[r],Array.isArray(a)){if(a[3]<=0)return"continue";E.fillStyle=fe(a)}else if(a.t===Y.LINEAR){var g=Hr(a.stops,a.d,0,0,s-2*u,c-2*l),v=E.createLinearGradient(g.x1+A,g.y1+_,g.x2+A,g.y2+_);g.stop.forEach(function(e){v.addColorStop(e.offset,fe(e.color))}),E.fillStyle=v}else if(a.t===Y.RADIAL){g=Xr(a.stops,a.d,0,0,s-2*u,c-2*l);var y=E.createRadialGradient(g.cx+A,g.cy+_,0,g.cx+A,g.cy+_,g.total);g.stop.forEach(function(e){y.addColorStop(e.offset,fe(e.color))});var b=g.matrix;if(b){var x=(n=oe.getOffscreenCanvas(s,c)).ctx;x.beginPath(),e.forEach(function(e){ba(x,e,A,_)}),t&&x.closePath(),x.clip(),x.fillStyle=y,x.setTransform(b[0],b[1],b[4],b[5],b[12],b[13]),x.fill(f===K.EVEN_ODD?"evenodd":"nonzero")}else E.fillStyle=y}else if(a.t===Y.CONIC){g=jr(a.stops,a.d,0,0,s-2*u,c-2*l);var T=E.createConicGradient(g.angle,g.cx+A,g.cy+_);g.stop.forEach(function(e){T.addColorStop(e.offset,fe(e.color))}),E.fillStyle=T}o!==j.NORMAL&&(E.globalCompositeOperation=xa(o)),n?(E.drawImage(n.canvas,0,0),n.release()):E.fill(f===K.EVEN_ODD?"evenodd":"nonzero"),o!==j.NORMAL&&(E.globalCompositeOperation="source-over")},I=0,R=h.length;I<R;I++)M(I);E.globalAlpha=1,E.globalCompositeOperation="source-over",w===Q.ROUND?E.lineCap="round":w===Q.SQUARE?E.lineCap="square":E.lineCap="butt",k===Z.ROUND?E.lineJoin="round":k===Z.BEVEL?E.lineJoin="bevel":E.lineJoin="miter",E.miterLimit=S;for(var P=function(r,i){if(!v[r]||!y[r])return"continue";var h=g[r],d=b[r];if(E.globalCompositeOperation=xa(x[r]),Array.isArray(h))E.strokeStyle=fe(h);else if(h.t===Y.LINEAR){var f=Hr(h.stops,h.d,0,0,s+2*n,c+2*o),m=E.createLinearGradient(f.x1+A,f.y1+_,f.x2+A,f.y2+_);f.stop.forEach(function(e){m.addColorStop(e.offset,fe(e.color))}),E.strokeStyle=m}else if(h.t===Y.RADIAL){f=Xr(h.stops,h.d,0,0,s-2*u,c-2*l);var p=E.createRadialGradient(f.cx+A,f.cy+_,0,f.cx+A,f.cy+_,f.total);f.stop.forEach(function(e){p.addColorStop(e.offset,fe(e.color))});var T=f.matrix;if(T){var w=oe.getOffscreenCanvas(a.w,a.h),k=w.ctx;return k.setLineDash(E.getLineDash()),k.lineCap=E.lineCap,k.lineJoin=E.lineJoin,k.miterLimit=E.miterLimit,k.lineWidth=y[r],k.strokeStyle="#FFF",k.beginPath(),e.forEach(function(e){ba(k,e,A,_)}),t&&k.closePath(),d===J.INSIDE&&t?(k.lineWidth=2*y[r],k.save(),k.clip(),k.stroke(),k.restore()):d===J.OUTSIDE&&t?(k.lineWidth=2*y[r],k.stroke(),k.save(),k.clip(),k.globalCompositeOperation="destination-out",k.strokeStyle="#FFF",k.stroke(),k.restore()):k.stroke(),k.fillStyle=p,k.globalCompositeOperation="source-in",k.setTransform(T[0],T[1],T[4],T[5],T[12],T[13]),k.fillRect(0,0,s,c),E.drawImage(w.canvas,0,0),w.release(),"continue"}E.strokeStyle=p}else if(h.t===Y.CONIC){f=jr(h.stops,h.d,0,0,s-2*u,c-2*l);var S=E.createConicGradient(f.angle,f.cx+A,f.cy+_);f.stop.forEach(function(e){S.addColorStop(e.offset,fe(e.color))}),E.strokeStyle=S}var C,M=void 0;d===J.INSIDE&&t?E.lineWidth=2*y[r]:d===J.OUTSIDE&&t?(M=oe.getOffscreenCanvas(a.w,a.h),(C=M.ctx).setLineDash(E.getLineDash()),C.lineCap=E.lineCap,C.lineJoin=E.lineJoin,C.miterLimit=E.miterLimit,C.strokeStyle=E.strokeStyle,C.lineWidth=2*y[r],C.beginPath(),e.forEach(function(e){ba(C,e,A,_)})):E.lineWidth=y[r],t&&C&&C.closePath(),d===J.INSIDE&&t?(E.save(),E.clip(),E.stroke(),E.restore()):d===J.OUTSIDE&&t?(C.stroke(),C.save(),C.clip(),C.globalCompositeOperation="destination-out",C.strokeStyle="#FFF",C.stroke(),C.restore(),E.drawImage(M.canvas,0,0),M.release()):E.stroke()},O=(I=0,g.length);I<O;I++)P(I);E.globalCompositeOperation="source-over"},_=0,M=C.length;_<M;_++)A(_)}},r.prototype.genTexture=function(e){var t;this.renderCanvas(),null===(t=this.textureCache)||void 0===t||t.release();var r=this.canvasCache;(null==r?void 0:r.available)?(this.textureTarget=this.textureCache=new Zi(e,this._bboxInt||this.bboxInt,r),r.release()):this.textureTarget=this.textureCache=void 0},r.prototype.resetTextureTarget=function(){var e=this,t=e.textureCache,r=e.textureTotal,i=e.textureFilter;(null==i?void 0:i.available)&&(this.textureTarget=i),(null==r?void 0:r.available)&&(this.textureTarget=r),(null==t?void 0:t.available)&&(this.textureTarget=t)},r.prototype.updateStyle=function(e,t){var r=Gr(e);return this.updateFormatStyle(r,t)},r.prototype.updateFormatStyle=function(e,t){var r,i=this.updateFormatStyleData(e);return i.length||t&&t(!0),null===(r=this.root)||void 0===r?void 0:r.addUpdate(this,i,void 0,t)},r.prototype.updateFormatStyleData=function(e){var t=[];for(var r in e)e.hasOwnProperty(r)&&(ei(e,this.style,r)||(this.style[r]=e[r],t.push(r)));return t},r.prototype.clearTexCache=function(e){var t,r,i;void 0===e&&(e=!1),e&&(this.refreshLevel|=ci.REPAINT,null===(t=this.textureCache)||void 0===t||t.release()),null===(r=this.textureTotal)||void 0===r||r.release(),null===(i=this.textureFilter)||void 0===i||i.release()},r.prototype.clearTexCacheUpward=function(e){void 0===e&&(e=!1);for(var t=this.parent;t;)t.clearTexCache(e),t=t.parent},r.prototype.clearMask=function(e){var t;if(void 0===e&&(e=!0),null===(t=this.textureMask)||void 0===t||t.release(),this.resetTextureTarget(),this.struct.next=0,this.refreshLevel|=ci.MASK,e)for(var r=this.parent;r&&r!==this.root;)r.clearTexCache(),r._rect=void 0,r._bbox=void 0,r._bboxInt=void 0,r._filterBbox=void 0,r._filterBboxInt=void 0,r.tempBbox=void 0,r=r.parent},r.prototype.refresh=function(e,t){var r;void 0===e&&(e=ci.REPAINT),null===(r=this.root)||void 0===r||r.addUpdate(this,[],e,t)},r.prototype.getBackgroundCoords=function(e,t){void 0===e&&(e=0),void 0===t&&(t=0);var r=this.computedStyle,i=r.borderTopLeftRadius,a=r.borderTopRightRadius,n=r.borderBottomLeftRadius,o=r.borderBottomRightRadius,s=Math.min(.5*r.width,.5*r.height),c=Math.min(s,i),u=Math.min(s,a),l=Math.min(s,n),h=Math.min(s,o);return 0===c&&0===u&&0===l&&0===h?[[e,t],[r.width,t],[r.width,r.height],[e,r.height],[e,t]]:[[c,t],[r.width-u,t],[r.width-u+u*br,t,r.width,u*br,r.width,u],[r.width,r.height-h],[r.width,r.height-h+h*br,r.width-h+h*br,r.height,r.width-h,r.height],[l,r.height],[l*br,r.height,e,r.height-l+l*br,e,r.height-l],[e,c],[e,c-c*br,c-c*br,t,c,t]]},r.prototype.getStyle=function(){return C(this.style)},r.prototype.getComputedStyle=function(){var e=Object.assign({},this.computedStyle);return this.isMounted&&(e.color=e.color.slice(0),e.backgroundColor=e.backgroundColor.slice(0),e.fill=C(e.fill),e.stroke=C(e.stroke),e.fillOpacity=e.fillOpacity.slice(0),e.fillEnable=e.fillEnable.slice(0),e.fillMode=e.fillMode.slice(0),e.strokeEnable=e.strokeEnable.slice(0),e.strokeWidth=e.strokeWidth.slice(0),e.transformOrigin=e.transformOrigin.slice(0),e.strokeDasharray=e.strokeDasharray.slice(0)),e},r.prototype.getCssStyle=function(e){var t=this;void 0===e&&(e=!1);var r=this.style,i=this.computedStyle,a={};return["top","right","bottom","left","width","height","translateX","translateY","scaleX","scaleY","rotateZ","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"].forEach(function(e){var t=r[e];t.u===V.AUTO?a[e]="auto":t.u===V.PERCENT?a[e]=t.v+"%":t.u!==V.PX&&t.u!==V.NUMBER&&t.u!==V.DEG||(a[e]=t.v)}),a.opacity=r.opacity.v,a.visibility=r.visibility.v===te.VISIBLE?"visible":"hidden",a.color=fe(r.color.v),a.backgroundColor=fe(r.backgroundColor.v),a.fontStyle=["normal","italic","oblique"][r.fontStyle.v],a.textAlign=["left","right","center","justify"][r.textAlign.v],a.textVerticalAlign=["top","middle","bottom"][r.textVerticalAlign.v],a.mixBlendMode=ai(r.mixBlendMode.v),a.objectFit=["fill","contain","cover"][r.objectFit.v],["strokeEnable","fillEnable","fillOpacity","strokeWidth"].forEach(function(e){a[e]=r[e].map(function(e){return e.v})}),e?this.isMounted?a.fill=i.fill.map(function(e){return ni(e,t.width,t.height,!0)}):oe.error("Can not get CSS standard fill unmounted"):a.fill=ga(r.fill).map(function(e){return ni(e)}),a.fillRule=["nonzero","evenodd"][r.fillRule.v],a.fillMode=r.fillMode.map(function(e){return ai(e.v)}),e?this.isMounted?a.stroke=i.stroke.map(function(e){return ni(e,t.width,t.height,!0)}):oe.error("Can not get CSS standard stroke unmounted"):a.stroke=va(r.stroke).map(function(e){return ni(e,t.width,t.height)}),a.strokeLinecap=["butt","round","square"][r.strokeLinecap.v],a.strokeLinejoin=["miter","round","bevel"][r.strokeLinejoin.v],a.strokePosition=r.strokePosition.map(function(e){return oi(e.v)}),a.strokeMiterlimit=r.strokeMiterlimit.v,a.strokeDasharray=r.strokeDasharray.map(function(e){return e.v}),a.strokeMode=r.strokeMode.map(function(e){return ai(e.v)}),a.transformOrigin=r.transformOrigin.map(function(e){return e.u===V.PERCENT?e.v+"%":e}),a.overflow=["visible","hidden"][r.overflow.v],a.filter=ya(r.filter,i.width,i.height).map(function(e){return(t=e).u===V.GAUSS_BLUR?"gaussBlur("+t.radius+")":t.u===V.RADIAL_BLUR?"radialBlur("+t.radius+","+t.center.join(", ")+")":t.u===V.MOTION_BLUR?"motionBlur("+t.radius+","+t.offset+")":t.u===V.BLOOM?"bloom("+t.threshold+","+t.knee+")":t.u===V.LIGHT_DARK?"lightDark("+t.radius+","+t.angle+")":void 0;var t}),a},r.prototype.isParent=function(e){for(var t=this.parent;t;){if(t===e)return!0;t=t.parent}return!1},r.prototype.isChild=function(e){return e.isParent(this)},r.prototype.insertAfter=function(e,t){e.remove();var r=this.root,i=this.parent;if(!i)throw new Error("Can not appendSelf without parent");e.parent=i,e.prev=this,this.next&&(this.next.prev=e),e.next=this.next,this.next=e,e.root=r;var a=i.children,n=a.indexOf(this);a.splice(n+1,0,e),i.isDestroyed?t&&t(!0):(i.insertStruct(e,n+1),r.addUpdate(e,[],ci.ADD_DOM,t))},r.prototype.insertBefore=function(e,t){e.remove();var r=this.root,i=this.parent;if(!i)throw new Error("Can not prependBefore without parent");e.parent=i,e.prev=this.prev,this.prev&&(this.prev.next=e),e.next=this,this.prev=e,e.root=r;var a=i.children,n=a.indexOf(this);a.splice(n,0,e),i.isDestroyed?t&&t(!0):(i.insertStruct(e,n),r.addUpdate(e,[],ci.ADD_DOM,t))},r.prototype.remove=function(e){var t=this.root,r=this.parent;if(r){var i=r.children.indexOf(this);if(-1===i)throw new Error("Invalid index of remove()");r.children.splice(i,1);var a=this.prev,n=this.next;a&&(a.next=n),n&&(n.prev=a),r.deleteStruct(this)}t&&this.isMounted?t.addUpdate(this,[],ci.REMOVE_DOM,e):e&&e(!0)},r.prototype.getBoundingClientRect=function(e){var t=(null==e?void 0:e.includeBbox)?this._bbox||this.bbox:this._rect||this.rect,r=Tt(t[0],t[1],t[2],t[3],this.matrixWorld),i=r.x1,a=r.y1,n=r.x2,o=r.y2,s=r.x3,c=r.y3,u=r.x4,l=r.y4,h=Math.min(i,n,s,u),d=Math.min(a,o,c,l),f=Math.max(i,n,s,u),m=Math.max(a,o,c,l);return{left:h,top:d,right:f,bottom:m,width:f-h,height:m-d,points:[{x:i,y:a},{x:n,y:o},{x:s,y:c},{x:u,y:l}]}},r.prototype.getOffsetRect=function(){var e=this.computedStyle,t=e.left+e.translateX,r=e.top+e.translateY;return{left:t,top:r,right:t+this.width,bottom:r+this.height}},r.prototype.startSizeChange=function(){var e=this,t=e.width,r=e.height,i=e.style,a=e.computedStyle,n=e.parent;if(e.isDestroyed||!n)throw new Error("Can not resize a destroyed Node or Root");var o=i.left,s=i.right,c=i.top,u=i.bottom,l=i.translateX,h=i.translateY,d=n.width,f=n.height;if(l.v&&l.u===V.PERCENT){var m=l.v*t*.01;o.u===V.PERCENT?o.v+=100*m/d:o.u===V.PX&&(o.v+=m),a.left+=m,s.u===V.PERCENT?s.v-=100*m/d:s.u===V.PX&&(s.v-=m),a.right-=m,l.v=0}if(h.v&&h.u===V.PERCENT){m=h.v*r*.01;c.u===V.PERCENT?c.v+=100*m/f:c.u===V.PX&&(c.v+=m),a.top+=m,u.u===V.PERCENT?u.v-=100*m/f:u.u===V.PX&&(u.v-=m),a.bottom-=m,h.v=0}},r.prototype.endSizeChange=function(e){var t=e.translateX,r=e.translateY,i=this,a=i.style,n=i.computedStyle,o=i.parent,s=i.width,c=i.height,u=a.left,l=a.right,h=a.top,d=a.bottom,f=o,m=f.width,p=f.height;if(t.v&&t.u===V.PERCENT){var g=t.v*s*.01;u.u===V.PX?u.v-=g:u.u===V.PERCENT&&(u.v-=100*g/m),n.left-=g,l.u===V.PX?l.v+=g:l.u===V.PERCENT&&(l.v+=100*g/m),n.right+=g,n.translateX+=g}if(r.v&&r.u===V.PERCENT){g=r.v*c*.01;h.u===V.PX?h.v-=g:a.top.u===V.PERCENT&&(h.v-=100*g/p),n.top-=g,d.u===V.PX?d.v+=g:d.u===V.PERCENT&&(d.v+=100*g/p),n.bottom+=g,n.translateY+=g}a.translateX.v=t.v,a.translateX.u=t.u,a.translateY.v=r.v,a.translateY.u=r.u},r.prototype.endPosChange=function(e,t,r){var i=this,a=i.style,n=i.computedStyle,o=i.parent;if(o){var s=e.translateX,c=e.translateY,u=a.top,l=a.right,h=a.bottom,d=a.left,f=o.width,m=o.height;t&&(d.u===V.PX?d.v+=t:d.u===V.PERCENT&&(d.v+=100*t/f),n.left+=t,l.u===V.PX?l.v-=t:l.u===V.PERCENT&&(l.v-=100*t/f),n.right-=t,n.translateX-=t),r&&(u.u===V.PX?u.v+=r:u.u===V.PERCENT&&(u.v+=100*r/m),n.top+=r,h.u===V.PX?h.v-=r:h.u===V.PERCENT&&(h.v-=100*r/m),n.bottom-=r,n.translateY-=r),a.translateX.v=s.v,a.translateX.u=s.u,a.translateY.v=c.v,a.translateY.u=c.u}},r.prototype.adjustPosAndSizeSelf=function(e,t,r,i){var a=this,n=a.style,o=a.computedStyle,s=a.parent,c=a.root;if(s&&c&&(e||t||r||i)){var u=s.width,l=s.height,h=n.top,d=n.right,f=n.bottom,m=n.left,p=n.width,g=n.height,v=n.translateX,y=n.translateY,b=(e||r)&&v.u===V.PERCENT&&v.v;if(b){var x=.01*b*this.width;m.u===V.PX?m.v+=x:m.u===V.PERCENT&&(m.v+=100*x/u),o.left+=x,d.u===V.PX?d.v-=x:d.u===V.PERCENT&&(d.v-=100*x/u),o.right-=x}if(e&&(m.u===V.PX?m.v+=e:m.u===V.PERCENT&&(m.v+=100*e/u),o.left+=e),r&&(d.u===V.PX?d.v-=r:d.u===V.PERCENT&&(d.v-=100*r/u),o.right-=r),r-e&&(p.u===V.PX?p.v=r+this.width-e:p.u===V.PERCENT&&(p.v=100*(r+this.width-e)/s.width),o.width=s.width-o.left-o.right),this.width<0){o.width=-this.width;var T=o.left,w=o.right;o.left=u-w,m.u===V.PX?m.v=o.left:m.u===V.PERCENT&&(m.v=100*o.left/u),o.right=u-T,d.u===V.PX?d.v=o.right:d.u===V.PERCENT&&(d.v=100*o.right/u)}if(b){x=.01*b*this.width;m.u===V.PX?m.v-=x:m.u===V.PERCENT&&(m.v-=100*x/u),o.left-=x,d.u===V.PX?d.v+=x:d.u===V.PERCENT&&(d.v+=100*x/u),o.right+=x}var k=(t||i)&&y.u===V.PERCENT&&y.v;if(k){x=.01*k*this.height;h.u===V.PX?h.v+=x:h.u===V.PERCENT&&(h.v+=100*x/l),o.top+=x,f.u===V.PX?f.v-=x:f.u===V.PERCENT&&(f.v-=100*x/l),o.bottom-=x}if(t&&(h.u===V.PX?h.v+=t:h.u===V.PERCENT&&(h.v+=100*t/l),o.top+=t),i&&(f.u===V.PX?f.v-=i:f.u===V.PERCENT&&(f.v-=100*i/l),o.bottom-=i),i-t&&(g.u===V.PX?g.v=i+this.height-t:g.u===V.PERCENT&&(g.v=100*(i+this.height-t)/s.height),o.height=s.height-o.top-o.bottom),this.height<0){o.height=-this.height;var S=o.top,E=o.bottom;o.top=l-S,h.u===V.PX?h.v=o.top:h.u===V.PERCENT&&(h.v=100*o.top/l),o.bottom=l-E,f.u===V.PX?f.v=o.bottom:f.u===V.PERCENT&&(f.v=100*o.bottom/l)}if(k){x=.01*k*this.height;h.u===V.PX?h.v-=x:h.u===V.PERCENT&&(h.v-=100*x/l),o.top-=x,f.u===V.PX?f.v+=x:f.u===V.PERCENT&&(f.v+=100*x/l),o.bottom+=x}this.refreshLevel|=ci.TRANSFORM_ALL,c.rl|=ci.TRANSFORM_ALL,this.calMatrix(ci.TRANSFORM_ALL),this._rect=void 0,this._bbox=void 0,this._bboxInt=void 0,this._filterBbox=void 0,this._filterBboxInt=void 0,this.tempBbox=void 0}},r.prototype.checkPosSizeUpward=function(){for(var e=this.root,t=this.parent;t&&t!==e&&t.adjustPosAndSize();)t=t.parent},r.prototype.adjustPosAndSize=function(){return!1},r.prototype.initAnimate=function(e,t){this.animationList.push(e);var r=this.root;return this.isDestroyed||!r?(e.cancel(),e):(r.aniController.addAni(e),t.autoPlay?e.play():"backwards"!==t.fill&&"both"!==t.fill||e.gotoAndStop(0),e)},r.prototype.animate=function(e,t){var r=new fa(this,e,t);return this.initAnimate(r,t)},r.prototype.release=function(){this.remove(),this.animationList.splice(0).forEach(function(e){return e.remove()}),this.clearTexCache()},r.prototype.cloneProps=function(){var e=Object.assign({},this.props);return e.name=this.name,e.style=this.getCssStyle(),e},r.prototype.clone=function(){return new r(this.cloneProps())},Object.defineProperty(r.prototype,"width",{get:function(){return this.computedStyle.width||0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"height",{get:function(){return this.computedStyle.height||0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"matrixWorld",{get:function(){var e,t=this.root,r=this._matrixWorld;if(!t)return r;for(var i=this,a=this.hasCacheMw,n=i.parent,o=-1,s=[];n;)s.push(n),n.hasCacheMw&&n.localMwId===i.parentMwId||(a=!1,o=s.length),i=n,n=n.parent;if(!a){if(o>-1){s.splice(o),s.reverse();for(var c=0,u=s.length;c<u;c++){var l=s[c];if(l.hasCacheMw&&l.parentMwId!==(null===(e=l.parent)||void 0===e?void 0:e.localMwId)&&l.localMwId++,l.hasCacheMw=!0,l===t)ut(l._matrixWorld,l.matrix);else{var h=l.parent.perspectiveMatrix,d=l.perspectiveMatrixSelf,f=l.matrix;d&&(f=ot(d,f)),h&&(f=ot(h,f));var m=ot(l.parent._matrixWorld,f);ut(l._matrixWorld,m),l.parentMwId=l.parent.localMwId}}}if(this.hasCacheMw&&this.localMwId++,this.hasCacheMw=!0,n=this.parent){h=n.perspectiveMatrix,d=this.perspectiveMatrixSelf,f=this.matrix;d&&(f=ot(d,f)),h&&(f=ot(h,f)),ut(r,m=ot(n._matrixWorld,f)),this.parentMwId=n.localMwId}else{ut(r,(d=this.perspectiveMatrixSelf)?ot(d,this.matrix):this.matrix)}}return r},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"rect",{get:function(){var e=this._rect;return e||((e=this._rect=new Float32Array(4))[0]=0,e[1]=0,e[2]=this.computedStyle.width,e[3]=this.computedStyle.height),e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"bbox",{get:function(){var e=this._bbox;if(!e){var t=this._rect||this.rect;e=this._bbox=t.slice(0)}return e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"filterBbox",{get:function(){var e=this._filterBbox;if(!e){var t=this._bbox||this.bbox;e=this._filterBbox=t.slice(0)}return e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"bboxInt",{get:function(){var e=this._bboxInt;return e||mi(e=this._bboxInt=(this._bbox||this.bbox).slice(0)),e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"filterBboxInt",{get:function(){var e=this._filterBboxInt;return e||mi(e=this._filterBboxInt=(this._filterBbox||this.filterBbox).slice(0)),e},enumerable:!1,configurable:!0}),r}(M);!function(e){e[e.NONE=0]="NONE",e[e.LOADING=1]="LOADING",e[e.LOADED=2]="LOADED"}(Ta||(Ta={}));var Sa={};function Ea(e,t){return i(this,void 0,void 0,function(){var r,i,n,o,s,c,u,l,h;return a(this,function(a){switch(a.label){case 0:if(r=Sa[e]){if(r.count++,r.state===Ta.LOADED)return[2,r.res];if(r.state===Ta.LOADING)return[2,new Promise(function(e){r.list.push(e)})]}return r=Sa[e]={state:Ta.LOADING,list:[],count:0,res:{success:!1,frames:[],width:0,height:0,release:function(){r.count--,r.count<=0&&(r.res.source&&URL.revokeObjectURL(r.res.source.src),r.res.frames.forEach(function(e){return e.close()}),delete Sa[e])}}},[4,fetch(e,Object.assign({mode:"cors"},t))];case 1:return 200!==(i=a.sent()).status&&304!==i.status?(r.state=Ta.LOADED,[2,r.res]):[4,i.arrayBuffer()];case 2:return n=a.sent(),"undefined"==typeof ImageDecoder?[3,9]:function(e){var t=[71,73,70,56,55,97];return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&(e[4]===t[4]||57===e[4])&&e[5]===t[5]}(new Uint8Array(n))?[4,(o=new ImageDecoder({data:n,type:"image/gif"})).tracks.ready]:[3,9];case 3:if(a.sent(),!(s=o.tracks.selectedTrack))return[3,8];c=0,a.label=4;case 4:return c<s.frameCount?[4,o.decode({frameIndex:c})]:[3,7];case 5:u=a.sent(),r.res.frames.push(u.image),a.label=6;case 6:return c++,[3,4];case 7:return r.state=Ta.LOADED,r.res.success=!0,r.res.width=r.res.frames[0].codedWidth,r.res.height=r.res.frames[0].codedHeight,r.count++,r.list.splice(0).forEach(function(e){r.count++,e(r.res)}),o.close(),[2,r.res];case 8:o.close(),a.label=9;case 9:return l=new Blob([n]),(h=new Image).src=URL.createObjectURL(l),r.count++,[2,new Promise(function(e){h.onload=function(){r.state=Ta.LOADED,r.res.success=!0,r.res.source=h,r.res.width=h.width,r.res.height=h.height,e(r.res),r.list.splice(0).forEach(function(e){r.count++,e(r.res)})},h.onerror=function(){r.state=Ta.LOADED,e(r.res),r.list.splice(0).forEach(function(e){r.count++,e(r.res)})}})]}})})}var Ca=function(e){function r(t,r,i){var a=e.call(this,t,i)||this;return a.node=t,a._frameArea=r,a._frameAreaR=r.slice(0).reverse(),a.currentFrameArea=a._frameArea,a.originFrameIndex=t.frameIndex,a.setCurrentFrameArea(),a}return t(r,e),r.prototype.setCurrentFrameArea=function(){var e=this.direction,t=this._playCount;this.currentFrameArea="backwards"===e?this._frameAreaR:"alternate"===e?t%2==0?this._frameArea:this._frameAreaR:"alternateReverse"===e&&t%2==0?this._frameAreaR:this._frameArea},r.prototype.finish=function(){"finished"!==this._playState&&(e.prototype.finish.call(this),this.onFirstInEndDelay())},r.prototype.cancel=function(){"idle"!==this._playState&&(e.prototype.cancel.call(this),this.node.frameIndex=this.originFrameIndex)},r.prototype.onRunning=function(t){e.prototype.onRunning.call(this,t);var r=this,i=r.node,a=r.duration,n=r.delay,o=r.iterations,s=r.currentFrameArea,c=r.time;if(!(this._currentTime<n)){var u=this._playCount>=o-1,l=c/a;this.easing&&(l=this.easing(l)),u&&l>=1||(i.frameIndex=Math.floor(s[0]+(s[1]-s[0])*l))}},r.prototype.onFirstInDelay=function(){var e=this,t=e.fill,r=e.currentFrameArea,i=e.node;"backwards"!==t&&"both"!==t||(i.frameIndex=r[0])},r.prototype.onFirstInEndDelay=function(){var e=this.fill,t=this.node;if("forwards"===e||"both"===e){var r=this.currentFrameArea;t.frameIndex=r[r.length-1]}else t.frameIndex=this.originFrameIndex},r.prototype.onChangePlayCount=function(){this.setCurrentFrameArea()},r}(da),Aa="refresh_complete",_a="waiting",Ma="can_play",Ia="meta",Ra="error",Pa="load",Oa=function(e){function r(t){var r=e.call(this,t)||this;t.onLoad&&(r.onLoad=t.onLoad),r._frameIndex=t.frameIndex||0,r.isPure=!0;var i=r._src=t.src||"";if(i){var a=function(){if(r.isMounted){var e=r.style,t=e.left,i=e.top,a=e.right,n=e.bottom,o=e.width,s=e.height;(t.u===V.AUTO||a.u===V.AUTO)&&o.u===V.AUTO||(i.u===V.AUTO||n.u===V.AUTO)&&s.u===V.AUTO?r.refresh(ci.REFLOW):r.refresh()}r.onLoad&&r.onLoad(),r.emit(Pa)},n=function(e){var t=Sa[e];if((null==t?void 0:t.state)===Ta.LOADED)return t.res}(i);n?n.success&&(r.loader=n,a()):(r.contentLoadingNum=1,Ea(i).then(function(e){r.loader=e,r.contentLoadingNum=0,e.success&&a()}))}return r}return t(r,e),r.prototype.lay=function(t){e.prototype.lay.call(this,t);var r=this,i=r.style,a=r.computedStyle,n=r.loader,o=i.left,s=i.top,c=i.right,u=i.bottom,l=i.width,h=i.height;if(n){var d=(o.u===V.AUTO||c.u===V.AUTO)&&l.u===V.AUTO,f=(s.u===V.AUTO||u.u===V.AUTO)&&h.u===V.AUTO;d&&(a.width=f?n.width:n.width*a.height/n.height,o.u===V.AUTO&&c.u===V.AUTO?(a.left=0,a.right=t.w-a.width):o.u===V.AUTO?a.left=t.w-a.right-a.width:c.u===V.AUTO&&(a.right=t.w-a.left-a.width)),f&&(a.height=d?n.height:n.height*a.width/n.width,s.u===V.AUTO&&u.u===V.AUTO?(a.top=0,a.bottom=t.h-a.height):s.u===V.AUTO?a.top=t.h-a.bottom-a.height:u.u===V.AUTO&&(a.bottom=t.h-a.top-a.height))}},r.prototype.calRepaintStyle=function(t){e.prototype.calRepaintStyle.call(this,t);var r=this.computedStyle,i=this.loader;if(this.isPure=r.backgroundColor[3]<=0,this.isPure&&(null==i?void 0:i.success)){var a=r.objectFit,n=r.borderTopLeftRadius,o=r.borderTopRightRadius,s=r.borderBottomLeftRadius,c=r.borderBottomRightRadius;if(a!==ae.COVER&&a!==ae.FILL||!(n||o||s||c)){if(a===ae.CONTAIN&&(n||o||s||c)){var u=i.width/i.height,l=r.width/r.height;if(l>u){var h=r.height*u,d=.5*(r.width-h);(n>d||o>d||s>d||c>d)&&(this.isPure=!1)}else if(l<u){var f=r.width/u,m=.5*(r.height-f);(n>m||o>m||s>m||c>m)&&(this.isPure=!1)}else this.isPure=!1}}else this.isPure=!1}},r.prototype.calContent=function(){this.hasContent=!1;var e=this.loader;return(null==e?void 0:e.success)?e.frames.length?this._frameIndex>=0&&this._frameIndex<e.frames.length&&(this.hasContent=!0):e.source&&(this.hasContent=!0):this.hasContent=this.computedStyle.backgroundColor[3]>0,this.hasContent},r.prototype.renderCanvas=function(){var t,r,i=this,a=i.isPure,n=i.loader,o=i.computedStyle;if(a){if(null===(t=this.canvasCache)||void 0===t||t.release(),null==n?void 0:n.success){var s=n.width,c=n.height;if(n.frames.length){var u=Math.min(n.frames.length-1,Math.max(0,this._frameIndex));if((Q=n.frames[u])&&(s>L.maxTextureSize||c>L.maxTextureSize))if((R=this.canvasCache=xi.getVideoFrameInstance(s,c,Q)).available=!0,1===R.getCount()){var l=o.width,h=o.height,d=o.objectFit,f=0,m=0,p=n.width/n.height,g=l/h;if(d===ae.CONTAIN){if(g>p){var v=h*p;f=.5*(l-v),l=v}else if(g<p){var y=l/p;m=.5*(h-y),h=y}}else if(d===ae.COVER)if(g>p){var b=l/p;m=.5*(h-b),h=b}else if(g<p){var x=h*p;f=.5*(l-x),l=x}for(var T=0,w=(U=R.list).length;T<w;T++){var k=U[T],S=k.x,E=k.y;k.os.ctx.drawImage(Q,-S+f,-E+m,l,h)}}}else if(n.source&&(n.width>L.maxTextureSize||n.height>L.maxTextureSize)){if((R=this.canvasCache=xi.getImgInstance(s,c,this._src)).available=!0,1===R.getCount()){l=o.width,h=o.height,d=o.objectFit,f=0,m=0,p=n.width/n.height,g=l/h;if(d===ae.CONTAIN){if(g>p){var C=h*p;f=.5*(l-C),l=C}else if(g<p){var A=l/p;m=.5*(h-A),h=A}}else if(d===ae.COVER)if(g>p){var _=l/p;m=.5*(h-_),h=_}else if(g<p){var M=h*p;f=.5*(l-M),l=M}for(T=0,w=(U=R.list).length;T<w;T++){var I=U[T];S=I.x,E=I.y;I.os.ctx.drawImage(n.source,-S+f,-E+m,l,h)}}}}}else{e.prototype.renderCanvas.call(this);var R,P=this.computedStyle,O=this._bboxInt||this.bboxInt;S=O[0],E=O[1],s=O[2]-S,c=O[3]-E,l=P.width,h=P.height,d=P.objectFit,f=0,m=0;if(null==n?void 0:n.success){p=n.width/n.height,g=l/h;if(d===ae.CONTAIN){if(g>p){var D=h*p;f=.5*(l-D),l=D}else if(g<p){var B=l/p;m=.5*(h-B),h=B}}else if(d===ae.COVER)if(g>p){var F=l/p;m=.5*(h-F),h=F}else if(g<p){var N=h*p;f=.5*(l-N),l=N}}(R=this.canvasCache=(null===(r=this.canvasCache)||void 0===r?void 0:r.available)?this.canvasCache:new xi(s,c,-S,-E)).available=!0;var U;for(T=0,w=(U=R.list).length;T<w;T++){var z=U[T],W=z.x,V=z.y,H=z.os.ctx,X=-W,j=-V;if(null==n?void 0:n.success){var G=P.borderTopLeftRadius,Y=P.borderTopRightRadius,q=P.borderBottomLeftRadius,K=P.borderBottomRightRadius;if(G||Y||q||K){var $=this.getBackgroundCoords(W,V);H.save(),H.beginPath(),ba(H,$,-W,-V),H.closePath(),H.clip()}if(n.frames.length){var Q;u=Math.min(n.frames.length-1,Math.max(0,this._frameIndex));(Q=n.frames[u])&&H.drawImage(Q,X+f,j+m,l,h)}else n.source&&H.drawImage(n.source,X+f,j+m,l,h);(G||Y||q||K)&&H.restore()}}}},r.prototype.genTexture=function(t){var r=this,i=r.isPure,a=r.loader,n=r.canvasCache;if(i){if(null==a?void 0:a.success)if(a.width>L.maxTextureSize||a.height>L.maxTextureSize)if((null==n?void 0:n.available)&&Zi.hasCanvasCacheInstance(n)){var o=Zi.getCanvasCacheInstance(t,n,this._rect||this.rect);this.textureTarget=this.textureCache=o}else{this.renderCanvas();o=Zi.getCanvasCacheInstance(t,this.canvasCache,this._rect||this.rect);this.textureTarget=this.textureCache=o,this.canvasCache.release()}else{var s=this.computedStyle,c=s.width,u=s.height,l=s.objectFit,h=this._rect||this.rect,d=(o=void 0,a.width/a.height),f=c/u;if(l===ae.CONTAIN){if(f>d){var m=.5*(c-(v=u*d));(h=h.slice(0))[0]+=m,h[2]-=m}else if(f<d){m=.5*(u-(p=c/d));(h=h.slice(0))[1]+=m,h[3]-=m}}else if(l===ae.COVER)if(f>d){var p=c/d;o={x1:0,y3:g=(m=.5*Math.abs(u-p))/p,x3:1,y1:1-g}}else if(f<d){var g,v=u*d;o={x1:g=(m=.5*Math.abs(c-v))/v,y3:0,x3:1-g,y1:1}}if(a.frames.length){var y=Math.min(a.frames.length-1,Math.max(0,this._frameIndex)),b=a.frames[y];if(b){var x=Zi.getVideoFrameInstance(t,b,h,o);this.textureTarget=this.textureCache=x}}else if(a.source){x=Zi.getImgInstance(t,a.source,h,o);this.textureTarget=this.textureCache=x}}}else e.prototype.genTexture.call(this,t)},r.prototype.release=function(){e.prototype.release.call(this);var t=this.loader;(null==t?void 0:t.success)&&t.release()},r.prototype.gifAnimate=function(e,t){var r=new Ca(this,e,t);return this.initAnimate(r,t)},r.prototype.cloneProps=function(){var t=e.prototype.cloneProps.call(this);return t.src=this._src,t},r.prototype.clone=function(){return new r(this.cloneProps())},Object.defineProperty(r.prototype,"src",{get:function(){return this._src},set:function(e){this._src!==e&&(this._src=e,this.refresh())},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"frameIndex",{get:function(){return this._frameIndex},set:function(e){this._frameIndex!==e&&(this._frameIndex=e,this.refresh())},enumerable:!1,configurable:!0}),r}(ka);var Da={parseJSON:function(e){var t=e.tagName,r=e.props,i=void 0===r?{}:r,a=e.children,n=void 0===a?[]:a,o=e.animation,s=void 0===o?[]:o;if(!t)throw new Error("Missing tagName");if(!Array.isArray(n))throw new Error("Children must be an array");if(!Array.isArray(s))throw new Error("Animation must be an array");if("img"!==t)throw new Error("Unknown tagName");return new Oa(i)}},Ba=function(e){function r(t,r){void 0===r&&(r=[]);var i=e.call(this,t)||this;return i.children=r,i}return t(r,e),r.prototype.didMount=function(){e.prototype.didMount.call(this);var t=this.children,r=t.length;if(r){var i=t[0];i.parent=this,i.didMount();for(var a=i,n=1;n<r;n++){var o=t[n];o.didMount(),o.parent=this,a.next=o,o.prev=a,a=o}}},r.prototype.didUnmount=function(){e.prototype.didUnmount.call(this),this.children.forEach(function(e){e.didUnmount()})},r.prototype.layout=function(t){e.prototype.layout.call(this,t);for(var r=this.children,i=0,a=r.length;i<a;i++){r[i].layout({w:this.computedStyle.width,h:this.computedStyle.height})}},r.prototype.structure=function(t){var r=e.prototype.structure.call(this,t);return this.children.forEach(function(e){r=r.concat(e.structure(t+1))}),r[0].num=this.children.length,r[0].total=r.length-1,r},r.prototype.insertStruct=function(e,t){var r,i=this.struct,a=this.root,n=e.structure(i.lv+1),o=a.structs;if(t){var s=this.children[t-1].struct,c=s.total;r=o.indexOf(s)+c+1}else r=o.indexOf(i)+1;o.splice.apply(o,function(e,t,r){if(r||2===arguments.length)for(var i,a=0,n=t.length;a<n;a++)!i&&a in t||(i||(i=Array.prototype.slice.call(t,0,a)),i[a]=t[a]);return e.concat(i||Array.prototype.slice.call(t))}([r,0],n,!1));var u=n[0].total+1;i.num++,i.total+=u;for(var l=this.parent;l;)l.struct.total+=u,l=l.parent},r.prototype.deleteStruct=function(e){var t=e.struct,r=t.total+1,i=this.root.structs,a=i.indexOf(t);i.splice(a,r);var n=this.struct;n.num--,n.total-=r;for(var o=this.parent;o;)o.struct.total-=r,o=o.parent},r.prototype.appendChild=function(e,t){e.remove();var r=this.root,i=this.children,a=i.length;if(a){var n=i[i.length-1];n.next=e,e.prev=n}e.parent=this,e.root=r,i.push(e),r&&this.isMounted?(this.insertStruct(e,a),r.addUpdate(e,[],ci.ADD_DOM,t)):t&&t(!0)},r.prototype.prependChild=function(e,t){e.remove();var r=this.root,i=this.children;if(i.length){var a=i[0];a.next=e,e.prev=a}e.parent=this,e.root=r,i.push(e),r&&!this.isDestroyed?(this.insertStruct(e,0),r.addUpdate(e,[],ci.ADD_DOM,t)):t&&t(!0)},r.prototype.removeChild=function(e,t){e.parent===this?e.remove(t):oe.error("Invalid parameter of removeChild()")},r.prototype.removeAllChildren=function(e){for(var t=this.children.length-1;t>=0;t--)t?this.children[t].remove():this.children[t].remove(e)},r}(ka),Fa={alpha:!0,antialias:!0,premultipliedAlpha:!0,preserveDrawingBuffer:!0,depth:!0,stencil:!0};function La(e,t,r,i){var a=e.createFramebuffer();return e.bindFramebuffer(e.FRAMEBUFFER,a),t&&e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.viewport(0,0,r,i),a}function Na(e,t,r,i){e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteFramebuffer(t),r&&i&&e.viewport(0,0,r,i)}function Ua(e,t,r,i){return za(e,t,0,0,r,i)}function za(e,t,r,i,a,n){var o,s,c=Tt(e[0],e[1],e[2],e[3],t),u=c.x1,l=c.y1,h=c.x2,d=c.y2,f=c.x3,m=c.y3,p=c.x4,g=c.y4;return u===p&&l===d&&h===f&&m===g?(u>h&&(u=(o=[f,u])[0],f=o[1]),d>m&&(l=(s=[m,l])[0],m=s[1]),xr(r,i,r+a,i+n,u,l,f,m,!1)):Tr(r,i,r+a,i+n,[{x:u,y:l},{x:h,y:d},{x:f,y:m},{x:p,y:g}],!1)}var Wa=void 0,Va=function(){function e(e,t,r){this.program=t,this.options=r||{},this.uniform={},this.attrib={},this.uniformValue={},this.initLocations(e)}return e.prototype.initLocations=function(e){var t=this;this.options.uniform&&this.options.uniform.forEach(function(r){t.uniform[r]=e.getUniformLocation(t.program,r)}),this.options.attrib&&this.options.attrib.forEach(function(r){t.attrib[r]=e.getAttribLocation(t.program,r)})},e.useProgram=function(e,t){Wa!==t&&(Wa=t,e.useProgram(t.program))},e}(),Ha=function(e){function r(t,r,i){var a=e.call(this,t,i)||this;return a.node=t,a._timeArea=[r,r+a.duration],a._timeAreaR=a._timeArea.slice(0).reverse(),a.currentTimeArea=a._timeArea,a.originTime=t.currentTime,a.setCurrentTimeArea(),a}return t(r,e),r.prototype.setCurrentTimeArea=function(){var e=this.direction,t=this._playCount;this.currentTimeArea="backwards"===e?this._timeArea:"alternate"===e?t%2==0?this._timeAreaR:this._timeArea:"alternateReverse"===e?t%2==0?this._timeArea:this._timeAreaR:this._timeArea},r.prototype.finish=function(){"finished"!==this._playState&&(e.prototype.finish.call(this),this.onFirstInEndDelay())},r.prototype.cancel=function(){"idle"!==this._playState&&(e.prototype.cancel.call(this),this.node.currentTime=this.originTime)},r.prototype.play=function(){e.prototype.play.call(this),"running"!==this._playState||this._currentTime||(this.node.currentTime=0)},r.prototype.onRunning=function(t,r){var i;e.prototype.onRunning.call(this,t,r);var a=this,n=a.node,o=a.duration,s=a.delay,c=a.iterations,u=a.currentTimeArea,l=a.time,h=this._currentTime;if(h<s)n.currentTime=h-s;else{var d=this._playCount>=c-1,f=l/o;this.easing&&(f=this.easing(f)),d&&f>=1?n instanceof ef&&l-o>=L.releasePrevDuration&&n.computedStyle.visibility===te.HIDDEN&&(null===(i=n.decoder)||void 0===i||i.releaseGOPList(),n.videoFrame=void 0):n.currentTime=Math.floor(u[0]+(u[1]-u[0])*f)}},r.prototype.onFirstInDelay=function(){var e=this,t=e.fill,r=e.currentTimeArea,i=e.node;"backwards"!==t&&"both"!==t||(i.currentTime=r[0])},r.prototype.onFirstInEndDelay=function(){var e=this.fill,t=this.node;if("forwards"===e||"both"===e){var r=this.currentTimeArea;t.currentTime=r[r.length-1]}else t.currentTime=this.originTime},r.prototype.onChangePlayCount=function(){this.setCurrentTimeArea()},Object.defineProperty(r.prototype,"timeArea",{get:function(){return this._timeArea.slice(0)},enumerable:!1,configurable:!0}),r}(da);
2
2
  /*!
3
3
  * Copyright (c) 2025-present, Vanilagy and contributors
4
4
  *
@@ -6,7 +6,7 @@
6
6
  * License, v. 2.0. If a copy of the MPL was not distributed with this
7
7
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
8
8
  */
9
- function jr(e){if(!e)throw new Error("Assertion failed.")}const Xr=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},qr=e=>e&&e[e.length-1],Gr=e=>e>=0&&e<2**32;class Kr{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,r=7-(7&this.pos),i=(t&1<<r)>>r;return this.pos++,i}readBits(e){if(1===e)return this.readBit();let t=0;for(let r=0;r<e;r++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const r=this.pos+e;for(let e=this.pos;e<r;e++){const i=Math.floor(e/8);let a=this.bytes[i];const n=7-(7&e);a&=~(1<<n),a|=(t&1<<r-e-1)>>r-e-1<<n,this.bytes[i]=a}this.pos=r}readAlignedByte(){if(this.pos%8!=0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new Kr(this.bytes);return e.pos=this.pos,e}}const Yr=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<t)-1+e.readBits(t)},$r=e=>{const t=Yr(e);return 1&t?t+1>>1:-(t>>1)},Qr=e=>e.constructor===Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),Zr=e=>e.constructor===DataView?e:e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),Jr=new TextDecoder,ei=new TextEncoder,ti=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),ri={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ii=ti(ri),ai={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},ni=ti(ai),si={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},oi=ti(si),ci=e=>!!(e&&e.primaries&&e.transfer&&e.matrix&&void 0!==e.fullRange),li=e=>e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class ui{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const t=new Promise(t=>{e=t}),r=this.currentPromise;return this.currentPromise=t,await r,e}}const hi=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),di=e=>(e=(e=(e=(e=(e=e>>1&1431655765|(1431655765&e)<<1)>>2&858993459|(858993459&e)<<2)>>4&252645135|(252645135&e)<<4)>>8&16711935|(16711935&e)<<8)>>16&65535|(65535&e)<<16)>>>0,fi=(e,t,r)=>{let i=0,a=e.length-1,n=-1;for(;i<=a;){const s=i+a>>1,o=r(e[s]);o===t?(n=s,a=s-1):o<t?i=s+1:a=s-1}return n},mi=(e,t,r)=>{let i=0,a=e.length-1,n=-1;for(;i<=a;){const s=i+(a-i+1)/2|0;r(e[s])<=t?(n=s,i=s+1):a=s-1}return n},pi=(e,t,r)=>{const i=mi(e,r(t),r);e.splice(i+1,0,t)},gi=()=>{let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}},vi=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},yi=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},bi=e=>{throw new Error(`Unexpected value: ${e}`)},ki=(e,t,r)=>{const i=e.getUint8(t),a=e.getUint8(t+1),n=e.getUint8(t+2);return r?i|a<<8|n<<16:i<<16|a<<8|n},Ti=(e,t,r)=>Math.max(t,Math.min(r,e)),wi="und",Si=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},xi=(e,t)=>Math.round(e/t)*t,Ci=/^[a-z]{3}$/,Ei=e=>Ci.test(e),Ai=1e6*(1+Number.EPSILON),Pi=(e,t)=>{const r={...e,...t};if(e.headers||t.headers){const i=e.headers?Ii(e.headers):{},a=t.headers?Ii(t.headers):{},n={...i};Object.entries(a).forEach(([e,t])=>{const r=Object.keys(n).find(t=>t.toLowerCase()===e.toLowerCase());r&&delete n[r],n[e]=t}),r.headers=n}return r},Ii=e=>{if(e instanceof Headers){const t={};return e.forEach((e,r)=>{t[r]=e}),t}if(Array.isArray(e)){const t={};return e.forEach(([e,r])=>{t[e]=r}),t}return e},Ri=async(e,t,r,i)=>{let a=0;for(;;)try{return await e(t,r)}catch(e){a++;const r=i(a,e,t);if(null===r)throw e;if(console.error("Retrying failed fetch. Error:",e),!Number.isFinite(r)||r<0)throw new TypeError("Retry delay must be a non-negative finite number.");r>0&&await new Promise(e=>setTimeout(e,1e3*r))}};class Oi{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let Mi=null;const _i=()=>null!==Mi?Mi:Mi=!("undefined"==typeof navigator||!navigator.vendor?.match(/apple/i));let Di=null;let Bi=null;const Fi=(e,t)=>-1!==e?e:t,Ni=(e,t,r,i)=>e<=i&&r<=t,Li=function*(e){for(const t in e){const r=e[t];void 0!==r&&(yield{key:t,value:r})}},Ui=e=>{switch(e.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},zi=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r},Wi=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0},Vi=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Hi=e=>"number"==typeof e&&!Number.isNaN(e);
9
+ function Xa(e){if(!e)throw new Error("Assertion failed.")}const ja=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},Ga=e=>e&&e[e.length-1],Ya=e=>e>=0&&e<2**32;class qa{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,r=7-(7&this.pos),i=(t&1<<r)>>r;return this.pos++,i}readBits(e){if(1===e)return this.readBit();let t=0;for(let r=0;r<e;r++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const r=this.pos+e;for(let e=this.pos;e<r;e++){const i=Math.floor(e/8);let a=this.bytes[i];const n=7-(7&e);a&=~(1<<n),a|=(t&1<<r-e-1)>>r-e-1<<n,this.bytes[i]=a}this.pos=r}readAlignedByte(){if(this.pos%8!=0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new qa(this.bytes);return e.pos=this.pos,e}}const Ka=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<t)-1+e.readBits(t)},$a=e=>{const t=Ka(e);return 1&t?t+1>>1:-(t>>1)},Qa=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),Za=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),Ja=new TextDecoder,en=new TextEncoder,tn=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),rn={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},an=tn(rn),nn={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},on=tn(nn),sn={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},cn=tn(sn),un=e=>!!(e&&e.primaries&&e.transfer&&e.matrix&&void 0!==e.fullRange),ln=e=>e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class hn{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const t=new Promise(t=>{e=t}),r=this.currentPromise;return this.currentPromise=t,await r,e}}const dn=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),fn=e=>(e=(e=(e=(e=(e=e>>1&1431655765|(1431655765&e)<<1)>>2&858993459|(858993459&e)<<2)>>4&252645135|(252645135&e)<<4)>>8&16711935|(16711935&e)<<8)>>16&65535|(65535&e)<<16)>>>0,mn=(e,t,r)=>{let i=0,a=e.length-1,n=-1;for(;i<=a;){const o=i+a>>1,s=r(e[o]);s===t?(n=o,a=o-1):s<t?i=o+1:a=o-1}return n},pn=(e,t,r)=>{let i=0,a=e.length-1,n=-1;for(;i<=a;){const o=i+(a-i+1)/2|0;r(e[o])<=t?(n=o,i=o+1):a=o-1}return n},gn=(e,t,r)=>{const i=pn(e,r(t),r);e.splice(i+1,0,t)},vn=()=>{let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}},yn=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},bn=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},xn=e=>{throw new Error(`Unexpected value: ${e}`)},Tn=(e,t,r)=>{const i=e.getUint8(t),a=e.getUint8(t+1),n=e.getUint8(t+2);return r?i|a<<8|n<<16:i<<16|a<<8|n},wn=(e,t,r,i)=>{r>>>=0,r&=16777215,e.setUint8(t,r>>>16&255),e.setUint8(t+1,r>>>8&255),e.setUint8(t+2,255&r)},kn=(e,t,r)=>Math.max(t,Math.min(r,e)),Sn="und",En=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},Cn=(e,t)=>Math.round(e/t)*t,An=/^[a-z]{3}$/,_n=e=>An.test(e),Mn=1e6*(1+Number.EPSILON),In=(e,t)=>{const r={...e,...t};if(e.headers||t.headers){const i=e.headers?Rn(e.headers):{},a=t.headers?Rn(t.headers):{},n={...i};Object.entries(a).forEach(([e,t])=>{const r=Object.keys(n).find(t=>t.toLowerCase()===e.toLowerCase());r&&delete n[r],n[e]=t}),r.headers=n}return r},Rn=e=>{if(e instanceof Headers){const t={};return e.forEach((e,r)=>{t[r]=e}),t}if(Array.isArray(e)){const t={};return e.forEach(([e,r])=>{t[e]=r}),t}return e},Pn=async(e,t,r,i,a)=>{let n=0;for(;;)try{return await e(t,r)}catch(e){if(a())throw e;n++;const r=i(n,e,t);if(null===r)throw e;if(console.error("Retrying failed fetch. Error:",e),!Number.isFinite(r)||r<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(r>0&&await new Promise(e=>setTimeout(e,1e3*r)),a())throw e}};class On{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let Dn=null;const Bn=()=>null!==Dn?Dn:Dn=!("undefined"==typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let Fn=null;let Ln=null;const Nn=()=>null!==Ln?Ln:Ln=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent));let Un=null;const zn=(e,t)=>-1!==e?e:t,Wn=(e,t,r,i)=>e<=i&&r<=t,Vn=function*(e){for(const t in e){const r=e[t];void 0!==r&&(yield{key:t,value:r})}},Hn=e=>{switch(e.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},Xn=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r},jn=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0},Gn=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Yn=e=>"number"==typeof e&&!Number.isNaN(e);
10
10
  /*!
11
11
  * Copyright (c) 2025-present, Vanilagy and contributors
12
12
  *
@@ -14,7 +14,7 @@ function jr(e){if(!e)throw new Error("Assertion failed.")}const Xr=e=>{const t=(
14
14
  * License, v. 2.0. If a copy of the MPL was not distributed with this
15
15
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
16
16
  */
17
- class ji{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("string"!=typeof t)throw new TypeError("mimeType must be a string.")}}class Xi{constructor(e,t,r,i){if(this.data=e,this.mimeType=t,this.name=r,this.description=i,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==t&&"string"!=typeof t)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw new TypeError("name, when provided, must be a string.");if(void 0!==i&&"string"!=typeof i)throw new TypeError("description, when provided, must be a string.")}}const qi={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Gi=["avc","hevc","vp9","av1","vp8"],Ki=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Yi=["aac","opus","mp3","vorbis","flac"],$i=[...Yi,...Ki],Qi=["webvtt"],Zi=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Ji=".01.01.01.01.00",ea=".0.110.01.01.01.0",ta=e=>{const t=e.split(".");return[1,1,Number(t[1]),2,1,Number(t[2]),3,1,Number(t[3]),4,1,t[4]?Number(t[4]):1]},ra=e=>{const t=e.split("."),r=Number(t[1]),i=t[2];return[129,(r<<5)+Number(i.slice(0,-1)),(("H"===i.slice(-1)?1:0)<<7)+((8===Number(t[3])?0:1)<<6)+0+((t[4]?Number(t[4]):0)<<4)+((t[5]?Number(t[5][0]):1)<<3)+((t[5]?Number(t[5][1]):1)<<2)+(t[5]?Number(t[5][2]):0),0]},ia=e=>{const{codec:t,codecDescription:r,colorSpace:i,avcCodecInfo:a,hevcCodecInfo:n,vp9CodecInfo:s,av1CodecInfo:o}=e;if("avc"===t){if(jr(null!==e.avcType),a){const t=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${e.avcType}.${hi(t)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${hi(r.subarray(1,4))}`}if("hevc"===t){let e,t,i,a,s,o;if(n)e=n.generalProfileSpace,t=n.generalProfileIdc,i=di(n.generalProfileCompatibilityFlags),a=n.generalTierFlag,s=n.generalLevelIdc,o=[...n.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const n=Zr(r),c=n.getUint8(1);e=c>>6&3,t=31&c,i=di(n.getUint32(2)),a=c>>5&1,s=n.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(n.getUint8(6+e))}let c="hev1.";for(c+=["","A","B","C"][e]+t,c+=".",c+=i.toString(16).toUpperCase(),c+=".",c+=0===a?"L":"H",c+=s;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(c+=".",c+=o.map(e=>e.toString(16).toUpperCase()).join(".")),c}if("vp8"===t)return"vp8";if("vp9"===t){if(!s){const t=e.width*e.height;let r=qr(Zi).level;for(const e of Zi)if(t<=e.maxPictureSize){r=e.level;break}return`vp09.00.${r.toString().padStart(2,"0")}.08`}let t=`vp09.${s.profile.toString().padStart(2,"0")}.${s.level.toString().padStart(2,"0")}.${s.bitDepth.toString().padStart(2,"0")}.${s.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${s.colourPrimaries.toString().padStart(2,"0")}.${s.transferCharacteristics.toString().padStart(2,"0")}.${s.matrixCoefficients.toString().padStart(2,"0")}.${s.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Ji)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let r=qr(Zi).level;for(const e of Zi)if(t<=e.maxPictureSize){r=e.level;break}return`av01.0.${r.toString().padStart(2,"0")}M.08`}const t=o.profile,r=o.level.toString().padStart(2,"0"),a=o.tier?"H":"M",n=o.bitDepth.toString().padStart(2,"0"),s=o.monochrome?"1":"0",c=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),l=i?.primaries?ri[i.primaries]:1,u=i?.transfer?ai[i.transfer]:1,h=i?.matrix?si[i.matrix]:1,d=i?.fullRange?1:0;let f=`av01.${t}.${r}${a}.${n}`;return f+=`.${s}.${c.toString().padStart(3,"0")}`,f+=`.${l.toString().padStart(2,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${h.toString().padStart(2,"0")}`,f+=`.${d}`,f.endsWith(ea)&&(f=f.slice(0,-17)),f}throw new TypeError(`Unhandled codec '${t}'.`)},aa=e=>{const{codec:t,codecDescription:r,aacCodecInfo:i}=e;if("aac"===t){if(!i)throw new TypeError("AAC codec info must be provided.");if(i.isMpeg2)return"mp4a.67";return`mp4a.40.${oa(r).objectType}`}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if(t&&Ki.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},na=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],sa=[-1,1,2,3,4,5,6,8],oa=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new Kr(e);let r=t.readBits(5);31===r&&(r=32+t.readBits(6));const i=t.readBits(4);let a=null;15===i?a=t.readBits(24):i<na.length&&(a=na[i]);const n=t.readBits(4);let s=null;return n>=1&&n<=7&&(s=sa[n]),{objectType:r,frequencyIndex:i,sampleRate:a,channelConfiguration:n,numberOfChannels:s}},ca=48e3,la=/^pcm-([usf])(\d+)+(be)?$/,ua=e=>{if(jr(Ki.includes(e)),"ulaw"===e)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===e)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const t=la.exec(e);let r;jr(t),r="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:r,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},ha=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],da=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,fa=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,ma=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,pa=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,ga=e=>{if(!e)throw new TypeError("Video chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Video chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Video chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!ha.some(t=>e.decoderConfig.codec.startsWith(t)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(void 0!==e.decoderConfig.description&&!li(e.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==e.decoderConfig.colorSpace){const{colorSpace:t}=e.decoderConfig;if("object"!=typeof t)throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const r=Object.keys(ri);if(null!=t.primaries&&!r.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);const i=Object.keys(ai);if(null!=t.transfer&&!i.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);const a=Object.keys(si);if(null!=t.matrix&&!a.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(null!=t.fullRange&&"boolean"!=typeof t.fullRange)throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(e.decoderConfig.codec.startsWith("avc1")||e.decoderConfig.codec.startsWith("avc3")){if(!da.test(e.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(e.decoderConfig.codec.startsWith("hev1")||e.decoderConfig.codec.startsWith("hvc1")){if(!fa.test(e.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(e.decoderConfig.codec.startsWith("vp8")){if("vp8"!==e.decoderConfig.codec)throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(e.decoderConfig.codec.startsWith("vp09")){if(!ma.test(e.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(e.decoderConfig.codec.startsWith("av01")&&!pa.test(e.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},va=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],ya=e=>{if(!e)throw new TypeError("Audio chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Audio chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!va.some(t=>e.decoderConfig.codec.startsWith(t)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==e.decoderConfig.description&&!li(e.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(e.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(e.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!e.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(e.decoderConfig.codec.startsWith("mp3")||e.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==e.decoderConfig.codec&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(e.decoderConfig.codec.startsWith("opus")){if("opus"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(e.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!e.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(e.decoderConfig.codec.startsWith("flac")){if("flac"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');const t=42;if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<t)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((e.decoderConfig.codec.startsWith("pcm")||e.decoderConfig.codec.startsWith("ulaw")||e.decoderConfig.codec.startsWith("alaw"))&&!Ki.includes(e.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Ki.join(", ")}).`)},ba=e=>{if(!e)throw new TypeError("Subtitle metadata must be provided.");if("object"!=typeof e)throw new TypeError("Subtitle metadata must be an object.");if(!e.config)throw new TypeError("Subtitle metadata must include a config object.");if("object"!=typeof e.config)throw new TypeError("Subtitle metadata config must be an object.");if("string"!=typeof e.config.description)throw new TypeError("Subtitle metadata config description must be a string.")};
17
+ class qn{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("string"!=typeof t)throw new TypeError("mimeType must be a string.")}}class Kn{constructor(e,t,r,i){if(this.data=e,this.mimeType=t,this.name=r,this.description=i,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==t&&"string"!=typeof t)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw new TypeError("name, when provided, must be a string.");if(void 0!==i&&"string"!=typeof i)throw new TypeError("description, when provided, must be a string.")}}const $n={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Qn=["avc","hevc","vp9","av1","vp8"],Zn=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Jn=["aac","opus","mp3","vorbis","flac"],eo=[...Jn,...Zn],to=["webvtt"],ro=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],io=".01.01.01.01.00",ao=".0.110.01.01.01.0",no=e=>{const t=e.split(".");return[1,1,Number(t[1]),2,1,Number(t[2]),3,1,Number(t[3]),4,1,t[4]?Number(t[4]):1]},oo=e=>{const t=e.split("."),r=Number(t[1]),i=t[2];return[129,(r<<5)+Number(i.slice(0,-1)),(("H"===i.slice(-1)?1:0)<<7)+((8===Number(t[3])?0:1)<<6)+0+((t[4]?Number(t[4]):0)<<4)+((t[5]?Number(t[5][0]):1)<<3)+((t[5]?Number(t[5][1]):1)<<2)+(t[5]?Number(t[5][2]):0),0]},so=e=>{const{codec:t,codecDescription:r,colorSpace:i,avcCodecInfo:a,hevcCodecInfo:n,vp9CodecInfo:o,av1CodecInfo:s}=e;if("avc"===t){if(Xa(null!==e.avcType),a){const t=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${e.avcType}.${dn(t)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${dn(r.subarray(1,4))}`}if("hevc"===t){let e,t,i,a,o,s;if(n)e=n.generalProfileSpace,t=n.generalProfileIdc,i=fn(n.generalProfileCompatibilityFlags),a=n.generalTierFlag,o=n.generalLevelIdc,s=[...n.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const n=Za(r),c=n.getUint8(1);e=c>>6&3,t=31&c,i=fn(n.getUint32(2)),a=c>>5&1,o=n.getUint8(12),s=[];for(let e=0;e<6;e++)s.push(n.getUint8(6+e))}let c="hev1.";for(c+=["","A","B","C"][e]+t,c+=".",c+=i.toString(16).toUpperCase(),c+=".",c+=0===a?"L":"H",c+=o;s.length>0&&0===s[s.length-1];)s.pop();return s.length>0&&(c+=".",c+=s.map(e=>e.toString(16).toUpperCase()).join(".")),c}if("vp8"===t)return"vp8";if("vp9"===t){if(!o){const t=e.width*e.height;let r=Ga(ro).level;for(const e of ro)if(t<=e.maxPictureSize){r=e.level;break}return`vp09.00.${r.toString().padStart(2,"0")}.08`}let t=`vp09.${o.profile.toString().padStart(2,"0")}.${o.level.toString().padStart(2,"0")}.${o.bitDepth.toString().padStart(2,"0")}.${o.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${o.colourPrimaries.toString().padStart(2,"0")}.${o.transferCharacteristics.toString().padStart(2,"0")}.${o.matrixCoefficients.toString().padStart(2,"0")}.${o.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(io)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!s){const t=e.width*e.height;let r=Ga(ro).level;for(const e of ro)if(t<=e.maxPictureSize){r=e.level;break}return`av01.0.${r.toString().padStart(2,"0")}M.08`}const t=s.profile,r=s.level.toString().padStart(2,"0"),a=s.tier?"H":"M",n=s.bitDepth.toString().padStart(2,"0"),o=s.monochrome?"1":"0",c=100*s.chromaSubsamplingX+10*s.chromaSubsamplingY+1*(s.chromaSubsamplingX&&s.chromaSubsamplingY?s.chromaSamplePosition:0),u=i?.primaries?rn[i.primaries]:1,l=i?.transfer?nn[i.transfer]:1,h=i?.matrix?sn[i.matrix]:1,d=i?.fullRange?1:0;let f=`av01.${t}.${r}${a}.${n}`;return f+=`.${o}.${c.toString().padStart(3,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${l.toString().padStart(2,"0")}`,f+=`.${h.toString().padStart(2,"0")}`,f+=`.${d}`,f.endsWith(ao)&&(f=f.slice(0,-17)),f}throw new TypeError(`Unhandled codec '${t}'.`)},co=e=>{const{codec:t,codecDescription:r,aacCodecInfo:i}=e;if("aac"===t){if(!i)throw new TypeError("AAC codec info must be provided.");if(i.isMpeg2)return"mp4a.67";return`mp4a.40.${ho(r).objectType}`}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if(t&&Zn.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},uo=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],lo=[-1,1,2,3,4,5,6,8],ho=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new qa(e);let r=t.readBits(5);31===r&&(r=32+t.readBits(6));const i=t.readBits(4);let a=null;15===i?a=t.readBits(24):i<uo.length&&(a=uo[i]);const n=t.readBits(4);let o=null;return n>=1&&n<=7&&(o=lo[n]),{objectType:r,frequencyIndex:i,sampleRate:a,channelConfiguration:n,numberOfChannels:o}},fo=48e3,mo=/^pcm-([usf])(\d+)+(be)?$/,po=e=>{if(Xa(Zn.includes(e)),"ulaw"===e)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===e)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const t=mo.exec(e);let r;Xa(t),r="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:r,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},go=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],vo=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,yo=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,bo=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,xo=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,To=e=>{if(!e)throw new TypeError("Video chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Video chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Video chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!go.some(t=>e.decoderConfig.codec.startsWith(t)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(void 0!==e.decoderConfig.description&&!ln(e.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==e.decoderConfig.colorSpace){const{colorSpace:t}=e.decoderConfig;if("object"!=typeof t)throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const r=Object.keys(rn);if(null!=t.primaries&&!r.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);const i=Object.keys(nn);if(null!=t.transfer&&!i.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);const a=Object.keys(sn);if(null!=t.matrix&&!a.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(null!=t.fullRange&&"boolean"!=typeof t.fullRange)throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(e.decoderConfig.codec.startsWith("avc1")||e.decoderConfig.codec.startsWith("avc3")){if(!vo.test(e.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(e.decoderConfig.codec.startsWith("hev1")||e.decoderConfig.codec.startsWith("hvc1")){if(!yo.test(e.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(e.decoderConfig.codec.startsWith("vp8")){if("vp8"!==e.decoderConfig.codec)throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(e.decoderConfig.codec.startsWith("vp09")){if(!bo.test(e.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(e.decoderConfig.codec.startsWith("av01")&&!xo.test(e.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},wo=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],ko=e=>{if(!e)throw new TypeError("Audio chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Audio chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!wo.some(t=>e.decoderConfig.codec.startsWith(t)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==e.decoderConfig.description&&!ln(e.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(e.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(e.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!e.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(e.decoderConfig.codec.startsWith("mp3")||e.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==e.decoderConfig.codec&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(e.decoderConfig.codec.startsWith("opus")){if("opus"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(e.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!e.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(e.decoderConfig.codec.startsWith("flac")){if("flac"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');const t=42;if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<t)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((e.decoderConfig.codec.startsWith("pcm")||e.decoderConfig.codec.startsWith("ulaw")||e.decoderConfig.codec.startsWith("alaw"))&&!Zn.includes(e.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Zn.join(", ")}).`)},So=e=>{if(!e)throw new TypeError("Subtitle metadata must be provided.");if("object"!=typeof e)throw new TypeError("Subtitle metadata must be an object.");if(!e.config)throw new TypeError("Subtitle metadata must include a config object.");if("object"!=typeof e.config)throw new TypeError("Subtitle metadata config must be an object.");if("string"!=typeof e.config.description)throw new TypeError("Subtitle metadata config description must be a string.")};
18
18
  /*!
19
19
  * Copyright (c) 2025-present, Vanilagy and contributors
20
20
  *
@@ -22,28 +22,28 @@ class ji{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Arr
22
22
  * License, v. 2.0. If a copy of the MPL was not distributed with this
23
23
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
24
24
  */
25
- class ka{constructor(e){this.mutex=new ui,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,r){t+=e.source._timestampOffset;let i=this.trackTimestampInfo.get(e);if(!i){if(!r)throw new Error("First packet must be a key packet.");i={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:t},this.trackTimestampInfo.set(e,i)}if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(r&&(i.maxTimestampBeforeLastKeyPacket=i.maxTimestamp),t<i.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${i.maxTimestampBeforeLastKeyPacket}s.`);return i.maxTimestamp=Math.max(i.maxTimestamp,t),t}}
25
+ class Eo{constructor(e){this.mutex=new hn,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,r){t+=e.source._timestampOffset;let i=this.trackTimestampInfo.get(e);if(!i){if(!r)throw new Error("First packet must be a key packet.");i={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:t},this.trackTimestampInfo.set(e,i)}if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(r&&(i.maxTimestampBeforeLastKeyPacket=i.maxTimestamp),t<i.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${i.maxTimestampBeforeLastKeyPacket}s.`);return i.maxTimestamp=Math.max(i.maxTimestamp,t),t}}
26
26
  /*!
27
27
  * Copyright (c) 2025-present, Vanilagy and contributors
28
28
  *
29
29
  * This Source Code Form is subject to the terms of the Mozilla Public
30
30
  * License, v. 2.0. If a copy of the MPL was not distributed with this
31
31
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
32
- */var Ta,wa;!function(e){e[e.IDR=5]="IDR",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.SPS_EXT=13]="SPS_EXT"}(Ta||(Ta={})),function(e){e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(wa||(wa={}));const Sa=e=>{const t=[];let r=0;for(;r<e.length;){let i=-1,a=0;for(let t=r;t<e.length-3;t++){if(0===e[t]&&0===e[t+1]&&1===e[t+2]){i=t,a=3;break}if(t<e.length-4&&0===e[t]&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]){i=t,a=4;break}}if(-1===i)break;if(r>0&&i>r){const a=e.subarray(r,i);a.length>0&&t.push(a)}r=i+a}if(r<e.length){const i=e.subarray(r);i.length>0&&t.push(i)}return t},xa=(e,t)=>{const r=[];let i=0;const a=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;i+t<=e.length;){let n;1===t?n=a.getUint8(i):2===t?n=a.getUint16(i,!1):3===t?n=ki(a,i,!1):4===t?n=a.getUint32(i,!1):(bi(t),jr(!1)),i+=t;const s=e.subarray(i,i+n);r.push(s),i+=n}return r},Ca=e=>{const t=[],r=e.length;for(let i=0;i<r;i++)i+2<r&&0===e[i]&&0===e[i+1]&&3===e[i+2]?(t.push(0,0),i+=2):t.push(e[i]);return new Uint8Array(t)},Ea=e=>31&e[0],Aa=e=>{try{const t=Sa(e),r=t.filter(e=>Ea(e)===Ta.SPS),i=t.filter(e=>Ea(e)===Ta.PPS),a=t.filter(e=>Ea(e)===Ta.SPS_EXT);if(0===r.length)return null;if(0===i.length)return null;const n=r[0],s=Pa(n);jr(null!==s);const o=100===s.profileIdc||110===s.profileIdc||122===s.profileIdc||144===s.profileIdc;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:r,pictureParameterSets:i,chromaFormat:o?s.chromaFormatIdc:null,bitDepthLumaMinus8:o?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?a:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},Pa=e=>{try{const t=new Kr(Ca(e));t.skipBits(1),t.skipBits(2);if(7!==t.readBits(5))return null;const r=t.readAlignedByte(),i=t.readAlignedByte(),a=t.readAlignedByte();Yr(t);let n=null,s=null,o=null;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){n=Yr(t),3===n&&t.skipBits(1),s=Yr(t),o=Yr(t),t.skipBits(1);if(t.readBits(1))for(let e=0;e<(3!==n?8:12);e++){if(t.readBits(1)){const r=e<6?16:64;let i=8,a=8;for(let e=0;e<r;e++){if(0!==a){a=(i+$r(t)+256)%256}i=0===a?i:a}}}}Yr(t);const c=Yr(t);if(0===c)Yr(t);else if(1===c){t.skipBits(1),$r(t),$r(t);const e=Yr(t);for(let r=0;r<e;r++)$r(t)}Yr(t),t.skipBits(1),Yr(t),Yr(t);return{profileIdc:r,constraintFlags:i,levelIdc:a,frameMbsOnlyFlag:t.readBits(1),chromaFormatIdc:n,bitDepthLumaMinus8:s,bitDepthChromaMinus8:o}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},Ia=(e,t)=>{if(t.description){const r=3&Qr(t.description)[21];return xa(e,r+1)}return Sa(e)},Ra=e=>e[0]>>1&63,Oa=e=>{try{const t=Sa(e),r=t.filter(e=>Ra(e)===wa.VPS_NUT),i=t.filter(e=>Ra(e)===wa.SPS_NUT),a=t.filter(e=>Ra(e)===wa.PPS_NUT),n=t.filter(e=>Ra(e)===wa.PREFIX_SEI_NUT||Ra(e)===wa.SUFFIX_SEI_NUT);if(0===i.length||0===a.length)return null;const s=i[0],o=new Kr(Ca(s));o.skipBits(16),o.readBits(4);const c=o.readBits(3),l=o.readBits(1),{general_profile_space:u,general_tier_flag:h,general_profile_idc:d,general_profile_compatibility_flags:f,general_constraint_indicator_flags:m,general_level_idc:p}=Ma(o,c);Yr(o);const g=Yr(o);3===g&&o.skipBits(1),Yr(o),Yr(o),o.readBits(1)&&(Yr(o),Yr(o),Yr(o),Yr(o));const v=Yr(o),y=Yr(o);Yr(o);const b=o.readBits(1);for(let e=b?0:c;e<=c;e++)Yr(o),Yr(o),Yr(o);Yr(o),Yr(o),Yr(o),Yr(o),Yr(o),Yr(o),o.readBits(1)&&o.readBits(1)&&_a(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),Yr(o),Yr(o),o.skipBits(1));const k=Yr(o);if(Da(o,k),o.readBits(1)){const e=Yr(o);for(let t=0;t<e;t++)Yr(o),o.skipBits(1)}o.skipBits(1),o.skipBits(1);let T=0;o.readBits(1)&&(T=Fa(o,c));let w=0;if(a.length>0){const e=a[0],t=new Kr(Ca(e));t.skipBits(16),Yr(t),Yr(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),Yr(t),Yr(t),$r(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&Yr(t),$r(t),$r(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const r=t.readBits(1),i=t.readBits(1);w=r||i?r&&!i?2:!r&&i?3:0:0}const S=[...r.length?[{arrayCompleteness:1,nalUnitType:wa.VPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:wa.SPS_NUT,nalUnits:i}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:wa.PPS_NUT,nalUnits:a}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Ra(n[0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:u,generalTierFlag:h,generalProfileIdc:d,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:m,generalLevelIdc:p,minSpatialSegmentationIdc:T,parallelismType:w,chromaFormatIdc:g,bitDepthLumaMinus8:v,bitDepthChromaMinus8:y,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:l,lengthSizeMinusOne:3,arrays:S}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},Ma=(e,t)=>{const r=e.readBits(2),i=e.readBits(1),a=e.readBits(5);let n=0;for(let t=0;t<32;t++)n=n<<1|e.readBits(1);const s=new Uint8Array(6);for(let t=0;t<6;t++)s[t]=e.readBits(8);const o=e.readBits(8),c=[],l=[];for(let r=0;r<t;r++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let r=t;r<8;r++)e.skipBits(2);for(let r=0;r<t;r++)c[r]&&e.skipBits(88),l[r]&&e.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:a,general_profile_compatibility_flags:n,general_constraint_indicator_flags:s,general_level_idc:o}},_a=e=>{for(let t=0;t<4;t++)for(let r=0;r<(3===t?2:6);r++){if(e.readBits(1)){const r=Math.min(64,1<<4+(t<<1));t>1&&$r(e);for(let t=0;t<r;t++)$r(e)}else Yr(e)}},Da=(e,t)=>{const r=[];for(let i=0;i<t;i++)r[i]=Ba(e,i,t,r)},Ba=(e,t,r,i)=>{let a=0,n=0,s=0;if(0!==t&&(n=e.readBits(1)),n){if(t===r){s=t-(Yr(e)+1)}else s=t-1;e.readBits(1),Yr(e);const n=i[s]??0;for(let t=0;t<=n;t++){e.readBits(1)||e.readBits(1)}a=i[s]}else{const t=Yr(e),r=Yr(e);for(let r=0;r<t;r++)Yr(e),e.readBits(1);for(let t=0;t<r;t++)Yr(e),e.readBits(1);a=t+r}return a},Fa=(e,t)=>{if(e.readBits(1)){255===e.readBits(8)&&(e.readBits(16),e.readBits(16))}if(e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),e.readBits(1),e.readBits(1)&&(e.readBits(8),e.readBits(8),e.readBits(8))),e.readBits(1)&&(Yr(e),Yr(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(Yr(e),Yr(e),Yr(e),Yr(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&Yr(e),e.readBits(1)&&Na(e,!0,t)),e.readBits(1)){e.readBits(1),e.readBits(1),e.readBits(1);const t=Yr(e);return Yr(e),Yr(e),Yr(e),Yr(e),t}return 0},Na=(e,t,r)=>{let i=!1,a=!1,n=!1;i=1===e.readBits(1),a=1===e.readBits(1),(i||a)&&(n=1===e.readBits(1),n&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),n&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let t=0;t<=r;t++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let r=!1;t?Yr(e):r=1===e.readBits(1);let s=1;if(!r){s=Yr(e)+1}i&&La(e,s,n),a&&La(e,s,n)}},La=(e,t,r)=>{for(let i=0;i<t;i++)Yr(e),Yr(e),r&&(Yr(e),Yr(e)),e.readBits(1)},Ua=e=>{const t=new Kr(e);if(2!==t.readBits(2))return null;const r=t.readBits(1),i=(t.readBits(1)<<1)+r;3===i&&t.skipBits(1);if(1===t.readBits(1))return null;if(0!==t.readBits(1))return null;t.skipBits(2);if(4817730!==t.readBits(24))return null;let a=8;if(i>=2){a=t.readBits(1)?12:10}const n=t.readBits(3);let s=0,o=0;if(7!==n){if(o=t.readBits(1),1===i||3===i){const e=t.readBits(1),r=t.readBits(1);s=e||r?e&&!r?2:1:3,t.skipBits(1)}else s=1}else s=3,o=1;const c=(t.readBits(16)+1)*(t.readBits(16)+1);let l=qr(Zi).level;for(const e of Zi)if(c<=e.maxPictureSize){l=e.level;break}return{profile:i,level:l,bitDepth:a,chromaSubsampling:s,videoFullRangeFlag:o,colourPrimaries:2===n?1:1===n?6:2,transferCharacteristics:2===n?1:1===n?6:2,matrixCoefficients:7===n?0:2===n?1:1===n?6:2}},za=function*(e){const t=new Kr(e),r=()=>{let e=0;for(let r=0;r<8;r++){const i=t.readAlignedByte();if(e|=(127&i)<<7*r,!(128&i))break;if(7===r&&128&i)return null}return e>=2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const i=t.readBits(4),a=t.readBits(1),n=t.readBits(1);let s;if(t.skipBits(1),a&&t.skipBits(8),n){const e=r();if(null===e)return;s=e}else s=Math.floor(t.getBitsLeft()/8);jr(t.pos%8==0),yield{type:i,data:e.subarray(t.pos/8,t.pos/8+s)},t.skipBits(8*s)}},Wa=e=>{for(const{type:t,data:r}of za(e)){if(1!==t)continue;const e=new Kr(r),i=e.readBits(3);e.readBits(1);let a=0,n=0,s=0;if(e.readBits(1))a=e.readBits(5);else{if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1))return null}const t=e.readBits(1);t&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));const r=e.readBits(5);for(let i=0;i<=r;i++){e.skipBits(12);const r=e.readBits(5);if(0===i&&(a=r),r>7){const t=e.readBits(1);0===i&&(n=t)}if(t){if(e.readBits(1)){const t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}e.readBits(1)&&e.skipBits(4)}}const o=e.readBits(1);let c=8;if(2===i&&o){c=e.readBits(1)?12:10}else i<=2&&(c=o?10:8);let l=0;1!==i&&(l=e.readBits(1));let u=1,h=1,d=0;return l||(0===i?(u=1,h=1):1===i?(u=0,h=0):12===c&&(u=e.readBits(1),u&&(h=e.readBits(1))),u&&h&&(d=e.readBits(2))),{profile:i,level:a,tier:n,bitDepth:c,monochrome:l,chromaSubsamplingX:u,chromaSubsamplingY:h,chromaSamplePosition:d}}return null},Va=e=>{const t=Zr(e),r=t.getUint8(9),i=t.getUint16(10,!0),a=t.getUint32(12,!0),n=t.getInt16(16,!0),s=t.getUint8(18);let o=null;return s&&(o=e.subarray(19,21+r)),{outputChannelCount:r,preSkip:i,inputSampleRate:a,outputGain:n,channelMappingFamily:s,channelMappingTable:o}},Ha=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],ja=e=>{if(e.length<7)throw new Error("Setup header is too short.");if(5!==e[0])throw new Error("Wrong packet type in Setup header.");if("vorbis"!==String.fromCharCode(...e.slice(1,7)))throw new Error("Invalid packet signature in Setup header.");const t=e.length,r=new Uint8Array(t);for(let i=0;i<t;i++)r[i]=e[t-1-i];const i=new Kr(r);let a=0;for(;i.getBitsLeft()>97;)if(1===i.readBits(1)){a=i.pos;break}if(0===a)throw new Error("Invalid Setup header: framing bit not found.");let n=0,s=!1,o=0;for(;i.getBitsLeft()>=97;){const e=i.pos,t=i.readBits(8),r=i.readBits(16),a=i.readBits(16);if(t>63||0!==r||0!==a){i.pos=e;break}if(i.skipBits(1),n++,n>64)break;i.clone().readBits(6)+1===n&&(s=!0,o=n)}if(!s)throw new Error("Invalid Setup header: mode header not found.");if(o>63)throw new Error(`Unsupported mode count: ${o}.`);const c=o;i.pos=0,i.skipBits(a);const l=Array(c).fill(0);for(let e=c-1;e>=0;e--)i.skipBits(40),l[e]=i.readBits(1);return{modeBlockflags:l}},Xa=(e,t,r)=>{switch(e){case"avc":{const e=((e,t)=>{if(t.description){const r=3&Qr(t.description)[4];return xa(e,r+1)}return Sa(e)})(r,t);return e.some(e=>Ea(e)===Ta.IDR)?"key":"delta"}case"hevc":{const e=Ia(r,t).some(e=>{const t=Ra(e);return wa.BLA_W_LP<=t&&t<=wa.RSV_IRAP_VCL23});return e?"key":"delta"}case"vp8":return 0===(1&r[0])?"key":"delta";case"vp9":{const e=new Kr(r);if(2!==e.readBits(2))return null;const t=e.readBits(1);3===(e.readBits(1)<<1)+t&&e.skipBits(1);if(e.readBits(1))return null;return 0===e.readBits(1)?"key":"delta"}case"av1":{let e=!1;for(const{type:t,data:i}of za(r))if(1===t){const t=new Kr(i);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";const t=new Kr(i);if(t.readBits(1))return null;return 0===t.readBits(2)?"key":"delta"}return null}default:bi(e),jr(!1)}};var qa;!function(e){e[e.STREAMINFO=0]="STREAMINFO",e[e.VORBIS_COMMENT=4]="VORBIS_COMMENT",e[e.PICTURE=6]="PICTURE"}(qa||(qa={}));const Ga=(e,t)=>{const r=Zr(e);let i=0;const a=r.getUint32(i,!0);i+=4;const n=Jr.decode(e.subarray(i,i+a));i+=a,a>0&&(t.raw??={},t.raw.vendor??=n);const s=r.getUint32(i,!0);i+=4;for(let a=0;a<s;a++){const a=r.getUint32(i,!0);i+=4;const n=Jr.decode(e.subarray(i,i+a));i+=a;const s=n.indexOf("=");if(-1===s)continue;const o=n.slice(0,s).toUpperCase(),c=n.slice(s+1);switch(t.raw??={},t.raw[o]??=c,o){case"TITLE":t.title??=c;break;case"DESCRIPTION":t.description??=c;break;case"ARTIST":t.artist??=c;break;case"ALBUM":t.album??=c;break;case"ALBUMARTIST":t.albumArtist??=c;break;case"COMMENT":t.comment??=c;break;case"LYRICS":t.lyrics??=c;break;case"TRACKNUMBER":{const e=c.split("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(t.trackNumber??=r),i&&Number.isInteger(i)&&i>0&&(t.tracksTotal??=i)}break;case"TRACKTOTAL":{const e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case"DISCNUMBER":{const e=c.split("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(t.discNumber??=r),i&&Number.isInteger(i)&&i>0&&(t.discsTotal??=i)}break;case"DISCTOTAL":{const e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case"DATE":{const e=new Date(c);Number.isNaN(e.getTime())||(t.date??=e)}break;case"GENRE":t.genre??=c;break;case"METADATA_BLOCK_PICTURE":{const e=zi(c),r=Zr(e),i=r.getUint32(0,!1),a=r.getUint32(4,!1),n=String.fromCharCode(...e.subarray(8,8+a)),s=r.getUint32(8+a,!1),o=Jr.decode(e.subarray(12+a,12+a+s)),l=r.getUint32(a+s+28),u=e.subarray(a+s+32,a+s+32+l);t.images??=[],t.images.push({data:u,mimeType:n,kind:3===i?"coverFront":4===i?"coverBack":"unknown",name:void 0,description:o||void 0})}}}};
32
+ */var Co,Ao;!function(e){e[e.IDR=5]="IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.SPS_EXT=13]="SPS_EXT"}(Co||(Co={})),function(e){e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(Ao||(Ao={}));const _o=e=>{const t=[];let r=0;for(;r<e.length;){let i=-1,a=0;for(let t=r;t<e.length-3;t++){if(0===e[t]&&0===e[t+1]&&1===e[t+2]){i=t,a=3;break}if(t<e.length-4&&0===e[t]&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]){i=t,a=4;break}}if(-1===i)break;if(r>0&&i>r){const a=e.subarray(r,i);a.length>0&&t.push(a)}r=i+a}if(r<e.length){const i=e.subarray(r);i.length>0&&t.push(i)}return t},Mo=(e,t)=>{const r=[];let i=0;const a=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;i+t<=e.length;){let n;1===t?n=a.getUint8(i):2===t?n=a.getUint16(i,!1):3===t?n=Tn(a,i,!1):4===t?n=a.getUint32(i,!1):(xn(t),Xa(!1)),i+=t;const o=e.subarray(i,i+n);r.push(o),i+=n}return r},Io=e=>{const t=[],r=e.length;for(let i=0;i<r;i++)i+2<r&&0===e[i]&&0===e[i+1]&&3===e[i+2]?(t.push(0,0),i+=2):t.push(e[i]);return new Uint8Array(t)},Ro=new Uint8Array([0,0,0,1]),Po=(e,t)=>{const r=e.reduce((e,r)=>e+t+r.byteLength,0),i=new Uint8Array(r);let a=0;for(const r of e){const e=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(t){case 1:e.setUint8(a,r.byteLength);break;case 2:e.setUint16(a,r.byteLength,!1);break;case 3:wn(e,a,r.byteLength);break;case 4:e.setUint32(a,r.byteLength,!1)}a+=t,i.set(r,a),a+=r.byteLength}return i},Oo=(e,t)=>{if(t.description){const r=3&Qa(t.description)[4];return Mo(e,r+1)}return _o(e)},Do=(e,t)=>{if(t.description){const r=3&Qa(t.description)[4];return Po(e,r+1)}return(e=>{const t=e.reduce((e,t)=>e+Ro.byteLength+t.byteLength,0),r=new Uint8Array(t);let i=0;for(const t of e)r.set(Ro,i),i+=Ro.byteLength,r.set(t,i),i+=t.byteLength;return r})(e)},Bo=e=>31&e[0],Fo=e=>{try{const t=_o(e),r=t.filter(e=>Bo(e)===Co.SPS),i=t.filter(e=>Bo(e)===Co.PPS),a=t.filter(e=>Bo(e)===Co.SPS_EXT);if(0===r.length)return null;if(0===i.length)return null;const n=r[0],o=Lo(n);Xa(null!==o);const s=100===o.profileIdc||110===o.profileIdc||122===o.profileIdc||144===o.profileIdc;return{configurationVersion:1,avcProfileIndication:o.profileIdc,profileCompatibility:o.constraintFlags,avcLevelIndication:o.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:r,pictureParameterSets:i,chromaFormat:s?o.chromaFormatIdc:null,bitDepthLumaMinus8:s?o.bitDepthLumaMinus8:null,bitDepthChromaMinus8:s?o.bitDepthChromaMinus8:null,sequenceParameterSetExt:s?a:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},Lo=e=>{try{const t=new qa(Io(e));t.skipBits(1),t.skipBits(2);if(7!==t.readBits(5))return null;const r=t.readAlignedByte(),i=t.readAlignedByte(),a=t.readAlignedByte();Ka(t);let n=null,o=null,s=null;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){n=Ka(t),3===n&&t.skipBits(1),o=Ka(t),s=Ka(t),t.skipBits(1);if(t.readBits(1))for(let e=0;e<(3!==n?8:12);e++){if(t.readBits(1)){const r=e<6?16:64;let i=8,a=8;for(let e=0;e<r;e++){if(0!==a){a=(i+$a(t)+256)%256}i=0===a?i:a}}}}Ka(t);const c=Ka(t);if(0===c)Ka(t);else if(1===c){t.skipBits(1),$a(t),$a(t);const e=Ka(t);for(let r=0;r<e;r++)$a(t)}Ka(t),t.skipBits(1),Ka(t),Ka(t);return{profileIdc:r,constraintFlags:i,levelIdc:a,frameMbsOnlyFlag:t.readBits(1),chromaFormatIdc:n,bitDepthLumaMinus8:o,bitDepthChromaMinus8:s}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},No=(e,t)=>{if(t.description){const r=3&Qa(t.description)[21];return Mo(e,r+1)}return _o(e)},Uo=e=>e[0]>>1&63,zo=e=>{try{const t=_o(e),r=t.filter(e=>Uo(e)===Ao.VPS_NUT),i=t.filter(e=>Uo(e)===Ao.SPS_NUT),a=t.filter(e=>Uo(e)===Ao.PPS_NUT),n=t.filter(e=>Uo(e)===Ao.PREFIX_SEI_NUT||Uo(e)===Ao.SUFFIX_SEI_NUT);if(0===i.length||0===a.length)return null;const o=i[0],s=new qa(Io(o));s.skipBits(16),s.readBits(4);const c=s.readBits(3),u=s.readBits(1),{general_profile_space:l,general_tier_flag:h,general_profile_idc:d,general_profile_compatibility_flags:f,general_constraint_indicator_flags:m,general_level_idc:p}=Wo(s,c);Ka(s);const g=Ka(s);3===g&&s.skipBits(1),Ka(s),Ka(s),s.readBits(1)&&(Ka(s),Ka(s),Ka(s),Ka(s));const v=Ka(s),y=Ka(s);Ka(s);const b=s.readBits(1);for(let e=b?0:c;e<=c;e++)Ka(s),Ka(s),Ka(s);Ka(s),Ka(s),Ka(s),Ka(s),Ka(s),Ka(s),s.readBits(1)&&s.readBits(1)&&Vo(s),s.skipBits(1),s.skipBits(1),s.readBits(1)&&(s.skipBits(4),s.skipBits(4),Ka(s),Ka(s),s.skipBits(1));const x=Ka(s);if(Ho(s,x),s.readBits(1)){const e=Ka(s);for(let t=0;t<e;t++)Ka(s),s.skipBits(1)}s.skipBits(1),s.skipBits(1);let T=0;s.readBits(1)&&(T=jo(s,c));let w=0;if(a.length>0){const e=a[0],t=new qa(Io(e));t.skipBits(16),Ka(t),Ka(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),Ka(t),Ka(t),$a(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&Ka(t),$a(t),$a(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const r=t.readBits(1),i=t.readBits(1);w=r||i?r&&!i?2:!r&&i?3:0:0}const k=[...r.length?[{arrayCompleteness:1,nalUnitType:Ao.VPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ao.SPS_NUT,nalUnits:i}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Ao.PPS_NUT,nalUnits:a}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Uo(n[0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:l,generalTierFlag:h,generalProfileIdc:d,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:m,generalLevelIdc:p,minSpatialSegmentationIdc:T,parallelismType:w,chromaFormatIdc:g,bitDepthLumaMinus8:v,bitDepthChromaMinus8:y,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:u,lengthSizeMinusOne:3,arrays:k}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},Wo=(e,t)=>{const r=e.readBits(2),i=e.readBits(1),a=e.readBits(5);let n=0;for(let t=0;t<32;t++)n=n<<1|e.readBits(1);const o=new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);const s=e.readBits(8),c=[],u=[];for(let r=0;r<t;r++)c.push(e.readBits(1)),u.push(e.readBits(1));if(t>0)for(let r=t;r<8;r++)e.skipBits(2);for(let r=0;r<t;r++)c[r]&&e.skipBits(88),u[r]&&e.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:a,general_profile_compatibility_flags:n,general_constraint_indicator_flags:o,general_level_idc:s}},Vo=e=>{for(let t=0;t<4;t++)for(let r=0;r<(3===t?2:6);r++){if(e.readBits(1)){const r=Math.min(64,1<<4+(t<<1));t>1&&$a(e);for(let t=0;t<r;t++)$a(e)}else Ka(e)}},Ho=(e,t)=>{const r=[];for(let i=0;i<t;i++)r[i]=Xo(e,i,t,r)},Xo=(e,t,r,i)=>{let a=0,n=0,o=0;if(0!==t&&(n=e.readBits(1)),n){if(t===r){o=t-(Ka(e)+1)}else o=t-1;e.readBits(1),Ka(e);const n=i[o]??0;for(let t=0;t<=n;t++){e.readBits(1)||e.readBits(1)}a=i[o]}else{const t=Ka(e),r=Ka(e);for(let r=0;r<t;r++)Ka(e),e.readBits(1);for(let t=0;t<r;t++)Ka(e),e.readBits(1);a=t+r}return a},jo=(e,t)=>{if(e.readBits(1)){255===e.readBits(8)&&(e.readBits(16),e.readBits(16))}if(e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),e.readBits(1),e.readBits(1)&&(e.readBits(8),e.readBits(8),e.readBits(8))),e.readBits(1)&&(Ka(e),Ka(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(Ka(e),Ka(e),Ka(e),Ka(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&Ka(e),e.readBits(1)&&Go(e,!0,t)),e.readBits(1)){e.readBits(1),e.readBits(1),e.readBits(1);const t=Ka(e);return Ka(e),Ka(e),Ka(e),Ka(e),t}return 0},Go=(e,t,r)=>{let i=!1,a=!1,n=!1;i=1===e.readBits(1),a=1===e.readBits(1),(i||a)&&(n=1===e.readBits(1),n&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),n&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let t=0;t<=r;t++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let r=!1;t?Ka(e):r=1===e.readBits(1);let o=1;if(!r){o=Ka(e)+1}i&&Yo(e,o,n),a&&Yo(e,o,n)}},Yo=(e,t,r)=>{for(let i=0;i<t;i++)Ka(e),Ka(e),r&&(Ka(e),Ka(e)),e.readBits(1)},qo=e=>{const t=new qa(e);if(2!==t.readBits(2))return null;const r=t.readBits(1),i=(t.readBits(1)<<1)+r;3===i&&t.skipBits(1);if(1===t.readBits(1))return null;if(0!==t.readBits(1))return null;t.skipBits(2);if(4817730!==t.readBits(24))return null;let a=8;if(i>=2){a=t.readBits(1)?12:10}const n=t.readBits(3);let o=0,s=0;if(7!==n){if(s=t.readBits(1),1===i||3===i){const e=t.readBits(1),r=t.readBits(1);o=e||r?e&&!r?2:1:3,t.skipBits(1)}else o=1}else o=3,s=1;const c=(t.readBits(16)+1)*(t.readBits(16)+1);let u=Ga(ro).level;for(const e of ro)if(c<=e.maxPictureSize){u=e.level;break}return{profile:i,level:u,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:2===n?1:1===n?6:2,transferCharacteristics:2===n?1:1===n?6:2,matrixCoefficients:7===n?0:2===n?1:1===n?6:2}},Ko=function*(e){const t=new qa(e),r=()=>{let e=0;for(let r=0;r<8;r++){const i=t.readAlignedByte();if(e|=(127&i)<<7*r,!(128&i))break;if(7===r&&128&i)return null}return e>=2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const i=t.readBits(4),a=t.readBits(1),n=t.readBits(1);let o;if(t.skipBits(1),a&&t.skipBits(8),n){const e=r();if(null===e)return;o=e}else o=Math.floor(t.getBitsLeft()/8);Xa(t.pos%8==0),yield{type:i,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(8*o)}},$o=e=>{for(const{type:t,data:r}of Ko(e)){if(1!==t)continue;const e=new qa(r),i=e.readBits(3);e.readBits(1);const a=e.readBits(1);let n=0,o=0,s=0;if(a)n=e.readBits(5);else{if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1))return null}const t=e.readBits(1);t&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));const r=e.readBits(5);for(let i=0;i<=r;i++){e.skipBits(12);const r=e.readBits(5);if(0===i&&(n=r),r>7){const t=e.readBits(1);0===i&&(o=t)}if(t){if(e.readBits(1)){const t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}e.readBits(1)&&e.skipBits(4)}}const c=e.readBits(4),u=e.readBits(4),l=c+1;e.skipBits(l);const h=u+1;e.skipBits(h);let d=0;if(d=a?0:e.readBits(1),d&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!a){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let r=0;if(r=e.readBits(1)?2:e.readBits(1),r>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const f=e.readBits(1);let m=8;if(2===i&&f){m=e.readBits(1)?12:10}else i<=2&&(m=f?10:8);let p=0;1!==i&&(p=e.readBits(1));let g=1,v=1,y=0;return p||(0===i?(g=1,v=1):1===i?(g=0,v=0):12===m&&(g=e.readBits(1),g&&(v=e.readBits(1))),g&&v&&(y=e.readBits(2))),{profile:i,level:n,tier:o,bitDepth:m,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:v,chromaSamplePosition:y}}return null},Qo=e=>{const t=Za(e),r=t.getUint8(9),i=t.getUint16(10,!0),a=t.getUint32(12,!0),n=t.getInt16(16,!0),o=t.getUint8(18);let s=null;return o&&(s=e.subarray(19,21+r)),{outputChannelCount:r,preSkip:i,inputSampleRate:a,outputGain:n,channelMappingFamily:o,channelMappingTable:s}},Zo=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Jo=e=>{if(e.length<7)throw new Error("Setup header is too short.");if(5!==e[0])throw new Error("Wrong packet type in Setup header.");if("vorbis"!==String.fromCharCode(...e.slice(1,7)))throw new Error("Invalid packet signature in Setup header.");const t=e.length,r=new Uint8Array(t);for(let i=0;i<t;i++)r[i]=e[t-1-i];const i=new qa(r);let a=0;for(;i.getBitsLeft()>97;)if(1===i.readBits(1)){a=i.pos;break}if(0===a)throw new Error("Invalid Setup header: framing bit not found.");let n=0,o=!1,s=0;for(;i.getBitsLeft()>=97;){const e=i.pos,t=i.readBits(8),r=i.readBits(16),a=i.readBits(16);if(t>63||0!==r||0!==a){i.pos=e;break}if(i.skipBits(1),n++,n>64)break;i.clone().readBits(6)+1===n&&(o=!0,s=n)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(s>63)throw new Error(`Unsupported mode count: ${s}.`);const c=s;i.pos=0,i.skipBits(a);const u=Array(c).fill(0);for(let e=c-1;e>=0;e--)i.skipBits(40),u[e]=i.readBits(1);return{modeBlockflags:u}},es=(e,t,r)=>{switch(e){case"avc":{const e=Oo(r,t);let i=e.some(e=>Bo(e)===Co.IDR);if(!i&&(!Nn()||(()=>{if(null!==Un)return Un;if("undefined"==typeof navigator)return null;const e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?Un=Number(e[1]):null})()>=144))for(const t of e){if(Bo(t)!==Co.SEI)continue;const e=Io(t);let r=1;do{let t=0;for(;;){const i=e[r++];if(void 0===i)break;if(t+=i,i<255)break}let a=0;for(;;){const t=e[r++];if(void 0===t)break;if(a+=t,t<255)break}if(t===6){const t=new qa(e);t.pos=8*r;const a=Ka(t),n=t.readBits(1);if(0===a&&1===n){i=!0;break}}r+=a}while(r<e.length-1)}return i?"key":"delta"}case"hevc":{const e=No(r,t).some(e=>{const t=Uo(e);return Ao.BLA_W_LP<=t&&t<=Ao.RSV_IRAP_VCL23});return e?"key":"delta"}case"vp8":return 0===(1&r[0])?"key":"delta";case"vp9":{const e=new qa(r);if(2!==e.readBits(2))return null;const t=e.readBits(1);3===(e.readBits(1)<<1)+t&&e.skipBits(1);if(e.readBits(1))return null;return 0===e.readBits(1)?"key":"delta"}case"av1":{let e=!1;for(const{type:t,data:i}of Ko(r))if(1===t){const t=new qa(i);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";const t=new qa(i);if(t.readBits(1))return null;return 0===t.readBits(2)?"key":"delta"}return null}default:xn(e),Xa(!1)}};var ts;!function(e){e[e.STREAMINFO=0]="STREAMINFO",e[e.VORBIS_COMMENT=4]="VORBIS_COMMENT",e[e.PICTURE=6]="PICTURE"}(ts||(ts={}));const rs=(e,t)=>{const r=Za(e);let i=0;const a=r.getUint32(i,!0);i+=4;const n=Ja.decode(e.subarray(i,i+a));i+=a,a>0&&(t.raw??={},t.raw.vendor??=n);const o=r.getUint32(i,!0);i+=4;for(let a=0;a<o;a++){const a=r.getUint32(i,!0);i+=4;const n=Ja.decode(e.subarray(i,i+a));i+=a;const o=n.indexOf("=");if(-1===o)continue;const s=n.slice(0,o).toUpperCase(),c=n.slice(o+1);switch(t.raw??={},t.raw[s]??=c,s){case"TITLE":t.title??=c;break;case"DESCRIPTION":t.description??=c;break;case"ARTIST":t.artist??=c;break;case"ALBUM":t.album??=c;break;case"ALBUMARTIST":t.albumArtist??=c;break;case"COMMENT":t.comment??=c;break;case"LYRICS":t.lyrics??=c;break;case"TRACKNUMBER":{const e=c.split("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(t.trackNumber??=r),i&&Number.isInteger(i)&&i>0&&(t.tracksTotal??=i)}break;case"TRACKTOTAL":{const e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case"DISCNUMBER":{const e=c.split("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(t.discNumber??=r),i&&Number.isInteger(i)&&i>0&&(t.discsTotal??=i)}break;case"DISCTOTAL":{const e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case"DATE":{const e=new Date(c);Number.isNaN(e.getTime())||(t.date??=e)}break;case"GENRE":t.genre??=c;break;case"METADATA_BLOCK_PICTURE":{const e=Xn(c),r=Za(e),i=r.getUint32(0,!1),a=r.getUint32(4,!1),n=String.fromCharCode(...e.subarray(8,8+a)),o=r.getUint32(8+a,!1),s=Ja.decode(e.subarray(12+a,12+a+o)),u=r.getUint32(a+o+28),l=e.subarray(a+o+32,a+o+32+u);t.images??=[],t.images.push({data:l,mimeType:n,kind:3===i?"coverFront":4===i?"coverBack":"unknown",name:void 0,description:s||void 0})}}}};
33
33
  /*!
34
34
  * Copyright (c) 2025-present, Vanilagy and contributors
35
35
  *
36
36
  * This Source Code Form is subject to the terms of the Mozilla Public
37
37
  * License, v. 2.0. If a copy of the MPL was not distributed with this
38
38
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
39
- */class Ka{constructor(e){this.input=e}}
39
+ */class is{constructor(e){this.input=e}}
40
40
  /*!
41
41
  * Copyright (c) 2025-present, Vanilagy and contributors
42
42
  *
43
43
  * This Source Code Form is subject to the terms of the Mozilla Public
44
44
  * License, v. 2.0. If a copy of the MPL was not distributed with this
45
45
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
46
- */const Ya=[],$a=[],Qa=new Uint8Array(0);class Za{constructor(e,t,r,i,a=-1,n,s){if(this.data=e,this.type=t,this.timestamp=r,this.duration=i,this.sequenceNumber=a,e===Qa&&void 0===n)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===n&&(n=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(i)||i<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(n)||n<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==s&&("object"!=typeof s||!s))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==s?.alpha&&!(s.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==s?.alphaByteLength&&(!Number.isInteger(s.alphaByteLength)||s.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=n,this.sideData=s??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Qa}get microsecondTimestamp(){return Math.trunc(Ai*this.timestamp)}get microsecondDuration(){return Math.trunc(Ai*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"==typeof EncodedAudioChunk)throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new Za(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(void 0!==e&&("object"!=typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new Za(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}
46
+ */const as=[],ns=[],os=new Uint8Array(0);class ss{constructor(e,t,r,i,a=-1,n,o){if(this.data=e,this.type=t,this.timestamp=r,this.duration=i,this.sequenceNumber=a,e===os&&void 0===n)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===n&&(n=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(i)||i<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(n)||n<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==o&&("object"!=typeof o||!o))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==o?.alpha&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==o?.alphaByteLength&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=n,this.sideData=o??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===os}get microsecondTimestamp(){return Math.trunc(Mn*this.timestamp)}get microsecondDuration(){return Math.trunc(Mn*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"==typeof EncodedAudioChunk)throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new ss(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(void 0!==e&&("object"!=typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new ss(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}
47
47
  /*!
48
48
  * Copyright (c) 2025-present, Vanilagy and contributors
49
49
  *
@@ -58,21 +58,21 @@ class ka{constructor(e){this.mutex=new ui,this.firstMediaStreamTimestamp=null,th
58
58
  * License, v. 2.0. If a copy of the MPL was not distributed with this
59
59
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
60
60
  */
61
- Vi();class Ja{get displayWidth(){return this.rotation%180==0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180==0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(Ai*this.timestamp)}get microsecondDuration(){return Math.trunc(Ai*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!=typeof t)throw new TypeError("init must be an object.");if(!("format"in t)||"string"!=typeof t.format)throw new TypeError("init.format must be a string.");if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=Qr(e).slice(),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace(t.colorSpace)}else if("undefined"!=typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==t?.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==t?.timestamp&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==t?.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=e.colorSpace}else{if(!("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");{if(!t||"object"!=typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!=typeof VideoFrame)return new Ja(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Ai),duration:Math.trunc((t.duration??0)*Ai)||void 0}),t);let r=0,i=0;if("naturalWidth"in e?(r=e.naturalWidth,i=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,i=e.videoHeight):"width"in e&&(r=Number(e.width),i=Number(e.height)),!r||!i)throw new TypeError("Could not determine dimensions.");const a=new OffscreenCanvas(r,i),n=a.getContext("2d",{alpha:null!==Di?Di:Di="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),willReadFrequently:!0});jr(n),n.drawImage(e,0,0),this._data=a,this.format="RGBX",this.codedWidth=r,this.codedHeight=i,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}}}clone(){if(this._closed)throw new Error("VideoSample is closed.");return jr(null!==this._data),en(this._data)?new Ja(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?new Ja(this._data.slice(),{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation}):new Ja(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(en(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(){if(this._closed)throw new Error("VideoSample is closed.");return jr(null!==this._data),en(this._data)?this._data.allocationSize():this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e){if(!li(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw new Error("VideoSample is closed.");if(jr(null!==this._data),en(this._data))await this._data.copyTo(e);else if(this._data instanceof Uint8Array){Qr(e).set(this._data)}else{const t=this._data.getContext("2d");jr(t);const r=t.getImageData(0,0,this.codedWidth,this.codedHeight);Qr(e).set(r.data)}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return jr(null!==this._data),en(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,r,i,a,n,s,o,c){let l=0,u=0,h=this.displayWidth,d=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==n?(l=t,u=r,h=i,d=a,f=n,m=s,void 0!==o?(p=o,g=c):(p=h,g=d)):(f=t,m=r,void 0!==i&&(p=i,g=a)),!("undefined"!=typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:u,sWidth:h,sHeight:d}=this._rotateSourceRegion(l,u,h,d,this.rotation));const v=this.toCanvasImageSource();e.save();const y=f+p/2,b=m+g/2;e.translate(y,b),e.rotate(this.rotation*Math.PI/180);const k=this.rotation%180==0?1:p/g;e.scale(1/k,k),e.drawImage(v,l,u,h,d,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){if(!("undefined"!=typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&rn(t.crop,"options.");const r=e.canvas.width,i=e.canvas.height,a=t.rotation??this.rotation,[n,s]=a%180==0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];let o,c,l,u;t.crop&&tn(t.crop,n,s);const{sx:h,sy:d,sWidth:f,sHeight:m}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??n,t.crop?.height??s,a);if("fill"===t.fit)o=0,c=0,l=r,u=i;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[n,s],h="contain"===t.fit?Math.min(r/e,i/a):Math.max(r/e,i/a);l=e*h,u=a*h,o=(r-l)/2,c=(i-u)/2}e.save();const p=a%180==0?1:l/u;e.translate(r/2,i/2),e.rotate(a*Math.PI/180),e.scale(1/p,p),e.translate(-r/2,-i/2),e.drawImage(this.toCanvasImageSource(),h,d,f,m,o,c,l,u),e.restore()}_rotateSourceRegion(e,t,r,i,a){return 90===a?[e,t,r,i]=[t,this.codedHeight-e-r,i,r]:180===a?[e,t]=[this.codedWidth-e-r,this.codedHeight-t-i]:270===a&&([e,t,r,i]=[this.codedWidth-t-i,e,i,r]),{sx:e,sy:t,sWidth:r,sHeight:i}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(jr(null!==this._data),this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}const en=e=>"undefined"!=typeof VideoFrame&&e instanceof VideoFrame,tn=(e,t,r)=>{e.left=Math.min(e.left,t),e.top=Math.min(e.top,r),e.width=Math.min(e.width,t-e.left),e.height=Math.min(e.height,r-e.top),jr(e.width>=0),jr(e.height>=0)},rn=(e,t)=>{if(!e||"object"!=typeof e)throw new TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(e.left)||e.left<0)throw new TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(e.top)||e.top<0)throw new TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(e.width)||e.width<0)throw new TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(e.height)||e.height<0)throw new TypeError(t+"crop.height must be a non-negative integer.")},an=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class nn{get microsecondTimestamp(){return Math.trunc(Ai*this.timestamp)}get microsecondDuration(){return Math.trunc(Ai*this.duration)}constructor(e){if(this._closed=!1,un(e)){if(null===e.format)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||"object"!=typeof e)throw new TypeError("Invalid AudioDataInit: must be an object.");if(!an.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(sn(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");let r;if(this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate,e.data instanceof ArrayBuffer)r=new Uint8Array(e.data);else{if(!ArrayBuffer.isView(e.data))throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");r=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength)}const i=this.numberOfFrames*this.numberOfChannels*sn(this.format);if(r.byteLength<i)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}}allocationSize(e){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(void 0!==e.format&&!an.has(e.format))throw new TypeError("Invalid format.");if(void 0!==e.frameOffset&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==e.frameCount&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const t=e.format??this.format,r=e.frameOffset??0;if(r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const i=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-r;if(i>this.numberOfFrames-r)throw new RangeError("frameCount out of range");const a=sn(t),n=on(t);if(n&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!n&&0!==e.planeIndex)throw new RangeError("planeIndex out of range");return(n?i:i*this.numberOfChannels)*a}copyTo(e,t){if(!li(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(void 0!==t.format&&!an.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{planeIndex:r,format:i,frameCount:a,frameOffset:n}=t,s=i??this.format;if(!s)throw new Error("Destination format not determined");const o=this.numberOfFrames,c=this.numberOfChannels,l=n??0;if(l>=o)throw new RangeError("frameOffset out of range");const u=void 0!==a?a:o-l;if(u>o-l)throw new RangeError("frameCount out of range");const h=sn(s),d=on(s);if(d&&r>=c)throw new RangeError("planeIndex out of range");if(!d&&0!==r)throw new RangeError("planeIndex out of range");const f=(d?u:u*c)*h;if(e.byteLength<f)throw new RangeError("Destination buffer is too small");const m=Zr(e),p=ln(s);if(un(this._data))if(d)if("f32-planar"===s)this._data.copyTo(e,{planeIndex:r,frameOffset:l,frameCount:u,format:"f32-planar"});else{const e=new ArrayBuffer(4*u),t=new Float32Array(e);this._data.copyTo(t,{planeIndex:r,frameOffset:l,frameCount:u,format:"f32-planar"});const i=new DataView(e);for(let e=0;e<u;e++){p(m,e*h,i.getFloat32(4*e,!0))}}else{const e=c,t=new Float32Array(u);for(let r=0;r<e;r++){this._data.copyTo(t,{planeIndex:r,frameOffset:l,frameCount:u,format:"f32-planar"});for(let i=0;i<u;i++){p(m,(i*e+r)*h,t[i])}}}else{const e=this._data,t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=this.format,a=cn(i),n=sn(i),s=on(i);for(let e=0;e<u;e++)if(d){let i;i=s?(r*o+(e+l))*n:((e+l)*c+r)*n;p(m,e*h,a(t,i))}else for(let r=0;r<c;r++){let i;i=s?(r*o+(e+l))*n:((e+l)*c+r)*n;p(m,(e*c+r)*h,a(t,i))}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(un(this._data)){const e=new nn(this._data.clone());return e.setTimestamp(this.timestamp),e}return new nn({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(un(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(un(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(on(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(new Uint8Array(t,r*e,e),{planeIndex:r,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(t,{planeIndex:r,format:"f32-planar"}),e.copyToChannel(t,r);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=e.numberOfChannels,i=e.sampleRate,a=e.length,n=Math.floor(24e4/r);let s=0,o=a;for(;o>0;){const a=Math.min(n,o),c=new Float32Array(r*a);for(let t=0;t<r;t++)e.copyFromChannel(c.subarray(t*a,(t+1)*a),t,s);yield new nn({format:"f32-planar",sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:t+s/i,data:c}),s+=a,o-=a}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=e.numberOfChannels,i=e.sampleRate,a=e.length,n=Math.floor(24e4/r);let s=0,o=a;const c=[];for(;o>0;){const a=Math.min(n,o),l=new Float32Array(r*a);for(let t=0;t<r;t++)e.copyFromChannel(l.subarray(t*a,(t+1)*a),t,s);const u=new nn({format:"f32-planar",sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:t+s/i,data:l});c.push(u),s+=a,o-=a}return c}}const sn=e=>{switch(e){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},on=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},cn=e=>{switch(e){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},ln=e=>{switch(e){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,Ti(127.5*(r+1),0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,Ti(Math.round(32767*r),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,Ti(Math.round(2147483647*r),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},un=e=>"undefined"!=typeof AudioData&&e instanceof AudioData,hn=e=>{if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.metadataOnly&&"boolean"!=typeof e.metadataOnly)throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(void 0!==e.verifyKeyPackets&&"boolean"!=typeof e.verifyKeyPackets)throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(e.verifyKeyPackets&&e.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},dn=e=>{if(!Hi(e))throw new TypeError("timestamp must be a number.")},fn=(e,t,r)=>r.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;const r=await e.determinePacketType(t);return r&&(t.type=r),t}):t;class mn{constructor(e){if(!(e instanceof xn))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(hn(e),this._track.input._disposed)throw new zo;return fn(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(dn(e),hn(t),this._track.input._disposed)throw new zo;return fn(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof Za))throw new TypeError("packet must be an EncodedPacket.");if(hn(t),this._track.input._disposed)throw new zo;return fn(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(dn(e),hn(t),this._track.input._disposed)throw new zo;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const r=await this._track._backing.getKeyPacket(e,t);if(!r||"delta"===r.type)return r;return"delta"===await this._track.determinePacketType(r)?this.getKeyPacket(r.timestamp-1/this._track.timeResolution,t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof Za))throw new TypeError("packet must be an EncodedPacket.");if(hn(t),this._track.input._disposed)throw new zo;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const r=await this._track._backing.getNextKeyPacket(e,t);if(!r||"delta"===r.type)return r;return"delta"===await this._track.determinePacketType(r)?this.getNextKeyPacket(r,t):r}packets(e,t,r={}){if(void 0!==e&&!(e instanceof Za))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof Za))throw new TypeError("endPacket must be an EncodedPacket.");if(hn(r),this._track.input._disposed)throw new zo;const i=[];let{promise:a,resolve:n}=gi(),{promise:s,resolve:o}=gi(),c=!1,l=!1,u=null;const h=[],d=()=>Math.max(2,h.length);(async()=>{let u=e??await this.getFirstPacket(r);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)i.length>d()?(({promise:s,resolve:o}=gi()),await s):(i.push(u),n(),({promise:a,resolve:n}=gi()),u=await this.getNextPacket(u,r));c=!0,n()})().catch(e=>{u||(u=e,n())});const f=this._track;return{async next(){for(;;){if(f.input._disposed)throw new zo;if(l)return{value:void 0,done:!0};if(u)throw u;if(i.length>0){const e=i.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),n(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class pn{constructor(e,t){this.onSample=e,this.onError=t}}class gn{mediaSamplesInRange(e=0,t=1/0){dn(e),dn(t);const r=[];let i=!1,a=null,{promise:n,resolve:s}=gi(),{promise:o,resolve:c}=gi(),l=!1,u=!1,h=!1,d=null;(async()=>{const f=new Error,m=await this._createDecoder(o=>{c(),o.timestamp>=t&&(u=!0),u?o.close():(a&&(o.timestamp>e?(r.push(a),i=!0):a.close()),o.timestamp>=e&&(r.push(o),i=!0),a=i?null:o,r.length>0&&(s(),({promise:n,resolve:s}=gi())))},e=>{d||(e.stack=f.stack,d=e,s())}),p=this._createPacketSink(),g=await p.getKeyPacket(e,{verifyKeyPackets:!0})??await p.getFirstPacket();if(!g)return;let v,y=g;if(t<1/0){const e=await p.getPacket(t),r=e?"key"===e.type&&e.timestamp===t?e:await p.getNextKeyPacket(e,{verifyKeyPackets:!0}):null;r&&(v=r)}const b=p.packets(g,v);for(await b.next();y&&!u&&!this._track.input._disposed;){const e=vn(r.length);if(r.length+m.getDecodeQueueSize()>e){({promise:o,resolve:c}=gi()),await o;continue}m.decode(y);const t=await b.next();if(t.done)break;y=t.value}await b.return(),h||this._track.input._disposed||await m.flush(),m.close(),!i&&a&&r.push(a),l=!0,s()})().catch(e=>{d||(d=e,s())});const f=this._track,m=()=>{a?.close();for(const e of r)e.close()};return{async next(){for(;;){if(f.input._disposed)throw m(),new zo;if(h)return{value:void 0,done:!0};if(d)throw m(),d;if(r.length>0){const e=r.shift();return c(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};await n}},return:async()=>(h=!0,u=!0,c(),s(),m(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const t=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),r=[],i=[];let{promise:a,resolve:n}=gi(),{promise:s,resolve:o}=gi(),c=!1,l=!1,u=null;const h=e=>{i.push(e),n(),({promise:a,resolve:n}=gi())};(async()=>{const e=new Error,a=await this._createDecoder(e=>{if(o(),l)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let r=0;r<t;r++)h(r<t-1?e.clone():e);else e.close()},t=>{u||(t.stack=e.stack,u=t,n())}),d=this._createPacketSink();let f=null,m=null,p=-1;const g=async()=>{jr(m);let e=m;for(a.decode(e);e.sequenceNumber<p;){const t=vn(i.length);for(;i.length+a.getDecodeQueueSize()>t&&!l;)({promise:s,resolve:o}=gi()),await s;if(l)break;const r=await d.getNextPacket(e);jr(r),a.decode(r),e=r}p=-1},v=async()=>{await a.flush();for(let e=0;e<r.length;e++)h(null);r.length=0};for await(const e of t){if(dn(e),l||this._track.input._disposed)break;const t=await d.getPacket(e),i=t&&await d.getKeyPacket(e,{verifyKeyPackets:!0});i?(f&&(i.sequenceNumber!==m.sequenceNumber||t.timestamp<f.timestamp)&&(await g(),await v()),r.push(t.timestamp),p=Math.max(t.sequenceNumber,p),f=t,m=i):(-1!==p&&(await g(),await v()),h(null),f=null)}l||this._track.input._disposed||(-1!==p&&await g(),await v()),a.close(),c=!0,n()})().catch(e=>{u||(u=e,n())});const d=this._track,f=()=>{for(const e of i)e?.close()};return{async next(){for(;;){if(d.input._disposed)throw f(),new zo;if(l)return{value:void 0,done:!0};if(u)throw f(),u;if(i.length>0){const e=i.shift();return jr(void 0!==e),o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),n(),f(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const vn=e=>0===e?40:8;class yn extends pn{constructor(e,t,r,i,a,n){super(e,t),this.codec=r,this.decoderConfig=i,this.rotation=a,this.timeResolution=n,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Oi,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;const s=Ya.find(e=>e.supports(r,i));if(s)this.customDecoder=new s,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=e=>{if(!(e instanceof Ja))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();jr(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===r&&this.decoderConfig.description&&(null!==Bi?Bi:Bi=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")))){const e=(e=>{try{const t=Zr(e);let r=0;const i=t.getUint8(r++),a=t.getUint8(r++),n=t.getUint8(r++),s=t.getUint8(r++),o=3&t.getUint8(r++),c=31&t.getUint8(r++),l=[];for(let i=0;i<c;i++){const i=t.getUint16(r,!1);r+=2,l.push(e.subarray(r,r+i)),r+=i}const u=t.getUint8(r++),h=[];for(let i=0;i<u;i++){const i=t.getUint16(r,!1);r+=2,h.push(e.subarray(r,r+i)),r+=i}const d={configurationVersion:i,avcProfileIndication:a,profileCompatibility:n,avcLevelIndication:s,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:h,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===a||110===a||122===a||144===a)&&r+4<=e.length){const i=3&t.getUint8(r++),a=7&t.getUint8(r++),n=7&t.getUint8(r++),s=t.getUint8(r++);d.chromaFormat=i,d.bitDepthLumaMinus8=a,d.bitDepthChromaMinus8=n;const o=[];for(let i=0;i<s;i++){const i=t.getUint16(r,!1);r+=2,o.push(e.subarray(r,r+i)),r+=i}d.sequenceParameterSetExt=o}return d}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}})(Qr(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Pa(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:t}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(jr(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}this.currentPacketIndex++,this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(jr(this.decoder),_i()||pi(this.inputTimestamps,e.timestamp,e=>e),this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e))}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed)return void this.pushNullAlphaFrame();if(!this.merger)try{this.merger=new bn}catch(t){return console.error("Due to an error, only color data will be decoded.",t),this.mergerCreationFailed=!0,void this.decodeAlphaData(e)}if(!this.alphaDecoder){const e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){const t=this.colorQueue.shift();jr(void 0!==t),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const e=this.colorQueue.shift();jr(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)};this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:this.onError}),this.alphaDecoder.configure(this.decoderConfig)}const t=Xa(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){return Ia(e,this.decoderConfig).some(e=>{const t=Ra(e);return t===wa.RASL_N||t===wa.RASL_R})}sampleHandler(e){if(_i()){if(this.sampleQueue.length>0&&e.timestamp>=qr(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}pi(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();jr(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){if(!t){const t=new Ja(e);return void this.sampleHandler(t)}jr(this.merger),this.merger.update(e,t),e.close(),t.close();const r=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),i=new Ja(r);this.sampleHandler(i)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(jr(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),_i()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(jr(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}class bn{constructor(){"undefined"!=typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){const e=this.createShader(this.gl.VERTEX_SHADER,"#version 300 es\n\t\t\tin vec2 a_position;\n\t\t\tin vec2 a_texCoord;\n\t\t\tout vec2 v_texCoord;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = vec4(a_position, 0.0, 1.0);\n\t\t\t\tv_texCoord = a_texCoord;\n\t\t\t}\n\t\t"),t=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_colorTexture;\n\t\t\tuniform sampler2D u_alphaTexture;\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec3 color = texture(u_colorTexture, v_texCoord).rgb;\n\t\t\t\tfloat alpha = texture(u_alphaTexture, v_texCoord).r;\n\t\t\t\tfragColor = vec4(color, alpha);\n\t\t\t}\n\t\t"),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){const r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),r}createVAO(){const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const i=this.gl.getAttribLocation(this.program,"a_position"),a=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){e.displayWidth===this.canvas.width&&e.displayHeight===this.canvas.height||(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class kn extends gn{constructor(e){if(!(e instanceof Cn))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=this._track.codec,i=this._track.rotation,a=await this._track.getDecoderConfig(),n=this._track.timeResolution;return jr(r&&a),new yn(e,t,r,a,i,n)}_createPacketSink(){return new mn(this._track)}async getSample(e){dn(e);for await(const t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}class Tn extends pn{constructor(e,t,r,i){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Oi,this.customDecoderQueueSize=0,this.currentTimestamp=null;const a=t=>{(null===this.currentTimestamp||Math.abs(t.timestamp-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=t.timestamp);const r=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const a=i.sampleRate;t.setTimestamp(Math.round(r*a)/a),e(t)},n=$a.find(e=>e.supports(r,i));n?(this.customDecoder=new n,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=e=>{if(!(e instanceof nn))throw new TypeError("The argument passed to onSample must be an AudioSample.");a(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init())):(this.decoder=new AudioDecoder({output:e=>{try{a(new nn(e))}catch(e){this.onError(e)}},error:t}),this.decoder.configure(i))}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(jr(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(jr(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(jr(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(jr(this.decoder),this.decoder.close())}}class wn extends pn{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,jr(Ki.includes(r.codec)),this.codec=r.codec;const{dataType:i,sampleSize:a,littleEndian:n}=ua(this.codec);switch(this.inputSampleSize=a,a){case 1:"unsigned"===i?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===i?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===i?this.readInputValue=(e,t)=>(e=>{let t=0,r=0,i=~e;128&i&&(i&=-129,t=-1),r=5+((240&i)>>4);const a=(1<<r|(15&i)<<r-4|1<<r-5)-33;return 0===t?a:-a})(e.getUint8(t)):"alaw"===i?this.readInputValue=(e,t)=>(e=>{let t=0,r=0,i=85^e;128&i&&(i&=-129,t=-1),r=4+((240&i)>>4);let a=0;return a=4!==r?1<<r|(15&i)<<r-4|1<<r-5:i<<1|1,0===t?a:-a})(e.getUint8(t)):jr(!1);break;case 2:"unsigned"===i?this.readInputValue=(e,t)=>e.getUint16(t,n)-32768:"signed"===i?this.readInputValue=(e,t)=>e.getInt16(t,n):jr(!1);break;case 3:"unsigned"===i?this.readInputValue=(e,t)=>ki(e,t,n)-2**23:"signed"===i?this.readInputValue=(e,t)=>((e,t,r)=>ki(e,t,r)<<8>>8)(e,t,n):jr(!1);break;case 4:"unsigned"===i?this.readInputValue=(e,t)=>e.getUint32(t,n)-2**31:"signed"===i?this.readInputValue=(e,t)=>e.getInt32(t,n):"float"===i?this.readInputValue=(e,t)=>e.getFloat32(t,n):jr(!1);break;case 8:"float"===i?this.readInputValue=(e,t)=>e.getFloat64(t,n):jr(!1);break;default:bi(a),jr(!1)}switch(a){case 1:"ulaw"===i||"alaw"===i?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,r)=>e.setUint8(t,r+128));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r<<8,!0);break;case 4:this.outputSampleSize=4,"float"===i?(this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0);break;default:bi(a),jr(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=Zr(e.data),r=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,i=r*this.decoderConfig.numberOfChannels*this.outputSampleSize,a=new ArrayBuffer(i),n=new DataView(a);for(let e=0;e<r*this.decoderConfig.numberOfChannels;e++){const r=e*this.inputSampleSize,i=e*this.outputSampleSize,a=this.readInputValue(t,r);this.writeOutputValue(n,i,a)}const s=r/this.decoderConfig.sampleRate;(null===this.currentTimestamp||Math.abs(e.timestamp-this.currentTimestamp)>=s)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=s;const c=new nn({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:r,timestamp:o});this.onSample(c)}async flush(){}close(){}}class Sn extends gn{constructor(e){if(!(e instanceof En))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=this._track.codec,i=await this._track.getDecoderConfig();return jr(r&&i),Ki.includes(i.codec)?new wn(e,t,i):new Tn(e,t,r,i)}_createPacketSink(){return new mn(this._track)}async getSample(e){dn(e);for await(const t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}
61
+ Gn();let cs=-1/0,us=-1/0,ls=null;"undefined"!=typeof FinalizationRegistry&&(ls=new FinalizationRegistry(e=>{const t=Date.now();"video"===e.type?(t-cs>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),cs=t),"undefined"!=typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-us>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),us=t),"undefined"!=typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));const hs=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],ds=new Set(hs);class fs{get displayWidth(){return this.rotation%180==0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180==0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(Mn*this.timestamp)}get microsecondDuration(){return Math.trunc(Mn*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!=typeof t)throw new TypeError("init must be an object.");if(void 0===t.format||!ds.has(t.format))throw new TypeError("init.format must be one of: "+hs.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=Qa(e).slice(),this._layout=t.layout??bs(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new ms(t.colorSpace)}else if("undefined"!=typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==t?.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==t?.timestamp&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==t?.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new ms(e.colorSpace)}else{if(!("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");{if(!t||"object"!=typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!=typeof VideoFrame)return new fs(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Mn),duration:Math.trunc((t.duration??0)*Mn)||void 0}),t);let r=0,i=0;if("naturalWidth"in e?(r=e.naturalWidth,i=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,i=e.videoHeight):"width"in e&&(r=Number(e.width),i=Number(e.height)),!r||!i)throw new TypeError("Could not determine dimensions.");const a=new OffscreenCanvas(r,i),n=a.getContext("2d",{alpha:null!==Fn?Fn:Fn="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),willReadFrequently:!0});Xa(n),n.drawImage(e,0,0),this._data=a,this._layout=null,this.format="RGBX",this.codedWidth=r,this.codedHeight=i,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new ms({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}}ls?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return Xa(null!==this._data),ps(this._data)?new fs(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(Xa(this._layout),new fs(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})):new fs(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(ls?.unregister(this),ps(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(ys(e),this._closed)throw new Error("VideoSample is closed.");if(null===(e.format??this.format))throw new Error("Cannot get allocation size when format is null. Please manually provide an RGB pixel format in the options instead.");if(Xa(null!==this._data),!ps(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){const t=this.toVideoFrame(),r=t.allocationSize(e);return t.close(),r}return ps(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!ln(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(ys(t),this._closed)throw new Error("VideoSample is closed.");if(null===(t.format??this.format))throw new Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(Xa(null!==this._data),!ps(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){const r=this.toVideoFrame(),i=await r.copyTo(e,t);return r.close(),i}if(ps(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array){Xa(this._layout);return Qa(e).set(this._data),this._layout}{const t=this._data.getContext("2d");Xa(t);const r=t.getImageData(0,0,this.codedWidth,this.codedHeight);return Qa(e).set(r.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return Xa(null!==this._data),ps(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,r,i,a,n,o,s,c){let u=0,l=0,h=this.displayWidth,d=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==n?(u=t,l=r,h=i,d=a,f=n,m=o,void 0!==s?(p=s,g=c):(p=h,g=d)):(f=t,m=r,void 0!==i&&(p=i,g=a)),!("undefined"!=typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(l))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:l,sWidth:h,sHeight:d}=this._rotateSourceRegion(u,l,h,d,this.rotation));const v=this.toCanvasImageSource();e.save();const y=f+p/2,b=m+g/2;e.translate(y,b),e.rotate(this.rotation*Math.PI/180);const x=this.rotation%180==0?1:p/g;e.scale(1/x,x),e.drawImage(v,u,l,h,d,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){if(!("undefined"!=typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&vs(t.crop,"options.");const r=e.canvas.width,i=e.canvas.height,a=t.rotation??this.rotation,[n,o]=a%180==0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];let s,c,u,l;t.crop&&gs(t.crop,n,o);const{sx:h,sy:d,sWidth:f,sHeight:m}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??n,t.crop?.height??o,a);if("fill"===t.fit)s=0,c=0,u=r,l=i;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[n,o],h="contain"===t.fit?Math.min(r/e,i/a):Math.max(r/e,i/a);u=e*h,l=a*h,s=(r-u)/2,c=(i-l)/2}e.save();const p=a%180==0?1:u/l;e.translate(r/2,i/2),e.rotate(a*Math.PI/180),e.scale(1/p,p),e.translate(-r/2,-i/2),e.drawImage(this.toCanvasImageSource(),h,d,f,m,s,c,u,l),e.restore()}_rotateSourceRegion(e,t,r,i,a){return 90===a?[e,t,r,i]=[t,this.codedHeight-e-r,i,r]:180===a?[e,t]=[this.codedWidth-e-r,this.codedHeight-t-i]:270===a&&([e,t,r,i]=[this.codedWidth-t-i,e,i,r]),{sx:e,sy:t,sWidth:r,sHeight:i}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(Xa(null!==this._data),this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}class ms{constructor(e){this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const ps=e=>"undefined"!=typeof VideoFrame&&e instanceof VideoFrame,gs=(e,t,r)=>{e.left=Math.min(e.left,t),e.top=Math.min(e.top,r),e.width=Math.min(e.width,t-e.left),e.height=Math.min(e.height,r-e.top),Xa(e.width>=0),Xa(e.height>=0)},vs=(e,t)=>{if(!e||"object"!=typeof e)throw new TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(e.left)||e.left<0)throw new TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(e.top)||e.top<0)throw new TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(e.width)||e.width<0)throw new TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(e.height)||e.height<0)throw new TypeError(t+"crop.height must be a non-negative integer.")},ys=e=>{if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.colorSpace&&!["display-p3","srgb"].includes(e.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(void 0!==e.format&&"string"!=typeof e.format)throw new TypeError("options.format, when provided, must be a string.");if(void 0!==e.layout){if(!Array.isArray(e.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const t of e.layout){if(!t||"object"!=typeof t)throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==e.rect){if(!e.rect||"object"!=typeof e.rect)throw new TypeError("options.rect, when provided, must be an object.");if(void 0!==e.rect.x&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==e.rect.y&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==e.rect.width&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==e.rect.height&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},bs=(e,t,r)=>{const i=xs(e),a=[];let n=0;for(const e of i){const i=Math.ceil(t/e.widthDivisor),o=Math.ceil(r/e.heightDivisor),s=i*e.sampleBytes,c=s*o;a.push({offset:n,stride:s}),n+=c}return a},xs=e=>{const t=(e,t,r,i,a)=>{const n=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:r,heightDivisor:i},{sampleBytes:t,widthDivisor:r,heightDivisor:i}];return a&&n.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),n};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:xn(e),Xa(!1)}},Ts=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class ws{get microsecondTimestamp(){return Math.trunc(Mn*this.timestamp)}get microsecondDuration(){return Math.trunc(Mn*this.duration)}constructor(e){if(this._closed=!1,As(e)){if(null===e.format)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||"object"!=typeof e)throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Ts.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(ks(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");let r;if(this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate,e.data instanceof ArrayBuffer)r=new Uint8Array(e.data);else{if(!ArrayBuffer.isView(e.data))throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");r=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength)}const i=this.numberOfFrames*this.numberOfChannels*ks(this.format);if(r.byteLength<i)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}ls?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(void 0!==e.format&&!Ts.has(e.format))throw new TypeError("Invalid format.");if(void 0!==e.frameOffset&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==e.frameCount&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const t=e.format??this.format,r=e.frameOffset??0;if(r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const i=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-r;if(i>this.numberOfFrames-r)throw new RangeError("frameCount out of range");const a=ks(t),n=Ss(t);if(n&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!n&&0!==e.planeIndex)throw new RangeError("planeIndex out of range");return(n?i:i*this.numberOfChannels)*a}copyTo(e,t){if(!ln(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(void 0!==t.format&&!Ts.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{planeIndex:r,format:i,frameCount:a,frameOffset:n}=t,o=this.format,s=i??this.format;if(!s)throw new Error("Destination format not determined");const c=this.numberOfFrames,u=this.numberOfChannels,l=n??0;if(l>=c)throw new RangeError("frameOffset out of range");const h=void 0!==a?a:c-l;if(h>c-l)throw new RangeError("frameCount out of range");const d=ks(s),f=Ss(s);if(f&&r>=u)throw new RangeError("planeIndex out of range");if(!f&&0!==r)throw new RangeError("planeIndex out of range");const m=(f?h:h*u)*d;if(e.byteLength<m)throw new RangeError("Destination buffer is too small");const p=Za(e),g=Cs(s);if(As(this._data))Bn()&&u>2&&s!==o?_s(this._data,p,o,s,u,r,l,h):this._data.copyTo(e,{planeIndex:r,frameOffset:l,frameCount:h,format:s});else{const e=this._data,t=Za(e),i=Es(o),a=ks(o),n=Ss(o);for(let e=0;e<h;e++)if(f){let o;o=n?(r*c+(e+l))*a:((e+l)*u+r)*a;g(p,e*d,i(t,o))}else for(let r=0;r<u;r++){let o;o=n?(r*c+(e+l))*a:((e+l)*u+r)*a;g(p,(e*u+r)*d,i(t,o))}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(As(this._data)){const e=new ws(this._data.clone());return e.setTimestamp(this.timestamp),e}return new ws({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(ls?.unregister(this),As(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(As(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(Ss(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(new Uint8Array(t,r*e,e),{planeIndex:r,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(t,{planeIndex:r,format:"f32-planar"}),e.copyToChannel(t,r);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=e.numberOfChannels,i=e.sampleRate,a=e.length,n=Math.floor(24e4/r);let o=0,s=a;for(;s>0;){const a=Math.min(n,s),c=new Float32Array(r*a);for(let t=0;t<r;t++)e.copyFromChannel(c.subarray(t*a,(t+1)*a),t,o);yield new ws({format:"f32-planar",sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:t+o/i,data:c}),o+=a,s-=a}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=e.numberOfChannels,i=e.sampleRate,a=e.length,n=Math.floor(24e4/r);let o=0,s=a;const c=[];for(;s>0;){const a=Math.min(n,s),u=new Float32Array(r*a);for(let t=0;t<r;t++)e.copyFromChannel(u.subarray(t*a,(t+1)*a),t,o);const l=new ws({format:"f32-planar",sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:t+o/i,data:u});c.push(l),o+=a,s-=a}return c}}const ks=e=>{switch(e){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},Ss=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Es=e=>{switch(e){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Cs=e=>{switch(e){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,kn(127.5*(r+1),0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,kn(Math.round(32767*r),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,kn(Math.round(2147483647*r),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},As=e=>"undefined"!=typeof AudioData&&e instanceof AudioData,_s=(e,t,r,i,a,n,o,s)=>{const c=Es(r),u=Cs(i),l=ks(r),h=ks(i),d=Ss(r);if(Ss(i))if(d){const i=new ArrayBuffer(s*l),a=Za(i);e.copyTo(i,{planeIndex:n,frameOffset:o,frameCount:s,format:r});for(let e=0;e<s;e++){u(t,e*h,c(a,e*l))}}else{const i=new ArrayBuffer(s*a*l),d=Za(i);e.copyTo(i,{planeIndex:0,frameOffset:o,frameCount:s,format:r});for(let e=0;e<s;e++){u(t,e*h,c(d,(e*a+n)*l))}}else if(d){const i=new ArrayBuffer(s*l),n=Za(i);for(let d=0;d<a;d++){e.copyTo(i,{planeIndex:d,frameOffset:o,frameCount:s,format:r});for(let e=0;e<s;e++){u(t,(e*a+d)*h,c(n,e*l))}}}else{const i=new ArrayBuffer(s*a*l),n=Za(i);e.copyTo(i,{planeIndex:0,frameOffset:o,frameCount:s,format:r});for(let e=0;e<s;e++)for(let r=0;r<a;r++){const i=e*a+r;u(t,i*h,c(n,i*l))}}},Ms=e=>{if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.metadataOnly&&"boolean"!=typeof e.metadataOnly)throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(void 0!==e.verifyKeyPackets&&"boolean"!=typeof e.verifyKeyPackets)throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(e.verifyKeyPackets&&e.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},Is=e=>{if(!Yn(e))throw new TypeError("timestamp must be a number.")},Rs=(e,t,r)=>r.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;const r=await e.determinePacketType(t);return r&&(t.type=r),t}):t;class Ps{constructor(e){if(!(e instanceof Vs))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(Ms(e),this._track.input._disposed)throw new il;return Rs(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(Is(e),Ms(t),this._track.input._disposed)throw new il;return Rs(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof ss))throw new TypeError("packet must be an EncodedPacket.");if(Ms(t),this._track.input._disposed)throw new il;return Rs(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Is(e),Ms(t),this._track.input._disposed)throw new il;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const r=await this._track._backing.getKeyPacket(e,t);if(!r)return r;Xa("key"===r.type);return"delta"===await this._track.determinePacketType(r)?this.getKeyPacket(r.timestamp-1/this._track.timeResolution,t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof ss))throw new TypeError("packet must be an EncodedPacket.");if(Ms(t),this._track.input._disposed)throw new il;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const r=await this._track._backing.getNextKeyPacket(e,t);if(!r)return r;Xa("key"===r.type);return"delta"===await this._track.determinePacketType(r)?this.getNextKeyPacket(r,t):r}packets(e,t,r={}){if(void 0!==e&&!(e instanceof ss))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof ss))throw new TypeError("endPacket must be an EncodedPacket.");if(Ms(r),this._track.input._disposed)throw new il;const i=[];let{promise:a,resolve:n}=vn(),{promise:o,resolve:s}=vn(),c=!1,u=!1,l=null;const h=[],d=()=>Math.max(2,h.length);(async()=>{let l=e??await this.getFirstPacket(r);for(;l&&!u&&!this._track.input._disposed&&!(t&&l.sequenceNumber>=t?.sequenceNumber);)i.length>d()?(({promise:o,resolve:s}=vn()),await o):(i.push(l),n(),({promise:a,resolve:n}=vn()),l=await this.getNextPacket(l,r));c=!0,n()})().catch(e=>{l||(l=e,n())});const f=this._track;return{async next(){for(;;){if(f.input._disposed)throw new il;if(u)return{value:void 0,done:!0};if(l)throw l;if(i.length>0){const e=i.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return s(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(u=!0,s(),n(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class Os{constructor(e,t){this.onSample=e,this.onError=t}}class Ds{mediaSamplesInRange(e=0,t=1/0){Is(e),Is(t);const r=[];let i=!1,a=null,{promise:n,resolve:o}=vn(),{promise:s,resolve:c}=vn(),u=!1,l=!1,h=!1,d=null;(async()=>{const f=await this._createDecoder(s=>{c(),s.timestamp>=t&&(l=!0),l?s.close():(a&&(s.timestamp>e?(r.push(a),i=!0):a.close()),s.timestamp>=e&&(r.push(s),i=!0),a=i?null:s,r.length>0&&(o(),({promise:n,resolve:o}=vn())))},e=>{d||(d=e,o())}),m=this._createPacketSink(),p=await m.getKeyPacket(e,{verifyKeyPackets:!0})??await m.getFirstPacket();let g,v=p;if(t<1/0){const e=await m.getPacket(t),r=e?"key"===e.type&&e.timestamp===t?e:await m.getNextKeyPacket(e,{verifyKeyPackets:!0}):null;r&&(g=r)}const y=m.packets(p??void 0,g);for(await y.next();v&&!l&&!this._track.input._disposed;){const e=Bs(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:s,resolve:c}=vn()),await s;continue}f.decode(v);const t=await y.next();if(t.done)break;v=t.value}await y.return(),h||this._track.input._disposed||await f.flush(),f.close(),!i&&a&&r.push(a),u=!0,o()})().catch(e=>{d||(d=e,o())});const f=this._track,m=()=>{a?.close();for(const e of r)e.close()};return{async next(){for(;;){if(f.input._disposed)throw m(),new il;if(h)return{value:void 0,done:!0};if(d)throw m(),d;if(r.length>0){const e=r.shift();return c(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(h=!0,l=!0,c(),o(),m(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const t=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),r=[],i=[];let{promise:a,resolve:n}=vn(),{promise:o,resolve:s}=vn(),c=!1,u=!1,l=null;const h=e=>{i.push(e),n(),({promise:a,resolve:n}=vn())};(async()=>{const e=await this._createDecoder(e=>{if(s(),u)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let r=0;r<t;r++)h(r<t-1?e.clone():e);else e.close()},e=>{l||(l=e,n())}),a=this._createPacketSink();let d=null,f=null,m=-1;const p=async()=>{Xa(f);let t=f;for(e.decode(t);t.sequenceNumber<m;){const r=Bs(i.length);for(;i.length+e.getDecodeQueueSize()>r&&!u;)({promise:o,resolve:s}=vn()),await o;if(u)break;const n=await a.getNextPacket(t);Xa(n),e.decode(n),t=n}m=-1},g=async()=>{await e.flush();for(let e=0;e<r.length;e++)h(null);r.length=0};for await(const e of t){if(Is(e),u||this._track.input._disposed)break;const t=await a.getPacket(e),i=t&&await a.getKeyPacket(e,{verifyKeyPackets:!0});i?(d&&(i.sequenceNumber!==f.sequenceNumber||t.timestamp<d.timestamp)&&(await p(),await g()),r.push(t.timestamp),m=Math.max(t.sequenceNumber,m),d=t,f=i):(-1!==m&&(await p(),await g()),h(null),d=null)}u||this._track.input._disposed||(-1!==m&&await p(),await g()),e.close(),c=!0,n()})().catch(e=>{l||(l=e,n())});const d=this._track,f=()=>{for(const e of i)e?.close()};return{async next(){for(;;){if(d.input._disposed)throw f(),new il;if(u)return{value:void 0,done:!0};if(l)throw f(),l;if(i.length>0){const e=i.shift();return Xa(void 0!==e),s(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(u=!0,s(),n(),f(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const Bs=e=>0===e?40:8;class Fs extends Os{constructor(e,t,r,i,a,n){super(e,t),this.codec=r,this.decoderConfig=i,this.rotation=a,this.timeResolution=n,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new On,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;const o=as.find(e=>e.supports(r,i));if(o)this.customDecoder=new o,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=e=>{if(!(e instanceof fs))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();Xa(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===r&&this.decoderConfig.description&&Nn()){const e=(e=>{try{const t=Za(e);let r=0;const i=t.getUint8(r++),a=t.getUint8(r++),n=t.getUint8(r++),o=t.getUint8(r++),s=3&t.getUint8(r++),c=31&t.getUint8(r++),u=[];for(let i=0;i<c;i++){const i=t.getUint16(r,!1);r+=2,u.push(e.subarray(r,r+i)),r+=i}const l=t.getUint8(r++),h=[];for(let i=0;i<l;i++){const i=t.getUint16(r,!1);r+=2,h.push(e.subarray(r,r+i)),r+=i}const d={configurationVersion:i,avcProfileIndication:a,profileCompatibility:n,avcLevelIndication:o,lengthSizeMinusOne:s,sequenceParameterSets:u,pictureParameterSets:h,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===a||110===a||122===a||144===a)&&r+4<=e.length){const i=3&t.getUint8(r++),a=7&t.getUint8(r++),n=7&t.getUint8(r++),o=t.getUint8(r++);d.chromaFormat=i,d.bitDepthLumaMinus8=a,d.bitDepthChromaMinus8=n;const s=[];for(let i=0;i<o;i++){const i=t.getUint16(r,!1);r+=2,s.push(e.subarray(r,r+i)),r+=i}d.sequenceParameterSetExt=s}return d}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}})(Qa(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Lo(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}const t=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(Xa(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(Xa(this.decoder),Bn()||gn(this.inputTimestamps,e.timestamp,e=>e),Nn()&&0===this.currentPacketIndex&&"avc"===this.codec){const t=Oo(e.data,this.decoderConfig).filter(e=>{const t=Bo(e);return!(t>=20&&t<=31)}),r=Do(t,this.decoderConfig);e=new ss(r,e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed)return void this.pushNullAlphaFrame();if(!this.merger)try{this.merger=new Ls}catch(t){return console.error("Due to an error, only color data will be decoded.",t),this.mergerCreationFailed=!0,void this.decodeAlphaData(e)}if(!this.alphaDecoder){const e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){const t=this.colorQueue.shift();Xa(void 0!==t),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const e=this.colorQueue.shift();Xa(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=es(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){return No(e,this.decoderConfig).some(e=>{const t=Uo(e);return t===Ao.RASL_N||t===Ao.RASL_R})}sampleHandler(e){if(Bn()){if(this.sampleQueue.length>0&&e.timestamp>=Ga(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}gn(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();Xa(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){if(!t){const t=new fs(e);return void this.sampleHandler(t)}Xa(this.merger),this.merger.update(e,t),e.close(),t.close();const r=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),i=new fs(r);this.sampleHandler(i)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(Xa(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Bn()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(Xa(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}class Ls{constructor(){"undefined"!=typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){const e=this.createShader(this.gl.VERTEX_SHADER,"#version 300 es\n\t\t\tin vec2 a_position;\n\t\t\tin vec2 a_texCoord;\n\t\t\tout vec2 v_texCoord;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = vec4(a_position, 0.0, 1.0);\n\t\t\t\tv_texCoord = a_texCoord;\n\t\t\t}\n\t\t"),t=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_colorTexture;\n\t\t\tuniform sampler2D u_alphaTexture;\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec3 color = texture(u_colorTexture, v_texCoord).rgb;\n\t\t\t\tfloat alpha = texture(u_alphaTexture, v_texCoord).r;\n\t\t\t\tfragColor = vec4(color, alpha);\n\t\t\t}\n\t\t"),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){const r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),r}createVAO(){const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const i=this.gl.getAttribLocation(this.program,"a_position"),a=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){e.displayWidth===this.canvas.width&&e.displayHeight===this.canvas.height||(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class Ns extends Ds{constructor(e){if(!(e instanceof Hs))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=this._track.codec,i=this._track.rotation,a=await this._track.getDecoderConfig(),n=this._track.timeResolution;return Xa(r&&a),new Fs(e,t,r,a,i,n)}_createPacketSink(){return new Ps(this._track)}async getSample(e){Is(e);for await(const t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}class Us extends Os{constructor(e,t,r,i){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new On,this.customDecoderQueueSize=0,this.currentTimestamp=null;const a=t=>{(null===this.currentTimestamp||Math.abs(t.timestamp-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=t.timestamp);const r=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const a=i.sampleRate;t.setTimestamp(Math.round(r*a)/a),e(t)},n=ns.find(e=>e.supports(r,i));if(n)this.customDecoder=new n,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=e=>{if(!(e instanceof ws))throw new TypeError("The argument passed to onSample must be an AudioSample.");a(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{a(new ws(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(i)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(Xa(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(Xa(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(Xa(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(Xa(this.decoder),this.decoder.close())}}class zs extends Os{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,Xa(Zn.includes(r.codec)),this.codec=r.codec;const{dataType:i,sampleSize:a,littleEndian:n}=po(this.codec);switch(this.inputSampleSize=a,a){case 1:"unsigned"===i?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===i?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===i?this.readInputValue=(e,t)=>(e=>{let t=0,r=0,i=~e;128&i&&(i&=-129,t=-1),r=5+((240&i)>>4);const a=(1<<r|(15&i)<<r-4|1<<r-5)-33;return 0===t?a:-a})(e.getUint8(t)):"alaw"===i?this.readInputValue=(e,t)=>(e=>{let t=0,r=0,i=85^e;128&i&&(i&=-129,t=-1),r=4+((240&i)>>4);let a=0;return a=4!==r?1<<r|(15&i)<<r-4|1<<r-5:i<<1|1,0===t?a:-a})(e.getUint8(t)):Xa(!1);break;case 2:"unsigned"===i?this.readInputValue=(e,t)=>e.getUint16(t,n)-32768:"signed"===i?this.readInputValue=(e,t)=>e.getInt16(t,n):Xa(!1);break;case 3:"unsigned"===i?this.readInputValue=(e,t)=>Tn(e,t,n)-2**23:"signed"===i?this.readInputValue=(e,t)=>((e,t,r)=>Tn(e,t,r)<<8>>8)(e,t,n):Xa(!1);break;case 4:"unsigned"===i?this.readInputValue=(e,t)=>e.getUint32(t,n)-2**31:"signed"===i?this.readInputValue=(e,t)=>e.getInt32(t,n):"float"===i?this.readInputValue=(e,t)=>e.getFloat32(t,n):Xa(!1);break;case 8:"float"===i?this.readInputValue=(e,t)=>e.getFloat64(t,n):Xa(!1);break;default:xn(a),Xa(!1)}switch(a){case 1:"ulaw"===i||"alaw"===i?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,r)=>e.setUint8(t,r+128));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r<<8,!0);break;case 4:this.outputSampleSize=4,"float"===i?(this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0);break;default:xn(a),Xa(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=Za(e.data),r=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,i=r*this.decoderConfig.numberOfChannels*this.outputSampleSize,a=new ArrayBuffer(i),n=new DataView(a);for(let e=0;e<r*this.decoderConfig.numberOfChannels;e++){const r=e*this.inputSampleSize,i=e*this.outputSampleSize,a=this.readInputValue(t,r);this.writeOutputValue(n,i,a)}const o=r/this.decoderConfig.sampleRate;(null===this.currentTimestamp||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);const s=this.currentTimestamp;this.currentTimestamp+=o;const c=new ws({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:r,timestamp:s});this.onSample(c)}async flush(){}close(){}}class Ws extends Ds{constructor(e){if(!(e instanceof Xs))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=this._track.codec,i=await this._track.getDecoderConfig();return Xa(r&&i),Zn.includes(i.codec)?new zs(e,t,i):new Us(e,t,r,i)}_createPacketSink(){return new Ps(this._track)}async getSample(e){Is(e);for await(const t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}
62
62
  /*!
63
63
  * Copyright (c) 2025-present, Vanilagy and contributors
64
64
  *
65
65
  * This Source Code Form is subject to the terms of the Mozilla Public
66
66
  * License, v. 2.0. If a copy of the MPL was not distributed with this
67
67
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
68
- */class xn{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Cn}isAudioTrack(){return this instanceof En}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){const t=new mn(this);let r=1/0,i=-1/0,a=0,n=0;for await(const s of t.packets(void 0,void 0,{metadataOnly:!0})){if(a>=e&&s.timestamp>=i)break;r=Math.min(r,s.timestamp),i=Math.max(i,s.timestamp+s.duration),a++,n+=s.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(i-r)).toPrecision(16)):0,averageBitrate:a?Number((8*n/(i-r)).toPrecision(16)):0}}}class Cn extends xn{constructor(e,t){super(e,t),this._backing=t}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180==0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180==0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pg"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getDecoderConfig();return e?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=this._backing.getCodec();if(jr(null!==t),Ya.some(r=>r.supports(t,e)))return!0;if("undefined"==typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Za))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(null===this.codec)return null;const t=await this.getDecoderConfig();return jr(t),Xa(this.codec,t,e.data)}}class En extends xn{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getDecoderConfig();return e?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=this._backing.getCodec();if(jr(null!==t),$a.some(r=>r.supports(t,e)))return!0;if(e.codec.startsWith("pcm-"))return!0;if("undefined"==typeof AudioDecoder)return!1;return!0===(await AudioDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Za))throw new TypeError("packet must be an EncodedPacket.");return null===this.codec?null:"key"}}
68
+ */class Vs{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Hs}isAudioTrack(){return this instanceof Xs}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){const t=new Ps(this);let r=1/0,i=-1/0,a=0,n=0;for await(const o of t.packets(void 0,void 0,{metadataOnly:!0})){if(a>=e&&o.timestamp>=i)break;r=Math.min(r,o.timestamp),i=Math.max(i,o.timestamp+o.duration),a++,n+=o.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(i-r)).toPrecision(16)):0,averageBitrate:a?Number((8*n/(i-r)).toPrecision(16)):0}}}class Hs extends Vs{constructor(e,t){super(e,t),this._backing=t}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180==0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180==0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pg"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getDecoderConfig();return e?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=this._backing.getCodec();if(Xa(null!==t),as.some(r=>r.supports(t,e)))return!0;if("undefined"==typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ss))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(null===this.codec)return null;const t=await this.getDecoderConfig();return Xa(t),es(this.codec,t,e.data)}}class Xs extends Vs{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getDecoderConfig();return e?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=this._backing.getCodec();if(Xa(null!==t),ns.some(r=>r.supports(t,e)))return!0;if(e.codec.startsWith("pcm-"))return!0;if("undefined"==typeof AudioDecoder)return!1;return!0===(await AudioDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ss))throw new TypeError("packet must be an EncodedPacket.");return null===this.codec?null:"key"}}
69
69
  /*!
70
70
  * Copyright (c) 2025-present, Vanilagy and contributors
71
71
  *
72
72
  * This Source Code Form is subject to the terms of the Mozilla Public
73
73
  * License, v. 2.0. If a copy of the MPL was not distributed with this
74
74
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
75
- */const An=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");if(e.codecStrings.length>0){t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`}return t},Pn=16,In=e=>{let t=Qo(e);const r=sc(e,4);let i=8;1===t&&(t=tc(e),i=16);const a=t-i;return a<0?null:{name:r,totalSize:t,headerSize:i,contentSize:a}},Rn=e=>Jo(e)/65536,On=e=>Jo(e)/1073741824,Mn=e=>{let t=0;for(let r=0;r<4;r++){t<<=7;const r=Xo(e);if(t|=127&r,!(128&r))break}return t},_n=e=>{let t=Go(e);return e.skip(2),t=Math.min(t,e.remainingLength),Jr.decode(jo(e,t))},Dn=e=>{const t=In(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const r=Qo(e);e.skip(4);const i=jo(e,t.contentSize-8);switch(r){case 1:return Jr.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new ji(i,"image/jpeg");case 14:return new ji(i,"image/png");case 27:return new ji(i,"image/bmp");default:return i}};
75
+ */const js=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");if(e.codecStrings.length>0){t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`}return t},Gs=16,Ys=e=>{let t=ml(e);const r=kl(e,4);let i=8;1===t&&(t=yl(e),i=16);const a=t-i;return a<0?null:{name:r,totalSize:t,headerSize:i,contentSize:a}},qs=e=>gl(e)/65536,Ks=e=>gl(e)/1073741824,$s=e=>{let t=0;for(let r=0;r<4;r++){t<<=7;const r=cl(e);if(t|=127&r,!(128&r))break}return t},Qs=e=>{let t=ll(e);return e.skip(2),t=Math.min(t,e.remainingLength),Ja.decode(sl(e,t))},Zs=e=>{const t=Ys(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const r=ml(e);e.skip(4);const i=sl(e,t.contentSize-8);switch(r){case 1:return Ja.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new qn(i,"image/jpeg");case 14:return new qn(i,"image/png");case 27:return new qn(i,"image/bmp");default:return i}};
76
76
  /*!
77
77
  * Copyright (c) 2025-present, Vanilagy and contributors
78
78
  *
@@ -87,7 +87,7 @@ Vi();class Ja{get displayWidth(){return this.rotation%180==0?this.codedWidth:thi
87
87
  * License, v. 2.0. If a copy of the MPL was not distributed with this
88
88
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
89
89
  */
90
- class Bn extends Ka{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.tracks.map(e=>e.inputTrack.getCodecParameterString()));return An({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>"video"===e.info?.type),hasAudio:this.tracks.some(e=>"audio"===e.info?.type),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,8,Pn);if(t instanceof Promise&&(t=await t),!t)break;const r=e,i=In(t);if(!i)break;if("ftyp"===i.name){const e=sc(t,4);this.isQuickTime="qt "===e}else if("moov"===i.name){let e=this.reader.requestSlice(t.filePos,i.contentSize);if(e instanceof Promise&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));for(const e of this.tracks){const t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}break}e=r+i.totalSize}if(this.isFragmented&&null!==this.reader.fileSize){let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),jr(e);const t=Qo(e),r=this.reader.fileSize-t;if(r>=0&&r<=this.reader.fileSize-Pn){let e=this.reader.requestSliceRange(r,8,Pn);if(e instanceof Promise&&(e=await e),e){const t=In(e);if(t&&"mfra"===t.name){let r=this.reader.requestSlice(e.filePos,t.contentSize);r instanceof Promise&&(r=await r),r&&this.readContiguousBoxes(r)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=t,jr(this.moovSlice);const r=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(r),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&Ki.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){jr("audio"===e.info?.type);const r=ua(e.info.codec),i=[],a=[];for(let n=0;n<t.sampleToChunk.length;n++){const s=t.sampleToChunk[n],o=t.sampleToChunk[n+1],c=(o?o.startChunkIndex:t.chunkOffsets.length)-s.startChunkIndex;for(let n=0;n<c;n++){const o=s.startSampleIndex+n*s.samplesPerChunk,c=o+s.samplesPerChunk,l=mi(t.sampleTimingEntries,o,e=>e.startIndex),u=t.sampleTimingEntries[l],h=mi(t.sampleTimingEntries,c,e=>e.startIndex),d=t.sampleTimingEntries[h],f=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,m=d.startDecodeTimestamp+(c-d.startIndex)*d.delta-f,p=qr(i);p&&p.delta===m?p.count++:i.push({startIndex:s.startChunkIndex+n,startDecodeTimestamp:f,count:1,delta:m});const g=s.samplesPerChunk*r.sampleSize*e.info.numberOfChannels;a.push(g)}s.startSampleIndex=s.startChunkIndex,s.samplesPerChunk=1}t.sampleTimingEntries=i,t.sampleSizes=a}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const e of t.sampleTimingEntries)for(let r=0;r<e.count;r++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+r*e.delta,sampleIndex:e.startIndex+r});for(const e of t.sampleCompositionTimeOffsets)for(let r=0;r<e.count;r++){const i=e.startIndex+r,a=t.presentationTimestamps[i];a&&(a.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,Pn);t instanceof Promise&&(t=await t),jr(t);const r=In(t);jr("moof"===r?.name);let i=this.reader.requestSlice(e,r.totalSize);i instanceof Promise&&(i=await i),jr(i),this.traverseBox(i);const a=this.lastReadFragment;jr(a&&a.moofOffset===e);for(const[,e]of a.trackData){const t=e.track,{fragmentPositionCache:r}=t;if(!e.startTimestampIsFinal){const i=t.fragmentLookupTable.find(e=>e.moofOffset===a.moofOffset);if(i)Hn(e,i.timestamp);else{const t=mi(r,a.moofOffset-1,e=>e.moofOffset);if(-1!==t){const i=r[t];Hn(e,i.endTimestamp)}}e.startTimestampIsFinal=!0}const i=mi(r,e.startTimestamp,e=>e.startTimestamp);-1!==i&&r[i].moofOffset===a.moofOffset||r.splice(i+1,0,{moofOffset:a.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp})}return a}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){if(!this.traverseBox(e))break}}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){const t=e.filePos,r=In(e);if(!r)break;yield{boxInfo:r,slice:e},e.filePos=t+r.totalSize}}traverseBox(e){const t=e.filePos,r=In(e);if(!r)return!1;const i=e.filePos,a=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"wave":this.readContiguousBoxes(e.slice(i,r.contentSize));break;case"mvhd":{const t=Xo(e);e.skip(3),1===t?(e.skip(16),this.movieTimescale=Qo(e),this.movieDurationInTimescale=tc(e)):(e.skip(8),this.movieTimescale=Qo(e),this.movieDurationInTimescale=Qo(e))}break;case"trak":{const t={id:-1,demuxer:this,inputTrack:null,disposition:{...qi},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:wi,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=t,this.readContiguousBoxes(e.slice(i,r.contentSize)),-1!==t.id&&-1!==t.timescale&&null!==t.info)if("video"===t.info.type&&-1!==t.info.width){const e=t;t.inputTrack=new Cn(this.input,new Nn(e)),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.inputTrack=new En(this.input,new Ln(e)),this.tracks.push(t)}this.currentTrack=null}break;case"tkhd":{const t=this.currentTrack;if(!t)break;const r=Xo(e),i=!!(1&Ko(e));if(t.disposition.default=i,0===r)e.skip(8),t.id=Qo(e),e.skip(4),t.durationInMovieTimescale=Qo(e);else{if(1!==r)throw new Error(`Incorrect track header version ${r}.`);e.skip(16),t.id=Qo(e),e.skip(4),t.durationInMovieTimescale=tc(e)}e.skip(16);const a=[Rn(e),Rn(e),On(e),Rn(e),Rn(e),On(e),Rn(e),Rn(e),On(e)],n=Xr(xi(jn(a),90));jr(0===n||90===n||180===n||270===n),t.rotation=n}break;case"elst":{const t=this.currentTrack;if(!t)break;const r=Xo(e);e.skip(3);let i=!1,a=0;const n=Qo(e);for(let s=0;s<n;s++){const n=1===r?tc(e):Qo(e),s=1===r?rc(e):Jo(e),o=Rn(e);if(0!==n){if(i){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(-1!==s){if(1!==o){console.warn("Unsupported edit list entry: media rate must be 1.");break}t.editListPreviousSegmentDurations=a,t.editListOffset=s,i=!0}else a+=n}}}break;case"mdhd":{const t=this.currentTrack;if(!t)break;const r=Xo(e);e.skip(3),0===r?(e.skip(8),t.timescale=Qo(e),t.durationInMediaTimescale=Qo(e)):1===r&&(e.skip(16),t.timescale=Qo(e),t.durationInMediaTimescale=tc(e));let i=Go(e);if(i>0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&i))+t.languageCode,i>>=5;Ei(t.languageCode)||(t.languageCode=wi)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const r=sc(e,4);"vide"===r?t.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:"soun"===r&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{const a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(i,r.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const r=Xo(e);e.skip(3);const i=Qo(e);for(let a=0;a<i;a++){const i=e.filePos,a=In(e);if(!a)break;t.internalCodecId=a.name;const n=a.name.toLowerCase();if("video"===t.info.type)"avc1"===n||"avc3"===n?(t.info.codec="avc",t.info.avcType="avc1"===n?1:3):"hvc1"===n||"hev1"===n?t.info.codec="hevc":"vp08"===n?t.info.codec="vp8":"vp09"===n?t.info.codec="vp9":"av01"===n?t.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${a.name}').`),e.skip(24),t.info.width=Go(e),t.info.height=Go(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,i+a.totalSize-e.filePos));else{"mp4a"===n||("opus"===n?t.info.codec="opus":"flac"===n?t.info.codec="flac":"twos"===n||"sowt"===n||"raw "===n||"in24"===n||"in32"===n||"fl32"===n||"fl64"===n||"lpcm"===n||"ipcm"===n||"fpcm"===n||("ulaw"===n?t.info.codec="ulaw":"alaw"===n?t.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${a.name}').`))),e.skip(8);const s=Go(e);e.skip(6);let o=Go(e),c=Go(e);e.skip(4);let l=Qo(e)/65536;if(0===r&&s>0)if(1===s)e.skip(4),c=8*Qo(e),e.skip(8);else if(2===s){e.skip(4),l=nc(e),o=Qo(e),e.skip(4),c=Qo(e);const r=Qo(e);if(e.skip(8),"lpcm"===n){const e=c+7>>3,i=Boolean(1&r),a=Boolean(2&r),n=4&r?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=a?"pcm-f32be":"pcm-f32"):n&1<<e-1?1===e?t.info.codec="pcm-s8":2===e?t.info.codec=a?"pcm-s16be":"pcm-s16":3===e?t.info.codec=a?"pcm-s24be":"pcm-s24":4===e&&(t.info.codec=a?"pcm-s32be":"pcm-s32"):1===e&&(t.info.codec="pcm-u8")),null===t.info.codec&&console.warn("Unsupported PCM format.")}}"opus"===t.info.codec&&(l=ca),t.info.numberOfChannels=o,t.info.sampleRate=l,"twos"===n?8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null):"sowt"===n?8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null):"raw "===n?t.info.codec="pcm-u8":"in24"===n?t.info.codec="pcm-s24be":"in32"===n?t.info.codec="pcm-s32be":"fl32"===n?t.info.codec="pcm-f32be":"fl64"===n?t.info.codec="pcm-f64be":"ipcm"===n?t.info.codec="pcm-s16be":"fpcm"===n&&(t.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,i+a.totalSize-e.filePos))}}}break;case"avcC":{const t=this.currentTrack;if(!t)break;jr(t.info),t.info.codecDescription=jo(e,r.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;jr(t.info),t.info.codecDescription=jo(e,r.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;jr("video"===t.info?.type),e.skip(4);const r=Xo(e),i=Xo(e),a=Xo(e),n=a>>4,s=a>>1&7,o=1&a,c=Xo(e),l=Xo(e),u=Xo(e);t.info.vp9CodecInfo={profile:r,level:i,bitDepth:n,chromaSubsampling:s,videoFullRangeFlag:o,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case"av1C":{const t=this.currentTrack;if(!t)break;jr("video"===t.info?.type),e.skip(1);const r=Xo(e),i=r>>5,a=31&r,n=Xo(e),s=n>>7,o=n>>6&1,c=n>>4&1,l=n>>3&1,u=n>>2&1,h=3&n,d=2===i&&o?n>>5&1?12:10:o?10:8;t.info.av1CodecInfo={profile:i,level:a,tier:s,bitDepth:d,monochrome:c,chromaSubsamplingX:l,chromaSubsamplingY:u,chromaSamplePosition:h}}break;case"colr":{const t=this.currentTrack;if(!t)break;jr("video"===t.info?.type);if("nclx"!==sc(e,4))break;const r=Go(e),i=Go(e),a=Go(e),n=Boolean(128&Xo(e));t.info.colorSpace={primaries:ii[r],transfer:ni[i],matrix:oi[a],fullRange:n}}break;case"esds":{const t=this.currentTrack;if(!t)break;jr("audio"===t.info?.type),e.skip(4);jr(3===Xo(e)),Mn(e),e.skip(2);const r=Xo(e),i=!!(64&r),a=!!(32&r);if(!!(128&r)&&e.skip(2),i){const t=Xo(e);e.skip(t)}a&&e.skip(2);jr(4===Xo(e));const n=Mn(e),s=e.filePos,o=Xo(e);if(64===o||103===o?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===o}):105===o||107===o?t.info.codec="mp3":221===o?t.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),n>e.filePos-s){jr(5===Xo(e));const r=Mn(e);if(t.info.codecDescription=jo(e,r),"aac"===t.info.codec){const e=oa(t.info.codecDescription);null!==e.numberOfChannels&&(t.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(t.info.sampleRate=e.sampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;jr("audio"===t.info?.type);255&Go(e)&&("pcm-s16be"===t.info.codec?t.info.codec="pcm-s16":"pcm-s24be"===t.info.codec?t.info.codec="pcm-s24":"pcm-s32be"===t.info.codec?t.info.codec="pcm-s32":"pcm-f32be"===t.info.codec?t.info.codec="pcm-f32":"pcm-f64be"===t.info.codec&&(t.info.codec="pcm-f64"))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;jr("audio"===t.info?.type),e.skip(4);const r=Xo(e),i=Boolean(1&r),a=Xo(e);"pcm-s16be"===t.info.codec?i?16===a?t.info.codec="pcm-s16":24===a?t.info.codec="pcm-s24":32===a?t.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${a}.`),t.info.codec=null):16===a?t.info.codec="pcm-s16be":24===a?t.info.codec="pcm-s24be":32===a?t.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${a}.`),t.info.codec=null):"pcm-f32be"===t.info.codec&&(i?32===a?t.info.codec="pcm-f32":64===a?t.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${a}.`),t.info.codec=null):32===a?t.info.codec="pcm-f32be":64===a?t.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${a}.`),t.info.codec=null));break}case"dOps":{const t=this.currentTrack;if(!t)break;jr("audio"===t.info?.type),e.skip(1);const r=Xo(e),i=Go(e),a=Qo(e),n=Yo(e),s=Xo(e);let o;o=0!==s?jo(e,2+r):new Uint8Array(0);const c=new Uint8Array(19+o.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,r),l.setUint16(10,i,!0),l.setUint32(12,a,!0),l.setInt16(16,n,!0),l.setUint8(18,s),c.set(o,19),t.info.codecDescription=c,t.info.numberOfChannels=r}break;case"dfLa":{const t=this.currentTrack;if(!t)break;jr("audio"===t.info?.type),e.skip(4);const r=127,i=128,n=e.filePos;for(;e.filePos<a;){const a=Xo(e),n=Ko(e);if((a&r)===qa.STREAMINFO){e.skip(10);const r=Qo(e),i=r>>>12,a=1+(r>>9&7);t.info.sampleRate=i,t.info.numberOfChannels=a,e.skip(20)}else e.skip(n);if(a&i)break}const s=e.filePos;e.filePos=n;const o=jo(e,s-n),c=new Uint8Array(4+o.byteLength);new DataView(c.buffer).setUint32(0,1716281667,!1),c.set(o,4),t.info.codecDescription=c}break;case"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Qo(e);let i=0,a=0;for(let n=0;n<r;n++){const r=Qo(e),n=Qo(e);t.sampleTable.sampleTimingEntries.push({startIndex:i,startDecodeTimestamp:a,count:r,delta:n}),i+=r,a+=r*n}}break;case"ctts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Qo(e);let i=0;for(let a=0;a<r;a++){const r=Qo(e),a=Jo(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:i,count:r,offset:a}),i+=r}}break;case"stsz":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Qo(e),i=Qo(e);if(0===r)for(let r=0;r<i;r++){const r=Qo(e);t.sampleTable.sampleSizes.push(r)}else t.sampleTable.sampleSizes.push(r)}break;case"stz2":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),e.skip(3);const r=Xo(e),i=Qo(e),a=jo(e,Math.ceil(i*r/8)),n=new Kr(a);for(let e=0;e<i;e++){const e=n.readBits(r);t.sampleTable.sampleSizes.push(e)}}break;case"stss":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];const r=Qo(e);for(let i=0;i<r;i++){const r=Qo(e)-1;t.sampleTable.keySampleIndices.push(r)}0!==t.sampleTable.keySampleIndices[0]&&t.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Qo(e);for(let i=0;i<r;i++){const r=Qo(e)-1,i=Qo(e),a=Qo(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:r,samplesPerChunk:i,sampleDescriptionIndex:a})}let i=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=i,e<t.sampleTable.sampleToChunk.length-1){i+=(t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex)*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case"stco":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Qo(e);for(let i=0;i<r;i++){const r=Qo(e);t.sampleTable.chunkOffsets.push(r)}}break;case"co64":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Qo(e);for(let i=0;i<r;i++){const r=tc(e);t.sampleTable.chunkOffsets.push(r)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(i,r.contentSize));break;case"mehd":{const t=Xo(e);e.skip(3);const r=1===t?tc(e):Qo(e);this.movieDurationInTimescale=r}break;case"trex":{e.skip(4);const t=Qo(e),r=Qo(e),i=Qo(e),a=Qo(e),n=Qo(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:r,defaultSampleDuration:i,defaultSampleSize:a,defaultSampleFlags:n})}break;case"tfra":{const t=Xo(e);e.skip(3);const r=Qo(e),i=this.tracks.find(e=>e.id===r);if(!i)break;const a=Qo(e),n=(12&a)>>2,s=3&a,o=[Xo,Go,Ko,Qo],c=o[(48&a)>>4],l=o[n],u=o[s],h=Qo(e);for(let r=0;r<h;r++){const r=1===t?tc(e):Qo(e),a=1===t?tc(e):Qo(e);c(e),l(e),u(e),i.fragmentLookupTable.push({timestamp:r,moofOffset:a})}i.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<i.fragmentLookupTable.length-1;e++){const t=i.fragmentLookupTable[e],r=i.fragmentLookupTable[e+1];t.timestamp===r.timestamp&&(i.fragmentLookupTable.splice(e+1,1),e--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:new Map},this.readContiguousBoxes(e.slice(i,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(jr(this.currentFragment),this.readContiguousBoxes(e.slice(i,r.contentSize)),this.currentTrack){const e=this.currentFragment.trackData.get(this.currentTrack.id);if(e){const{currentFragmentState:t}=this.currentTrack;jr(t),null!==t.startTimestamp&&(Hn(e,t.startTimestamp),e.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{jr(this.currentFragment),e.skip(1);const t=Ko(e),r=Boolean(1&t),i=Boolean(2&t),a=Boolean(8&t),n=Boolean(16&t),s=Boolean(32&t),o=Boolean(65536&t),c=Boolean(131072&t),l=Qo(e),u=this.tracks.find(e=>e.id===l);if(!u)break;const h=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:h?.defaultSampleDescriptionIndex??null,defaultSampleDuration:h?.defaultSampleDuration??null,defaultSampleSize:h?.defaultSampleSize??null,defaultSampleFlags:h?.defaultSampleFlags??null,startTimestamp:null},r?u.currentFragmentState.baseDataOffset=tc(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),i&&(u.currentFragmentState.sampleDescriptionIndex=Qo(e)),a&&(u.currentFragmentState.defaultSampleDuration=Qo(e)),n&&(u.currentFragmentState.defaultSampleSize=Qo(e)),s&&(u.currentFragmentState.defaultSampleFlags=Qo(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;jr(t.currentFragmentState);const r=Xo(e);e.skip(3);const i=0===r?Qo(e):tc(e);t.currentFragmentState.startTimestamp=i}break;case"trun":{const t=this.currentTrack;if(!t)break;if(jr(this.currentFragment),jr(t.currentFragmentState),this.currentFragment.trackData.has(t.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}const r=Xo(e),i=Ko(e),a=Boolean(1&i),n=Boolean(4&i),s=Boolean(256&i),o=Boolean(512&i),c=Boolean(1024&i),l=Boolean(2048&i),u=Qo(e);let h=t.currentFragmentState.baseDataOffset;a&&(h+=Jo(e));let d=null;n&&(d=Qo(e));let f=h;if(0===u){this.currentFragment.implicitBaseDataOffset=f;break}let m=0;const p={track:t,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(t.id,p);for(let i=0;i<u;i++){let a,n,u;s?a=Qo(e):(jr(null!==t.currentFragmentState.defaultSampleDuration),a=t.currentFragmentState.defaultSampleDuration),o?n=Qo(e):(jr(null!==t.currentFragmentState.defaultSampleSize),n=t.currentFragmentState.defaultSampleSize),c?u=Qo(e):(jr(null!==t.currentFragmentState.defaultSampleFlags),u=t.currentFragmentState.defaultSampleFlags),0===i&&null!==d&&(u=d);let h=0;l&&(h=0===r?Qo(e):Jo(e));const g=!(65536&u);p.samples.push({presentationTimestamp:m+h,duration:a,byteOffset:f,byteSize:n,isKeyFrame:g}),f+=n,m+=a}p.presentationTimestamps=p.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let e=0;e<p.presentationTimestamps.length;e++){const t=p.presentationTimestamps[e],r=p.samples[t.sampleIndex];if(null===p.firstKeyFrameTimestamp&&r.isKeyFrame&&(p.firstKeyFrameTimestamp=r.presentationTimestamp),e<p.presentationTimestamps.length-1){const i=p.presentationTimestamps[e+1];r.duration=i.presentationTimestamp-t.presentationTimestamp}}const g=p.samples[p.presentationTimestamps[0].sampleIndex],v=p.samples[qr(p.presentationTimestamps).sampleIndex];p.startTimestamp=g.presentationTimestamp,p.endTimestamp=v.presentationTimestamp+v.duration,this.currentFragment.implicitBaseDataOffset=f}break;case"udta":{const t=this.iterateContiguousBoxes(e.slice(i,r.contentSize));for(const{boxInfo:e,slice:r}of t){if("meta"!==e.name&&!this.currentTrack){const t=r.filePos;this.metadataTags.raw??={},"©"===e.name[0]?this.metadataTags.raw[e.name]??=_n(r):this.metadataTags.raw[e.name]??=jo(r,e.contentSize),r.filePos=t}switch(e.name){case"meta":r.skip(-e.headerSize),this.traverseBox(r);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=Jr.decode(jo(r,e.contentSize)):this.metadataTags.title??=_n(r);break;case"©des":this.currentTrack||(this.metadataTags.description??=_n(r));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=_n(r));break;case"©alb":this.currentTrack||(this.metadataTags.album??=_n(r));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=_n(r));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=_n(r));break;case"©day":if(!this.currentTrack){const e=new Date(_n(r));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=_n(r));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=_n(r))}}}break;case"meta":{if(this.currentTrack)break;const t=0!==Qo(e);this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(i,r.contentSize)):this.readContiguousBoxes(e.slice(i+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const t=Qo(e);for(let r=0;r<t;r++){const t=Qo(e);e.skip(4);const i=Jr.decode(jo(e,t-8));this.currentMetadataKeys.set(r+1,i)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const t=this.iterateContiguousBoxes(e.slice(i,r.contentSize));for(const{boxInfo:e,slice:r}of t){let t=e.name;const i=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(i)&&(t=this.currentMetadataKeys.get(i));const a=Dn(r);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=a,t){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":"string"==typeof a&&(this.metadataTags.title??=a);break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":"string"==typeof a&&(this.metadataTags.description??=a);break;case"©ART":case"com.apple.quicktime.artist":case"artist":"string"==typeof a&&(this.metadataTags.artist??=a);break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":"string"==typeof a&&(this.metadataTags.album??=a);break;case"aART":case"album_artist":"string"==typeof a&&(this.metadataTags.albumArtist??=a);break;case"©cmt":case"com.apple.quicktime.comment":case"comment":"string"==typeof a&&(this.metadataTags.comment??=a);break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":"string"==typeof a&&(this.metadataTags.genre??=a);break;case"©lyr":case"lyrics":"string"==typeof a&&(this.metadataTags.lyrics??=a);break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if("string"==typeof a){const e=new Date(a);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"covr":case"com.apple.quicktime.artwork":a instanceof ji?(this.metadataTags.images??=[],this.metadataTags.images.push({data:a.data,kind:"coverFront",mimeType:a.mimeType})):a instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:a,kind:"coverFront",mimeType:"image/*"}));break;case"track":if("string"==typeof a){const e=a.split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(this.metadataTags.tracksTotal??=r)}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=Zr(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),r>0&&(this.metadataTags.tracksTotal??=r)}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=Zr(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),r>0&&(this.metadataTags.discsTotal??=r)}}}}}return e.filePos=a,!0}}class Fn{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){const e=await this.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Si(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Un(i,r),n=await this.fetchPacketForSampleIndex(a,t);return Xn(i)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const i=mi(t.presentationTimestamps,r,e=>e.presentationTimestamp);return{sampleIndex:-1!==i?t.presentationTimestamps[i].sampleIndex:-1,correctSampleFound:-1!==i&&r<t.endTimestamp}},r,r,t):n}async getNextPacket(e,t){const r=this.packetToSampleIndex.get(e);if(void 0!==r)return this.fetchPacketForSampleIndex(r+1,t);const i=this.packetToFragmentLocation.get(e);if(void 0===i)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,e=>{if(e===i.fragment){const t=e.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<t.samples.length)return{sampleIndex:i.sampleIndex+1,correctSampleFound:!0}}else{if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Un(i,r),n=-1===a?-1:Wn(i,a),s=await this.fetchPacketForSampleIndex(n,t);return Xn(i)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const i=yi(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=r);return{sampleIndex:-1!==i?t.presentationTimestamps[i].sampleIndex:-1,correctSampleFound:-1!==i&&r<t.endTimestamp}},r,r,t):s}async getNextKeyPacket(e,t){const r=this.packetToSampleIndex.get(e);if(void 0!==r){const e=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Vn(e,r);return this.fetchPacketForSampleIndex(i,t)}const i=this.packetToFragmentLocation.get(e);if(void 0===i)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,e=>{if(e===i.fragment){const t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>i.sampleIndex);if(-1!==t)return{sampleIndex:t,correctSampleFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.samples.findIndex(e=>e.isKeyFrame);return jr(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=zn(r,e);if(!i)return null;let a;if(t.metadataOnly)a=Qa;else{let e=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);e instanceof Promise&&(e=await e),jr(e),a=jo(e,i.sampleSize)}const n=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,s=i.duration/this.internalTrack.timescale,o=new Za(a,i.isKeyFrame?"key":"delta",n,s,e,i.sampleSize);return this.packetToSampleIndex.set(o,e),o}async fetchPacketInFragment(e,t,r){if(-1===t)return null;const i=e.trackData.get(this.internalTrack.id).samples[t];let a;if(jr(i),r.metadataOnly)a=Qa;else{let e=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);e instanceof Promise&&(e=await e),jr(e),a=jo(e,i.byteSize)}const n=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,s=i.duration/this.internalTrack.timescale,o=new Za(a,i.isKeyFrame?"key":"delta",n,s,e.moofOffset+t,i.byteSize);return this.packetToFragmentLocation.set(o,{fragment:e,sampleIndex:t}),o}async performFragmentedLookup(e,t,r,i,a){const n=this.internalTrack.demuxer;let s=null,o=null,c=-1;if(e){const{sampleIndex:r,correctSampleFound:i}=t(e);if(i)return this.fetchPacketInFragment(e,r,a);-1!==r&&(o=e,c=r)}const l=mi(this.internalTrack.fragmentLookupTable,r,e=>e.timestamp),u=-1!==l?this.internalTrack.fragmentLookupTable[l]:null,h=mi(this.internalTrack.fragmentPositionCache,r,e=>e.startTimestamp),d=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,f=Math.max(u?.moofOffset??0,d?.moofOffset??0)||null;let m;for(e?null===f||e.moofOffset>=f?(m=e.moofOffset+e.moofSize,s=e):m=f:m=f??0;;){if(s){const e=s.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>i)break}let e=n.reader.requestSliceRange(m,8,Pn);if(e instanceof Promise&&(e=await e),!e)break;const r=m,l=In(e);if(!l)break;if("moof"===l.name){s=await n.readFragment(r);const{sampleIndex:e,correctSampleFound:i}=t(s);if(i)return this.fetchPacketInFragment(s,e,a);-1!==e&&(o=s,c=e)}m=r+l.totalSize}if(u&&(!o||o.moofOffset<u.moofOffset)){const e=this.internalTrack.fragmentLookupTable[l-1];jr(!e||e.timestamp<u.timestamp);const r=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,r,i,a)}return o?this.fetchPacketInFragment(o,c,a):null}}class Nn extends Fn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo){if("av1"===this.internalTrack.info.codec&&!this.internalTrack.info.av1CodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&Wa(e.data)}}else{const e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&Ua(e.data)}return{codec:ia(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}}class Ln extends Fn{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:aa(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}const Un=(e,t)=>{if(e.presentationTimestamps){const r=mi(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===r?-1:e.presentationTimestamps[r].sampleIndex}{const r=mi(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===r)return-1;const i=e.sampleTimingEntries[r];return i.startIndex+Math.min(Math.floor((t-i.startDecodeTimestamp)/i.delta),i.count-1)}},zn=(e,t)=>{const r=mi(e.sampleTimingEntries,t,e=>e.startIndex),i=e.sampleTimingEntries[r];if(!i||i.startIndex+i.count<=t)return null;let a=i.startDecodeTimestamp+(t-i.startIndex)*i.delta;const n=mi(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),s=e.sampleCompositionTimeOffsets[n];s&&t-s.startIndex<s.count&&(a+=s.offset);const o=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],c=mi(e.sampleToChunk,t,e=>e.startSampleIndex),l=e.sampleToChunk[c];jr(l);const u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),h=e.chunkOffsets[u],d=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk;let f=0,m=h;if(1===e.sampleSizes.length)m+=o*(t-d),f+=o*l.samplesPerChunk;else for(let r=d;r<d+l.samplesPerChunk;r++){const i=e.sampleSizes[r];r<t&&(m+=i),f+=i}let p=i.delta;if(e.presentationTimestamps){const r=e.presentationTimestampIndexMap[t];if(jr(void 0!==r),r<e.presentationTimestamps.length-1){p=e.presentationTimestamps[r+1].presentationTimestamp-a}}return{presentationTimestamp:a,duration:p,sampleOffset:m,sampleSize:o,chunkOffset:h,chunkSize:f,isKeyFrame:!e.keySampleIndices||-1!==fi(e.keySampleIndices,t,e=>e)}},Wn=(e,t)=>{if(!e.keySampleIndices)return t;const r=mi(e.keySampleIndices,t,e=>e);return e.keySampleIndices[r]??-1},Vn=(e,t)=>{if(!e.keySampleIndices)return t+1;const r=mi(e.keySampleIndices,t,e=>e);return e.keySampleIndices[r+1]??-1},Hn=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(const r of e.samples)r.presentationTimestamp+=t;for(const r of e.presentationTimestamps)r.presentationTimestamp+=t},jn=e=>{const[t,,,r]=e,i=Math.hypot(t,r),a=t/i,n=r/i,s=-Math.atan2(n,a)*(180/Math.PI);return Number.isFinite(s)?s:0},Xn=e=>0===e.sampleSizes.length;
90
+ class Js extends is{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.tracks.map(e=>e.inputTrack.getCodecParameterString()));return js({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>"video"===e.info?.type),hasAudio:this.tracks.some(e=>"audio"===e.info?.type),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,8,Gs);if(t instanceof Promise&&(t=await t),!t)break;const r=e,i=Ys(t);if(!i)break;if("ftyp"===i.name){const e=kl(t,4);this.isQuickTime="qt "===e}else if("moov"===i.name){let e=this.reader.requestSlice(t.filePos,i.contentSize);if(e instanceof Promise&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));for(const e of this.tracks){const t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}break}e=r+i.totalSize}if(this.isFragmented&&null!==this.reader.fileSize){let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),Xa(e);const t=ml(e),r=this.reader.fileSize-t;if(r>=0&&r<=this.reader.fileSize-Gs){let e=this.reader.requestSliceRange(r,8,Gs);if(e instanceof Promise&&(e=await e),e){const t=Ys(e);if(t&&"mfra"===t.name){let r=this.reader.requestSlice(e.filePos,t.contentSize);r instanceof Promise&&(r=await r),r&&this.readContiguousBoxes(r)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=t,Xa(this.moovSlice);const r=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(r),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&Zn.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){Xa("audio"===e.info?.type);const r=po(e.info.codec),i=[],a=[];for(let n=0;n<t.sampleToChunk.length;n++){const o=t.sampleToChunk[n],s=t.sampleToChunk[n+1],c=(s?s.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let n=0;n<c;n++){const s=o.startSampleIndex+n*o.samplesPerChunk,c=s+o.samplesPerChunk,u=pn(t.sampleTimingEntries,s,e=>e.startIndex),l=t.sampleTimingEntries[u],h=pn(t.sampleTimingEntries,c,e=>e.startIndex),d=t.sampleTimingEntries[h],f=l.startDecodeTimestamp+(s-l.startIndex)*l.delta,m=d.startDecodeTimestamp+(c-d.startIndex)*d.delta-f,p=Ga(i);p&&p.delta===m?p.count++:i.push({startIndex:o.startChunkIndex+n,startDecodeTimestamp:f,count:1,delta:m});const g=o.samplesPerChunk*r.sampleSize*e.info.numberOfChannels;a.push(g)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=i,t.sampleSizes=a}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const e of t.sampleTimingEntries)for(let r=0;r<e.count;r++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+r*e.delta,sampleIndex:e.startIndex+r});for(const e of t.sampleCompositionTimeOffsets)for(let r=0;r<e.count;r++){const i=e.startIndex+r,a=t.presentationTimestamps[i];a&&(a.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,Gs);t instanceof Promise&&(t=await t),Xa(t);const r=Ys(t);Xa("moof"===r?.name);let i=this.reader.requestSlice(e,r.totalSize);i instanceof Promise&&(i=await i),Xa(i),this.traverseBox(i);const a=this.lastReadFragment;Xa(a&&a.moofOffset===e);for(const[,e]of a.trackData){const t=e.track,{fragmentPositionCache:r}=t;if(!e.startTimestampIsFinal){const i=t.fragmentLookupTable.find(e=>e.moofOffset===a.moofOffset);if(i)sc(e,i.timestamp);else{const t=pn(r,a.moofOffset-1,e=>e.moofOffset);if(-1!==t){const i=r[t];sc(e,i.endTimestamp)}}e.startTimestampIsFinal=!0}const i=pn(r,e.startTimestamp,e=>e.startTimestamp);-1!==i&&r[i].moofOffset===a.moofOffset||r.splice(i+1,0,{moofOffset:a.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp})}return a}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){if(!this.traverseBox(e))break}}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){const t=e.filePos,r=Ys(e);if(!r)break;yield{boxInfo:r,slice:e},e.filePos=t+r.totalSize}}traverseBox(e){const t=e.filePos,r=Ys(e);if(!r)return!1;const i=e.filePos,a=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"wave":this.readContiguousBoxes(e.slice(i,r.contentSize));break;case"mvhd":{const t=cl(e);e.skip(3),1===t?(e.skip(16),this.movieTimescale=ml(e),this.movieDurationInTimescale=yl(e)):(e.skip(8),this.movieTimescale=ml(e),this.movieDurationInTimescale=ml(e))}break;case"trak":{const t={id:-1,demuxer:this,inputTrack:null,disposition:{...$n},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Sn,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=t,this.readContiguousBoxes(e.slice(i,r.contentSize)),-1!==t.id&&-1!==t.timescale&&null!==t.info)if("video"===t.info.type&&-1!==t.info.width){const e=t;t.inputTrack=new Hs(this.input,new tc(e)),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.inputTrack=new Xs(this.input,new rc(e)),this.tracks.push(t)}this.currentTrack=null}break;case"tkhd":{const t=this.currentTrack;if(!t)break;const r=cl(e),i=!!(1&hl(e));if(t.disposition.default=i,0===r)e.skip(8),t.id=ml(e),e.skip(4),t.durationInMovieTimescale=ml(e);else{if(1!==r)throw new Error(`Incorrect track header version ${r}.`);e.skip(16),t.id=ml(e),e.skip(4),t.durationInMovieTimescale=yl(e)}e.skip(16);const a=[qs(e),qs(e),Ks(e),qs(e),qs(e),Ks(e),qs(e),qs(e),Ks(e)],n=ja(Cn(cc(a),90));Xa(0===n||90===n||180===n||270===n),t.rotation=n}break;case"elst":{const t=this.currentTrack;if(!t)break;const r=cl(e);e.skip(3);let i=!1,a=0;const n=ml(e);for(let o=0;o<n;o++){const n=1===r?yl(e):ml(e),o=1===r?bl(e):gl(e),s=qs(e);if(0!==n){if(i){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(-1!==o){if(1!==s){console.warn("Unsupported edit list entry: media rate must be 1.");break}t.editListPreviousSegmentDurations=a,t.editListOffset=o,i=!0}else a+=n}}}break;case"mdhd":{const t=this.currentTrack;if(!t)break;const r=cl(e);e.skip(3),0===r?(e.skip(8),t.timescale=ml(e),t.durationInMediaTimescale=ml(e)):1===r&&(e.skip(16),t.timescale=ml(e),t.durationInMediaTimescale=yl(e));let i=ll(e);if(i>0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&i))+t.languageCode,i>>=5;_n(t.languageCode)||(t.languageCode=Sn)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const r=kl(e,4);"vide"===r?t.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:"soun"===r&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{const a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(i,r.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const r=cl(e);e.skip(3);const i=ml(e);for(let a=0;a<i;a++){const i=e.filePos,a=Ys(e);if(!a)break;t.internalCodecId=a.name;const n=a.name.toLowerCase();if("video"===t.info.type)"avc1"===n||"avc3"===n?(t.info.codec="avc",t.info.avcType="avc1"===n?1:3):"hvc1"===n||"hev1"===n?t.info.codec="hevc":"vp08"===n?t.info.codec="vp8":"vp09"===n?t.info.codec="vp9":"av01"===n?t.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${a.name}').`),e.skip(24),t.info.width=ll(e),t.info.height=ll(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,i+a.totalSize-e.filePos));else{"mp4a"===n||("opus"===n?t.info.codec="opus":"flac"===n?t.info.codec="flac":"twos"===n||"sowt"===n||"raw "===n||"in24"===n||"in32"===n||"fl32"===n||"fl64"===n||"lpcm"===n||"ipcm"===n||"fpcm"===n||("ulaw"===n?t.info.codec="ulaw":"alaw"===n?t.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${a.name}').`))),e.skip(8);const o=ll(e);e.skip(6);let s=ll(e),c=ll(e);e.skip(4);let u=ml(e)/65536;if(0===r&&o>0)if(1===o)e.skip(4),c=8*ml(e),e.skip(8);else if(2===o){e.skip(4),u=wl(e),s=ml(e),e.skip(4),c=ml(e);const r=ml(e);if(e.skip(8),"lpcm"===n){const e=c+7>>3,i=Boolean(1&r),a=Boolean(2&r),n=4&r?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=a?"pcm-f32be":"pcm-f32"):n&1<<e-1?1===e?t.info.codec="pcm-s8":2===e?t.info.codec=a?"pcm-s16be":"pcm-s16":3===e?t.info.codec=a?"pcm-s24be":"pcm-s24":4===e&&(t.info.codec=a?"pcm-s32be":"pcm-s32"):1===e&&(t.info.codec="pcm-u8")),null===t.info.codec&&console.warn("Unsupported PCM format.")}}"opus"===t.info.codec&&(u=fo),t.info.numberOfChannels=s,t.info.sampleRate=u,"twos"===n?8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null):"sowt"===n?8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null):"raw "===n?t.info.codec="pcm-u8":"in24"===n?t.info.codec="pcm-s24be":"in32"===n?t.info.codec="pcm-s32be":"fl32"===n?t.info.codec="pcm-f32be":"fl64"===n?t.info.codec="pcm-f64be":"ipcm"===n?t.info.codec="pcm-s16be":"fpcm"===n&&(t.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,i+a.totalSize-e.filePos))}}}break;case"avcC":{const t=this.currentTrack;if(!t)break;Xa(t.info),t.info.codecDescription=sl(e,r.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;Xa(t.info),t.info.codecDescription=sl(e,r.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;Xa("video"===t.info?.type),e.skip(4);const r=cl(e),i=cl(e),a=cl(e),n=a>>4,o=a>>1&7,s=1&a,c=cl(e),u=cl(e),l=cl(e);t.info.vp9CodecInfo={profile:r,level:i,bitDepth:n,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:c,transferCharacteristics:u,matrixCoefficients:l}}break;case"av1C":{const t=this.currentTrack;if(!t)break;Xa("video"===t.info?.type),e.skip(1);const r=cl(e),i=r>>5,a=31&r,n=cl(e),o=n>>7,s=n>>6&1,c=n>>4&1,u=n>>3&1,l=n>>2&1,h=3&n,d=2===i&&s?n>>5&1?12:10:s?10:8;t.info.av1CodecInfo={profile:i,level:a,tier:o,bitDepth:d,monochrome:c,chromaSubsamplingX:u,chromaSubsamplingY:l,chromaSamplePosition:h}}break;case"colr":{const t=this.currentTrack;if(!t)break;Xa("video"===t.info?.type);if("nclx"!==kl(e,4))break;const r=ll(e),i=ll(e),a=ll(e),n=Boolean(128&cl(e));t.info.colorSpace={primaries:an[r],transfer:on[i],matrix:cn[a],fullRange:n}}break;case"esds":{const t=this.currentTrack;if(!t)break;Xa("audio"===t.info?.type),e.skip(4);Xa(3===cl(e)),$s(e),e.skip(2);const r=cl(e),i=!!(64&r),a=!!(32&r);if(!!(128&r)&&e.skip(2),i){const t=cl(e);e.skip(t)}a&&e.skip(2);Xa(4===cl(e));const n=$s(e),o=e.filePos,s=cl(e);if(64===s||103===s?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===s}):105===s||107===s?t.info.codec="mp3":221===s?t.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${s}) - discarding track.`),e.skip(12),n>e.filePos-o){Xa(5===cl(e));const r=$s(e);if(t.info.codecDescription=sl(e,r),"aac"===t.info.codec){const e=ho(t.info.codecDescription);null!==e.numberOfChannels&&(t.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(t.info.sampleRate=e.sampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;Xa("audio"===t.info?.type);255&ll(e)&&("pcm-s16be"===t.info.codec?t.info.codec="pcm-s16":"pcm-s24be"===t.info.codec?t.info.codec="pcm-s24":"pcm-s32be"===t.info.codec?t.info.codec="pcm-s32":"pcm-f32be"===t.info.codec?t.info.codec="pcm-f32":"pcm-f64be"===t.info.codec&&(t.info.codec="pcm-f64"))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;Xa("audio"===t.info?.type),e.skip(4);const r=cl(e),i=Boolean(1&r),a=cl(e);"pcm-s16be"===t.info.codec?i?16===a?t.info.codec="pcm-s16":24===a?t.info.codec="pcm-s24":32===a?t.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${a}.`),t.info.codec=null):16===a?t.info.codec="pcm-s16be":24===a?t.info.codec="pcm-s24be":32===a?t.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${a}.`),t.info.codec=null):"pcm-f32be"===t.info.codec&&(i?32===a?t.info.codec="pcm-f32":64===a?t.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${a}.`),t.info.codec=null):32===a?t.info.codec="pcm-f32be":64===a?t.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${a}.`),t.info.codec=null));break}case"dOps":{const t=this.currentTrack;if(!t)break;Xa("audio"===t.info?.type),e.skip(1);const r=cl(e),i=ll(e),a=ml(e),n=dl(e),o=cl(e);let s;s=0!==o?sl(e,2+r):new Uint8Array(0);const c=new Uint8Array(19+s.byteLength),u=new DataView(c.buffer);u.setUint32(0,1332770163,!1),u.setUint32(4,1214603620,!1),u.setUint8(8,1),u.setUint8(9,r),u.setUint16(10,i,!0),u.setUint32(12,a,!0),u.setInt16(16,n,!0),u.setUint8(18,o),c.set(s,19),t.info.codecDescription=c,t.info.numberOfChannels=r}break;case"dfLa":{const t=this.currentTrack;if(!t)break;Xa("audio"===t.info?.type),e.skip(4);const r=127,i=128,n=e.filePos;for(;e.filePos<a;){const a=cl(e),n=hl(e);if((a&r)===ts.STREAMINFO){e.skip(10);const r=ml(e),i=r>>>12,a=1+(r>>9&7);t.info.sampleRate=i,t.info.numberOfChannels=a,e.skip(20)}else e.skip(n);if(a&i)break}const o=e.filePos;e.filePos=n;const s=sl(e,o-n),c=new Uint8Array(4+s.byteLength);new DataView(c.buffer).setUint32(0,1716281667,!1),c.set(s,4),t.info.codecDescription=c}break;case"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=ml(e);let i=0,a=0;for(let n=0;n<r;n++){const r=ml(e),n=ml(e);t.sampleTable.sampleTimingEntries.push({startIndex:i,startDecodeTimestamp:a,count:r,delta:n}),i+=r,a+=r*n}}break;case"ctts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=ml(e);let i=0;for(let a=0;a<r;a++){const r=ml(e),a=gl(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:i,count:r,offset:a}),i+=r}}break;case"stsz":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=ml(e),i=ml(e);if(0===r)for(let r=0;r<i;r++){const r=ml(e);t.sampleTable.sampleSizes.push(r)}else t.sampleTable.sampleSizes.push(r)}break;case"stz2":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),e.skip(3);const r=cl(e),i=ml(e),a=sl(e,Math.ceil(i*r/8)),n=new qa(a);for(let e=0;e<i;e++){const e=n.readBits(r);t.sampleTable.sampleSizes.push(e)}}break;case"stss":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];const r=ml(e);for(let i=0;i<r;i++){const r=ml(e)-1;t.sampleTable.keySampleIndices.push(r)}0!==t.sampleTable.keySampleIndices[0]&&t.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=ml(e);for(let i=0;i<r;i++){const r=ml(e)-1,i=ml(e),a=ml(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:r,samplesPerChunk:i,sampleDescriptionIndex:a})}let i=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=i,e<t.sampleTable.sampleToChunk.length-1){i+=(t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex)*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case"stco":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=ml(e);for(let i=0;i<r;i++){const r=ml(e);t.sampleTable.chunkOffsets.push(r)}}break;case"co64":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=ml(e);for(let i=0;i<r;i++){const r=yl(e);t.sampleTable.chunkOffsets.push(r)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(i,r.contentSize));break;case"mehd":{const t=cl(e);e.skip(3);const r=1===t?yl(e):ml(e);this.movieDurationInTimescale=r}break;case"trex":{e.skip(4);const t=ml(e),r=ml(e),i=ml(e),a=ml(e),n=ml(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:r,defaultSampleDuration:i,defaultSampleSize:a,defaultSampleFlags:n})}break;case"tfra":{const t=cl(e);e.skip(3);const r=ml(e),i=this.tracks.find(e=>e.id===r);if(!i)break;const a=ml(e),n=(12&a)>>2,o=3&a,s=[cl,ll,hl,ml],c=s[(48&a)>>4],u=s[n],l=s[o],h=ml(e);for(let r=0;r<h;r++){const r=1===t?yl(e):ml(e),a=1===t?yl(e):ml(e);c(e),u(e),l(e),i.fragmentLookupTable.push({timestamp:r,moofOffset:a})}i.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<i.fragmentLookupTable.length-1;e++){const t=i.fragmentLookupTable[e],r=i.fragmentLookupTable[e+1];t.timestamp===r.timestamp&&(i.fragmentLookupTable.splice(e+1,1),e--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:new Map},this.readContiguousBoxes(e.slice(i,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(Xa(this.currentFragment),this.readContiguousBoxes(e.slice(i,r.contentSize)),this.currentTrack){const e=this.currentFragment.trackData.get(this.currentTrack.id);if(e){const{currentFragmentState:t}=this.currentTrack;Xa(t),null!==t.startTimestamp&&(sc(e,t.startTimestamp),e.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{Xa(this.currentFragment),e.skip(1);const t=hl(e),r=Boolean(1&t),i=Boolean(2&t),a=Boolean(8&t),n=Boolean(16&t),o=Boolean(32&t),s=Boolean(65536&t),c=Boolean(131072&t),u=ml(e),l=this.tracks.find(e=>e.id===u);if(!l)break;const h=this.fragmentTrackDefaults.find(e=>e.trackId===u);this.currentTrack=l,l.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:h?.defaultSampleDescriptionIndex??null,defaultSampleDuration:h?.defaultSampleDuration??null,defaultSampleSize:h?.defaultSampleSize??null,defaultSampleFlags:h?.defaultSampleFlags??null,startTimestamp:null},r?l.currentFragmentState.baseDataOffset=yl(e):c&&(l.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),i&&(l.currentFragmentState.sampleDescriptionIndex=ml(e)),a&&(l.currentFragmentState.defaultSampleDuration=ml(e)),n&&(l.currentFragmentState.defaultSampleSize=ml(e)),o&&(l.currentFragmentState.defaultSampleFlags=ml(e)),s&&(l.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;Xa(t.currentFragmentState);const r=cl(e);e.skip(3);const i=0===r?ml(e):yl(e);t.currentFragmentState.startTimestamp=i}break;case"trun":{const t=this.currentTrack;if(!t)break;if(Xa(this.currentFragment),Xa(t.currentFragmentState),this.currentFragment.trackData.has(t.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}const r=cl(e),i=hl(e),a=Boolean(1&i),n=Boolean(4&i),o=Boolean(256&i),s=Boolean(512&i),c=Boolean(1024&i),u=Boolean(2048&i),l=ml(e);let h=t.currentFragmentState.baseDataOffset;a&&(h+=gl(e));let d=null;n&&(d=ml(e));let f=h;if(0===l){this.currentFragment.implicitBaseDataOffset=f;break}let m=0;const p={track:t,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(t.id,p);for(let i=0;i<l;i++){let a,n,l;o?a=ml(e):(Xa(null!==t.currentFragmentState.defaultSampleDuration),a=t.currentFragmentState.defaultSampleDuration),s?n=ml(e):(Xa(null!==t.currentFragmentState.defaultSampleSize),n=t.currentFragmentState.defaultSampleSize),c?l=ml(e):(Xa(null!==t.currentFragmentState.defaultSampleFlags),l=t.currentFragmentState.defaultSampleFlags),0===i&&null!==d&&(l=d);let h=0;u&&(h=0===r?ml(e):gl(e));const g=!(65536&l);p.samples.push({presentationTimestamp:m+h,duration:a,byteOffset:f,byteSize:n,isKeyFrame:g}),f+=n,m+=a}p.presentationTimestamps=p.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let e=0;e<p.presentationTimestamps.length;e++){const t=p.presentationTimestamps[e],r=p.samples[t.sampleIndex];if(null===p.firstKeyFrameTimestamp&&r.isKeyFrame&&(p.firstKeyFrameTimestamp=r.presentationTimestamp),e<p.presentationTimestamps.length-1){const i=p.presentationTimestamps[e+1];r.duration=i.presentationTimestamp-t.presentationTimestamp}}const g=p.samples[p.presentationTimestamps[0].sampleIndex],v=p.samples[Ga(p.presentationTimestamps).sampleIndex];p.startTimestamp=g.presentationTimestamp,p.endTimestamp=v.presentationTimestamp+v.duration,this.currentFragment.implicitBaseDataOffset=f}break;case"udta":{const t=this.iterateContiguousBoxes(e.slice(i,r.contentSize));for(const{boxInfo:e,slice:r}of t){if("meta"!==e.name&&!this.currentTrack){const t=r.filePos;this.metadataTags.raw??={},"©"===e.name[0]?this.metadataTags.raw[e.name]??=Qs(r):this.metadataTags.raw[e.name]??=sl(r,e.contentSize),r.filePos=t}switch(e.name){case"meta":r.skip(-e.headerSize),this.traverseBox(r);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=Ja.decode(sl(r,e.contentSize)):this.metadataTags.title??=Qs(r);break;case"©des":this.currentTrack||(this.metadataTags.description??=Qs(r));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=Qs(r));break;case"©alb":this.currentTrack||(this.metadataTags.album??=Qs(r));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Qs(r));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=Qs(r));break;case"©day":if(!this.currentTrack){const e=new Date(Qs(r));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=Qs(r));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=Qs(r))}}}break;case"meta":{if(this.currentTrack)break;const t=0!==ml(e);this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(i,r.contentSize)):this.readContiguousBoxes(e.slice(i+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const t=ml(e);for(let r=0;r<t;r++){const t=ml(e);e.skip(4);const i=Ja.decode(sl(e,t-8));this.currentMetadataKeys.set(r+1,i)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const t=this.iterateContiguousBoxes(e.slice(i,r.contentSize));for(const{boxInfo:e,slice:r}of t){let t=e.name;const i=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(i)&&(t=this.currentMetadataKeys.get(i));const a=Zs(r);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=a,t){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":"string"==typeof a&&(this.metadataTags.title??=a);break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":"string"==typeof a&&(this.metadataTags.description??=a);break;case"©ART":case"com.apple.quicktime.artist":case"artist":"string"==typeof a&&(this.metadataTags.artist??=a);break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":"string"==typeof a&&(this.metadataTags.album??=a);break;case"aART":case"album_artist":"string"==typeof a&&(this.metadataTags.albumArtist??=a);break;case"©cmt":case"com.apple.quicktime.comment":case"comment":"string"==typeof a&&(this.metadataTags.comment??=a);break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":"string"==typeof a&&(this.metadataTags.genre??=a);break;case"©lyr":case"lyrics":"string"==typeof a&&(this.metadataTags.lyrics??=a);break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if("string"==typeof a){const e=new Date(a);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"covr":case"com.apple.quicktime.artwork":a instanceof qn?(this.metadataTags.images??=[],this.metadataTags.images.push({data:a.data,kind:"coverFront",mimeType:a.mimeType})):a instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:a,kind:"coverFront",mimeType:"image/*"}));break;case"track":if("string"==typeof a){const e=a.split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(this.metadataTags.tracksTotal??=r)}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=Za(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),r>0&&(this.metadataTags.tracksTotal??=r)}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=Za(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),r>0&&(this.metadataTags.discsTotal??=r)}}}}}return e.filePos=a,!0}}class ec{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){const e=await this.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return En(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ic(i,r),n=await this.fetchPacketForSampleIndex(a,t);return uc(i)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const i=pn(t.presentationTimestamps,r,e=>e.presentationTimestamp);return{sampleIndex:-1!==i?t.presentationTimestamps[i].sampleIndex:-1,correctSampleFound:-1!==i&&r<t.endTimestamp}},r,r,t):n}async getNextPacket(e,t){const r=this.packetToSampleIndex.get(e);if(void 0!==r)return this.fetchPacketForSampleIndex(r+1,t);const i=this.packetToFragmentLocation.get(e);if(void 0===i)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,e=>{if(e===i.fragment){const t=e.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<t.samples.length)return{sampleIndex:i.sampleIndex+1,correctSampleFound:!0}}else{if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ac(i,r),n=await this.fetchPacketForSampleIndex(a,t);return uc(i)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const i=bn(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=r);return{sampleIndex:-1!==i?t.presentationTimestamps[i].sampleIndex:-1,correctSampleFound:-1!==i&&r<t.endTimestamp}},r,r,t):n}async getNextKeyPacket(e,t){const r=this.packetToSampleIndex.get(e);if(void 0!==r){const e=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=oc(e,r);return this.fetchPacketForSampleIndex(i,t)}const i=this.packetToFragmentLocation.get(e);if(void 0===i)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,e=>{if(e===i.fragment){const t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>i.sampleIndex);if(-1!==t)return{sampleIndex:t,correctSampleFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.samples.findIndex(e=>e.isKeyFrame);return Xa(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=nc(r,e);if(!i)return null;let a;if(t.metadataOnly)a=os;else{let e=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);e instanceof Promise&&(e=await e),Xa(e),a=sl(e,i.sampleSize)}const n=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=i.duration/this.internalTrack.timescale,s=new ss(a,i.isKeyFrame?"key":"delta",n,o,e,i.sampleSize);return this.packetToSampleIndex.set(s,e),s}async fetchPacketInFragment(e,t,r){if(-1===t)return null;const i=e.trackData.get(this.internalTrack.id).samples[t];let a;if(Xa(i),r.metadataOnly)a=os;else{let e=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);e instanceof Promise&&(e=await e),Xa(e),a=sl(e,i.byteSize)}const n=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=i.duration/this.internalTrack.timescale,s=new ss(a,i.isKeyFrame?"key":"delta",n,o,e.moofOffset+t,i.byteSize);return this.packetToFragmentLocation.set(s,{fragment:e,sampleIndex:t}),s}async performFragmentedLookup(e,t,r,i,a){const n=this.internalTrack.demuxer;let o=null,s=null,c=-1;if(e){const{sampleIndex:r,correctSampleFound:i}=t(e);if(i)return this.fetchPacketInFragment(e,r,a);-1!==r&&(s=e,c=r)}const u=pn(this.internalTrack.fragmentLookupTable,r,e=>e.timestamp),l=-1!==u?this.internalTrack.fragmentLookupTable[u]:null,h=pn(this.internalTrack.fragmentPositionCache,r,e=>e.startTimestamp),d=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,f=Math.max(l?.moofOffset??0,d?.moofOffset??0)||null;let m;for(e?null===f||e.moofOffset>=f?(m=e.moofOffset+e.moofSize,o=e):m=f:m=f??0;;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>i)break}let e=n.reader.requestSliceRange(m,8,Gs);if(e instanceof Promise&&(e=await e),!e)break;const r=m,u=Ys(e);if(!u)break;if("moof"===u.name){o=await n.readFragment(r);const{sampleIndex:e,correctSampleFound:i}=t(o);if(i)return this.fetchPacketInFragment(o,e,a);-1!==e&&(s=o,c=e)}m=r+u.totalSize}if(l&&(!s||s.moofOffset<l.moofOffset)){const e=this.internalTrack.fragmentLookupTable[u-1];Xa(!e||e.timestamp<l.timestamp);const r=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,r,i,a)}return s?this.fetchPacketInFragment(s,c,a):null}}class tc extends ec{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo){if("av1"===this.internalTrack.info.codec&&!this.internalTrack.info.av1CodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&$o(e.data)}}else{const e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&qo(e.data)}return{codec:so(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}}class rc extends ec{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:co(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}const ic=(e,t)=>{if(e.presentationTimestamps){const r=pn(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===r?-1:e.presentationTimestamps[r].sampleIndex}{const r=pn(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===r)return-1;const i=e.sampleTimingEntries[r];return i.startIndex+Math.min(Math.floor((t-i.startDecodeTimestamp)/i.delta),i.count-1)}},ac=(e,t)=>{if(!e.keySampleIndices)return ic(e,t);if(e.presentationTimestamps){const r=pn(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(-1===r)return-1;for(let t=r;t>=0;t--){const r=e.presentationTimestamps[t].sampleIndex;if(-1!==mn(e.keySampleIndices,r,e=>e))return r}return-1}{const r=ic(e,t),i=pn(e.keySampleIndices,r,e=>e);return e.keySampleIndices[i]??-1}},nc=(e,t)=>{const r=pn(e.sampleTimingEntries,t,e=>e.startIndex),i=e.sampleTimingEntries[r];if(!i||i.startIndex+i.count<=t)return null;let a=i.startDecodeTimestamp+(t-i.startIndex)*i.delta;const n=pn(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[n];o&&t-o.startIndex<o.count&&(a+=o.offset);const s=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],c=pn(e.sampleToChunk,t,e=>e.startSampleIndex),u=e.sampleToChunk[c];Xa(u);const l=u.startChunkIndex+Math.floor((t-u.startSampleIndex)/u.samplesPerChunk),h=e.chunkOffsets[l],d=u.startSampleIndex+(l-u.startChunkIndex)*u.samplesPerChunk;let f=0,m=h;if(1===e.sampleSizes.length)m+=s*(t-d),f+=s*u.samplesPerChunk;else for(let r=d;r<d+u.samplesPerChunk;r++){const i=e.sampleSizes[r];r<t&&(m+=i),f+=i}let p=i.delta;if(e.presentationTimestamps){const r=e.presentationTimestampIndexMap[t];if(Xa(void 0!==r),r<e.presentationTimestamps.length-1){p=e.presentationTimestamps[r+1].presentationTimestamp-a}}return{presentationTimestamp:a,duration:p,sampleOffset:m,sampleSize:s,chunkOffset:h,chunkSize:f,isKeyFrame:!e.keySampleIndices||-1!==mn(e.keySampleIndices,t,e=>e)}},oc=(e,t)=>{if(!e.keySampleIndices)return t+1;const r=pn(e.keySampleIndices,t,e=>e);return e.keySampleIndices[r+1]??-1},sc=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(const r of e.samples)r.presentationTimestamp+=t;for(const r of e.presentationTimestamps)r.presentationTimestamp+=t},cc=e=>{const[t,,,r]=e,i=Math.hypot(t,r),a=t/i,n=r/i,o=-Math.atan2(n,a)*(180/Math.PI);return Number.isFinite(o)?o:0},uc=e=>0===e.sampleSizes.length;
91
91
  /*!
92
92
  * Copyright (c) 2025-present, Vanilagy and contributors
93
93
  *
@@ -95,28 +95,28 @@ class Bn extends Ka{constructor(e){super(e),this.moovSlice=null,this.currentTrac
95
95
  * License, v. 2.0. If a copy of the MPL was not distributed with this
96
96
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
97
97
  */
98
- class qn{constructor(e){this.value=e}}class Gn{constructor(e){this.value=e}}class Kn{constructor(e){this.value=e}}class Yn{constructor(e){this.value=e}}var $n;!function(e){e[e.EBML=440786851]="EBML",e[e.EBMLVersion=17030]="EBMLVersion",e[e.EBMLReadVersion=17143]="EBMLReadVersion",e[e.EBMLMaxIDLength=17138]="EBMLMaxIDLength",e[e.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",e[e.DocType=17026]="DocType",e[e.DocTypeVersion=17031]="DocTypeVersion",e[e.DocTypeReadVersion=17029]="DocTypeReadVersion",e[e.Void=236]="Void",e[e.Segment=408125543]="Segment",e[e.SeekHead=290298740]="SeekHead",e[e.Seek=19899]="Seek",e[e.SeekID=21419]="SeekID",e[e.SeekPosition=21420]="SeekPosition",e[e.Duration=17545]="Duration",e[e.Info=357149030]="Info",e[e.TimestampScale=2807729]="TimestampScale",e[e.MuxingApp=19840]="MuxingApp",e[e.WritingApp=22337]="WritingApp",e[e.Tracks=374648427]="Tracks",e[e.TrackEntry=174]="TrackEntry",e[e.TrackNumber=215]="TrackNumber",e[e.TrackUID=29637]="TrackUID",e[e.TrackType=131]="TrackType",e[e.FlagEnabled=185]="FlagEnabled",e[e.FlagDefault=136]="FlagDefault",e[e.FlagForced=21930]="FlagForced",e[e.FlagOriginal=21934]="FlagOriginal",e[e.FlagHearingImpaired=21931]="FlagHearingImpaired",e[e.FlagVisualImpaired=21932]="FlagVisualImpaired",e[e.FlagCommentary=21935]="FlagCommentary",e[e.FlagLacing=156]="FlagLacing",e[e.Name=21358]="Name",e[e.Language=2274716]="Language",e[e.LanguageBCP47=2274717]="LanguageBCP47",e[e.CodecID=134]="CodecID",e[e.CodecPrivate=25506]="CodecPrivate",e[e.CodecDelay=22186]="CodecDelay",e[e.SeekPreRoll=22203]="SeekPreRoll",e[e.DefaultDuration=2352003]="DefaultDuration",e[e.Video=224]="Video",e[e.PixelWidth=176]="PixelWidth",e[e.PixelHeight=186]="PixelHeight",e[e.AlphaMode=21440]="AlphaMode",e[e.Audio=225]="Audio",e[e.SamplingFrequency=181]="SamplingFrequency",e[e.Channels=159]="Channels",e[e.BitDepth=25188]="BitDepth",e[e.SimpleBlock=163]="SimpleBlock",e[e.BlockGroup=160]="BlockGroup",e[e.Block=161]="Block",e[e.BlockAdditions=30113]="BlockAdditions",e[e.BlockMore=166]="BlockMore",e[e.BlockAdditional=165]="BlockAdditional",e[e.BlockAddID=238]="BlockAddID",e[e.BlockDuration=155]="BlockDuration",e[e.ReferenceBlock=251]="ReferenceBlock",e[e.Cluster=524531317]="Cluster",e[e.Timestamp=231]="Timestamp",e[e.Cues=475249515]="Cues",e[e.CuePoint=187]="CuePoint",e[e.CueTime=179]="CueTime",e[e.CueTrackPositions=183]="CueTrackPositions",e[e.CueTrack=247]="CueTrack",e[e.CueClusterPosition=241]="CueClusterPosition",e[e.Colour=21936]="Colour",e[e.MatrixCoefficients=21937]="MatrixCoefficients",e[e.TransferCharacteristics=21946]="TransferCharacteristics",e[e.Primaries=21947]="Primaries",e[e.Range=21945]="Range",e[e.Projection=30320]="Projection",e[e.ProjectionType=30321]="ProjectionType",e[e.ProjectionPoseRoll=30325]="ProjectionPoseRoll",e[e.Attachments=423732329]="Attachments",e[e.AttachedFile=24999]="AttachedFile",e[e.FileDescription=18046]="FileDescription",e[e.FileName=18030]="FileName",e[e.FileMediaType=18016]="FileMediaType",e[e.FileData=18012]="FileData",e[e.FileUID=18094]="FileUID",e[e.Chapters=272869232]="Chapters",e[e.Tags=307544935]="Tags",e[e.Tag=29555]="Tag",e[e.Targets=25536]="Targets",e[e.TargetTypeValue=26826]="TargetTypeValue",e[e.TargetType=25546]="TargetType",e[e.TagTrackUID=25541]="TagTrackUID",e[e.TagEditionUID=25545]="TagEditionUID",e[e.TagChapterUID=25540]="TagChapterUID",e[e.TagAttachmentUID=25542]="TagAttachmentUID",e[e.SimpleTag=26568]="SimpleTag",e[e.TagName=17827]="TagName",e[e.TagLanguage=17530]="TagLanguage",e[e.TagString=17543]="TagString",e[e.TagBinary=17541]="TagBinary",e[e.ContentEncodings=28032]="ContentEncodings",e[e.ContentEncoding=25152]="ContentEncoding",e[e.ContentEncodingOrder=20529]="ContentEncodingOrder",e[e.ContentEncodingScope=20530]="ContentEncodingScope",e[e.ContentCompression=20532]="ContentCompression",e[e.ContentCompAlgo=16980]="ContentCompAlgo",e[e.ContentCompSettings=16981]="ContentCompSettings",e[e.ContentEncryption=20533]="ContentEncryption"}($n||($n={}));const Qn=[$n.EBML,$n.Segment],Zn=[$n.SeekHead,$n.Info,$n.Cluster,$n.Tracks,$n.Cues,$n.Attachments,$n.Chapters,$n.Tags],Jn=[...Qn,...Zn],es=e=>e<256?1:e<65536?2:e<1<<24?3:e<2**32?4:e<2**40?5:6,ts=e=>e<256n?1:e<65536n?2:e<1n<<24n?3:e<1n<<32n?4:e<1n<<40n?5:e<1n<<48n?6:e<1n<<56n?7:8,rs=e=>e>=-64&&e<64?1:e>=-8192&&e<8192?2:e>=-1048576&&e<1<<20?3:e>=-134217728&&e<1<<27?4:e>=-17179869184&&e<2**34?5:6;class is{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=es(e)){let r=0;switch(t){case 6:this.helperView.setUint8(r++,e/2**40|0);case 5:this.helperView.setUint8(r++,e/2**32|0);case 4:this.helperView.setUint8(r++,e>>24);case 3:this.helperView.setUint8(r++,e>>16);case 2:this.helperView.setUint8(r++,e>>8);case 1:this.helperView.setUint8(r++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,r))}writeUnsignedBigInt(e,t=ts(e)){let r=0;for(let i=t-1;i>=0;i--)this.helperView.setUint8(r++,Number(e>>BigInt(8*i)&0xffn));this.writer.write(this.helper.subarray(0,r))}writeSignedInt(e,t=rs(e)){e<0&&(e+=2**(8*t)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=(e=>{if(e<127)return 1;if(e<16383)return 2;if(e<2097151)return 3;if(e<268435455)return 4;if(e<2**35-1)return 5;if(e<2**42-1)return 6;throw new Error("EBML varint size not supported "+e)})(e)){let r=0;switch(t){case 1:this.helperView.setUint8(r++,128|e);break;case 2:this.helperView.setUint8(r++,64|e>>8),this.helperView.setUint8(r++,e);break;case 3:this.helperView.setUint8(r++,32|e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 4:this.helperView.setUint8(r++,16|e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 5:this.helperView.setUint8(r++,8|e/2**32&7),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 6:this.helperView.setUint8(r++,4|e/2**40&3),this.helperView.setUint8(r++,e/2**32|0),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,r))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(e=>e.charCodeAt(0))))}writeEBML(e){if(null!==e)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(const t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){const t=this.writer.getPos(),r=-1===e.size?1:e.size??4;-1===e.size?this.writeByte(255):this.writer.seek(this.writer.getPos()+r);const i=this.writer.getPos();if(this.dataOffsets.set(e,i),this.writeEBML(e.data),-1!==e.size){const e=this.writer.getPos()-i,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(e,r),this.writer.seek(a)}}else if("number"==typeof e.data){const t=e.size??es(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if("bigint"==typeof e.data){const t=e.size??ts(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if("string"==typeof e.data)this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof qn)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof Gn)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof Kn){const t=e.size??rs(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof Yn){const t=ei.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else bi(e.data)}}const as=16,ns=e=>{const t=Xo(e);if(e.skip(-1),0===t)return null;let r=1,i=128;for(;0===(t&i);)r++,i>>=1;return r},ss=e=>{const t=Xo(e);if(0===t)return null;let r=1,i=128;for(;0===(t&i);)r++,i>>=1;let a=t&i-1;for(let t=1;t<r;t++)a*=256,a+=Xo(e);return a},os=(e,t)=>{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let r=0;for(let i=0;i<t;i++)r*=256,r+=Xo(e);return r},cs=e=>{const t=ns(e);if(null===t)return null;return os(e,t)},ls=e=>{let t=Xo(e);return 255===t?t=null:(e.skip(-1),t=ss(e),72057594037927940===t&&(t=null)),t},us=e=>{const t=cs(e);if(null===t)return null;return{id:t,size:ls(e)}},hs=(e,t)=>{const r=jo(e,t);let i=0;for(;i<t&&0!==r[i];)i+=1;return String.fromCharCode(...r.subarray(0,i))},ds=(e,t)=>{const r=jo(e,t);let i=0;for(;i<t&&0!==r[i];)i+=1;return Jr.decode(r.subarray(0,i))},fs=(e,t)=>{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?ac(e):nc(e)},ms=async(e,t,r,i)=>{const a=new Set(r);let n=t;for(;null===i||n<i;){let t=e.requestSliceRange(n,2,as);if(t instanceof Promise&&(t=await t),!t)break;const r=us(t);if(!r)break;if(a.has(r.id))return{pos:n,found:!0};vs(r.size),n=t.filePos+r.size}return{pos:null!==i&&i>n?i:n,found:!1}},ps=async(e,t,r,i)=>{const a=new Set(r);let n=t;for(;n<i;){let t=e.requestSliceRange(n,0,Math.min(65536,i-n));if(t instanceof Promise&&(t=await t),!t)break;if(t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=n;const e=cs(t);if(null!==e&&a.has(e))return n;n++}}return null},gs={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function vs(e){if(null===e)throw new Error("Undefined element size is used in a place where it is not supported.")}
98
+ class lc{constructor(e){this.value=e}}class hc{constructor(e){this.value=e}}class dc{constructor(e){this.value=e}}class fc{constructor(e){this.value=e}}var mc;!function(e){e[e.EBML=440786851]="EBML",e[e.EBMLVersion=17030]="EBMLVersion",e[e.EBMLReadVersion=17143]="EBMLReadVersion",e[e.EBMLMaxIDLength=17138]="EBMLMaxIDLength",e[e.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",e[e.DocType=17026]="DocType",e[e.DocTypeVersion=17031]="DocTypeVersion",e[e.DocTypeReadVersion=17029]="DocTypeReadVersion",e[e.Void=236]="Void",e[e.Segment=408125543]="Segment",e[e.SeekHead=290298740]="SeekHead",e[e.Seek=19899]="Seek",e[e.SeekID=21419]="SeekID",e[e.SeekPosition=21420]="SeekPosition",e[e.Duration=17545]="Duration",e[e.Info=357149030]="Info",e[e.TimestampScale=2807729]="TimestampScale",e[e.MuxingApp=19840]="MuxingApp",e[e.WritingApp=22337]="WritingApp",e[e.Tracks=374648427]="Tracks",e[e.TrackEntry=174]="TrackEntry",e[e.TrackNumber=215]="TrackNumber",e[e.TrackUID=29637]="TrackUID",e[e.TrackType=131]="TrackType",e[e.FlagEnabled=185]="FlagEnabled",e[e.FlagDefault=136]="FlagDefault",e[e.FlagForced=21930]="FlagForced",e[e.FlagOriginal=21934]="FlagOriginal",e[e.FlagHearingImpaired=21931]="FlagHearingImpaired",e[e.FlagVisualImpaired=21932]="FlagVisualImpaired",e[e.FlagCommentary=21935]="FlagCommentary",e[e.FlagLacing=156]="FlagLacing",e[e.Name=21358]="Name",e[e.Language=2274716]="Language",e[e.LanguageBCP47=2274717]="LanguageBCP47",e[e.CodecID=134]="CodecID",e[e.CodecPrivate=25506]="CodecPrivate",e[e.CodecDelay=22186]="CodecDelay",e[e.SeekPreRoll=22203]="SeekPreRoll",e[e.DefaultDuration=2352003]="DefaultDuration",e[e.Video=224]="Video",e[e.PixelWidth=176]="PixelWidth",e[e.PixelHeight=186]="PixelHeight",e[e.AlphaMode=21440]="AlphaMode",e[e.Audio=225]="Audio",e[e.SamplingFrequency=181]="SamplingFrequency",e[e.Channels=159]="Channels",e[e.BitDepth=25188]="BitDepth",e[e.SimpleBlock=163]="SimpleBlock",e[e.BlockGroup=160]="BlockGroup",e[e.Block=161]="Block",e[e.BlockAdditions=30113]="BlockAdditions",e[e.BlockMore=166]="BlockMore",e[e.BlockAdditional=165]="BlockAdditional",e[e.BlockAddID=238]="BlockAddID",e[e.BlockDuration=155]="BlockDuration",e[e.ReferenceBlock=251]="ReferenceBlock",e[e.Cluster=524531317]="Cluster",e[e.Timestamp=231]="Timestamp",e[e.Cues=475249515]="Cues",e[e.CuePoint=187]="CuePoint",e[e.CueTime=179]="CueTime",e[e.CueTrackPositions=183]="CueTrackPositions",e[e.CueTrack=247]="CueTrack",e[e.CueClusterPosition=241]="CueClusterPosition",e[e.Colour=21936]="Colour",e[e.MatrixCoefficients=21937]="MatrixCoefficients",e[e.TransferCharacteristics=21946]="TransferCharacteristics",e[e.Primaries=21947]="Primaries",e[e.Range=21945]="Range",e[e.Projection=30320]="Projection",e[e.ProjectionType=30321]="ProjectionType",e[e.ProjectionPoseRoll=30325]="ProjectionPoseRoll",e[e.Attachments=423732329]="Attachments",e[e.AttachedFile=24999]="AttachedFile",e[e.FileDescription=18046]="FileDescription",e[e.FileName=18030]="FileName",e[e.FileMediaType=18016]="FileMediaType",e[e.FileData=18012]="FileData",e[e.FileUID=18094]="FileUID",e[e.Chapters=272869232]="Chapters",e[e.Tags=307544935]="Tags",e[e.Tag=29555]="Tag",e[e.Targets=25536]="Targets",e[e.TargetTypeValue=26826]="TargetTypeValue",e[e.TargetType=25546]="TargetType",e[e.TagTrackUID=25541]="TagTrackUID",e[e.TagEditionUID=25545]="TagEditionUID",e[e.TagChapterUID=25540]="TagChapterUID",e[e.TagAttachmentUID=25542]="TagAttachmentUID",e[e.SimpleTag=26568]="SimpleTag",e[e.TagName=17827]="TagName",e[e.TagLanguage=17530]="TagLanguage",e[e.TagString=17543]="TagString",e[e.TagBinary=17541]="TagBinary",e[e.ContentEncodings=28032]="ContentEncodings",e[e.ContentEncoding=25152]="ContentEncoding",e[e.ContentEncodingOrder=20529]="ContentEncodingOrder",e[e.ContentEncodingScope=20530]="ContentEncodingScope",e[e.ContentCompression=20532]="ContentCompression",e[e.ContentCompAlgo=16980]="ContentCompAlgo",e[e.ContentCompSettings=16981]="ContentCompSettings",e[e.ContentEncryption=20533]="ContentEncryption"}(mc||(mc={}));const pc=[mc.EBML,mc.Segment],gc=[mc.SeekHead,mc.Info,mc.Cluster,mc.Tracks,mc.Cues,mc.Attachments,mc.Chapters,mc.Tags],vc=[...pc,...gc],yc=e=>e<256?1:e<65536?2:e<1<<24?3:e<2**32?4:e<2**40?5:6,bc=e=>e<256n?1:e<65536n?2:e<1n<<24n?3:e<1n<<32n?4:e<1n<<40n?5:e<1n<<48n?6:e<1n<<56n?7:8,xc=e=>e>=-64&&e<64?1:e>=-8192&&e<8192?2:e>=-1048576&&e<1<<20?3:e>=-134217728&&e<1<<27?4:e>=-17179869184&&e<2**34?5:6;class Tc{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=yc(e)){let r=0;switch(t){case 6:this.helperView.setUint8(r++,e/2**40|0);case 5:this.helperView.setUint8(r++,e/2**32|0);case 4:this.helperView.setUint8(r++,e>>24);case 3:this.helperView.setUint8(r++,e>>16);case 2:this.helperView.setUint8(r++,e>>8);case 1:this.helperView.setUint8(r++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,r))}writeUnsignedBigInt(e,t=bc(e)){let r=0;for(let i=t-1;i>=0;i--)this.helperView.setUint8(r++,Number(e>>BigInt(8*i)&0xffn));this.writer.write(this.helper.subarray(0,r))}writeSignedInt(e,t=xc(e)){e<0&&(e+=2**(8*t)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=(e=>{if(e<127)return 1;if(e<16383)return 2;if(e<2097151)return 3;if(e<268435455)return 4;if(e<2**35-1)return 5;if(e<2**42-1)return 6;throw new Error("EBML varint size not supported "+e)})(e)){let r=0;switch(t){case 1:this.helperView.setUint8(r++,128|e);break;case 2:this.helperView.setUint8(r++,64|e>>8),this.helperView.setUint8(r++,e);break;case 3:this.helperView.setUint8(r++,32|e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 4:this.helperView.setUint8(r++,16|e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 5:this.helperView.setUint8(r++,8|e/2**32&7),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 6:this.helperView.setUint8(r++,4|e/2**40&3),this.helperView.setUint8(r++,e/2**32|0),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,r))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(e=>e.charCodeAt(0))))}writeEBML(e){if(null!==e)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(const t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){const t=this.writer.getPos(),r=-1===e.size?1:e.size??4;-1===e.size?this.writeByte(255):this.writer.seek(this.writer.getPos()+r);const i=this.writer.getPos();if(this.dataOffsets.set(e,i),this.writeEBML(e.data),-1!==e.size){const e=this.writer.getPos()-i,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(e,r),this.writer.seek(a)}}else if("number"==typeof e.data){const t=e.size??yc(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if("bigint"==typeof e.data){const t=e.size??bc(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if("string"==typeof e.data)this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof lc)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof hc)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof dc){const t=e.size??xc(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof fc){const t=en.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else xn(e.data)}}const wc=16,kc=e=>{const t=cl(e);if(e.skip(-1),0===t)return null;let r=1,i=128;for(;0===(t&i);)r++,i>>=1;return r},Sc=e=>{const t=cl(e);if(0===t)return null;let r=1,i=128;for(;0===(t&i);)r++,i>>=1;let a=t&i-1;for(let t=1;t<r;t++)a*=256,a+=cl(e);return a},Ec=(e,t)=>{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let r=0;for(let i=0;i<t;i++)r*=256,r+=cl(e);return r},Cc=e=>{const t=kc(e);if(null===t)return null;return Ec(e,t)},Ac=e=>{let t=cl(e);return 255===t?t=null:(e.skip(-1),t=Sc(e),72057594037927940===t&&(t=null)),t},_c=e=>{const t=Cc(e);if(null===t)return null;return{id:t,size:Ac(e)}},Mc=(e,t)=>{const r=sl(e,t);let i=0;for(;i<t&&0!==r[i];)i+=1;return String.fromCharCode(...r.subarray(0,i))},Ic=(e,t)=>{const r=sl(e,t);let i=0;for(;i<t&&0!==r[i];)i+=1;return Ja.decode(r.subarray(0,i))},Rc=(e,t)=>{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?Tl(e):wl(e)},Pc=async(e,t,r,i)=>{const a=new Set(r);let n=t;for(;null===i||n<i;){let t=e.requestSliceRange(n,2,wc);if(t instanceof Promise&&(t=await t),!t)break;const r=_c(t);if(!r)break;if(a.has(r.id))return{pos:n,found:!0};Bc(r.size),n=t.filePos+r.size}return{pos:null!==i&&i>n?i:n,found:!1}},Oc=async(e,t,r,i)=>{const a=new Set(r);let n=t;for(;n<i;){let t=e.requestSliceRange(n,0,Math.min(65536,i-n));if(t instanceof Promise&&(t=await t),!t)break;if(t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=n;const e=Cc(t);if(null!==e&&a.has(e))return n;n++}}return null},Dc={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function Bc(e){if(null===e)throw new Error("Undefined element size is used in a place where it is not supported.")}
99
99
  /*!
100
100
  * Copyright (c) 2025-present, Vanilagy and contributors
101
101
  *
102
102
  * This Source Code Form is subject to the terms of the Mozilla Public
103
103
  * License, v. 2.0. If a copy of the MPL was not distributed with this
104
104
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
105
- */const ys=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");if(e.codecStrings.length>0){t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`}return t};
105
+ */const Fc=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");if(e.codecStrings.length>0){t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`}return t};
106
106
  /*!
107
107
  * Copyright (c) 2025-present, Vanilagy and contributors
108
108
  *
109
109
  * This Source Code Form is subject to the terms of the Mozilla Public
110
110
  * License, v. 2.0. If a copy of the MPL was not distributed with this
111
111
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
112
- */var bs,ks,Ts;!function(e){e[e.None=0]="None",e[e.Xiph=1]="Xiph",e[e.FixedSize=2]="FixedSize",e[e.Ebml=3]="Ebml"}(bs||(bs={})),function(e){e[e.Block=1]="Block",e[e.Private=2]="Private",e[e.Next=4]="Next"}(ks||(ks={})),function(e){e[e.Zlib=0]="Zlib",e[e.Bzlib=1]="Bzlib",e[e.lzo1x=2]="lzo1x",e[e.HeaderStripping=3]="HeaderStripping"}(Ts||(Ts={}));const ws=[{id:$n.SeekHead,flag:"seekHeadSeen"},{id:$n.Info,flag:"infoSeen"},{id:$n.Tracks,flag:"tracksSeen"},{id:$n.Cues,flag:"cuesSeen"}],Ss=10485760;class xs extends Ka{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.inputTrack))}async getMimeType(){await this.readMetadata();const e=await this.getTracks(),t=await Promise.all(e.map(e=>e.getCodecParameterString()));return ys({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>"video"===e.info?.type)),hasAudio:this.segments.some(e=>e.tracks.some(e=>"audio"===e.info?.type)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const e of this.segments)e.metadataTagsCollected||(null!==this.reader.fileSize&&await this.loadSegmentMetadata(e),e.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,as);if(t instanceof Promise&&(t=await t),!t)break;const r=us(t);if(!r)break;const i=r.id;let a=r.size;const n=t.filePos;if(i===$n.EBML){vs(a);let e=this.reader.requestSlice(n,a);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(i===$n.Segment){if(await this.readSegment(n,a),null===a)break;if(null===this.reader.fileSize)break}else if(i===$n.Cluster){if(null===this.reader.fileSize)break;if(null===a){a=(await ms(this.reader,n,Jn,this.reader.fileSize)).pos-n}const e=qr(this.segments);e&&(e.elementEndPos=n+a)}vs(a),e=n+a}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:null===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;null===this.currentSegment.elementEndPos||r<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(r,2,as);if(e instanceof Promise&&(e=await e),!e)break;const t=r,i=us(e);if(!i||!Zn.includes(i.id)&&i.id!==$n.Void){const e=await ps(this.reader,t,Zn,Math.min(this.currentSegment.elementEndPos??1/0,t+Ss));if(e){r=e;continue}break}const{id:a,size:n}=i,s=e.filePos,o=ws.findIndex(e=>e.id===a);if(-1!==o){const e=ws[o].flag;this.currentSegment[e]=!0,vs(n);let t=this.reader.requestSlice(s,n);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(a===$n.Tags||a===$n.Attachments){a===$n.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,vs(n);let e=this.reader.requestSlice(s,n);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(a===$n.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(null===n)break;r=s+n}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const t of this.currentSegment.seekEntries){const r=ws.find(e=>e.id===t.id);if(!r)continue;if(this.currentSegment[r.flag])continue;let i=this.reader.requestSliceRange(e+t.segmentPosition,2,as);if(i instanceof Promise&&(i=await i),!i)continue;const a=us(i);if(!a)continue;const{id:n,size:s}=a;if(n!==r.id)continue;vs(s),this.currentSegment[r.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);o instanceof Promise&&(o=await o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3),this.currentSegment.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));const i=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const e of this.currentSegment.cuePoints){const t=i.get(e.trackId);t&&t.cuePoints.push(e)}for(const e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;t<e.cuePoints.length-1;t++){const r=e.cuePoints[t],i=e.cuePoints[t+1];r.time===i.time&&(e.cuePoints.splice(t+1,1),t--)}}let a=null,n=-1/0;for(const e of this.currentSegment.tracks)e.cuePoints.length>n&&(n=e.cuePoints.length,a=e);for(const e of this.currentSegment.tracks)0===e.cuePoints.length&&(e.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,as);r instanceof Promise&&(r=await r),jr(r);const i=e,a=us(r);jr(a);jr(a.id===$n.Cluster);let n=a.size;const s=r.filePos;if(null===n){n=(await ms(this.reader,s,Jn,t.elementEndPos)).pos-s}let o=this.reader.requestSlice(s,n);o instanceof Promise&&(o=await o);const c={segment:t,elementStartPos:i,elementEndPos:s+n,dataStartPos:s,timestamp:-1,trackData:new Map};if(this.currentCluster=c,o){const e=this.readContiguousElements(o,Jn);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;jr(e.blocks.length>0);let r=!1;for(let t=0;t<e.blocks.length;t++){const i=e.blocks[t];i.timestamp+=c.timestamp,r||=i.lacing!==bs.None}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let r=0;r<e.presentationTimestamps.length;r++){const i=e.presentationTimestamps[r],a=e.blocks[i.blockIndex];if(null===e.firstKeyFrameTimestamp&&a.isKeyFrame&&(e.firstKeyFrameTimestamp=a.timestamp),r<e.presentationTimestamps.length-1){const t=e.presentationTimestamps[r+1];a.duration=t.timestamp-a.timestamp}else 0===a.duration&&null!=t.defaultDuration&&a.lacing===bs.None&&(a.duration=t.defaultDuration)}r&&(this.expandLacedBlocks(e.blocks,t),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const a=e.blocks[e.presentationTimestamps[0].blockIndex],n=e.blocks[qr(e.presentationTimestamps).blockIndex];e.startTimestamp=a.timestamp,e.endTimestamp=n.timestamp+n.duration;const s=mi(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);-1!==s&&t.clusterPositionCache[s].elementStartPos===i||t.clusterPositionCache.splice(s+1,0,{elementStartPos:c.elementStartPos,startTimestamp:e.startTimestamp})}return t.lastReadCluster=c,c}getTrackDataInCluster(e,t){let r=e.trackData.get(t);if(!r){const i=e.segment.tracks.find(e=>e.id===t);if(!i)return null;r={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,r)}return r}expandLacedBlocks(e,t){for(let r=0;r<e.length;r++){const i=e[r];if(i.lacing===bs.None)continue;i.decoded||(i.data=this.decodeBlockData(t,i.data),i.decoded=!0);const a=Vo.tempFromBytes(i.data),n=[],s=Xo(a)+1;switch(i.lacing){case bs.Xiph:{let e=0;for(let t=0;t<s-1;t++){let t=0;for(;a.bufferPos<a.length;){const r=Xo(a);if(t+=r,r<255){n.push(t),e+=t;break}}}n.push(a.length-(a.bufferPos+e))}break;case bs.FixedSize:{const e=a.length-1,t=Math.floor(e/s);for(let e=0;e<s;e++)n.push(t)}break;case bs.Ebml:{const e=ss(a);jr(null!==e);let t=e;n.push(t);let r=t;for(let e=1;e<s-1;e++){const e=a.bufferPos,i=ss(a);jr(null!==i);t+=i-((1<<7*(a.bufferPos-e)-1)-1),n.push(t),r+=t}n.push(a.length-(a.bufferPos+r))}break;default:jr(!1)}jr(n.length===s),e.splice(r,1);const o=i.duration||s*(t.defaultDuration??0);for(let t=0;t<s;t++){const c=n[t],l=jo(a,c),u=i.timestamp+o*t/s,h=o/s;e.splice(r+t,0,{timestamp:u,duration:h,isKeyFrame:i.isKeyFrame,data:l,lacing:bs.None,decoded:!0,mainAdditional:i.mainAdditional})}r+=s,r--}}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(t.id!==$n.Tags||e.tagsSeen){if(t.id!==$n.Attachments||e.attachmentsSeen)continue}else;let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,as);if(r instanceof Promise&&(r=await r),!r)continue;const i=us(r);if(!i||i.id!==t.id)continue;const{size:a}=i;vs(a),jr(!this.currentSegment),this.currentSegment=e;let n=this.reader.requestSlice(r.filePos,a);n instanceof Promise&&(n=await n),n&&this.readContiguousElements(n),this.currentSegment=null,t.id===$n.Tags?e.tagsSeen=!0:t.id===$n.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){const r=e.filePos;for(;e.filePos-r<=e.length-2;){const r=e.filePos;if(!this.traverseElement(e,t))return r}return e.filePos}traverseElement(e,t){const r=us(e);if(!r)return!1;if(t&&t.includes(r.id))return!1;const{id:i,size:a}=r,n=e.filePos;switch(vs(a),i){case $n.DocType:this.isWebM="webm"===hs(e,a);break;case $n.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(n,a)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case $n.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=os(e,a)}break;case $n.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=os(e,a)}break;case $n.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=os(e,a),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case $n.Duration:if(!this.currentSegment)break;this.currentSegment.duration=fs(e,a);break;case $n.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...qi},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:wi,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(n,a)),this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==ks.Block||e.data.algorithm!==Ts.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){this.currentTrack.codecId===gs.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===gs.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===gs.vp8?this.currentTrack.info.codec="vp8":t===gs.vp9?this.currentTrack.info.codec="vp9":t===gs.av1&&(this.currentTrack.info.codec="av1");const e=this.currentTrack,r=new Cn(this.input,new Es(e));this.currentTrack.inputTrack=r,this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type&&-1!==this.currentTrack.info.numberOfChannels&&-1!==this.currentTrack.info.sampleRate){t===gs.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===gs.mp3?this.currentTrack.info.codec="mp3":t===gs.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=ca):t===gs.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===gs.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack,r=new En(this.input,new As(e));this.currentTrack.inputTrack=r,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case $n.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=os(e,a);break;case $n.TrackType:{if(!this.currentTrack)break;const t=os(e,a);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case $n.FlagEnabled:if(!this.currentTrack)break;os(e,a)||(this.currentSegment.tracks.pop(),this.currentTrack=null);break;case $n.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!os(e,a);break;case $n.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!os(e,a);break;case $n.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!os(e,a);break;case $n.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!os(e,a);break;case $n.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!os(e,a);break;case $n.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!os(e,a);break;case $n.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=hs(e,a);break;case $n.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=jo(e,a);break;case $n.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*os(e,a)/1e9;break;case $n.Name:if(!this.currentTrack)break;this.currentTrack.name=ds(e,a);break;case $n.Language:if(!this.currentTrack)break;if(this.currentTrack.languageCode!==wi)break;this.currentTrack.languageCode=hs(e,a),Ei(this.currentTrack.languageCode)||(this.currentTrack.languageCode=wi);break;case $n.LanguageBCP47:{if(!this.currentTrack)break;const t=hs(e,a).split("-")[0];this.currentTrack.languageCode=t||wi}break;case $n.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(n,a));break;case $n.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=os(e,a);break;case $n.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=os(e,a);break;case $n.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===os(e,a);break;case $n.Colour:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(n,a));break;case $n.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=os(e,a),r=oi[t]??null;this.currentTrack.info.colorSpace.matrix=r}break;case $n.Range:if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===os(e,a);break;case $n.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=os(e,a),r=ni[t]??null;this.currentTrack.info.colorSpace.transfer=r}break;case $n.Primaries:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=os(e,a),r=ii[t]??null;this.currentTrack.info.colorSpace.primaries=r}break;case $n.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(n,a));break;case $n.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-fs(e,a);try{this.currentTrack.info.rotation=Xr(t)}catch{}}break;case $n.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(n,a));break;case $n.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=fs(e,a);break;case $n.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=os(e,a);break;case $n.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=os(e,a);break;case $n.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(n,a)),this.currentCueTime=null;break;case $n.CueTime:this.currentCueTime=os(e,a);break;case $n.CueTrackPositions:{if(null===this.currentCueTime)break;jr(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(n,a)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case $n.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=os(e,a)}break;case $n.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;jr(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+os(e,a)}break;case $n.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=os(e,a);break;case $n.SimpleBlock:{if(!this.currentCluster)break;const t=ss(e);if(null===t)break;const r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;const i=Yo(e),s=Xo(e),o=s>>1&3;let c=!!(128&s);"audio"===r.track.info?.type&&r.track.info.codec&&(c=!0);const l=jo(e,a-(e.filePos-n)),u=r.track.decodingInstructions.length>0;r.blocks.push({timestamp:i,duration:0,isKeyFrame:c,data:l,lacing:o,decoded:!u,mainAdditional:null})}break;case $n.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(n,a)),this.currentBlock=null;break;case $n.Block:{if(!this.currentCluster)break;const t=ss(e);if(null===t)break;const r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;const i=Yo(e),s=Xo(e)>>1&3,o=jo(e,a-(e.filePos-n)),c=r.track.decodingInstructions.length>0;this.currentBlock={timestamp:i,duration:0,isKeyFrame:!0,data:o,lacing:s,decoded:!c,mainAdditional:null},r.blocks.push(this.currentBlock)}break;case $n.BlockAdditions:this.readContiguousElements(e.slice(n,a));break;case $n.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(n,a)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case $n.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=jo(e,a);break;case $n.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=os(e,a);break;case $n.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=os(e,a);break;case $n.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case $n.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(n,a));break;case $n.Targets:this.readContiguousElements(e.slice(n,a));break;case $n.TargetTypeValue:50!==os(e,a)&&(this.currentTagTargetIsMovie=!1);break;case $n.TagTrackUID:case $n.TagEditionUID:case $n.TagChapterUID:case $n.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case $n.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(n,a));break;case $n.TagName:this.currentSimpleTagName=ds(e,a);break;case $n.TagString:{if(!this.currentSimpleTagName)break;const t=ds(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case $n.TagBinary:{if(!this.currentSimpleTagName)break;const t=jo(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case $n.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(n,a));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new Xi(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const e=this.currentAttachedFile.fileName;let r="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?r="coverFront":t.startsWith("back.")&&(r="coverBack")}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:r,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case $n.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let r=0n;for(let i=0;i<t;i++)r<<=8n,r+=BigInt(Xo(e));return r})(e,a);break;case $n.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=ds(e,a);break;case $n.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=hs(e,a);break;case $n.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=jo(e,a);break;case $n.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=ds(e,a);break;case $n.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(n,a)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case $n.ContentEncoding:this.currentDecodingInstruction={order:0,scope:ks.Block,data:null},this.readContiguousElements(e.slice(n,a)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case $n.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=os(e,a);break;case $n.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=os(e,a);break;case $n.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Ts.Zlib,settings:null},this.readContiguousElements(e.slice(n,a));break;case $n.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=os(e,a);break;case $n.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=jo(e,a);break;case $n.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=n+a,!0}decodeBlockData(e,t){jr(e.decodingInstructions.length>0);let r=t;for(const t of e.decodingInstructions)if(jr(t.data),"decompress"===t.data.type)if(t.data.algorithm===Ts.HeaderStripping)if(t.data.settings&&t.data.settings.length>0){const e=t.data.settings,i=new Uint8Array(e.length+r.length);i.set(e,0),i.set(r,e.length),r=i}return r}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;const r=this.currentSegment.metadataTags;if(r.raw??={},r.raw[e]??=t,"string"==typeof t)switch(e.toLowerCase()){case"title":r.title??=t;break;case"description":r.description??=t;break;case"artist":r.artist??=t;break;case"album":r.album??=t;break;case"album_artist":r.albumArtist??=t;break;case"genre":r.genre??=t;break;case"comment":r.comment??=t;break;case"lyrics":r.lyrics??=t;break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||(r.date??=e)}break;case"track_number":case"part_number":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.trackNumber??=i),a&&Number.isInteger(a)&&a>0&&(r.tracksTotal??=a)}break;case"disc_number":case"disc":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.discNumber??=i),a&&Number.isInteger(a)&&a>0&&(r.discsTotal??=a)}}}}class Cs{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){const e=await this.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Si(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const r=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const i=mi(t.presentationTimestamps,r,e=>e.timestamp);return{blockIndex:-1!==i?t.presentationTimestamps[i].blockIndex:-1,correctBlockFound:-1!==i&&r<t.endTimestamp}},r,r,t)}async getNextPacket(e,t){const r=this.packetToClusterLocation.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,e=>{if(e===r.cluster){const t=e.trackData.get(this.internalTrack.id);if(r.blockIndex+1<t.blocks.length)return{blockIndex:r.blockIndex+1,correctBlockFound:!0}}else{if(e.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const r=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const i=yi(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=r);return{blockIndex:-1!==i?t.presentationTimestamps[i].blockIndex:-1,correctBlockFound:-1!==i&&r<t.endTimestamp}},r,r,t)}async getNextKeyPacket(e,t){const r=this.packetToClusterLocation.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,e=>{if(e===r.cluster){const t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>r.blockIndex);if(-1!==t)return{blockIndex:t,correctBlockFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.blocks.findIndex(e=>e.isKeyFrame);return jr(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(-1===t)return null;const i=e.trackData.get(this.internalTrack.id).blocks[t];jr(i),i.decoded||(i.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,i.data),i.decoded=!0);const a=r.metadataOnly?Qa:i.data,n=i.timestamp/this.internalTrack.segment.timestampFactor,s=i.duration/this.internalTrack.segment.timestampFactor,o={};i.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(o.alpha=r.metadataOnly?Qa:i.mainAdditional,o.alphaByteLength=i.mainAdditional.byteLength);const c=new Za(a,i.isKeyFrame?"key":"delta",n,s,e.dataStartPos+t,i.data.byteLength,o);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,r,i,a){const{demuxer:n,segment:s}=this.internalTrack;let o=null,c=null,l=-1;if(e){const{blockIndex:r,correctBlockFound:i}=t(e);if(i)return this.fetchPacketInCluster(e,r,a);-1!==r&&(c=e,l=r)}const u=mi(this.internalTrack.cuePoints,r,e=>e.time),h=-1!==u?this.internalTrack.cuePoints[u]:null,d=mi(this.internalTrack.clusterPositionCache,r,e=>e.startTimestamp),f=-1!==d?this.internalTrack.clusterPositionCache[d]:null,m=Math.max(h?.clusterPosition??0,f?.elementStartPos??0)||null;let p;for(e?null===m||e.elementStartPos>=m?(p=e.elementEndPos,o=e):p=m:p=m??s.clusterSeekStartPos;null===s.elementEndPos||p<=s.elementEndPos-2;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>i)break}let e=n.reader.requestSliceRange(p,2,as);if(e instanceof Promise&&(e=await e),!e)break;const r=p,u=us(e);if(!u||!Zn.includes(u.id)&&u.id!==$n.Void){const e=await ps(n.reader,r,Zn,Math.min(s.elementEndPos??1/0,r+Ss));if(e){p=e;continue}break}const h=u.id;let d=u.size;const f=e.filePos;if(h===$n.Cluster){o=await n.readCluster(r,s),d=o.elementEndPos-f;const{blockIndex:e,correctBlockFound:i}=t(o);if(i)return this.fetchPacketInCluster(o,e,a);-1!==e&&(c=o,l=e)}if(null===d){jr(h!==$n.Cluster);d=(await ms(n.reader,f,Jn,s.elementEndPos)).pos-f}const m=f+d;if(null===s.elementEndPos){let e=n.reader.requestSliceRange(m,2,as);if(e instanceof Promise&&(e=await e),!e)break;if(cs(e)===$n.Segment){s.elementEndPos=m;break}}p=m}if(h&&(!c||c.elementStartPos<h.clusterPosition)){const e=this.internalTrack.cuePoints[u-1];jr(!e||e.time<h.time);const r=e?.time??-1/0;return this.performClusterLookup(null,t,r,i,a)}return c?this.fetchPacketInCluster(c,l,a):null}}class Es extends Cs{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;return("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:ia({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&e?Aa(e.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&e?Oa(e.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&e?Ua(e.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&e?Wa(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}}class As extends Cs{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:aa({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}
112
+ */var Lc,Nc,Uc;!function(e){e[e.None=0]="None",e[e.Xiph=1]="Xiph",e[e.FixedSize=2]="FixedSize",e[e.Ebml=3]="Ebml"}(Lc||(Lc={})),function(e){e[e.Block=1]="Block",e[e.Private=2]="Private",e[e.Next=4]="Next"}(Nc||(Nc={})),function(e){e[e.Zlib=0]="Zlib",e[e.Bzlib=1]="Bzlib",e[e.lzo1x=2]="lzo1x",e[e.HeaderStripping=3]="HeaderStripping"}(Uc||(Uc={}));const zc=[{id:mc.SeekHead,flag:"seekHeadSeen"},{id:mc.Info,flag:"infoSeen"},{id:mc.Tracks,flag:"tracksSeen"},{id:mc.Cues,flag:"cuesSeen"}],Wc=10485760;class Vc extends is{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.inputTrack))}async getMimeType(){await this.readMetadata();const e=await this.getTracks(),t=await Promise.all(e.map(e=>e.getCodecParameterString()));return Fc({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>"video"===e.info?.type)),hasAudio:this.segments.some(e=>e.tracks.some(e=>"audio"===e.info?.type)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const e of this.segments)e.metadataTagsCollected||(null!==this.reader.fileSize&&await this.loadSegmentMetadata(e),e.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,wc);if(t instanceof Promise&&(t=await t),!t)break;const r=_c(t);if(!r)break;const i=r.id;let a=r.size;const n=t.filePos;if(i===mc.EBML){Bc(a);let e=this.reader.requestSlice(n,a);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(i===mc.Segment){if(await this.readSegment(n,a),null===a)break;if(null===this.reader.fileSize)break}else if(i===mc.Cluster){if(null===this.reader.fileSize)break;if(null===a){a=(await Pc(this.reader,n,vc,this.reader.fileSize)).pos-n}const e=Ga(this.segments);e&&(e.elementEndPos=n+a)}Bc(a),e=n+a}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:null===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;null===this.currentSegment.elementEndPos||r<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(r,2,wc);if(e instanceof Promise&&(e=await e),!e)break;const t=r,i=_c(e);if(!i||!gc.includes(i.id)&&i.id!==mc.Void){const e=await Oc(this.reader,t,gc,Math.min(this.currentSegment.elementEndPos??1/0,t+Wc));if(e){r=e;continue}break}const{id:a,size:n}=i,o=e.filePos,s=zc.findIndex(e=>e.id===a);if(-1!==s){const e=zc[s].flag;this.currentSegment[e]=!0,Bc(n);let t=this.reader.requestSlice(o,n);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(a===mc.Tags||a===mc.Attachments){a===mc.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Bc(n);let e=this.reader.requestSlice(o,n);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(a===mc.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(null===n)break;r=o+n}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const t of this.currentSegment.seekEntries){const r=zc.find(e=>e.id===t.id);if(!r)continue;if(this.currentSegment[r.flag])continue;let i=this.reader.requestSliceRange(e+t.segmentPosition,2,wc);if(i instanceof Promise&&(i=await i),!i)continue;const a=_c(i);if(!a)continue;const{id:n,size:o}=a;if(n!==r.id)continue;Bc(o),this.currentSegment[r.flag]=!0;let s=this.reader.requestSlice(i.filePos,o);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3),this.currentSegment.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));const i=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const e of this.currentSegment.cuePoints){const t=i.get(e.trackId);t&&t.cuePoints.push(e)}for(const e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;t<e.cuePoints.length-1;t++){const r=e.cuePoints[t],i=e.cuePoints[t+1];r.time===i.time&&(e.cuePoints.splice(t+1,1),t--)}}let a=null,n=-1/0;for(const e of this.currentSegment.tracks)e.cuePoints.length>n&&(n=e.cuePoints.length,a=e);for(const e of this.currentSegment.tracks)0===e.cuePoints.length&&(e.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,wc);r instanceof Promise&&(r=await r),Xa(r);const i=e,a=_c(r);Xa(a);Xa(a.id===mc.Cluster);let n=a.size;const o=r.filePos;if(null===n){n=(await Pc(this.reader,o,vc,t.elementEndPos)).pos-o}let s=this.reader.requestSlice(o,n);s instanceof Promise&&(s=await s);const c={segment:t,elementStartPos:i,elementEndPos:o+n,dataStartPos:o,timestamp:-1,trackData:new Map};if(this.currentCluster=c,s){const e=this.readContiguousElements(s,vc);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;Xa(e.blocks.length>0);let r=!1;for(let t=0;t<e.blocks.length;t++){const i=e.blocks[t];i.timestamp+=c.timestamp,r||=i.lacing!==Lc.None}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let r=0;r<e.presentationTimestamps.length;r++){const i=e.presentationTimestamps[r],a=e.blocks[i.blockIndex];if(null===e.firstKeyFrameTimestamp&&a.isKeyFrame&&(e.firstKeyFrameTimestamp=a.timestamp),r<e.presentationTimestamps.length-1){const t=e.presentationTimestamps[r+1];a.duration=t.timestamp-a.timestamp}else 0===a.duration&&null!=t.defaultDuration&&a.lacing===Lc.None&&(a.duration=t.defaultDuration)}r&&(this.expandLacedBlocks(e.blocks,t),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const a=e.blocks[e.presentationTimestamps[0].blockIndex],n=e.blocks[Ga(e.presentationTimestamps).blockIndex];e.startTimestamp=a.timestamp,e.endTimestamp=n.timestamp+n.duration;const o=pn(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);-1!==o&&t.clusterPositionCache[o].elementStartPos===i||t.clusterPositionCache.splice(o+1,0,{elementStartPos:c.elementStartPos,startTimestamp:e.startTimestamp})}return t.lastReadCluster=c,c}getTrackDataInCluster(e,t){let r=e.trackData.get(t);if(!r){const i=e.segment.tracks.find(e=>e.id===t);if(!i)return null;r={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,r)}return r}expandLacedBlocks(e,t){for(let r=0;r<e.length;r++){const i=e[r];if(i.lacing===Lc.None)continue;i.decoded||(i.data=this.decodeBlockData(t,i.data),i.decoded=!0);const a=nl.tempFromBytes(i.data),n=[],o=cl(a)+1;switch(i.lacing){case Lc.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;a.bufferPos<a.length;){const r=cl(a);if(t+=r,r<255){n.push(t),e+=t;break}}}n.push(a.length-(a.bufferPos+e))}break;case Lc.FixedSize:{const e=a.length-1,t=Math.floor(e/o);for(let e=0;e<o;e++)n.push(t)}break;case Lc.Ebml:{const e=Sc(a);Xa(null!==e);let t=e;n.push(t);let r=t;for(let e=1;e<o-1;e++){const e=a.bufferPos,i=Sc(a);Xa(null!==i);t+=i-((1<<7*(a.bufferPos-e)-1)-1),n.push(t),r+=t}n.push(a.length-(a.bufferPos+r))}break;default:Xa(!1)}Xa(n.length===o),e.splice(r,1);const s=i.duration||o*(t.defaultDuration??0);for(let t=0;t<o;t++){const c=n[t],u=sl(a,c),l=i.timestamp+s*t/o,h=s/o;e.splice(r+t,0,{timestamp:l,duration:h,isKeyFrame:i.isKeyFrame,data:u,lacing:Lc.None,decoded:!0,mainAdditional:i.mainAdditional})}r+=o,r--}}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(t.id!==mc.Tags||e.tagsSeen){if(t.id!==mc.Attachments||e.attachmentsSeen)continue}else;let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,wc);if(r instanceof Promise&&(r=await r),!r)continue;const i=_c(r);if(!i||i.id!==t.id)continue;const{size:a}=i;Bc(a),Xa(!this.currentSegment),this.currentSegment=e;let n=this.reader.requestSlice(r.filePos,a);n instanceof Promise&&(n=await n),n&&this.readContiguousElements(n),this.currentSegment=null,t.id===mc.Tags?e.tagsSeen=!0:t.id===mc.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){const r=e.filePos;for(;e.filePos-r<=e.length-2;){const r=e.filePos;if(!this.traverseElement(e,t))return r}return e.filePos}traverseElement(e,t){const r=_c(e);if(!r)return!1;if(t&&t.includes(r.id))return!1;const{id:i,size:a}=r,n=e.filePos;switch(Bc(a),i){case mc.DocType:this.isWebM="webm"===Mc(e,a);break;case mc.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(n,a)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case mc.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Ec(e,a)}break;case mc.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Ec(e,a)}break;case mc.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Ec(e,a),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case mc.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Rc(e,a);break;case mc.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...$n},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:Sn,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(n,a)),this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==Nc.Block||e.data.algorithm!==Uc.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){this.currentTrack.codecId===Dc.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Dc.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Dc.vp8?this.currentTrack.info.codec="vp8":t===Dc.vp9?this.currentTrack.info.codec="vp9":t===Dc.av1&&(this.currentTrack.info.codec="av1");const e=this.currentTrack,r=new Hs(this.input,new Xc(e));this.currentTrack.inputTrack=r,this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type&&-1!==this.currentTrack.info.numberOfChannels&&-1!==this.currentTrack.info.sampleRate){t===Dc.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Dc.mp3?this.currentTrack.info.codec="mp3":t===Dc.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=fo):t===Dc.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Dc.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack,r=new Xs(this.input,new jc(e));this.currentTrack.inputTrack=r,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case mc.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Ec(e,a);break;case mc.TrackType:{if(!this.currentTrack)break;const t=Ec(e,a);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case mc.FlagEnabled:if(!this.currentTrack)break;Ec(e,a)||(this.currentSegment.tracks.pop(),this.currentTrack=null);break;case mc.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Ec(e,a);break;case mc.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Ec(e,a);break;case mc.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Ec(e,a);break;case mc.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Ec(e,a);break;case mc.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Ec(e,a);break;case mc.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Ec(e,a);break;case mc.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Mc(e,a);break;case mc.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=sl(e,a);break;case mc.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*Ec(e,a)/1e9;break;case mc.Name:if(!this.currentTrack)break;this.currentTrack.name=Ic(e,a);break;case mc.Language:if(!this.currentTrack)break;if(this.currentTrack.languageCode!==Sn)break;this.currentTrack.languageCode=Mc(e,a),_n(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Sn);break;case mc.LanguageBCP47:{if(!this.currentTrack)break;const t=Mc(e,a).split("-")[0];this.currentTrack.languageCode=t||Sn}break;case mc.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(n,a));break;case mc.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=Ec(e,a);break;case mc.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=Ec(e,a);break;case mc.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===Ec(e,a);break;case mc.Colour:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(n,a));break;case mc.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=Ec(e,a),r=cn[t]??null;this.currentTrack.info.colorSpace.matrix=r}break;case mc.Range:if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===Ec(e,a);break;case mc.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=Ec(e,a),r=on[t]??null;this.currentTrack.info.colorSpace.transfer=r}break;case mc.Primaries:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=Ec(e,a),r=an[t]??null;this.currentTrack.info.colorSpace.primaries=r}break;case mc.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(n,a));break;case mc.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-Rc(e,a);try{this.currentTrack.info.rotation=ja(t)}catch{}}break;case mc.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(n,a));break;case mc.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=Rc(e,a);break;case mc.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=Ec(e,a);break;case mc.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=Ec(e,a);break;case mc.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(n,a)),this.currentCueTime=null;break;case mc.CueTime:this.currentCueTime=Ec(e,a);break;case mc.CueTrackPositions:{if(null===this.currentCueTime)break;Xa(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(n,a)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case mc.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Ec(e,a)}break;case mc.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;Xa(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Ec(e,a)}break;case mc.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Ec(e,a);break;case mc.SimpleBlock:{if(!this.currentCluster)break;const t=Sc(e);if(null===t)break;const r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;const i=dl(e),o=cl(e),s=o>>1&3;let c=!!(128&o);"audio"===r.track.info?.type&&r.track.info.codec&&(c=!0);const u=sl(e,a-(e.filePos-n)),l=r.track.decodingInstructions.length>0;r.blocks.push({timestamp:i,duration:0,isKeyFrame:c,data:u,lacing:s,decoded:!l,mainAdditional:null})}break;case mc.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(n,a)),this.currentBlock=null;break;case mc.Block:{if(!this.currentCluster)break;const t=Sc(e);if(null===t)break;const r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;const i=dl(e),o=cl(e)>>1&3,s=sl(e,a-(e.filePos-n)),c=r.track.decodingInstructions.length>0;this.currentBlock={timestamp:i,duration:0,isKeyFrame:!0,data:s,lacing:o,decoded:!c,mainAdditional:null},r.blocks.push(this.currentBlock)}break;case mc.BlockAdditions:this.readContiguousElements(e.slice(n,a));break;case mc.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(n,a)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case mc.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=sl(e,a);break;case mc.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Ec(e,a);break;case mc.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Ec(e,a);break;case mc.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case mc.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(n,a));break;case mc.Targets:this.readContiguousElements(e.slice(n,a));break;case mc.TargetTypeValue:50!==Ec(e,a)&&(this.currentTagTargetIsMovie=!1);break;case mc.TagTrackUID:case mc.TagEditionUID:case mc.TagChapterUID:case mc.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case mc.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(n,a));break;case mc.TagName:this.currentSimpleTagName=Ic(e,a);break;case mc.TagString:{if(!this.currentSimpleTagName)break;const t=Ic(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case mc.TagBinary:{if(!this.currentSimpleTagName)break;const t=sl(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case mc.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(n,a));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new Kn(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const e=this.currentAttachedFile.fileName;let r="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?r="coverFront":t.startsWith("back.")&&(r="coverBack")}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:r,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case mc.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let r=0n;for(let i=0;i<t;i++)r<<=8n,r+=BigInt(cl(e));return r})(e,a);break;case mc.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Ic(e,a);break;case mc.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Mc(e,a);break;case mc.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=sl(e,a);break;case mc.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Ic(e,a);break;case mc.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(n,a)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case mc.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Nc.Block,data:null},this.readContiguousElements(e.slice(n,a)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case mc.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Ec(e,a);break;case mc.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Ec(e,a);break;case mc.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Uc.Zlib,settings:null},this.readContiguousElements(e.slice(n,a));break;case mc.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=Ec(e,a);break;case mc.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=sl(e,a);break;case mc.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=n+a,!0}decodeBlockData(e,t){Xa(e.decodingInstructions.length>0);let r=t;for(const t of e.decodingInstructions)if(Xa(t.data),"decompress"===t.data.type)if(t.data.algorithm===Uc.HeaderStripping)if(t.data.settings&&t.data.settings.length>0){const e=t.data.settings,i=new Uint8Array(e.length+r.length);i.set(e,0),i.set(r,e.length),r=i}return r}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;const r=this.currentSegment.metadataTags;if(r.raw??={},r.raw[e]??=t,"string"==typeof t)switch(e.toLowerCase()){case"title":r.title??=t;break;case"description":r.description??=t;break;case"artist":r.artist??=t;break;case"album":r.album??=t;break;case"album_artist":r.albumArtist??=t;break;case"genre":r.genre??=t;break;case"comment":r.comment??=t;break;case"lyrics":r.lyrics??=t;break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||(r.date??=e)}break;case"track_number":case"part_number":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.trackNumber??=i),a&&Number.isInteger(a)&&a>0&&(r.tracksTotal??=a)}break;case"disc_number":case"disc":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.discNumber??=i),a&&Number.isInteger(a)&&a>0&&(r.discsTotal??=a)}}}}class Hc{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){const e=await this.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return En(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const r=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const i=pn(t.presentationTimestamps,r,e=>e.timestamp);return{blockIndex:-1!==i?t.presentationTimestamps[i].blockIndex:-1,correctBlockFound:-1!==i&&r<t.endTimestamp}},r,r,t)}async getNextPacket(e,t){const r=this.packetToClusterLocation.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,e=>{if(e===r.cluster){const t=e.trackData.get(this.internalTrack.id);if(r.blockIndex+1<t.blocks.length)return{blockIndex:r.blockIndex+1,correctBlockFound:!0}}else{if(e.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const r=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const i=bn(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=r);return{blockIndex:-1!==i?t.presentationTimestamps[i].blockIndex:-1,correctBlockFound:-1!==i&&r<t.endTimestamp}},r,r,t)}async getNextKeyPacket(e,t){const r=this.packetToClusterLocation.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,e=>{if(e===r.cluster){const t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>r.blockIndex);if(-1!==t)return{blockIndex:t,correctBlockFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.blocks.findIndex(e=>e.isKeyFrame);return Xa(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(-1===t)return null;const i=e.trackData.get(this.internalTrack.id).blocks[t];Xa(i),i.decoded||(i.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,i.data),i.decoded=!0);const a=r.metadataOnly?os:i.data,n=i.timestamp/this.internalTrack.segment.timestampFactor,o=i.duration/this.internalTrack.segment.timestampFactor,s={};i.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(s.alpha=r.metadataOnly?os:i.mainAdditional,s.alphaByteLength=i.mainAdditional.byteLength);const c=new ss(a,i.isKeyFrame?"key":"delta",n,o,e.dataStartPos+t,i.data.byteLength,s);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,r,i,a){const{demuxer:n,segment:o}=this.internalTrack;let s=null,c=null,u=-1;if(e){const{blockIndex:r,correctBlockFound:i}=t(e);if(i)return this.fetchPacketInCluster(e,r,a);-1!==r&&(c=e,u=r)}const l=pn(this.internalTrack.cuePoints,r,e=>e.time),h=-1!==l?this.internalTrack.cuePoints[l]:null,d=pn(this.internalTrack.clusterPositionCache,r,e=>e.startTimestamp),f=-1!==d?this.internalTrack.clusterPositionCache[d]:null,m=Math.max(h?.clusterPosition??0,f?.elementStartPos??0)||null;let p;for(e?null===m||e.elementStartPos>=m?(p=e.elementEndPos,s=e):p=m:p=m??o.clusterSeekStartPos;null===o.elementEndPos||p<=o.elementEndPos-2;){if(s){const e=s.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>i)break}let e=n.reader.requestSliceRange(p,2,wc);if(e instanceof Promise&&(e=await e),!e)break;const r=p,l=_c(e);if(!l||!gc.includes(l.id)&&l.id!==mc.Void){const e=await Oc(n.reader,r,gc,Math.min(o.elementEndPos??1/0,r+Wc));if(e){p=e;continue}break}const h=l.id;let d=l.size;const f=e.filePos;if(h===mc.Cluster){s=await n.readCluster(r,o),d=s.elementEndPos-f;const{blockIndex:e,correctBlockFound:i}=t(s);if(i)return this.fetchPacketInCluster(s,e,a);-1!==e&&(c=s,u=e)}if(null===d){Xa(h!==mc.Cluster);d=(await Pc(n.reader,f,vc,o.elementEndPos)).pos-f}const m=f+d;if(null===o.elementEndPos){let e=n.reader.requestSliceRange(m,2,wc);if(e instanceof Promise&&(e=await e),!e)break;if(Cc(e)===mc.Segment){o.elementEndPos=m;break}}p=m}if(h&&(!c||c.elementStartPos<h.clusterPosition)){const e=this.internalTrack.cuePoints[l-1];Xa(!e||e.time<h.time);const r=e?.time??-1/0;return this.performClusterLookup(null,t,r,i,a)}return c?this.fetchPacketInCluster(c,u,a):null}}class Xc extends Hc{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;return("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:so({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&e?Fo(e.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&e?zo(e.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&e?qo(e.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&e?$o(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}}class jc extends Hc{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:co({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}
113
113
  /*!
114
114
  * Copyright (c) 2025-present, Vanilagy and contributors
115
115
  *
116
116
  * This Source Code Form is subject to the terms of the Mozilla Public
117
117
  * License, v. 2.0. If a copy of the MPL was not distributed with this
118
118
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
119
- */const Ps=[44100,48e3,32e3],Is=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Rs=(e,t)=>{const r=e>>>24,i=e>>>16&255,a=e>>>8&255,n=255&e;if(255!==r&&255!==i&&255!==a&&255!==n)return{header:null,bytesAdvanced:4};if(255!==r)return{header:null,bytesAdvanced:1};if(224&~i)return{header:null,bytesAdvanced:1};let s=0,o=0;16&i?s=8&i?0:1:(s=1,o=1);const c=i>>3&3,l=i>>1&3,u=(a>>2&3)%3,h=n>>6&3,d=n>>4&3,f=n>>3&1,m=n>>2&1,p=3&n,g=Is[16*s*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const v=1e3*g,y=Ps[u]>>s+o,b=((e,t,r,i,a)=>0===t?0:1===t?Math.floor(144*r/(i<<e))+a:2===t?Math.floor(144*r/i)+a:4*(Math.floor(12*r/i)+a))(s,l,v,y,a>>1&1);if(null!==t&&t<b)return{header:null,bytesAdvanced:1};let k;return k=3===c?3===l?384:1152:3===l?384:2===l?1152:576,{header:{totalSize:b,mpegVersionId:c,layer:l,bitrate:v,frequencyIndex:u,sampleRate:y,channel:h,modeExtension:d,copyright:f,original:m,emphasis:p,audioSamplesInFrame:k},bytesAdvanced:1}},Os=e=>{let t=2130706432,r=0;for(;0!==t;)r>>=1,r|=e&t,t>>=8;return r};
119
+ */const Gc=[44100,48e3,32e3],Yc=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],qc=(e,t)=>{const r=e>>>24,i=e>>>16&255,a=e>>>8&255,n=255&e;if(255!==r&&255!==i&&255!==a&&255!==n)return{header:null,bytesAdvanced:4};if(255!==r)return{header:null,bytesAdvanced:1};if(224&~i)return{header:null,bytesAdvanced:1};let o=0,s=0;16&i?o=8&i?0:1:(o=1,s=1);const c=i>>3&3,u=i>>1&3,l=(a>>2&3)%3,h=n>>6&3,d=n>>4&3,f=n>>3&1,m=n>>2&1,p=3&n,g=Yc[16*o*4+16*u+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const v=1e3*g,y=Gc[l]>>o+s,b=((e,t,r,i,a)=>0===t?0:1===t?Math.floor(144*r/(i<<e))+a:2===t?Math.floor(144*r/i)+a:4*(Math.floor(12*r/i)+a))(o,u,v,y,a>>1&1);if(null!==t&&t<b)return{header:null,bytesAdvanced:1};let x;return x=3===c?3===u?384:1152:3===u?384:2===u?1152:576,{header:{totalSize:b,mpegVersionId:c,layer:u,bitrate:v,frequencyIndex:l,sampleRate:y,channel:h,modeExtension:d,copyright:f,original:m,emphasis:p,audioSamplesInFrame:x},bytesAdvanced:1}},Kc=e=>{let t=2130706432,r=0;for(;0!==t;)r>>=1,r|=e&t,t>>=8;return r};
120
120
  /*!
121
121
  * Copyright (c) 2025-present, Vanilagy and contributors
122
122
  *
@@ -124,28 +124,28 @@ class qn{constructor(e){this.value=e}}class Gn{constructor(e){this.value=e}}clas
124
124
  * License, v. 2.0. If a copy of the MPL was not distributed with this
125
125
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
126
126
  */
127
- var Ms,_s;!function(e){e[e.Unsynchronisation=128]="Unsynchronisation",e[e.ExtendedHeader=64]="ExtendedHeader",e[e.ExperimentalIndicator=32]="ExperimentalIndicator",e[e.Footer=16]="Footer"}(Ms||(Ms={})),function(e){e[e.ISO_8859_1=0]="ISO_8859_1",e[e.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",e[e.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",e[e.UTF_8=3]="UTF_8"}(_s||(_s={}));const Ds=128,Bs=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],Fs=(e,t)=>{const r=jo(e,t),i=Fi(r.indexOf(0),r.length),a=r.subarray(0,i);let n="";for(let e=0;e<a.length;e++)n+=String.fromCharCode(a[e]);return n.trimEnd()},Ns=e=>{const t=e.filePos,r=sc(e,3),i=Xo(e),a=Xo(e),n=Xo(e),s=Qo(e);if("ID3"!==r||255===i||255===a||2155905152&s)return e.filePos=t,null;return{majorVersion:i,revision:a,flags:n,size:Os(s)}},Ls=(e,t,r)=>{if(![2,3,4].includes(t.majorVersion))return void console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const i=jo(e,t.size),a=new Us(t,i);if(t.flags&Ms.Footer&&a.removeFooter(),t.flags&Ms.Unsynchronisation&&3===t.majorVersion&&a.ununsynchronizeAll(),t.flags&Ms.ExtendedHeader){const e=a.readU32();3===t.majorVersion?a.pos+=e:a.pos+=e-4}for(;a.pos<=a.bytes.length-a.frameHeaderSize();){const e=a.readId3V2Frame();if(!e)break;const i=a.pos,n=a.pos+e.size;let s=!1,o=!1,c=!1;if(3===t.majorVersion?(s=!!(64&e.flags),o=!!(128&e.flags)):4===t.majorVersion&&(s=!!(4&e.flags),o=!!(8&e.flags),c=!!(2&e.flags)||!!(t.flags&Ms.Unsynchronisation)),s)console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),a.pos=n;else if(o)console.warn(`Skipping compressed ID3v2 frame ${e.id}`),a.pos=n;else{switch(c&&a.ununsynchronizeRegion(a.pos,n),r.raw??={},"T"===e.id[0]?r.raw[e.id]??=a.readId3V2EncodingAndText(n):r.raw[e.id]??=a.readBytes(e.size),a.pos=i,e.id){case"TIT2":case"TT2":r.title??=a.readId3V2EncodingAndText(n);break;case"TIT3":case"TT3":r.description??=a.readId3V2EncodingAndText(n);break;case"TPE1":case"TP1":r.artist??=a.readId3V2EncodingAndText(n);break;case"TALB":case"TAL":r.album??=a.readId3V2EncodingAndText(n);break;case"TPE2":case"TP2":r.albumArtist??=a.readId3V2EncodingAndText(n);break;case"TRCK":case"TRK":{const e=a.readId3V2EncodingAndText(n).split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(r.tracksTotal??=i)}break;case"TPOS":case"TPA":{const e=a.readId3V2EncodingAndText(n).split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.discNumber??=t),i&&Number.isInteger(i)&&i>0&&(r.discsTotal??=i)}break;case"TCON":case"TCO":{const e=a.readId3V2EncodingAndText(n);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Bs[e]){r.genre??=Bs[e];break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Bs[e]){r.genre??=Bs[e];break}}r.genre??=e}break;case"TDRC":case"TDAT":{const e=a.readId3V2EncodingAndText(n),t=new Date(e);Number.isNaN(t.getTime())||(r.date??=t)}break;case"TYER":case"TYE":{const e=a.readId3V2EncodingAndText(n),t=Number.parseInt(e,10);Number.isInteger(t)&&(r.date??=new Date(t,0,1))}break;case"USLT":case"ULT":{const e=a.readU8();a.pos+=3,a.readId3V2Text(e,n),r.lyrics??=a.readId3V2Text(e,n)}break;case"COMM":case"COM":{const e=a.readU8();a.pos+=3,a.readId3V2Text(e,n),r.comment??=a.readId3V2Text(e,n)}break;case"APIC":case"PIC":{const e=a.readId3V2TextEncoding();let i;if(2===t.majorVersion){const e=a.readAscii(3);i="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else i=a.readId3V2Text(e,n);const s=a.readU8(),o=a.readId3V2Text(e,n).trimEnd(),c=n-a.pos;if(c>=0){const e=a.readBytes(c);r.images||(r.images=[]),r.images.push({data:e,mimeType:i,kind:3===s?"coverFront":4===s?"coverBack":"unknown",description:o})}}break;default:a.pos+=e.size}a.pos=n}}};class Us{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return 2===this.header.majorVersion?6:10}ununsynchronizeAll(){const e=[];for(let t=0;t<this.bytes.length;t++){const r=this.bytes[t];if(e.push(r),255===r&&t!==this.bytes.length-1){0===this.bytes[t]&&t++}}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){const r=[];for(let i=e;i<t;i++){const e=this.bytes[i];if(r.push(e),255===e&&i!==t-1){0===this.bytes[i+1]&&i++}}const i=this.bytes.subarray(0,e),a=this.bytes.subarray(t);this.bytes=new Uint8Array(i.length+r.length+a.length),this.bytes.set(i,0),this.bytes.set(r,i.length),this.bytes.set(a,i.length+r.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-10),this.view=new DataView(this.bytes.buffer)}readBytes(e){const t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){const e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){const e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){const e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+1);return this.pos+=3,256*e+t}readU32(){const e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let r=0;r<e;r++)t+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=e,t}readId3V2Frame(){if(2===this.header.majorVersion){const e=this.readAscii(3);if("\0\0\0"===e)return null;return{id:e,size:this.readU24(),flags:0}}{const e=this.readAscii(4);if("\0\0\0\0"===e)return null;const t=this.readU32();let r=4===this.header.majorVersion?Os(t):t;const i=this.readU16(),a=this.pos,n=e=>{const t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;const t=this.readAscii(4);if("\0\0\0\0"!==t&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!n(r)){const e=4===this.header.majorVersion?t:Os(t);n(e)&&(r=e)}return this.pos=a,{id:e,size:r,flags:i}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const r=this.pos,i=this.readBytes(t-this.pos);switch(e){case _s.ISO_8859_1:{let e="";for(let t=0;t<i.length;t++){const a=i[t];if(0===a){this.pos=r+t+1;break}e+=String.fromCharCode(a)}return e}case _s.UTF_16_WITH_BOM:if(255===i[0]&&254===i[1]){const e=new TextDecoder("utf-16le"),t=Fi(i.findIndex((e,t)=>0===e&&0===i[t+1]&&t%2==0),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(2,t))}if(254===i[0]&&255===i[1]){const e=new TextDecoder("utf-16be"),t=Fi(i.findIndex((e,t)=>0===e&&0===i[t+1]&&t%2==0),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(2,t))}{const e=Fi(i.findIndex(e=>0===e),i.length);return this.pos=r+Math.min(e+1,i.length),Jr.decode(i.subarray(0,e))}case _s.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=Fi(i.findIndex((e,t)=>0===e&&0===i[t+1]&&t%2==0),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(0,t))}case _s.UTF_8:{const e=Fi(i.findIndex(e=>0===e),i.length);return this.pos=r+Math.min(e+1,i.length),Jr.decode(i.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}
127
+ var $c,Qc;!function(e){e[e.Unsynchronisation=128]="Unsynchronisation",e[e.ExtendedHeader=64]="ExtendedHeader",e[e.ExperimentalIndicator=32]="ExperimentalIndicator",e[e.Footer=16]="Footer"}($c||($c={})),function(e){e[e.ISO_8859_1=0]="ISO_8859_1",e[e.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",e[e.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",e[e.UTF_8=3]="UTF_8"}(Qc||(Qc={}));const Zc=128,Jc=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],eu=(e,t)=>{const r=sl(e,t),i=zn(r.indexOf(0),r.length),a=r.subarray(0,i);let n="";for(let e=0;e<a.length;e++)n+=String.fromCharCode(a[e]);return n.trimEnd()},tu=e=>{const t=e.filePos,r=kl(e,3),i=cl(e),a=cl(e),n=cl(e),o=ml(e);if("ID3"!==r||255===i||255===a||2155905152&o)return e.filePos=t,null;return{majorVersion:i,revision:a,flags:n,size:Kc(o)}},ru=(e,t,r)=>{if(![2,3,4].includes(t.majorVersion))return void console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const i=sl(e,t.size),a=new iu(t,i);if(t.flags&$c.Footer&&a.removeFooter(),t.flags&$c.Unsynchronisation&&3===t.majorVersion&&a.ununsynchronizeAll(),t.flags&$c.ExtendedHeader){const e=a.readU32();3===t.majorVersion?a.pos+=e:a.pos+=e-4}for(;a.pos<=a.bytes.length-a.frameHeaderSize();){const e=a.readId3V2Frame();if(!e)break;const i=a.pos,n=a.pos+e.size;let o=!1,s=!1,c=!1;if(3===t.majorVersion?(o=!!(64&e.flags),s=!!(128&e.flags)):4===t.majorVersion&&(o=!!(4&e.flags),s=!!(8&e.flags),c=!!(2&e.flags)||!!(t.flags&$c.Unsynchronisation)),o)console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),a.pos=n;else if(s)console.warn(`Skipping compressed ID3v2 frame ${e.id}`),a.pos=n;else{switch(c&&a.ununsynchronizeRegion(a.pos,n),r.raw??={},"T"===e.id[0]?r.raw[e.id]??=a.readId3V2EncodingAndText(n):r.raw[e.id]??=a.readBytes(e.size),a.pos=i,e.id){case"TIT2":case"TT2":r.title??=a.readId3V2EncodingAndText(n);break;case"TIT3":case"TT3":r.description??=a.readId3V2EncodingAndText(n);break;case"TPE1":case"TP1":r.artist??=a.readId3V2EncodingAndText(n);break;case"TALB":case"TAL":r.album??=a.readId3V2EncodingAndText(n);break;case"TPE2":case"TP2":r.albumArtist??=a.readId3V2EncodingAndText(n);break;case"TRCK":case"TRK":{const e=a.readId3V2EncodingAndText(n).split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(r.tracksTotal??=i)}break;case"TPOS":case"TPA":{const e=a.readId3V2EncodingAndText(n).split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.discNumber??=t),i&&Number.isInteger(i)&&i>0&&(r.discsTotal??=i)}break;case"TCON":case"TCO":{const e=a.readId3V2EncodingAndText(n);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Jc[e]){r.genre??=Jc[e];break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Jc[e]){r.genre??=Jc[e];break}}r.genre??=e}break;case"TDRC":case"TDAT":{const e=a.readId3V2EncodingAndText(n),t=new Date(e);Number.isNaN(t.getTime())||(r.date??=t)}break;case"TYER":case"TYE":{const e=a.readId3V2EncodingAndText(n),t=Number.parseInt(e,10);Number.isInteger(t)&&(r.date??=new Date(t,0,1))}break;case"USLT":case"ULT":{const e=a.readU8();a.pos+=3,a.readId3V2Text(e,n),r.lyrics??=a.readId3V2Text(e,n)}break;case"COMM":case"COM":{const e=a.readU8();a.pos+=3,a.readId3V2Text(e,n),r.comment??=a.readId3V2Text(e,n)}break;case"APIC":case"PIC":{const e=a.readId3V2TextEncoding();let i;if(2===t.majorVersion){const e=a.readAscii(3);i="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else i=a.readId3V2Text(e,n);const o=a.readU8(),s=a.readId3V2Text(e,n).trimEnd(),c=n-a.pos;if(c>=0){const e=a.readBytes(c);r.images||(r.images=[]),r.images.push({data:e,mimeType:i,kind:3===o?"coverFront":4===o?"coverBack":"unknown",description:s})}}break;default:a.pos+=e.size}a.pos=n}}};class iu{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return 2===this.header.majorVersion?6:10}ununsynchronizeAll(){const e=[];for(let t=0;t<this.bytes.length;t++){const r=this.bytes[t];if(e.push(r),255===r&&t!==this.bytes.length-1){0===this.bytes[t]&&t++}}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){const r=[];for(let i=e;i<t;i++){const e=this.bytes[i];if(r.push(e),255===e&&i!==t-1){0===this.bytes[i+1]&&i++}}const i=this.bytes.subarray(0,e),a=this.bytes.subarray(t);this.bytes=new Uint8Array(i.length+r.length+a.length),this.bytes.set(i,0),this.bytes.set(r,i.length),this.bytes.set(a,i.length+r.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-10),this.view=new DataView(this.bytes.buffer)}readBytes(e){const t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){const e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){const e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){const e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+1);return this.pos+=3,256*e+t}readU32(){const e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let r=0;r<e;r++)t+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=e,t}readId3V2Frame(){if(2===this.header.majorVersion){const e=this.readAscii(3);if("\0\0\0"===e)return null;return{id:e,size:this.readU24(),flags:0}}{const e=this.readAscii(4);if("\0\0\0\0"===e)return null;const t=this.readU32();let r=4===this.header.majorVersion?Kc(t):t;const i=this.readU16(),a=this.pos,n=e=>{const t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;const t=this.readAscii(4);if("\0\0\0\0"!==t&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!n(r)){const e=4===this.header.majorVersion?t:Kc(t);n(e)&&(r=e)}return this.pos=a,{id:e,size:r,flags:i}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const r=this.pos,i=this.readBytes(t-this.pos);switch(e){case Qc.ISO_8859_1:{let e="";for(let t=0;t<i.length;t++){const a=i[t];if(0===a){this.pos=r+t+1;break}e+=String.fromCharCode(a)}return e}case Qc.UTF_16_WITH_BOM:if(255===i[0]&&254===i[1]){const e=new TextDecoder("utf-16le"),t=zn(i.findIndex((e,t)=>0===e&&0===i[t+1]&&t%2==0),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(2,t))}if(254===i[0]&&255===i[1]){const e=new TextDecoder("utf-16be"),t=zn(i.findIndex((e,t)=>0===e&&0===i[t+1]&&t%2==0),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(2,t))}{const e=zn(i.findIndex(e=>0===e),i.length);return this.pos=r+Math.min(e+1,i.length),Ja.decode(i.subarray(0,e))}case Qc.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=zn(i.findIndex((e,t)=>0===e&&0===i[t+1]&&t%2==0),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(0,t))}case Qc.UTF_8:{const e=zn(i.findIndex(e=>0===e),i.length);return this.pos=r+Math.min(e+1,i.length),Ja.decode(i.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}
128
128
  /*!
129
129
  * Copyright (c) 2025-present, Vanilagy and contributors
130
130
  *
131
131
  * This Source Code Form is subject to the terms of the Mozilla Public
132
132
  * License, v. 2.0. If a copy of the MPL was not distributed with this
133
133
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
134
- */const zs=async(e,t,r)=>{let i=t;for(;null===r||i<r;){let t=e.requestSlice(i,4);if(t instanceof Promise&&(t=await t),!t)break;const r=Qo(t),a=Rs(r,null!==e.fileSize?e.fileSize-i:null);if(a.header)return{header:a.header,startPos:i};i+=a.bytesAdvanced}return null};
134
+ */const au=async(e,t,r)=>{let i=t;for(;null===r||i<r;){let t=e.requestSlice(i,4);if(t instanceof Promise&&(t=await t),!t)break;const r=ml(t),a=qc(r,null!==e.fileSize?e.fileSize-i:null);if(a.header)return{header:a.header,startPos:i};i+=a.bytesAdvanced}return null};
135
135
  /*!
136
136
  * Copyright (c) 2025-present, Vanilagy and contributors
137
137
  *
138
138
  * This Source Code Form is subject to the terms of the Mozilla Public
139
139
  * License, v. 2.0. If a copy of the MPL was not distributed with this
140
140
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
141
- */class Ws extends Ka{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new ui,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.tracks=[new En(this.input,new Vs(this))]})()}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=Ns(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await zs(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const r=(i=t.mpegVersionId,a=t.channel,3===i?3===a?21:36:3===a?13:21);var i,a;let n=this.reader.requestSlice(e.startPos+r,4);if(n instanceof Promise&&(n=await n),n){const e=Qo(n);if(1483304551===e||1231971951===e)return}this.firstFrameHeader||(this.firstFrameHeader=t),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);const s=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,o={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(o),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return jr(e),e.computeDuration()}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let r=this.reader.requestSlice(e,10);if(r instanceof Promise&&(r=await r),!r)break;const i=Ns(r);if(!i)break;t=!0;let a=this.reader.requestSlice(r.filePos,i.size);if(a instanceof Promise&&(a=await a),!a)break;Ls(a,i,this.metadataTags),e=r.filePos+i.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Ds){let e=this.reader.requestSlice(this.reader.fileSize-Ds,Ds);e instanceof Promise&&(e=await e),jr(e);"TAG"===sc(e,3)&&((e,t)=>{const r=e.filePos;t.raw??={},t.raw.TAG??=jo(e,125),e.filePos=r;const i=Fs(e,30);i&&(t.title??=i);const a=Fs(e,30);a&&(t.artist??=a);const n=Fs(e,30);n&&(t.album??=n);const s=Fs(e,4),o=Number.parseInt(s,10);Number.isInteger(o)&&o>0&&(t.date??=new Date(o,0,1));const c=jo(e,30);let l;if(0===c[28]&&0!==c[29]){const r=c[29];r>0&&(t.trackNumber??=r),e.skip(-30),l=Fs(e,28),e.skip(2)}else e.skip(-30),l=Fs(e,30);l&&(t.comment??=l);const u=Xo(e);u<Bs.length&&(t.genre??=Bs[u])})(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class Vs{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return jr(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return wi}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return jr(this.demuxer.firstFrameHeader),3===this.demuxer.firstFrameHeader.channel?1:2}getSampleRate(){return jr(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...qi}}async getDecoderConfig(){return jr(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:3===this.demuxer.firstFrameHeader.channel?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(-1===e)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=Qa;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;i=jo(e,r.dataSize)}return new Za(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const r=fi(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===r)throw new Error("Packet was not created from this track.");const i=r+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const r=mi(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===r&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(r,t);if(r>=0&&r+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(r,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
141
+ */class nu extends is{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new hn,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.tracks=[new Xs(this.input,new ou(this))]})()}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=tu(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await au(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const r=(i=t.mpegVersionId,a=t.channel,3===i?3===a?21:36:3===a?13:21);var i,a;let n=this.reader.requestSlice(e.startPos+r,4);if(n instanceof Promise&&(n=await n),n){const e=ml(n);if(1483304551===e||1231971951===e)return}this.firstFrameHeader||(this.firstFrameHeader=t),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);const o=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,s={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:o,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(s),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return Xa(e),e.computeDuration()}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let r=this.reader.requestSlice(e,10);if(r instanceof Promise&&(r=await r),!r)break;const i=tu(r);if(!i)break;t=!0;let a=this.reader.requestSlice(r.filePos,i.size);if(a instanceof Promise&&(a=await a),!a)break;ru(a,i,this.metadataTags),e=r.filePos+i.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Zc){let e=this.reader.requestSlice(this.reader.fileSize-Zc,Zc);e instanceof Promise&&(e=await e),Xa(e);"TAG"===kl(e,3)&&((e,t)=>{const r=e.filePos;t.raw??={},t.raw.TAG??=sl(e,125),e.filePos=r;const i=eu(e,30);i&&(t.title??=i);const a=eu(e,30);a&&(t.artist??=a);const n=eu(e,30);n&&(t.album??=n);const o=eu(e,4),s=Number.parseInt(o,10);Number.isInteger(s)&&s>0&&(t.date??=new Date(s,0,1));const c=sl(e,30);let u;if(0===c[28]&&0!==c[29]){const r=c[29];r>0&&(t.trackNumber??=r),e.skip(-30),u=eu(e,28),e.skip(2)}else e.skip(-30),u=eu(e,30);u&&(t.comment??=u);const l=cl(e);l<Jc.length&&(t.genre??=Jc[l])})(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class ou{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return Xa(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Sn}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return Xa(this.demuxer.firstFrameHeader),3===this.demuxer.firstFrameHeader.channel?1:2}getSampleRate(){return Xa(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...$n}}async getDecoderConfig(){return Xa(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:3===this.demuxer.firstFrameHeader.channel?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(-1===e)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=os;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;i=sl(e,r.dataSize)}return new ss(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const r=mn(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===r)throw new Error("Packet was not created from this track.");const i=r+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const r=pn(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===r&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(r,t);if(r>=0&&r+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(r,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
142
142
  /*!
143
143
  * Copyright (c) 2025-present, Vanilagy and contributors
144
144
  *
145
145
  * This Source Code Form is subject to the terms of the Mozilla Public
146
146
  * License, v. 2.0. If a copy of the MPL was not distributed with this
147
147
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
148
- */const Hs=1399285583,js=new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=2147483648&t?t<<1^79764919:t<<1;js[e]=t>>>0&4294967295}const Xs=e=>{const t=Zr(e),r=t.getUint32(22,!0);t.setUint32(22,0,!0);let i=0;for(let t=0;t<e.length;t++){const r=e[t];i=(i<<8^js[i>>>24^r])>>>0}return t.setUint32(22,r,!0),i},qs=(e,t,r)=>{let i=0,a=null;if(e.length>0)if("vorbis"===t.codec){jr(t.vorbisInfo);const n=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,s=(e[0]&n)>>1;if(s>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let o=r;const c=t.vorbisInfo.modeBlockflags[s];if(a=t.vorbisInfo.blocksizes[c],1===c){const r=1+(1|n),i=e[0]&r?1:0;o=t.vorbisInfo.blocksizes[i]}i=null!==o?o+a>>2:0}else if("opus"===t.codec){const t=(e=>{const t=e[0]>>3;return{durationInSamples:Ha[t]}})(e);i=t.durationInSamples}return{durationInSamples:i,vorbisBlockSize:a}},Gs=27,Ks=282,Ys=e=>{const t=e.filePos;if(Zo(e)!==Hs)return null;e.skip(1);const r=Xo(e),i=ic(e),a=Zo(e),n=Zo(e),s=Zo(e),o=Xo(e),c=new Uint8Array(o);for(let t=0;t<o;t++)c[t]=Xo(e);const l=27+o,u=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:r,granulePosition:i,serialNumber:a,sequenceNumber:n,checksum:s,lacingValues:c}},$s=(e,t)=>{for(;e.filePos<t-3;){const t=Zo(e),r=79;if((255&t)===r||(t>>>8&255)===r||(t>>>16&255)===r||(t>>>24&255)===r){if(e.skip(-4),t===Hs)return!0;e.skip(1)}}return!1};
148
+ */const su=1399285583,cu=new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=2147483648&t?t<<1^79764919:t<<1;cu[e]=t>>>0&4294967295}const uu=e=>{const t=Za(e),r=t.getUint32(22,!0);t.setUint32(22,0,!0);let i=0;for(let t=0;t<e.length;t++){const r=e[t];i=(i<<8^cu[i>>>24^r])>>>0}return t.setUint32(22,r,!0),i},lu=(e,t,r)=>{let i=0,a=null;if(e.length>0)if("vorbis"===t.codec){Xa(t.vorbisInfo);const n=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,o=(e[0]&n)>>1;if(o>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let s=r;const c=t.vorbisInfo.modeBlockflags[o];if(a=t.vorbisInfo.blocksizes[c],1===c){const r=1+(1|n),i=e[0]&r?1:0;s=t.vorbisInfo.blocksizes[i]}i=null!==s?s+a>>2:0}else if("opus"===t.codec){const t=(e=>{const t=e[0]>>3;return{durationInSamples:Zo[t]}})(e);i=t.durationInSamples}return{durationInSamples:i,vorbisBlockSize:a}},hu=27,du=282,fu=e=>{const t=e.filePos;if(pl(e)!==su)return null;e.skip(1);const r=cl(e),i=xl(e),a=pl(e),n=pl(e),o=pl(e),s=cl(e),c=new Uint8Array(s);for(let t=0;t<s;t++)c[t]=cl(e);const u=27+s,l=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:u+l,dataStartPos:t+u,dataSize:l,headerType:r,granulePosition:i,serialNumber:a,sequenceNumber:n,checksum:o,lacingValues:c}},mu=(e,t)=>{for(;e.filePos<t-3;){const t=pl(e),r=79;if((255&t)===r||(t>>>8&255)===r||(t>>>16&255)===r||(t>>>24&255)===r){if(e.skip(-4),t===su)return!0;e.skip(1)}}return!1};
149
149
  /*!
150
150
  * Copyright (c) 2025-present, Vanilagy and contributors
151
151
  *
@@ -153,7 +153,7 @@ var Ms,_s;!function(e){e[e.Unsynchronisation=128]="Unsynchronisation",e[e.Extend
153
153
  * License, v. 2.0. If a copy of the MPL was not distributed with this
154
154
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
155
155
  */
156
- class Qs extends Ka{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Gs,Ks);if(t instanceof Promise&&(t=await t),!t)break;const r=Ys(t);if(!r)break;if(!!!(2&r.headerType))break;this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=r.headerStartPos+r.totalSize}for(const e of this.bitstreams){const t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=7&&1===t.data[0]&&118===t.data[1]&&111===t.data[2]&&114===t.data[3]&&98===t.data[4]&&105===t.data[5]&&115===t.data[6]?await this.readVorbisMetadata(t,e):t.data.byteLength>=8&&79===t.data[0]&&112===t.data[1]&&117===t.data[2]&&115===t.data[3]&&72===t.data[4]&&101===t.data[5]&&97===t.data[6]&&100===t.data[7]&&await this.readOpusMetadata(t,e),null!==e.codecInfo.codec&&this.tracks.push(new En(this.input,new Zs(e,this))))}})()}async readVorbisMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;const i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;if(r=await this.findNextPacketStart(i),!r)return;const a=await this.readPacket(r.startPage,r.startSegmentIndex);if(!a)return;if(3!==i.data[0]||5!==a.data[0])return;const n=[],s=e=>{for(;n.push(Math.min(255,e)),!(e<255);)e-=255};s(e.data.length),s(i.data.length);const o=new Uint8Array(1+n.length+e.data.length+i.data.length+a.data.length);o[0]=2,o.set(n,1),o.set(e.data,1+n.length),o.set(i.data,1+n.length+e.data.length),o.set(a.data,1+n.length+e.data.length+i.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=a;const c=Zr(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);const l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&l),1<<(l>>4)],modeBlockflags:ja(a.data).modeBlockflags},Ga(i.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const r=await this.findNextPacketStart(e);if(!r)return;const i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=i;const a=Va(e.data);t.numberOfChannels=a.outputChannelCount,t.sampleRate=ca,t.codecInfo.opusInfo={preSkip:a.preSkip},Ga(i.data.subarray(8),this.metadataTags)}async readPacket(e,t){jr(t<e.lacingValues.length);let r=0;for(let i=0;i<t;i++)r+=e.lacingValues[i];let i=e,a=r,n=t;const s=[];e:for(;;){let t=this.reader.requestSlice(i.dataStartPos,i.dataSize);t instanceof Promise&&(t=await t),jr(t);const o=jo(t,i.dataSize);for(;;){if(n===i.lacingValues.length){s.push(o.subarray(r,a));break}const e=i.lacingValues[n];if(a+=e,e<255){s.push(o.subarray(r,a));break e}n++}let c=i.headerStartPos+i.totalSize;for(;;){let t=this.reader.requestSliceRange(c,Gs,Ks);if(t instanceof Promise&&(t=await t),!t)return null;const r=Ys(t);if(!r)return null;if(i=r,i.serialNumber===e.serialNumber)break;c=i.headerStartPos+i.totalSize}r=0,a=0,n=0}const o=s.reduce((e,t)=>e+t.length,0),c=new Uint8Array(o);let l=0;for(let e=0;e<s.length;e++){const t=s[e];c.set(t,l),l+=t.length}return{data:c,endPage:i,endSegmentIndex:n}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(4&e.endPage.headerType))return null;let t=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let r=this.reader.requestSliceRange(t,Gs,Ks);if(r instanceof Promise&&(r=await r),!r)return null;const i=Ys(r);if(!i)return null;if(i.serialNumber===e.endPage.serialNumber)return{startPage:i,startSegmentIndex:0};t=i.headerStartPos+i.totalSize}}async getMimeType(){await this.readMetadata();return(e=>{let t="audio/ogg";e.codecStrings&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({codecStrings:(await Promise.all(this.tracks.map(e=>e.getCodecParameterString()))).filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class Zs{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new ui,this.internalSampleRate="opus"===e.codecInfo.codec?ca:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return jr(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return wi}getDisposition(){return{...qi}}async getFirstTimestamp(){return 0}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(jr(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;const{durationInSamples:i,vorbisBlockSize:a}=qs(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),n=new Za(r.metadataOnly?Qa:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,i/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(n,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:i,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:a}),n}async getFirstPacket(e){jr(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;"opus"===this.bitstream.codecInfo.codec&&(jr(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);const i=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const r=this.encodedPacketToMetadata.get(e);if(!r)throw new Error("Packet was not created from this track.");const i=await this.demuxer.findNextPacketStart(r.packet);if(!i)return null;const a=r.timestampInSamples+r.durationInSamples,n=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(n,{timestampInSamples:a,vorbisLastBlocksize:r.vorbisBlockSize},t)}async getPacket(e,t){if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const r=Si(e*this.internalSampleRate);if(0===r)return this.getFirstPacket(t);if(r<0)return null;jr(this.bitstream.lastMetadataPacket);const i=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!i)return null;let a=i.startPage,n=this.demuxer.reader.fileSize;const s=[a];e:for(;a.headerStartPos+a.totalSize<n;){const e=a.headerStartPos,t=Math.floor((e+n)/2);let i=t;for(;;){const e=Math.min(i+65307,n-Gs);let o=this.demuxer.reader.requestSlice(i,e-i);o instanceof Promise&&(o=await o),jr(o);if(!$s(o,e)){n=t+Gs;continue e}let c=this.demuxer.reader.requestSliceRange(o.filePos,Gs,Ks);c instanceof Promise&&(c=await c),jr(c);const l=Ys(c);jr(l);let u=!1;if(l.serialNumber===this.bitstream.serialNumber)u=!0;else{let e=this.demuxer.reader.requestSlice(l.headerStartPos,l.totalSize);e instanceof Promise&&(e=await e),jr(e);const t=jo(e,l.totalSize);u=Xs(t)===l.checksum}if(!u){i=l.headerStartPos+4;continue}if(u&&l.serialNumber!==this.bitstream.serialNumber){i=l.headerStartPos+l.totalSize;continue}if(!(-1===l.granulePosition)){this.granulePositionToTimestampInSamples(l.granulePosition)>r?n=l.headerStartPos:(a=l,s.push(l));continue e}i=l.headerStartPos+l.totalSize}}let o=i.startPage;for(const e of s){if(e.granulePosition===a.granulePosition)break;(!o||e.headerStartPos>o.headerStartPos)&&(o=e)}let c=o;const l=[c];for(;c.serialNumber!==this.bitstream.serialNumber||c.granulePosition!==a.granulePosition;){const e=c.headerStartPos+c.totalSize;let t=this.demuxer.reader.requestSliceRange(e,Gs,Ks);t instanceof Promise&&(t=await t),jr(t);const r=Ys(t);jr(r),c=r,c.serialNumber===this.bitstream.serialNumber&&l.push(c)}jr(-1!==c.granulePosition);let u,h,d=null,f=c,m=0;if(c.headerStartPos===i.startPage.headerStartPos)u=this.granulePositionToTimestampInSamples(0),h=!0,d=0;else{u=0,h=!1;for(let e=c.lacingValues.length-1;e>=0;e--){if(c.lacingValues[e]<255){d=e+1;break}}if(null===d)throw new Error("Invalid page with granule position: no packets end on this page.");m=d-1;const e={data:Qa,endPage:f,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(e)){const e=eo(l,c,d);jr(e);const t=Js(l,e.page,e.segmentIndex);t&&(c=t.page,d=t.segmentIndex)}else for(;;){const e=eo(l,c,d);if(!e)break;const t=Js(l,e.page,e.segmentIndex);if(!t)break;if(c=t.page,d=t.segmentIndex,e.page.headerStartPos!==f.headerStartPos){f=e.page,m=e.segmentIndex;break}}}let p=null,g=null;for(;null!==c;){jr(null!==d);const e=await this.demuxer.readPacket(c,d);if(!e)break;if(!(c.headerStartPos===i.startPage.headerStartPos&&d<i.startSegmentIndex)){let i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:u,vorbisLastBlocksize:g?.vorbisBlockSize??null},t);jr(i);let a=this.encodedPacketToMetadata.get(i);if(jr(a),h||e.endPage.headerStartPos!==f.headerStartPos||e.endSegmentIndex!==m?u+=a.durationInSamples:(u=this.granulePositionToTimestampInSamples(c.granulePosition),h=!0,i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:u-a.durationInSamples,vorbisLastBlocksize:g?.vorbisBlockSize??null},t),jr(i),a=this.encodedPacketToMetadata.get(i),jr(a)),p=i,g=a,h&&(Math.max(u,0)>r||Math.max(a.timestampInSamples,0)===r))break}const a=await this.demuxer.findNextPacketStart(e);if(!a)break;c=a.startPage,d=a.startSegmentIndex}return p}async getPacketSequential(e,t){const r=await this.sequentialScanMutex.acquire();try{const r=Si(e*this.internalSampleRate);e=r/this.internalSampleRate;const i=mi(this.sequentialScanCache,r,e=>e.timestampInSamples);let a;if(-1!==i){const e=this.sequentialScanCache[i];a=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let n=0;for(;a&&a.timestamp<e;){const r=await this.getNextPacket(a,t);if(!r||r.timestamp>e)break;if(a=r,n++,100===n){n=0;const e=this.encodedPacketToMetadata.get(a);jr(e),this.sequentialScanCache.length>0&&jr(qr(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return a}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Js=(e,t,r)=>{let i=t,a=r;e:for(;;){for(a--;a>=0;a--){if(i.lacingValues[a]<255){a++;break e}}jr(-1===a);if(!(1&i.headerType)){a=0;break}const t=vi(e,e=>e.headerStartPos<i.headerStartPos);if(!t)return null;i=t,a=i.lacingValues.length}if(jr(-1!==a),a===i.lacingValues.length){const t=e[e.indexOf(i)+1];jr(t),i=t,a=0}return{page:i,segmentIndex:a}},eo=(e,t,r)=>{if(r>0)return{page:t,segmentIndex:r-1};const i=vi(e,e=>e.headerStartPos<t.headerStartPos);return i?{page:i,segmentIndex:i.lacingValues.length-1}:null};
156
+ class pu extends is{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,hu,du);if(t instanceof Promise&&(t=await t),!t)break;const r=fu(t);if(!r)break;if(!!!(2&r.headerType))break;this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=r.headerStartPos+r.totalSize}for(const e of this.bitstreams){const t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=7&&1===t.data[0]&&118===t.data[1]&&111===t.data[2]&&114===t.data[3]&&98===t.data[4]&&105===t.data[5]&&115===t.data[6]?await this.readVorbisMetadata(t,e):t.data.byteLength>=8&&79===t.data[0]&&112===t.data[1]&&117===t.data[2]&&115===t.data[3]&&72===t.data[4]&&101===t.data[5]&&97===t.data[6]&&100===t.data[7]&&await this.readOpusMetadata(t,e),null!==e.codecInfo.codec&&this.tracks.push(new Xs(this.input,new gu(e,this))))}})()}async readVorbisMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;const i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;if(r=await this.findNextPacketStart(i),!r)return;const a=await this.readPacket(r.startPage,r.startSegmentIndex);if(!a)return;if(3!==i.data[0]||5!==a.data[0])return;const n=[],o=e=>{for(;n.push(Math.min(255,e)),!(e<255);)e-=255};o(e.data.length),o(i.data.length);const s=new Uint8Array(1+n.length+e.data.length+i.data.length+a.data.length);s[0]=2,s.set(n,1),s.set(e.data,1+n.length),s.set(i.data,1+n.length+e.data.length),s.set(a.data,1+n.length+e.data.length+i.data.length),t.codecInfo.codec="vorbis",t.description=s,t.lastMetadataPacket=a;const c=Za(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);const u=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&u),1<<(u>>4)],modeBlockflags:Jo(a.data).modeBlockflags},rs(i.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const r=await this.findNextPacketStart(e);if(!r)return;const i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=i;const a=Qo(e.data);t.numberOfChannels=a.outputChannelCount,t.sampleRate=fo,t.codecInfo.opusInfo={preSkip:a.preSkip},rs(i.data.subarray(8),this.metadataTags)}async readPacket(e,t){Xa(t<e.lacingValues.length);let r=0;for(let i=0;i<t;i++)r+=e.lacingValues[i];let i=e,a=r,n=t;const o=[];e:for(;;){let t=this.reader.requestSlice(i.dataStartPos,i.dataSize);t instanceof Promise&&(t=await t),Xa(t);const s=sl(t,i.dataSize);for(;;){if(n===i.lacingValues.length){o.push(s.subarray(r,a));break}const e=i.lacingValues[n];if(a+=e,e<255){o.push(s.subarray(r,a));break e}n++}let c=i.headerStartPos+i.totalSize;for(;;){let t=this.reader.requestSliceRange(c,hu,du);if(t instanceof Promise&&(t=await t),!t)return null;const r=fu(t);if(!r)return null;if(i=r,i.serialNumber===e.serialNumber)break;c=i.headerStartPos+i.totalSize}r=0,a=0,n=0}const s=o.reduce((e,t)=>e+t.length,0),c=new Uint8Array(s);let u=0;for(let e=0;e<o.length;e++){const t=o[e];c.set(t,u),u+=t.length}return{data:c,endPage:i,endSegmentIndex:n}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(4&e.endPage.headerType))return null;let t=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let r=this.reader.requestSliceRange(t,hu,du);if(r instanceof Promise&&(r=await r),!r)return null;const i=fu(r);if(!i)return null;if(i.serialNumber===e.endPage.serialNumber)return{startPage:i,startSegmentIndex:0};t=i.headerStartPos+i.totalSize}}async getMimeType(){await this.readMetadata();return(e=>{let t="audio/ogg";e.codecStrings&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({codecStrings:(await Promise.all(this.tracks.map(e=>e.getCodecParameterString()))).filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class gu{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new hn,this.internalSampleRate="opus"===e.codecInfo.codec?fo:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return Xa(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return Sn}getDisposition(){return{...$n}}async getFirstTimestamp(){return 0}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(Xa(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;const{durationInSamples:i,vorbisBlockSize:a}=lu(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),n=new ss(r.metadataOnly?os:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,i/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(n,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:i,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:a}),n}async getFirstPacket(e){Xa(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;"opus"===this.bitstream.codecInfo.codec&&(Xa(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);const i=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const r=this.encodedPacketToMetadata.get(e);if(!r)throw new Error("Packet was not created from this track.");const i=await this.demuxer.findNextPacketStart(r.packet);if(!i)return null;const a=r.timestampInSamples+r.durationInSamples,n=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(n,{timestampInSamples:a,vorbisLastBlocksize:r.vorbisBlockSize},t)}async getPacket(e,t){if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const r=En(e*this.internalSampleRate);if(0===r)return this.getFirstPacket(t);if(r<0)return null;Xa(this.bitstream.lastMetadataPacket);const i=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!i)return null;let a=i.startPage,n=this.demuxer.reader.fileSize;const o=[a];e:for(;a.headerStartPos+a.totalSize<n;){const e=a.headerStartPos,t=Math.floor((e+n)/2);let i=t;for(;;){const e=Math.min(i+65307,n-hu);let s=this.demuxer.reader.requestSlice(i,e-i);s instanceof Promise&&(s=await s),Xa(s);if(!mu(s,e)){n=t+hu;continue e}let c=this.demuxer.reader.requestSliceRange(s.filePos,hu,du);c instanceof Promise&&(c=await c),Xa(c);const u=fu(c);Xa(u);let l=!1;if(u.serialNumber===this.bitstream.serialNumber)l=!0;else{let e=this.demuxer.reader.requestSlice(u.headerStartPos,u.totalSize);e instanceof Promise&&(e=await e),Xa(e);const t=sl(e,u.totalSize);l=uu(t)===u.checksum}if(!l){i=u.headerStartPos+4;continue}if(l&&u.serialNumber!==this.bitstream.serialNumber){i=u.headerStartPos+u.totalSize;continue}if(!(-1===u.granulePosition)){this.granulePositionToTimestampInSamples(u.granulePosition)>r?n=u.headerStartPos:(a=u,o.push(u));continue e}i=u.headerStartPos+u.totalSize}}let s=i.startPage;for(const e of o){if(e.granulePosition===a.granulePosition)break;(!s||e.headerStartPos>s.headerStartPos)&&(s=e)}let c=s;const u=[c];for(;c.serialNumber!==this.bitstream.serialNumber||c.granulePosition!==a.granulePosition;){const e=c.headerStartPos+c.totalSize;let t=this.demuxer.reader.requestSliceRange(e,hu,du);t instanceof Promise&&(t=await t),Xa(t);const r=fu(t);Xa(r),c=r,c.serialNumber===this.bitstream.serialNumber&&u.push(c)}Xa(-1!==c.granulePosition);let l,h,d=null,f=c,m=0;if(c.headerStartPos===i.startPage.headerStartPos)l=this.granulePositionToTimestampInSamples(0),h=!0,d=0;else{l=0,h=!1;for(let e=c.lacingValues.length-1;e>=0;e--){if(c.lacingValues[e]<255){d=e+1;break}}if(null===d)throw new Error("Invalid page with granule position: no packets end on this page.");m=d-1;const e={data:os,endPage:f,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(e)){const e=yu(u,c,d);Xa(e);const t=vu(u,e.page,e.segmentIndex);t&&(c=t.page,d=t.segmentIndex)}else for(;;){const e=yu(u,c,d);if(!e)break;const t=vu(u,e.page,e.segmentIndex);if(!t)break;if(c=t.page,d=t.segmentIndex,e.page.headerStartPos!==f.headerStartPos){f=e.page,m=e.segmentIndex;break}}}let p=null,g=null;for(;null!==c;){Xa(null!==d);const e=await this.demuxer.readPacket(c,d);if(!e)break;if(!(c.headerStartPos===i.startPage.headerStartPos&&d<i.startSegmentIndex)){let i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:l,vorbisLastBlocksize:g?.vorbisBlockSize??null},t);Xa(i);let a=this.encodedPacketToMetadata.get(i);if(Xa(a),h||e.endPage.headerStartPos!==f.headerStartPos||e.endSegmentIndex!==m?l+=a.durationInSamples:(l=this.granulePositionToTimestampInSamples(c.granulePosition),h=!0,i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:l-a.durationInSamples,vorbisLastBlocksize:g?.vorbisBlockSize??null},t),Xa(i),a=this.encodedPacketToMetadata.get(i),Xa(a)),p=i,g=a,h&&(Math.max(l,0)>r||Math.max(a.timestampInSamples,0)===r))break}const a=await this.demuxer.findNextPacketStart(e);if(!a)break;c=a.startPage,d=a.startSegmentIndex}return p}async getPacketSequential(e,t){const r=await this.sequentialScanMutex.acquire();try{const r=En(e*this.internalSampleRate);e=r/this.internalSampleRate;const i=pn(this.sequentialScanCache,r,e=>e.timestampInSamples);let a;if(-1!==i){const e=this.sequentialScanCache[i];a=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let n=0;for(;a&&a.timestamp<e;){const r=await this.getNextPacket(a,t);if(!r||r.timestamp>e)break;if(a=r,n++,100===n){n=0;const e=this.encodedPacketToMetadata.get(a);Xa(e),this.sequentialScanCache.length>0&&Xa(Ga(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return a}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const vu=(e,t,r)=>{let i=t,a=r;e:for(;;){for(a--;a>=0;a--){if(i.lacingValues[a]<255){a++;break e}}Xa(-1===a);if(!(1&i.headerType)){a=0;break}const t=yn(e,e=>e.headerStartPos<i.headerStartPos);if(!t)return null;i=t,a=i.lacingValues.length}if(Xa(-1!==a),a===i.lacingValues.length){const t=e[e.indexOf(i)+1];Xa(t),i=t,a=0}return{page:i,segmentIndex:a}},yu=(e,t,r)=>{if(r>0)return{page:t,segmentIndex:r-1};const i=yn(e,e=>e.headerStartPos<t.headerStartPos);return i?{page:i,segmentIndex:i.lacingValues.length-1}:null};
157
157
  /*!
158
158
  * Copyright (c) 2025-present, Vanilagy and contributors
159
159
  *
@@ -161,14 +161,14 @@ class Qs extends Ka{constructor(e){super(e),this.metadataPromise=null,this.bitst
161
161
  * License, v. 2.0. If a copy of the MPL was not distributed with this
162
162
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
163
163
  */
164
- var to;!function(e){e[e.PCM=1]="PCM",e[e.IEEE_FLOAT=3]="IEEE_FLOAT",e[e.ALAW=6]="ALAW",e[e.MULAW=7]="MULAW",e[e.EXTENSIBLE=65534]="EXTENSIBLE"}(to||(to={}));class ro extends Ka{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),jr(e);const t=sc(e,4),r="RIFX"!==t,i="RF64"===t,a=$o(e,r);let n=i?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if("WAVE"!==sc(e,4))throw new Error("Invalid WAVE file - wrong format");let s=0,o=null,c=e.filePos;for(;null===n||c<n;){let e=this.reader.requestSlice(c,8);if(e instanceof Promise&&(e=await e),!e)break;const t=sc(e,4),a=$o(e,r),l=e.filePos;if(i&&0===s&&"ds64"!==t)throw new Error('Invalid RF64 file: First chunk must be "ds64".');if("fmt "===t)await this.parseFmtChunk(l,a,r);else if("data"===t){if(o??=a,this.dataStart=e.filePos,this.dataSize=Math.min(o,(n??1/0)-this.dataStart),null===this.reader.fileSize)break}else if("ds64"===t){let e=this.reader.requestSlice(l,a);if(e instanceof Promise&&(e=await e),!e)break;const t=ec(e,r);o=ec(e,r),n=Math.min(t+8,this.reader.fileSize??1/0)}else"LIST"===t?await this.parseListChunk(l,a,r):"ID3 "!==t&&"id3 "!==t||await this.parseId3Chunk(l,a);c=l+a+(1&a),s++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(-1===this.dataStart)throw new Error('Invalid WAVE file - missing "data" chunk');const l=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/l)*l,this.tracks.push(new En(this.input,new ao(this)))})()}async parseFmtChunk(e,t,r){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let a=qo(i,r);const n=qo(i,r),s=$o(i,r);i.skip(4);const o=qo(i,r);let c;if(c=14===t?8:qo(i,r),t>=18&&357!==a){const e=qo(i,r),n=t-18;if(Math.min(n,e)>=22&&a===to.EXTENSIBLE){i.skip(6);const e=jo(i,16);a=e[0]|e[1]<<8}}a!==to.MULAW&&a!==to.ALAW||(c=8),this.audioInfo={format:a,numberOfChannels:n,sampleRate:s,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,r){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;const a=sc(i,4);if("INFO"!==a&&"INF0"!==a)return;let n=i.filePos;for(;n<=e+t-8;){i.filePos=n;const e=sc(i,4),t=$o(i,r),a=jo(i,t);let s=0;for(let e=0;e<a.length&&0!==a[e];e++)s++;const o=String.fromCharCode(...a.subarray(0,s));switch(this.metadataTags.raw??={},this.metadataTags.raw[e]=o,e){case"INAM":case"TITL":this.metadataTags.title??=o;break;case"TIT3":this.metadataTags.description??=o;break;case"IART":this.metadataTags.artist??=o;break;case"IPRD":this.metadataTags.album??=o;break;case"IPRT":case"ITRK":case"TRCK":{const e=o.split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(this.metadataTags.tracksTotal??=r)}break;case"ICRD":case"IDIT":{const e=new Date(o);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"YEAR":{const e=Number.parseInt(o,10);Number.isInteger(e)&&e>0&&(this.metadataTags.date??=new Date(e,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=o;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=o}n+=8+t+(1&t)}}async parseId3Chunk(e,t){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;const i=Ns(r);if(i){const t=r.slice(e+10,i.size);Ls(t,i,this.metadataTags)}}getCodec(){if(jr(this.audioInfo),this.audioInfo.format===to.MULAW)return"ulaw";if(this.audioInfo.format===to.ALAW)return"alaw";if(this.audioInfo.format===to.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}return this.audioInfo.format===to.IEEE_FLOAT&&4===this.audioInfo.sampleSizeInBytes?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return jr(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const io=2048;class ao{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return jr(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(jr(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return jr(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return jr(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return jr(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return wi}getDisposition(){return{...qi}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){jr(this.demuxer.audioInfo);const r=e*io*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const i=Math.min(io*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);if(e instanceof Promise&&(e=await e),!e)return null}let a;if(t.metadataOnly)a=Qa;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);e instanceof Promise&&(e=await e),jr(e),a=jo(e,i)}const n=e*io/this.demuxer.audioInfo.sampleRate,s=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,n),new Za(a,"key",n,s,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){jr(this.demuxer.audioInfo);const r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/io,(this.demuxer.dataSize-1)/(io*this.demuxer.audioInfo.blockSizeInBytes))),i=await this.getPacketAtIndex(r,t);if(i)return i;if(0===r)return null;jr(null===this.demuxer.reader.fileSize);let a=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;a;){const e=await this.getNextPacket(a,t);if(!e)break;a=e}return a}getNextPacket(e,t){jr(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/io);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
164
+ var bu;!function(e){e[e.PCM=1]="PCM",e[e.IEEE_FLOAT=3]="IEEE_FLOAT",e[e.ALAW=6]="ALAW",e[e.MULAW=7]="MULAW",e[e.EXTENSIBLE=65534]="EXTENSIBLE"}(bu||(bu={}));class xu extends is{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),Xa(e);const t=kl(e,4),r="RIFX"!==t,i="RF64"===t,a=fl(e,r);let n=i?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if("WAVE"!==kl(e,4))throw new Error("Invalid WAVE file - wrong format");let o=0,s=null,c=e.filePos;for(;null===n||c<n;){let e=this.reader.requestSlice(c,8);if(e instanceof Promise&&(e=await e),!e)break;const t=kl(e,4),a=fl(e,r),u=e.filePos;if(i&&0===o&&"ds64"!==t)throw new Error('Invalid RF64 file: First chunk must be "ds64".');if("fmt "===t)await this.parseFmtChunk(u,a,r);else if("data"===t){if(s??=a,this.dataStart=e.filePos,this.dataSize=Math.min(s,(n??1/0)-this.dataStart),null===this.reader.fileSize)break}else if("ds64"===t){let e=this.reader.requestSlice(u,a);if(e instanceof Promise&&(e=await e),!e)break;const t=vl(e,r);s=vl(e,r),n=Math.min(t+8,this.reader.fileSize??1/0)}else"LIST"===t?await this.parseListChunk(u,a,r):"ID3 "!==t&&"id3 "!==t||await this.parseId3Chunk(u,a);c=u+a+(1&a),o++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(-1===this.dataStart)throw new Error('Invalid WAVE file - missing "data" chunk');const u=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/u)*u,this.tracks.push(new Xs(this.input,new wu(this)))})()}async parseFmtChunk(e,t,r){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let a=ul(i,r);const n=ul(i,r),o=fl(i,r);i.skip(4);const s=ul(i,r);let c;if(c=14===t?8:ul(i,r),t>=18&&357!==a){const e=ul(i,r),n=t-18;if(Math.min(n,e)>=22&&a===bu.EXTENSIBLE){i.skip(6);const e=sl(i,16);a=e[0]|e[1]<<8}}a!==bu.MULAW&&a!==bu.ALAW||(c=8),this.audioInfo={format:a,numberOfChannels:n,sampleRate:o,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:s}}async parseListChunk(e,t,r){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;const a=kl(i,4);if("INFO"!==a&&"INF0"!==a)return;let n=i.filePos;for(;n<=e+t-8;){i.filePos=n;const e=kl(i,4),t=fl(i,r),a=sl(i,t);let o=0;for(let e=0;e<a.length&&0!==a[e];e++)o++;const s=String.fromCharCode(...a.subarray(0,o));switch(this.metadataTags.raw??={},this.metadataTags.raw[e]=s,e){case"INAM":case"TITL":this.metadataTags.title??=s;break;case"TIT3":this.metadataTags.description??=s;break;case"IART":this.metadataTags.artist??=s;break;case"IPRD":this.metadataTags.album??=s;break;case"IPRT":case"ITRK":case"TRCK":{const e=s.split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(this.metadataTags.tracksTotal??=r)}break;case"ICRD":case"IDIT":{const e=new Date(s);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"YEAR":{const e=Number.parseInt(s,10);Number.isInteger(e)&&e>0&&(this.metadataTags.date??=new Date(e,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=s;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=s}n+=8+t+(1&t)}}async parseId3Chunk(e,t){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;const i=tu(r);if(i){const t=r.slice(e+10,i.size);ru(t,i,this.metadataTags)}}getCodec(){if(Xa(this.audioInfo),this.audioInfo.format===bu.MULAW)return"ulaw";if(this.audioInfo.format===bu.ALAW)return"alaw";if(this.audioInfo.format===bu.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}return this.audioInfo.format===bu.IEEE_FLOAT&&4===this.audioInfo.sampleSizeInBytes?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return Xa(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Tu=2048;class wu{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return Xa(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(Xa(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return Xa(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return Xa(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return Xa(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Sn}getDisposition(){return{...$n}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){Xa(this.demuxer.audioInfo);const r=e*Tu*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const i=Math.min(Tu*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);if(e instanceof Promise&&(e=await e),!e)return null}let a;if(t.metadataOnly)a=os;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);e instanceof Promise&&(e=await e),Xa(e),a=sl(e,i)}const n=e*Tu/this.demuxer.audioInfo.sampleRate,o=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,n),new ss(a,"key",n,o,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){Xa(this.demuxer.audioInfo);const r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Tu,(this.demuxer.dataSize-1)/(Tu*this.demuxer.audioInfo.blockSizeInBytes))),i=await this.getPacketAtIndex(r,t);if(i)return i;if(0===r)return null;Xa(null===this.demuxer.reader.fileSize);let a=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;a;){const e=await this.getNextPacket(a,t);if(!e)break;a=e}return a}getNextPacket(e,t){Xa(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Tu);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
165
165
  /*!
166
166
  * Copyright (c) 2025-present, Vanilagy and contributors
167
167
  *
168
168
  * This Source Code Form is subject to the terms of the Mozilla Public
169
169
  * License, v. 2.0. If a copy of the MPL was not distributed with this
170
170
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
171
- */const no=e=>{const t=e.filePos,r=jo(e,9),i=new Kr(r);if(4095!==i.readBits(12))return null;i.skipBits(1);if(0!==i.readBits(2))return null;const a=i.readBits(1),n=i.readBits(2)+1,s=i.readBits(4);if(15===s)return null;i.skipBits(1);const o=i.readBits(3);if(0===o)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const c=i.readBits(13);i.skipBits(11);const l=i.readBits(2)+1;if(1!==l)throw new Error("ADTS frames with more than one AAC frame are not supported.");let u=null;return 1===a?e.filePos-=2:u=i.readBits(16),{objectType:n,samplingFrequencyIndex:s,channelConfiguration:o,frameLength:c,numberOfAacFrames:l,crcCheck:u,startPos:t}},so=1024;class oo extends Ka{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new ui,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();jr(this.firstFrameHeader),this.tracks=[new En(this.input,new co(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=no(e);if(!t)return void(this.lastSampleLoaded=!0);if(null!==this.reader.fileSize&&t.startPos+t.frameLength>this.reader.fileSize)return void(this.lastSampleLoaded=!0);this.firstFrameHeader||(this.firstFrameHeader=t);const r=na[t.samplingFrequencyIndex];jr(void 0!==r);const i=so/r,a=t.crcCheck?9:7,n={timestamp:this.nextTimestampInSamples/r,duration:i,dataStart:t.startPos+a,dataSize:t.frameLength-a};this.loadedSamples.push(n),this.nextTimestampInSamples+=so,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return jr(e),e.computeDuration()}async getMetadataTags(){return{}}}class co{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/so}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return wi}getCodec(){return"aac"}getInternalCodecId(){return jr(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){jr(this.demuxer.firstFrameHeader);const e=sa[this.demuxer.firstFrameHeader.channelConfiguration];return jr(void 0!==e),e}getSampleRate(){jr(this.demuxer.firstFrameHeader);const e=na[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return jr(void 0!==e),e}getDisposition(){return{...qi}}async getDecoderConfig(){jr(this.demuxer.firstFrameHeader);const e=new Uint8Array(3),t=new Kr(e),{objectType:r,samplingFrequencyIndex:i,channelConfiguration:a}=this.demuxer.firstFrameHeader;return r>31?(t.writeBits(5,31),t.writeBits(6,r-32)):t.writeBits(5,r),t.writeBits(4,i),t.writeBits(4,a),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((t.pos-1)/8))}}async getPacketAtIndex(e,t){if(-1===e)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=Qa;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;i=jo(e,r.dataSize)}return new Za(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const r=fi(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===r)throw new Error("Packet was not created from this track.");const i=r+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const r=mi(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===r&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(r,t);if(r>=0&&r+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(r,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
171
+ */const ku=e=>{const t=e.filePos,r=sl(e,9),i=new qa(r);if(4095!==i.readBits(12))return null;i.skipBits(1);if(0!==i.readBits(2))return null;const a=i.readBits(1),n=i.readBits(2)+1,o=i.readBits(4);if(15===o)return null;i.skipBits(1);const s=i.readBits(3);if(0===s)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const c=i.readBits(13);i.skipBits(11);const u=i.readBits(2)+1;if(1!==u)throw new Error("ADTS frames with more than one AAC frame are not supported.");let l=null;return 1===a?e.filePos-=2:l=i.readBits(16),{objectType:n,samplingFrequencyIndex:o,channelConfiguration:s,frameLength:c,numberOfAacFrames:u,crcCheck:l,startPos:t}},Su=1024;class Eu extends is{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new hn,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();Xa(this.firstFrameHeader),this.tracks=[new Xs(this.input,new Cu(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=ku(e);if(!t)return void(this.lastSampleLoaded=!0);if(null!==this.reader.fileSize&&t.startPos+t.frameLength>this.reader.fileSize)return void(this.lastSampleLoaded=!0);this.firstFrameHeader||(this.firstFrameHeader=t);const r=uo[t.samplingFrequencyIndex];Xa(void 0!==r);const i=Su/r,a=t.crcCheck?9:7,n={timestamp:this.nextTimestampInSamples/r,duration:i,dataStart:t.startPos+a,dataSize:t.frameLength-a};this.loadedSamples.push(n),this.nextTimestampInSamples+=Su,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return Xa(e),e.computeDuration()}async getMetadataTags(){return{}}}class Cu{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/Su}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Sn}getCodec(){return"aac"}getInternalCodecId(){return Xa(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){Xa(this.demuxer.firstFrameHeader);const e=lo[this.demuxer.firstFrameHeader.channelConfiguration];return Xa(void 0!==e),e}getSampleRate(){Xa(this.demuxer.firstFrameHeader);const e=uo[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return Xa(void 0!==e),e}getDisposition(){return{...$n}}async getDecoderConfig(){Xa(this.demuxer.firstFrameHeader);const e=new Uint8Array(3),t=new qa(e),{objectType:r,samplingFrequencyIndex:i,channelConfiguration:a}=this.demuxer.firstFrameHeader;return r>31?(t.writeBits(5,31),t.writeBits(6,r-32)):t.writeBits(5,r),t.writeBits(4,i),t.writeBits(4,a),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((t.pos-1)/8))}}async getPacketAtIndex(e,t){if(-1===e)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=os;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;i=sl(e,r.dataSize)}return new ss(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const r=mn(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===r)throw new Error("Packet was not created from this track.");const i=r+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const r=pn(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===r&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(r,t);if(r>=0&&r+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(r,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
172
172
  /*!
173
173
  * Copyright (c) 2025-present, Vanilagy and contributors
174
174
  *
@@ -183,14 +183,14 @@ var to;!function(e){e[e.PCM=1]="PCM",e[e.IEEE_FLOAT=3]="IEEE_FLOAT",e[e.ALAW=6]=
183
183
  * License, v. 2.0. If a copy of the MPL was not distributed with this
184
184
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
185
185
  */
186
- class lo extends Ka{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new ui,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),jr(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),jr(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;null===this.reader.fileSize||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,null===t)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);jr(t);const r=Xo(t),i=Ko(t),a=!!(128&r);switch(127&r){case qa.STREAMINFO:{let t=this.reader.requestSlice(e,i);if(t instanceof Promise&&(t=await t),jr(t),null===t)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const r=jo(t,34),a=new Kr(r),n=a.readBits(16),s=a.readBits(16),o=a.readBits(24),c=a.readBits(24),l=a.readBits(20),u=a.readBits(3)+1;a.readBits(5);const h=a.readBits(36);a.skipBits(128);const d=new Uint8Array(42);d.set(new Uint8Array([102,76,97,67]),0),d.set(new Uint8Array([128,0,0,34]),4),d.set(r,8),this.audioInfo={numberOfChannels:u,sampleRate:l,totalSamples:h,minimumBlockSize:n,maximumBlockSize:s,minimumFrameSize:o,maximumFrameSize:c,description:d},this.track=new En(this.input,new uo(this));break}case qa.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,i);t instanceof Promise&&(t=await t),jr(t),Ga(jo(t,i),this.metadataTags);break}case qa.PICTURE:{let t=this.reader.requestSlice(e,i);t instanceof Promise&&(t=await t),jr(t);const r=Qo(t),a=Qo(t),n=Jr.decode(jo(t,a)),s=Qo(t),o=Jr.decode(jo(t,s));t.skip(16);const c=Qo(t),l=jo(t,c);this.metadataTags.images??=[],this.metadataTags.images.push({data:l,mimeType:n,kind:3===r?"coverFront":4===r?"coverBack":"unknown",description:o});break}}if(e+=i,a){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){jr(this.audioInfo);const r=this.audioInfo.maximumFrameSize+16,i=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,r);if(!i)return null;const a=this.readFlacFrameHeader({slice:i,isFirstPacket:t});if(!a)return null;for(i.filePos=e+this.audioInfo.minimumFrameSize;;){if(i.filePos>i.end-6)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:i.end-e,isLastFrame:!0};if(255===Xo(i)){const t=i.filePos;if(Xo(i)!==(1===this.blockingBit?249:248)){i.filePos=t;continue}i.skip(-2);const r=i.filePos-e,n=this.readFlacFrameHeader({slice:i,isFirstPacket:!1});if(!n){i.filePos=t;continue}if(0===this.blockingBit){if(n.num-a.num!==1){i.filePos=t;continue}}else if(n.num-a.num!==a.blockSize){i.filePos=t;continue}return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:r,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const r=e.filePos,i=jo(e,4),a=new Kr(i);if(32764!==a.readBits(15))return null;if(null===this.blockingBit){jr(t);const e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){jr(!t);if(1!==a.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");jr(!t);if(0!==a.readBits(1))return null}const n=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*2**e:6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?2**e:null)(a.readBits(4));if(!n)return null;jr(this.audioInfo);const s=((e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}})(a.readBits(4),this.audioInfo.sampleRate);if(!s)return null;a.readBits(4),a.readBits(3);if(0!==a.readBits(1))return null;const o=(e=>{let t=0;const r=new Kr(jo(e,1));for(;1===r.readBits(1);)t++;if(0===t)return r.readBits(7);const i=[],a=t-1,n=new Kr(jo(e,a)),s=8-t-1;for(let e=0;e<s;e++)i.unshift(r.readBits(1));for(let e=0;e<a;e++)for(let e=0;e<8;e++){const t=n.readBits(1);e<2||i.unshift(t)}const o=i.reduce((e,t,r)=>e|t<<r,0);return o})(e),c=((e,t)=>"uncommon-u16"===t?Go(e)+1:"uncommon-u8"===t?Xo(e)+1:"number"==typeof t?t:(bi(t),void jr(!1)))(e,n),l=((e,t)=>"uncommon-u16"===t?Go(e):"uncommon-u16-10"===t?10*Go(e):"uncommon-u8"===t?Xo(e):"number"==typeof t?t:null)(e,s);if(null===l)return null;if(l!==this.audioInfo.sampleRate)return null;const u=e.filePos-r,h=Xo(e);e.skip(-u),e.skip(-1);const d=(e=>{let t=0;for(const r of e){t^=r;for(let e=0;e<8;e++)128&t?t=t<<1^7:t<<=1,t&=255}return t})(jo(e,u));return h!==d?null:{num:o,blockSize:c,sampleRate:l}}async advanceReader(){await this.readMetadata(),jr(null!==this.lastLoadedPos),jr(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t)return void(this.lastSampleLoaded=!0);const r=this.loadedSamples[this.loadedSamples.length-1],i={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(i),t.isLastFrame&&(this.lastSampleLoaded=!0)}}class uo{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return jr(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return jr(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return wi}getTimeResolution(){return jr(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...qi}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return jr(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(jr(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");const r=await this.demuxer.readingMutex.acquire();try{for(;;){const r=mi(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===r){await this.demuxer.advanceReader();continue}const i=this.demuxer.loadedSamples[r],a=i.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(a+i.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(r,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader()}}finally{r()}}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const r=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&r>=this.demuxer.loadedSamples.length)return null;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=Qa;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;i=jo(e,r.byteSize)}jr(this.demuxer.audioInfo);const a=r.blockOffset/this.demuxer.audioInfo.sampleRate,n=r.blockSize/this.demuxer.audioInfo.sampleRate;return new Za(i,"key",a,n,e,r.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}
186
+ class Au extends is{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new hn,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),Xa(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),Xa(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;null===this.reader.fileSize||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,null===t)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);Xa(t);const r=cl(t),i=hl(t),a=!!(128&r);switch(127&r){case ts.STREAMINFO:{let t=this.reader.requestSlice(e,i);if(t instanceof Promise&&(t=await t),Xa(t),null===t)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const r=sl(t,34),a=new qa(r),n=a.readBits(16),o=a.readBits(16),s=a.readBits(24),c=a.readBits(24),u=a.readBits(20),l=a.readBits(3)+1;a.readBits(5);const h=a.readBits(36);a.skipBits(128);const d=new Uint8Array(42);d.set(new Uint8Array([102,76,97,67]),0),d.set(new Uint8Array([128,0,0,34]),4),d.set(r,8),this.audioInfo={numberOfChannels:l,sampleRate:u,totalSamples:h,minimumBlockSize:n,maximumBlockSize:o,minimumFrameSize:s,maximumFrameSize:c,description:d},this.track=new Xs(this.input,new _u(this));break}case ts.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,i);t instanceof Promise&&(t=await t),Xa(t),rs(sl(t,i),this.metadataTags);break}case ts.PICTURE:{let t=this.reader.requestSlice(e,i);t instanceof Promise&&(t=await t),Xa(t);const r=ml(t),a=ml(t),n=Ja.decode(sl(t,a)),o=ml(t),s=Ja.decode(sl(t,o));t.skip(16);const c=ml(t),u=sl(t,c);this.metadataTags.images??=[],this.metadataTags.images.push({data:u,mimeType:n,kind:3===r?"coverFront":4===r?"coverBack":"unknown",description:s});break}}if(e+=i,a){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){Xa(this.audioInfo);const r=this.audioInfo.maximumFrameSize+16,i=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,r);if(!i)return null;const a=this.readFlacFrameHeader({slice:i,isFirstPacket:t});if(!a)return null;for(i.filePos=e+this.audioInfo.minimumFrameSize;;){if(i.filePos>i.end-6)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:i.end-e,isLastFrame:!0};if(255===cl(i)){const t=i.filePos;if(cl(i)!==(1===this.blockingBit?249:248)){i.filePos=t;continue}i.skip(-2);const r=i.filePos-e,n=this.readFlacFrameHeader({slice:i,isFirstPacket:!1});if(!n){i.filePos=t;continue}if(0===this.blockingBit){if(n.num-a.num!==1){i.filePos=t;continue}}else if(n.num-a.num!==a.blockSize){i.filePos=t;continue}return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:r,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const r=e.filePos,i=sl(e,4),a=new qa(i);if(32764!==a.readBits(15))return null;if(null===this.blockingBit){Xa(t);const e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){Xa(!t);if(1!==a.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");Xa(!t);if(0!==a.readBits(1))return null}const n=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*2**e:6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?2**e:null)(a.readBits(4));if(!n)return null;Xa(this.audioInfo);const o=((e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}})(a.readBits(4),this.audioInfo.sampleRate);if(!o)return null;a.readBits(4),a.readBits(3);if(0!==a.readBits(1))return null;const s=(e=>{let t=0;const r=new qa(sl(e,1));for(;1===r.readBits(1);)t++;if(0===t)return r.readBits(7);const i=[],a=t-1,n=new qa(sl(e,a)),o=8-t-1;for(let e=0;e<o;e++)i.unshift(r.readBits(1));for(let e=0;e<a;e++)for(let e=0;e<8;e++){const t=n.readBits(1);e<2||i.unshift(t)}const s=i.reduce((e,t,r)=>e|t<<r,0);return s})(e),c=((e,t)=>"uncommon-u16"===t?ll(e)+1:"uncommon-u8"===t?cl(e)+1:"number"==typeof t?t:(xn(t),void Xa(!1)))(e,n),u=((e,t)=>"uncommon-u16"===t?ll(e):"uncommon-u16-10"===t?10*ll(e):"uncommon-u8"===t?cl(e):"number"==typeof t?t:null)(e,o);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const l=e.filePos-r,h=cl(e);e.skip(-l),e.skip(-1);const d=(e=>{let t=0;for(const r of e){t^=r;for(let e=0;e<8;e++)128&t?t=t<<1^7:t<<=1,t&=255}return t})(sl(e,l));return h!==d?null:{num:s,blockSize:c,sampleRate:u}}async advanceReader(){await this.readMetadata(),Xa(null!==this.lastLoadedPos),Xa(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t)return void(this.lastSampleLoaded=!0);const r=this.loadedSamples[this.loadedSamples.length-1],i={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(i),t.isLastFrame&&(this.lastSampleLoaded=!0)}}class _u{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return Xa(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return Xa(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Sn}getTimeResolution(){return Xa(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...$n}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return Xa(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(Xa(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");const r=await this.demuxer.readingMutex.acquire();try{for(;;){const r=pn(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===r){await this.demuxer.advanceReader();continue}const i=this.demuxer.loadedSamples[r],a=i.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(a+i.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(r,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader()}}finally{r()}}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const r=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&r>=this.demuxer.loadedSamples.length)return null;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=os;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;i=sl(e,r.byteSize)}Xa(this.demuxer.audioInfo);const a=r.blockOffset/this.demuxer.audioInfo.sampleRate,n=r.blockSize/this.demuxer.audioInfo.sampleRate;return new ss(i,"key",a,n,e,r.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}
187
187
  /*!
188
188
  * Copyright (c) 2025-present, Vanilagy and contributors
189
189
  *
190
190
  * This Source Code Form is subject to the terms of the Mozilla Public
191
191
  * License, v. 2.0. If a copy of the MPL was not distributed with this
192
192
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
193
- */class ho{}class fo extends ho{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);return"ftyp"!==sc(t,4)?null:sc(t,4)}_createDemuxer(e){return new Bn(e)}}class mo extends fo{async _canReadInput(e){const t=await this._getMajorBrand(e);return!!t&&"qt "!==t}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class po extends fo{async _canReadInput(e){return"qt "===await this._getMajorBrand(e)}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class go extends ho{async isSupportedEBMLOfDocType(e,t){let r=e._reader.requestSlice(0,as);if(r instanceof Promise&&(r=await r),!r)return!1;const i=ns(r);if(null===i)return!1;if(i<1||i>8)return!1;if(os(r,i)!==$n.EBML)return!1;const a=ls(r);if(null===a)return!1;let n=e._reader.requestSlice(r.filePos,a);if(n instanceof Promise&&(n=await n),!n)return!1;const s=r.filePos;for(;n.filePos<=s+a-2;){const e=us(n);if(!e)break;const{id:r,size:i}=e,a=n.filePos;if(null===i)return!1;switch(r){case $n.EBMLVersion:if(1!==os(n,i))return!1;break;case $n.EBMLReadVersion:if(1!==os(n,i))return!1;break;case $n.DocType:if(hs(n,i)!==t)return!1;break;case $n.DocTypeVersion:if(os(n,i)>4)return!1}n.filePos=a+i}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new xs(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class vo extends go{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class yo extends ho{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let r=0,i=!1;for(;;){let t=e._reader.requestSlice(r,10);if(t instanceof Promise&&(t=await t),!t)break;const a=Ns(t);if(!a)break;i=!0,r=t.filePos+a.size}const a=await zs(e._reader,r,r+4096);if(!a)return!1;if(i)return!0;r=a.startPos+a.header.totalSize;const n=await zs(e._reader,r,r+4);if(!n)return!1;const s=a.header,o=n.header;return s.channel===o.channel&&s.sampleRate===o.sampleRate}_createDemuxer(e){return new Ws(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class bo extends ho{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;const r=sc(t,4);if("RIFF"!==r&&"RIFX"!==r&&"RF64"!==r)return!1;t.skip(4);return"WAVE"===sc(t,4)}_createDemuxer(e){return new ro(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class ko extends ho{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"OggS"===sc(t,4)}_createDemuxer(e){return new Qs(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class To extends ho{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"fLaC"===sc(t,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new lo(e)}}class wo extends ho{async _canReadInput(e){let t=e._reader.requestSliceRange(0,7,9);if(t instanceof Promise&&(t=await t),!t)return!1;const r=no(t);if(!r)return!1;if(t=e._reader.requestSliceRange(r.frameLength,7,9),t instanceof Promise&&(t=await t),!t)return!1;const i=no(t);return!!i&&(r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration)}_createDemuxer(e){return new oo(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}const So=new mo,xo=new po,Co=new go,Eo=new vo,Ao=new yo,Po=new bo,Io=new ko,Ro=new wo,Oo=[So,xo,Co,Eo,Po,Io,new To,Ao,Ro];
193
+ */class Mu{}class Iu extends Mu{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);return"ftyp"!==kl(t,4)?null:kl(t,4)}_createDemuxer(e){return new Js(e)}}class Ru extends Iu{async _canReadInput(e){const t=await this._getMajorBrand(e);return!!t&&"qt "!==t}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class Pu extends Iu{async _canReadInput(e){return"qt "===await this._getMajorBrand(e)}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class Ou extends Mu{async isSupportedEBMLOfDocType(e,t){let r=e._reader.requestSlice(0,wc);if(r instanceof Promise&&(r=await r),!r)return!1;const i=kc(r);if(null===i)return!1;if(i<1||i>8)return!1;if(Ec(r,i)!==mc.EBML)return!1;const a=Ac(r);if(null===a)return!1;let n=e._reader.requestSlice(r.filePos,a);if(n instanceof Promise&&(n=await n),!n)return!1;const o=r.filePos;for(;n.filePos<=o+a-2;){const e=_c(n);if(!e)break;const{id:r,size:i}=e,a=n.filePos;if(null===i)return!1;switch(r){case mc.EBMLVersion:if(1!==Ec(n,i))return!1;break;case mc.EBMLReadVersion:if(1!==Ec(n,i))return!1;break;case mc.DocType:if(Mc(n,i)!==t)return!1;break;case mc.DocTypeVersion:if(Ec(n,i)>4)return!1}n.filePos=a+i}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Vc(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Du extends Ou{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Bu extends Mu{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let r=0,i=!1;for(;;){let t=e._reader.requestSlice(r,10);if(t instanceof Promise&&(t=await t),!t)break;const a=tu(t);if(!a)break;i=!0,r=t.filePos+a.size}const a=await au(e._reader,r,r+4096);if(!a)return!1;if(i)return!0;r=a.startPos+a.header.totalSize;const n=await au(e._reader,r,r+4);if(!n)return!1;const o=a.header,s=n.header;return o.channel===s.channel&&o.sampleRate===s.sampleRate}_createDemuxer(e){return new nu(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Fu extends Mu{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;const r=kl(t,4);if("RIFF"!==r&&"RIFX"!==r&&"RF64"!==r)return!1;t.skip(4);return"WAVE"===kl(t,4)}_createDemuxer(e){return new xu(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Lu extends Mu{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"OggS"===kl(t,4)}_createDemuxer(e){return new pu(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Nu extends Mu{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"fLaC"===kl(t,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Au(e)}}class Uu extends Mu{async _canReadInput(e){let t=e._reader.requestSliceRange(0,7,9);if(t instanceof Promise&&(t=await t),!t)return!1;const r=ku(t);if(!r)return!1;if(t=e._reader.requestSliceRange(r.frameLength,7,9),t instanceof Promise&&(t=await t),!t)return!1;const i=ku(t);return!!i&&(r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration)}_createDemuxer(e){return new Eu(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}const zu=new Ru,Wu=new Pu,Vu=new Ou,Hu=new Du,Xu=new Bu,ju=new Fu,Gu=new Lu,Yu=new Uu,qu=[zu,Wu,Vu,Hu,ju,Gu,new Nu,Xu,Yu];
194
194
  /*!
195
195
  * Copyright (c) 2025-present, Vanilagy and contributors
196
196
  *
@@ -198,21 +198,21 @@ class lo extends Ka{constructor(e){super(e),this.loadedSamples=[],this.metadataP
198
198
  * License, v. 2.0. If a copy of the MPL was not distributed with this
199
199
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
200
200
  */
201
- class Mo{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new zo;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new zo;const e=await this.getSizeOrNull();if(null===e)throw new Error("Cannot determine the size of an unsized source.");return e}}const _o=524288,Do=(e,t,r)=>{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))){let e=null;try{"undefined"!=typeof window&&void 0!==window.location&&(e=new URL(r instanceof Request?r.url:r,window.location.href).origin)}catch{}if(("undefined"==typeof navigator||"boolean"!=typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return null}return Math.min(2**(e-2),16)};class Bo extends Mo{constructor(e,t={}){if(!("string"==typeof e||e instanceof URL||"undefined"!=typeof Request&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!=typeof t.requestInit))throw new TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!=typeof t.getRetryDelay)throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!Hi(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.fetchFn&&"function"!=typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Do,this._orchestrator=new Lo({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:No.network})}async _retrieveSize(){const e=new AbortController,t=await Ri(this._options.fetchFn??fetch,this._url,Pi(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay);if(!t.ok)throw new Error(`Error fetching ${String(this._url)}: ${t.status} ${t.statusText}`);let r,i;if(206===t.status)i=this._getPartialLengthFromRangeResponse(t),r=this._orchestrator.createWorker(0,Math.min(i,_o));else{const e=t.headers.get("Content-Length");if(!e)throw new Error(`HTTP response (status ${t.status}) must surface Content-Length header.`);i=Number(e),r=this._orchestrator.createWorker(0,i),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.")}return this._orchestrator.fileSize=i,this._existingResponses.set(r,{response:t,abortController:e}),this._orchestrator.runWorker(r),i}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;;){const t=this._existingResponses.get(e);this._existingResponses.delete(e);let r=t?.abortController,i=t?.response;if(r||(r=new AbortController,i=await Ri(this._options.fetchFn??fetch,this._url,Pi(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay)),jr(i),!i.ok)throw new Error(`Error fetching ${String(this._url)}: ${i.status} ${i.statusText}`);if(e.currentPos>0&&206!==i.status)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");const a=this._getPartialLengthFromRangeResponse(i),n=e.targetPos-e.currentPos;if(a<n)throw new Error(`HTTP response unexpectedly too short: Needed at least ${n} bytes, got only ${a}.`);if(!i.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const s=i.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return r.abort(),void(e.running=!1);let t;try{t=await s.read()}catch(e){const t=this._getRetryDelay(1,e,this._url);if(null!==t){console.error("Error while reading response stream. Attempting to resume.",e),await new Promise(e=>setTimeout(e,1e3*t));break}throw e}if(e.aborted)break;const{done:i,value:a}=t;if(i){if(this._orchestrator.forgetWorker(e),e.currentPos<e.targetPos)throw new Error("Response stream reader stopped unexpectedly before all requested data was read.");return void(e.running=!1)}this.onread?.(e.currentPos,e.currentPos+a.length),this._orchestrator.supplyWorkerData(e,a)}if(e.aborted)break}e.running=!1}_getPartialLengthFromRangeResponse(e){const t=e.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e)return Number(e[1]);throw new Error(`Invalid Content-Range header: ${t}`)}{const t=e.headers.get("Content-Length");if(t)return Number(t);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}}_dispose(){this._orchestrator.dispose()}}class Fo extends Mo{constructor(e){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if("function"!=typeof e.getSize)throw new TypeError("options.getSize must be a function.");if("function"!=typeof e.read)throw new TypeError("options.read must be a function.");if(void 0!==e.dispose&&"function"!=typeof e.dispose)throw new TypeError("options.dispose, when provided, must be a function.");if(void 0!==e.maxCacheSize&&(!Hi(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super(),this._options=e,this._orchestrator=new Lo({maxCacheSize:e.maxCacheSize??8388608,maxWorkerCount:2,prefetchProfile:No[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_retrieveSize(){const e=this._options.getSize();if(e instanceof Promise)return e.then(e=>{if(!Number.isInteger(e)||e<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=e,e});if(!Number.isInteger(e)||e<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){const t=e.currentPos,r=e.targetPos;let i=this._options.read(e.currentPos,r);if(i instanceof Promise&&(i=await i),e.aborted)break;if(i instanceof Uint8Array){if(i=Qr(i),i.length!==r-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${r-e.currentPos} bytes, but got ${i.length}.`);this.onread?.(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{if(!(i instanceof ReadableStream))throw new TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.");{const a=i.getReader();for(;e.currentPos<r&&!e.aborted;){const{done:i,value:n}=await a.read();if(i){if(e.currentPos<r)throw new Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${r-t} bytes, but got ${e.currentPos-t}`);break}if(!(n instanceof Uint8Array))throw new TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;const s=Qr(n);this.onread?.(e.currentPos,e.currentPos+s.length),this._orchestrator.supplyWorkerData(e,s)}}}}e.running=!1}_dispose(){this._orchestrator.dispose(),this._options.dispose?.()}}const No={none:(e,t)=>({start:e,end:t}),fileSystem:(e,t)=>{const r=65536;return{start:e=Math.floor((e-r)/r)*r,end:t=Math.ceil((t+r)/r)*r}},network:(e,t,r)=>{const i=65536;e=Math.max(0,Math.floor((e-i)/i)*i);for(const i of r){const r=8388608,a=Math.max((i.startPos+i.targetPos)/2,i.targetPos-r);if(Ni(e,t,a,i.targetPos)){const e=i.targetPos-i.startPos,a=Math.ceil((e+1)/r)*r,n=2**Math.ceil(Math.log2(e+1)),s=Math.min(n,a);t=Math.max(t,i.startPos+s)}}return{start:e,end:t=Math.max(t,e+_o)}}};class Lo{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){jr(null!==this.fileSize);const r=this.options.prefetchProfile(e,t,this.workers),i=Math.max(r.start,0),a=Math.min(r.end,this.fileSize);jr(i<=e&&t<=a);let n=null;const s=mi(this.cache,e,e=>e.start),o=-1!==s?this.cache[s]:null;o&&o.start<=e&&t<=o.end&&(o.age=this.nextAge++,n={bytes:o.bytes,view:o.view,offset:o.start});const c=mi(this.cache,i,e=>e.start),l=n?null:new Uint8Array(t-e);let u=0,h=i;const d=[];if(-1!==c){for(let r=c;r<this.cache.length;r++){const n=this.cache[r];if(n.start>=a)break;if(n.end<=i)continue;const s=Math.max(i,n.start),o=Math.min(a,n.end);if(jr(s<=o),h<s&&d.push({start:h,end:s}),h=o,l){const r=Math.max(e,n.start),i=Math.min(t,n.end);if(r<i){const t=r-e;l.set(n.bytes.subarray(r-n.start,i-n.start),t),t===u&&(u=i-e)}}n.age=this.nextAge++}h<a&&d.push({start:h,end:a})}else d.push({start:i,end:a});if(l&&u>=l.length&&(n={bytes:l,view:Zr(l),offset:e}),0===d.length)return jr(n),n;const{promise:f,resolve:m,reject:p}=gi(),g=[];for(const r of d){const i=Math.max(e,r.start),a=Math.min(t,r.end);i===r.start&&a===r.end?g.push(r):i<a&&g.push({start:i,end:a})}for(const t of d){const r=l&&{start:e,bytes:l,holes:g,resolve:m,reject:p};let i=!1;for(const e of this.workers){const a=2**17;if(Ni(t.start-a,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end),i=!0,r&&!e.pendingSlices.includes(r)&&e.pendingSlices.push(r),e.running||this.runWorker(e);break}}if(!i){const e=this.createWorker(t.start,t.end);r&&(e.pendingSlices=[r]),this.runWorker(e)}}return n||(jr(l),n=f.then(t=>({bytes:t,view:Zr(t),offset:e}))),n}createWorker(e,t){const r={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(r);this.workers.length>this.options.maxWorkerCount;){let e=0,t=this.workers[0];for(let r=1;r<this.workers.length;r++){const i=this.workers[r];i.age<t.age&&(e=r,t=i)}if(t.running&&t.pendingSlices.length>0)break;t.aborted=!0,this.workers.splice(e,1)}return r}runWorker(e){jr(!e.running),jr(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,!(e.pendingSlices.length>0))throw t;e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0})}supplyWorkerData(e,t){jr(!e.aborted);const r=e.currentPos,i=r+t.length;this.insertIntoCache({start:r,end:i,bytes:t,view:Zr(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let a=0;a<e.pendingSlices.length;a++){const n=e.pendingSlices[a],s=Math.max(r,n.start),o=Math.min(i,n.start+n.bytes.length);s<o&&n.bytes.set(t.subarray(s-r,o-r),s-n.start);for(let e=0;e<n.holes.length;e++){const t=n.holes[e];r<=t.start&&i>t.start&&(t.start=i),t.end<=t.start&&(n.holes.splice(e,1),e--)}0===n.holes.length&&(n.resolve(n.bytes),e.pendingSlices.splice(a,1),a--)}for(let t=0;t<this.workers.length;t++){const a=this.workers[t];e===a||a.running||Ni(r,i,a.currentPos,a.targetPos)&&(this.workers.splice(t,1),t--)}}forgetWorker(e){const t=this.workers.indexOf(e);jr(-1!==t),this.workers.splice(t,1)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=mi(this.cache,e.start,e=>e.start)+1;if(t>0){const r=this.cache[t-1];if(r.end>=e.end)return;if(r.end>e.start){const i=new Uint8Array(e.end-r.start);i.set(r.bytes,0),i.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=i,r.view=Zr(i),r.end=e.end,t--,e=r}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let r=t+1;r<this.cache.length;r++){const t=this.cache[r];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(r,1),this.currentCacheSize-=t.bytes.length,r--;continue}const i=new Uint8Array(t.end-e.start);i.set(e.bytes,0),i.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=i,e.view=Zr(i),e.end=t.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let r=1;r<this.cache.length;r++){const i=this.cache[r];i.age<t.age&&(e=r,t=i)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(const e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}
201
+ class Ku{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new il;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new il;const e=await this.getSizeOrNull();if(null===e)throw new Error("Cannot determine the size of an unsized source.");return e}}const $u=524288,Qu=(e,t,r)=>{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))){let e=null;try{"undefined"!=typeof window&&void 0!==window.location&&(e=new URL(r instanceof Request?r.url:r,window.location.href).origin)}catch{}if(("undefined"==typeof navigator||"boolean"!=typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(e-2),16)};class Zu extends Ku{constructor(e,t={}){if(!("string"==typeof e||e instanceof URL||"undefined"!=typeof Request&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!=typeof t.requestInit))throw new TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!=typeof t.getRetryDelay)throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!Yn(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.fetchFn&&"function"!=typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Qu,this._orchestrator=new tl({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:el.network})}async _retrieveSize(){const e=new AbortController,t=await Pn(this._options.fetchFn??fetch,this._url,In(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!t.ok)throw new Error(`Error fetching ${String(this._url)}: ${t.status} ${t.statusText}`);let r,i;if(206===t.status)i=this._getTotalLengthFromRangeResponse(t),r=this._orchestrator.createWorker(0,Math.min(i,$u));else{const e=t.headers.get("Content-Length");if(!e)throw new Error(`HTTP response (status ${t.status}) must surface Content-Length header.`);i=Number(e),r=this._orchestrator.createWorker(0,i),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.")}return this._orchestrator.fileSize=i,this._existingResponses.set(r,{response:t,abortController:e}),this._orchestrator.runWorker(r),i}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;;){const t=this._existingResponses.get(e);this._existingResponses.delete(e);let r=t?.abortController,i=t?.response;if(r||(r=new AbortController,i=await Pn(this._options.fetchFn??fetch,this._url,In(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay,()=>this._disposed)),Xa(i),!i.ok)throw new Error(`Error fetching ${String(this._url)}: ${i.status} ${i.statusText}`);if(e.currentPos>0&&206!==i.status)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!i.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const a=i.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return r.abort(),void(e.running=!1);let t;try{t=await a.read()}catch(e){if(this._disposed)throw e;const t=this._getRetryDelay(1,e,this._url);if(null!==t){console.error("Error while reading response stream. Attempting to resume.",e),await new Promise(e=>setTimeout(e,1e3*t));break}throw e}if(e.aborted)continue;const{done:i,value:n}=t;if(i){if(e.currentPos>=e.targetPos)return this._orchestrator.forgetWorker(e),void(e.running=!1);break}this.onread?.(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}}}_getTotalLengthFromRangeResponse(e){const t=e.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e)return Number(e[1])}const r=e.headers.get("Content-Length");if(r)return Number(r);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}}class Ju extends Ku{constructor(e){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if("function"!=typeof e.getSize)throw new TypeError("options.getSize must be a function.");if("function"!=typeof e.read)throw new TypeError("options.read must be a function.");if(void 0!==e.dispose&&"function"!=typeof e.dispose)throw new TypeError("options.dispose, when provided, must be a function.");if(void 0!==e.maxCacheSize&&(!Yn(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super(),this._options=e,this._orchestrator=new tl({maxCacheSize:e.maxCacheSize??8388608,maxWorkerCount:2,prefetchProfile:el[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_retrieveSize(){const e=this._options.getSize();if(e instanceof Promise)return e.then(e=>{if(!Number.isInteger(e)||e<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=e,e});if(!Number.isInteger(e)||e<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){const t=e.currentPos,r=e.targetPos;let i=this._options.read(e.currentPos,r);if(i instanceof Promise&&(i=await i),e.aborted)break;if(i instanceof Uint8Array){if(i=Qa(i),i.length!==r-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${r-e.currentPos} bytes, but got ${i.length}.`);this.onread?.(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{if(!(i instanceof ReadableStream))throw new TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.");{const a=i.getReader();for(;e.currentPos<r&&!e.aborted;){const{done:i,value:n}=await a.read();if(i){if(e.currentPos<r)throw new Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${r-t} bytes, but got ${e.currentPos-t}`);break}if(!(n instanceof Uint8Array))throw new TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;const o=Qa(n);this.onread?.(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}}}}e.running=!1}_dispose(){this._orchestrator.dispose(),this._options.dispose?.()}}const el={none:(e,t)=>({start:e,end:t}),fileSystem:(e,t)=>{const r=65536;return{start:e=Math.floor((e-r)/r)*r,end:t=Math.ceil((t+r)/r)*r}},network:(e,t,r)=>{const i=65536;e=Math.max(0,Math.floor((e-i)/i)*i);for(const i of r){const r=8388608,a=Math.max((i.startPos+i.targetPos)/2,i.targetPos-r);if(Wn(e,t,a,i.targetPos)){const e=i.targetPos-i.startPos,a=Math.ceil((e+1)/r)*r,n=2**Math.ceil(Math.log2(e+1)),o=Math.min(n,a);t=Math.max(t,i.startPos+o)}}return{start:e,end:t=Math.max(t,e+$u)}}};class tl{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){Xa(null!==this.fileSize);const r=this.options.prefetchProfile(e,t,this.workers),i=Math.max(r.start,0),a=Math.min(r.end,this.fileSize);Xa(i<=e&&t<=a);let n=null;const o=pn(this.cache,e,e=>e.start),s=-1!==o?this.cache[o]:null;s&&s.start<=e&&t<=s.end&&(s.age=this.nextAge++,n={bytes:s.bytes,view:s.view,offset:s.start});const c=pn(this.cache,i,e=>e.start),u=n?null:new Uint8Array(t-e);let l=0,h=i;const d=[];if(-1!==c){for(let r=c;r<this.cache.length;r++){const n=this.cache[r];if(n.start>=a)break;if(n.end<=i)continue;const o=Math.max(i,n.start),s=Math.min(a,n.end);if(Xa(o<=s),h<o&&d.push({start:h,end:o}),h=s,u){const r=Math.max(e,n.start),i=Math.min(t,n.end);if(r<i){const t=r-e;u.set(n.bytes.subarray(r-n.start,i-n.start),t),t===l&&(l=i-e)}}n.age=this.nextAge++}h<a&&d.push({start:h,end:a})}else d.push({start:i,end:a});if(u&&l>=u.length&&(n={bytes:u,view:Za(u),offset:e}),0===d.length)return Xa(n),n;const{promise:f,resolve:m,reject:p}=vn(),g=[];for(const r of d){const i=Math.max(e,r.start),a=Math.min(t,r.end);i===r.start&&a===r.end?g.push(r):i<a&&g.push({start:i,end:a})}for(const t of d){const r=u&&{start:e,bytes:u,holes:g,resolve:m,reject:p};let i=!1;for(const e of this.workers){const a=2**17;if(Wn(t.start-a,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end),i=!0,r&&!e.pendingSlices.includes(r)&&e.pendingSlices.push(r),e.running||this.runWorker(e);break}}if(!i){const e=this.createWorker(t.start,t.end);r&&(e.pendingSlices=[r]),this.runWorker(e)}}return n||(Xa(u),n=f.then(t=>({bytes:t,view:Za(t),offset:e}))),n}createWorker(e,t){const r={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(r);this.workers.length>this.options.maxWorkerCount;){let e=0,t=this.workers[0];for(let r=1;r<this.workers.length;r++){const i=this.workers[r];i.age<t.age&&(e=r,t=i)}if(t.running&&t.pendingSlices.length>0)break;t.aborted=!0,this.workers.splice(e,1)}return r}runWorker(e){Xa(!e.running),Xa(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,!(e.pendingSlices.length>0))throw t;e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0})}supplyWorkerData(e,t){Xa(!e.aborted);const r=e.currentPos,i=r+t.length;this.insertIntoCache({start:r,end:i,bytes:t,view:Za(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let a=0;a<e.pendingSlices.length;a++){const n=e.pendingSlices[a],o=Math.max(r,n.start),s=Math.min(i,n.start+n.bytes.length);o<s&&n.bytes.set(t.subarray(o-r,s-r),o-n.start);for(let e=0;e<n.holes.length;e++){const t=n.holes[e];r<=t.start&&i>t.start&&(t.start=i),t.end<=t.start&&(n.holes.splice(e,1),e--)}0===n.holes.length&&(n.resolve(n.bytes),e.pendingSlices.splice(a,1),a--)}for(let t=0;t<this.workers.length;t++){const a=this.workers[t];e===a||a.running||Wn(r,i,a.currentPos,a.targetPos)&&(this.workers.splice(t,1),t--)}}forgetWorker(e){const t=this.workers.indexOf(e);Xa(-1!==t),this.workers.splice(t,1)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=pn(this.cache,e.start,e=>e.start)+1;if(t>0){const r=this.cache[t-1];if(r.end>=e.end)return;if(r.end>e.start){const i=new Uint8Array(e.end-r.start);i.set(r.bytes,0),i.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=i,r.view=Za(i),r.end=e.end,t--,e=r}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let r=t+1;r<this.cache.length;r++){const t=this.cache[r];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(r,1),this.currentCacheSize-=t.bytes.length,r--;continue}const i=new Uint8Array(t.end-e.start);i.set(e.bytes,0),i.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=i,e.view=Za(i),e.end=t.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let r=1;r<this.cache.length;r++){const i=this.cache[r];i.age<t.age&&(e=r,t=i)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(const e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}
202
202
  /*!
203
203
  * Copyright (c) 2025-present, Vanilagy and contributors
204
204
  *
205
205
  * This Source Code Form is subject to the terms of the Mozilla Public
206
206
  * License, v. 2.0. If a copy of the MPL was not distributed with this
207
207
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
208
- */Vi();let Uo=class{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof ho)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Mo))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new Wo(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(const e of this._formats){if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this)}throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),jr(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(e=>e.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(e=>e.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(e=>e.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(e=>e.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}};class zo extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}
208
+ */Gn();let rl=class{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof Mu)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ku))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new al(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(const e of this._formats){if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this)}throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),Xa(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(e=>e.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(e=>e.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(e=>e.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(e=>e.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}};class il extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}
209
209
  /*!
210
210
  * Copyright (c) 2025-present, Vanilagy and contributors
211
211
  *
212
212
  * This Source Code Form is subject to the terms of the Mozilla Public
213
213
  * License, v. 2.0. If a copy of the MPL was not distributed with this
214
214
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
215
- */class Wo{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new zo;if(null!==this.fileSize&&e+t>this.fileSize)return null;const r=e+t,i=this.source._read(e,r);return i instanceof Promise?i.then(t=>t?new Vo(t.bytes,t.view,t.offset,e,r):null):i?new Vo(i.bytes,i.view,i.offset,e,r):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new zo;if(null!==this.fileSize)return this.requestSlice(e,Ti(this.fileSize-e,t,r));{const i=this.requestSlice(e,r),a=i=>{if(i)return i;const a=i=>(jr(null!==i),this.requestSlice(e,Ti(i-e,t,r))),n=this.source._retrieveSize();return n instanceof Promise?n.then(a):a(n)};return i instanceof Promise?i.then(a):a(i)}}}class Vo{constructor(e,t,r,i,a){this.bytes=e,this.view=t,this.offset=r,this.start=i,this.end=a,this.bufferPos=i-r}static tempFromBytes(e){return new Vo(e,Zr(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new Vo(this.bytes,this.view,this.offset,e,e+t)}}const Ho=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw new RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},jo=(e,t)=>{Ho(e,t);const r=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,r},Xo=e=>(Ho(e,1),e.view.getUint8(e.bufferPos++)),qo=(e,t)=>{Ho(e,2);const r=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,r},Go=e=>{Ho(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Ko=e=>{Ho(e,3);const t=ki(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Yo=e=>{Ho(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},$o=(e,t)=>{Ho(e,4);const r=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,r},Qo=e=>{Ho(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Zo=e=>{Ho(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Jo=e=>{Ho(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},ec=(e,t)=>{let r,i;return t?(r=$o(e,!0),i=$o(e,!0)):(i=$o(e,!1),r=$o(e,!1)),4294967296*i+r},tc=e=>4294967296*Qo(e)+Qo(e),rc=e=>4294967296*Jo(e)+Qo(e),ic=e=>{const t=Zo(e),r=(e=>{Ho(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*r+t},ac=e=>{Ho(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},nc=e=>{Ho(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},sc=(e,t)=>{Ho(e,t);let r="";for(let i=0;i<t;i++)r+=String.fromCharCode(e.bytes[e.bufferPos++]);return r},oc=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,cc=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,lc=e=>{const t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4),i=Math.floor(e%6e4/1e3),a=e%1e3;return t.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};
215
+ */class al{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new il;if(null!==this.fileSize&&e+t>this.fileSize)return null;const r=e+t,i=this.source._read(e,r);return i instanceof Promise?i.then(t=>t?new nl(t.bytes,t.view,t.offset,e,r):null):i?new nl(i.bytes,i.view,i.offset,e,r):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new il;if(null!==this.fileSize)return this.requestSlice(e,kn(this.fileSize-e,t,r));{const i=this.requestSlice(e,r),a=i=>{if(i)return i;const a=i=>(Xa(null!==i),this.requestSlice(e,kn(i-e,t,r))),n=this.source._retrieveSize();return n instanceof Promise?n.then(a):a(n)};return i instanceof Promise?i.then(a):a(i)}}}class nl{constructor(e,t,r,i,a){this.bytes=e,this.view=t,this.offset=r,this.start=i,this.end=a,this.bufferPos=i-r}static tempFromBytes(e){return new nl(e,Za(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new nl(this.bytes,this.view,this.offset,e,e+t)}}const ol=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw new RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},sl=(e,t)=>{ol(e,t);const r=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,r},cl=e=>(ol(e,1),e.view.getUint8(e.bufferPos++)),ul=(e,t)=>{ol(e,2);const r=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,r},ll=e=>{ol(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},hl=e=>{ol(e,3);const t=Tn(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},dl=e=>{ol(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},fl=(e,t)=>{ol(e,4);const r=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,r},ml=e=>{ol(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},pl=e=>{ol(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},gl=e=>{ol(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},vl=(e,t)=>{let r,i;return t?(r=fl(e,!0),i=fl(e,!0)):(i=fl(e,!1),r=fl(e,!1)),4294967296*i+r},yl=e=>4294967296*ml(e)+ml(e),bl=e=>4294967296*gl(e)+ml(e),xl=e=>{const t=pl(e),r=(e=>{ol(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*r+t},Tl=e=>{ol(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},wl=e=>{ol(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},kl=(e,t)=>{ol(e,t);let r="";for(let i=0;i<t;i++)r+=String.fromCharCode(e.bytes[e.bufferPos++]);return r},Sl=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,El=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Cl=e=>{const t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4),i=Math.floor(e%6e4/1e3),a=e%1e3;return t.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};
216
216
  /*!
217
217
  * Copyright (c) 2025-present, Vanilagy and contributors
218
218
  *
@@ -220,7 +220,7 @@ class Mo{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null
220
220
  * License, v. 2.0. If a copy of the MPL was not distributed with this
221
221
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
222
222
  */
223
- class uc{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const t of e.children)t&&this.writeBox(t);const r=this.writer.getPos(),i=e.size??r-t;this.writer.seek(t),this.writeBoxHeader(e,i),this.writer.seek(r)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const t=this.offsets.get(e);jr(void 0!==t);const r=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(r)}measureBox(e){if(e.contents&&!e.children){return this.measureBoxHeader(e)+e.contents.byteLength}{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const r of e.children)r&&(t+=this.measureBox(r));return t}}}const hc=new Uint8Array(8),dc=new DataView(hc.buffer),fc=e=>[(e%256+256)%256],mc=e=>(dc.setUint16(0,e,!1),[hc[0],hc[1]]),pc=e=>(dc.setInt16(0,e,!1),[hc[0],hc[1]]),gc=e=>(dc.setUint32(0,e,!1),[hc[1],hc[2],hc[3]]),vc=e=>(dc.setUint32(0,e,!1),[hc[0],hc[1],hc[2],hc[3]]),yc=e=>(dc.setInt32(0,e,!1),[hc[0],hc[1],hc[2],hc[3]]),bc=e=>(dc.setUint32(0,Math.floor(e/2**32),!1),dc.setUint32(4,e,!1),[hc[0],hc[1],hc[2],hc[3],hc[4],hc[5],hc[6],hc[7]]),kc=e=>(dc.setInt16(0,256*e,!1),[hc[0],hc[1]]),Tc=e=>(dc.setInt32(0,65536*e,!1),[hc[0],hc[1],hc[2],hc[3]]),wc=e=>(dc.setInt32(0,2**30*e,!1),[hc[0],hc[1],hc[2],hc[3]]),Sc=(e,t)=>{const r=[];let i=e;do{let e=127&i;i>>=7,r.length>0&&(e|=128),r.push(e)}while(i>0||t);return r.reverse()},xc=(e,t=!1)=>{const r=Array(e.length).fill(null).map((t,r)=>e.charCodeAt(r));return t&&r.push(0),r},Cc=e=>{let t=null;for(const r of e)(!t||r.timestamp>t.timestamp)&&(t=r);return t},Ec=e=>{const t=e*(Math.PI/180),r=Math.round(Math.cos(t)),i=Math.round(Math.sin(t));return[r,i,0,-i,r,0,0,0,1]},Ac=Ec(0),Pc=e=>[Tc(e[0]),Tc(e[1]),wc(e[2]),Tc(e[3]),Tc(e[4]),wc(e[5]),Tc(e[6]),Tc(e[7]),wc(e[8])],Ic=(e,t,r)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:r}),Rc=(e,t,r,i,a)=>Ic(e,[fc(t),gc(r),i??[]],a),Oc=e=>({type:"mdat",largeSize:e}),Mc=e=>Ic("moov",void 0,[_c(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>Dc(t,e.creationTime)),e.isFragmented?fl(e.trackDatas):null,Al(e)]),_c=(e,t)=>{const r=$l(Math.max(0,...t.filter(e=>e.samples.length>0).map(e=>{const t=Cc(e.samples);return t.timestamp+t.duration})),Kl),i=Math.max(0,...t.map(e=>e.track.id))+1,a=!Gr(e)||!Gr(r),n=a?bc:vc;return Rc("mvhd",+a,0,[n(e),n(e),vc(Kl),n(r),Tc(1),kc(1),Array(10).fill(0),Pc(Ac),Array(24).fill(0),vc(i)])},Dc=(e,t)=>{const r=Yl(e);return Ic("trak",void 0,[Bc(e,t),Fc(e,t),void 0!==r.name?Ic("udta",void 0,[Ic("name",[...ei.encode(r.name)])]):null])},Bc=(e,t)=>{const r=Cc(e.samples),i=$l(r?r.timestamp+r.duration:0,Kl),a=!Gr(t)||!Gr(i),n=a?bc:vc;let s;if("video"===e.type){const t=e.track.metadata.rotation;s=Ec(t??0)}else s=Ac;let o=2;return!1!==e.track.metadata.disposition?.default&&(o|=1),Rc("tkhd",+a,o,[n(t),n(t),vc(e.track.id),vc(0),n(i),Array(8).fill(0),mc(0),mc(e.track.id),kc("audio"===e.type?1:0),mc(0),Pc(s),Tc("video"===e.type?e.info.width:0),Tc("video"===e.type?e.info.height:0)])},Fc=(e,t)=>Ic("mdia",void 0,[Nc(e,t),zc(!0,Lc[e.type],Uc[e.type]),Wc(e)]),Nc=(e,t)=>{const r=Cc(e.samples),i=$l(r?r.timestamp+r.duration:0,e.timescale),a=!Gr(t)||!Gr(i),n=a?bc:vc;return Rc("mdhd",+a,0,[n(t),n(t),vc(e.timescale),n(i),mc(Wl(e.track.metadata.languageCode??wi)),mc(0)])},Lc={video:"vide",audio:"soun",subtitle:"text"},Uc={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},zc=(e,t,r,i="\0\0\0\0")=>Rc("hdlr",0,0,[e?xc("mhlr"):vc(0),xc(t),xc(i),vc(0),vc(0),xc(r,!0)]),Wc=e=>Ic("minf",void 0,[Vc[e.type](),Hc(),qc(e)]),Vc={video:()=>Rc("vmhd",0,1,[mc(0),mc(0),mc(0),mc(0)]),audio:()=>Rc("smhd",0,0,[mc(0),mc(0)]),subtitle:()=>Rc("nmhd",0,0)},Hc=()=>Ic("dinf",void 0,[jc()]),jc=()=>Rc("dref",0,0,[vc(1)],[Xc()]),Xc=()=>Rc("url ",0,1),qc=e=>{const t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>0!==e.sampleCompositionTimeOffset);return Ic("stbl",void 0,[Gc(e),sl(e),t?hl(e):null,t?dl(e):null,cl(e),ll(e),ul(e),ol(e)])},Gc=e=>{let t;if("video"===e.type)t=Kc(Bl(e.track.source._codec,e.info.decoderConfig.codec),e);else if("audio"===e.type){const r=Nl(e.track.source._codec,e.muxer.isQuickTime);jr(r),t=Qc(r,e)}else"subtitle"===e.type&&(t=nl(Ul[e.track.source._codec],e));return jr(t),Rc("stsd",0,0,[vc(1)],[t])},Kc=(e,t)=>Ic(e,[Array(6).fill(0),mc(1),mc(0),mc(0),Array(12).fill(0),mc(t.info.width),mc(t.info.height),vc(4718592),vc(4718592),vc(0),mc(1),Array(32).fill(0),mc(24),pc(65535)],[Fl[t.track.source._codec](t),ci(t.info.decoderConfig.colorSpace)?Yc(t):null]),Yc=e=>Ic("colr",[xc("nclx"),mc(ri[e.info.decoderConfig.colorSpace.primaries]),mc(ai[e.info.decoderConfig.colorSpace.transfer]),mc(si[e.info.decoderConfig.colorSpace.matrix]),fc((e.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),$c=e=>{if(!e.info.decoderConfig)return null;const t=e.info.decoderConfig,r=t.codec.split("."),i=Number(r[1]),a=Number(r[2]),n=(Number(r[3])<<4)+((r[4]?Number(r[4]):1)<<1)+(r[8]?Number(r[8]):Number(t.colorSpace?.fullRange??0)),s=r[5]?Number(r[5]):t.colorSpace?.primaries?ri[t.colorSpace.primaries]:2,o=r[6]?Number(r[6]):t.colorSpace?.transfer?ai[t.colorSpace.transfer]:2,c=r[7]?Number(r[7]):t.colorSpace?.matrix?si[t.colorSpace.matrix]:2;return Rc("vpcC",1,0,[fc(i),fc(a),fc(n),fc(s),fc(o),fc(c),mc(0)])},Qc=(e,t)=>{let r,i=0,a=16;if(Ki.includes(t.track.source._codec)){const e=t.track.source._codec,{sampleSize:r}=ua(e);a=8*r,a>16&&(i=1)}return r=0===i?[Array(6).fill(0),mc(1),mc(i),mc(0),vc(0),mc(t.info.numberOfChannels),mc(a),mc(0),mc(0),mc(t.info.sampleRate<65536?t.info.sampleRate:0),mc(0)]:[Array(6).fill(0),mc(1),mc(i),mc(0),vc(0),mc(t.info.numberOfChannels),mc(Math.min(a,16)),mc(0),mc(0),mc(t.info.sampleRate<65536?t.info.sampleRate:0),mc(0),vc(1),vc(a/8),vc(t.info.numberOfChannels*a/8),vc(2)],Ic(e,r,[Ll(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},Zc=e=>{let t;switch(e.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw new Error(`Unhandled audio codec: ${e.track.source._codec}`)}let r=[...fc(t),...fc(21),...gc(0),...vc(0),...vc(0)];if(e.info.decoderConfig.description){const t=Qr(e.info.decoderConfig.description);r=[...r,...fc(5),...Sc(t.byteLength),...t]}return r=[...mc(1),...fc(0),...fc(4),...Sc(r.length),...r,...fc(6),...fc(1),...fc(2)],r=[...fc(3),...Sc(r.length),...r],Rc("esds",0,0,r)},Jc=e=>Ic("wave",void 0,[el(e),tl(e),Ic("\0\0\0\0")]),el=e=>Ic("frma",[xc(Nl(e.track.source._codec,e.muxer.isQuickTime))]),tl=e=>{const{littleEndian:t}=ua(e.track.source._codec);return Ic("enda",[mc(+t)])},rl=e=>{let t=e.info.numberOfChannels,r=3840,i=e.info.sampleRate,a=0,n=0,s=new Uint8Array(0);const o=e.info.decoderConfig?.description;if(o){jr(o.byteLength>=18);const e=Qr(o),c=Va(e);t=c.outputChannelCount,r=c.preSkip,i=c.inputSampleRate,a=c.outputGain,n=c.channelMappingFamily,c.channelMappingTable&&(s=c.channelMappingTable)}return Ic("dOps",[fc(0),fc(t),mc(r),vc(i),pc(a),fc(n),...s])},il=e=>{const t=e.info.decoderConfig?.description;jr(t);const r=Qr(t);return Rc("dfLa",0,0,[...r.subarray(4)])},al=e=>{const{littleEndian:t,sampleSize:r}=ua(e.track.source._codec);return Rc("pcmC",0,0,[fc(+t),fc(8*r)])},nl=(e,t)=>Ic(e,[Array(6).fill(0),mc(1)],[zl[t.track.source._codec](t)]),sl=e=>Rc("stts",0,0,[vc(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[vc(e.sampleCount),vc(e.sampleDelta)])]),ol=e=>{if(e.samples.every(e=>"key"===e.type))return null;const t=[...e.samples.entries()].filter(([,e])=>"key"===e.type);return Rc("stss",0,0,[vc(t.length),t.map(([e])=>vc(e+1))])},cl=e=>Rc("stsc",0,0,[vc(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[vc(e.firstChunk),vc(e.samplesPerChunk),vc(1)])]),ll=e=>{if("audio"===e.type&&e.info.requiresPcmTransformation){const{sampleSize:t}=ua(e.track.source._codec);return Rc("stsz",0,0,[vc(t*e.info.numberOfChannels),vc(e.samples.reduce((t,r)=>t+$l(r.duration,e.timescale),0))])}return Rc("stsz",0,0,[vc(0),vc(e.samples.length),e.samples.map(e=>vc(e.size))])},ul=e=>e.finalizedChunks.length>0&&qr(e.finalizedChunks).offset>=2**32?Rc("co64",0,0,[vc(e.finalizedChunks.length),e.finalizedChunks.map(e=>bc(e.offset))]):Rc("stco",0,0,[vc(e.finalizedChunks.length),e.finalizedChunks.map(e=>vc(e.offset))]),hl=e=>Rc("ctts",1,0,[vc(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[vc(e.sampleCount),yc(e.sampleCompositionTimeOffset)])]),dl=e=>{let t=1/0,r=-1/0,i=1/0,a=-1/0;jr(e.compositionTimeOffsetTable.length>0),jr(e.samples.length>0);for(let i=0;i<e.compositionTimeOffsetTable.length;i++){const a=e.compositionTimeOffsetTable[i];t=Math.min(t,a.sampleCompositionTimeOffset),r=Math.max(r,a.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){const r=e.samples[t];i=Math.min(i,$l(r.timestamp,e.timescale)),a=Math.max(a,$l(r.timestamp+r.duration,e.timescale))}const n=Math.max(-t,0);return a>=2**31?null:Rc("cslg",0,0,[yc(n),yc(t),yc(r),yc(i),yc(a)])},fl=e=>Ic("mvex",void 0,e.map(ml)),ml=e=>Rc("trex",0,0,[vc(e.track.id),vc(1),vc(0),vc(0),vc(0)]),pl=(e,t)=>Ic("moof",void 0,[gl(e),...t.map(yl)]),gl=e=>Rc("mfhd",0,0,[vc(e)]),vl=e=>{let t=0,r=0;const i="delta"===e.type;return r|=+i,t|=i?1:2,t<<24|r<<16},yl=e=>Ic("traf",void 0,[bl(e),kl(e),Tl(e)]),bl=e=>{jr(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;const r=e.currentChunk.samples[1]??e.currentChunk.samples[0],i={duration:r.timescaleUnitsToNextSample,size:r.size,flags:vl(r)};return Rc("tfhd",0,131128,[vc(e.track.id),vc(i.duration),vc(i.size),vc(i.flags)])},kl=e=>(jr(e.currentChunk),Rc("tfdt",1,0,[bc($l(e.currentChunk.startTimestamp,e.timescale))])),Tl=e=>{jr(e.currentChunk);const t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),r=e.currentChunk.samples.map(e=>e.size),i=e.currentChunk.samples.map(vl),a=e.currentChunk.samples.map(t=>$l(t.timestamp-t.decodeTimestamp,e.timescale)),n=new Set(t),s=new Set(r),o=new Set(i),c=new Set(a),l=2===o.size&&i[0]!==i[1],u=n.size>1,h=s.size>1,d=!l&&o.size>1,f=c.size>1||[...c].some(e=>0!==e);let m=0;return m|=1,m|=4*+l,m|=256*+u,m|=512*+h,m|=1024*+d,m|=2048*+f,Rc("trun",1,m,[vc(e.currentChunk.samples.length),vc(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?vc(i[0]):[],e.currentChunk.samples.map((e,n)=>[u?vc(t[n]):[],h?vc(r[n]):[],d?vc(i[n]):[],f?yc(a[n]):[]])])},wl=(e,t)=>Rc("tfra",1,0,[vc(e.track.id),vc(63),vc(e.finalizedChunks.length),e.finalizedChunks.map(r=>[bc($l(r.samples[0].timestamp,e.timescale)),bc(r.moofOffset),vc(t+1),vc(1),vc(1)])]),Sl=()=>Rc("mfro",0,0,[vc(0)]),xl=()=>Ic("vtte"),Cl=(e,t,r,i,a)=>Ic("vttc",void 0,[null!==a?Ic("vsid",[yc(a)]):null,null!==r?Ic("iden",[...ei.encode(r)]):null,null!==t?Ic("ctim",[...ei.encode(lc(t))]):null,null!==i?Ic("sttg",[...ei.encode(i)]):null,Ic("payl",[...ei.encode(e)])]),El=e=>Ic("vtta",[...ei.encode(e)]),Al=e=>{const t=[],r=e.format._options.metadataFormat??"auto",i=e.output._metadataTags;if("mdir"===r||"auto"===r&&!e.isQuickTime){const e=Ml(i);e&&t.push(e)}else if("mdta"===r){const e=_l(i);e&&t.push(e)}else("udta"===r||"auto"===r&&e.isQuickTime)&&Pl(t,e.output._metadataTags);return 0===t.length?null:Ic("udta",void 0,t)},Pl=(e,t)=>{for(const{key:r,value:i}of Li(t))switch(r){case"title":e.push(Il("©nam",i));break;case"description":e.push(Il("©des",i));break;case"artist":e.push(Il("©ART",i));break;case"album":e.push(Il("©alb",i));break;case"albumArtist":e.push(Il("albr",i));break;case"genre":e.push(Il("©gen",i));break;case"date":e.push(Il("©day",i.toISOString().slice(0,10)));break;case"comment":e.push(Il("©cmt",i));break;case"lyrics":e.push(Il("©lyr",i));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:bi(r)}if(t.raw)for(const r in t.raw){const i=t.raw[r];null==i||4!==r.length||e.some(e=>e.type===r)||("string"==typeof i?e.push(Il(r,i)):i instanceof Uint8Array&&e.push(Ic(r,Array.from(i))))}},Il=(e,t)=>{const r=ei.encode(t);return Ic(e,[mc(r.length),mc(Wl("und")),Array.from(r)])},Rl={"image/jpeg":13,"image/png":14,"image/bmp":27},Ol=(e,t)=>{const r=[];for(const{key:i,value:a}of Li(e))switch(i){case"title":r.push({key:t?"title":"©nam",value:Dl(a)});break;case"description":r.push({key:t?"description":"©des",value:Dl(a)});break;case"artist":r.push({key:t?"artist":"©ART",value:Dl(a)});break;case"album":r.push({key:t?"album":"©alb",value:Dl(a)});break;case"albumArtist":r.push({key:t?"album_artist":"aART",value:Dl(a)});break;case"comment":r.push({key:t?"comment":"©cmt",value:Dl(a)});break;case"genre":r.push({key:t?"genre":"©gen",value:Dl(a)});break;case"lyrics":r.push({key:t?"lyrics":"©lyr",value:Dl(a)});break;case"date":r.push({key:t?"date":"©day",value:Dl(a.toISOString().slice(0,10))});break;case"images":for(const e of a)"coverFront"===e.kind&&r.push({key:"covr",value:Ic("data",[vc(Rl[e.mimeType]??0),vc(0),Array.from(e.data)])});break;case"trackNumber":if(t){const t=void 0!==e.tracksTotal?`${a}/${e.tracksTotal}`:a.toString();r.push({key:"track",value:Dl(t)})}else r.push({key:"trkn",value:Ic("data",[vc(0),vc(0),mc(0),mc(a),mc(e.tracksTotal??0),mc(0)])});break;case"discNumber":t||r.push({key:"disc",value:Ic("data",[vc(0),vc(0),mc(0),mc(a),mc(e.discsTotal??0),mc(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:bi(i)}if(e.raw)for(const i in e.raw){const a=e.raw[i];null==a||!t&&4!==i.length||r.some(e=>e.key===i)||("string"==typeof a?r.push({key:i,value:Dl(a)}):a instanceof Uint8Array?r.push({key:i,value:Ic("data",[vc(0),vc(0),Array.from(a)])}):a instanceof ji&&r.push({key:i,value:Ic("data",[vc(Rl[a.mimeType]??0),vc(0),Array.from(a.data)])}))}return r},Ml=e=>{const t=Ol(e,!1);return 0===t.length?null:Rc("meta",0,0,void 0,[zc(!1,"mdir","","appl"),Ic("ilst",void 0,t.map(e=>Ic(e.key,void 0,[e.value])))])},_l=e=>{const t=Ol(e,!0);return 0===t.length?null:Ic("meta",void 0,[zc(!1,"mdta",""),Rc("keys",0,0,[vc(t.length)],t.map(e=>Ic("mdta",[...ei.encode(e.key)]))),Ic("ilst",void 0,t.map((e,t)=>{const r=String.fromCharCode(...vc(t+1));return Ic(r,void 0,[e.value])}))])},Dl=e=>Ic("data",[vc(1),vc(0),...ei.encode(e)]),Bl=(e,t)=>{switch(e){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},Fl={avc:e=>e.info.decoderConfig&&Ic("avcC",[...Qr(e.info.decoderConfig.description)]),hevc:e=>e.info.decoderConfig&&Ic("hvcC",[...Qr(e.info.decoderConfig.description)]),vp8:$c,vp9:$c,av1:e=>Ic("av1C",ra(e.info.decoderConfig.codec))},Nl=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return"mp4a";case"opus":return"Opus";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt"}if(t)switch(e){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":case"pcm-s24be":return"in24";case"pcm-s32":case"pcm-s32be":return"in32";case"pcm-f32":case"pcm-f32be":return"fl32";case"pcm-f64":case"pcm-f64be":return"fl64"}else switch(e){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":return"ipcm";case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return"fpcm"}},Ll=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return Zc;case"opus":return rl;case"flac":return il}if(t)switch(e){case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return Jc}else switch(e){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return al}return null},Ul={webvtt:"wvtt"},zl={webvtt:e=>Ic("vttC",[...ei.encode(e.info.config.description)])},Wl=e=>{jr(3===e.length);let t=0;for(let r=0;r<3;r++)t<<=5,t+=e.charCodeAt(r)-96;return t};
223
+ class Al{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const t of e.children)t&&this.writeBox(t);const r=this.writer.getPos(),i=e.size??r-t;this.writer.seek(t),this.writeBoxHeader(e,i),this.writer.seek(r)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const t=this.offsets.get(e);Xa(void 0!==t);const r=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(r)}measureBox(e){if(e.contents&&!e.children){return this.measureBoxHeader(e)+e.contents.byteLength}{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const r of e.children)r&&(t+=this.measureBox(r));return t}}}const _l=new Uint8Array(8),Ml=new DataView(_l.buffer),Il=e=>[(e%256+256)%256],Rl=e=>(Ml.setUint16(0,e,!1),[_l[0],_l[1]]),Pl=e=>(Ml.setInt16(0,e,!1),[_l[0],_l[1]]),Ol=e=>(Ml.setUint32(0,e,!1),[_l[1],_l[2],_l[3]]),Dl=e=>(Ml.setUint32(0,e,!1),[_l[0],_l[1],_l[2],_l[3]]),Bl=e=>(Ml.setInt32(0,e,!1),[_l[0],_l[1],_l[2],_l[3]]),Fl=e=>(Ml.setUint32(0,Math.floor(e/2**32),!1),Ml.setUint32(4,e,!1),[_l[0],_l[1],_l[2],_l[3],_l[4],_l[5],_l[6],_l[7]]),Ll=e=>(Ml.setInt16(0,256*e,!1),[_l[0],_l[1]]),Nl=e=>(Ml.setInt32(0,65536*e,!1),[_l[0],_l[1],_l[2],_l[3]]),Ul=e=>(Ml.setInt32(0,2**30*e,!1),[_l[0],_l[1],_l[2],_l[3]]),zl=(e,t)=>{const r=[];let i=e;do{let e=127&i;i>>=7,r.length>0&&(e|=128),r.push(e)}while(i>0||t);return r.reverse()},Wl=(e,t=!1)=>{const r=Array(e.length).fill(null).map((t,r)=>e.charCodeAt(r));return t&&r.push(0),r},Vl=e=>{let t=null;for(const r of e)(!t||r.timestamp>t.timestamp)&&(t=r);return t},Hl=e=>{const t=e*(Math.PI/180),r=Math.round(Math.cos(t)),i=Math.round(Math.sin(t));return[r,i,0,-i,r,0,0,0,1]},Xl=Hl(0),jl=e=>[Nl(e[0]),Nl(e[1]),Ul(e[2]),Nl(e[3]),Nl(e[4]),Ul(e[5]),Nl(e[6]),Nl(e[7]),Ul(e[8])],Gl=(e,t,r)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:r}),Yl=(e,t,r,i,a)=>Gl(e,[Il(t),Ol(r),i??[]],a),ql=e=>({type:"mdat",largeSize:e}),Kl=e=>Gl("moov",void 0,[$l(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>Ql(t,e.creationTime)),e.isFragmented?Ih(e.trackDatas):null,Xh(e)]),$l=(e,t)=>{const r=fd(Math.max(0,...t.filter(e=>e.samples.length>0).map(e=>{const t=Vl(e.samples);return t.timestamp+t.duration})),hd),i=Math.max(0,...t.map(e=>e.track.id))+1,a=!Ya(e)||!Ya(r),n=a?Fl:Dl;return Yl("mvhd",+a,0,[n(e),n(e),Dl(hd),n(r),Nl(1),Ll(1),Array(10).fill(0),jl(Xl),Array(24).fill(0),Dl(i)])},Ql=(e,t)=>{const r=dd(e);return Gl("trak",void 0,[Zl(e,t),Jl(e,t),void 0!==r.name?Gl("udta",void 0,[Gl("name",[...en.encode(r.name)])]):null])},Zl=(e,t)=>{const r=Vl(e.samples),i=fd(r?r.timestamp+r.duration:0,hd),a=!Ya(t)||!Ya(i),n=a?Fl:Dl;let o;if("video"===e.type){const t=e.track.metadata.rotation;o=Hl(t??0)}else o=Xl;let s=2;return!1!==e.track.metadata.disposition?.default&&(s|=1),Yl("tkhd",+a,s,[n(t),n(t),Dl(e.track.id),Dl(0),n(i),Array(8).fill(0),Rl(0),Rl(e.track.id),Ll("audio"===e.type?1:0),Rl(0),jl(o),Nl("video"===e.type?e.info.width:0),Nl("video"===e.type?e.info.height:0)])},Jl=(e,t)=>Gl("mdia",void 0,[eh(e,t),ih(!0,th[e.type],rh[e.type]),ah(e)]),eh=(e,t)=>{const r=Vl(e.samples),i=fd(r?r.timestamp+r.duration:0,e.timescale),a=!Ya(t)||!Ya(i),n=a?Fl:Dl;return Yl("mdhd",+a,0,[n(t),n(t),Dl(e.timescale),n(i),Rl(ad(e.track.metadata.languageCode??Sn)),Rl(0)])},th={video:"vide",audio:"soun",subtitle:"text"},rh={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},ih=(e,t,r,i="\0\0\0\0")=>Yl("hdlr",0,0,[e?Wl("mhlr"):Dl(0),Wl(t),Wl(i),Dl(0),Dl(0),Wl(r,!0)]),ah=e=>Gl("minf",void 0,[nh[e.type](),oh(),uh(e)]),nh={video:()=>Yl("vmhd",0,1,[Rl(0),Rl(0),Rl(0),Rl(0)]),audio:()=>Yl("smhd",0,0,[Rl(0),Rl(0)]),subtitle:()=>Yl("nmhd",0,0)},oh=()=>Gl("dinf",void 0,[sh()]),sh=()=>Yl("dref",0,0,[Dl(1)],[ch()]),ch=()=>Yl("url ",0,1),uh=e=>{const t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>0!==e.sampleCompositionTimeOffset);return Gl("stbl",void 0,[lh(e),kh(e),t?_h(e):null,t?Mh(e):null,Eh(e),Ch(e),Ah(e),Sh(e)])},lh=e=>{let t;if("video"===e.type)t=hh(Zh(e.track.source._codec,e.info.decoderConfig.codec),e);else if("audio"===e.type){const r=ed(e.track.source._codec,e.muxer.isQuickTime);Xa(r),t=mh(r,e)}else"subtitle"===e.type&&(t=wh(rd[e.track.source._codec],e));return Xa(t),Yl("stsd",0,0,[Dl(1)],[t])},hh=(e,t)=>Gl(e,[Array(6).fill(0),Rl(1),Rl(0),Rl(0),Array(12).fill(0),Rl(t.info.width),Rl(t.info.height),Dl(4718592),Dl(4718592),Dl(0),Rl(1),Array(32).fill(0),Rl(24),Pl(65535)],[Jh[t.track.source._codec](t),un(t.info.decoderConfig.colorSpace)?dh(t):null]),dh=e=>Gl("colr",[Wl("nclx"),Rl(rn[e.info.decoderConfig.colorSpace.primaries]),Rl(nn[e.info.decoderConfig.colorSpace.transfer]),Rl(sn[e.info.decoderConfig.colorSpace.matrix]),Il((e.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),fh=e=>{if(!e.info.decoderConfig)return null;const t=e.info.decoderConfig,r=t.codec.split("."),i=Number(r[1]),a=Number(r[2]),n=(Number(r[3])<<4)+((r[4]?Number(r[4]):1)<<1)+(r[8]?Number(r[8]):Number(t.colorSpace?.fullRange??0)),o=r[5]?Number(r[5]):t.colorSpace?.primaries?rn[t.colorSpace.primaries]:2,s=r[6]?Number(r[6]):t.colorSpace?.transfer?nn[t.colorSpace.transfer]:2,c=r[7]?Number(r[7]):t.colorSpace?.matrix?sn[t.colorSpace.matrix]:2;return Yl("vpcC",1,0,[Il(i),Il(a),Il(n),Il(o),Il(s),Il(c),Rl(0)])},mh=(e,t)=>{let r,i=0,a=16;if(Zn.includes(t.track.source._codec)){const e=t.track.source._codec,{sampleSize:r}=po(e);a=8*r,a>16&&(i=1)}return r=0===i?[Array(6).fill(0),Rl(1),Rl(i),Rl(0),Dl(0),Rl(t.info.numberOfChannels),Rl(a),Rl(0),Rl(0),Rl(t.info.sampleRate<65536?t.info.sampleRate:0),Rl(0)]:[Array(6).fill(0),Rl(1),Rl(i),Rl(0),Dl(0),Rl(t.info.numberOfChannels),Rl(Math.min(a,16)),Rl(0),Rl(0),Rl(t.info.sampleRate<65536?t.info.sampleRate:0),Rl(0),Dl(1),Dl(a/8),Dl(t.info.numberOfChannels*a/8),Dl(2)],Gl(e,r,[td(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},ph=e=>{let t;switch(e.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw new Error(`Unhandled audio codec: ${e.track.source._codec}`)}let r=[...Il(t),...Il(21),...Ol(0),...Dl(0),...Dl(0)];if(e.info.decoderConfig.description){const t=Qa(e.info.decoderConfig.description);r=[...r,...Il(5),...zl(t.byteLength),...t]}return r=[...Rl(1),...Il(0),...Il(4),...zl(r.length),...r,...Il(6),...Il(1),...Il(2)],r=[...Il(3),...zl(r.length),...r],Yl("esds",0,0,r)},gh=e=>Gl("wave",void 0,[vh(e),yh(e),Gl("\0\0\0\0")]),vh=e=>Gl("frma",[Wl(ed(e.track.source._codec,e.muxer.isQuickTime))]),yh=e=>{const{littleEndian:t}=po(e.track.source._codec);return Gl("enda",[Rl(+t)])},bh=e=>{let t=e.info.numberOfChannels,r=3840,i=e.info.sampleRate,a=0,n=0,o=new Uint8Array(0);const s=e.info.decoderConfig?.description;if(s){Xa(s.byteLength>=18);const e=Qa(s),c=Qo(e);t=c.outputChannelCount,r=c.preSkip,i=c.inputSampleRate,a=c.outputGain,n=c.channelMappingFamily,c.channelMappingTable&&(o=c.channelMappingTable)}return Gl("dOps",[Il(0),Il(t),Rl(r),Dl(i),Pl(a),Il(n),...o])},xh=e=>{const t=e.info.decoderConfig?.description;Xa(t);const r=Qa(t);return Yl("dfLa",0,0,[...r.subarray(4)])},Th=e=>{const{littleEndian:t,sampleSize:r}=po(e.track.source._codec);return Yl("pcmC",0,0,[Il(+t),Il(8*r)])},wh=(e,t)=>Gl(e,[Array(6).fill(0),Rl(1)],[id[t.track.source._codec](t)]),kh=e=>Yl("stts",0,0,[Dl(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[Dl(e.sampleCount),Dl(e.sampleDelta)])]),Sh=e=>{if(e.samples.every(e=>"key"===e.type))return null;const t=[...e.samples.entries()].filter(([,e])=>"key"===e.type);return Yl("stss",0,0,[Dl(t.length),t.map(([e])=>Dl(e+1))])},Eh=e=>Yl("stsc",0,0,[Dl(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[Dl(e.firstChunk),Dl(e.samplesPerChunk),Dl(1)])]),Ch=e=>{if("audio"===e.type&&e.info.requiresPcmTransformation){const{sampleSize:t}=po(e.track.source._codec);return Yl("stsz",0,0,[Dl(t*e.info.numberOfChannels),Dl(e.samples.reduce((t,r)=>t+fd(r.duration,e.timescale),0))])}return Yl("stsz",0,0,[Dl(0),Dl(e.samples.length),e.samples.map(e=>Dl(e.size))])},Ah=e=>e.finalizedChunks.length>0&&Ga(e.finalizedChunks).offset>=2**32?Yl("co64",0,0,[Dl(e.finalizedChunks.length),e.finalizedChunks.map(e=>Fl(e.offset))]):Yl("stco",0,0,[Dl(e.finalizedChunks.length),e.finalizedChunks.map(e=>Dl(e.offset))]),_h=e=>Yl("ctts",1,0,[Dl(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[Dl(e.sampleCount),Bl(e.sampleCompositionTimeOffset)])]),Mh=e=>{let t=1/0,r=-1/0,i=1/0,a=-1/0;Xa(e.compositionTimeOffsetTable.length>0),Xa(e.samples.length>0);for(let i=0;i<e.compositionTimeOffsetTable.length;i++){const a=e.compositionTimeOffsetTable[i];t=Math.min(t,a.sampleCompositionTimeOffset),r=Math.max(r,a.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){const r=e.samples[t];i=Math.min(i,fd(r.timestamp,e.timescale)),a=Math.max(a,fd(r.timestamp+r.duration,e.timescale))}const n=Math.max(-t,0);return a>=2**31?null:Yl("cslg",0,0,[Bl(n),Bl(t),Bl(r),Bl(i),Bl(a)])},Ih=e=>Gl("mvex",void 0,e.map(Rh)),Rh=e=>Yl("trex",0,0,[Dl(e.track.id),Dl(1),Dl(0),Dl(0),Dl(0)]),Ph=(e,t)=>Gl("moof",void 0,[Oh(e),...t.map(Bh)]),Oh=e=>Yl("mfhd",0,0,[Dl(e)]),Dh=e=>{let t=0,r=0;const i="delta"===e.type;return r|=+i,t|=i?1:2,t<<24|r<<16},Bh=e=>Gl("traf",void 0,[Fh(e),Lh(e),Nh(e)]),Fh=e=>{Xa(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;const r=e.currentChunk.samples[1]??e.currentChunk.samples[0],i={duration:r.timescaleUnitsToNextSample,size:r.size,flags:Dh(r)};return Yl("tfhd",0,131128,[Dl(e.track.id),Dl(i.duration),Dl(i.size),Dl(i.flags)])},Lh=e=>(Xa(e.currentChunk),Yl("tfdt",1,0,[Fl(fd(e.currentChunk.startTimestamp,e.timescale))])),Nh=e=>{Xa(e.currentChunk);const t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),r=e.currentChunk.samples.map(e=>e.size),i=e.currentChunk.samples.map(Dh),a=e.currentChunk.samples.map(t=>fd(t.timestamp-t.decodeTimestamp,e.timescale)),n=new Set(t),o=new Set(r),s=new Set(i),c=new Set(a),u=2===s.size&&i[0]!==i[1],l=n.size>1,h=o.size>1,d=!u&&s.size>1,f=c.size>1||[...c].some(e=>0!==e);let m=0;return m|=1,m|=4*+u,m|=256*+l,m|=512*+h,m|=1024*+d,m|=2048*+f,Yl("trun",1,m,[Dl(e.currentChunk.samples.length),Dl(e.currentChunk.offset-e.currentChunk.moofOffset||0),u?Dl(i[0]):[],e.currentChunk.samples.map((e,n)=>[l?Dl(t[n]):[],h?Dl(r[n]):[],d?Dl(i[n]):[],f?Bl(a[n]):[]])])},Uh=(e,t)=>Yl("tfra",1,0,[Dl(e.track.id),Dl(63),Dl(e.finalizedChunks.length),e.finalizedChunks.map(r=>[Fl(fd(r.samples[0].timestamp,e.timescale)),Fl(r.moofOffset),Dl(t+1),Dl(1),Dl(1)])]),zh=()=>Yl("mfro",0,0,[Dl(0)]),Wh=()=>Gl("vtte"),Vh=(e,t,r,i,a)=>Gl("vttc",void 0,[null!==a?Gl("vsid",[Bl(a)]):null,null!==r?Gl("iden",[...en.encode(r)]):null,null!==t?Gl("ctim",[...en.encode(Cl(t))]):null,null!==i?Gl("sttg",[...en.encode(i)]):null,Gl("payl",[...en.encode(e)])]),Hh=e=>Gl("vtta",[...en.encode(e)]),Xh=e=>{const t=[],r=e.format._options.metadataFormat??"auto",i=e.output._metadataTags;if("mdir"===r||"auto"===r&&!e.isQuickTime){const e=Kh(i);e&&t.push(e)}else if("mdta"===r){const e=$h(i);e&&t.push(e)}else("udta"===r||"auto"===r&&e.isQuickTime)&&jh(t,e.output._metadataTags);return 0===t.length?null:Gl("udta",void 0,t)},jh=(e,t)=>{for(const{key:r,value:i}of Vn(t))switch(r){case"title":e.push(Gh("©nam",i));break;case"description":e.push(Gh("©des",i));break;case"artist":e.push(Gh("©ART",i));break;case"album":e.push(Gh("©alb",i));break;case"albumArtist":e.push(Gh("albr",i));break;case"genre":e.push(Gh("©gen",i));break;case"date":e.push(Gh("©day",i.toISOString().slice(0,10)));break;case"comment":e.push(Gh("©cmt",i));break;case"lyrics":e.push(Gh("©lyr",i));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:xn(r)}if(t.raw)for(const r in t.raw){const i=t.raw[r];null==i||4!==r.length||e.some(e=>e.type===r)||("string"==typeof i?e.push(Gh(r,i)):i instanceof Uint8Array&&e.push(Gl(r,Array.from(i))))}},Gh=(e,t)=>{const r=en.encode(t);return Gl(e,[Rl(r.length),Rl(ad("und")),Array.from(r)])},Yh={"image/jpeg":13,"image/png":14,"image/bmp":27},qh=(e,t)=>{const r=[];for(const{key:i,value:a}of Vn(e))switch(i){case"title":r.push({key:t?"title":"©nam",value:Qh(a)});break;case"description":r.push({key:t?"description":"©des",value:Qh(a)});break;case"artist":r.push({key:t?"artist":"©ART",value:Qh(a)});break;case"album":r.push({key:t?"album":"©alb",value:Qh(a)});break;case"albumArtist":r.push({key:t?"album_artist":"aART",value:Qh(a)});break;case"comment":r.push({key:t?"comment":"©cmt",value:Qh(a)});break;case"genre":r.push({key:t?"genre":"©gen",value:Qh(a)});break;case"lyrics":r.push({key:t?"lyrics":"©lyr",value:Qh(a)});break;case"date":r.push({key:t?"date":"©day",value:Qh(a.toISOString().slice(0,10))});break;case"images":for(const e of a)"coverFront"===e.kind&&r.push({key:"covr",value:Gl("data",[Dl(Yh[e.mimeType]??0),Dl(0),Array.from(e.data)])});break;case"trackNumber":if(t){const t=void 0!==e.tracksTotal?`${a}/${e.tracksTotal}`:a.toString();r.push({key:"track",value:Qh(t)})}else r.push({key:"trkn",value:Gl("data",[Dl(0),Dl(0),Rl(0),Rl(a),Rl(e.tracksTotal??0),Rl(0)])});break;case"discNumber":t||r.push({key:"disc",value:Gl("data",[Dl(0),Dl(0),Rl(0),Rl(a),Rl(e.discsTotal??0),Rl(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:xn(i)}if(e.raw)for(const i in e.raw){const a=e.raw[i];null==a||!t&&4!==i.length||r.some(e=>e.key===i)||("string"==typeof a?r.push({key:i,value:Qh(a)}):a instanceof Uint8Array?r.push({key:i,value:Gl("data",[Dl(0),Dl(0),Array.from(a)])}):a instanceof qn&&r.push({key:i,value:Gl("data",[Dl(Yh[a.mimeType]??0),Dl(0),Array.from(a.data)])}))}return r},Kh=e=>{const t=qh(e,!1);return 0===t.length?null:Yl("meta",0,0,void 0,[ih(!1,"mdir","","appl"),Gl("ilst",void 0,t.map(e=>Gl(e.key,void 0,[e.value])))])},$h=e=>{const t=qh(e,!0);return 0===t.length?null:Gl("meta",void 0,[ih(!1,"mdta",""),Yl("keys",0,0,[Dl(t.length)],t.map(e=>Gl("mdta",[...en.encode(e.key)]))),Gl("ilst",void 0,t.map((e,t)=>{const r=String.fromCharCode(...Dl(t+1));return Gl(r,void 0,[e.value])}))])},Qh=e=>Gl("data",[Dl(1),Dl(0),...en.encode(e)]),Zh=(e,t)=>{switch(e){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},Jh={avc:e=>e.info.decoderConfig&&Gl("avcC",[...Qa(e.info.decoderConfig.description)]),hevc:e=>e.info.decoderConfig&&Gl("hvcC",[...Qa(e.info.decoderConfig.description)]),vp8:fh,vp9:fh,av1:e=>Gl("av1C",oo(e.info.decoderConfig.codec))},ed=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return"mp4a";case"opus":return"Opus";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt"}if(t)switch(e){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":case"pcm-s24be":return"in24";case"pcm-s32":case"pcm-s32be":return"in32";case"pcm-f32":case"pcm-f32be":return"fl32";case"pcm-f64":case"pcm-f64be":return"fl64"}else switch(e){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":return"ipcm";case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return"fpcm"}},td=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return ph;case"opus":return bh;case"flac":return xh}if(t)switch(e){case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return gh}else switch(e){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return Th}return null},rd={webvtt:"wvtt"},id={webvtt:e=>Gl("vttC",[...en.encode(e.info.config.description)])},ad=e=>{Xa(3===e.length);let t=0;for(let r=0;r<3;r++)t<<=5,t+=e.charCodeAt(r)-96;return t};
224
224
  /*!
225
225
  * Copyright (c) 2025-present, Vanilagy and contributors
226
226
  *
@@ -228,47 +228,47 @@ class uc{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperV
228
228
  * License, v. 2.0. If a copy of the MPL was not distributed with this
229
229
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
230
230
  */
231
- class Vl{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}const r=t+e.byteLength-this.trackedStart;let i=this.trackedWrites.byteLength;for(;i<r;)i*=2;if(i!==this.trackedWrites.byteLength){const e=new Uint8Array(i);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}}const Hl=65536,jl=2**32;class Xl extends Vl{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(Hl,{maxByteLength:jl})}catch{this.buffer=new ArrayBuffer(Hl),this.supportsResize=!1}else this.buffer=new ArrayBuffer(Hl);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let t=this.buffer.byteLength;for(;t<e;)t*=2;if(t!==this.buffer.byteLength){if(t>jl)throw new Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this.supportsResize)this.buffer.resize(t);else{const e=new ArrayBuffer(t),r=new Uint8Array(e);r.set(this.bytes,0),this.buffer=e,this.bytes=r}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,t){return this.bytes.slice(e,t)}}
231
+ class nd{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}const r=t+e.byteLength-this.trackedStart;let i=this.trackedWrites.byteLength;for(;i<r;)i*=2;if(i!==this.trackedWrites.byteLength){const e=new Uint8Array(i);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}}const od=65536,sd=2**32;class cd extends nd{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(od,{maxByteLength:sd})}catch{this.buffer=new ArrayBuffer(od),this.supportsResize=!1}else this.buffer=new ArrayBuffer(od);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let t=this.buffer.byteLength;for(;t<e;)t*=2;if(t!==this.buffer.byteLength){if(t>sd)throw new Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this.supportsResize)this.buffer.resize(t);else{const e=new ArrayBuffer(t),r=new Uint8Array(e);r.set(this.bytes,0),this.buffer=e,this.bytes=r}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,t){return this.bytes.slice(e,t)}}
232
232
  /*!
233
233
  * Copyright (c) 2025-present, Vanilagy and contributors
234
234
  *
235
235
  * This Source Code Form is subject to the terms of the Mozilla Public
236
236
  * License, v. 2.0. If a copy of the MPL was not distributed with this
237
237
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
238
- */class ql{constructor(){this._output=null,this.onwrite=null}}class Gl extends ql{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new Xl(this)}}
238
+ */class ud{constructor(){this._output=null,this.onwrite=null}}class ld extends ud{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new cd(this)}}
239
239
  /*!
240
240
  * Copyright (c) 2025-present, Vanilagy and contributors
241
241
  *
242
242
  * This Source Code Form is subject to the terms of the Mozilla Public
243
243
  * License, v. 2.0. If a copy of the MPL was not distributed with this
244
244
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
245
- */const Kl=1e3,Yl=e=>{const t={},r=e.track;return void 0!==r.metadata.name&&(t.name=r.metadata.name),t},$l=(e,t,r=!0)=>{const i=e*t;return r?Math.round(i):i};class Ql extends ka{constructor(e,t){super(e),this.auxTarget=new Gl,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new uc(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=gi(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=t,this.writer=e._writer,this.boxWriter=new uc(this.writer),this.isQuickTime=t instanceof au;const r=this.writer instanceof Xl&&"in-memory";this.fastStart=t._options.fastStart??r,this.isFragmented="fragmented"===this.fastStart,("in-memory"===this.fastStart||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=t._options.minimumFragmentDuration??1}async start(){const e=await this.mutex.acquire(),t=this.output._tracks.some(e=>"video"===e.type&&"avc"===e.source._codec);if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox((r={isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented}).isQuickTime?Ic("ftyp",[xc("qt "),vc(512),xc("qt ")]):r.fragmented?Ic("ftyp",[xc("iso5"),vc(512),xc("iso5"),xc("iso6"),xc("mp41")]):Ic("ftyp",[xc("isom"),vc(512),xc("isom"),r.holdsAvc?xc("avc1"):[],xc("mp41")])),this.format._options.onFtyp){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onFtyp(e,t)}var r;if(this.ftypSize=this.writer.getPos(),"in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(const e of this.output._tracks)if(void 0===e.metadata.maximumPacketCount)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Oc(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(e=>{if("video"===e.type)return e.info.decoderConfig.codec;if("audio"===e.type)return e.info.decoderConfig.codec;return{webvtt:"wvtt"}[e.track.source._codec]});return An({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>"video"===e.type),hasAudio:this.trackDatas.some(e=>"audio"===e.type),codecStrings:e})}getVideoTrackData(e,t,r){const i=this.trackDatas.find(t=>t.track===e);if(i)return i;ga(r),jr(r),jr(r.decoderConfig);const a={...r.decoderConfig};jr(void 0!==a.codedWidth),jr(void 0!==a.codedHeight);let n=!1;if("avc"!==e.source._codec||a.description){if("hevc"===e.source._codec&&!a.description){const e=Oa(t.data);if(!e)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");a.description=(e=>{const t=[];t.push(e.configurationVersion),t.push((3&e.generalProfileSpace)<<6|(1&e.generalTierFlag)<<5|31&e.generalProfileIdc),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(255&e.generalProfileCompatibilityFlags),t.push(...e.generalConstraintIndicatorFlags),t.push(255&e.generalLevelIdc),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(255&e.minSpatialSegmentationIdc),t.push(252|3&e.parallelismType),t.push(252|3&e.chromaFormatIdc),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.avgFrameRate>>8&255),t.push(255&e.avgFrameRate),t.push((3&e.constantFrameRate)<<6|(7&e.numTemporalLayers)<<3|(1&e.temporalIdNested)<<2|3&e.lengthSizeMinusOne),t.push(255&e.arrays.length);for(const r of e.arrays){t.push((1&r.arrayCompleteness)<<7|63&r.nalUnitType),t.push(r.nalUnits.length>>8&255),t.push(255&r.nalUnits.length);for(const e of r.nalUnits){t.push(e.length>>8&255),t.push(255&e.length);for(let r=0;r<e.length;r++)t.push(e[r])}}return new Uint8Array(t)})(e),n=!0}}else{const e=Aa(t.data);if(!e)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");a.description=(e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const r of e.sequenceParameterSets){const e=r.byteLength;t.push(e>>8),t.push(255&e);for(let i=0;i<e;i++)t.push(r[i])}t.push(e.pictureParameterSets.length);for(const r of e.pictureParameterSets){const e=r.byteLength;t.push(e>>8),t.push(255&e);for(let i=0;i<e;i++)t.push(r[i])}if(100===e.avcProfileIndication||110===e.avcProfileIndication||122===e.avcProfileIndication||144===e.avcProfileIndication){jr(null!==e.chromaFormat),jr(null!==e.bitDepthLumaMinus8),jr(null!==e.bitDepthChromaMinus8),jr(null!==e.sequenceParameterSetExt),t.push(252|3&e.chromaFormat),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.sequenceParameterSetExt.length);for(const r of e.sequenceParameterSetExt){const e=r.byteLength;t.push(e>>8),t.push(255&e);for(let i=0;i<e;i++)t.push(r[i])}}return new Uint8Array(t)})(e),n=!0}const s=((e,t)=>{const r=e<0?-1:1;let i=0,a=1,n=1,s=0,o=e=Math.abs(e);for(;;){const e=Math.floor(o),c=e*n+i,l=e*s+a;if(l>t)return{numerator:r*n,denominator:s};if(i=n,a=s,n=c,s=l,o=1/(o-e),!isFinite(o))break}return{numerator:r*n,denominator:s}})(1/(e.metadata.frameRate??57600),1e6).denominator,o={muxer:this,track:e,type:"video",info:{width:a.codedWidth,height:a.codedHeight,decoderConfig:a,requiresAnnexBTransformation:n},timescale:s,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getAudioTrackData(e,t){const r=this.trackDatas.find(t=>t.track===e);if(r)return r;ya(t),jr(t),jr(t.decoderConfig);const i={muxer:this,track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig,requiresPcmTransformation:!this.isFragmented&&Ki.includes(e.source._codec)},timescale:t.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}getSubtitleTrackData(e,t){const r=this.trackDatas.find(t=>t.track===e);if(r)return r;ba(t),jr(t),jr(t.config);const i={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,r){const i=await this.mutex.acquire();try{const i=this.getVideoTrackData(e,t,r);let a=t.data;if(i.info.requiresAnnexBTransformation){const e=(e=>{const t=Sa(e);if(0===t.length)return null;let r=0;for(const e of t)r+=4+e.byteLength;const i=new Uint8Array(r),a=new DataView(i.buffer);let n=0;for(const e of t){const t=e.byteLength;a.setUint32(n,t,!1),n+=4,i.set(e,n),n+=e.byteLength}return i})(a);if(!e)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=e}const n=this.validateAndNormalizeTimestamp(i.track,t.timestamp,"key"===t.type),s=this.createSampleForTrack(i,a,n,t.duration,t.type);await this.registerSample(i,s)}finally{i()}}async addEncodedAudioPacket(e,t,r){const i=await this.mutex.acquire();try{const i=this.getAudioTrackData(e,r),a=this.validateAndNormalizeTimestamp(i.track,t.timestamp,"key"===t.type),n=this.createSampleForTrack(i,t.data,a,t.duration,t.type);i.info.requiresPcmTransformation&&await this.maybePadWithSilence(i,a),await this.registerSample(i,n)}finally{i()}}async maybePadWithSilence(e,t){const r=qr(e.samples),i=r?r.timestamp+r.duration:0,a=t-i,n=$l(a,e.timescale);if(n>0){const{sampleSize:t,silentValue:r}=ua(e.info.decoderConfig.codec),s=n*e.info.numberOfChannels,o=new Uint8Array(t*s).fill(r),c=this.createSampleForTrack(e,new Uint8Array(o.buffer),i,a,"key");await this.registerSample(e,c)}}async addSubtitleCue(e,t,r){const i=await this.mutex.acquire();try{const i=this.getSubtitleTrackData(e,r);this.validateAndNormalizeTimestamp(i.track,t.timestamp,!0),"webvtt"===e.source._codec&&(i.cueQueue.push(t),await this.processWebVTTCues(i,t.timestamp))}finally{i()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const r=new Set([]);for(const i of e.cueQueue)jr(i.timestamp<=t),jr(e.lastCueEndTimestamp<=i.timestamp+i.duration),r.add(Math.max(i.timestamp,e.lastCueEndTimestamp)),r.add(i.timestamp+i.duration);const i=[...r].sort((e,t)=>e-t),a=i[0],n=i[1]??a;if(t<n)break;if(e.lastCueEndTimestamp<a){this.auxWriter.seek(0);const t=xl();this.auxBoxWriter.writeBox(t);const r=this.auxWriter.getSlice(0,this.auxWriter.getPos()),i=this.createSampleForTrack(e,r,e.lastCueEndTimestamp,a-e.lastCueEndTimestamp,"key");await this.registerSample(e,i),e.lastCueEndTimestamp=a}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){const r=e.cueQueue[t];if(r.timestamp>=n)break;oc.lastIndex=0;const i=oc.test(r.text),s=r.timestamp+r.duration;let o=e.cueToSourceId.get(r);if(void 0===o&&n<s&&(o=e.nextSourceId++,e.cueToSourceId.set(r,o)),r.notes){const e=El(r.notes);this.auxBoxWriter.writeBox(e)}const c=Cl(r.text,i?a:null,r.identifier??null,r.settings??null,o??null);this.auxBoxWriter.writeBox(c),s===n&&e.cueQueue.splice(t--,1)}const s=this.auxWriter.getSlice(0,this.auxWriter.getPos()),o=this.createSampleForTrack(e,s,a,n-a,"key");await this.registerSample(e,o),e.lastCueEndTimestamp=n}}createSampleForTrack(e,t,r,i,a){return{timestamp:r,decodeTimestamp:r,duration:i,data:t,size:t.byteLength,type:a,timescaleUnitsToNextSample:$l(i,e.timescale)}}processTimestamps(e,t){if(0===e.timestampProcessingQueue.length)return;if("audio"===e.type&&e.info.requiresPcmTransformation){let t=0;for(let r=0;r<e.timestampProcessingQueue.length;r++){const i=e.timestampProcessingQueue[r];t+=$l(i.duration,e.timescale)}if(0===e.timeToSampleTable.length)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{qr(e.timeToSampleTable).sampleCount+=t}return void(e.timestampProcessingQueue.length=0)}const r=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);for(let t=0;t<e.timestampProcessingQueue.length;t++){const i=e.timestampProcessingQueue[t];i.decodeTimestamp=r[t],this.isFragmented||null!==e.lastTimescaleUnits||(i.decodeTimestamp=0);const a=$l(i.timestamp-i.decodeTimestamp,e.timescale),n=$l(i.duration,e.timescale);if(null!==e.lastTimescaleUnits){jr(e.lastSample);const t=$l(i.decodeTimestamp,e.timescale,!1),r=Math.round(t-e.lastTimescaleUnits);if(jr(r>=0),e.lastTimescaleUnits+=r,e.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let t=qr(e.timeToSampleTable);if(jr(t),1===t.sampleCount){t.sampleDelta=r;const i=e.timeToSampleTable[e.timeToSampleTable.length-2];i&&i.sampleDelta===r&&(i.sampleCount++,e.timeToSampleTable.pop(),t=i)}else t.sampleDelta!==r&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:r}));t.sampleDelta===n?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:n});const i=qr(e.compositionTimeOffsetTable);jr(i),i.sampleCompositionTimeOffset===a?i.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=$l(i.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:n}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=i}if(e.timestampProcessingQueue.length=0,jr(e.lastSample),jr(null!==e.lastTimescaleUnits),void 0!==t&&0===e.lastSample.timescaleUnitsToNextSample){jr("key"===t.type);const r=$l(t.timestamp,e.timescale,!1),i=Math.round(r-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=i}}async registerSample(e,t){"key"===t.type&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):"reserve"===this.fastStart?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),"reserve"===this.fastStart)){const t=e.track.metadata.maximumPacketCount;if(jr(void 0!==t),e.samples.length>t)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let r=!1;if(e.currentChunk){e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const i=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const a=this.trackDatas.every(r=>{if(e===r)return"key"===t.type;const i=r.sampleQueue[0];return i?"key"===i.type:r.track.source._closed});i>=this.minimumFragmentDuration&&a&&t.timestamp>this.maxWrittenTimestamp&&(r=!0,await this.finalizeFragment())}else r=i>=.5}else r=!0;r&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),jr(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(jr(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if("audio"===e.type&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,r)=>t+$l(r.duration,e.timescale),0)),0!==e.compactlyCodedChunkTable.length&&qr(e.compactlyCodedChunkTable).samplesPerChunk===t||e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),"in-memory"!==this.fastStart){e.currentChunk.offset=this.writer.getPos();for(const t of e.currentChunk.samples)jr(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}else e.currentChunk.offset=0}async interleaveSamples(e=!1){if(jr(this.isFragmented),e||this.allTracksAreKnown())e:for(;;){let t=null,r=1/0;for(const i of this.trackDatas){if(!e&&0===i.sampleQueue.length&&!i.track.source._closed)break e;i.sampleQueue.length>0&&i.sampleQueue[0].timestamp<r&&(t=i,r=i.sampleQueue[0].timestamp)}if(!t)break;const i=t.sampleQueue.shift();await this.addSampleToTrack(t,i)}}async finalizeFragment(e=!0){jr(this.isFragmented);const t=this.nextFragmentNumber++;if(1===t){this.format._options.onMoov&&this.writer.startTrackingWrites();const e=Mc(this);if(this.boxWriter.writeBox(e),this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}const r=this.trackDatas.filter(e=>e.currentChunk),i=pl(t,r),a=this.writer.getPos(),n=a+this.boxWriter.measureBox(i);let s=n+8,o=1/0;for(const e of r){e.currentChunk.offset=s,e.currentChunk.moofOffset=a;for(const t of e.currentChunk.samples)s+=t.size;o=Math.min(o,e.currentChunk.startTimestamp)}const c=s-n,l=c>=2**32;if(l)for(const e of r)e.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();const u=pl(t,r);if(this.boxWriter.writeBox(u),this.format._options.onMoof){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,o)}jr(this.writer.getPos()===n),this.format._options.onMdat&&this.writer.startTrackingWrites();const h=Oc(l);h.size=c,this.boxWriter.writeBox(h),this.writer.seek(n+(l?Pn:8));for(const e of r)for(const t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(const e of r)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(this.allTracksAreKnown()){if(!this.mdat){const e=Mc(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;jr(null!==this.ftypSize),this.writer.seek(this.ftypSize+t),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Oc(!0),this.boxWriter.writeBox(this.mdat);for(const e of this.trackDatas){for(const t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){jr("reserve"===this.fastStart);let e=0;for(const t of this.trackDatas){const r=t.track.metadata.maximumPacketCount;jr(void 0!==r),e+=8*Math.ceil(2/3*r),e+=4*r,e+=8*Math.ceil(2/3*r),e+=12*Math.ceil(2/3*r),e+=4*r,e+=8*r}return e}async onTrackClose(e){const t=await this.mutex.acquire();if("subtitle"===e.type&&"webvtt"===e.source._codec){const t=this.trackDatas.find(t=>t.track===e);t&&await this.processWebVTTCues(t,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const e of this.trackDatas)"subtitle"===e.type&&"webvtt"===e.track.source._codec&&await this.processWebVTTCues(e,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const e of this.trackDatas)this.processTimestamps(e);await this.finalizeFragment(!1)}else for(const e of this.trackDatas)this.processTimestamps(e),await this.finalizeCurrentChunk(e);if("in-memory"===this.fastStart){let e;this.mdat=Oc(!1);for(let t=0;t<2;t++){const t=Mc(this),r=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let i=this.writer.getPos()+r+e;for(const t of this.finalizedChunks){t.offset=i;for(const{data:r}of t.samples)jr(r),i+=r.byteLength,e+=r.byteLength}if(i<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const t=Mc(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(const e of this.finalizedChunks)for(const t of e.samples)jr(t.data),this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}}else if(this.isFragmented){const e=this.writer.getPos(),r=(t=this.trackDatas,Ic("mfra",void 0,[...t.map(wl),Sl()]));this.boxWriter.writeBox(r);const i=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(i)}else{jr(this.mdat);const e=this.boxWriter.offsets.get(this.mdat);jr(void 0!==e);const t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}const r=Mc(this);if("reserve"===this.fastStart){jr(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);const e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:e})}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);if(this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}var t;e()}}
245
+ */const hd=1e3,dd=e=>{const t={},r=e.track;return void 0!==r.metadata.name&&(t.name=r.metadata.name),t},fd=(e,t,r=!0)=>{const i=e*t;return r?Math.round(i):i};class md extends Eo{constructor(e,t){super(e),this.auxTarget=new ld,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new Al(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=vn(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=t,this.writer=e._writer,this.boxWriter=new Al(this.writer),this.isQuickTime=t instanceof Td;const r=this.writer instanceof cd&&"in-memory";this.fastStart=t._options.fastStart??r,this.isFragmented="fragmented"===this.fastStart,("in-memory"===this.fastStart||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=t._options.minimumFragmentDuration??1}async start(){const e=await this.mutex.acquire(),t=this.output._tracks.some(e=>"video"===e.type&&"avc"===e.source._codec);if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox((r={isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented}).isQuickTime?Gl("ftyp",[Wl("qt "),Dl(512),Wl("qt ")]):r.fragmented?Gl("ftyp",[Wl("iso5"),Dl(512),Wl("iso5"),Wl("iso6"),Wl("mp41")]):Gl("ftyp",[Wl("isom"),Dl(512),Wl("isom"),r.holdsAvc?Wl("avc1"):[],Wl("mp41")])),this.format._options.onFtyp){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onFtyp(e,t)}var r;if(this.ftypSize=this.writer.getPos(),"in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(const e of this.output._tracks)if(void 0===e.metadata.maximumPacketCount)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=ql(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(e=>{if("video"===e.type)return e.info.decoderConfig.codec;if("audio"===e.type)return e.info.decoderConfig.codec;return{webvtt:"wvtt"}[e.track.source._codec]});return js({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>"video"===e.type),hasAudio:this.trackDatas.some(e=>"audio"===e.type),codecStrings:e})}getVideoTrackData(e,t,r){const i=this.trackDatas.find(t=>t.track===e);if(i)return i;To(r),Xa(r),Xa(r.decoderConfig);const a={...r.decoderConfig};Xa(void 0!==a.codedWidth),Xa(void 0!==a.codedHeight);let n=!1;if("avc"!==e.source._codec||a.description){if("hevc"===e.source._codec&&!a.description){const e=zo(t.data);if(!e)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");a.description=(e=>{const t=[];t.push(e.configurationVersion),t.push((3&e.generalProfileSpace)<<6|(1&e.generalTierFlag)<<5|31&e.generalProfileIdc),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(255&e.generalProfileCompatibilityFlags),t.push(...e.generalConstraintIndicatorFlags),t.push(255&e.generalLevelIdc),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(255&e.minSpatialSegmentationIdc),t.push(252|3&e.parallelismType),t.push(252|3&e.chromaFormatIdc),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.avgFrameRate>>8&255),t.push(255&e.avgFrameRate),t.push((3&e.constantFrameRate)<<6|(7&e.numTemporalLayers)<<3|(1&e.temporalIdNested)<<2|3&e.lengthSizeMinusOne),t.push(255&e.arrays.length);for(const r of e.arrays){t.push((1&r.arrayCompleteness)<<7|63&r.nalUnitType),t.push(r.nalUnits.length>>8&255),t.push(255&r.nalUnits.length);for(const e of r.nalUnits){t.push(e.length>>8&255),t.push(255&e.length);for(let r=0;r<e.length;r++)t.push(e[r])}}return new Uint8Array(t)})(e),n=!0}}else{const e=Fo(t.data);if(!e)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");a.description=(e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const r of e.sequenceParameterSets){const e=r.byteLength;t.push(e>>8),t.push(255&e);for(let i=0;i<e;i++)t.push(r[i])}t.push(e.pictureParameterSets.length);for(const r of e.pictureParameterSets){const e=r.byteLength;t.push(e>>8),t.push(255&e);for(let i=0;i<e;i++)t.push(r[i])}if(100===e.avcProfileIndication||110===e.avcProfileIndication||122===e.avcProfileIndication||144===e.avcProfileIndication){Xa(null!==e.chromaFormat),Xa(null!==e.bitDepthLumaMinus8),Xa(null!==e.bitDepthChromaMinus8),Xa(null!==e.sequenceParameterSetExt),t.push(252|3&e.chromaFormat),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.sequenceParameterSetExt.length);for(const r of e.sequenceParameterSetExt){const e=r.byteLength;t.push(e>>8),t.push(255&e);for(let i=0;i<e;i++)t.push(r[i])}}return new Uint8Array(t)})(e),n=!0}const o=((e,t)=>{const r=e<0?-1:1;let i=0,a=1,n=1,o=0,s=e=Math.abs(e);for(;;){const e=Math.floor(s),c=e*n+i,u=e*o+a;if(u>t)return{numerator:r*n,denominator:o};if(i=n,a=o,n=c,o=u,s=1/(s-e),!isFinite(s))break}return{numerator:r*n,denominator:o}})(1/(e.metadata.frameRate??57600),1e6).denominator,s={muxer:this,track:e,type:"video",info:{width:a.codedWidth,height:a.codedHeight,decoderConfig:a,requiresAnnexBTransformation:n},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(s),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getAudioTrackData(e,t){const r=this.trackDatas.find(t=>t.track===e);if(r)return r;ko(t),Xa(t),Xa(t.decoderConfig);const i={muxer:this,track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig,requiresPcmTransformation:!this.isFragmented&&Zn.includes(e.source._codec)},timescale:t.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}getSubtitleTrackData(e,t){const r=this.trackDatas.find(t=>t.track===e);if(r)return r;So(t),Xa(t),Xa(t.config);const i={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,r){const i=await this.mutex.acquire();try{const i=this.getVideoTrackData(e,t,r);let a=t.data;if(i.info.requiresAnnexBTransformation){const e=_o(a);if(0===e.length)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=Po(e,4)}const n=this.validateAndNormalizeTimestamp(i.track,t.timestamp,"key"===t.type),o=this.createSampleForTrack(i,a,n,t.duration,t.type);await this.registerSample(i,o)}finally{i()}}async addEncodedAudioPacket(e,t,r){const i=await this.mutex.acquire();try{const i=this.getAudioTrackData(e,r),a=this.validateAndNormalizeTimestamp(i.track,t.timestamp,"key"===t.type),n=this.createSampleForTrack(i,t.data,a,t.duration,t.type);i.info.requiresPcmTransformation&&await this.maybePadWithSilence(i,a),await this.registerSample(i,n)}finally{i()}}async maybePadWithSilence(e,t){const r=Ga(e.samples),i=r?r.timestamp+r.duration:0,a=t-i,n=fd(a,e.timescale);if(n>0){const{sampleSize:t,silentValue:r}=po(e.info.decoderConfig.codec),o=n*e.info.numberOfChannels,s=new Uint8Array(t*o).fill(r),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),i,a,"key");await this.registerSample(e,c)}}async addSubtitleCue(e,t,r){const i=await this.mutex.acquire();try{const i=this.getSubtitleTrackData(e,r);this.validateAndNormalizeTimestamp(i.track,t.timestamp,!0),"webvtt"===e.source._codec&&(i.cueQueue.push(t),await this.processWebVTTCues(i,t.timestamp))}finally{i()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const r=new Set([]);for(const i of e.cueQueue)Xa(i.timestamp<=t),Xa(e.lastCueEndTimestamp<=i.timestamp+i.duration),r.add(Math.max(i.timestamp,e.lastCueEndTimestamp)),r.add(i.timestamp+i.duration);const i=[...r].sort((e,t)=>e-t),a=i[0],n=i[1]??a;if(t<n)break;if(e.lastCueEndTimestamp<a){this.auxWriter.seek(0);const t=Wh();this.auxBoxWriter.writeBox(t);const r=this.auxWriter.getSlice(0,this.auxWriter.getPos()),i=this.createSampleForTrack(e,r,e.lastCueEndTimestamp,a-e.lastCueEndTimestamp,"key");await this.registerSample(e,i),e.lastCueEndTimestamp=a}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){const r=e.cueQueue[t];if(r.timestamp>=n)break;Sl.lastIndex=0;const i=Sl.test(r.text),o=r.timestamp+r.duration;let s=e.cueToSourceId.get(r);if(void 0===s&&n<o&&(s=e.nextSourceId++,e.cueToSourceId.set(r,s)),r.notes){const e=Hh(r.notes);this.auxBoxWriter.writeBox(e)}const c=Vh(r.text,i?a:null,r.identifier??null,r.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===n&&e.cueQueue.splice(t--,1)}const o=this.auxWriter.getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,a,n-a,"key");await this.registerSample(e,s),e.lastCueEndTimestamp=n}}createSampleForTrack(e,t,r,i,a){return{timestamp:r,decodeTimestamp:r,duration:i,data:t,size:t.byteLength,type:a,timescaleUnitsToNextSample:fd(i,e.timescale)}}processTimestamps(e,t){if(0===e.timestampProcessingQueue.length)return;if("audio"===e.type&&e.info.requiresPcmTransformation){let t=0;for(let r=0;r<e.timestampProcessingQueue.length;r++){const i=e.timestampProcessingQueue[r];t+=fd(i.duration,e.timescale)}if(0===e.timeToSampleTable.length)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{Ga(e.timeToSampleTable).sampleCount+=t}return void(e.timestampProcessingQueue.length=0)}const r=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);for(let t=0;t<e.timestampProcessingQueue.length;t++){const i=e.timestampProcessingQueue[t];i.decodeTimestamp=r[t],this.isFragmented||null!==e.lastTimescaleUnits||(i.decodeTimestamp=0);const a=fd(i.timestamp-i.decodeTimestamp,e.timescale),n=fd(i.duration,e.timescale);if(null!==e.lastTimescaleUnits){Xa(e.lastSample);const t=fd(i.decodeTimestamp,e.timescale,!1),r=Math.round(t-e.lastTimescaleUnits);if(Xa(r>=0),e.lastTimescaleUnits+=r,e.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let t=Ga(e.timeToSampleTable);if(Xa(t),1===t.sampleCount){t.sampleDelta=r;const i=e.timeToSampleTable[e.timeToSampleTable.length-2];i&&i.sampleDelta===r&&(i.sampleCount++,e.timeToSampleTable.pop(),t=i)}else t.sampleDelta!==r&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:r}));t.sampleDelta===n?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:n});const i=Ga(e.compositionTimeOffsetTable);Xa(i),i.sampleCompositionTimeOffset===a?i.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=fd(i.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:n}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=i}if(e.timestampProcessingQueue.length=0,Xa(e.lastSample),Xa(null!==e.lastTimescaleUnits),void 0!==t&&0===e.lastSample.timescaleUnitsToNextSample){Xa("key"===t.type);const r=fd(t.timestamp,e.timescale,!1),i=Math.round(r-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=i}}async registerSample(e,t){"key"===t.type&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):"reserve"===this.fastStart?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),"reserve"===this.fastStart)){const t=e.track.metadata.maximumPacketCount;if(Xa(void 0!==t),e.samples.length>t)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let r=!1;if(e.currentChunk){e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const i=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const a=this.trackDatas.every(r=>{if(e===r)return"key"===t.type;const i=r.sampleQueue[0];return i?"key"===i.type:r.track.source._closed});i>=this.minimumFragmentDuration&&a&&t.timestamp>this.maxWrittenTimestamp&&(r=!0,await this.finalizeFragment())}else r=i>=.5}else r=!0;r&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),Xa(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(Xa(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if("audio"===e.type&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,r)=>t+fd(r.duration,e.timescale),0)),0!==e.compactlyCodedChunkTable.length&&Ga(e.compactlyCodedChunkTable).samplesPerChunk===t||e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),"in-memory"!==this.fastStart){e.currentChunk.offset=this.writer.getPos();for(const t of e.currentChunk.samples)Xa(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}else e.currentChunk.offset=0}async interleaveSamples(e=!1){if(Xa(this.isFragmented),e||this.allTracksAreKnown())e:for(;;){let t=null,r=1/0;for(const i of this.trackDatas){if(!e&&0===i.sampleQueue.length&&!i.track.source._closed)break e;i.sampleQueue.length>0&&i.sampleQueue[0].timestamp<r&&(t=i,r=i.sampleQueue[0].timestamp)}if(!t)break;const i=t.sampleQueue.shift();await this.addSampleToTrack(t,i)}}async finalizeFragment(e=!0){Xa(this.isFragmented);const t=this.nextFragmentNumber++;if(1===t){this.format._options.onMoov&&this.writer.startTrackingWrites();const e=Kl(this);if(this.boxWriter.writeBox(e),this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}const r=this.trackDatas.filter(e=>e.currentChunk),i=Ph(t,r),a=this.writer.getPos(),n=a+this.boxWriter.measureBox(i);let o=n+8,s=1/0;for(const e of r){e.currentChunk.offset=o,e.currentChunk.moofOffset=a;for(const t of e.currentChunk.samples)o+=t.size;s=Math.min(s,e.currentChunk.startTimestamp)}const c=o-n,u=c>=2**32;if(u)for(const e of r)e.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();const l=Ph(t,r);if(this.boxWriter.writeBox(l),this.format._options.onMoof){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,s)}Xa(this.writer.getPos()===n),this.format._options.onMdat&&this.writer.startTrackingWrites();const h=ql(u);h.size=c,this.boxWriter.writeBox(h),this.writer.seek(n+(u?Gs:8));for(const e of r)for(const t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(const e of r)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(this.allTracksAreKnown()){if(!this.mdat){const e=Kl(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;Xa(null!==this.ftypSize),this.writer.seek(this.ftypSize+t),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=ql(!0),this.boxWriter.writeBox(this.mdat);for(const e of this.trackDatas){for(const t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){Xa("reserve"===this.fastStart);let e=0;for(const t of this.trackDatas){const r=t.track.metadata.maximumPacketCount;Xa(void 0!==r),e+=8*Math.ceil(2/3*r),e+=4*r,e+=8*Math.ceil(2/3*r),e+=12*Math.ceil(2/3*r),e+=4*r,e+=8*r}return e}async onTrackClose(e){const t=await this.mutex.acquire();if("subtitle"===e.type&&"webvtt"===e.source._codec){const t=this.trackDatas.find(t=>t.track===e);t&&await this.processWebVTTCues(t,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const e of this.trackDatas)"subtitle"===e.type&&"webvtt"===e.track.source._codec&&await this.processWebVTTCues(e,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const e of this.trackDatas)this.processTimestamps(e);await this.finalizeFragment(!1)}else for(const e of this.trackDatas)this.processTimestamps(e),await this.finalizeCurrentChunk(e);if("in-memory"===this.fastStart){let e;this.mdat=ql(!1);for(let t=0;t<2;t++){const t=Kl(this),r=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let i=this.writer.getPos()+r+e;for(const t of this.finalizedChunks){t.offset=i;for(const{data:r}of t.samples)Xa(r),i+=r.byteLength,e+=r.byteLength}if(i<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const t=Kl(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(const e of this.finalizedChunks)for(const t of e.samples)Xa(t.data),this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}}else if(this.isFragmented){const e=this.writer.getPos(),r=(t=this.trackDatas,Gl("mfra",void 0,[...t.map(Uh),zh()]));this.boxWriter.writeBox(r);const i=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(i)}else{Xa(this.mdat);const e=this.boxWriter.offsets.get(this.mdat);Xa(void 0!==e);const t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}const r=Kl(this);if("reserve"===this.fastStart){Xa(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);const e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:e})}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);if(this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}var t;e()}}
246
246
  /*!
247
247
  * Copyright (c) 2025-present, Vanilagy and contributors
248
248
  *
249
249
  * This Source Code Form is subject to the terms of the Mozilla Public
250
250
  * License, v. 2.0. If a copy of the MPL was not distributed with this
251
251
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
252
- */const Zl="Mediabunny",Jl={video:1,audio:2,subtitle:17};class eu extends ka{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=gi(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.duration=0,this.writer=e._writer,this.format=t,this.ebmlWriter=new is(this.writer),this.format._options.appendOnly&&(this.writer.ensureMonotonicity=!0)}async start(){const e=await this.mutex.acquire();this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:$n.EBML,data:[{id:$n.EBMLVersion,data:1},{id:$n.EBMLReadVersion,data:1},{id:$n.EBMLMaxIDLength,data:4},{id:$n.EBMLMaxSizeLength,data:8},{id:$n.DocType,data:this.format instanceof su?"webm":"matroska"},{id:$n.DocTypeVersion,data:2},{id:$n.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(e,t)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;const t=new Uint8Array([28,83,187,107]),r=new Uint8Array([21,73,169,102]),i=new Uint8Array([22,84,174,107]),a=new Uint8Array([25,65,164,105]),n=new Uint8Array([18,84,195,103]),s={id:$n.SeekHead,data:[{id:$n.Seek,data:[{id:$n.SeekID,data:t},{id:$n.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:$n.Seek,data:[{id:$n.SeekID,data:r},{id:$n.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:$n.Seek,data:[{id:$n.SeekID,data:i},{id:$n.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:$n.Seek,data:[{id:$n.SeekID,data:a},{id:$n.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:$n.Seek,data:[{id:$n.SeekID,data:n},{id:$n.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=s}createSegmentInfo(){const e={id:$n.Duration,data:new Gn(0)};this.segmentDuration=e;const t={id:$n.Info,data:[{id:$n.TimestampScale,data:1e6},{id:$n.MuxingApp,data:Zl},{id:$n.WritingApp,data:Zl},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){const e={id:$n.Tracks,data:[]};this.tracksElement=e;for(const t of this.trackDatas){const r=gs[t.track.source._codec];jr(r);let i=0;if("audio"===t.type&&"opus"===t.track.source._codec){i=8e7;const e=t.info.decoderConfig.description;if(e){const t=Qr(e),r=Va(t);i=Math.round(r.preSkip/ca*1e9)}}e.data.push({id:$n.TrackEntry,data:[{id:$n.TrackNumber,data:t.track.id},{id:$n.TrackUID,data:t.track.id},{id:$n.TrackType,data:Jl[t.type]},!1===t.track.metadata.disposition?.default?{id:$n.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:$n.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:$n.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:$n.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:$n.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:$n.FlagCommentary,data:1}:null,{id:$n.FlagLacing,data:0},{id:$n.Language,data:t.track.metadata.languageCode??wi},{id:$n.CodecID,data:r},{id:$n.CodecDelay,data:0},{id:$n.SeekPreRoll,data:i},void 0!==t.track.metadata.name?{id:$n.Name,data:new Yn(t.track.metadata.name)}:null,"video"===t.type?this.videoSpecificTrackInfo(t):null,"audio"===t.type?this.audioSpecificTrackInfo(t):null,"subtitle"===t.type?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,rotation:r}=e.track.metadata,i=[e.info.decoderConfig.description?{id:$n.CodecPrivate,data:Qr(e.info.decoderConfig.description)}:null,t?{id:$n.DefaultDuration,data:1e9/t}:null],a=r?Xr(-r):0,n=e.info.decoderConfig.colorSpace,s={id:$n.Video,data:[{id:$n.PixelWidth,data:e.info.width},{id:$n.PixelHeight,data:e.info.height},e.info.alphaMode?{id:$n.AlphaMode,data:1}:null,ci(n)?{id:$n.Colour,data:[{id:$n.MatrixCoefficients,data:si[n.matrix]},{id:$n.TransferCharacteristics,data:ai[n.transfer]},{id:$n.Primaries,data:ri[n.primaries]},{id:$n.Range,data:n.fullRange?2:1}]}:null,a?{id:$n.Projection,data:[{id:$n.ProjectionType,data:0},{id:$n.ProjectionPoseRoll,data:new qn((a+180)%360-180)}]}:null]};return i.push(s),i}audioSpecificTrackInfo(e){const t=Ki.includes(e.track.source._codec)?ua(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:$n.CodecPrivate,data:Qr(e.info.decoderConfig.description)}:null,{id:$n.Audio,data:[{id:$n.SamplingFrequency,data:new qn(e.info.sampleRate)},{id:$n.Channels,data:e.info.numberOfChannels},t?{id:$n.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[{id:$n.CodecPrivate,data:ei.encode(e.info.config.description)}]}maybeCreateTags(){const e=[],t=(t,r)=>{e.push({id:$n.SimpleTag,data:[{id:$n.TagName,data:new Yn(t)},"string"==typeof r?{id:$n.TagString,data:new Yn(r)}:{id:$n.TagBinary,data:r}]})},r=this.output._metadataTags,i=new Set;for(const{key:e,value:a}of Li(r))switch(e){case"title":t("TITLE",a),i.add("TITLE");break;case"description":t("DESCRIPTION",a),i.add("DESCRIPTION");break;case"artist":t("ARTIST",a),i.add("ARTIST");break;case"album":t("ALBUM",a),i.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",a),i.add("ALBUM_ARTIST");break;case"genre":t("GENRE",a),i.add("GENRE");break;case"comment":t("COMMENT",a),i.add("COMMENT");break;case"lyrics":t("LYRICS",a),i.add("LYRICS");break;case"date":t("DATE",a.toISOString().slice(0,10)),i.add("DATE");break;case"trackNumber":t("PART_NUMBER",void 0!==r.tracksTotal?`${a}/${r.tracksTotal}`:a.toString()),i.add("PART_NUMBER");break;case"discNumber":t("DISC",void 0!==r.discsTotal?`${a}/${r.discsTotal}`:a.toString()),i.add("DISC");break;case"tracksTotal":case"discsTotal":case"images":case"raw":break;default:bi(e)}if(r.raw)for(const e in r.raw){const a=r.raw[e];null==a||i.has(e)||("string"==typeof a||a instanceof Uint8Array)&&t(e,a)}0!==e.length&&(this.tagsElement={id:$n.Tags,data:[{id:$n.Tag,data:[{id:$n.Targets,data:[{id:$n.TargetTypeValue,data:50},{id:$n.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],r=new Set,i=e.images??[];for(const e of i){let i,a=e.name;if(void 0===a){a=("coverFront"===e.kind?"cover":"coverBack"===e.kind?"back":"image")+(Ui(e.mimeType)??"")}for(;;){i=0n;for(let e=0;e<8;e++)i<<=8n,i|=BigInt(Math.floor(256*Math.random()));if(0n!==i&&!r.has(i))break}r.add(i),t.push({id:$n.AttachedFile,data:[void 0!==e.description?{id:$n.FileDescription,data:new Yn(e.description)}:null,{id:$n.FileName,data:new Yn(a)},{id:$n.FileMediaType,data:e.mimeType},{id:$n.FileData,data:e.data},{id:$n.FileUID,data:i}]})}for(const[r,a]of Object.entries(e.raw??{})){if(!(a instanceof Xi))continue;/^\d+$/.test(r)&&(i.find(e=>e.mimeType===a.mimeType&&Wi(e.data,a.data))||t.push({id:$n.AttachedFile,data:[void 0!==a.description?{id:$n.FileDescription,data:new Yn(a.description)}:null,{id:$n.FileName,data:new Yn(a.name??"")},{id:$n.FileMediaType,data:a.mimeType??""},{id:$n.FileData,data:a.data},{id:$n.FileUID,data:BigInt(r)}]}))}0!==t.length&&(this.attachmentsElement={id:$n.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:$n.Segment,size:this.format._options.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(e,t)}}createCues(){this.cues={id:$n.Cues,data:[]}}get segmentDataOffset(){return jr(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(e=>{if("video"===e.type)return e.info.decoderConfig.codec;if("audio"===e.type)return e.info.decoderConfig.codec;return{webvtt:"wvtt"}[e.track.source._codec]});return ys({isWebM:this.format instanceof su,hasVideo:this.trackDatas.some(e=>"video"===e.type),hasAudio:this.trackDatas.some(e=>"audio"===e.type),codecStrings:e})}getVideoTrackData(e,t,r){const i=this.trackDatas.find(t=>t.track===e);if(i)return i;ga(r),jr(r),jr(r.decoderConfig),jr(void 0!==r.decoderConfig.codedWidth),jr(void 0!==r.decoderConfig.codedHeight);const a={track:e,type:"video",info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,decoderConfig:r.decoderConfig,alphaMode:!!t.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null};return"vp9"===e.source._codec?a.info.decoderConfig={...a.info.decoderConfig,description:new Uint8Array(ta(a.info.decoderConfig.codec))}:"av1"===e.source._codec&&(a.info.decoderConfig={...a.info.decoderConfig,description:new Uint8Array(ra(a.info.decoderConfig.codec))}),this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getAudioTrackData(e,t){const r=this.trackDatas.find(t=>t.track===e);if(r)return r;ya(t),jr(t),jr(t.decoderConfig);const i={track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}getSubtitleTrackData(e,t){const r=this.trackDatas.find(t=>t.track===e);if(r)return r;ba(t),jr(t),jr(t.config);const i={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,r){const i=await this.mutex.acquire();try{const i=this.getVideoTrackData(e,t,r),a="key"===t.type;let n=this.validateAndNormalizeTimestamp(i.track,t.timestamp,a),s=t.duration;void 0!==e.metadata.frameRate&&(n=xi(n,1/e.metadata.frameRate),s=xi(s,1/e.metadata.frameRate));const o=i.info.alphaMode?t.sideData.alpha??null:null,c=this.createInternalChunk(t.data,n,s,t.type,o);"vp9"===e.source._codec&&this.fixVP9ColorSpace(i,c),i.chunkQueue.push(c),await this.interleaveChunks()}finally{i()}}async addEncodedAudioPacket(e,t,r){const i=await this.mutex.acquire();try{const i=this.getAudioTrackData(e,r),a="key"===t.type,n=this.validateAndNormalizeTimestamp(i.track,t.timestamp,a),s=this.createInternalChunk(t.data,n,t.duration,t.type);i.chunkQueue.push(s),await this.interleaveChunks()}finally{i()}}async addSubtitleCue(e,t,r){const i=await this.mutex.acquire();try{const i=this.getSubtitleTrackData(e,r),a=this.validateAndNormalizeTimestamp(i.track,t.timestamp,!0);let n=t.text;const s=Math.round(1e3*a);oc.lastIndex=0,n=n.replace(oc,e=>{const t=(e=>{const t=cc.exec(e);if(!t)throw new Error("Expected match.");return 36e5*Number(t[1]||"0")+6e4*Number(t[2])+1e3*Number(t[3])+Number(t[4])})(e.slice(1,-1));return`<${lc(t-s)}>`});const o=ei.encode(n),c=`${t.settings??""}\n${t.identifier??""}\n${t.notes??""}`,l=this.createInternalChunk(o,a,t.duration,"key",c.trim()?ei.encode(c):null);i.chunkQueue.push(l),await this.interleaveChunks()}finally{i()}}async interleaveChunks(e=!1){if(e||this.allTracksAreKnown()){e:for(;;){let t=null,r=1/0;for(const i of this.trackDatas){if(!e&&0===i.chunkQueue.length&&!i.track.source._closed)break e;i.chunkQueue.length>0&&i.chunkQueue[0].timestamp<r&&(t=i,r=i.chunkQueue[0].timestamp)}if(!t)break;const i=t.chunkQueue.shift();this.writeBlock(t,i)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if("key"!==t.type)return;if(!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;const r=new Kr(t.data);r.skipBits(2);const i=r.readBits(1),a=(r.readBits(1)<<1)+i;3===a&&r.skipBits(1);if(r.readBits(1))return;if(0!==r.readBits(1))return;r.skipBits(2);if(4817730!==r.readBits(24))return;a>=2&&r.skipBits(1);const n={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];((e,t,r,i)=>{for(let a=t;a<r;a++){const t=Math.floor(a/8);let n=e[t];const s=7-(7&a);n&=~(1<<s),n|=(i&1<<r-a-1)>>r-a-1<<s,e[t]=n}})(t.data,r.pos,r.pos+3,n)}createInternalChunk(e,t,r,i,a=null){return{data:e,type:i,timestamp:t,duration:r,additions:a}}writeBlock(e,t){this.segment||this.createSegment();const r=Math.round(1e3*t.timestamp),i=this.trackDatas.every(r=>{if(e===r)return"key"===t.type;const i=r.chunkQueue[0];return i?"key"===i.type:r.track.source._closed});let a=!1;if(this.currentCluster){jr(null!==this.currentClusterStartMsTimestamp),jr(null!==this.currentClusterMaxMsTimestamp);const e=r-this.currentClusterStartMsTimestamp;a=i&&r>this.currentClusterMaxMsTimestamp&&e>=1e3*(this.format._options.minimumClusterDuration??1)||e>32767}else a=!0;a&&this.createNewCluster(r);const n=r-this.currentClusterStartMsTimestamp;if(n<-32768)return;const s=new Uint8Array(4),o=new DataView(s.buffer);o.setUint8(0,128|e.track.id),o.setInt16(1,n,!1);const c=Math.round(1e3*t.duration);if(t.additions){const i={id:$n.BlockGroup,data:[{id:$n.Block,data:[s,t.data]},"delta"===t.type?{id:$n.ReferenceBlock,data:new Kn(e.lastWrittenMsTimestamp-r)}:null,t.additions?{id:$n.BlockAdditions,data:[{id:$n.BlockMore,data:[{id:$n.BlockAddID,data:1},{id:$n.BlockAdditional,data:t.additions}]}]}:null,c>0?{id:$n.BlockDuration,data:c}:null]};this.ebmlWriter.writeEBML(i)}else{o.setUint8(3,Number("key"===t.type)<<7);const e={id:$n.SimpleBlock,data:[s,t.data]};this.ebmlWriter.writeEBML(e)}this.duration=Math.max(this.duration,r+c),e.lastWrittenMsTimestamp=r,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:r}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,r)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:$n.Cluster,size:this.format._options.appendOnly?-1:5,data:[{id:$n.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(jr(this.currentCluster),!this.format._options.appendOnly){const e=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),t=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(e,5),this.writer.seek(t)}if(this.format._options.onCluster){jr(null!==this.currentClusterStartMsTimestamp);const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onCluster(e,t,this.currentClusterStartMsTimestamp/1e3)}const e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=new Map;for(const[e,{firstMsTimestamp:r}]of this.trackDatasInCurrentCluster)t.has(r)||t.set(r,[]),t.get(r).push(e);const r=[...t.entries()].sort((e,t)=>e[0]-t[0]);for(const[t,i]of r)jr(this.cues),this.cues.data.push({id:$n.CuePoint,data:[{id:$n.CueTime,data:t},...i.map(t=>({id:$n.CueTrackPositions,data:[{id:$n.CueTrack,data:t.track.id},{id:$n.CueClusterPosition,data:e}]}))]})}async onTrackClose(){const e=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),e()}async finalize(){const e=await this.mutex.acquire();if(this.allTracksKnown.resolve(),this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),jr(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const e=this.writer.getPos(),t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,6),this.segmentDuration.data=new Gn(this.duration),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),jr(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead),this.writer.seek(e)}e()}}
252
+ */const pd="Mediabunny",gd={video:1,audio:2,subtitle:17};class vd extends Eo{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=vn(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.duration=0,this.writer=e._writer,this.format=t,this.ebmlWriter=new Tc(this.writer),this.format._options.appendOnly&&(this.writer.ensureMonotonicity=!0)}async start(){const e=await this.mutex.acquire();this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:mc.EBML,data:[{id:mc.EBMLVersion,data:1},{id:mc.EBMLReadVersion,data:1},{id:mc.EBMLMaxIDLength,data:4},{id:mc.EBMLMaxSizeLength,data:8},{id:mc.DocType,data:this.format instanceof kd?"webm":"matroska"},{id:mc.DocTypeVersion,data:2},{id:mc.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(e,t)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;const t=new Uint8Array([28,83,187,107]),r=new Uint8Array([21,73,169,102]),i=new Uint8Array([22,84,174,107]),a=new Uint8Array([25,65,164,105]),n=new Uint8Array([18,84,195,103]),o={id:mc.SeekHead,data:[{id:mc.Seek,data:[{id:mc.SeekID,data:t},{id:mc.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:mc.Seek,data:[{id:mc.SeekID,data:r},{id:mc.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:mc.Seek,data:[{id:mc.SeekID,data:i},{id:mc.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:mc.Seek,data:[{id:mc.SeekID,data:a},{id:mc.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:mc.Seek,data:[{id:mc.SeekID,data:n},{id:mc.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=o}createSegmentInfo(){const e={id:mc.Duration,data:new hc(0)};this.segmentDuration=e;const t={id:mc.Info,data:[{id:mc.TimestampScale,data:1e6},{id:mc.MuxingApp,data:pd},{id:mc.WritingApp,data:pd},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){const e={id:mc.Tracks,data:[]};this.tracksElement=e;for(const t of this.trackDatas){const r=Dc[t.track.source._codec];Xa(r);let i=0;if("audio"===t.type&&"opus"===t.track.source._codec){i=8e7;const e=t.info.decoderConfig.description;if(e){const t=Qa(e),r=Qo(t);i=Math.round(r.preSkip/fo*1e9)}}e.data.push({id:mc.TrackEntry,data:[{id:mc.TrackNumber,data:t.track.id},{id:mc.TrackUID,data:t.track.id},{id:mc.TrackType,data:gd[t.type]},!1===t.track.metadata.disposition?.default?{id:mc.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:mc.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:mc.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:mc.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:mc.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:mc.FlagCommentary,data:1}:null,{id:mc.FlagLacing,data:0},{id:mc.Language,data:t.track.metadata.languageCode??Sn},{id:mc.CodecID,data:r},{id:mc.CodecDelay,data:0},{id:mc.SeekPreRoll,data:i},void 0!==t.track.metadata.name?{id:mc.Name,data:new fc(t.track.metadata.name)}:null,"video"===t.type?this.videoSpecificTrackInfo(t):null,"audio"===t.type?this.audioSpecificTrackInfo(t):null,"subtitle"===t.type?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,rotation:r}=e.track.metadata,i=[e.info.decoderConfig.description?{id:mc.CodecPrivate,data:Qa(e.info.decoderConfig.description)}:null,t?{id:mc.DefaultDuration,data:1e9/t}:null],a=r?ja(-r):0,n=e.info.decoderConfig.colorSpace,o={id:mc.Video,data:[{id:mc.PixelWidth,data:e.info.width},{id:mc.PixelHeight,data:e.info.height},e.info.alphaMode?{id:mc.AlphaMode,data:1}:null,un(n)?{id:mc.Colour,data:[{id:mc.MatrixCoefficients,data:sn[n.matrix]},{id:mc.TransferCharacteristics,data:nn[n.transfer]},{id:mc.Primaries,data:rn[n.primaries]},{id:mc.Range,data:n.fullRange?2:1}]}:null,a?{id:mc.Projection,data:[{id:mc.ProjectionType,data:0},{id:mc.ProjectionPoseRoll,data:new lc((a+180)%360-180)}]}:null]};return i.push(o),i}audioSpecificTrackInfo(e){const t=Zn.includes(e.track.source._codec)?po(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:mc.CodecPrivate,data:Qa(e.info.decoderConfig.description)}:null,{id:mc.Audio,data:[{id:mc.SamplingFrequency,data:new lc(e.info.sampleRate)},{id:mc.Channels,data:e.info.numberOfChannels},t?{id:mc.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[{id:mc.CodecPrivate,data:en.encode(e.info.config.description)}]}maybeCreateTags(){const e=[],t=(t,r)=>{e.push({id:mc.SimpleTag,data:[{id:mc.TagName,data:new fc(t)},"string"==typeof r?{id:mc.TagString,data:new fc(r)}:{id:mc.TagBinary,data:r}]})},r=this.output._metadataTags,i=new Set;for(const{key:e,value:a}of Vn(r))switch(e){case"title":t("TITLE",a),i.add("TITLE");break;case"description":t("DESCRIPTION",a),i.add("DESCRIPTION");break;case"artist":t("ARTIST",a),i.add("ARTIST");break;case"album":t("ALBUM",a),i.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",a),i.add("ALBUM_ARTIST");break;case"genre":t("GENRE",a),i.add("GENRE");break;case"comment":t("COMMENT",a),i.add("COMMENT");break;case"lyrics":t("LYRICS",a),i.add("LYRICS");break;case"date":t("DATE",a.toISOString().slice(0,10)),i.add("DATE");break;case"trackNumber":t("PART_NUMBER",void 0!==r.tracksTotal?`${a}/${r.tracksTotal}`:a.toString()),i.add("PART_NUMBER");break;case"discNumber":t("DISC",void 0!==r.discsTotal?`${a}/${r.discsTotal}`:a.toString()),i.add("DISC");break;case"tracksTotal":case"discsTotal":case"images":case"raw":break;default:xn(e)}if(r.raw)for(const e in r.raw){const a=r.raw[e];null==a||i.has(e)||("string"==typeof a||a instanceof Uint8Array)&&t(e,a)}0!==e.length&&(this.tagsElement={id:mc.Tags,data:[{id:mc.Tag,data:[{id:mc.Targets,data:[{id:mc.TargetTypeValue,data:50},{id:mc.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],r=new Set,i=e.images??[];for(const e of i){let i,a=e.name;if(void 0===a){a=("coverFront"===e.kind?"cover":"coverBack"===e.kind?"back":"image")+(Hn(e.mimeType)??"")}for(;;){i=0n;for(let e=0;e<8;e++)i<<=8n,i|=BigInt(Math.floor(256*Math.random()));if(0n!==i&&!r.has(i))break}r.add(i),t.push({id:mc.AttachedFile,data:[void 0!==e.description?{id:mc.FileDescription,data:new fc(e.description)}:null,{id:mc.FileName,data:new fc(a)},{id:mc.FileMediaType,data:e.mimeType},{id:mc.FileData,data:e.data},{id:mc.FileUID,data:i}]})}for(const[r,a]of Object.entries(e.raw??{})){if(!(a instanceof Kn))continue;/^\d+$/.test(r)&&(i.find(e=>e.mimeType===a.mimeType&&jn(e.data,a.data))||t.push({id:mc.AttachedFile,data:[void 0!==a.description?{id:mc.FileDescription,data:new fc(a.description)}:null,{id:mc.FileName,data:new fc(a.name??"")},{id:mc.FileMediaType,data:a.mimeType??""},{id:mc.FileData,data:a.data},{id:mc.FileUID,data:BigInt(r)}]}))}0!==t.length&&(this.attachmentsElement={id:mc.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:mc.Segment,size:this.format._options.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(e,t)}}createCues(){this.cues={id:mc.Cues,data:[]}}get segmentDataOffset(){return Xa(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(e=>{if("video"===e.type)return e.info.decoderConfig.codec;if("audio"===e.type)return e.info.decoderConfig.codec;return{webvtt:"wvtt"}[e.track.source._codec]});return Fc({isWebM:this.format instanceof kd,hasVideo:this.trackDatas.some(e=>"video"===e.type),hasAudio:this.trackDatas.some(e=>"audio"===e.type),codecStrings:e})}getVideoTrackData(e,t,r){const i=this.trackDatas.find(t=>t.track===e);if(i)return i;To(r),Xa(r),Xa(r.decoderConfig),Xa(void 0!==r.decoderConfig.codedWidth),Xa(void 0!==r.decoderConfig.codedHeight);const a={track:e,type:"video",info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,decoderConfig:r.decoderConfig,alphaMode:!!t.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null};return"vp9"===e.source._codec?a.info.decoderConfig={...a.info.decoderConfig,description:new Uint8Array(no(a.info.decoderConfig.codec))}:"av1"===e.source._codec&&(a.info.decoderConfig={...a.info.decoderConfig,description:new Uint8Array(oo(a.info.decoderConfig.codec))}),this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getAudioTrackData(e,t){const r=this.trackDatas.find(t=>t.track===e);if(r)return r;ko(t),Xa(t),Xa(t.decoderConfig);const i={track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}getSubtitleTrackData(e,t){const r=this.trackDatas.find(t=>t.track===e);if(r)return r;So(t),Xa(t),Xa(t.config);const i={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,r){const i=await this.mutex.acquire();try{const i=this.getVideoTrackData(e,t,r),a="key"===t.type;let n=this.validateAndNormalizeTimestamp(i.track,t.timestamp,a),o=t.duration;void 0!==e.metadata.frameRate&&(n=Cn(n,1/e.metadata.frameRate),o=Cn(o,1/e.metadata.frameRate));const s=i.info.alphaMode?t.sideData.alpha??null:null,c=this.createInternalChunk(t.data,n,o,t.type,s);"vp9"===e.source._codec&&this.fixVP9ColorSpace(i,c),i.chunkQueue.push(c),await this.interleaveChunks()}finally{i()}}async addEncodedAudioPacket(e,t,r){const i=await this.mutex.acquire();try{const i=this.getAudioTrackData(e,r),a="key"===t.type,n=this.validateAndNormalizeTimestamp(i.track,t.timestamp,a),o=this.createInternalChunk(t.data,n,t.duration,t.type);i.chunkQueue.push(o),await this.interleaveChunks()}finally{i()}}async addSubtitleCue(e,t,r){const i=await this.mutex.acquire();try{const i=this.getSubtitleTrackData(e,r),a=this.validateAndNormalizeTimestamp(i.track,t.timestamp,!0);let n=t.text;const o=Math.round(1e3*a);Sl.lastIndex=0,n=n.replace(Sl,e=>{const t=(e=>{const t=El.exec(e);if(!t)throw new Error("Expected match.");return 36e5*Number(t[1]||"0")+6e4*Number(t[2])+1e3*Number(t[3])+Number(t[4])})(e.slice(1,-1));return`<${Cl(t-o)}>`});const s=en.encode(n),c=`${t.settings??""}\n${t.identifier??""}\n${t.notes??""}`,u=this.createInternalChunk(s,a,t.duration,"key",c.trim()?en.encode(c):null);i.chunkQueue.push(u),await this.interleaveChunks()}finally{i()}}async interleaveChunks(e=!1){if(e||this.allTracksAreKnown()){e:for(;;){let t=null,r=1/0;for(const i of this.trackDatas){if(!e&&0===i.chunkQueue.length&&!i.track.source._closed)break e;i.chunkQueue.length>0&&i.chunkQueue[0].timestamp<r&&(t=i,r=i.chunkQueue[0].timestamp)}if(!t)break;const i=t.chunkQueue.shift();this.writeBlock(t,i)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if("key"!==t.type)return;if(!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;const r=new qa(t.data);r.skipBits(2);const i=r.readBits(1),a=(r.readBits(1)<<1)+i;3===a&&r.skipBits(1);if(r.readBits(1))return;if(0!==r.readBits(1))return;r.skipBits(2);if(4817730!==r.readBits(24))return;a>=2&&r.skipBits(1);const n={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];((e,t,r,i)=>{for(let a=t;a<r;a++){const t=Math.floor(a/8);let n=e[t];const o=7-(7&a);n&=~(1<<o),n|=(i&1<<r-a-1)>>r-a-1<<o,e[t]=n}})(t.data,r.pos,r.pos+3,n)}createInternalChunk(e,t,r,i,a=null){return{data:e,type:i,timestamp:t,duration:r,additions:a}}writeBlock(e,t){this.segment||this.createSegment();const r=Math.round(1e3*t.timestamp),i=this.trackDatas.every(r=>{if(e===r)return"key"===t.type;const i=r.chunkQueue[0];return i?"key"===i.type:r.track.source._closed});let a=!1;if(this.currentCluster){Xa(null!==this.currentClusterStartMsTimestamp),Xa(null!==this.currentClusterMaxMsTimestamp);const e=r-this.currentClusterStartMsTimestamp;a=i&&r>this.currentClusterMaxMsTimestamp&&e>=1e3*(this.format._options.minimumClusterDuration??1)||e>32767}else a=!0;a&&this.createNewCluster(r);const n=r-this.currentClusterStartMsTimestamp;if(n<-32768)return;const o=new Uint8Array(4),s=new DataView(o.buffer);s.setUint8(0,128|e.track.id),s.setInt16(1,n,!1);const c=Math.round(1e3*t.duration);if(t.additions){const i={id:mc.BlockGroup,data:[{id:mc.Block,data:[o,t.data]},"delta"===t.type?{id:mc.ReferenceBlock,data:new dc(e.lastWrittenMsTimestamp-r)}:null,t.additions?{id:mc.BlockAdditions,data:[{id:mc.BlockMore,data:[{id:mc.BlockAddID,data:1},{id:mc.BlockAdditional,data:t.additions}]}]}:null,c>0?{id:mc.BlockDuration,data:c}:null]};this.ebmlWriter.writeEBML(i)}else{s.setUint8(3,Number("key"===t.type)<<7);const e={id:mc.SimpleBlock,data:[o,t.data]};this.ebmlWriter.writeEBML(e)}this.duration=Math.max(this.duration,r+c),e.lastWrittenMsTimestamp=r,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:r}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,r)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:mc.Cluster,size:this.format._options.appendOnly?-1:5,data:[{id:mc.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(Xa(this.currentCluster),!this.format._options.appendOnly){const e=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),t=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(e,5),this.writer.seek(t)}if(this.format._options.onCluster){Xa(null!==this.currentClusterStartMsTimestamp);const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onCluster(e,t,this.currentClusterStartMsTimestamp/1e3)}const e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=new Map;for(const[e,{firstMsTimestamp:r}]of this.trackDatasInCurrentCluster)t.has(r)||t.set(r,[]),t.get(r).push(e);const r=[...t.entries()].sort((e,t)=>e[0]-t[0]);for(const[t,i]of r)Xa(this.cues),this.cues.data.push({id:mc.CuePoint,data:[{id:mc.CueTime,data:t},...i.map(t=>({id:mc.CueTrackPositions,data:[{id:mc.CueTrack,data:t.track.id},{id:mc.CueClusterPosition,data:e}]}))]})}async onTrackClose(){const e=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),e()}async finalize(){const e=await this.mutex.acquire();if(this.allTracksKnown.resolve(),this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),Xa(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const e=this.writer.getPos(),t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,6),this.segmentDuration.data=new hc(this.duration),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),Xa(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead),this.writer.seek(e)}e()}}
253
253
  /*!
254
254
  * Copyright (c) 2025-present, Vanilagy and contributors
255
255
  *
256
256
  * This Source Code Form is subject to the terms of the Mozilla Public
257
257
  * License, v. 2.0. If a copy of the MPL was not distributed with this
258
258
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
259
- */class tu{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Gi.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>$i.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Qi.includes(e))}_codecUnsupportedHint(e){return""}}class ru extends tu{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.fastStart&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(void 0!==e.minimumFragmentDuration&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(void 0!==e.onFtyp&&"function"!=typeof e.onFtyp)throw new TypeError("options.onFtyp, when provided, must be a function.");if(void 0!==e.onMoov&&"function"!=typeof e.onMoov)throw new TypeError("options.onMoov, when provided, must be a function.");if(void 0!==e.onMdat&&"function"!=typeof e.onMdat)throw new TypeError("options.onMdat, when provided, must be a function.");if(void 0!==e.onMoof&&"function"!=typeof e.onMoof)throw new TypeError("options.onMoof, when provided, must be a function.");if(void 0!==e.metadataFormat&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new Ql(e,this)}}class iu extends ru{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Gi,...Yi,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Qi]}_codecUnsupportedHint(e){return(new au).getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class au extends ru{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Gi,...$i]}_codecUnsupportedHint(e){return(new iu).getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class nu extends tu{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.appendOnly&&"boolean"!=typeof e.appendOnly)throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(void 0!==e.minimumClusterDuration&&(!Number.isFinite(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(void 0!==e.onEbmlHeader&&"function"!=typeof e.onEbmlHeader)throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(void 0!==e.onSegmentHeader&&"function"!=typeof e.onSegmentHeader)throw new TypeError("options.onHeader, when provided, must be a function.");if(void 0!==e.onCluster&&"function"!=typeof e.onCluster)throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new eu(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...Gi,...Yi,...Ki.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...Qi]}get supportsVideoRotationMetadata(){return!1}}class su extends nu{constructor(e){super(e)}getSupportedCodecs(){return[...Gi.filter(e=>["vp8","vp9","av1"].includes(e)),...$i.filter(e=>["opus","vorbis"].includes(e)),...Qi]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return(new nu).getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}
259
+ */class yd{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Qn.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>eo.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>to.includes(e))}_codecUnsupportedHint(e){return""}}class bd extends yd{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.fastStart&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(void 0!==e.minimumFragmentDuration&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(void 0!==e.onFtyp&&"function"!=typeof e.onFtyp)throw new TypeError("options.onFtyp, when provided, must be a function.");if(void 0!==e.onMoov&&"function"!=typeof e.onMoov)throw new TypeError("options.onMoov, when provided, must be a function.");if(void 0!==e.onMdat&&"function"!=typeof e.onMdat)throw new TypeError("options.onMdat, when provided, must be a function.");if(void 0!==e.onMoof&&"function"!=typeof e.onMoof)throw new TypeError("options.onMoof, when provided, must be a function.");if(void 0!==e.metadataFormat&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new md(e,this)}}class xd extends bd{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Qn,...Jn,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...to]}_codecUnsupportedHint(e){return(new Td).getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class Td extends bd{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Qn,...eo]}_codecUnsupportedHint(e){return(new xd).getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class wd extends yd{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.appendOnly&&"boolean"!=typeof e.appendOnly)throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(void 0!==e.minimumClusterDuration&&(!Number.isFinite(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(void 0!==e.onEbmlHeader&&"function"!=typeof e.onEbmlHeader)throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(void 0!==e.onSegmentHeader&&"function"!=typeof e.onSegmentHeader)throw new TypeError("options.onHeader, when provided, must be a function.");if(void 0!==e.onCluster&&"function"!=typeof e.onCluster)throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new vd(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...Qn,...Jn,...Zn.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...to]}get supportsVideoRotationMetadata(){return!1}}class kd extends wd{constructor(e){super(e)}getSupportedCodecs(){return[...Qn.filter(e=>["vp8","vp9","av1"].includes(e)),...eo.filter(e=>["opus","vorbis"].includes(e)),...to]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return(new wd).getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}
260
260
  /*!
261
261
  * Copyright (c) 2025-present, Vanilagy and contributors
262
262
  *
263
263
  * This Source Code Form is subject to the terms of the Mozilla Public
264
264
  * License, v. 2.0. If a copy of the MPL was not distributed with this
265
265
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
266
- */class ou{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if("canceled"===this._connectedTrack.output.state)throw new Error("Output has been canceled.");if("finalizing"===this._connectedTrack.output.state||"finalized"===this._connectedTrack.output.state)throw new Error("Output has been finalized.");if("pending"===this._connectedTrack.output.state)throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if("pending"===e.output.state)throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,"finalizing"!==e.output.state&&"finalized"!==e.output.state&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise?this._closingPromise:this._flushAndClose(e)}}class cu extends ou{constructor(e){if(super(),this._connectedTrack=null,!Gi.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${Gi.join(", ")}.`);this._codec=e}}class lu extends cu{constructor(e){super(e)}add(e,t){if(!(e instanceof Za))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class uu extends ou{constructor(e){if(super(),this._connectedTrack=null,!$i.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${$i.join(", ")}.`);this._codec=e}}class hu extends uu{constructor(e){super(e)}add(e,t){if(!(e instanceof Za))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}}class du extends ou{constructor(e){if(super(),this._connectedTrack=null,!Qi.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Qi.join(", ")}.`);this._codec=e}}
266
+ */class Sd{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if("canceled"===this._connectedTrack.output.state)throw new Error("Output has been canceled.");if("finalizing"===this._connectedTrack.output.state||"finalized"===this._connectedTrack.output.state)throw new Error("Output has been finalized.");if("pending"===this._connectedTrack.output.state)throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if("pending"===e.output.state)throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,"finalizing"!==e.output.state&&"finalized"!==e.output.state&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise?this._closingPromise:this._flushAndClose(e)}}class Ed extends Sd{constructor(e){if(super(),this._connectedTrack=null,!Qn.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${Qn.join(", ")}.`);this._codec=e}}class Cd extends Ed{constructor(e){super(e)}add(e,t){if(!(e instanceof ss))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class Ad extends Sd{constructor(e){if(super(),this._connectedTrack=null,!eo.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${eo.join(", ")}.`);this._codec=e}}class _d extends Ad{constructor(e){super(e)}add(e,t){if(!(e instanceof ss))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}}class Md extends Sd{constructor(e){if(super(),this._connectedTrack=null,!to.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${to.join(", ")}.`);this._codec=e}}
267
267
  /*!
268
268
  * Copyright (c) 2025-present, Vanilagy and contributors
269
269
  *
270
270
  * This Source Code Form is subject to the terms of the Mozilla Public
271
271
  * License, v. 2.0. If a copy of the MPL was not distributed with this
272
272
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
273
- */const fu=["video","audio","subtitle"],mu=e=>{if(!e||"object"!=typeof e)throw new TypeError("metadata must be an object.");if(void 0!==e.languageCode&&!Ei(e.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(void 0!==e.name&&"string"!=typeof e.name)throw new TypeError("metadata.name, when provided, must be a string.");if(void 0!==e.disposition&&(e=>{if(!e||"object"!=typeof e)throw new TypeError("disposition must be an object.");if(void 0!==e.default&&"boolean"!=typeof e.default)throw new TypeError("disposition.default must be a boolean.");if(void 0!==e.forced&&"boolean"!=typeof e.forced)throw new TypeError("disposition.forced must be a boolean.");if(void 0!==e.original&&"boolean"!=typeof e.original)throw new TypeError("disposition.original must be a boolean.");if(void 0!==e.commentary&&"boolean"!=typeof e.commentary)throw new TypeError("disposition.commentary must be a boolean.");if(void 0!==e.hearingImpaired&&"boolean"!=typeof e.hearingImpaired)throw new TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==e.visuallyImpaired&&"boolean"!=typeof e.visuallyImpaired)throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(e.disposition),void 0!==e.maximumPacketCount&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")};class pu{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new ui,this._metadataTags={},!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!(e.format instanceof tu))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof ql))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof cu))throw new TypeError("source must be a VideoSource.");if(mu(t),void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(void 0!==t.frameRate&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);this._addTrack("video",e,t)}addAudioTrack(e,t={}){if(!(e instanceof uu))throw new TypeError("source must be an AudioSource.");mu(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof du))throw new TypeError("source must be a SubtitleSource.");mu(t),this._addTrack("subtitle",e,t)}setMetadataTags(e){if((e=>{if(!e||"object"!=typeof e)throw new TypeError("tags must be an object.");if(void 0!==e.title&&"string"!=typeof e.title)throw new TypeError("tags.title, when provided, must be a string.");if(void 0!==e.description&&"string"!=typeof e.description)throw new TypeError("tags.description, when provided, must be a string.");if(void 0!==e.artist&&"string"!=typeof e.artist)throw new TypeError("tags.artist, when provided, must be a string.");if(void 0!==e.album&&"string"!=typeof e.album)throw new TypeError("tags.album, when provided, must be a string.");if(void 0!==e.albumArtist&&"string"!=typeof e.albumArtist)throw new TypeError("tags.albumArtist, when provided, must be a string.");if(void 0!==e.trackNumber&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(void 0!==e.tracksTotal&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(void 0!==e.discNumber&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(void 0!==e.discsTotal&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(void 0!==e.genre&&"string"!=typeof e.genre)throw new TypeError("tags.genre, when provided, must be a string.");if(void 0!==e.date&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(void 0!==e.lyrics&&"string"!=typeof e.lyrics)throw new TypeError("tags.lyrics, when provided, must be a string.");if(void 0!==e.images){if(!Array.isArray(e.images))throw new TypeError("tags.images, when provided, must be an array.");for(const t of e.images){if(!t||"object"!=typeof t)throw new TypeError("Each image in tags.images must be an object.");if(!(t.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if("string"!=typeof t.mimeType)throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(t.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(void 0!==e.comment&&"string"!=typeof e.comment)throw new TypeError("tags.comment, when provided, must be a string.");if(void 0!==e.raw){if(!e.raw||"object"!=typeof e.raw)throw new TypeError("tags.raw, when provided, must be an object.");for(const t of Object.values(e.raw))if(!(null===t||"string"==typeof t||t instanceof Uint8Array||t instanceof ji||t instanceof Xi))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}})(e),"pending"!==this.state)throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e,t,r){if("pending"!==this.state)throw new Error("Cannot add track after output has been started or canceled.");if(t._connectedTrack)throw new Error("Source is already used for a track.");const i=this.format.getSupportedTrackCounts(),a=this._tracks.reduce((t,r)=>t+(r.type===e?1:0),0),n=i[e].max;if(a===n)throw new Error(0===n?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${n} ${e} track`+(1===n?"":"s")+".");const s=i.total.max;if(this._tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks`+(1===s?"":"s")+" in total.");const o={id:this._tracks.length+1,output:this,type:e,source:t,metadata:r};if("video"===o.type){const e=this.format.getSupportedVideoCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(o.source._codec));if(!e.includes(o.source._codec))throw new Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}else if("audio"===o.type){const e=this.format.getSupportedAudioCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(o.source._codec));if(!e.includes(o.source._codec))throw new Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}else if("subtitle"===o.type){const e=this.format.getSupportedSubtitleCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(o.source._codec));if(!e.includes(o.source._codec))throw new Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}this._tracks.push(o),t._connectedTrack=o}async start(){const e=this.format.getSupportedTrackCounts();for(const t of fu){const r=this._tracks.reduce((e,r)=>e+(r.type===t?1:0),0),i=e[t].min;if(r<i)throw new Error(i===e[t].max?`${this.format._name} requires exactly ${i} ${t} track${1===i?"":"s"}.`:`${this.format._name} requires at least ${i} ${t} track${1===i?"":"s"}.`)}const t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track`+(1===t?"":"s")+".":`${this.format._name} requires at least ${t} track`+(1===t?"":"s")+".");if("canceled"===this.state)throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();const e=await this._mutex.acquire();await this._muxer.start();const t=this._tracks.map(e=>e.source._start());await Promise.all(t),e()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){return this._cancelPromise?(console.warn("Output has already been canceled."),this._cancelPromise):"finalizing"!==this.state&&"finalized"!==this.state?this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await this._writer.close(),e()})():void console.warn("Output has already been finalized.")}async finalize(){if("pending"===this.state)throw new Error("Cannot finalize before starting.");if("canceled"===this.state)throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}}var gu="VideoRange";function vu(){return i(this,void 0,void 0,function(){return a(this,function(e){return[2,new Promise(function(e,t){var r=indexedDB.open("VideoEditorDB",1);r.onupgradeneeded=function(e){var t=e.target.result;t.objectStoreNames.contains(gu)||t.createObjectStore(gu,{keyPath:"id"})},r.onsuccess=function(){e(r.result)},r.onerror=function(){t("IndexedDB Error: ".concat(r.error))}})]})})}function yu(e){return new Promise(function(t,r){e.onsuccess=function(){return t(e.result)},e.onerror=function(){return r(e.error)}})}function bu(e){return new Promise(function(t,r){e.oncomplete=function(){return t(void 0)},e.onerror=function(){return r(e.error)}})}function ku(e,t){return i(this,void 0,void 0,function(){var r;return a(this,function(i){switch(i.label){case 0:return t?[3,2]:[4,vu()];case 1:t=i.sent(),i.label=2;case 2:return r=t.transaction(gu,"readonly"),[2,yu(r.objectStore(gu).get(e))]}})})}function Tu(e,t){return i(this,void 0,void 0,function(){var r;return a(this,function(i){switch(i.label){case 0:return t?[3,2]:[4,vu()];case 1:t=i.sent(),i.label=2;case 2:return r=t.transaction(gu,"readwrite"),[4,yu(r.objectStore(gu).put(e))];case 3:return i.sent(),[4,bu(r)];case 4:return i.sent(),[2]}})})}var wu,Su,xu,Cu=4194304;function Eu(e,t,n,s,o){return i(this,void 0,void 0,function(){var c,l,u,h,d,f,m,p,g,v,y,b;return a(this,function(k){switch(k.label){case 0:return F.indexedDB?[3,4]:[4,fetch(e,r(r({},o),{cache:"force-cache",headers:{"Cache-Control":"max-age=31536000",Range:"bytes=".concat(t,"-").concat(n)}}))];case 1:return 206!==(c=k.sent()).status?[3,3]:[4,c.arrayBuffer()];case 2:return[2,{status:206,arrayBuffer:k.sent()}];case 3:return[2,{status:c.status}];case 4:for(l=[],u=Cu*Math.floor(t/Cu),h=u;u<=n;)d=Math.min(s-1,u+Cu-1),l.push([u,d]),u=d+1;return[4,vu()];case 5:return f=k.sent(),[4,Promise.all(l.map(function(t){return function(e,t,n,s,o){return i(this,void 0,void 0,function(){var i,c,l,u;return a(this,function(a){switch(a.label){case 0:return[4,ku(i=e+":"+t+"-"+n,s)];case 1:return(c=a.sent())?[2,{status:206,arrayBuffer:c.arrayBuffer}]:(console.log("miss",i),[4,fetch(e,r(r({},o),{cache:"force-cache",headers:{"Cache-Control":"max-age=31536000",Range:"bytes=".concat(t,"-").concat(n)}}))]);case 2:return 206!==(l=a.sent()).status?[3,5]:[4,l.arrayBuffer()];case 3:return u=a.sent(),[4,Tu({id:i,arrayBuffer:u})];case 4:return a.sent(),[2,{status:206,arrayBuffer:u}];case 5:return[2,{status:l.status}]}})})}(e,t[0],t[1],f,o)}))];case 6:for(m=k.sent(),p=new Uint8Array(l.length*Cu*8),g=0,v=m.length;g<v;g++){if(206!==(y=m[g]).status)return[2,{status:y.status}];b=new Uint8Array(y.arrayBuffer),p.set(b,g*Cu)}return[2,{status:206,arrayBuffer:p.buffer.slice(t-h,n-h+1)}]}})})}function Au(e){return i(this,void 0,void 0,function(){return a(this,function(t){return[2,new Promise(function(t){return setTimeout(t,e)})]})})}!function(e){e[e.META=0]="META",e[e.DECODE=1]="DECODE",e[e.DECODE_FRAME=2]="DECODE_FRAME",e[e.RELEASE=3]="RELEASE"}(wu||(wu={})),function(e){e.META="meta",e.ERROR="error",e.DECODED="decoded",e.DECODED_FRAME="decoded_frame"}(Su||(Su={})),function(e){e[e.NONE=0]="NONE",e[e.DECODING=1]="DECODING",e[e.DECODED=2]="DECODED",e[e.DECODED_FRAME=3]="DECODED_FRAME",e[e.ERROR=4]="ERROR"}(xu||(xu={}));var Pu,Iu,Ru={},Ou=function(e){return i(void 0,void 0,void 0,function(){var t,r,n,o,c,l,u,h,d,f,m,p,g,v,y,b,k,T,w,S,x,C,E,A,P,I,R,O,M,_,D,B,F,N,L,U,z,W,V,H,j,X,q,G,K,Y,$,Q,Z,J,ee,te,re,ie,ae,ne,se,oe,ce,le,ue,he,de,fe,me,pe,ge,ve,ye,be,ke,Te,we,Se,xe,Ce,Ee,Ae,Pe,Ie,Re,Oe,Me,_e,De,Be,Fe,Ne,Le,Ue,ze,We;return a(this,function(Ve){switch(Ve.label){case 0:return t=e.data,r=t.url,n=t.id,o=t.type,c=t.isWorker,l=function(e){var t={url:r,type:Su.ERROR,data:e};return c&&self.postMessage(t),{data:t}},Ru[r]||(Ru[r]={gopList:[]}),u=Ru[r],o!==wu.META?[3,38]:[4,fetch(r,{method:"HEAD"})];case 1:if(h=Ve.sent(),!(d=h.headers.get("content-length"))||200!==h.status&&304!==h.status)return[2,l("Unknown content-length")];f=parseInt(d),m={duration:0,fileSize:f},p=void 0,p=e.data.preloadAll?new Bo(r):new Fo({read:function(e,t){return i(void 0,void 0,void 0,function(){var i;return a(this,function(a){switch(a.label){case 0:return[4,Eu(r,e,t-1,f)];case 1:if(!(i=a.sent().arrayBuffer))throw new Error("Missing buffer in range: "+e+"-"+(t-1));return[2,new Uint8Array(i)]}})})},getSize:function(){return i(void 0,void 0,void 0,function(){return a(this,function(e){return[2,f]})})},prefetchProfile:"network"}),g=new Uo({formats:Oo,source:p}),Ve.label=2;case 2:return Ve.trys.push([2,4,,5]),[4,g.computeDuration()];case 3:return v=Ve.sent(),m.duration=1e3*v,[3,5];case 4:return y=Ve.sent(),[2,l(y.message)];case 5:return[4,g.getPrimaryVideoTrack()];case 6:return(b=Ve.sent())?(u.videoTrack=b,[4,b.computeDuration()]):[3,21];case 7:fe=Ve.sent(),re=new mn(b),Ve.label=8;case 8:Ve.trys.push([8,13,14,19]),k=!0,T=s(re.packets(void 0,void 0,{metadataOnly:!0})),Ve.label=9;case 9:return[4,T.next()];case 10:if(w=Ve.sent(),we=w.done)return[3,12];if(Ce=w.value,k=!1,"key"===(_=Ce).type){if(S=u.gopList.length){if(L=u.gopList[S-1],e.data.gopMinDuration&&1e3*_.timestamp-L.timestamp<e.data.gopMinDuration)return[3,11];L.duration=L.audioDuration=1e3*_.timestamp-L.timestamp}u.gopList.push({state:xu.NONE,index:u.gopList.length,sequenceNumber:_.sequenceNumber,timestamp:1e3*_.timestamp,duration:1e3*_.duration,audioTimestamp:1e3*_.timestamp,audioDuration:1e3*_.duration,users:[]})}Ve.label=11;case 11:return k=!0,[3,9];case 12:return[3,19];case 13:return x=Ve.sent(),Se={error:x},[3,19];case 14:return Ve.trys.push([14,,17,18]),k||we||!(xe=T.return)?[3,16]:[4,xe.call(T)];case 15:Ve.sent(),Ve.label=16;case 16:return[3,18];case 17:if(Se)throw Se.error;return[7];case 18:return[7];case 19:return(N=u.gopList.length)&&((L=u.gopList[N-1]).duration=L.audioDuration=1e3*fe-L.timestamp),[4,b.getFirstTimestamp()];case 20:de=Ve.sent(),m.video={id:b.id,languageCode:b.languageCode,codec:b.codec,name:b.name,codedWidth:b.codedWidth,codedHeight:b.codedHeight,displayWidth:b.displayWidth,displayHeight:b.displayHeight,width:b.displayWidth,height:b.displayHeight,timeResolution:b.timeResolution,rotation:b.rotation,timestamp:1e3*de,duration:1e3*fe},Ve.label=21;case 21:return[4,g.getPrimaryAudioTrack()];case 22:return(C=Ve.sent())?(u.audioTrack=C,[4,C.computeDuration()]):[3,37];case 23:return fe=Ve.sent(),[4,C.getFirstTimestamp()];case 24:if(de=Ve.sent(),m.audio={id:C.id,languageCode:C.languageCode,codec:C.codec,name:C.name,numberOfChannels:C.numberOfChannels,sampleRate:C.sampleRate,timestamp:1e3*de,duration:1e3*fe},b)return[3,37];E=e.data.gopMinDuration||5e3,re=new mn(C),A=-1,P=!0,I=0,Ve.label=25;case 25:Ve.trys.push([25,30,31,36]),R=!0,O=s(re.packets(void 0,void 0,{metadataOnly:!0})),Ve.label=26;case 26:return[4,O.next()];case 27:if(M=Ve.sent(),Ee=M.done)return[3,29];Ie=M.value,R=!1,_=Ie,-1===A&&(A=_.timestamp),D=_.timestamp-A,(P||1e3*D>=E)&&(P=!1,(B=u.gopList.length)&&((L=u.gopList[B-1]).duration=L.audioDuration=1e3*_.timestamp-L.timestamp),u.gopList.push({state:xu.NONE,index:u.gopList.length,sequenceNumber:I,timestamp:1e3*_.timestamp,duration:1e3*_.duration,audioTimestamp:1e3*_.timestamp,audioDuration:1e3*_.duration,users:[]}),A=_.timestamp),I++,Ve.label=28;case 28:return R=!0,[3,26];case 29:return[3,36];case 30:return F=Ve.sent(),Ae={error:F},[3,36];case 31:return Ve.trys.push([31,,34,35]),R||Ee||!(Pe=O.return)?[3,33]:[4,Pe.call(O)];case 32:Ve.sent(),Ve.label=33;case 33:return[3,35];case 34:if(Ae)throw Ae.error;return[7];case 35:return[7];case 36:(N=u.gopList.length)&&((L=u.gopList[N-1]).duration=L.audioDuration=1e3*fe-L.timestamp),Ve.label=37;case 37:return U=u.gopList.map(function(e){return{index:e.index,sequenceNumber:e.sequenceNumber,timestamp:e.timestamp,duration:e.duration,audioTimestamp:e.audioTimestamp,audioDuration:e.audioDuration}}),be={url:r,type:Su.META,data:{meta:m,simpleGOPList:U}},c&&self.postMessage(be),[2,{data:be}];case 38:return o!==wu.DECODE?[3,64]:(ke=u.gopList[e.data.index])&&ke.state!==xu.ERROR?ke.state===xu.DECODED?[2]:(ke.users.includes(n)||ke.users.push(n),[4,Au(100)]):[2];case 39:if(Ve.sent(),!ke.users.includes(n))return[2];if(ke.state===xu.DECODING||ke.state===xu.DECODED)return[2];if(ke.state=xu.DECODING,z=[],!u.videoTrack)return[3,51];re=new kn(u.videoTrack),Ve.label=40;case 40:Ve.trys.push([40,45,46,51]),W=!0,V=s(re.samples(.001*ke.timestamp,.001*(ke.timestamp+ke.duration))),Ve.label=41;case 41:return[4,V.next()];case 42:if(H=Ve.sent(),Re=H.done)return[3,44];_e=H.value,W=!1,le=_e,z.push(le.toVideoFrame()),le.close(),Ve.label=43;case 43:return W=!0,[3,41];case 44:return[3,51];case 45:return j=Ve.sent(),Oe={error:j},[3,51];case 46:return Ve.trys.push([46,,49,50]),W||Re||!(Me=V.return)?[3,48]:[4,Me.call(V)];case 47:Ve.sent(),Ve.label=48;case 48:return[3,50];case 49:if(Oe)throw Oe.error;return[7];case 50:return[7];case 51:if(Z=[],J=0,ee=-1,te=0,!u.audioTrack||e.data.mute||ke.didAudioChunk)return[3,63];ke.didAudioChunk=!0,re=new Sn(u.audioTrack),ie=.001*ke.timestamp,ae=.001*(ke.timestamp+ke.duration),ne=re.samples(ie,ae),Ve.label=52;case 52:Ve.trys.push([52,57,58,63]),X=!0,q=s(ne),Ve.label=53;case 53:return[4,q.next()];case 54:if(G=Ve.sent(),De=G.done)return[3,56];if(Ne=G.value,X=!1,J=(le=Ne).sampleRate,ue=le.numberOfChannels,he=le.numberOfFrames,de=le.timestamp,fe=le.duration,de>=ae&&ke.index<u.gopList.length-1||de<ie)return[3,55];for(-1===ee&&(ee=1e3*de),te=1e3*de-ee+1e3*fe,me=[],pe=0;pe<ue;pe++)ge=new Float32Array(he),le.copyTo(ge,{planeIndex:pe,format:"f32-planar"}),me.push(ge);Z.push({format:"f32-planar",channels:me,sampleRate:J,numberOfFrames:he,numberOfChannels:ue,timestamp:1e3*de,duration:1e3*fe}),le.close(),Ve.label=55;case 55:return X=!0,[3,53];case 56:return[3,63];case 57:return K=Ve.sent(),Be={error:K},[3,63];case 58:return Ve.trys.push([58,,61,62]),X||De||!(Fe=q.return)?[3,60]:[4,Fe.call(q)];case 59:Ve.sent(),Ve.label=60;case 60:return[3,62];case 61:if(Be)throw Be.error;return[7];case 62:return[7];case 63:return ke.state!==xu.DECODING?(ke.didAudioChunk=!1,z.forEach(function(e){e.close()}),[2]):(ke.state=xu.DECODED,Y=[],z.forEach(function(e){return Y.push(e)}),Z.forEach(function(e){e.channels.forEach(function(e){Y.push(e.buffer)})}),be={url:r,type:Su.DECODED,data:{index:e.data.index,videoFrames:z,audioChunks:Z,sampleRate:J,audioTimeStamp:ee,audioDuration:te}},c&&self.postMessage(be,Y),[2,{data:be}]);case 64:return o!==wu.DECODE_FRAME?[3,79]:(ke=u.gopList[e.data.index])&&ke.state!==xu.ERROR?($=e.data.time,Q=void 0,u.videoTrack?[4,(re=new kn(u.videoTrack)).getSample(.001*$)]:[3,66]):[2];case 65:(le=Ve.sent())&&(Q=le.toVideoFrame(),le.close()),Ve.label=66;case 66:if(Z=[],J=0,ee=-1,te=0,!u.audioTrack||e.data.mute||ke.didAudioChunk)return[3,78];ke.didAudioChunk=!0,re=new Sn(u.audioTrack),ie=.001*ke.timestamp,ae=.001*(ke.timestamp+ke.duration),ne=re.samples(ie,ae),Ve.label=67;case 67:Ve.trys.push([67,72,73,78]),se=!0,oe=s(ne),Ve.label=68;case 68:return[4,oe.next()];case 69:if(ce=Ve.sent(),Le=ce.done)return[3,71];if(We=ce.value,se=!1,J=(le=We).sampleRate,ue=le.numberOfChannels,he=le.numberOfFrames,de=le.timestamp,fe=le.duration,de>=ae&&ke.index<u.gopList.length-1||de<ie)return[3,70];for(-1===ee&&(ee=1e3*de),te=1e3*de-ee+1e3*fe,me=[],pe=0;pe<ue;pe++)ge=new Float32Array(he),le.copyTo(ge,{planeIndex:pe,format:"f32-planar"}),me.push(ge);Z.push({format:"f32-planar",channels:me,sampleRate:J,numberOfFrames:he,numberOfChannels:ue,timestamp:1e3*de,duration:1e3*fe}),le.close(),Ve.label=70;case 70:return se=!0,[3,68];case 71:return[3,78];case 72:return ve=Ve.sent(),Ue={error:ve},[3,78];case 73:return Ve.trys.push([73,,76,77]),se||Le||!(ze=oe.return)?[3,75]:[4,ze.call(oe)];case 74:Ve.sent(),Ve.label=75;case 75:return[3,77];case 76:if(Ue)throw Ue.error;return[7];case 77:return[7];case 78:return ye=[],Q&&ye.push(Q),Z&&Z.forEach(function(e){e.channels.forEach(function(e){ye.push(e.buffer)})}),be={url:r,type:Su.DECODED_FRAME,data:{index:e.data.index,time:$,videoFrame:Q,audioChunks:Z,sampleRate:J,audioTimeStamp:ee,audioDuration:te}},c&&self.postMessage(be,ye),[2,{data:be}];case 79:if(o===wu.RELEASE){if(!(ke=u.gopList[e.data.index]))return[2];(Te=ke.users.indexOf(e.data.id))>-1&&ke.users.splice(Te,1),ke.users.length||(ke.state=xu.NONE)}Ve.label=80;case 80:return[2]}})})};self.onmessage=Ou,function(e){e.META="meta",e.LOADED="loaded",e.ERROR="error",e.PROGRESS="progress",e.CANPLAY="canplay",e.AUDIO_BUFFER="audio_buffer"}(Pu||(Pu={})),function(e){e[e.NONE=0]="NONE",e[e.LOADING_META=1]="LOADING_META",e[e.META=2]="META",e[e.LOADED=3]="LOADED",e[e.ERROR=4]="ERROR"}(Iu||(Iu={}));var Mu,_u={},Du=0,Bu=0,Fu=0,Nu=function(e){function i(t){var r=e.call(this)||this;return r.url=t,r.id=Du++,r.currentTime=-1/0,r.gopIndex=-1,r.error=!1,r}return t(i,e),i.prototype.initWorker=function(){var e=this;if(!Mu){if(F.decoderWorker)Mu=new Worker(F.decoderWorker);else if(F.decoderWorkerStr){var t=new Blob([F.decoderWorkerStr.trim()],{type:"application/javascript"}),i=URL.createObjectURL(t);Mu=new Worker(i)}var a=function(t){var i,a,n,s;if(null==t?void 0:t.data){var o=t.data,c=o.url,l=o.type,u=o.data,h=_u[c];if(h)if(l===Su.META)h.state=Iu.META,h.meta=u.meta,h.gopList=u.simpleGOPList.map(function(e){return r(r({},e),{state:xu.NONE,videoFrames:[],users:[]})}),h.metaList.splice(0).forEach(function(e){e.start(e.currentTime),e.emit(Pu.META,u.meta)});else if(l===Su.DECODED){var d=h.gopList[u.index];if(d){if(d.state=xu.DECODED,d.videoFrames.forEach(function(e){return e.close()}),null===(i=d.audioBufferSourceNode)||void 0===i||i.stop(),null===(a=d.audioBufferSourceNode)||void 0===a||a.disconnect(),d.audioBuffer=void 0,d.videoFrames=u.videoFrames,null===(n=u.audioChunks)||void 0===n?void 0:n.length){var f=u.audioChunks.reduce(function(e,t){return e+t.numberOfFrames},0),m=new OfflineAudioContext(u.audioChunks[0].numberOfChannels,f,u.sampleRate).createBuffer(u.audioChunks[0].channels.length,f,u.sampleRate),p=0;u.audioChunks.forEach(function(e){for(var t=0;t<e.channels.length;t++){m.getChannelData(t).set(e.channels[t],p)}p+=e.numberOfFrames}),d.audioBuffer=m}d.users.forEach(function(e){e.gopIndex===d.index&&e.emit(Pu.CANPLAY,d),d.audioBuffer&&e.gopIndex<d.index&&e.emit(Pu.AUDIO_BUFFER,d)})}}else if(l===Su.DECODED_FRAME){var g=h.singleHash[u.time]=h.singleHash[u.time]||{videoFrame:u.videoFrame,users:[]};g.users.includes(e)||g.users.push(e);var v=h.gopList[u.index];if(v){if(v.state=xu.DECODED_FRAME,null===(s=u.audioChunks)||void 0===s?void 0:s.length){f=u.audioChunks.reduce(function(e,t){return e+t.numberOfFrames},0);var y=new OfflineAudioContext(u.audioChunks[0].numberOfChannels,f,u.sampleRate).createBuffer(u.audioChunks[0].channels.length,f,u.sampleRate),b=0;u.audioChunks.forEach(function(e){for(var t=0;t<e.channels.length;t++){y.getChannelData(t).set(e.channels[t],b)}b+=e.numberOfFrames}),v.audioBuffer=y}v.users.forEach(function(e){e.gopIndex===v.index&&e.currentTime===u.time&&e.emit(Pu.CANPLAY,v)})}}else l===Su.ERROR&&h.metaList.forEach(function(e){e.error=!0,e.emit(Pu.ERROR,u)})}};Mu?Mu.onmessage=a:this.onMessage=a}},i.prototype.start=function(e){var t,r=this;this.initWorker();var i=this.currentTime;this.currentTime=e;var a=this.url,n=this.id,s=_u[a];if(s)if(s.state===Iu.LOADING_META)s.metaList.includes(this)||(s.metaList.push(this),s.loadList.push(this),s.count++);else if(s.state===Iu.META){if(s.loadList.includes(this)||(s.loadList.push(this),s.count++,this.emit(Pu.META,s.meta)),F.singleSample&&i>=0){var o=s.singleHash[i];if(o){var c=o.users.indexOf(this);c>-1&&o.users.splice(c,1),o.users.length||(null===(t=o.videoFrame)||void 0===t||t.close(),delete s.singleHash[i])}}this.process(e)}else s.state===Iu.ERROR&&this.emit(Pu.ERROR,s.error);else{_u[a]={state:Iu.LOADING_META,metaList:[this],loadList:[this],meta:{duration:0,fileSize:0},gopList:[],singleHash:{},count:1};var l={url:a,id:n,type:wu.META,messageId:Bu++,isWorker:!!F.decoderWorker||!!F.decoderWorkerStr,preloadAll:F.preloadAll,gopMinDuration:F.gopMinDuration};Mu?Mu.postMessage(l):Ou({data:l}).then(function(e){r.onMessage&&r.onMessage(e)})}},i.prototype.process=function(e){if(e<-F.decodeNextDuration)this.releaseGOPList();else{var t=_u[this.url];if(t&&t.state!==Iu.NONE&&t.state!==Iu.LOADING_META){var r=t.meta.duration,i=t.gopList;if(i.length)if(e>=r+F.decodeNextDuration)this.releaseGOPList();else{var a=this.getForwardsNearestGOPIndex(e);this.gopIndex=a;var n=i[a];if(n){this.decodeGOP(n,e);for(var s=a-1;s>=0;s--){var o=i[s];o&&o.timestamp+o.duration<e-F.releasePrevDuration&&this.releaseGOP(o)}if(!F.singleSample){s=a+1;for(var c=i.length;s<c;s++){var l=i[s];l&&l.timestamp<e+F.decodeNextDuration?this.decodeGOP(l):l&&l.timestamp>=e+F.decodeNextDuration&&this.releaseGOP(l)}}}}}}},i.prototype.getForwardsNearestGOPIndex=function(e){var t=_u[this.url],r=t.meta.duration,i=t.gopList;if(e<-F.decodeNextDuration||!i.length||e>r+F.decodeNextDuration)return-1;if(1===i.length||e<=0)return 0;if(e>r)return i.length-1;for(var a=0,n=i.length-1;a<n;){if(a===n-1)return i[n].timestamp<=e?n:a;var s=a+(n-a>>1),o=i[s].timestamp;if(o===e)return s;o>e?n=Math.max(s-1,a+1):a=Math.min(s,n-1)}return-1},i.prototype.getFrameByTime=function(e){var t,r=_u[this.url],i=r.meta.duration,a=r.gopList;if(!(e<0||!a.length||e>i)){if(F.singleSample)return null===(t=r.singleHash[e])||void 0===t?void 0:t.videoFrame;var n;if(1===a.length)n=a[0];else(o=this.getForwardsNearestGOPIndex(e))>-1&&(n=a[o]);if(n){var s=n.videoFrames;if(!s.length)return;if(1===s.length)return s[0];for(var o=0,c=s.length-1;o<c;){if(o===c-1){var l=s[c];return.001*l.timestamp<=e?l:s[o]}var u=o+(c-o>>1),h=s[u],d=.001*h.timestamp;if(d===e||d<e&&d+.001*(h.duration||0)>e)return s[u];d>e?c=Math.max(u-1,o+1):o=Math.min(u,c-1)}}}},i.prototype.decodeGOP=function(e,t){var r=this;if(e.state!==xu.ERROR&&e.state!==xu.DECODED&&(e.users.includes(this)||e.users.push(this),e.state!==xu.DECODING))if(e.state=xu.DECODING,e.videoFrames.splice(0).forEach(function(e){return e.close()}),e.audioBufferSourceNode&&(e.audioBufferSourceNode.stop(),e.audioBufferSourceNode.disconnect(),e.audioBufferSourceNode=void 0),F.singleSample){var i={url:this.url,id:Du,type:wu.DECODE_FRAME,messageId:Bu++,isWorker:!!F.decoderWorker||!!F.decoderWorkerStr,index:e.index,time:t,mute:F.mute,spf:Fu};Mu?Mu.postMessage(i):Ou({data:i}).then(function(e){r.onMessage&&r.onMessage(e)})}else{e.audioBuffer=void 0;i={url:this.url,type:wu.DECODE,id:this.id,messageId:Bu++,isWorker:!!F.decoderWorker||!!F.decoderWorkerStr,index:e.index,mute:F.mute};Mu?Mu.postMessage(i):Ou({data:i}).then(function(e){r.onMessage&&r.onMessage(e)})}},i.prototype.releaseGOP=function(e){var t,r,i=this,a=e.users.indexOf(this);if(a>-1){e.users.splice(a,1),e.users.length||(e.state!==xu.DECODING&&e.state!==xu.DECODED||(e.state=xu.NONE),e.videoFrames.splice(0).forEach(function(e){return e.close()}),null===(t=e.audioBufferSourceNode)||void 0===t||t.stop(),null===(r=e.audioBufferSourceNode)||void 0===r||r.disconnect(),e.audioBuffer=void 0);var n={url:this.url,type:wu.RELEASE,id:this.id,index:e.index,messageId:Bu++,isWorker:!!F.decoderWorker||!!F.decoderWorkerStr};Mu?Mu.postMessage(n):Ou({data:n}).then(function(e){i.onMessage&&i.onMessage(e)})}},i.prototype.releaseGOPList=function(){var e=this;_u[this.url].gopList.forEach(function(t){e.releaseGOP(t)})},i.prototype.release=function(){this.releaseGOPList();var e=_u[this.url];if(!e)throw new Error("Unknown release url: "+this.url);var t=e.metaList.indexOf(this);t>-1&&e.metaList.splice(t,1),(t=e.loadList.indexOf(this))>-1&&e.loadList.splice(t,1),e.count--,e.count||delete _u[this.url]},Object.defineProperty(i.prototype,"gopList",{get:function(){var e;return null===(e=_u[this.url])||void 0===e?void 0:e.gopList},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"currentGOP",{get:function(){var e;return null===(e=_u[this.url])||void 0===e?void 0:e.gopList[this.gopIndex]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cache",{get:function(){return _u[this.url]},enumerable:!1,configurable:!0}),Object.defineProperty(i,"spf",{set:function(e){Fu=e},enumerable:!1,configurable:!0}),i}(R),Lu=function(e){function r(t){var r,i=e.call(this,t)||this;t.onMeta&&(i.onMeta=t.onMeta),t.onCanplay&&(i.onCanplay=t.onCanplay),t.onError&&(i.onError=t.onError),t.onWaiting&&(i.onWaiting=t.onWaiting),i._currentTime=t.currentTime||0,i._volumn=Math.max(0,Math.min(1,null!==(r=t.volumn)&&void 0!==r?r:1)),i.isPure=!0;var a=i._src=t.src||"";if(a){i._currentTime>=0&&(i.contentLoadingNum=1);var n=i._decoder=new Nu(a);n.on(Pu.META,function(e){if(i._metaData=e,i._currentTime>=0&&i._currentTime<e.duration?i.contentLoadingNum=1:i.contentLoadingNum=0,i.isMounted){var t=i.style,r=t.left,a=t.top,n=t.right,s=t.bottom,o=t.width,c=t.height;(r.u!==W.AUTO&&n.u!==W.AUTO||o.u!==W.AUTO)&&(a.u!==W.AUTO&&s.u!==W.AUTO||c.u!==W.AUTO)||i.refresh(Bt.REFLOW)}i.onMeta&&i.onMeta(e),i.emit(Rr,e)}),n.on(Pu.ERROR,function(e){ne.error(e),i.contentLoadingNum=0,i.onError&&i.onError(e),i.emit(Or,e),i.refresh()}),n.on(Pu.CANPLAY,function(e){var t=n.getFrameByTime(i._currentTime);i.videoFrame=t,i.contentLoadingNum=0,i.onCanplay&&i.onCanplay(),i.emit(Ir),i.refresh()}),n.on([Pu.CANPLAY,Pu.AUDIO_BUFFER],function(e){var t=i.root;if(t&&e.audioBuffer){var r=t.audioContext,a=i.timeAnimation;if("running"===(null==a?void 0:a.playState)&&r){var n=a.currentTime-a.delay;if(n>=e.timestamp+e.duration||a.duration<=e.timestamp)return;var s=r.createBufferSource();s.buffer=e.audioBuffer,i.gainNode||(i.gainNode=r.createGain(),i.gainNode.gain.value=i.volumn,i.gainNode.connect(r.destination)),s.connect(i.gainNode),n>=e.audioTimestamp?s.start(0,.001*(n-e.audioTimestamp),.001*(a.duration-n)):s.start(r.currentTime+.001*(e.audioTimestamp-n),0,.001*(a.duration-e.audioTimestamp))}}}),n.start(i._currentTime)}return i}return t(r,e),r.prototype.lay=function(t){e.prototype.lay.call(this,t);var r=this,i=r.style,a=r.computedStyle,n=r._metaData,s=i.left,o=i.top,c=i.right,l=i.bottom,u=i.width,h=i.height;if(null==n?void 0:n.video){var d=(s.u===W.AUTO||c.u===W.AUTO)&&u.u===W.AUTO,f=(o.u===W.AUTO||l.u===W.AUTO)&&h.u===W.AUTO;d&&(a.width=f?n.video.width:n.video.height*a.height/n.video.height,s.u===W.AUTO&&c.u===W.AUTO?(a.left=0,a.right=t.w-a.width):s.u===W.AUTO?a.left=t.w-a.right-a.width:c.u===W.AUTO&&(a.right=t.w-a.left-a.width)),f&&(a.height=d?n.video.height:n.video.height*a.width/n.video.width,o.u===W.AUTO&&l.u===W.AUTO?(a.top=0,a.bottom=t.h-a.height):o.u===W.AUTO?a.top=t.h-a.bottom-a.height:l.u===W.AUTO&&(a.bottom=t.h-a.top-a.height))}},r.prototype.calRepaintStyle=function(t){e.prototype.calRepaintStyle.call(this,t);var r=this.computedStyle,i=this.videoFrame;if(this.isPure=r.backgroundColor[3]<=0,this.isPure&&i){var a=r.objectFit,n=r.borderTopLeftRadius,s=r.borderTopRightRadius,o=r.borderBottomLeftRadius,c=r.borderBottomRightRadius;if(a!==ie.COVER&&a!==ie.FILL||!(n||s||o||c)){if(a===ie.CONTAIN&&(n||s||o||c)){var l=i.displayWidth/i.displayHeight,u=r.width/r.height;if(u>l){var h=r.height*l,d=.5*(r.width-h);(n>d||s>d||o>d||c>d)&&(this.isPure=!1)}else if(u<l){var f=r.width/l,m=.5*(r.height-f);(n>m||s>m||o>m||c>m)&&(this.isPure=!1)}else this.isPure=!1}}else this.isPure=!1}},r.prototype.calContent=function(){return this.hasContent=!1,this.computedStyle.visibility===ee.HIDDEN||0===this.computedStyle.opacity||(this._videoFrame||this.computedStyle.backgroundColor[3]>0)&&(this.hasContent=!0),this.hasContent},r.prototype.renderCanvas=function(){var t,r=this,i=r.isPure,a=r.videoFrame,n=r.computedStyle;if(i){if(null===(t=this.canvasCache)||void 0===t||t.release(),a&&(a.displayWidth>F.maxTextureSize||a.displayHeight>F.maxTextureSize))if((y=this.canvasCache=Zt.getVideoFrameInstance(a.displayWidth,a.displayHeight,a)).available=!0,1===y.getCount()){var s=n.width,o=n.height,c=n.objectFit,l=0,u=0,h=a.displayWidth/a.displayHeight,d=s/o;if(c===ie.CONTAIN){if(d>h)l=.5*(s-(k=o*h)),s=k;else if(d<h){u=.5*(o-(T=s/h)),o=T}}else if(c===ie.COVER){if(d>h)u=.5*(o-(T=s/h)),o=T;else if(d<h){l=.5*(s-(k=o*h)),s=k}}for(var f=0,m=(E=y.list).length;f<m;f++){var p=E[f],g=p.x,v=p.y;p.os.ctx.drawImage(a,-g+l,-v+u,s,o)}}}else{e.prototype.renderCanvas.call(this);var y,b=this._bboxInt||this.bboxInt,k=(g=b[0],v=b[1],b[2]-g),T=b[3]-v;l=0,u=0,s=n.width,o=n.height,c=n.objectFit;if(a){h=a.displayWidth/a.displayHeight,d=s/o;if(c===ie.CONTAIN){if(d>h){var w=o*h;l+=.5*(s-w),s=w}else if(d<h){var S=s/h;u+=.5*(o-S),o=S}}else if(c===ie.COVER)if(d>h){var x=s/h;u=.5*(o-x),o=x}else if(d<h){var C=o*h;l=.5*(s-C),s=C}}(y=this.canvasCache=new Zt(k,T,-g,-v)).available=!0;var E=y.list;if(n.backgroundColor[3]>0){var A=this.getBackgroundCoords(g,v);E.forEach(function(e){var t=e.x,r=e.y,i=e.os.ctx;i.fillStyle=he(n.backgroundColor),i.beginPath(),Er(i,A,1,-t,-r),i.closePath(),i.fill()})}for(f=0,m=E.length;f<m;f++){var P=E[f],I=P.x,R=P.y,O=P.os.ctx,M=-I,_=-R;a&&O.drawImage(a,M+l,_+u,s,o)}}},r.prototype.genTexture=function(t){var r=this,i=r.isPure,a=r.videoFrame,n=r.canvasCache;if(i){if(a)if(a.displayWidth>F.maxTextureSize||a.displayHeight>F.maxTextureSize)if((null==n?void 0:n.available)&&ir.hasCanvasCacheInstance(n)){var s=ir.getCanvasCacheInstance(t,n,this._rect||this.rect);this.textureTarget=this.textureCache=s}else{this.renderCanvas();s=ir.getCanvasCacheInstance(t,this.canvasCache,this._rect||this.rect);this.textureTarget=this.textureCache=s,this.canvasCache.release()}else{var o=this.computedStyle,c=o.width,l=o.height,u=o.objectFit,h=this._rect||this.rect,d=(s=void 0,a.displayWidth/a.displayHeight),f=c/l;if(u===ie.CONTAIN){if(f>d){var m=.5*(c-(v=l*d));(h=h.slice(0))[0]+=m,h[2]-=m}else if(f<d){m=.5*(l-(p=c/d));(h=h.slice(0))[1]+=m,h[3]-=m}}else if(u===ie.COVER)if(f>d){var p=c/d;s={x1:0,y1:g=(m=.5*Math.abs(l-p))/p,x3:1,y3:1-g}}else if(f<d){var g,v=l*d;s={x1:g=(m=.5*Math.abs(c-v))/v,y1:0,x3:1-g,y3:1}}var y=ir.getVideoFrameInstance(t,a,h,s);this.textureTarget=this.textureCache=y}}else e.prototype.genTexture.call(this,t)},r.prototype.calContentLoading=function(){var t=e.prototype.calContentLoading.call(this);if(t){if(this._currentTime>=0){if(!this._metaData)return t;if(this._currentTime<this._metaData.duration)return t}return 0}return t},r.prototype.release=function(){e.prototype.release.call(this);var t=this._decoder,r=this.gainNode;t&&t.release(),r&&(r.disconnect(),this.gainNode=void 0)},r.prototype.timeAnimate=function(e,t){var r;null===(r=this.timeAnimation)||void 0===r||r.remove();var i=this.timeAnimation=new Uu(this,e,t);return this.initAnimate(i,t)},Object.defineProperty(r.prototype,"src",{get:function(){return this._src},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"currentTime",{get:function(){return this._currentTime},set:function(e){var t;if(this._currentTime!==e){this._currentTime=e;var r=this._decoder;if(r){var i=e;r.start(i);var a=this._videoFrame,n=r.getFrameByTime(i);this.videoFrame=n,!n&&(null===(t=r.currentGOP)||void 0===t?void 0:t.state)===xu.DECODING&&e>=0&&!r.error&&(this._metaData&&this._metaData.duration,this.contentLoadingNum=1),a&&!n&&this._metaData&&e>=0&&e<this._metaData.duration&&!r.error&&(this.onWaiting&&this.onWaiting(),this.emit(Pr))}}},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"duration",{get:function(){var e;return(null===(e=this._metaData)||void 0===e?void 0:e.duration)||0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"metaData",{get:function(){return this._metaData},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"volumn",{get:function(){return this._volumn},set:function(e){var t=Math.max(0,Math.min(1,e));this._volumn!==t&&(this._volumn=t,this.gainNode&&(this.gainNode.gain.value=t))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"decoder",{get:function(){return this._decoder},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"videoFrame",{get:function(){return this._videoFrame},set:function(e){this._videoFrame!==e&&(this._videoFrame=e,this.refresh())},enumerable:!1,configurable:!0}),r}(wr),Uu=function(e){function r(t,r,i){var a=e.call(this,t,i)||this;return a.node=t,a._timeArea=[r,r+a.duration],a._timeAreaR=a._timeArea.slice(0).reverse(),a.currentTimeArea=a._timeArea,a.originTime=t.currentTime,a.setCurrentTimeArea(),a}return t(r,e),r.prototype.setCurrentTimeArea=function(){var e=this.direction,t=this._playCount;this.currentTimeArea="backwards"===e?this._timeArea:"alternate"===e?t%2==0?this._timeAreaR:this._timeArea:"alternateReverse"===e?t%2==0?this._timeArea:this._timeAreaR:this._timeArea},r.prototype.finish=function(){"finished"!==this._playState&&(e.prototype.finish.call(this),this.onFirstInEndDelay())},r.prototype.cancel=function(){"idle"!==this._playState&&(e.prototype.cancel.call(this),this.node.currentTime=this.originTime)},r.prototype.onRunning=function(t,r){var i;e.prototype.onRunning.call(this,t,r);var a=this,n=a.node,s=a.duration,o=a.delay,c=a.iterations,l=a.currentTimeArea,u=a.time,h=this._currentTime;if(h<o)n.currentTime=h-o;else{var d=this._playCount>=c-1,f=u/s;this.easing&&(f=this.easing(f)),d&&f>=1?n instanceof Lu&&u-s>=F.releasePrevDuration&&n.computedStyle.visibility===ee.HIDDEN&&(null===(i=n.decoder)||void 0===i||i.releaseGOPList(),n.videoFrame=void 0):n.currentTime=Math.floor(l[0]+(l[1]-l[0])*f)}},r.prototype.onFirstInDelay=function(){var e=this,t=e.fill,r=e.currentTimeArea,i=e.node;"backwards"!==t&&"both"!==t||(i.currentTime=r[0])},r.prototype.onFirstInEndDelay=function(){var e=this.fill,t=this.node;if("forwards"===e||"both"===e){var r=this.currentTimeArea;t.currentTime=r[r.length-1]}else t.currentTime=this.originTime},r.prototype.onChangePlayCount=function(){this.setCurrentTimeArea()},Object.defineProperty(r.prototype,"area",{get:function(){return this._timeArea.slice(0)},enumerable:!1,configurable:!0}),r}(mr),zu=function(e){function r(t){var r,i=e.call(this,t)||this;t.onMeta&&(i.onMeta=t.onMeta),t.onCanplay&&(i.onCanplay=t.onCanplay),t.onError&&(i.onError=t.onError),t.onWaiting&&(i.onWaiting=t.onWaiting),i._currentTime=t.currentTime||0,i._volumn=Math.max(0,Math.min(1,null!==(r=t.volumn)&&void 0!==r?r:1));var a=i._src=t.src||"";if(a){i._currentTime>=0&&(i.contentLoadingNum=1);var n=i._decoder=new Nu(a);n.on(Pu.META,function(e){i._metaData=e,i._currentTime>=0&&i._currentTime<=e.duration?i.contentLoadingNum=1:i.contentLoadingNum=0,i.onMeta&&i.onMeta(e),i.emit(Rr)}),n.on(Pu.ERROR,function(e){ne.error(e),i.contentLoadingNum=0,i.onError&&i.onError(e),i.emit(Or),i.refresh()}),n.on(Pu.CANPLAY,function(e){i.contentLoadingNum=0,i.onCanplay&&i.onCanplay(),i.emit(Ir),i.refresh()}),n.on([Pu.CANPLAY,Pu.AUDIO_BUFFER],function(e){var t=i.root;if(t&&e.audioBuffer){var r=t.audioContext,a=i.timeAnimation;if("running"===(null==a?void 0:a.playState)&&r){var n=a.currentTime-a.delay;if(n>=e.timestamp+e.duration||a.duration<=e.timestamp)return;var s=r.createBufferSource();s.buffer=e.audioBuffer,i.gainNode||(i.gainNode=r.createGain(),i.gainNode.gain.value=i.volumn,i.gainNode.connect(r.destination)),s.connect(i.gainNode),n>=e.audioTimestamp?s.start(0,.001*(n-e.audioTimestamp),.001*(a.duration-n)):s.start(r.currentTime+.001*(e.audioTimestamp-n),0,.001*(a.duration-e.audioTimestamp))}}}),n.start(i._currentTime)}return i}return t(r,e),r.prototype.calContentLoading=function(){var t=e.prototype.calContentLoading.call(this);if(t){if(this._currentTime>=0){if(!this._metaData)return t;if(this._currentTime<this._metaData.duration)return t}return 0}return t},r.prototype.release=function(){e.prototype.release.call(this);var t=this,r=t.loader,i=t.audioBufferSourceNode,a=t.gainNode;(null==r?void 0:r.success)&&r.release(),i&&(i.stop(),i.disconnect(),this.audioBufferSourceNode=void 0),a&&(a.disconnect(),this.gainNode=void 0)},r.prototype.timeAnimate=function(e,t){var r;null===(r=this.timeAnimation)||void 0===r||r.remove();var i=this.timeAnimation=new Uu(this,e,t);return this.initAnimate(i,t)},Object.defineProperty(r.prototype,"src",{get:function(){return this._src},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"currentTime",{get:function(){return this._currentTime},set:function(e){if(this._currentTime!==e){this._currentTime=e;var t=this._decoder;if(t){var r=e,i=t.currentGOP;t.start(r);var a=t.currentGOP;!(null==a?void 0:a.audioBuffer)&&(null==a?void 0:a.state)===xu.DECODING&&e>=0&&!t.error&&(this._metaData&&this._metaData.duration,this.contentLoadingNum=1),(null==i?void 0:i.audioBuffer)&&!(null==a?void 0:a.audioBuffer)&&this._metaData&&e>=0&&e<this._metaData.duration&&!t.error&&(this.onWaiting&&this.onWaiting(),this.emit(Pr))}}},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"duration",{get:function(){var e;return(null===(e=this.loader)||void 0===e?void 0:e.duration)||0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"metaData",{get:function(){return this._metaData},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"volumn",{get:function(){return this._volumn},set:function(e){var t=Math.max(0,Math.min(1,e));this._volumn!==t&&(this._volumn=t,this.gainNode&&(this.gainNode.gain.value=t))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"decoder",{get:function(){return this._decoder},enumerable:!1,configurable:!0}),r}(wr),Wu=function(e){function r(t){var r=e.call(this)||this;return r.aniList=[],r.audioContext=t,r}return t(r,e),r.prototype.addAni=function(e){-1===this.aniList.indexOf(e)&&(this.aniList.push(e),1===this.aniList.length&&this.checkEvent())},r.prototype.removeAni=function(e){var t=this.aniList.indexOf(e);t>-1&&(this.aniList.splice(t,1),0===t&&this.checkEvent())},r.prototype.play=function(){this.aniList.forEach(function(e){e.play(),Vu(e)})},r.prototype.pause=function(){this.aniList.forEach(function(e){e.pause(),Hu(e)})},r.prototype.resume=function(){this.aniList.forEach(function(e){e.resume(),Vu(e)})},r.prototype.finish=function(){this.aniList.forEach(function(e){e.finish(),Hu(e)})},r.prototype.cancel=function(){this.aniList.forEach(function(e){e.cancel(),Hu(e)})},r.prototype.gotoAndPlay=function(e){this.aniList.forEach(function(t){t.gotoAndPlay(e),Vu(t)})},r.prototype.gotoAndStop=function(e){this.aniList.forEach(function(t){t.gotoAndStop(e),Hu(t)}),this.aniList.forEach(function(e){e.afterRunning()})},r.prototype.checkEvent=function(){var e=this,t=this.aniList[0];t&&Object.keys(this.__eHash).forEach(function(r){e.__eHash[r].forEach(function(e){t.on(r,e)})})},r.prototype.on=function(t,r){e.prototype.on.call(this,t,r),this.aniList.length&&this.aniList[0].on(t,r)},r.prototype.once=function(t,r){e.prototype.once.call(this,t,r),this.aniList.length&&this.aniList[0].once(t,r)},r.prototype.off=function(t,r){e.prototype.off.call(this,t,r),this.aniList.length&&this.aniList[0].off(t,r)},Object.defineProperty(r.prototype,"currentTime",{get:function(){var e=this.aniList[0];return e?e.currentTime:0},set:function(e){this.aniList.forEach(function(t){t.currentTime=e})},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"duration",{get:function(){var e=this.aniList[0];return e?e.delay+e.duration+e.endDelay:0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"playCount",{get:function(){var e=this.aniList[0];return e?e.playCount:0},set:function(e){this.aniList.forEach(function(t){t.playCount=e})},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"playState",{get:function(){var e=this.aniList[0];return e?e.playState:"idle"},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"pending",{get:function(){var e=this.aniList[0];return!e||"running"!==e.playState},enumerable:!1,configurable:!0}),r}(R);function Vu(e){if(!(e.currentTime>=e.delay+e.duration)&&e instanceof Uu){var t=e.node;if(!(t instanceof zu||t instanceof Lu))return;if(t.gainNode&&(t.gainNode.disconnect(),t.gainNode=void 0),t.decoder){var r=t.decoder.currentGOP;if((null==r?void 0:r.audioBuffer)&&t.root){var i=t.root.audioContext;t.gainNode||(t.gainNode=i.createGain(),t.gainNode.gain.value=t.volumn),r.audioBufferSourceNode&&(r.audioBufferSourceNode.stop(),r.audioBufferSourceNode.disconnect(),r.audioBufferSourceNode=void 0);var a=i.createBufferSource();a.buffer=r.audioBuffer,a.connect(t.gainNode),t.gainNode.connect(i.destination),r.audioBufferSourceNode=a;var n=e.currentTime-e.delay;n>=r.audioTimestamp?a.start(0,.001*(n-r.audioTimestamp),.001*(e.duration-n)):a.start(i.currentTime+.001*(r.audioTimestamp-n),0,.001*(e.duration-r.audioTimestamp));for(var s=t.decoder.gopList,o=t.decoder.gopIndex+1,c=s.length;o<c;o++){var l=s[o];if(l.audioBufferSourceNode&&(l.audioBufferSourceNode.stop(),l.audioBufferSourceNode.disconnect(),l.audioBufferSourceNode=void 0),l.audioBuffer){var u=i.createBufferSource();u.buffer=l.audioBuffer,t.gainNode||(t.gainNode=i.createGain(),t.gainNode.gain.value=t.volumn),u.connect(t.gainNode),t.gainNode.connect(i.destination),l.audioBufferSourceNode=u,u.start(i.currentTime+.001*(l.audioTimestamp-n),0,.001*(e.duration-l.audioTimestamp))}}}}}}function Hu(e){var t,r;if(e instanceof Uu){var i=e.node;if(!(i instanceof zu||i instanceof Lu))return;i.gainNode&&(i.gainNode.disconnect(),i.gainNode=void 0),null===(r=null===(t=i.decoder)||void 0===t?void 0:t.gopList)||void 0===r||r.forEach(function(e){var t,r;null===(t=e.audioBufferSourceNode)||void 0===t||t.stop(),null===(r=e.audioBufferSourceNode)||void 0===r||r.disconnect(),e.audioBufferSourceNode=void 0})}}var ju,Xu,qu,Gu,Ku,Yu,$u,Qu=function(e){function r(t){var r=e.call(this,t)||this;t.onMeta&&(r.onMeta=t.onMeta),t.onLoad&&(r.onLoad=t.onLoad),r._currentTime=t.currentTime||0;var i=function(){var e=window.lottie;if(!e)throw new Error("Missing lottie-web library");r._metaData={duration:1e3*r._json.op/r._json.fr},r.contentLoadingNum=0,r.onMeta&&r.onMeta(r._metaData),r.emit(Rr,r._metaData);var t=document.createElement("div");t.style.width=r._json.w+"px",t.style.height=r._json.h+"px",t.style.position="fixed",t.style.visibility="hidden",t.style.transform="translate(9999px, 9999px)",t.style.pointerEvents="none",document.body.appendChild(t);var i=r._lottie=e.loadAnimation({container:t,renderer:"canvas",loop:!0,autoplay:!0,animationData:r._json,rendererSettings:{preserveDrawingBuffer:!0}});i.addEventListener("DOMLoaded",function(){if(r.canvas=t.querySelector("canvas"),r._currentTime>=0&&r._currentTime<r._metaData.duration&&i.goToAndStop(r._currentTime),r.isMounted){var e=r.style,a=e.left,n=e.top,s=e.right,o=e.bottom,c=e.width,l=e.height;(a.u===W.AUTO||s.u===W.AUTO)&&c.u===W.AUTO||(n.u===W.AUTO||o.u===W.AUTO)&&l.u===W.AUTO?r.refresh(Bt.REFLOW):r.refresh()}r.onLoad&&r.onLoad(),r.emit(Mr)})};if(t.src)r._src=t.src,r._currentTime>=0&&(r.contentLoadingNum=1),fetch(t.src,t.options).then(function(e){return e.json()}).then(function(e){r._json=e,i()});else{if(!t.json)throw new Error("Missing src or json in Lottie");r._json=t.json,i()}return r}return t(r,e),r.prototype.lay=function(t){e.prototype.lay.call(this,t);var r=this,i=r.style,a=r.computedStyle,n=r._json,s=i.left,o=i.top,c=i.right,l=i.bottom,u=i.width,h=i.height;if(n){var d=(s.u===W.AUTO||c.u===W.AUTO)&&u.u===W.AUTO,f=(o.u===W.AUTO||l.u===W.AUTO)&&h.u===W.AUTO;d&&(a.width=f?n.w:n.w*a.height/n.h,s.u===W.AUTO&&c.u===W.AUTO?(a.left=0,a.right=t.w-a.width):s.u===W.AUTO?a.left=t.w-a.right-a.width:c.u===W.AUTO&&(a.right=t.w-a.left-a.width)),f&&(a.height=d?n.h:n.h*a.width/n.w,o.u===W.AUTO&&l.u===W.AUTO?(a.top=0,a.bottom=t.h-a.height):o.u===W.AUTO?a.top=t.h-a.bottom-a.height:l.u===W.AUTO&&(a.bottom=t.h-a.top-a.height))}},r.prototype.calContent=function(){return this.hasContent=!1,this.computedStyle.visibility===ee.HIDDEN||0===this.computedStyle.opacity||(this._metaData?this._currentTime>=0&&this._currentTime<this._metaData.duration&&(this.hasContent=!0):this.hasContent=this.computedStyle.backgroundColor[3]>0),this.hasContent},r.prototype.renderCanvas=function(){var t=this,r=t._json,i=t._currentTime,a=t._metaData,n=t.canvas,s=t.computedStyle;e.prototype.renderCanvas.call(this);var o=this._bboxInt||this.bboxInt,c=o[0],l=o[1],u=o[2]-c,h=o[3]-l,d=0,f=0,m=s.width,p=s.height,g=s.objectFit;if(r&&n&&a&&i>=0&&i<a.duration){var v=r.w/r.h,y=m/p;if(g===ie.CONTAIN){if(y>v){var b=p*v;d+=.5*(m-b),m=b}else if(y<v){var k=m/v;f+=.5*(p-k),p=k}}else if(g===ie.COVER)if(y>v){var T=m/v;f=.5*(p-T),p=T}else if(y<v){var w=p*v;d=.5*(m-w),m=w}}var S=this.canvasCache=new Zt(u,h,-c,-l);S.available=!0;var x=S.list;if(s.backgroundColor[3]>0){var C=this.getBackgroundCoords(c,l);x.forEach(function(e){var t=e.x,r=e.y,i=e.os.ctx;i.fillStyle=he(s.backgroundColor),i.beginPath(),Er(i,C,1,-t,-r),i.closePath(),i.fill()})}for(var E=0,A=x.length;E<A;E++){var P=x[E],I=P.x,R=P.y,O=P.os.ctx,M=-I,_=-R;n&&O.drawImage(n,M+d,_+f,m,p)}},r.prototype.calContentLoading=function(){var t=e.prototype.calContentLoading.call(this);return t?this._currentTime>=0&&this._metaData&&this._currentTime<this._metaData.duration?t:0:t},r.prototype.release=function(){e.prototype.release.call(this);var t=this.lottie;t&&t.destroy()},r.prototype.timeAnimate=function(e,t){var r;null===(r=this.timeAnimation)||void 0===r||r.remove();var i=this.timeAnimation=new Uu(this,e,t);return this.initAnimate(i,t)},Object.defineProperty(r.prototype,"src",{get:function(){return this._src},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"json",{get:function(){return this._json},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"currentTime",{get:function(){return this._currentTime},set:function(e){if(this._currentTime!==e){this._currentTime=e;var t=this._lottie;t&&(t.goToAndStop(e),this.refresh())}},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"duration",{get:function(){var e;return(null===(e=this._metaData)||void 0===e?void 0:e.duration)||0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"metaData",{get:function(){return this._metaData},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"lottie",{get:function(){return this._lottie},enumerable:!1,configurable:!0}),r}(wr);!function(e){e[e.INIT=0]="INIT",e[e.FRAME=1]="FRAME",e[e.END=2]="END"}(ju||(ju={})),function(e){e[e.PROGRESS=0]="PROGRESS",e[e.FINISH=1]="FINISH",e[e.ERROR=2]="ERROR"}(Xu||(Xu={}));var Zu,Ju=!1,eh=!1,th=[],rh=0,ih=0,ah=function(e){return i(void 0,void 0,void 0,function(){var t,r,i,n,s,o,c,l,u,h,d,f,m,p,g,v,y,b,k,T,w,S,x,C,E,A,P,I,R,O,M,_,D,B,F,N,L;return a(this,function(a){switch(a.label){case 0:if(t=e.data,r=t.type,i=t.isWorker,n=function(e){var t={type:Xu.ERROR,error:e};return i&&self.postMessage(t),{data:t}},s=new Promise(function(e){Zu=e}),r!==ju.INIT)return[3,2];if(qu&&(qu.close(),qu=void 0),Gu&&(Gu.close(),Gu=void 0),o=function(){if(Ju&&eh){var e={type:Xu.PROGRESS};i&&self.postMessage(e),Zu({data:e})}},c=null===(N=e.data.videoEncoderConfig)||void 0===N?void 0:N.codec,l=void 0,l=/^vp/.test(c)?new su:new iu,Ku=new pu({format:l,target:new Gl}),/^vp8/.test(c)?Yu=new lu("vp8"):/^vp09\./.test(c)?Yu=new lu("vp9"):/^av01\./.test(c)?Yu=new lu("av1"):/^hev1\./.test(c)||/^hvc1\./.test(c)?Yu=new lu("hevc"):(/^avc1\./.test(c)||/^avc3\./.test(c))&&(Yu=new lu("avc")),Yu&&(Ku.addVideoTrack(Yu),qu=new VideoEncoder({output:function(e,t){var r=Za.fromEncodedChunk(e);Yu.add(r,t),Ju=!0,o()},error:function(e){n(e.message)}}),qu.configure(e.data.videoEncoderConfig)),u=null===(L=e.data.audioEncoderConfig)||void 0===L?void 0:L.codec,e.data.mute?$u=void 0:/^mp3/.test(u)?$u=new hu("mp3"):/^flac/.test(u)?$u=new hu("flac"):/^opus/.test(u)?$u=new hu("opus"):/^vorbis/.test(u)?$u=new hu("vorbis"):/^pcm-/.test(u)?$u=new hu(u):/^mp4a\./.test(u)?$u=new hu("aac"):/^ulaw/.test(u)?$u=new hu("ulaw"):/^alaw/.test(u)&&($u=new hu("alaw")),$u){for(Ku.addAudioTrack($u),Gu=new AudioEncoder({output:function(e,t){var r=Za.fromEncodedChunk(e);$u.add(r,t),eh=!0,o()},error:function(e){n(e.message)}}),Gu.configure(e.data.audioEncoderConfig),th.splice(0),h=e.data.audioEncoderConfig.sampleRate*Math.ceil(.001*e.data.duration),O=0;O<e.data.audioEncoderConfig.numberOfChannels;O++)th.push(new Float32Array(h));rh=0,ih=0}return[4,Ku.start()];case 1:return a.sent(),[3,8];case 2:if(r!==ju.FRAME)return[3,3];if(Ju=!1,eh=!1,d=e.data.videoFrame,qu&&"configured"===qu.state&&d&&qu.encode(d),null==d||d.close(),f=e.data.audioList,m=e.data.audioEncoderConfig,p=m.numberOfChannels,g=m.sampleRate,Gu&&"configured"===Gu.state){if(f.length)for(O=0,v=f.length;O<v;O++)for(y=f[O],b=y.audioChunk,k=y.volume,T=Math.round(.001*b.timestamp*g),w=b.numberOfFrames,S=0;S<p;S++)for(x=th[S],C=b.channels[S],E=0;E<w;E++)A=x[P=T+E]+C[E]*k,x[P]=Math.max(-1,Math.min(1,A));if(e.data.timestamp&&(P=Math.round(.001*e.data.timestamp*g))>rh){for(I=P-rh,R=new Float32Array(I*th.length),O=0;O<th.length;O++)M=th[O],_=M.subarray(rh,P),R.set(_,O*I);D=new AudioData({format:"f32-planar",sampleRate:g,numberOfFrames:I,numberOfChannels:p,timestamp:ih,data:R}),rh=P,ih=e.data.timestamp,Gu.encode(D)}eh=!0}else e.data.mute&&(eh=!0);return[2,s];case 3:return r!==ju.END?[3,8]:qu&&Ku?[4,qu.flush()]:[2];case 4:return a.sent(),qu.close(),qu=void 0,"configured"!==(null==Gu?void 0:Gu.state)?[3,6]:[4,Gu.flush()];case 5:a.sent(),Gu.close(),Gu=void 0,a.label=6;case 6:return[4,Ku.finalize()];case 7:if(a.sent(),B=Ku.target.buffer,Ku=void 0,F={type:Xu.FINISH,buffer:B},!i)return[2,{data:F}];self.postMessage(F,[B]),a.label=8;case 8:return[2]}})})};function nh(e,t,r){return i(this,void 0,void 0,function(){var i,n,s,o,c,l;return a(this,function(a){switch(a.label){case 0:return e.numberOfChannels===t&&e.sampleRate===r?[2,e]:(i=Math.round(e.length*r/e.sampleRate),n=new OfflineAudioContext(t,i,r),s=n.createBufferSource(),1===e.numberOfChannels&&2===t?(o=new OfflineAudioContext(2,e.length,e.sampleRate),c=o.createBuffer(2,e.length,e.sampleRate),l=e.getChannelData(0),c.copyToChannel(l,0,0),c.copyToChannel(l,1,0),s.buffer=c):s.buffer=e,s.connect(n.destination),s.start(0),[4,n.startRendering()]);case 1:return[2,a.sent()]}})})}function sh(e,t,r){var i=Math.floor(.001*t*e.sampleRate),a=Math.min(Math.ceil(.001*r*e.sampleRate),e.length);if(i>a||i>=e.length)throw new Error("Invalid range");if(0===i&&a>=e.length-1)return e;for(var n=new OfflineAudioContext(e.numberOfChannels,a-i+1,e.sampleRate).createBuffer(e.numberOfChannels,a-i+1,e.sampleRate),s=0;s<e.numberOfChannels;s++){var o=e.getChannelData(s).subarray(i,a+1);n.copyToChannel(o,s,0)}return n}self.onmessage=ah;var oh,ch,lh,uh={stereo2Mono:function(e,t){for(var r=e.length,i=new Float32Array(r),a=0;a<r;a++)i[a]=.5*(e[a]+t[a]);return i},extractAudioBuffer:function(e,t,r){var i=e.sampleRate,a=e.numberOfChannels,n=Math.floor(.001*t*i),s=Math.min(Math.ceil(.001*r*i),e.length),o=s-n;if(!(o<=0)){for(var c=1e3*n/i,l=1e3*o/i,u=[],h=0;h<a;h++){var d=e.getChannelData(h).subarray(n,s);u.push(new Float32Array(d))}return{format:"f32-planar",channels:u,numberOfFrames:o,startFrame:n,endFrame:s,sampleRate:i,numberOfChannels:a,timestamp:c,duration:l}}},reSample:nh,sliceAudioBuffer:sh,convertS16ToFloat32:function(e,t){var r=new Int16Array(e instanceof ArrayBuffer?e:e.buffer);r.length!==t&&console.error("数据长度校验失败:预期 ".concat(t," 个样本,实际 Int16Array 长度为 ").concat(r.length,"。"));for(var i=new Float32Array(t),a=0;a<t;a++){var n=r[a];i[a]=n/32768}return i}},hh=0;!function(e){e.START="start",e.PROGRESS="progress",e.FINISH="finish",e.ERROR="error"}(lh||(lh={}));var dh=function(e){function r(){return e.call(this)||this}return t(r,e),r.prototype.initWorker=function(){if(!oh)if(F.encoderWorker)oh=new Worker(F.encoderWorker);else if(F.encoderWorkerStr){var e=new Blob([F.encoderWorkerStr.trim()],{type:"application/javascript"}),t=URL.createObjectURL(e);oh=new Worker(t)}},r.prototype.start=function(e,t){return i(this,void 0,void 0,function(){var r,n,s,o,c,l,u,h,d,f,m,p=this;return a(this,function(g){switch(g.label){case 0:if(!e.canvas)throw new Error("Root Missing appendTo canvas");return this.initWorker(),r=Object.assign({codec:"avc1.420028",width:e.width,height:e.height,bitrate:5e6,bitrateMode:"variable",framerate:30,hardwareAcceleration:"no-preference"},null==t?void 0:t.video),[4,VideoEncoder.isConfigSupported(r)];case 1:if(!(n=g.sent())||!n.supported)throw new Error("Unsupported video encoder config");return s=Object.assign({codec:"opus",sampleRate:44100,numberOfChannels:2},null==t?void 0:t.audio),(o=(null==t?void 0:t.duration)||e.aniController.duration)&&r.framerate?(c=1e3/r.framerate,l=Math.ceil(o/c),u={type:ju.INIT,messageId:hh++,isWorker:!!F.encoderWorker||!!F.encoderWorkerStr,duration:o,videoEncoderConfig:r,audioEncoderConfig:s,mute:F.mute},oh?(oh.postMessage(u),[3,4]):[3,2]):[2];case 2:return[4,ah({data:u})];case 3:g.sent(),g.label=4;case 4:this.emit(lh.START,l),Nu.spf=c,h={},d=function(t){var r;return a(this,function(n){switch(n.label){case 0:return r=t*c,console.warn("encode>>>>>>>>>>>>>>>>",t,l,r),e.aniController.gotoAndStop(r),f.emit(lh.PROGRESS,t,l,!0),[4,new Promise(function(n,o){var u=function(){return i(p,void 0,void 0,function(){var i,u,d,f,m,p,g,v,y,b,k,T,w,S,x,C,E,A,P,I,R,O=this;return a(this,function(a){switch(a.label){case 0:return[4,createImageBitmap(e.canvas)];case 1:if(i=a.sent(),u=new VideoFrame(i,{timestamp:1e3*r,duration:1e3*c}),d=[],F.mute)return[3,5];f=0,m=e.aniController.aniList.length,a.label=2;case 2:return f<m?(p=e.aniController.aniList[f],g=p.delay,v=p.duration,p instanceof Uu&&p.currentTime>=g&&p.currentTime<v+g?(y=p.node)instanceof Qu||!y.volumn?[3,4]:(b=y.decoder)&&(k=b.currentGOP)&&(T=k.audioBuffer)?(w=y.id+"-"+k.index,h[w]?[3,4]:(h[w]=!0,S=k.audioTimestamp-k.timestamp,[4,nh(sh(T,0,p.duration-k.audioTimestamp),s.numberOfChannels,s.sampleRate)])):[3,4]:[3,4]):[3,5];case 3:for(x=a.sent(),C=[],E=0;E<s.numberOfChannels;E++)A=x.getChannelData(E),C.push(A);d.push({audioChunk:{format:"f32-planar",channels:C,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,numberOfFrames:x.length,timestamp:r+S,duration:1e3*x.duration},volume:y.volumn}),a.label=4;case 4:return f++,[3,2];case 5:return P=function(e){e.data.type===Xu.PROGRESS?(n(),O.emit(lh.PROGRESS,t,l,!1)):(o(e.data.error),O.emit(lh.ERROR,e.data.error))},I={type:ju.FRAME,messageId:hh++,isWorker:!!F.encoderWorker||!!F.encoderWorkerStr,timestamp:r,videoFrame:u,audioList:d,audioEncoderConfig:s,mute:F.mute},(R=[]).push(u),d.forEach(function(e){e.audioChunk.channels.forEach(function(e){R.push(e.buffer)})}),oh?(oh.onmessage=P,oh.postMessage(I,R)):ah({data:I}).then(function(e){P(e)}),[2]}})})};e.contentLoadingCount?e.once(Ir,u):e.rl?e.once(Ar,u):u()})];case 1:return n.sent(),[2]}})},f=this,m=0,g.label=5;case 5:return m<l?[5,d(m)]:[3,8];case 6:g.sent(),g.label=7;case 7:return m++,[3,5];case 8:return[2,new Promise(function(e){var t=function(t){t.data.type===Xu.FINISH&&e(t.data.buffer),p.emit(lh.FINISH)},r={type:ju.END,messageId:hh++,isWorker:!!F.encoderWorker||!!F.encoderWorkerStr};oh?(oh.onmessage=t,oh.postMessage(r)):ah({data:r}).then(function(e){t(e)})})]}})})},r.getInstance=function(){return ch||(ch=new r),ch},r}(R),fh=function(e){function r(t,r){void 0===r&&(r=[]);var i=e.call(this,t,r)||this;return i.root=i,i.refs={},i.structs=[],i.task=[],i.aniTask=[],i.rl=Bt.NONE,i.programs={},i.frameCb=function(e){var t=i.aniTask.slice(0);t.forEach(function(t){t.onRunning(e)});var r=i.task.splice(0);r.length&&i.draw(),t.forEach(function(e){e.afterRunning()}),r.forEach(function(e){e&&e(!1)}),i.task.length||i.aniTask.length||Hr.offFrame(i.frameCb)},i.audioContext=new AudioContext,i.aniController=new Wu(i.audioContext),i.contentLoadingCount=0,i.lastContentLoadingCount=0,i}return t(r,e),r.prototype.appendTo=function(e){this.canvas=e;var t=Object.assign(Nr,this.props.contextAttributes),r=e.getContext("webgl2",t);if(r?this.isWebgl2=!0:(r=e.getContext("webgl",t),this.isWebgl2=!1),!r)throw new Error("Webgl unsupported!");this.appendToGl(r)},r.prototype.appendToGl=function(e){this.ctx?ne.error("Duplicate appendToGl"):(this.ctx=e,this.initShaders(e),this.reLayout(),this.didMount(),this.structs=this.structure(0),this.addUpdate(this,[],Bt.ADD_DOM))},r.prototype.reLayout=function(){this.checkRoot(),this.layout({w:this.computedStyle.width,h:this.computedStyle.height})},r.prototype.checkRoot=function(){var e,t=this.style,r=t.width,i=t.height,a=this.canvas;r.u===W.AUTO?a&&(r.u=W.PX,this.computedStyle.width=r.v=Math.max(1,a.width)):this.computedStyle.width=Math.max(1,this.style.width.v),i.u===W.AUTO?a&&(i.u=W.PX,this.computedStyle.height=i.v=Math.max(1,a.height)):this.computedStyle.height=Math.max(1,this.style.height.v),null===(e=this.ctx)||void 0===e||e.viewport(0,0,this.computedStyle.width,this.computedStyle.height)},r.prototype.addUpdate=function(e,t,r,i){if(void 0===r&&(r=Bt.NONE),!this.isMounted)return Bt.NONE;var a=r;if(t&&t.length)for(var n=0,s=t.length;n<s;n++){a|=zt(t[n])}return this.calUpdate(e,a)?this.asyncDraw(i):i&&i(!0),a},r.prototype.calUpdate=function(e,t){if(t===Bt.NONE||!this.isMounted)return!1;var r=function(e){return e>=Bt.REFLOW}(t);r?e===this?this.reLayout():function(e,t){var r=e.parent;t&Bt.REMOVE_DOM?e.didUnmount():(e.layout({w:r.computedStyle.width,h:r.computedStyle.height}),t&Bt.ADD_DOM&&e.didMount())}(e,t):t>=Bt.REPAINT?e.calRepaintStyle(t):(t&Bt.TRANSFORM_ALL&&e.calMatrix(t),t&Bt.OPACITY&&e.calOpacity());e.clearTexCacheUpward(),e.refreshLevel|=t,this.rl|=t;for(var i=e.parent;i;){if(i.computedStyle.visibility===ee.HIDDEN)return!1;i=i.parent}return t>Bt.NONE},r.prototype.asyncDraw=function(e){var t=this.task,r=this.aniTask;t.length||r.length||Hr.onFrame(this.frameCb),t.push(e)},r.prototype.cancelAsyncDraw=function(e){var t=this.task,r=this.aniTask,i=t.indexOf(e);i>-1&&(t.splice(i,1),t.length||r.length||Hr.offFrame(this.frameCb))},r.prototype.addAnimation=function(e){var t=this.task,r=this.aniTask;t.length||r.length||Hr.onFrame(this.frameCb),-1===r.indexOf(e)&&r.push(e)},r.prototype.removeAnimation=function(e){var t=this.task,r=this.aniTask,i=r.indexOf(e);i>-1&&(r.splice(i,1),t.length||r.length||Hr.offFrame(this.frameCb))},r.prototype.draw=function(){this.isMounted&&(this.rl>Bt.NONE&&(this.clear(),this.rl=Bt.NONE,this.ctx&&(zr(this.ctx,this),this.emit("refresh"),this.contentLoadingCount?this.lastContentLoadingCount||this.emit(Pr):(this.lastContentLoadingCount&&this.emit(Ir),this.emit(Ar)),this.lastContentLoadingCount=this.contentLoadingCount)))},r.prototype.clear=function(){var e=this.ctx;e&&(e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT))},r.prototype.initShaders=function(e){var t=this.programs.program=Wt(e,"#define GLSLIFY 1\nattribute vec2 a_position;varying vec4 v_position;attribute vec2 a_texCoords;varying vec2 v_texCoords;attribute float a_opacity;varying float v_opacity;void main(){gl_Position=vec4(a_position,0,1);v_position=gl_Position;v_texCoords=a_texCoords;v_opacity=a_opacity;}","#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec4 v_position;varying vec2 v_texCoords;varying float v_opacity;uniform float x1;uniform float y1;uniform float x2;uniform float y2;uniform sampler2D u_texture;void main(){if(v_position.x<x1||v_position.x>x2||v_position.y<y1||v_position.y>y2){discard;}float opacity=v_opacity;if(opacity<=0.0){discard;}opacity=clamp(opacity,0.0,1.0);vec4 color=texture2D(u_texture,v_texCoords);gl_FragColor=color*opacity;}");e.useProgram(t)},r.prototype.encode=function(e){return i(this,void 0,void 0,function(){return a(this,function(t){return[2,dh.getInstance().start(this,e)]})})},r}(Fr),mh=function(){function e(e,t,r,i,a){void 0===i&&(i=!1),void 0===a&&(a=!1),this.x=0,this.y=e,this.w=0,this.h=t,this.index=r,this.list=[],this.startEnter=i,this.endEnter=a}return e.prototype.add=function(e){this.list.push(e),this.w+=e.w},e.prototype.verticalAlign=function(){for(var e=this.baseline,t=this.list,r=0,i=t.length;r<i;r++){var a=t[r],n=a.baseline;if(n!==e){var s=e-n;a.y+=s}}},e.prototype.offsetX=function(e){this.x+=e;for(var t=this.list,r=0,i=t.length;r<i;r++)t[r].x+=e},e.prototype.offsetY=function(e){this.y+=e;for(var t=this.list,r=0,i=t.length;r<i;r++)t[r].y+=e},Object.defineProperty(e.prototype,"size",{get:function(){return this.list.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"baseline",{get:function(){for(var e=0,t=this.list,r=0,i=t.length;r<i;r++)e=Math.max(e,t[r].baseline);return e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"lineHeight",{get:function(){var e=this.list;if(e.length){for(var t=0,r=0,i=e.length;r<i;r++)t=Math.max(t,e[r].lineHeight);return t}return this.h},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"width",{get:function(){return Math.ceil(this.w)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return Math.ceil(this.lineHeight)},enumerable:!1,configurable:!0}),e}(),ph=function(e,t,r,i,a,n,s,o,c,l,u,h,d,f,m,p,g,v){this.x=e,this.y=t,this.w=r,this.lineHeight=i,this.baseline=a,this.contentArea=n,this.index=s,this.str=o,this.font=c,this.fontFamily=l,this.fontSize=u,this.color=h,this.letterSpacing=d,this.textDecoration=f,this.textShadow=m,this.stroke=p,this.strokeWidth=g,this.strokeEnable=v};function gh(e){return"\n"===e||"\u2028"===e}function vh(e,t,r,i,a,n,s){var o=t,c=r,l=0,u=!1,h=Math.round(a/n);for(h<=0?h=1:h>r-t&&(h=r-t);o<c;){var d=e.measureText(i.slice(t,t+h)).width;if(d===a){l=a,u=!0;break}if(d>a+1e-10){if(u=!0,1===h){l=d;break}if(o===c-1||o-t===h-1){h=o-t;break}c=h+t-1;var f=Math.round((d-a)/n);f<=0&&(f=1),(h-=f)<o-t&&(h=o-t)}else{if(l=d,h===r-t)break;o=h+t;var m=Math.round((a-d)/n);m<=0&&(m=1),(h+=m)>c-t&&(h=c-t)}}for(var p=t,g=t+h;p<g;p++)if(gh(i.charAt(p)))return{hypotheticalNum:h=p-t,rw:l=e.measureText(i.slice(t,t+h)).width,newLine:u=!1};if(t+h<r&&/[\w.-]/.test(i.charAt(t+h-1)))for(var v=t+h-2;v>t;v--)if(!/[\w.-]/.test(i.charAt(v)))return{hypotheticalNum:h=v-t+1,rw:l=e.measureText(i.slice(t,t+h)).width,newLine:u=!0};return gh(i.charAt(t+h))&&(u=!1),{hypotheticalNum:h,rw:l,newLine:u}}function yh(e,t,r){void 0===r&&(r=1),1!==r?(e.font=t.font.replace(/([\d.e+-]+)px/gi,function(e,t){return t*r+"px"}),e.letterSpacing=t.letterSpacing*r+"px"):(e.font=t.font,e.letterSpacing=t.letterSpacing+"px")}var bh,kh=1e-4,Th=function(e){function i(t){var r,i=e.call(this,t)||this;return i._content=t.content||"",i.rich=((null===(r=t.rich)||void 0===r?void 0:r.slice(0))||[]).map(function(e){return Ot(e,i.style)}),i.computedRich=i.rich.map(function(e){return i.calComputedRich(e)}),i.mergeRich(),i.lineBoxList=[],i.cursor={isMulti:!1,startLineBox:0,endLineBox:0,startTextBox:0,endTextBox:0,startString:0,endString:0,start:0,end:0},i.tempCursorX=0,i}return t(i,e),i.prototype.didMount=function(){e.prototype.didMount.call(this);var t=this.props.textBehaviour,r=this,i=r.style,a=r.computedStyle,n=r.parent,s=i.left,o=i.right,c=i.top,l=i.bottom,u=i.width,h=i.height,d=i.transformOrigin,f=!1;if("auto"===t&&u.u!==W.AUTO&&(s.u===W.AUTO||o.u===W.AUTO)){var m=this.width;if(u.u===W.PX?m=this.width-u.v:u.u===W.PERCENT&&(m=this.width-.01*u.v*n.width),Math.abs(m)>kh&&d[0].u===W.PERCENT){var p=this.getOffsetRect(),g=Rt(u,n.width);p.left=a.left+Rt(i.translateX,g),p.right=p.left+g;var v=a.textAlign;if(v===V.LEFT){var y=m*d[0].v*.01;this.adjustPosAndSizeSelf(y,0,y,0),f=!0}else if(v===V.RIGHT){y=m*d[0].v*.01;this.adjustPosAndSizeSelf(-y,0,-y,0),f=!0}}i.width={v:0,u:W.AUTO}}if(!("auto"!==t&&"autoH"!==t||h.u===W.AUTO||c.u!==W.AUTO&&l.u!==W.AUTO)){m=0;if(h.u===W.PX?m=this.height-h.v:h.u===W.PERCENT&&(m=this.height-.01*h.v*n.height),Math.abs(m)>kh&&d[1].u===W.PERCENT){p=this.getOffsetRect();var b=Rt(h,n.height);p.top=a.top+Rt(i.translateY,b),p.bottom=p.top+b;var k=a.textVerticalAlign;if(k===H.TOP){y=m*d[1].v*.01;this.adjustPosAndSizeSelf(0,y,0,y),f=!0}else if(k===H.BOTTOM){y=m*d[1].v*.01;this.adjustPosAndSizeSelf(0,-y,0,-y),f=!0}}i.height={v:0,u:W.AUTO}}f&&this.checkPosSizeUpward()},i.prototype.lay=function(t){var r=this;e.prototype.lay.call(this,t);var i=this,a=i.computedRich,n=i.style,s=i.computedStyle,o=i._content,c=i.lineBoxList,l=n.left,u=n.right,h=n.top,d=n.bottom,f=n.width,m=n.height,p=f.u===W.AUTO&&(l.u===W.AUTO||u.u===W.AUTO),g=m.u===W.AUTO&&(h.u===W.AUTO||d.u===W.AUTO);if(!this.isMounted){var v=this.props.textBehaviour;"auto"!==v||f.u===W.AUTO||l.u!==W.AUTO&&u.u!==W.AUTO||(p=!0),"auto"!==v&&"autoH"!==v||m.u===W.AUTO||h.u!==W.AUTO&&d.u!==W.AUTO||(g=!0)}var y,b,k,T,w,S,x,C,E,A,P,I,R,O,M=0,_=o.length,D=0,B=0,F=0,N={};if(a.length)for(var L=0,U=a.length;L<U;L++){var z=a[L];N[z.location]=L;var j=z.fontFamily;Ve.waitIfNotRegister(j,function(){r.refresh(Bt.REFLOW)})}else{j=s.fontFamily;Ve.waitIfNotRegister(j,function(){r.refresh(Bt.REFLOW)})}var X=ne.getFontCanvas().ctx;if(a.length){var q=a[0];b=q.letterSpacing||0,k=q.paragraphSpacing||0,y=.8*q.fontSize+b,w=xt(q,T=q.lineHeight||St(q)),S=Ct(q,T),x=q.fontFamily,C=q.fontSize,E=he(q.color),A=q.textDecoration||[],P=q.textShadow,I=q.stroke,R=q.strokeWidth,O=q.strokeEnable,X.font=Tt(q),X.letterSpacing=b+"px"}else b=s.letterSpacing,k=s.paragraphSpacing,y=.8*s.fontWeight+b,w=xt(s,T=s.lineHeight||St(s)),S=Ct(s,T),x=s.fontFamily,C=s.fontSize,E=he(this.style.color.v),A=this.style.textDecoration.map(function(e){return e.v}),P=this.style.textShadow.v,I=br(this.style.stroke),R=this.style.strokeWidth.map(function(e){return e.v}),O=this.style.strokeEnable.map(function(e){return e.v}),X.font=Tt(s),X.letterSpacing=b+"px";var G=new mh(F,T,M,!1);c.splice(0),c.push(G);for(var K=p?Number.MAX_SAFE_INTEGER:this.width;M<_;){var Y=N[M];if(M&&Y){var $=a[Y];b=$.letterSpacing||0,k=$.paragraphSpacing||0,y=.8*$.fontSize+b,w=xt($,T=$.lineHeight||St($)),S=Ct($,T),x=$.fontFamily,C=$.fontSize,E=he($.color),A=$.textDecoration||[],P=$.textShadow,I=$.stroke,R=$.strokeWidth,O=$.strokeEnable,X.font=Tt($),X.letterSpacing=b+"px"}if(gh(o.charAt(M)))M++,B=0,F+=G.height+k,G.verticalAlign(),G.endEnter=!0,G=new mh(F,T,M,!0),c.push(G);else{U=_;if(a.length)for(var Q=M+1;Q<U;Q++)if(N[Q]){U=Q;break}if(X.measureText(o.charAt(M)).width>K-B+1e-10&&B)B=0,F+=G.height,M<_&&(G.verticalAlign(),G=new mh(F,T,M,!1),c.push(G));else{var Z=vh(X,M,U,o,K-B,y),J=Z.hypotheticalNum,ee=Z.rw,te=Z.newLine,re=new ph(B,F,ee,T,w,S,M,o.slice(M,M+J),X.font,x,C,E,b,A,P,I,R,O);G.add(re),M+=J,D=Math.max(D,Math.ceil(ee+B)),te?(B=0,F+=G.height,M<_&&(G.verticalAlign(),G=new mh(F,T,M,!1),c.push(G))):B+=ee}}}if((G.verticalAlign(),D=Math.max(D,G.width),b&&b<0&&(D-=b),p)&&(ve=D-this.width)){s.width=D;var ie=n.left,ae=n.right;ie.u!==W.AUTO&&ae.u!==W.AUTO||(ie.u!==W.AUTO?s.right-=ve:ae.u!==W.AUTO&&(s.left-=ve))}if(g){var se=G.y+G.height;if(ve=se-this.height){s.height=se;var oe=n.top,ce=n.bottom;oe.u!==W.AUTO&&ce.u!==W.AUTO||(oe.u!==W.AUTO?s.bottom-=ve:ce.u!==W.AUTO&&(s.top-=ve))}}if(a&&a.length){var le={};a.forEach(function(e){le[e.location]=e});var ue=a[0].textAlign,de=0;for(U=c.length;de<U;de++){var fe=c[de];if(fe.startEnter||!fe.index){var me=le[fe.index];me&&(ue=me.textAlign)}if(ue===V.CENTER)(ve=this.width-fe.width)&&fe.offsetX(.5*ve);else if(ue===V.RIGHT){(ve=this.width-fe.width)&&fe.offsetX(ve)}}}else if(o&&s.textAlign!==V.LEFT){var pe=0;for(U=c.length;pe<U;pe++){var ge=c[pe];if(s.textAlign===V.CENTER)(ve=this.width-ge.width)&&ge.offsetX(.5*ve);else if(s.textAlign===V.RIGHT){var ve;(ve=this.width-ge.width)&&ge.offsetX(ve)}}}var ye=this.height-G.y-G.height;if(ye){var be=s.textVerticalAlign;if(be===H.MIDDLE){var ke=0;for(U=c.length;ke<U;ke++){c[ke].offsetY(.5*ye)}}else if(be===H.BOTTOM){var Te=0;for(U=c.length;Te<U;Te++){c[Te].offsetY(ye)}}}},i.prototype.cutRich=function(e,t){var r=this.rich;if(r.length){for(var i=t-e,a=0,n=r.length;a<n;a++){var s=r[a];if(s.location<=e&&s.location+s.length>e){if(s.location+s.length>=t){s.length-=i;for(var o=a+1;o<n;o++)r[o].location-=i;s.length||r.splice(a,1)}else{s.length=e-s.location;for(var c=a+1,l=r.length;c<l;c++){var u=r[c];if(u.location<=t&&(u.location+u.length>t||c===l-1)){u.length-=t-u.location,u.location-=i;o=c+1;for(var h=r.length;o<h;o++)r[o].location-=i;a<c-1&&r.splice(a+1,c-a-1),u.length||r.splice(c,1);break}}s.length||r.splice(a,1)}break}}this.mergeRich()}},i.prototype.expandRich=function(e,t){var r=this,i=r.rich,a=r.computedRich,n=r.style,s=r._content;if(!i.length){var o={location:e,length:t,fontFamily:n.fontFamily,fontSize:n.fontSize,fontWeight:n.fontWeight,fontStyle:n.fontStyle,letterSpacing:n.letterSpacing,lineHeight:n.lineHeight,paragraphSpacing:n.paragraphSpacing,textAlign:n.textAlign,textDecoration:n.textDecoration,textShadow:n.textShadow,color:n.color,stroke:n.stroke.slice(0),strokeEnable:n.strokeEnable.slice(0),strokeWidth:n.strokeWidth.slice(0)};return i.push(o),void a.push(this.calComputedRich(o))}e=Math.max(0,e);for(var c=0,l=i.length;c<l;c++){var u=i[c];if(u.location<=e&&u.location+u.length>=e){if(e===u.location+u.length&&gh(s.charAt(e-1)))continue;u.length+=t,a[c].length+=t;for(var h=c+1;h<l;h++)i[h].location+=t,a[h].location+=t;return}}i[i.length-1].length+=t,a[a.length-1].length+=t},i.prototype.insertRich=function(e,t,r){var i=this,a=i.rich,n=i.computedRich,s=i.style,o=Object.assign({location:t,length:r,fontFamily:s.fontFamily,fontSize:s.fontSize,fontWeight:s.fontWeight,fontStyle:s.fontStyle,letterSpacing:s.letterSpacing,lineHeight:s.lineHeight,paragraphSpacing:s.paragraphSpacing,textAlign:s.textAlign,textDecoration:s.textDecoration,textShadow:s.textShadow,color:s.color,stroke:s.stroke,strokeEnable:s.strokeEnable,strokeWidth:s.strokeWidth},e),c=this.calComputedRich(o);if(!a.length)return a.push(o),void n.push(c);for(var l=0,u=a.length;l<u;l++){var h=a[l];if(h.location<=t&&h.location+h.length>=t){for(var d=l+1;d<u;d++)a[d].location+=r,n[d].location+=r;if(h.location===t)a.splice(l,0,o),n.splice(l,0,c),h.location+=r,n[l].location+=r;else if(h.location+h.length===t)a.splice(l+1,0,o),n.splice(l+1,0,c);else if(h.location+h.length>t){var f=A(h);h.length=t-h.location,f.location=t+r,f.length-=h.length,a.splice(l+1,0,o),a.splice(l+2,0,f);var m=n[l],p=A(m);m.length=h.length,p.location=f.location,p.length=f.length,n.splice(l+1,0,c),n.splice(l+2,0,p)}return void this.mergeRich()}}a.push(o),n.push(c),this.mergeRich()},i.prototype.mergeRich=function(){var e=this,t=e.rich,i=e.computedRich,a=e._content,n=e.style;if(t.length){for(var s=t.length-1;s>=0;s--){var o=t[s];(o.location<0||o.length<=0)&&(t.splice(s,1),i.splice(s,1))}t.sort(function(e,t){return e.location===t.location?e.length-t.length:e.location-t.location}),i.sort(function(e,t){return e.location===t.location?e.length-t.length:e.location-t.location});var c=!1,l=Ot({location:0,length:0},n);if(a.length){var u=t[t.length-1],h=i[i.length-1];if(u.location+u.length>a.length)u.length=a.length-u.location,h.length=a.length-h.location,c=!0;else if(u.location+u.length<a.length){var d=r(r({},l),{location:u.location+u.length,length:a.length-u.location-u.length});t.push(d),i.push(this.calComputedRich(d))}var f=t[0];if(f.location>0){d=r(r({},l),{location:0,length:f.location});t.unshift(d),i.unshift(this.calComputedRich(d)),c=!0}}for(s=t.length-2;s>=0;s--){var m=t[s],p=t[s+1];if(p.length)if(m.length){var g=m.location+m.length;if(g===p.location)P(m,p,["color","fontFamily","fontSize","letterSpacing","lineHeight","textDecoration","paragraphSpacing","textShadow","stroke","strokeEnable","strokeWidth"])?(m.textAlign.v===p.textAlign.v||gh(a.charAt(p.location-1)))&&(m.length+=p.length,t.splice(s+1,1),i[s].length=m.length,i.splice(s+1,1),c=!0):1===p.length&&gh(a.charAt(p.location))&&(m.length+=p.length,t.splice(s+1,1),i[s].length=m.length,i.splice(s+1,1),c=!0);else{if(g<p.location){d=r(r({},l),{location:g,length:p.location-g});t.splice(s+1,0,d),i.splice(s+1,0,this.calComputedRich(d))}else{var v=m.location+m.length-p.location;p.location+=v,p.length-=v,i[s+1].location=p.location,i[s+1].length=p.length}c=!0}}else t.splice(s,1),i.splice(s,1),s++;else t.splice(s+1,1),i.splice(s+1,1)}return c}},i.prototype.calComputedRich=function(e){return{location:e.location,length:e.length,fontFamily:e.fontFamily.v,fontSize:e.fontSize.v,fontWeight:e.fontWeight.v,fontStyle:e.fontStyle.v,lineHeight:e.lineHeight.v,letterSpacing:e.letterSpacing.v,paragraphSpacing:e.paragraphSpacing.v,textAlign:e.textAlign.v,textDecoration:e.textDecoration.map(function(e){return e.v}),color:e.color.v,textShadow:e.textShadow.v,stroke:br(e.stroke),strokeWidth:e.strokeWidth.map(function(e){return e.v}),strokeEnable:e.strokeEnable.map(function(e){return e.v})}},i.prototype.calReflowStyle=function(){var t=this;e.prototype.calReflowStyle.call(this),this.computedRich=this.rich.map(function(e){return t.calComputedRich(e)})},i.prototype.calRepaintStyle=function(t){e.prototype.calRepaintStyle.call(this,t);var r=this.rich;if(r.length)this.computedRich.forEach(function(e,t){e.textDecoration=r[t].textDecoration.map(function(e){return e.v}),e.color=r[t].color.v,e.textShadow=r[t].textShadow.v,e.stroke=br(r[t].stroke),e.strokeWidth=r[t].strokeWidth.map(function(e){return e.v}),e.strokeEnable=r[t].strokeEnable.map(function(e){return e.v})});else{var i=this.computedStyle;this.lineBoxList.forEach(function(e){e.list.forEach(function(e){e.color=he(i.color)})})}},i.prototype.calContent=function(){return this.hasContent=!1,this.computedStyle.visibility===ee.HIDDEN||0===this.computedStyle.opacity||(this._content||this.computedStyle.backgroundColor[3]>0)&&(this.hasContent=!0),this.hasContent},i.prototype.renderCanvas=function(){e.prototype.renderCanvas.call(this);var t=this._bboxInt||this.bboxInt,r=t[0],i=t[1],a=t[2]-r,n=t[3]-i,s=-r,o=-i,c=this.computedStyle,l=this.lineBoxList,u=this.canvasCache=new Zt(a,n,s,o);u.available=!0;var h=u.list;if(c.backgroundColor[3]>0){var d=this.getBackgroundCoords(r,i);h.forEach(function(e){var t=e.x,r=e.y,i=e.os.ctx;i.fillStyle=he(c.backgroundColor),i.beginPath(),Er(i,d,1,-t,-r),i.closePath(),i.fill()})}var f=this.getSortedCursor(),m=f.isMulti,p=f.startLineBox,g=f.startTextBox,v=f.startString,y=f.endLineBox,b=f.endTextBox,k=f.endString,T=f.start,w=f.end;if(m&&T!==w)for(var S=0,x=h.length;S<x;S++){var C=h[S],E=C.x,A=C.y,P=C.os.ctx,I=-E,R=-A;if(P.fillStyle="#f4d3c1",p===y){var O=(D=l[p]).list,M=(B=O[g]).x+I;P.font=B.font,P.letterSpacing=B.letterSpacing+"px",M+=P.measureText(B.str.slice(0,v)).width;var _=(B=O[b]).x+I;P.font=B.font,_+=P.measureText(B.str.slice(0,k)).width,P.fillRect(M,D.y+R,_-M,D.lineHeight)}else{var D,B,F=(D=l[p]).list;if(B=F[g]){M=B.x+I;P.font=B.font,P.letterSpacing=B.letterSpacing+"px",M+=P.measureText(B.str.slice(0,v)).width,P.fillRect(M,D.y+R,D.w+I-M,D.lineHeight)}for(var N=p+1,L=y;N<L;N++){var U=l[N];U.list.length&&P.fillRect(U.list[0].x+I,U.y+R,U.w,U.lineHeight)}if(B=(F=(D=l[y]).list)[b]){M=B.x+I;P.font=B.font,P.letterSpacing=B.letterSpacing+"px",M+=P.measureText(B.str.slice(0,k)).width,P.fillRect(D.x+I,D.y+R,M-(D.x+I),D.lineHeight)}}}var z=c.strokeDasharray,W=c.strokeLinecap,V=c.strokeLinejoin,H=function(e,t){var r=h[e],i=r.x,c=r.y,u=r.os.ctx;u.setLineDash(z),W===$.ROUND?u.lineCap="round":W===$.SQUARE?u.lineCap="square":u.lineCap="butt",V===Q.ROUND?u.lineJoin="round":V===Q.BEVEL?u.lineJoin="bevel":u.lineJoin="miter";for(var d=-i,f=-c,m=0,p=l.length;m<p;m++){var g=l[m];if(g.y>=n)break;for(var v=g.list,y=v.length,b=function(e){var t=v[e],r=t.textDecoration,i=t.textShadow,c=t.stroke,l=t.strokeWidth,h=t.strokeEnable;yh(u,t);for(var m=function(e,r){if(!h[e]||!l[e])return"continue";var i=c[e];if(Array.isArray(i))u.strokeStyle=he(i);else if(i.t===q.LINEAR){var m=vt(i.stops,i.d,d,f,a-2*s,n-2*o),p=u.createLinearGradient(m.x1,m.y1,m.x2,m.y2);m.stop.forEach(function(e){p.addColorStop(e.offset,he(e.color))}),u.strokeStyle=p}else if(i.t===q.RADIAL){m=yt(i.stops,i.d,d,f,a-2*s,n-2*o);var g=u.createRadialGradient(m.cx,m.cy,0,m.cx,m.cy,m.total);m.stop.forEach(function(e){g.addColorStop(e.offset,he(e.color))});var v=m.matrix;if(v){var y=ne.getOffscreenCanvas(a,n),b=y.ctx;return b.setLineDash(u.getLineDash()),b.lineCap=u.lineCap,b.lineJoin=u.lineJoin,b.miterLimit=u.miterLimit,b.lineWidth=l[e],b.lineWidth=l[e],b.strokeStyle="#FFF",b.strokeText(t.str,t.x+d,t.y+t.baseline+f),b.globalCompositeOperation="source-in",b.setTransform(v[0],v[1],v[4],v[5],v[12],v[13]),b.fillStyle=g,b.fillRect(0,0,a,n),u.drawImage(y.canvas,0,0),y.release(),"continue"}u.strokeStyle=g}else if(i.t===q.CONIC){m=bt(i.stops,i.d,d,f,a-2*s,n-2*o);var k=u.createConicGradient(m.angle,m.cx+d,m.cy+f);m.stop.forEach(function(e){k.addColorStop(e.offset,he(e.color))}),u.strokeStyle=k}u.lineWidth=l[e],u.strokeText(t.str,t.x+d,t.y+t.baseline+f)},p=0,g=c.length;p<g;p++)m(p);u.fillStyle=t.color,i?(u.shadowOffsetX=i.x,u.shadowOffsetY=i.y,u.shadowBlur=i.blur,u.shadowColor=he(i.color)):(u.shadowOffsetX=0,u.shadowOffsetY=0,u.shadowBlur=0,u.shadowColor="transparent"),u.fillText(t.str,t.x+d,t.y+t.baseline+f),u.shadowOffsetX=0,u.shadowOffsetY=0,u.shadowBlur=0,u.shadowColor="transparent",r.length&&r.forEach(function(e){if(e===te.UNDERLINE){var r=Math.min(3,.05*t.lineHeight);u.fillRect(t.x+d,t.y+t.contentArea+f-.5*r,t.w,r)}else if(e===te.LINE_THROUGH){var i=Math.min(3,.05*t.lineHeight);u.fillRect(t.x+d,t.y+.5*t.lineHeight+f-.5*i,t.w,i)}})},k=0;k<y;k++)b(k)}};for(S=0,x=h.length;S<x;S++)H(S)},i.prototype.setCursorStartByAbsCoords=function(e,t){var r=this.matrixWorld,i=tt({x:e,y:t},Ke(r)),a=this.lineBoxList,n=this.cursor,s=n.start;n.isMulti=!1;for(var o=a.length,c=0;c<o;c++){var l=a[c];if(i.y>=l.y&&i.y<l.y+l.lineHeight){n.startLineBox=n.endLineBox=c;var u=this.getCursorByLocalX(i.x,l,!1);n.endTextBox=n.startTextBox,n.endString=n.startString,n.end=n.start,this.tempCursorX=u.x,n.start!==s&&(this.inputStyle=void 0);var h=tt({x:u.x,y:u.y},r);return{x:h.x,y:h.y,h:u.h*r[0]}}}var d=a[o-1];n.startLineBox=n.endLineBox=o-1;var f=this.getCursorByLocalX(this.width,d,!1);n.endTextBox=n.startTextBox,n.endString=n.startString,n.end=n.start,this.tempCursorX=f.x,n.start!==s&&(this.inputStyle=void 0);var m=tt({x:f.x,y:f.y},r);return{x:m.x,y:m.y,h:f.h*r[0]}},i.prototype.setCursorEndByAbsCoords=function(e,t){var r=this.matrixWorld,i=tt({x:e,y:t},Ke(r)),a=this.lineBoxList,n=this.cursor,s=n.end;n.isMulti=!0;for(var o=a.length,c=0;c<o;c++){var l=a[c];if(i.y>=l.y&&i.y<l.y+l.lineHeight){n.endLineBox=c;var u=this.getCursorByLocalX(i.x,l,!0);n.end!==s&&this.refresh();var h=tt({x:u.x,y:u.y},r);return{x:h.x,y:h.y,h:u.h*r[0]}}}var d=a[o-1];n.endLineBox=o-1;var f=this.getCursorByLocalX(this.width,d,!0);n.end!==s&&this.refresh(),n.end!==n.start&&(this.inputStyle=void 0);var m=tt({x:f.x,y:f.y},r);return{x:m.x,y:m.y,h:f.h*r[0]}},i.prototype.resetCursor=function(){var e=this.cursor;e.isMulti&&(e.isMulti=!1,e.start!==e.end&&(this.refresh(),e.endLineBox=e.startLineBox,e.endTextBox=e.startTextBox,e.endString=e.startString,e.end=e.start))},i.prototype.reLocateCursor=function(){var e=this.cursor,t=this.lineBoxList,r=e.start,i=e.end,a=e.isMulti,n=0;e:for(var s=0,o=t.length;s<o;s++)for(var c=0,l=(u=t[s]).list.length;c<l;c++){if((d=n+u.list[c].str.length)>=r){e.startLineBox=s,e.startTextBox=c,e.startString=r-n;break e}n=d}if(a&&i!==r){n=0;e:for(s=0,o=t.length;s<o;s++){c=0;for(var u,h=(u=t[s]).list.length;c<h;c++){var d;if((d=n+u.list[c].str.length)>=i){e.endLineBox=s,e.endTextBox=c,e.endString=i-n;break e}n=d}}}else e.endLineBox=e.startLineBox,e.endTextBox=e.startTextBox,e.endString=e.startString},i.prototype.beforeEdit=function(){var e=this,t=e.style,r=e.computedStyle,i=e.parent,a=e.isDestroyed,n=e.width,s=e.height;if(a||!i)throw new Error("Can not edit a destroyed Text");var o=this.getStyle(),c=t.left,l=t.right,u=t.top,h=t.bottom,d=t.width,f=t.height,m=t.translateX,p=t.translateY,g=t.textAlign,v=t.textVerticalAlign,y=c.u!==W.AUTO&&l.u!==W.AUTO||d.u!==W.AUTO,b=g.v===V.LEFT&&!y&&(c.u!==W.AUTO&&m.v&&m.u===W.PERCENT||l.u!==W.AUTO),k=g.v===V.CENTER&&!y&&(-50!==m.v||m.u!==W.PERCENT),T=g.v===V.RIGHT&&l.u===W.AUTO,w=u.u!==W.AUTO&&h.u!==W.AUTO||f.u!==W.AUTO,S=v.v===H.TOP&&!w&&(u.u!==W.AUTO&&p.v&&p.u===W.PERCENT||h.u!==W.AUTO),x=v.v===H.MIDDLE&&!w&&(-50!==p.v||p.u!==W.PERCENT),C=v.v===H.BOTTOM&&!w&&h.u===W.AUTO,E=i.width,A=i.height,P=!1,I=0;if(m.u===W.PX?I=m.v:m.u===W.PERCENT&&(I=.01*m.v*n),b)c.u!==W.AUTO&&m.v&&m.u===W.PERCENT?(P=!0,r.left+=I,c.u===W.PX?c.v+=I:c.u===W.PERCENT&&(c.v+=100*I/E),r.right-=I,l.u===W.PX?l.v-=I:l.u===W.PERCENT&&(l.v-=100*I/E)):l.u!==W.AUTO&&(P=!0,r.left+=I,c.v=r.left,c.u=W.PX,r.right-=I,l.v=0,l.u=W.AUTO),m.v=0;else if(k){if(m.u===W.AUTO||m.u===W.PX){P=!0;var R=.5*n-m.v;r.left+=R,r.right-=R,c.u===W.PX?(c.v+=R,m.v=-50):c.u===W.PERCENT?(c.v+=100*R/E,m.v=-50):l.u===W.PX?(l.v+=R,m.v=50):l.u===W.PERCENT&&(l.v+=100*R/E,m.v=50),m.u=W.PERCENT}else if(m.u===W.PERCENT&&-50!==m.v){P=!0;R=.5*n-m.v*n;r.left+=R,r.right-=R,c.u===W.PX?(c.v+=R,m.v=-50):c.u===W.PERCENT?(c.v+=100*R/E,m.v=-50):l.u===W.PX?(l.v+=R,m.v=50):l.u===W.PERCENT&&(l.v+=100*R/E,m.v=50)}}else T&&(P=!0,r.left+=I,c.u!==W.AUTO&&(c.v=0,c.u=W.AUTO),r.right-=I,l.v=r.right,l.u=W.PX,m.v=0);var O=0;if(p.u===W.PX?O=p.v:p.u===W.PERCENT&&(O=.01*p.v*s),S)u.u!==W.AUTO&&p.v&&p.u===W.PERCENT?(P=!0,r.top+=O,u.u===W.PX?u.v+=O:u.u===W.PERCENT&&(u.v+=100*O/A),r.bottom-=O,h.u===W.PX?h.v-=O:h.u===W.PERCENT&&(h.v-=100*O/A)):h.u!==W.AUTO&&(P=!0,r.top+=O,u.v=r.top,u.u=W.PX,r.bottom-=O,h.v=0,h.u=W.AUTO),p.v=0;else if(x){if(p.u===W.AUTO||p.u===W.PX){P=!0;var M=.5*s-p.v;r.top+=M,r.bottom-=M,u.u===W.PX?(u.v+=M,p.v=-50):u.u===W.PERCENT?(u.v+=100*M/A,p.v=-50):h.u===W.PX?(h.v+=M,p.v=50):h.u===W.PERCENT&&(h.v+=100*M/A,p.v=50),p.u=W.PERCENT}else if(p.u===W.PERCENT&&-50!==p.v){P=!0;M=.5*s-p.v*s;r.top+=M,r.bottom-=M,u.u===W.PX?(u.v+=M,p.v=-50):u.u===W.PERCENT?(u.v+=100*M/A,p.v=-50):h.u===W.PX?(h.v-=M,p.v=50):h.u===W.PERCENT&&(h.v-=100*M/A,p.v=50),p.v=-50}}else C&&(P=!0,r.top+=O,u.u!==W.AUTO&&(u.v=0,u.u=W.AUTO),r.bottom-=O,h.v=r.bottom,h.u=W.PX,p.v=0);if(P)return this.editStyle={isLeft:b,isCenter:k,isRight:T,isTop:S,isMiddle:x,isBottom:C,isFixedHeight:w,prev:o}},i.prototype.afterEdit=function(){if(this.editStyle){var e=this.editStyle,t=e.isLeft,r=e.isCenter,i=e.isRight,a=e.isTop,n=e.isMiddle,s=e.isBottom;e.isFixedHeight;var o=e.prev,c=this,l=c.style,u=c.computedStyle,h=c.parent,d=c.width,f=c.height,m=o.left,p=o.right,g=o.top,v=o.bottom,y=o.translateX,b=o.translateY,k=h,T=k.width,w=k.height,S=0;if(y.u===W.PX?S=y.v:y.u===W.PERCENT&&(S=.01*y.v*d),t){if(m.u!==W.AUTO&&y.v&&y.u===W.PERCENT){if(m.u===W.PX)l.left.v-=S,u.left-=S;else if(m.u===W.PERCENT){var x=100*S/T;l.left.v-=x,u.left-=S}if(p.u===W.PX)l.right.v+=S,u.right+=S;else if(p.u===W.PERCENT){x=100*S/T;l.right.v+=x,u.right+=S}u.translateX+=S}else p.u!==W.AUTO&&(l.left.v=0,l.left.u=W.AUTO,u.left-=S,l.right.v=p.v,l.right.u=p.u,u.right+=S);l.translateX.v=y.v}else if(r){if(y.u===W.AUTO||y.u===W.PX){var C=.5*d-y.v;m.u===W.PX?l.left.v-=C:m.u===W.PERCENT?l.left.v-=100*C/T:p.u===W.PX?l.right.v-=C:p.u===W.PERCENT&&(l.right.v-=100*C/T),l.translateX.v=y.v,l.translateX.u=y.u}else if(y.u===W.PERCENT&&-50!==y.v){C=.5*d-y.v*d;m.u===W.PX?l.left.v-=C:m.u===W.PERCENT&&(l.left.v-=100*C/T),p.u===W.PX?l.right.v-=C:p.u===W.PERCENT&&(l.right.v-=100*C/T),l.translateX.v=y.v}}else i&&(u.left-=S,m.u===W.PX?l.left.v=u.left:m.u===W.PERCENT&&(l.left.v=100*u.left/T),l.left.u=m.u,u.right+=S,p.u===W.AUTO&&(l.right.v=0,l.right.u=W.AUTO),l.translateX.v=y.v,l.translateX.u=y.u);var E=0;if(b.u===W.PX?E=b.v:b.u===W.PERCENT&&(E=.01*b.v*f),a){if(g.u!==W.AUTO&&b.v&&b.u===W.PERCENT){if(g.u===W.PX)l.top.v-=E,u.top-=E;else if(g.u===W.PERCENT){x=100*E/w;l.top.v-=x,u.top-=E}if(v.u===W.PX)l.bottom.v+=E,u.bottom+=E;else if(v.u===W.PERCENT){x=100*E/w;l.bottom.v+=x,u.bottom+=E}}else v.u!==W.AUTO&&(l.top.v=0,l.top.u=W.AUTO,u.top-=E,l.bottom.v=v.v,l.bottom.u=v.u,u.bottom+=E);l.translateY.v=b.v,u.translateY+=E}else if(n){if(b.u===W.AUTO||b.u===W.PX){var A=.5*f-b.v;g.u===W.PX?l.top.v-=A:g.u===W.PERCENT?l.top.v-=100*A/w:v.u===W.PX?l.bottom.v-=A:v.u===W.PERCENT&&(l.bottom.v-=100*A/w),l.translateY.v=b.v,l.translateY.u=W.PX}else if(b.u===W.PERCENT&&-50!==b.v){A=.5*f-b.v*f;g.u===W.PX?l.top.v-=A:g.u===W.PERCENT?l.top.v-=100*A/w:v.u===W.PX?l.bottom.v-=A:v.u===W.PERCENT&&(l.bottom.v-=100*A/w),l.translateY.v=b.v}}else s&&(u.top-=E,g.u===W.PX?l.top.v=u.top:g.u===W.PERCENT&&(l.top.v=100*u.top/w),u.bottom+=E,v.u===W.AUTO&&(l.bottom.v=0,l.bottom.u=W.AUTO),l.translateY.v=b.v,l.translateY.u=b.u)}},i.prototype.updateCursorByIndex=function(e){var t=this.setCursorByIndex(e,!1),r=t.lineBox,i=t.textBox,a=this.cursor,n=this.matrixWorld;if(i){var s=ne.getFontCanvas().ctx;s.font=i.font,s.letterSpacing=i.letterSpacing+"px";var o=i.str,c=s.measureText(o.slice(0,a.startString)).width;this.tempCursorX=i.x+c}else{var l=this.computedStyle.textAlign;l===V.CENTER?this.tempCursorX=.5*this.width:l===V.RIGHT?this.tempCursorX=this.width:this.tempCursorX=0}var u=tt({x:this.tempCursorX,y:r.y},n);return{x:u.x,y:u.y,h:r.lineHeight*n[0]}},i.prototype.setCursorByIndex=function(e,t){void 0===t&&(t=!1);var r=this.lineBoxList,i=this.cursor;t?i.end=e:i.start=e;for(var a=0,n=r.length;a<n;a++){var s=r[a],o=s.list;if(!o.length&&s.index===e)return i.startLineBox=a,i.startTextBox=0,i.startString=0,{lineBox:s,textBox:void 0};for(var c=0,l=o.length;c<l;c++){var u=o[c];if(e>=u.index&&(e<u.index+u.str.length||c===l-1&&s.endEnter&&e<=u.index+u.str.length))return t?(i.endLineBox=a,i.endTextBox=c,i.endString=e-u.index):(i.startLineBox=a,i.startTextBox=c,i.startString=e-u.index),{lineBox:s,textBox:u}}}var h=r.length-1,d=r[h],f=d.list;if(t?i.endLineBox=h:i.startLineBox=h,!f||!f.length)return t?(i.endTextBox=0,i.endString=0):(i.startTextBox=0,i.startString=0),{lineBox:d,textBox:void 0};var m=f.length-1,p=f[m];return t?(i.endTextBox=m,i.endString=p.str.length):(i.startTextBox=m,i.startString=p.str.length),{lineBox:d,textBox:p}},i.prototype.checkCursorMulti=function(){var e=this.cursor;return e.isMulti&&e.start===e.end&&(e.isMulti=!1),e.isMulti},i.prototype.getCursorAbsCoords=function(){var e=this.matrixWorld,t=this.lineBoxList,r=this.cursor;if(!r.isMulti){var i=t[r.startLineBox],a=i.list,n=i.lineHeight;if(!a.length){var s=this.computedStyle.textAlign,o=0;s===V.CENTER?o=.5*this.width:s===V.RIGHT&&(o=this.width);var c=tt({x:o,y:i.y},e);return{x:c.x,y:c.y,h:n*e[0]}}var l=tt({x:this.tempCursorX,y:i.y},e);return{x:l.x,y:l.y,h:n*e[0]}}},i.prototype.moveCursor=function(e,t){void 0===t&&(t=!1);var r=this.matrixWorld,i=this.cursor,a=this.getSortedCursor(),n=t?a.endLineBox:a.startLineBox,s=t?a.endTextBox:a.startTextBox,o=t?a.endString:a.startString,c=this.lineBoxList,l=c[n],u=l.list,h=u[s],d=t?a.end:a.start;if(i.isMulti&&!t){if(i.isMulti=!1,i.start!==i.end&&this.refresh(),39===e||40===e){var f=a.endLineBox,m=a.endTextBox,p=a.endString;d=(h=(u=(l=c[f]).list)[m])?h.index+p:l.index+p}return this.inputStyle=void 0,this.updateCursorByIndex(d)}if(t&&(i.isMulti=!0),37===e){if(0===d)return;0===o?0===s?(t?i.endLineBox=--n:i.startLineBox=--n,(u=(l=c[n]).list).length?(t?i.endTextBox=s=u.length-1:i.startTextBox=s=u.length-1,h=u[s],t?(i.endString=h.str.length-(l.endEnter?0:1),i.end=h.index+i.endString):(i.startString=h.str.length-(l.endEnter?0:1),i.start=h.index+i.startString)):t?(i.endTextBox=0,i.endString=0,i.end=l.index):(i.startTextBox=0,i.startString=0,i.start=l.index)):(t?i.endTextBox=--s:i.startTextBox=--s,h=u[s],t?(i.endString=h.str.length-1,i.end=h.index+i.endString):(i.startString=h.str.length-1,i.start=h.index+i.startString)):t?(i.endString=--o,i.end=h.index+i.endString):(i.startString=--o,i.start=h.index+i.startString)}else if(38===e){if(0===d)return;if(0!==n){l=c[--n],t?i.endLineBox=n:i.startLineBox=n;var g=this.getCursorByLocalX(this.tempCursorX,l,t);t&&this.refresh(),this.inputStyle=void 0;var v=tt({x:g.x,y:g.y},r);return{x:v.x,y:v.y,h:l.lineHeight*r[0]}}t?i.endTextBox=0:i.startTextBox=0,h=u[0],t?(i.endString=0,i.end=0):(i.startString=0,i.start=0)}else if(39===e){if(d===this._content.length)return;!h||s===u.length-1&&o===h.str.length&&l.endEnter?(t?(i.endLineBox=++n,i.endTextBox=0,i.endString=0):(i.startLineBox=++n,i.startTextBox=0,i.startString=0),h=(u=(l=c[n]).list)[0],t?i.end=h.index:i.start=h.index):s===u.length-1&&o===h.str.length?(t?(i.endLineBox=++n,i.endTextBox=0,i.endString=1):(i.startLineBox=++n,i.startTextBox=0,i.startString=1),h=(u=(l=c[n]).list)[0],t?i.end=h.index+1:i.start=h.index+1):o===h.str.length?(t?i.endTextBox=++s:i.startTextBox=++s,h=u[s],t?(i.endString=1,i.end=h.index+1):(i.startString=1,i.start=h.index+1),s===u.length-1&&1===h.str.length&&!l.endEnter&&n<c.length-1&&(t?i.endLineBox=++n:i.startLineBox=++n,u=(l=c[n]).list,t?i.endTextBox=s=0:i.startTextBox=s=0,h=u[s],t?(i.endString=0,i.end=h.index):(i.startString=0,i.start=h.index))):o===h.str.length-1?s===u.length-1?l.endEnter||n===c.length-1?t?(i.endString++,i.end=h.index+i.endString):(i.startString++,i.start=h.index+i.startString):(t?i.endLineBox=++n:i.startLineBox=++n,u=(l=c[n]).list,t?i.endTextBox=s=0:i.startTextBox=s=0,h=u[s],t?(i.endString=0,i.end=h.index):(i.startString=0,i.start=h.index)):(t?i.endTextBox=++s:i.startTextBox=++s,h=u[s],t?(i.endString=0,i.end=h.index):(i.startString=0,i.start=h.index)):t?(i.endString=++o,i.end=h.index+i.endString):(i.startString=++o,i.start=h.index+i.startString)}else if(40===e){if(d===this._content.length)return;if(n!==c.length-1){l=c[++n],t?i.endLineBox=n:i.startLineBox=n;g=this.getCursorByLocalX(this.tempCursorX,l,t);t&&this.refresh(),this.inputStyle=void 0;var y=tt({x:g.x,y:g.y},r);return{x:y.x,y:y.y,h:l.lineHeight*r[0]}}t?i.endTextBox=s=u.length-1:i.startTextBox=s=u.length-1,h=u[s],t?(i.endString=h?h.str.length:0,i.end=h.index+i.endString):(i.startString=h?h.str.length:0,i.start=h.index+i.startString)}if(h){var b=ne.getFontCanvas().ctx;b.font=h.font,b.letterSpacing=h.letterSpacing+"px";var k=h.str,T=b.measureText(k.slice(0,i.startString)).width;this.tempCursorX=h.x+T}else{var w=this.computedStyle.textAlign;w===V.CENTER?this.tempCursorX=.5*this.width:w===V.RIGHT?this.tempCursorX=this.width:this.tempCursorX=0}t&&this.refresh(),this.inputStyle=void 0;var S=tt({x:this.tempCursorX,y:l.y},r);return{x:S.x,y:S.y,h:l.lineHeight*r[0]}},i.prototype.selectAll=function(){var e=this.lineBoxList,t=e.length,r=e[t-1],i=null==r?void 0:r.list,a=i?i[i.length-1]:void 0;Object.assign(this.cursor,{isMulti:!0,startLineBox:0,startTextBox:0,startString:0,start:0,endLineBox:t-1,endTextBox:i?i.length-1:0,endString:a?a.str.length:0,end:this._content.length}),this.refresh()},i.prototype.input=function(e){var t=this.getSortedCursor(),r=t.isMulti,i=t.start,a=t.end,n=this._content;if(r){var s=this.getCursorRich();this.cursor.isMulti=!1,this._content=n.slice(0,i)+n.slice(a),this.cutRich(i,a),n=this._content,this._content=n.slice(0,i)+e+n.slice(i),this.insertRich(s[0],i,e.length)}else if(this.inputStyle){s=this.getCursorRich();this._content=n.slice(0,i)+e+n.slice(i),this.insertRich(Object.assign({},s[0],this.inputStyle),i,e.length),this.inputStyle=void 0}else this._content=n.slice(0,i)+e+n.slice(i),this.expandRich(i,e.length);this.refresh(Bt.REFLOW),this.updateCursorByIndex(i+e.length)},i.prototype.enter=function(){this.inputStyle=void 0;var e=this.getSortedCursor(),t=e.isMulti,r=e.start,i=e.end;if(t){this.cursor.isMulti=!1,this.cutRich(r,i);var a=this._content;this._content=a.slice(0,r)+a.slice(i)}this.expandRich(r,1);var n=this._content;this._content=n.slice(0,r)+"\n"+n.slice(r),this.refresh(Bt.REFLOW),this.updateCursorByIndex(r+1)},i.prototype.delete=function(e){void 0===e&&(e=!1),this.inputStyle=void 0;var t=this._content;if(t){var r=this.getSortedCursor(),i=r.isMulti,a=r.start,n=r.end;a<1&&!i&&!e||a===t.length&&e||(i?(this.cursor.isMulti=!1,this._content=t.slice(0,a)+t.slice(n),this.cutRich(a,n)):e?(this._content=t.slice(0,a)+t.slice(a+1),this.cutRich(a,a+1)):(this._content=t.slice(0,a-1)+t.slice(a),this.cutRich(a-1,a)),this.refresh(Bt.REFLOW),i||e?this.updateCursorByIndex(a):this.updateCursorByIndex(a-1))}},i.prototype.getSortedCursor=function(){var e,t=this.cursor,r=t.isMulti,i=t.startLineBox,a=t.startTextBox,n=t.startString,s=t.endLineBox,o=t.endTextBox,c=t.endString,l=t.start,u=t.end,h=!1;return r?l>u&&(i=(e=[s,o,c,u,i,a,n,l])[0],a=e[1],n=e[2],l=e[3],s=e[4],o=e[5],c=e[6],u=e[7],h=!0):(s=i,o=a,c=n,u=l),{isMulti:r,startLineBox:i,startTextBox:a,startString:n,endLineBox:s,endTextBox:o,endString:c,start:l,end:u,isReversed:h}},i.prototype.getCursorRich=function(){var e=this.rich,t=this.lineBoxList,r=[];if(!e.length)return r;function i(t,r,i){for(void 0===r&&(r=0),void 0===i&&(i=e.length-1);r<i;){var a=Math.floor(.5*(r+i)),n=e[a];if(n.location<t&&n.location+n.length>=t)return n;n.location>=t?i=Math.min(a,i-1):r=Math.max(a,r+1)}return e[r]}var a=this.getSortedCursor(),n=a.isMulti,s=a.startLineBox,o=a.startTextBox,c=a.startString,l=a.start,u=a.end;if(n)for(var h=0,d=e.length;h<d;h++){if((f=e[h]).location>=u)break;f.location+f.length>l&&r.push(f)}if(!n||!r.length){var f,m=t[s],p=m.list;if(p.length)(f=i(p[o].index+(o+c===0?1:c)))&&-1===r.indexOf(f)&&r.push(f);else(f=i(m.index))&&-1===r.indexOf(f)&&r.push(f)}return r},i.prototype.getCursorByLocalX=function(e,t,r){void 0===r&&(r=!1);var i=t.list,a=this.cursor,n=0,s=t.y,o=t.lineHeight;r?a.endString=a.end=0:a.startString=a.start=0;e:for(var c=0,l=i.length;c<l;c++){var u=(S=i[c]).x,h=S.w,d=S.str,f=S.font,m=S.letterSpacing;if(!c&&e<u||e>=u&&e<u+h||c===l-1){r?a.endTextBox=c:a.startTextBox=c;var p=ne.getFontCanvas().ctx;p.font=f,p.letterSpacing=m+"px";for(var g=0,v=d.length;g<v;){if(g===v-1){var y=p.measureText(d.slice(0,g)).width,b=p.measureText(d.slice(0,v)).width;e-(u+y)>u+b-e?(n=u+b,r?(a.endString=v,a.end=S.index+v):(a.startString=v,a.start=S.index+v)):(n=u+y,r?(a.endString=g,a.end=S.index+g):(a.startString=g,a.start=S.index+g));break e}var k=g+(v-g>>1),T=p.measureText(d.slice(0,k)).width;if(e>u+T)g=k;else{if(!(e<u+T)){r?(a.endString=k,a.end=S.index+k):(a.startString=k,a.start=S.index+k),n=u+T;break e}v=k}}}}var w=r?a.endTextBox:a.startTextBox;if(w<i.length-1){var S=i[w];(r?a.endString:a.startString)===S.str.length&&(r?(a.endTextBox++,a.endString=0,a.end=i[w+1].index):(a.startTextBox++,a.startString=0,a.start=i[w+1].index))}if(!i.length){r?(a.endString=0,a.end=t.index):(a.startString=0,a.start=t.index);var x=this.computedStyle.textAlign;x===V.CENTER?n=.5*this.width:x===V.RIGHT&&(n=this.width)}return{x:n,y:s,h:o}},i.prototype.getRich=function(){return this.rich.map(function(e){return Object.assign({},e)})},i.prototype.getCursor=function(){return Object.assign({},this.cursor)},i.prototype.updateStyle=function(t,r){var i=e.prototype.updateStyle.call(this,t,r);return i&&i&Bt.REFLOW_REPAINT&&this.reLocateCursor(),i},i.prototype.updateRangeStyle=function(e,t,r,i){var a=kt(r),n=this.updateRangeStyleData(e,t,a);return n&&this.refresh(n,i),n&Bt.REFLOW_REPAINT&&this.reLocateCursor(),n},i.prototype.updateRangeStyleData=function(e,t,i){var a=Bt.NONE;0===e&&this.updateFormatStyleData(i);var n=this,s=n.rich,o=n.computedRich,c=n.style;if(s.length)for(var l=0,u=s.length;l<u&&!(t<1);l++){var h=s[l],d=o[l];if(e>=h.location&&e<h.location+h.length){if(e>h.location){var f=r(r({},h),{length:e-h.location});s.splice(l,0,f),l++,u++,h.location+=f.length,h.length-=f.length,o.splice(l,0,this.calComputedRich(f)),d.location=h.location,d.length=h.length}var m=!1;if(e+t<h.location+h.length){var p=r(r({},h),{location:e+t,length:h.location+h.length-e-t});s.splice(l+1,0,p),h.length-=p.length,o.splice(l+1,0,this.calComputedRich(p)),d.length=h.length,m=!0}if(a|=this.updateRichItem(h,d,i),m)break;e+=h.length,t-=h.length}}else if(0===e&&t>=this._content.length){var g=this.updateFormatStyle(i);g&&(a|=g)}else{if(e>0){var v=Ot({location:0,length:e},c);s.push(v),o.push(this.calComputedRich(v))}var y={location:e,length:t};if(oe.forEach(function(e){y[e]=c[e]}),Object.assign(y,i),s.push(y),o.push(this.calComputedRich(y)),e+t<this._content.length){v=Ot({location:e+t,length:this._content.length-e-t},c);s.push(v),o.push(this.calComputedRich(v))}a|=Bt.REFLOW}return this.mergeRich(),a},i.prototype.updateRichItem=function(e,t,r){var i=Bt.NONE;if(r.fontFamily&&r.fontFamily.v!==e.fontFamily.v&&(e.fontFamily=r.fontFamily,i|=Bt.REFLOW),r.fontSize&&r.fontSize.v!==e.fontSize.v&&(e.fontSize=r.fontSize,i|=Bt.REFLOW),r.color&&(e.color.v[0]===r.color.v[0]&&e.color.v[1]===r.color.v[1]&&e.color.v[2]===r.color.v[2]&&e.color.v[3]===r.color.v[3]||(e.color=r.color,i|=Bt.REFLOW)),r.letterSpacing&&r.letterSpacing.v!==e.letterSpacing.v&&(e.letterSpacing=r.letterSpacing,i|=Bt.REFLOW),r.lineHeight&&r.lineHeight.v!==e.lineHeight.v&&(e.lineHeight=r.lineHeight,i|=Bt.REFLOW),r.paragraphSpacing&&r.paragraphSpacing.v!==e.paragraphSpacing.v&&(e.paragraphSpacing=r.paragraphSpacing,i|=Bt.REFLOW),r.textAlign&&r.textAlign.v!==e.textAlign.v&&(e.textAlign=r.textAlign,i|=Bt.REFLOW),r.textDecoration)if(r.textDecoration.length!==e.textDecoration.length)e.textDecoration=r.textDecoration,i|=Bt.REFLOW;else for(var a=0,n=e.textDecoration.length;a<n;a++)if(r.textDecoration[a].v!==e.textDecoration[a].v){e.textDecoration=r.textDecoration,i|=Bt.REFLOW;break}return r.textShadow&&r.textShadow.v!==e.textShadow.v&&(e.textShadow=r.textShadow,i|=Bt.REFLOW),Object.assign(t,this.calComputedRich(e)),i},Object.defineProperty(i.prototype,"bbox",{get:function(){var e=this._bbox;if(!e){var t=this._rect||this.rect;e=this._bbox=t.slice(0),this.lineBoxList.forEach(function(t){t.list.forEach(function(t){var r=t.fontFamily,i=t.fontSize,a=t.lineHeight,n=t.str,s=t.font,o=t.textShadow,c=a;if(Ve.hasRegister(r)){c=Ve.data[r].lhr*i}else{var l=ne.getFontCanvas().ctx;l.font=s;var u=l.measureText(n);c=u.actualBoundingBoxAscent+u.actualBoundingBoxDescent}var h=Math.max(0,.5*(c-a));if(h>0){var d=t.y-h,f=t.lineHeight+h;e[1]=Math.min(e[1],d),e[3]=Math.max(e[3],f)}if(o){var m=dt(o.blur),p=o.x+m,g=o.y+m;p>0?e[2]=Math.max(e[2],t.x+t.w+p):p<0&&(e[0]=Math.min(e[0],t.x+p)),g>0?e[3]=Math.max(e[3],t.y+t.lineHeight+g+h):g<0&&(e[1]=Math.min(e[1],t.y+g-h))}})});var r=this.computedStyle,i=r.strokeWidth,a=r.strokeEnable,n=r.strokePosition,s=0;i.forEach(function(e,t){a[t]&&(n[t]===Z.INSIDE||(s=n[t]===Z.OUTSIDE?Math.max(s,2*e):Math.max(s,.5*e*2)))}),e[0]-=s,e[1]-=s,e[2]+=s,e[3]+=s}return e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"content",{get:function(){return this._content},set:function(e){this._content!==e&&(this._content=e,this.refresh(Bt.REFLOW))},enumerable:!1,configurable:!0}),i}(wr),wh={Container:Fr,Bitmap:_r,Node:wr,Root:fh,Video:Lu,Audio:zu,Text:Th,Lottie:Qu};!function(e){e[e.NONE=0]="NONE",e[e.LOADING=1]="LOADING",e[e.LOADED=2]="LOADED"}(bh||(bh={}));var Sh,xh={};!function(e){e[e.NONE=0]="NONE",e[e.LOADING=1]="LOADING",e[e.LOADED=2]="LOADED"}(Sh||(Sh={}));var Ch={};var Eh,Ah={type:I,Event:R,inject:ne,opentype:Be,loadImg:xr,loadAudio:function(e,t){return i(this,void 0,void 0,function(){var r,i,n,s;return a(this,function(a){switch(a.label){case 0:if(r=xh[e]){if(r.count++,r.state===bh.LOADED)return[2,r.res];if(r.state===bh.LOADING)return[2,new Promise(function(e){r.list.push(e)})]}return r=xh[e]={state:bh.LOADING,list:[],count:0,res:{success:!1,duration:0,release:function(){r.count--,r.count<=0&&(r.res.audioBuffer=void 0,delete xh[e])}}},[4,fetch(e,Object.assign({mode:"cors"},t))];case 1:return 200!==(i=a.sent()).status&&304!==i.status?(r.state=bh.LOADED,[2,r.res]):[4,i.arrayBuffer()];case 2:return n=a.sent(),[4,(new AudioContext).decodeAudioData(n)];case 3:return s=a.sent(),r.count++,[2,new Promise(function(e){r.res.success=!0,r.res.audioBuffer=s,r.res.duration=Math.ceil(1e3*s.duration),r.state=bh.LOADED,e(r.res),r.list.splice(0).forEach(function(e){r.count++,e(r.res)})})]}})})},loadFont:function(e,t,r){return i(this,void 0,void 0,function(){var i,n,s;return a(this,function(a){switch(a.label){case 0:if(i=Ch[e]){if(i.count++,i.state===Sh.LOADED)return[2,i.res];if(i.state===Sh.LOADING)return[2,new Promise(function(e){i.list.push(e)})]}return i=Ch[e]={state:Sh.LOADING,list:[],count:0,res:{success:!1,release:function(){i.count--,i.count<=0&&delete Ch[e]}}},[4,fetch(e,Object.assign({mode:"cors"},r))];case 1:return 200!==(n=a.sent()).status&&304!==n.status?(i.state=Sh.LOADED,[2,i.res]):[4,n.arrayBuffer()];case 2:return s=a.sent(),[4,Ve.registerAb(s,t)];case 3:return a.sent(),i.count++,[2,new Promise(function(e){i.res.success=!0,i.res.arrayBuffer=s,i.state=Sh.LOADED,e(i.res),i.list.splice(0).forEach(function(e){i.count++,e(i.res)})})]}})})},loadRange:Eu,MbVideoDecoder:Nu,MbVideoDecoderEvent:Pu,MbVideoEncoder:dh,MbVideoEncoderEvent:lh,sound:uh},Ph={font:Ve,transform:ht,define:ce,css:Ut,color:fe},Ih=function(){function e(e,t){this.root=e,this.dom=t;var r=this.select=document.createElement("div");r.className="select",r.style.display="none",r.innerHTML='\n <div class="sub"></div>\n <span class="l">\n <b></b>\n </span>\n <span class="t">\n <b></b>\n </span>\n <span class="r">\n <b></b>\n </span>\n <span class="b">\n <b></b>\n </span>\n <span class="tl">\n <b></b>\n </span>\n <span class="tr">\n <b></b>\n </span>\n <span class="br">\n <b></b>\n </span>\n <span class="bl">\n <b></b>\n </span>\n',t.appendChild(r)}return e.prototype.showSelect=function(e){this.updateSelect(e),this.select.style.display="block"},e.prototype.updateSelect=function(e){var t=this.select.querySelector(".sub");if(1===e.length){t.innerHTML="",this.select.classList.remove("multi"),e[0].computedStyle.visibility===ee.VISIBLE?this.select.classList.remove("hide"):this.select.classList.add("hide");var r=this.calRect(e[0]);this.select.style.left=r.left+"px",this.select.style.top=r.top+"px",this.select.style.width=r.width+"px",this.select.style.height=r.height+"px",this.select.style.transform=r.transform}},e.prototype.calRect=function(e){var t=this.root.canvas,r=e._rect||e.rect,i=e.matrixWorld,a=t.clientWidth/t.width,n=t.clientHeight/t.height;if(1!==a||1!==n){var s=Xe();i=Ge(s,i),Je(s,a),et(s,n),i=Ge(s,i)}var o=rt(r[0],r[1],r[2],r[3],i),c=o.x1,l=o.y1,u=o.x2,h=o.y2,d=o.x3,f=o.y3,m={left:c,top:l,width:Math.sqrt(Math.pow(c-u,2)+Math.pow(l-h,2)),height:Math.sqrt(Math.pow(u-d,2)+Math.pow(h-f,2)),transform:""};if(u>c){if(h!==l){var p=at(Math.atan((h-l)/(u-c)));m.transform="rotateZ(".concat(p,"deg)")}}else if(u<c){p=at(Math.atan((h-l)/(u-c)));m.transform="rotateZ(".concat(p+180,"deg)")}else h>l?m.transform="rotateZ(90deg)":h<l&&(m.transform="rotateZ(-90deg)");return m},e.prototype.hideSelect=function(){this.select.style.display="none"},e.prototype.release=function(){this.select.remove()},e.prototype.metaKey=function(e){e?this.select.classList.add("rotate"):this.select.classList.remove("rotate")},e.prototype.isSelectControlDom=function(e){return e.parentElement===this.select},e.prototype.getAspectRatio=function(){var e=this.select.style;return{x:parseFloat(e.left),y:parseFloat(e.top),w:parseFloat(e.width),h:parseFloat(e.height)}},e}();!function(e){e[e.NORMAL=0]="NORMAL",e[e.HAND=1]="HAND",e[e.RESIZE=2]="RESIZE",e[e.EDIT_TEXT=3]="EDIT_TEXT",e[e.EDIT_GRADIENT=4]="EDIT_GRADIENT",e[e.EDIT_GEOM=5]="EDIT_GEOM",e[e.ADD_TEXT=6]="ADD_TEXT",e[e.ADD_RECT=7]="ADD_RECT",e[e.ADD_OVAL=8]="ADD_OVAL",e[e.ADD_ROUND=9]="ADD_ROUND",e[e.ADD_TRIANGLE=10]="ADD_TRIANGLE",e[e.ADD_LINE=11]="ADD_LINE",e[e.ADD_STAR=12]="ADD_STAR",e[e.ADD_IMG=13]="ADD_IMG",e[e.ADD_PEN=14]="ADD_PEN",e[e.ADD_CUSTOM_GEOM=15]="ADD_CUSTOM_GEOM"}(Eh||(Eh={}));var Rh,Oh=Eh,Mh="cursor",_h="content",Dh="state_change",Bh={SELECT:"select",MOVE:"move",REMOVE:"remove",ADD:"add",RESIZE:"resize",ROTATE:"rotate",CURSOR:Mh,CONTENT:_h,STATE_CHANGE:Dh},Fh=function(e){this.nodes=e},Nh=function(e){function r(t,r){var i=e.call(this,t)||this;return i.data=r,i}return t(r,e),r.prototype.execute=function(){var e=this.nodes,t=this.data;e.forEach(function(e,i){var a=t[i],n=a.dx,s=a.dy,o=e.getStyle(),c=e.computedStyle;r.operate(e,c,n,s),e.endPosChange(o,n,s),e.checkPosSizeUpward()})},r.prototype.undo=function(){var e=this.nodes,t=this.data;e.forEach(function(e,i){var a=t[i],n=a.dx,s=a.dy,o=e.getStyle(),c=e.computedStyle;r.operate(e,c,-n,-s),e.endPosChange(o,-n,-s),e.checkPosSizeUpward()})},r.operate=function(e,t,r,i){e.updateStyle({translateX:t.translateX+r,translateY:t.translateY+i})},r}(Fh);var Lh=function(){function e(e){void 0===e&&(e=100),this.commands=[],this.commandsR=[],this.size=Math.max(1,e),this.lastTime=0}return e.prototype.addCommand=function(e,t){void 0===t&&(t=!1),this.commandsR.splice(0);var r=this.commands.length;if(!t&&r>0){var i=this.commands[r-1];if(Date.now()-this.lastTime<F.historyTime&&function(e,t){if(e.constructor!==t.constructor)return!1;var r=e.nodes,i=t.nodes;if(r.length!==i.length)return!1;for(var a=0,n=r.length;a<n;a++)if(r[a]!==i[a])return!1;return!0}(i,e)){var a=!0;if(i instanceof Nh){var n=e.data;i.data.forEach(function(e,t){e.dx+=n[t].dx,e.dy+=n[t].dy})}else a=!1;if(a)return void(this.lastTime=Date.now())}}this.lastTime=Date.now(),r>=this.size&&this.commands.slice(0,r-this.size+1),this.commands.push(e)},e.prototype.undo=function(){if(this.commands.length){var e=this.commands.pop();return e.undo(),this.commandsR.push(e),e}},e.prototype.redo=function(){if(this.commandsR.length){var e=this.commandsR.pop();return e.execute(),this.commands.push(e),e}},e.getInstance=function(){return Rh||(Rh=new e),Rh},e}();var Uh,zh=function(e){function r(t,r){var i=e.call(this,t)||this;return i.data=r,i}return t(r,e),r.prototype.execute=function(){this.nodes.forEach(function(e){e.remove()})},r.prototype.undo=function(){var e=this.nodes,t=this.data;e.forEach(function(e,r){!function(e,t){var r=e.style,i=e.computedStyle,a=t.x,n=t.y,s=t.parent,o=t.index,c=A(r.top),l=A(r.right),u=A(r.bottom),h=A(r.left),d=A(r.width),f=A(r.height);r.left={v:a,u:W.PX},r.right={v:0,u:W.AUTO},r.top={v:n,u:W.PX},r.bottom={v:0,u:W.AUTO},r.width={v:i.width,u:W.PX},r.height={v:i.height,u:W.PX},function(e,t,r){var i=e.children;r<=0?e.prependChild(t):r>=i.length?e.appendChild(t):i[r].insertAfter(t)}(s,e,o),h.u===W.PERCENT?r.left={v:100*i.left/s.width,u:W.PERCENT}:h.u===W.PX?r.left={v:i.left,u:W.PX}:h.u===W.AUTO&&(r.left={v:0,u:W.AUTO}),l.u===W.PERCENT?r.right={v:100*i.right/s.width,u:W.PERCENT}:l.u===W.PX?r.right={v:i.right,u:W.PX}:l.u===W.AUTO&&(r.right={v:0,u:W.AUTO}),c.u===W.PERCENT?r.top={v:100*i.top/s.height,u:W.PERCENT}:c.u===W.PX?r.top={v:i.top,u:W.PX}:c.u===W.AUTO&&(r.top={v:0,u:W.AUTO}),u.u===W.PERCENT?r.bottom={v:100*i.bottom/s.height,u:W.PERCENT}:u.u===W.PX?r.bottom={v:i.bottom,u:W.PX}:u.u===W.AUTO&&(r.bottom={v:0,u:W.AUTO}),d.u===W.PERCENT?r.width={v:100*i.width/s.width,u:W.PERCENT}:d.u===W.PX?r.width={v:i.width,u:W.PX}:d.u===W.AUTO&&(r.width={v:0,u:W.AUTO}),f.u===W.PERCENT?r.height={v:100*i.height/s.height,u:W.PERCENT}:f.u===W.PX?r.height={v:i.height,u:W.PX}:f.u===W.AUTO&&(r.height={v:0,u:W.AUTO})}(e,t[r])})},r.operate=function(e){var t=e.parent,r=t.children.indexOf(e),i={x:e.computedStyle.left,y:e.computedStyle.top,parent:t,index:r};return e.remove(),i},r}(Fh);function Wh(e,t,r,i){void 0===i&&(i=!1);var a=e.style,n={};if(r>t.height){r-=t.height,r=Math.max(r,1),a.top.u===W.PX?n.top=t.top+t.height:a.left.u===W.PERCENT&&(n.top=100*(t.top+t.height)/e.parent.height+"%");var s=Object.assign({},t);s.height=0,Object.assign(n,Vh(e,s,r)),n.scaleY=-1*t.scaleY}else r=Math.min(r,t.height-1),n.scaleY=t.scaleY,a.top.u===W.PX||a.top.u===W.PERCENT?(a.top.u===W.PX?n.top=t.top+r:n.top=100*(t.top+r)/e.parent.height+"%",a.height.u===W.PX||a.height.u===W.AUTO&&a.bottom.u===W.AUTO?n.height=t.height-r:a.height.u===W.PERCENT&&(n.height=100*(t.height-r)/e.parent.height+"%")):a.height.u!==W.PX&&a.height.u!==W.PERCENT&&a.height.u!==W.AUTO||(a.height.u===W.PX||a.height.u===W.AUTO?n.height=t.height-r:n.height=100*(t.height-r)/e.parent.height+"%");if(i){var o=Vh(e,t,-r);o.height&&("number"==typeof o.height?o.height=t.height-2*r:o.height=100*(t.height-2*r)/e.parent.height+"%"),Object.assign(n,o)}return n}function Vh(e,t,r,i){void 0===i&&(i=!1);var a=e.style,n={};if(r<-t.height){r+=t.height,r=Math.min(r,-1),a.bottom.u===W.PX?n.bottom=t.bottom+t.height:a.bottom.u===W.PERCENT&&(n.bottom=100*(t.bottom+t.height)/e.parent.height+"%");var s=Object.assign({},t);s.height=0,Object.assign(n,Wh(e,s,r)),n.scaleY=-1*t.scaleY}else r=Math.max(r,1-t.height),n.scaleY=t.scaleY,a.bottom.u===W.PX||a.bottom.u===W.PERCENT?(a.bottom.u===W.PX?n.bottom=t.bottom-r:n.bottom=100*(t.bottom-r)/e.parent.height+"%",a.height.u===W.PX||a.height.u===W.AUTO&&a.top.u===W.AUTO?n.height=t.height+r:a.height.u===W.PERCENT&&(n.height=100*(t.height+r)/e.parent.height+"%")):a.height.u!==W.PX&&a.height.u!==W.PERCENT&&a.height.u!==W.AUTO||(a.height.u===W.PX||a.height.u===W.AUTO?n.height=t.height+r:n.height=100*(t.height+r)/e.parent.height+"%");if(i){var o=Wh(e,t,-r);o.height&&("number"==typeof o.height?o.height=t.height+2*r:o.height=100*(t.height+2*r)/e.parent.height+"%"),Object.assign(n,o)}return n}function Hh(e,t,r,i){void 0===i&&(i=!1);var a=e.style,n={};if(r>t.width){r-=t.width,r=Math.max(r,1),a.left.u===W.PX?n.left=t.left+t.width:a.left.u===W.PERCENT&&(n.left=100*(t.left+t.width)/e.parent.width+"%");var s=Object.assign({},t);s.width=0,Object.assign(n,jh(e,s,r)),n.scaleX=-1*t.scaleX}else r=Math.min(r,t.width-1),n.scaleX=t.scaleX,a.left.u===W.PX||a.left.u===W.PERCENT?(a.left.u===W.PX?n.left=t.left+r:n.left=100*(t.left+r)/e.parent.width+"%",a.width.u===W.PX||a.width.u===W.AUTO&&a.right.u===W.AUTO?n.width=t.width-r:a.width.u===W.PERCENT&&(n.width=100*(t.width-r)/e.parent.width+"%")):a.width.u!==W.PX&&a.width.u!==W.PERCENT&&a.width.u!==W.AUTO||(a.width.u===W.PX||a.width.u===W.AUTO?n.width=t.width-r:n.width=100*(t.width-r)/e.parent.width+"%");if(i){var o=jh(e,t,-r);o.width&&("number"==typeof o.width?o.width=t.width-2*r:o.width=100*(t.width-2*r)/e.parent.width+"%"),Object.assign(n,o)}return n}function jh(e,t,r,i){void 0===i&&(i=!1);var a=e.style,n={};if(r<-t.width){r+=t.width,r=Math.min(r,-1),a.right.u===W.PX?n.right=t.right+t.width:a.right.u===W.PERCENT&&(n.right=100*(t.right+t.width)/e.parent.width+"%");var s=Object.assign({},t);s.width=0,Object.assign(n,Hh(e,s,r)),n.scaleX=-1*t.scaleX}else r=Math.max(r,1-t.width),n.scaleX=t.scaleX,a.right.u===W.PX||a.right.u===W.PERCENT?(a.right.u===W.PX?n.right=t.right-r:n.right=100*(t.right-r)/e.parent.width+"%",a.width.u===W.PX||a.width.u===W.AUTO&&a.left.u===W.AUTO?n.width=t.width+r:a.width.u===W.PERCENT&&(n.width=100*(t.width+r)/e.parent.width+"%")):a.width.u!==W.PX&&a.width.u!==W.PERCENT&&a.width.u!==W.AUTO||(a.width.u===W.PX||a.width.u===W.AUTO?n.width=t.width+r:n.width=100*(t.width+r)/e.parent.width+"%");if(i){var o=Hh(e,t,-r);o.width&&("number"==typeof o.width?o.width=t.width+2*r:o.width=100*(t.width+2*r)/e.parent.width+"%"),Object.assign(n,o)}return n}function Xh(e,t,r){var i=r*(t.width/t.height),a=Hh(e,t,.5*-i),n=jh(e,t,.5*i),s=Object.assign({},a,n);if(s.width)if("number"==typeof s.width){var o=s.width-t.width;s.width=t.width+2*o}else{var c=e.parent.width;o=parseFloat(s.width)*c*.01-t.width;s.width=100*(t.width+2*o)/c+"%"}return s}function qh(e,t,r,i){void 0===i&&(i=!1);var a=Wh(e,t,r);if(i){var n=Vh(e,t,-r);n.height&&("number"==typeof n.height?n.height=t.height-2*r:n.height=100*(t.height-2*r)/e.parent.height+"%"),Object.assign(a,n)}var s=Xh(e,t,i?2*-r:-r);return Object.assign(a,s)}function Gh(e,t,r,i){void 0===i&&(i=!1);var a=Vh(e,t,r);if(i){var n=Wh(e,t,-r);n.height&&("number"==typeof n.height?n.height=t.height+2*r:n.height=100*(t.height+2*r)/e.parent.height+"%"),Object.assign(a,n)}var s=Xh(e,t,i?2*r:r);return Object.assign(a,s)}function Kh(e,t,r){var i=r/(t.width/t.height),a=Wh(e,t,.5*-i),n=Vh(e,t,.5*i),s=Object.assign({},a,n);if(s.height)if("number"==typeof s.height){var o=s.height-t.height;s.height=t.height+2*o}else{var c=e.parent.height;o=parseFloat(s.height)*c*.01-t.height;s.height=100*(t.height+2*o)/c+"%"}return s}function Yh(e,t,r,i){void 0===i&&(i=!1);var a=Hh(e,t,r);if(i){var n=jh(e,t,-r);n.width&&("number"==typeof n.width?n.width=t.width-2*r:n.width=100*(t.width-2*r)/e.parent.width+"%"),Object.assign(a,n)}var s=Kh(e,t,i?2*-r:-r);return Object.assign(a,s)}function $h(e,t,r,i){void 0===i&&(i=!1);var a=jh(e,t,r);if(i){var n=Hh(e,t,-r);n.width&&("number"==typeof n.width?n.width=t.width+2*r:n.width=100*(t.width+2*r)/e.parent.width+"%"),Object.assign(a,n)}var s=Kh(e,t,i?2*r:r);return Object.assign(a,s)}function Qh(e,t,r,i){void 0===i&&(i=!0);var a=e.width,n=e.height,s=n/a;i||(s*=-1);var o=-1/s,c=a+t,l=n+r,u=(l-n+s*a-o*c)/(s-o);return{x:u,y:o*u-o*c+l}}function Zh(e,t,r,i){i&&(e.left?"number"==typeof e.left?e.left+=i:e.left=parseFloat(e.left)+i/t.parent.width*100+"%":e.width||(t.style.left.u===W.PERCENT?e.left=100*(r.left+i)/t.parent.width+"%":t.style.left.u===W.PX&&(e.left=r.left+i)),e.right?"number"==typeof e.right?e.right-=i:e.right=parseFloat(e.right)-i/t.parent.width*100+"%":e.width||(t.style.right.u===W.PERCENT?e.right=100*(r.right-i)/t.parent.width+"%":t.style.right.u===W.PX&&(e.right=r.right-i)))}function Jh(e,t,r,i){i&&(e.top?"number"==typeof e.top?e.top+=i:e.top=parseFloat(e.top)+i/t.parent.height*100+"%":e.height||(t.style.top.u===W.PERCENT?e.top=100*(r.top+i)/t.parent.height+"%":t.style.top.u===W.PX&&(e.top=r.top+i)),e.bottom?"number"==typeof e.bottom?e.bottom-=i:e.bottom=parseFloat(e.bottom)-i/t.parent.height*100+"%":e.height||(t.style.bottom.u===W.PERCENT?e.bottom=100*(r.bottom-i)/t.parent.height+"%":t.style.bottom.u===W.PX&&(e.bottom=r.bottom-i)))}function ed(e,t,r){var i=e*r.h/r.w,a=r.y+.5*r.h;return(t.y+.5*t.h-a)*i/r.h}function td(e,t,r){var i=e*r.w/r.h,a=r.x+.5*r.w;return(t.x+.5*t.w-a)*i/r.w}function rd(e,t,r,i,a,n,s){void 0===n&&(n=!1),void 0===s&&(s=!1);var o=n?qh(e,t,r*i.h/a.h,s):Wh(e,t,r*i.h/a.h,s),c=td(r,i,a);s&&(c*=2),Zh(o,e,t,-c);return Jh(o,e,t,s?-r*(i.y+.5*i.h-a.y-.5*a.h)*2/a.h:r*(a.y+a.h-i.y-i.h)/a.h),o}function id(e,t,r,i,a,n,s){void 0===n&&(n=!1),void 0===s&&(s=!1);var o=n?Gh(e,t,r*i.h/a.h,s):Vh(e,t,r*i.h/a.h,s);if(n){var c=td(r,i,a);s&&(c*=2),Zh(o,e,t,c)}return Jh(o,e,t,s?r*(i.y+.5*i.h-a.y-.5*a.h)*2/a.h:r*(i.y-a.y)/a.h),o}function ad(e,t,r,i,a,n,s){void 0===n&&(n=!1),void 0===s&&(s=!1);var o=n?Yh(e,t,r*i.w/a.w,s):Hh(e,t,r*i.w/a.w,s);if(n){var c=ed(r,i,a);s&&(c*=2),Jh(o,e,t,-c)}return Zh(o,e,t,s?-r*(i.x+.5*i.w-a.x-.5*a.w)*2/a.w:r*(a.x+a.w-i.x-i.w)/a.w),o}function nd(e,t,r,i,a,n,s){void 0===n&&(n=!1),void 0===s&&(s=!1);var o=n?$h(e,t,r*i.w/a.w,s):jh(e,t,r*i.w/a.w,s);if(n){var c=ed(r,i,a);s&&(c*=2),Jh(o,e,t,c)}return Zh(o,e,t,s?r*(i.x+.5*i.w-a.x-.5*a.w)*2/a.w:r*(i.x-a.x)/a.w),o}function sd(e,t,r,i,a,n){var s=rd(e,t,r,i,a);delete n.top,delete n.height,delete n.bottom,void 0!==s.top&&(n.top=s.top),void 0!==s.height&&(n.height=s.height),void 0!==s.bottom&&(n.bottom=s.bottom)}function od(e,t,r,i,a,n){var s=id(e,t,r,i,a);delete n.top,delete n.height,delete n.bottom,void 0!==s.top&&(n.top=s.top),void 0!==s.height&&(n.height=s.height),void 0!==s.bottom&&(n.bottom=s.bottom)}!function(e){e[e.T=0]="T",e[e.R=1]="R",e[e.B=2]="B",e[e.L=3]="L",e[e.TL=4]="TL",e[e.TR=5]="TR",e[e.BL=6]="BL",e[e.BR=7]="BR"}(Uh||(Uh={}));var cd=function(e){function r(t,r){var i=e.call(this,t)||this;return i.data=r,i}return t(r,e),r.prototype.execute=function(){var e=this.nodes,t=this.data;e.forEach(function(e,i){var a=t[i],n=a.dx,s=a.dy,o=a.controlType,c=a.aspectRatio,l=a.clientRect,u=a.selectRect,h=a.fromCenter,d=a.widthToAuto,f=a.heightToAuto,m=e.getStyle();e.startSizeChange();var p=e.getComputedStyle(),g=e.getCssStyle();l?r.operateMultiAr(e,p,g,n,s,o,l,u,c,h,d,f):r.operate(e,p,g,n,s,o,c,h,d,f),e.endSizeChange(m),e.checkPosSizeUpward()})},r.prototype.undo=function(){var e=this.nodes,t=this.data;e.forEach(function(e,i){var a=t[i],n=a.dx,s=a.dy,o=a.controlType,c=a.aspectRatio,l=a.clientRect,u=a.selectRect,h=a.fromCenter,d=a.widthFromAuto,f=a.heightFromAuto,m=e.getStyle();e.startSizeChange();var p=e.getComputedStyle(),g=e.getCssStyle();o=function(e){return e}(o),l?r.operateMultiAr(e,p,g,-n,-s,o,l,u,c,h,d,f):r.operate(e,p,g,-n,-s,o,c,h,d,f),e.endSizeChange(m),e.checkPosSizeUpward()})},r.operate=function(e,t,r,i,a,n,s,o,c,l){void 0===o&&(o=!1),void 0===c&&(c=!1),void 0===l&&(l=!1);var u={left:r.left,right:r.right,top:r.top,bottom:r.bottom,width:r.width,height:r.height,scaleX:r.scaleX,scaleY:r.scaleY};s?n===Uh.T?Object.assign(u,qh(e,t,a,o)):n===Uh.R?Object.assign(u,$h(e,t,i,o)):n===Uh.B?Object.assign(u,Gh(e,t,a,o)):n===Uh.L?Object.assign(u,Yh(e,t,i,o)):n===Uh.TL?Object.assign(u,function(e,t,r,i,a){void 0===a&&(a=!1);var n=Qh(t,r,i,!0),s=n.x,o=n.y,c=Hh(e,t,s-t.width,a);return Object.assign(c,Wh(e,t,o-t.height,a)),c}(e,t,i,a,o)):n===Uh.TR?Object.assign(u,function(e,t,r,i,a){void 0===a&&(a=!1);var n=Qh(t,r,i,!1),s=n.x,o=n.y,c=jh(e,t,s-t.width,a);return Object.assign(c,Wh(e,t,o-t.height,a)),c}(e,t,i,a,o)):n===Uh.BL?Object.assign(u,function(e,t,r,i,a){void 0===a&&(a=!1);var n=Qh(t,r,i,!1),s=n.x,o=n.y,c=Hh(e,t,s-t.width,a);return Object.assign(c,Vh(e,t,o-t.height,a)),c}(e,t,i,a,o)):n===Uh.BR&&Object.assign(u,function(e,t,r,i,a){void 0===a&&(a=!1);var n=Qh(t,r,i,!0),s=n.x,o=n.y,c=jh(e,t,s-t.width,a);return Object.assign(c,Vh(e,t,o-t.height,a)),c}(e,t,i,a,o)):(n===Uh.T||n===Uh.TL||n===Uh.TR?Object.assign(u,Wh(e,t,a,o)):n!==Uh.B&&n!==Uh.BL&&n!==Uh.BR||Object.assign(u,Vh(e,t,a,o)),n===Uh.L||n===Uh.TL||n===Uh.BL?Object.assign(u,Hh(e,t,i,o)):n!==Uh.R&&n!==Uh.TR&&n!==Uh.BR||Object.assign(u,jh(e,t,i,o))),c&&(u.width="auto"),l&&(u.height="auto"),e.updateStyle(u)},r.operateMultiAr=function(e,t,r,i,a,n,s,o,c,l,u,h){void 0===l&&(l=!1),void 0===u&&(u=!1),void 0===h&&(h=!1);var d={left:r.left,right:r.right,top:r.top,bottom:r.bottom,width:r.width,height:r.height,scaleX:r.scaleX,scaleY:r.scaleY};if(n===Uh.T)Object.assign(d,rd(e,t,a,s,o,c,l));else if(n===Uh.R)Object.assign(d,nd(e,t,i,s,o,c,l));else if(n===Uh.B)Object.assign(d,id(e,t,a,s,o,c,l));else if(n===Uh.L)Object.assign(d,ad(e,t,i,s,o,c,l));else{if(c){var f={width:o.w,height:o.h},m=Qh(f,i,a,[Uh.TL,Uh.BR].includes(n)),p=m.x,g=m.y;i=p-f.width,a=g-f.height}n===Uh.TL?Object.assign(d,function(e,t,r,i,a,n,s,o){void 0===s&&(s=!1),void 0===o&&(o=!1);var c=ad(e,t,r,a,n,s,o);if(o)return c;if(s)sd(e,t,i,a,n,c);else{var l=rd(e,t,i,a,n,s,o);Object.assign(c,l)}return c}(e,t,i,a,s,o,c,l)):n===Uh.TR?Object.assign(d,function(e,t,r,i,a,n,s,o){void 0===s&&(s=!1),void 0===o&&(o=!1);var c=nd(e,t,r,a,n,s,o);if(o)return c;if(s)sd(e,t,i,a,n,c);else{var l=rd(e,t,i,a,n,s,o);Object.assign(c,l)}return c}(e,t,i,a,s,o,c,l)):n===Uh.BL?Object.assign(d,function(e,t,r,i,a,n,s,o){void 0===s&&(s=!1),void 0===o&&(o=!1);var c=ad(e,t,r,a,n,s,o);if(o)return c;if(s)od(e,t,i,a,n,c);else{var l=id(e,t,i,a,n,s,o);Object.assign(c,l)}return c}(e,t,i,a,s,o,c,l)):n===Uh.BR&&Object.assign(d,function(e,t,r,i,a,n,s,o){void 0===s&&(s=!1),void 0===o&&(o=!1);var c=nd(e,t,r,a,n,s,o);if(o)return c;if(s)od(e,t,i,a,n,c);else{var l=id(e,t,i,a,n,s,o);Object.assign(c,l)}return c}(e,t,i,a,s,o,c,l))}u&&(d.width="auto"),h&&(d.height="auto"),e.updateStyle(d)},r}(Fh);var ld=function(e){function r(t,r){var i=e.call(this,t)||this;return i.data=r,i}return t(r,e),r.prototype.execute=function(){var e=this.nodes,t=this.data;e.forEach(function(e,r){e.updateStyle(t[r].next)})},r.prototype.undo=function(){var e=this.nodes,t=this.data;e.forEach(function(e,r){e.updateStyle(t[r].prev)})},r}(Fh),ud=function(e){function r(t,r){return e.call(this,t,r)||this}return t(r,e),r}(ld);function hd(e,t,r){for(var i=e.children,a=i.length-1;a>=0;a--){var n=i[a],s=n.matrixWorld;if(n.hasContent&&n.computedStyle.visibility!==ee.HIDDEN){var o=n._rect||n.rect;if(nt(t,r,o[0],o[1],o[2],o[3],s,!0)){var c;if(n instanceof Fr)if(c=hd(n,t,r))return c;return n}if(n instanceof Fr&&(c=hd(n,t,r)))return c}}}function dd(e,t,r,i){return hd(e,t,r)}var fd=function(e){function r(t,r){var i=e.call(this,t)||this;return i.data=r,i}return t(r,e),r.prototype.execute=function(){var e=this.nodes,t=this.data;e.forEach(function(e,r){e.beforeEdit(),e.cursor=t[r].next.cursor,e.content=t[r].next.content,e.rich=t[r].next.rich,e.afterEdit()})},r.prototype.undo=function(){var e=this.nodes,t=this.data;e.forEach(function(e,r){e.beforeEdit(),e.cursor=t[r].prev.cursor,e.content=t[r].prev.content,e.rich=t[r].prev.rich,e.afterEdit()})},r}(Fh),md=function(){function e(e,t,r){var i=this;this.root=e,this.dom=t,this.listener=r,this.ignoreBlur=[],this.ignoreBlurUnFocus=[],this.hasBlur=!0;var a=this.containerEl=document.createElement("div");a.className="input",a.style.position="absolute",a.style.pointerEvents="none",a.style.opacity="0",t.appendChild(a);var n=this.inputEl=document.createElement("input");n.style.position="absolute",n.style.left="0px",n.style.top="0px",n.style.width="10px",n.style.height="100%",n.style.boxSizing="content-box",n.style.border="none",n.style.pointerEvents="none",n.style.opacity="0",n.type="text",n.autocomplete="off",n.spellcheck=!1,a.appendChild(n);var s=function(e){if(i.node){var t=i.node.content,a=i.node.getRich(),s=i.node.getCursor();e(),i.updateCursor(),i.showCursor(),n.value="",i.listener.select.updateSelect([i.node]),r.emit([_h,Mh],[i.node]),i.listener.history.addCommand(new fd([i.node],[{prev:{content:t,rich:a,cursor:s},next:{content:i.node.content,rich:i.node.getRich(),cursor:i.node.getCursor()}}]),i.hasBlur),i.hasBlur=!1}},o=function(e){e&&s(function(){var t;null===(t=i.node)||void 0===t||t.input(e)})},c=!1;n.addEventListener("keydown",function(e){var t=e.keyCode,a=e.code;if(i.node)if(13===t||"Enter"===a)s(function(){var e;null===(e=i.node)||void 0===e||e.enter()});else if(8===t||46===t||"Backspace"===a||"Delete"===a)e.stopPropagation(),c||s(function(){var e;null===(e=i.node)||void 0===e||e.delete(46===t||"Delete"===a)});else if((t>=37&&t<=40||["ArrowUp","ArrowRight","ArrowDown","ArrowLeft"].includes(a))&&(e.stopPropagation(),!c)){var n=i.node.moveCursor(t,e.shiftKey);e.shiftKey?i.hideCursor():(i.showCursor(),i.updateCursor(n)),r.emit(Mh,[i.node])}}),n.addEventListener("input",function(e){if(!c){var t=e.data;t&&o(t)}}),n.addEventListener("paste",function(e){var t;e.stopPropagation(),null===(t=e.clipboardData)||void 0===t||t.getData("text")}),n.addEventListener("compositionstart",function(e){c=!0}),n.addEventListener("compositionend",function(e){c=!1;var t=e.data;t&&o(t)});var l=this.cursorEl=document.createElement("div");l.style.position="absolute",l.style.left="0px",l.style.top="0px",l.style.width="10px",l.style.height="100%",l.style.borderLeft="1px solid #000",l.style.pointerEvents="none",a.appendChild(l),l.animate([{visibility:"visible",borderColor:"#000"},{visibility:"visible",borderColor:"#FFF"},{visibility:"hidden"},{visibility:"hidden"}],{duration:800,iterations:1/0}),this.onClick=function(e){if(r.state===Oh.EDIT_TEXT){for(var t=e.target,a=t;a;){if(i.ignoreBlurUnFocus.includes(a))return;if(a===r.dom||i.ignoreBlur.includes(a))return void(["INPUT","SELECT","TEXTAREA"].includes(t.tagName.toUpperCase())||i.focus());a=a.parentElement}var n=i.node;r.cancelEditText(),n.resetCursor(),n.afterEdit(),n.inputStyle=void 0}},document.addEventListener("click",this.onClick)}return e.prototype.show=function(e,t,r){this.node=e,this.update(t,r),this.focus(),this.showCursor()},e.prototype.update=function(e,t){var r=this.node.setCursorStartByAbsCoords(e,t);this.updateCursor(r)},e.prototype.hide=function(){if(this.hideCursor(),this.blur(),this.node){if(!this.node.content.length){var e=this.listener.history.commands[0];e&&e instanceof fd&&e.nodes[0]===this.node&&e.undo(),this.listener.removeNode()}this.node=void 0}},e.prototype.focus=function(){this.inputEl.focus()},e.prototype.blur=function(){this.inputEl.blur(),this.hasBlur=!0},e.prototype.showCursor=function(){this.containerEl.style.opacity="1"},e.prototype.hideCursor=function(){this.containerEl.style.opacity="0"},e.prototype.updateCursor=function(e){if(e=e||this.node.getCursorAbsCoords()){var t=this.node.root.canvas;this.containerEl.style.left=e.x*t.clientWidth/t.width+"px",this.containerEl.style.top=e.y*t.clientWidth/t.width+"px",this.containerEl.style.height=e.h*t.clientWidth/t.width+"px"}},e.prototype.release=function(){this.containerEl.remove(),document.removeEventListener("click",this.onClick)},e}(),pd="undefined"!=typeof navigator&&/win/i.test(navigator.platform),gd=function(e){function r(t,r,i){var a=e.call(this)||this;return a.root=t,a.dom=r,a.options=i,a.state=Eh.NORMAL,a.isMouseDown=!1,a.isMouseMove=!1,a.originX=0,a.originY=0,a.startX=0,a.startY=0,a.centerX=0,a.centerY=0,a.metaKey=!1,a.shiftKey=!1,a.ctrlKey=!1,a.altKey=!1,a.eventListenerList=[{type:"mousedown",cb:a.onMouseDown.bind(a)},{type:"mousemove",cb:a.onMouseMove.bind(a)},{type:"mouseup",cb:a.onMouseUp.bind(a)},{type:"dblclick",cb:a.onDblClick.bind(a)},{type:"keydown",cb:a.onKeyDown.bind(a)},{type:"keyup",cb:a.onKeyUp.bind(a)}],a.eventListenerList.forEach(function(e){"keydown"===e.type||"keyup"===e.type?document.addEventListener(e.type,e.cb):r.addEventListener(e.type,e.cb)}),a.history=new Lh,a.selected=[],a.select=new Ih(t,r),a.computedStyle=[],a.originStyle=[],a.cssStyle=[],a.input=new md(t,r,a),a.dx=0,a.dy=0,a.isControl=!1,a.isRotate=!1,a.controlType=Uh.T,a}return t(r,e),r.prototype.updateOrigin=function(){var e=this.dom.getBoundingClientRect();this.originX=e.left,this.originY=e.top},r.prototype.prepare=function(){var e=this.selected;this.computedStyle=e.map(function(e){return e.getComputedStyle()}),this.originStyle=e.map(function(e){return e.getStyle()})},r.prototype.getNode=function(e,t){return this.metaKey||pd&&this.ctrlKey,dd(this.root,e,t)},r.prototype.onMouseDown=function(e){var t,r;if(0===e.button){var i=this.selected;this.isMouseDown=!0,this.updateOrigin(),this.startX=e.clientX-this.originX,this.startY=e.clientY-this.originY;var a=this.root.canvas,n=this.startX*a.width/a.clientWidth,s=this.startY*a.height/a.clientHeight,o=e.target;if(this.isControl=this.select.isSelectControlDom(o)){this.state===Eh.EDIT_TEXT&&this.cancelEditText();var c=this.controlType={t:Uh.T,r:Uh.R,b:Uh.B,l:Uh.L,tl:Uh.TL,tr:Uh.TR,bl:Uh.BL,br:Uh.BR}[o.className];this.prepare();var l=this.metaKey||pd&&this.ctrlKey;if(!(null===(r=null===(t=this.options)||void 0===t?void 0:t.disabled)||void 0===r?void 0:r.rotate)&&1===i.length&&l&&[Uh.TL,Uh.TR,Uh.BL,Uh.BR].indexOf(c)>-1){var u=i[0].getBoundingClientRect().points,h=function(e,t,r,i,a,n,s,o,c,l){void 0===c&&(c=!0),void 0===l&&(l=0);var u=(o-n)*(r-e)-(s-a)*(i-t);if(0!==u){var h=((s-a)*(t-n)-(o-n)*(e-a))/u,d=((r-e)*(t-n)-(i-t)*(e-a))/u,f=1-l;if(c&&(h<l||h>f||d<l||d>f))return;return{x:e+h*(r-e),y:t+h*(i-t),toSource:h,toClip:d}}}(u[0].x,u[0].y,u[2].x,u[2].y,u[1].x,u[1].y,u[3].x,u[3].y);this.centerX=h.x*a.clientWidth/a.width,this.centerY=h.y*a.clientHeight/a.height,this.isRotate=!0}else this.beforeResize()}else{var d=this.getNode(n,s),f=i.slice(0);if(d){if((h=i.indexOf(d))>-1){if(this.state===Eh.EDIT_TEXT){var m=d;if(this.shiftKey)m.setCursorEndByAbsCoords(n,s),m.inputStyle=void 0,this.input.hideCursor();else{var p=m.cursor,g=p.isMulti,v=p.startLineBox,y=p.startTextBox,b=p.startString;m.resetCursor();var k=m.setCursorStartByAbsCoords(n,s);if(this.input.updateCursor(k),this.input.showCursor(),m.cursor.isMulti===g&&m.cursor.startLineBox===v&&m.cursor.startTextBox===y&&m.cursor.startString===b)return}return void this.emit(Mh,[m])}}else{if(this.state===Eh.EDIT_TEXT)return void this.cancelEditText(f[0]);if(this.shiftKey)for(var T=i.length-1;T>=0;T--){var w=i[T];if(d.isParent(w))i.splice(T,1);else if(d.isChild(w))return}else i.splice(0);i.push(d)}}else{if(this.state===Eh.EDIT_TEXT)return void this.cancelEditText(f[0]);i.splice(0)}this.updateActive(!0)}}},r.prototype.onMouseMove=function(e){var t=this,r=this.root.canvas,i=e.clientX-this.originX-this.startX,a=e.clientY-this.originY-this.startY,n=this.dx=i*r.width/r.clientWidth,s=this.dy=a*r.height/r.clientHeight,o=this.selected;if(this.isControl){if(Math.abs(i)<=1&&Math.abs(a)<=1&&!this.isMouseMove)return;if(this.isRotate){var c=this.centerX,l=this.centerY,u=this.startX,h=this.startY,d=e.clientX-this.originX,f=e.clientY-this.originY,m=at(st(Math.sqrt(Math.pow(u-d,2)+Math.pow(h-f,2)),Math.sqrt(Math.pow(c-d,2)+Math.pow(l-f,2)),Math.sqrt(Math.pow(u-c,2)+Math.pow(h-l,2)))),p=je(u-c,h-l,d-c,f-l);if(this.shiftKey)for(var g=0;g<=180;g+=15)if(Math.abs(m-g)<=7.5){m=g;break}var v=o[0],y=(this.computedStyle[0].rotateZ+m*(p>=0?1:-1))%360;v.updateStyle({rotateZ:y}),this.select.updateSelect(o),this.emit(Bh.ROTATE,o.slice(0))}else{var b=this.shiftKey,k=this.altKey,T=this.controlType;o.forEach(function(e,r){t.isMouseMove||(e.startSizeChange(),t.computedStyle[r]=e.getComputedStyle(),t.cssStyle[r]=e.getCssStyle());var i=t.computedStyle[r],a=t.cssStyle[r];t.selectRect&&t.clientRect&&t.clientRect[r]?cd.operateMultiAr(e,i,a,n,s,T,t.clientRect[r],t.selectRect,b,k):cd.operate(e,i,a,n,s,T,b,k)}),this.select.updateSelect(o),this.emit(Bh.RESIZE,o.slice(0))}this.isMouseMove=!0}else if(this.isMouseDown){if(Math.abs(i)<=1&&Math.abs(a)<=1&&!this.isMouseMove)return;if(this.isMouseMove=!0,this.state===Eh.EDIT_TEXT){var w=(e.clientX-this.originX)*r.width/r.clientWidth,S=(e.clientY-this.originY)*r.height/r.clientHeight,x=o[0],C=x.cursor,E=C.isMulti,A=C.start,P=C.end;x.setCursorEndByAbsCoords(w,S),this.input.hideCursor();var I=x.cursor;E===I.isMulti&&A===I.start&&P===I.end||this.emit(Mh,o.slice(0))}else this.select.select.classList.add("move"),this.shiftKey&&(Math.abs(n)>=Math.abs(s)?this.dy=a=s=0:this.dx=i=n=0),o.forEach(function(e,r){var i=t.computedStyle[r];Nh.operate(e,i,n,s)}),this.select.updateSelect(o),this.emit(Bh.MOVE,o.slice(0))}},r.prototype.onMouseUp=function(){var e=this,t=this.selected,r=this.dx,i=this.dy;if(this.isControl){if(this.isRotate){var a=t[0];(r||i)&&this.history.addCommand(new ud([a],[{prev:{rotateZ:this.computedStyle[0].rotateZ},next:{rotateZ:a.computedStyle.rotateZ}}]),!0)}else if(this.isMouseMove){var n=this.shiftKey,s=this.altKey,o=this.controlType,c=[];t.forEach(function(t,a){if(t.endSizeChange(e.originStyle[a]),r||i){var l={dx:r,dy:i,controlType:o,aspectRatio:n,clientRect:e.clientRect&&e.clientRect[a],selectRect:e.selectRect,fromCenter:s},u=e.originStyle[a];u.width.u===W.AUTO&&(l.widthFromAuto=!0),u.height.u===W.AUTO&&(l.heightFromAuto=!0),c.push(l)}}),c.length&&this.history.addCommand(new cd(t.slice(0),c))}}else if(this.isMouseMove)if(this.state===Eh.EDIT_TEXT){t[0].checkCursorMulti()?this.input.hideCursor():(this.input.updateCursor(),this.input.showCursor()),this.input.focus()}else{this.select.select.classList.remove("move");var l=this.dx,u=this.dy,h=[];t.forEach(function(t,r){(l||u)&&(t.endPosChange(e.originStyle[r],l,u),h.push({dx:l,dy:u}))}),h.length&&this.history.addCommand(new Nh(t.slice(0),h),!0)}this.isControl=!1,this.isRotate=!1,this.isMouseDown=!1,this.isMouseMove=!1},r.prototype.onDblClick=function(e){if(0===e.button){var t=this.root.canvas,r=this.startX*t.width/t.clientWidth,i=this.startY*t.height/t.clientHeight,a=this.getNode(r,i);if(1!==this.selected.length||a!==this.selected[0])this.selected.splice(0),a&&this.selected.push(a),this.updateActive(!0);else if(a instanceof Th){this.input.show(a,r,i),a.beforeEdit();var n=this.state;this.state=Eh.EDIT_TEXT,this.select.select.classList.add("text"),this.emit(Dh,n,this.state)}}},r.prototype.onKeyDown=function(e){var t,r,i,a;this.metaKey=e.metaKey,this.altKey=e.altKey,this.ctrlKey=e.ctrlKey,this.shiftKey=e.shiftKey;var n=this.metaKey||pd&&this.ctrlKey;!(null===(a=null===(i=this.options)||void 0===i?void 0:i.disabled)||void 0===a?void 0:a.rotate)&&n&&1===this.selected.length&&this.select.metaKey(!0);var s=e.keyCode,o=e.code,c=e.target,l=["INPUT","TEXTAREA","SELECT"].includes(c.tagName.toUpperCase());if(8===s||46===s||"Backspace"===o||"Delete"===o){if(l)return;this.removeNode()}else if(27===s||"Escape"===o)this.state===Eh.EDIT_TEXT?this.cancelEditText():(this.selected.splice(0),this.select.hideSelect(),this.emit(Bh.SELECT,[]));else if(s>=37&&s<=40||["ArrowUp","ArrowRight","ArrowDown","ArrowLeft"].includes(o)){if(l)return;e.preventDefault();var u=0,h=0;37===s?u=this.shiftKey?-10:this.altKey?-.1:-1:38===s?h=this.shiftKey?-10:this.altKey?-.1:-1:39===s?u=this.shiftKey?10:this.altKey?.1:1:40===s&&(h=this.shiftKey?10:this.altKey?.1:1);var d=this.selected.slice(0),f=[];d.forEach(function(e){var t=e.getStyle();Nh.operate(e,e.computedStyle,u,h),e.endPosChange(t,u,h),f.push({dx:u,dy:h})}),d.length&&(this.select.updateSelect(d),this.emit(Bh.MOVE,d.slice(0)),this.history.addCommand(new Nh(d,f)))}else if(65!==s&&"KeyA"!==o||!n){if((90===s||"KeyZ"===o)&&n){if(l&&c!==this.input.inputEl)return;e.preventDefault();var m=void 0;if(m=this.shiftKey?this.history.redo():this.history.undo()){d=m.nodes.slice(0);var p=this.selected.slice(0),g=!1;if(m instanceof zh||(this.selected.splice(0),(t=this.selected).push.apply(t,d),this.updateActive(),g=!0),m instanceof Nh)this.emit(Bh.MOVE,d.slice(0));else if(m instanceof cd)this.emit(Bh.RESIZE,d.slice(0));else if(m instanceof zh)this.shiftKey?(this.selected.splice(0),this.select.hideSelect(),this.emit(Bh.REMOVE,d.slice(0)),this.emit(Bh.SELECT,[])):(this.selected.splice(0),(r=this.selected).push.apply(r,d),this.updateActive(),this.emit(Bh.ADD,d.slice(0)),this.emit(Bh.SELECT,d.slice(0)));else if(m instanceof ud)this.emit(Bh.ROTATE,d.slice(0));else if(m instanceof fd){if(this.state===Eh.EDIT_TEXT){var v=d[0],y=v.getSortedCursor(),b=y.isMulti,k=y.start;if(b)this.input.hideCursor();else{var T=v.updateCursorByIndex(k);this.input.updateCursor(T),this.input.showCursor()}this.input.focus()}this.emit(_h,d.slice(0))}if(g)if(d.length!==p.length)this.emit(Bh.SELECT,d.slice(0));else for(var w=0,S=d.length;w<S;w++)if(d[w]!==p[w]){this.emit(Bh.SELECT,d.slice(0));break}}}}else this.state===Eh.EDIT_TEXT&&c===this.input.inputEl&&(e.preventDefault(),this.input.node.selectAll(),this.input.hideCursor())},r.prototype.onKeyUp=function(e){var t,r;this.metaKey=e.metaKey,this.altKey=e.altKey,this.ctrlKey=e.ctrlKey,this.shiftKey=e.shiftKey;var i=this.metaKey||pd&&this.ctrlKey;(null===(r=null===(t=this.options)||void 0===t?void 0:t.disabled)||void 0===r?void 0:r.rotate)||i||this.isRotate||this.select.metaKey(!1)},r.prototype.removeNode=function(e){if(void 0===e&&(e=this.selected),e.length){var t=[];e.forEach(function(e,r){var i=zh.operate(e);t.push(i)}),this.select.hideSelect(),this.history.addCommand(new zh(e.slice(0),t)),this.emit(Bh.REMOVE,e.slice(0)),this.emit(Bh.SELECT,[])}},r.prototype.active=function(e){var t=this.selected,r=!1;if(e.length!==t.length)r=!0;else for(var i=0,a=e.length;i<a;i++)if(e[i]!==t[i]){r=!0;break}r&&(t.splice(0),t.push.apply(t,e),this.updateActive(!0))},r.prototype.updateActive=function(e){void 0===e&&(e=!1),this.prepare();var t=this.selected;t.length?this.select.showSelect(t):this.select.hideSelect(),e&&this.emit(Bh.SELECT,t.slice(0))},r.prototype.beforeResize=function(){this.selected.length>1&&this.shiftKey?(this.selectRect=this.select.getAspectRatio(),this.clientRect=this.selected.map(function(e){var t=e.getBoundingClientRect();return{x:t.left,y:t.top,w:t.width,h:t.height}})):(this.selectRect=void 0,this.clientRect=void 0)},r.prototype.cancelEditText=function(e){if(this.state===Eh.EDIT_TEXT){var t=e||this.selected[0];t&&(t.resetCursor(),t.afterEdit(),t.inputStyle=void 0),this.input.hide(),this.state=Eh.NORMAL,this.select.select.classList.remove("text"),this.emit(Dh,Eh.EDIT_TEXT,this.state)}},r.prototype.release=function(){var e=this;this.eventListenerList.splice(0).forEach(function(t){"keydown"===t.type||"keyup"===t.type?document.removeEventListener(t.type,t.cb):e.dom.removeEventListener(t.type,t.cb)}),this.select.release(),this.input.release()},r}(R);return{parser:Br,node:wh,util:Ah,config:F,style:Ph,interaction:{Listener:gd,interactionEvent:Bh,state:Oh,Select:Ih,Input:md}}});
273
+ */const Id=["video","audio","subtitle"],Rd=e=>{if(!e||"object"!=typeof e)throw new TypeError("metadata must be an object.");if(void 0!==e.languageCode&&!_n(e.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(void 0!==e.name&&"string"!=typeof e.name)throw new TypeError("metadata.name, when provided, must be a string.");if(void 0!==e.disposition&&(e=>{if(!e||"object"!=typeof e)throw new TypeError("disposition must be an object.");if(void 0!==e.default&&"boolean"!=typeof e.default)throw new TypeError("disposition.default must be a boolean.");if(void 0!==e.forced&&"boolean"!=typeof e.forced)throw new TypeError("disposition.forced must be a boolean.");if(void 0!==e.original&&"boolean"!=typeof e.original)throw new TypeError("disposition.original must be a boolean.");if(void 0!==e.commentary&&"boolean"!=typeof e.commentary)throw new TypeError("disposition.commentary must be a boolean.");if(void 0!==e.hearingImpaired&&"boolean"!=typeof e.hearingImpaired)throw new TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==e.visuallyImpaired&&"boolean"!=typeof e.visuallyImpaired)throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(e.disposition),void 0!==e.maximumPacketCount&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")};class Pd{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new hn,this._metadataTags={},!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!(e.format instanceof yd))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof ud))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof Ed))throw new TypeError("source must be a VideoSource.");if(Rd(t),void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(void 0!==t.frameRate&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);this._addTrack("video",e,t)}addAudioTrack(e,t={}){if(!(e instanceof Ad))throw new TypeError("source must be an AudioSource.");Rd(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof Md))throw new TypeError("source must be a SubtitleSource.");Rd(t),this._addTrack("subtitle",e,t)}setMetadataTags(e){if((e=>{if(!e||"object"!=typeof e)throw new TypeError("tags must be an object.");if(void 0!==e.title&&"string"!=typeof e.title)throw new TypeError("tags.title, when provided, must be a string.");if(void 0!==e.description&&"string"!=typeof e.description)throw new TypeError("tags.description, when provided, must be a string.");if(void 0!==e.artist&&"string"!=typeof e.artist)throw new TypeError("tags.artist, when provided, must be a string.");if(void 0!==e.album&&"string"!=typeof e.album)throw new TypeError("tags.album, when provided, must be a string.");if(void 0!==e.albumArtist&&"string"!=typeof e.albumArtist)throw new TypeError("tags.albumArtist, when provided, must be a string.");if(void 0!==e.trackNumber&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(void 0!==e.tracksTotal&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(void 0!==e.discNumber&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(void 0!==e.discsTotal&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(void 0!==e.genre&&"string"!=typeof e.genre)throw new TypeError("tags.genre, when provided, must be a string.");if(void 0!==e.date&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(void 0!==e.lyrics&&"string"!=typeof e.lyrics)throw new TypeError("tags.lyrics, when provided, must be a string.");if(void 0!==e.images){if(!Array.isArray(e.images))throw new TypeError("tags.images, when provided, must be an array.");for(const t of e.images){if(!t||"object"!=typeof t)throw new TypeError("Each image in tags.images must be an object.");if(!(t.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if("string"!=typeof t.mimeType)throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(t.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(void 0!==e.comment&&"string"!=typeof e.comment)throw new TypeError("tags.comment, when provided, must be a string.");if(void 0!==e.raw){if(!e.raw||"object"!=typeof e.raw)throw new TypeError("tags.raw, when provided, must be an object.");for(const t of Object.values(e.raw))if(!(null===t||"string"==typeof t||t instanceof Uint8Array||t instanceof qn||t instanceof Kn))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}})(e),"pending"!==this.state)throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e,t,r){if("pending"!==this.state)throw new Error("Cannot add track after output has been started or canceled.");if(t._connectedTrack)throw new Error("Source is already used for a track.");const i=this.format.getSupportedTrackCounts(),a=this._tracks.reduce((t,r)=>t+(r.type===e?1:0),0),n=i[e].max;if(a===n)throw new Error(0===n?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${n} ${e} track`+(1===n?"":"s")+".");const o=i.total.max;if(this._tracks.length===o)throw new Error(`${this.format._name} does not support more than ${o} tracks`+(1===o?"":"s")+" in total.");const s={id:this._tracks.length+1,output:this,type:e,source:t,metadata:r};if("video"===s.type){const e=this.format.getSupportedVideoCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(s.source._codec));if(!e.includes(s.source._codec))throw new Error(`Codec '${s.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(s.source._codec))}else if("audio"===s.type){const e=this.format.getSupportedAudioCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(s.source._codec));if(!e.includes(s.source._codec))throw new Error(`Codec '${s.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(s.source._codec))}else if("subtitle"===s.type){const e=this.format.getSupportedSubtitleCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(s.source._codec));if(!e.includes(s.source._codec))throw new Error(`Codec '${s.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(s.source._codec))}this._tracks.push(s),t._connectedTrack=s}async start(){const e=this.format.getSupportedTrackCounts();for(const t of Id){const r=this._tracks.reduce((e,r)=>e+(r.type===t?1:0),0),i=e[t].min;if(r<i)throw new Error(i===e[t].max?`${this.format._name} requires exactly ${i} ${t} track${1===i?"":"s"}.`:`${this.format._name} requires at least ${i} ${t} track${1===i?"":"s"}.`)}const t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track`+(1===t?"":"s")+".":`${this.format._name} requires at least ${t} track`+(1===t?"":"s")+".");if("canceled"===this.state)throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();const e=await this._mutex.acquire();await this._muxer.start();const t=this._tracks.map(e=>e.source._start());await Promise.all(t),e()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){return this._cancelPromise?(console.warn("Output has already been canceled."),this._cancelPromise):"finalizing"!==this.state&&"finalized"!==this.state?this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await this._writer.close(),e()})():void console.warn("Output has already been finalized.")}async finalize(){if("pending"===this.state)throw new Error("Cannot finalize before starting.");if("canceled"===this.state)throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}}var Od="VideoRange";function Dd(){return i(this,void 0,void 0,function(){return a(this,function(e){return[2,new Promise(function(e,t){var r=indexedDB.open("VideoEditorDB",1);r.onupgradeneeded=function(e){var t=e.target.result;t.objectStoreNames.contains(Od)||t.createObjectStore(Od,{keyPath:"id"})},r.onsuccess=function(){e(r.result)},r.onerror=function(){t("IndexedDB Error: ".concat(r.error))}})]})})}function Bd(e){return new Promise(function(t,r){e.onsuccess=function(){return t(e.result)},e.onerror=function(){return r(e.error)}})}function Fd(e){return new Promise(function(t,r){e.oncomplete=function(){return t(void 0)},e.onerror=function(){return r(e.error)}})}function Ld(e,t){return i(this,void 0,void 0,function(){var r;return a(this,function(i){switch(i.label){case 0:return t?[3,2]:[4,Dd()];case 1:t=i.sent(),i.label=2;case 2:return r=t.transaction(Od,"readonly"),[2,Bd(r.objectStore(Od).get(e))]}})})}function Nd(e,t){return i(this,void 0,void 0,function(){var r;return a(this,function(i){switch(i.label){case 0:return t?[3,2]:[4,Dd()];case 1:t=i.sent(),i.label=2;case 2:return r=t.transaction(Od,"readwrite"),[4,Bd(r.objectStore(Od).put(e))];case 3:return i.sent(),[4,Fd(r)];case 4:return i.sent(),[2]}})})}var Ud,zd,Wd,Vd=4194304;function Hd(e,t,n,o,s){return i(this,void 0,void 0,function(){var c,u,l,h,d,f,m,p,g,v,y,b;return a(this,function(x){switch(x.label){case 0:return(null==s?void 0:s.indexedDB)?[3,4]:[4,fetch(e,r(r({},s),{cache:"force-cache",headers:{"Cache-Control":"max-age=31536000",Range:"bytes=".concat(t,"-").concat(n)}}))];case 1:return 206!==(c=x.sent()).status?[3,3]:[4,c.arrayBuffer()];case 2:return[2,{status:206,arrayBuffer:x.sent()}];case 3:return[2,{status:c.status}];case 4:for(u=[],l=Vd*Math.floor(t/Vd),h=l;l<=n;)d=Math.min(o-1,l+Vd-1),u.push([l,d]),l=d+1;return[4,Dd()];case 5:return f=x.sent(),[4,Promise.all(u.map(function(t){return function(e,t,n,o,s){return i(this,void 0,void 0,function(){var i,c,u,l;return a(this,function(a){switch(a.label){case 0:return[4,Ld(i=e+":"+t+"-"+n,o)];case 1:return(c=a.sent())?[2,{status:206,arrayBuffer:c.arrayBuffer}]:[4,fetch(e,r(r({},s),{cache:"force-cache",headers:{"Cache-Control":"max-age=31536000",Range:"bytes=".concat(t,"-").concat(n)}}))];case 2:return 206!==(u=a.sent()).status?[3,5]:[4,u.arrayBuffer()];case 3:return l=a.sent(),[4,Nd({id:i,arrayBuffer:l})];case 4:return a.sent(),[2,{status:206,arrayBuffer:l}];case 5:return[2,{status:u.status}]}})})}(e,t[0],t[1],f,s)}))];case 6:for(m=x.sent(),p=new Uint8Array(u.length*Vd*8),g=0,v=m.length;g<v;g++){if(206!==(y=m[g]).status)return[2,{status:y.status}];b=new Uint8Array(y.arrayBuffer),p.set(b,g*Vd)}return[2,{status:206,arrayBuffer:p.buffer.slice(t-h,n-h+1)}]}})})}function Xd(e){return i(this,void 0,void 0,function(){return a(this,function(t){return[2,new Promise(function(t){return setTimeout(t,e)})]})})}!function(e){e[e.META=0]="META",e[e.DECODE=1]="DECODE",e[e.RELEASE=2]="RELEASE"}(Ud||(Ud={})),function(e){e.META="meta",e.ERROR="error",e.DECODED="decoded"}(zd||(zd={})),function(e){e[e.NONE=0]="NONE",e[e.DECODING=1]="DECODING",e[e.DECODED=2]="DECODED",e[e.DECODED_FRAME=3]="DECODED_FRAME",e[e.ERROR=4]="ERROR"}(Wd||(Wd={}));var jd,Gd,Yd={},qd=function(e){return i(void 0,void 0,void 0,function(){var t,r,n,s,c,u,l,h,d,f,m,p,g,v,y,b,x,T,w,k,S,E,C,A,_,M,I,R,P,O,D,B,F,L,N,U,z,W,V,H,X,j,G,Y,q,K,$,Q,Z,J,ee,te,re,ie,ae,ne,oe,se,ce,ue,le,he,de,fe,me,pe,ge,ve,ye,be,xe,Te,we,ke,Se,Ee,Ce,Ae,_e,Me,Ie;return a(this,function(Re){switch(Re.label){case 0:return t=e.data,r=t.url,n=t.id,s=t.type,c=t.isWorker,u=function(e){var t={url:r,type:zd.ERROR,data:e};return c&&self.postMessage(t),{data:t}},Yd[r]||(Yd[r]={gopList:[]}),l=Yd[r],s!==Ud.META?[3,38]:[4,fetch(r,{method:"HEAD"})];case 1:if(h=Re.sent(),!(d=h.headers.get("content-length"))||200!==h.status&&304!==h.status)return[2,u("Unknown content-length")];f=parseInt(d),m={duration:0,fileSize:f},p=void 0,p=e.data.preloadAll?new Zu(r):new Ju({read:function(t,n){return i(void 0,void 0,void 0,function(){var i;return a(this,function(a){switch(a.label){case 0:return[4,Hd(r,t,n-1,f,{indexedDB:e.data.indexedDB})];case 1:if(!(i=a.sent().arrayBuffer))throw new Error("Missing buffer in range: "+t+"-"+(n-1));return[2,new Uint8Array(i)]}})})},getSize:function(){return i(void 0,void 0,void 0,function(){return a(this,function(e){return[2,f]})})},prefetchProfile:"network"}),g=new rl({formats:qu,source:p}),Re.label=2;case 2:return Re.trys.push([2,4,,5]),[4,g.computeDuration()];case 3:return v=Re.sent(),m.duration=1e3*v,[3,5];case 4:return y=Re.sent(),[2,u(y.message)];case 5:return[4,g.getPrimaryVideoTrack()];case 6:return(b=Re.sent())?(l.videoTrack=b,[4,b.computeDuration()]):[3,21];case 7:oe=Re.sent(),K=new Ps(b),Re.label=8;case 8:Re.trys.push([8,13,14,19]),x=!0,T=o(K.packets(void 0,void 0,{metadataOnly:!0})),Re.label=9;case 9:return[4,T.next()];case 10:if(w=Re.sent(),pe=w.done)return[3,12];if(ye=w.value,x=!1,"key"===(O=ye).type){if(k=l.gopList.length){if(N=l.gopList[k-1],e.data.gopMinDuration&&1e3*O.timestamp-N.timestamp<e.data.gopMinDuration)return[3,11];N.duration=N.audioDuration=1e3*O.timestamp-N.timestamp}l.gopList.push({state:Wd.NONE,index:l.gopList.length,sequenceNumber:O.sequenceNumber,timestamp:1e3*O.timestamp,duration:1e3*O.duration,audioTimestamp:1e3*O.timestamp,audioDuration:1e3*O.duration,users:[]})}Re.label=11;case 11:return x=!0,[3,9];case 12:return[3,19];case 13:return S=Re.sent(),ge={error:S},[3,19];case 14:return Re.trys.push([14,,17,18]),x||pe||!(ve=T.return)?[3,16]:[4,ve.call(T)];case 15:Re.sent(),Re.label=16;case 16:return[3,18];case 17:if(ge)throw ge.error;return[7];case 18:return[7];case 19:return(L=l.gopList.length)&&((N=l.gopList[L-1]).duration=N.audioDuration=1e3*oe-N.timestamp),[4,b.getFirstTimestamp()];case 20:ne=Re.sent(),m.video={id:b.id,languageCode:b.languageCode,codec:b.codec,name:b.name,codedWidth:b.codedWidth,codedHeight:b.codedHeight,displayWidth:b.displayWidth,displayHeight:b.displayHeight,width:b.displayWidth,height:b.displayHeight,timeResolution:b.timeResolution,rotation:b.rotation,timestamp:1e3*ne,duration:1e3*oe},Re.label=21;case 21:return[4,g.getPrimaryAudioTrack()];case 22:return(E=Re.sent())?(l.audioTrack=E,[4,E.computeDuration()]):[3,37];case 23:return oe=Re.sent(),[4,E.getFirstTimestamp()];case 24:if(ne=Re.sent(),m.audio={id:E.id,languageCode:E.languageCode,codec:E.codec,name:E.name,numberOfChannels:E.numberOfChannels,sampleRate:E.sampleRate,timestamp:1e3*ne,duration:1e3*oe},b)return[3,37];C=e.data.gopMinDuration||5e3,K=new Ps(E),A=-1,_=!0,M=0,Re.label=25;case 25:Re.trys.push([25,30,31,36]),I=!0,R=o(K.packets(void 0,void 0,{metadataOnly:!0})),Re.label=26;case 26:return[4,R.next()];case 27:if(P=Re.sent(),be=P.done)return[3,29];we=P.value,I=!1,O=we,-1===A&&(A=O.timestamp),D=O.timestamp-A,(_||1e3*D>=C)&&(_=!1,(B=l.gopList.length)&&((N=l.gopList[B-1]).duration=N.audioDuration=1e3*O.timestamp-N.timestamp),l.gopList.push({state:Wd.NONE,index:l.gopList.length,sequenceNumber:M,timestamp:1e3*O.timestamp,duration:1e3*O.duration,audioTimestamp:1e3*O.timestamp,audioDuration:1e3*O.duration,users:[]}),A=O.timestamp),M++,Re.label=28;case 28:return I=!0,[3,26];case 29:return[3,36];case 30:return F=Re.sent(),xe={error:F},[3,36];case 31:return Re.trys.push([31,,34,35]),I||be||!(Te=R.return)?[3,33]:[4,Te.call(R)];case 32:Re.sent(),Re.label=33;case 33:return[3,35];case 34:if(xe)throw xe.error;return[7];case 35:return[7];case 36:(L=l.gopList.length)&&((N=l.gopList[L-1]).duration=N.audioDuration=1e3*oe-N.timestamp),Re.label=37;case 37:return U=l.gopList.map(function(e){return{index:e.index,sequenceNumber:e.sequenceNumber,timestamp:e.timestamp,duration:e.duration,audioTimestamp:e.audioTimestamp,audioDuration:e.audioDuration}}),de={url:r,type:zd.META,data:{meta:m,simpleGOPList:U}},c&&self.postMessage(de),[2,{data:de}];case 38:return s!==Ud.DECODE?[3,64]:(fe=l.gopList[e.data.index])&&fe.state!==Wd.ERROR?fe.state===Wd.DECODED?[2]:(fe.users.includes(n)||fe.users.push(n),[4,Xd(100)]):[2];case 39:if(Re.sent(),!fe.users.includes(n))return[2];if(fe.state===Wd.DECODING||fe.state===Wd.DECODED)return[2];if(fe.state=Wd.DECODING,z=[],!l.videoTrack)return[3,51];K=new Ns(l.videoTrack),Re.label=40;case 40:Re.trys.push([40,45,46,51]),W=!0,V=o(K.samples(.001*fe.timestamp,.001*(fe.timestamp+fe.duration))),Re.label=41;case 41:return[4,V.next()];case 42:if(H=Re.sent(),ke=H.done)return[3,44];Ce=H.value,W=!1,re=Ce,z.push(re.toVideoFrame()),re.close(),Re.label=43;case 43:return W=!0,[3,41];case 44:return[3,51];case 45:return X=Re.sent(),Se={error:X},[3,51];case 46:return Re.trys.push([46,,49,50]),W||ke||!(Ee=V.return)?[3,48]:[4,Ee.call(V)];case 47:Re.sent(),Re.label=48;case 48:return[3,50];case 49:if(Se)throw Se.error;return[7];case 50:return[7];case 51:if(j=[],G=0,Y=-1,q=0,!l.audioTrack||e.data.mute||fe.didAudioChunk)return[3,63];fe.didAudioChunk=!0,K=new Ws(l.audioTrack),$=.001*fe.timestamp,Q=.001*(fe.timestamp+fe.duration),Z=K.samples($,Q),Re.label=52;case 52:Re.trys.push([52,57,58,63]),J=!0,ee=o(Z),Re.label=53;case 53:return[4,ee.next()];case 54:if(te=Re.sent(),Ae=te.done)return[3,56];if(Ie=te.value,J=!1,G=(re=Ie).sampleRate,ie=re.numberOfChannels,ae=re.numberOfFrames,ne=re.timestamp,oe=re.duration,ne>=Q&&fe.index<l.gopList.length-1||ne<$)return[3,55];for(-1===Y&&(Y=1e3*ne),q=1e3*ne-Y+1e3*oe,se=[],ce=0;ce<ie;ce++)ue=new Float32Array(ae),re.copyTo(ue,{planeIndex:ce,format:"f32-planar"}),se.push(ue);j.push({format:"f32-planar",channels:se,sampleRate:G,numberOfFrames:ae,numberOfChannels:ie,timestamp:1e3*ne,duration:1e3*oe}),re.close(),Re.label=55;case 55:return J=!0,[3,53];case 56:return[3,63];case 57:return le=Re.sent(),_e={error:le},[3,63];case 58:return Re.trys.push([58,,61,62]),J||Ae||!(Me=ee.return)?[3,60]:[4,Me.call(ee)];case 59:Re.sent(),Re.label=60;case 60:return[3,62];case 61:if(_e)throw _e.error;return[7];case 62:return[7];case 63:return fe.state!==Wd.DECODING?(fe.didAudioChunk=!1,z.forEach(function(e){e.close()}),[2]):(fe.state=Wd.DECODED,he=[],z.forEach(function(e){return he.push(e)}),j.forEach(function(e){e.channels.forEach(function(e){he.push(e.buffer)})}),de={url:r,type:zd.DECODED,data:{index:e.data.index,videoFrames:z,audioChunks:j,sampleRate:G,audioTimeStamp:Y,audioDuration:q}},c&&self.postMessage(de,he),[2,{data:de}]);case 64:if(s===Ud.RELEASE){if(!(fe=l.gopList[e.data.index]))return[2];(me=fe.users.indexOf(e.data.id))>-1&&fe.users.splice(me,1),fe.users.length||(fe.state=Wd.NONE,fe.didAudioChunk=!1)}Re.label=65;case 65:return[2]}})})};self.onmessage=qd,function(e){e.META="meta",e.LOADED="loaded",e.ERROR="error",e.PROGRESS="progress",e.CANPLAY="canplay",e.AUDIO_BUFFER="audio_buffer"}(jd||(jd={})),function(e){e[e.NONE=0]="NONE",e[e.LOADING_META=1]="LOADING_META",e[e.META=2]="META",e[e.LOADED=3]="LOADED",e[e.ERROR=4]="ERROR"}(Gd||(Gd={}));var Kd,$d={},Qd=0,Zd=0,Jd=function(e){function i(t){var r=e.call(this)||this;return r.url=t,r.id=Qd++,r.currentTime=-1/0,r.gopIndex=-1,r.error=!1,r}return t(i,e),i.prototype.initWorker=function(){if(!Kd){if(L.decoderWorker)Kd=new Worker(L.decoderWorker);else if(L.decoderWorkerStr){var e=new Blob([L.decoderWorkerStr.trim()],{type:"application/javascript"}),t=URL.createObjectURL(e);Kd=new Worker(t)}var i=function(e){var t,i,a;if(null==e?void 0:e.data){var n=e.data,o=n.url,s=n.type,c=n.data,u=$d[o];if(u)if(s===zd.META)u.state=Gd.META,u.meta=c.meta,u.gopList=c.simpleGOPList.map(function(e){return r(r({},e),{state:Wd.NONE,videoFrames:[],users:[]})}),u.metaList.splice(0).forEach(function(e){e.start(e.currentTime),e.emit(jd.META,c.meta)});else if(s===zd.DECODED){var l=u.gopList[c.index];if(l){if(l.state=Wd.DECODED,l.videoFrames.forEach(function(e){return e.close()}),null===(t=l.audioBufferSourceNode)||void 0===t||t.stop(),null===(i=l.audioBufferSourceNode)||void 0===i||i.disconnect(),l.audioBuffer=void 0,l.videoFrames=c.videoFrames,null===(a=c.audioChunks)||void 0===a?void 0:a.length){var h=c.audioChunks.reduce(function(e,t){return e+t.numberOfFrames},0),d=new OfflineAudioContext(c.audioChunks[0].numberOfChannels,h,c.sampleRate).createBuffer(c.audioChunks[0].channels.length,h,c.sampleRate),f=0;c.audioChunks.forEach(function(e){for(var t=0;t<e.channels.length;t++){d.getChannelData(t).set(e.channels[t],f)}f+=e.numberOfFrames}),l.audioBuffer=d}l.users.forEach(function(e){e.gopIndex===l.index&&e.emit(jd.CANPLAY,l),l.audioBuffer&&e.gopIndex<l.index&&e.emit(jd.AUDIO_BUFFER,l)})}}else s===zd.ERROR&&u.metaList.forEach(function(e){e.error=!0,e.emit(jd.ERROR,c)})}};Kd?Kd.onmessage=i:this.onMessage=i}},i.prototype.start=function(e){var t=this;this.initWorker(),this.currentTime,this.currentTime=e;var r=this.url,i=this.id,a=$d[r];if(a)a.state===Gd.LOADING_META?a.metaList.includes(this)||(a.metaList.push(this),a.loadList.push(this),a.count++):a.state===Gd.META?(a.loadList.includes(this)||(a.loadList.push(this),a.count++,this.emit(jd.META,a.meta)),this.process(e)):a.state===Gd.ERROR&&this.emit(jd.ERROR,a.error);else{$d[r]={state:Gd.LOADING_META,metaList:[this],loadList:[this],meta:{duration:0,fileSize:0},gopList:[],singleHash:{},count:1};var n={url:r,id:i,type:Ud.META,messageId:Zd++,isWorker:!!L.decoderWorker||!!L.decoderWorkerStr,indexedDB:L.indexedDB,preloadAll:L.preloadAll,gopMinDuration:L.gopMinDuration};Kd?Kd.postMessage(n):qd({data:n}).then(function(e){t.onMessage&&t.onMessage(e)})}},i.prototype.process=function(e){if(e<-L.decodeNextDuration)this.releaseGOPList();else{var t=$d[this.url];if(t&&t.state!==Gd.NONE&&t.state!==Gd.LOADING_META){var r=t.meta.duration,i=t.gopList;if(i.length)if(e>=r+L.decodeNextDuration)this.releaseGOPList();else{var a=this.getForwardsNearestGOPIndex(e);this.gopIndex=a;var n=i[a];if(n){this.decodeGOP(n);for(var o=a-1;o>=0;o--){var s=i[o];s&&s.timestamp+s.duration<e-L.releasePrevDuration&&this.releaseGOP(s)}o=a+1;for(var c=i.length;o<c;o++){var u=i[o];u&&u.timestamp<e+L.decodeNextDuration?this.decodeGOP(u):u&&u.timestamp>=e+L.decodeNextDuration&&this.releaseGOP(u)}}}}}},i.prototype.getForwardsNearestGOPIndex=function(e){var t=$d[this.url],r=t.meta.duration,i=t.gopList;if(e<-L.decodeNextDuration||!i.length||e>r+.001)return-1;if(1===i.length||e<=0)return 0;if(e>r)return i.length-1;for(var a=0,n=i.length-1;a<n;){if(a===n-1)return i[n].timestamp<=e?n:a;var o=a+(n-a>>1),s=i[o].timestamp;if(s===e)return o;s>e?n=Math.max(o-1,a+1):a=Math.min(o,n-1)}return-1},i.prototype.getFrameByTime=function(e){var t=$d[this.url],r=t.meta.duration,i=t.gopList;if(!(e<0||!i.length||e>r+.001)){var a;if(1===i.length)a=i[0];else(o=this.getForwardsNearestGOPIndex(e))>-1&&(a=i[o]);if(a&&a.state===Wd.DECODED){var n=a.videoFrames;if(!n.length)return;if(1===n.length)return n[0];for(var o=0,s=n.length-1;o<s;){if(o===s-1){var c=n[s];return.001*c.timestamp<=e?c:n[o]}var u=o+(s-o>>1),l=n[u],h=.001*l.timestamp;if(h===e||h<e&&h+.001*(l.duration||0)>e)return n[u];h>e?s=Math.max(u-1,o+1):o=Math.min(u,s-1)}}}},i.prototype.decodeGOP=function(e){var t=this;if(e.state!==Wd.ERROR){var r=!1;if(e.users.includes(this)||(r=!0,e.users.push(this)),e.state!==Wd.DECODED){if(e.state!==Wd.DECODING){e.state=Wd.DECODING,e.videoFrames.splice(0).forEach(function(e){return e.close()}),e.audioBufferSourceNode&&(e.audioBufferSourceNode.stop(),e.audioBufferSourceNode.disconnect(),e.audioBufferSourceNode=void 0),e.audioBuffer=void 0;var i={url:this.url,type:Ud.DECODE,id:this.id,messageId:Zd++,isWorker:!!L.decoderWorker||!!L.decoderWorkerStr,index:e.index,mute:L.mute};Kd?Kd.postMessage(i):qd({data:i}).then(function(e){t.onMessage&&t.onMessage(e)})}}else r&&this.emit(jd.CANPLAY,e)}},i.prototype.releaseGOP=function(e){var t,r,i=this,a=e.users.indexOf(this);if(a>-1){e.users.splice(a,1),e.users.length||(e.state!==Wd.DECODING&&e.state!==Wd.DECODED||(e.state=Wd.NONE),e.videoFrames.splice(0).forEach(function(e){return e.close()}),null===(t=e.audioBufferSourceNode)||void 0===t||t.stop(),null===(r=e.audioBufferSourceNode)||void 0===r||r.disconnect(),e.audioBuffer=void 0);var n={url:this.url,type:Ud.RELEASE,id:this.id,index:e.index,messageId:Zd++,isWorker:!!L.decoderWorker||!!L.decoderWorkerStr};Kd?Kd.postMessage(n):qd({data:n}).then(function(e){i.onMessage&&i.onMessage(e)})}},i.prototype.releaseGOPList=function(){var e=this;$d[this.url].gopList.forEach(function(t){e.releaseGOP(t)})},i.prototype.release=function(){this.releaseGOPList();var e=$d[this.url];if(!e)throw new Error("Unknown release url: "+this.url);var t=e.metaList.indexOf(this);t>-1&&e.metaList.splice(t,1),(t=e.loadList.indexOf(this))>-1&&e.loadList.splice(t,1),e.count--,e.count||delete $d[this.url]},Object.defineProperty(i.prototype,"gopList",{get:function(){var e;return null===(e=$d[this.url])||void 0===e?void 0:e.gopList},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"currentGOP",{get:function(){var e;return null===(e=$d[this.url])||void 0===e?void 0:e.gopList[this.gopIndex]},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"cache",{get:function(){return $d[this.url]},enumerable:!1,configurable:!0}),i}(M),ef=function(e){function r(t){var r,i=e.call(this,t)||this;t.onMeta&&(i.onMeta=t.onMeta),t.onCanplay&&(i.onCanplay=t.onCanplay),t.onError&&(i.onError=t.onError),t.onWaiting&&(i.onWaiting=t.onWaiting),i._currentTime=t.currentTime||0,i._volumn=Math.max(0,Math.min(1,null!==(r=t.volumn)&&void 0!==r?r:1)),i.isPure=!0;var a=i._src=t.src||"";if(a){i._currentTime>=0&&(i.contentLoadingNum=1);var n=i._decoder=new Jd(a);n.on(jd.META,function(e){if(i._metaData=e,i._currentTime>=0&&i._currentTime<e.duration?i.contentLoadingNum=1:i.contentLoadingNum=0,i.isMounted){var t=i.style,r=t.left,a=t.top,n=t.right,o=t.bottom,s=t.width,c=t.height;(r.u!==V.AUTO&&n.u!==V.AUTO||s.u!==V.AUTO)&&(a.u!==V.AUTO&&o.u!==V.AUTO||c.u!==V.AUTO)||i.refresh(ci.REFLOW)}i.onMeta&&i.onMeta(e),i.emit(Ia,e)}),n.on(jd.ERROR,function(e){oe.error(e),i.contentLoadingNum=0,i.onError&&i.onError(e),i.emit(Ra,e),i.refresh()}),n.on(jd.CANPLAY,function(e){var t=n.getFrameByTime(i._currentTime);i.videoFrame=t,i.contentLoadingNum=0,i.onCanplay&&i.onCanplay(),i.emit(Ma),i.refresh()}),n.on([jd.CANPLAY,jd.AUDIO_BUFFER],function(e){var t=i.root;if(t&&e.audioBuffer){var r=t.audioContext,a=i.timeAnimation;if("running"===(null==a?void 0:a.playState)&&r){var n=a.currentTime-a.delay;if(n>=e.timestamp+e.duration||a.duration<=e.timestamp)return;var o=r.createBufferSource();o.buffer=e.audioBuffer,i.gainNode||(i.gainNode=r.createGain(),i.gainNode.gain.value=i.volumn,i.gainNode.connect(r.destination)),o.connect(i.gainNode),n>=e.audioTimestamp?o.start(0,.001*(n-e.audioTimestamp),.001*(a.duration-n)):o.start(r.currentTime+.001*(e.audioTimestamp-n),0,.001*(a.duration-e.audioTimestamp))}}}),n.start(i._currentTime)}return i}return t(r,e),r.prototype.lay=function(t){e.prototype.lay.call(this,t);var r=this,i=r.style,a=r.computedStyle,n=r._metaData,o=i.left,s=i.top,c=i.right,u=i.bottom,l=i.width,h=i.height;if(null==n?void 0:n.video){var d=(o.u===V.AUTO||c.u===V.AUTO)&&l.u===V.AUTO,f=(s.u===V.AUTO||u.u===V.AUTO)&&h.u===V.AUTO;d&&(a.width=f?n.video.width:n.video.height*a.height/n.video.height,o.u===V.AUTO&&c.u===V.AUTO?(a.left=0,a.right=t.w-a.width):o.u===V.AUTO?a.left=t.w-a.right-a.width:c.u===V.AUTO&&(a.right=t.w-a.left-a.width)),f&&(a.height=d?n.video.height:n.video.height*a.width/n.video.width,s.u===V.AUTO&&u.u===V.AUTO?(a.top=0,a.bottom=t.h-a.height):s.u===V.AUTO?a.top=t.h-a.bottom-a.height:u.u===V.AUTO&&(a.bottom=t.h-a.top-a.height))}},r.prototype.calRepaintStyle=function(t){e.prototype.calRepaintStyle.call(this,t);var r=this.computedStyle,i=this.videoFrame;if(this.isPure=r.backgroundColor[3]<=0,this.isPure&&i){var a=r.objectFit,n=r.borderTopLeftRadius,o=r.borderTopRightRadius,s=r.borderBottomLeftRadius,c=r.borderBottomRightRadius;if(a!==ae.COVER&&a!==ae.FILL||!(n||o||s||c)){if(a===ae.CONTAIN&&(n||o||s||c)){var u=i.displayWidth/i.displayHeight,l=r.width/r.height;if(l>u){var h=r.height*u,d=.5*(r.width-h);(n>d||o>d||s>d||c>d)&&(this.isPure=!1)}else if(l<u){var f=r.width/u,m=.5*(r.height-f);(n>m||o>m||s>m||c>m)&&(this.isPure=!1)}else this.isPure=!1}}else this.isPure=!1}},r.prototype.calContent=function(){return this.hasContent=!1,(this._videoFrame||this.computedStyle.backgroundColor[3]>0)&&(this.hasContent=!0),this.hasContent},r.prototype.renderCanvas=function(){var t,r,i=this,a=i.isPure,n=i.videoFrame,o=i.computedStyle;if(a){if(null===(t=this.canvasCache)||void 0===t||t.release(),n&&(n.displayWidth>L.maxTextureSize||n.displayHeight>L.maxTextureSize))if((b=this.canvasCache=xi.getVideoFrameInstance(n.displayWidth,n.displayHeight,n)).available=!0,1===b.getCount()){var s=o.width,c=o.height,u=o.objectFit,l=0,h=0,d=n.displayWidth/n.displayHeight,f=s/c;if(u===ae.CONTAIN){if(f>d)l=.5*(s-(T=c*d)),s=T;else if(f<d){h=.5*(c-(w=s/d)),c=w}}else if(u===ae.COVER){if(f>d)h=.5*(c-(w=s/d)),c=w;else if(f<d){l=.5*(s-(T=c*d)),s=T}}for(var m=0,p=(A=b.list).length;m<p;m++){var g=A[m],v=g.x,y=g.y;g.os.ctx.drawImage(n,-v+l,-y+h,s,c)}}}else{e.prototype.renderCanvas.call(this);var b,x=this._bboxInt||this.bboxInt,T=(v=x[0],y=x[1],x[2]-v),w=x[3]-y;l=0,h=0,s=o.width,c=o.height,u=o.objectFit;if(n){d=n.displayWidth/n.displayHeight,f=s/c;if(u===ae.CONTAIN){if(f>d){var k=c*d;l+=.5*(s-k),s=k}else if(f<d){var S=s/d;h+=.5*(c-S),c=S}}else if(u===ae.COVER)if(f>d){var E=s/d;h=.5*(c-E),c=E}else if(f<d){var C=c*d;l=.5*(s-C),s=C}}(b=this.canvasCache=(null===(r=this.canvasCache)||void 0===r?void 0:r.available)?this.canvasCache:new xi(T,w,-v,-y)).available=!0;var A;for(m=0,p=(A=b.list).length;m<p;m++){var _=A[m],M=_.x,I=_.y,R=_.os.ctx,P=-M,O=-I;n&&R.drawImage(n,P+l,O+h,s,c)}}},r.prototype.genTexture=function(t){var r=this,i=r.isPure,a=r.videoFrame,n=r.canvasCache;if(i){if(a)if(a.displayWidth>L.maxTextureSize||a.displayHeight>L.maxTextureSize)if((null==n?void 0:n.available)&&Zi.hasCanvasCacheInstance(n)){var o=Zi.getCanvasCacheInstance(t,n,this._rect||this.rect);this.textureTarget=this.textureCache=o}else{this.renderCanvas();o=Zi.getCanvasCacheInstance(t,this.canvasCache,this._rect||this.rect);this.textureTarget=this.textureCache=o,this.canvasCache.release()}else{var s=this.computedStyle,c=s.width,u=s.height,l=s.objectFit,h=this._rect||this.rect,d=(o=void 0,a.displayWidth/a.displayHeight),f=c/u;if(l===ae.CONTAIN){if(f>d){var m=.5*(c-(v=u*d));(h=h.slice(0))[0]+=m,h[2]-=m}else if(f<d){m=.5*(u-(p=c/d));(h=h.slice(0))[1]+=m,h[3]-=m}}else if(l===ae.COVER)if(f>d){var p=c/d;o={x1:0,y3:g=(m=.5*Math.abs(u-p))/p,x3:1,y1:1-g}}else if(f<d){var g,v=u*d;o={x1:g=(m=.5*Math.abs(c-v))/v,y3:0,x3:1-g,y1:1}}var y=Zi.getVideoFrameInstance(t,a,h,o);this.textureTarget=this.textureCache=y}}else e.prototype.genTexture.call(this,t)},r.prototype.calContentLoading=function(){var t=e.prototype.calContentLoading.call(this);if(t){if(this._currentTime>=0){if(!this._metaData)return t;if(this._currentTime<this._metaData.duration)return t}return 0}return t},r.prototype.release=function(){e.prototype.release.call(this);var t=this._decoder,r=this.gainNode;t&&t.release(),r&&(r.disconnect(),this.gainNode=void 0)},r.prototype.timeAnimate=function(e,t){var r;null===(r=this.timeAnimation)||void 0===r||r.remove();var i=this.timeAnimation=new Ha(this,e,t);return this.initAnimate(i,t)},r.prototype.cloneProps=function(){var t=e.prototype.cloneProps.call(this);return t.src=this._src,t.currentTime=this._currentTime,t.volumn=this._volumn,t},r.prototype.clone=function(){return new r(this.cloneProps())},Object.defineProperty(r.prototype,"src",{get:function(){return this._src},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"currentTime",{get:function(){return this._currentTime},set:function(e){var t;if(this._currentTime!==e){this._currentTime=e;var r=this._decoder;if(r){var i=e;r.start(i);var a=this._videoFrame,n=r.getFrameByTime(i);this.videoFrame=n,this.contentLoadingNum=0,!n&&(null===(t=r.currentGOP)||void 0===t?void 0:t.state)===Wd.DECODING&&e>=0&&!r.error&&(this._metaData&&this._metaData.duration,this.contentLoadingNum=1),a&&!n&&this._metaData&&e>=0&&e<this._metaData.duration&&!r.error&&(this.onWaiting&&this.onWaiting(),this.emit(_a))}}},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"duration",{get:function(){var e;return(null===(e=this._metaData)||void 0===e?void 0:e.duration)||0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"metaData",{get:function(){return this._metaData},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"volumn",{get:function(){return this._volumn},set:function(e){var t=Math.max(0,Math.min(1,e));this._volumn!==t&&(this._volumn=t,this.gainNode&&(this.gainNode.gain.value=t))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"decoder",{get:function(){return this._decoder},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"videoFrame",{get:function(){return this._videoFrame},set:function(e){this._videoFrame!==e&&(this._videoFrame=e,this.refresh())},enumerable:!1,configurable:!0}),r}(ka);function tf(e,t,r,i,a,n,o){for(var s=L.maxTextureSize,c=s-2*o,u=[],l=t.bbox,h=a,d=n,f=0,m=Math.ceil(d/c);f<m;f++)for(var p=1,g=Math.ceil(h/s);p<g;p++){var v=Math.max(l[0],r+p*s-2*o),y=Math.max(l[1],i+f*c-o),b=Math.min(l[2],v+4*o),x=Math.min(l[3],y+c+2*o),T=new Float32Array([v,y,b,x]);v>l[2]-2*o&&(v=T[0]=Math.max(l[0],l[2]-2*o),b=T[2]=l[2]),y>l[3]-2*o&&(y=T[1]=Math.max(l[1],l[3]-2*o),x=T[3]=l[3]);var w=T[2]-T[0],k=T[3]-T[1];u.push({bbox:T,w:w,h:k,t:ki(e,0,void 0,w,k),x1:Math.max(l[0],v+o),y1:Math.max(l[1],f?y+o:y),x2:Math.min(l[2],b-o),y2:Math.min(l[3],f===m-1?x:y+c+o)})}for(f=1,m=Math.ceil(d/s);f<m;f++)for(p=0,g=Math.ceil(h/c);p<g;p++){v=Math.max(l[0],r+p*c-o),y=Math.max(l[1],i+f*s-2*o),b=Math.min(l[2],v+c+2*o),x=Math.min(l[3],y+4*o),T=new Float32Array([v,y,b,x]);v>l[2]-2*o&&(v=T[0]=Math.max(l[0],l[2]-2*o),b=T[2]=l[2]),y>l[3]-2*o&&(y=T[1]=Math.max(l[1],l[3]-2*o),x=T[3]=l[3]);var S=T[2]-T[0],E=T[3]-T[1];u.push({bbox:T,w:S,h:E,t:ki(e,0,void 0,S,E),x1:Math.max(l[0],p?v+o:v),y1:Math.max(l[1],y+o),x2:Math.min(l[2],p===g-1?b:v+c+o),y2:Math.min(l[3],x-o)})}return u}function rf(e,t,r,i,a,n){Va.useProgram(e,t),e.blendFunc(e.ONE,e.ZERO);for(var o=r.list,s=0,c=o.length;s<c;s++){var u=o[s],l=u.bbox,h=u.w,d=u.h,f=u.t;e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,f,0),e.viewport(0,0,h,d);for(var m=.5*h,p=.5*d,g=0,v=i.length;g<v;g++){var y=i[g],b=y.bbox,x=y.w,T=y.h,w=y.t,k=b.slice(0);k[0]!==a[0]&&(k[0]+=n),k[1]!==a[1]&&(k[1]+=n),k[2]!==a[2]&&(k[2]-=n),k[3]!==a[3]&&(k[3]-=n);var S=k[2]-k[0],E=k[3]-k[1];za(l,void 0,k[0],k[1],S,E)&&Ei(e,m,p,t,{opacity:1,bbox:k,t:w,tc:{x1:(k[0]===a[0]?0:n)/x,y1:(k[1]===a[1]?0:n)/T,x3:(k[2]===a[2]?x:x-n)/x,y3:(k[3]===a[3]?T:T-n)/T},dx:-l[0],dy:-l[1]})}}e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA),i.forEach(function(t){return e.deleteTexture(t.t)})}function af(e,t,r,i,a,n,o,s){for(var c,u=L.maxTextureSize,l=r.list,h=i.list,d=0,f=Math.ceil(s/u);d<f;d++)for(var m=0,p=Math.ceil(o/u);m<p;m++){var g=m===p-1?o-m*u:u,v=d===f-1?s-d*u:u,y=ki(e,0,void 0,g,v),b=a+m*u,x=n+d*u,T=g,w=v,k={bbox:new Float32Array([b,x,b+T,x+w]),w:g,h:v,t:y};h.push(k),c?(e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,y,0),e.viewport(0,0,g,v)):c=La(e,y,g,v);for(var S=.5*g,E=.5*v,C=0,A=l.length;C<A;C++){var _=l[C],M=_.bbox,I=_.t;I&&za(M,void 0,b,x,T,w)&&Ei(e,S,E,t,{opacity:1,bbox:M,t:I,dx:-b,dy:-x})}}return c}function nf(e,t,r){var i,a;if((e instanceof ef||e instanceof Oa)&&e.isPure)if(e instanceof ef){var n=e.metaData;if((null===(i=null==n?void 0:n.video)||void 0===i?void 0:i.displayWidth)!==t||n.video.displayHeight!==r)return!0}else if((null===(a=e.loader)||void 0===a?void 0:a.width)!==t||e.loader.height!==r)return!0;return!1}function of(e,t,r,i,a,n,o){var s=t.programs,c=s.box,u=s.dualDown,l=s.dualUp,h=n,d=o,f=void 0;if(i){Va.useProgram(e,u),f=a;for(var m=1;m<=i;m++){var p=Math.ceil(n*Math.pow(.5,m)),g=Math.ceil(o*Math.pow(.5,m));e.viewport(0,0,p,g),f=Ui(e,u,y=f,h,d,p,g),y!==a&&e.deleteTexture(y),h=p,d=g}}Va.useProgram(e,c),e.viewport(0,0,h,d);var v=function(e,t,r,i,a,n){var o=Li(e,t),s=o.pointBuffer,c=o.a_position,u=o.texBuffer,l=o.a_texCoords,h=t.uniform.u_texture,d=t.uniform.u_pw,f=t.uniform.u_ph;e.uniform1f(d,1/i),e.uniform1f(f,1/a);for(var m=t.uniform.u_direction,p=t.uniform.u_r,g=r,v=ki(e,0,void 0,i,a),y=ki(e,0,void 0,i,a),b=0,x=n.length;b<x;b++){var T=n[b]-1>>1;e.uniform1i(p,T),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,v,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),Si(e,g,0),e.uniform1i(h,0),e.uniform1i(m,0),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,y,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),Si(e,v,0),e.uniform1i(m,1),e.drawArrays(e.TRIANGLE_STRIP,0,4),g=y}return e.deleteBuffer(s),e.deleteBuffer(u),e.disableVertexAttribArray(c),e.disableVertexAttribArray(l),e.deleteTexture(v),y}(e,c,f||a,h,d,r);if(i){Va.useProgram(e,l),f=v;for(m=i-1;m>=0;m--){var y;p=Math.ceil(n*Math.pow(.5,m)),g=Math.ceil(o*Math.pow(.5,m));e.viewport(0,0,p,g),f=Ui(e,l,y=f,h,d,p,g),e.deleteTexture(y),h=p,d=g}v=f}return e.viewport(0,0,n,o),Va.useProgram(e,s.main),v}function sf(e,t,r,i,a,n,o,s){var c,u=i.bbox.slice(0),l=u[0],h=u[1],d=u[2]-u[0],f=u[3]-u[1],m=t.programs,p=m.bloom,g=m.bloomBlur,v=m.main;Va.useProgram(e,v),nf(r,d,f)&&((c=Zi.getEmptyInstance(e,u)).available=!0);var y=c?af(e,v,i,c,l,h,d,f):La(e,i.list[0].t,d,f),b=Zi.getEmptyInstance(e,u);b.available=!0,Va.useProgram(e,g),function(e,t,r,i,a,n){var o,s=r.list,c=i.list;s.forEach(function(r){var i=r.t,s=r.w,u=r.h,l=r.bbox,h=ki(e,0,void 0,s,u);o?(e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,h,0),e.viewport(0,0,s,u)):o=La(e,h,s,u),function(e,t,r,i,a){var n=Li(e,t),o=n.pointBuffer,s=n.a_position,c=n.texBuffer,u=n.a_texCoords;if(i!==t.uniformValue.u_threshold){var l=t.uniform.u_threshold;e.uniform1f(l,i)}if(a!==t.uniformValue.u_knee){var h=t.uniform.u_knee;e.uniform1f(h,a)}Si(e,r,0);var d=t.uniform.u_texture;e.uniform1i(d,0),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.deleteBuffer(o),e.deleteBuffer(c),e.disableVertexAttribArray(s),e.disableVertexAttribArray(u)}(e,t,i,a,n),c.push({bbox:l.slice(0),t:h,w:s,h:u})}),Na(e,o)}(e,g,c||i,b,a,n);for(var x=Math.min(d,f),T=0;x>=8&&(x>>=1,!(++T>=4)););var w=Zi.getEmptyInstance(e,u);w.available=!0,w.list=function(e,t,r,i,a){var n=r.list,o=i.list,s=t.programs,c=s.dualDown13,u=s.dualUp13;Va.useProgram(e,c);for(var l,h=[],d=function(t){var r=[];n.forEach(function(i){var a=i.t,n=i.w,o=i.h,s=n>>t+1,u=o>>t+1,h=ki(e,0,void 0,s,u),d={w:n>>t,h:o>>t,t:h};l?(e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,h,0),e.viewport(0,0,s,u)):l=La(e,h,s,u),function(e,t,r,i,a,n){void 0===n&&(n=1);var o=Li(e,t),s=o.pointBuffer,c=o.a_position,u=o.texBuffer,l=o.a_texCoords,h=t.uniform.u_xy;e.uniform2f(h,n/i,n/a),Si(e,r,0),e.uniform1i(t.uniform.u_texture,0),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.deleteBuffer(s),e.deleteBuffer(u),e.disableVertexAttribArray(c),e.disableVertexAttribArray(l)}(e,c,a,s,u),r.push(d)}),h.push(r)},f=0;f<a;f++)d(f);Va.useProgram(e,u);var m=function(t){h[t].forEach(function(r,i){var a=r.t,s=r.w,c=r.h,l=ki(e,0,void 0,s,c);e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,l,0),t?e.viewport(0,0,s,c):e.viewport(0,0,n[i].w,n[i].h);var d=t?h[t-1][i].t:n[i].t;!function(e,t,r,i,a,n,o){void 0===o&&(o=1);var s=Li(e,t),c=s.pointBuffer,u=s.a_position,l=s.texBuffer,h=s.a_texCoords,d=t.uniform.u_xy;e.uniform2f(d,o/a,o/n),Si(e,r,0),Si(e,i,1),e.uniform1i(t.uniform.u_texture1,0),e.uniform1i(t.uniform.u_texture2,1),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.deleteBuffer(c),e.deleteBuffer(l),e.disableVertexAttribArray(u),e.disableVertexAttribArray(h)}(e,u,d,a,s,c),e.deleteTexture(h[t][i].t),t?(e.deleteTexture(h[t-1][i].t),h[t-1][i].t=l):o[i]={bbox:n[i].bbox.slice(0),w:n[i].w,h:n[i].h,t:l}})};for(f=a-1;f>=0;f--)m(f);return Na(e,l),o}(e,t,b,w,T),b.release(),Va.useProgram(e,p);var k=Zi.getEmptyInstance(e,u);k.available=!0;var S=c?c.list:i.list;return e.bindFramebuffer(e.FRAMEBUFFER,y),w.list.forEach(function(t,r){var i=t.w,a=t.h,n=t.t,o=t.bbox,s=ki(e,0,void 0,i,a);e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0),e.viewport(0,0,i,a),function(e,t,r,i){var a=Li(e,t),n=a.pointBuffer,o=a.a_position,s=a.texBuffer,c=a.a_texCoords;Si(e,r,0),Si(e,i,1),e.uniform1i(t.uniform.u_texture1,0),e.uniform1i(t.uniform.u_texture2,1),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.deleteBuffer(n),e.deleteBuffer(s),e.disableVertexAttribArray(o),e.disableVertexAttribArray(c)}(e,p,S[r].t,n),k.list.push({bbox:o.slice(0),w:i,h:a,t:s})}),Va.useProgram(e,v),e.viewport(0,0,o,s),c&&c.release(),w&&w.release(),Na(e,y),k}function cf(e,t,r,i,a,n,o,s,c,u){var l=t.programs,h=l.cm;Va.useProgram(e,h);var d,f=r;if(i||1!==a||1!==n||1!==o||1!==s){var m=fr(i%360),p=Math.cos(m),g=Math.sin(m),v=.213*(1-a),y=.715*(1-a),b=.072*(1-a),x=n-1,T=.5*(1-o),w=ot(i?new Float32Array([.213+.787*p-.213*g,.715-.715*p-.715*g,.072-.072*p+.928*g,0,.213-.213*p+.143*g,.715+.285*p+.14*g,.072-.072*p-.283*g,0,.213-.213*p-.787*g,.715-.715*p+.715*g,.072+.928*p+.072*g,0,0,0,0,1]):at(),1!==a?new Float32Array([v+a,y,b,0,v,y+a,b,0,v,y,b+a,0,0,0,0,1]):at());if(1!==o&&(w[0]*=o,w[1]*=o,w[2]*=o,w[4]*=o,w[5]*=o,w[6]*=o,w[8]*=o,w[9]*=o,w[10]*=o),1!==s){var k=Math.min(1,Math.max(0,1-s));ut(w,ot(w,new Float32Array([.393+.607*k,.769-.769*k,.189-.189*k,0,.349-.349*k,.686+.314*k,.168-.168*k,0,.272-.272*k,.534-.534*k,.131+.869*k,0,0,0,0,1])))}var S=f,E=function(e,t,r,i,a){var n=Zi.getEmptyInstance(e,r.bbox);n.available=!0;for(var o=r.list,s=n.list,c=0,u=o.length;c<u;c++){var l=o[c],h=l.bbox,d=l.w,f=l.h,m=l.t,p=ki(e,0,void 0,d,f);a?(e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,p,0),e.viewport(0,0,d,f)):a=La(e,p,d,f),m&&Hi(e,t,m,i),s.push({bbox:h.slice(0),w:d,h:f,t:p})}return{res:n,frameBuffer:a}}(e,h,S,[w[0],w[1],w[2],w[3],x+T,w[4],w[5],w[6],w[7],x+T,w[8],w[9],w[10],w[11],x+T,0,0,0,1],d);f=E.res,d=E.frameBuffer,S!==r&&S.release()}if(Va.useProgram(e,l.main),d)return Na(e,d,c,u),f;e.viewport(0,0,c,u)}function uf(e){return(e.visibility===te.HIDDEN||e.opacity<=0)&&!e.maskMode}function lf(e,t,r,i,a){for(var n=r+a+1,o=t.length;n<o;n++){var s=t[n],c=s.node,u=s.lv,l=c.computedStyle;if(i>u){e.struct.next=n-r-a-1;break}if(n===o-1||l.breakMask&&i===u){e.struct.next=n-r-a;break}}}function hf(e,t,r,i,a,n,o){var s=(t.tempBbox||t._bbox||t.bbox).slice(0);if(st(t.tempMatrix),t.computedStyle.overflow===ie.HIDDEN||t.computedStyle.overflow===ie.CLIP)return s;for(var c=r+1,u=r+i+1;c<u;c++){var l=e[c],h=l.node,d=l.total,f=h.textureTarget;if(a){var m=h.parent,p=m.perspectiveMatrix,g=h.perspectiveMatrixSelf,v=h.matrix;g&&(v=ot(g,v)),p&&(v=ot(p,v));var y=ot(m.tempMatrix,v);ut(h.tempMatrix,y);var b=f&&f!==h.textureCache?f.bbox:h._filterBboxInt||h.filterBboxInt;b[2]-b[0]&&b[3]-b[1]&&hi(s,b,v)}var x=o[c];x&&(x.isTop=!1,n.subList.push(x)),(null==f?void 0:f.available)&&f!==h.textureCache&&(c+=d)}return s}function df(e,t,r,i,a,n,o,s,c){var u;if(void 0===c&&(c=!1),null===(u=r.textureTotal)||void 0===u?void 0:u.available){if(!c)return r.textureTotal;if(r.textureTotal!==r.textureCache)return r.textureTotal}var l=r.tempBbox;if(r.tempBbox=void 0,mi(l),!n&&!c){var h=r.textureCache;return!(null==h?void 0:h.available)&&r.hasContent&&(r.genTexture(e),h=r.textureCache),h}var d=t.programs,f=d.main;Va.useProgram(e,f);var m=l[0],p=l[1],g=Math.ceil(l[2]-m),v=Math.ceil(l[3]-p),y=Zi.getEmptyInstance(e,l);y.available=!0;for(var b,x=y.list,T=L.maxTextureSize,w=[],k=0,S=Math.ceil(v/T);k<S;k++)for(var E=0,C=Math.ceil(g/T);E<C;E++){var A=E===C-1?g-E*T:T,_=k===S-1?v-k*T:T,M=m+E*T,I=p+k*T,R=new Float32Array([M,I,M+A,I+_]);w.push({x:m+E*T,y:p+k*T,w:A,h:_,bbox:R})}for(k=a,S=a+n+1;k<S;k++){var P=i[k],O=P.node,D=P.total,B=P.next,F=O.computedStyle;if(uf(F))k+=D+B;else{var N=void 0,U=void 0;if(k===a){if(N=O.tempOpacity=1,st(O.tempMatrix),U=O.tempMatrix,F.perspectiveSelf>=1){var z=F.transformOrigin;ut(U,H=Mr(F.perspectiveSelf,z[0]-m,z[1]-p))}if(F.perspective>=1){var W=F.perspectiveOrigin;ut(U,re=ot(Mr(F.perspective,W[0]-m,W[1]-p),U))}}else{var V=O.parent;N=O.tempOpacity=F.opacity*V.tempOpacity;var H=void 0;if(F.perspectiveSelf>=1){z=F.transformOrigin;H=Mr(F.perspectiveSelf,z[0]-m,z[1]-p)}var X=O.transform;if(nt(X))U=V.tempMatrix,H&&(U=ot(U,H));else{var G=_r(X,(z=F.transformOrigin)[0]-m,z[1]-p);U=ot(V.tempMatrix,H?ot(H,G):G)}}ut(O.tempMatrix,U);var Y=O.textureTarget;if(!(null==Y?void 0:Y.available)&&O.hasContent&&(O.genTexture(e),Y=O.textureTarget),Y&&Y.available)for(var q=F.mixBlendMode,K=Y.list,$=(E=0,w.length);E<$;E++)for(var Q=w[E],Z=Q.x,J=Q.y,ee=Q.w,te=Q.h,re=Q.t,ie=.5*ee,ae=.5*te,ne=0,oe=K.length;ne<oe;ne++){var se=K[ne],ce=se.bbox,ue=se.t,le=se.tc;if(ue&&za(ce,U,Z,J,ee,te)){re||(re=Q.t=ki(e,0,void 0,ee,te)),b?(e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,re,0),e.viewport(0,0,ee,te)):b=La(e,re,ee,te);var he=void 0;q!==j.NORMAL&&k>a&&(he=ki(e,0,void 0,ee,te),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,he,0)),Ei(e,ie,ae,f,{opacity:N,matrix:U,bbox:ce,t:ue,tc:le,dx:-Q.x,dy:-Q.y}),q!==j.NORMAL&&he&&(re=Q.t=pf(e,re,he,q,d,ee,te))}}(null==Y?void 0:Y.available)&&Y!==O.textureCache&&(k+=D+B)}}return b&&Na(e,b,o,s),w.forEach(function(e){x.push({bbox:e.bbox,w:e.w,h:e.h,t:e.t})}),y}function ff(e,t,r,i,a){var n,o;if(null===(n=r.textureFilter)||void 0===n?void 0:n.available)return r.textureFilter;var s=r.computedStyle.filter,c=r.textureTarget;return s.forEach(function(n){if(n.u===V.GAUSS_BLUR){if(n.radius>=1){var s=function(e,t,r,i,a,n,o,s){void 0===s&&(s=!1);var c=Pr(a),u=s?Dr(c):0,l=i.bbox.slice(0);u&&(l[0]-=u,l[1]-=u,l[2]+=u,l[3]+=u);var h,d=l[0],f=l[1],m=l[2]-l[0],p=l[3]-l[1],g=t.programs.main;Va.useProgram(e,g),(u||nf(r,m,p))&&((h=Zi.getEmptyInstance(e,l)).available=!0);var v=h?h.list:i.list,y=h?af(e,g,i,h,d,f,m,p):La(e,i.list[0].t,m,p),b=function(e){var t=0;return e>=256?t=4:e>=64?t=3:e>=16?t=2:e>=4&&(t=1),t}(a),x=Br(a*Math.pow(.5,b)),T=Zi.getEmptyInstance(e,l);T.available=!0;for(var w=T.list,k=0,S=v.length;k<S;k++){var E=v[k],C=E.bbox,A=E.w,_=E.h,M=E.t;w.push({bbox:C.slice(0),w:A,h:_,t:M&&of(e,t,x,b,M,A,_)})}if(v.length>1){var I=tf(e,T,d,f,m,p,u);for(k=0,S=I.length;k<S;k++){var R=I[k],P=(C=R.bbox,R.w),O=R.h;M=R.t,Va.useProgram(e,g),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,M,0),e.viewport(0,0,P,O);for(var D=.5*P,B=.5*O,F=!1,L=0,N=v.length;L<N;L++){var U=v[L],z=U.bbox,W=U.t,V=z[2]-z[0],H=z[3]-z[1];W&&za(C,void 0,z[0],z[1],V,H)&&(Ei(e,D,B,g,{opacity:1,bbox:z,t:W,dx:-C[0],dy:-C[1]}),F=!0)}F&&(R.t=of(e,t,x,b,M,P,O),e.deleteTexture(M))}rf(e,g,T,I,l,u)}return h&&h.release(),Va.useProgram(e,g),Na(e,y,n,o),T}(e,t,r,o||c,n.radius,i,a);o&&o.release(),o=s}}else if(n.u===V.RADIAL_BLUR){if(n.radius>=1){s=function(e,t,r,i,a,n,o,s,c){void 0===c&&(c=!1);var u=i.bbox,l=Pr(a),h=c?Dr(l):0,d=u.slice(0),f=d[2]-d[0],m=d[3]-d[1],p=n[0]*f,g=n[1]*m,v=2*h/Math.sqrt(f*f+m*m),y=Math.ceil(v*p),b=Math.ceil(v*(f-p)),x=Math.ceil(v*g),T=Math.ceil(v*(m-g));d[0]-=y,d[1]-=x,d[2]+=b,d[3]+=T;var w,k=d[0],S=d[1],E=d[2]-d[0],C=d[3]-d[1],A=t.programs,_=A.main;(h||nf(r,E,C))&&((w=Zi.getEmptyInstance(e,d)).available=!0);var M=w?w.list:i.list,I=w?af(e,_,i,w,k,S,E,C):La(e,i.list[0].t,E,C),R=A.radial;Va.useProgram(e,R);var P=Zi.getEmptyInstance(e,d);P.available=!0;for(var O=P.list,D=p+y,B=g+x,F=0,L=M.length;F<L;F++){var N=M[F],U=N.bbox,z=N.w,W=N.h,V=N.t;e.viewport(0,0,z,W);var H=U[2]-U[0],X=U[3]-U[1],j=[(D-U[0]+d[0])/H,(B-U[1]+d[1])/X],G=V&&Wi(e,R,V,v,h,j,z,W);O.push({bbox:U.slice(0),w:z,h:W,t:G})}if(M.length>1){var Y=tf(e,P,k,S,E,C,h);for(F=0,L=Y.length;F<L;F++){var q=Y[F],K=(U=q.bbox,q.w),$=q.h;V=q.t,Va.useProgram(e,_),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,V,0),e.viewport(0,0,K,$),j=[(D-U[0]+d[0])/(U[2]-U[0]),(B-U[1]+d[0])/(U[3]-U[1])];for(var Q=.5*K,Z=.5*$,J=!1,ee=0,te=M.length;ee<te;ee++){var re=M[ee],ie=re.bbox,ae=re.t;H=ie[2]-ie[0],X=ie[3]-ie[1],ae&&za(U,void 0,ie[0],ie[1],H,X)&&(Ei(e,Q,Z,_,{opacity:1,bbox:new Float32Array([ie[0],ie[1],ie[2],ie[3]]),t:ae,dx:-U[0],dy:-U[1]}),J=!0)}J&&(Va.useProgram(e,R),q.t=Wi(e,R,V,v,h,j,K,$)),e.deleteTexture(V)}rf(e,_,P,Y,d,h)}return w&&w.release(),Va.useProgram(e,_),Na(e,I,o,s),P}(e,t,r,o||c,n.radius,n.center,i,a);o&&o.release(),o=s}}else if(n.u===V.MOTION_BLUR){if(n.radius>=1){s=function(e,t,r,i,a,n,o,s,c,u,l){void 0===u&&(u=!1),void 0===l&&(l=!1);var h=fr(n),d=u?3*a:0,f=a,m=i.bbox.slice(0);if(d){var p=Math.sin(h),g=Math.cos(h),v=Math.abs(Math.ceil(p*d)),y=Math.abs(Math.ceil(g*d));m[0]-=y,m[1]-=v,m[2]+=y,m[3]+=v}var b,x=m[0],T=m[1],w=m[2]-m[0],k=m[3]-m[1],S=t.programs,E=S.main;(d||nf(r,w,k))&&((b=Zi.getEmptyInstance(e,m)).available=!0);var C=b?b.list:i.list,A=b?af(e,E,i,b,x,T,w,k):La(e,i.list[0].t,w,k),_=S.motion;Va.useProgram(e,_);var M=Zi.getEmptyInstance(e,m);M.available=!0;for(var I=M.list,R=0,P=C.length;R<P;R++){var O=C[R],D=O.bbox,B=O.w,F=O.h,L=O.t;e.viewport(0,0,B,F);var N=L&&zi(e,_,L,f,h,o,B,F,l);I.push({bbox:D.slice(0),w:B,h:F,t:N})}if(C.length>1){var U=tf(e,M,x,T,w,k,d);for(R=0,P=U.length;R<P;R++){var z=U[R],W=(D=z.bbox,z.w),V=z.h;L=z.t,Va.useProgram(e,E),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,L,0),e.viewport(0,0,W,V);for(var H=.5*W,X=.5*V,j=!1,G=0,Y=C.length;G<Y;G++){var q=C[G],K=q.bbox,$=q.t,Q=K[2]-K[0],Z=K[3]-K[1];$&&za(D,void 0,K[0],K[1],Q,Z)&&(Ei(e,H,X,E,{opacity:1,bbox:K,t:$,dx:-D[0],dy:-D[1]}),j=!0)}j&&(Va.useProgram(e,_),z.t=zi(e,_,L,f,h,o,W,V,l)),e.deleteTexture(L)}rf(e,E,M,U,m,d)}return b&&b.release(),Va.useProgram(e,E),Na(e,A,s,c),M}(e,t,r,o||c,n.radius,n.angle,n.offset,i,a);o&&o.release(),o=s}}else if(n.u===V.BLOOM){if(n.threshold>0){s=sf(e,t,r,o||c,n.threshold,n.knee,i,a);o&&o.release(),o=s}}else if(n.u===V.LIGHT_DARK){s=function(e,t,r,i,a,n,o,s){var c,u=fr(n),l=i.bbox.slice(0),h=l[0],d=l[1],f=l[2]-l[0],m=l[3]-l[1],p=t.programs,g=p.main;nf(r,f,m)&&((c=Zi.getEmptyInstance(e,l)).available=!0);var v=c?c.list:i.list,y=c?af(e,g,i,c,h,d,f,m):La(e,i.list[0].t,f,m),b=p.lightDark;Va.useProgram(e,b);var x=Zi.getEmptyInstance(e,l);x.available=!0;for(var T=x.list,w=0,k=v.length;w<k;w++){var S=v[w],E=S.bbox,C=S.w,A=S.h,_=S.t,M=ki(e,0,void 0,C,A);e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,M,0),e.viewport(0,0,C,A),Xi(e,b,_,a,u,C,A),T.push({bbox:E.slice(0),w:C,h:A,t:M})}return v.length,Va.useProgram(e,g),e.viewport(0,0,o,s),c&&c.release(),Na(e,y),x}(e,t,r,o||c,n.radius,n.angle,i,a);o&&o.release(),o=s}else if(n.u===V.HUE_ROTATE&&n.radius%360||n.u===V.SATURATE&&1!==n.radius||n.u===V.BRIGHTNESS&&1!==n.radius||n.u===V.CONTRAST&&1!==n.radius||n.u===V.SEPIA&&n.radius>0&&n.radius<1){s=cf(e,t,o||c,n.u===V.HUE_ROTATE?n.radius:0,n.u===V.SATURATE?n.radius:1,n.u===V.BRIGHTNESS?n.radius:1,n.u===V.CONTRAST?n.radius:1,n.u===V.SEPIA?n.radius:0,i,a);o&&o.release(),o=s}}),o}function mf(e,t,r,i,a,n,o,s,c,u){var l,h,d;if((null===(l=r.textureMask)||void 0===l?void 0:l.available)||!r.hasContent)return r.textureMask;(null===(h=r.textureTarget)||void 0===h?void 0:h.available)||r.genTexture(e);var f=r.textureTarget;if(!r.next)return f;var m=f.list,p=t.programs;Va.useProgram(e,p.main);var g=f.bbox,v=r.computedStyle,y=g[0],b=g[1],x=g[2]-y,T=g[3]-b,w=Zi.getEmptyInstance(e,g);w.available=!0;var k,S,E=w.list,C=L.maxTextureSize;nf(r,x,T)&&(r.tempBbox=(r.tempBbox||r._rect||r.rect).slice(0),m=(S=df(e,t,r,a,n,s,c,u,!0)).list);for(var A=xt(r.matrix),_=0,M=Math.ceil(T/C);_<M;_++)for(var I=0,R=Math.ceil(x/C);I<R;I++){var P=I===R-1?x-I*C:C,O=_===M-1?T-_*C:C,D=ki(e,0,void 0,P,O),B=y+I*C,F=b+_*C,N={bbox:new Float32Array([B,F,B+P,F+O]),w:P,h:O,t:D};E.push(N);var U=y+I*C,z=b+_*C;k?(e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,D,0),e.viewport(0,0,P,O)):k=La(e,D,P,O);var W=.5*P,V=.5*O;if([$.ALPHA_WITH,$.GRAY_WITH].includes(i)&&v.visibility===te.VISIBLE&&v.opacity>0&&f.available){var H=null===(d=m[_*R+I])||void 0===d?void 0:d.t;H&&Ei(e,W,V,p.main,{opacity:1,bbox:new Float32Array([0,0,P,O]),t:H})}for(var X=!_&&!I,G=n+s+1,Y=a.length;G<Y;G++){var q=a[G],K=q.node,Q=q.lv,Z=q.total,J=q.next,ee=K.computedStyle;if(o>Q){r.struct.next=G-n-s-1;break}if(G===Y||(ee.breakMask||ee.maskMode)&&o===Q){r.struct.next=G-n-s-1;break}if(uf(ee))G+=Z+J;else{var re=void 0,ie=void 0;if(X){if(o===Q)re=K.tempOpacity=ee.opacity,ie=ot(A,K.matrix);else{var ae=K.parent;re=K.tempOpacity=ee.opacity*ae.tempOpacity,ie=ot(ae.tempMatrix,K.matrix)}ut(K.tempMatrix,ie)}else re=K.tempOpacity,ie=K.tempMatrix;var ne=K.textureTarget;if(!(null==ne?void 0:ne.available)&&K.hasContent&&(K.genTexture(e),ne=K.textureTarget),null==ne?void 0:ne.available){var oe=ee.mixBlendMode;if(!za(ne.bbox,ie,U,z,P,O))continue;for(var se=ne.list,ce=0,ue=se.length;ce<ue;ce++){var le=se[ce],he=le.bbox,de=le.t;if(de&&za(he,ie,U,z,P,O)){var fe=void 0;oe!==j.NORMAL&&(G>n+s+1&&[$.OUTLINE,$.ALPHA,$.GRAY].includes(i)||G>n+s&&[$.ALPHA_WITH,$.GRAY_WITH].includes(i))&&(fe=ki(e,0,void 0,P,O),k?(e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,fe,0),e.viewport(0,0,P,O)):k=La(e,fe,P,O)),Ei(e,W,V,p.main,{opacity:re,matrix:ie,bbox:he,t:de,dx:-U,dy:-z}),oe!==j.NORMAL&&fe&&(N.t=pf(e,N.t,fe,oe,p,P,O))}}}((null==ne?void 0:ne.available)&&ne!==K.textureCache||ee.maskMode)&&(![$.OUTLINE,$.ALPHA_WITH,$.GRAY_WITH].includes(ee.maskMode)||K.next&&!K.next.computedStyle.breakMask)&&(G+=Z+J)}}}var me=Zi.getEmptyInstance(e,g);me.available=!0;var pe=me.list;if(i===$.GRAY||i===$.GRAY_WITH){Va.useProgram(e,p.maskGray);for(_=0,M=E.length;_<M;_++){var ge=E[_],ve=ge.bbox,ye=ge.w,be=ge.h;D=ge.t,fe=void 0;m[_]&&m[_].t&&D&&(fe=ki(e,0,void 0,ye,be),k?(e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,fe,0),e.viewport(0,0,ye,be)):k=La(e,fe,ye,be),m[_]&&m[_].t&&Ni(e,p.maskGray,m[_].t,D)),pe.push({bbox:ve.slice(0),w:ye,h:be,t:fe})}}else{Va.useProgram(e,p.mask);for(_=0,M=E.length;_<M;_++){var xe=E[_],Te=xe.bbox,we=xe.w,ke=xe.h;D=xe.t,fe=ki(e,0,void 0,we,ke);k?(e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,fe,0),e.viewport(0,0,we,ke)):k=La(e,fe,we,ke),Ni(e,p.mask,m[_].t,D),pe.push({bbox:Te.slice(0),w:we,h:ke,t:fe})}}return Va.useProgram(e,p.main),w.release(),S&&S.release(),k?Na(e,k,c,u):e.viewport(0,0,c,u),me}function pf(e,t,r,i,a,n,o){var s;i===j.MULTIPLY?s=a.multiplyProgram:i===j.SCREEN?s=a.screenProgram:i===j.OVERLAY?s=a.overlayProgram:i===j.DARKEN?s=a.darkenProgram:i===j.LIGHTEN?s=a.lightenProgram:i===j.COLOR_DODGE?s=a.colorDodgeProgram:i===j.COLOR_BURN?s=a.colorBurnProgram:i===j.HARD_LIGHT?s=a.hardLightProgram:i===j.SOFT_LIGHT?s=a.softLightProgram:i===j.DIFFERENCE?s=a.differenceProgram:i===j.EXCLUSION?s=a.exclusionProgram:i===j.HUE?s=a.hueProgram:i===j.SATURATION?s=a.saturationProgram:i===j.COLOR?s=a.colorProgram:i===j.LUMINOSITY?s=a.luminosityProgram:(oe.error("Unknown mixBlendMode: "+i),s=a.program),e.useProgram(s);var c=ki(e,0,void 0,n,o);return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,c,0),Vi(e,s,t,r),e.deleteTexture(t),e.deleteTexture(r),e.useProgram(a.program),c}function gf(e){e.valid=!0;for(var t=e.subList;t.length;){var r=t.pop();r.valid=!0;for(var i=r.subList;i.length;)t.push(i.pop())}}var vf,yf={genTotal:df,genFilter:ff,genMask:function(e){var t=e.root,r=e.computedStyle,i=e.struct;t&&i&&mf(t.ctx,t,e,r.maskMode,t.structs,t.structs.indexOf(i),i.lv,i.total,t.width,t.height)}};function bf(e,t){var r=t.structs,i=t.width,a=t.height,n=t.isWebgl2;!function(e,t,r,i,a,n){var o,s,c,u,l,h=t.structs,d=t.width,f=t.height;t.contentLoadingCount=0;for(var m=[],p=[],g=0,v=h.length;g<v;g++){var y=h[g],b=y.node,x=y.lv,T=y.total,w=y.next,k=b.refreshLevel,S=b.computedStyle,E=b.textureTotal,C=b.textureFilter,A=b.textureMask;b.refreshLevel=ci.NONE,k>=ci.REPAINT&&b.calContent(),t.contentLoadingCount+=b.calContentLoading();var _=S.filter,M=S.opacity,I=S.mixBlendMode,R=S.overflow,P=S.maskMode,O=(M>0&&M<1||I!==j.NORMAL||R===ie.HIDDEN)&&T>0&&!(null==E?void 0:E.available),D=_.map(function(e){return e.u===V.BLOOM?e.threshold>0:e.u===V.SEPIA?e.radius>0&&e.radius<1:e.radius>=1}).filter(function(e){return e}).length>0&&!(null==C?void 0:C.available),B=P>0&&!(null==A?void 0:A.available);if(B&&(b.next&&!b.next.computedStyle.breakMask&&b.next.computedStyle.maskMode===$.NONE||(B=!1,null===(o=b.textureMask)||void 0===o||o.release(),b.textureMask=void 0)),O||D||B){var F={i:g,lv:x,total:T,node:b,valid:!1,subList:[],isNew:!1,isTop:!0};m.push(F),p[g]=F}(null==E?void 0:E.available)&&(g+=T),(null==A?void 0:A.available)&&(g+=w)}m.sort(function(e,t){return e.lv===t.lv?t.i-e.i:t.lv-e.lv});var L=0;for(v=m.length;L<v;L++){g=(U=m[L]).i,T=U.total,b=U.node;var N=U.isNew=!b.tempBbox;b.tempBbox=hf(h,b,g,T,N,U,p)}for(L=0,v=m.length;L<v;L++){b=(U=m[L]).node;var U,z=U.isTop;if(g=U.i,x=U.lv,T=U.total,z&&za(b.tempBbox,b.matrixWorld,r,i,a-r,n-i)&&(gf(U),b.computedStyle.maskMode)){lf(b,h,g,x,T);for(var W=L;W>=0;W--){var H=m[W];if(H.i>g+T+b.struct.next)break;gf(H)}}}for(L=0,v=m.length;L<v;L++){var X=m[L],G=(g=X.i,x=X.lv,T=X.total,b=X.node,X.valid);if(N=X.isNew,P=b.computedStyle.maskMode,G){if(!uf(b.computedStyle)){var Y=void 0;(null===(s=b.textureTotal)||void 0===s?void 0:s.available)||(F=df(e,t,b,h,g,T,d,f))&&!Y&&(b.textureTotal=b.textureTarget=F,Y=F),b.textureTarget&&!(null===(c=b.textureFilter)||void 0===c?void 0:c.available)&&(F=ff(e,t,b,d,f))&&(b.textureFilter=b.textureTarget=F,Y=F),P&&(null===(u=b.textureTarget)||void 0===u?void 0:u.available)&&!(null===(l=b.textureMask)||void 0===l?void 0:l.available)&&b.next&&(F=mf(e,t,b,P,h,g,x,T,d,f))&&(b.textureMask=b.textureTarget=F,Y=F)}}else N&&P&&lf(b,h,g,x,T)}}(e,t,0,0,i,a);var o=.5*i,s=.5*a,c=t.programs,u=c.main,l=c.pr;Va.useProgram(e,u),e.viewport(0,0,i,a);for(var h=[],d=0,f=r.length;d<f;d++){var m=r[d],p=m.node,g=m.total,v=m.next;if(uf(p.computedStyle)){for(var y=d+1;y<d+g;y++){var b=r[y].node;xf(b,y,b.parent)}d+=g+v}else{xf(p,d,p.parent);var x=p._opacity,T=p._matrixWorld,w=p.textureTarget,k=!1;if((null==w?void 0:w.available)?k=Ua(w.bbox,T,i,a):(k=Ua(p._filterBbox||p.filterBbox,T,i,a))&&p.hasContent&&(p.genTexture(e),w=p.textureTarget),k&&(null==w?void 0:w.available))for(var S=w.list,E=0,C=S.length;E<C;E++){var A=S[E],_=A.bbox,M=A.t,I=A.tc;M&&(n?h.push({opacity:x,matrix:T,bbox:_,t:M,tc:I}):Ei(e,o,s,u,{opacity:x,matrix:T,bbox:_,t:M,tc:I}))}(null==w?void 0:w.available)&&w!==p.textureCache&&(d+=g+v)}}n&&(Va.useProgram(e,l),function(e,t,r,i,a){if(a.length){var n=e.createVertexArray();e.bindVertexArray(n);for(var o=Math.floor(a.length/Ci),s=0;s<o;s++)Fi(e,t,r,i,a.slice(s*Ci,s*Ci+16));a.length%Ci&&Fi(e,t,r,i,a.slice(o*Ci)),e.bindVertexArray(null)}}(e,o,s,l,h),Va.useProgram(e,u))}function xf(e,t,r){var i=!1,a=!1;if(t?(i=e.hasCacheOp&&e.parentOpId===r.localOpId,a=e.hasCacheMw&&e.parentMwId===r.localMwId):(i=e.hasCacheOp,a=e.hasCacheMw),i||(e._opacity=r?r._opacity*e.computedStyle.opacity:e.computedStyle.opacity,r&&(e.parentOpId=r.localOpId),e.hasCacheOp=!0),!a){var n=null==r?void 0:r.perspectiveMatrix,o=e.perspectiveMatrixSelf,s=e.matrix;o&&(s=ot(o,s)),n&&(s=ot(n,s)),ut(e._matrixWorld,r?ot(r._matrixWorld,s):s),r&&(e.parentMwId=r.localMwId),e.hasCacheMw&&e.localMwId++,e.hasCacheMw=!0}}var Tf=function(){function e(){this.task=[],this.now=oe.now(),this.id=0}return e.prototype.init=function(){var e=this,t=this.task;oe.cancelAnimationFrame(this.id);var r=this.now=oe.now(),i=function(){oe.cancelAnimationFrame(e.id),e.id=oe.requestAnimationFrame(function(){var a=e.now=oe.now();if(!vf&&t.length){var n=a-r;n=Math.max(n,0),r=a,t.slice(0).forEach(function(e){e(n)}),t.length&&i()}})};i()},e.prototype.onFrame=function(e){var t=this.task;t.length||this.init(),t.push(e)},e.prototype.offFrame=function(e){var t=this.task,r=t.indexOf(e);r>-1&&t.splice(r,1),t.length||(oe.cancelAnimationFrame(this.id),this.now=0)},e.prototype.nextFrame=function(e){var t=this,r=function(i){e(i),t.offFrame(r)};return this.onFrame(r),r},e.prototype.pause=function(){vf=!0},e.prototype.resume=function(){vf&&(this.init(),vf=!1)},e}(),wf=new Tf;var kf="#define GLSLIFY 1\nattribute vec2 a_position;attribute vec2 a_texCoords;varying vec2 v_texCoords;void main(){gl_Position=vec4(a_position,0,1);v_texCoords=a_texCoords;}",Sf=function(e){function r(t){var r,i=e.call(this,t)||this;t.onMeta&&(i.onMeta=t.onMeta),t.onCanplay&&(i.onCanplay=t.onCanplay),t.onError&&(i.onError=t.onError),t.onWaiting&&(i.onWaiting=t.onWaiting),i._currentTime=t.currentTime||0,i._volumn=Math.max(0,Math.min(1,null!==(r=t.volumn)&&void 0!==r?r:1));var a=i._src=t.src||"";if(a){i._currentTime>=0&&(i.contentLoadingNum=1);var n=i._decoder=new Jd(a);n.on(jd.META,function(e){i._metaData=e,i._currentTime>=0&&i._currentTime<=e.duration?i.contentLoadingNum=1:i.contentLoadingNum=0,i.onMeta&&i.onMeta(e),i.emit(Ia)}),n.on(jd.ERROR,function(e){oe.error(e),i.contentLoadingNum=0,i.onError&&i.onError(e),i.emit(Ra),i.refresh()}),n.on(jd.CANPLAY,function(e){i.contentLoadingNum=0,i.onCanplay&&i.onCanplay(),i.emit(Ma),i.refresh()}),n.on([jd.CANPLAY,jd.AUDIO_BUFFER],function(e){var t=i.root;if(t&&e.audioBuffer){var r=t.audioContext,a=i.timeAnimation;if("running"===(null==a?void 0:a.playState)&&r){var n=a.currentTime-a.delay;if(n>=e.timestamp+e.duration||a.duration<=e.timestamp)return;var o=r.createBufferSource();o.buffer=e.audioBuffer,i.gainNode||(i.gainNode=r.createGain(),i.gainNode.gain.value=i.volumn,i.gainNode.connect(r.destination)),o.connect(i.gainNode),n>=e.audioTimestamp?o.start(0,.001*(n-e.audioTimestamp),.001*(a.duration-n)):o.start(r.currentTime+.001*(e.audioTimestamp-n),0,.001*(a.duration-e.audioTimestamp))}}}),n.start(i._currentTime)}return i}return t(r,e),r.prototype.calContentLoading=function(){var t=e.prototype.calContentLoading.call(this);if(t){if(this._currentTime>=0){if(!this._metaData)return t;if(this._currentTime<this._metaData.duration)return t}return 0}return t},r.prototype.release=function(){e.prototype.release.call(this);var t=this,r=t.loader,i=t.audioBufferSourceNode,a=t.gainNode;(null==r?void 0:r.success)&&r.release(),i&&(i.stop(),i.disconnect(),this.audioBufferSourceNode=void 0),a&&(a.disconnect(),this.gainNode=void 0)},r.prototype.timeAnimate=function(e,t){var r;null===(r=this.timeAnimation)||void 0===r||r.remove();var i=this.timeAnimation=new Ha(this,e,t);return this.initAnimate(i,t)},Object.defineProperty(r.prototype,"src",{get:function(){return this._src},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"currentTime",{get:function(){return this._currentTime},set:function(e){if(this._currentTime!==e){this._currentTime=e;var t=this._decoder;if(t){var r=e,i=t.currentGOP;t.start(r);var a=t.currentGOP;!(null==a?void 0:a.audioBuffer)&&(null==a?void 0:a.state)===Wd.DECODING&&e>=0&&!t.error&&(this._metaData&&this._metaData.duration,this.contentLoadingNum=1),(null==i?void 0:i.audioBuffer)&&!(null==a?void 0:a.audioBuffer)&&this._metaData&&e>=0&&e<this._metaData.duration&&!t.error&&(this.onWaiting&&this.onWaiting(),this.emit(_a))}}},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"duration",{get:function(){var e;return(null===(e=this.loader)||void 0===e?void 0:e.duration)||0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"metaData",{get:function(){return this._metaData},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"volumn",{get:function(){return this._volumn},set:function(e){var t=Math.max(0,Math.min(1,e));this._volumn!==t&&(this._volumn=t,this.gainNode&&(this.gainNode.gain.value=t))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"decoder",{get:function(){return this._decoder},enumerable:!1,configurable:!0}),r}(ka),Ef=function(e){function r(t){var r=e.call(this)||this;return r.aniList=[],r.audioContext=t,r}return t(r,e),r.prototype.addAni=function(e){-1===this.aniList.indexOf(e)&&(this.aniList.push(e),1===this.aniList.length&&this.checkEvent())},r.prototype.removeAni=function(e){var t=this.aniList.indexOf(e);t>-1&&(this.aniList.splice(t,1),0===t&&this.checkEvent())},r.prototype.play=function(){this.aniList.forEach(function(e){e.play(),Cf(e)})},r.prototype.pause=function(){this.aniList.forEach(function(e){e.pause(),Af(e)})},r.prototype.resume=function(){this.aniList.forEach(function(e){e.resume(),Cf(e)})},r.prototype.finish=function(){this.aniList.forEach(function(e){e.finish(),Af(e)})},r.prototype.cancel=function(){this.aniList.forEach(function(e){e.cancel(),Af(e)})},r.prototype.gotoAndPlay=function(e){this.aniList.forEach(function(t){t.gotoAndPlay(e),Cf(t)})},r.prototype.gotoAndStop=function(e){this.aniList.forEach(function(t){t.gotoAndStop(e),Af(t)}),this.aniList.forEach(function(e){e.afterRunning()})},r.prototype.checkEvent=function(){var e=this,t=this.aniList[0];t&&Object.keys(this.__eHash).forEach(function(r){e.__eHash[r].forEach(function(e){t.on(r,e)})})},r.prototype.on=function(t,r){e.prototype.on.call(this,t,r),this.aniList.length&&this.aniList[0].on(t,r)},r.prototype.once=function(t,r){e.prototype.once.call(this,t,r),this.aniList.length&&this.aniList[0].once(t,r)},r.prototype.off=function(t,r){e.prototype.off.call(this,t,r),this.aniList.length&&this.aniList[0].off(t,r)},Object.defineProperty(r.prototype,"currentTime",{get:function(){var e=this.aniList[0];return e?e.currentTime:0},set:function(e){this.aniList.forEach(function(t){t.currentTime=e})},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"duration",{get:function(){var e=this.aniList[0];return e?e.delay+e.duration+e.endDelay:0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"playCount",{get:function(){var e=this.aniList[0];return e?e.playCount:0},set:function(e){this.aniList.forEach(function(t){t.playCount=e})},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"playState",{get:function(){var e=this.aniList[0];return e?e.playState:"idle"},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"pending",{get:function(){var e=this.aniList[0];return!e||"running"!==e.playState},enumerable:!1,configurable:!0}),r}(M);function Cf(e){if(!(e.currentTime>=e.delay+e.duration)&&e instanceof Ha){var t=e.node;if(!(t instanceof Sf||t instanceof ef))return;if(t.gainNode&&(t.gainNode.disconnect(),t.gainNode=void 0),t.decoder){var r=t.decoder.currentGOP;if((null==r?void 0:r.audioBuffer)&&t.root){var i=t.root.audioContext;if(t.gainNode||(t.gainNode=i.createGain(),t.gainNode.gain.value=t.volumn),r.audioBufferSourceNode){try{r.audioBufferSourceNode.stop()}catch(e){}r.audioBufferSourceNode.disconnect(),r.audioBufferSourceNode=void 0}var a=i.createBufferSource();a.buffer=r.audioBuffer,a.connect(t.gainNode),t.gainNode.connect(i.destination),r.audioBufferSourceNode=a;var n=e.currentTime-e.delay;n>=r.audioTimestamp?a.start(0,.001*(n-r.audioTimestamp),.001*(e.duration-n)):a.start(i.currentTime+.001*(r.audioTimestamp-n),0,.001*(e.duration-r.audioTimestamp));for(var o=t.decoder.gopList,s=t.decoder.gopIndex+1,c=o.length;s<c;s++){var u=o[s];if(e.duration<=u.timestamp)return;if(u.audioBufferSourceNode){try{u.audioBufferSourceNode.stop()}catch(e){}u.audioBufferSourceNode.disconnect(),u.audioBufferSourceNode=void 0}if(u.audioBuffer){var l=i.createBufferSource();l.buffer=u.audioBuffer,t.gainNode||(t.gainNode=i.createGain(),t.gainNode.gain.value=t.volumn),l.connect(t.gainNode),t.gainNode.connect(i.destination),u.audioBufferSourceNode=l,l.start(i.currentTime+.001*(u.audioTimestamp-n),0,.001*(e.duration-u.audioTimestamp))}}}}}}function Af(e){var t,r;if(e instanceof Ha){var i=e.node;if(!(i instanceof Sf||i instanceof ef))return;i.gainNode&&(i.gainNode.disconnect(),i.gainNode=void 0),null===(r=null===(t=i.decoder)||void 0===t?void 0:t.gopList)||void 0===r||r.forEach(function(e){var t,r;try{null===(t=e.audioBufferSourceNode)||void 0===t||t.stop()}catch(e){}null===(r=e.audioBufferSourceNode)||void 0===r||r.disconnect(),e.audioBufferSourceNode=void 0})}}var _f,Mf,If,Rf,Pf,Of,Df,Bf,Ff=function(e){function r(t){var r=e.call(this,t)||this;t.onMeta&&(r.onMeta=t.onMeta),t.onLoad&&(r.onLoad=t.onLoad),r._currentTime=t.currentTime||0;var i=function(){var e=window.lottie;if(!e)throw new Error("Missing lottie-web library");r._metaData={duration:1e3*r._json.op/r._json.fr},r.contentLoadingNum=0,r.onMeta&&r.onMeta(r._metaData),r.emit(Ia,r._metaData);var t=document.createElement("div");t.style.width=r._json.w+"px",t.style.height=r._json.h+"px",t.style.position="fixed",t.style.visibility="hidden",t.style.transform="translate(9999px, 9999px)",t.style.pointerEvents="none",document.body.appendChild(t);var i=r._lottie=e.loadAnimation({container:t,renderer:"canvas",loop:!0,autoplay:!0,animationData:r._json,rendererSettings:{preserveDrawingBuffer:!0}});i.addEventListener("DOMLoaded",function(){if(r.canvas=t.querySelector("canvas"),r._currentTime>=0&&r._currentTime<r._metaData.duration&&i.goToAndStop(r._currentTime),r.isMounted){var e=r.style,a=e.left,n=e.top,o=e.right,s=e.bottom,c=e.width,u=e.height;(a.u===V.AUTO||o.u===V.AUTO)&&c.u===V.AUTO||(n.u===V.AUTO||s.u===V.AUTO)&&u.u===V.AUTO?r.refresh(ci.REFLOW):r.refresh()}r.onLoad&&r.onLoad(),r.emit(Pa)})};if(t.src)r._src=t.src,r._currentTime>=0&&(r.contentLoadingNum=1),fetch(t.src,t.options).then(function(e){return e.json()}).then(function(e){r._json=e,i()});else{if(!t.json)throw new Error("Missing src or json in Lottie");r._json=t.json,i()}return r}return t(r,e),r.prototype.lay=function(t){e.prototype.lay.call(this,t);var r=this,i=r.style,a=r.computedStyle,n=r._json,o=i.left,s=i.top,c=i.right,u=i.bottom,l=i.width,h=i.height;if(n){var d=(o.u===V.AUTO||c.u===V.AUTO)&&l.u===V.AUTO,f=(s.u===V.AUTO||u.u===V.AUTO)&&h.u===V.AUTO;d&&(a.width=f?n.w:n.w*a.height/n.h,o.u===V.AUTO&&c.u===V.AUTO?(a.left=0,a.right=t.w-a.width):o.u===V.AUTO?a.left=t.w-a.right-a.width:c.u===V.AUTO&&(a.right=t.w-a.left-a.width)),f&&(a.height=d?n.h:n.h*a.width/n.w,s.u===V.AUTO&&u.u===V.AUTO?(a.top=0,a.bottom=t.h-a.height):s.u===V.AUTO?a.top=t.h-a.bottom-a.height:u.u===V.AUTO&&(a.bottom=t.h-a.top-a.height))}},r.prototype.calContent=function(){return this.hasContent=!1,this._metaData?this._currentTime>=0&&this._currentTime<this._metaData.duration&&(this.hasContent=!0):this.hasContent=this.computedStyle.backgroundColor[3]>0,this.hasContent},r.prototype.renderCanvas=function(){var t=this,r=t._json,i=t._currentTime,a=t._metaData,n=t.canvas,o=t.computedStyle;e.prototype.renderCanvas.call(this);var s=this._bboxInt||this.bboxInt,c=s[0],u=s[1],l=s[2]-c,h=s[3]-u,d=0,f=0,m=o.width,p=o.height,g=o.objectFit;if(r&&n&&a&&i>=0&&i<a.duration){var v=r.w/r.h,y=m/p;if(g===ae.CONTAIN){if(y>v){var b=p*v;d+=.5*(m-b),m=b}else if(y<v){var x=m/v;f+=.5*(p-x),p=x}}else if(g===ae.COVER)if(y>v){var T=m/v;f=.5*(p-T),p=T}else if(y<v){var w=p*v;d=.5*(m-w),m=w}}var k=this.canvasCache=new xi(l,h,-c,-u);k.available=!0;var S=k.list;if(o.backgroundColor[3]>0){var E=this.getBackgroundCoords(c,u);S.forEach(function(e){var t=e.x,r=e.y,i=e.os.ctx;i.fillStyle=fe(o.backgroundColor),i.beginPath(),ba(i,E,-t,-r),i.closePath(),i.fill()})}for(var C=0,A=S.length;C<A;C++){var _=S[C],M=_.x,I=_.y,R=_.os.ctx,P=-M,O=-I;n&&R.drawImage(n,P+d,O+f,m,p)}},r.prototype.calContentLoading=function(){var t=e.prototype.calContentLoading.call(this);return t?this._currentTime>=0&&this._metaData&&this._currentTime<this._metaData.duration?t:0:t},r.prototype.release=function(){e.prototype.release.call(this);var t=this.lottie;t&&t.destroy()},r.prototype.timeAnimate=function(e,t){var r;null===(r=this.timeAnimation)||void 0===r||r.remove();var i=this.timeAnimation=new Ha(this,e,t);return this.initAnimate(i,t)},Object.defineProperty(r.prototype,"src",{get:function(){return this._src},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"json",{get:function(){return this._json},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"currentTime",{get:function(){return this._currentTime},set:function(e){if(this._currentTime!==e){this._currentTime=e;var t=this._lottie;t&&(t.goToAndStop(e),this.refresh())}},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"duration",{get:function(){var e;return(null===(e=this._metaData)||void 0===e?void 0:e.duration)||0},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"metaData",{get:function(){return this._metaData},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"lottie",{get:function(){return this._lottie},enumerable:!1,configurable:!0}),r}(ka);!function(e){e[e.INIT=0]="INIT",e[e.FRAME=1]="FRAME",e[e.END=2]="END"}(_f||(_f={})),function(e){e[e.PROGRESS=0]="PROGRESS",e[e.FINISH=1]="FINISH",e[e.ERROR=2]="ERROR"}(Mf||(Mf={}));var Lf,Nf=0,Uf=0,zf=[],Wf=0,Vf=0;function Hf(e,t,r){var i=t.numberOfChannels,a=t.sampleRate;if(e&&"configured"===e.state&&r){var n=Math.floor(.001*r*a);if(n>Wf){for(var o=n-Wf,s=new Float32Array(o*zf.length),c=0;c<zf.length;c++){var u=zf[c].subarray(Wf,n);s.set(u,c*o)}var l=new AudioData({format:"f32-planar",sampleRate:a,numberOfFrames:o,numberOfChannels:i,timestamp:Vf,data:s});Wf=n,Vf=r,e.encode(l)}}}var Xf=function(e){return i(void 0,void 0,void 0,function(){var t,r,i,n,o,s,c,u,l,h,d,f,m,p,g,v,y,b,x,T,w,k,S,E,C,A,_,M,I,R,P;return a(this,function(a){switch(a.label){case 0:if(t=e.data,r=t.type,i=t.isWorker,n=function(e){var t={type:Mf.ERROR,error:e};return i&&self.postMessage(t),{data:t}},Nf>=0&&(Lf=new Promise(function(e){Bf=e})),r!==_f.INIT)return[3,2];if(Lf=void 0,Nf=e.data.encoderFrameQue||0,Uf=0,Nf>=0&&(Lf=new Promise(function(e){Bf=e})),If&&(If.close(),If=void 0),Rf&&(Rf.close(),Rf=void 0),o=function(){if(Lf&&(! --Uf||Uf<Nf)){var e={type:Mf.PROGRESS};i&&self.postMessage(e),Bf({data:e})}},s=null===(R=e.data.videoEncoderConfig)||void 0===R?void 0:R.codec,c=void 0,c=/^vp/.test(s)?new kd:new xd,Pf=new Pd({format:c,target:new ld}),/^vp8/.test(s)?Of=new Cd("vp8"):/^vp09\./.test(s)?Of=new Cd("vp9"):/^av01\./.test(s)?Of=new Cd("av1"):/^hev1\./.test(s)||/^hvc1\./.test(s)?Of=new Cd("hevc"):(/^avc1\./.test(s)||/^avc3\./.test(s))&&(Of=new Cd("avc")),Of&&(Pf.addVideoTrack(Of),If=new VideoEncoder({output:function(t,r){var i=ss.fromEncodedChunk(t);Of.add(i,r),Rf&&Hf(Rf,e.data.audioEncoderConfig,.001*t.timestamp),o()},error:function(e){n(e.message)}}),If.configure(e.data.videoEncoderConfig)),u=null===(P=e.data.audioEncoderConfig)||void 0===P?void 0:P.codec,e.data.mute?Df=void 0:/^mp3/.test(u)?Df=new _d("mp3"):/^flac/.test(u)?Df=new _d("flac"):/^opus/.test(u)?Df=new _d("opus"):/^vorbis/.test(u)?Df=new _d("vorbis"):/^pcm-/.test(u)?Df=new _d(u):/^mp4a\./.test(u)?Df=new _d("aac"):/^ulaw/.test(u)?Df=new _d("ulaw"):/^alaw/.test(u)&&(Df=new _d("alaw")),Df){for(Pf.addAudioTrack(Df),Rf=new AudioEncoder({output:function(e,t){var r=ss.fromEncodedChunk(e);Df.add(r,t)},error:function(e){n(e.message)}}),Rf.configure(e.data.audioEncoderConfig),zf.splice(0),l=e.data.audioEncoderConfig.sampleRate*Math.ceil(.001*e.data.duration),g=0;g<e.data.audioEncoderConfig.numberOfChannels;g++)zf.push(new Float32Array(l));Wf=0,Vf=0}return[4,Pf.start()];case 1:return a.sent(),[3,15];case 2:return r!==_f.FRAME?[3,10]:(Uf++,h=e.data.videoFrame,If&&"configured"===If.state&&h?If.encodeQueueSize>5?[4,Xd(100)]:[3,8]:[3,9]);case 3:a.sent(),oe.warn("encodeQueueSize: "+If.encodeQueueSize),g=0,a.label=4;case 4:return g<20?If.encodeQueueSize>5?[4,Xd(100)]:[3,6]:[3,8];case 5:return a.sent(),oe.warn("encodeQueueSize: "+If.encodeQueueSize+", "+g),[3,7];case 6:return[3,8];case 7:return g++,[3,4];case 8:If.encode(h),a.label=9;case 9:if(null==h||h.close(),Rf){if((d=e.data.audioList).length&&d.length)for(f=e.data.audioEncoderConfig,m=f.numberOfChannels,p=f.sampleRate,g=0,v=d.length;g<v;g++)for(y=d[g],b=y.audioChunk,x=y.volume,T=Math.round(.001*b.timestamp*p),w=b.numberOfFrames,k=0;k<m;k++)for(S=zf[k],E=b.channels[k],C=0;C<w;C++)_=S[A=T+C]+E[C]*x,S[A]=Math.max(-1,Math.min(1,_));Hf(Rf,e.data.audioEncoderConfig,e.data.timestamp)}return!Lf||Uf<Nf?(I={type:Mf.PROGRESS},i&&self.postMessage(I),[2,{data:I}]):[2,Lf];case 10:return r!==_f.END?[3,15]:If&&Pf?[4,If.flush()]:[2];case 11:return a.sent(),If.close(),If=void 0,"configured"!==(null==Rf?void 0:Rf.state)?[3,13]:(Hf(Rf,e.data.audioEncoderConfig,e.data.timestamp),[4,Rf.flush()]);case 12:a.sent(),Rf.close(),Rf=void 0,a.label=13;case 13:return[4,Pf.finalize()];case 14:if(a.sent(),M=Pf.target.buffer,Pf=void 0,I={type:Mf.FINISH,buffer:M},!i)return[2,{data:I}];self.postMessage(I,[M]),a.label=15;case 15:return[2]}})})};function jf(e,t,r){return i(this,void 0,void 0,function(){var i,n,o,s,c,u;return a(this,function(a){switch(a.label){case 0:return e.numberOfChannels===t&&e.sampleRate===r?[2,e]:(i=Math.round(e.length*r/e.sampleRate),n=new OfflineAudioContext(t,i,r),o=n.createBufferSource(),1===e.numberOfChannels&&2===t?(s=new OfflineAudioContext(2,e.length,e.sampleRate),c=s.createBuffer(2,e.length,e.sampleRate),u=e.getChannelData(0),c.copyToChannel(u,0,0),c.copyToChannel(u,1,0),o.buffer=c):o.buffer=e,o.connect(n.destination),o.start(0),[4,n.startRendering()]);case 1:return[2,a.sent()]}})})}function Gf(e,t,r){var i=Math.floor(.001*t*e.sampleRate),a=Math.min(Math.ceil(.001*r*e.sampleRate),e.length);if(i>a||i>=e.length)throw new Error("Invalid range");if(0===i&&a>=e.length-1)return e;for(var n=new OfflineAudioContext(e.numberOfChannels,a-i+1,e.sampleRate).createBuffer(e.numberOfChannels,a-i+1,e.sampleRate),o=0;o<e.numberOfChannels;o++){var s=e.getChannelData(o).subarray(i,a+1);n.copyToChannel(s,o,0)}return n}self.onmessage=Xf;var Yf,qf,Kf,$f={stereo2Mono:function(e,t){for(var r=e.length,i=new Float32Array(r),a=0;a<r;a++)i[a]=.5*(e[a]+t[a]);return i},extractAudioBuffer:function(e,t,r){var i=e.sampleRate,a=e.numberOfChannels,n=Math.floor(.001*t*i),o=Math.min(Math.ceil(.001*r*i),e.length),s=o-n;if(!(s<=0)){for(var c=1e3*n/i,u=1e3*s/i,l=[],h=0;h<a;h++){var d=e.getChannelData(h).subarray(n,o);l.push(new Float32Array(d))}return{format:"f32-planar",channels:l,numberOfFrames:s,startFrame:n,endFrame:o,sampleRate:i,numberOfChannels:a,timestamp:c,duration:u}}},reSample:jf,sliceAudioBuffer:Gf,convertS16ToFloat32:function(e,t){var r=new Int16Array(e instanceof ArrayBuffer?e:e.buffer);r.length!==t&&console.error("数据长度校验失败:预期 ".concat(t," 个样本,实际 Int16Array 长度为 ").concat(r.length,"。"));for(var i=new Float32Array(t),a=0;a<t;a++){var n=r[a];i[a]=n/32768}return i}},Qf=0;!function(e){e.START="start",e.PROGRESS="progress",e.FINISH="finish",e.ERROR="error"}(Kf||(Kf={}));var Zf=function(e){function r(){return e.call(this)||this}return t(r,e),r.prototype.initWorker=function(){if(!Yf)if(L.encoderWorker)Yf=new Worker(L.encoderWorker);else if(L.encoderWorkerStr){var e=new Blob([L.encoderWorkerStr.trim()],{type:"application/javascript"}),t=URL.createObjectURL(e);Yf=new Worker(t)}},r.prototype.start=function(e,t){return i(this,void 0,void 0,function(){var r,n,o,s,c,u,l,h,d,f,m,p,g,v=this;return a(this,function(y){switch(y.label){case 0:if(!e.canvas)throw new Error("Root Missing appendTo canvas");return this.initWorker(),r=Object.assign({codec:"avc1.420028",width:e.width,height:e.height,bitrate:5e6,bitrateMode:"variable",framerate:30,hardwareAcceleration:"no-preference"},null==t?void 0:t.video),[4,VideoEncoder.isConfigSupported(r)];case 1:if(!(n=y.sent())||!n.supported)throw new Error("Unsupported video encoder config");return o=Object.assign({codec:"opus",sampleRate:44100,numberOfChannels:2},null==t?void 0:t.audio),s=(null==t?void 0:t.timestamp)||0,(c=(null==t?void 0:t.duration)||e.aniController.duration)&&r.framerate?(u=1e3/r.framerate,l=Math.ceil((c-s)/u),h=Math.floor(s/u),d={type:_f.INIT,messageId:Qf++,isWorker:!!L.encoderWorker||!!L.encoderWorkerStr,duration:c,num:l,videoEncoderConfig:r,audioEncoderConfig:o,mute:L.mute,encoderFrameQue:L.encoderFrameQue},Yf?(Yf.postMessage(d),[3,4]):[3,2]):[2];case 2:return[4,Xf({data:d})];case 3:y.sent(),y.label=4;case 4:this.emit(Kf.START,l),f={},m=function(t){var r;return a(this,function(n){switch(n.label){case 0:return r=(t+h)*u,e.aniController.gotoAndStop(r),p.emit(Kf.PROGRESS,t,l,!0),[4,new Promise(function(n,s){var c=function(){return i(v,void 0,void 0,function(){var i,c,h,d,m,p,g,v,y,b,x,T,w,k,S,E,C,A,_,M,I,R=this;return a(this,function(a){switch(a.label){case 0:return[4,createImageBitmap(e.canvas)];case 1:if(i=a.sent(),c=new VideoFrame(i,{timestamp:1e3*r,duration:1e3*u}),h=[],L.mute)return[3,5];d=0,m=e.aniController.aniList.length,a.label=2;case 2:return d<m?(p=e.aniController.aniList[d],g=p.delay,v=p.duration,p instanceof Ha&&p.currentTime>=g&&p.currentTime<v+g?(y=p.node)instanceof Ff||!y.volumn?[3,4]:(b=y.decoder)&&(x=b.currentGOP)&&(T=x.audioBuffer)?(w=y.id+"-"+x.index,f[w]?[3,4]:(f[w]=!0,k=x.audioTimestamp-x.timestamp,[4,jf(Gf(T,0,p.duration-x.audioTimestamp),o.numberOfChannels,o.sampleRate)])):[3,4]:[3,4]):[3,5];case 3:for(S=a.sent(),E=[],C=0;C<o.numberOfChannels;C++)A=S.getChannelData(C),E.push(A);h.push({audioChunk:{format:"f32-planar",channels:E,sampleRate:o.sampleRate,numberOfChannels:o.numberOfChannels,numberOfFrames:S.length,timestamp:r+k,duration:1e3*S.duration},volume:y.volumn}),a.label=4;case 4:return d++,[3,2];case 5:return _=function(e){e.data.type===Mf.PROGRESS?(n(),R.emit(Kf.PROGRESS,t,l,!1)):(s(e.data.error),R.emit(Kf.ERROR,e.data.error))},M={type:_f.FRAME,messageId:Qf++,isWorker:!!L.encoderWorker||!!L.encoderWorkerStr,timestamp:r,videoFrame:c,audioList:h,audioEncoderConfig:o,mute:L.mute},(I=[]).push(c),h.forEach(function(e){e.audioChunk.channels.forEach(function(e){I.push(e.buffer)})}),Yf?(Yf.onmessage=_,Yf.postMessage(M,I)):Xf({data:M}).then(function(e){_(e)}),[2]}})})};e.contentLoadingCount?e.once(Ma,c):e.rl?e.once(Aa,c):c()})];case 1:return n.sent(),[2]}})},p=this,g=0,y.label=5;case 5:return g<l?[5,m(g)]:[3,8];case 6:y.sent(),y.label=7;case 7:return g++,[3,5];case 8:return[2,new Promise(function(e){var t=function(t){t.data.type===Mf.FINISH&&e(t.data.buffer),v.emit(Kf.FINISH)},i={type:_f.END,messageId:Qf++,isWorker:!!L.encoderWorker||!!L.encoderWorkerStr,videoEncoderConfig:r,audioEncoderConfig:o,timestamp:s+u};Yf?(Yf.onmessage=t,Yf.postMessage(i)):Xf({data:i}).then(function(e){t(e)})})]}})})},r.getInstance=function(){return qf||(qf=new r),qf},r}(M),Jf=function(e){function r(t,r){void 0===r&&(r=[]);var i=e.call(this,t,r)||this;return i.root=i,i.refs={},i.structs=[],i.task=[],i.aniTask=[],i.rl=ci.NONE,i.programs={},i.frameCb=function(e){var t=i.aniTask.slice(0);t.forEach(function(t){t.onRunning(e)});var r=i.task.splice(0);r.length&&i.draw(),t.forEach(function(e){e.afterRunning()}),r.forEach(function(e){e&&e(!1)}),i.task.length||i.aniTask.length||wf.offFrame(i.frameCb)},i.audioContext=new AudioContext,i.aniController=new Ef(i.audioContext),i.contentLoadingCount=0,i.lastContentLoadingCount=0,i.firstDraw=!0,i}return t(r,e),r.prototype.appendTo=function(e){this.canvas=e;var t=Object.assign(Fa,this.props.contextAttributes),r=e.getContext("webgl2",t);if(r?this.isWebgl2=!0:(r=e.getContext("webgl",t),this.isWebgl2=!1),!r)throw new Error("Webgl unsupported!");this.appendToGl(r)},r.prototype.appendToGl=function(e){this.ctx?oe.error("Duplicate appendToGl"):(this.ctx=e,L.init(e.getParameter(e.MAX_TEXTURE_SIZE),e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),e.getParameter(e.MAX_VARYING_VECTORS)),this.initProgram(e),this.reLayout(),this.didMount(),this.structs=this.structure(0),this.asyncDraw())},r.prototype.reLayout=function(){this.checkRoot(),this.layout({w:this.computedStyle.width,h:this.computedStyle.height})},r.prototype.checkRoot=function(){var e,t=this.style,r=t.width,i=t.height,a=this.canvas;r.u===V.AUTO?a&&(r.u=V.PX,this.computedStyle.width=r.v=Math.max(1,a.width)):this.computedStyle.width=Math.max(1,this.style.width.v),i.u===V.AUTO?a&&(i.u=V.PX,this.computedStyle.height=i.v=Math.max(1,a.height)):this.computedStyle.height=Math.max(1,this.style.height.v),null===(e=this.ctx)||void 0===e||e.viewport(0,0,this.computedStyle.width,this.computedStyle.height)},r.prototype.addUpdate=function(e,t,r,i){if(void 0===r&&(r=ci.NONE),!this.isMounted)return ci.NONE;var a=r;if(t&&t.length)for(var n=0,o=t.length;n<o;n++){a|=li(t[n])}return this.calUpdate(e,a)?this.asyncDraw(i):i&&i(!0),a},r.prototype.calUpdate=function(e,t){if(t===ci.NONE||!this.isMounted)return!1;var r=function(e){return e>=ci.REFLOW}(t);if(r)e===this?this.reLayout():function(e,t){var r=e.parent;t&ci.REMOVE_DOM?e.didUnmount():(e.layout({w:r.computedStyle.width,h:r.computedStyle.height}),t&ci.ADD_DOM&&e.didMount())}(e,t);else if(t>=ci.REPAINT)e.calRepaintStyle(t);else{var i=e.style,a=e.computedStyle;t&ci.TRANSFORM_ALL&&e.calMatrix(t),t&(ci.PERSPECTIVE|ci.TRANSLATE|ci.TRANSFORM_ALL)&&e.calPerspective(),t&(ci.PERSPECTIVE_SELF|ci.TRANSLATE|ci.TRANSFORM_ORIGIN|ci.TRANSFORM_ALL)&&e.calPerspectiveSelf(),t&ci.OPACITY&&e.calOpacity(),t&ci.FILTER&&e.calFilter(t),t&ci.MIX_BLEND_MODE&&(a.mixBlendMode=i.mixBlendMode.v);var n=!1;if(t&ci.MASK&&(e.clearMask(),n=!0,e.calMask()),t&ci.BREAK_MASK){var o=e.mask;e.calMask();var s=e.mask;if(a.breakMask&&o?o.clearMask():!a.breakMask&&s||(t&=ci.FULL^ci.BREAK_MASK),!a.breakMask||o)for(var c=e.prev;c;){if(c.computedStyle.maskMode){c.clearMask();break}if(c.computedStyle.breakMask)break;c=c.prev}}a.maskMode&&!n&&t&&e.clearMask()}e.clearTexCacheUpward(),e.refreshLevel|=t,this.rl|=t;var u=e.mask;!u||t&ci.MASK||t&ci.BREAK_MASK||u.clearMask();for(var l=e.parent;l;){if(l.computedStyle.visibility===te.HIDDEN)return!1;l=l.parent}return t>ci.NONE},r.prototype.asyncDraw=function(e){var t=this.task,r=this.aniTask;t.length||r.length||wf.onFrame(this.frameCb),t.push(e)},r.prototype.cancelAsyncDraw=function(e){var t=this.task,r=this.aniTask,i=t.indexOf(e);i>-1&&(t.splice(i,1),t.length||r.length||wf.offFrame(this.frameCb))},r.prototype.addAnimation=function(e){var t=this.task,r=this.aniTask;t.length||r.length||wf.onFrame(this.frameCb),-1===r.indexOf(e)&&r.push(e)},r.prototype.removeAnimation=function(e){var t=this.task,r=this.aniTask,i=r.indexOf(e);i>-1&&(r.splice(i,1),t.length||r.length||wf.offFrame(this.frameCb))},r.prototype.draw=function(){this.isMounted&&(this.rl>ci.NONE&&(this.clear(),this.rl=ci.NONE,this.ctx&&(bf(this.ctx,this),this.emit("refresh"),this.contentLoadingCount?this.lastContentLoadingCount||this.emit(_a):((this.lastContentLoadingCount||this.firstDraw)&&this.emit(Ma),this.emit(Aa)),this.lastContentLoadingCount=this.contentLoadingCount,this.firstDraw=!1)))},r.prototype.clear=function(){var e=this.ctx;e&&(e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT))},r.prototype.initProgram=function(e){var t=this.isWebgl2;this.programs.main=new Va(e,Ti(e,"#define GLSLIFY 1\nattribute vec4 a_position;varying vec4 v_position;attribute vec2 a_texCoords;varying vec2 v_texCoords;void main(){gl_Position=vec4(a_position.xy,0,a_position.z);v_position=gl_Position;v_texCoords=a_texCoords;}","#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec4 v_position;varying vec2 v_texCoords;uniform float u_opacity;uniform sampler2D u_texture;void main(){if(u_opacity<=0.0){discard;}vec4 color=texture2D(u_texture,v_texCoords);if(color.a<=0.0){discard;}gl_FragColor=color*u_opacity;}"),{uniform:["u_clip","u_texture","u_opacity"],attrib:["a_position","a_texCoords"]}),t&&(this.programs.pr=new Va(e,Ti(e,"#version 300 es\n#define GLSLIFY 1\nin vec3 a_position;in vec2 a_texCoords;in float a_opacity;in float a_textureIndex;in vec4 a_clip;out vec4 v_position;out vec2 v_texCoords;out float v_opacity;out float v_textureIndex;out vec4 v_clip;void main(){gl_Position=vec4(a_position.xy,0,a_position.z);v_position=gl_Position;v_texCoords=a_texCoords;v_opacity=a_opacity;v_textureIndex=a_textureIndex;v_clip=a_clip;}","#version 300 es\n#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nin vec4 v_position;in vec2 v_texCoords;in float v_opacity;in float v_textureIndex;out vec4 fragColor;uniform sampler2D u_texture[16];void main(){if(v_opacity<=0.0){discard;}vec4 color;if(v_textureIndex==0.0){color=texture(u_texture[0],v_texCoords);}else if(v_textureIndex==1.0){color=texture(u_texture[1],v_texCoords);}else if(v_textureIndex==2.0){color=texture(u_texture[2],v_texCoords);}else if(v_textureIndex==3.0){color=texture(u_texture[3],v_texCoords);}else if(v_textureIndex==4.0){color=texture(u_texture[4],v_texCoords);}else if(v_textureIndex==5.0){color=texture(u_texture[5],v_texCoords);}else if(v_textureIndex==6.0){color=texture(u_texture[6],v_texCoords);}else if(v_textureIndex==7.0){color=texture(u_texture[7],v_texCoords);}else if(v_textureIndex==8.0){color=texture(u_texture[8],v_texCoords);}else if(v_textureIndex==9.0){color=texture(u_texture[9],v_texCoords);}else if(v_textureIndex==10.0){color=texture(u_texture[10],v_texCoords);}else if(v_textureIndex==11.0){color=texture(u_texture[11],v_texCoords);}else if(v_textureIndex==12.0){color=texture(u_texture[12],v_texCoords);}else if(v_textureIndex==13.0){color=texture(u_texture[13],v_texCoords);}else if(v_textureIndex==14.0){color=texture(u_texture[14],v_texCoords);}else if(v_textureIndex==15.0){color=texture(u_texture[15],v_texCoords);}fragColor=color*v_opacity;}"),{uniform:["u_texture[0]","u_texture[1]","u_texture[2]","u_texture[3]","u_texture[4]","u_texture[5]","u_texture[6]","u_texture[7]","u_texture[8]","u_texture[9]","u_texture[10]","u_texture[11]","u_texture[12]","u_texture[13]","u_texture[14]","u_texture[15]"],attrib:["a_position","a_texCoords","a_opacity","a_clip","a_textureIndex"]})),this.programs.box=new Va(e,Ti(e,kf,"#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec2 v_texCoords;uniform sampler2D u_texture;uniform float u_pw;uniform float u_ph;uniform int u_r;uniform int u_direction;const int MAX_KERNEL_SIZE=1024;void main(){vec4 color=texture2D(u_texture,v_texCoords);float total=1.0;if(u_r==0){if(u_direction==0){color+=texture2D(u_texture,vec2(v_texCoords.x+u_pw,v_texCoords.y))*0.125;color+=texture2D(u_texture,vec2(v_texCoords.x-u_pw,v_texCoords.y))*0.125;}else{color+=texture2D(u_texture,vec2(v_texCoords.x,v_texCoords.y+u_ph))*0.125;color+=texture2D(u_texture,vec2(v_texCoords.x,v_texCoords.y-u_ph))*0.125;}total+=0.25;}else{for(int i=1;i<MAX_KERNEL_SIZE;i++){if(u_direction==0){float offset=float(i)*u_pw;color+=texture2D(u_texture,vec2(v_texCoords.x+offset,v_texCoords.y));color+=texture2D(u_texture,vec2(v_texCoords.x-offset,v_texCoords.y));}else{float offset=float(i)*u_ph;color+=texture2D(u_texture,vec2(v_texCoords.x,v_texCoords.y+offset));color+=texture2D(u_texture,vec2(v_texCoords.x,v_texCoords.y-offset));}total+=2.0;if(i>=u_r){break;}}}gl_FragColor=color/total;}"),{uniform:["u_texture","u_pw","u_ph","u_r","u_direction"],attrib:["a_position","a_texCoords"]}),this.programs.dualDown=new Va(e,Ti(e,kf,"#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec2 v_texCoords;uniform vec2 u_xy;uniform sampler2D u_texture;void main(){vec4 color=texture2D(u_texture,v_texCoords);color+=texture2D(u_texture,v_texCoords+vec2(u_xy.x,u_xy.y))*0.125;color+=texture2D(u_texture,v_texCoords+vec2(u_xy.x,-u_xy.y))*0.125;color+=texture2D(u_texture,v_texCoords+vec2(-u_xy.x,u_xy.y))*0.125;color+=texture2D(u_texture,v_texCoords+vec2(-u_xy.x,-u_xy.y))*0.125;gl_FragColor=color;}"),{uniform:["u_xy","u_texture"],attrib:["a_position","a_texCoords"]}),this.programs.dualUp=new Va(e,Ti(e,kf,"#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec2 v_texCoords;uniform float u_x;uniform float u_y;uniform sampler2D u_texture;void main(){vec4 color=texture2D(u_texture,v_texCoords+vec2(u_x,u_y)*0.5)*2.0;color+=texture2D(u_texture,v_texCoords+vec2(u_x,-u_y)*0.5)*2.0;color+=texture2D(u_texture,v_texCoords+vec2(-u_x,u_y)*0.5)*2.0;color+=texture2D(u_texture,v_texCoords+vec2(-u_x,-u_y)*0.5)*2.0;color+=texture2D(u_texture,v_texCoords+vec2(u_x,0.0));color+=texture2D(u_texture,v_texCoords+vec2(-u_x,0.0));color+=texture2D(u_texture,v_texCoords+vec2(0.0,u_y));color+=texture2D(u_texture,v_texCoords+vec2(0.0,-u_y));gl_FragColor=color/12.0;}"),{uniform:["u_x","u_y","u_texture"],attrib:["a_position","a_texCoords"]}),this.programs.motion=new Va(e,Ti(e,kf,"#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec2 v_texCoords;uniform sampler2D u_texture;uniform int u_kernel;uniform vec4 u_velocity;uniform int u_limit;const int MAX_KERNEL_SIZE=1024;void main(){vec4 color=texture2D(u_texture,v_texCoords+u_velocity.zw);for(int i=1;i<MAX_KERNEL_SIZE;i++){if(i>=u_kernel){break;}vec2 bias=u_velocity.xy*(float(i)/float(u_kernel));vec2 c1=v_texCoords+bias+u_velocity.zw;vec2 c2=v_texCoords-bias+u_velocity.zw;if(u_limit==1){if(c1.x<0.0){c1.x+=1.0;}else if(c1.x>1.0){c1.x-=1.0;}if(c1.y<0.0){c1.y+=1.0;}else if(c1.y>1.0){c1.y-=1.0;}if(c2.x<0.0){c2.x+=1.0;}else if(c2.x>1.0){c2.x-=1.0;}if(c2.y<0.0){c2.y+=1.0;}else if(c2.y>1.0){c2.y-=1.0;}}color+=texture2D(u_texture,c1);color+=texture2D(u_texture,c2);}gl_FragColor=color/float((u_kernel-1)*2+1);}"),{uniform:["u_kernel","u_velocity","u_texture","u_limit"],attrib:["a_position","a_texCoords"]}),this.programs.radial=new Va(e,Ti(e,kf,"#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec2 v_texCoords;uniform sampler2D u_texture;uniform int u_kernel;uniform vec2 u_center;uniform float u_ratio;const int MAX_KERNEL_SIZE=1024;void main(void){if(v_texCoords.x==u_center.x&&v_texCoords.y==u_center.y){gl_FragColor=texture2D(u_texture,v_texCoords);return;}vec4 color=texture2D(u_texture,v_texCoords);int k=u_kernel-1;float total=1.0;for(int i=1;i<MAX_KERNEL_SIZE-1;i++){if(i>=k){break;}total++;vec2 velocity=-(v_texCoords-u_center)*u_ratio;vec2 bias=velocity*(float(i)/float(k));color+=texture2D(u_texture,v_texCoords+bias);}gl_FragColor=color/total;}"),{uniform:["u_kernel","u_center","u_ratio","u_texture"],attrib:["a_position","a_texCoords"]}),this.programs.cm=new Va(e,Ti(e,kf,"#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec2 v_texCoords;uniform sampler2D u_texture;uniform float u_m[20];void main(){vec4 c=texture2D(u_texture,v_texCoords);if(c.a>0.0){c.rgb/=c.a;}vec4 result;result.r=(u_m[0]*c.r);result.r+=(u_m[1]*c.g);result.r+=(u_m[2]*c.b);result.r+=(u_m[3]*c.a);result.r+=u_m[4];result.g=(u_m[5]*c.r);result.g+=(u_m[6]*c.g);result.g+=(u_m[7]*c.b);result.g+=(u_m[8]*c.a);result.g+=u_m[9];result.b=(u_m[10]*c.r);result.b+=(u_m[11]*c.g);result.b+=(u_m[12]*c.b);result.b+=(u_m[13]*c.a);result.b+=u_m[14];result.a=(u_m[15]*c.r);result.a+=(u_m[16]*c.g);result.a+=(u_m[17]*c.b);result.a+=(u_m[18]*c.a);result.a+=u_m[19];gl_FragColor=vec4(result.rgb*result.a,result.a);}"),{uniform:["u_m","u_m[0]","u_texture"],attrib:["a_position","a_texCoords"]}),this.programs.mask=new Va(e,Ti(e,kf,"#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec2 v_texCoords;uniform sampler2D u_texture1;uniform sampler2D u_texture2;void main(){vec4 color1=texture2D(u_texture1,v_texCoords);if(color1.a<=0.0){discard;}vec4 color2=texture2D(u_texture2,v_texCoords);if(color2.a<=0.0){discard;}gl_FragColor=color2*color1.a;}"),{uniform:["u_texture1","u_texture2"],attrib:["a_position","a_texCoords"]}),this.programs.maskGray=new Va(e,Ti(e,kf,"#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec2 v_texCoords;uniform sampler2D u_texture1;uniform sampler2D u_texture2;uniform vec2 u_d;void main(){vec4 color1=texture2D(u_texture1,v_texCoords);if(color1.a<=0.0){discard;}vec4 color2=texture2D(u_texture2,v_texCoords+u_d);if(color2.a<=0.0){discard;}float gray=max(color1.r,max(color1.g,color1.b));gl_FragColor=color2*color1.a*gray;}"),{uniform:["u_texture1","u_texture2","u_d"],attrib:["a_position","a_texCoords"]}),this.programs.bloom=new Va(e,Ti(e,kf,"#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec2 v_texCoords;uniform sampler2D u_texture1;uniform sampler2D u_texture2;vec3 ACESFilm(vec3 x){float a=2.51;float b=0.03;float c=2.43;float d=0.59;float e=0.14;return clamp((x*(a*x+b))/(x*(c*x+d)+e),0.0,1.0);}void main(){vec3 sceneColor=texture2D(u_texture1,v_texCoords).rgb;sceneColor=pow(sceneColor,vec3(2.2));vec3 bloomColor=texture2D(u_texture2,v_texCoords).rgb;vec3 result=sceneColor+bloomColor;result=ACESFilm(result);result=pow(result,vec3(1.0/2.2));gl_FragColor=vec4(result,1.0);}"),{uniform:["u_texture1","u_texture2","u_threshold"],attrib:["a_position","a_texCoords"]}),this.programs.bloomBlur=new Va(e,Ti(e,kf,"#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec2 v_texCoords;uniform sampler2D u_texture;uniform float u_threshold;uniform float u_knee;void main(){vec4 color=texture2D(u_texture,v_texCoords);vec3 linearColor=pow(color.rgb,vec3(2.2));float brightness=dot(linearColor,vec3(0.299,0.587,0.114));float k=u_threshold*u_knee;float soft=brightness-u_threshold+k;soft=clamp(soft,0.0,2.0*k);soft=(soft*soft)/(4.0*k+0.0001);float factor=max(soft,brightness-u_threshold)/max(brightness,0.0001);vec3 brightPart=linearColor*factor;gl_FragColor=vec4(brightPart,1.0);}"),{uniform:["u_texture","u_threshold"],attrib:["a_position","a_texCoords"]}),this.programs.dualDown13=new Va(e,Ti(e,kf,"#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec2 v_texCoords;uniform vec2 u_xy;uniform sampler2D u_texture;void main(){vec4 color=texture2D(u_texture,v_texCoords)*0.125;color+=texture2D(u_texture,v_texCoords+vec2(u_xy.x,u_xy.y))*0.125;color+=texture2D(u_texture,v_texCoords+vec2(u_xy.x,-u_xy.y))*0.125;color+=texture2D(u_texture,v_texCoords+vec2(-u_xy.x,u_xy.y))*0.125;color+=texture2D(u_texture,v_texCoords+vec2(-u_xy.x,-u_xy.y))*0.125;color+=texture2D(u_texture,v_texCoords+vec2(u_xy.x*2.0,u_xy.y*2.0))*0.03125;color+=texture2D(u_texture,v_texCoords+vec2(u_xy.x*2.0,-u_xy.y*2.0))*0.03125;color+=texture2D(u_texture,v_texCoords+vec2(-u_xy.x*2.0,u_xy.y*2.0))*0.03125;color+=texture2D(u_texture,v_texCoords+vec2(-u_xy.x*2.0,-u_xy.y*2.0))*0.03125;color+=texture2D(u_texture,v_texCoords+vec2(u_xy.x*2.0,0))*0.0625;color+=texture2D(u_texture,v_texCoords+vec2(-u_xy.x*2.0,0))*0.0625;color+=texture2D(u_texture,v_texCoords+vec2(0,u_xy.y*2.0))*0.0625;color+=texture2D(u_texture,v_texCoords+vec2(0,-u_xy.y*2.0))*0.0625;gl_FragColor=color;}"),{uniform:["u_xy","u_texture"],attrib:["a_position","a_texCoords"]}),this.programs.dualUp13=new Va(e,Ti(e,kf,"#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec2 v_texCoords;uniform vec2 u_xy;uniform sampler2D u_texture1;uniform sampler2D u_texture2;void main(){vec4 color1=texture2D(u_texture1,v_texCoords);vec4 color2=texture2D(u_texture2,v_texCoords)*0.25;color2+=texture2D(u_texture2,v_texCoords+vec2(u_xy.x,u_xy.y))*0.125;color2+=texture2D(u_texture2,v_texCoords+vec2(u_xy.x,-u_xy.y))*0.125;color2+=texture2D(u_texture2,v_texCoords+vec2(-u_xy.x,u_xy.y))*0.125;color2+=texture2D(u_texture2,v_texCoords+vec2(-u_xy.x,-u_xy.y))*0.125;color2+=texture2D(u_texture2,v_texCoords+vec2(u_xy.x,0))*0.0625;color2+=texture2D(u_texture2,v_texCoords+vec2(-u_xy.x,0))*0.0625;color2+=texture2D(u_texture2,v_texCoords+vec2(0,u_xy.y))*0.0625;color2+=texture2D(u_texture2,v_texCoords+vec2(0,-u_xy.y))*0.0625;gl_FragColor=vec4(color1.rgb+color2.rgb*0.6,1.0);}"),{uniform:["u_xy","u_texture1","u_texture2"],attrib:["a_position","a_texCoords"]}),this.programs.lightDark=new Va(e,Ti(e,kf,"#ifdef GL_ES\nprecision mediump float;\n#define GLSLIFY 1\n#endif\nvarying vec2 v_texCoords;uniform sampler2D u_texture;uniform vec2 u_velocity;uniform int u_radius;const int MAX_KERNEL_SIZE=1024;void main(){vec4 color=texture2D(u_texture,v_texCoords);float total=float(u_radius);for(int i=1;i<MAX_KERNEL_SIZE;i++){if(i>u_radius){break;}vec2 bias=u_velocity.xy*float(i);vec2 bias1=v_texCoords+bias;vec2 bias2=v_texCoords-bias;float add=0.0;float reduce=0.0;if(bias1.x<0.0||bias1.x>1.0||bias1.y<0.0||bias1.y>1.0){add=1.0;}else{add=1.0-texture2D(u_texture,bias1).a;}if(bias2.x<0.0||bias2.x>1.0||bias2.y<0.0||bias2.y>1.0){reduce=-1.0;}else{reduce=texture2D(u_texture,bias2).a-1.0;}if(add>0.0){float f=(total-float(i))/total/total;color.r+=add*f;color.g+=add*f;color.b+=add*f;}if(reduce<0.0){float f=(total-float(i))/total/total;color.r+=reduce*f;color.g+=reduce*f;color.b+=reduce*f;}}gl_FragColor=vec4(clamp(0.0,color.r,1.0),clamp(0.0,color.g,1.0),clamp(0.0,color.b,1.0),color.a);}"),{uniform:["u_texture","u_velocity","u_radius"],attrib:["a_position","a_texCoords"]}),Va.useProgram(e,this.programs.main)},r.prototype.encode=function(e){return i(this,void 0,void 0,function(){return a(this,function(t){return[2,Zf.getInstance().start(this,e)]})})},r}(Ba),em=function(){function e(e,t,r,i,a){void 0===i&&(i=!1),void 0===a&&(a=!1),this.x=0,this.y=e,this.w=0,this.h=t,this.index=r,this.list=[],this.startEnter=i,this.endEnter=a}return e.prototype.add=function(e){this.list.push(e),this.w+=e.w},e.prototype.verticalAlign=function(){for(var e=this.baseline,t=this.list,r=0,i=t.length;r<i;r++){var a=t[r],n=a.baseline;if(n!==e){var o=e-n;a.y+=o}}},e.prototype.offsetX=function(e){this.x+=e;for(var t=this.list,r=0,i=t.length;r<i;r++)t[r].x+=e},e.prototype.offsetY=function(e){this.y+=e;for(var t=this.list,r=0,i=t.length;r<i;r++)t[r].y+=e},Object.defineProperty(e.prototype,"size",{get:function(){return this.list.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"baseline",{get:function(){for(var e=0,t=this.list,r=0,i=t.length;r<i;r++)e=Math.max(e,t[r].baseline);return e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"lineHeight",{get:function(){var e=this.list;if(e.length){for(var t=0,r=0,i=e.length;r<i;r++)t=Math.max(t,e[r].lineHeight);return t}return this.h},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"width",{get:function(){return Math.ceil(this.w)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return Math.ceil(this.lineHeight)},enumerable:!1,configurable:!0}),e}(),tm=function(e,t,r,i,a,n,o,s,c,u,l,h,d,f,m,p,g,v){this.x=e,this.y=t,this.w=r,this.lineHeight=i,this.baseline=a,this.contentArea=n,this.index=o,this.str=s,this.font=c,this.fontFamily=u,this.fontSize=l,this.color=h,this.letterSpacing=d,this.textDecoration=f,this.textShadow=m,this.stroke=p,this.strokeWidth=g,this.strokeEnable=v};function rm(e){return"\n"===e||"\u2028"===e}function im(e,t,r,i,a,n,o){var s=t,c=r,u=0,l=!1,h=Math.round(a/n);for(h<=0?h=1:h>r-t&&(h=r-t);s<c;){var d=e.measureText(i.slice(t,t+h)).width;if(d===a){u=a,l=!0;break}if(d>a+1e-10){if(l=!0,1===h){u=d;break}if(s===c-1||s-t===h-1){h=s-t;break}c=h+t-1;var f=Math.round((d-a)/n);f<=0&&(f=1),(h-=f)<s-t&&(h=s-t)}else{if(u=d,h===r-t)break;s=h+t;var m=Math.round((a-d)/n);m<=0&&(m=1),(h+=m)>c-t&&(h=c-t)}}for(var p=t,g=t+h;p<g;p++)if(rm(i.charAt(p)))return{hypotheticalNum:h=p-t,rw:u=e.measureText(i.slice(t,t+h)).width,newLine:l=!1};if(t+h<r&&/[\w.-]/.test(i.charAt(t+h-1)))for(var v=t+h-2;v>t;v--)if(!/[\w.-]/.test(i.charAt(v)))return{hypotheticalNum:h=v-t+1,rw:u=e.measureText(i.slice(t,t+h)).width,newLine:l=!0};return rm(i.charAt(t+h))&&(l=!1),{hypotheticalNum:h,rw:u,newLine:l}}function am(e,t,r){void 0===r&&(r=1),1!==r?(e.font=t.font.replace(/([\d.e+-]+)px/gi,function(e,t){return t*r+"px"}),e.letterSpacing=t.letterSpacing*r+"px"):(e.font=t.font,e.letterSpacing=t.letterSpacing+"px")}var nm=1e-4,om=function(e){function i(t){var r,i=e.call(this,t)||this;return i._content=t.content.toString()||"",i.rich=((null===(r=t.rich)||void 0===r?void 0:r.slice(0))||[]).map(function(e){return ii(e,i.style)}),i.computedRich=i.rich.map(function(e){return i.calComputedRich(e)}),i.mergeRich(),i.lineBoxList=[],i.cursor={isMulti:!1,startLineBox:0,endLineBox:0,startTextBox:0,endTextBox:0,startString:0,endString:0,start:0,end:0},i.tempCursorX=0,i}return t(i,e),i.prototype.didMount=function(){e.prototype.didMount.call(this);var t=this.props.textBehaviour,r=this,i=r.style,a=r.computedStyle,n=r.parent,o=i.left,s=i.right,c=i.top,u=i.bottom,l=i.width,h=i.height,d=i.transformOrigin,f=!1;if("auto"===t&&l.u!==V.AUTO&&(o.u===V.AUTO||s.u===V.AUTO)){var m=this.width;if(l.u===V.PX?m=this.width-l.v:l.u===V.PERCENT&&(m=this.width-.01*l.v*n.width),Math.abs(m)>nm&&d[0].u===V.PERCENT){var p=this.getOffsetRect(),g=ri(l,n.width);p.left=a.left+ri(i.translateX,g),p.right=p.left+g;var v=a.textAlign;if(v===H.LEFT){var y=m*d[0].v*.01;this.adjustPosAndSizeSelf(y,0,y,0),f=!0}else if(v===H.RIGHT){y=m*d[0].v*.01;this.adjustPosAndSizeSelf(-y,0,-y,0),f=!0}}i.width={v:0,u:V.AUTO}}if(!("auto"!==t&&"autoH"!==t||h.u===V.AUTO||c.u!==V.AUTO&&u.u!==V.AUTO)){m=0;if(h.u===V.PX?m=this.height-h.v:h.u===V.PERCENT&&(m=this.height-.01*h.v*n.height),Math.abs(m)>nm&&d[1].u===V.PERCENT){p=this.getOffsetRect();var b=ri(h,n.height);p.top=a.top+ri(i.translateY,b),p.bottom=p.top+b;var x=a.textVerticalAlign;if(x===X.TOP){y=m*d[1].v*.01;this.adjustPosAndSizeSelf(0,y,0,y),f=!0}else if(x===X.BOTTOM){y=m*d[1].v*.01;this.adjustPosAndSizeSelf(0,-y,0,-y),f=!0}}i.height={v:0,u:V.AUTO}}f&&this.checkPosSizeUpward()},i.prototype.lay=function(t){var r=this;e.prototype.lay.call(this,t);var i=this,a=i.computedRich,n=i.style,o=i.computedStyle,s=i._content,c=i.lineBoxList,u=n.left,l=n.right,h=n.top,d=n.bottom,f=n.width,m=n.height,p=f.u===V.AUTO&&(u.u===V.AUTO||l.u===V.AUTO),g=m.u===V.AUTO&&(h.u===V.AUTO||d.u===V.AUTO);if(!this.isMounted){var v=this.props.textBehaviour;"auto"!==v||f.u===V.AUTO||u.u!==V.AUTO&&l.u!==V.AUTO||(p=!0),"auto"!==v&&"autoH"!==v||m.u===V.AUTO||h.u!==V.AUTO&&d.u!==V.AUTO||(g=!0)}var y,b,x,T,w,k,S,E,C,A,_,M,I,R,P=0,O=s.length,D=0,B=0,F=0,L={};if(a.length)for(var N=0,U=a.length;N<U;N++){var z=a[N];L[z.location]=N;var W=z.fontFamily;Xe.waitIfNotRegister(W,function(){r.refresh(ci.REFLOW)})}else{W=o.fontFamily;Xe.waitIfNotRegister(W,function(){r.refresh(ci.REFLOW)})}var j=oe.getFontCanvas().ctx;if(a.length){var G=a[0];b=G.letterSpacing||0,x=G.paragraphSpacing||0,y=.8*G.fontSize+b,w=$r(G,T=G.lineHeight||Kr(G)),k=Qr(G,T),S=G.fontFamily,E=G.fontSize,C=fe(G.color),A=G.textDecoration||[],_=G.textShadow,M=G.stroke,I=G.strokeWidth,R=G.strokeEnable,j.font=Yr(G),j.letterSpacing=b+"px"}else b=o.letterSpacing,x=o.paragraphSpacing,y=.8*o.fontWeight+b,w=$r(o,T=o.lineHeight||Kr(o)),k=Qr(o,T),S=o.fontFamily,E=o.fontSize,C=fe(this.style.color.v),A=this.style.textDecoration.map(function(e){return e.v}),_=this.style.textShadow.v,M=va(this.style.stroke),I=this.style.strokeWidth.map(function(e){return e.v}),R=this.style.strokeEnable.map(function(e){return e.v}),j.font=Yr(o),j.letterSpacing=b+"px";var Y=new em(F,T,P,!1);c.splice(0),c.push(Y);for(var q=p?Number.MAX_SAFE_INTEGER:this.width;P<O;){var K=L[P];if(P&&K){var $=a[K];b=$.letterSpacing||0,x=$.paragraphSpacing||0,y=.8*$.fontSize+b,w=$r($,T=$.lineHeight||Kr($)),k=Qr($,T),S=$.fontFamily,E=$.fontSize,C=fe($.color),A=$.textDecoration||[],_=$.textShadow,M=$.stroke,I=$.strokeWidth,R=$.strokeEnable,j.font=Yr($),j.letterSpacing=b+"px"}if(rm(s.charAt(P)))P++,B=0,F+=Y.height+x,Y.verticalAlign(),Y.endEnter=!0,Y=new em(F,T,P,!0),c.push(Y);else{U=O;if(a.length)for(var Q=P+1;Q<U;Q++)if(L[Q]){U=Q;break}if(j.measureText(s.charAt(P)).width>q-B+1e-10&&B)B=0,F+=Y.height,P<O&&(Y.verticalAlign(),Y=new em(F,T,P,!1),c.push(Y));else{var Z=im(j,P,U,s,q-B,y),J=Z.hypotheticalNum,ee=Z.rw,te=Z.newLine,re=new tm(B,F,ee,T,w,k,P,s.slice(P,P+J),j.font,S,E,C,b,A,_,M,I,R);Y.add(re),P+=J,D=Math.max(D,Math.ceil(ee+B)),te?(B=0,F+=Y.height,P<O&&(Y.verticalAlign(),Y=new em(F,T,P,!1),c.push(Y))):B+=ee}}}if((Y.verticalAlign(),D=Math.max(D,Y.width),b&&b<0&&(D-=b),p)&&(ve=D-this.width)){o.width=D;var ie=n.left,ae=n.right;ie.u!==V.AUTO&&ae.u!==V.AUTO||(ie.u!==V.AUTO?o.right-=ve:ae.u!==V.AUTO&&(o.left-=ve))}if(g){var ne=Y.y+Y.height;if(ve=ne-this.height){o.height=ne;var se=n.top,ce=n.bottom;se.u!==V.AUTO&&ce.u!==V.AUTO||(se.u!==V.AUTO?o.bottom-=ve:ce.u!==V.AUTO&&(o.top-=ve))}}if(a&&a.length){var ue={};a.forEach(function(e){ue[e.location]=e});var le=a[0].textAlign,he=0;for(U=c.length;he<U;he++){var de=c[he];if(de.startEnter||!de.index){var me=ue[de.index];me&&(le=me.textAlign)}if(le===H.CENTER)(ve=this.width-de.width)&&de.offsetX(.5*ve);else if(le===H.RIGHT){(ve=this.width-de.width)&&de.offsetX(ve)}}}else if(s&&o.textAlign!==H.LEFT){var pe=0;for(U=c.length;pe<U;pe++){var ge=c[pe];if(o.textAlign===H.CENTER)(ve=this.width-ge.width)&&ge.offsetX(.5*ve);else if(o.textAlign===H.RIGHT){var ve;(ve=this.width-ge.width)&&ge.offsetX(ve)}}}var ye=this.height-Y.y-Y.height;if(ye){var be=o.textVerticalAlign;if(be===X.MIDDLE){var xe=0;for(U=c.length;xe<U;xe++){c[xe].offsetY(.5*ye)}}else if(be===X.BOTTOM){var Te=0;for(U=c.length;Te<U;Te++){c[Te].offsetY(ye)}}}},i.prototype.cutRich=function(e,t){var r=this.rich;if(r.length){for(var i=t-e,a=0,n=r.length;a<n;a++){var o=r[a];if(o.location<=e&&o.location+o.length>e){if(o.location+o.length>=t){o.length-=i;for(var s=a+1;s<n;s++)r[s].location-=i;o.length||r.splice(a,1)}else{o.length=e-o.location;for(var c=a+1,u=r.length;c<u;c++){var l=r[c];if(l.location<=t&&(l.location+l.length>t||c===u-1)){l.length-=t-l.location,l.location-=i;s=c+1;for(var h=r.length;s<h;s++)r[s].location-=i;a<c-1&&r.splice(a+1,c-a-1),l.length||r.splice(c,1);break}}o.length||r.splice(a,1)}break}}this.mergeRich()}},i.prototype.expandRich=function(e,t){var r=this,i=r.rich,a=r.computedRich,n=r.style,o=r._content;if(!i.length){var s={location:e,length:t,fontFamily:n.fontFamily,fontSize:n.fontSize,fontWeight:n.fontWeight,fontStyle:n.fontStyle,letterSpacing:n.letterSpacing,lineHeight:n.lineHeight,paragraphSpacing:n.paragraphSpacing,textAlign:n.textAlign,textDecoration:n.textDecoration,textShadow:n.textShadow,color:n.color,stroke:n.stroke.slice(0),strokeEnable:n.strokeEnable.slice(0),strokeWidth:n.strokeWidth.slice(0)};return i.push(s),void a.push(this.calComputedRich(s))}e=Math.max(0,e);for(var c=0,u=i.length;c<u;c++){var l=i[c];if(l.location<=e&&l.location+l.length>=e){if(e===l.location+l.length&&rm(o.charAt(e-1)))continue;l.length+=t,a[c].length+=t;for(var h=c+1;h<u;h++)i[h].location+=t,a[h].location+=t;return}}i[i.length-1].length+=t,a[a.length-1].length+=t},i.prototype.insertRich=function(e,t,r){var i=this,a=i.rich,n=i.computedRich,o=i.style,s=Object.assign({location:t,length:r,fontFamily:o.fontFamily,fontSize:o.fontSize,fontWeight:o.fontWeight,fontStyle:o.fontStyle,letterSpacing:o.letterSpacing,lineHeight:o.lineHeight,paragraphSpacing:o.paragraphSpacing,textAlign:o.textAlign,textDecoration:o.textDecoration,textShadow:o.textShadow,color:o.color,stroke:o.stroke,strokeEnable:o.strokeEnable,strokeWidth:o.strokeWidth},e),c=this.calComputedRich(s);if(!a.length)return a.push(s),void n.push(c);for(var u=0,l=a.length;u<l;u++){var h=a[u];if(h.location<=t&&h.location+h.length>=t){for(var d=u+1;d<l;d++)a[d].location+=r,n[d].location+=r;if(h.location===t)a.splice(u,0,s),n.splice(u,0,c),h.location+=r,n[u].location+=r;else if(h.location+h.length===t)a.splice(u+1,0,s),n.splice(u+1,0,c);else if(h.location+h.length>t){var f=C(h);h.length=t-h.location,f.location=t+r,f.length-=h.length,a.splice(u+1,0,s),a.splice(u+2,0,f);var m=n[u],p=C(m);m.length=h.length,p.location=f.location,p.length=f.length,n.splice(u+1,0,c),n.splice(u+2,0,p)}return void this.mergeRich()}}a.push(s),n.push(c),this.mergeRich()},i.prototype.mergeRich=function(){var e=this,t=e.rich,i=e.computedRich,a=e._content,n=e.style;if(t.length){for(var o=t.length-1;o>=0;o--){var s=t[o];(s.location<0||s.length<=0)&&(t.splice(o,1),i.splice(o,1))}t.sort(function(e,t){return e.location===t.location?e.length-t.length:e.location-t.location}),i.sort(function(e,t){return e.location===t.location?e.length-t.length:e.location-t.location});var c=!1,u=ii({location:0,length:0},n);if(a.length){var l=t[t.length-1],h=i[i.length-1];if(l.location+l.length>a.length)l.length=a.length-l.location,h.length=a.length-h.location,c=!0;else if(l.location+l.length<a.length){var d=r(r({},u),{location:l.location+l.length,length:a.length-l.location-l.length});t.push(d),i.push(this.calComputedRich(d))}var f=t[0];if(f.location>0){d=r(r({},u),{location:0,length:f.location});t.unshift(d),i.unshift(this.calComputedRich(d)),c=!0}}for(o=t.length-2;o>=0;o--){var m=t[o],p=t[o+1];if(p.length)if(m.length){var g=m.location+m.length;if(g===p.location)A(m,p,["color","fontFamily","fontSize","letterSpacing","lineHeight","textDecoration","paragraphSpacing","textShadow","stroke","strokeEnable","strokeWidth"])?(m.textAlign.v===p.textAlign.v||rm(a.charAt(p.location-1)))&&(m.length+=p.length,t.splice(o+1,1),i[o].length=m.length,i.splice(o+1,1),c=!0):1===p.length&&rm(a.charAt(p.location))&&(m.length+=p.length,t.splice(o+1,1),i[o].length=m.length,i.splice(o+1,1),c=!0);else{if(g<p.location){d=r(r({},u),{location:g,length:p.location-g});t.splice(o+1,0,d),i.splice(o+1,0,this.calComputedRich(d))}else{var v=m.location+m.length-p.location;p.location+=v,p.length-=v,i[o+1].location=p.location,i[o+1].length=p.length}c=!0}}else t.splice(o,1),i.splice(o,1),o++;else t.splice(o+1,1),i.splice(o+1,1)}return c}},i.prototype.calComputedRich=function(e){return{location:e.location,length:e.length,fontFamily:e.fontFamily.v,fontSize:e.fontSize.v,fontWeight:e.fontWeight.v,fontStyle:e.fontStyle.v,lineHeight:e.lineHeight.v,letterSpacing:e.letterSpacing.v,paragraphSpacing:e.paragraphSpacing.v,textAlign:e.textAlign.v,textDecoration:e.textDecoration.map(function(e){return e.v}),color:e.color.v,textShadow:e.textShadow.v,stroke:va(e.stroke),strokeWidth:e.strokeWidth.map(function(e){return e.v}),strokeEnable:e.strokeEnable.map(function(e){return e.v})}},i.prototype.calReflowStyle=function(){var t=this;e.prototype.calReflowStyle.call(this),this.computedRich=this.rich.map(function(e){return t.calComputedRich(e)})},i.prototype.calRepaintStyle=function(t){e.prototype.calRepaintStyle.call(this,t);var r=this.rich;if(r.length)this.computedRich.forEach(function(e,t){e.textDecoration=r[t].textDecoration.map(function(e){return e.v}),e.color=r[t].color.v,e.textShadow=r[t].textShadow.v,e.stroke=va(r[t].stroke),e.strokeWidth=r[t].strokeWidth.map(function(e){return e.v}),e.strokeEnable=r[t].strokeEnable.map(function(e){return e.v})});else{var i=this.computedStyle;this.lineBoxList.forEach(function(e){e.list.forEach(function(e){e.color=fe(i.color),e.stroke=i.stroke,e.strokeWidth=i.strokeWidth,e.strokeEnable=i.strokeEnable})})}},i.prototype.calContent=function(){this.hasContent=!1;var e=this.computedStyle;return(this._content||e.backgroundColor[3]>0)&&(this.hasContent=!0),this.hasContent},i.prototype.renderCanvas=function(){var t;e.prototype.renderCanvas.call(this);var r=this._bboxInt||this.bboxInt,i=r[0],a=r[1],n=r[2]-i,o=r[3]-a,s=-i,c=-a,u=this.computedStyle,l=this.lineBoxList,h=this.canvasCache=(null===(t=this.canvasCache)||void 0===t?void 0:t.available)?this.canvasCache:new xi(n,o,-i,-a);h.available=!0;var d=h.list,f=this.getSortedCursor(),m=f.isMulti,p=f.startLineBox,g=f.startTextBox,v=f.startString,y=f.endLineBox,b=f.endTextBox,x=f.endString,T=f.start,w=f.end;if(m&&T!==w)for(var k=0,S=d.length;k<S;k++){var E=d[k],C=E.x,A=E.y,_=E.os.ctx,M=-C,I=-A;if(_.fillStyle="#f4d3c1",p===y){var R=(D=l[p]).list,P=(B=R[g]).x+M;_.font=B.font,_.letterSpacing=B.letterSpacing+"px",P+=_.measureText(B.str.slice(0,v)).width;var O=(B=R[b]).x+M;_.font=B.font,O+=_.measureText(B.str.slice(0,x)).width,_.fillRect(P,D.y+I,O-P,D.lineHeight)}else{var D,B,F=(D=l[p]).list;if(B=F[g]){P=B.x+M;_.font=B.font,_.letterSpacing=B.letterSpacing+"px",P+=_.measureText(B.str.slice(0,v)).width,_.fillRect(P,D.y+I,D.w+M-P,D.lineHeight)}for(var L=p+1,N=y;L<N;L++){var U=l[L];U.list.length&&_.fillRect(U.list[0].x+M,U.y+I,U.w,U.lineHeight)}if(B=(F=(D=l[y]).list)[b]){P=B.x+M;_.font=B.font,_.letterSpacing=B.letterSpacing+"px",P+=_.measureText(B.str.slice(0,x)).width,_.fillRect(D.x+M,D.y+I,P-(D.x+M),D.lineHeight)}}}var z=u.strokeDasharray,W=u.strokeLinecap,V=u.strokeLinejoin,H=function(e,t){var r=d[e],i=r.x,a=r.y,u=r.os.ctx;u.miterLimit=1,u.fillStyle="transparent",u.setLineDash(z),W===Q.ROUND?u.lineCap="round":W===Q.SQUARE?u.lineCap="square":u.lineCap="butt",V===Z.ROUND?u.lineJoin="round":V===Z.BEVEL?u.lineJoin="bevel":u.lineJoin="miter";for(var h=-i,f=-a,m=0,p=l.length;m<p;m++){var g=l[m];if(g.y>=o)break;for(var v=g.list,y=v.length,b=function(e){var t=v[e],r=t.textDecoration,i=t.textShadow,a=t.stroke,l=t.strokeWidth,d=t.strokeEnable;am(u,t);for(var m=function(e,r){if(!d[e]||!l[e])return"continue";var i=a[e];if(Array.isArray(i))u.strokeStyle=fe(i);else if(i.t===Y.LINEAR){var m=Hr(i.stops,i.d,h,f,n-2*s,o-2*c),p=u.createLinearGradient(m.x1,m.y1,m.x2,m.y2);m.stop.forEach(function(e){p.addColorStop(e.offset,fe(e.color))}),u.strokeStyle=p}else if(i.t===Y.RADIAL){m=Xr(i.stops,i.d,h,f,n-2*s,o-2*c);var g=u.createRadialGradient(m.cx,m.cy,0,m.cx,m.cy,m.total);m.stop.forEach(function(e){g.addColorStop(e.offset,fe(e.color))});var v=m.matrix;if(v){var y=oe.getOffscreenCanvas(n,o),b=y.ctx;return b.setLineDash(u.getLineDash()),b.lineCap=u.lineCap,b.lineJoin=u.lineJoin,b.miterLimit=u.miterLimit,b.lineWidth=l[e],b.lineWidth=l[e],b.strokeStyle="#FFF",b.strokeText(t.str,t.x+h,t.y+t.baseline+f),b.globalCompositeOperation="source-in",b.setTransform(v[0],v[1],v[4],v[5],v[12],v[13]),b.fillStyle=g,b.fillRect(0,0,n,o),u.drawImage(y.canvas,0,0),y.release(),"continue"}u.strokeStyle=g}else if(i.t===Y.CONIC){m=jr(i.stops,i.d,h,f,n-2*s,o-2*c);var x=u.createConicGradient(m.angle,m.cx+h,m.cy+f);m.stop.forEach(function(e){x.addColorStop(e.offset,fe(e.color))}),u.strokeStyle=x}u.lineWidth=l[e],u.strokeText(t.str,t.x+h,t.y+t.baseline+f)},p=0,g=a.length;p<g;p++)m(p);u.fillStyle=t.color,i?(u.shadowOffsetX=i.x,u.shadowOffsetY=i.y,u.shadowBlur=i.blur,u.shadowColor=fe(i.color)):(u.shadowOffsetX=0,u.shadowOffsetY=0,u.shadowBlur=0,u.shadowColor="transparent"),u.fillText(t.str,t.x+h,t.y+t.baseline+f),u.shadowOffsetX=0,u.shadowOffsetY=0,u.shadowBlur=0,u.shadowColor="transparent",r.length&&r.forEach(function(e){if(e===re.UNDERLINE){var r=Math.min(3,.05*t.lineHeight);u.fillRect(t.x+h,t.y+t.contentArea+f-.5*r,t.w,r)}else if(e===re.LINE_THROUGH){var i=Math.min(3,.05*t.lineHeight);u.fillRect(t.x+h,t.y+.5*t.lineHeight+f-.5*i,t.w,i)}})},x=0;x<y;x++)b(x)}};for(k=0,S=d.length;k<S;k++)H(k)},i.prototype.setCursorStartByAbsCoords=function(e,t){var r=this.matrixWorld,i=bt({x:e,y:t},ct(r)),a=this.lineBoxList,n=this.cursor,o=n.start;n.isMulti=!1;for(var s=a.length,c=0;c<s;c++){var u=a[c];if(i.y>=u.y&&i.y<u.y+u.lineHeight){n.startLineBox=n.endLineBox=c;var l=this.getCursorByLocalX(i.x,u,!1);n.endTextBox=n.startTextBox,n.endString=n.startString,n.end=n.start,this.tempCursorX=l.x,n.start!==o&&(this.inputStyle=void 0);var h=bt({x:l.x,y:l.y},r);return{x:h.x,y:h.y,h:l.h*r[0]}}}var d=a[s-1];n.startLineBox=n.endLineBox=s-1;var f=this.getCursorByLocalX(this.width,d,!1);n.endTextBox=n.startTextBox,n.endString=n.startString,n.end=n.start,this.tempCursorX=f.x,n.start!==o&&(this.inputStyle=void 0);var m=bt({x:f.x,y:f.y},r);return{x:m.x,y:m.y,h:f.h*r[0]}},i.prototype.setCursorEndByAbsCoords=function(e,t){var r=this.matrixWorld,i=bt({x:e,y:t},ct(r)),a=this.lineBoxList,n=this.cursor,o=n.end;n.isMulti=!0;for(var s=a.length,c=0;c<s;c++){var u=a[c];if(i.y>=u.y&&i.y<u.y+u.lineHeight){n.endLineBox=c;var l=this.getCursorByLocalX(i.x,u,!0);n.end!==o&&this.refresh();var h=bt({x:l.x,y:l.y},r);return{x:h.x,y:h.y,h:l.h*r[0]}}}var d=a[s-1];n.endLineBox=s-1;var f=this.getCursorByLocalX(this.width,d,!0);n.end!==o&&this.refresh(),n.end!==n.start&&(this.inputStyle=void 0);var m=bt({x:f.x,y:f.y},r);return{x:m.x,y:m.y,h:f.h*r[0]}},i.prototype.resetCursor=function(){var e=this.cursor;e.isMulti&&(e.isMulti=!1,e.start!==e.end&&(this.refresh(),e.endLineBox=e.startLineBox,e.endTextBox=e.startTextBox,e.endString=e.startString,e.end=e.start))},i.prototype.reLocateCursor=function(){var e=this.cursor,t=this.lineBoxList,r=e.start,i=e.end,a=e.isMulti,n=0;e:for(var o=0,s=t.length;o<s;o++)for(var c=0,u=(l=t[o]).list.length;c<u;c++){if((d=n+l.list[c].str.length)>=r){e.startLineBox=o,e.startTextBox=c,e.startString=r-n;break e}n=d}if(a&&i!==r){n=0;e:for(o=0,s=t.length;o<s;o++){c=0;for(var l,h=(l=t[o]).list.length;c<h;c++){var d;if((d=n+l.list[c].str.length)>=i){e.endLineBox=o,e.endTextBox=c,e.endString=i-n;break e}n=d}}}else e.endLineBox=e.startLineBox,e.endTextBox=e.startTextBox,e.endString=e.startString},i.prototype.beforeEdit=function(){var e=this,t=e.style,r=e.computedStyle,i=e.parent,a=e.isDestroyed,n=e.width,o=e.height;if(a||!i)throw new Error("Can not edit a destroyed Text");var s=this.getStyle(),c=t.left,u=t.right,l=t.top,h=t.bottom,d=t.width,f=t.height,m=t.translateX,p=t.translateY,g=t.textAlign,v=t.textVerticalAlign,y=c.u!==V.AUTO&&u.u!==V.AUTO||d.u!==V.AUTO,b=g.v===H.LEFT&&!y&&(c.u!==V.AUTO&&m.v&&m.u===V.PERCENT||u.u!==V.AUTO),x=g.v===H.CENTER&&!y&&(-50!==m.v||m.u!==V.PERCENT),T=g.v===H.RIGHT&&u.u===V.AUTO,w=l.u!==V.AUTO&&h.u!==V.AUTO||f.u!==V.AUTO,k=v.v===X.TOP&&!w&&(l.u!==V.AUTO&&p.v&&p.u===V.PERCENT||h.u!==V.AUTO),S=v.v===X.MIDDLE&&!w&&(-50!==p.v||p.u!==V.PERCENT),E=v.v===X.BOTTOM&&!w&&h.u===V.AUTO,C=i.width,A=i.height,_=!1,M=0;if(m.u===V.PX?M=m.v:m.u===V.PERCENT&&(M=.01*m.v*n),b)c.u!==V.AUTO&&m.v&&m.u===V.PERCENT?(_=!0,r.left+=M,c.u===V.PX?c.v+=M:c.u===V.PERCENT&&(c.v+=100*M/C),r.right-=M,u.u===V.PX?u.v-=M:u.u===V.PERCENT&&(u.v-=100*M/C)):u.u!==V.AUTO&&(_=!0,r.left+=M,c.v=r.left,c.u=V.PX,r.right-=M,u.v=0,u.u=V.AUTO),m.v=0;else if(x){if(m.u===V.AUTO||m.u===V.PX){_=!0;var I=.5*n-m.v;r.left+=I,r.right-=I,c.u===V.PX?(c.v+=I,m.v=-50):c.u===V.PERCENT?(c.v+=100*I/C,m.v=-50):u.u===V.PX?(u.v+=I,m.v=50):u.u===V.PERCENT&&(u.v+=100*I/C,m.v=50),m.u=V.PERCENT}else if(m.u===V.PERCENT&&-50!==m.v){_=!0;I=.5*n-m.v*n;r.left+=I,r.right-=I,c.u===V.PX?(c.v+=I,m.v=-50):c.u===V.PERCENT?(c.v+=100*I/C,m.v=-50):u.u===V.PX?(u.v+=I,m.v=50):u.u===V.PERCENT&&(u.v+=100*I/C,m.v=50)}}else T&&(_=!0,r.left+=M,c.u!==V.AUTO&&(c.v=0,c.u=V.AUTO),r.right-=M,u.v=r.right,u.u=V.PX,m.v=0);var R=0;if(p.u===V.PX?R=p.v:p.u===V.PERCENT&&(R=.01*p.v*o),k)l.u!==V.AUTO&&p.v&&p.u===V.PERCENT?(_=!0,r.top+=R,l.u===V.PX?l.v+=R:l.u===V.PERCENT&&(l.v+=100*R/A),r.bottom-=R,h.u===V.PX?h.v-=R:h.u===V.PERCENT&&(h.v-=100*R/A)):h.u!==V.AUTO&&(_=!0,r.top+=R,l.v=r.top,l.u=V.PX,r.bottom-=R,h.v=0,h.u=V.AUTO),p.v=0;else if(S){if(p.u===V.AUTO||p.u===V.PX){_=!0;var P=.5*o-p.v;r.top+=P,r.bottom-=P,l.u===V.PX?(l.v+=P,p.v=-50):l.u===V.PERCENT?(l.v+=100*P/A,p.v=-50):h.u===V.PX?(h.v+=P,p.v=50):h.u===V.PERCENT&&(h.v+=100*P/A,p.v=50),p.u=V.PERCENT}else if(p.u===V.PERCENT&&-50!==p.v){_=!0;P=.5*o-p.v*o;r.top+=P,r.bottom-=P,l.u===V.PX?(l.v+=P,p.v=-50):l.u===V.PERCENT?(l.v+=100*P/A,p.v=-50):h.u===V.PX?(h.v-=P,p.v=50):h.u===V.PERCENT&&(h.v-=100*P/A,p.v=50),p.v=-50}}else E&&(_=!0,r.top+=R,l.u!==V.AUTO&&(l.v=0,l.u=V.AUTO),r.bottom-=R,h.v=r.bottom,h.u=V.PX,p.v=0);if(_)return this.editStyle={isLeft:b,isCenter:x,isRight:T,isTop:k,isMiddle:S,isBottom:E,isFixedHeight:w,prev:s}},i.prototype.afterEdit=function(){if(this.editStyle){var e=this.editStyle,t=e.isLeft,r=e.isCenter,i=e.isRight,a=e.isTop,n=e.isMiddle,o=e.isBottom;e.isFixedHeight;var s=e.prev,c=this,u=c.style,l=c.computedStyle,h=c.parent,d=c.width,f=c.height,m=s.left,p=s.right,g=s.top,v=s.bottom,y=s.translateX,b=s.translateY,x=h,T=x.width,w=x.height,k=0;if(y.u===V.PX?k=y.v:y.u===V.PERCENT&&(k=.01*y.v*d),t){if(m.u!==V.AUTO&&y.v&&y.u===V.PERCENT){if(m.u===V.PX)u.left.v-=k,l.left-=k;else if(m.u===V.PERCENT){var S=100*k/T;u.left.v-=S,l.left-=k}if(p.u===V.PX)u.right.v+=k,l.right+=k;else if(p.u===V.PERCENT){S=100*k/T;u.right.v+=S,l.right+=k}l.translateX+=k}else p.u!==V.AUTO&&(u.left.v=0,u.left.u=V.AUTO,l.left-=k,u.right.v=p.v,u.right.u=p.u,l.right+=k);u.translateX.v=y.v}else if(r){if(y.u===V.AUTO||y.u===V.PX){var E=.5*d-y.v;m.u===V.PX?u.left.v-=E:m.u===V.PERCENT?u.left.v-=100*E/T:p.u===V.PX?u.right.v-=E:p.u===V.PERCENT&&(u.right.v-=100*E/T),u.translateX.v=y.v,u.translateX.u=y.u}else if(y.u===V.PERCENT&&-50!==y.v){E=.5*d-y.v*d;m.u===V.PX?u.left.v-=E:m.u===V.PERCENT&&(u.left.v-=100*E/T),p.u===V.PX?u.right.v-=E:p.u===V.PERCENT&&(u.right.v-=100*E/T),u.translateX.v=y.v}}else i&&(l.left-=k,m.u===V.PX?u.left.v=l.left:m.u===V.PERCENT&&(u.left.v=100*l.left/T),u.left.u=m.u,l.right+=k,p.u===V.AUTO&&(u.right.v=0,u.right.u=V.AUTO),u.translateX.v=y.v,u.translateX.u=y.u);var C=0;if(b.u===V.PX?C=b.v:b.u===V.PERCENT&&(C=.01*b.v*f),a){if(g.u!==V.AUTO&&b.v&&b.u===V.PERCENT){if(g.u===V.PX)u.top.v-=C,l.top-=C;else if(g.u===V.PERCENT){S=100*C/w;u.top.v-=S,l.top-=C}if(v.u===V.PX)u.bottom.v+=C,l.bottom+=C;else if(v.u===V.PERCENT){S=100*C/w;u.bottom.v+=S,l.bottom+=C}}else v.u!==V.AUTO&&(u.top.v=0,u.top.u=V.AUTO,l.top-=C,u.bottom.v=v.v,u.bottom.u=v.u,l.bottom+=C);u.translateY.v=b.v,l.translateY+=C}else if(n){if(b.u===V.AUTO||b.u===V.PX){var A=.5*f-b.v;g.u===V.PX?u.top.v-=A:g.u===V.PERCENT?u.top.v-=100*A/w:v.u===V.PX?u.bottom.v-=A:v.u===V.PERCENT&&(u.bottom.v-=100*A/w),u.translateY.v=b.v,u.translateY.u=V.PX}else if(b.u===V.PERCENT&&-50!==b.v){A=.5*f-b.v*f;g.u===V.PX?u.top.v-=A:g.u===V.PERCENT?u.top.v-=100*A/w:v.u===V.PX?u.bottom.v-=A:v.u===V.PERCENT&&(u.bottom.v-=100*A/w),u.translateY.v=b.v}}else o&&(l.top-=C,g.u===V.PX?u.top.v=l.top:g.u===V.PERCENT&&(u.top.v=100*l.top/w),l.bottom+=C,v.u===V.AUTO&&(u.bottom.v=0,u.bottom.u=V.AUTO),u.translateY.v=b.v,u.translateY.u=b.u)}},i.prototype.updateCursorByIndex=function(e){var t=this.setCursorByIndex(e,!1),r=t.lineBox,i=t.textBox,a=this.cursor,n=this.matrixWorld;if(i){var o=oe.getFontCanvas().ctx;o.font=i.font,o.letterSpacing=i.letterSpacing+"px";var s=i.str,c=o.measureText(s.slice(0,a.startString)).width;this.tempCursorX=i.x+c}else{var u=this.computedStyle.textAlign;u===H.CENTER?this.tempCursorX=.5*this.width:u===H.RIGHT?this.tempCursorX=this.width:this.tempCursorX=0}var l=bt({x:this.tempCursorX,y:r.y},n);return{x:l.x,y:l.y,h:r.lineHeight*n[0]}},i.prototype.setCursorByIndex=function(e,t){void 0===t&&(t=!1);var r=this.lineBoxList,i=this.cursor;t?i.end=e:i.start=e;for(var a=0,n=r.length;a<n;a++){var o=r[a],s=o.list;if(!s.length&&o.index===e)return i.startLineBox=a,i.startTextBox=0,i.startString=0,{lineBox:o,textBox:void 0};for(var c=0,u=s.length;c<u;c++){var l=s[c];if(e>=l.index&&(e<l.index+l.str.length||c===u-1&&o.endEnter&&e<=l.index+l.str.length))return t?(i.endLineBox=a,i.endTextBox=c,i.endString=e-l.index):(i.startLineBox=a,i.startTextBox=c,i.startString=e-l.index),{lineBox:o,textBox:l}}}var h=r.length-1,d=r[h],f=d.list;if(t?i.endLineBox=h:i.startLineBox=h,!f||!f.length)return t?(i.endTextBox=0,i.endString=0):(i.startTextBox=0,i.startString=0),{lineBox:d,textBox:void 0};var m=f.length-1,p=f[m];return t?(i.endTextBox=m,i.endString=p.str.length):(i.startTextBox=m,i.startString=p.str.length),{lineBox:d,textBox:p}},i.prototype.checkCursorMulti=function(){var e=this.cursor;return e.isMulti&&e.start===e.end&&(e.isMulti=!1),e.isMulti},i.prototype.getCursorAbsCoords=function(){var e=this.matrixWorld,t=this.lineBoxList,r=this.cursor;if(!r.isMulti){var i=t[r.startLineBox],a=i.list,n=i.lineHeight;if(!a.length){var o=this.computedStyle.textAlign,s=0;o===H.CENTER?s=.5*this.width:o===H.RIGHT&&(s=this.width);var c=bt({x:s,y:i.y},e);return{x:c.x,y:c.y,h:n*e[0]}}var u=bt({x:this.tempCursorX,y:i.y},e);return{x:u.x,y:u.y,h:n*e[0]}}},i.prototype.moveCursor=function(e,t){void 0===t&&(t=!1);var r=this.matrixWorld,i=this.cursor,a=this.getSortedCursor(),n=t?a.endLineBox:a.startLineBox,o=t?a.endTextBox:a.startTextBox,s=t?a.endString:a.startString,c=this.lineBoxList,u=c[n],l=u.list,h=l[o],d=t?a.end:a.start;if(i.isMulti&&!t){if(i.isMulti=!1,i.start!==i.end&&this.refresh(),39===e||40===e){var f=a.endLineBox,m=a.endTextBox,p=a.endString;d=(h=(l=(u=c[f]).list)[m])?h.index+p:u.index+p}return this.inputStyle=void 0,this.updateCursorByIndex(d)}if(t&&(i.isMulti=!0),37===e){if(0===d)return;0===s?0===o?(t?i.endLineBox=--n:i.startLineBox=--n,(l=(u=c[n]).list).length?(t?i.endTextBox=o=l.length-1:i.startTextBox=o=l.length-1,h=l[o],t?(i.endString=h.str.length-(u.endEnter?0:1),i.end=h.index+i.endString):(i.startString=h.str.length-(u.endEnter?0:1),i.start=h.index+i.startString)):t?(i.endTextBox=0,i.endString=0,i.end=u.index):(i.startTextBox=0,i.startString=0,i.start=u.index)):(t?i.endTextBox=--o:i.startTextBox=--o,h=l[o],t?(i.endString=h.str.length-1,i.end=h.index+i.endString):(i.startString=h.str.length-1,i.start=h.index+i.startString)):t?(i.endString=--s,i.end=h.index+i.endString):(i.startString=--s,i.start=h.index+i.startString)}else if(38===e){if(0===d)return;if(0!==n){u=c[--n],t?i.endLineBox=n:i.startLineBox=n;var g=this.getCursorByLocalX(this.tempCursorX,u,t);t&&this.refresh(),this.inputStyle=void 0;var v=bt({x:g.x,y:g.y},r);return{x:v.x,y:v.y,h:u.lineHeight*r[0]}}t?i.endTextBox=0:i.startTextBox=0,h=l[0],t?(i.endString=0,i.end=0):(i.startString=0,i.start=0)}else if(39===e){if(d===this._content.length)return;!h||o===l.length-1&&s===h.str.length&&u.endEnter?(t?(i.endLineBox=++n,i.endTextBox=0,i.endString=0):(i.startLineBox=++n,i.startTextBox=0,i.startString=0),h=(l=(u=c[n]).list)[0],t?i.end=h.index:i.start=h.index):o===l.length-1&&s===h.str.length?(t?(i.endLineBox=++n,i.endTextBox=0,i.endString=1):(i.startLineBox=++n,i.startTextBox=0,i.startString=1),h=(l=(u=c[n]).list)[0],t?i.end=h.index+1:i.start=h.index+1):s===h.str.length?(t?i.endTextBox=++o:i.startTextBox=++o,h=l[o],t?(i.endString=1,i.end=h.index+1):(i.startString=1,i.start=h.index+1),o===l.length-1&&1===h.str.length&&!u.endEnter&&n<c.length-1&&(t?i.endLineBox=++n:i.startLineBox=++n,l=(u=c[n]).list,t?i.endTextBox=o=0:i.startTextBox=o=0,h=l[o],t?(i.endString=0,i.end=h.index):(i.startString=0,i.start=h.index))):s===h.str.length-1?o===l.length-1?u.endEnter||n===c.length-1?t?(i.endString++,i.end=h.index+i.endString):(i.startString++,i.start=h.index+i.startString):(t?i.endLineBox=++n:i.startLineBox=++n,l=(u=c[n]).list,t?i.endTextBox=o=0:i.startTextBox=o=0,h=l[o],t?(i.endString=0,i.end=h.index):(i.startString=0,i.start=h.index)):(t?i.endTextBox=++o:i.startTextBox=++o,h=l[o],t?(i.endString=0,i.end=h.index):(i.startString=0,i.start=h.index)):t?(i.endString=++s,i.end=h.index+i.endString):(i.startString=++s,i.start=h.index+i.startString)}else if(40===e){if(d===this._content.length)return;if(n!==c.length-1){u=c[++n],t?i.endLineBox=n:i.startLineBox=n;g=this.getCursorByLocalX(this.tempCursorX,u,t);t&&this.refresh(),this.inputStyle=void 0;var y=bt({x:g.x,y:g.y},r);return{x:y.x,y:y.y,h:u.lineHeight*r[0]}}t?i.endTextBox=o=l.length-1:i.startTextBox=o=l.length-1,h=l[o],t?(i.endString=h?h.str.length:0,i.end=h.index+i.endString):(i.startString=h?h.str.length:0,i.start=h.index+i.startString)}if(h){var b=oe.getFontCanvas().ctx;b.font=h.font,b.letterSpacing=h.letterSpacing+"px";var x=h.str,T=b.measureText(x.slice(0,i.startString)).width;this.tempCursorX=h.x+T}else{var w=this.computedStyle.textAlign;w===H.CENTER?this.tempCursorX=.5*this.width:w===H.RIGHT?this.tempCursorX=this.width:this.tempCursorX=0}t&&this.refresh(),this.inputStyle=void 0;var k=bt({x:this.tempCursorX,y:u.y},r);return{x:k.x,y:k.y,h:u.lineHeight*r[0]}},i.prototype.selectAll=function(){var e=this.lineBoxList,t=e.length,r=e[t-1],i=null==r?void 0:r.list,a=i?i[i.length-1]:void 0;Object.assign(this.cursor,{isMulti:!0,startLineBox:0,startTextBox:0,startString:0,start:0,endLineBox:t-1,endTextBox:i?i.length-1:0,endString:a?a.str.length:0,end:this._content.length}),this.refresh()},i.prototype.input=function(e){var t=this.getSortedCursor(),r=t.isMulti,i=t.start,a=t.end,n=this._content;if(r){var o=this.getCursorRich();this.cursor.isMulti=!1,this._content=n.slice(0,i)+n.slice(a),this.cutRich(i,a),n=this._content,this._content=n.slice(0,i)+e+n.slice(i),this.insertRich(o[0],i,e.length)}else if(this.inputStyle){o=this.getCursorRich();this._content=n.slice(0,i)+e+n.slice(i),this.insertRich(Object.assign({},o[0],this.inputStyle),i,e.length),this.inputStyle=void 0}else this._content=n.slice(0,i)+e+n.slice(i),this.expandRich(i,e.length);this.refresh(ci.REFLOW),this.updateCursorByIndex(i+e.length)},i.prototype.enter=function(){this.inputStyle=void 0;var e=this.getSortedCursor(),t=e.isMulti,r=e.start,i=e.end;if(t){this.cursor.isMulti=!1,this.cutRich(r,i);var a=this._content;this._content=a.slice(0,r)+a.slice(i)}this.expandRich(r,1);var n=this._content;this._content=n.slice(0,r)+"\n"+n.slice(r),this.refresh(ci.REFLOW),this.updateCursorByIndex(r+1)},i.prototype.delete=function(e){void 0===e&&(e=!1),this.inputStyle=void 0;var t=this._content;if(t){var r=this.getSortedCursor(),i=r.isMulti,a=r.start,n=r.end;a<1&&!i&&!e||a===t.length&&e||(i?(this.cursor.isMulti=!1,this._content=t.slice(0,a)+t.slice(n),this.cutRich(a,n)):e?(this._content=t.slice(0,a)+t.slice(a+1),this.cutRich(a,a+1)):(this._content=t.slice(0,a-1)+t.slice(a),this.cutRich(a-1,a)),this.refresh(ci.REFLOW),i||e?this.updateCursorByIndex(a):this.updateCursorByIndex(a-1))}},i.prototype.getSortedCursor=function(){var e,t=this.cursor,r=t.isMulti,i=t.startLineBox,a=t.startTextBox,n=t.startString,o=t.endLineBox,s=t.endTextBox,c=t.endString,u=t.start,l=t.end,h=!1;return r?u>l&&(i=(e=[o,s,c,l,i,a,n,u])[0],a=e[1],n=e[2],u=e[3],o=e[4],s=e[5],c=e[6],l=e[7],h=!0):(o=i,s=a,c=n,l=u),{isMulti:r,startLineBox:i,startTextBox:a,startString:n,endLineBox:o,endTextBox:s,endString:c,start:u,end:l,isReversed:h}},i.prototype.getCursorRich=function(){var e=this.rich,t=this.lineBoxList,r=[];if(!e.length)return r;function i(t,r,i){for(void 0===r&&(r=0),void 0===i&&(i=e.length-1);r<i;){var a=Math.floor(.5*(r+i)),n=e[a];if(n.location<t&&n.location+n.length>=t)return n;n.location>=t?i=Math.min(a,i-1):r=Math.max(a,r+1)}return e[r]}var a=this.getSortedCursor(),n=a.isMulti,o=a.startLineBox,s=a.startTextBox,c=a.startString,u=a.start,l=a.end;if(n)for(var h=0,d=e.length;h<d;h++){if((f=e[h]).location>=l)break;f.location+f.length>u&&r.push(f)}if(!n||!r.length){var f,m=t[o],p=m.list;if(p.length)(f=i(p[s].index+(s+c===0?1:c)))&&-1===r.indexOf(f)&&r.push(f);else(f=i(m.index))&&-1===r.indexOf(f)&&r.push(f)}return r},i.prototype.getCursorByLocalX=function(e,t,r){void 0===r&&(r=!1);var i=t.list,a=this.cursor,n=0,o=t.y,s=t.lineHeight;r?a.endString=a.end=0:a.startString=a.start=0;e:for(var c=0,u=i.length;c<u;c++){var l=(k=i[c]).x,h=k.w,d=k.str,f=k.font,m=k.letterSpacing;if(!c&&e<l||e>=l&&e<l+h||c===u-1){r?a.endTextBox=c:a.startTextBox=c;var p=oe.getFontCanvas().ctx;p.font=f,p.letterSpacing=m+"px";for(var g=0,v=d.length;g<v;){if(g===v-1){var y=p.measureText(d.slice(0,g)).width,b=p.measureText(d.slice(0,v)).width;e-(l+y)>l+b-e?(n=l+b,r?(a.endString=v,a.end=k.index+v):(a.startString=v,a.start=k.index+v)):(n=l+y,r?(a.endString=g,a.end=k.index+g):(a.startString=g,a.start=k.index+g));break e}var x=g+(v-g>>1),T=p.measureText(d.slice(0,x)).width;if(e>l+T)g=x;else{if(!(e<l+T)){r?(a.endString=x,a.end=k.index+x):(a.startString=x,a.start=k.index+x),n=l+T;break e}v=x}}}}var w=r?a.endTextBox:a.startTextBox;if(w<i.length-1){var k=i[w];(r?a.endString:a.startString)===k.str.length&&(r?(a.endTextBox++,a.endString=0,a.end=i[w+1].index):(a.startTextBox++,a.startString=0,a.start=i[w+1].index))}if(!i.length){r?(a.endString=0,a.end=t.index):(a.startString=0,a.start=t.index);var S=this.computedStyle.textAlign;S===H.CENTER?n=.5*this.width:S===H.RIGHT&&(n=this.width)}return{x:n,y:o,h:s}},i.prototype.getRich=function(){return this.rich.map(function(e){return Object.assign({},e)})},i.prototype.getCursor=function(){return Object.assign({},this.cursor)},i.prototype.updateStyle=function(t,r){var i=e.prototype.updateStyle.call(this,t,r);return i&&i&ci.REFLOW_REPAINT&&this.reLocateCursor(),i},i.prototype.updateRangeStyle=function(e,t,r,i){var a=Gr(r),n=this.updateRangeStyleData(e,t,a);return n&&this.refresh(n,i),n&ci.REFLOW_REPAINT&&this.reLocateCursor(),n},i.prototype.updateRangeStyleData=function(e,t,i){var a=ci.NONE,n=this,o=n.rich,s=n.computedRich,c=n.style;if(o.length)for(var u=0,l=o.length;u<l&&!(t<1);u++){var h=o[u],d=s[u];if(e>=h.location&&e<h.location+h.length){if(e>h.location){var f=r(r({},h),{length:e-h.location});o.splice(u,0,f),u++,l++,h.location+=f.length,h.length-=f.length,s.splice(u,0,this.calComputedRich(f)),d.location=h.location,d.length=h.length}var m=!1;if(e+t<h.location+h.length){var p=r(r({},h),{location:e+t,length:h.location+h.length-e-t});o.splice(u+1,0,p),h.length-=p.length,s.splice(u+1,0,this.calComputedRich(p)),d.length=h.length,m=!0}if(a|=this.updateRichItem(h,d,i),m)break;e+=h.length,t-=h.length}}else if(0===e&&t>=this._content.length){var g=this.updateFormatStyle(i);g&&(a|=g)}else{if(e>0){var v=ii({location:0,length:e},c);o.push(v),s.push(this.calComputedRich(v))}var y={location:e,length:t};if(ue.forEach(function(e){y[e]=c[e]}),Object.assign(y,i),o.push(y),s.push(this.calComputedRich(y)),e+t<this._content.length){v=ii({location:e+t,length:this._content.length-e-t},c);o.push(v),s.push(this.calComputedRich(v))}a|=ci.REFLOW}return this.mergeRich(),0===e&&this.updateFormatStyleData(i),a},i.prototype.updateRichItem=function(e,t,r){var i=ci.NONE;if(r.fontFamily&&r.fontFamily.v!==e.fontFamily.v&&(e.fontFamily=r.fontFamily,i|=ci.REFLOW),r.fontSize&&r.fontSize.v!==e.fontSize.v&&(e.fontSize=r.fontSize,i|=ci.REFLOW),r.color&&(e.color.v[0]===r.color.v[0]&&e.color.v[1]===r.color.v[1]&&e.color.v[2]===r.color.v[2]&&e.color.v[3]===r.color.v[3]||(e.color=r.color,i|=ci.REFLOW)),r.letterSpacing&&r.letterSpacing.v!==e.letterSpacing.v&&(e.letterSpacing=r.letterSpacing,i|=ci.REFLOW),r.lineHeight&&r.lineHeight.v!==e.lineHeight.v&&(e.lineHeight=r.lineHeight,i|=ci.REFLOW),r.paragraphSpacing&&r.paragraphSpacing.v!==e.paragraphSpacing.v&&(e.paragraphSpacing=r.paragraphSpacing,i|=ci.REFLOW),r.textAlign&&r.textAlign.v!==e.textAlign.v&&(e.textAlign=r.textAlign,i|=ci.REFLOW),r.textDecoration)if(r.textDecoration.length!==e.textDecoration.length)e.textDecoration=r.textDecoration,i|=ci.REFLOW;else for(var a=0,n=e.textDecoration.length;a<n;a++)if(r.textDecoration[a].v!==e.textDecoration[a].v){e.textDecoration=r.textDecoration,i|=ci.REFLOW;break}return r.textShadow&&r.textShadow.v!==e.textShadow.v&&(e.textShadow=r.textShadow,i|=ci.REFLOW),Object.assign(t,this.calComputedRich(e)),i},i.prototype.getTextBehaviour=function(){var e=this.style,t=e.left,r=e.right,i=e.top,a=e.bottom,n=e.width,o=e.height,s=n.u===V.AUTO&&(t.u===V.AUTO||r.u===V.AUTO),c=o.u===V.AUTO&&(i.u===V.AUTO||a.u===V.AUTO);return s?"auto":c?"autoH":"fixed"},i.prototype.cloneProps=function(){var t=e.prototype.cloneProps.call(this);if(this.isMounted){var r=t.textBehaviour=this.getTextBehaviour(),i=t.style;"auto"===r?(i.width=this.width,i.height=this.height):"autoH"===r&&(i.height=this.height)}return t.content=this._content,t},i.prototype.clone=function(){return new i(this.cloneProps())},Object.defineProperty(i.prototype,"bbox",{get:function(){var e=this._bbox;if(!e){var t=this._rect||this.rect;e=this._bbox=t.slice(0),this.lineBoxList.forEach(function(t){t.list.forEach(function(t){var r=t.fontFamily,i=t.fontSize,a=t.lineHeight,n=t.str,o=t.font,s=t.textShadow,c=a;if(Xe.hasRegister(r)){c=Xe.data[r].lhr*i}else{var u=oe.getFontCanvas().ctx;u.font=o;var l=u.measureText(n);c=l.actualBoundingBoxAscent+l.actualBoundingBoxDescent}var h=Math.max(0,.5*(c-a));if(h>0){var d=t.y-h,f=t.lineHeight+h;e[1]=Math.min(e[1],d),e[3]=Math.max(e[3],f)}if(s){var m=Or(s.blur),p=s.x+m,g=s.y+m;p>0?e[2]=Math.max(e[2],t.x+t.w+p):p<0&&(e[0]=Math.min(e[0],t.x+p)),g>0?e[3]=Math.max(e[3],t.y+t.lineHeight+g+h):g<0&&(e[1]=Math.min(e[1],t.y+g-h))}})});var r=this.computedStyle,i=r.strokeWidth,a=r.strokeEnable,n=r.strokePosition,o=0;i.forEach(function(e,t){a[t]&&(n[t]===J.INSIDE||(o=n[t]===J.OUTSIDE?Math.max(o,2*e):Math.max(o,.5*e*2)))}),e[0]-=o,e[1]-=o,e[2]+=o,e[3]+=o}return e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"content",{get:function(){return this._content},set:function(e){this._content!==e&&(this._content=e,this.refresh(ci.REFLOW))},enumerable:!1,configurable:!0}),i}(ka);function sm(e){return(e.curveMode===ce.STRAIGHT||e.curveMode===ce.NONE||"straight"===e.curveMode||"none"===e.curveMode)&&!!e.cornerRadius&&e.cornerRadius>0}function cm(e,t,r,i,a,n){var o=vr(e.absX,e.absY,t.absX,t.absY),s=vr(t.absX,t.absY,r.absX,r.absY),c=yr(vr(e.absX,e.absY,r.absX,r.absY),o,s),u=Math.tan(.5*c),l=n/u,h=Math.min(i?.5*o:o,a?.5*s:s);l>h&&(n=(l=h)*u);var d=Ze(e.absX-t.absX,e.absY-t.absY),f=Ze(r.absX-t.absX,r.absY-t.absY),m={x:d.x*l,y:d.y*l};m.x+=t.absX,m.y+=t.absY;var p={x:f.x*l,y:f.y*l};p.x+=t.absX,p.y+=t.absY;var g=4/3*Math.tan((Math.PI-c)/4),v={x:d.x*-n*g,y:d.y*-n*g};v.x+=m.x,v.y+=m.y;var y={x:f.x*-n*g,y:f.y*-n*g};return y.x+=p.x,y.y+=p.y,{prevTangent:m,prevHandle:v,nextTangent:p,nextHandle:y}}function um(e,t,r,i,a,n){var o,s,c,u;if(i){var l=Math.sqrt(Math.pow(t.absX-e.absX,2)+Math.pow(t.absY-e.absY,2));n=Math.min(n,.5*l)}if(a){l=Math.sqrt(Math.pow(t.absX-r.absX,2)+Math.pow(t.absY-r.absY,2));n=Math.min(n,.5*l)}var h=e.absFx-t.absX,d=e.absFy-t.absY,f=r.absTx-t.absX,m=r.absTy-t.absY,p=e.absX-t.absX,g=e.absY-t.absY,v=r.absX-t.absX,y=r.absY-t.absY,b=qe(h,d,f,m),x=qe(p,g,v,y),T=qe(h,d,p,g),w=qe(f,m,v,y);if(!(Math.abs(b)<1e-6)){var k=[{x:e.absX,y:e.absY},{x:null!==(o=e.absFx)&&void 0!==o?o:e.absX,y:null!==(s=e.absFy)&&void 0!==s?s:e.absY},{x:t.absX,y:t.absY}],S=[{x:t.absX,y:t.absY},{x:null!==(c=r.absTx)&&void 0!==c?c:r.absX,y:null!==(u=r.absTy)&&void 0!==u?u:r.absY},{x:r.absX,y:r.absY}],E=dr.intersectBezier2Bezier2(k[0].x,k[0].y,k[1].x,k[1].y,k[2].x,k[2].y,S[0].x,S[0].y,S[1].x,S[1].y,S[2].x,S[2].y).filter(function(e){return e.x!==S[0].x&&e.y!==S[0].y}).sort(function(e,t){return e.t1===t.t1?t.t2-e.t2:t.t1-e.t1}),C=E.length;if(!C)return lm(k,S,t,C,!1,b,x,T,w,n,0,1,0,1);var A=E.map(function(e){return e.t1}),_=E.map(function(e){return Ut(S,e.x,e.y)[0]});if(!_.find(function(e){return void 0===e})){var M=!1;A.unshift(1),A.push(0),_.unshift(0),_.push(1);for(var I=0;I<=C;I++){var R=lm(k,S,t,C,M,b,x,T,w,n,A[I+1],A[I],_[I],_[I+1]);if(R)return R;M=!M}}}}function lm(e,t,r,i,a,n,o,s,c,u,l,h,d,f){var m=dm(e,i,a,n,o,s,u,!0,l,h),p=dm(t,i,a,n,o,c,u,!1,d,f);if(!(!m||m.length<2||!p||p.length<2)){var g=function(e,t){var r=pm(e,0),i=pm(t,1),a=function(e){var t={};e.forEach(function(e){var r,i=e.x1,a=e.x2;i>a&&(i=(r=[a,i])[0],a=r[1]),fm(t,i,e),fm(t,a,e)});var r=[];return Object.keys(t).forEach(function(e){return r.push({x:parseFloat(e),arr:t[e]})}),r.sort(function(e,t){return e.x-t.x})}(r.concat(i)),n=[],o=[],s=[];for(;a.length;){o.length&&o.splice(0).forEach(function(e){var t=n.indexOf(e);n.splice(t,1)});for(var c=a.shift().arr;c.length;){var u=c.shift();if(!u.isDeleted){var l=u.belong,h=u.bbox;if(u.isVisited)o.push(u);else{if(n.length)for(var d=u.x1,f=u.y1,m=u.x2,p=u.y2,g=u.bbox,v=0;v<n.length;v++){var y=n[v];if(!y.isDeleted&&!u.isDeleted&&y.belong!==l){var b=y.x1,x=y.y1,T=y.x2,w=y.y2;if(xr(h[0],h[1],h[2],h[3],g[0],g[1],g[2],g[3],!0)){var k=(w-x)*(m-d)-(T-b)*(p-f);if(0!==k){var S=((T-b)*(f-x)-(w-x)*(d-b))/k,E=((m-d)*(f-x)-(p-f)*(d-b))/k;if(S>=0&&S<=1&&E>=0&&E<=1){var C=d+S*(m-d),A=f+S*(p-f);s.push({x:C,y:A,t1:0===l?u.t:y.t,t2:0===l?y.t:u.t}),u.isDeleted=!0;break}}}}}u.isDeleted||(n.push(u),u.isVisited=!0)}}}}return s}(m,p);if(g.length){var v=g[0];if(g.length>1)for(var y=Math.pow(r.absX-v.x,2)+Math.pow(r.absY-v.y,2),b=1,x=g.length;b<x;b++){var T=g[b],w=Math.pow(r.absX-T.x,2)+Math.pow(r.absY-T.y,2);w<y&&(v=T,y=w)}var k=Ft(e,v.t1),S=Ft(t,v.t2),E=zt(e,v.t1),C=zt(t,v.t2),A=k.y-E*k.x,_=(S.y-C*S.x-A)/(E-C),M=E*_+A;Math.abs(E)<1e-9?(M=k.y,C!==1/0&&C!==-1/0||(_=S.x)):Math.abs(C)<1e-9?(M=S.y,E!==1/0&&E!==-1/0||(_=k.x)):E===1/0||E===-1/0?(_=k.x,M=S.y):C!==1/0&&C!==-1/0||(_=S.x,M=k.y);var I=vr(k.x,k.y,_,M),R=vr(_,M,S.x,S.y),P=yr(vr(k.x,k.y,S.x,S.y),I,R),O=4/3*Math.tan((Math.PI-P)/4),D=Ze(k.x-_,k.y-M),B=Ze(S.x-_,S.y-M),F={x:D.x*-u*O,y:D.y*-u*O};F.x+=k.x,F.y+=k.y;var L={x:B.x*-u*O,y:B.y*-u*O};return L.x+=S.x,L.y+=S.y,{prevTangent:k,prevHandle:F,nextTangent:S,nextHandle:L,t1:v.t1,t2:v.t2}}}}var hm={11010:1,11e3:1,11110:1,11100:1,11001:1,11111:1,11012:1,11002:1,11112:1,11102:1,11013:1,11103:1,10010:0,10100:0,10011:0,10001:0,10111:0,10101:0,"00010":0,"00000":0,"00110":0,"00100":0,"00011":0,"00101":0,"00002":0,"00012":0,"00102":0,"00112":0,"00003":0,"00103":0,"01000":1,"01110":1,"01001":1,"01011":1,"01101":1,"01111":1};function dm(e,t,r,i,a,n,o,s,c,u){var l=(a>=0?"0":"1")+(i>=0?"0":"1")+(s?"0":"1")+(n>=0?"0":"1")+t;if(hm.hasOwnProperty(l)){for(var h=Math.ceil(Pt(e)),d=[],f=function(t){var i=t/h;if(i<=c||i>u)return"continue";var a,n=2*(e[0].x-2*e[1].x+e[2].x)*i+2*e[1].x-2*e[0].x,s=2*(e[0].y-2*e[1].y+e[2].y)*i+2*e[1].y-2*e[0].y,f=Ft(e,i),m=zt(e,i),p=0;p=Math.abs(m)<1e-12?1/0:m===1/0||m===-1/0?0:-1/m,a=p===1/0?f.y:f.y-p*f.x;var g=void 0,v=void 0;p===1/0?(g=[f.x,f.x],v=[f.y-o,f.y+o]):v=(g=Et([Math.pow(f.x,2)+Math.pow(a,2)-2*f.y*a+Math.pow(f.y,2)-Math.pow(o,2),2*(a*p-f.x-f.y*p),Math.pow(p,2)+1])).map(function(e){return p*e+a});var y=qe(g[0]-f.x,v[0]-f.y,n,s)>=0?0:1;r&&(y=(y+1)%2),hm[l]===y?d.push({x:g[0],y:v[0],t:i}):d.push({x:g[1],y:v[1],t:i})},m=0;m<=h;m++)f(m);return d}}function fm(e,t,r){var i=e[t]=e[t]||[];r.isVisited?(i.unshift(r),r.isVisited=!1):(i.push(r),r.isVisited=!0)}var mm=0;function pm(e,t){for(var r,i,a=[],n=1,o=e.length;n<o;n++){var s=e[n-1],c=s.x,u=s.y,l=s.t,h=e[n],d=h.x,f=h.y,m=h.t;(d<c||c===d&&f<u)&&(c=(r=[d,c])[0],d=r[1],u=(i=[f,u])[0],f=i[1]);var p=[c,Math.min(u,f),d,Math.max(u,f)];a.push({id:mm++,x1:c,y1:u,x2:d,y2:f,bbox:p,belong:t,isVisited:!1,isDeleted:!1,t:.5*(l+m)})}return a}var gm,vm=function(e){function r(t){var r=e.call(this,t)||this;return r.props=t,r.points=[],t.points.forEach(function(e){r.points.push(si(e))}),r.isClosed=t.isClosed||!1,r}return t(r,e),r.prototype.lay=function(t){e.prototype.lay.call(this,t),this.coords=void 0},r.prototype.calRepaintStyle=function(t){e.prototype.calRepaintStyle.call(this,t),this.coords=void 0,this._rect=void 0},r.prototype.buildPoints=function(){this.coords||(this.coords=function(e,t,r,i){if(void 0===r&&(r=1),void 0===i&&(i=1),!e.length)return[];for(var a=[],n=!1,o=0,s=e.length;o<s;o++)(O=e[o]).absX=(O.x||0)*r,O.absY=(O.y||0)*i,O.absTx=O.tx*r,O.absTy=O.ty*i,O.absFx=O.fx*r,O.absFy=O.fy*i,sm(O)&&(n=!0);var c=[];if(n){o=0;for(var u=e.length;o<u;o++){var l=e[o];if(sm(l)){var h=(o+1)%u,d=e[o?o-1:u-1],f=e[h],m=l.cornerRadius,p=sm(d),g=p||d.curveMode===ce.STRAIGHT||!d.hasCurveFrom,v=sm(f),y=v||f.curveMode===ce.STRAIGHT||!f.hasCurveTo;c[o]=g&&y?cm(d,l,f,p,v,m):um(d,l,f,p,v,m)}}}for(var b=e.map(function(e){return Object.assign({},e)}),x=(o=0,b.length);o<x;o++){var T=c[o];if(T){var w=T.prevTangent,k=T.prevHandle,S=T.nextTangent,E=T.nextHandle,C={x:0,y:0,cornerRadius:0,curveMode:ce.NONE,hasCurveFrom:!0,fx:0,fy:0,hasCurveTo:!1,tx:0,ty:0,absX:w.x,absY:w.y,absFx:k.x,absFy:k.y,absTx:0,absTy:0,dspX:0,dspY:0,dspFx:0,dspFy:0,dspTx:0,dspTy:0},A={x:0,y:0,cornerRadius:0,curveMode:ce.NONE,hasCurveFrom:!1,fx:0,fy:0,hasCurveTo:!0,tx:0,ty:0,absX:S.x,absY:S.y,absFx:0,absFy:0,absTx:E.x,absTy:E.y,dspX:0,dspY:0,dspFx:0,dspFy:0,dspTx:0,dspTy:0};if(T.t1){var _=Bt([{x:(D=b[(o+x-1)%x]).absX,y:D.absY},{x:D.absFx,y:D.absFy},{x:b[o].absX,y:b[o].absY}],0,T.t1);D.absFx=_[1].x,D.absFy=_[1].y}if(T.t2){var M=b[(o+1)%x];_=Bt([{x:M.absX,y:M.absY},{x:M.absTx,y:M.absTy},{x:b[o].absX,y:b[o].absY}],0,1-T.t2),M.absTx=_[1].x,M.absTy=_[1].y}b.splice(o,1,C,A),o++,x++,c.splice(o,0,void 0)}}var I=b[0],R=[I.absX,I.absY];a.push(R);var P=b.length;for(o=1;o<P;o++){var O=b[o],D=b[o-1],B=[O.absX,O.absY];O.hasCurveTo&&B.unshift(O.absTx,O.absTy),D.hasCurveFrom&&B.unshift(D.absFx,D.absFy),a.push(B)}if(t){var F=b[P-1],L=[I.absX,I.absY];I.hasCurveTo&&L.unshift(I.absTx,I.absTy),F.hasCurveFrom&&L.unshift(F.absFx,F.absFy),a.push(L)}return a}(this.points,this.isClosed,this.width,this.height))},r.prototype.calContent=function(){return this.buildPoints(),this.hasContent=!!this.coords&&this.coords.length>1},r.prototype.isLine=function(){this.buildPoints();var e=this.coords;return!!e&&2===e.length&&2===e[0].length&&2===e[1].length},r.prototype.refresh=function(t,r){void 0===t&&(t=ci.REPAINT),t>=ci.REPAINT&&(this.coords=void 0),e.prototype.refresh.call(this,t,r)},r.prototype.renderCanvas=function(){e.prototype.renderCanvas.call(this),this.buildPoints();var t=this.coords;t&&t.length&&this.renderFillStroke([t],!1)},Object.defineProperty(r.prototype,"rect",{get:function(){var e=this._rect;if(!e){e=this._rect=new Float32Array(4),this.buildPoints();var t=this.coords;t&&t.length&&function(e,t){var r=!0;t=t||new Float32Array(4);for(var i=0,a=0,n=0,o=e.length;n<o;n++){var s=e[n];if(r){if(!(c=di(s,t))){oe.error("Unsupported point data: "+n+" - "+s.join(","));continue}i=c.x,a=c.y,r=!1}else{var c;if(!(c=fi(s,i,a,t))){oe.error("Unsupported point data: "+n+" - "+s.join(","));continue}i=c.x,a=c.y}}}(t,e)}return e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"bbox",{get:function(){var e=this._bbox;if(!e){var t=this._rect||this.rect;e=this._bbox=t.slice(0),this.buildPoints();var r=this.computedStyle,i=r.strokeWidth,a=r.strokeEnable,n=r.strokePosition,o=r.strokeLinecap,s=r.strokeLinejoin,c=r.strokeMiterlimit,u=this.isClosed,l=0;i.forEach(function(e,t){a[t]&&(n[t]===J.OUTSIDE&&u?l=Math.max(l,e):n[t]!==J.CENTER&&u||(l=Math.max(l,.5*e)))});var h=e[0]-l,d=e[1]-l,f=e[2]+l,m=e[3]+l;e=this._bbox=u?function(e,t,r,i,a){var n=e.slice(0);if(i===Z.ROUND)return n[0]-=t,n[1]-=t,n[2]+=t,n[3]+=t,n;if(!r.length)return n;for(var o=[],s=[],c=r[0],u=c[0],l=c[1],h=1,d=r.length;h<d;h++){var f=0,m=0;2===(y=r[h]).length?(f=y[0]-u,m=y[1]-l,u=y[0],l=y[1],o.push([f,m])):4===y.length?(f=2*(u-2*y[0]+y[2])+2*y[0]-2*u,m=2*(l-2*y[1]+y[3])+2*y[1]-2*l,u=y[2],l=y[3],o.push([f,m])):6===y.length&&(f=3*(-u+3*y[0]-3*y[2]+y[4])+2*(3*u-6*y[0]+3*y[2])+3*y[0]-3*u,m=3*(-l+3*y[1]-3*y[3]+y[5])+2*(3*l-6*y[1]+3*y[3])+3*y[1]-3*l,u=y[4],l=y[5],o.push([f,m]));var p=Math.atan(Math.abs(m/f)),g=Math.sin(p)*t,v=Math.cos(p)*t;f>=0?m>=0?s.push([-g,v]):s.push([g,v]):m>=0?s.push([-g,-v]):s.push([g,-v])}for(h=0,d=o.length;h<d;h++){var y=o[h],b=o[(h+1)%d];if(y[0]&&y[1]&&b[0]&&b[1]){var x=qe(y[0],y[1],b[0],b[1]),T=s[h],w=s[(h+1)%d];if(T[0]||T[1]||w[0]||w[1]){var k=0,S=0,E=0,C=0,A=[y[0]+T[0],y[1]+T[1]],_=qe(y[0],y[1],A[0],A[1]);x>=0&&_>=0||x<0&&_<0?(k=-T[0],S=-T[1]):(k=T[0],S=T[1]);var M=[b[0]+w[0],b[1]+w[1]],I=qe(b[0],b[1],M[0],M[1]);x>=0&&I>=0||x<0&&I<0?(E=-w[0],C=-w[1]):(E=w[0],C=w[1]);var R=r[h],P=r[h+1],O=r[(h+2)%d],D=R.length,B=P.length,F=O.length,L=R[D-2]+k,N=R[D-1]+S,U=P[B-2]+k,z=P[B-1]+S,W=P[B-2]+E,V=P[B-1]+C,H=cr(L,N,U,z,W,V,O[F-2]+E,O[F-1]+C,!1);if(H&&1!==H.toSource&&0!==H.toClip)if(i===Z.BEVEL)if((q=2*t/Math.sqrt(Math.pow(W-U,2)+Math.pow(V-z,2)))>=1)n[0]=Math.min(n[0],U,W),n[1]=Math.min(n[1],z,V),n[2]=Math.max(n[2],U,W),n[3]=Math.max(n[3],z,V);else{var X=H.x-(H.x-U)*q,j=H.y-(H.y-z)*q,G=H.x-(H.x-W)*q,Y=H.y-(H.y-V)*q;n[0]=Math.min(n[0],X,G),n[1]=Math.min(n[1],j,Y),n[2]=Math.max(n[2],X,G),n[3]=Math.max(n[3],j,Y)}else if(i===Z.MITER){var q;if((q=Math.sqrt(Math.pow(H.x-P[B-2],2)+Math.pow(H.y-P[B-1],2))/t)>a){var K=2*t/Math.sqrt(Math.pow(W-U,2)+Math.pow(V-z,2));K>=1?(n[0]=Math.min(n[0],U,W),n[1]=Math.min(n[1],z,V),n[2]=Math.max(n[2],U,W),n[3]=Math.max(n[3],z,V)):(X=H.x-(H.x-U)*K,j=H.y-(H.y-z)*K,G=H.x-(H.x-W)*K,Y=H.y-(H.y-V)*K,n[0]=Math.min(n[0],X,G),n[1]=Math.min(n[1],j,Y),n[2]=Math.max(n[2],X,G),n[3]=Math.max(n[3],j,Y))}else n[0]=Math.min(n[0],H.x),n[1]=Math.min(n[1],H.y),n[2]=Math.max(n[2],H.x),n[3]=Math.max(n[3],H.y)}}}}return n}(e,l,this.coords||[],s,c):function(e,t,r,i){var a=e.slice(0);if(i===Q.ROUND&&(a[0]-=t,a[1]-=t,a[2]+=t,a[3]+=t),!r.length)return a;for(var n=r[0],o=r[r.length-1],s=o.length,c=[],u=0;u<s;u+=2)c.push({x:o[u],y:o[u+1]});var l=0,h=0;s>2?(l=Math.abs(zt(c,0)),h=Math.abs(zt(c,1))):l=h=Math.abs(o[s-1]-n[1])/Math.abs(o[s-2]-n[0]);var d=Math.atan(l),f=Math.atan(h),m=Math.sin(d),p=Math.cos(d),g=Math.sin(f),v=Math.cos(f),y=m===1/0?t:Math.abs(m*t),b=p===1/0?t:Math.abs(p*t),x=g===1/0?t:Math.abs(g*t),T=v===1/0?t:Math.abs(v*t);return i===Q.BUTT?(a[0]=Math.min(a[0],n[0]-y,o[s-2]-x),a[1]=Math.min(a[1],n[1]-b,o[s-1]-T),a[2]=Math.max(a[2],n[0]+y,o[s-2]+x),a[3]=Math.max(a[3],n[1]+b,o[s-1]+T)):i===Q.SQUARE&&(a[0]=Math.min(a[0],n[0]-y-b,o[s-2]-x-T),a[1]=Math.min(a[1],n[1]-y-b,o[s-1]-x-T),a[2]=Math.max(a[2],n[0]+y+b,o[s-2]+x+T),a[3]=Math.max(a[3],n[1]+y+b,o[s-1]+x+T)),a}(e,l,this.coords||[],o),e[0]=Math.min(e[0],h),e[1]=Math.min(e[1],d),e[2]=Math.max(e[2],f),e[3]=Math.max(e[3],m)}return e},enumerable:!1,configurable:!0}),r}(ka),ym={Container:Ba,Bitmap:Oa,Node:ka,Root:Jf,Video:ef,Audio:Sf,Text:om,Lottie:Ff,Polyline:vm};!function(e){e[e.NONE=0]="NONE",e[e.LOADING=1]="LOADING",e[e.LOADED=2]="LOADED"}(gm||(gm={}));var bm,xm={};!function(e){e[e.NONE=0]="NONE",e[e.LOADING=1]="LOADING",e[e.LOADED=2]="LOADED"}(bm||(bm={}));var Tm={};var wm,km={type:_,Event:M,inject:oe,opentype:Le,loadImg:Ea,loadAudio:function(e,t){return i(this,void 0,void 0,function(){var r,i,n,o;return a(this,function(a){switch(a.label){case 0:if(r=xm[e]){if(r.count++,r.state===gm.LOADED)return[2,r.res];if(r.state===gm.LOADING)return[2,new Promise(function(e){r.list.push(e)})]}return r=xm[e]={state:gm.LOADING,list:[],count:0,res:{success:!1,duration:0,release:function(){r.count--,r.count<=0&&(r.res.audioBuffer=void 0,delete xm[e])}}},[4,fetch(e,Object.assign({mode:"cors"},t))];case 1:return 200!==(i=a.sent()).status&&304!==i.status?(r.state=gm.LOADED,[2,r.res]):[4,i.arrayBuffer()];case 2:return n=a.sent(),[4,(new AudioContext).decodeAudioData(n)];case 3:return o=a.sent(),r.count++,[2,new Promise(function(e){r.res.success=!0,r.res.audioBuffer=o,r.res.duration=Math.ceil(1e3*o.duration),r.state=gm.LOADED,e(r.res),r.list.splice(0).forEach(function(e){r.count++,e(r.res)})})]}})})},loadFont:function(e,t,r){return i(this,void 0,void 0,function(){var i,n,o;return a(this,function(a){switch(a.label){case 0:if(i=Tm[e]){if(i.count++,i.state===bm.LOADED)return[2,i.res];if(i.state===bm.LOADING)return[2,new Promise(function(e){i.list.push(e)})]}return i=Tm[e]={state:bm.LOADING,list:[],count:0,res:{success:!1,release:function(){i.count--,i.count<=0&&delete Tm[e]}}},[4,fetch(e,Object.assign({mode:"cors"},r))];case 1:return 200!==(n=a.sent()).status&&304!==n.status?(i.state=bm.LOADED,[2,i.res]):[4,n.arrayBuffer()];case 2:return o=a.sent(),[4,Xe.registerAb(o,t)];case 3:return a.sent(),i.count++,[2,new Promise(function(e){i.res.success=!0,i.res.arrayBuffer=o,i.state=bm.LOADED,e(i.res),i.list.splice(0).forEach(function(e){i.count++,e(i.res)})})]}})})},loadRange:Hd,MbVideoDecoder:Jd,MbVideoDecoderEvent:jd,MbVideoEncoder:Zf,MbVideoEncoderEvent:Kf,sound:$f},Sm={font:Xe,transform:Rr,define:le,css:ui,color:pe},Em=function(){function e(e,t){this.root=e,this.dom=t;var r=this.select=document.createElement("div");r.className="select",r.style.display="none",r.innerHTML='\n <div class="sub"></div>\n <span class="l">\n <b></b>\n </span>\n <span class="t">\n <b></b>\n </span>\n <span class="r">\n <b></b>\n </span>\n <span class="b">\n <b></b>\n </span>\n <span class="tl">\n <b></b>\n </span>\n <span class="tr">\n <b></b>\n </span>\n <span class="br">\n <b></b>\n </span>\n <span class="bl">\n <b></b>\n </span>\n',t.appendChild(r)}return e.prototype.showSelect=function(e){this.updateSelect(e),this.select.style.display="block"},e.prototype.updateSelect=function(e){var t=this.select.querySelector(".sub");if(1===e.length){t.innerHTML="",this.select.classList.remove("multi"),e[0].computedStyle.visibility===te.VISIBLE?this.select.classList.remove("hide"):this.select.classList.add("hide");var r=this.calRect(e[0]);this.select.style.left=r.left+"px",this.select.style.top=r.top+"px",this.select.style.width=r.width+"px",this.select.style.height=r.height+"px",this.select.style.transform=r.transform}},e.prototype.calRect=function(e){var t=this.root.canvas,r=e._rect||e.rect,i=e.matrixWorld,a=t.clientWidth/t.width,n=t.clientHeight/t.height;if(1!==a||1!==n){var o=at();i=ot(o,i),vt(o,a),yt(o,n),i=ot(o,i)}var s=Tt(r[0],r[1],r[2],r[3],i),c=s.x1,u=s.y1,l=s.x2,h=s.y2,d=s.x3,f=s.y3;s.x4,s.y4;var m={left:c,top:u,width:Math.sqrt(Math.pow(c-l,2)+Math.pow(u-h,2)),height:Math.sqrt(Math.pow(l-d,2)+Math.pow(h-f,2)),transform:""};if(l>c){if(h!==u){var p=mr(Math.atan((h-u)/(l-c)));m.transform="rotateZ(".concat(p,"deg)")}}else if(l<c){p=mr(Math.atan((h-u)/(l-c)));m.transform="rotateZ(".concat(p+180,"deg)")}else h>u?m.transform="rotateZ(90deg)":h<u&&(m.transform="rotateZ(-90deg)");return m},e.prototype.hideSelect=function(){this.select.style.display="none"},e.prototype.release=function(){this.select.remove()},e.prototype.metaKey=function(e){e?this.select.classList.add("rotate"):this.select.classList.remove("rotate")},e.prototype.isSelectControlDom=function(e){return e.parentElement===this.select},e.prototype.getAspectRatio=function(){var e=this.select.style;return{x:parseFloat(e.left),y:parseFloat(e.top),w:parseFloat(e.width),h:parseFloat(e.height)}},e}();!function(e){e[e.NORMAL=0]="NORMAL",e[e.HAND=1]="HAND",e[e.RESIZE=2]="RESIZE",e[e.EDIT_TEXT=3]="EDIT_TEXT",e[e.EDIT_GRADIENT=4]="EDIT_GRADIENT",e[e.EDIT_GEOM=5]="EDIT_GEOM",e[e.ADD_TEXT=6]="ADD_TEXT",e[e.ADD_RECT=7]="ADD_RECT",e[e.ADD_OVAL=8]="ADD_OVAL",e[e.ADD_ROUND=9]="ADD_ROUND",e[e.ADD_TRIANGLE=10]="ADD_TRIANGLE",e[e.ADD_LINE=11]="ADD_LINE",e[e.ADD_STAR=12]="ADD_STAR",e[e.ADD_IMG=13]="ADD_IMG",e[e.ADD_PEN=14]="ADD_PEN",e[e.ADD_CUSTOM_GEOM=15]="ADD_CUSTOM_GEOM"}(wm||(wm={}));var Cm,Am=wm,_m="cursor",Mm="content",Im="state_change",Rm={SELECT:"select",MOVE:"move",REMOVE:"remove",ADD:"add",RESIZE:"resize",ROTATE:"rotate",CURSOR:_m,CONTENT:Mm,STATE_CHANGE:Im},Pm=function(e){this.nodes=e},Om=function(e){function r(t,r){var i=e.call(this,t)||this;return i.data=r,i}return t(r,e),r.prototype.execute=function(){var e=this.nodes,t=this.data;e.forEach(function(e,i){var a=t[i],n=a.dx,o=a.dy,s=e.getStyle(),c=e.computedStyle;r.operate(e,c,n,o),e.endPosChange(s,n,o),e.checkPosSizeUpward()})},r.prototype.undo=function(){var e=this.nodes,t=this.data;e.forEach(function(e,i){var a=t[i],n=a.dx,o=a.dy,s=e.getStyle(),c=e.computedStyle;r.operate(e,c,-n,-o),e.endPosChange(s,-n,-o),e.checkPosSizeUpward()})},r.operate=function(e,t,r,i){e.updateStyle({translateX:t.translateX+r,translateY:t.translateY+i})},r}(Pm);var Dm=function(){function e(e){void 0===e&&(e=100),this.commands=[],this.commandsR=[],this.size=Math.max(1,e),this.lastTime=0}return e.prototype.addCommand=function(e,t){void 0===t&&(t=!1),this.commandsR.splice(0);var r=this.commands.length;if(!t&&r>0){var i=this.commands[r-1];if(Date.now()-this.lastTime<L.historyTime&&function(e,t){if(e.constructor!==t.constructor)return!1;var r=e.nodes,i=t.nodes;if(r.length!==i.length)return!1;for(var a=0,n=r.length;a<n;a++)if(r[a]!==i[a])return!1;return!0}(i,e)){var a=!0;if(i instanceof Om){var n=e.data;i.data.forEach(function(e,t){e.dx+=n[t].dx,e.dy+=n[t].dy})}else a=!1;if(a)return void(this.lastTime=Date.now())}}this.lastTime=Date.now(),r>=this.size&&this.commands.slice(0,r-this.size+1),this.commands.push(e)},e.prototype.undo=function(){if(this.commands.length){var e=this.commands.pop();return e.undo(),this.commandsR.push(e),e}},e.prototype.redo=function(){if(this.commandsR.length){var e=this.commandsR.pop();return e.execute(),this.commands.push(e),e}},e.getInstance=function(){return Cm||(Cm=new e),Cm},e}();var Bm,Fm=function(e){function r(t,r){var i=e.call(this,t)||this;return i.data=r,i}return t(r,e),r.prototype.execute=function(){this.nodes.forEach(function(e){e.remove()})},r.prototype.undo=function(){var e=this.nodes,t=this.data;e.forEach(function(e,r){!function(e,t){var r=e.style,i=e.computedStyle,a=t.x,n=t.y,o=t.parent,s=t.index,c=C(r.top),u=C(r.right),l=C(r.bottom),h=C(r.left),d=C(r.width),f=C(r.height);r.left={v:a,u:V.PX},r.right={v:0,u:V.AUTO},r.top={v:n,u:V.PX},r.bottom={v:0,u:V.AUTO},r.width={v:i.width,u:V.PX},r.height={v:i.height,u:V.PX},function(e,t,r){var i=e.children;r<=0?e.prependChild(t):r>=i.length?e.appendChild(t):i[r].insertAfter(t)}(o,e,s),h.u===V.PERCENT?r.left={v:100*i.left/o.width,u:V.PERCENT}:h.u===V.PX?r.left={v:i.left,u:V.PX}:h.u===V.AUTO&&(r.left={v:0,u:V.AUTO}),u.u===V.PERCENT?r.right={v:100*i.right/o.width,u:V.PERCENT}:u.u===V.PX?r.right={v:i.right,u:V.PX}:u.u===V.AUTO&&(r.right={v:0,u:V.AUTO}),c.u===V.PERCENT?r.top={v:100*i.top/o.height,u:V.PERCENT}:c.u===V.PX?r.top={v:i.top,u:V.PX}:c.u===V.AUTO&&(r.top={v:0,u:V.AUTO}),l.u===V.PERCENT?r.bottom={v:100*i.bottom/o.height,u:V.PERCENT}:l.u===V.PX?r.bottom={v:i.bottom,u:V.PX}:l.u===V.AUTO&&(r.bottom={v:0,u:V.AUTO}),d.u===V.PERCENT?r.width={v:100*i.width/o.width,u:V.PERCENT}:d.u===V.PX?r.width={v:i.width,u:V.PX}:d.u===V.AUTO&&(r.width={v:0,u:V.AUTO}),f.u===V.PERCENT?r.height={v:100*i.height/o.height,u:V.PERCENT}:f.u===V.PX?r.height={v:i.height,u:V.PX}:f.u===V.AUTO&&(r.height={v:0,u:V.AUTO})}(e,t[r])})},r.operate=function(e){var t=e.parent,r=t.children.indexOf(e),i={x:e.computedStyle.left,y:e.computedStyle.top,parent:t,index:r};return e.remove(),i},r}(Pm);function Lm(e,t,r,i){void 0===i&&(i=!1);var a=e.style,n={};if(r>t.height){r-=t.height,r=Math.max(r,1),a.top.u===V.PX?n.top=t.top+t.height:a.left.u===V.PERCENT&&(n.top=100*(t.top+t.height)/e.parent.height+"%");var o=Object.assign({},t);o.height=0,Object.assign(n,Nm(e,o,r)),n.scaleY=-1*t.scaleY}else r=Math.min(r,t.height-1),n.scaleY=t.scaleY,a.top.u===V.PX||a.top.u===V.PERCENT?(a.top.u===V.PX?n.top=t.top+r:n.top=100*(t.top+r)/e.parent.height+"%",a.height.u===V.PX||a.height.u===V.AUTO&&a.bottom.u===V.AUTO?n.height=t.height-r:a.height.u===V.PERCENT&&(n.height=100*(t.height-r)/e.parent.height+"%")):a.height.u!==V.PX&&a.height.u!==V.PERCENT&&a.height.u!==V.AUTO||(a.height.u===V.PX||a.height.u===V.AUTO?n.height=t.height-r:n.height=100*(t.height-r)/e.parent.height+"%");if(i){var s=Nm(e,t,-r);s.height&&("number"==typeof s.height?s.height=t.height-2*r:s.height=100*(t.height-2*r)/e.parent.height+"%"),Object.assign(n,s)}return n}function Nm(e,t,r,i){void 0===i&&(i=!1);var a=e.style,n={};if(r<-t.height){r+=t.height,r=Math.min(r,-1),a.bottom.u===V.PX?n.bottom=t.bottom+t.height:a.bottom.u===V.PERCENT&&(n.bottom=100*(t.bottom+t.height)/e.parent.height+"%");var o=Object.assign({},t);o.height=0,Object.assign(n,Lm(e,o,r)),n.scaleY=-1*t.scaleY}else r=Math.max(r,1-t.height),n.scaleY=t.scaleY,a.bottom.u===V.PX||a.bottom.u===V.PERCENT?(a.bottom.u===V.PX?n.bottom=t.bottom-r:n.bottom=100*(t.bottom-r)/e.parent.height+"%",a.height.u===V.PX||a.height.u===V.AUTO&&a.top.u===V.AUTO?n.height=t.height+r:a.height.u===V.PERCENT&&(n.height=100*(t.height+r)/e.parent.height+"%")):a.height.u!==V.PX&&a.height.u!==V.PERCENT&&a.height.u!==V.AUTO||(a.height.u===V.PX||a.height.u===V.AUTO?n.height=t.height+r:n.height=100*(t.height+r)/e.parent.height+"%");if(i){var s=Lm(e,t,-r);s.height&&("number"==typeof s.height?s.height=t.height+2*r:s.height=100*(t.height+2*r)/e.parent.height+"%"),Object.assign(n,s)}return n}function Um(e,t,r,i){void 0===i&&(i=!1);var a=e.style,n={};if(r>t.width){r-=t.width,r=Math.max(r,1),a.left.u===V.PX?n.left=t.left+t.width:a.left.u===V.PERCENT&&(n.left=100*(t.left+t.width)/e.parent.width+"%");var o=Object.assign({},t);o.width=0,Object.assign(n,zm(e,o,r)),n.scaleX=-1*t.scaleX}else r=Math.min(r,t.width-1),n.scaleX=t.scaleX,a.left.u===V.PX||a.left.u===V.PERCENT?(a.left.u===V.PX?n.left=t.left+r:n.left=100*(t.left+r)/e.parent.width+"%",a.width.u===V.PX||a.width.u===V.AUTO&&a.right.u===V.AUTO?n.width=t.width-r:a.width.u===V.PERCENT&&(n.width=100*(t.width-r)/e.parent.width+"%")):a.width.u!==V.PX&&a.width.u!==V.PERCENT&&a.width.u!==V.AUTO||(a.width.u===V.PX||a.width.u===V.AUTO?n.width=t.width-r:n.width=100*(t.width-r)/e.parent.width+"%");if(i){var s=zm(e,t,-r);s.width&&("number"==typeof s.width?s.width=t.width-2*r:s.width=100*(t.width-2*r)/e.parent.width+"%"),Object.assign(n,s)}return n}function zm(e,t,r,i){void 0===i&&(i=!1);var a=e.style,n={};if(r<-t.width){r+=t.width,r=Math.min(r,-1),a.right.u===V.PX?n.right=t.right+t.width:a.right.u===V.PERCENT&&(n.right=100*(t.right+t.width)/e.parent.width+"%");var o=Object.assign({},t);o.width=0,Object.assign(n,Um(e,o,r)),n.scaleX=-1*t.scaleX}else r=Math.max(r,1-t.width),n.scaleX=t.scaleX,a.right.u===V.PX||a.right.u===V.PERCENT?(a.right.u===V.PX?n.right=t.right-r:n.right=100*(t.right-r)/e.parent.width+"%",a.width.u===V.PX||a.width.u===V.AUTO&&a.left.u===V.AUTO?n.width=t.width+r:a.width.u===V.PERCENT&&(n.width=100*(t.width+r)/e.parent.width+"%")):a.width.u!==V.PX&&a.width.u!==V.PERCENT&&a.width.u!==V.AUTO||(a.width.u===V.PX||a.width.u===V.AUTO?n.width=t.width+r:n.width=100*(t.width+r)/e.parent.width+"%");if(i){var s=Um(e,t,-r);s.width&&("number"==typeof s.width?s.width=t.width+2*r:s.width=100*(t.width+2*r)/e.parent.width+"%"),Object.assign(n,s)}return n}function Wm(e,t,r){var i=r*(t.width/t.height),a=Um(e,t,.5*-i),n=zm(e,t,.5*i),o=Object.assign({},a,n);if(o.width)if("number"==typeof o.width){var s=o.width-t.width;o.width=t.width+2*s}else{var c=e.parent.width;s=parseFloat(o.width)*c*.01-t.width;o.width=100*(t.width+2*s)/c+"%"}return o}function Vm(e,t,r,i){void 0===i&&(i=!1);var a=Lm(e,t,r);if(i){var n=Nm(e,t,-r);n.height&&("number"==typeof n.height?n.height=t.height-2*r:n.height=100*(t.height-2*r)/e.parent.height+"%"),Object.assign(a,n)}var o=Wm(e,t,i?2*-r:-r);return Object.assign(a,o)}function Hm(e,t,r,i){void 0===i&&(i=!1);var a=Nm(e,t,r);if(i){var n=Lm(e,t,-r);n.height&&("number"==typeof n.height?n.height=t.height+2*r:n.height=100*(t.height+2*r)/e.parent.height+"%"),Object.assign(a,n)}var o=Wm(e,t,i?2*r:r);return Object.assign(a,o)}function Xm(e,t,r){var i=r/(t.width/t.height),a=Lm(e,t,.5*-i),n=Nm(e,t,.5*i),o=Object.assign({},a,n);if(o.height)if("number"==typeof o.height){var s=o.height-t.height;o.height=t.height+2*s}else{var c=e.parent.height;s=parseFloat(o.height)*c*.01-t.height;o.height=100*(t.height+2*s)/c+"%"}return o}function jm(e,t,r,i){void 0===i&&(i=!1);var a=Um(e,t,r);if(i){var n=zm(e,t,-r);n.width&&("number"==typeof n.width?n.width=t.width-2*r:n.width=100*(t.width-2*r)/e.parent.width+"%"),Object.assign(a,n)}var o=Xm(e,t,i?2*-r:-r);return Object.assign(a,o)}function Gm(e,t,r,i){void 0===i&&(i=!1);var a=zm(e,t,r);if(i){var n=Um(e,t,-r);n.width&&("number"==typeof n.width?n.width=t.width+2*r:n.width=100*(t.width+2*r)/e.parent.width+"%"),Object.assign(a,n)}var o=Xm(e,t,i?2*r:r);return Object.assign(a,o)}function Ym(e,t,r,i){void 0===i&&(i=!0);var a=e.width,n=e.height,o=n/a;i||(o*=-1);var s=-1/o,c=a+t,u=n+r,l=(u-n+o*a-s*c)/(o-s);return{x:l,y:s*l-s*c+u}}function qm(e,t,r,i){i&&(e.left?"number"==typeof e.left?e.left+=i:e.left=parseFloat(e.left)+i/t.parent.width*100+"%":e.width||(t.style.left.u===V.PERCENT?e.left=100*(r.left+i)/t.parent.width+"%":t.style.left.u===V.PX&&(e.left=r.left+i)),e.right?"number"==typeof e.right?e.right-=i:e.right=parseFloat(e.right)-i/t.parent.width*100+"%":e.width||(t.style.right.u===V.PERCENT?e.right=100*(r.right-i)/t.parent.width+"%":t.style.right.u===V.PX&&(e.right=r.right-i)))}function Km(e,t,r,i){i&&(e.top?"number"==typeof e.top?e.top+=i:e.top=parseFloat(e.top)+i/t.parent.height*100+"%":e.height||(t.style.top.u===V.PERCENT?e.top=100*(r.top+i)/t.parent.height+"%":t.style.top.u===V.PX&&(e.top=r.top+i)),e.bottom?"number"==typeof e.bottom?e.bottom-=i:e.bottom=parseFloat(e.bottom)-i/t.parent.height*100+"%":e.height||(t.style.bottom.u===V.PERCENT?e.bottom=100*(r.bottom-i)/t.parent.height+"%":t.style.bottom.u===V.PX&&(e.bottom=r.bottom-i)))}function $m(e,t,r){var i=e*r.h/r.w,a=r.y+.5*r.h;return(t.y+.5*t.h-a)*i/r.h}function Qm(e,t,r){var i=e*r.w/r.h,a=r.x+.5*r.w;return(t.x+.5*t.w-a)*i/r.w}function Zm(e,t,r,i,a,n,o){void 0===n&&(n=!1),void 0===o&&(o=!1);var s=n?Vm(e,t,r*i.h/a.h,o):Lm(e,t,r*i.h/a.h,o),c=Qm(r,i,a);o&&(c*=2),qm(s,e,t,-c);return Km(s,e,t,o?-r*(i.y+.5*i.h-a.y-.5*a.h)*2/a.h:r*(a.y+a.h-i.y-i.h)/a.h),s}function Jm(e,t,r,i,a,n,o){void 0===n&&(n=!1),void 0===o&&(o=!1);var s=n?Hm(e,t,r*i.h/a.h,o):Nm(e,t,r*i.h/a.h,o);if(n){var c=Qm(r,i,a);o&&(c*=2),qm(s,e,t,c)}return Km(s,e,t,o?r*(i.y+.5*i.h-a.y-.5*a.h)*2/a.h:r*(i.y-a.y)/a.h),s}function ep(e,t,r,i,a,n,o){void 0===n&&(n=!1),void 0===o&&(o=!1);var s=n?jm(e,t,r*i.w/a.w,o):Um(e,t,r*i.w/a.w,o);if(n){var c=$m(r,i,a);o&&(c*=2),Km(s,e,t,-c)}return qm(s,e,t,o?-r*(i.x+.5*i.w-a.x-.5*a.w)*2/a.w:r*(a.x+a.w-i.x-i.w)/a.w),s}function tp(e,t,r,i,a,n,o){void 0===n&&(n=!1),void 0===o&&(o=!1);var s=n?Gm(e,t,r*i.w/a.w,o):zm(e,t,r*i.w/a.w,o);if(n){var c=$m(r,i,a);o&&(c*=2),Km(s,e,t,c)}return qm(s,e,t,o?r*(i.x+.5*i.w-a.x-.5*a.w)*2/a.w:r*(i.x-a.x)/a.w),s}function rp(e,t,r,i,a,n){var o=Zm(e,t,r,i,a);delete n.top,delete n.height,delete n.bottom,void 0!==o.top&&(n.top=o.top),void 0!==o.height&&(n.height=o.height),void 0!==o.bottom&&(n.bottom=o.bottom)}function ip(e,t,r,i,a,n){var o=Jm(e,t,r,i,a);delete n.top,delete n.height,delete n.bottom,void 0!==o.top&&(n.top=o.top),void 0!==o.height&&(n.height=o.height),void 0!==o.bottom&&(n.bottom=o.bottom)}!function(e){e[e.T=0]="T",e[e.R=1]="R",e[e.B=2]="B",e[e.L=3]="L",e[e.TL=4]="TL",e[e.TR=5]="TR",e[e.BL=6]="BL",e[e.BR=7]="BR"}(Bm||(Bm={}));var ap=function(e){function r(t,r){var i=e.call(this,t)||this;return i.data=r,i}return t(r,e),r.prototype.execute=function(){var e=this.nodes,t=this.data;e.forEach(function(e,i){var a=t[i],n=a.dx,o=a.dy,s=a.controlType,c=a.aspectRatio,u=a.clientRect,l=a.selectRect,h=a.fromCenter,d=a.widthToAuto,f=a.heightToAuto,m=e.getStyle();e.startSizeChange();var p=e.getComputedStyle(),g=e.getCssStyle();u?r.operateMultiAr(e,p,g,n,o,s,u,l,c,h,d,f):r.operate(e,p,g,n,o,s,c,h,d,f),e.endSizeChange(m),e.checkPosSizeUpward()})},r.prototype.undo=function(){var e=this.nodes,t=this.data;e.forEach(function(e,i){var a=t[i],n=a.dx,o=a.dy,s=a.controlType,c=a.aspectRatio,u=a.clientRect,l=a.selectRect,h=a.fromCenter,d=a.widthFromAuto,f=a.heightFromAuto,m=e.getStyle();e.startSizeChange();var p=e.getComputedStyle(),g=e.getCssStyle();s=function(e){return e}(s),u?r.operateMultiAr(e,p,g,-n,-o,s,u,l,c,h,d,f):r.operate(e,p,g,-n,-o,s,c,h,d,f),e.endSizeChange(m),e.checkPosSizeUpward()})},r.operate=function(e,t,r,i,a,n,o,s,c,u){void 0===s&&(s=!1),void 0===c&&(c=!1),void 0===u&&(u=!1);var l={left:r.left,right:r.right,top:r.top,bottom:r.bottom,width:r.width,height:r.height,scaleX:r.scaleX,scaleY:r.scaleY};o?n===Bm.T?Object.assign(l,Vm(e,t,a,s)):n===Bm.R?Object.assign(l,Gm(e,t,i,s)):n===Bm.B?Object.assign(l,Hm(e,t,a,s)):n===Bm.L?Object.assign(l,jm(e,t,i,s)):n===Bm.TL?Object.assign(l,function(e,t,r,i,a){void 0===a&&(a=!1);var n=Ym(t,r,i,!0),o=n.x,s=n.y,c=Um(e,t,o-t.width,a);return Object.assign(c,Lm(e,t,s-t.height,a)),c}(e,t,i,a,s)):n===Bm.TR?Object.assign(l,function(e,t,r,i,a){void 0===a&&(a=!1);var n=Ym(t,r,i,!1),o=n.x,s=n.y,c=zm(e,t,o-t.width,a);return Object.assign(c,Lm(e,t,s-t.height,a)),c}(e,t,i,a,s)):n===Bm.BL?Object.assign(l,function(e,t,r,i,a){void 0===a&&(a=!1);var n=Ym(t,r,i,!1),o=n.x,s=n.y,c=Um(e,t,o-t.width,a);return Object.assign(c,Nm(e,t,s-t.height,a)),c}(e,t,i,a,s)):n===Bm.BR&&Object.assign(l,function(e,t,r,i,a){void 0===a&&(a=!1);var n=Ym(t,r,i,!0),o=n.x,s=n.y,c=zm(e,t,o-t.width,a);return Object.assign(c,Nm(e,t,s-t.height,a)),c}(e,t,i,a,s)):(n===Bm.T||n===Bm.TL||n===Bm.TR?Object.assign(l,Lm(e,t,a,s)):n!==Bm.B&&n!==Bm.BL&&n!==Bm.BR||Object.assign(l,Nm(e,t,a,s)),n===Bm.L||n===Bm.TL||n===Bm.BL?Object.assign(l,Um(e,t,i,s)):n!==Bm.R&&n!==Bm.TR&&n!==Bm.BR||Object.assign(l,zm(e,t,i,s))),c&&(l.width="auto"),u&&(l.height="auto"),e.updateStyle(l)},r.operateMultiAr=function(e,t,r,i,a,n,o,s,c,u,l,h){void 0===u&&(u=!1),void 0===l&&(l=!1),void 0===h&&(h=!1);var d={left:r.left,right:r.right,top:r.top,bottom:r.bottom,width:r.width,height:r.height,scaleX:r.scaleX,scaleY:r.scaleY};if(n===Bm.T)Object.assign(d,Zm(e,t,a,o,s,c,u));else if(n===Bm.R)Object.assign(d,tp(e,t,i,o,s,c,u));else if(n===Bm.B)Object.assign(d,Jm(e,t,a,o,s,c,u));else if(n===Bm.L)Object.assign(d,ep(e,t,i,o,s,c,u));else{if(c){var f={width:s.w,height:s.h},m=Ym(f,i,a,[Bm.TL,Bm.BR].includes(n)),p=m.x,g=m.y;i=p-f.width,a=g-f.height}n===Bm.TL?Object.assign(d,function(e,t,r,i,a,n,o,s){void 0===o&&(o=!1),void 0===s&&(s=!1);var c=ep(e,t,r,a,n,o,s);if(s)return c;if(o)rp(e,t,i,a,n,c);else{var u=Zm(e,t,i,a,n,o,s);Object.assign(c,u)}return c}(e,t,i,a,o,s,c,u)):n===Bm.TR?Object.assign(d,function(e,t,r,i,a,n,o,s){void 0===o&&(o=!1),void 0===s&&(s=!1);var c=tp(e,t,r,a,n,o,s);if(s)return c;if(o)rp(e,t,i,a,n,c);else{var u=Zm(e,t,i,a,n,o,s);Object.assign(c,u)}return c}(e,t,i,a,o,s,c,u)):n===Bm.BL?Object.assign(d,function(e,t,r,i,a,n,o,s){void 0===o&&(o=!1),void 0===s&&(s=!1);var c=ep(e,t,r,a,n,o,s);if(s)return c;if(o)ip(e,t,i,a,n,c);else{var u=Jm(e,t,i,a,n,o,s);Object.assign(c,u)}return c}(e,t,i,a,o,s,c,u)):n===Bm.BR&&Object.assign(d,function(e,t,r,i,a,n,o,s){void 0===o&&(o=!1),void 0===s&&(s=!1);var c=tp(e,t,r,a,n,o,s);if(s)return c;if(o)ip(e,t,i,a,n,c);else{var u=Jm(e,t,i,a,n,o,s);Object.assign(c,u)}return c}(e,t,i,a,o,s,c,u))}l&&(d.width="auto"),h&&(d.height="auto"),e.updateStyle(d)},r}(Pm);var np=function(e){function r(t,r){var i=e.call(this,t)||this;return i.data=r,i}return t(r,e),r.prototype.execute=function(){var e=this.nodes,t=this.data;e.forEach(function(e,r){e.updateStyle(t[r].next)})},r.prototype.undo=function(){var e=this.nodes,t=this.data;e.forEach(function(e,r){e.updateStyle(t[r].prev)})},r}(Pm),op=function(e){function r(t,r){return e.call(this,t,r)||this}return t(r,e),r}(np);function sp(e,t,r){for(var i=e.children,a=i.length-1;a>=0;a--){var n=i[a],o=n.matrixWorld;if(n.hasContent&&n.computedStyle.visibility!==te.HIDDEN&&n.computedStyle.pointerEvents){var s=n._rect||n.rect;if(gr(t,r,s[0],s[1],s[2],s[3],o,!0)){if(n instanceof Ba){var c;if(c=sp(n,t,r))return c}else{var u=n.prev;if(u&&cp(u,t,r))return u}return n}if(n instanceof Ba&&(c=sp(n,t,r)))return c}}}function cp(e,t,r){var i=e.computedStyle;if(i.maskMode!==$.NONE&&i.pointerEvents){var a=e._rect||e.rect,n=e.matrixWorld;return gr(t,r,a[0],a[1],a[2],a[3],n,!0)}return!1}function up(e,t,r,i){return sp(e,t,r)}var lp=function(e){function r(t,r){var i=e.call(this,t)||this;return i.data=r,i}return t(r,e),r.prototype.execute=function(){var e=this.nodes,t=this.data;e.forEach(function(e,r){e.beforeEdit(),e.cursor=t[r].next.cursor,e.content=t[r].next.content,e.rich=t[r].next.rich,e.afterEdit()})},r.prototype.undo=function(){var e=this.nodes,t=this.data;e.forEach(function(e,r){e.beforeEdit(),e.cursor=t[r].prev.cursor,e.content=t[r].prev.content,e.rich=t[r].prev.rich,e.afterEdit()})},r}(Pm),hp=function(){function e(e,t,r){var i=this;this.root=e,this.dom=t,this.listener=r,this.ignoreBlur=[],this.ignoreBlurUnFocus=[],this.hasBlur=!0;var a=this.containerEl=document.createElement("div");a.className="input",a.style.position="absolute",a.style.pointerEvents="none",a.style.opacity="0",t.appendChild(a);var n=this.inputEl=document.createElement("input");n.style.position="absolute",n.style.left="0px",n.style.top="0px",n.style.width="10px",n.style.height="100%",n.style.boxSizing="content-box",n.style.border="none",n.style.pointerEvents="none",n.style.opacity="0",n.type="text",n.autocomplete="off",n.spellcheck=!1,a.appendChild(n);var o=function(e){if(i.node){var t=i.node.content,a=i.node.getRich(),o=i.node.getCursor();e(),i.updateCursor(),i.showCursor(),n.value="",i.listener.select.updateSelect([i.node]),r.emit([Mm,_m],[i.node]),i.listener.history.addCommand(new lp([i.node],[{prev:{content:t,rich:a,cursor:o},next:{content:i.node.content,rich:i.node.getRich(),cursor:i.node.getCursor()}}]),i.hasBlur),i.hasBlur=!1}},s=function(e){e&&o(function(){var t;null===(t=i.node)||void 0===t||t.input(e)})},c=!1;n.addEventListener("keydown",function(e){var t=e.keyCode,a=e.code;if(i.node)if(13===t||"Enter"===a)o(function(){var e;null===(e=i.node)||void 0===e||e.enter()});else if(8===t||46===t||"Backspace"===a||"Delete"===a)e.stopPropagation(),c||o(function(){var e;null===(e=i.node)||void 0===e||e.delete(46===t||"Delete"===a)});else if((t>=37&&t<=40||["ArrowUp","ArrowRight","ArrowDown","ArrowLeft"].includes(a))&&(e.stopPropagation(),!c)){var n=i.node.moveCursor(t,e.shiftKey);e.shiftKey?i.hideCursor():(i.showCursor(),i.updateCursor(n)),r.emit(_m,[i.node])}}),n.addEventListener("input",function(e){if(!c){var t=e.data;t&&s(t)}}),n.addEventListener("paste",function(e){var t;e.stopPropagation(),null===(t=e.clipboardData)||void 0===t||t.getData("text")}),n.addEventListener("compositionstart",function(e){c=!0}),n.addEventListener("compositionend",function(e){c=!1;var t=e.data;t&&s(t)});var u=this.cursorEl=document.createElement("div");u.style.position="absolute",u.style.left="0px",u.style.top="0px",u.style.width="10px",u.style.height="100%",u.style.borderLeft="1px solid #000",u.style.pointerEvents="none",a.appendChild(u),u.animate([{visibility:"visible",borderColor:"#000"},{visibility:"visible",borderColor:"#FFF"},{visibility:"hidden"},{visibility:"hidden"}],{duration:800,iterations:1/0}),this.onClick=function(e){if(r.state===Am.EDIT_TEXT){for(var t=e.target,a=t;a;){if(i.ignoreBlurUnFocus.includes(a))return;if(a===r.dom||i.ignoreBlur.includes(a))return void(["INPUT","SELECT","TEXTAREA"].includes(t.tagName.toUpperCase())||i.focus());a=a.parentElement}var n=i.node;r.cancelEditText(),n.resetCursor(),n.afterEdit(),n.inputStyle=void 0}},document.addEventListener("click",this.onClick)}return e.prototype.show=function(e,t,r){this.node=e,this.update(t,r),this.focus(),this.showCursor()},e.prototype.update=function(e,t){var r=this.node.setCursorStartByAbsCoords(e,t);this.updateCursor(r)},e.prototype.hide=function(){if(this.hideCursor(),this.blur(),this.node){if(!this.node.content.length){var e=this.listener.history.commands[0];e&&e instanceof lp&&e.nodes[0]===this.node&&e.undo(),this.listener.removeNode()}this.node=void 0}},e.prototype.focus=function(){this.inputEl.focus()},e.prototype.blur=function(){this.inputEl.blur(),this.hasBlur=!0},e.prototype.showCursor=function(){this.containerEl.style.opacity="1"},e.prototype.hideCursor=function(){this.containerEl.style.opacity="0"},e.prototype.updateCursor=function(e){if(e=e||this.node.getCursorAbsCoords()){var t=this.node.root.canvas;this.containerEl.style.left=e.x*t.clientWidth/t.width+"px",this.containerEl.style.top=e.y*t.clientWidth/t.width+"px",this.containerEl.style.height=e.h*t.clientWidth/t.width+"px"}},e.prototype.release=function(){this.containerEl.remove(),document.removeEventListener("click",this.onClick)},e}(),dp="undefined"!=typeof navigator&&/win/i.test(navigator.platform),fp=function(e){function r(t,r,i){var a=e.call(this)||this;return a.root=t,a.dom=r,a.options=i,a.state=wm.NORMAL,a.isMouseDown=!1,a.isMouseMove=!1,a.originX=0,a.originY=0,a.startX=0,a.startY=0,a.centerX=0,a.centerY=0,a.metaKey=!1,a.shiftKey=!1,a.ctrlKey=!1,a.altKey=!1,a.eventListenerList=[{type:"mousedown",cb:a.onMouseDown.bind(a)},{type:"mousemove",cb:a.onMouseMove.bind(a)},{type:"mouseup",cb:a.onMouseUp.bind(a)},{type:"dblclick",cb:a.onDblClick.bind(a)},{type:"keydown",cb:a.onKeyDown.bind(a)},{type:"keyup",cb:a.onKeyUp.bind(a)}],a.eventListenerList.forEach(function(e){"keydown"===e.type||"keyup"===e.type?document.addEventListener(e.type,e.cb):r.addEventListener(e.type,e.cb)}),a.history=new Dm,a.selected=[],a.select=new Em(t,r),a.computedStyle=[],a.originStyle=[],a.cssStyle=[],a.input=new hp(t,r,a),a.dx=0,a.dy=0,a.isControl=!1,a.isRotate=!1,a.controlType=Bm.T,a}return t(r,e),r.prototype.updateOrigin=function(){var e=this.dom.getBoundingClientRect();this.originX=e.left,this.originY=e.top},r.prototype.prepare=function(){var e=this.selected;this.computedStyle=e.map(function(e){return e.getComputedStyle()}),this.originStyle=e.map(function(e){return e.getStyle()})},r.prototype.getNode=function(e,t){return this.metaKey||dp&&this.ctrlKey,up(this.root,e,t)},r.prototype.onMouseDown=function(e){var t,r;if(0===e.button){var i=this.selected;this.isMouseDown=!0,this.updateOrigin(),this.startX=e.clientX-this.originX,this.startY=e.clientY-this.originY;var a=this.root.canvas,n=this.startX*a.width/a.clientWidth,o=this.startY*a.height/a.clientHeight,s=e.target;if(this.isControl=this.select.isSelectControlDom(s)){this.state===wm.EDIT_TEXT&&this.cancelEditText();var c=this.controlType={t:Bm.T,r:Bm.R,b:Bm.B,l:Bm.L,tl:Bm.TL,tr:Bm.TR,bl:Bm.BL,br:Bm.BR}[s.className];this.prepare();var u=this.metaKey||dp&&this.ctrlKey;if(!(null===(r=null===(t=this.options)||void 0===t?void 0:t.disabled)||void 0===r?void 0:r.rotate)&&1===i.length&&u&&[Bm.TL,Bm.TR,Bm.BL,Bm.BR].indexOf(c)>-1){var l=i[0].getBoundingClientRect().points,h=cr(l[0].x,l[0].y,l[2].x,l[2].y,l[1].x,l[1].y,l[3].x,l[3].y);this.centerX=h.x*a.clientWidth/a.width,this.centerY=h.y*a.clientHeight/a.height,this.isRotate=!0}else this.beforeResize()}else{var d=this.getNode(n,o),f=i.slice(0);if(d){if((h=i.indexOf(d))>-1){if(this.state===wm.EDIT_TEXT){var m=d;if(this.shiftKey)m.setCursorEndByAbsCoords(n,o),m.inputStyle=void 0,this.input.hideCursor();else{var p=m.cursor,g=p.isMulti,v=p.startLineBox,y=p.startTextBox,b=p.startString;m.resetCursor();var x=m.setCursorStartByAbsCoords(n,o);if(this.input.updateCursor(x),this.input.showCursor(),m.cursor.isMulti===g&&m.cursor.startLineBox===v&&m.cursor.startTextBox===y&&m.cursor.startString===b)return}return void this.emit(_m,[m])}}else{if(this.state===wm.EDIT_TEXT)return void this.cancelEditText(f[0]);if(this.shiftKey)for(var T=i.length-1;T>=0;T--){var w=i[T];if(d.isParent(w))i.splice(T,1);else if(d.isChild(w))return}else i.splice(0);i.push(d)}}else{if(this.state===wm.EDIT_TEXT)return void this.cancelEditText(f[0]);i.splice(0)}this.updateActive(!0)}}},r.prototype.onMouseMove=function(e){var t=this,r=this.root.canvas,i=e.clientX-this.originX-this.startX,a=e.clientY-this.originY-this.startY,n=this.dx=i*r.width/r.clientWidth,o=this.dy=a*r.height/r.clientHeight,s=this.selected;if(this.isControl){if(Math.abs(i)<=1&&Math.abs(a)<=1&&!this.isMouseMove)return;if(this.isRotate){var c=this.centerX,u=this.centerY,l=this.startX,h=this.startY,d=e.clientX-this.originX,f=e.clientY-this.originY,m=mr(yr(Math.sqrt(Math.pow(l-d,2)+Math.pow(h-f,2)),Math.sqrt(Math.pow(c-d,2)+Math.pow(u-f,2)),Math.sqrt(Math.pow(l-c,2)+Math.pow(h-u,2)))),p=qe(l-c,h-u,d-c,f-u);if(this.shiftKey)for(var g=0;g<=180;g+=15)if(Math.abs(m-g)<=7.5){m=g;break}var v=s[0],y=(this.computedStyle[0].rotateZ+m*(p>=0?1:-1))%360;v.updateStyle({rotateZ:y}),this.select.updateSelect(s),this.emit(Rm.ROTATE,s.slice(0))}else{var b=this.shiftKey,x=this.altKey,T=this.controlType;s.forEach(function(e,r){t.isMouseMove||(e.startSizeChange(),t.computedStyle[r]=e.getComputedStyle(),t.cssStyle[r]=e.getCssStyle());var i=t.computedStyle[r],a=t.cssStyle[r];t.selectRect&&t.clientRect&&t.clientRect[r]?ap.operateMultiAr(e,i,a,n,o,T,t.clientRect[r],t.selectRect,b,x):ap.operate(e,i,a,n,o,T,b,x)}),this.select.updateSelect(s),this.emit(Rm.RESIZE,s.slice(0))}this.isMouseMove=!0}else if(this.isMouseDown){if(Math.abs(i)<=1&&Math.abs(a)<=1&&!this.isMouseMove)return;if(this.isMouseMove=!0,this.state===wm.EDIT_TEXT){var w=(e.clientX-this.originX)*r.width/r.clientWidth,k=(e.clientY-this.originY)*r.height/r.clientHeight,S=s[0],E=S.cursor,C=E.isMulti,A=E.start,_=E.end;S.setCursorEndByAbsCoords(w,k),this.input.hideCursor();var M=S.cursor;C===M.isMulti&&A===M.start&&_===M.end||this.emit(_m,s.slice(0))}else this.select.select.classList.add("move"),this.shiftKey&&(Math.abs(n)>=Math.abs(o)?this.dy=a=o=0:this.dx=i=n=0),s.forEach(function(e,r){var i=t.computedStyle[r];Om.operate(e,i,n,o)}),this.select.updateSelect(s),this.emit(Rm.MOVE,s.slice(0))}},r.prototype.onMouseUp=function(){var e=this,t=this.selected,r=this.dx,i=this.dy;if(this.isControl){if(this.isRotate){var a=t[0];(r||i)&&this.history.addCommand(new op([a],[{prev:{rotateZ:this.computedStyle[0].rotateZ},next:{rotateZ:a.computedStyle.rotateZ}}]),!0)}else if(this.isMouseMove){var n=this.shiftKey,o=this.altKey,s=this.controlType,c=[];t.forEach(function(t,a){if(t.endSizeChange(e.originStyle[a]),r||i){var u={dx:r,dy:i,controlType:s,aspectRatio:n,clientRect:e.clientRect&&e.clientRect[a],selectRect:e.selectRect,fromCenter:o},l=e.originStyle[a];l.width.u===V.AUTO&&(u.widthFromAuto=!0),l.height.u===V.AUTO&&(u.heightFromAuto=!0),c.push(u)}}),c.length&&this.history.addCommand(new ap(t.slice(0),c))}}else if(this.isMouseMove)if(this.state===wm.EDIT_TEXT){t[0].checkCursorMulti()?this.input.hideCursor():(this.input.updateCursor(),this.input.showCursor()),this.input.focus()}else{this.select.select.classList.remove("move");var u=this.dx,l=this.dy,h=[];t.forEach(function(t,r){(u||l)&&(t.endPosChange(e.originStyle[r],u,l),h.push({dx:u,dy:l}))}),h.length&&this.history.addCommand(new Om(t.slice(0),h),!0)}this.isControl=!1,this.isRotate=!1,this.isMouseDown=!1,this.isMouseMove=!1},r.prototype.onDblClick=function(e){if(0===e.button){var t=this.root.canvas,r=this.startX*t.width/t.clientWidth,i=this.startY*t.height/t.clientHeight,a=this.getNode(r,i);if(1!==this.selected.length||a!==this.selected[0])this.selected.splice(0),a&&this.selected.push(a),this.updateActive(!0);else if(a instanceof om){this.input.show(a,r,i),a.beforeEdit();var n=this.state;this.state=wm.EDIT_TEXT,this.select.select.classList.add("text"),this.emit(Im,n,this.state)}}},r.prototype.onKeyDown=function(e){var t,r,i,a;this.metaKey=e.metaKey,this.altKey=e.altKey,this.ctrlKey=e.ctrlKey,this.shiftKey=e.shiftKey;var n=this.metaKey||dp&&this.ctrlKey;!(null===(a=null===(i=this.options)||void 0===i?void 0:i.disabled)||void 0===a?void 0:a.rotate)&&n&&1===this.selected.length&&this.select.metaKey(!0);var o=e.keyCode,s=e.code,c=e.target,u=["INPUT","TEXTAREA","SELECT"].includes(c.tagName.toUpperCase());if(8===o||46===o||"Backspace"===s||"Delete"===s){if(u)return;this.removeNode()}else if(27===o||"Escape"===s)this.state===wm.EDIT_TEXT?this.cancelEditText():(this.selected.splice(0),this.select.hideSelect(),this.emit(Rm.SELECT,[]));else if(o>=37&&o<=40||["ArrowUp","ArrowRight","ArrowDown","ArrowLeft"].includes(s)){if(u)return;e.preventDefault();var l=0,h=0;37===o?l=this.shiftKey?-10:this.altKey?-.1:-1:38===o?h=this.shiftKey?-10:this.altKey?-.1:-1:39===o?l=this.shiftKey?10:this.altKey?.1:1:40===o&&(h=this.shiftKey?10:this.altKey?.1:1);var d=this.selected.slice(0),f=[];d.forEach(function(e){var t=e.getStyle();Om.operate(e,e.computedStyle,l,h),e.endPosChange(t,l,h),f.push({dx:l,dy:h})}),d.length&&(this.select.updateSelect(d),this.emit(Rm.MOVE,d.slice(0)),this.history.addCommand(new Om(d,f)))}else if(65!==o&&"KeyA"!==s||!n){if((90===o||"KeyZ"===s)&&n){if(u&&c!==this.input.inputEl)return;e.preventDefault();var m=void 0;if(m=this.shiftKey?this.history.redo():this.history.undo()){d=m.nodes.slice(0);var p=this.selected.slice(0),g=!1;if(m instanceof Fm||(this.selected.splice(0),(t=this.selected).push.apply(t,d),this.updateActive(),g=!0),m instanceof Om)this.emit(Rm.MOVE,d.slice(0));else if(m instanceof ap)this.emit(Rm.RESIZE,d.slice(0));else if(m instanceof Fm)this.shiftKey?(this.selected.splice(0),this.select.hideSelect(),this.emit(Rm.REMOVE,d.slice(0)),this.emit(Rm.SELECT,[])):(this.selected.splice(0),(r=this.selected).push.apply(r,d),this.updateActive(),this.emit(Rm.ADD,d.slice(0)),this.emit(Rm.SELECT,d.slice(0)));else if(m instanceof op)this.emit(Rm.ROTATE,d.slice(0));else if(m instanceof lp){if(this.state===wm.EDIT_TEXT){var v=d[0],y=v.getSortedCursor(),b=y.isMulti,x=y.start;if(b)this.input.hideCursor();else{var T=v.updateCursorByIndex(x);this.input.updateCursor(T),this.input.showCursor()}this.input.focus()}this.emit(Mm,d.slice(0))}if(g)if(d.length!==p.length)this.emit(Rm.SELECT,d.slice(0));else for(var w=0,k=d.length;w<k;w++)if(d[w]!==p[w]){this.emit(Rm.SELECT,d.slice(0));break}}}}else this.state===wm.EDIT_TEXT&&c===this.input.inputEl&&(e.preventDefault(),this.input.node.selectAll(),this.input.hideCursor())},r.prototype.onKeyUp=function(e){var t,r;this.metaKey=e.metaKey,this.altKey=e.altKey,this.ctrlKey=e.ctrlKey,this.shiftKey=e.shiftKey;var i=this.metaKey||dp&&this.ctrlKey;(null===(r=null===(t=this.options)||void 0===t?void 0:t.disabled)||void 0===r?void 0:r.rotate)||i||this.isRotate||this.select.metaKey(!1)},r.prototype.removeNode=function(e){if(void 0===e&&(e=this.selected),e.length){var t=e.splice(0).filter(function(e){return!e.isLocked}),r=[];e.forEach(function(e,t){var i=Fm.operate(e);r.push(i)}),this.select.hideSelect(),this.history.addCommand(new Fm(t,r)),this.emit(Rm.REMOVE,t.slice(0)),this.emit(Rm.SELECT,[])}},r.prototype.active=function(e){var t=this.selected,r=!1;if(e.length!==t.length)r=!0;else for(var i=0,a=e.length;i<a;i++)if(e[i]!==t[i]){r=!0;break}r&&(t.splice(0),t.push.apply(t,e),this.updateActive(!0))},r.prototype.updateActive=function(e){void 0===e&&(e=!1),this.prepare();var t=this.selected;t.length?this.select.showSelect(t):this.select.hideSelect(),e&&this.emit(Rm.SELECT,t.slice(0))},r.prototype.beforeResize=function(){this.selected.length>1&&this.shiftKey?(this.selectRect=this.select.getAspectRatio(),this.clientRect=this.selected.map(function(e){var t=e.getBoundingClientRect();return{x:t.left,y:t.top,w:t.width,h:t.height}})):(this.selectRect=void 0,this.clientRect=void 0)},r.prototype.cancelEditText=function(e){if(this.state===wm.EDIT_TEXT){var t=e||this.selected[0];t&&(t.resetCursor(),t.afterEdit(),t.inputStyle=void 0),this.input.hide(),this.state=wm.NORMAL,this.select.select.classList.remove("text"),this.emit(Im,wm.EDIT_TEXT,this.state)}},r.prototype.release=function(){var e=this;this.eventListenerList.splice(0).forEach(function(t){"keydown"===t.type||"keyup"===t.type?document.removeEventListener(t.type,t.cb):e.dom.removeEventListener(t.type,t.cb)}),this.select.release(),this.input.release()},r}(M);return{parser:Da,node:ym,util:km,config:L,style:Sm,interaction:{Listener:fp,interactionEvent:Rm,state:Am,Select:Em,Input:hp},animation:{frame:wf,AbstractAnimation:da,CssAnimation:fa,GifAnimation:Ca,TimeAnimation:Ha,AniController:Ef,animationEvent:ha},math:Ur,history:{History:Dm,AbstractCommand:Pm,MoveCommand:Om,RemoveCommand:Fm,ResizeCommand:ap,RotateCommand:op,TextCommand:lp},refresh:{CanvasCache:xi,TextureCache:Zi,merge:yf},format:P}});
274
274
  //# sourceMappingURL=index.min.js.map