polotno 2.36.8 → 2.36.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/canvas/html-element.js
CHANGED
|
@@ -13,4 +13,4 @@ import t from"react";import{observer as e}from"mobx-react-lite";import{Group as
|
|
|
13
13
|
.ql-direction-rtl {
|
|
14
14
|
direction: rtl;
|
|
15
15
|
}
|
|
16
|
-
`;let L=["bold","color","font","italic","size","strike","underline","indent","list","direction"];export const setQuillFormats=t=>{L=t};export const createQuill=t=>new a(t,{toolbar:!1,keyboard:!1,clipboard:{matchVisual:!1},formats:L});export const setQuillContent=(t,e)=>{var o=t.clipboard.convert("<div class='ql-editor' style='outline: none;'>"+e+"<p><br></p></div>");t.setContents(o),t.history.clear()};const X=({html:e,onBlur:o,onChange:n,element:i,clickCoords:r})=>{var l;const d=t.useRef(null);t.useEffect(()=>{if(!d.current){return}const t=(i=d.current,new a(i,{toolbar:!1,keyboard:!1,clipboard:{matchVisual:!1},formats:L}));var i;s.runInAction(()=>{quillRef.editor.instance=t}),window.__polotnoQuill=t,t.on("text-change",()=>{t.getSelection()&&s.runInAction(()=>{quillRef.currentFormat=t.getFormat(t.getSelection())}),setTimeout(()=>{var t;const e=null===(t=d.current)||void 0===t?void 0:t.childNodes[0];if(!e){return}const o=e.innerHTML;n(Y(o))},10)}),setQuillContent(t,e),r?setCursorFromCoords(t,r):t.setSelection(0,0,"api"),t.on("selection-change",(e,o,n)=>{e&&s.runInAction(()=>{quillRef.currentFormat=t.getFormat(t.getSelection())})}),d.current.childNodes[0].addEventListener("blur",t=>{const e=t.relatedTarget;if(null==e?void 0:e.classList.contains("ql-clipboard")){return}const n=function(t){return!!t&&!!t.closest(".sketch-picker")}(e);n||o()});const l=d.current.childNodes[0],c=e=>{var o,n;const i=t.getSelection();if(!i||0===i.length){return}const r=t.getText(i.index,i.length).replace(/\n$/,""),a=window.getSelection();let l="";if(a&&a.rangeCount>0){const t=a.getRangeAt(0),e=document.createElement("div");e.appendChild(t.cloneContents()),l=e.innerHTML}if(null===(o=e.clipboardData)||void 0===o||o.setData("text/plain",r),l){const t='<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e<div style="white-space: pre-wrap; word-wrap: break-word;">'+l+"</div>\x3c!--EndFragment--\x3e</body></html>";null===(n=e.clipboardData)||void 0===n||n.setData("text/html",t)}e.preventDefault()},f=e=>{c(e);const o=t.getSelection();o&&o.length>0&&t.deleteText(o.index,o.length)};return l.addEventListener("copy",c),l.addEventListener("cut",f),()=>{l.removeEventListener("copy",c),l.removeEventListener("cut",f),s.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={}}),delete window.__polotnoQuill}},[]),t.useEffect(()=>c(()=>i.text,()=>{var t,o;const n=quillRef.editor.instance;if(!n){return}const r=n.getSelection(),a=null===(o=null===(t=d.current)||void 0===t?void 0:t.childNodes)||void 0===o?void 0:o[0];Y((null==a?void 0:a.innerHTML)||"")===i.text||(setQuillContent(n,e),r&&(n.setSelection(r.index,r.length),s.runInAction(()=>{quillRef.currentFormat=n.getFormat(n.getSelection())})))},{fireImmediately:!0}),[]),t.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=d.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]);const f={color:i.fill};i.fill.indexOf("gradient")>=0&&(f.backgroundColor=i.fill,f.backgroundImage=i.fill,f.backgroundSize="100% 100%",f.backgroundRepeat="repeat",f.webkitBackgroundClip="text",f.MozBackgroundClip="text",f.WebkitTextFillColor="transparent",f.MozTextFillColor="transparent");const u=M(i);return t.createElement($,{ref:d,style:Object.assign(Object.assign({},f),{fontSize:i.fontSize,fontWeight:i.fontWeight,textTransform:i.textTransform,width:i.a.width,fontFamily:'"'+i.fontFamily+'"',lineHeight:i.lineHeight,letterSpacing:i.letterSpacing*i.fontSize+"px",textAlign:i.align,opacity:Math.max(i.a.opacity,.2),textShadow:i.shadowEnabled?`${i.shadowOffsetX}px ${i.shadowOffsetY}px ${i.shadowBlur}px ${A(i.shadowColor,null!==(l=i.shadowOpacity)&&void 0!==l?l:1)}`:void 0,caretColor:u}),dir:p(R(i.text))})};function q(t){return!function(t){const e=t.getContext("2d").getImageData(0,0,t.width,t.height).data;for(let o=0;o<e.length;o+=4){if(0!==e[o+3]){return!0}}return!1}(t)}const I=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);export const HTMLElement=e(({element:e,store:a})=>{var c,p;const b=t.useRef(null),[F,M]=t.useState(),[Y,L]=t.useState(!1),[D,W]=t.useState(!1),B=t.useRef(e.height),H=a.selectedShapes.indexOf(e)>=0&&e.selectable,_=g(H),N=e.fontSize/3,{textVerticalResizeEnabled:Q}=d,V=d.autoDeleteEmptyText,J=g(e.fontFamily),[G]=h(a,e.fontFamily,e.fontStyle,e.fontWeight),U=e._editModeEnabled;E(b);const K=G?e.fontFamily:J!==e.fontFamily?J:"Arial",Z=x(e).fill,tt=P(e,{fontFamily:K,color:Z}),et=P(e,{fontFamily:K,color:Z,forEditor:!0}),ot=t.useRef([]),[,nt]=t.useReducer(t=>t+1,0);t.useEffect(()=>{const t=ot.current;t.length>0&&(ot.current=[],t.forEach(t=>t()))});let{width:it,height:rt}=function(e,o,n){return t.useMemo(()=>w(e),[e,o.width,n])}(tt,e,G);t.useEffect(()=>{if(!G){return}const t=(t,o,n,i)=>{const r=k(`text ${e.id}`),l=()=>{a.history.ignore(t,o,n).then(()=>{ot.current.push(r),nt()})};i?queueMicrotask(l):l()};if(!e.height){return void t(()=>{e.height||e.set({height:rt})},void 0,void 0,!0)}const{textOverflow:o}=d;if("change-font-size"!==o||Y){"resize"===o&&(Q&&e.height<rt&&!Y&&t(()=>{e.set({height:rt})},!1,!0),Q||e.height===rt||t(()=>{e.set({height:rt})},!1,!0))}else{const o=(t=>{let e=t.fontSize;for(let o=1;o<50;o++){const o=P(Object.assign(Object.assign({},t.toJSON()),{fontSize:e}),{fontFamily:t.fontFamily}),{height:n}=w(o);if(!(t.height&&n>t.height||!d.textSplitAllowed&&!t.curveEnabled&&v({html:o}))){break}e-=.5}return e})(e);o!==e.fontSize?t(()=>{e.set({fontSize:o})},!1,!0):e.height!==rt&&(Q&&e.height<rt?t(()=>{e.set({height:rt})},!1,!0):Q||t(()=>{e.set({height:rt})},!1,!0))}});const at=t.useMemo(()=>{const t={lastArgs:null,lastResult:null};return async function(e){return t.lastArgs&&t.lastResult&&(o=t.lastArgs,n=e,JSON.stringify(o)===JSON.stringify(n))||(t.lastResult=await y(e),t.lastArgs=Object.assign({},e)),t.lastResult;var o,n}},[]),lt=t.useRef(0),st=t.useRef(null);t.useEffect(()=>{Y||U||(async()=>{lt.current++;const t=lt.current;let o=k(`text ${e.id} ${t}`);st.current&&st.current(),st.current=o,W(!0);let n=null;const i=I?5:1;for(let l=0;l<i;l++){const o=l>0?at:y;try{if(n=await o({skipCache:l>0,html:tt,width:e.width||1,height:e.height||rt||1,fontFamily:K,padding:N,pixelRatio:a._elementsPixelRatio,font:a.fonts.find(t=>t.fontFamily===K)||O.globalFonts.find(t=>t.fontFamily===K)}),t!==lt.current){return}if(I&&n&&q(n)){await new Promise(t=>setTimeout(t,50*(l+1)));continue}break}catch(r){console.error(r),z(`Error rendering rich text with id ${e.id}`);break}}n?M(n):o?(o(),o=null):console.error("Finish function is called twice!"),W(!1)})()},[tt,Y,rt,U,K,e.height,a._elementsPixelRatio,G]);const[ct,dt]=j(D,300),[ft]=j(Y,300,!0),ut=ft||ct;t.useEffect(()=>{var t;if(!ut){return s.autorun(()=>{const t=b.current;f(t,e)})}null===(t=b.current)||void 0===t||t.clearCache()},[F,ut,e.shadowColor,e.shadowOffsetX,e.shadowOffsetY,e.shadowOpacity]),t.useEffect(()=>{F&&!D&&st.current&&(st.current(),st.current=null)},[F,D]),t.useLayoutEffect(()=>{if(!G){return}if(!e.curveEnabled){return}const t=new l.TextPath({data:m(e.a.width,e.a.height,e.curvePower,e.a.fontSize),text:R(e.text),letterSpacing:e.letterSpacing*e.a.fontSize,fontSize:e.a.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle,align:"center",textBaseline:"middle",fill:e.fill}),o=t.getSelfRect().width;if(o){const t=o-e.a.width,n=e.a.rotation*Math.PI/180,i=-t/2*Math.cos(n),r=-t/2*Math.sin(n);e.set({width:o,x:e.a.x+i,y:e.a.y+r})}t.destroy()},[G,e.curveEnabled,e.curvePower,e.text,e.fontSize,e.fontFamily,e.fontWeight,e.fontStyle,e.letterSpacing]),t.useEffect(()=>()=>{st.current&&st.current()},[]),t.useEffect(()=>{_&&!H&&V&&""===R(e.text)&&e.removable&&!e.placeholder&&a.deleteElements([e.id])},[V,e.placeholder,e.removable,e.text,H,_]);let ht=0;"middle"===e.verticalAlign&&(ht=(e.height-rt)/2),"bottom"===e.verticalAlign&&(ht=e.height-rt);const gt=u({fontLoaded:G,fontFamily:e.fontFamily,fontSize:e.fontSize,lineHeight:e.lineHeight}),mt=C(),pt=m(e.a.width,rt,e.curvePower,e.fontSize),xt=t.useRef(null),wt=t.useRef(null),yt=U&&e.strokeWidth>0&&!e.curveEnabled;return t.createElement(t.Fragment,null,t.createElement(r,{x:e.a.x,y:e.a.y,offsetX:e.backgroundPadding*(e.fontSize*gt*.5),offsetY:e.backgroundPadding*(e.fontSize*gt*.5),rotation:e.a.rotation,hideInExport:!e.showInExport,listening:!1,visible:e.backgroundEnabled,opacity:e.backgroundOpacity*e.a.opacity,fill:e.backgroundColor,width:e.a.width+e.backgroundPadding*(e.fontSize*gt),height:e.a.height+e.backgroundPadding*(e.fontSize*gt),cornerRadius:e.backgroundCornerRadius*(e.fontSize*gt*.5)}),t.createElement(i,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,data:pt,stroke:"red",strokeWidth:1,visible:!1}),t.createElement(r,{ref:b,name:"element",x:e.a.x,y:e.a.y,listening:e.selectable,rotation:e.a.rotation,width:e.a.width,height:e.a.height,visible:!ut,draggable:mt?e.draggable&&H:e.draggable,preventDefault:!mt||H,opacity:U?0:e.a.opacity,hideInExport:!e.showInExport,onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{e.set({x:t.target.x(),y:t.target.y()})},id:e.id,onDblClick:t=>{e.contentEditable&&(wt.current={x:t.evt.clientX,y:t.evt.clientY},e.toggleEditMode(!0))},onDblTap:t=>{var o;if(e.contentEditable){const n=null===(o=t.evt.changedTouches)||void 0===o?void 0:o[0];wt.current=n?{x:n.clientX,y:n.clientY}:null,e.toggleEditMode(!0)}},onTransformStart:t=>{L(!0),B.current=e.height},onTransform:t=>{var o;const n=t.target,i=(null===(o=n.getStage())||void 0===o?void 0:o.findOne("Transformer")).getActiveAnchor(),r="middle-left"===i||"middle-right"===i,a="top-center"===i||"bottom-center"===i,l=n.scaleX();if(r){const t=n.scaleX(),o=n.width()*t,i=e.fontSize;let r=o;if(o<i&&(r=i,xt.current&&n.position(xt.current)),n.width(r),n.scaleX(1),d.textVerticalResizeEnabled){const t=Math.max(rt,B.current);e.set({height:t})}e.set({width:n.width(),x:n.x(),y:n.y()})}else if(a){const o="resize"===d.textOverflow,i="number"==typeof e.lineHeight?e.lineHeight:1;let r=o?rt:i*e.fontSize;const a=Math.max(r,t.target.height()*t.target.scaleY());n.scaleY(1),e.set({x:n.x(),y:n.y(),height:a,rotation:n.rotation()})}else{n.scaleX(1),n.scaleY(1),e.set({fontSize:e.fontSize*l,letterSpacing:e.letterSpacing,width:n.width()*l,x:n.x(),y:n.y(),rotation:n.rotation(),height:n.height()*l})}xt.current=t.target.position()},onTransformEnd:t=>{L(!1),W(!0);const o=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:e.fontSize*o,width:t.target.width()*o,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),shadowBlur:e.shadowBlur*o,shadowOffsetX:e.shadowOffsetX*o,shadowOffsetY:e.shadowOffsetY*o,strokeWidth:e.strokeWidth*o})}}),t.createElement(n,{ref:b,image:F,x:e.a.x,y:e.a.y,offsetX:N,offsetY:N-ht,listening:!1,rotation:e.a.rotation,width:e.a.width+2*N,height:(e.a.width+2*N)*((null!==(c=null==F?void 0:F.height)&&void 0!==c?c:0)/((null==F?void 0:F.width)||1)||1),visible:!ut&&!U,opacity:e.a.opacity,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,hideInExport:!e.showInExport,editModeEnabled:e._editModeEnabled||Y||ut}),(ut||yt)&&t.createElement(o,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-ht},t.createElement(S,{divProps:{style:{pointerEvents:"none"}}},t.createElement($,{dangerouslySetInnerHTML:{__html:tt},style:{pointerEvents:"none",opacity:e.a.opacity,textShadow:e.shadowEnabled?`${e.shadowOffsetX}px ${e.shadowOffsetY}px ${e.shadowBlur}px ${A(e.shadowColor,null!==(p=e.shadowOpacity)&&void 0!==p?p:1)}`:void 0}}))),U&&t.createElement(o,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-ht},t.createElement(S,null,t.createElement(X,{html:et,element:e,onChange:t=>{const o=T({oldText:R(e.text),newText:R(t),element:e});e.set({text:t,fontSize:o})},onBlur:t=>{e.toggleEditMode(!1),dt(!0)},clickCoords:wt.current}))))});export function setCursorFromCoords(t,e){if(!t||!e){return}const{x:o,y:n}=e;try{let e=null;if(document.caretRangeFromPoint){e=document.caretRangeFromPoint(o,n)}else if(document.caretPositionFromPoint){const t=document.caretPositionFromPoint(o,n);t&&(e=document.createRange(),e.setStart(t.offsetNode,t.offset))}if(e){const o=a.find(e.startContainer,!0);if(o){const n=o.offset(t.scroll)+e.startOffset;return void t.setSelection(n,0,"api")}}}catch(i){}t.setSelection(0,0,"api")}
|
|
16
|
+
`;let L=["bold","color","font","italic","size","strike","underline","indent","list","direction"];export const setQuillFormats=t=>{L=t};export const createQuill=t=>new a(t,{toolbar:!1,keyboard:!1,clipboard:{matchVisual:!1},formats:L});export const setQuillContent=(t,e)=>{var o=t.clipboard.convert("<div class='ql-editor' style='outline: none;'>"+e+"<p><br></p></div>");t.setContents(o),t.history.clear()};const X=({html:e,onBlur:o,onChange:n,element:i,clickCoords:r})=>{var l;const d=t.useRef(null);t.useEffect(()=>{if(!d.current){return}const t=(i=d.current,new a(i,{toolbar:!1,keyboard:!1,clipboard:{matchVisual:!1},formats:L}));var i;s.runInAction(()=>{quillRef.editor.instance=t}),window.__polotnoQuill=t,t.on("text-change",()=>{t.getSelection()&&s.runInAction(()=>{quillRef.currentFormat=t.getFormat(t.getSelection())}),setTimeout(()=>{var t;const e=null===(t=d.current)||void 0===t?void 0:t.childNodes[0];if(!e){return}const o=e.innerHTML;n(Y(o))},10)}),setQuillContent(t,e),r?setCursorFromCoords(t,r):t.setSelection(0,0,"api"),t.on("selection-change",(e,o,n)=>{e&&s.runInAction(()=>{quillRef.currentFormat=t.getFormat(t.getSelection())})}),d.current.childNodes[0].addEventListener("blur",t=>{const e=t.relatedTarget;if(null==e?void 0:e.classList.contains("ql-clipboard")){return}const n=function(t){return!!t&&!!t.closest(".sketch-picker")}(e);n||o()});const l=d.current.childNodes[0],c=e=>{var o,n;const i=t.getSelection();if(!i||0===i.length){return}const r=t.getText(i.index,i.length).replace(/\n$/,""),a=window.getSelection();let l="";if(a&&a.rangeCount>0){const t=a.getRangeAt(0),e=document.createElement("div");e.appendChild(t.cloneContents()),l=e.innerHTML}if(null===(o=e.clipboardData)||void 0===o||o.setData("text/plain",r),l){const t='<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e<div style="white-space: pre-wrap; word-wrap: break-word;">'+l+"</div>\x3c!--EndFragment--\x3e</body></html>";null===(n=e.clipboardData)||void 0===n||n.setData("text/html",t)}e.preventDefault()},f=e=>{c(e);const o=t.getSelection();o&&o.length>0&&t.deleteText(o.index,o.length)};return l.addEventListener("copy",c),l.addEventListener("cut",f),()=>{l.removeEventListener("copy",c),l.removeEventListener("cut",f),s.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={}}),delete window.__polotnoQuill}},[]),t.useEffect(()=>c(()=>i.text,()=>{var t,o;const n=quillRef.editor.instance;if(!n){return}const r=n.getSelection(),a=null===(o=null===(t=d.current)||void 0===t?void 0:t.childNodes)||void 0===o?void 0:o[0];Y((null==a?void 0:a.innerHTML)||"")===i.text||(setQuillContent(n,e),r&&(n.setSelection(r.index,r.length),s.runInAction(()=>{quillRef.currentFormat=n.getFormat(n.getSelection())})))},{fireImmediately:!0}),[]),t.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=d.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]);const f={color:i.fill};i.fill.indexOf("gradient")>=0&&(f.backgroundColor=i.fill,f.backgroundImage=i.fill,f.backgroundSize="100% 100%",f.backgroundRepeat="repeat",f.webkitBackgroundClip="text",f.MozBackgroundClip="text",f.WebkitTextFillColor="transparent",f.MozTextFillColor="transparent");const u=M(i);return t.createElement($,{ref:d,style:Object.assign(Object.assign({},f),{fontSize:i.fontSize,fontWeight:i.fontWeight,textTransform:i.textTransform,width:i.a.width,fontFamily:'"'+i.fontFamily+'"',lineHeight:i.lineHeight,letterSpacing:i.letterSpacing*i.fontSize+"px",textAlign:i.align,opacity:Math.max(i.a.opacity,.2),textShadow:i.shadowEnabled?`${i.shadowOffsetX}px ${i.shadowOffsetY}px ${i.shadowBlur}px ${A(i.shadowColor,null!==(l=i.shadowOpacity)&&void 0!==l?l:1)}`:void 0,caretColor:u}),dir:p(R(i.text))})};function q(t){return!function(t){const e=t.getContext("2d").getImageData(0,0,t.width,t.height).data;for(let o=0;o<e.length;o+=4){if(0!==e[o+3]){return!0}}return!1}(t)}const I=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);export const HTMLElement=e(({element:e,store:a})=>{var c,p;const b=t.useRef(null),[F,M]=t.useState(),[Y,L]=t.useState(!1),[D,W]=t.useState(!1),B=t.useRef(e.height),H=a.selectedShapes.indexOf(e)>=0&&e.selectable,_=g(H),N=e.fontSize/3,{textVerticalResizeEnabled:Q}=d,V=d.autoDeleteEmptyText,J=g(e.fontFamily),[G]=h(a,e.fontFamily,e.fontStyle,e.fontWeight),U=e._editModeEnabled;E(b);const K=G?e.fontFamily:J!==e.fontFamily?J:"Arial",Z=x(e).fill,tt=P(e,{fontFamily:K,color:Z}),et=P(e,{fontFamily:K,color:Z,forEditor:!0}),ot=t.useRef([]),[,nt]=t.useReducer(t=>t+1,0);t.useEffect(()=>{const t=ot.current;t.length>0&&(ot.current=[],t.forEach(t=>t()))});let{width:it,height:rt}=function(e,o,n){return t.useMemo(()=>w(e),[e,o.width,n])}(tt,e,G);t.useEffect(()=>{if(!G){return}const t=(t,o,n,i)=>{const r=k(`text ${e.id}`),l=()=>{a.history.ignore(t,o,n).then(()=>{ot.current.push(r),nt()})};i?queueMicrotask(l):l()};if(!e.height){return void t(()=>{e.height||e.set({height:rt})},void 0,void 0,!0)}const{textOverflow:o}=d;if("change-font-size"!==o||Y){"resize"===o&&(Q&&e.height<rt&&!Y&&t(()=>{e.set({height:rt})},!1,!0),Q||e.height===rt||Y||t(()=>{e.set({height:rt})},!1,!0))}else{const o=(t=>{let e=t.fontSize;for(let o=1;o<50;o++){const o=P(Object.assign(Object.assign({},t.toJSON()),{fontSize:e}),{fontFamily:t.fontFamily}),{height:n}=w(o);if(!(t.height&&n>t.height||!d.textSplitAllowed&&!t.curveEnabled&&v({html:o}))){break}e-=.5}return e})(e);o!==e.fontSize?t(()=>{e.set({fontSize:o})},!1,!0):e.height!==rt&&(Q&&e.height<rt?t(()=>{e.set({height:rt})},!1,!0):Q||t(()=>{e.set({height:rt})},!1,!0))}});const at=t.useMemo(()=>{const t={lastArgs:null,lastResult:null};return async function(e){return t.lastArgs&&t.lastResult&&(o=t.lastArgs,n=e,JSON.stringify(o)===JSON.stringify(n))||(t.lastResult=await y(e),t.lastArgs=Object.assign({},e)),t.lastResult;var o,n}},[]),lt=t.useRef(0),st=t.useRef(null);t.useEffect(()=>{Y||U||(async()=>{lt.current++;const t=lt.current;let o=k(`text ${e.id} ${t}`);st.current&&st.current(),st.current=o,W(!0);let n=null;const i=I?5:1;for(let l=0;l<i;l++){const o=l>0?at:y;try{if(n=await o({skipCache:l>0,html:tt,width:e.width||1,height:e.height||rt||1,fontFamily:K,padding:N,pixelRatio:a._elementsPixelRatio,font:a.fonts.find(t=>t.fontFamily===K)||O.globalFonts.find(t=>t.fontFamily===K)}),t!==lt.current){return}if(I&&n&&q(n)){await new Promise(t=>setTimeout(t,50*(l+1)));continue}break}catch(r){console.error(r),z(`Error rendering rich text with id ${e.id}`);break}}n?M(n):o?(o(),o=null):console.error("Finish function is called twice!"),W(!1)})()},[tt,Y,rt,U,K,e.height,a._elementsPixelRatio,G]);const[ct,dt]=j(D,300),[ft]=j(Y,300,!0),ut=ft||ct;t.useEffect(()=>{var t;if(!ut){return s.autorun(()=>{const t=b.current;f(t,e)})}null===(t=b.current)||void 0===t||t.clearCache()},[F,ut,e.shadowColor,e.shadowOffsetX,e.shadowOffsetY,e.shadowOpacity]),t.useEffect(()=>{F&&!D&&st.current&&(st.current(),st.current=null)},[F,D]),t.useLayoutEffect(()=>{if(!G){return}if(!e.curveEnabled){return}const t=new l.TextPath({data:m(e.a.width,e.a.height,e.curvePower,e.a.fontSize),text:R(e.text),letterSpacing:e.letterSpacing*e.a.fontSize,fontSize:e.a.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle,align:"center",textBaseline:"middle",fill:e.fill}),o=t.getSelfRect().width;if(o){const t=o-e.a.width,n=e.a.rotation*Math.PI/180,i=-t/2*Math.cos(n),r=-t/2*Math.sin(n);e.set({width:o,x:e.a.x+i,y:e.a.y+r})}t.destroy()},[G,e.curveEnabled,e.curvePower,e.text,e.fontSize,e.fontFamily,e.fontWeight,e.fontStyle,e.letterSpacing]),t.useEffect(()=>()=>{st.current&&st.current()},[]),t.useEffect(()=>{_&&!H&&V&&""===R(e.text)&&e.removable&&!e.placeholder&&a.deleteElements([e.id])},[V,e.placeholder,e.removable,e.text,H,_]);let ht=0;"middle"===e.verticalAlign&&(ht=(e.height-rt)/2),"bottom"===e.verticalAlign&&(ht=e.height-rt);const gt=u({fontLoaded:G,fontFamily:e.fontFamily,fontSize:e.fontSize,lineHeight:e.lineHeight}),mt=C(),pt=m(e.a.width,rt,e.curvePower,e.fontSize),xt=t.useRef(null),wt=t.useRef(null),yt=U&&e.strokeWidth>0&&!e.curveEnabled;return t.createElement(t.Fragment,null,t.createElement(r,{x:e.a.x,y:e.a.y,offsetX:e.backgroundPadding*(e.fontSize*gt*.5),offsetY:e.backgroundPadding*(e.fontSize*gt*.5),rotation:e.a.rotation,hideInExport:!e.showInExport,listening:!1,visible:e.backgroundEnabled,opacity:e.backgroundOpacity*e.a.opacity,fill:e.backgroundColor,width:e.a.width+e.backgroundPadding*(e.fontSize*gt),height:e.a.height+e.backgroundPadding*(e.fontSize*gt),cornerRadius:e.backgroundCornerRadius*(e.fontSize*gt*.5)}),t.createElement(i,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,data:pt,stroke:"red",strokeWidth:1,visible:!1}),t.createElement(r,{ref:b,name:"element",x:e.a.x,y:e.a.y,listening:e.selectable,rotation:e.a.rotation,width:e.a.width,height:e.a.height,visible:!ut,draggable:mt?e.draggable&&H:e.draggable,preventDefault:!mt||H,opacity:U?0:e.a.opacity,hideInExport:!e.showInExport,onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{e.set({x:t.target.x(),y:t.target.y()})},id:e.id,onDblClick:t=>{e.contentEditable&&(wt.current={x:t.evt.clientX,y:t.evt.clientY},e.toggleEditMode(!0))},onDblTap:t=>{var o;if(e.contentEditable){const n=null===(o=t.evt.changedTouches)||void 0===o?void 0:o[0];wt.current=n?{x:n.clientX,y:n.clientY}:null,e.toggleEditMode(!0)}},onTransformStart:t=>{L(!0),B.current=e.height},onTransform:t=>{var o;const n=t.target,i=(null===(o=n.getStage())||void 0===o?void 0:o.findOne("Transformer")).getActiveAnchor(),r="middle-left"===i||"middle-right"===i,a="top-center"===i||"bottom-center"===i,l=n.scaleX();if(r){const t=n.scaleX(),o=n.width()*t,i=e.fontSize;let r=o;if(o<i&&(r=i,xt.current&&n.position(xt.current)),n.width(r),n.scaleX(1),d.textVerticalResizeEnabled){const t=Math.max(rt,B.current);e.set({height:t})}e.set({width:n.width(),x:n.x(),y:n.y()})}else if(a){const o="resize"===d.textOverflow,i="number"==typeof e.lineHeight?e.lineHeight:1;let r=o?rt:i*e.fontSize;const a=Math.max(r,t.target.height()*t.target.scaleY());n.scaleY(1),e.set({x:n.x(),y:n.y(),height:a,rotation:n.rotation()})}else{n.scaleX(1),n.scaleY(1),e.set({fontSize:e.fontSize*l,letterSpacing:e.letterSpacing,width:n.width()*l,x:n.x(),y:n.y(),rotation:n.rotation(),height:n.height()*l})}xt.current=t.target.position()},onTransformEnd:t=>{L(!1),W(!0);const o=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:e.fontSize*o,width:t.target.width()*o,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),shadowBlur:e.shadowBlur*o,shadowOffsetX:e.shadowOffsetX*o,shadowOffsetY:e.shadowOffsetY*o,strokeWidth:e.strokeWidth*o})}}),t.createElement(n,{ref:b,image:F,x:e.a.x,y:e.a.y,offsetX:N,offsetY:N-ht,listening:!1,rotation:e.a.rotation,width:e.a.width+2*N,height:(e.a.width+2*N)*((null!==(c=null==F?void 0:F.height)&&void 0!==c?c:0)/((null==F?void 0:F.width)||1)||1),visible:!ut&&!U,opacity:e.a.opacity,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,hideInExport:!e.showInExport,editModeEnabled:e._editModeEnabled||Y||ut}),(ut||yt)&&t.createElement(o,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-ht},t.createElement(S,{divProps:{style:{pointerEvents:"none"}}},t.createElement($,{dangerouslySetInnerHTML:{__html:tt},style:{pointerEvents:"none",opacity:e.a.opacity,textShadow:e.shadowEnabled?`${e.shadowOffsetX}px ${e.shadowOffsetY}px ${e.shadowBlur}px ${A(e.shadowColor,null!==(p=e.shadowOpacity)&&void 0!==p?p:1)}`:void 0}}))),U&&t.createElement(o,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-ht},t.createElement(S,null,t.createElement(X,{html:et,element:e,onChange:t=>{const o=T({oldText:R(e.text),newText:R(t),element:e});e.set({text:t,fontSize:o})},onBlur:t=>{e.toggleEditMode(!1),dt(!0)},clickCoords:wt.current}))))});export function setCursorFromCoords(t,e){if(!t||!e){return}const{x:o,y:n}=e;try{let e=null;if(document.caretRangeFromPoint){e=document.caretRangeFromPoint(o,n)}else if(document.caretPositionFromPoint){const t=document.caretPositionFromPoint(o,n);t&&(e=document.createRange(),e.setStart(t.offsetNode,t.offset))}if(e){const o=a.find(e.startContainer,!0);if(o){const n=o.offset(t.scroll)+e.startOffset;return void t.setSelection(n,0,"api")}}}catch(i){}t.setSelection(0,0,"api")}
|
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import e from"react";import{observer as t}from"mobx-react-lite";import{Button as n,Navbar as i}from"@blueprintjs/core";import{Plus as r,Play as o}from"@blueprintjs/icons";import a from"../utils/styled.js";import{flags as l}from"../utils/flags.js";import{t as s}from"../utils/l10n.js";import{Pages as m}from"./pages.js";import{CurrentTime as
|
|
1
|
+
import e from"react";import{observer as t}from"mobx-react-lite";import{Button as n,Navbar as i}from"@blueprintjs/core";import{Plus as r,Play as o}from"@blueprintjs/icons";import a from"../utils/styled.js";import{flags as l}from"../utils/flags.js";import{t as s}from"../utils/l10n.js";import{Pages as m}from"./pages.js";import{CurrentTime as d}from"./current-time.js";import{Audios as c}from"./audios.js";import{ElementsTimeline as u}from"./elements.js";import{PlayButton as p}from"./play-button.js";import{TimeRuler as v}from"./time-ruler.js";const f=a("div")`
|
|
2
2
|
position: relative;
|
|
3
3
|
height: 0px;
|
|
4
4
|
`,h=a("div")`
|
|
@@ -35,4 +35,4 @@ import e from"react";import{observer as t}from"mobx-react-lite";import{Button as
|
|
|
35
35
|
&.active::before {
|
|
36
36
|
background: var(--polotno-accent-color, #137cbd);
|
|
37
37
|
}
|
|
38
|
-
`;export const PagesTimeline=t(({store:t,defaultOpened:a=!1})=>{const g=e.useRef(null),[b,x]=e.useState(a),[w,y]=e.useState(.02),[j,k]=e.useState(()=>(e=>{if(!l.animationsEnabled){return 65}const t=e.pages.reduce((e,t)=>e+t.children.length,0),n=25*e.audios.length+20*t+140;return Math.min(Math.max(n,140),420)})(t)),[L,C]=e.useState(!1),M=e.useRef(0),R=e.useRef(j),S=e.useRef(!1),P=t.duration*w,z=e.useCallback(e=>{if(!S.current){return}const t=e.clientY-M.current,n=R.current-t,i=Math.min(420,Math.max(140,n));k(i)},[]),D=e.useCallback(()=>{S.current&&(S.current=!1,C(!1),window.removeEventListener("mousemove",z),window.removeEventListener("mouseup",D))},[z]);return e.useEffect(()=>()=>{window.removeEventListener("mousemove",z),window.removeEventListener("mouseup",D)},[z,D]),e.createElement(e.Fragment,null,e.createElement(f,null,e.createElement(h,null,e.createElement(i,{style:{height:"35px",padding:"0 5px"}},e.createElement(i.Group,{style:{height:"35px"}},e.createElement(n,{minimal:!0,onClick:()=>{x(!b)},icon:l.animationsEnabled&&!b?e.createElement(o,null):null},s("pagesTimeline.pages")))))),e.createElement(i,{style:{padding:"5px",height:"auto",zIndex:1,position:"relative",overflow:"visible",display:b?"block":"none"},className:"polotno-pages-timeline"},l.animationsEnabled&&e.createElement(E,{onMouseDown:e=>{e.preventDefault(),M.current=e.clientY,R.current=j,S.current=!0,C(!0),window.addEventListener("mousemove",z),window.addEventListener("mouseup",D)},className:L?"active":void 0,title:"Drag to adjust timeline height"}),l.animationsEnabled&&e.createElement("div",{style:{display:"flex",justifyContent:"center"}},e.createElement(p,{store:t,scale:w,onScaleChange:y})),e.createElement("div",{style:{width:"100%",position:"relative",height:j}},e.createElement("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,overflowX:"auto",padding:"0 24px"},ref:g},e.createElement("div",{style:{position:"relative",minWidth:l.animationsEnabled?P+"px":void 0}},l.animationsEnabled&&e.createElement(v,{store:t,scale:w,minWidth:P}),e.createElement("div",{style:{position:"relative",display:"flex"}},e.createElement("div",{style:{position:"relative",minWidth:l.animationsEnabled?P+"px":void 0,height:"60px"}},e.createElement(m,{store:t,scale:w})),e.createElement(n,{icon:e.createElement(r,null),style:{width:"60px",marginLeft:"12px"},onClick:()=>{var e;t.addPage({bleed:(null===(e=t.activePage)||void 0===e?void 0:e.bleed)||0})},minimal:!0})),l.animationsEnabled&&e.createElement(e.Fragment,null,e.createElement(u,{store:t,scale:w,width:P}),e.createElement(
|
|
38
|
+
`;export const PagesTimeline=t(({store:t,defaultOpened:a=!1})=>{const g=e.useRef(null),[b,x]=e.useState(a),[w,y]=e.useState(.02),[j,k]=e.useState(()=>(e=>{if(!l.animationsEnabled){return 65}const t=e.pages.reduce((e,t)=>e+t.children.length,0),n=25*e.audios.length+20*t+140;return Math.min(Math.max(n,140),420)})(t)),[L,C]=e.useState(!1),M=e.useRef(0),R=e.useRef(j),S=e.useRef(!1),P=t.duration*w,z=e.useCallback(e=>{if(!S.current){return}const t=e.clientY-M.current,n=R.current-t,i=Math.min(420,Math.max(140,n));k(i)},[]),D=e.useCallback(()=>{S.current&&(S.current=!1,C(!1),window.removeEventListener("mousemove",z),window.removeEventListener("mouseup",D))},[z]);return e.useEffect(()=>()=>{window.removeEventListener("mousemove",z),window.removeEventListener("mouseup",D)},[z,D]),e.createElement(e.Fragment,null,e.createElement(f,null,e.createElement(h,null,e.createElement(i,{style:{height:"35px",padding:"0 5px"}},e.createElement(i.Group,{style:{height:"35px"}},e.createElement(n,{minimal:!0,onClick:()=>{x(!b)},icon:l.animationsEnabled&&!b?e.createElement(o,null):null},s("pagesTimeline.pages")))))),e.createElement(i,{style:{padding:"5px",height:"auto",zIndex:1,position:"relative",overflow:"visible",display:b?"block":"none"},className:"polotno-pages-timeline"},l.animationsEnabled&&e.createElement(E,{onMouseDown:e=>{e.preventDefault(),M.current=e.clientY,R.current=j,S.current=!0,C(!0),window.addEventListener("mousemove",z),window.addEventListener("mouseup",D)},className:L?"active":void 0,title:"Drag to adjust timeline height"}),l.animationsEnabled&&e.createElement("div",{style:{display:"flex",justifyContent:"center"}},e.createElement(p,{store:t,scale:w,onScaleChange:y})),e.createElement("div",{dir:"ltr",style:{width:"100%",position:"relative",height:j}},e.createElement("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,overflowX:"auto",padding:"0 24px"},ref:g},e.createElement("div",{style:{position:"relative",minWidth:l.animationsEnabled?P+"px":void 0}},l.animationsEnabled&&e.createElement(v,{store:t,scale:w,minWidth:P}),e.createElement("div",{style:{position:"relative",display:"flex"}},e.createElement("div",{style:{position:"relative",minWidth:l.animationsEnabled?P+"px":void 0,height:"60px"}},e.createElement(m,{store:t,scale:w})),e.createElement(n,{icon:e.createElement(r,null),style:{width:"60px",marginLeft:"12px"},onClick:()=>{var e;t.addPage({bleed:(null===(e=t.activePage)||void 0===e?void 0:e.bleed)||0})},minimal:!0})),l.animationsEnabled&&e.createElement(e.Fragment,null,e.createElement(u,{store:t,scale:w,width:P}),e.createElement(c,{store:t,scale:w,width:P})),l.animationsEnabled&&e.createElement(d,{store:t,scale:w,dragAreaRef:g,variant:"timeline"}))))))});
|
package/polotno.bundle.js
CHANGED
|
@@ -180,7 +180,7 @@ For more info see: https://github.com/konvajs/react-konva/issues/194
|
|
|
180
180
|
.ql-direction-rtl {
|
|
181
181
|
direction: rtl;
|
|
182
182
|
}
|
|
183
|
-
`,oO=["bold","color","font","italic","size","strike","underline","indent","list","direction"],oA=e=>{oO=e},oI=e=>new(m(aP))(e,{toolbar:!1,keyboard:!1,clipboard:{matchVisual:!1},formats:oO}),oR=(e,t)=>{var n=e.clipboard.convert("<div class='ql-editor' style='outline: none;'>"+t+"<p><br></p></div>");e.setContents(n),e.history.clear()},oL=({html:e,onBlur:t,onChange:n,element:r,clickCoords:i})=>{let a=m(S).useRef(null);m(S).useEffect(()=>{if(!a.current)return;let r=oI(a.current);E.runInAction(()=>{oT.editor.instance=r}),window.__polotnoQuill=r,r.on("text-change",()=>{r.getSelection()&&E.runInAction(()=>{oT.currentFormat=r.getFormat(r.getSelection())}),setTimeout(()=>{let e=a.current?.childNodes[0];e&&n(oE(e.innerHTML))},10)}),oR(r,e),i?function(e,t){if(!e||!t)return;let{x:n,y:r}=t;try{let t=null;if(document.caretRangeFromPoint)t=document.caretRangeFromPoint(n,r);else if(document.caretPositionFromPoint){let e=document.caretPositionFromPoint(n,r);e&&(t=document.createRange()).setStart(e.offsetNode,e.offset)}if(t){let n=m(aP).find(t.startContainer,!0);if(n){let r=n.offset(e.scroll)+t.startOffset;e.setSelection(r,0,"api");return}}}catch(e){}e.setSelection(0,0,"api")}(r,i):r.setSelection(0,0,"api"),r.on("selection-change",(e,t,n)=>{e&&E.runInAction(()=>{oT.currentFormat=r.getFormat(r.getSelection())})}),a.current.childNodes[0].addEventListener("blur",e=>{var n;let r=e.relatedTarget;r?.classList.contains("ql-clipboard")||(n=r)&&n.closest(".sketch-picker")||t()});let o=a.current.childNodes[0],s=e=>{let t=r.getSelection();if(!t||0===t.length)return;let n=r.getText(t.index,t.length).replace(/\n$/,""),i=window.getSelection(),a="";if(i&&i.rangeCount>0){let e=i.getRangeAt(0),t=document.createElement("div");t.appendChild(e.cloneContents()),a=t.innerHTML}if(e.clipboardData?.setData("text/plain",n),a){let t='<div style="white-space: pre-wrap; word-wrap: break-word;">'+a+"</div>";e.clipboardData?.setData("text/html",'<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e'+t+"\x3c!--EndFragment--\x3e</body></html>")}e.preventDefault()},l=e=>{s(e);let t=r.getSelection();t&&t.length>0&&r.deleteText(t.index,t.length)};return o.addEventListener("copy",s),o.addEventListener("cut",l),()=>{o.removeEventListener("copy",s),o.removeEventListener("cut",l),E.runInAction(()=>{oT.editor.instance=null,oT.currentFormat={}}),delete window.__polotnoQuill}},[]),m(S).useEffect(()=>(0,E.reaction)(()=>r.text,()=>{let t=oT.editor.instance;if(!t)return;let n=t.getSelection(),i=a.current?.childNodes?.[0];oE(i?.innerHTML||"")!==r.text&&(oR(t,e),n&&(t.setSelection(n.index,n.length),E.runInAction(()=>{oT.currentFormat=t.getFormat(t.getSelection())})))},{fireImmediately:!0}),[]),m(S).useEffect(()=>{window.addEventListener("blur",t);let e=e=>{a.current?.contains(e.target)||t()};return window.addEventListener("touchstart",e),()=>{window.removeEventListener("blur",t),window.removeEventListener("touchstart",e)}},[]);let o={color:r.fill};r.fill.indexOf("gradient")>=0&&(o.backgroundColor=r.fill,o.backgroundImage=r.fill,o.backgroundSize="100% 100%",o.backgroundRepeat="repeat",o.webkitBackgroundClip="text",o.MozBackgroundClip="text",o.WebkitTextFillColor="transparent",o.MozTextFillColor="transparent");let s=iZ(r);return(0,C.jsx)(oP,{ref:a,style:{...o,fontSize:r.fontSize,fontWeight:r.fontWeight,textTransform:r.textTransform,width:r.a.width,fontFamily:'"'+r.fontFamily+'"',lineHeight:r.lineHeight,letterSpacing:r.letterSpacing*r.fontSize+"px",textAlign:r.align,opacity:Math.max(r.a.opacity,.2),textShadow:r.shadowEnabled?`${r.shadowOffsetX}px ${r.shadowOffsetY}px ${r.shadowBlur}px ${o_(r.shadowColor,r.shadowOpacity??1)}`:void 0,caretColor:s},dir:iH(iz(r.text))})},oM=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),oN=j(({element:e,store:t})=>{let n=m(S).useRef(null),[r,i]=m(S).useState(),[a,o]=m(S).useState(!1),[s,l]=m(S).useState(!1),c=m(S).useRef(e.height),u=t.selectedShapes.indexOf(e)>=0&&e.selectable,d=i3(u),h=e.fontSize/3,{textVerticalResizeEnabled:f}=iS,p=iS.autoDeleteEmptyText,g=i3(e.fontFamily),[y]=i2(t,e.fontFamily,e.fontStyle,e.fontWeight),v=e._editModeEnabled;r0(n);let b=y?e.fontFamily:g!==e.fontFamily?g:"Arial",x=rQ(e).fill,w=i$(e,{fontFamily:b,color:x}),k=i$(e,{fontFamily:b,color:x,forEditor:!0}),_=m(S).useRef([]),[,T]=m(S).useReducer(e=>e+1,0);m(S).useEffect(()=>{let e=_.current;e.length>0&&(_.current=[],e.forEach(e=>e()))});let{width:P,height:O}=m(S).useMemo(()=>od(w),[w,e.width,y]);m(S).useEffect(()=>{if(!y)return;let n=(n,r,i,a)=>{let o=r5(`text ${e.id}`),s=()=>{t.history.ignore(n,r,i).then(()=>{_.current.push(o),T()})};a?queueMicrotask(s):s()};if(!e.height)return void n(()=>{e.height||e.set({height:O})},void 0,void 0,!0);let{textOverflow:r}=iS;if("change-font-size"!==r||a)"resize"===r&&(f&&e.height<O&&!a&&n(()=>{e.set({height:O})},!1,!0),f||e.height===O||n(()=>{e.set({height:O})},!1,!0));else{let t=(e=>{let t=e.fontSize;for(let n=1;n<50;n++){let n=i$({...e.toJSON(),fontSize:t},{fontFamily:e.fontFamily}),{height:r}=od(n);if(!(e.height&&r>e.height||!iS.textSplitAllowed&&!e.curveEnabled&&function({html:e}){let t=document.createElement("div");t.innerHTML=e,t.style.display="inline-block",t.style.position="fixed",t.style.top="0px",t.style.left="0px",t.style.zIndex="1000",t.style.whiteSpace="nowrap",t.style.visibility="hidden";let n=ou();n.appendChild(t);let r=t.innerText,i=t.childNodes[0];i.style.whiteSpace="nowrap";let a=r?.split(/\s+/)||[],o=!1;for(let e=0;e<a.length;e++){let n=a[e];if(i&&(i.textContent=n,o=i.scrollWidth>t.clientWidth))break}return n.removeChild(t),o}({html:n})))break;t-=.5}return t})(e);t!==e.fontSize?n(()=>{e.set({fontSize:t})},!1,!0):e.height!==O&&(f&&e.height<O?n(()=>{e.set({height:O})},!1,!0):f||n(()=>{e.set({height:O})},!1,!0))}});let A=m(S).useMemo(()=>{let e={lastArgs:null,lastResult:null};return async function(t){var n;return e.lastArgs&&e.lastResult&&(n=e.lastArgs,JSON.stringify(n)===JSON.stringify(t))||(e.lastResult=await og(t),e.lastArgs={...t}),e.lastResult}},[]),I=m(S).useRef(0),R=m(S).useRef(null),L=async()=>{I.current++;let n=I.current,r=r5(`text ${e.id} ${n}`);R.current&&R.current(),R.current=r,l(!0);let a=null,o=oM?5:1;for(let r=0;r<o;r++){let i=r>0?A:og;try{var s;if(a=await i({skipCache:r>0,html:w,width:e.width||1,height:e.height||O||1,fontFamily:b,padding:h,pixelRatio:t._elementsPixelRatio,font:t.fonts.find(e=>e.fontFamily===b)||is.find(e=>e.fontFamily===b)}),n!==I.current)return;if(oM&&a&&(s=a,!function(e){let t=e.getContext("2d").getImageData(0,0,e.width,e.height).data;for(let e=0;e<t.length;e+=4)if(0!==t[e+3])return!0;return!1}(s))){await new Promise(e=>setTimeout(e,50*(r+1)));continue}break}catch(t){console.error(t),it(`Error rendering rich text with id ${e.id}`);break}}a?i(a):r?(r(),r=null):console.error("Finish function is called twice!"),l(!1)};m(S).useEffect(()=>{a||v||L()},[w,a,O,v,b,e.height,t._elementsPixelRatio,y]);let[M,N]=au(s,300),[j]=au(a,300,!0),D=j||M;m(S).useEffect(()=>D?void n.current?.clearCache():E.autorun(()=>{iW(n.current,e)}),[r,D,e.shadowColor,e.shadowOffsetX,e.shadowOffsetY,e.shadowOpacity]),m(S).useEffect(()=>{r&&!s&&R.current&&(R.current(),R.current=null)},[r,s]),m(S).useLayoutEffect(()=>{if(!y||!e.curveEnabled)return;let t=new n_.TextPath({data:iV(e.a.width,e.a.height,e.curvePower,e.a.fontSize),text:iz(e.text),letterSpacing:e.letterSpacing*e.a.fontSize,fontSize:e.a.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle,align:"center",textBaseline:"middle",fill:e.fill}),n=t.getSelfRect().width;if(n){let t=n-e.a.width,r=e.a.rotation*Math.PI/180,i=-(t/2)*Math.cos(r),a=-(t/2)*Math.sin(r);e.set({width:n,x:e.a.x+i,y:e.a.y+a})}t.destroy()},[y,e.curveEnabled,e.curvePower,e.text,e.fontSize,e.fontFamily,e.fontWeight,e.fontStyle,e.letterSpacing]),m(S).useEffect(()=>()=>{R.current&&R.current()},[]),m(S).useEffect(()=>{d&&!u&&p&&""===iz(e.text)&&e.removable&&!e.placeholder&&t.deleteElements([e.id])},[p,e.placeholder,e.removable,e.text,u,d]);let z=0;"middle"===e.verticalAlign&&(z=(e.height-O)/2),"bottom"===e.verticalAlign&&(z=e.height-O);let B=i4({fontLoaded:y,fontFamily:e.fontFamily,fontSize:e.fontSize,lineHeight:e.lineHeight}),F=iK(),H=iV(e.a.width,O,e.curvePower,e.fontSize),V=m(S).useRef(null),U=m(S).useRef(null),$=v&&e.strokeWidth>0&&!e.curveEnabled;return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(rP,{x:e.a.x,y:e.a.y,offsetX:e.backgroundPadding*(e.fontSize*B*.5),offsetY:e.backgroundPadding*(e.fontSize*B*.5),rotation:e.a.rotation,hideInExport:!e.showInExport,listening:!1,visible:e.backgroundEnabled,opacity:e.backgroundOpacity*e.a.opacity,fill:e.backgroundColor,width:e.a.width+e.backgroundPadding*(e.fontSize*B),height:e.a.height+e.backgroundPadding*(e.fontSize*B),cornerRadius:e.backgroundCornerRadius*(e.fontSize*B*.5)}),(0,C.jsx)(rR,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,data:H,stroke:"red",strokeWidth:1,visible:!1}),(0,C.jsx)(rP,{ref:n,name:"element",x:e.a.x,y:e.a.y,listening:e.selectable,rotation:e.a.rotation,width:e.a.width,height:e.a.height,visible:!D,draggable:F?e.draggable&&u:e.draggable,preventDefault:!F||u,opacity:v?0:e.a.opacity,hideInExport:!e.showInExport,onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{e.set({x:t.target.x(),y:t.target.y()})},id:e.id,onDblClick:t=>{e.contentEditable&&(U.current={x:t.evt.clientX,y:t.evt.clientY},e.toggleEditMode(!0))},onDblTap:t=>{if(e.contentEditable){let n=t.evt.changedTouches?.[0];U.current=n?{x:n.clientX,y:n.clientY}:null,e.toggleEditMode(!0)}},onTransformStart:t=>{o(!0),c.current=e.height},onTransform:t=>{let n=t.target,r=(n.getStage()?.findOne("Transformer")).getActiveAnchor(),i=n.scaleX();if("middle-left"===r||"middle-right"===r){let t=n.scaleX(),r=n.width()*t,i=e.fontSize,a=r;if(r<i&&(a=i,V.current&&n.position(V.current)),n.width(a),n.scaleX(1),iS.textVerticalResizeEnabled){let t=Math.max(O,c.current);e.set({height:t})}e.set({width:n.width(),x:n.x(),y:n.y()})}else if("top-center"===r||"bottom-center"===r){let r="resize"===iS.textOverflow,i="number"==typeof e.lineHeight?e.lineHeight:1,a=Math.max(r?O:i*e.fontSize,t.target.height()*t.target.scaleY());n.scaleY(1),e.set({x:n.x(),y:n.y(),height:a,rotation:n.rotation()})}else n.scaleX(1),n.scaleY(1),e.set({fontSize:e.fontSize*i,letterSpacing:e.letterSpacing,width:n.width()*i,x:n.x(),y:n.y(),rotation:n.rotation(),height:n.height()*i});V.current=t.target.position()},onTransformEnd:t=>{o(!1),l(!0);let n=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:e.fontSize*n,width:t.target.width()*n,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),shadowBlur:e.shadowBlur*n,shadowOffsetX:e.shadowOffsetX*n,shadowOffsetY:e.shadowOffsetY*n,strokeWidth:e.strokeWidth*n})}}),(0,C.jsx)(rA,{ref:n,image:r,x:e.a.x,y:e.a.y,offsetX:h,offsetY:h-z,listening:!1,rotation:e.a.rotation,width:e.a.width+2*h,height:(e.a.width+2*h)*((r?.height??0)/(r?.width||1)||1),visible:!D&&!v,opacity:e.a.opacity,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,hideInExport:!e.showInExport,editModeEnabled:e._editModeEnabled||a||D}),(D||$)&&(0,C.jsx)(rE,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-z,children:(0,C.jsx)(rz,{divProps:{style:{pointerEvents:"none"}},children:(0,C.jsx)(oP,{dangerouslySetInnerHTML:{__html:w},style:{pointerEvents:"none",opacity:e.a.opacity,textShadow:e.shadowEnabled?`${e.shadowOffsetX}px ${e.shadowOffsetY}px ${e.shadowBlur}px ${o_(e.shadowColor,e.shadowOpacity??1)}`:void 0}})})}),v&&(0,C.jsx)(rE,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-z,children:(0,C.jsx)(rz,{children:(0,C.jsx)(oL,{html:k,element:e,onChange:t=>{let n=iX({oldText:iz(e.text),newText:iz(t),element:e});e.set({text:t,fontSize:n})},onBlur:t=>{e.toggleEditMode(!1),N(!0)},clickCoords:U.current})})})]})});var S=(x("8NFma"),x("8NFma"));function oj(e){return e/180*Math.PI}function oD(e,t,n,r,i){let a=Math.sqrt(n*n+r*r);return{x:e+a*Math.cos(i+=Math.atan2(r,n)),y:t+a*Math.sin(i)}}function oz(e){let{x:t,y:n,width:r,height:i}=e,a=oj(e.rotation),o=oD(t,n,0,0,a),s=oD(t,n,r,0,a),l=oD(t,n,r,i,a),c=oD(t,n,0,i,a),u=Math.min(o.x,s.x,l.x,c.x),d=Math.min(o.y,s.y,l.y,c.y),h=Math.max(o.x,s.x,l.x,c.x),f=Math.max(o.y,s.y,l.y,c.y);return{x:u,y:d,width:h-u,height:f-d,minX:u,minY:d,maxX:h,maxY:f}}function oB(e){let t=e.map(e=>oz(e)),n=Math.min(...t.map(e=>e.minX)),r=Math.min(...t.map(e=>e.minY)),i=Math.max(...t.map(e=>e.maxX)),a=Math.max(...t.map(e=>e.maxY));return{x:n,y:r,width:i-n,height:a-r,minX:n,minY:r,maxX:i,maxY:a}}let oF={stroke:"rgb(0, 161, 255)",strokeWidth:1,dash:[4,6]},oH=({targetKonvaNodes:e,guideKonvaNode:t,distance:n,snapDirection:r})=>n<5,oV=e=>{oH=e};function oU(e,t){var n=[],r=[];e.vertical.forEach(e=>{t.vertical.forEach(t=>{var r=Math.abs(e.offset-t.guide);oH({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:r,snapDirection:e.snap})&&n.push({lineGuide:e.offset,diff:r,snap:t.snap,offset:t.offset})})}),e.horizontal.forEach(e=>{t.horizontal.forEach(t=>{var n=Math.abs(e.offset-t.guide);oH({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:n,snapDirection:e.snap})&&r.push({lineGuide:e.offset,diff:n,snap:t.snap,offset:t.offset})})});var i=[];let a=n.sort((e,t)=>e.diff-t.diff),o=r.sort((e,t)=>e.diff-t.diff);var s=a[0],l=o[0];return s&&a.filter(e=>.1>Math.abs(e.diff-s.diff)).forEach(e=>{i.push({orientation:"V",...e})}),l&&o.filter(e=>.1>Math.abs(e.diff-l.diff)).forEach(e=>{i.push({orientation:"H",...e})}),i}let o$=()=>{if(0===n_.DD._dragElements.size)return;let e=[...n_.DD._dragElements.entries()],t=e.find(([e,t])=>t.node instanceof n_.Transformer);t&&(e.splice(e.indexOf(t),1),e.unshift(t),n_.DD._dragElements.clear(),e.forEach(([e,t])=>{n_.DD._dragElements.set(e,t)}))};function oq(e,t,n){let r=e=>e.hasName("element")||e.hasName("line-anchor")||e.hasName("page-background")||e.hasName("elements-area"),i=n=>{let i,a,o,s=n.target.getLayer().children.find(e=>"line-guides"===e.name());s?.destroyChildren();var l,c,u,d,h=oU((l=[n.target,...t.map(e=>e.current)],i=e.current?.getStage(),c=[],u=[],i.find(r).forEach(e=>{if(!(l.indexOf(e)>=0)){var t=e.getClientRect({skipShadow:!0,skipStroke:!0});e.hasName("line-anchor")&&(t={x:e.absolutePosition().x,y:e.absolutePosition().y,width:0,height:0}),c.push({offset:t.x,node:e,snap:"start"},{offset:t.x+t.width,node:e,snap:"end"},{offset:t.x+t.width/2,node:e,snap:"center"}),u.push({offset:t.y,node:e,snap:"start"},{offset:t.y+t.height,node:e,snap:"end"},{offset:t.y+t.height/2,node:e,snap:"center"})}}),{vertical:c,horizontal:u}),{vertical:[{guide:(d=n.target).absolutePosition().x,offset:0,snap:"center",nodes:[d]}],horizontal:[{guide:d.absolutePosition().y,offset:0,snap:"center",nodes:[d]}]});if(!h.length)return;a=e.current?.getLayer(),o=a?.children.find(e=>"line-guides"===e.name()),h.forEach(e=>{if("H"===e.orientation){var t=new n_.Line({x:-a.getStage().x(),y:-a.getStage().y(),points:[-6e3,e.lineGuide,6e3,e.lineGuide],stroke:oF.stroke,strokeWidth:oF.strokeWidth,name:"guid-line",dash:oF.dash});o?.add(t),a.batchDraw()}else if("V"===e.orientation){var t=new n_.Line({x:-a.getStage().x(),y:-a.getStage().y(),points:[e.lineGuide,-6e3,e.lineGuide,6e3],stroke:oF.stroke,strokeWidth:oF.strokeWidth,name:"guid-line",dash:oF.dash});o?.add(t)}});let f=n.target.getAbsolutePosition(),p={...f};h.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":p.x=e.lineGuide+e.offset;break;case"H":p.y=e.lineGuide+e.offset}}});let m=p.x-f.x,g=p.y-f.y;if(!(n.evt.ctrlKey||n.evt.metaKey)){let e=n.target.getAbsolutePosition();n.target.absolutePosition({x:e.x+m,y:e.y+g})}},a=e=>{if(!e.target)return;let t=e.target.getLayer(),n=t.children.find(e=>"line-guides"===e.name());n?.destroyChildren(),t.batchDraw()};m(S).useEffect(()=>{e.current&&(e.current.on("dragmove",i),e.current.on("dragend",a))},n)}function oW(e,t){return e.x*t.x+e.y*t.y}let oG={"top-left":"bottom-right","top-center":"bottom-center","top-right":"bottom-left","middle-right":"middle-left","bottom-right":"top-left","bottom-center":"top-center","bottom-left":"top-right","middle-left":"middle-right"};function oK(e){let{x:t,y:n,width:r,height:i,rotation:a}=e.a,o=a*Math.PI/180,s={x:t+i/2*Math.cos(o+Math.PI/2),y:n+i/2*Math.sin(o+Math.PI/2)},l={x:s.x+r*Math.cos(o),y:s.y+r*Math.sin(o)};return{middleLeft:s,middleRight:l}}function oY(e,t,n){let r=Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2)),i=Math.atan2(t.y-e.y,t.x-e.x),a=180*i/Math.PI;return{x:e.x+Math.cos(i-Math.PI/2)*n/2,y:e.y+Math.sin(i-Math.PI/2)*n/2,width:r,height:n,rotation:a}}let oX=(e,t)=>{let n=h9.anchorSize||10;return{offsetX:n/2/e,offsetY:n/2/e,width:n/e,height:n/e,cornerRadius:(h9.anchorCornerRadius||0)/e,fill:h9.anchorFill||"white",stroke:h9.anchorStroke||"rgb(0, 161, 255)",strokeWidth:h9.anchorStrokeWidth||2,strokeScaleEnabled:!1,draggable:!0,dragDistance:0,onMouseEnter:e=>{e.target.getStage().container().style.cursor="crosshair"},onMouseLeave:e=>{e.target.getStage().container().style.cursor=""},onDragStart:e=>{t.history.startTransaction()},onDragEnd:e=>{t.history.endTransaction()}}},oQ=j(({element:e,type:t})=>{let n=rQ(e,e.a.color,"fill"),r=rQ(e,e.a.color,"stroke"),i={strokeWidth:e.height,lineCap:"round",lineJoin:"round",...r,...n,opacity:e.a.opacity,hideInExport:!e.showInExport};return(0,C.jsxs)(C.Fragment,{children:["arrow"===t&&(0,C.jsx)(rO,{points:[3*e.height,-(2*e.height),0,0,3*e.height,2*e.height],...i}),"triangle"===t&&(0,C.jsx)(rO,{points:[3*e.height,-(2*e.height),0,0,3*e.height,2*e.height],closed:!0,...i}),"bar"===t&&(0,C.jsx)(rO,{points:[0,-(2*e.height),0,2*e.height],closed:!0,...i}),"square"===t&&(0,C.jsx)(rO,{points:[0,-(2*e.height),4*e.height,-(2*e.height),4*e.height,2*e.height,0,2*e.height],closed:!0,...i}),"circle"===t&&(0,C.jsx)("Circle",{x:2*e.height,y:0,radius:2*e.height,...i})]})}),oZ=j(({element:e,store:t})=>{let n=m(S).useRef(null),r=m(S).useRef(null),i=m(S).useRef(null),a=e.selectable||"admin"===t.role,o=iK(),s=t.selectedElements.indexOf(e)>=0&&1===t.selectedElements.length,l=t.selectedShapes.indexOf(e)>=0&&e.selectable,{middleLeft:c,middleRight:u}=oK(e);oq(r,[n],[s]),oq(i,[n],[s]);let d=rQ(e,e.a.color,"stroke");return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(rO,{ref:n,name:"element",id:e.id,x:e.a.x,y:e.a.y,points:[0,0,e.a.width,0],offsetY:-e.a.height/2,strokeWidth:e.a.height,hitStrokeWidth:Math.max(e.a.height,20),dash:e.dash.map(t=>t*e.a.height),...d,rotation:e.a.rotation,opacity:e.animated("opacity"),shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,listening:a,draggable:o?e.draggable&&l:e.draggable,preventDefault:!o||l,hideInExport:!e.showInExport,onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{e.set({x:t.target.x(),y:t.target.y()})},onTransform:t=>{let n=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({height:e.height*n,width:e.width*n,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation()})}}),(0,C.jsx)(rE,{x:c.x,y:c.y,rotation:e.rotation,hideInExport:!e.showInExport,onClick:e=>n.current?.fire("click",e),onTap:e=>n.current?.fire("tap",e),children:(0,C.jsx)(oQ,{element:e,type:e.startHead})}),(0,C.jsx)(rE,{x:u.x,y:u.y,rotation:e.rotation+180,onClick:e=>n.current?.fire("click",e),onTap:e=>n.current?.fire("tap",e),children:(0,C.jsx)(oQ,{element:e,type:e.endHead})}),s&&e.resizable&&(0,C.jsx)(rB,{selector:".page-abs-container",enabled:!0,children:(0,C.jsxs)(rE,{visible:s,children:[(0,C.jsx)(rP,{x:c.x,y:c.y,ref:r,name:"line-anchor",...oX(t.scale,t),onDragMove:t=>{let n=oY(t.target.position(),u,e.height);e.set({x:n.x,y:n.y,width:n.width,rotation:n.rotation})}}),(0,C.jsx)(rP,{x:u.x,y:u.y,ref:i,name:"line-anchor",...oX(t.scale,t),onDragMove:t=>{let n=oY(c,t.target.position(),e.height);e.set({x:n.x,y:n.y,width:n.width,rotation:n.rotation})}})]})})]})});var S=x("8NFma"),E=x("2SBKn"),S=x("8NFma"),E=x("2SBKn");function oJ(e){if(!e)throw Error("Assertion failed.")}let o0=e=>{let t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw Error(`Invalid rotation ${e}.`)},o1=e=>e&&e[e.length-1];class o2{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(7&this.pos);return this.pos++,(t&1<<n)>>n}readBits(e){if(1===e)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(7&e);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}readAlignedByte(){if(this.pos%8!=0)throw Error("Bitstream is not byte-aligned.");let 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(){let e=new o2(this.bytes);return e.pos=this.pos,e}}let o4=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw Error("Invalid exponential-Golomb code.");return(1<<t)-1+e.readBits(t)},o3=e=>{let t=o4(e);return(1&t)==0?-(t>>1):t+1>>1},o8=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),o6=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),o5=new TextDecoder,o9=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),o7={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},se=o9(o7),st={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},sn=o9(st),sr={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},si=o9(sr),sa=e=>e instanceof ArrayBuffer||"u">typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class so{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||(t(),this.pending--,n=!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}}let ss=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),sl=e=>(e=(e=(e=(e=(e=e>>1&0x55555555|(0x55555555&e)<<1)>>2&0x33333333|(0x33333333&e)<<2)>>4&0xf0f0f0f|(0xf0f0f0f&e)<<4)>>8&0xff00ff|(0xff00ff&e)<<8)>>16&65535|(65535&e)<<16)>>>0,sc=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+i>>1,s=n(e[o]);s===t?(a=o,i=o-1):s<t?r=o+1:i=o-1}return a},su=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+(i-r+1)/2|0;n(e[o])<=t?(a=o,r=o+1):i=o-1}return a},sd=(e,t,n)=>{let r=su(e,n(t),n);e.splice(r+1,0,t)},sh=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},sf=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]},sp=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return -1},sm=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},sg=e=>{throw Error(`Unexpected value: ${e}`)},sy=(e,t,n)=>{let r=e.getUint8(t),i=e.getUint8(t+1),a=e.getUint8(t+2);return n?r|i<<8|a<<16:r<<16|i<<8|a},sv=(e,t,n,r)=>{n>>>=0,n&=0xffffff,r?(e.setUint8(t,255&n),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,255&n))},sb=(e,t)=>({async next(){let n=await e.next();return n.done?{value:void 0,done:!0}:{value:t(n.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),sx=(e,t,n)=>Math.max(t,Math.min(n,e)),sw=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},sC=(e,t)=>Math.floor(e/t)*t,sS=/^[a-z]{3}$/,sk=1e6*(1+Number.EPSILON),s_=(e,t)=>{let n={...e,...t};if(e.headers||t.headers){let r=e.headers?sE(e.headers):{},i=t.headers?sE(t.headers):{},a={...r};Object.entries(i).forEach(([e,t])=>{let n=Object.keys(a).find(t=>t.toLowerCase()===e.toLowerCase());n&&delete a[n],a[e]=t}),n.headers=a}return n},sE=e=>{if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}if(Array.isArray(e)){let t={};return e.forEach(([e,n])=>{t[e]=n}),t}return e},sT=async(e,t,n,r,i)=>{let a=0;for(;;)try{return await e(t,n)}catch(n){if(i())throw n;let e=r(++a,n,t);if(null===e)throw n;if(console.error("Retrying failed fetch. Error:",n),!Number.isFinite(e)||e<0)throw TypeError("Retry delay must be a non-negative finite number.");if(e>0&&await new Promise(t=>setTimeout(t,1e3*e)),i())throw n}};class sP{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let sO=null,sA=()=>null!==sO?sO:sO=!!("u">typeof navigator&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),sI=null,sR=()=>null!==sI?sI:sI="u">typeof navigator&&navigator.userAgent?.includes("Firefox"),sL=null,sM=()=>null!==sL?sL:sL=!!("u">typeof navigator&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),sN=null,sj=()=>{if(null!==sN)return sN;if("u"<typeof navigator)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?sN=Number(e[1]):null},sD=(e,t)=>-1!==e?e:t,sz=(e,t,n,r)=>e<=r&&n<=t,sB=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},sF=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},sH=e=>"number"==typeof e&&!Number.isNaN(e),sV=["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"];[...sV];let sU=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],s$=[{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:0x2200000,maxBitrate:18e7,level:60},{maxPictureSize:0x2200000,maxBitrate:24e7,level:61},{maxPictureSize:0x2200000,maxBitrate:48e7,level:62}],sq=".01.01.01.01.00",sW=".0.110.01.01.01.0",sG=e=>{let{codec:t,codecDescription:n,colorSpace:r,avcCodecInfo:i,hevcCodecInfo:a,vp9CodecInfo:o,av1CodecInfo:s}=e;if("avc"===t){if(oJ(null!==e.avcType),i){let t=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${e.avcType}.${ss(t)}`}if(!n||n.byteLength<4)throw TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${ss(n.subarray(1,4))}`}if("hevc"===t){let e,t,r,i,o,s;if(a)e=a.generalProfileSpace,t=a.generalProfileIdc,r=sl(a.generalProfileCompatibilityFlags),i=a.generalTierFlag,o=a.generalLevelIdc,s=[...a.generalConstraintIndicatorFlags];else{if(!n||n.byteLength<23)throw TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let a=o6(n),l=a.getUint8(1);e=l>>6&3,t=31&l,r=sl(a.getUint32(2)),i=l>>5&1,o=a.getUint8(12),s=[];for(let e=0;e<6;e++)s.push(a.getUint8(6+e))}let l="hev1.";for(l+=["","A","B","C"][e]+t,l+=".",l+=r.toString(16).toUpperCase(),l+=".",l+=0===i?"L":"H",l+=o;s.length>0&&0===s[s.length-1];)s.pop();return s.length>0&&(l+=".",l+=s.map(e=>e.toString(16).toUpperCase()).join(".")),l}if("vp8"===t)return"vp8";if("vp9"===t){if(!o){let t=e.width*e.height,n=o1(s$).level;for(let e of s$)if(t<=e.maxPictureSize){n=e.level;break}return`vp09.00.${n.toString().padStart(2,"0")}.08`}let t=o.profile.toString().padStart(2,"0"),n=o.level.toString().padStart(2,"0"),r=o.bitDepth.toString().padStart(2,"0"),i=o.chromaSubsampling.toString().padStart(2,"0"),a=o.colourPrimaries.toString().padStart(2,"0"),s=o.transferCharacteristics.toString().padStart(2,"0"),l=o.matrixCoefficients.toString().padStart(2,"0"),c=o.videoFullRangeFlag.toString().padStart(2,"0"),u=`vp09.${t}.${n}.${r}.${i}`;return(u+=`.${a}.${s}.${l}.${c}`).endsWith(sq)&&(u=u.slice(0,-sq.length)),u}if("av1"===t){if(!s){let t=e.width*e.height,n=o1(s$).level;for(let e of s$)if(t<=e.maxPictureSize){n=e.level;break}return`av01.0.${n.toString().padStart(2,"0")}M.08`}let t=s.profile,n=s.level.toString().padStart(2,"0"),i=s.tier?"H":"M",a=s.bitDepth.toString().padStart(2,"0"),o=s.monochrome?"1":"0",l=100*s.chromaSubsamplingX+10*s.chromaSubsamplingY+ +(s.chromaSubsamplingX&&s.chromaSubsamplingY?s.chromaSamplePosition:0),c=r?.primaries?o7[r.primaries]:1,u=r?.transfer?st[r.transfer]:1,d=r?.matrix?sr[r.matrix]:1,h=+!!r?.fullRange,f=`av01.${t}.${n}${i}.${a}`;return f+=`.${o}.${l.toString().padStart(3,"0")}`,f+=`.${c.toString().padStart(2,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${d.toString().padStart(2,"0")}`,(f+=`.${h}`).endsWith(sW)&&(f=f.slice(0,-sW.length)),f}throw TypeError(`Unhandled codec '${t}'.`)},sK=e=>{let{codec:t,codecDescription:n,aacCodecInfo:r}=e;if("aac"===t){if(!r)throw TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;return e=null!==r.objectType?r.objectType:sQ(n).objectType,`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";else if("ac3"===t)return"ac-3";else if("eac3"===t)return"ec-3";else if(t&&sV.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},sY=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],sX=[-1,1,2,3,4,5,6,8],sQ=e=>{if(!e||e.byteLength<2)throw TypeError("AAC description must be at least 2 bytes long.");let t=new o2(e),n=t.readBits(5);31===n&&(n=32+t.readBits(6));let r=t.readBits(4),i=null;15===r?i=t.readBits(24):r<sY.length&&(i=sY[r]);let a=t.readBits(4),o=null;return a>=1&&a<=7&&(o=sX[a]),{objectType:n,frequencyIndex:r,sampleRate:i,channelConfiguration:a,numberOfChannels:o}},sZ=/^pcm-([usf])(\d+)+(be)?$/,sJ=[48e3,44100,32e3],s0=[24e3,22050,16e3];(NK=jT||(jT={}))[NK.NON_IDR_SLICE=1]="NON_IDR_SLICE",NK[NK.SLICE_DPA=2]="SLICE_DPA",NK[NK.SLICE_DPB=3]="SLICE_DPB",NK[NK.SLICE_DPC=4]="SLICE_DPC",NK[NK.IDR=5]="IDR",NK[NK.SEI=6]="SEI",NK[NK.SPS=7]="SPS",NK[NK.PPS=8]="PPS",NK[NK.AUD=9]="AUD",NK[NK.SPS_EXT=13]="SPS_EXT",(NY=jP||(jP={}))[NY.RASL_N=8]="RASL_N",NY[NY.RASL_R=9]="RASL_R",NY[NY.BLA_W_LP=16]="BLA_W_LP",NY[NY.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",NY[NY.VPS_NUT=32]="VPS_NUT",NY[NY.SPS_NUT=33]="SPS_NUT",NY[NY.PPS_NUT=34]="PPS_NUT",NY[NY.AUD_NUT=35]="AUD_NUT",NY[NY.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",NY[NY.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT";let s1=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(-1===r||r>=e.length-2)break;let i=0;if((t=r)+3<e.length&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]?i=4:0===e[t+1]&&1===e[t+2]&&(i=3),0===i){t++;continue}-1!==n&&t>n&&(yield{offset:n,length:t-n}),t=n=t+i}-1!==n&&n<e.length&&(yield{offset:n,length:e.length-n})},s2=function*(e,t){let n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+t<=e.length;){let e;1===t?e=r.getUint8(n):2===t?e=r.getUint16(n,!1):3===t?e=sy(r,n,!1):(oJ(4===t),e=r.getUint32(n,!1)),n+=t,yield{offset:n,length:e},n+=e}},s4=(e,t)=>t.description?s2(e,(3&o8(t.description)[4])+1):s1(e),s3=e=>31&e,s8=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&0===e[r]&&0===e[r+1]&&3===e[r+2]?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)},s6=new Uint8Array([0,0,0,1]),s5=e=>{try{let t=[],n=[],r=[];for(let i of s1(e)){let a=e.subarray(i.offset,i.offset+i.length),o=s3(a[0]);o===jT.SPS?t.push(a):o===jT.PPS?n.push(a):o===jT.SPS_EXT&&r.push(a)}if(0===t.length||0===n.length)return null;let i=t[0],a=s9(i);oJ(null!==a);let o=100===a.profileIdc||110===a.profileIdc||122===a.profileIdc||144===a.profileIdc;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},s9=e=>{try{let t=new o2(s8(e));t.skipBits(1),t.skipBits(2);let n=t.readBits(5);if(7!==n)return null;let r=t.readAlignedByte(),i=t.readAlignedByte(),a=t.readAlignedByte();o4(t);let o=1,s=0,l=0,c=0;if((100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r)&&(o=o4(t),3===o&&(c=t.readBits(1)),s=o4(t),l=o4(t),t.skipBits(1),t.readBits(1))){for(let e=0;e<(3!==o?8:12);e++)if(t.readBits(1)){let n=e<6?16:64,r=8,i=8;for(let e=0;e<n;e++){if(0!==i){let e=o3(t);i=(r+e+256)%256}r=0===i?r:i}}}o4(t);let u=o4(t);if(0===u)o4(t);else if(1===u){t.skipBits(1),o3(t),o3(t);let e=o4(t);for(let n=0;n<e;n++)o3(t)}o4(t),t.skipBits(1);let d=o4(t),h=o4(t),f=16*(d+1),p=16*(h+1),m=f,g=p,y=t.readBits(1);if(y||t.skipBits(1),t.skipBits(1),t.readBits(1)){let e,n,r=o4(t),i=o4(t),a=o4(t),s=o4(t),l=0===c?o:0;if(0===l)e=1,n=2-y;else{let t=3===o?1:2,r=1===o?2:1;e=t,n=r*(2-y)}m-=e*(r+i),g-=n*(a+s)}let v=2,b=2,x=2,w=0,C=null,S=null;if(t.readBits(1)){if(t.readBits(1)){let e=t.readBits(8);255===e&&(t.skipBits(16),t.skipBits(16))}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),w=t.readBits(1),t.readBits(1)&&(v=t.readBits(8),b=t.readBits(8),x=t.readBits(8))),t.readBits(1)&&(o4(t),o4(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let e=t.readBits(1);e&&s7(t);let n=t.readBits(1);n&&s7(t),(e||n)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),o4(t),o4(t),o4(t),o4(t),C=o4(t),S=o4(t))}if(null===C)if(oJ(null===S),(44===r||86===r||100===r||110===r||122===r||244===r)&&16&i)C=0,S=0;else{let e=sU.find(e=>e.level>=a)??o1(sU),t=Math.min(Math.floor(e.maxDpbMbs/((2-y)*(h+1)*(d+1))),16);C=t,S=t}return oJ(null!==S),{profileIdc:r,constraintFlags:i,levelIdc:a,frameMbsOnlyFlag:y,chromaFormatIdc:o,bitDepthLumaMinus8:s,bitDepthChromaMinus8:l,codedWidth:f,codedHeight:p,displayWidth:m,displayHeight:g,colourPrimaries:v,matrixCoefficients:x,transferCharacteristics:b,fullRangeFlag:w,numReorderFrames:C,maxDecFrameBuffering:S}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},s7=e=>{let t=o4(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)o4(e),o4(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},le=(e,t)=>t.description?s2(e,(3&o8(t.description)[21])+1):s1(e),lt=e=>e>>1&63,ln=e=>{try{let t=new o2(s8(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:l,general_level_idc:c}=li(t,n);o4(t);let u=o4(t),d=0;3===u&&(d=t.readBits(1));let h=o4(t),f=o4(t),p=h,m=f;if(t.readBits(1)){let e=o4(t),n=o4(t),r=o4(t),i=o4(t),a=1,o=1,s=0===d?u:0;1===s?(a=2,o=2):2===s&&(a=2,o=1),p-=(e+n)*a,m-=(r+i)*o}let g=o4(t),y=o4(t);o4(t);let v=t.readBits(1)?0:n,b=0;for(let e=v;e<=n;e++)o4(t),b=o4(t),o4(t);o4(t),o4(t),o4(t),o4(t),o4(t),o4(t),t.readBits(1)&&t.readBits(1)&&la(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),o4(t),o4(t),t.skipBits(1));let x=o4(t);if(lo(t,x),t.readBits(1)){let e=o4(t);for(let n=0;n<e;n++)o4(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let w=2,C=2,S=2,k=0,_=0;if(t.readBits(1)){let e=ll(t,n);w=e.colourPrimaries,C=e.transferCharacteristics,S=e.matrixCoefficients,k=e.fullRangeFlag,_=e.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,colourPrimaries:w,transferCharacteristics:C,matrixCoefficients:S,fullRangeFlag:k,maxDecFrameBuffering:b+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:l,generalLevelIdc:c,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:_}}catch(e){return console.error("Error parsing HEVC SPS:",e),null}},lr=e=>{try{let t=[],n=[],r=[],i=[];for(let a of s1(e)){let o=e.subarray(a.offset,a.offset+a.length),s=lt(o[0]);s===jP.VPS_NUT?t.push(o):s===jP.SPS_NUT?n.push(o):s===jP.PPS_NUT?r.push(o):(s===jP.PREFIX_SEI_NUT||s===jP.SUFFIX_SEI_NUT)&&i.push(o)}if(0===n.length||0===r.length)return null;let a=ln(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new o2(s8(e));t.skipBits(16),o4(t),o4(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),o4(t),o4(t),o3(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&o4(t),o3(t),o3(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);o=n||i?n&&!i?2:!n&&i?3:0:0}let s=[...t.length?[{arrayCompleteness:1,nalUnitType:jP.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:jP.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:jP.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:lt(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:s}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},li=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),l=[],c=[];for(let n=0;n<t;n++)l.push(e.readBits(1)),c.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)l[n]&&e.skipBits(88),c[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},la=e=>{for(let t=0;t<4;t++)for(let n=0;n<(3===t?2:6);n++)if(e.readBits(1)){let n=Math.min(64,1<<4+(t<<1));t>1&&o3(e);for(let t=0;t<n;t++)o3(e)}else o4(e)},lo=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=ls(e,r,t,n)},ls=(e,t,n,r)=>{let i=0,a=0,o=0;if(0!==t&&(a=e.readBits(1)),a){o=t===n?t-(o4(e)+1):t-1,e.readBits(1),o4(e);let a=r[o]??0;for(let t=0;t<=a;t++)e.readBits(1)||e.readBits(1);i=r[o]}else{let t=o4(e),n=o4(e);for(let n=0;n<t;n++)o4(e),e.readBits(1);for(let t=0;t<n;t++)o4(e),e.readBits(1);i=t+n}return i},ll=(e,t)=>{let n=2,r=2,i=2,a=0,o=0;return e.readBits(1)&&255===e.readBits(8)&&(e.readBits(16),e.readBits(16)),e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(o4(e),o4(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(o4(e),o4(e),o4(e),o4(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&o4(e),e.readBits(1)&&lc(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=o4(e),o4(e),o4(e),o4(e),o4(e)),{colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},lc=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=1===e.readBits(1),i=1===e.readBits(1),(r||i)&&((a=1===e.readBits(1))&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=1===e.readBits(1),n=!0;t||(n=1===e.readBits(1));let o=!1;n?o4(e):o=1===e.readBits(1);let s=1;o||(s=o4(e)+1),r&&lu(e,s,a),i&&lu(e,s,a)}},lu=(e,t,n)=>{for(let r=0;r<t;r++)o4(e),o4(e),n&&(o4(e),o4(e)),e.readBits(1)},ld=e=>{let t=new o2(e);if(2!==t.readBits(2))return null;let n=t.readBits(1),r=(t.readBits(1)<<1)+n;if(3===r&&t.skipBits(1),1===t.readBits(1)||0!==t.readBits(1)||(t.skipBits(2),4817730!==t.readBits(24)))return null;let i=8;r>=2&&(i=t.readBits(1)?12:10);let a=t.readBits(3),o=0,s=0;if(7!==a)if(s=t.readBits(1),1===r||3===r){let e=t.readBits(1),n=t.readBits(1);o=e||n?e&&!n?2:1:3,t.skipBits(1)}else o=1;else o=3,s=1;let l=(t.readBits(16)+1)*(t.readBits(16)+1),c=o1(s$).level;for(let e of s$)if(l<=e.maxPictureSize){c=e.level;break}return{profile:r,level:c,bitDepth:i,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:2===a?1:1===a?6:2,transferCharacteristics:2===a?1:1===a?6:2,matrixCoefficients:7===a?0:2===a?1:1===a?6:2}},lh=function*(e){let t=new o2(e),n=()=>{let e=0;for(let n=0;n<8;n++){let r=t.readAlignedByte();if(e|=(127&r)<<7*n,!(128&r))break;if(7===n&&128&r)return null}return e>=0x100000000-1?null:e};for(;t.getBitsLeft()>=8;){let r;t.skipBits(1);let i=t.readBits(4),a=t.readBits(1),o=t.readBits(1);if(t.skipBits(1),a&&t.skipBits(8),o){let e=n();if(null===e)return;r=e}else r=Math.floor(t.getBitsLeft()/8);oJ(t.pos%8==0),yield{type:i,data:e.subarray(t.pos/8,t.pos/8+r)},t.skipBits(8*r)}},lf=e=>{for(let{type:t,data:n}of lh(e)){if(1!==t)continue;let e=new o2(n),r=e.readBits(3);e.readBits(1);let i=e.readBits(1),a=0,o=0,s=0;if(i)a=e.readBits(5);else{if(e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.readBits(1)))return null;let t=e.readBits(1);t&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));let n=e.readBits(5);for(let r=0;r<=n;r++){e.skipBits(12);let n=e.readBits(5);if(0===r&&(a=n),n>7){let t=e.readBits(1);0===r&&(o=t)}if(t&&e.readBits(1)){let t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}e.readBits(1)&&e.skipBits(4)}}let l=e.readBits(4),c=e.readBits(4),u=l+1;e.skipBits(u);let d=c+1;e.skipBits(d);if((i?0:e.readBits(1))&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let n=e.readBits(1);(n?2:e.readBits(1))>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let h=e.readBits(1),f=8;2===r&&h?f=e.readBits(1)?12:10:r<=2&&(f=h?10:8);let p=0;1!==r&&(p=e.readBits(1));let m=1,g=1,y=0;return!p&&(0===r?(m=1,g=1):1===r?(m=0,g=0):12===f&&(m=e.readBits(1))&&(g=e.readBits(1)),m&&g&&(y=e.readBits(2))),{profile:r,level:a,tier:o,bitDepth:f,monochrome:p,chromaSubsamplingX:m,chromaSubsamplingY:g,chromaSamplePosition:y}}return null},lp=[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],lm=(e,t,n)=>{switch(e){case"avc":for(let e of s4(n,t)){let t=s3(n[e.offset]);if(t>=jT.NON_IDR_SLICE&&t<=jT.SLICE_DPC)break;if(t===jT.IDR)return"key";if(t===jT.SEI&&(!sM()||sj()>=144)){let t=s8(n.subarray(e.offset,e.offset+e.length)),r=1;do{let e=0;for(;;){let n=t[r++];if(void 0===n||(e+=n,n<255))break}let n=0;for(;;){let e=t[r++];if(void 0===e||(n+=e,e<255))break}if(6===e){let e=new o2(t);e.pos=8*r;let n=o4(e),i=e.readBits(1);if(0===n&&1===i)return"key"}r+=n}while(r<t.length-1)}}return"delta";case"hevc":for(let e of le(n,t)){let t=lt(n[e.offset]);if(t<jP.BLA_W_LP)break;if(t<=jP.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 0==(1&n[0])?"key":"delta";case"vp9":{let e=new o2(n);if(2!==e.readBits(2))return null;let t=e.readBits(1);if(3===(e.readBits(1)<<1)+t&&e.skipBits(1),e.readBits(1))return null;return 0===e.readBits(1)?"key":"delta"}case"av1":{let e=!1;for(let{type:t,data:r}of lh(n))if(1===t){let t=new o2(r);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";let t=new o2(r);if(t.readBits(1))return null;return 0===t.readBits(2)?"key":"delta"}return null}default:sg(e),oJ(!1)}};(NX=jO||(jO={}))[NX.STREAMINFO=0]="STREAMINFO",NX[NX.VORBIS_COMMENT=4]="VORBIS_COMMENT",NX[NX.PICTURE=6]="PICTURE";let lg=(e,t)=>{let n=o6(e),r=0,i=n.getUint32(r,!0);r+=4;let a=o5.decode(e.subarray(r,r+i));r+=i,i>0&&(t.raw??={},t.raw.vendor??=a);let o=n.getUint32(r,!0);r+=4;for(let i=0;i<o;i++){let i=n.getUint32(r,!0);r+=4;let a=o5.decode(e.subarray(r,r+i));r+=i;let o=a.indexOf("=");if(-1===o)continue;let s=a.slice(0,o).toUpperCase(),l=a.slice(o+1);switch(t.raw??={},t.raw[s]??=l,s){case"TITLE":t.title??=l;break;case"DESCRIPTION":t.description??=l;break;case"ARTIST":t.artist??=l;break;case"ALBUM":t.album??=l;break;case"ALBUMARTIST":t.albumArtist??=l;break;case"COMMENT":t.comment??=l;break;case"LYRICS":t.lyrics??=l;break;case"TRACKNUMBER":{let e=l.split("/"),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.trackNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??=r)}break;case"TRACKTOTAL":{let e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case"DISCNUMBER":{let e=l.split("/"),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.discNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??=r)}break;case"DISCTOTAL":{let e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case"DATE":{let e=new Date(l);Number.isNaN(e.getTime())||(t.date??=e)}break;case"GENRE":t.genre??=l;break;case"METADATA_BLOCK_PICTURE":{let e=sB(l),n=o6(e),r=n.getUint32(0,!1),i=n.getUint32(4,!1),a=String.fromCharCode(...e.subarray(8,8+i)),o=n.getUint32(8+i,!1),s=o5.decode(e.subarray(12+i,12+i+o)),c=n.getUint32(i+o+28),u=e.subarray(i+o+32,i+o+32+c);t.images??=[],t.images.push({data:u,mimeType:a,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:s||void 0})}}}},ly=[2,1,2,3,3,4,4,5],lv=e=>{if(e.length<7||11!==e[0]||119!==e[1])return null;let t=new o2(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(3===n)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return(1&o)!=0&&1!==o&&t.skipBits(2),(4&o)!=0&&t.skipBits(2),2===o&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},lb=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840];new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);let lx=[1,2,3,6],lw=e=>{let t;if(e.length<6||11!==e[0]||119!==e[1])return null;let n=new o2(e);n.skipBits(16);let r=n.readBits(2);if(n.skipBits(3),0!==r&&2!==r)return null;let i=n.readBits(11),a=n.readBits(2),o=0;3===a?(o=n.readBits(2),t=3):t=n.readBits(2);let s=n.readBits(3),l=n.readBits(1),c=n.readBits(5);if(c<11||c>16)return null;let u=lx[t];return{dataRate:Math.round((i+1)*(a<3?sJ[a]/1e3:s0[o]/1e3)/(16*u)),substreams:[{fscod:a,fscod2:o,bsid:c,bsmod:0,acmod:s,lfeon:l,numDepSub:0,chanLoc:0}]}},lC=e=>{let t=e.substreams[0];return(oJ(t),t.fscod<3)?sJ[t.fscod]:null!==t.fscod2&&t.fscod2<3?s0[t.fscod2]:null},lS=e=>{let t=e.substreams[0];oJ(t);let n=ly[t.acmod]+t.lfeon;if(t.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let r=0;r<9;r++)t.chanLoc&1<<8-r&&(n+=e[r])}return n};class lk{constructor(e){this.input=e}}let l_=[],lE=[];class lT{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new lZ;if(e<0||null!==this.fileSize&&e+t>this.fileSize)return null;let n=e+t,r=this.source._read(e,n);return r instanceof Promise?r.then(t=>t?new lP(t.bytes,t.view,t.offset,e,n):null):r?new lP(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new lZ;if(e<0)return null;if(null!==this.fileSize)return this.requestSlice(e,sx(this.fileSize-e,t,n));{let r=this.requestSlice(e,n),i=r=>{if(r)return r;let i=r=>(oJ(null!==r),this.requestSlice(e,sx(r-e,t,n))),a=this.source._retrieveSize();return a instanceof Promise?a.then(i):i(a)};return r instanceof Promise?r.then(i):i(r)}}}class lP{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(e){return new lP(e,o6(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 RangeError("Slicing outside of original slice.");return new lP(this.bytes,this.view,this.offset,e,e+t)}}let lO=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw 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.`)},lA=(e,t)=>{lO(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},lI=e=>(lO(e,1),e.view.getUint8(e.bufferPos++)),lR=(e,t)=>{lO(e,2);let n=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,n},lL=e=>{lO(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},lM=e=>{lO(e,3);let t=sy(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},lN=e=>{lO(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},lj=(e,t)=>{lO(e,4);let n=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,n},lD=e=>{lO(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},lz=e=>{lO(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},lB=e=>{lO(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},lF=(e,t)=>{let n,r;return t?(n=lj(e,!0),r=lj(e,!0)):(r=lj(e,!1),n=lj(e,!1)),0x100000000*r+n},lH=e=>0x100000000*lD(e)+lD(e),lV=e=>0x100000000*lB(e)+lD(e),lU=e=>{lO(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},l$=(e,t)=>{lO(e,t);let n="";for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n};x("foUwZ");class lq{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new lZ;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new lZ;let e=await this.getSizeOrNull();if(null===e)throw Error("Cannot determine the size of an unsized source.");return e}}class lW extends lq{constructor(e){if(!(e instanceof ArrayBuffer)&&!("u">typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=o8(e),this._view=o6(e)}_retrieveSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this.onread?.(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}}let lG=(e,t,n)=>{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{"u">typeof window&&void 0!==window.location&&(e=new URL(n instanceof Request?n.url:n,window.location.href).origin)}catch{}if(("u"<typeof navigator||"boolean"!=typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(e-2),16)};class lK extends lq{constructor(e,t={}){if("string"!=typeof e&&!(e instanceof URL)&&!("u">typeof Request&&e instanceof Request))throw TypeError("url must be a string, URL or Request.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!=typeof t.requestInit))throw TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!=typeof t.getRetryDelay)throw TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!sH(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!=typeof t.fetchFn)throw TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??lG,this._orchestrator=new lX({maxCacheSize:t.maxCacheSize??0x4000000,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:lY.network})}async _retrieveSize(){let e,t,n=new AbortController,r=await sT(this._options.fetchFn??fetch,this._url,s_(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:n.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);if(206===r.status)t=this._getTotalLengthFromRangeResponse(r),e=this._orchestrator.createWorker(0,Math.min(t,524288));else{let n=r.headers.get("Content-Length");if(n)t=Number(n),e=this._orchestrator.createWorker(0,t),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.");else throw Error(`HTTP response (status ${r.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=t,this._existingResponses.set(e,{response:r,abortController:n}),this._orchestrator.runWorker(e),t}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;;){let t=this._existingResponses.get(e);this._existingResponses.delete(e);let n=t?.abortController,r=t?.response;if(n||(n=new AbortController,r=await sT(this._options.fetchFn??fetch,this._url,s_(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed)),oJ(r),!r.ok)throw Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);if(e.currentPos>0&&206!==r.status)throw Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!r.body)throw Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let i=r.body.getReader();for(;;){let t;if(e.currentPos>=e.targetPos||e.aborted){n.abort(),e.running=!1;return}try{t=await i.read()}catch(t){if(this._disposed)throw t;let e=this._getRetryDelay(1,t,this._url);if(null!==e){console.error("Error while reading response stream. Attempting to resume.",t),await new Promise(t=>setTimeout(t,1e3*e));break}throw t}if(e.aborted)continue;let{done:r,value:a}=t;if(r){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+a.length),this._orchestrator.supplyWorkerData(e,a)}}}_getTotalLengthFromRangeResponse(e){let t=e.headers.get("Content-Range");if(t){let e=/\/(\d+)/.exec(t);if(e)return Number(e[1])}let n=e.headers.get("Content-Length");if(n)return Number(n);throw Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}}let lY={network:(e,t,n)=>{for(let r of(e=Math.max(0,65536*Math.floor((e-65536)/65536)),n))if(sz(e,t,Math.max((r.startPos+r.targetPos)/2,r.targetPos-8388608),r.targetPos)){let e=r.targetPos-r.startPos,n=8388608*Math.ceil((e+1)/8388608),i=Math.min(2**Math.ceil(Math.log2(e+1)),n);t=Math.max(t,r.startPos+i)}return t=Math.max(t,e+524288),{start:e,end:t}}};class lX{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){oJ(null!==this.fileSize);let n=this.options.prefetchProfile(e,t,this.workers),r=Math.max(n.start,0),i=Math.min(n.end,this.fileSize);oJ(r<=e&&t<=i);let a=null,o=su(this.cache,e,e=>e.start),s=-1!==o?this.cache[o]:null;s&&s.start<=e&&t<=s.end&&(s.age=this.nextAge++,a={bytes:s.bytes,view:s.view,offset:s.start});let l=su(this.cache,r,e=>e.start),c=a?null:new Uint8Array(t-e),u=0,d=r,h=[];if(-1!==l){for(let n=l;n<this.cache.length;n++){let a=this.cache[n];if(a.start>=i)break;if(a.end<=r)continue;let o=Math.max(r,a.start),s=Math.min(i,a.end);if(oJ(o<=s),d<o&&h.push({start:d,end:o}),d=s,c){let n=Math.max(e,a.start),r=Math.min(t,a.end);if(n<r){let t=n-e;c.set(a.bytes.subarray(n-a.start,r-a.start),t),t===u&&(u=r-e)}}a.age=this.nextAge++}d<i&&h.push({start:d,end:i})}else h.push({start:r,end:i});if(c&&u>=c.length&&(a={bytes:c,view:o6(c),offset:e}),0===h.length)return oJ(a),a;let{promise:f,resolve:p,reject:m}=sh(),g=[];for(let n of h){let r=Math.max(e,n.start),i=Math.min(t,n.end);r===n.start&&i===n.end?g.push(n):r<i&&g.push({start:r,end:i})}for(let t of h){let n=c&&{start:e,bytes:c,holes:g,resolve:p,reject:m},r=!1;for(let e of this.workers)if(sz(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end),r=!0,n&&!e.pendingSlices.includes(n)&&e.pendingSlices.push(n),e.running||this.runWorker(e);break}if(!r){let e=this.createWorker(t.start,t.end);n&&(e.pendingSlices=[n]),this.runWorker(e)}}return a||(oJ(c),a=f.then(t=>({bytes:t,view:o6(t),offset:e}))),a}createWorker(e,t){let n={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(n);this.workers.length>this.options.maxWorkerCount;){let e=0,t=this.workers[0];for(let n=1;n<this.workers.length;n++){let r=this.workers[n];r.age<t.age&&(e=n,t=r)}if(t.running&&t.pendingSlices.length>0)break;t.aborted=!0,this.workers.splice(e,1)}return n}runWorker(e){oJ(!e.running),oJ(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)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){oJ(!e.aborted);let n=e.currentPos,r=n+t.length;this.insertIntoCache({start:n,end:r,bytes:t,view:o6(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let i=0;i<e.pendingSlices.length;i++){let a=e.pendingSlices[i],o=Math.max(n,a.start),s=Math.min(r,a.start+a.bytes.length);o<s&&a.bytes.set(t.subarray(o-n,s-n),o-a.start);for(let e=0;e<a.holes.length;e++){let t=a.holes[e];n<=t.start&&r>t.start&&(t.start=r),t.end<=t.start&&(a.holes.splice(e,1),e--)}0===a.holes.length&&(a.resolve(a.bytes),e.pendingSlices.splice(i,1),i--)}for(let t=0;t<this.workers.length;t++){let i=this.workers[t];e!==i&&!i.running&&sz(n,r,i.currentPos,i.targetPos)&&(this.workers.splice(t,1),t--)}}forgetWorker(e){let t=this.workers.indexOf(e);oJ(-1!==t),this.workers.splice(t,1)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=su(this.cache,e.start,e=>e.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let r=new Uint8Array(e.end-n.start);r.set(n.bytes,0),r.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=r,n.view=o6(r),n.end=e.end,t--,e=n}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 n=t+1;n<this.cache.length;n++){let t=this.cache[n];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(n,1),this.currentCacheSize-=t.bytes.length,n--;continue}let r=new Uint8Array(t.end-e.start);r.set(e.bytes,0),r.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=r,e.view=o6(r),e.end=t.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let n=1;n<this.cache.length;n++){let r=this.cache[n];r.age<t.age&&(e=n,t=r)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}sF();class lQ{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||"object"!=typeof e)throw TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof uB)))throw TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof lq))throw TypeError("options.source must be a Source.");if(e.source._disposed)throw Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new lT(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{for(let e of(this._reader.fileSize=await this._source.getSizeOrNull(),this._formats))if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),oJ(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getFirstTimestamp(){let e=await this.getTracks();return 0===e.length?0:Math.min(...await Promise.all(e.map(e=>e.getFirstTimestamp())))}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 lZ extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}let lJ=new Uint8Array(0);class l0{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===lJ&&void 0===a)throw Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===a&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw TypeError("duration must be a non-negative number.");if(!Number.isFinite(i))throw TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw TypeError("byteLength must be a non-negative integer.");if(void 0!==o&&("object"!=typeof o||!o))throw TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===lJ}get microsecondTimestamp(){return Math.trunc(sk*this.timestamp)}get microsecondDuration(){return Math.trunc(sk*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if("u"<typeof EncodedVideoChunk)throw 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 TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if("u"<typeof EncodedVideoChunk)throw 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 TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("u"<typeof EncodedAudioChunk)throw 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 TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let n=new Uint8Array(e.byteLength);return e.copyTo(n),new l0(n,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 TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&"key"!==e.type&&"delta"!==e.type)throw TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&("object"!=typeof e.sideData||null===e.sideData))throw TypeError("options.sideData, when provided, must be an object.");return new l0(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}sF();let l1=-1/0,l2=-1/0,l4=null;"u">typeof FinalizationRegistry&&(l4=new FinalizationRegistry(e=>{let t=Date.now();"video"===e.type?(t-l1>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),l1=t),"u">typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-l2>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),l2=t),"u">typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));let l3=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],l8=new Set(l3);class l6{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(sk*this.timestamp)}get microsecondDuration(){return Math.trunc(sk*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||"u">typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!=typeof t)throw TypeError("init must be an object.");if(void 0===t.format||!l8.has(t.format))throw TypeError("init.format must be one of: "+l3.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw TypeError("init.codedHeight must be a positive integer.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=o8(e).slice(),this._layout=t.layout??cn(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new l5(t.colorSpace)}else if("u">typeof VideoFrame&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new l5(e.colorSpace)}else if("u">typeof HTMLImageElement&&e instanceof HTMLImageElement||"u">typeof SVGImageElement&&e instanceof SVGImageElement||"u">typeof ImageBitmap&&e instanceof ImageBitmap||"u">typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"u">typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"u">typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!=typeof t)throw TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if("u">typeof VideoFrame)return new l6(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*sk),duration:Math.trunc((t.duration??0)*sk)||void 0}),t);let n=0,r=0;if("naturalWidth"in e?(n=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,r=e.videoHeight):"width"in e&&(n=Number(e.width),r=Number(e.height)),!n||!r)throw TypeError("Could not determine dimensions.");let i=new OffscreenCanvas(n,r),a=i.getContext("2d",{alpha:sR(),willReadFrequently:!0});oJ(a),a.drawImage(e,0,0),this._data=i,this._layout=null,this.format="RGBX",this.codedWidth=n,this.codedHeight=r,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new l5({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");l4?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw Error("VideoSample is closed.");return(oJ(null!==this._data),l9(this._data))?new l6(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(oJ(this._layout),new l6(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})):new l6(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||(l4?.unregister(this),l9(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(ct(e),this._closed)throw Error("VideoSample is closed.");if(null===this.format)throw Error("Cannot get allocation size when format is null. Sorry!");if(oJ(null!==this._data),!l9(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let t=this.toVideoFrame(),n=t.allocationSize(e);return t.close(),n}return l9(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!sa(e))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(ct(t),this._closed)throw Error("VideoSample is closed.");if(null===this.format)throw Error("Cannot copy video sample data when format is null. Sorry!");if(oJ(null!==this._data),!l9(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){let n=this.toVideoFrame(),r=await n.copyTo(e,t);return n.close(),r}if(l9(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array)return oJ(this._layout),o8(e).set(this._data),this._layout;{let t=this._data.getContext("2d");oJ(t);let n=t.getImageData(0,0,this.codedWidth,this.codedHeight);return o8(e).set(n.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw Error("VideoSample is closed.");return(oJ(null!==this._data),l9(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,n,r,i,a,o,s,l){let c=0,u=0,d=this.displayWidth,h=this.displayHeight,f=0,p=0,m=this.displayWidth,g=this.displayHeight;if(void 0!==a?(c=t,u=n,d=r,h=i,f=a,p=o,void 0!==s?(m=s,g=l):(m=d,g=h)):(f=t,p=n,void 0!==r&&(m=r,g=i)),!("u">typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"u">typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw TypeError("sx must be a number.");if(!Number.isFinite(u))throw TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw TypeError("dx must be a number.");if(!Number.isFinite(p))throw TypeError("dy must be a number.");if(!Number.isFinite(m)||m<0)throw TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw TypeError("dHeight must be a non-negative number.");if(this._closed)throw Error("VideoSample is closed.");({sx:c,sy:u,sWidth:d,sHeight:h}=this._rotateSourceRegion(c,u,d,h,this.rotation));let y=this.toCanvasImageSource();e.save();let v=f+m/2,b=p+g/2;e.translate(v,b),e.rotate(this.rotation*Math.PI/180);let x=this.rotation%180==0?1:m/g;e.scale(1/x,x),e.drawImage(y,c,u,d,h,-m/2,-g/2,m,g),e.restore()}drawWithFit(e,t){let n,r,i,a;if(!("u">typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"u">typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&ce(t.crop,"options.");let o=e.canvas.width,s=e.canvas.height,l=t.rotation??this.rotation,[c,u]=l%180==0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];t.crop&&l7(t.crop,c,u);let{sx:d,sy:h,sWidth:f,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??c,t.crop?.height??u,l);if("fill"===t.fit)n=0,r=0,i=o,a=s;else{let[e,l]=t.crop?[t.crop.width,t.crop.height]:[c,u],d="contain"===t.fit?Math.min(o/e,s/l):Math.max(o/e,s/l);i=e*d,a=l*d,n=(o-i)/2,r=(s-a)/2}e.save();let m=l%180==0?1:i/a;e.translate(o/2,s/2),e.rotate(l*Math.PI/180),e.scale(1/m,m),e.translate(-o/2,-s/2),e.drawImage(this.toCanvasImageSource(),d,h,f,p,n,r,i,a),e.restore()}_rotateSourceRegion(e,t,n,r,i){return 90===i?[e,t,n,r]=[t,this.codedHeight-e-n,r,n]:180===i?[e,t]=[this.codedWidth-e-n,this.codedHeight-t-r]:270===i&&([e,t,n,r]=[this.codedWidth-t-r,e,r,n]),{sx:e,sy:t,sWidth:n,sHeight:r}}toCanvasImageSource(){if(this._closed)throw Error("VideoSample is closed.");if(oJ(null!==this._data),!(this._data instanceof Uint8Array))return this._data;{let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}}setRotation(e){if(![0,90,180,270].includes(e))throw TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}class l5{constructor(e){this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}let l9=e=>"u">typeof VideoFrame&&e instanceof VideoFrame,l7=(e,t,n)=>{e.left=Math.min(e.left,t),e.top=Math.min(e.top,n),e.width=Math.min(e.width,t-e.left),e.height=Math.min(e.height,n-e.top),oJ(e.width>=0),oJ(e.height>=0)},ce=(e,t)=>{if(!e||"object"!=typeof e)throw TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(e.left)||e.left<0)throw TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(e.top)||e.top<0)throw TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(e.width)||e.width<0)throw TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(e.height)||e.height<0)throw TypeError(t+"crop.height must be a non-negative integer.")},ct=e=>{if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.colorSpace&&!["display-p3","srgb"].includes(e.colorSpace))throw TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(void 0!==e.format&&"string"!=typeof e.format)throw TypeError("options.format, when provided, must be a string.");if(void 0!==e.layout){if(!Array.isArray(e.layout))throw TypeError("options.layout, when provided, must be an array.");for(let t of e.layout){if(!t||"object"!=typeof t)throw TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==e.rect){if(!e.rect||"object"!=typeof e.rect)throw TypeError("options.rect, when provided, must be an object.");if(void 0!==e.rect.x&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==e.rect.y&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==e.rect.width&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==e.rect.height&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw TypeError("options.rect.height, when provided, must be a non-negative integer.")}},cn=(e,t,n)=>{let r=cr(e),i=[],a=0;for(let e of r){let r=Math.ceil(t/e.widthDivisor),o=Math.ceil(n/e.heightDivisor),s=r*e.sampleBytes,l=s*o;i.push({offset:a,stride:s}),a+=l}return i},cr=e=>{let t=(e,t,n,r,i)=>{let a=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:n,heightDivisor:r},{sampleBytes:t,widthDivisor:n,heightDivisor:r}];return i&&a.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),a};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:sg(e),oJ(!1)}},ci=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class ca{get microsecondTimestamp(){return Math.trunc(sk*this.timestamp)}get microsecondDuration(){return Math.trunc(sk*this.duration)}constructor(e){if(this._closed=!1,cu(e)){if(null===e.format)throw 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{let t;if(!e||"object"!=typeof e)throw TypeError("Invalid AudioDataInit: must be an object.");if(!ci.has(e.format))throw TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw TypeError("init.timestamp must be a number.");let n=e.data.byteLength/(co(e.format)*e.numberOfChannels);if(!Number.isInteger(n))throw TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");if(this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=n,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=n/e.sampleRate,e.data instanceof ArrayBuffer)t=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))t=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw TypeError("Invalid AudioDataInit: data is not a BufferSource.");let r=this.numberOfFrames*this.numberOfChannels*co(this.format);if(t.byteLength<r)throw TypeError("Invalid AudioDataInit: insufficient data size.");this._data=t}l4?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if(void 0!==e.format&&!ci.has(e.format))throw TypeError("Invalid format.");if(void 0!==e.frameOffset&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if(void 0!==e.frameCount&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw RangeError("frameOffset out of range");let r=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-n;if(r>this.numberOfFrames-n)throw RangeError("frameCount out of range");let i=co(t),a=cs(t);if(a&&e.planeIndex>=this.numberOfChannels||!a&&0!==e.planeIndex)throw RangeError("planeIndex out of range");return(a?r:r*this.numberOfChannels)*i}copyTo(e,t){if(!sa(e))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if(void 0!==t.format&&!ci.has(t.format))throw TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let{planeIndex:n,format:r,frameCount:i,frameOffset:a}=t,o=this.format,s=r??this.format;if(!s)throw Error("Destination format not determined");let l=this.numberOfFrames,c=this.numberOfChannels,u=a??0;if(u>=l)throw RangeError("frameOffset out of range");let d=void 0!==i?i:l-u;if(d>l-u)throw RangeError("frameCount out of range");let h=co(s),f=cs(s);if(f&&n>=c||!f&&0!==n)throw RangeError("planeIndex out of range");let p=f?d:d*c;if(e.byteLength<p*h)throw RangeError("Destination buffer is too small");let m=o6(e),g=cc(s);if(cu(this._data))sA()&&c>2&&s!==o?cd(this._data,m,o,s,c,n,u,d):this._data.copyTo(e,{planeIndex:n,frameOffset:u,frameCount:d,format:s});else{let e=o6(this._data),t=cl(o),r=co(o),i=cs(o);for(let a=0;a<d;a++)if(f)g(m,a*h,t(e,i?(n*l+(a+u))*r:((a+u)*c+n)*r));else for(let n=0;n<c;n++)g(m,(a*c+n)*h,t(e,i?(n*l+(a+u))*r:((a+u)*c+n)*r))}}clone(){if(this._closed)throw Error("AudioSample is closed.");if(!cu(this._data))return new ca({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data});{let e=new ca(this._data.clone());return e.setTimestamp(this.timestamp),e}}close(){this._closed||(l4?.unregister(this),cu(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw Error("AudioSample is closed.");if(!cu(this._data))return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()});if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(cs(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}{let 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})}}toAudioBuffer(){if(this._closed)throw Error("AudioSample is closed.");let 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 n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let n=e.numberOfChannels,r=e.sampleRate,i=e.length,a=Math.floor(24e4/n),o=0,s=i;for(;s>0;){let i=Math.min(a,s),l=new Float32Array(n*i);for(let t=0;t<n;t++)e.copyFromChannel(l.subarray(t*i,(t+1)*i),t,o);yield new ca({format:"f32-planar",sampleRate:r,numberOfFrames:i,numberOfChannels:n,timestamp:t+o/r,data:l}),o+=i,s-=i}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let n=e.numberOfChannels,r=e.sampleRate,i=e.length,a=Math.floor(24e4/n),o=0,s=i,l=[];for(;s>0;){let i=Math.min(a,s),c=new Float32Array(n*i);for(let t=0;t<n;t++)e.copyFromChannel(c.subarray(t*i,(t+1)*i),t,o);let u=new ca({format:"f32-planar",sampleRate:r,numberOfFrames:i,numberOfChannels:n,timestamp:t+o/r,data:c});l.push(u),o+=i,s-=i}return l}}let co=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 Error("Unknown AudioSampleFormat")}},cs=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},cl=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)/0x80000000;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},cc=e=>{switch(e){case"u8":case"u8-planar":return(e,t,n)=>e.setUint8(t,sx((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,n)=>e.setInt16(t,sx(Math.round(32767*n),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,n)=>e.setInt32(t,sx(Math.round(0x7fffffff*n),-0x80000000,0x7fffffff),!0);case"f32":case"f32-planar":return(e,t,n)=>e.setFloat32(t,n,!0)}},cu=e=>"u">typeof AudioData&&e instanceof AudioData,cd=(e,t,n,r,i,a,o,s)=>{let l=cl(n),c=cc(r),u=co(n),d=co(r),h=cs(n);if(cs(r))if(h){let r=new ArrayBuffer(s*u),i=o6(r);e.copyTo(r,{planeIndex:a,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;c(t,e*d,l(i,n))}}else{let r=new ArrayBuffer(s*i*u),h=o6(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=(e*i+a)*u;c(t,e*d,l(h,n))}}else if(h){let r=new ArrayBuffer(s*u),a=o6(r);for(let h=0;h<i;h++){e.copyTo(r,{planeIndex:h,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;c(t,(e*i+h)*d,l(a,n))}}}else{let r=new ArrayBuffer(s*i*u),a=o6(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++)for(let n=0;n<i;n++){let r=e*i+n,o=r*u;c(t,r*d,l(a,o))}}},ch=e=>{if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.metadataOnly&&"boolean"!=typeof e.metadataOnly)throw TypeError("options.metadataOnly, when defined, must be a boolean.");if(void 0!==e.verifyKeyPackets&&"boolean"!=typeof e.verifyKeyPackets)throw TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},cf=e=>{if(!sH(e))throw TypeError("timestamp must be a number.")},cp=(e,t,n)=>n.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;let n=await e.determinePacketType(t);return n&&(t.type=n),t}):t;class cm{constructor(e){if(!(e instanceof cS))throw TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(ch(e),this._track.input._disposed)throw new lZ;return cp(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(cf(e),ch(t),this._track.input._disposed)throw new lZ;return cp(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof l0))throw TypeError("packet must be an EncodedPacket.");if(ch(t),this._track.input._disposed)throw new lZ;return cp(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(cf(e),ch(t),this._track.input._disposed)throw new lZ;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(oJ("key"===n.type),"delta"===await this._track.determinePacketType(n))?this.getKeyPacket(n.timestamp-1/this._track.timeResolution,t):n}async getNextKeyPacket(e,t={}){if(!(e instanceof l0))throw TypeError("packet must be an EncodedPacket.");if(ch(t),this._track.input._disposed)throw new lZ;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(oJ("key"===n.type),"delta"===await this._track.determinePacketType(n))?this.getNextKeyPacket(n,t):n}packets(e,t,n={}){if(void 0!==e&&!(e instanceof l0))throw TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!n?.metadataOnly)throw TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof l0))throw TypeError("endPacket must be an EncodedPacket.");if(ch(n),this._track.input._disposed)throw new lZ;let r=[],{promise:i,resolve:a}=sh(),{promise:o,resolve:s}=sh(),l=!1,c=!1,u=null,d=[],h=()=>Math.max(2,d.length);(async()=>{let u=e??await this.getFirstPacket(n);for(;u&&!c&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(r.length>h()){({promise:o,resolve:s}=sh()),await o;continue}r.push(u),a(),({promise:i,resolve:a}=sh()),u=await this.getNextPacket(u,n)}l=!0,a()})().catch(e=>{u||(u=e,a())});let f=this._track;return{async next(){for(;;)if(f.input._disposed)throw new lZ;else if(c)return{value:void 0,done:!0};else if(u)throw u;else if(r.length>0){let e=r.shift(),t=performance.now();for(d.push(t);d.length>0&&t-d[0]>=1e3;)d.shift();return s(),{value:e,done:!1}}else{if(l)return{value:void 0,done:!0};await i}},return:async()=>(c=!0,s(),a(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class cg{constructor(e,t){this.onSample=e,this.onError=t}}class cy{mediaSamplesInRange(e=0,t=1/0){cf(e),cf(t);let n=[],r=!1,i=null,{promise:a,resolve:o}=sh(),{promise:s,resolve:l}=sh(),c=!1,u=!1,d=!1,h=null;(async()=>{let f=await this._createDecoder(s=>{(l(),s.timestamp>=t&&(u=!0),u)?s.close():(i&&(s.timestamp>e?(n.push(i),r=!0):i.close()),s.timestamp>=e&&(n.push(s),r=!0),i=r?null:s,n.length>0&&(o(),{promise:a,resolve:o}=sh()))},e=>{h||(h=e,o())}),p=this._createPacketSink(),m=await p.getKeyPacket(e,{verifyKeyPackets:!0})??await p.getFirstPacket(),g=m,y=p.packets(m??void 0,void 0);for(await y.next();g&&!u&&!this._track.input._disposed;){let e=cv(n.length);if(n.length+f.getDecodeQueueSize()>e){({promise:s,resolve:l}=sh()),await s;continue}f.decode(g);let t=await y.next();if(t.done)break;g=t.value}await y.return(),d||this._track.input._disposed||await f.flush(),f.close(),!r&&i&&n.push(i),c=!0,o()})().catch(e=>{h||(h=e,o())});let f=this._track,p=()=>{for(let e of(i?.close(),n))e.close()};return{async next(){for(;;)if(f.input._disposed)throw p(),new lZ;else if(d)return{value:void 0,done:!0};else if(h)throw p(),h;else if(n.length>0){let e=n.shift();return l(),{value:e,done:!1}}else{if(c)return{value:void 0,done:!0};await a}},return:async()=>(d=!0,u=!0,l(),o(),p(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError("Argument must be an iterable or async iterable.");let t=sm(e),n=[],r=[],{promise:i,resolve:a}=sh(),{promise:o,resolve:s}=sh(),l=!1,c=!1,u=null,d=e=>{r.push(e),a(),{promise:i,resolve:a}=sh()};(async()=>{let e=await this._createDecoder(e=>{if(s(),c)return void e.close();let t=0;for(;n.length>0&&e.timestamp-n[0]>-1e-10;)t++,n.shift();if(t>0)for(let n=0;n<t;n++)d(n<t-1?e.clone():e);else e.close()},e=>{u||(u=e,a())}),i=this._createPacketSink(),h=null,f=null,p=-1,m=async()=>{oJ(f);let t=f;for(e.decode(t);t.sequenceNumber<p;){let n=cv(r.length);for(;r.length+e.getDecodeQueueSize()>n&&!c;)({promise:o,resolve:s}=sh()),await o;if(c)break;let a=await i.getNextPacket(t);oJ(a),e.decode(a),t=a}p=-1},g=async()=>{await e.flush();for(let e=0;e<n.length;e++)d(null);n.length=0};for await(let e of t){if(cf(e),c||this._track.input._disposed)break;let t=await i.getPacket(e),r=t&&await i.getKeyPacket(e,{verifyKeyPackets:!0});if(!r){-1!==p&&(await m(),await g()),d(null),h=null;continue}h&&(r.sequenceNumber!==f.sequenceNumber||t.timestamp<h.timestamp)&&(await m(),await g()),n.push(t.timestamp),p=Math.max(t.sequenceNumber,p),h=t,f=r}c||this._track.input._disposed||(-1!==p&&await m(),await g()),e.close(),l=!0,a()})().catch(e=>{u||(u=e,a())});let h=this._track,f=()=>{for(let e of r)e?.close()};return{async next(){for(;;)if(h.input._disposed)throw f(),new lZ;else if(c)return{value:void 0,done:!0};else if(u)throw f(),u;else if(r.length>0){let e=r.shift();return oJ(void 0!==e),s(),{value:e,done:!1}}else{if(l)return{value:void 0,done:!0};await i}},return:async()=>(c=!0,s(),a(),f(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}let cv=e=>0===e?40:8;class cb extends cg{constructor(e,t,n,r,i,a){super(e,t),this.codec=n,this.decoderConfig=r,this.rotation=i,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new sP,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;let o=l_.find(e=>e.supports(n,r));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof l6))throw TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let e=e=>{if(this.alphaQueue.length>0){let t=this.alphaQueue.shift();oJ(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===n&&this.decoderConfig.description&&sM()){let e=(e=>{try{let t=o6(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=t.getUint8(n++),o=t.getUint8(n++),s=3&t.getUint8(n++),l=31&t.getUint8(n++),c=[];for(let r=0;r<l;r++){let r=t.getUint16(n,!1);n+=2,c.push(e.subarray(n,n+r)),n+=r}let u=t.getUint8(n++),d=[];for(let r=0;r<u;r++){let r=t.getUint16(n,!1);n+=2,d.push(e.subarray(n,n+r)),n+=r}let h={configurationVersion:r,avcProfileIndication:i,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:s,sequenceParameterSets:c,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===i||110===i||122===i||144===i)&&n+4<=e.length){let r=3&t.getUint8(n++),i=7&t.getUint8(n++),a=7&t.getUint8(n++),o=t.getUint8(n++);h.chromaFormat=r,h.bitDepthLumaMinus8=i,h.bitDepthChromaMinus8=a;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}h.sequenceParameterSetExt=s}return h}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}})(o8(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=s9(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let t=Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(oJ(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(oJ(this.decoder),sA()||sd(this.inputTimestamps,e.timestamp,e=>e),sM()&&0===this.currentPacketIndex&&"avc"===this.codec){let t=[];for(let n of s4(e.data,this.decoderConfig)){let r=s3(e.data[n.offset]);r>=20&&r<=31||t.push(e.data.subarray(n.offset,n.offset+n.length))}e=new l0(((e,t)=>{if(t.description)return((e,t)=>{let n=new Uint8Array(e.reduce((e,n)=>e+t+n.byteLength,0)),r=0;for(let i of e){let e=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(t){case 1:e.setUint8(r,i.byteLength);break;case 2:e.setUint16(r,i.byteLength,!1);break;case 3:sv(e,r,i.byteLength,!1);break;case 4:e.setUint32(r,i.byteLength,!1)}r+=t,n.set(i,r),r+=i.byteLength}return n})(e,(3&o8(t.description)[4])+1);let n=new Uint8Array(e.reduce((e,t)=>e+s6.byteLength+t.byteLength,0)),r=0;for(let t of e)n.set(s6,r),r+=s6.byteLength,n.set(t,r),r+=t.byteLength;return n})(t,this.decoderConfig),e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed)return void this.pushNullAlphaFrame();if(!this.merger)try{this.merger=new cx}catch(t){console.error("Due to an error, only color data will be decoded.",t),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let t=this.colorQueue.shift();oJ(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){let e=this.colorQueue.shift();oJ(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)},t=Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=lm(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){for(let t of le(e,this.decoderConfig)){let n=lt(e[t.offset]);if(n===jP.RASL_N||n===jP.RASL_R)return!0}return!1}sampleHandler(e){if(sA()){if(this.sampleQueue.length>0&&e.timestamp>=o1(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}sd(this.sampleQueue,e,e=>e.timestamp)}else{let t=this.inputTimestamps.shift();oJ(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){let t=new l6(e);this.sampleHandler(t);return}oJ(this.merger),this.merger.update(e,t),e.close(),t.close();let n=new l6(new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}));this.sampleHandler(n)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(oJ(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),sA()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){for(let e of(this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(oJ(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()),this.sampleQueue))e.close();this.sampleQueue.length=0}}class cx{constructor(){"u">typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw 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(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
183
|
+
`,oO=["bold","color","font","italic","size","strike","underline","indent","list","direction"],oA=e=>{oO=e},oI=e=>new(m(aP))(e,{toolbar:!1,keyboard:!1,clipboard:{matchVisual:!1},formats:oO}),oR=(e,t)=>{var n=e.clipboard.convert("<div class='ql-editor' style='outline: none;'>"+t+"<p><br></p></div>");e.setContents(n),e.history.clear()},oL=({html:e,onBlur:t,onChange:n,element:r,clickCoords:i})=>{let a=m(S).useRef(null);m(S).useEffect(()=>{if(!a.current)return;let r=oI(a.current);E.runInAction(()=>{oT.editor.instance=r}),window.__polotnoQuill=r,r.on("text-change",()=>{r.getSelection()&&E.runInAction(()=>{oT.currentFormat=r.getFormat(r.getSelection())}),setTimeout(()=>{let e=a.current?.childNodes[0];e&&n(oE(e.innerHTML))},10)}),oR(r,e),i?function(e,t){if(!e||!t)return;let{x:n,y:r}=t;try{let t=null;if(document.caretRangeFromPoint)t=document.caretRangeFromPoint(n,r);else if(document.caretPositionFromPoint){let e=document.caretPositionFromPoint(n,r);e&&(t=document.createRange()).setStart(e.offsetNode,e.offset)}if(t){let n=m(aP).find(t.startContainer,!0);if(n){let r=n.offset(e.scroll)+t.startOffset;e.setSelection(r,0,"api");return}}}catch(e){}e.setSelection(0,0,"api")}(r,i):r.setSelection(0,0,"api"),r.on("selection-change",(e,t,n)=>{e&&E.runInAction(()=>{oT.currentFormat=r.getFormat(r.getSelection())})}),a.current.childNodes[0].addEventListener("blur",e=>{var n;let r=e.relatedTarget;r?.classList.contains("ql-clipboard")||(n=r)&&n.closest(".sketch-picker")||t()});let o=a.current.childNodes[0],s=e=>{let t=r.getSelection();if(!t||0===t.length)return;let n=r.getText(t.index,t.length).replace(/\n$/,""),i=window.getSelection(),a="";if(i&&i.rangeCount>0){let e=i.getRangeAt(0),t=document.createElement("div");t.appendChild(e.cloneContents()),a=t.innerHTML}if(e.clipboardData?.setData("text/plain",n),a){let t='<div style="white-space: pre-wrap; word-wrap: break-word;">'+a+"</div>";e.clipboardData?.setData("text/html",'<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e'+t+"\x3c!--EndFragment--\x3e</body></html>")}e.preventDefault()},l=e=>{s(e);let t=r.getSelection();t&&t.length>0&&r.deleteText(t.index,t.length)};return o.addEventListener("copy",s),o.addEventListener("cut",l),()=>{o.removeEventListener("copy",s),o.removeEventListener("cut",l),E.runInAction(()=>{oT.editor.instance=null,oT.currentFormat={}}),delete window.__polotnoQuill}},[]),m(S).useEffect(()=>(0,E.reaction)(()=>r.text,()=>{let t=oT.editor.instance;if(!t)return;let n=t.getSelection(),i=a.current?.childNodes?.[0];oE(i?.innerHTML||"")!==r.text&&(oR(t,e),n&&(t.setSelection(n.index,n.length),E.runInAction(()=>{oT.currentFormat=t.getFormat(t.getSelection())})))},{fireImmediately:!0}),[]),m(S).useEffect(()=>{window.addEventListener("blur",t);let e=e=>{a.current?.contains(e.target)||t()};return window.addEventListener("touchstart",e),()=>{window.removeEventListener("blur",t),window.removeEventListener("touchstart",e)}},[]);let o={color:r.fill};r.fill.indexOf("gradient")>=0&&(o.backgroundColor=r.fill,o.backgroundImage=r.fill,o.backgroundSize="100% 100%",o.backgroundRepeat="repeat",o.webkitBackgroundClip="text",o.MozBackgroundClip="text",o.WebkitTextFillColor="transparent",o.MozTextFillColor="transparent");let s=iZ(r);return(0,C.jsx)(oP,{ref:a,style:{...o,fontSize:r.fontSize,fontWeight:r.fontWeight,textTransform:r.textTransform,width:r.a.width,fontFamily:'"'+r.fontFamily+'"',lineHeight:r.lineHeight,letterSpacing:r.letterSpacing*r.fontSize+"px",textAlign:r.align,opacity:Math.max(r.a.opacity,.2),textShadow:r.shadowEnabled?`${r.shadowOffsetX}px ${r.shadowOffsetY}px ${r.shadowBlur}px ${o_(r.shadowColor,r.shadowOpacity??1)}`:void 0,caretColor:s},dir:iH(iz(r.text))})},oM=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),oN=j(({element:e,store:t})=>{let n=m(S).useRef(null),[r,i]=m(S).useState(),[a,o]=m(S).useState(!1),[s,l]=m(S).useState(!1),c=m(S).useRef(e.height),u=t.selectedShapes.indexOf(e)>=0&&e.selectable,d=i3(u),h=e.fontSize/3,{textVerticalResizeEnabled:f}=iS,p=iS.autoDeleteEmptyText,g=i3(e.fontFamily),[y]=i2(t,e.fontFamily,e.fontStyle,e.fontWeight),v=e._editModeEnabled;r0(n);let b=y?e.fontFamily:g!==e.fontFamily?g:"Arial",x=rQ(e).fill,w=i$(e,{fontFamily:b,color:x}),k=i$(e,{fontFamily:b,color:x,forEditor:!0}),_=m(S).useRef([]),[,T]=m(S).useReducer(e=>e+1,0);m(S).useEffect(()=>{let e=_.current;e.length>0&&(_.current=[],e.forEach(e=>e()))});let{width:P,height:O}=m(S).useMemo(()=>od(w),[w,e.width,y]);m(S).useEffect(()=>{if(!y)return;let n=(n,r,i,a)=>{let o=r5(`text ${e.id}`),s=()=>{t.history.ignore(n,r,i).then(()=>{_.current.push(o),T()})};a?queueMicrotask(s):s()};if(!e.height)return void n(()=>{e.height||e.set({height:O})},void 0,void 0,!0);let{textOverflow:r}=iS;if("change-font-size"!==r||a)"resize"===r&&(f&&e.height<O&&!a&&n(()=>{e.set({height:O})},!1,!0),f||e.height===O||a||n(()=>{e.set({height:O})},!1,!0));else{let t=(e=>{let t=e.fontSize;for(let n=1;n<50;n++){let n=i$({...e.toJSON(),fontSize:t},{fontFamily:e.fontFamily}),{height:r}=od(n);if(!(e.height&&r>e.height||!iS.textSplitAllowed&&!e.curveEnabled&&function({html:e}){let t=document.createElement("div");t.innerHTML=e,t.style.display="inline-block",t.style.position="fixed",t.style.top="0px",t.style.left="0px",t.style.zIndex="1000",t.style.whiteSpace="nowrap",t.style.visibility="hidden";let n=ou();n.appendChild(t);let r=t.innerText,i=t.childNodes[0];i.style.whiteSpace="nowrap";let a=r?.split(/\s+/)||[],o=!1;for(let e=0;e<a.length;e++){let n=a[e];if(i&&(i.textContent=n,o=i.scrollWidth>t.clientWidth))break}return n.removeChild(t),o}({html:n})))break;t-=.5}return t})(e);t!==e.fontSize?n(()=>{e.set({fontSize:t})},!1,!0):e.height!==O&&(f&&e.height<O?n(()=>{e.set({height:O})},!1,!0):f||n(()=>{e.set({height:O})},!1,!0))}});let A=m(S).useMemo(()=>{let e={lastArgs:null,lastResult:null};return async function(t){var n;return e.lastArgs&&e.lastResult&&(n=e.lastArgs,JSON.stringify(n)===JSON.stringify(t))||(e.lastResult=await og(t),e.lastArgs={...t}),e.lastResult}},[]),I=m(S).useRef(0),R=m(S).useRef(null),L=async()=>{I.current++;let n=I.current,r=r5(`text ${e.id} ${n}`);R.current&&R.current(),R.current=r,l(!0);let a=null,o=oM?5:1;for(let r=0;r<o;r++){let i=r>0?A:og;try{var s;if(a=await i({skipCache:r>0,html:w,width:e.width||1,height:e.height||O||1,fontFamily:b,padding:h,pixelRatio:t._elementsPixelRatio,font:t.fonts.find(e=>e.fontFamily===b)||is.find(e=>e.fontFamily===b)}),n!==I.current)return;if(oM&&a&&(s=a,!function(e){let t=e.getContext("2d").getImageData(0,0,e.width,e.height).data;for(let e=0;e<t.length;e+=4)if(0!==t[e+3])return!0;return!1}(s))){await new Promise(e=>setTimeout(e,50*(r+1)));continue}break}catch(t){console.error(t),it(`Error rendering rich text with id ${e.id}`);break}}a?i(a):r?(r(),r=null):console.error("Finish function is called twice!"),l(!1)};m(S).useEffect(()=>{a||v||L()},[w,a,O,v,b,e.height,t._elementsPixelRatio,y]);let[M,N]=au(s,300),[j]=au(a,300,!0),D=j||M;m(S).useEffect(()=>D?void n.current?.clearCache():E.autorun(()=>{iW(n.current,e)}),[r,D,e.shadowColor,e.shadowOffsetX,e.shadowOffsetY,e.shadowOpacity]),m(S).useEffect(()=>{r&&!s&&R.current&&(R.current(),R.current=null)},[r,s]),m(S).useLayoutEffect(()=>{if(!y||!e.curveEnabled)return;let t=new n_.TextPath({data:iV(e.a.width,e.a.height,e.curvePower,e.a.fontSize),text:iz(e.text),letterSpacing:e.letterSpacing*e.a.fontSize,fontSize:e.a.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle,align:"center",textBaseline:"middle",fill:e.fill}),n=t.getSelfRect().width;if(n){let t=n-e.a.width,r=e.a.rotation*Math.PI/180,i=-(t/2)*Math.cos(r),a=-(t/2)*Math.sin(r);e.set({width:n,x:e.a.x+i,y:e.a.y+a})}t.destroy()},[y,e.curveEnabled,e.curvePower,e.text,e.fontSize,e.fontFamily,e.fontWeight,e.fontStyle,e.letterSpacing]),m(S).useEffect(()=>()=>{R.current&&R.current()},[]),m(S).useEffect(()=>{d&&!u&&p&&""===iz(e.text)&&e.removable&&!e.placeholder&&t.deleteElements([e.id])},[p,e.placeholder,e.removable,e.text,u,d]);let z=0;"middle"===e.verticalAlign&&(z=(e.height-O)/2),"bottom"===e.verticalAlign&&(z=e.height-O);let B=i4({fontLoaded:y,fontFamily:e.fontFamily,fontSize:e.fontSize,lineHeight:e.lineHeight}),F=iK(),H=iV(e.a.width,O,e.curvePower,e.fontSize),V=m(S).useRef(null),U=m(S).useRef(null),$=v&&e.strokeWidth>0&&!e.curveEnabled;return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(rP,{x:e.a.x,y:e.a.y,offsetX:e.backgroundPadding*(e.fontSize*B*.5),offsetY:e.backgroundPadding*(e.fontSize*B*.5),rotation:e.a.rotation,hideInExport:!e.showInExport,listening:!1,visible:e.backgroundEnabled,opacity:e.backgroundOpacity*e.a.opacity,fill:e.backgroundColor,width:e.a.width+e.backgroundPadding*(e.fontSize*B),height:e.a.height+e.backgroundPadding*(e.fontSize*B),cornerRadius:e.backgroundCornerRadius*(e.fontSize*B*.5)}),(0,C.jsx)(rR,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,data:H,stroke:"red",strokeWidth:1,visible:!1}),(0,C.jsx)(rP,{ref:n,name:"element",x:e.a.x,y:e.a.y,listening:e.selectable,rotation:e.a.rotation,width:e.a.width,height:e.a.height,visible:!D,draggable:F?e.draggable&&u:e.draggable,preventDefault:!F||u,opacity:v?0:e.a.opacity,hideInExport:!e.showInExport,onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{e.set({x:t.target.x(),y:t.target.y()})},id:e.id,onDblClick:t=>{e.contentEditable&&(U.current={x:t.evt.clientX,y:t.evt.clientY},e.toggleEditMode(!0))},onDblTap:t=>{if(e.contentEditable){let n=t.evt.changedTouches?.[0];U.current=n?{x:n.clientX,y:n.clientY}:null,e.toggleEditMode(!0)}},onTransformStart:t=>{o(!0),c.current=e.height},onTransform:t=>{let n=t.target,r=(n.getStage()?.findOne("Transformer")).getActiveAnchor(),i=n.scaleX();if("middle-left"===r||"middle-right"===r){let t=n.scaleX(),r=n.width()*t,i=e.fontSize,a=r;if(r<i&&(a=i,V.current&&n.position(V.current)),n.width(a),n.scaleX(1),iS.textVerticalResizeEnabled){let t=Math.max(O,c.current);e.set({height:t})}e.set({width:n.width(),x:n.x(),y:n.y()})}else if("top-center"===r||"bottom-center"===r){let r="resize"===iS.textOverflow,i="number"==typeof e.lineHeight?e.lineHeight:1,a=Math.max(r?O:i*e.fontSize,t.target.height()*t.target.scaleY());n.scaleY(1),e.set({x:n.x(),y:n.y(),height:a,rotation:n.rotation()})}else n.scaleX(1),n.scaleY(1),e.set({fontSize:e.fontSize*i,letterSpacing:e.letterSpacing,width:n.width()*i,x:n.x(),y:n.y(),rotation:n.rotation(),height:n.height()*i});V.current=t.target.position()},onTransformEnd:t=>{o(!1),l(!0);let n=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:e.fontSize*n,width:t.target.width()*n,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),shadowBlur:e.shadowBlur*n,shadowOffsetX:e.shadowOffsetX*n,shadowOffsetY:e.shadowOffsetY*n,strokeWidth:e.strokeWidth*n})}}),(0,C.jsx)(rA,{ref:n,image:r,x:e.a.x,y:e.a.y,offsetX:h,offsetY:h-z,listening:!1,rotation:e.a.rotation,width:e.a.width+2*h,height:(e.a.width+2*h)*((r?.height??0)/(r?.width||1)||1),visible:!D&&!v,opacity:e.a.opacity,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,hideInExport:!e.showInExport,editModeEnabled:e._editModeEnabled||a||D}),(D||$)&&(0,C.jsx)(rE,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-z,children:(0,C.jsx)(rz,{divProps:{style:{pointerEvents:"none"}},children:(0,C.jsx)(oP,{dangerouslySetInnerHTML:{__html:w},style:{pointerEvents:"none",opacity:e.a.opacity,textShadow:e.shadowEnabled?`${e.shadowOffsetX}px ${e.shadowOffsetY}px ${e.shadowBlur}px ${o_(e.shadowColor,e.shadowOpacity??1)}`:void 0}})})}),v&&(0,C.jsx)(rE,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-z,children:(0,C.jsx)(rz,{children:(0,C.jsx)(oL,{html:k,element:e,onChange:t=>{let n=iX({oldText:iz(e.text),newText:iz(t),element:e});e.set({text:t,fontSize:n})},onBlur:t=>{e.toggleEditMode(!1),N(!0)},clickCoords:U.current})})})]})});var S=(x("8NFma"),x("8NFma"));function oj(e){return e/180*Math.PI}function oD(e,t,n,r,i){let a=Math.sqrt(n*n+r*r);return{x:e+a*Math.cos(i+=Math.atan2(r,n)),y:t+a*Math.sin(i)}}function oz(e){let{x:t,y:n,width:r,height:i}=e,a=oj(e.rotation),o=oD(t,n,0,0,a),s=oD(t,n,r,0,a),l=oD(t,n,r,i,a),c=oD(t,n,0,i,a),u=Math.min(o.x,s.x,l.x,c.x),d=Math.min(o.y,s.y,l.y,c.y),h=Math.max(o.x,s.x,l.x,c.x),f=Math.max(o.y,s.y,l.y,c.y);return{x:u,y:d,width:h-u,height:f-d,minX:u,minY:d,maxX:h,maxY:f}}function oB(e){let t=e.map(e=>oz(e)),n=Math.min(...t.map(e=>e.minX)),r=Math.min(...t.map(e=>e.minY)),i=Math.max(...t.map(e=>e.maxX)),a=Math.max(...t.map(e=>e.maxY));return{x:n,y:r,width:i-n,height:a-r,minX:n,minY:r,maxX:i,maxY:a}}let oF={stroke:"rgb(0, 161, 255)",strokeWidth:1,dash:[4,6]},oH=({targetKonvaNodes:e,guideKonvaNode:t,distance:n,snapDirection:r})=>n<5,oV=e=>{oH=e};function oU(e,t){var n=[],r=[];e.vertical.forEach(e=>{t.vertical.forEach(t=>{var r=Math.abs(e.offset-t.guide);oH({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:r,snapDirection:e.snap})&&n.push({lineGuide:e.offset,diff:r,snap:t.snap,offset:t.offset})})}),e.horizontal.forEach(e=>{t.horizontal.forEach(t=>{var n=Math.abs(e.offset-t.guide);oH({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:n,snapDirection:e.snap})&&r.push({lineGuide:e.offset,diff:n,snap:t.snap,offset:t.offset})})});var i=[];let a=n.sort((e,t)=>e.diff-t.diff),o=r.sort((e,t)=>e.diff-t.diff);var s=a[0],l=o[0];return s&&a.filter(e=>.1>Math.abs(e.diff-s.diff)).forEach(e=>{i.push({orientation:"V",...e})}),l&&o.filter(e=>.1>Math.abs(e.diff-l.diff)).forEach(e=>{i.push({orientation:"H",...e})}),i}let o$=()=>{if(0===n_.DD._dragElements.size)return;let e=[...n_.DD._dragElements.entries()],t=e.find(([e,t])=>t.node instanceof n_.Transformer);t&&(e.splice(e.indexOf(t),1),e.unshift(t),n_.DD._dragElements.clear(),e.forEach(([e,t])=>{n_.DD._dragElements.set(e,t)}))};function oq(e,t,n){let r=e=>e.hasName("element")||e.hasName("line-anchor")||e.hasName("page-background")||e.hasName("elements-area"),i=n=>{let i,a,o,s=n.target.getLayer().children.find(e=>"line-guides"===e.name());s?.destroyChildren();var l,c,u,d,h=oU((l=[n.target,...t.map(e=>e.current)],i=e.current?.getStage(),c=[],u=[],i.find(r).forEach(e=>{if(!(l.indexOf(e)>=0)){var t=e.getClientRect({skipShadow:!0,skipStroke:!0});e.hasName("line-anchor")&&(t={x:e.absolutePosition().x,y:e.absolutePosition().y,width:0,height:0}),c.push({offset:t.x,node:e,snap:"start"},{offset:t.x+t.width,node:e,snap:"end"},{offset:t.x+t.width/2,node:e,snap:"center"}),u.push({offset:t.y,node:e,snap:"start"},{offset:t.y+t.height,node:e,snap:"end"},{offset:t.y+t.height/2,node:e,snap:"center"})}}),{vertical:c,horizontal:u}),{vertical:[{guide:(d=n.target).absolutePosition().x,offset:0,snap:"center",nodes:[d]}],horizontal:[{guide:d.absolutePosition().y,offset:0,snap:"center",nodes:[d]}]});if(!h.length)return;a=e.current?.getLayer(),o=a?.children.find(e=>"line-guides"===e.name()),h.forEach(e=>{if("H"===e.orientation){var t=new n_.Line({x:-a.getStage().x(),y:-a.getStage().y(),points:[-6e3,e.lineGuide,6e3,e.lineGuide],stroke:oF.stroke,strokeWidth:oF.strokeWidth,name:"guid-line",dash:oF.dash});o?.add(t),a.batchDraw()}else if("V"===e.orientation){var t=new n_.Line({x:-a.getStage().x(),y:-a.getStage().y(),points:[e.lineGuide,-6e3,e.lineGuide,6e3],stroke:oF.stroke,strokeWidth:oF.strokeWidth,name:"guid-line",dash:oF.dash});o?.add(t)}});let f=n.target.getAbsolutePosition(),p={...f};h.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":p.x=e.lineGuide+e.offset;break;case"H":p.y=e.lineGuide+e.offset}}});let m=p.x-f.x,g=p.y-f.y;if(!(n.evt.ctrlKey||n.evt.metaKey)){let e=n.target.getAbsolutePosition();n.target.absolutePosition({x:e.x+m,y:e.y+g})}},a=e=>{if(!e.target)return;let t=e.target.getLayer(),n=t.children.find(e=>"line-guides"===e.name());n?.destroyChildren(),t.batchDraw()};m(S).useEffect(()=>{e.current&&(e.current.on("dragmove",i),e.current.on("dragend",a))},n)}function oW(e,t){return e.x*t.x+e.y*t.y}let oG={"top-left":"bottom-right","top-center":"bottom-center","top-right":"bottom-left","middle-right":"middle-left","bottom-right":"top-left","bottom-center":"top-center","bottom-left":"top-right","middle-left":"middle-right"};function oK(e){let{x:t,y:n,width:r,height:i,rotation:a}=e.a,o=a*Math.PI/180,s={x:t+i/2*Math.cos(o+Math.PI/2),y:n+i/2*Math.sin(o+Math.PI/2)},l={x:s.x+r*Math.cos(o),y:s.y+r*Math.sin(o)};return{middleLeft:s,middleRight:l}}function oY(e,t,n){let r=Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2)),i=Math.atan2(t.y-e.y,t.x-e.x),a=180*i/Math.PI;return{x:e.x+Math.cos(i-Math.PI/2)*n/2,y:e.y+Math.sin(i-Math.PI/2)*n/2,width:r,height:n,rotation:a}}let oX=(e,t)=>{let n=h9.anchorSize||10;return{offsetX:n/2/e,offsetY:n/2/e,width:n/e,height:n/e,cornerRadius:(h9.anchorCornerRadius||0)/e,fill:h9.anchorFill||"white",stroke:h9.anchorStroke||"rgb(0, 161, 255)",strokeWidth:h9.anchorStrokeWidth||2,strokeScaleEnabled:!1,draggable:!0,dragDistance:0,onMouseEnter:e=>{e.target.getStage().container().style.cursor="crosshair"},onMouseLeave:e=>{e.target.getStage().container().style.cursor=""},onDragStart:e=>{t.history.startTransaction()},onDragEnd:e=>{t.history.endTransaction()}}},oQ=j(({element:e,type:t})=>{let n=rQ(e,e.a.color,"fill"),r=rQ(e,e.a.color,"stroke"),i={strokeWidth:e.height,lineCap:"round",lineJoin:"round",...r,...n,opacity:e.a.opacity,hideInExport:!e.showInExport};return(0,C.jsxs)(C.Fragment,{children:["arrow"===t&&(0,C.jsx)(rO,{points:[3*e.height,-(2*e.height),0,0,3*e.height,2*e.height],...i}),"triangle"===t&&(0,C.jsx)(rO,{points:[3*e.height,-(2*e.height),0,0,3*e.height,2*e.height],closed:!0,...i}),"bar"===t&&(0,C.jsx)(rO,{points:[0,-(2*e.height),0,2*e.height],closed:!0,...i}),"square"===t&&(0,C.jsx)(rO,{points:[0,-(2*e.height),4*e.height,-(2*e.height),4*e.height,2*e.height,0,2*e.height],closed:!0,...i}),"circle"===t&&(0,C.jsx)("Circle",{x:2*e.height,y:0,radius:2*e.height,...i})]})}),oZ=j(({element:e,store:t})=>{let n=m(S).useRef(null),r=m(S).useRef(null),i=m(S).useRef(null),a=e.selectable||"admin"===t.role,o=iK(),s=t.selectedElements.indexOf(e)>=0&&1===t.selectedElements.length,l=t.selectedShapes.indexOf(e)>=0&&e.selectable,{middleLeft:c,middleRight:u}=oK(e);oq(r,[n],[s]),oq(i,[n],[s]);let d=rQ(e,e.a.color,"stroke");return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(rO,{ref:n,name:"element",id:e.id,x:e.a.x,y:e.a.y,points:[0,0,e.a.width,0],offsetY:-e.a.height/2,strokeWidth:e.a.height,hitStrokeWidth:Math.max(e.a.height,20),dash:e.dash.map(t=>t*e.a.height),...d,rotation:e.a.rotation,opacity:e.animated("opacity"),shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,listening:a,draggable:o?e.draggable&&l:e.draggable,preventDefault:!o||l,hideInExport:!e.showInExport,onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{e.set({x:t.target.x(),y:t.target.y()})},onTransform:t=>{let n=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({height:e.height*n,width:e.width*n,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation()})}}),(0,C.jsx)(rE,{x:c.x,y:c.y,rotation:e.rotation,hideInExport:!e.showInExport,onClick:e=>n.current?.fire("click",e),onTap:e=>n.current?.fire("tap",e),children:(0,C.jsx)(oQ,{element:e,type:e.startHead})}),(0,C.jsx)(rE,{x:u.x,y:u.y,rotation:e.rotation+180,onClick:e=>n.current?.fire("click",e),onTap:e=>n.current?.fire("tap",e),children:(0,C.jsx)(oQ,{element:e,type:e.endHead})}),s&&e.resizable&&(0,C.jsx)(rB,{selector:".page-abs-container",enabled:!0,children:(0,C.jsxs)(rE,{visible:s,children:[(0,C.jsx)(rP,{x:c.x,y:c.y,ref:r,name:"line-anchor",...oX(t.scale,t),onDragMove:t=>{let n=oY(t.target.position(),u,e.height);e.set({x:n.x,y:n.y,width:n.width,rotation:n.rotation})}}),(0,C.jsx)(rP,{x:u.x,y:u.y,ref:i,name:"line-anchor",...oX(t.scale,t),onDragMove:t=>{let n=oY(c,t.target.position(),e.height);e.set({x:n.x,y:n.y,width:n.width,rotation:n.rotation})}})]})})]})});var S=x("8NFma"),E=x("2SBKn"),S=x("8NFma"),E=x("2SBKn");function oJ(e){if(!e)throw Error("Assertion failed.")}let o0=e=>{let t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw Error(`Invalid rotation ${e}.`)},o1=e=>e&&e[e.length-1];class o2{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(7&this.pos);return this.pos++,(t&1<<n)>>n}readBits(e){if(1===e)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(7&e);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}readAlignedByte(){if(this.pos%8!=0)throw Error("Bitstream is not byte-aligned.");let 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(){let e=new o2(this.bytes);return e.pos=this.pos,e}}let o4=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw Error("Invalid exponential-Golomb code.");return(1<<t)-1+e.readBits(t)},o3=e=>{let t=o4(e);return(1&t)==0?-(t>>1):t+1>>1},o8=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),o6=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),o5=new TextDecoder,o9=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),o7={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},se=o9(o7),st={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},sn=o9(st),sr={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},si=o9(sr),sa=e=>e instanceof ArrayBuffer||"u">typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class so{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||(t(),this.pending--,n=!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}}let ss=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),sl=e=>(e=(e=(e=(e=(e=e>>1&0x55555555|(0x55555555&e)<<1)>>2&0x33333333|(0x33333333&e)<<2)>>4&0xf0f0f0f|(0xf0f0f0f&e)<<4)>>8&0xff00ff|(0xff00ff&e)<<8)>>16&65535|(65535&e)<<16)>>>0,sc=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+i>>1,s=n(e[o]);s===t?(a=o,i=o-1):s<t?r=o+1:i=o-1}return a},su=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+(i-r+1)/2|0;n(e[o])<=t?(a=o,r=o+1):i=o-1}return a},sd=(e,t,n)=>{let r=su(e,n(t),n);e.splice(r+1,0,t)},sh=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},sf=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]},sp=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return -1},sm=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},sg=e=>{throw Error(`Unexpected value: ${e}`)},sy=(e,t,n)=>{let r=e.getUint8(t),i=e.getUint8(t+1),a=e.getUint8(t+2);return n?r|i<<8|a<<16:r<<16|i<<8|a},sv=(e,t,n,r)=>{n>>>=0,n&=0xffffff,r?(e.setUint8(t,255&n),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,255&n))},sb=(e,t)=>({async next(){let n=await e.next();return n.done?{value:void 0,done:!0}:{value:t(n.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),sx=(e,t,n)=>Math.max(t,Math.min(n,e)),sw=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},sC=(e,t)=>Math.floor(e/t)*t,sS=/^[a-z]{3}$/,sk=1e6*(1+Number.EPSILON),s_=(e,t)=>{let n={...e,...t};if(e.headers||t.headers){let r=e.headers?sE(e.headers):{},i=t.headers?sE(t.headers):{},a={...r};Object.entries(i).forEach(([e,t])=>{let n=Object.keys(a).find(t=>t.toLowerCase()===e.toLowerCase());n&&delete a[n],a[e]=t}),n.headers=a}return n},sE=e=>{if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}if(Array.isArray(e)){let t={};return e.forEach(([e,n])=>{t[e]=n}),t}return e},sT=async(e,t,n,r,i)=>{let a=0;for(;;)try{return await e(t,n)}catch(n){if(i())throw n;let e=r(++a,n,t);if(null===e)throw n;if(console.error("Retrying failed fetch. Error:",n),!Number.isFinite(e)||e<0)throw TypeError("Retry delay must be a non-negative finite number.");if(e>0&&await new Promise(t=>setTimeout(t,1e3*e)),i())throw n}};class sP{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let sO=null,sA=()=>null!==sO?sO:sO=!!("u">typeof navigator&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),sI=null,sR=()=>null!==sI?sI:sI="u">typeof navigator&&navigator.userAgent?.includes("Firefox"),sL=null,sM=()=>null!==sL?sL:sL=!!("u">typeof navigator&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),sN=null,sj=()=>{if(null!==sN)return sN;if("u"<typeof navigator)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?sN=Number(e[1]):null},sD=(e,t)=>-1!==e?e:t,sz=(e,t,n,r)=>e<=r&&n<=t,sB=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},sF=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},sH=e=>"number"==typeof e&&!Number.isNaN(e),sV=["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"];[...sV];let sU=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],s$=[{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:0x2200000,maxBitrate:18e7,level:60},{maxPictureSize:0x2200000,maxBitrate:24e7,level:61},{maxPictureSize:0x2200000,maxBitrate:48e7,level:62}],sq=".01.01.01.01.00",sW=".0.110.01.01.01.0",sG=e=>{let{codec:t,codecDescription:n,colorSpace:r,avcCodecInfo:i,hevcCodecInfo:a,vp9CodecInfo:o,av1CodecInfo:s}=e;if("avc"===t){if(oJ(null!==e.avcType),i){let t=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${e.avcType}.${ss(t)}`}if(!n||n.byteLength<4)throw TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${ss(n.subarray(1,4))}`}if("hevc"===t){let e,t,r,i,o,s;if(a)e=a.generalProfileSpace,t=a.generalProfileIdc,r=sl(a.generalProfileCompatibilityFlags),i=a.generalTierFlag,o=a.generalLevelIdc,s=[...a.generalConstraintIndicatorFlags];else{if(!n||n.byteLength<23)throw TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let a=o6(n),l=a.getUint8(1);e=l>>6&3,t=31&l,r=sl(a.getUint32(2)),i=l>>5&1,o=a.getUint8(12),s=[];for(let e=0;e<6;e++)s.push(a.getUint8(6+e))}let l="hev1.";for(l+=["","A","B","C"][e]+t,l+=".",l+=r.toString(16).toUpperCase(),l+=".",l+=0===i?"L":"H",l+=o;s.length>0&&0===s[s.length-1];)s.pop();return s.length>0&&(l+=".",l+=s.map(e=>e.toString(16).toUpperCase()).join(".")),l}if("vp8"===t)return"vp8";if("vp9"===t){if(!o){let t=e.width*e.height,n=o1(s$).level;for(let e of s$)if(t<=e.maxPictureSize){n=e.level;break}return`vp09.00.${n.toString().padStart(2,"0")}.08`}let t=o.profile.toString().padStart(2,"0"),n=o.level.toString().padStart(2,"0"),r=o.bitDepth.toString().padStart(2,"0"),i=o.chromaSubsampling.toString().padStart(2,"0"),a=o.colourPrimaries.toString().padStart(2,"0"),s=o.transferCharacteristics.toString().padStart(2,"0"),l=o.matrixCoefficients.toString().padStart(2,"0"),c=o.videoFullRangeFlag.toString().padStart(2,"0"),u=`vp09.${t}.${n}.${r}.${i}`;return(u+=`.${a}.${s}.${l}.${c}`).endsWith(sq)&&(u=u.slice(0,-sq.length)),u}if("av1"===t){if(!s){let t=e.width*e.height,n=o1(s$).level;for(let e of s$)if(t<=e.maxPictureSize){n=e.level;break}return`av01.0.${n.toString().padStart(2,"0")}M.08`}let t=s.profile,n=s.level.toString().padStart(2,"0"),i=s.tier?"H":"M",a=s.bitDepth.toString().padStart(2,"0"),o=s.monochrome?"1":"0",l=100*s.chromaSubsamplingX+10*s.chromaSubsamplingY+ +(s.chromaSubsamplingX&&s.chromaSubsamplingY?s.chromaSamplePosition:0),c=r?.primaries?o7[r.primaries]:1,u=r?.transfer?st[r.transfer]:1,d=r?.matrix?sr[r.matrix]:1,h=+!!r?.fullRange,f=`av01.${t}.${n}${i}.${a}`;return f+=`.${o}.${l.toString().padStart(3,"0")}`,f+=`.${c.toString().padStart(2,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${d.toString().padStart(2,"0")}`,(f+=`.${h}`).endsWith(sW)&&(f=f.slice(0,-sW.length)),f}throw TypeError(`Unhandled codec '${t}'.`)},sK=e=>{let{codec:t,codecDescription:n,aacCodecInfo:r}=e;if("aac"===t){if(!r)throw TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;return e=null!==r.objectType?r.objectType:sQ(n).objectType,`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";else if("ac3"===t)return"ac-3";else if("eac3"===t)return"ec-3";else if(t&&sV.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},sY=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],sX=[-1,1,2,3,4,5,6,8],sQ=e=>{if(!e||e.byteLength<2)throw TypeError("AAC description must be at least 2 bytes long.");let t=new o2(e),n=t.readBits(5);31===n&&(n=32+t.readBits(6));let r=t.readBits(4),i=null;15===r?i=t.readBits(24):r<sY.length&&(i=sY[r]);let a=t.readBits(4),o=null;return a>=1&&a<=7&&(o=sX[a]),{objectType:n,frequencyIndex:r,sampleRate:i,channelConfiguration:a,numberOfChannels:o}},sZ=/^pcm-([usf])(\d+)+(be)?$/,sJ=[48e3,44100,32e3],s0=[24e3,22050,16e3];(NK=jT||(jT={}))[NK.NON_IDR_SLICE=1]="NON_IDR_SLICE",NK[NK.SLICE_DPA=2]="SLICE_DPA",NK[NK.SLICE_DPB=3]="SLICE_DPB",NK[NK.SLICE_DPC=4]="SLICE_DPC",NK[NK.IDR=5]="IDR",NK[NK.SEI=6]="SEI",NK[NK.SPS=7]="SPS",NK[NK.PPS=8]="PPS",NK[NK.AUD=9]="AUD",NK[NK.SPS_EXT=13]="SPS_EXT",(NY=jP||(jP={}))[NY.RASL_N=8]="RASL_N",NY[NY.RASL_R=9]="RASL_R",NY[NY.BLA_W_LP=16]="BLA_W_LP",NY[NY.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",NY[NY.VPS_NUT=32]="VPS_NUT",NY[NY.SPS_NUT=33]="SPS_NUT",NY[NY.PPS_NUT=34]="PPS_NUT",NY[NY.AUD_NUT=35]="AUD_NUT",NY[NY.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",NY[NY.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT";let s1=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(-1===r||r>=e.length-2)break;let i=0;if((t=r)+3<e.length&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]?i=4:0===e[t+1]&&1===e[t+2]&&(i=3),0===i){t++;continue}-1!==n&&t>n&&(yield{offset:n,length:t-n}),t=n=t+i}-1!==n&&n<e.length&&(yield{offset:n,length:e.length-n})},s2=function*(e,t){let n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+t<=e.length;){let e;1===t?e=r.getUint8(n):2===t?e=r.getUint16(n,!1):3===t?e=sy(r,n,!1):(oJ(4===t),e=r.getUint32(n,!1)),n+=t,yield{offset:n,length:e},n+=e}},s4=(e,t)=>t.description?s2(e,(3&o8(t.description)[4])+1):s1(e),s3=e=>31&e,s8=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&0===e[r]&&0===e[r+1]&&3===e[r+2]?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)},s6=new Uint8Array([0,0,0,1]),s5=e=>{try{let t=[],n=[],r=[];for(let i of s1(e)){let a=e.subarray(i.offset,i.offset+i.length),o=s3(a[0]);o===jT.SPS?t.push(a):o===jT.PPS?n.push(a):o===jT.SPS_EXT&&r.push(a)}if(0===t.length||0===n.length)return null;let i=t[0],a=s9(i);oJ(null!==a);let o=100===a.profileIdc||110===a.profileIdc||122===a.profileIdc||144===a.profileIdc;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},s9=e=>{try{let t=new o2(s8(e));t.skipBits(1),t.skipBits(2);let n=t.readBits(5);if(7!==n)return null;let r=t.readAlignedByte(),i=t.readAlignedByte(),a=t.readAlignedByte();o4(t);let o=1,s=0,l=0,c=0;if((100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r)&&(o=o4(t),3===o&&(c=t.readBits(1)),s=o4(t),l=o4(t),t.skipBits(1),t.readBits(1))){for(let e=0;e<(3!==o?8:12);e++)if(t.readBits(1)){let n=e<6?16:64,r=8,i=8;for(let e=0;e<n;e++){if(0!==i){let e=o3(t);i=(r+e+256)%256}r=0===i?r:i}}}o4(t);let u=o4(t);if(0===u)o4(t);else if(1===u){t.skipBits(1),o3(t),o3(t);let e=o4(t);for(let n=0;n<e;n++)o3(t)}o4(t),t.skipBits(1);let d=o4(t),h=o4(t),f=16*(d+1),p=16*(h+1),m=f,g=p,y=t.readBits(1);if(y||t.skipBits(1),t.skipBits(1),t.readBits(1)){let e,n,r=o4(t),i=o4(t),a=o4(t),s=o4(t),l=0===c?o:0;if(0===l)e=1,n=2-y;else{let t=3===o?1:2,r=1===o?2:1;e=t,n=r*(2-y)}m-=e*(r+i),g-=n*(a+s)}let v=2,b=2,x=2,w=0,C=null,S=null;if(t.readBits(1)){if(t.readBits(1)){let e=t.readBits(8);255===e&&(t.skipBits(16),t.skipBits(16))}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),w=t.readBits(1),t.readBits(1)&&(v=t.readBits(8),b=t.readBits(8),x=t.readBits(8))),t.readBits(1)&&(o4(t),o4(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let e=t.readBits(1);e&&s7(t);let n=t.readBits(1);n&&s7(t),(e||n)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),o4(t),o4(t),o4(t),o4(t),C=o4(t),S=o4(t))}if(null===C)if(oJ(null===S),(44===r||86===r||100===r||110===r||122===r||244===r)&&16&i)C=0,S=0;else{let e=sU.find(e=>e.level>=a)??o1(sU),t=Math.min(Math.floor(e.maxDpbMbs/((2-y)*(h+1)*(d+1))),16);C=t,S=t}return oJ(null!==S),{profileIdc:r,constraintFlags:i,levelIdc:a,frameMbsOnlyFlag:y,chromaFormatIdc:o,bitDepthLumaMinus8:s,bitDepthChromaMinus8:l,codedWidth:f,codedHeight:p,displayWidth:m,displayHeight:g,colourPrimaries:v,matrixCoefficients:x,transferCharacteristics:b,fullRangeFlag:w,numReorderFrames:C,maxDecFrameBuffering:S}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},s7=e=>{let t=o4(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)o4(e),o4(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},le=(e,t)=>t.description?s2(e,(3&o8(t.description)[21])+1):s1(e),lt=e=>e>>1&63,ln=e=>{try{let t=new o2(s8(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:l,general_level_idc:c}=li(t,n);o4(t);let u=o4(t),d=0;3===u&&(d=t.readBits(1));let h=o4(t),f=o4(t),p=h,m=f;if(t.readBits(1)){let e=o4(t),n=o4(t),r=o4(t),i=o4(t),a=1,o=1,s=0===d?u:0;1===s?(a=2,o=2):2===s&&(a=2,o=1),p-=(e+n)*a,m-=(r+i)*o}let g=o4(t),y=o4(t);o4(t);let v=t.readBits(1)?0:n,b=0;for(let e=v;e<=n;e++)o4(t),b=o4(t),o4(t);o4(t),o4(t),o4(t),o4(t),o4(t),o4(t),t.readBits(1)&&t.readBits(1)&&la(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),o4(t),o4(t),t.skipBits(1));let x=o4(t);if(lo(t,x),t.readBits(1)){let e=o4(t);for(let n=0;n<e;n++)o4(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let w=2,C=2,S=2,k=0,_=0;if(t.readBits(1)){let e=ll(t,n);w=e.colourPrimaries,C=e.transferCharacteristics,S=e.matrixCoefficients,k=e.fullRangeFlag,_=e.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,colourPrimaries:w,transferCharacteristics:C,matrixCoefficients:S,fullRangeFlag:k,maxDecFrameBuffering:b+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:l,generalLevelIdc:c,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:_}}catch(e){return console.error("Error parsing HEVC SPS:",e),null}},lr=e=>{try{let t=[],n=[],r=[],i=[];for(let a of s1(e)){let o=e.subarray(a.offset,a.offset+a.length),s=lt(o[0]);s===jP.VPS_NUT?t.push(o):s===jP.SPS_NUT?n.push(o):s===jP.PPS_NUT?r.push(o):(s===jP.PREFIX_SEI_NUT||s===jP.SUFFIX_SEI_NUT)&&i.push(o)}if(0===n.length||0===r.length)return null;let a=ln(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new o2(s8(e));t.skipBits(16),o4(t),o4(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),o4(t),o4(t),o3(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&o4(t),o3(t),o3(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);o=n||i?n&&!i?2:!n&&i?3:0:0}let s=[...t.length?[{arrayCompleteness:1,nalUnitType:jP.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:jP.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:jP.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:lt(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:s}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},li=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),l=[],c=[];for(let n=0;n<t;n++)l.push(e.readBits(1)),c.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)l[n]&&e.skipBits(88),c[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},la=e=>{for(let t=0;t<4;t++)for(let n=0;n<(3===t?2:6);n++)if(e.readBits(1)){let n=Math.min(64,1<<4+(t<<1));t>1&&o3(e);for(let t=0;t<n;t++)o3(e)}else o4(e)},lo=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=ls(e,r,t,n)},ls=(e,t,n,r)=>{let i=0,a=0,o=0;if(0!==t&&(a=e.readBits(1)),a){o=t===n?t-(o4(e)+1):t-1,e.readBits(1),o4(e);let a=r[o]??0;for(let t=0;t<=a;t++)e.readBits(1)||e.readBits(1);i=r[o]}else{let t=o4(e),n=o4(e);for(let n=0;n<t;n++)o4(e),e.readBits(1);for(let t=0;t<n;t++)o4(e),e.readBits(1);i=t+n}return i},ll=(e,t)=>{let n=2,r=2,i=2,a=0,o=0;return e.readBits(1)&&255===e.readBits(8)&&(e.readBits(16),e.readBits(16)),e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(o4(e),o4(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(o4(e),o4(e),o4(e),o4(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&o4(e),e.readBits(1)&&lc(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=o4(e),o4(e),o4(e),o4(e),o4(e)),{colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},lc=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=1===e.readBits(1),i=1===e.readBits(1),(r||i)&&((a=1===e.readBits(1))&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=1===e.readBits(1),n=!0;t||(n=1===e.readBits(1));let o=!1;n?o4(e):o=1===e.readBits(1);let s=1;o||(s=o4(e)+1),r&&lu(e,s,a),i&&lu(e,s,a)}},lu=(e,t,n)=>{for(let r=0;r<t;r++)o4(e),o4(e),n&&(o4(e),o4(e)),e.readBits(1)},ld=e=>{let t=new o2(e);if(2!==t.readBits(2))return null;let n=t.readBits(1),r=(t.readBits(1)<<1)+n;if(3===r&&t.skipBits(1),1===t.readBits(1)||0!==t.readBits(1)||(t.skipBits(2),4817730!==t.readBits(24)))return null;let i=8;r>=2&&(i=t.readBits(1)?12:10);let a=t.readBits(3),o=0,s=0;if(7!==a)if(s=t.readBits(1),1===r||3===r){let e=t.readBits(1),n=t.readBits(1);o=e||n?e&&!n?2:1:3,t.skipBits(1)}else o=1;else o=3,s=1;let l=(t.readBits(16)+1)*(t.readBits(16)+1),c=o1(s$).level;for(let e of s$)if(l<=e.maxPictureSize){c=e.level;break}return{profile:r,level:c,bitDepth:i,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:2===a?1:1===a?6:2,transferCharacteristics:2===a?1:1===a?6:2,matrixCoefficients:7===a?0:2===a?1:1===a?6:2}},lh=function*(e){let t=new o2(e),n=()=>{let e=0;for(let n=0;n<8;n++){let r=t.readAlignedByte();if(e|=(127&r)<<7*n,!(128&r))break;if(7===n&&128&r)return null}return e>=0x100000000-1?null:e};for(;t.getBitsLeft()>=8;){let r;t.skipBits(1);let i=t.readBits(4),a=t.readBits(1),o=t.readBits(1);if(t.skipBits(1),a&&t.skipBits(8),o){let e=n();if(null===e)return;r=e}else r=Math.floor(t.getBitsLeft()/8);oJ(t.pos%8==0),yield{type:i,data:e.subarray(t.pos/8,t.pos/8+r)},t.skipBits(8*r)}},lf=e=>{for(let{type:t,data:n}of lh(e)){if(1!==t)continue;let e=new o2(n),r=e.readBits(3);e.readBits(1);let i=e.readBits(1),a=0,o=0,s=0;if(i)a=e.readBits(5);else{if(e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.readBits(1)))return null;let t=e.readBits(1);t&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));let n=e.readBits(5);for(let r=0;r<=n;r++){e.skipBits(12);let n=e.readBits(5);if(0===r&&(a=n),n>7){let t=e.readBits(1);0===r&&(o=t)}if(t&&e.readBits(1)){let t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}e.readBits(1)&&e.skipBits(4)}}let l=e.readBits(4),c=e.readBits(4),u=l+1;e.skipBits(u);let d=c+1;e.skipBits(d);if((i?0:e.readBits(1))&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let n=e.readBits(1);(n?2:e.readBits(1))>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let h=e.readBits(1),f=8;2===r&&h?f=e.readBits(1)?12:10:r<=2&&(f=h?10:8);let p=0;1!==r&&(p=e.readBits(1));let m=1,g=1,y=0;return!p&&(0===r?(m=1,g=1):1===r?(m=0,g=0):12===f&&(m=e.readBits(1))&&(g=e.readBits(1)),m&&g&&(y=e.readBits(2))),{profile:r,level:a,tier:o,bitDepth:f,monochrome:p,chromaSubsamplingX:m,chromaSubsamplingY:g,chromaSamplePosition:y}}return null},lp=[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],lm=(e,t,n)=>{switch(e){case"avc":for(let e of s4(n,t)){let t=s3(n[e.offset]);if(t>=jT.NON_IDR_SLICE&&t<=jT.SLICE_DPC)break;if(t===jT.IDR)return"key";if(t===jT.SEI&&(!sM()||sj()>=144)){let t=s8(n.subarray(e.offset,e.offset+e.length)),r=1;do{let e=0;for(;;){let n=t[r++];if(void 0===n||(e+=n,n<255))break}let n=0;for(;;){let e=t[r++];if(void 0===e||(n+=e,e<255))break}if(6===e){let e=new o2(t);e.pos=8*r;let n=o4(e),i=e.readBits(1);if(0===n&&1===i)return"key"}r+=n}while(r<t.length-1)}}return"delta";case"hevc":for(let e of le(n,t)){let t=lt(n[e.offset]);if(t<jP.BLA_W_LP)break;if(t<=jP.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 0==(1&n[0])?"key":"delta";case"vp9":{let e=new o2(n);if(2!==e.readBits(2))return null;let t=e.readBits(1);if(3===(e.readBits(1)<<1)+t&&e.skipBits(1),e.readBits(1))return null;return 0===e.readBits(1)?"key":"delta"}case"av1":{let e=!1;for(let{type:t,data:r}of lh(n))if(1===t){let t=new o2(r);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";let t=new o2(r);if(t.readBits(1))return null;return 0===t.readBits(2)?"key":"delta"}return null}default:sg(e),oJ(!1)}};(NX=jO||(jO={}))[NX.STREAMINFO=0]="STREAMINFO",NX[NX.VORBIS_COMMENT=4]="VORBIS_COMMENT",NX[NX.PICTURE=6]="PICTURE";let lg=(e,t)=>{let n=o6(e),r=0,i=n.getUint32(r,!0);r+=4;let a=o5.decode(e.subarray(r,r+i));r+=i,i>0&&(t.raw??={},t.raw.vendor??=a);let o=n.getUint32(r,!0);r+=4;for(let i=0;i<o;i++){let i=n.getUint32(r,!0);r+=4;let a=o5.decode(e.subarray(r,r+i));r+=i;let o=a.indexOf("=");if(-1===o)continue;let s=a.slice(0,o).toUpperCase(),l=a.slice(o+1);switch(t.raw??={},t.raw[s]??=l,s){case"TITLE":t.title??=l;break;case"DESCRIPTION":t.description??=l;break;case"ARTIST":t.artist??=l;break;case"ALBUM":t.album??=l;break;case"ALBUMARTIST":t.albumArtist??=l;break;case"COMMENT":t.comment??=l;break;case"LYRICS":t.lyrics??=l;break;case"TRACKNUMBER":{let e=l.split("/"),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.trackNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??=r)}break;case"TRACKTOTAL":{let e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case"DISCNUMBER":{let e=l.split("/"),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.discNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??=r)}break;case"DISCTOTAL":{let e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case"DATE":{let e=new Date(l);Number.isNaN(e.getTime())||(t.date??=e)}break;case"GENRE":t.genre??=l;break;case"METADATA_BLOCK_PICTURE":{let e=sB(l),n=o6(e),r=n.getUint32(0,!1),i=n.getUint32(4,!1),a=String.fromCharCode(...e.subarray(8,8+i)),o=n.getUint32(8+i,!1),s=o5.decode(e.subarray(12+i,12+i+o)),c=n.getUint32(i+o+28),u=e.subarray(i+o+32,i+o+32+c);t.images??=[],t.images.push({data:u,mimeType:a,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:s||void 0})}}}},ly=[2,1,2,3,3,4,4,5],lv=e=>{if(e.length<7||11!==e[0]||119!==e[1])return null;let t=new o2(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(3===n)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return(1&o)!=0&&1!==o&&t.skipBits(2),(4&o)!=0&&t.skipBits(2),2===o&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},lb=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840];new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);let lx=[1,2,3,6],lw=e=>{let t;if(e.length<6||11!==e[0]||119!==e[1])return null;let n=new o2(e);n.skipBits(16);let r=n.readBits(2);if(n.skipBits(3),0!==r&&2!==r)return null;let i=n.readBits(11),a=n.readBits(2),o=0;3===a?(o=n.readBits(2),t=3):t=n.readBits(2);let s=n.readBits(3),l=n.readBits(1),c=n.readBits(5);if(c<11||c>16)return null;let u=lx[t];return{dataRate:Math.round((i+1)*(a<3?sJ[a]/1e3:s0[o]/1e3)/(16*u)),substreams:[{fscod:a,fscod2:o,bsid:c,bsmod:0,acmod:s,lfeon:l,numDepSub:0,chanLoc:0}]}},lC=e=>{let t=e.substreams[0];return(oJ(t),t.fscod<3)?sJ[t.fscod]:null!==t.fscod2&&t.fscod2<3?s0[t.fscod2]:null},lS=e=>{let t=e.substreams[0];oJ(t);let n=ly[t.acmod]+t.lfeon;if(t.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let r=0;r<9;r++)t.chanLoc&1<<8-r&&(n+=e[r])}return n};class lk{constructor(e){this.input=e}}let l_=[],lE=[];class lT{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new lZ;if(e<0||null!==this.fileSize&&e+t>this.fileSize)return null;let n=e+t,r=this.source._read(e,n);return r instanceof Promise?r.then(t=>t?new lP(t.bytes,t.view,t.offset,e,n):null):r?new lP(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new lZ;if(e<0)return null;if(null!==this.fileSize)return this.requestSlice(e,sx(this.fileSize-e,t,n));{let r=this.requestSlice(e,n),i=r=>{if(r)return r;let i=r=>(oJ(null!==r),this.requestSlice(e,sx(r-e,t,n))),a=this.source._retrieveSize();return a instanceof Promise?a.then(i):i(a)};return r instanceof Promise?r.then(i):i(r)}}}class lP{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(e){return new lP(e,o6(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 RangeError("Slicing outside of original slice.");return new lP(this.bytes,this.view,this.offset,e,e+t)}}let lO=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw 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.`)},lA=(e,t)=>{lO(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},lI=e=>(lO(e,1),e.view.getUint8(e.bufferPos++)),lR=(e,t)=>{lO(e,2);let n=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,n},lL=e=>{lO(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},lM=e=>{lO(e,3);let t=sy(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},lN=e=>{lO(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},lj=(e,t)=>{lO(e,4);let n=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,n},lD=e=>{lO(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},lz=e=>{lO(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},lB=e=>{lO(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},lF=(e,t)=>{let n,r;return t?(n=lj(e,!0),r=lj(e,!0)):(r=lj(e,!1),n=lj(e,!1)),0x100000000*r+n},lH=e=>0x100000000*lD(e)+lD(e),lV=e=>0x100000000*lB(e)+lD(e),lU=e=>{lO(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},l$=(e,t)=>{lO(e,t);let n="";for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n};x("foUwZ");class lq{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new lZ;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new lZ;let e=await this.getSizeOrNull();if(null===e)throw Error("Cannot determine the size of an unsized source.");return e}}class lW extends lq{constructor(e){if(!(e instanceof ArrayBuffer)&&!("u">typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=o8(e),this._view=o6(e)}_retrieveSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this.onread?.(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}}let lG=(e,t,n)=>{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{"u">typeof window&&void 0!==window.location&&(e=new URL(n instanceof Request?n.url:n,window.location.href).origin)}catch{}if(("u"<typeof navigator||"boolean"!=typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(e-2),16)};class lK extends lq{constructor(e,t={}){if("string"!=typeof e&&!(e instanceof URL)&&!("u">typeof Request&&e instanceof Request))throw TypeError("url must be a string, URL or Request.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!=typeof t.requestInit))throw TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!=typeof t.getRetryDelay)throw TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!sH(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!=typeof t.fetchFn)throw TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??lG,this._orchestrator=new lX({maxCacheSize:t.maxCacheSize??0x4000000,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:lY.network})}async _retrieveSize(){let e,t,n=new AbortController,r=await sT(this._options.fetchFn??fetch,this._url,s_(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:n.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);if(206===r.status)t=this._getTotalLengthFromRangeResponse(r),e=this._orchestrator.createWorker(0,Math.min(t,524288));else{let n=r.headers.get("Content-Length");if(n)t=Number(n),e=this._orchestrator.createWorker(0,t),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.");else throw Error(`HTTP response (status ${r.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=t,this._existingResponses.set(e,{response:r,abortController:n}),this._orchestrator.runWorker(e),t}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;;){let t=this._existingResponses.get(e);this._existingResponses.delete(e);let n=t?.abortController,r=t?.response;if(n||(n=new AbortController,r=await sT(this._options.fetchFn??fetch,this._url,s_(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed)),oJ(r),!r.ok)throw Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);if(e.currentPos>0&&206!==r.status)throw Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!r.body)throw Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let i=r.body.getReader();for(;;){let t;if(e.currentPos>=e.targetPos||e.aborted){n.abort(),e.running=!1;return}try{t=await i.read()}catch(t){if(this._disposed)throw t;let e=this._getRetryDelay(1,t,this._url);if(null!==e){console.error("Error while reading response stream. Attempting to resume.",t),await new Promise(t=>setTimeout(t,1e3*e));break}throw t}if(e.aborted)continue;let{done:r,value:a}=t;if(r){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+a.length),this._orchestrator.supplyWorkerData(e,a)}}}_getTotalLengthFromRangeResponse(e){let t=e.headers.get("Content-Range");if(t){let e=/\/(\d+)/.exec(t);if(e)return Number(e[1])}let n=e.headers.get("Content-Length");if(n)return Number(n);throw Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}}let lY={network:(e,t,n)=>{for(let r of(e=Math.max(0,65536*Math.floor((e-65536)/65536)),n))if(sz(e,t,Math.max((r.startPos+r.targetPos)/2,r.targetPos-8388608),r.targetPos)){let e=r.targetPos-r.startPos,n=8388608*Math.ceil((e+1)/8388608),i=Math.min(2**Math.ceil(Math.log2(e+1)),n);t=Math.max(t,r.startPos+i)}return t=Math.max(t,e+524288),{start:e,end:t}}};class lX{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){oJ(null!==this.fileSize);let n=this.options.prefetchProfile(e,t,this.workers),r=Math.max(n.start,0),i=Math.min(n.end,this.fileSize);oJ(r<=e&&t<=i);let a=null,o=su(this.cache,e,e=>e.start),s=-1!==o?this.cache[o]:null;s&&s.start<=e&&t<=s.end&&(s.age=this.nextAge++,a={bytes:s.bytes,view:s.view,offset:s.start});let l=su(this.cache,r,e=>e.start),c=a?null:new Uint8Array(t-e),u=0,d=r,h=[];if(-1!==l){for(let n=l;n<this.cache.length;n++){let a=this.cache[n];if(a.start>=i)break;if(a.end<=r)continue;let o=Math.max(r,a.start),s=Math.min(i,a.end);if(oJ(o<=s),d<o&&h.push({start:d,end:o}),d=s,c){let n=Math.max(e,a.start),r=Math.min(t,a.end);if(n<r){let t=n-e;c.set(a.bytes.subarray(n-a.start,r-a.start),t),t===u&&(u=r-e)}}a.age=this.nextAge++}d<i&&h.push({start:d,end:i})}else h.push({start:r,end:i});if(c&&u>=c.length&&(a={bytes:c,view:o6(c),offset:e}),0===h.length)return oJ(a),a;let{promise:f,resolve:p,reject:m}=sh(),g=[];for(let n of h){let r=Math.max(e,n.start),i=Math.min(t,n.end);r===n.start&&i===n.end?g.push(n):r<i&&g.push({start:r,end:i})}for(let t of h){let n=c&&{start:e,bytes:c,holes:g,resolve:p,reject:m},r=!1;for(let e of this.workers)if(sz(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end),r=!0,n&&!e.pendingSlices.includes(n)&&e.pendingSlices.push(n),e.running||this.runWorker(e);break}if(!r){let e=this.createWorker(t.start,t.end);n&&(e.pendingSlices=[n]),this.runWorker(e)}}return a||(oJ(c),a=f.then(t=>({bytes:t,view:o6(t),offset:e}))),a}createWorker(e,t){let n={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(n);this.workers.length>this.options.maxWorkerCount;){let e=0,t=this.workers[0];for(let n=1;n<this.workers.length;n++){let r=this.workers[n];r.age<t.age&&(e=n,t=r)}if(t.running&&t.pendingSlices.length>0)break;t.aborted=!0,this.workers.splice(e,1)}return n}runWorker(e){oJ(!e.running),oJ(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)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){oJ(!e.aborted);let n=e.currentPos,r=n+t.length;this.insertIntoCache({start:n,end:r,bytes:t,view:o6(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let i=0;i<e.pendingSlices.length;i++){let a=e.pendingSlices[i],o=Math.max(n,a.start),s=Math.min(r,a.start+a.bytes.length);o<s&&a.bytes.set(t.subarray(o-n,s-n),o-a.start);for(let e=0;e<a.holes.length;e++){let t=a.holes[e];n<=t.start&&r>t.start&&(t.start=r),t.end<=t.start&&(a.holes.splice(e,1),e--)}0===a.holes.length&&(a.resolve(a.bytes),e.pendingSlices.splice(i,1),i--)}for(let t=0;t<this.workers.length;t++){let i=this.workers[t];e!==i&&!i.running&&sz(n,r,i.currentPos,i.targetPos)&&(this.workers.splice(t,1),t--)}}forgetWorker(e){let t=this.workers.indexOf(e);oJ(-1!==t),this.workers.splice(t,1)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=su(this.cache,e.start,e=>e.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let r=new Uint8Array(e.end-n.start);r.set(n.bytes,0),r.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=r,n.view=o6(r),n.end=e.end,t--,e=n}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 n=t+1;n<this.cache.length;n++){let t=this.cache[n];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(n,1),this.currentCacheSize-=t.bytes.length,n--;continue}let r=new Uint8Array(t.end-e.start);r.set(e.bytes,0),r.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=r,e.view=o6(r),e.end=t.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let n=1;n<this.cache.length;n++){let r=this.cache[n];r.age<t.age&&(e=n,t=r)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}sF();class lQ{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||"object"!=typeof e)throw TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof uB)))throw TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof lq))throw TypeError("options.source must be a Source.");if(e.source._disposed)throw Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new lT(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{for(let e of(this._reader.fileSize=await this._source.getSizeOrNull(),this._formats))if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),oJ(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getFirstTimestamp(){let e=await this.getTracks();return 0===e.length?0:Math.min(...await Promise.all(e.map(e=>e.getFirstTimestamp())))}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 lZ extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}let lJ=new Uint8Array(0);class l0{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===lJ&&void 0===a)throw Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===a&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw TypeError("duration must be a non-negative number.");if(!Number.isFinite(i))throw TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw TypeError("byteLength must be a non-negative integer.");if(void 0!==o&&("object"!=typeof o||!o))throw TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===lJ}get microsecondTimestamp(){return Math.trunc(sk*this.timestamp)}get microsecondDuration(){return Math.trunc(sk*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if("u"<typeof EncodedVideoChunk)throw 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 TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if("u"<typeof EncodedVideoChunk)throw 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 TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("u"<typeof EncodedAudioChunk)throw 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 TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let n=new Uint8Array(e.byteLength);return e.copyTo(n),new l0(n,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 TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&"key"!==e.type&&"delta"!==e.type)throw TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&("object"!=typeof e.sideData||null===e.sideData))throw TypeError("options.sideData, when provided, must be an object.");return new l0(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}sF();let l1=-1/0,l2=-1/0,l4=null;"u">typeof FinalizationRegistry&&(l4=new FinalizationRegistry(e=>{let t=Date.now();"video"===e.type?(t-l1>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),l1=t),"u">typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-l2>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),l2=t),"u">typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));let l3=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],l8=new Set(l3);class l6{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(sk*this.timestamp)}get microsecondDuration(){return Math.trunc(sk*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||"u">typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!=typeof t)throw TypeError("init must be an object.");if(void 0===t.format||!l8.has(t.format))throw TypeError("init.format must be one of: "+l3.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw TypeError("init.codedHeight must be a positive integer.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=o8(e).slice(),this._layout=t.layout??cn(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new l5(t.colorSpace)}else if("u">typeof VideoFrame&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new l5(e.colorSpace)}else if("u">typeof HTMLImageElement&&e instanceof HTMLImageElement||"u">typeof SVGImageElement&&e instanceof SVGImageElement||"u">typeof ImageBitmap&&e instanceof ImageBitmap||"u">typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"u">typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"u">typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!=typeof t)throw TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if("u">typeof VideoFrame)return new l6(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*sk),duration:Math.trunc((t.duration??0)*sk)||void 0}),t);let n=0,r=0;if("naturalWidth"in e?(n=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(n=e.videoWidth,r=e.videoHeight):"width"in e&&(n=Number(e.width),r=Number(e.height)),!n||!r)throw TypeError("Could not determine dimensions.");let i=new OffscreenCanvas(n,r),a=i.getContext("2d",{alpha:sR(),willReadFrequently:!0});oJ(a),a.drawImage(e,0,0),this._data=i,this._layout=null,this.format="RGBX",this.codedWidth=n,this.codedHeight=r,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new l5({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");l4?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw Error("VideoSample is closed.");return(oJ(null!==this._data),l9(this._data))?new l6(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(oJ(this._layout),new l6(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})):new l6(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||(l4?.unregister(this),l9(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(ct(e),this._closed)throw Error("VideoSample is closed.");if(null===this.format)throw Error("Cannot get allocation size when format is null. Sorry!");if(oJ(null!==this._data),!l9(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let t=this.toVideoFrame(),n=t.allocationSize(e);return t.close(),n}return l9(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!sa(e))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(ct(t),this._closed)throw Error("VideoSample is closed.");if(null===this.format)throw Error("Cannot copy video sample data when format is null. Sorry!");if(oJ(null!==this._data),!l9(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){let n=this.toVideoFrame(),r=await n.copyTo(e,t);return n.close(),r}if(l9(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array)return oJ(this._layout),o8(e).set(this._data),this._layout;{let t=this._data.getContext("2d");oJ(t);let n=t.getImageData(0,0,this.codedWidth,this.codedHeight);return o8(e).set(n.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw Error("VideoSample is closed.");return(oJ(null!==this._data),l9(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,n,r,i,a,o,s,l){let c=0,u=0,d=this.displayWidth,h=this.displayHeight,f=0,p=0,m=this.displayWidth,g=this.displayHeight;if(void 0!==a?(c=t,u=n,d=r,h=i,f=a,p=o,void 0!==s?(m=s,g=l):(m=d,g=h)):(f=t,p=n,void 0!==r&&(m=r,g=i)),!("u">typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"u">typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw TypeError("sx must be a number.");if(!Number.isFinite(u))throw TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw TypeError("dx must be a number.");if(!Number.isFinite(p))throw TypeError("dy must be a number.");if(!Number.isFinite(m)||m<0)throw TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw TypeError("dHeight must be a non-negative number.");if(this._closed)throw Error("VideoSample is closed.");({sx:c,sy:u,sWidth:d,sHeight:h}=this._rotateSourceRegion(c,u,d,h,this.rotation));let y=this.toCanvasImageSource();e.save();let v=f+m/2,b=p+g/2;e.translate(v,b),e.rotate(this.rotation*Math.PI/180);let x=this.rotation%180==0?1:m/g;e.scale(1/x,x),e.drawImage(y,c,u,d,h,-m/2,-g/2,m,g),e.restore()}drawWithFit(e,t){let n,r,i,a;if(!("u">typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"u">typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&ce(t.crop,"options.");let o=e.canvas.width,s=e.canvas.height,l=t.rotation??this.rotation,[c,u]=l%180==0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];t.crop&&l7(t.crop,c,u);let{sx:d,sy:h,sWidth:f,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??c,t.crop?.height??u,l);if("fill"===t.fit)n=0,r=0,i=o,a=s;else{let[e,l]=t.crop?[t.crop.width,t.crop.height]:[c,u],d="contain"===t.fit?Math.min(o/e,s/l):Math.max(o/e,s/l);i=e*d,a=l*d,n=(o-i)/2,r=(s-a)/2}e.save();let m=l%180==0?1:i/a;e.translate(o/2,s/2),e.rotate(l*Math.PI/180),e.scale(1/m,m),e.translate(-o/2,-s/2),e.drawImage(this.toCanvasImageSource(),d,h,f,p,n,r,i,a),e.restore()}_rotateSourceRegion(e,t,n,r,i){return 90===i?[e,t,n,r]=[t,this.codedHeight-e-n,r,n]:180===i?[e,t]=[this.codedWidth-e-n,this.codedHeight-t-r]:270===i&&([e,t,n,r]=[this.codedWidth-t-r,e,r,n]),{sx:e,sy:t,sWidth:n,sHeight:r}}toCanvasImageSource(){if(this._closed)throw Error("VideoSample is closed.");if(oJ(null!==this._data),!(this._data instanceof Uint8Array))return this._data;{let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}}setRotation(e){if(![0,90,180,270].includes(e))throw TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}class l5{constructor(e){this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}let l9=e=>"u">typeof VideoFrame&&e instanceof VideoFrame,l7=(e,t,n)=>{e.left=Math.min(e.left,t),e.top=Math.min(e.top,n),e.width=Math.min(e.width,t-e.left),e.height=Math.min(e.height,n-e.top),oJ(e.width>=0),oJ(e.height>=0)},ce=(e,t)=>{if(!e||"object"!=typeof e)throw TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(e.left)||e.left<0)throw TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(e.top)||e.top<0)throw TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(e.width)||e.width<0)throw TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(e.height)||e.height<0)throw TypeError(t+"crop.height must be a non-negative integer.")},ct=e=>{if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.colorSpace&&!["display-p3","srgb"].includes(e.colorSpace))throw TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(void 0!==e.format&&"string"!=typeof e.format)throw TypeError("options.format, when provided, must be a string.");if(void 0!==e.layout){if(!Array.isArray(e.layout))throw TypeError("options.layout, when provided, must be an array.");for(let t of e.layout){if(!t||"object"!=typeof t)throw TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==e.rect){if(!e.rect||"object"!=typeof e.rect)throw TypeError("options.rect, when provided, must be an object.");if(void 0!==e.rect.x&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==e.rect.y&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==e.rect.width&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==e.rect.height&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw TypeError("options.rect.height, when provided, must be a non-negative integer.")}},cn=(e,t,n)=>{let r=cr(e),i=[],a=0;for(let e of r){let r=Math.ceil(t/e.widthDivisor),o=Math.ceil(n/e.heightDivisor),s=r*e.sampleBytes,l=s*o;i.push({offset:a,stride:s}),a+=l}return i},cr=e=>{let t=(e,t,n,r,i)=>{let a=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:n,heightDivisor:r},{sampleBytes:t,widthDivisor:n,heightDivisor:r}];return i&&a.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),a};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:sg(e),oJ(!1)}},ci=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class ca{get microsecondTimestamp(){return Math.trunc(sk*this.timestamp)}get microsecondDuration(){return Math.trunc(sk*this.duration)}constructor(e){if(this._closed=!1,cu(e)){if(null===e.format)throw 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{let t;if(!e||"object"!=typeof e)throw TypeError("Invalid AudioDataInit: must be an object.");if(!ci.has(e.format))throw TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw TypeError("init.timestamp must be a number.");let n=e.data.byteLength/(co(e.format)*e.numberOfChannels);if(!Number.isInteger(n))throw TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");if(this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=n,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=n/e.sampleRate,e.data instanceof ArrayBuffer)t=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))t=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw TypeError("Invalid AudioDataInit: data is not a BufferSource.");let r=this.numberOfFrames*this.numberOfChannels*co(this.format);if(t.byteLength<r)throw TypeError("Invalid AudioDataInit: insufficient data size.");this._data=t}l4?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if(void 0!==e.format&&!ci.has(e.format))throw TypeError("Invalid format.");if(void 0!==e.frameOffset&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if(void 0!==e.frameCount&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw RangeError("frameOffset out of range");let r=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-n;if(r>this.numberOfFrames-n)throw RangeError("frameCount out of range");let i=co(t),a=cs(t);if(a&&e.planeIndex>=this.numberOfChannels||!a&&0!==e.planeIndex)throw RangeError("planeIndex out of range");return(a?r:r*this.numberOfChannels)*i}copyTo(e,t){if(!sa(e))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if(void 0!==t.format&&!ci.has(t.format))throw TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let{planeIndex:n,format:r,frameCount:i,frameOffset:a}=t,o=this.format,s=r??this.format;if(!s)throw Error("Destination format not determined");let l=this.numberOfFrames,c=this.numberOfChannels,u=a??0;if(u>=l)throw RangeError("frameOffset out of range");let d=void 0!==i?i:l-u;if(d>l-u)throw RangeError("frameCount out of range");let h=co(s),f=cs(s);if(f&&n>=c||!f&&0!==n)throw RangeError("planeIndex out of range");let p=f?d:d*c;if(e.byteLength<p*h)throw RangeError("Destination buffer is too small");let m=o6(e),g=cc(s);if(cu(this._data))sA()&&c>2&&s!==o?cd(this._data,m,o,s,c,n,u,d):this._data.copyTo(e,{planeIndex:n,frameOffset:u,frameCount:d,format:s});else{let e=o6(this._data),t=cl(o),r=co(o),i=cs(o);for(let a=0;a<d;a++)if(f)g(m,a*h,t(e,i?(n*l+(a+u))*r:((a+u)*c+n)*r));else for(let n=0;n<c;n++)g(m,(a*c+n)*h,t(e,i?(n*l+(a+u))*r:((a+u)*c+n)*r))}}clone(){if(this._closed)throw Error("AudioSample is closed.");if(!cu(this._data))return new ca({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data});{let e=new ca(this._data.clone());return e.setTimestamp(this.timestamp),e}}close(){this._closed||(l4?.unregister(this),cu(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw Error("AudioSample is closed.");if(!cu(this._data))return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()});if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(cs(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}{let 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})}}toAudioBuffer(){if(this._closed)throw Error("AudioSample is closed.");let 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 n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let n=e.numberOfChannels,r=e.sampleRate,i=e.length,a=Math.floor(24e4/n),o=0,s=i;for(;s>0;){let i=Math.min(a,s),l=new Float32Array(n*i);for(let t=0;t<n;t++)e.copyFromChannel(l.subarray(t*i,(t+1)*i),t,o);yield new ca({format:"f32-planar",sampleRate:r,numberOfFrames:i,numberOfChannels:n,timestamp:t+o/r,data:l}),o+=i,s-=i}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let n=e.numberOfChannels,r=e.sampleRate,i=e.length,a=Math.floor(24e4/n),o=0,s=i,l=[];for(;s>0;){let i=Math.min(a,s),c=new Float32Array(n*i);for(let t=0;t<n;t++)e.copyFromChannel(c.subarray(t*i,(t+1)*i),t,o);let u=new ca({format:"f32-planar",sampleRate:r,numberOfFrames:i,numberOfChannels:n,timestamp:t+o/r,data:c});l.push(u),o+=i,s-=i}return l}}let co=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 Error("Unknown AudioSampleFormat")}},cs=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},cl=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)/0x80000000;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},cc=e=>{switch(e){case"u8":case"u8-planar":return(e,t,n)=>e.setUint8(t,sx((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,n)=>e.setInt16(t,sx(Math.round(32767*n),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,n)=>e.setInt32(t,sx(Math.round(0x7fffffff*n),-0x80000000,0x7fffffff),!0);case"f32":case"f32-planar":return(e,t,n)=>e.setFloat32(t,n,!0)}},cu=e=>"u">typeof AudioData&&e instanceof AudioData,cd=(e,t,n,r,i,a,o,s)=>{let l=cl(n),c=cc(r),u=co(n),d=co(r),h=cs(n);if(cs(r))if(h){let r=new ArrayBuffer(s*u),i=o6(r);e.copyTo(r,{planeIndex:a,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;c(t,e*d,l(i,n))}}else{let r=new ArrayBuffer(s*i*u),h=o6(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=(e*i+a)*u;c(t,e*d,l(h,n))}}else if(h){let r=new ArrayBuffer(s*u),a=o6(r);for(let h=0;h<i;h++){e.copyTo(r,{planeIndex:h,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;c(t,(e*i+h)*d,l(a,n))}}}else{let r=new ArrayBuffer(s*i*u),a=o6(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++)for(let n=0;n<i;n++){let r=e*i+n,o=r*u;c(t,r*d,l(a,o))}}},ch=e=>{if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.metadataOnly&&"boolean"!=typeof e.metadataOnly)throw TypeError("options.metadataOnly, when defined, must be a boolean.");if(void 0!==e.verifyKeyPackets&&"boolean"!=typeof e.verifyKeyPackets)throw TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},cf=e=>{if(!sH(e))throw TypeError("timestamp must be a number.")},cp=(e,t,n)=>n.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;let n=await e.determinePacketType(t);return n&&(t.type=n),t}):t;class cm{constructor(e){if(!(e instanceof cS))throw TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(ch(e),this._track.input._disposed)throw new lZ;return cp(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(cf(e),ch(t),this._track.input._disposed)throw new lZ;return cp(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof l0))throw TypeError("packet must be an EncodedPacket.");if(ch(t),this._track.input._disposed)throw new lZ;return cp(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(cf(e),ch(t),this._track.input._disposed)throw new lZ;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(oJ("key"===n.type),"delta"===await this._track.determinePacketType(n))?this.getKeyPacket(n.timestamp-1/this._track.timeResolution,t):n}async getNextKeyPacket(e,t={}){if(!(e instanceof l0))throw TypeError("packet must be an EncodedPacket.");if(ch(t),this._track.input._disposed)throw new lZ;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(oJ("key"===n.type),"delta"===await this._track.determinePacketType(n))?this.getNextKeyPacket(n,t):n}packets(e,t,n={}){if(void 0!==e&&!(e instanceof l0))throw TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!n?.metadataOnly)throw TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof l0))throw TypeError("endPacket must be an EncodedPacket.");if(ch(n),this._track.input._disposed)throw new lZ;let r=[],{promise:i,resolve:a}=sh(),{promise:o,resolve:s}=sh(),l=!1,c=!1,u=null,d=[],h=()=>Math.max(2,d.length);(async()=>{let u=e??await this.getFirstPacket(n);for(;u&&!c&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(r.length>h()){({promise:o,resolve:s}=sh()),await o;continue}r.push(u),a(),({promise:i,resolve:a}=sh()),u=await this.getNextPacket(u,n)}l=!0,a()})().catch(e=>{u||(u=e,a())});let f=this._track;return{async next(){for(;;)if(f.input._disposed)throw new lZ;else if(c)return{value:void 0,done:!0};else if(u)throw u;else if(r.length>0){let e=r.shift(),t=performance.now();for(d.push(t);d.length>0&&t-d[0]>=1e3;)d.shift();return s(),{value:e,done:!1}}else{if(l)return{value:void 0,done:!0};await i}},return:async()=>(c=!0,s(),a(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class cg{constructor(e,t){this.onSample=e,this.onError=t}}class cy{mediaSamplesInRange(e=0,t=1/0){cf(e),cf(t);let n=[],r=!1,i=null,{promise:a,resolve:o}=sh(),{promise:s,resolve:l}=sh(),c=!1,u=!1,d=!1,h=null;(async()=>{let f=await this._createDecoder(s=>{(l(),s.timestamp>=t&&(u=!0),u)?s.close():(i&&(s.timestamp>e?(n.push(i),r=!0):i.close()),s.timestamp>=e&&(n.push(s),r=!0),i=r?null:s,n.length>0&&(o(),{promise:a,resolve:o}=sh()))},e=>{h||(h=e,o())}),p=this._createPacketSink(),m=await p.getKeyPacket(e,{verifyKeyPackets:!0})??await p.getFirstPacket(),g=m,y=p.packets(m??void 0,void 0);for(await y.next();g&&!u&&!this._track.input._disposed;){let e=cv(n.length);if(n.length+f.getDecodeQueueSize()>e){({promise:s,resolve:l}=sh()),await s;continue}f.decode(g);let t=await y.next();if(t.done)break;g=t.value}await y.return(),d||this._track.input._disposed||await f.flush(),f.close(),!r&&i&&n.push(i),c=!0,o()})().catch(e=>{h||(h=e,o())});let f=this._track,p=()=>{for(let e of(i?.close(),n))e.close()};return{async next(){for(;;)if(f.input._disposed)throw p(),new lZ;else if(d)return{value:void 0,done:!0};else if(h)throw p(),h;else if(n.length>0){let e=n.shift();return l(),{value:e,done:!1}}else{if(c)return{value:void 0,done:!0};await a}},return:async()=>(d=!0,u=!0,l(),o(),p(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError("Argument must be an iterable or async iterable.");let t=sm(e),n=[],r=[],{promise:i,resolve:a}=sh(),{promise:o,resolve:s}=sh(),l=!1,c=!1,u=null,d=e=>{r.push(e),a(),{promise:i,resolve:a}=sh()};(async()=>{let e=await this._createDecoder(e=>{if(s(),c)return void e.close();let t=0;for(;n.length>0&&e.timestamp-n[0]>-1e-10;)t++,n.shift();if(t>0)for(let n=0;n<t;n++)d(n<t-1?e.clone():e);else e.close()},e=>{u||(u=e,a())}),i=this._createPacketSink(),h=null,f=null,p=-1,m=async()=>{oJ(f);let t=f;for(e.decode(t);t.sequenceNumber<p;){let n=cv(r.length);for(;r.length+e.getDecodeQueueSize()>n&&!c;)({promise:o,resolve:s}=sh()),await o;if(c)break;let a=await i.getNextPacket(t);oJ(a),e.decode(a),t=a}p=-1},g=async()=>{await e.flush();for(let e=0;e<n.length;e++)d(null);n.length=0};for await(let e of t){if(cf(e),c||this._track.input._disposed)break;let t=await i.getPacket(e),r=t&&await i.getKeyPacket(e,{verifyKeyPackets:!0});if(!r){-1!==p&&(await m(),await g()),d(null),h=null;continue}h&&(r.sequenceNumber!==f.sequenceNumber||t.timestamp<h.timestamp)&&(await m(),await g()),n.push(t.timestamp),p=Math.max(t.sequenceNumber,p),h=t,f=r}c||this._track.input._disposed||(-1!==p&&await m(),await g()),e.close(),l=!0,a()})().catch(e=>{u||(u=e,a())});let h=this._track,f=()=>{for(let e of r)e?.close()};return{async next(){for(;;)if(h.input._disposed)throw f(),new lZ;else if(c)return{value:void 0,done:!0};else if(u)throw f(),u;else if(r.length>0){let e=r.shift();return oJ(void 0!==e),s(),{value:e,done:!1}}else{if(l)return{value:void 0,done:!0};await i}},return:async()=>(c=!0,s(),a(),f(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}let cv=e=>0===e?40:8;class cb extends cg{constructor(e,t,n,r,i,a){super(e,t),this.codec=n,this.decoderConfig=r,this.rotation=i,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new sP,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;let o=l_.find(e=>e.supports(n,r));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof l6))throw TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let e=e=>{if(this.alphaQueue.length>0){let t=this.alphaQueue.shift();oJ(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===n&&this.decoderConfig.description&&sM()){let e=(e=>{try{let t=o6(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=t.getUint8(n++),o=t.getUint8(n++),s=3&t.getUint8(n++),l=31&t.getUint8(n++),c=[];for(let r=0;r<l;r++){let r=t.getUint16(n,!1);n+=2,c.push(e.subarray(n,n+r)),n+=r}let u=t.getUint8(n++),d=[];for(let r=0;r<u;r++){let r=t.getUint16(n,!1);n+=2,d.push(e.subarray(n,n+r)),n+=r}let h={configurationVersion:r,avcProfileIndication:i,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:s,sequenceParameterSets:c,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===i||110===i||122===i||144===i)&&n+4<=e.length){let r=3&t.getUint8(n++),i=7&t.getUint8(n++),a=7&t.getUint8(n++),o=t.getUint8(n++);h.chromaFormat=r,h.bitDepthLumaMinus8=i,h.bitDepthChromaMinus8=a;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}h.sequenceParameterSetExt=s}return h}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}})(o8(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=s9(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let t=Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(oJ(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(oJ(this.decoder),sA()||sd(this.inputTimestamps,e.timestamp,e=>e),sM()&&0===this.currentPacketIndex&&"avc"===this.codec){let t=[];for(let n of s4(e.data,this.decoderConfig)){let r=s3(e.data[n.offset]);r>=20&&r<=31||t.push(e.data.subarray(n.offset,n.offset+n.length))}e=new l0(((e,t)=>{if(t.description)return((e,t)=>{let n=new Uint8Array(e.reduce((e,n)=>e+t+n.byteLength,0)),r=0;for(let i of e){let e=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(t){case 1:e.setUint8(r,i.byteLength);break;case 2:e.setUint16(r,i.byteLength,!1);break;case 3:sv(e,r,i.byteLength,!1);break;case 4:e.setUint32(r,i.byteLength,!1)}r+=t,n.set(i,r),r+=i.byteLength}return n})(e,(3&o8(t.description)[4])+1);let n=new Uint8Array(e.reduce((e,t)=>e+s6.byteLength+t.byteLength,0)),r=0;for(let t of e)n.set(s6,r),r+=s6.byteLength,n.set(t,r),r+=t.byteLength;return n})(t,this.decoderConfig),e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed)return void this.pushNullAlphaFrame();if(!this.merger)try{this.merger=new cx}catch(t){console.error("Due to an error, only color data will be decoded.",t),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let t=this.colorQueue.shift();oJ(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){let e=this.colorQueue.shift();oJ(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)},t=Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=lm(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){for(let t of le(e,this.decoderConfig)){let n=lt(e[t.offset]);if(n===jP.RASL_N||n===jP.RASL_R)return!0}return!1}sampleHandler(e){if(sA()){if(this.sampleQueue.length>0&&e.timestamp>=o1(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}sd(this.sampleQueue,e,e=>e.timestamp)}else{let t=this.inputTimestamps.shift();oJ(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){let t=new l6(e);this.sampleHandler(t);return}oJ(this.merger),this.merger.update(e,t),e.close(),t.close();let n=new l6(new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}));this.sampleHandler(n)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(oJ(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),sA()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){for(let e of(this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(oJ(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()),this.sampleQueue))e.close();this.sampleQueue.length=0}}class cx{constructor(){"u">typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw 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(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
184
184
|
in vec2 a_position;
|
|
185
185
|
in vec2 a_texCoord;
|
|
186
186
|
out vec2 v_texCoord;
|
package/utils/clipboard.d.ts
CHANGED
package/utils/clipboard.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{forEveryChild as e}from"../model/group-model.js";import{getTotalClientRect as t}from"./math.js";let a={data:[],pageId:""};const o="polotno_clipboard",l=(e,t)=>{a={data:JSON.parse(JSON.stringify(e)),pageId:t||""};try{localStorage.setItem(o,JSON.stringify(e)),localStorage.setItem(o+"_page",t||"")}catch(l){}},
|
|
1
|
+
import{forEveryChild as e}from"../model/group-model.js";import{getTotalClientRect as t}from"./math.js";let a={data:[],pageId:""};const o="polotno_clipboard",l=(e,t)=>{a={data:JSON.parse(JSON.stringify(e)),pageId:t||""};try{localStorage.setItem(o,JSON.stringify(e)),localStorage.setItem(o+"_page",t||"")}catch(l){}},r=()=>{try{const e=localStorage.getItem(o),t=localStorage.getItem(o+"_page");if(e){return{data:JSON.parse(e),pageId:t}}}catch(e){}return a};export const copy=e=>{var t;0!==e.selectedElements.length&&l(e.selectedElements.map(e=>e.toJSON()),null===(t=e.activePage)||void 0===t?void 0:t.id)};export const cut=e=>{var t;l(e.selectedElements.map(e=>e.toJSON()),null===(t=e.activePage)||void 0===t?void 0:t.id);let a=e.selectedElements.filter(e=>e.removable).map(e=>e.id);e.deleteElements(a)};export const paste=a=>{a.history.transaction(()=>{var o,d;let i=0,c=0;const{data:s,pageId:n}=r();if(n===(null===(o=a.activePage)||void 0===o?void 0:o.id)){i=a.width/20,c=a.height/20}else{const o=[];e({children:s},e=>{"group"!==e.type&&o.push(e)});const l=t(o);l.maxX>a.width&&(i=-l.minX),l.maxY>a.height&&(c=-l.minY)}const p=[];e({children:s},e=>{delete e.id,"group"!==e.type&&(e.x+=i,e.y+=c)}),s.forEach(e=>{var t;const o=null===(t=a.activePage)||void 0===t?void 0:t.addElement(e);o&&p.push(o.id)}),l(s,null===(d=a.activePage)||void 0===d?void 0:d.id),a.selectElements(p)})};export const isClipboardEmpty=()=>0===r().data.length;export const resetClipboard=()=>{a={data:[],pageId:""};try{localStorage.removeItem(o),localStorage.removeItem(o+"_page")}catch(e){}};
|
package/utils/validate-key.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as e from"mobx";import{getAPI as o}from"./api.js";import{setRemoveBackgroundEnabled as t}from"./flags.js";const n=e.observable({value:!1}),a=e.observable({value:"v1"});export const ___=()=>a.value;const i=e.observable({value:0});export const ____=()=>i.value;export const isCreditVisible=()=>n.value;const r=e.action(()=>{n.value=!0});let s="";export const getKey=()=>s||"";let l="undefined"!=typeof window?window.location.origin:"";const c="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,d="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===l&&c&&(l="headless"),"file://"===l&&d&&(l="electron");const p=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${l}" here: https://polotno.com/cabinet`;let u=fetch;export const __=e=>{u=e};export async function isKeyPaid(n){for(let s=0;s<5;s++){try{const r=await u(o()+"/validate-key",{method:"POST",body:JSON.stringify({key:n,site:location.host,skdVersion:"2.36.
|
|
1
|
+
import*as e from"mobx";import{getAPI as o}from"./api.js";import{setRemoveBackgroundEnabled as t}from"./flags.js";const n=e.observable({value:!1}),a=e.observable({value:"v1"});export const ___=()=>a.value;const i=e.observable({value:0});export const ____=()=>i.value;export const isCreditVisible=()=>n.value;const r=e.action(()=>{n.value=!0});let s="";export const getKey=()=>s||"";let l="undefined"!=typeof window?window.location.origin:"";const c="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,d="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===l&&c&&(l="headless"),"file://"===l&&d&&(l="electron");const p=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${l}" here: https://polotno.com/cabinet`;let u=fetch;export const __=e=>{u=e};export async function isKeyPaid(n){for(let s=0;s<5;s++){try{const r=await u(o()+"/validate-key",{method:"POST",body:JSON.stringify({key:n,site:location.host,skdVersion:"2.36.10"})});if(e.runInAction(()=>{a.value=r.headers.get("x-api-version")||""}),!n){return console.error("Polotno API is initialized without API key. It may lead to unexpected behavior and stop working. Please create API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1}),!1}if(200!==r.status){await new Promise(e=>setTimeout(e,3e3));continue}const s=await r.json();return s.is_valid||(console.error("Polotno API key is not valid. Please get new API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1})),s.is_paid||(console.log("%cPolotno Free Version. For development usage only. https://polotno.com/","background: rgb(0, 161, 255); color: white; padding: 5px; margin: 5px;"),e.runInAction(()=>{0===i.value&&(i.value=2)})),s.is_domain_valid||console.log(p,"background: rgba(247, 101, 68, 1); color: white; padding: 5px; margin: 5px;"),t(s.remove_background_enabled),s.is_paid||!1}catch(r){await new Promise(e=>setTimeout(e,3e3))}}return console.error("Can not validate Polotno API key. Please report to anton@polotno.com immediately."),!0}export async function validateKey(e,o){s=e,await isKeyPaid(e)&&!o||r()}
|