krono-flow 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,274 @@
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;
2
+ /*!
3
+ * Copyright (c) 2025-present, Vanilagy and contributors
4
+ *
5
+ * This Source Code Form is subject to the terms of the Mozilla Public
6
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
7
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
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);
10
+ /*!
11
+ * Copyright (c) 2025-present, Vanilagy and contributors
12
+ *
13
+ * This Source Code Form is subject to the terms of the Mozilla Public
14
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
15
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
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.")};
18
+ /*!
19
+ * Copyright (c) 2025-present, Vanilagy and contributors
20
+ *
21
+ * This Source Code Form is subject to the terms of the Mozilla Public
22
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
23
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
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}}
26
+ /*!
27
+ * Copyright (c) 2025-present, Vanilagy and contributors
28
+ *
29
+ * This Source Code Form is subject to the terms of the Mozilla Public
30
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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})}}}};
33
+ /*!
34
+ * Copyright (c) 2025-present, Vanilagy and contributors
35
+ *
36
+ * This Source Code Form is subject to the terms of the Mozilla Public
37
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
38
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
39
+ */class Ka{constructor(e){this.input=e}}
40
+ /*!
41
+ * Copyright (c) 2025-present, Vanilagy and contributors
42
+ *
43
+ * This Source Code Form is subject to the terms of the Mozilla Public
44
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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)}}
47
+ /*!
48
+ * Copyright (c) 2025-present, Vanilagy and contributors
49
+ *
50
+ * This Source Code Form is subject to the terms of the Mozilla Public
51
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
52
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
53
+ */
54
+ /*!
55
+ * Copyright (c) 2025-present, Vanilagy and contributors
56
+ *
57
+ * This Source Code Form is subject to the terms of the Mozilla Public
58
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
59
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
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)}}
62
+ /*!
63
+ * Copyright (c) 2025-present, Vanilagy and contributors
64
+ *
65
+ * This Source Code Form is subject to the terms of the Mozilla Public
66
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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"}}
69
+ /*!
70
+ * Copyright (c) 2025-present, Vanilagy and contributors
71
+ *
72
+ * This Source Code Form is subject to the terms of the Mozilla Public
73
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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}};
76
+ /*!
77
+ * Copyright (c) 2025-present, Vanilagy and contributors
78
+ *
79
+ * This Source Code Form is subject to the terms of the Mozilla Public
80
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
81
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
82
+ */
83
+ /*!
84
+ * Copyright (c) 2025-present, Vanilagy and contributors
85
+ *
86
+ * This Source Code Form is subject to the terms of the Mozilla Public
87
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
88
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
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;
91
+ /*!
92
+ * Copyright (c) 2025-present, Vanilagy and contributors
93
+ *
94
+ * This Source Code Form is subject to the terms of the Mozilla Public
95
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
96
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
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.")}
99
+ /*!
100
+ * Copyright (c) 2025-present, Vanilagy and contributors
101
+ *
102
+ * This Source Code Form is subject to the terms of the Mozilla Public
103
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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};
106
+ /*!
107
+ * Copyright (c) 2025-present, Vanilagy and contributors
108
+ *
109
+ * This Source Code Form is subject to the terms of the Mozilla Public
110
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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}}
113
+ /*!
114
+ * Copyright (c) 2025-present, Vanilagy and contributors
115
+ *
116
+ * This Source Code Form is subject to the terms of the Mozilla Public
117
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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};
120
+ /*!
121
+ * Copyright (c) 2025-present, Vanilagy and contributors
122
+ *
123
+ * This Source Code Form is subject to the terms of the Mozilla Public
124
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
125
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
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)}}
128
+ /*!
129
+ * Copyright (c) 2025-present, Vanilagy and contributors
130
+ *
131
+ * This Source Code Form is subject to the terms of the Mozilla Public
132
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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};
135
+ /*!
136
+ * Copyright (c) 2025-present, Vanilagy and contributors
137
+ *
138
+ * This Source Code Form is subject to the terms of the Mozilla Public
139
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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)}}
142
+ /*!
143
+ * Copyright (c) 2025-present, Vanilagy and contributors
144
+ *
145
+ * This Source Code Form is subject to the terms of the Mozilla Public
146
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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};
149
+ /*!
150
+ * Copyright (c) 2025-present, Vanilagy and contributors
151
+ *
152
+ * This Source Code Form is subject to the terms of the Mozilla Public
153
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
154
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
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};
157
+ /*!
158
+ * Copyright (c) 2025-present, Vanilagy and contributors
159
+ *
160
+ * This Source Code Form is subject to the terms of the Mozilla Public
161
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
162
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
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)}}
165
+ /*!
166
+ * Copyright (c) 2025-present, Vanilagy and contributors
167
+ *
168
+ * This Source Code Form is subject to the terms of the Mozilla Public
169
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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)}}
172
+ /*!
173
+ * Copyright (c) 2025-present, Vanilagy and contributors
174
+ *
175
+ * This Source Code Form is subject to the terms of the Mozilla Public
176
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
177
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
178
+ */
179
+ /*!
180
+ * Copyright (c) 2025-present, Vanilagy and contributors
181
+ *
182
+ * This Source Code Form is subject to the terms of the Mozilla Public
183
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
184
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
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)}}
187
+ /*!
188
+ * Copyright (c) 2025-present, Vanilagy and contributors
189
+ *
190
+ * This Source Code Form is subject to the terms of the Mozilla Public
191
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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];
194
+ /*!
195
+ * Copyright (c) 2025-present, Vanilagy and contributors
196
+ *
197
+ * This Source Code Form is subject to the terms of the Mozilla Public
198
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
199
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
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}}
202
+ /*!
203
+ * Copyright (c) 2025-present, Vanilagy and contributors
204
+ *
205
+ * This Source Code Form is subject to the terms of the Mozilla Public
206
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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"}}
209
+ /*!
210
+ * Copyright (c) 2025-present, Vanilagy and contributors
211
+ *
212
+ * This Source Code Form is subject to the terms of the Mozilla Public
213
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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")};
216
+ /*!
217
+ * Copyright (c) 2025-present, Vanilagy and contributors
218
+ *
219
+ * This Source Code Form is subject to the terms of the Mozilla Public
220
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
221
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
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};
224
+ /*!
225
+ * Copyright (c) 2025-present, Vanilagy and contributors
226
+ *
227
+ * This Source Code Form is subject to the terms of the Mozilla Public
228
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
229
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
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)}}
232
+ /*!
233
+ * Copyright (c) 2025-present, Vanilagy and contributors
234
+ *
235
+ * This Source Code Form is subject to the terms of the Mozilla Public
236
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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)}}
239
+ /*!
240
+ * Copyright (c) 2025-present, Vanilagy and contributors
241
+ *
242
+ * This Source Code Form is subject to the terms of the Mozilla Public
243
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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()}}
246
+ /*!
247
+ * Copyright (c) 2025-present, Vanilagy and contributors
248
+ *
249
+ * This Source Code Form is subject to the terms of the Mozilla Public
250
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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()}}
253
+ /*!
254
+ * Copyright (c) 2025-present, Vanilagy and contributors
255
+ *
256
+ * This Source Code Form is subject to the terms of the Mozilla Public
257
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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.":""}}
260
+ /*!
261
+ * Copyright (c) 2025-present, Vanilagy and contributors
262
+ *
263
+ * This Source Code Form is subject to the terms of the Mozilla Public
264
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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}}
267
+ /*!
268
+ * Copyright (c) 2025-present, Vanilagy and contributors
269
+ *
270
+ * This Source Code Form is subject to the terms of the Mozilla Public
271
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
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}}});
274
+ //# sourceMappingURL=index.min.js.map