@omnimedia/omnitool 1.1.0-60 → 1.1.0-62
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/package.json +1 -1
- package/s/demo/routines/playback-test.ts +2 -17
- package/s/driver/fns/work.ts +3 -4
- package/s/timeline/renderers/player/parts/playback.ts +5 -2
- package/s/timeline/renderers/player/player.ts +19 -9
- package/x/demo/demo.bundle.min.js +4 -4
- package/x/demo/demo.bundle.min.js.map +3 -3
- package/x/demo/routines/playback-test.js +2 -16
- package/x/demo/routines/playback-test.js.map +1 -1
- package/x/driver/driver.worker.bundle.min.js +7 -11
- package/x/driver/driver.worker.bundle.min.js.map +4 -4
- package/x/driver/fns/work.js +0 -2
- package/x/driver/fns/work.js.map +1 -1
- package/x/index.html +2 -2
- package/x/tests.bundle.min.js +5 -5
- package/x/tests.bundle.min.js.map +3 -3
- package/x/tests.html +1 -1
- package/x/timeline/renderers/player/parts/playback.d.ts +2 -1
- package/x/timeline/renderers/player/parts/playback.js +4 -2
- package/x/timeline/renderers/player/parts/playback.js.map +1 -1
- package/x/timeline/renderers/player/player.d.ts +2 -2
- package/x/timeline/renderers/player/player.js +17 -10
- package/x/timeline/renderers/player/player.js.map +1 -1
- package/x/driver/WebGLRenderer-OMRWYQIV.js +0 -2
- package/x/driver/WebGLRenderer-OMRWYQIV.js.map +0 -7
- package/x/driver/WebGPURenderer-KQJB2OJJ.js +0 -2
- package/x/driver/WebGPURenderer-KQJB2OJJ.js.map +0 -7
- package/x/driver/browserAll-YBZEJCN3.js +0 -2
- package/x/driver/browserAll-YBZEJCN3.js.map +0 -7
- package/x/driver/chunk-3L3MB5NY.js +0 -393
- package/x/driver/chunk-3L3MB5NY.js.map +0 -7
- package/x/driver/chunk-42BQ4XKE.js +0 -269
- package/x/driver/chunk-42BQ4XKE.js.map +0 -7
- package/x/driver/chunk-4HAYG3N5.js +0 -327
- package/x/driver/chunk-4HAYG3N5.js.map +0 -7
- package/x/driver/chunk-BFBY7VYB.js +0 -42
- package/x/driver/chunk-BFBY7VYB.js.map +0 -7
- package/x/driver/chunk-KM6O72WE.js +0 -157
- package/x/driver/chunk-KM6O72WE.js.map +0 -7
- package/x/driver/chunk-N6HD4WYJ.js +0 -2
- package/x/driver/chunk-N6HD4WYJ.js.map +0 -7
- package/x/driver/chunk-WCZ2O3UN.js +0 -15
- package/x/driver/chunk-WCZ2O3UN.js.map +0 -7
- package/x/driver/chunk-XWNSF3WJ.js +0 -2
- package/x/driver/chunk-XWNSF3WJ.js.map +0 -7
- package/x/driver/webworkerAll-BKJQW6P7.js +0 -2
- package/x/driver/webworkerAll-BKJQW6P7.js.map +0 -7
|
@@ -1,14 +1,10 @@
|
|
|
1
|
-
import"./chunk-WCZ2O3UN.js";import"./chunk-3L3MB5NY.js";import"./chunk-BFBY7VYB.js";import"./chunk-N6HD4WYJ.js";import"./chunk-KM6O72WE.js";import"./chunk-4HAYG3N5.js";import{Q as ms,a as Kt,b as ml,c as zi,d as Lo}from"./chunk-42BQ4XKE.js";var Qr=Kt(er=>{"use strict";function vl(t,e,r){if(r===void 0&&(r=Array.prototype),t&&typeof r.find=="function")return r.find.call(t,e);for(var i=0;i<t.length;i++)if(Object.prototype.hasOwnProperty.call(t,i)){var n=t[i];if(e.call(void 0,n,i,t))return n}}function xs(t,e){return e===void 0&&(e=Object),e&&typeof e.freeze=="function"?e.freeze(t):t}function _l(t,e){if(t===null||typeof t!="object")throw new TypeError("target is not an object");for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}var ua=xs({HTML:"text/html",isHTML:function(t){return t===ua.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),la=xs({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(t){return t===la.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"});er.assign=_l;er.find=vl;er.freeze=xs;er.MIME_TYPE=ua;er.NAMESPACE=la});var Ds=Kt(ft=>{var wa=Qr(),Ue=wa.find,Xr=wa.NAMESPACE;function Pl(t){return t!==""}function Dl(t){return t?t.split(/[\t\n\f\r ]+/).filter(Pl):[]}function Il(t,e){return t.hasOwnProperty(e)||(t[e]=!0),t}function da(t){if(!t)return[];var e=Dl(t);return Object.keys(e.reduce(Il,{}))}function Fl(t){return function(e){return t&&t.indexOf(e)!==-1}}function Yr(t,e){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}function pe(t,e){var r=t.prototype;if(!(r instanceof e)){let n=function(){};var i=n;n.prototype=e.prototype,n=new n,Yr(r,n),t.prototype=r=n}r.constructor!=t&&(typeof t!="function"&&console.error("unknown Class:"+t),r.constructor=t)}var ge={},_e=ge.ELEMENT_NODE=1,rr=ge.ATTRIBUTE_NODE=2,rn=ge.TEXT_NODE=3,xa=ge.CDATA_SECTION_NODE=4,ya=ge.ENTITY_REFERENCE_NODE=5,Bl=ge.ENTITY_NODE=6,Ta=ge.PROCESSING_INSTRUCTION_NODE=7,ka=ge.COMMENT_NODE=8,Sa=ge.DOCUMENT_NODE=9,Ca=ge.DOCUMENT_TYPE_NODE=10,Ye=ge.DOCUMENT_FRAGMENT_NODE=11,Rl=ge.NOTATION_NODE=12,le={},oe={},n0=le.INDEX_SIZE_ERR=(oe[1]="Index size error",1),s0=le.DOMSTRING_SIZE_ERR=(oe[2]="DOMString size error",2),he=le.HIERARCHY_REQUEST_ERR=(oe[3]="Hierarchy request error",3),o0=le.WRONG_DOCUMENT_ERR=(oe[4]="Wrong document",4),a0=le.INVALID_CHARACTER_ERR=(oe[5]="Invalid character",5),c0=le.NO_DATA_ALLOWED_ERR=(oe[6]="No data allowed",6),u0=le.NO_MODIFICATION_ALLOWED_ERR=(oe[7]="No modification allowed",7),Ea=le.NOT_FOUND_ERR=(oe[8]="Not found",8),l0=le.NOT_SUPPORTED_ERR=(oe[9]="Not supported",9),fa=le.INUSE_ATTRIBUTE_ERR=(oe[10]="Attribute in use",10),d0=le.INVALID_STATE_ERR=(oe[11]="Invalid state",11),f0=le.SYNTAX_ERR=(oe[12]="Syntax error",12),m0=le.INVALID_MODIFICATION_ERR=(oe[13]="Invalid modification",13),h0=le.NAMESPACE_ERR=(oe[14]="Invalid namespace",14),p0=le.INVALID_ACCESS_ERR=(oe[15]="Invalid access",15);function K(t,e){if(e instanceof Error)var r=e;else r=this,Error.call(this,oe[t]),this.message=oe[t],Error.captureStackTrace&&Error.captureStackTrace(this,K);return r.code=t,e&&(this.message=this.message+": "+e),r}K.prototype=Error.prototype;Yr(le,K);function Ke(){}Ke.prototype={length:0,item:function(t){return t>=0&&t<this.length?this[t]:null},toString:function(t,e){for(var r=[],i=0;i<this.length;i++)tr(this[i],r,t,e);return r.join("")},filter:function(t){return Array.prototype.filter.call(this,t)},indexOf:function(t){return Array.prototype.indexOf.call(this,t)}};function ir(t,e){this._node=t,this._refresh=e,ks(this)}function ks(t){var e=t._node._inc||t._node.ownerDocument._inc;if(t._inc!==e){var r=t._refresh(t._node);if(Ma(t,"length",r.length),!t.$$length||r.length<t.$$length)for(var i=r.length;i in t;i++)Object.prototype.hasOwnProperty.call(t,i)&&delete t[i];Yr(r,t),t._inc=e}}ir.prototype.item=function(t){return ks(this),this[t]||null};pe(ir,Ke);function nn(){}function Aa(t,e){for(var r=t.length;r--;)if(t[r]===e)return r}function ma(t,e,r,i){if(i?e[Aa(e,i)]=r:e[e.length++]=r,t){r.ownerElement=t;var n=t.ownerDocument;n&&(i&&Pa(n,t,i),Ol(n,t,r))}}function ha(t,e,r){var i=Aa(e,r);if(i>=0){for(var n=e.length-1;i<n;)e[i]=e[++i];if(e.length=n,t){var s=t.ownerDocument;s&&(Pa(s,t,r),r.ownerElement=null)}}else throw new K(Ea,new Error(t.tagName+"@"+r))}nn.prototype={length:0,item:Ke.prototype.item,getNamedItem:function(t){for(var e=this.length;e--;){var r=this[e];if(r.nodeName==t)return r}},setNamedItem:function(t){var e=t.ownerElement;if(e&&e!=this._ownerElement)throw new K(fa);var r=this.getNamedItem(t.nodeName);return ma(this._ownerElement,this,t,r),r},setNamedItemNS:function(t){var e=t.ownerElement,r;if(e&&e!=this._ownerElement)throw new K(fa);return r=this.getNamedItemNS(t.namespaceURI,t.localName),ma(this._ownerElement,this,t,r),r},removeNamedItem:function(t){var e=this.getNamedItem(t);return ha(this._ownerElement,this,e),e},removeNamedItemNS:function(t,e){var r=this.getNamedItemNS(t,e);return ha(this._ownerElement,this,r),r},getNamedItemNS:function(t,e){for(var r=this.length;r--;){var i=this[r];if(i.localName==e&&i.namespaceURI==t)return i}return null}};function va(){}va.prototype={hasFeature:function(t,e){return!0},createDocument:function(t,e,r){var i=new Zr;if(i.implementation=this,i.childNodes=new Ke,i.doctype=r||null,r&&i.appendChild(r),e){var n=i.createElementNS(t,e);i.appendChild(n)}return i},createDocumentType:function(t,e,r){var i=new an;return i.name=t,i.nodeName=t,i.publicId=e||"",i.systemId=r||"",i}};function H(){}H.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(t,e){return sn(this,t,e)},replaceChild:function(t,e){sn(this,t,e,Ia),e&&this.removeChild(e)},removeChild:function(t){return Da(this,t)},appendChild:function(t){return this.insertBefore(t,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(t){return Ts(this.ownerDocument||this,this,t)},normalize:function(){for(var t=this.firstChild;t;){var e=t.nextSibling;e&&e.nodeType==rn&&t.nodeType==rn?(this.removeChild(e),t.appendData(e.data)):(t.normalize(),t=e)}},isSupported:function(t,e){return this.ownerDocument.implementation.hasFeature(t,e)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(t){for(var e=this;e;){var r=e._nsMap;if(r){for(var i in r)if(Object.prototype.hasOwnProperty.call(r,i)&&r[i]===t)return i}e=e.nodeType==rr?e.ownerDocument:e.parentNode}return null},lookupNamespaceURI:function(t){for(var e=this;e;){var r=e._nsMap;if(r&&Object.prototype.hasOwnProperty.call(r,t))return r[t];e=e.nodeType==rr?e.ownerDocument:e.parentNode}return null},isDefaultNamespace:function(t){var e=this.lookupPrefix(t);return e==null}};function _a(t){return t=="<"&&"<"||t==">"&&">"||t=="&"&&"&"||t=='"'&&"""||"&#"+t.charCodeAt()+";"}Yr(ge,H);Yr(ge,H.prototype);function Kr(t,e){if(e(t))return!0;if(t=t.firstChild)do if(Kr(t,e))return!0;while(t=t.nextSibling)}function Zr(){this.ownerDocument=this}function Ol(t,e,r){t&&t._inc++;var i=r.namespaceURI;i===Xr.XMLNS&&(e._nsMap[r.prefix?r.localName:""]=r.value)}function Pa(t,e,r,i){t&&t._inc++;var n=r.namespaceURI;n===Xr.XMLNS&&delete e._nsMap[r.prefix?r.localName:""]}function Ss(t,e,r){if(t&&t._inc){t._inc++;var i=e.childNodes;if(r)i[i.length++]=r;else{for(var n=e.firstChild,s=0;n;)i[s++]=n,n=n.nextSibling;i.length=s,delete i[i.length]}}}function Da(t,e){var r=e.previousSibling,i=e.nextSibling;return r?r.nextSibling=i:t.firstChild=i,i?i.previousSibling=r:t.lastChild=r,e.parentNode=null,e.previousSibling=null,e.nextSibling=null,Ss(t.ownerDocument,t),e}function Nl(t){return t&&(t.nodeType===H.DOCUMENT_NODE||t.nodeType===H.DOCUMENT_FRAGMENT_NODE||t.nodeType===H.ELEMENT_NODE)}function Ml(t){return t&&(ze(t)||Cs(t)||Ze(t)||t.nodeType===H.DOCUMENT_FRAGMENT_NODE||t.nodeType===H.COMMENT_NODE||t.nodeType===H.PROCESSING_INSTRUCTION_NODE)}function Ze(t){return t&&t.nodeType===H.DOCUMENT_TYPE_NODE}function ze(t){return t&&t.nodeType===H.ELEMENT_NODE}function Cs(t){return t&&t.nodeType===H.TEXT_NODE}function pa(t,e){var r=t.childNodes||[];if(Ue(r,ze)||Ze(e))return!1;var i=Ue(r,Ze);return!(e&&i&&r.indexOf(i)>r.indexOf(e))}function ga(t,e){var r=t.childNodes||[];function i(s){return ze(s)&&s!==e}if(Ue(r,i))return!1;var n=Ue(r,Ze);return!(e&&n&&r.indexOf(n)>r.indexOf(e))}function Ul(t,e,r){if(!Nl(t))throw new K(he,"Unexpected parent node type "+t.nodeType);if(r&&r.parentNode!==t)throw new K(Ea,"child not in parent");if(!Ml(e)||Ze(e)&&t.nodeType!==H.DOCUMENT_NODE)throw new K(he,"Unexpected node type "+e.nodeType+" for parent node type "+t.nodeType)}function zl(t,e,r){var i=t.childNodes||[],n=e.childNodes||[];if(e.nodeType===H.DOCUMENT_FRAGMENT_NODE){var s=n.filter(ze);if(s.length>1||Ue(n,Cs))throw new K(he,"More than one element or text in fragment");if(s.length===1&&!pa(t,r))throw new K(he,"Element in fragment can not be inserted before doctype")}if(ze(e)&&!pa(t,r))throw new K(he,"Only one element can be added and only after doctype");if(Ze(e)){if(Ue(i,Ze))throw new K(he,"Only one doctype is allowed");var o=Ue(i,ze);if(r&&i.indexOf(o)<i.indexOf(r))throw new K(he,"Doctype can only be inserted before an element");if(!r&&o)throw new K(he,"Doctype can not be appended since element is present")}}function Ia(t,e,r){var i=t.childNodes||[],n=e.childNodes||[];if(e.nodeType===H.DOCUMENT_FRAGMENT_NODE){var s=n.filter(ze);if(s.length>1||Ue(n,Cs))throw new K(he,"More than one element or text in fragment");if(s.length===1&&!ga(t,r))throw new K(he,"Element in fragment can not be inserted before doctype")}if(ze(e)&&!ga(t,r))throw new K(he,"Only one element can be added and only after doctype");if(Ze(e)){let c=function(u){return Ze(u)&&u!==r};var a=c;if(Ue(i,c))throw new K(he,"Only one doctype is allowed");var o=Ue(i,ze);if(r&&i.indexOf(o)<i.indexOf(r))throw new K(he,"Doctype can only be inserted before an element")}}function sn(t,e,r,i){Ul(t,e,r),t.nodeType===H.DOCUMENT_NODE&&(i||zl)(t,e,r);var n=e.parentNode;if(n&&n.removeChild(e),e.nodeType===Ye){var s=e.firstChild;if(s==null)return e;var o=e.lastChild}else s=o=e;var a=r?r.previousSibling:t.lastChild;s.previousSibling=a,o.nextSibling=r,a?a.nextSibling=s:t.firstChild=s,r==null?t.lastChild=o:r.previousSibling=o;do s.parentNode=t;while(s!==o&&(s=s.nextSibling));return Ss(t.ownerDocument||t,t),e.nodeType==Ye&&(e.firstChild=e.lastChild=null),e}function Vl(t,e){return e.parentNode&&e.parentNode.removeChild(e),e.parentNode=t,e.previousSibling=t.lastChild,e.nextSibling=null,e.previousSibling?e.previousSibling.nextSibling=e:t.firstChild=e,t.lastChild=e,Ss(t.ownerDocument,t,e),e}Zr.prototype={nodeName:"#document",nodeType:Sa,doctype:null,documentElement:null,_inc:1,insertBefore:function(t,e){if(t.nodeType==Ye){for(var r=t.firstChild;r;){var i=r.nextSibling;this.insertBefore(r,e),r=i}return t}return sn(this,t,e),t.ownerDocument=this,this.documentElement===null&&t.nodeType===_e&&(this.documentElement=t),t},removeChild:function(t){return this.documentElement==t&&(this.documentElement=null),Da(this,t)},replaceChild:function(t,e){sn(this,t,e,Ia),t.ownerDocument=this,e&&this.removeChild(e),ze(t)&&(this.documentElement=t)},importNode:function(t,e){return Na(this,t,e)},getElementById:function(t){var e=null;return Kr(this.documentElement,function(r){if(r.nodeType==_e&&r.getAttribute("id")==t)return e=r,!0}),e},getElementsByClassName:function(t){var e=da(t);return new ir(this,function(r){var i=[];return e.length>0&&Kr(r.documentElement,function(n){if(n!==r&&n.nodeType===_e){var s=n.getAttribute("class");if(s){var o=t===s;if(!o){var a=da(s);o=e.every(Fl(a))}o&&i.push(n)}}}),i})},createElement:function(t){var e=new vt;e.ownerDocument=this,e.nodeName=t,e.tagName=t,e.localName=t,e.childNodes=new Ke;var r=e.attributes=new nn;return r._ownerElement=e,e},createDocumentFragment:function(){var t=new cn;return t.ownerDocument=this,t.childNodes=new Ke,t},createTextNode:function(t){var e=new Es;return e.ownerDocument=this,e.appendData(t),e},createComment:function(t){var e=new As;return e.ownerDocument=this,e.appendData(t),e},createCDATASection:function(t){var e=new vs;return e.ownerDocument=this,e.appendData(t),e},createProcessingInstruction:function(t,e){var r=new Ps;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=t,r.nodeValue=r.data=e,r},createAttribute:function(t){var e=new on;return e.ownerDocument=this,e.name=t,e.nodeName=t,e.localName=t,e.specified=!0,e},createEntityReference:function(t){var e=new _s;return e.ownerDocument=this,e.nodeName=t,e},createElementNS:function(t,e){var r=new vt,i=e.split(":"),n=r.attributes=new nn;return r.childNodes=new Ke,r.ownerDocument=this,r.nodeName=e,r.tagName=e,r.namespaceURI=t,i.length==2?(r.prefix=i[0],r.localName=i[1]):r.localName=e,n._ownerElement=r,r},createAttributeNS:function(t,e){var r=new on,i=e.split(":");return r.ownerDocument=this,r.nodeName=e,r.name=e,r.namespaceURI=t,r.specified=!0,i.length==2?(r.prefix=i[0],r.localName=i[1]):r.localName=e,r}};pe(Zr,H);function vt(){this._nsMap={}}vt.prototype={nodeType:_e,hasAttribute:function(t){return this.getAttributeNode(t)!=null},getAttribute:function(t){var e=this.getAttributeNode(t);return e&&e.value||""},getAttributeNode:function(t){return this.attributes.getNamedItem(t)},setAttribute:function(t,e){var r=this.ownerDocument.createAttribute(t);r.value=r.nodeValue=""+e,this.setAttributeNode(r)},removeAttribute:function(t){var e=this.getAttributeNode(t);e&&this.removeAttributeNode(e)},appendChild:function(t){return t.nodeType===Ye?this.insertBefore(t,null):Vl(this,t)},setAttributeNode:function(t){return this.attributes.setNamedItem(t)},setAttributeNodeNS:function(t){return this.attributes.setNamedItemNS(t)},removeAttributeNode:function(t){return this.attributes.removeNamedItem(t.nodeName)},removeAttributeNS:function(t,e){var r=this.getAttributeNodeNS(t,e);r&&this.removeAttributeNode(r)},hasAttributeNS:function(t,e){return this.getAttributeNodeNS(t,e)!=null},getAttributeNS:function(t,e){var r=this.getAttributeNodeNS(t,e);return r&&r.value||""},setAttributeNS:function(t,e,r){var i=this.ownerDocument.createAttributeNS(t,e);i.value=i.nodeValue=""+r,this.setAttributeNode(i)},getAttributeNodeNS:function(t,e){return this.attributes.getNamedItemNS(t,e)},getElementsByTagName:function(t){return new ir(this,function(e){var r=[];return Kr(e,function(i){i!==e&&i.nodeType==_e&&(t==="*"||i.tagName==t)&&r.push(i)}),r})},getElementsByTagNameNS:function(t,e){return new ir(this,function(r){var i=[];return Kr(r,function(n){n!==r&&n.nodeType===_e&&(t==="*"||n.namespaceURI===t)&&(e==="*"||n.localName==e)&&i.push(n)}),i})}};Zr.prototype.getElementsByTagName=vt.prototype.getElementsByTagName;Zr.prototype.getElementsByTagNameNS=vt.prototype.getElementsByTagNameNS;pe(vt,H);function on(){}on.prototype.nodeType=rr;pe(on,H);function Jr(){}Jr.prototype={data:"",substringData:function(t,e){return this.data.substring(t,t+e)},appendData:function(t){t=this.data+t,this.nodeValue=this.data=t,this.length=t.length},insertData:function(t,e){this.replaceData(t,0,e)},appendChild:function(t){throw new Error(oe[he])},deleteData:function(t,e){this.replaceData(t,e,"")},replaceData:function(t,e,r){var i=this.data.substring(0,t),n=this.data.substring(t+e);r=i+r+n,this.nodeValue=this.data=r,this.length=r.length}};pe(Jr,H);function Es(){}Es.prototype={nodeName:"#text",nodeType:rn,splitText:function(t){var e=this.data,r=e.substring(t);e=e.substring(0,t),this.data=this.nodeValue=e,this.length=e.length;var i=this.ownerDocument.createTextNode(r);return this.parentNode&&this.parentNode.insertBefore(i,this.nextSibling),i}};pe(Es,Jr);function As(){}As.prototype={nodeName:"#comment",nodeType:ka};pe(As,Jr);function vs(){}vs.prototype={nodeName:"#cdata-section",nodeType:xa};pe(vs,Jr);function an(){}an.prototype.nodeType=Ca;pe(an,H);function Fa(){}Fa.prototype.nodeType=Rl;pe(Fa,H);function Ba(){}Ba.prototype.nodeType=Bl;pe(Ba,H);function _s(){}_s.prototype.nodeType=ya;pe(_s,H);function cn(){}cn.prototype.nodeName="#document-fragment";cn.prototype.nodeType=Ye;pe(cn,H);function Ps(){}Ps.prototype.nodeType=Ta;pe(Ps,H);function Ra(){}Ra.prototype.serializeToString=function(t,e,r){return Oa.call(t,e,r)};H.prototype.toString=Oa;function Oa(t,e){var r=[],i=this.nodeType==9&&this.documentElement||this,n=i.prefix,s=i.namespaceURI;if(s&&n==null){var n=i.lookupPrefix(s);if(n==null)var o=[{namespace:s,prefix:null}]}return tr(this,r,t,e,o),r.join("")}function ba(t,e,r){var i=t.prefix||"",n=t.namespaceURI;if(!n||i==="xml"&&n===Xr.XML||n===Xr.XMLNS)return!1;for(var s=r.length;s--;){var o=r[s];if(o.prefix===i)return o.namespace!==n}return!0}function ys(t,e,r){t.push(" ",e,'="',r.replace(/[<>&"\t\n\r]/g,_a),'"')}function tr(t,e,r,i,n){if(n||(n=[]),i)if(t=i(t),t){if(typeof t=="string"){e.push(t);return}}else return;switch(t.nodeType){case _e:var s=t.attributes,o=s.length,w=t.firstChild,a=t.tagName;r=Xr.isHTML(t.namespaceURI)||r;var c=a;if(!r&&!t.prefix&&t.namespaceURI){for(var u,l=0;l<s.length;l++)if(s.item(l).name==="xmlns"){u=s.item(l).value;break}if(!u)for(var d=n.length-1;d>=0;d--){var f=n[d];if(f.prefix===""&&f.namespace===t.namespaceURI){u=f.namespace;break}}if(u!==t.namespaceURI)for(var d=n.length-1;d>=0;d--){var f=n[d];if(f.namespace===t.namespaceURI){f.prefix&&(c=f.prefix+":"+a);break}}}e.push("<",c);for(var m=0;m<o;m++){var p=s.item(m);p.prefix=="xmlns"?n.push({prefix:p.localName,namespace:p.value}):p.nodeName=="xmlns"&&n.push({prefix:"",namespace:p.value})}for(var m=0;m<o;m++){var p=s.item(m);if(ba(p,r,n)){var g=p.prefix||"",b=p.namespaceURI;ys(e,g?"xmlns:"+g:"xmlns",b),n.push({prefix:g,namespace:b})}tr(p,e,r,i,n)}if(a===c&&ba(t,r,n)){var g=t.prefix||"",b=t.namespaceURI;ys(e,g?"xmlns:"+g:"xmlns",b),n.push({prefix:g,namespace:b})}if(w||r&&!/^(?:meta|link|img|br|hr|input)$/i.test(a)){if(e.push(">"),r&&/^script$/i.test(a))for(;w;)w.data?e.push(w.data):tr(w,e,r,i,n.slice()),w=w.nextSibling;else for(;w;)tr(w,e,r,i,n.slice()),w=w.nextSibling;e.push("</",c,">")}else e.push("/>");return;case Sa:case Ye:for(var w=t.firstChild;w;)tr(w,e,r,i,n.slice()),w=w.nextSibling;return;case rr:return ys(e,t.name,t.value);case rn:return e.push(t.data.replace(/[<&>]/g,_a));case xa:return e.push("<![CDATA[",t.data,"]]>");case ka:return e.push("<!--",t.data,"-->");case Ca:var x=t.publicId,y=t.systemId;if(e.push("<!DOCTYPE ",t.name),x)e.push(" PUBLIC ",x),y&&y!="."&&e.push(" ",y),e.push(">");else if(y&&y!=".")e.push(" SYSTEM ",y,">");else{var T=t.internalSubset;T&&e.push(" [",T,"]"),e.push(">")}return;case Ta:return e.push("<?",t.target," ",t.data,"?>");case ya:return e.push("&",t.nodeName,";");default:e.push("??",t.nodeName)}}function Na(t,e,r){var i;switch(e.nodeType){case _e:i=e.cloneNode(!1),i.ownerDocument=t;case Ye:break;case rr:r=!0;break}if(i||(i=e.cloneNode(!1)),i.ownerDocument=t,i.parentNode=null,r)for(var n=e.firstChild;n;)i.appendChild(Na(t,n,r)),n=n.nextSibling;return i}function Ts(t,e,r){var i=new e.constructor;for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var s=e[n];typeof s!="object"&&s!=i[n]&&(i[n]=s)}switch(e.childNodes&&(i.childNodes=new Ke),i.ownerDocument=t,i.nodeType){case _e:var o=e.attributes,a=i.attributes=new nn,c=o.length;a._ownerElement=i;for(var u=0;u<c;u++)i.setAttributeNode(Ts(t,o.item(u),!0));break;case rr:r=!0}if(r)for(var l=e.firstChild;l;)i.appendChild(Ts(t,l,r)),l=l.nextSibling;return i}function Ma(t,e,r){t[e]=r}try{if(Object.defineProperty){let t=function(e){switch(e.nodeType){case _e:case Ye:var r=[];for(e=e.firstChild;e;)e.nodeType!==7&&e.nodeType!==8&&r.push(t(e)),e=e.nextSibling;return r.join("");default:return e.nodeValue}};Ll=t,Object.defineProperty(ir.prototype,"length",{get:function(){return ks(this),this.$$length}}),Object.defineProperty(H.prototype,"textContent",{get:function(){return t(this)},set:function(e){switch(this.nodeType){case _e:case Ye:for(;this.firstChild;)this.removeChild(this.firstChild);(e||String(e))&&this.appendChild(this.ownerDocument.createTextNode(e));break;default:this.data=e,this.value=e,this.nodeValue=e}}}),Ma=function(e,r,i){e["$$"+r]=i}}}catch{}var Ll;ft.DocumentType=an;ft.DOMException=K;ft.DOMImplementation=va;ft.Element=vt;ft.Node=H;ft.NodeList=Ke;ft.XMLSerializer=Ra});var za=Kt(ei=>{"use strict";var Ua=Qr().freeze;ei.XML_ENTITIES=Ua({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});ei.HTML_ENTITIES=Ua({Aacute:"\xC1",aacute:"\xE1",Abreve:"\u0102",abreve:"\u0103",ac:"\u223E",acd:"\u223F",acE:"\u223E\u0333",Acirc:"\xC2",acirc:"\xE2",acute:"\xB4",Acy:"\u0410",acy:"\u0430",AElig:"\xC6",aelig:"\xE6",af:"\u2061",Afr:"\u{1D504}",afr:"\u{1D51E}",Agrave:"\xC0",agrave:"\xE0",alefsym:"\u2135",aleph:"\u2135",Alpha:"\u0391",alpha:"\u03B1",Amacr:"\u0100",amacr:"\u0101",amalg:"\u2A3F",AMP:"&",amp:"&",And:"\u2A53",and:"\u2227",andand:"\u2A55",andd:"\u2A5C",andslope:"\u2A58",andv:"\u2A5A",ang:"\u2220",ange:"\u29A4",angle:"\u2220",angmsd:"\u2221",angmsdaa:"\u29A8",angmsdab:"\u29A9",angmsdac:"\u29AA",angmsdad:"\u29AB",angmsdae:"\u29AC",angmsdaf:"\u29AD",angmsdag:"\u29AE",angmsdah:"\u29AF",angrt:"\u221F",angrtvb:"\u22BE",angrtvbd:"\u299D",angsph:"\u2222",angst:"\xC5",angzarr:"\u237C",Aogon:"\u0104",aogon:"\u0105",Aopf:"\u{1D538}",aopf:"\u{1D552}",ap:"\u2248",apacir:"\u2A6F",apE:"\u2A70",ape:"\u224A",apid:"\u224B",apos:"'",ApplyFunction:"\u2061",approx:"\u2248",approxeq:"\u224A",Aring:"\xC5",aring:"\xE5",Ascr:"\u{1D49C}",ascr:"\u{1D4B6}",Assign:"\u2254",ast:"*",asymp:"\u2248",asympeq:"\u224D",Atilde:"\xC3",atilde:"\xE3",Auml:"\xC4",auml:"\xE4",awconint:"\u2233",awint:"\u2A11",backcong:"\u224C",backepsilon:"\u03F6",backprime:"\u2035",backsim:"\u223D",backsimeq:"\u22CD",Backslash:"\u2216",Barv:"\u2AE7",barvee:"\u22BD",Barwed:"\u2306",barwed:"\u2305",barwedge:"\u2305",bbrk:"\u23B5",bbrktbrk:"\u23B6",bcong:"\u224C",Bcy:"\u0411",bcy:"\u0431",bdquo:"\u201E",becaus:"\u2235",Because:"\u2235",because:"\u2235",bemptyv:"\u29B0",bepsi:"\u03F6",bernou:"\u212C",Bernoullis:"\u212C",Beta:"\u0392",beta:"\u03B2",beth:"\u2136",between:"\u226C",Bfr:"\u{1D505}",bfr:"\u{1D51F}",bigcap:"\u22C2",bigcirc:"\u25EF",bigcup:"\u22C3",bigodot:"\u2A00",bigoplus:"\u2A01",bigotimes:"\u2A02",bigsqcup:"\u2A06",bigstar:"\u2605",bigtriangledown:"\u25BD",bigtriangleup:"\u25B3",biguplus:"\u2A04",bigvee:"\u22C1",bigwedge:"\u22C0",bkarow:"\u290D",blacklozenge:"\u29EB",blacksquare:"\u25AA",blacktriangle:"\u25B4",blacktriangledown:"\u25BE",blacktriangleleft:"\u25C2",blacktriangleright:"\u25B8",blank:"\u2423",blk12:"\u2592",blk14:"\u2591",blk34:"\u2593",block:"\u2588",bne:"=\u20E5",bnequiv:"\u2261\u20E5",bNot:"\u2AED",bnot:"\u2310",Bopf:"\u{1D539}",bopf:"\u{1D553}",bot:"\u22A5",bottom:"\u22A5",bowtie:"\u22C8",boxbox:"\u29C9",boxDL:"\u2557",boxDl:"\u2556",boxdL:"\u2555",boxdl:"\u2510",boxDR:"\u2554",boxDr:"\u2553",boxdR:"\u2552",boxdr:"\u250C",boxH:"\u2550",boxh:"\u2500",boxHD:"\u2566",boxHd:"\u2564",boxhD:"\u2565",boxhd:"\u252C",boxHU:"\u2569",boxHu:"\u2567",boxhU:"\u2568",boxhu:"\u2534",boxminus:"\u229F",boxplus:"\u229E",boxtimes:"\u22A0",boxUL:"\u255D",boxUl:"\u255C",boxuL:"\u255B",boxul:"\u2518",boxUR:"\u255A",boxUr:"\u2559",boxuR:"\u2558",boxur:"\u2514",boxV:"\u2551",boxv:"\u2502",boxVH:"\u256C",boxVh:"\u256B",boxvH:"\u256A",boxvh:"\u253C",boxVL:"\u2563",boxVl:"\u2562",boxvL:"\u2561",boxvl:"\u2524",boxVR:"\u2560",boxVr:"\u255F",boxvR:"\u255E",boxvr:"\u251C",bprime:"\u2035",Breve:"\u02D8",breve:"\u02D8",brvbar:"\xA6",Bscr:"\u212C",bscr:"\u{1D4B7}",bsemi:"\u204F",bsim:"\u223D",bsime:"\u22CD",bsol:"\\",bsolb:"\u29C5",bsolhsub:"\u27C8",bull:"\u2022",bullet:"\u2022",bump:"\u224E",bumpE:"\u2AAE",bumpe:"\u224F",Bumpeq:"\u224E",bumpeq:"\u224F",Cacute:"\u0106",cacute:"\u0107",Cap:"\u22D2",cap:"\u2229",capand:"\u2A44",capbrcup:"\u2A49",capcap:"\u2A4B",capcup:"\u2A47",capdot:"\u2A40",CapitalDifferentialD:"\u2145",caps:"\u2229\uFE00",caret:"\u2041",caron:"\u02C7",Cayleys:"\u212D",ccaps:"\u2A4D",Ccaron:"\u010C",ccaron:"\u010D",Ccedil:"\xC7",ccedil:"\xE7",Ccirc:"\u0108",ccirc:"\u0109",Cconint:"\u2230",ccups:"\u2A4C",ccupssm:"\u2A50",Cdot:"\u010A",cdot:"\u010B",cedil:"\xB8",Cedilla:"\xB8",cemptyv:"\u29B2",cent:"\xA2",CenterDot:"\xB7",centerdot:"\xB7",Cfr:"\u212D",cfr:"\u{1D520}",CHcy:"\u0427",chcy:"\u0447",check:"\u2713",checkmark:"\u2713",Chi:"\u03A7",chi:"\u03C7",cir:"\u25CB",circ:"\u02C6",circeq:"\u2257",circlearrowleft:"\u21BA",circlearrowright:"\u21BB",circledast:"\u229B",circledcirc:"\u229A",circleddash:"\u229D",CircleDot:"\u2299",circledR:"\xAE",circledS:"\u24C8",CircleMinus:"\u2296",CirclePlus:"\u2295",CircleTimes:"\u2297",cirE:"\u29C3",cire:"\u2257",cirfnint:"\u2A10",cirmid:"\u2AEF",cirscir:"\u29C2",ClockwiseContourIntegral:"\u2232",CloseCurlyDoubleQuote:"\u201D",CloseCurlyQuote:"\u2019",clubs:"\u2663",clubsuit:"\u2663",Colon:"\u2237",colon:":",Colone:"\u2A74",colone:"\u2254",coloneq:"\u2254",comma:",",commat:"@",comp:"\u2201",compfn:"\u2218",complement:"\u2201",complexes:"\u2102",cong:"\u2245",congdot:"\u2A6D",Congruent:"\u2261",Conint:"\u222F",conint:"\u222E",ContourIntegral:"\u222E",Copf:"\u2102",copf:"\u{1D554}",coprod:"\u2210",Coproduct:"\u2210",COPY:"\xA9",copy:"\xA9",copysr:"\u2117",CounterClockwiseContourIntegral:"\u2233",crarr:"\u21B5",Cross:"\u2A2F",cross:"\u2717",Cscr:"\u{1D49E}",cscr:"\u{1D4B8}",csub:"\u2ACF",csube:"\u2AD1",csup:"\u2AD0",csupe:"\u2AD2",ctdot:"\u22EF",cudarrl:"\u2938",cudarrr:"\u2935",cuepr:"\u22DE",cuesc:"\u22DF",cularr:"\u21B6",cularrp:"\u293D",Cup:"\u22D3",cup:"\u222A",cupbrcap:"\u2A48",CupCap:"\u224D",cupcap:"\u2A46",cupcup:"\u2A4A",cupdot:"\u228D",cupor:"\u2A45",cups:"\u222A\uFE00",curarr:"\u21B7",curarrm:"\u293C",curlyeqprec:"\u22DE",curlyeqsucc:"\u22DF",curlyvee:"\u22CE",curlywedge:"\u22CF",curren:"\xA4",curvearrowleft:"\u21B6",curvearrowright:"\u21B7",cuvee:"\u22CE",cuwed:"\u22CF",cwconint:"\u2232",cwint:"\u2231",cylcty:"\u232D",Dagger:"\u2021",dagger:"\u2020",daleth:"\u2138",Darr:"\u21A1",dArr:"\u21D3",darr:"\u2193",dash:"\u2010",Dashv:"\u2AE4",dashv:"\u22A3",dbkarow:"\u290F",dblac:"\u02DD",Dcaron:"\u010E",dcaron:"\u010F",Dcy:"\u0414",dcy:"\u0434",DD:"\u2145",dd:"\u2146",ddagger:"\u2021",ddarr:"\u21CA",DDotrahd:"\u2911",ddotseq:"\u2A77",deg:"\xB0",Del:"\u2207",Delta:"\u0394",delta:"\u03B4",demptyv:"\u29B1",dfisht:"\u297F",Dfr:"\u{1D507}",dfr:"\u{1D521}",dHar:"\u2965",dharl:"\u21C3",dharr:"\u21C2",DiacriticalAcute:"\xB4",DiacriticalDot:"\u02D9",DiacriticalDoubleAcute:"\u02DD",DiacriticalGrave:"`",DiacriticalTilde:"\u02DC",diam:"\u22C4",Diamond:"\u22C4",diamond:"\u22C4",diamondsuit:"\u2666",diams:"\u2666",die:"\xA8",DifferentialD:"\u2146",digamma:"\u03DD",disin:"\u22F2",div:"\xF7",divide:"\xF7",divideontimes:"\u22C7",divonx:"\u22C7",DJcy:"\u0402",djcy:"\u0452",dlcorn:"\u231E",dlcrop:"\u230D",dollar:"$",Dopf:"\u{1D53B}",dopf:"\u{1D555}",Dot:"\xA8",dot:"\u02D9",DotDot:"\u20DC",doteq:"\u2250",doteqdot:"\u2251",DotEqual:"\u2250",dotminus:"\u2238",dotplus:"\u2214",dotsquare:"\u22A1",doublebarwedge:"\u2306",DoubleContourIntegral:"\u222F",DoubleDot:"\xA8",DoubleDownArrow:"\u21D3",DoubleLeftArrow:"\u21D0",DoubleLeftRightArrow:"\u21D4",DoubleLeftTee:"\u2AE4",DoubleLongLeftArrow:"\u27F8",DoubleLongLeftRightArrow:"\u27FA",DoubleLongRightArrow:"\u27F9",DoubleRightArrow:"\u21D2",DoubleRightTee:"\u22A8",DoubleUpArrow:"\u21D1",DoubleUpDownArrow:"\u21D5",DoubleVerticalBar:"\u2225",DownArrow:"\u2193",Downarrow:"\u21D3",downarrow:"\u2193",DownArrowBar:"\u2913",DownArrowUpArrow:"\u21F5",DownBreve:"\u0311",downdownarrows:"\u21CA",downharpoonleft:"\u21C3",downharpoonright:"\u21C2",DownLeftRightVector:"\u2950",DownLeftTeeVector:"\u295E",DownLeftVector:"\u21BD",DownLeftVectorBar:"\u2956",DownRightTeeVector:"\u295F",DownRightVector:"\u21C1",DownRightVectorBar:"\u2957",DownTee:"\u22A4",DownTeeArrow:"\u21A7",drbkarow:"\u2910",drcorn:"\u231F",drcrop:"\u230C",Dscr:"\u{1D49F}",dscr:"\u{1D4B9}",DScy:"\u0405",dscy:"\u0455",dsol:"\u29F6",Dstrok:"\u0110",dstrok:"\u0111",dtdot:"\u22F1",dtri:"\u25BF",dtrif:"\u25BE",duarr:"\u21F5",duhar:"\u296F",dwangle:"\u29A6",DZcy:"\u040F",dzcy:"\u045F",dzigrarr:"\u27FF",Eacute:"\xC9",eacute:"\xE9",easter:"\u2A6E",Ecaron:"\u011A",ecaron:"\u011B",ecir:"\u2256",Ecirc:"\xCA",ecirc:"\xEA",ecolon:"\u2255",Ecy:"\u042D",ecy:"\u044D",eDDot:"\u2A77",Edot:"\u0116",eDot:"\u2251",edot:"\u0117",ee:"\u2147",efDot:"\u2252",Efr:"\u{1D508}",efr:"\u{1D522}",eg:"\u2A9A",Egrave:"\xC8",egrave:"\xE8",egs:"\u2A96",egsdot:"\u2A98",el:"\u2A99",Element:"\u2208",elinters:"\u23E7",ell:"\u2113",els:"\u2A95",elsdot:"\u2A97",Emacr:"\u0112",emacr:"\u0113",empty:"\u2205",emptyset:"\u2205",EmptySmallSquare:"\u25FB",emptyv:"\u2205",EmptyVerySmallSquare:"\u25AB",emsp:"\u2003",emsp13:"\u2004",emsp14:"\u2005",ENG:"\u014A",eng:"\u014B",ensp:"\u2002",Eogon:"\u0118",eogon:"\u0119",Eopf:"\u{1D53C}",eopf:"\u{1D556}",epar:"\u22D5",eparsl:"\u29E3",eplus:"\u2A71",epsi:"\u03B5",Epsilon:"\u0395",epsilon:"\u03B5",epsiv:"\u03F5",eqcirc:"\u2256",eqcolon:"\u2255",eqsim:"\u2242",eqslantgtr:"\u2A96",eqslantless:"\u2A95",Equal:"\u2A75",equals:"=",EqualTilde:"\u2242",equest:"\u225F",Equilibrium:"\u21CC",equiv:"\u2261",equivDD:"\u2A78",eqvparsl:"\u29E5",erarr:"\u2971",erDot:"\u2253",Escr:"\u2130",escr:"\u212F",esdot:"\u2250",Esim:"\u2A73",esim:"\u2242",Eta:"\u0397",eta:"\u03B7",ETH:"\xD0",eth:"\xF0",Euml:"\xCB",euml:"\xEB",euro:"\u20AC",excl:"!",exist:"\u2203",Exists:"\u2203",expectation:"\u2130",ExponentialE:"\u2147",exponentiale:"\u2147",fallingdotseq:"\u2252",Fcy:"\u0424",fcy:"\u0444",female:"\u2640",ffilig:"\uFB03",fflig:"\uFB00",ffllig:"\uFB04",Ffr:"\u{1D509}",ffr:"\u{1D523}",filig:"\uFB01",FilledSmallSquare:"\u25FC",FilledVerySmallSquare:"\u25AA",fjlig:"fj",flat:"\u266D",fllig:"\uFB02",fltns:"\u25B1",fnof:"\u0192",Fopf:"\u{1D53D}",fopf:"\u{1D557}",ForAll:"\u2200",forall:"\u2200",fork:"\u22D4",forkv:"\u2AD9",Fouriertrf:"\u2131",fpartint:"\u2A0D",frac12:"\xBD",frac13:"\u2153",frac14:"\xBC",frac15:"\u2155",frac16:"\u2159",frac18:"\u215B",frac23:"\u2154",frac25:"\u2156",frac34:"\xBE",frac35:"\u2157",frac38:"\u215C",frac45:"\u2158",frac56:"\u215A",frac58:"\u215D",frac78:"\u215E",frasl:"\u2044",frown:"\u2322",Fscr:"\u2131",fscr:"\u{1D4BB}",gacute:"\u01F5",Gamma:"\u0393",gamma:"\u03B3",Gammad:"\u03DC",gammad:"\u03DD",gap:"\u2A86",Gbreve:"\u011E",gbreve:"\u011F",Gcedil:"\u0122",Gcirc:"\u011C",gcirc:"\u011D",Gcy:"\u0413",gcy:"\u0433",Gdot:"\u0120",gdot:"\u0121",gE:"\u2267",ge:"\u2265",gEl:"\u2A8C",gel:"\u22DB",geq:"\u2265",geqq:"\u2267",geqslant:"\u2A7E",ges:"\u2A7E",gescc:"\u2AA9",gesdot:"\u2A80",gesdoto:"\u2A82",gesdotol:"\u2A84",gesl:"\u22DB\uFE00",gesles:"\u2A94",Gfr:"\u{1D50A}",gfr:"\u{1D524}",Gg:"\u22D9",gg:"\u226B",ggg:"\u22D9",gimel:"\u2137",GJcy:"\u0403",gjcy:"\u0453",gl:"\u2277",gla:"\u2AA5",glE:"\u2A92",glj:"\u2AA4",gnap:"\u2A8A",gnapprox:"\u2A8A",gnE:"\u2269",gne:"\u2A88",gneq:"\u2A88",gneqq:"\u2269",gnsim:"\u22E7",Gopf:"\u{1D53E}",gopf:"\u{1D558}",grave:"`",GreaterEqual:"\u2265",GreaterEqualLess:"\u22DB",GreaterFullEqual:"\u2267",GreaterGreater:"\u2AA2",GreaterLess:"\u2277",GreaterSlantEqual:"\u2A7E",GreaterTilde:"\u2273",Gscr:"\u{1D4A2}",gscr:"\u210A",gsim:"\u2273",gsime:"\u2A8E",gsiml:"\u2A90",Gt:"\u226B",GT:">",gt:">",gtcc:"\u2AA7",gtcir:"\u2A7A",gtdot:"\u22D7",gtlPar:"\u2995",gtquest:"\u2A7C",gtrapprox:"\u2A86",gtrarr:"\u2978",gtrdot:"\u22D7",gtreqless:"\u22DB",gtreqqless:"\u2A8C",gtrless:"\u2277",gtrsim:"\u2273",gvertneqq:"\u2269\uFE00",gvnE:"\u2269\uFE00",Hacek:"\u02C7",hairsp:"\u200A",half:"\xBD",hamilt:"\u210B",HARDcy:"\u042A",hardcy:"\u044A",hArr:"\u21D4",harr:"\u2194",harrcir:"\u2948",harrw:"\u21AD",Hat:"^",hbar:"\u210F",Hcirc:"\u0124",hcirc:"\u0125",hearts:"\u2665",heartsuit:"\u2665",hellip:"\u2026",hercon:"\u22B9",Hfr:"\u210C",hfr:"\u{1D525}",HilbertSpace:"\u210B",hksearow:"\u2925",hkswarow:"\u2926",hoarr:"\u21FF",homtht:"\u223B",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",Hopf:"\u210D",hopf:"\u{1D559}",horbar:"\u2015",HorizontalLine:"\u2500",Hscr:"\u210B",hscr:"\u{1D4BD}",hslash:"\u210F",Hstrok:"\u0126",hstrok:"\u0127",HumpDownHump:"\u224E",HumpEqual:"\u224F",hybull:"\u2043",hyphen:"\u2010",Iacute:"\xCD",iacute:"\xED",ic:"\u2063",Icirc:"\xCE",icirc:"\xEE",Icy:"\u0418",icy:"\u0438",Idot:"\u0130",IEcy:"\u0415",iecy:"\u0435",iexcl:"\xA1",iff:"\u21D4",Ifr:"\u2111",ifr:"\u{1D526}",Igrave:"\xCC",igrave:"\xEC",ii:"\u2148",iiiint:"\u2A0C",iiint:"\u222D",iinfin:"\u29DC",iiota:"\u2129",IJlig:"\u0132",ijlig:"\u0133",Im:"\u2111",Imacr:"\u012A",imacr:"\u012B",image:"\u2111",ImaginaryI:"\u2148",imagline:"\u2110",imagpart:"\u2111",imath:"\u0131",imof:"\u22B7",imped:"\u01B5",Implies:"\u21D2",in:"\u2208",incare:"\u2105",infin:"\u221E",infintie:"\u29DD",inodot:"\u0131",Int:"\u222C",int:"\u222B",intcal:"\u22BA",integers:"\u2124",Integral:"\u222B",intercal:"\u22BA",Intersection:"\u22C2",intlarhk:"\u2A17",intprod:"\u2A3C",InvisibleComma:"\u2063",InvisibleTimes:"\u2062",IOcy:"\u0401",iocy:"\u0451",Iogon:"\u012E",iogon:"\u012F",Iopf:"\u{1D540}",iopf:"\u{1D55A}",Iota:"\u0399",iota:"\u03B9",iprod:"\u2A3C",iquest:"\xBF",Iscr:"\u2110",iscr:"\u{1D4BE}",isin:"\u2208",isindot:"\u22F5",isinE:"\u22F9",isins:"\u22F4",isinsv:"\u22F3",isinv:"\u2208",it:"\u2062",Itilde:"\u0128",itilde:"\u0129",Iukcy:"\u0406",iukcy:"\u0456",Iuml:"\xCF",iuml:"\xEF",Jcirc:"\u0134",jcirc:"\u0135",Jcy:"\u0419",jcy:"\u0439",Jfr:"\u{1D50D}",jfr:"\u{1D527}",jmath:"\u0237",Jopf:"\u{1D541}",jopf:"\u{1D55B}",Jscr:"\u{1D4A5}",jscr:"\u{1D4BF}",Jsercy:"\u0408",jsercy:"\u0458",Jukcy:"\u0404",jukcy:"\u0454",Kappa:"\u039A",kappa:"\u03BA",kappav:"\u03F0",Kcedil:"\u0136",kcedil:"\u0137",Kcy:"\u041A",kcy:"\u043A",Kfr:"\u{1D50E}",kfr:"\u{1D528}",kgreen:"\u0138",KHcy:"\u0425",khcy:"\u0445",KJcy:"\u040C",kjcy:"\u045C",Kopf:"\u{1D542}",kopf:"\u{1D55C}",Kscr:"\u{1D4A6}",kscr:"\u{1D4C0}",lAarr:"\u21DA",Lacute:"\u0139",lacute:"\u013A",laemptyv:"\u29B4",lagran:"\u2112",Lambda:"\u039B",lambda:"\u03BB",Lang:"\u27EA",lang:"\u27E8",langd:"\u2991",langle:"\u27E8",lap:"\u2A85",Laplacetrf:"\u2112",laquo:"\xAB",Larr:"\u219E",lArr:"\u21D0",larr:"\u2190",larrb:"\u21E4",larrbfs:"\u291F",larrfs:"\u291D",larrhk:"\u21A9",larrlp:"\u21AB",larrpl:"\u2939",larrsim:"\u2973",larrtl:"\u21A2",lat:"\u2AAB",lAtail:"\u291B",latail:"\u2919",late:"\u2AAD",lates:"\u2AAD\uFE00",lBarr:"\u290E",lbarr:"\u290C",lbbrk:"\u2772",lbrace:"{",lbrack:"[",lbrke:"\u298B",lbrksld:"\u298F",lbrkslu:"\u298D",Lcaron:"\u013D",lcaron:"\u013E",Lcedil:"\u013B",lcedil:"\u013C",lceil:"\u2308",lcub:"{",Lcy:"\u041B",lcy:"\u043B",ldca:"\u2936",ldquo:"\u201C",ldquor:"\u201E",ldrdhar:"\u2967",ldrushar:"\u294B",ldsh:"\u21B2",lE:"\u2266",le:"\u2264",LeftAngleBracket:"\u27E8",LeftArrow:"\u2190",Leftarrow:"\u21D0",leftarrow:"\u2190",LeftArrowBar:"\u21E4",LeftArrowRightArrow:"\u21C6",leftarrowtail:"\u21A2",LeftCeiling:"\u2308",LeftDoubleBracket:"\u27E6",LeftDownTeeVector:"\u2961",LeftDownVector:"\u21C3",LeftDownVectorBar:"\u2959",LeftFloor:"\u230A",leftharpoondown:"\u21BD",leftharpoonup:"\u21BC",leftleftarrows:"\u21C7",LeftRightArrow:"\u2194",Leftrightarrow:"\u21D4",leftrightarrow:"\u2194",leftrightarrows:"\u21C6",leftrightharpoons:"\u21CB",leftrightsquigarrow:"\u21AD",LeftRightVector:"\u294E",LeftTee:"\u22A3",LeftTeeArrow:"\u21A4",LeftTeeVector:"\u295A",leftthreetimes:"\u22CB",LeftTriangle:"\u22B2",LeftTriangleBar:"\u29CF",LeftTriangleEqual:"\u22B4",LeftUpDownVector:"\u2951",LeftUpTeeVector:"\u2960",LeftUpVector:"\u21BF",LeftUpVectorBar:"\u2958",LeftVector:"\u21BC",LeftVectorBar:"\u2952",lEg:"\u2A8B",leg:"\u22DA",leq:"\u2264",leqq:"\u2266",leqslant:"\u2A7D",les:"\u2A7D",lescc:"\u2AA8",lesdot:"\u2A7F",lesdoto:"\u2A81",lesdotor:"\u2A83",lesg:"\u22DA\uFE00",lesges:"\u2A93",lessapprox:"\u2A85",lessdot:"\u22D6",lesseqgtr:"\u22DA",lesseqqgtr:"\u2A8B",LessEqualGreater:"\u22DA",LessFullEqual:"\u2266",LessGreater:"\u2276",lessgtr:"\u2276",LessLess:"\u2AA1",lesssim:"\u2272",LessSlantEqual:"\u2A7D",LessTilde:"\u2272",lfisht:"\u297C",lfloor:"\u230A",Lfr:"\u{1D50F}",lfr:"\u{1D529}",lg:"\u2276",lgE:"\u2A91",lHar:"\u2962",lhard:"\u21BD",lharu:"\u21BC",lharul:"\u296A",lhblk:"\u2584",LJcy:"\u0409",ljcy:"\u0459",Ll:"\u22D8",ll:"\u226A",llarr:"\u21C7",llcorner:"\u231E",Lleftarrow:"\u21DA",llhard:"\u296B",lltri:"\u25FA",Lmidot:"\u013F",lmidot:"\u0140",lmoust:"\u23B0",lmoustache:"\u23B0",lnap:"\u2A89",lnapprox:"\u2A89",lnE:"\u2268",lne:"\u2A87",lneq:"\u2A87",lneqq:"\u2268",lnsim:"\u22E6",loang:"\u27EC",loarr:"\u21FD",lobrk:"\u27E6",LongLeftArrow:"\u27F5",Longleftarrow:"\u27F8",longleftarrow:"\u27F5",LongLeftRightArrow:"\u27F7",Longleftrightarrow:"\u27FA",longleftrightarrow:"\u27F7",longmapsto:"\u27FC",LongRightArrow:"\u27F6",Longrightarrow:"\u27F9",longrightarrow:"\u27F6",looparrowleft:"\u21AB",looparrowright:"\u21AC",lopar:"\u2985",Lopf:"\u{1D543}",lopf:"\u{1D55D}",loplus:"\u2A2D",lotimes:"\u2A34",lowast:"\u2217",lowbar:"_",LowerLeftArrow:"\u2199",LowerRightArrow:"\u2198",loz:"\u25CA",lozenge:"\u25CA",lozf:"\u29EB",lpar:"(",lparlt:"\u2993",lrarr:"\u21C6",lrcorner:"\u231F",lrhar:"\u21CB",lrhard:"\u296D",lrm:"\u200E",lrtri:"\u22BF",lsaquo:"\u2039",Lscr:"\u2112",lscr:"\u{1D4C1}",Lsh:"\u21B0",lsh:"\u21B0",lsim:"\u2272",lsime:"\u2A8D",lsimg:"\u2A8F",lsqb:"[",lsquo:"\u2018",lsquor:"\u201A",Lstrok:"\u0141",lstrok:"\u0142",Lt:"\u226A",LT:"<",lt:"<",ltcc:"\u2AA6",ltcir:"\u2A79",ltdot:"\u22D6",lthree:"\u22CB",ltimes:"\u22C9",ltlarr:"\u2976",ltquest:"\u2A7B",ltri:"\u25C3",ltrie:"\u22B4",ltrif:"\u25C2",ltrPar:"\u2996",lurdshar:"\u294A",luruhar:"\u2966",lvertneqq:"\u2268\uFE00",lvnE:"\u2268\uFE00",macr:"\xAF",male:"\u2642",malt:"\u2720",maltese:"\u2720",Map:"\u2905",map:"\u21A6",mapsto:"\u21A6",mapstodown:"\u21A7",mapstoleft:"\u21A4",mapstoup:"\u21A5",marker:"\u25AE",mcomma:"\u2A29",Mcy:"\u041C",mcy:"\u043C",mdash:"\u2014",mDDot:"\u223A",measuredangle:"\u2221",MediumSpace:"\u205F",Mellintrf:"\u2133",Mfr:"\u{1D510}",mfr:"\u{1D52A}",mho:"\u2127",micro:"\xB5",mid:"\u2223",midast:"*",midcir:"\u2AF0",middot:"\xB7",minus:"\u2212",minusb:"\u229F",minusd:"\u2238",minusdu:"\u2A2A",MinusPlus:"\u2213",mlcp:"\u2ADB",mldr:"\u2026",mnplus:"\u2213",models:"\u22A7",Mopf:"\u{1D544}",mopf:"\u{1D55E}",mp:"\u2213",Mscr:"\u2133",mscr:"\u{1D4C2}",mstpos:"\u223E",Mu:"\u039C",mu:"\u03BC",multimap:"\u22B8",mumap:"\u22B8",nabla:"\u2207",Nacute:"\u0143",nacute:"\u0144",nang:"\u2220\u20D2",nap:"\u2249",napE:"\u2A70\u0338",napid:"\u224B\u0338",napos:"\u0149",napprox:"\u2249",natur:"\u266E",natural:"\u266E",naturals:"\u2115",nbsp:"\xA0",nbump:"\u224E\u0338",nbumpe:"\u224F\u0338",ncap:"\u2A43",Ncaron:"\u0147",ncaron:"\u0148",Ncedil:"\u0145",ncedil:"\u0146",ncong:"\u2247",ncongdot:"\u2A6D\u0338",ncup:"\u2A42",Ncy:"\u041D",ncy:"\u043D",ndash:"\u2013",ne:"\u2260",nearhk:"\u2924",neArr:"\u21D7",nearr:"\u2197",nearrow:"\u2197",nedot:"\u2250\u0338",NegativeMediumSpace:"\u200B",NegativeThickSpace:"\u200B",NegativeThinSpace:"\u200B",NegativeVeryThinSpace:"\u200B",nequiv:"\u2262",nesear:"\u2928",nesim:"\u2242\u0338",NestedGreaterGreater:"\u226B",NestedLessLess:"\u226A",NewLine:`
|
|
2
|
-
`,nexist:"\u2204",nexists:"\u2204",Nfr:"\u{1D511}",nfr:"\u{1D52B}",ngE:"\u2267\u0338",nge:"\u2271",ngeq:"\u2271",ngeqq:"\u2267\u0338",ngeqslant:"\u2A7E\u0338",nges:"\u2A7E\u0338",nGg:"\u22D9\u0338",ngsim:"\u2275",nGt:"\u226B\u20D2",ngt:"\u226F",ngtr:"\u226F",nGtv:"\u226B\u0338",nhArr:"\u21CE",nharr:"\u21AE",nhpar:"\u2AF2",ni:"\u220B",nis:"\u22FC",nisd:"\u22FA",niv:"\u220B",NJcy:"\u040A",njcy:"\u045A",nlArr:"\u21CD",nlarr:"\u219A",nldr:"\u2025",nlE:"\u2266\u0338",nle:"\u2270",nLeftarrow:"\u21CD",nleftarrow:"\u219A",nLeftrightarrow:"\u21CE",nleftrightarrow:"\u21AE",nleq:"\u2270",nleqq:"\u2266\u0338",nleqslant:"\u2A7D\u0338",nles:"\u2A7D\u0338",nless:"\u226E",nLl:"\u22D8\u0338",nlsim:"\u2274",nLt:"\u226A\u20D2",nlt:"\u226E",nltri:"\u22EA",nltrie:"\u22EC",nLtv:"\u226A\u0338",nmid:"\u2224",NoBreak:"\u2060",NonBreakingSpace:"\xA0",Nopf:"\u2115",nopf:"\u{1D55F}",Not:"\u2AEC",not:"\xAC",NotCongruent:"\u2262",NotCupCap:"\u226D",NotDoubleVerticalBar:"\u2226",NotElement:"\u2209",NotEqual:"\u2260",NotEqualTilde:"\u2242\u0338",NotExists:"\u2204",NotGreater:"\u226F",NotGreaterEqual:"\u2271",NotGreaterFullEqual:"\u2267\u0338",NotGreaterGreater:"\u226B\u0338",NotGreaterLess:"\u2279",NotGreaterSlantEqual:"\u2A7E\u0338",NotGreaterTilde:"\u2275",NotHumpDownHump:"\u224E\u0338",NotHumpEqual:"\u224F\u0338",notin:"\u2209",notindot:"\u22F5\u0338",notinE:"\u22F9\u0338",notinva:"\u2209",notinvb:"\u22F7",notinvc:"\u22F6",NotLeftTriangle:"\u22EA",NotLeftTriangleBar:"\u29CF\u0338",NotLeftTriangleEqual:"\u22EC",NotLess:"\u226E",NotLessEqual:"\u2270",NotLessGreater:"\u2278",NotLessLess:"\u226A\u0338",NotLessSlantEqual:"\u2A7D\u0338",NotLessTilde:"\u2274",NotNestedGreaterGreater:"\u2AA2\u0338",NotNestedLessLess:"\u2AA1\u0338",notni:"\u220C",notniva:"\u220C",notnivb:"\u22FE",notnivc:"\u22FD",NotPrecedes:"\u2280",NotPrecedesEqual:"\u2AAF\u0338",NotPrecedesSlantEqual:"\u22E0",NotReverseElement:"\u220C",NotRightTriangle:"\u22EB",NotRightTriangleBar:"\u29D0\u0338",NotRightTriangleEqual:"\u22ED",NotSquareSubset:"\u228F\u0338",NotSquareSubsetEqual:"\u22E2",NotSquareSuperset:"\u2290\u0338",NotSquareSupersetEqual:"\u22E3",NotSubset:"\u2282\u20D2",NotSubsetEqual:"\u2288",NotSucceeds:"\u2281",NotSucceedsEqual:"\u2AB0\u0338",NotSucceedsSlantEqual:"\u22E1",NotSucceedsTilde:"\u227F\u0338",NotSuperset:"\u2283\u20D2",NotSupersetEqual:"\u2289",NotTilde:"\u2241",NotTildeEqual:"\u2244",NotTildeFullEqual:"\u2247",NotTildeTilde:"\u2249",NotVerticalBar:"\u2224",npar:"\u2226",nparallel:"\u2226",nparsl:"\u2AFD\u20E5",npart:"\u2202\u0338",npolint:"\u2A14",npr:"\u2280",nprcue:"\u22E0",npre:"\u2AAF\u0338",nprec:"\u2280",npreceq:"\u2AAF\u0338",nrArr:"\u21CF",nrarr:"\u219B",nrarrc:"\u2933\u0338",nrarrw:"\u219D\u0338",nRightarrow:"\u21CF",nrightarrow:"\u219B",nrtri:"\u22EB",nrtrie:"\u22ED",nsc:"\u2281",nsccue:"\u22E1",nsce:"\u2AB0\u0338",Nscr:"\u{1D4A9}",nscr:"\u{1D4C3}",nshortmid:"\u2224",nshortparallel:"\u2226",nsim:"\u2241",nsime:"\u2244",nsimeq:"\u2244",nsmid:"\u2224",nspar:"\u2226",nsqsube:"\u22E2",nsqsupe:"\u22E3",nsub:"\u2284",nsubE:"\u2AC5\u0338",nsube:"\u2288",nsubset:"\u2282\u20D2",nsubseteq:"\u2288",nsubseteqq:"\u2AC5\u0338",nsucc:"\u2281",nsucceq:"\u2AB0\u0338",nsup:"\u2285",nsupE:"\u2AC6\u0338",nsupe:"\u2289",nsupset:"\u2283\u20D2",nsupseteq:"\u2289",nsupseteqq:"\u2AC6\u0338",ntgl:"\u2279",Ntilde:"\xD1",ntilde:"\xF1",ntlg:"\u2278",ntriangleleft:"\u22EA",ntrianglelefteq:"\u22EC",ntriangleright:"\u22EB",ntrianglerighteq:"\u22ED",Nu:"\u039D",nu:"\u03BD",num:"#",numero:"\u2116",numsp:"\u2007",nvap:"\u224D\u20D2",nVDash:"\u22AF",nVdash:"\u22AE",nvDash:"\u22AD",nvdash:"\u22AC",nvge:"\u2265\u20D2",nvgt:">\u20D2",nvHarr:"\u2904",nvinfin:"\u29DE",nvlArr:"\u2902",nvle:"\u2264\u20D2",nvlt:"<\u20D2",nvltrie:"\u22B4\u20D2",nvrArr:"\u2903",nvrtrie:"\u22B5\u20D2",nvsim:"\u223C\u20D2",nwarhk:"\u2923",nwArr:"\u21D6",nwarr:"\u2196",nwarrow:"\u2196",nwnear:"\u2927",Oacute:"\xD3",oacute:"\xF3",oast:"\u229B",ocir:"\u229A",Ocirc:"\xD4",ocirc:"\xF4",Ocy:"\u041E",ocy:"\u043E",odash:"\u229D",Odblac:"\u0150",odblac:"\u0151",odiv:"\u2A38",odot:"\u2299",odsold:"\u29BC",OElig:"\u0152",oelig:"\u0153",ofcir:"\u29BF",Ofr:"\u{1D512}",ofr:"\u{1D52C}",ogon:"\u02DB",Ograve:"\xD2",ograve:"\xF2",ogt:"\u29C1",ohbar:"\u29B5",ohm:"\u03A9",oint:"\u222E",olarr:"\u21BA",olcir:"\u29BE",olcross:"\u29BB",oline:"\u203E",olt:"\u29C0",Omacr:"\u014C",omacr:"\u014D",Omega:"\u03A9",omega:"\u03C9",Omicron:"\u039F",omicron:"\u03BF",omid:"\u29B6",ominus:"\u2296",Oopf:"\u{1D546}",oopf:"\u{1D560}",opar:"\u29B7",OpenCurlyDoubleQuote:"\u201C",OpenCurlyQuote:"\u2018",operp:"\u29B9",oplus:"\u2295",Or:"\u2A54",or:"\u2228",orarr:"\u21BB",ord:"\u2A5D",order:"\u2134",orderof:"\u2134",ordf:"\xAA",ordm:"\xBA",origof:"\u22B6",oror:"\u2A56",orslope:"\u2A57",orv:"\u2A5B",oS:"\u24C8",Oscr:"\u{1D4AA}",oscr:"\u2134",Oslash:"\xD8",oslash:"\xF8",osol:"\u2298",Otilde:"\xD5",otilde:"\xF5",Otimes:"\u2A37",otimes:"\u2297",otimesas:"\u2A36",Ouml:"\xD6",ouml:"\xF6",ovbar:"\u233D",OverBar:"\u203E",OverBrace:"\u23DE",OverBracket:"\u23B4",OverParenthesis:"\u23DC",par:"\u2225",para:"\xB6",parallel:"\u2225",parsim:"\u2AF3",parsl:"\u2AFD",part:"\u2202",PartialD:"\u2202",Pcy:"\u041F",pcy:"\u043F",percnt:"%",period:".",permil:"\u2030",perp:"\u22A5",pertenk:"\u2031",Pfr:"\u{1D513}",pfr:"\u{1D52D}",Phi:"\u03A6",phi:"\u03C6",phiv:"\u03D5",phmmat:"\u2133",phone:"\u260E",Pi:"\u03A0",pi:"\u03C0",pitchfork:"\u22D4",piv:"\u03D6",planck:"\u210F",planckh:"\u210E",plankv:"\u210F",plus:"+",plusacir:"\u2A23",plusb:"\u229E",pluscir:"\u2A22",plusdo:"\u2214",plusdu:"\u2A25",pluse:"\u2A72",PlusMinus:"\xB1",plusmn:"\xB1",plussim:"\u2A26",plustwo:"\u2A27",pm:"\xB1",Poincareplane:"\u210C",pointint:"\u2A15",Popf:"\u2119",popf:"\u{1D561}",pound:"\xA3",Pr:"\u2ABB",pr:"\u227A",prap:"\u2AB7",prcue:"\u227C",prE:"\u2AB3",pre:"\u2AAF",prec:"\u227A",precapprox:"\u2AB7",preccurlyeq:"\u227C",Precedes:"\u227A",PrecedesEqual:"\u2AAF",PrecedesSlantEqual:"\u227C",PrecedesTilde:"\u227E",preceq:"\u2AAF",precnapprox:"\u2AB9",precneqq:"\u2AB5",precnsim:"\u22E8",precsim:"\u227E",Prime:"\u2033",prime:"\u2032",primes:"\u2119",prnap:"\u2AB9",prnE:"\u2AB5",prnsim:"\u22E8",prod:"\u220F",Product:"\u220F",profalar:"\u232E",profline:"\u2312",profsurf:"\u2313",prop:"\u221D",Proportion:"\u2237",Proportional:"\u221D",propto:"\u221D",prsim:"\u227E",prurel:"\u22B0",Pscr:"\u{1D4AB}",pscr:"\u{1D4C5}",Psi:"\u03A8",psi:"\u03C8",puncsp:"\u2008",Qfr:"\u{1D514}",qfr:"\u{1D52E}",qint:"\u2A0C",Qopf:"\u211A",qopf:"\u{1D562}",qprime:"\u2057",Qscr:"\u{1D4AC}",qscr:"\u{1D4C6}",quaternions:"\u210D",quatint:"\u2A16",quest:"?",questeq:"\u225F",QUOT:'"',quot:'"',rAarr:"\u21DB",race:"\u223D\u0331",Racute:"\u0154",racute:"\u0155",radic:"\u221A",raemptyv:"\u29B3",Rang:"\u27EB",rang:"\u27E9",rangd:"\u2992",range:"\u29A5",rangle:"\u27E9",raquo:"\xBB",Rarr:"\u21A0",rArr:"\u21D2",rarr:"\u2192",rarrap:"\u2975",rarrb:"\u21E5",rarrbfs:"\u2920",rarrc:"\u2933",rarrfs:"\u291E",rarrhk:"\u21AA",rarrlp:"\u21AC",rarrpl:"\u2945",rarrsim:"\u2974",Rarrtl:"\u2916",rarrtl:"\u21A3",rarrw:"\u219D",rAtail:"\u291C",ratail:"\u291A",ratio:"\u2236",rationals:"\u211A",RBarr:"\u2910",rBarr:"\u290F",rbarr:"\u290D",rbbrk:"\u2773",rbrace:"}",rbrack:"]",rbrke:"\u298C",rbrksld:"\u298E",rbrkslu:"\u2990",Rcaron:"\u0158",rcaron:"\u0159",Rcedil:"\u0156",rcedil:"\u0157",rceil:"\u2309",rcub:"}",Rcy:"\u0420",rcy:"\u0440",rdca:"\u2937",rdldhar:"\u2969",rdquo:"\u201D",rdquor:"\u201D",rdsh:"\u21B3",Re:"\u211C",real:"\u211C",realine:"\u211B",realpart:"\u211C",reals:"\u211D",rect:"\u25AD",REG:"\xAE",reg:"\xAE",ReverseElement:"\u220B",ReverseEquilibrium:"\u21CB",ReverseUpEquilibrium:"\u296F",rfisht:"\u297D",rfloor:"\u230B",Rfr:"\u211C",rfr:"\u{1D52F}",rHar:"\u2964",rhard:"\u21C1",rharu:"\u21C0",rharul:"\u296C",Rho:"\u03A1",rho:"\u03C1",rhov:"\u03F1",RightAngleBracket:"\u27E9",RightArrow:"\u2192",Rightarrow:"\u21D2",rightarrow:"\u2192",RightArrowBar:"\u21E5",RightArrowLeftArrow:"\u21C4",rightarrowtail:"\u21A3",RightCeiling:"\u2309",RightDoubleBracket:"\u27E7",RightDownTeeVector:"\u295D",RightDownVector:"\u21C2",RightDownVectorBar:"\u2955",RightFloor:"\u230B",rightharpoondown:"\u21C1",rightharpoonup:"\u21C0",rightleftarrows:"\u21C4",rightleftharpoons:"\u21CC",rightrightarrows:"\u21C9",rightsquigarrow:"\u219D",RightTee:"\u22A2",RightTeeArrow:"\u21A6",RightTeeVector:"\u295B",rightthreetimes:"\u22CC",RightTriangle:"\u22B3",RightTriangleBar:"\u29D0",RightTriangleEqual:"\u22B5",RightUpDownVector:"\u294F",RightUpTeeVector:"\u295C",RightUpVector:"\u21BE",RightUpVectorBar:"\u2954",RightVector:"\u21C0",RightVectorBar:"\u2953",ring:"\u02DA",risingdotseq:"\u2253",rlarr:"\u21C4",rlhar:"\u21CC",rlm:"\u200F",rmoust:"\u23B1",rmoustache:"\u23B1",rnmid:"\u2AEE",roang:"\u27ED",roarr:"\u21FE",robrk:"\u27E7",ropar:"\u2986",Ropf:"\u211D",ropf:"\u{1D563}",roplus:"\u2A2E",rotimes:"\u2A35",RoundImplies:"\u2970",rpar:")",rpargt:"\u2994",rppolint:"\u2A12",rrarr:"\u21C9",Rrightarrow:"\u21DB",rsaquo:"\u203A",Rscr:"\u211B",rscr:"\u{1D4C7}",Rsh:"\u21B1",rsh:"\u21B1",rsqb:"]",rsquo:"\u2019",rsquor:"\u2019",rthree:"\u22CC",rtimes:"\u22CA",rtri:"\u25B9",rtrie:"\u22B5",rtrif:"\u25B8",rtriltri:"\u29CE",RuleDelayed:"\u29F4",ruluhar:"\u2968",rx:"\u211E",Sacute:"\u015A",sacute:"\u015B",sbquo:"\u201A",Sc:"\u2ABC",sc:"\u227B",scap:"\u2AB8",Scaron:"\u0160",scaron:"\u0161",sccue:"\u227D",scE:"\u2AB4",sce:"\u2AB0",Scedil:"\u015E",scedil:"\u015F",Scirc:"\u015C",scirc:"\u015D",scnap:"\u2ABA",scnE:"\u2AB6",scnsim:"\u22E9",scpolint:"\u2A13",scsim:"\u227F",Scy:"\u0421",scy:"\u0441",sdot:"\u22C5",sdotb:"\u22A1",sdote:"\u2A66",searhk:"\u2925",seArr:"\u21D8",searr:"\u2198",searrow:"\u2198",sect:"\xA7",semi:";",seswar:"\u2929",setminus:"\u2216",setmn:"\u2216",sext:"\u2736",Sfr:"\u{1D516}",sfr:"\u{1D530}",sfrown:"\u2322",sharp:"\u266F",SHCHcy:"\u0429",shchcy:"\u0449",SHcy:"\u0428",shcy:"\u0448",ShortDownArrow:"\u2193",ShortLeftArrow:"\u2190",shortmid:"\u2223",shortparallel:"\u2225",ShortRightArrow:"\u2192",ShortUpArrow:"\u2191",shy:"\xAD",Sigma:"\u03A3",sigma:"\u03C3",sigmaf:"\u03C2",sigmav:"\u03C2",sim:"\u223C",simdot:"\u2A6A",sime:"\u2243",simeq:"\u2243",simg:"\u2A9E",simgE:"\u2AA0",siml:"\u2A9D",simlE:"\u2A9F",simne:"\u2246",simplus:"\u2A24",simrarr:"\u2972",slarr:"\u2190",SmallCircle:"\u2218",smallsetminus:"\u2216",smashp:"\u2A33",smeparsl:"\u29E4",smid:"\u2223",smile:"\u2323",smt:"\u2AAA",smte:"\u2AAC",smtes:"\u2AAC\uFE00",SOFTcy:"\u042C",softcy:"\u044C",sol:"/",solb:"\u29C4",solbar:"\u233F",Sopf:"\u{1D54A}",sopf:"\u{1D564}",spades:"\u2660",spadesuit:"\u2660",spar:"\u2225",sqcap:"\u2293",sqcaps:"\u2293\uFE00",sqcup:"\u2294",sqcups:"\u2294\uFE00",Sqrt:"\u221A",sqsub:"\u228F",sqsube:"\u2291",sqsubset:"\u228F",sqsubseteq:"\u2291",sqsup:"\u2290",sqsupe:"\u2292",sqsupset:"\u2290",sqsupseteq:"\u2292",squ:"\u25A1",Square:"\u25A1",square:"\u25A1",SquareIntersection:"\u2293",SquareSubset:"\u228F",SquareSubsetEqual:"\u2291",SquareSuperset:"\u2290",SquareSupersetEqual:"\u2292",SquareUnion:"\u2294",squarf:"\u25AA",squf:"\u25AA",srarr:"\u2192",Sscr:"\u{1D4AE}",sscr:"\u{1D4C8}",ssetmn:"\u2216",ssmile:"\u2323",sstarf:"\u22C6",Star:"\u22C6",star:"\u2606",starf:"\u2605",straightepsilon:"\u03F5",straightphi:"\u03D5",strns:"\xAF",Sub:"\u22D0",sub:"\u2282",subdot:"\u2ABD",subE:"\u2AC5",sube:"\u2286",subedot:"\u2AC3",submult:"\u2AC1",subnE:"\u2ACB",subne:"\u228A",subplus:"\u2ABF",subrarr:"\u2979",Subset:"\u22D0",subset:"\u2282",subseteq:"\u2286",subseteqq:"\u2AC5",SubsetEqual:"\u2286",subsetneq:"\u228A",subsetneqq:"\u2ACB",subsim:"\u2AC7",subsub:"\u2AD5",subsup:"\u2AD3",succ:"\u227B",succapprox:"\u2AB8",succcurlyeq:"\u227D",Succeeds:"\u227B",SucceedsEqual:"\u2AB0",SucceedsSlantEqual:"\u227D",SucceedsTilde:"\u227F",succeq:"\u2AB0",succnapprox:"\u2ABA",succneqq:"\u2AB6",succnsim:"\u22E9",succsim:"\u227F",SuchThat:"\u220B",Sum:"\u2211",sum:"\u2211",sung:"\u266A",Sup:"\u22D1",sup:"\u2283",sup1:"\xB9",sup2:"\xB2",sup3:"\xB3",supdot:"\u2ABE",supdsub:"\u2AD8",supE:"\u2AC6",supe:"\u2287",supedot:"\u2AC4",Superset:"\u2283",SupersetEqual:"\u2287",suphsol:"\u27C9",suphsub:"\u2AD7",suplarr:"\u297B",supmult:"\u2AC2",supnE:"\u2ACC",supne:"\u228B",supplus:"\u2AC0",Supset:"\u22D1",supset:"\u2283",supseteq:"\u2287",supseteqq:"\u2AC6",supsetneq:"\u228B",supsetneqq:"\u2ACC",supsim:"\u2AC8",supsub:"\u2AD4",supsup:"\u2AD6",swarhk:"\u2926",swArr:"\u21D9",swarr:"\u2199",swarrow:"\u2199",swnwar:"\u292A",szlig:"\xDF",Tab:" ",target:"\u2316",Tau:"\u03A4",tau:"\u03C4",tbrk:"\u23B4",Tcaron:"\u0164",tcaron:"\u0165",Tcedil:"\u0162",tcedil:"\u0163",Tcy:"\u0422",tcy:"\u0442",tdot:"\u20DB",telrec:"\u2315",Tfr:"\u{1D517}",tfr:"\u{1D531}",there4:"\u2234",Therefore:"\u2234",therefore:"\u2234",Theta:"\u0398",theta:"\u03B8",thetasym:"\u03D1",thetav:"\u03D1",thickapprox:"\u2248",thicksim:"\u223C",ThickSpace:"\u205F\u200A",thinsp:"\u2009",ThinSpace:"\u2009",thkap:"\u2248",thksim:"\u223C",THORN:"\xDE",thorn:"\xFE",Tilde:"\u223C",tilde:"\u02DC",TildeEqual:"\u2243",TildeFullEqual:"\u2245",TildeTilde:"\u2248",times:"\xD7",timesb:"\u22A0",timesbar:"\u2A31",timesd:"\u2A30",tint:"\u222D",toea:"\u2928",top:"\u22A4",topbot:"\u2336",topcir:"\u2AF1",Topf:"\u{1D54B}",topf:"\u{1D565}",topfork:"\u2ADA",tosa:"\u2929",tprime:"\u2034",TRADE:"\u2122",trade:"\u2122",triangle:"\u25B5",triangledown:"\u25BF",triangleleft:"\u25C3",trianglelefteq:"\u22B4",triangleq:"\u225C",triangleright:"\u25B9",trianglerighteq:"\u22B5",tridot:"\u25EC",trie:"\u225C",triminus:"\u2A3A",TripleDot:"\u20DB",triplus:"\u2A39",trisb:"\u29CD",tritime:"\u2A3B",trpezium:"\u23E2",Tscr:"\u{1D4AF}",tscr:"\u{1D4C9}",TScy:"\u0426",tscy:"\u0446",TSHcy:"\u040B",tshcy:"\u045B",Tstrok:"\u0166",tstrok:"\u0167",twixt:"\u226C",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",Uacute:"\xDA",uacute:"\xFA",Uarr:"\u219F",uArr:"\u21D1",uarr:"\u2191",Uarrocir:"\u2949",Ubrcy:"\u040E",ubrcy:"\u045E",Ubreve:"\u016C",ubreve:"\u016D",Ucirc:"\xDB",ucirc:"\xFB",Ucy:"\u0423",ucy:"\u0443",udarr:"\u21C5",Udblac:"\u0170",udblac:"\u0171",udhar:"\u296E",ufisht:"\u297E",Ufr:"\u{1D518}",ufr:"\u{1D532}",Ugrave:"\xD9",ugrave:"\xF9",uHar:"\u2963",uharl:"\u21BF",uharr:"\u21BE",uhblk:"\u2580",ulcorn:"\u231C",ulcorner:"\u231C",ulcrop:"\u230F",ultri:"\u25F8",Umacr:"\u016A",umacr:"\u016B",uml:"\xA8",UnderBar:"_",UnderBrace:"\u23DF",UnderBracket:"\u23B5",UnderParenthesis:"\u23DD",Union:"\u22C3",UnionPlus:"\u228E",Uogon:"\u0172",uogon:"\u0173",Uopf:"\u{1D54C}",uopf:"\u{1D566}",UpArrow:"\u2191",Uparrow:"\u21D1",uparrow:"\u2191",UpArrowBar:"\u2912",UpArrowDownArrow:"\u21C5",UpDownArrow:"\u2195",Updownarrow:"\u21D5",updownarrow:"\u2195",UpEquilibrium:"\u296E",upharpoonleft:"\u21BF",upharpoonright:"\u21BE",uplus:"\u228E",UpperLeftArrow:"\u2196",UpperRightArrow:"\u2197",Upsi:"\u03D2",upsi:"\u03C5",upsih:"\u03D2",Upsilon:"\u03A5",upsilon:"\u03C5",UpTee:"\u22A5",UpTeeArrow:"\u21A5",upuparrows:"\u21C8",urcorn:"\u231D",urcorner:"\u231D",urcrop:"\u230E",Uring:"\u016E",uring:"\u016F",urtri:"\u25F9",Uscr:"\u{1D4B0}",uscr:"\u{1D4CA}",utdot:"\u22F0",Utilde:"\u0168",utilde:"\u0169",utri:"\u25B5",utrif:"\u25B4",uuarr:"\u21C8",Uuml:"\xDC",uuml:"\xFC",uwangle:"\u29A7",vangrt:"\u299C",varepsilon:"\u03F5",varkappa:"\u03F0",varnothing:"\u2205",varphi:"\u03D5",varpi:"\u03D6",varpropto:"\u221D",vArr:"\u21D5",varr:"\u2195",varrho:"\u03F1",varsigma:"\u03C2",varsubsetneq:"\u228A\uFE00",varsubsetneqq:"\u2ACB\uFE00",varsupsetneq:"\u228B\uFE00",varsupsetneqq:"\u2ACC\uFE00",vartheta:"\u03D1",vartriangleleft:"\u22B2",vartriangleright:"\u22B3",Vbar:"\u2AEB",vBar:"\u2AE8",vBarv:"\u2AE9",Vcy:"\u0412",vcy:"\u0432",VDash:"\u22AB",Vdash:"\u22A9",vDash:"\u22A8",vdash:"\u22A2",Vdashl:"\u2AE6",Vee:"\u22C1",vee:"\u2228",veebar:"\u22BB",veeeq:"\u225A",vellip:"\u22EE",Verbar:"\u2016",verbar:"|",Vert:"\u2016",vert:"|",VerticalBar:"\u2223",VerticalLine:"|",VerticalSeparator:"\u2758",VerticalTilde:"\u2240",VeryThinSpace:"\u200A",Vfr:"\u{1D519}",vfr:"\u{1D533}",vltri:"\u22B2",vnsub:"\u2282\u20D2",vnsup:"\u2283\u20D2",Vopf:"\u{1D54D}",vopf:"\u{1D567}",vprop:"\u221D",vrtri:"\u22B3",Vscr:"\u{1D4B1}",vscr:"\u{1D4CB}",vsubnE:"\u2ACB\uFE00",vsubne:"\u228A\uFE00",vsupnE:"\u2ACC\uFE00",vsupne:"\u228B\uFE00",Vvdash:"\u22AA",vzigzag:"\u299A",Wcirc:"\u0174",wcirc:"\u0175",wedbar:"\u2A5F",Wedge:"\u22C0",wedge:"\u2227",wedgeq:"\u2259",weierp:"\u2118",Wfr:"\u{1D51A}",wfr:"\u{1D534}",Wopf:"\u{1D54E}",wopf:"\u{1D568}",wp:"\u2118",wr:"\u2240",wreath:"\u2240",Wscr:"\u{1D4B2}",wscr:"\u{1D4CC}",xcap:"\u22C2",xcirc:"\u25EF",xcup:"\u22C3",xdtri:"\u25BD",Xfr:"\u{1D51B}",xfr:"\u{1D535}",xhArr:"\u27FA",xharr:"\u27F7",Xi:"\u039E",xi:"\u03BE",xlArr:"\u27F8",xlarr:"\u27F5",xmap:"\u27FC",xnis:"\u22FB",xodot:"\u2A00",Xopf:"\u{1D54F}",xopf:"\u{1D569}",xoplus:"\u2A01",xotime:"\u2A02",xrArr:"\u27F9",xrarr:"\u27F6",Xscr:"\u{1D4B3}",xscr:"\u{1D4CD}",xsqcup:"\u2A06",xuplus:"\u2A04",xutri:"\u25B3",xvee:"\u22C1",xwedge:"\u22C0",Yacute:"\xDD",yacute:"\xFD",YAcy:"\u042F",yacy:"\u044F",Ycirc:"\u0176",ycirc:"\u0177",Ycy:"\u042B",ycy:"\u044B",yen:"\xA5",Yfr:"\u{1D51C}",yfr:"\u{1D536}",YIcy:"\u0407",yicy:"\u0457",Yopf:"\u{1D550}",yopf:"\u{1D56A}",Yscr:"\u{1D4B4}",yscr:"\u{1D4CE}",YUcy:"\u042E",yucy:"\u044E",Yuml:"\u0178",yuml:"\xFF",Zacute:"\u0179",zacute:"\u017A",Zcaron:"\u017D",zcaron:"\u017E",Zcy:"\u0417",zcy:"\u0437",Zdot:"\u017B",zdot:"\u017C",zeetrf:"\u2128",ZeroWidthSpace:"\u200B",Zeta:"\u0396",zeta:"\u03B6",Zfr:"\u2128",zfr:"\u{1D537}",ZHcy:"\u0416",zhcy:"\u0436",zigrarr:"\u21DD",Zopf:"\u2124",zopf:"\u{1D56B}",Zscr:"\u{1D4B5}",zscr:"\u{1D4CF}",zwj:"\u200D",zwnj:"\u200C"});ei.entityMap=ei.HTML_ENTITIES});var $a=Kt(Fs=>{var ni=Qr().NAMESPACE,Is=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,Va=new RegExp("[\\-\\.0-9"+Is.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),La=new RegExp("^"+Is.source+Va.source+"*(?::"+Is.source+Va.source+"*)?$"),ti=0,mt=1,nr=2,ri=3,sr=4,or=5,ii=6,un=7;function ar(t,e){this.message=t,this.locator=e,Error.captureStackTrace&&Error.captureStackTrace(this,ar)}ar.prototype=new Error;ar.prototype.name=ar.name;function Wa(){}Wa.prototype={parse:function(t,e,r){var i=this.domBuilder;i.startDocument(),Ga(e,e={}),ql(t,e,r,i,this.errorHandler),i.endDocument()}};function ql(t,e,r,i,n){function s(X){if(X>65535){X-=65536;var Ce=55296+(X>>10),fl=56320+(X&1023);return String.fromCharCode(Ce,fl)}else return String.fromCharCode(X)}function o(X){var Ce=X.slice(1,-1);return Object.hasOwnProperty.call(r,Ce)?r[Ce]:Ce.charAt(0)==="#"?s(parseInt(Ce.substr(1).replace("x","0x"))):(n.error("entity not found:"+X),X)}function a(X){if(X>g){var Ce=t.substring(g,X).replace(/&#?\w+;/g,o);f&&c(g),i.characters(Ce,0,X-g),g=X}}function c(X,Ce){for(;X>=l&&(Ce=d.exec(t));)u=Ce.index,l=u+Ce[0].length,f.lineNumber++;f.columnNumber=X-u+1}for(var u=0,l=0,d=/.*(?:\r\n?|\n)|.*$/g,f=i.locator,m=[{currentNSMap:e}],p={},g=0;;){try{var b=t.indexOf("<",g);if(b<0){if(!t.substr(g).match(/^\s*$/)){var w=i.doc,x=w.createTextNode(t.substr(g));w.appendChild(x),i.currentElement=x}return}switch(b>g&&a(b),t.charAt(b+1)){case"/":var B=t.indexOf(">",b+3),y=t.substring(b+2,B).replace(/[ \t\n\r]+$/g,""),T=m.pop();B<0?(y=t.substring(b+2).replace(/[\s<].*/,""),n.error("end tag name: "+y+" is not complete:"+T.tagName),B=b+1+y.length):y.match(/\s</)&&(y=y.replace(/[\s<].*/,""),n.error("end tag name: "+y+" maybe not complete"),B=b+1+y.length);var E=T.localNSMap,S=T.tagName==y,P=S||T.tagName&&T.tagName.toLowerCase()==y.toLowerCase();if(P){if(i.endElement(T.uri,T.localName,y),E)for(var v in E)Object.prototype.hasOwnProperty.call(E,v)&&i.endPrefixMapping(v);S||n.fatalError("end tag name: "+y+" is not match the current start tagName:"+T.tagName)}else m.push(T);B++;break;case"?":f&&c(b),B=$l(t,b,i);break;case"!":f&&c(b),B=jl(t,b,i,n);break;default:f&&c(b);var F=new ja,M=m[m.length-1].currentNSMap,B=Hl(t,b,F,M,o,n),Q=F.length;if(!F.closed&&Gl(t,B,F.tagName,p)&&(F.closed=!0,r.nbsp||n.warning("unclosed xml attribute")),f&&Q){for(var je=qa(f,{}),Ui=0;Ui<Q;Ui++){var Vo=F[Ui];c(Vo.offset),Vo.locator=qa(f,{})}i.locator=je,Ha(F,i,M)&&m.push(F),i.locator=f}else Ha(F,i,M)&&m.push(F);ni.isHTML(F.uri)&&!F.closed?B=Wl(t,B,F.tagName,o,i):B++}}catch(X){if(X instanceof ar)throw X;n.error("element parse error: "+X),B=-1}B>g?g=B:a(Math.max(b,g)+1)}}function qa(t,e){return e.lineNumber=t.lineNumber,e.columnNumber=t.columnNumber,e}function Hl(t,e,r,i,n,s){function o(m,p,g){r.attributeNames.hasOwnProperty(m)&&s.fatalError("Attribute "+m+" redefined"),r.addValue(m,p.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,n),g)}for(var a,c,u=++e,l=ti;;){var d=t.charAt(u);switch(d){case"=":if(l===mt)a=t.slice(e,u),l=ri;else if(l===nr)l=ri;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(l===ri||l===mt)if(l===mt&&(s.warning('attribute value must after "="'),a=t.slice(e,u)),e=u+1,u=t.indexOf(d,e),u>0)c=t.slice(e,u),o(a,c,e-1),l=or;else throw new Error("attribute value no end '"+d+"' match");else if(l==sr)c=t.slice(e,u),o(a,c,e),s.warning('attribute "'+a+'" missed start quot('+d+")!!"),e=u+1,l=or;else throw new Error('attribute value must after "="');break;case"/":switch(l){case ti:r.setTagName(t.slice(e,u));case or:case ii:case un:l=un,r.closed=!0;case sr:case mt:break;case nr:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return s.error("unexpected end of input"),l==ti&&r.setTagName(t.slice(e,u)),u;case">":switch(l){case ti:r.setTagName(t.slice(e,u));case or:case ii:case un:break;case sr:case mt:c=t.slice(e,u),c.slice(-1)==="/"&&(r.closed=!0,c=c.slice(0,-1));case nr:l===nr&&(c=a),l==sr?(s.warning('attribute "'+c+'" missed quot(")!'),o(a,c,e)):((!ni.isHTML(i[""])||!c.match(/^(?:disabled|checked|selected)$/i))&&s.warning('attribute "'+c+'" missed value!! "'+c+'" instead!!'),o(c,c,e));break;case ri:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(l){case ti:r.setTagName(t.slice(e,u)),l=ii;break;case mt:a=t.slice(e,u),l=nr;break;case sr:var c=t.slice(e,u);s.warning('attribute "'+c+'" missed quot(")!!'),o(a,c,e);case or:l=ii;break}else switch(l){case nr:var f=r.tagName;(!ni.isHTML(i[""])||!a.match(/^(?:disabled|checked|selected)$/i))&&s.warning('attribute "'+a+'" missed value!! "'+a+'" instead2!!'),o(a,a,e),e=u,l=mt;break;case or:s.warning('attribute space is required"'+a+'"!!');case ii:l=mt,e=u;break;case ri:l=sr,e=u;break;case un:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function Ha(t,e,r){for(var i=t.tagName,n=null,d=t.length;d--;){var s=t[d],o=s.qName,a=s.value,f=o.indexOf(":");if(f>0)var c=s.prefix=o.slice(0,f),u=o.slice(f+1),l=c==="xmlns"&&u;else u=o,c=null,l=o==="xmlns"&&"";s.localName=u,l!==!1&&(n==null&&(n={},Ga(r,r={})),r[l]=n[l]=a,s.uri=ni.XMLNS,e.startPrefixMapping(l,a))}for(var d=t.length;d--;){s=t[d];var c=s.prefix;c&&(c==="xml"&&(s.uri=ni.XML),c!=="xmlns"&&(s.uri=r[c||""]))}var f=i.indexOf(":");f>0?(c=t.prefix=i.slice(0,f),u=t.localName=i.slice(f+1)):(c=null,u=t.localName=i);var m=t.uri=r[c||""];if(e.startElement(m,u,i,t),t.closed){if(e.endElement(m,u,i),n)for(c in n)Object.prototype.hasOwnProperty.call(n,c)&&e.endPrefixMapping(c)}else return t.currentNSMap=r,t.localNSMap=n,!0}function Wl(t,e,r,i,n){if(/^(?:script|textarea)$/i.test(r)){var s=t.indexOf("</"+r+">",e),o=t.substring(e+1,s);if(/[&<]/.test(o))return/^script$/i.test(r)?(n.characters(o,0,o.length),s):(o=o.replace(/&#?\w+;/g,i),n.characters(o,0,o.length),s)}return e+1}function Gl(t,e,r,i){var n=i[r];return n==null&&(n=t.lastIndexOf("</"+r+">"),n<e&&(n=t.lastIndexOf("</"+r)),i[r]=n),n<e}function Ga(t,e){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}function jl(t,e,r,i){var n=t.charAt(e+2);switch(n){case"-":if(t.charAt(e+3)==="-"){var s=t.indexOf("-->",e+4);return s>e?(r.comment(t,e+4,s-e-4),s+3):(i.error("Unclosed comment"),-1)}else return-1;default:if(t.substr(e+3,6)=="CDATA["){var s=t.indexOf("]]>",e+9);return r.startCDATA(),r.characters(t,e+9,s-e-9),r.endCDATA(),s+3}var o=Ql(t,e),a=o.length;if(a>1&&/!doctype/i.test(o[0][0])){var c=o[1][0],u=!1,l=!1;a>3&&(/^public$/i.test(o[2][0])?(u=o[3][0],l=a>4&&o[4][0]):/^system$/i.test(o[2][0])&&(l=o[3][0]));var d=o[a-1];return r.startDTD(c,u,l),r.endDTD(),d.index+d[0].length}}return-1}function $l(t,e,r){var i=t.indexOf("?>",e);if(i){var n=t.substring(e,i).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);if(n){var s=n[0].length;return r.processingInstruction(n[1],n[2]),i+2}else return-1}return-1}function ja(){this.attributeNames={}}ja.prototype={setTagName:function(t){if(!La.test(t))throw new Error("invalid tagName:"+t);this.tagName=t},addValue:function(t,e,r){if(!La.test(t))throw new Error("invalid attribute:"+t);this.attributeNames[t]=this.length,this[this.length++]={qName:t,value:e,offset:r}},length:0,getLocalName:function(t){return this[t].localName},getLocator:function(t){return this[t].locator},getQName:function(t){return this[t].qName},getURI:function(t){return this[t].uri},getValue:function(t){return this[t].value}};function Ql(t,e){var r,i=[],n=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(n.lastIndex=e,n.exec(t);r=n.exec(t);)if(i.push(r),r[1])return i}Fs.XMLReader=Wa;Fs.ParseError=ar});var ec=Kt(dn=>{var Xl=Qr(),Kl=Ds(),Qa=za(),Ya=$a(),Yl=Kl.DOMImplementation,Xa=Xl.NAMESPACE,Zl=Ya.ParseError,Jl=Ya.XMLReader;function Za(t){return t.replace(/\r[\n\u0085]/g,`
|
|
3
|
-
|
|
4
|
-
`)}function Ja(t){this.options=t||{locator:{}}}Ja.prototype.parseFromString=function(t,e){var r=this.options,i=new Jl,n=r.domBuilder||new si,s=r.errorHandler,o=r.locator,a=r.xmlns||{},c=/\/x?html?$/.test(e),u=c?Qa.HTML_ENTITIES:Qa.XML_ENTITIES;o&&n.setDocumentLocator(o),i.errorHandler=ed(s,n,o),i.domBuilder=r.domBuilder||n,c&&(a[""]=Xa.HTML),a.xml=a.xml||Xa.XML;var l=r.normalizeLineEndings||Za;return t&&typeof t=="string"?i.parse(l(t),a,u):i.errorHandler.error("invalid doc source"),n.doc};function ed(t,e,r){if(!t){if(e instanceof si)return e;t=e}var i={},n=t instanceof Function;r=r||{};function s(o){var a=t[o];!a&&n&&(a=t.length==2?function(c){t(o,c)}:t),i[o]=a&&function(c){a("[xmldom "+o+"] "+c+Bs(r))}||function(){}}return s("warning"),s("error"),s("fatalError"),i}function si(){this.cdata=!1}function cr(t,e){e.lineNumber=t.lineNumber,e.columnNumber=t.columnNumber}si.prototype={startDocument:function(){this.doc=new Yl().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(t,e,r,i){var n=this.doc,s=n.createElementNS(t,r||e),o=i.length;ln(this,s),this.currentElement=s,this.locator&&cr(this.locator,s);for(var a=0;a<o;a++){var t=i.getURI(a),c=i.getValue(a),r=i.getQName(a),u=n.createAttributeNS(t,r);this.locator&&cr(i.getLocator(a),u),u.value=u.nodeValue=c,s.setAttributeNode(u)}},endElement:function(t,e,r){var i=this.currentElement,n=i.tagName;this.currentElement=i.parentNode},startPrefixMapping:function(t,e){},endPrefixMapping:function(t){},processingInstruction:function(t,e){var r=this.doc.createProcessingInstruction(t,e);this.locator&&cr(this.locator,r),ln(this,r)},ignorableWhitespace:function(t,e,r){},characters:function(t,e,r){if(t=Ka.apply(this,arguments),t){if(this.cdata)var i=this.doc.createCDATASection(t);else var i=this.doc.createTextNode(t);this.currentElement?this.currentElement.appendChild(i):/^\s*$/.test(t)&&this.doc.appendChild(i),this.locator&&cr(this.locator,i)}},skippedEntity:function(t){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(t){(this.locator=t)&&(t.lineNumber=0)},comment:function(t,e,r){t=Ka.apply(this,arguments);var i=this.doc.createComment(t);this.locator&&cr(this.locator,i),ln(this,i)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(t,e,r){var i=this.doc.implementation;if(i&&i.createDocumentType){var n=i.createDocumentType(t,e,r);this.locator&&cr(this.locator,n),ln(this,n),this.doc.doctype=n}},warning:function(t){console.warn("[xmldom warning] "+t,Bs(this.locator))},error:function(t){console.error("[xmldom error] "+t,Bs(this.locator))},fatalError:function(t){throw new Zl(t,this.locator)}};function Bs(t){if(t)return`
|
|
5
|
-
@`+(t.systemId||"")+"#[line:"+t.lineNumber+",col:"+t.columnNumber+"]"}function Ka(t,e,r){return typeof t=="string"?t.substr(e,r):t.length>=e+r||e?new java.lang.String(t,e,r)+"":t}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(t){si.prototype[t]=function(){return null}});function ln(t,e){t.currentElement?t.currentElement.appendChild(e):t.doc.appendChild(e)}dn.__DOMHandler=si;dn.normalizeLineEndings=Za;dn.DOMParser=Ja});var rc=Kt(fn=>{var tc=Ds();fn.DOMImplementation=tc.DOMImplementation;fn.XMLSerializer=tc.XMLSerializer;fn.DOMParser=ec().DOMParser});function hs(t,e){return{error:r=>t.error({...e,...r}),rpcRequest:r=>t.rpcRequest({...e,...r}),rpcError:r=>t.rpcError({...e,...r})}}var Vi=()=>t=>({plain:t.none,errMessage:t.mix(t.brightRed,t.bold),errName:t.red,errStack:t.mix(t.red,t.dim),timestamp:t.blue,timestampErr:t.red});function qo(){return Vi()}var dt=Object.freeze({black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",brightBlack:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightBlue:"\x1B[94m",brightMagenta:"\x1B[95m",brightCyan:"\x1B[96m",brightWhite:"\x1B[97m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgBrightBlack:"\x1B[100m",bgBrightRed:"\x1B[101m",bgBrightGreen:"\x1B[102m",bgBrightYellow:"\x1B[103m",bgBrightBlue:"\x1B[104m",bgBrightMagenta:"\x1B[105m",bgBrightCyan:"\x1B[106m",bgBrightWhite:"\x1B[107m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",inverse:"\x1B[7m",hidden:"\x1B[8m",strikethrough:"\x1B[9m",reset:"\x1B[0m"});var Li=()=>({none:t=>t,uncolor:pl,mix:gl,hex:bl,rgb:Ho,bgRgb:wl});function pl(t){return t.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"")}function gl(...t){return e=>{for(let r of t)e=r(e);return e}}function bl(t){t=t.replace(/^#/,"");let e,r,i,n;if(t.length===3)e=parseInt(t.split("").map(s=>s+s).join(""),16);else if(t.length===6)e=parseInt(t,16);else throw new Error("Invalid hex color");return r=e>>16&255,i=e>>8&255,n=e&255,Ho(r,i,n)}function Ho(t,e,r){let i=`\x1B[38;2;${t};${e};${r}m`;return n=>`${i}${n}${dt.reset}`}function wl(t,e,r){let i=`\x1B[48;2;${t};${e};${r}m`;return n=>`${i}${n}${dt.reset}`}var qr={...Object.fromEntries(Object.entries(dt).map(([t])=>[t,e=>e])),...Li()};var Hr={...Object.fromEntries(Object.entries(dt).map(([t,e])=>[t,r=>`${e}${r}${dt.reset}`])),...Li()};function ps(){return typeof Deno<"u"&&typeof Deno.version<"u"}function gs(){return typeof process<"u"&&process.versions&&process.versions.node}function Wo(){return gs()?process.env.FORCE_COLOR||process.stdout.isTTY&&process.env.TERM!=="dumb":ps()?Deno.env.get("FORCE_COLOR")||Deno.isatty(Deno.stdout.rid)&&Deno.env.get("TERM")!=="dumb":!1}var bs=()=>Wo()?Hr:qr;var qi=()=>({colors:t,theme:e})=>{let r=e(t);function i(o){let a=o.stack?`
|
|
6
|
-
`+o.stack+`
|
|
7
|
-
`:"";return[r.errName(o.name+":"),r.errMessage(o.message)].join(" ")+r.errStack(a)}function n(o){return o&&o instanceof Error?i(o):o}function s(o){return o&&o instanceof Error?i(o):r.errMessage(o)}return{stdout:o=>o.map(n),stderr:o=>o.map(s)}};function Wr(...t){return e=>({stdout:r=>{for(let i of t)r=i(e).stdout(r);return r},stderr:r=>{for(let i of t)r=i(e).stderr(r);return r}})}function xl(){return{icon:"\u{1F6A8}",now:()=>Date.now()}}var Hi=t=>({colors:e,theme:r})=>{let i={...xl(),...t},n=r(e),s=new Date(i.now()),o=s.getUTCFullYear().toString().padStart(4,"0"),a=(s.getUTCMonth()+1).toString().padStart(2,"0"),c=s.getUTCDate().toString().padStart(2,"0"),u=`${o}-${a}-${c}`,l=s.getUTCHours().toString().padStart(2,"0"),d=s.getUTCMinutes().toString().padStart(2,"0"),f=s.getUTCSeconds().toString().padStart(2,"0"),m=s.getUTCMilliseconds().toString().padStart(3,"0"),p=`${l}:${d}:${f}.${m}`,g=`${u}::${p}`;return{stdout:b=>[n.timestamp(g),...b],stderr:b=>[n.timestampErr(g),...[i.icon].filter(Boolean),...b]}};function Go(){return Wr(qi(),Hi())}var Wi=()=>({stdout:async t=>{await Deno.stdout.write(new TextEncoder().encode(t+`
|
|
1
|
+
function ms(t,e){return{error:r=>t.error({...e,...r}),rpcRequest:r=>t.rpcRequest({...e,...r}),rpcError:r=>t.rpcError({...e,...r})}}var Zr=()=>t=>({plain:t.none,errMessage:t.mix(t.brightRed,t.bold),errName:t.red,errStack:t.mix(t.red,t.dim),timestamp:t.blue,timestampErr:t.red});function Cn(){return Zr()}var Ke=Object.freeze({black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",brightBlack:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightBlue:"\x1B[94m",brightMagenta:"\x1B[95m",brightCyan:"\x1B[96m",brightWhite:"\x1B[97m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgBrightBlack:"\x1B[100m",bgBrightRed:"\x1B[101m",bgBrightGreen:"\x1B[102m",bgBrightYellow:"\x1B[103m",bgBrightBlue:"\x1B[104m",bgBrightMagenta:"\x1B[105m",bgBrightCyan:"\x1B[106m",bgBrightWhite:"\x1B[107m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",inverse:"\x1B[7m",hidden:"\x1B[8m",strikethrough:"\x1B[9m",reset:"\x1B[0m"});var Jr=()=>({none:t=>t,uncolor:Jo,mix:ec,hex:tc,rgb:_n,bgRgb:rc});function Jo(t){return t.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"")}function ec(...t){return e=>{for(let r of t)e=r(e);return e}}function tc(t){t=t.replace(/^#/,"");let e,r,i,s;if(t.length===3)e=parseInt(t.split("").map(n=>n+n).join(""),16);else if(t.length===6)e=parseInt(t,16);else throw new Error("Invalid hex color");return r=e>>16&255,i=e>>8&255,s=e&255,_n(r,i,s)}function _n(t,e,r){let i=`\x1B[38;2;${t};${e};${r}m`;return s=>`${i}${s}${Ke.reset}`}function rc(t,e,r){let i=`\x1B[48;2;${t};${e};${r}m`;return s=>`${i}${s}${Ke.reset}`}var mr={...Object.fromEntries(Object.entries(Ke).map(([t])=>[t,e=>e])),...Jr()};var pr={...Object.fromEntries(Object.entries(Ke).map(([t,e])=>[t,r=>`${e}${r}${Ke.reset}`])),...Jr()};function ps(){return typeof Deno<"u"&&typeof Deno.version<"u"}function gs(){return typeof process<"u"&&process.versions&&process.versions.node}function Pn(){return gs()?process.env.FORCE_COLOR||process.stdout.isTTY&&process.env.TERM!=="dumb":ps()?Deno.env.get("FORCE_COLOR")||Deno.isatty(Deno.stdout.rid)&&Deno.env.get("TERM")!=="dumb":!1}var ws=()=>Pn()?pr:mr;var ei=()=>({colors:t,theme:e})=>{let r=e(t);function i(a){let o=a.stack?`
|
|
2
|
+
`+a.stack+`
|
|
3
|
+
`:"";return[r.errName(a.name+":"),r.errMessage(a.message)].join(" ")+r.errStack(o)}function s(a){return a&&a instanceof Error?i(a):a}function n(a){return a&&a instanceof Error?i(a):r.errMessage(a)}return{stdout:a=>a.map(s),stderr:a=>a.map(n)}};function gr(...t){return e=>({stdout:r=>{for(let i of t)r=i(e).stdout(r);return r},stderr:r=>{for(let i of t)r=i(e).stderr(r);return r}})}function ic(){return{icon:"\u{1F6A8}",now:()=>Date.now()}}var ti=t=>({colors:e,theme:r})=>{let i={...ic(),...t},s=r(e),n=new Date(i.now()),a=n.getUTCFullYear().toString().padStart(4,"0"),o=(n.getUTCMonth()+1).toString().padStart(2,"0"),c=n.getUTCDate().toString().padStart(2,"0"),l=`${a}-${o}-${c}`,d=n.getUTCHours().toString().padStart(2,"0"),u=n.getUTCMinutes().toString().padStart(2,"0"),h=n.getUTCSeconds().toString().padStart(2,"0"),f=n.getUTCMilliseconds().toString().padStart(3,"0"),p=`${d}:${u}:${h}.${f}`,g=`${l}::${p}`;return{stdout:w=>[s.timestamp(g),...w],stderr:w=>[s.timestampErr(g),...[i.icon].filter(Boolean),...w]}};function En(){return gr(ei(),ti())}var ri=()=>({stdout:async t=>{await Deno.stdout.write(new TextEncoder().encode(t+`
|
|
8
4
|
`))},stderr:async t=>{await Deno.stderr.write(new TextEncoder().encode(t+`
|
|
9
|
-
`))}});var
|
|
5
|
+
`))}});var ii=()=>({stdout:async t=>{process.stdout.write(t+`
|
|
10
6
|
`)},stderr:async t=>{process.stderr.write(t+`
|
|
11
|
-
`)}});var ji=()=>({stdout:async t=>console.log(t),stderr:async t=>console.error(t)});var jo=()=>ps()?Wi():gs()?Gi():ji();var $o=()=>({stdout:async()=>{},stderr:async()=>{}});function Qo(){return()=>({stdout:t=>t,stderr:t=>t})}var Yt=class t{static writers={auto:jo,void:$o,deno:Wi,node:Gi,console:ji};static colors={auto:bs,colorful:()=>Hr,colorless:()=>qr};static themes={auto:qo,basic:Vi};static shapers={auto:Go,none:Qo,errors:qi,timestamp:Hi};writer=t.writers.auto();colors=t.colors.auto();theme=t.themes.auto();shaper=t.shapers.auto();async log(...e){await this.writer.stdout(this.shaper(this).stdout(e).join(" "))}async error(...e){await this.writer.stderr(this.shaper(this).stderr(e).join(" "))}setWriter(e){return this.writer=e,this}setColors(e){return this.colors=e,this}setTheme(e){return this.theme=e,this}setShaper(...e){return this.shaper=Wr(...e),this}};var Gr=class extends Yt{static dummy(){return new this().setWriter(Yt.writers.void())}rpcRequest=async({request:e,...r})=>{let i=this.colors.none;this.log(...this.#e(r),i(`${e.method}()`))};rpcError=async({request:e,error:r,...i})=>{this.error(...this.#e(i),`${e.method}()`,r)};#e({meta:e,label:r,remote:i}){let n=this.colors.mix(this.colors.blue,this.colors.dim),s=this.colors.mix(this.colors.cyan,this.colors.dim);return[e?this.#t(e):void 0,r||void 0,i===void 0?void 0:i?n("<-"):s("->")].filter(Boolean)}#t(e){let{headers:r}=e.request;return[this.colors.yellow(`[${e.ip}]`),this.colors.green(r.origin?r.origin:"(no-origin)")].join(" ")}};var Ne=class extends Gr{rpcRequest=async()=>{}};function Me(){let t,e,r=new Promise((n,s)=>{t=n,e=s});function i(n){return n.then(t).catch(e),r}return{promise:r,resolve:t,reject:e,entangle:i}}var Xo=Object.freeze({happy:t=>t!=null,sad:t=>t==null,boolean:t=>typeof t=="boolean",number:t=>typeof t=="number",string:t=>typeof t=="string",bigint:t=>typeof t=="bigint",object:t=>typeof t=="object"&&t!==null,array:t=>Array.isArray(t),fn:t=>typeof t=="function",symbol:t=>typeof t=="symbol"});var jr=class extends Error{milliseconds;name=this.constructor.name;constructor(e){super(`deadline exceeded (${(e/1e3).toFixed(1)} seconds)`),this.milliseconds=e}};function Ko(t,e){return t<=0||t===1/0?e():new Promise((r,i)=>{let n=setTimeout(()=>i(new jr(t)),t);e().then(r).catch(i).finally(()=>clearTimeout(n))})}function $i(){let t=[];function e(){for(let r of t)r();t=[]}return e.schedule=(...r)=>(t.push(...r),e),e}function Yo(t,e){let r=t;for(let i of e)if(r=r[i],Xo.sad(r))break;return r}function yl(){let t=new Set;async function e(...c){await Promise.all([...t].map(u=>u(...c)))}function r(c){return t.add(c),()=>{t.delete(c)}}async function i(...c){return e(...c)}function n(c){return r(c)}async function s(c){let{promise:u,resolve:l}=Me(),d=n(async(...f)=>{c&&await c(...f),l(f),d()});return u}function o(){t.clear()}let a={pub:i,sub:n,publish:e,subscribe:r,on:r,next:s,clear:o};return Object.assign(n,a),Object.assign(i,a),a}function Qi(t){let e=yl();return t&&e.sub(t),e.pub}var $e;(function(t){t.version="2.0";function e(r){return"id"in r?r.id:null}t.getId=e,t.errorCodes={serverError:-32e3,unexposedError:-32001}})($e||($e={}));var Xi=class extends Error{name=this.constructor.name},St=class extends Error{name=this.constructor.name};async function Zo({tap:t,request:e,action:r}){let i=$e.getId(e);try{let n=await r();return i===null?null:{id:i,result:n,jsonrpc:$e.version}}catch(n){return t.rpcError({request:e,error:n}),i===null?null:{id:i,jsonrpc:$e.version,error:n instanceof Xi?{code:$e.errorCodes.serverError,message:n.message}:{code:$e.errorCodes.unexposedError,message:"unexposed error"}}}}function Ki(t){let e=t.tap??new Ne;return async r=>{let i=r.method.split("."),n=Yo(t.fns,i),s=async()=>await n(...r.params);return e.rpcRequest({request:r}),await Zo({tap:e,request:r,action:s})}}var Jo=Symbol("tune"),Tl=Symbol("query"),kl=Symbol("notify"),Sl=Symbol("settings");function ea(t){function e(r){let i={notify:void 0};return new Proxy((()=>{}),{apply:(n,s,o)=>t(r,o,i),get:(n,s)=>{if(s!=="then")return s===Jo?o=>(...a)=>t(r,a,{...i,...o}):s===kl?(...o)=>t(r,o,{...i,notify:!0}):s===Tl?(...o)=>t(r,o,{...i,notify:!1}):s===Sl?i:(n[s]||(n[s]=e([...r,s])),n[s])},set:(n,s,o)=>(n[s]=o,!0)})}return e([])}function Ct(t){let{endpoint:e,tap:r=new Ne}=t,i=1;return ea(async(n,s,o)=>{let a=o.notify??t.notify??!1,c=o.transfer,u={jsonrpc:"2.0",method:n.join("."),params:s},l=a?u:{...u,id:i++};r.rpcRequest({request:l});let d=await e(l,{transfer:c});if(a&&!d)return null;if(!d)throw new St("response was null, but shouldn't be, because the request was not a notification");if("error"in d)throw new St(t.label?`${t.label}: ${d.error.message}`:d.error.message);return d.result})}function $r(t){return Ct({endpoint:Ki(t),tap:t.tap})}var Et=class{recv=Qi();sendRequest=Qi();sendResponse=Qi();static makeEntangledPair({origin:e="example.e280.org"}={}){let r=new this,i=new this,n=[r.sendRequest.sub(o=>i.recv(o,{origin:e})),r.sendResponse.sub(o=>i.recv(o,{origin:e})),i.sendRequest.sub(o=>r.recv(o,{origin:e})),i.sendResponse.sub(o=>r.recv(o,{origin:e}))];return[r,i,()=>n.forEach(o=>o())]}};function Yi(t,e){return t.addEventListener("message",e),()=>t.removeEventListener("message",e)}function ta(t,e){return async(r,{transfer:i}={})=>{if("id"in r){let n=Me();return e(r,i,n.promise),t.wait(r.id,r.method).then(s=>(n.resolve(s),s))}else{let n=Promise.resolve(null);return e(r,i,n),n}}}function ra(t){let e=[],r=[];for(let i of Array.isArray(t)?t:[t])"method"in i?e.push(i):r.push(i);return{requests:e,responses:r}}async function ia(t,e){let r=(await Promise.all(e.map(async i=>t(i)))).filter(i=>i!==null);return r.length===0?null:r.length===1?r[0]:r}var Zt=class extends Et{dispose=$i();constructor(e){super(),this.dispose.schedule(this.sendRequest.sub((r,i)=>e.postMessage(r,i)),this.sendResponse.sub((r,i)=>e.postMessage(r,i)),Yi(e,r=>this.recv(r.data,r)))}};var Zi=class{remote;transfer;constructor(e){this.remote=e}};var ws=Object.freeze({timeout:6e4,maxRequestBytes:1e7});var Ji=class{timeout;pending=new Map;constructor(e){this.timeout=e}async wait(e,r){let i=Me();return this.pending.set(e,{method:r,deferred:i}),await Ko(this.timeout,()=>i.promise).catch(n=>{throw n instanceof jr&&(n.message=`request #${e} ${r}(), ${n.message}`),n})}deliverResponse(e){let r=this.pending.get(e.id);r&&("error"in e?r.deferred.reject(new St(e.error.message)):r.deferred.resolve(e))}};var At=class{options;remote;remoteEndpoint;dispose=$i();#e;constructor(e){this.options=e;let{conduit:r,tap:i}=e;this.#e=new Ji(e.timeout??ws.timeout),this.remoteEndpoint=ta(this.#e,r.sendRequest.pub.bind(r.sendRequest)),this.remote=Ct({endpoint:this.remoteEndpoint,tap:i&&hs(i,{remote:!0})}),this.dispose.schedule(r.recv.sub(n=>this.recv(n)))}async recv(e){let r=new Zi(this.remote),{conduit:i,rpc:n,tap:s}=this.options,{requests:o,responses:a}=ra(e);for(let d of a)this.#e.deliverResponse(d);if(!n)return;let c=await n(r),u=Ki({fns:c,tap:s&&hs(s,{remote:!1})}),l=await ia(u,o);l&&await i.sendResponse(l,r.transfer)}};var Qe={derive:{host:t=>({host:t.remote.host,get transfer(){return t.transfer},set transfer(e){t.transfer=e}}),work:t=>({work:t.remote,get transfer(){return t.transfer},set transfer(e){t.transfer=e}})},mock:{host:()=>({host:void 0,transfer:void 0}),work:()=>({work:void 0,transfer:void 0})}};var Xe=new Ne;async function na(t,e,r={}){let i=r.tap??Xe,n=new At({tap:i,timeout:r.timeout??1/0,conduit:new Zt(t.getSelf()),rpc:async s=>e(Qe.derive.host(s))});return await n.remote.infra.ready(),n.remote.host}var Jt=class{worker;messenger;constructor(e,r){this.worker=e,this.messenger=r}static async make(e,r){let i=r.tap??Xe,n=r.label??"comrade",s=e.loadWorker(r.workerUrl,n),o=Me(),a={async ready(){o.resolve()}},c=new At({tap:i,timeout:r.timeout??1/0,conduit:new Zt(s),rpc:async u=>({infra:a,host:r.setupHost(Qe.derive.work(u))})});return await o.promise,new this(s,c)}get work(){return this.messenger.remote}terminate(){this.worker.terminate()}};var en=class{threads;static async make(e,r){let i=r.workerCount??e.guessOptimalThreadCount(),n=await Promise.all([...Array(i)].map(async(s,o)=>Jt.make(e,{...r,label:r.label??`${r.label??"comrade"}_${o+1}`})));return new this(n,{tap:r.tap})}work;#e=new Set;#t=[];constructor(e,r={}){this.threads=e;let i=r.tap??Xe,n=async(s,o)=>this.#i({request:s,prom:Me(),transfer:o?.transfer});this.work=Ct({tap:i,endpoint:n}),e.forEach(s=>this.#e.add(s))}get threadCount(){return this.threads.length}terminate(){for(let e of this.threads)e.terminate()}#i(e){return this.#t.push(e),this.#r(),e.prom.promise}#r(){for(;this.#e.size>0&&this.#t.length>0;){let e=[...this.#e].pop();this.#e.delete(e);let r=this.#t.shift();this.#e.delete(e);let i=e.messenger.remoteEndpoint(r.request,{transfer:r.transfer});r.prom.entangle(i).finally(()=>{this.#e.add(e),this.#r()})}}};var sa=t=>({thread:e=>Jt.make(t,e),cluster:e=>en.make(t,e),worker:(e,r={})=>na(t,e,r),work:e=>e,host:e=>e,mocks(e){let{setupWork:r,setupHost:i,tap:n=Xe}=e,s=Qe.mock.host(),o=Qe.mock.work();return o.work=$r({tap:n,fns:r(s)}),s.host=$r({tap:n,fns:i(o)}),{workShell:o,hostShell:s,work:o.work,host:s.host}},mockWork(e,r=Xe){let i=Qe.mock.host(),n=Qe.mock.work();return n.work=$r({tap:r,fns:e(i)}),{workShell:n,hostShell:i,work:n.work,mockHost:s=>(i.host=$r({tap:r,fns:s(n)}),{workShell:n,hostShell:i,work:n.work,host:i.host})}}});var oa=()=>({getSelf(){return self},guessOptimalThreadCount(){let t=navigator.hardwareConcurrency??1;return Math.max(1,t-1)},loadWorker(t,e){return new window.Worker(t,{name:e,type:"module"})},async loadWasm(t){return WebAssembly.instantiateStreaming(fetch(t))}});var Al=oa(),tn=sa(Al);var aa={extension:{type:zi.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await import("./browserAll-YBZEJCN3.js")}};var ca={extension:{type:zi.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await import("./webworkerAll-BKJQW6P7.js")}};var ic=ml(rc(),1),Rs={createCanvas:(t,e)=>new OffscreenCanvas(t??0,e??0),createImage:()=>new Image,getCanvasRenderingContext2D:()=>OffscreenCanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>globalThis.location.href,getFontFaceSet:()=>globalThis.fonts,fetch:(t,e)=>fetch(t,e),parseXML:t=>new ic.DOMParser().parseFromString(t,"text/xml")};Lo.add(aa,ca);function h(t){if(!t)throw new Error("Assertion failed.")}var mn=t=>{let e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},G=t=>t&&t[t.length-1],_t=t=>t>=0&&t<2**32,W=class t{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),r=this.bytes[e]??0,i=7-(this.pos&7),n=(r&1<<i)>>i;return this.pos++,n}readBits(e){if(e===1)return this.readBit();let r=0;for(let i=0;i<e;i++)r<<=1,r|=this.readBit();return r}writeBits(e,r){let i=this.pos+e;for(let n=this.pos;n<i;n++){let s=Math.floor(n/8),o=this.bytes[s],a=7-(n&7);o&=~(1<<a),o|=(r&1<<i-n-1)>>i-n-1<<a,this.bytes[s]=o}this.pos=i}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,r=this.bytes[e]??0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new t(this.bytes);return e.pos=this.pos,e}},_=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},Ve=t=>{let e=_(t);return(e&1)===0?-(e>>1):e+1>>1};var J=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),V=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),ae=new TextDecoder,we=new TextEncoder;var zs=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),Pt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},hn=zs(Pt),Dt={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},pn=zs(Dt),It={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},gn=zs(It),sc=t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,ur=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),be=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,r=new Promise(n=>{e=n}),i=this.currentPromise;return this.currentPromise=r,await i,e}},Vs=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),Ls=t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0),Ft=(t,e,r)=>{let i=0,n=t.length-1,s=-1;for(;i<=n;){let o=i+n>>1,a=r(t[o]);a===e?(s=o,n=o-1):a<e?i=o+1:n=o-1}return s},U=(t,e,r)=>{let i=0,n=t.length-1,s=-1;for(;i<=n;){let o=i+(n-i+1)/2|0;r(t[o])<=e?(s=o,i=o+1):n=o-1}return s},qs=(t,e,r)=>{let i=U(t,r(e),r);t.splice(i+1,0,e)},ce=()=>{let t,e;return{promise:new Promise((i,n)=>{t=i,e=n}),resolve:t,reject:e}};var Hs=(t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return t[r]},bn=(t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1},oc=async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},ac=t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},ue=t=>{throw new Error(`Unexpected value: ${t}`)},Bt=(t,e,r)=>{let i=t.getUint8(e),n=t.getUint8(e+1),s=t.getUint8(e+2);return r?i|n<<8|s<<16:i<<16|n<<8|s},cc=(t,e,r)=>Bt(t,e,r)<<8>>8,oi=(t,e,r,i)=>{r=r>>>0,r=r&16777215,i?(t.setUint8(e,r&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r>>>16&255)):(t.setUint8(e,r>>>16&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r&255))},uc=(t,e,r,i)=>{r=ee(r,-8388608,8388607),r<0&&(r=r+16777216&16777215),oi(t,e,r,i)};var ee=(t,e,r)=>Math.max(e,Math.min(r,t)),Z="und",Rt=t=>{let e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},lc=(t,e)=>Math.round(t/e)*e,dc=t=>{let e=0;for(;t;)e++,t>>=1;return e},td=/^[a-z]{3}$/,lr=t=>td.test(t),Le=1e6*(1+Number.EPSILON),Ws=(t,e)=>{let r={...t,...e};if(t.headers||e.headers){let i=t.headers?nc(t.headers):{},n=e.headers?nc(e.headers):{},s={...i};Object.entries(n).forEach(([o,a])=>{let c=Object.keys(s).find(u=>u.toLowerCase()===o.toLowerCase());c&&delete s[c],s[o]=a}),r.headers=s}return r},nc=t=>{if(t instanceof Headers){let e={};return t.forEach((r,i)=>{e[i]=r}),e}if(Array.isArray(t)){let e={};return t.forEach(([r,i])=>{e[r]=i}),e}return t},Gs=async(t,e,r,i,n)=>{let s=0;for(;;)try{return await t(e,r)}catch(o){if(n())throw o;s++;let a=i(s,o,e);if(a===null)throw o;if(console.error("Retrying failed fetch. Error:",o),!Number.isFinite(a)||a<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(a>0&&await new Promise(c=>setTimeout(c,1e3*a)),n())throw o}},fc=(t,e)=>{let r=t<0?-1:1;t=Math.abs(t);let i=0,n=1,s=1,o=0,a=t;for(;;){let c=Math.floor(a),u=c*s+i,l=c*o+n;if(l>e)return{numerator:r*s,denominator:o};if(i=s,n=o,s=u,o=l,a=1/(a-c),!isFinite(a))break}return{numerator:r*s,denominator:o}},ht=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},Os=null,pt=()=>Os!==null?Os:Os=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),Ns=null,dr=()=>Ns!==null?Ns:Ns=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),Ms=null,ai=()=>Ms!==null?Ms:Ms=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),Us=null,mc=()=>{if(Us!==null)return Us;if(typeof navigator>"u")return null;let t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?Us=Number(t[1]):null},Ot=(t,e)=>t!==-1?t:e,wn=(t,e,r,i)=>t<=i&&r<=e,ci=function*(t){for(let e in t){let r=t[e];r!==void 0&&(yield{key:e,value:r})}};var hc=t=>{let e=atob(t),r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i);return r};var xn=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},ui=t=>typeof t=="number"&&!Number.isNaN(t);var Pe=class{constructor(e,r){if(this.data=e,this.mimeType=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof r!="string")throw new TypeError("mimeType must be a string.")}},li=class{constructor(e,r,i,n){if(this.data=e,this.mimeType=r,this.name=i,this.description=n,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!==void 0&&typeof r!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("description, when provided, must be a string.")}},pc=t=>{if(!t||typeof t!="object")throw new TypeError("tags must be an object.");if(t.title!==void 0&&typeof t.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(t.artist!==void 0&&typeof t.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(t.album!==void 0&&typeof t.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(t.albumArtist!==void 0&&typeof t.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(t.trackNumber!==void 0&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(t.tracksTotal!==void 0&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(t.discNumber!==void 0&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(t.discsTotal!==void 0&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(t.genre!==void 0&&typeof t.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(t.date!==void 0&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(t.lyrics!==void 0&&typeof t.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(t.images!==void 0){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(let e of t.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(t.comment!==void 0&&typeof t.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(t.raw!==void 0){if(!t.raw||typeof t.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(let e of Object.values(t.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof Pe)&&!(e instanceof li))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}};var xe={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},gc=t=>{if(!t||typeof t!="object")throw new TypeError("disposition must be an object.");if(t.default!==void 0&&typeof t.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(t.forced!==void 0&&typeof t.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(t.original!==void 0&&typeof t.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(t.commentary!==void 0&&typeof t.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(t.hearingImpaired!==void 0&&typeof t.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(t.visuallyImpaired!==void 0&&typeof t.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};var qe=["avc","hevc","vp9","av1","vp8"],Y=["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"],js=["aac","opus","mp3","vorbis","flac"],et=[...js,...Y],Nt=["webvtt"],bc=[{maxMacroblocks:99,maxBitrate:64e3,level:10},{maxMacroblocks:396,maxBitrate:192e3,level:11},{maxMacroblocks:396,maxBitrate:384e3,level:12},{maxMacroblocks:396,maxBitrate:768e3,level:13},{maxMacroblocks:396,maxBitrate:2e6,level:20},{maxMacroblocks:792,maxBitrate:4e6,level:21},{maxMacroblocks:1620,maxBitrate:4e6,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14e6,level:31},{maxMacroblocks:5120,maxBitrate:2e7,level:32},{maxMacroblocks:8192,maxBitrate:2e7,level:40},{maxMacroblocks:8192,maxBitrate:5e7,level:41},{maxMacroblocks:8704,maxBitrate:5e7,level:42},{maxMacroblocks:22080,maxBitrate:135e6,level:50},{maxMacroblocks:36864,maxBitrate:24e7,level:51},{maxMacroblocks:36864,maxBitrate:24e7,level:52},{maxMacroblocks:139264,maxBitrate:24e7,level:60},{maxMacroblocks:139264,maxBitrate:48e7,level:61},{maxMacroblocks:139264,maxBitrate:8e8,level:62}],wc=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],Je=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],xc=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],yc=".01.01.01.01.00",Tc=".0.110.01.01.01.0",kc=(t,e,r,i)=>{if(t==="avc"){let s=Math.ceil(e/16)*Math.ceil(r/16),o=bc.find(d=>s<=d.maxMacroblocks&&i<=d.maxBitrate)??G(bc),a=o?o.level:0,c="64".padStart(2,"0"),u="00",l=a.toString(16).padStart(2,"0");return`avc1.${c}${u}${l}`}else if(t==="hevc"){let a=e*r,c=wc.find(l=>a<=l.maxPictureSize&&i<=l.maxBitrate)??G(wc);return`hev1.1.6.${c.tier}${c.level}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){let s=e*r;return`vp09.00.${(Je.find(c=>s<=c.maxPictureSize&&i<=c.maxBitrate)??G(Je)).level.toString().padStart(2,"0")}.08`}else if(t==="av1"){let s=e*r,o=xc.find(u=>s<=u.maxPictureSize&&i<=u.maxBitrate)??G(xc);return`av01.0.${o.level.toString().padStart(2,"0")}${o.tier}.08`}}throw new TypeError(`Unhandled codec '${t}'.`)};var Sc=t=>{let e=t.split("."),n=(1<<7)+1,s=Number(e[1]),o=e[2],a=Number(o.slice(0,-1)),c=(s<<5)+a,u=o.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,f=0,m=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,g=e[5]?Number(e[5][1]):1,b=e[5]?Number(e[5][2]):0,w=(u<<7)+(d<<6)+(f<<5)+(m<<4)+(p<<3)+(g<<2)+b;return[n,c,w,0]},yn=t=>{let{codec:e,codecDescription:r,colorSpace:i,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:o,av1CodecInfo:a}=t;if(e==="avc"){if(h(t.avcType!==null),n){let c=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${t.avcType}.${Vs(c)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${Vs(r.subarray(1,4))}`}else if(e==="hevc"){let c,u,l,d,f,m;if(s)c=s.generalProfileSpace,u=s.generalProfileIdc,l=Ls(s.generalProfileCompatibilityFlags),d=s.generalTierFlag,f=s.generalLevelIdc,m=[...s.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let g=V(r),b=g.getUint8(1);c=b>>6&3,u=b&31,l=Ls(g.getUint32(2)),d=b>>5&1,f=g.getUint8(12),m=[];for(let w=0;w<6;w++)m.push(g.getUint8(6+w))}let p="hev1.";for(p+=["","A","B","C"][c]+u,p+=".",p+=l.toString(16).toUpperCase(),p+=".",p+=d===0?"L":"H",p+=f;m.length>0&&m[m.length-1]===0;)m.pop();return m.length>0&&(p+=".",p+=m.map(g=>g.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!o){let w=t.width*t.height,x=G(Je).level;for(let y of Je)if(w<=y.maxPictureSize){x=y.level;break}return`vp09.00.${x.toString().padStart(2,"0")}.08`}let c=o.profile.toString().padStart(2,"0"),u=o.level.toString().padStart(2,"0"),l=o.bitDepth.toString().padStart(2,"0"),d=o.chromaSubsampling.toString().padStart(2,"0"),f=o.colourPrimaries.toString().padStart(2,"0"),m=o.transferCharacteristics.toString().padStart(2,"0"),p=o.matrixCoefficients.toString().padStart(2,"0"),g=o.videoFullRangeFlag.toString().padStart(2,"0"),b=`vp09.${c}.${u}.${l}.${d}`;return b+=`.${f}.${m}.${p}.${g}`,b.endsWith(yc)&&(b=b.slice(0,-yc.length)),b}else if(e==="av1"){if(!a){let y=t.width*t.height,T=G(Je).level;for(let E of Je)if(y<=E.maxPictureSize){T=E.level;break}return`av01.0.${T.toString().padStart(2,"0")}M.08`}let c=a.profile,u=a.level.toString().padStart(2,"0"),l=a.tier?"H":"M",d=a.bitDepth.toString().padStart(2,"0"),f=a.monochrome?"1":"0",m=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0),p=i?.primaries?Pt[i.primaries]:1,g=i?.transfer?Dt[i.transfer]:1,b=i?.matrix?It[i.matrix]:1,w=i?.fullRange?1:0,x=`av01.${c}.${u}${l}.${d}`;return x+=`.${f}.${m.toString().padStart(3,"0")}`,x+=`.${p.toString().padStart(2,"0")}`,x+=`.${g.toString().padStart(2,"0")}`,x+=`.${b.toString().padStart(2,"0")}`,x+=`.${w}`,x.endsWith(Tc)&&(x=x.slice(0,-Tc.length)),x}}throw new TypeError(`Unhandled codec '${e}'.`)},Cc=(t,e,r)=>{if(t==="aac")return e>=2&&r<=24e3?"mp4a.40.29":r<=24e3?"mp4a.40.5":"mp4a.40.2";if(t==="mp3")return"mp3";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";if(t==="flac")return"flac";if(Y.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},Tn=t=>{let{codec:e,codecDescription:r,aacCodecInfo:i}=t;if(e==="aac"){if(!i)throw new TypeError("AAC codec info must be provided.");return i.isMpeg2?"mp4a.67":`mp4a.40.${di(r).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&Y.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},fr=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],kn=[-1,1,2,3,4,5,6,8],di=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new W(t),r=e.readBits(5);r===31&&(r=32+e.readBits(6));let i=e.readBits(4),n=null;i===15?n=e.readBits(24):i<fr.length&&(n=fr[i]);let s=e.readBits(4),o=null;return s>=1&&s<=7&&(o=kn[s]),{objectType:r,frequencyIndex:i,sampleRate:n,channelConfiguration:s,numberOfChannels:o}},Ec=t=>{let e=fr.indexOf(t.sampleRate),r=null;e===-1&&(e=15,r=t.sampleRate);let i=kn.indexOf(t.numberOfChannels);if(i===-1)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let n=13;t.objectType>=32&&(n+=6),e===15&&(n+=24);let s=Math.ceil(n/8),o=new Uint8Array(s),a=new W(o);return t.objectType<32?a.writeBits(5,t.objectType):(a.writeBits(5,31),a.writeBits(6,t.objectType-32)),a.writeBits(4,e),e===15&&a.writeBits(24,r),a.writeBits(4,i),o},Mt=48e3,Ac=/^pcm-([usf])(\d+)+(be)?$/,Te=t=>{if(h(Y.includes(t)),t==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(t==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=Ac.exec(t);h(e);let r;e[1]==="u"?r="unsigned":e[1]==="s"?r="signed":r="float";let i=Number(e[2])/8,n=e[3]!=="be",s=t==="pcm-u8"?2**7:0;return{dataType:r,sampleSize:i,littleEndian:n,silentValue:s}},$s=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":t==="vp8"?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":t.startsWith("mp4a.40")||t==="mp4a.67"?"aac":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"?"mp3":t==="opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ulaw"?"ulaw":t==="alaw"?"alaw":Ac.test(t)?t:t==="webvtt"?"webvtt":null,vc=t=>t==="avc"?{avc:{format:"avc"}}:t==="hevc"?{hevc:{format:"hevc"}}:{},_c=t=>t==="aac"?{aac:{format:"aac"}}:t==="opus"?{opus:{format:"opus"}}:{},rd=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],id=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,nd=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,sd=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,od=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Pc=t=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Video chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!rd.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(t.decoderConfig.description!==void 0&&!ur(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=t.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let r=Object.keys(Pt);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);let i=Object.keys(Dt);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);let n=Object.keys(It);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!id.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(t.decoderConfig.codec.startsWith("hev1")||t.decoderConfig.codec.startsWith("hvc1")){if(!nd.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(t.decoderConfig.codec.startsWith("vp8")){if(t.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(t.decoderConfig.codec.startsWith("vp09")){if(!sd.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(t.decoderConfig.codec.startsWith("av01")&&!od.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},ad=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],Dc=t=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!ad.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(t.decoderConfig.description!==void 0&&!ur(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if(t.decoderConfig.codec!=="mp3"&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if(t.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if(t.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if(t.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!Y.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Y.join(", ")}).`)},Ic=t=>{if(!t)throw new TypeError("Subtitle metadata must be provided.");if(typeof t!="object")throw new TypeError("Subtitle metadata must be an object.");if(!t.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof t.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof t.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};var Sn=class{constructor(e){this.mutex=new be,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,r,i){r+=e.source._timestampOffset;let n=this.trackTimestampInfo.get(e);if(!n){if(!i)throw new Error("First packet must be a key packet.");n={maxTimestamp:r,maxTimestampBeforeLastKeyPacket:r},this.trackTimestampInfo.set(e,n)}if(r<0)throw new Error(`Timestamps must be non-negative (got ${r}s).`);if(i&&(n.maxTimestampBeforeLastKeyPacket=n.maxTimestamp),r<n.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${r}s, but largest timestamp is ${n.maxTimestampBeforeLastKeyPacket}s.`);return n.maxTimestamp=Math.max(n.maxTimestamp,r),r}};var Ut;(function(t){t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.SPS_EXT=13]="SPS_EXT"})(Ut||(Ut={}));var me;(function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(me||(me={}));var mr=t=>{let e=[],r=0;for(;r<t.length;){let i=-1,n=0;for(let s=r;s<t.length-3;s++){if(t[s]===0&&t[s+1]===0&&t[s+2]===1){i=s,n=3;break}if(s<t.length-4&&t[s]===0&&t[s+1]===0&&t[s+2]===0&&t[s+3]===1){i=s,n=4;break}}if(i===-1)break;if(r>0&&i>r){let s=t.subarray(r,i);s.length>0&&e.push(s)}r=i+n}if(r<t.length){let i=t.subarray(r);i.length>0&&e.push(i)}return e},Bc=(t,e)=>{let r=[],i=0,n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;i+e<=t.length;){let s;e===1?s=n.getUint8(i):e===2?s=n.getUint16(i,!1):e===3?s=Bt(n,i,!1):e===4?s=n.getUint32(i,!1):(ue(e),h(!1)),i+=e;let o=t.subarray(i,i+s);r.push(o),i+=s}return r},Cn=t=>{let e=[],r=t.length;for(let i=0;i<r;i++)i+2<r&&t[i]===0&&t[i+1]===0&&t[i+2]===3?(e.push(0,0),i+=2):e.push(t[i]);return new Uint8Array(e)},Qs=new Uint8Array([0,0,0,1]),cd=t=>{let e=t.reduce((n,s)=>n+Qs.byteLength+s.byteLength,0),r=new Uint8Array(e),i=0;for(let n of t)r.set(Qs,i),i+=Qs.byteLength,r.set(n,i),i+=n.byteLength;return r},Xs=(t,e)=>{let r=t.reduce((s,o)=>s+e+o.byteLength,0),i=new Uint8Array(r),n=0;for(let s of t){let o=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(e){case 1:o.setUint8(n,s.byteLength);break;case 2:o.setUint16(n,s.byteLength,!1);break;case 3:oi(o,n,s.byteLength,!1);break;case 4:o.setUint32(n,s.byteLength,!1);break}n+=e,i.set(s,n),n+=s.byteLength}return i},Ks=(t,e)=>{if(e.description){let n=(J(e.description)[4]&3)+1;return Bc(t,n)}else return mr(t)},Rc=(t,e)=>{if(e.description){let n=(J(e.description)[4]&3)+1;return Xs(t,n)}else return cd(t)},zt=t=>t[0]&31,En=t=>{try{let e=mr(t),r=e.filter(c=>zt(c)===Ut.SPS),i=e.filter(c=>zt(c)===Ut.PPS),n=e.filter(c=>zt(c)===Ut.SPS_EXT);if(r.length===0||i.length===0)return null;let s=r[0],o=Ys(s);h(o!==null);let a=o.profileIdc===100||o.profileIdc===110||o.profileIdc===122||o.profileIdc===144;return{configurationVersion:1,avcProfileIndication:o.profileIdc,profileCompatibility:o.constraintFlags,avcLevelIndication:o.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:r,pictureParameterSets:i,chromaFormat:a?o.chromaFormatIdc:null,bitDepthLumaMinus8:a?o.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?o.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?n:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},Oc=t=>{let e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|t.lengthSizeMinusOne&3),e.push(224|t.sequenceParameterSets.length&31);for(let r of t.sequenceParameterSets){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}e.push(t.pictureParameterSets.length);for(let r of t.pictureParameterSets){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}if(t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144){h(t.chromaFormat!==null),h(t.bitDepthLumaMinus8!==null),h(t.bitDepthChromaMinus8!==null),h(t.sequenceParameterSetExt!==null),e.push(252|t.chromaFormat&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.sequenceParameterSetExt.length);for(let r of t.sequenceParameterSetExt){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}}return new Uint8Array(e)},Nc=t=>{try{let e=V(t),r=0,i=e.getUint8(r++),n=e.getUint8(r++),s=e.getUint8(r++),o=e.getUint8(r++),a=e.getUint8(r++)&3,c=e.getUint8(r++)&31,u=[];for(let m=0;m<c;m++){let p=e.getUint16(r,!1);r+=2,u.push(t.subarray(r,r+p)),r+=p}let l=e.getUint8(r++),d=[];for(let m=0;m<l;m++){let p=e.getUint16(r,!1);r+=2,d.push(t.subarray(r,r+p)),r+=p}let f={configurationVersion:i,avcProfileIndication:n,profileCompatibility:s,avcLevelIndication:o,lengthSizeMinusOne:a,sequenceParameterSets:u,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((n===100||n===110||n===122||n===144)&&r+4<=t.length){let m=e.getUint8(r++)&3,p=e.getUint8(r++)&7,g=e.getUint8(r++)&7,b=e.getUint8(r++);f.chromaFormat=m,f.bitDepthLumaMinus8=p,f.bitDepthChromaMinus8=g;let w=[];for(let x=0;x<b;x++){let y=e.getUint16(r,!1);r+=2,w.push(t.subarray(r,r+y)),r+=y}f.sequenceParameterSetExt=w}return f}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},Ys=t=>{try{let e=new W(Cn(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let i=e.readAlignedByte(),n=e.readAlignedByte(),s=e.readAlignedByte();_(e);let o=null,a=null,c=null;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(o=_(e),o===3&&e.skipBits(1),a=_(e),c=_(e),e.skipBits(1),e.readBits(1))){for(let f=0;f<(o!==3?8:12);f++)if(e.readBits(1)){let p=f<6?16:64,g=8,b=8;for(let w=0;w<p;w++){if(b!==0){let x=Ve(e);b=(g+x+256)%256}g=b===0?g:b}}}_(e);let u=_(e);if(u===0)_(e);else if(u===1){e.skipBits(1),Ve(e),Ve(e);let d=_(e);for(let f=0;f<d;f++)Ve(e)}_(e),e.skipBits(1),_(e),_(e);let l=e.readBits(1);return{profileIdc:i,constraintFlags:n,levelIdc:s,frameMbsOnlyFlag:l,chromaFormatIdc:o,bitDepthLumaMinus8:a,bitDepthChromaMinus8:c}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},Zs=(t,e)=>{if(e.description){let n=(J(e.description)[21]&3)+1;return Bc(t,n)}else return mr(t)},tt=t=>t[0]>>1&63,An=t=>{try{let e=mr(t),r=e.filter(M=>tt(M)===me.VPS_NUT),i=e.filter(M=>tt(M)===me.SPS_NUT),n=e.filter(M=>tt(M)===me.PPS_NUT),s=e.filter(M=>tt(M)===me.PREFIX_SEI_NUT||tt(M)===me.SUFFIX_SEI_NUT);if(i.length===0||n.length===0)return null;let o=i[0],a=new W(Cn(o));a.skipBits(16),a.readBits(4);let c=a.readBits(3),u=a.readBits(1),{general_profile_space:l,general_tier_flag:d,general_profile_idc:f,general_profile_compatibility_flags:m,general_constraint_indicator_flags:p,general_level_idc:g}=ud(a,c);_(a);let b=_(a);b===3&&a.skipBits(1),_(a),_(a),a.readBits(1)&&(_(a),_(a),_(a),_(a));let w=_(a),x=_(a);_(a);let T=a.readBits(1)?0:c;for(let M=T;M<=c;M++)_(a),_(a),_(a);_(a),_(a),_(a),_(a),_(a),_(a),a.readBits(1)&&a.readBits(1)&&ld(a),a.skipBits(1),a.skipBits(1),a.readBits(1)&&(a.skipBits(4),a.skipBits(4),_(a),_(a),a.skipBits(1));let E=_(a);if(dd(a,E),a.readBits(1)){let M=_(a);for(let B=0;B<M;B++)_(a),a.skipBits(1)}a.skipBits(1),a.skipBits(1);let S=0;a.readBits(1)&&(S=md(a,c));let P=0;if(n.length>0){let M=n[0],B=new W(Cn(M));B.skipBits(16),_(B),_(B),B.skipBits(1),B.skipBits(1),B.skipBits(3),B.skipBits(1),B.skipBits(1),_(B),_(B),Ve(B),B.skipBits(1),B.skipBits(1),B.readBits(1)&&_(B),Ve(B),Ve(B),B.skipBits(1),B.skipBits(1),B.skipBits(1),B.skipBits(1);let Q=B.readBits(1),je=B.readBits(1);!Q&&!je?P=0:Q&&!je?P=2:!Q&&je?P=3:P=0}let v=[...r.length?[{arrayCompleteness:1,nalUnitType:me.VPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:me.SPS_NUT,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:me.PPS_NUT,nalUnits:n}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:tt(s[0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:l,generalTierFlag:d,generalProfileIdc:f,generalProfileCompatibilityFlags:m,generalConstraintIndicatorFlags:p,generalLevelIdc:g,minSpatialSegmentationIdc:S,parallelismType:P,chromaFormatIdc:b,bitDepthLumaMinus8:w,bitDepthChromaMinus8:x,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:u,lengthSizeMinusOne:3,arrays:v}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},ud=(t,e)=>{let r=t.readBits(2),i=t.readBits(1),n=t.readBits(5),s=0;for(let l=0;l<32;l++)s=s<<1|t.readBits(1);let o=new Uint8Array(6);for(let l=0;l<6;l++)o[l]=t.readBits(8);let a=t.readBits(8),c=[],u=[];for(let l=0;l<e;l++)c.push(t.readBits(1)),u.push(t.readBits(1));if(e>0)for(let l=e;l<8;l++)t.skipBits(2);for(let l=0;l<e;l++)c[l]&&t.skipBits(88),u[l]&&t.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:o,general_level_idc:a}},ld=t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))_(t);else{let n=Math.min(64,1<<4+(e<<1));e>1&&Ve(t);for(let s=0;s<n;s++)Ve(t)}},dd=(t,e)=>{let r=[];for(let i=0;i<e;i++)r[i]=fd(t,i,e,r)},fd=(t,e,r,i)=>{let n=0,s=0,o=0;if(e!==0&&(s=t.readBits(1)),s){if(e===r){let c=_(t);o=e-(c+1)}else o=e-1;t.readBits(1),_(t);let a=i[o]??0;for(let c=0;c<=a;c++)t.readBits(1)||t.readBits(1);n=i[o]}else{let a=_(t),c=_(t);for(let u=0;u<a;u++)_(t),t.readBits(1);for(let u=0;u<c;u++)_(t),t.readBits(1);n=a+c}return n},md=(t,e)=>{if(t.readBits(1)&&t.readBits(8)===255&&(t.readBits(16),t.readBits(16)),t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),t.readBits(1),t.readBits(1)&&(t.readBits(8),t.readBits(8),t.readBits(8))),t.readBits(1)&&(_(t),_(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(_(t),_(t),_(t),_(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&_(t),t.readBits(1)&&hd(t,!0,e)),t.readBits(1)){t.readBits(1),t.readBits(1),t.readBits(1);let r=_(t);return _(t),_(t),_(t),_(t),r}return 0},hd=(t,e,r)=>{let i=!1,n=!1,s=!1;e&&(i=t.readBits(1)===1,n=t.readBits(1)===1,(i||n)&&(s=t.readBits(1)===1,s&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let o=0;o<=r;o++){let a=t.readBits(1)===1,c=!0;a||(c=t.readBits(1)===1);let u=!1;c?_(t):u=t.readBits(1)===1;let l=1;u||(l=_(t)+1),i&&Fc(t,l,s),n&&Fc(t,l,s)}},Fc=(t,e,r)=>{for(let i=0;i<e;i++)_(t),_(t),r&&(_(t),_(t)),t.readBits(1)},Mc=t=>{let e=[];e.push(t.configurationVersion),e.push((t.generalProfileSpace&3)<<6|(t.generalTierFlag&1)<<5|t.generalProfileIdc&31),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(t.generalProfileCompatibilityFlags&255),e.push(...t.generalConstraintIndicatorFlags),e.push(t.generalLevelIdc&255),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(t.minSpatialSegmentationIdc&255),e.push(252|t.parallelismType&3),e.push(252|t.chromaFormatIdc&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.avgFrameRate>>8&255),e.push(t.avgFrameRate&255),e.push((t.constantFrameRate&3)<<6|(t.numTemporalLayers&7)<<3|(t.temporalIdNested&1)<<2|t.lengthSizeMinusOne&3),e.push(t.arrays.length&255);for(let r of t.arrays){e.push((r.arrayCompleteness&1)<<7|0|r.nalUnitType&63),e.push(r.nalUnits.length>>8&255),e.push(r.nalUnits.length&255);for(let i of r.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let n=0;n<i.length;n++)e.push(i[n])}}return new Uint8Array(e)},vn=t=>{let e=new W(t);if(e.readBits(2)!==2)return null;let i=e.readBits(1),s=(e.readBits(1)<<1)+i;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let u=8;s>=2&&(u=e.readBits(1)?12:10);let l=e.readBits(3),d=0,f=0;if(l!==7)if(f=e.readBits(1),s===1||s===3){let P=e.readBits(1),v=e.readBits(1);d=!P&&!v?3:P&&!v?2:1,e.skipBits(1)}else d=1;else d=3,f=1;let m=e.readBits(16),p=e.readBits(16),g=m+1,b=p+1,w=g*b,x=G(Je).level;for(let S of Je)if(w<=S.maxPictureSize){x=S.level;break}return{profile:s,level:x,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:l===2?1:l===1?6:2,transferCharacteristics:l===2?1:l===1?6:2,matrixCoefficients:l===7?0:l===2?1:l===1?6:2}},Uc=function*(t){let e=new W(t),r=()=>{let i=0;for(let n=0;n<8;n++){let s=e.readAlignedByte();if(i|=(s&127)<<n*7,!(s&128))break;if(n===7&&s&128)return null}return i>=2**32-1?null:i};for(;e.getBitsLeft()>=8;){e.skipBits(1);let i=e.readBits(4),n=e.readBits(1),s=e.readBits(1);e.skipBits(1),n&&e.skipBits(8);let o;if(s){let a=r();if(a===null)return;o=a}else o=Math.floor(e.getBitsLeft()/8);h(e.pos%8===0),yield{type:i,data:t.subarray(e.pos/8,e.pos/8+o)},e.skipBits(o*8)}},_n=t=>{for(let{type:e,data:r}of Uc(t)){if(e!==1)continue;let i=new W(r),n=i.readBits(3),s=i.readBits(1),o=i.readBits(1),a=0,c=0,u=0;if(o)a=i.readBits(5);else{if(i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.readBits(1)))return null;let S=i.readBits(1);S&&(u=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5));let P=i.readBits(5);for(let v=0;v<=P;v++){i.skipBits(12);let F=i.readBits(5);if(v===0&&(a=F),F>7){let B=i.readBits(1);v===0&&(c=B)}if(S&&i.readBits(1)){let Q=u+1;i.skipBits(Q),i.skipBits(Q),i.skipBits(1)}i.readBits(1)&&i.skipBits(4)}}let l=i.readBits(4),d=i.readBits(4),f=l+1;i.skipBits(f);let m=d+1;i.skipBits(m);let p=0;if(o?p=0:p=i.readBits(1),p&&(i.skipBits(4),i.skipBits(3)),i.skipBits(1),i.skipBits(1),i.skipBits(1),!o){i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);let E=i.readBits(1);E&&(i.skipBits(1),i.skipBits(1));let S=i.readBits(1),P=0;S?P=2:P=i.readBits(1),P>0&&(i.readBits(1)||i.skipBits(1)),E&&i.skipBits(3)}i.skipBits(1),i.skipBits(1),i.skipBits(1);let g=i.readBits(1),b=8;n===2&&g?b=i.readBits(1)?12:10:n<=2&&(b=g?10:8);let w=0;n!==1&&(w=i.readBits(1));let x=1,y=1,T=0;return w||(n===0?(x=1,y=1):n===1?(x=0,y=0):b===12&&(x=i.readBits(1),x&&(y=i.readBits(1))),x&&y&&(T=i.readBits(2))),{profile:n,level:a,tier:c,bitDepth:b,monochrome:w,chromaSubsamplingX:x,chromaSubsamplingY:y,chromaSamplePosition:T}}return null},Pn=t=>{let e=V(t),r=e.getUint8(9),i=e.getUint16(10,!0),n=e.getUint32(12,!0),s=e.getInt16(16,!0),o=e.getUint8(18),a=null;return o&&(a=t.subarray(19,21+r)),{outputChannelCount:r,preSkip:i,inputSampleRate:n,outputGain:s,channelMappingFamily:o,channelMappingTable:a}},pd=[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],zc=t=>{let e=t[0]>>3;return{durationInSamples:pd[e]}},Vc=t=>{if(t.length<7)throw new Error("Setup header is too short.");if(t[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...t.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let r=t.length,i=new Uint8Array(r);for(let d=0;d<r;d++)i[d]=t[r-1-d];let n=new W(i),s=0;for(;n.getBitsLeft()>97;)if(n.readBits(1)===1){s=n.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let o=0,a=!1,c=0;for(;n.getBitsLeft()>=97;){let d=n.pos,f=n.readBits(8),m=n.readBits(16),p=n.readBits(16);if(f>63||m!==0||p!==0){n.pos=d;break}if(n.skipBits(1),o++,o>64)break;n.clone().readBits(6)+1===o&&(a=!0,c=o)}if(!a)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let u=c;n.pos=0,n.skipBits(s);let l=Array(u).fill(0);for(let d=u-1;d>=0;d--)n.skipBits(40),l[d]=n.readBits(1);return{modeBlockflags:l}},Dn=(t,e,r)=>{switch(t){case"avc":{let i=Ks(r,e),n=i.some(s=>zt(s)===Ut.IDR);if(!n&&(!ai()||mc()>=144))for(let s of i){if(zt(s)!==Ut.SEI)continue;let a=Cn(s),c=1;do{let u=0;for(;;){let f=a[c++];if(f===void 0||(u+=f,f<255))break}let l=0;for(;;){let f=a[c++];if(f===void 0||(l+=f,f<255))break}if(u===6){let f=new W(a);f.pos=8*c;let m=_(f),p=f.readBits(1);if(m===0&&p===1){n=!0;break}}c+=l}while(c<a.length-1)}return n?"key":"delta"}case"hevc":return Zs(r,e).some(s=>{let o=tt(s);return me.BLA_W_LP<=o&&o<=me.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return(r[0]&1)===0?"key":"delta";case"vp9":{let i=new W(r);if(i.readBits(2)!==2)return null;let n=i.readBits(1);return(i.readBits(1)<<1)+n===3&&i.skipBits(1),i.readBits(1)?null:i.readBits(1)===0?"key":"delta"}case"av1":{let i=!1;for(let{type:n,data:s}of Uc(r))if(n===1){let o=new W(s);o.skipBits(4),i=!!o.readBits(1)}else if(n===3||n===6||n===7){if(i)return"key";let o=new W(s);return o.readBits(1)?null:o.readBits(2)===0?"key":"delta"}return null}default:ue(t),h(!1)}},gt;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(gt||(gt={}));var fi=(t,e)=>{let r=V(t),i=0,n=r.getUint32(i,!0);i+=4;let s=ae.decode(t.subarray(i,i+n));i+=n,n>0&&(e.raw??={},e.raw.vendor??=s);let o=r.getUint32(i,!0);i+=4;for(let a=0;a<o;a++){let c=r.getUint32(i,!0);i+=4;let u=ae.decode(t.subarray(i,i+c));i+=c;let l=u.indexOf("=");if(l===-1)continue;let d=u.slice(0,l).toUpperCase(),f=u.slice(l+1);switch(e.raw??={},e.raw[d]??=f,d){case"TITLE":e.title??=f;break;case"DESCRIPTION":e.description??=f;break;case"ARTIST":e.artist??=f;break;case"ALBUM":e.album??=f;break;case"ALBUMARTIST":e.albumArtist??=f;break;case"COMMENT":e.comment??=f;break;case"LYRICS":e.lyrics??=f;break;case"TRACKNUMBER":{let m=f.split("/"),p=Number.parseInt(m[0],10),g=m[1]&&Number.parseInt(m[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.tracksTotal??=g)}break;case"TRACKTOTAL":{let m=Number.parseInt(f,10);Number.isInteger(m)&&m>0&&(e.tracksTotal??=m)}break;case"DISCNUMBER":{let m=f.split("/"),p=Number.parseInt(m[0],10),g=m[1]&&Number.parseInt(m[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.discsTotal??=g)}break;case"DISCTOTAL":{let m=Number.parseInt(f,10);Number.isInteger(m)&&m>0&&(e.discsTotal??=m)}break;case"DATE":{let m=new Date(f);Number.isNaN(m.getTime())||(e.date??=m)}break;case"GENRE":e.genre??=f;break;case"METADATA_BLOCK_PICTURE":{let m=hc(f),p=V(m),g=p.getUint32(0,!1),b=p.getUint32(4,!1),w=String.fromCharCode(...m.subarray(8,8+b)),x=p.getUint32(8+b,!1),y=ae.decode(m.subarray(12+b,12+b+x)),T=p.getUint32(b+x+28),E=m.subarray(b+x+32,b+x+32+T);e.images??=[],e.images.push({data:E,mimeType:w,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:y||void 0})}break}}};var de=class{constructor(e){this.input=e}};var In=[],Fn=[],Lc=[],qc=[];var te=new Uint8Array(0),L=class t{constructor(e,r,i,n,s=-1,o,a){if(this.data=e,this.type=r,this.timestamp=i,this.duration=n,this.sequenceNumber=s,e===te&&o===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(o===void 0&&(o=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!=="key"&&r!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(o)||o<0)throw new TypeError("byteLength must be a non-negative integer.");if(a!==void 0&&(typeof a!="object"||!a))throw new TypeError("sideData, when provided, must be an object.");if(a?.alpha!==void 0&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(a?.alphaByteLength!==void 0&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=o,this.sideData=a??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===te}get microsecondTimestamp(){return Math.trunc(Le*this.timestamp)}get microsecondDuration(){return Math.trunc(Le*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,r){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let i=new Uint8Array(e.byteLength);return e.copyTo(i),new t(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,r)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new t(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var Hc=t=>{let i=t,n=4096,s=0,o=12,a=0;for(i<0&&(i=-i,s=128),i+=33,i>8191&&(i=8191);(i&n)!==n&&o>=5;)n>>=1,o--;return a=i>>o-4&15,~(s|o-5<<4|a)&255},Wc=t=>{let r=0,i=0,n=~t;n&128&&(n&=-129,r=-1),i=((n&240)>>4)+5;let s=(1<<i|(n&15)<<i-4|1<<i-5)-33;return r===0?s:-s},Gc=t=>{let r=2048,i=0,n=11,s=0,o=t;for(o<0&&(o=-o,i=128),o>4095&&(o=4095);(o&r)!==r&&n>=5;)r>>=1,n--;return s=o>>(n===4?1:n-4)&15,(i|n-4<<4|s)^85},jc=t=>{let e=0,r=0,i=t^85;i&128&&(i&=-129,e=-1),r=((i&240)>>4)+4;let n=0;return r!==4?n=1<<r|(i&15)<<r-4|1<<r-5:n=i<<1|1,e===0?n:-n};xn();var $c=-1/0,Qc=-1/0,hi=null;typeof FinalizationRegistry<"u"&&(hi=new FinalizationRegistry(t=>{let e=Date.now();t.type==="video"?(e-$c>=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."),$c=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-Qc>=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."),Qc=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));var eo=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],gd=new Set(eo),Ee=class t{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(Le*this.timestamp)}get microsecondDuration(){return Math.trunc(Le*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,r){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.format===void 0||!gd.has(r.format))throw new TypeError("init.format must be one of: "+eo.join(", "));if(!Number.isInteger(r.codedWidth)||r.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(r.codedHeight)||r.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=J(e).slice(),this._layout=r.layout??bd(r.format,r.codedWidth,r.codedHeight),this.format=r.format,this.codedWidth=r.codedWidth,this.codedHeight=r.codedHeight,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new pr(r.colorSpace)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(r?.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(r?.timestamp!==void 0&&!Number.isFinite(r?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(r?.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=r?.rotation??0,this.timestamp=r?.timestamp??e.timestamp/1e6,this.duration=r?.duration??(e.duration??0)/1e6,this.colorSpace=new pr(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new t(new VideoFrame(e,{timestamp:Math.trunc(r.timestamp*Le),duration:Math.trunc((r.duration??0)*Le)||void 0}),r);let i=0,n=0;if("naturalWidth"in e?(i=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,n=e.videoHeight):"width"in e&&(i=Number(e.width),n=Number(e.height)),!i||!n)throw new TypeError("Could not determine dimensions.");let s=new OffscreenCanvas(i,n),o=s.getContext("2d",{alpha:dr(),willReadFrequently:!0});h(o),o.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.codedWidth=i,this.codedHeight=n,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new pr({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");hi?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return h(this._data!==null),Vt(this._data)?new t(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(h(this._layout),new t(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 t(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||(hi?.unregister(this),Vt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Xc(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)===null)throw new Error("Cannot get allocation size when format is null. Please manually provide an RGB pixel format in the options instead.");if(h(this._data!==null),!Vt(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let r=this.toVideoFrame(),i=r.allocationSize(e);return r.close(),i}return Vt(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,r={}){if(!ur(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Xc(r),this._closed)throw new Error("VideoSample is closed.");if((r.format??this.format)===null)throw new Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(h(this._data!==null),!Vt(this._data)&&(r.colorSpace||r.format&&r.format!==this.format||r.layout||r.rect)){let i=this.toVideoFrame(),n=await i.copyTo(e,r);return i.close(),n}if(Vt(this._data))return this._data.copyTo(e,r);if(this._data instanceof Uint8Array)return h(this._layout),J(e).set(this._data),this._layout;{let n=this._data.getContext("2d");h(n);let s=n.getImageData(0,0,this.codedWidth,this.codedHeight);return J(e).set(s.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return h(this._data!==null),Vt(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,r,i,n,s,o,a,c,u){let l=0,d=0,f=this.displayWidth,m=this.displayHeight,p=0,g=0,b=this.displayWidth,w=this.displayHeight;if(o!==void 0?(l=r,d=i,f=n,m=s,p=o,g=a,c!==void 0?(b=c,w=u):(b=f,w=m)):(p=r,g=i,n!==void 0&&(b=n,w=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(g))throw new TypeError("dy must be a number.");if(!Number.isFinite(b)||b<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:d,sWidth:f,sHeight:m}=this._rotateSourceRegion(l,d,f,m,this.rotation));let x=this.toCanvasImageSource();e.save();let y=p+b/2,T=g+w/2;e.translate(y,T),e.rotate(this.rotation*Math.PI/180);let E=this.rotation%180===0?1:b/w;e.scale(1/E,E),e.drawImage(x,l,d,f,m,-b/2,-w/2,b,w),e.restore()}drawWithFit(e,r){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");r.crop!==void 0&&Yc(r.crop,"options.");let i=e.canvas.width,n=e.canvas.height,s=r.rotation??this.rotation,[o,a]=s%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];r.crop&&Kc(r.crop,o,a);let c,u,l,d,{sx:f,sy:m,sWidth:p,sHeight:g}=this._rotateSourceRegion(r.crop?.left??0,r.crop?.top??0,r.crop?.width??o,r.crop?.height??a,s);if(r.fit==="fill")c=0,u=0,l=i,d=n;else{let[w,x]=r.crop?[r.crop.width,r.crop.height]:[o,a],y=r.fit==="contain"?Math.min(i/w,n/x):Math.max(i/w,n/x);l=w*y,d=x*y,c=(i-l)/2,u=(n-d)/2}e.save();let b=s%180===0?1:l/d;e.translate(i/2,n/2),e.rotate(s*Math.PI/180),e.scale(1/b,b),e.translate(-i/2,-n/2),e.drawImage(this.toCanvasImageSource(),f,m,p,g,c,u,l,d),e.restore()}_rotateSourceRegion(e,r,i,n,s){return s===90?[e,r,i,n]=[r,this.codedHeight-e-i,n,i]:s===180?[e,r]=[this.codedWidth-e-i,this.codedHeight-r-n]:s===270&&([e,r,i,n]=[this.codedWidth-r-n,e,n,i]),{sx:e,sy:r,sWidth:i,sHeight:n}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(h(this._data!==null),this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}},pr=class{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}}},Vt=t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,Kc=(t,e,r)=>{t.left=Math.min(t.left,e),t.top=Math.min(t.top,r),t.width=Math.min(t.width,e-t.left),t.height=Math.min(t.height,r-t.top),h(t.width>=0),h(t.height>=0)},Yc=(t,e)=>{if(!t||typeof t!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Xc=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.colorSpace!==void 0&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(t.format!==void 0&&typeof t.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of t.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.rect!==void 0){if(!t.rect||typeof t.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(t.rect.x!==void 0&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(t.rect.y!==void 0&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(t.rect.width!==void 0&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(t.rect.height!==void 0&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},bd=(t,e,r)=>{let i=wd(t),n=[],s=0;for(let o of i){let a=Math.ceil(e/o.widthDivisor),c=Math.ceil(r/o.heightDivisor),u=a*o.sampleBytes,l=u*c;n.push({offset:s,stride:u}),s+=l}return n},wd=t=>{let e=(r,i,n,s,o)=>{let a=[{sampleBytes:r,widthDivisor:1,heightDivisor:1},{sampleBytes:i,widthDivisor:n,heightDivisor:s},{sampleBytes:i,widthDivisor:n,heightDivisor:s}];return o&&a.push({sampleBytes:r,widthDivisor:1,heightDivisor:1}),a};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(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:ue(t),h(!1)}},Js=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),Ae=class t{get microsecondTimestamp(){return Math.trunc(Le*this.timestamp)}get microsecondDuration(){return Math.trunc(Le*this.duration)}constructor(e){if(this._closed=!1,mi(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Js.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");let r=e.data.byteLength/(Lt(e.format)*e.numberOfChannels);if(!Number.isInteger(r))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=r,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=r/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let n=this.numberOfFrames*this.numberOfChannels*Lt(this.format);if(i.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}hi?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Js.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let r=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let n=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(n>this.numberOfFrames-i)throw new RangeError("frameCount out of range");let s=Lt(r),o=hr(r);if(o&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!o&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(o?n:n*this.numberOfChannels)*s}copyTo(e,r){if(!ur(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(r.planeIndex)||r.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(r.format!==void 0&&!Js.has(r.format))throw new TypeError("Invalid format.");if(r.frameOffset!==void 0&&(!Number.isInteger(r.frameOffset)||r.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(r.frameCount!==void 0&&(!Number.isInteger(r.frameCount)||r.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:i,format:n,frameCount:s,frameOffset:o}=r,a=this.format,c=n??this.format;if(!c)throw new Error("Destination format not determined");let u=this.numberOfFrames,l=this.numberOfChannels,d=o??0;if(d>=u)throw new RangeError("frameOffset out of range");let f=s!==void 0?s:u-d;if(f>u-d)throw new RangeError("frameCount out of range");let m=Lt(c),p=hr(c);if(p&&i>=l)throw new RangeError("planeIndex out of range");if(!p&&i!==0)throw new RangeError("planeIndex out of range");let b=(p?f:f*l)*m;if(e.byteLength<b)throw new RangeError("Destination buffer is too small");let w=V(e),x=Jc(c);if(mi(this._data))pt()&&l>2&&c!==a?xd(this._data,w,a,c,l,i,d,f):this._data.copyTo(e,{planeIndex:i,frameOffset:d,frameCount:f,format:c});else{let y=this._data,T=V(y),E=Zc(a),S=Lt(a),P=hr(a);for(let v=0;v<f;v++)if(p){let F=v*m,M;P?M=(i*u+(v+d))*S:M=((v+d)*l+i)*S;let B=E(T,M);x(w,F,B)}else for(let F=0;F<l;F++){let B=(v*l+F)*m,Q;P?Q=(F*u+(v+d))*S:Q=((v+d)*l+F)*S;let je=E(T,Q);x(w,B,je)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(mi(this._data)){let e=new t(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new t({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(hi?.unregister(this),mi(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(mi(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(hr(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),r=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(r,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:r})}else{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})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),r=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(r,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(r,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,o=e.length,a=Math.floor(i/n),c=0,u=o;for(;u>0;){let l=Math.min(a,u),d=new Float32Array(n*l);for(let f=0;f<n;f++)e.copyFromChannel(d.subarray(f*l,(f+1)*l),f,c);yield new t({format:"f32-planar",sampleRate:s,numberOfFrames:l,numberOfChannels:n,timestamp:r+c/s,data:d}),c+=l,u-=l}}static fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,o=e.length,a=Math.floor(i/n),c=0,u=o,l=[];for(;u>0;){let d=Math.min(a,u),f=new Float32Array(n*d);for(let p=0;p<n;p++)e.copyFromChannel(f.subarray(p*d,(p+1)*d),p,c);let m=new t({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:n,timestamp:r+c/s,data:f});l.push(m),c+=d,u-=d}return l}},Lt=t=>{switch(t){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},hr=t=>{switch(t){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Zc=t=>{switch(t){case"u8":case"u8-planar":return(e,r)=>(e.getUint8(r)-128)/128;case"s16":case"s16-planar":return(e,r)=>e.getInt16(r,!0)/32768;case"s32":case"s32-planar":return(e,r)=>e.getInt32(r,!0)/2147483648;case"f32":case"f32-planar":return(e,r)=>e.getFloat32(r,!0)}},Jc=t=>{switch(t){case"u8":case"u8-planar":return(e,r,i)=>e.setUint8(r,ee((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,r,i)=>e.setInt16(r,ee(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,r,i)=>e.setInt32(r,ee(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,r,i)=>e.setFloat32(r,i,!0)}},mi=t=>typeof AudioData<"u"&&t instanceof AudioData,xd=(t,e,r,i,n,s,o,a)=>{let c=Zc(r),u=Jc(i),l=Lt(r),d=Lt(i),f=hr(r);if(hr(i))if(f){let p=new ArrayBuffer(a*l),g=V(p);t.copyTo(p,{planeIndex:s,frameOffset:o,frameCount:a,format:r});for(let b=0;b<a;b++){let w=b*l,x=b*d,y=c(g,w);u(e,x,y)}}else{let p=new ArrayBuffer(a*n*l),g=V(p);t.copyTo(p,{planeIndex:0,frameOffset:o,frameCount:a,format:r});for(let b=0;b<a;b++){let w=(b*n+s)*l,x=b*d,y=c(g,w);u(e,x,y)}}else if(f){let p=a*l,g=new ArrayBuffer(p),b=V(g);for(let w=0;w<n;w++){t.copyTo(g,{planeIndex:w,frameOffset:o,frameCount:a,format:r});for(let x=0;x<a;x++){let y=x*l,T=(x*n+w)*d,E=c(b,y);u(e,T,E)}}}else{let p=new ArrayBuffer(a*n*l),g=V(p);t.copyTo(p,{planeIndex:0,frameOffset:o,frameCount:a,format:r});for(let b=0;b<a;b++)for(let w=0;w<n;w++){let x=b*n+w,y=x*l,T=x*d,E=c(g,y);u(e,T,E)}}};var gr=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.metadataOnly!==void 0&&typeof t.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(t.verifyKeyPackets!==void 0&&typeof t.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(t.verifyKeyPackets&&t.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},qt=t=>{if(!ui(t))throw new TypeError("timestamp must be a number.")},to=(t,e,r)=>r.verifyKeyPackets?e.then(async i=>{if(!i||i.type==="delta")return i;let n=await t.determinePacketType(i);return n&&(i.type=n),i}):e,Ht=class{constructor(e){if(!(e instanceof br))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(gr(e),this._track.input._disposed)throw new re;return to(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,r={}){if(qt(e),gr(r),this._track.input._disposed)throw new re;return to(this._track,this._track._backing.getPacket(e,r),r)}getNextPacket(e,r={}){if(!(e instanceof L))throw new TypeError("packet must be an EncodedPacket.");if(gr(r),this._track.input._disposed)throw new re;return to(this._track,this._track._backing.getNextPacket(e,r),r)}async getKeyPacket(e,r={}){if(qt(e),gr(r),this._track.input._disposed)throw new re;if(!r.verifyKeyPackets)return this._track._backing.getKeyPacket(e,r);let i=await this._track._backing.getKeyPacket(e,r);return i&&(h(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getKeyPacket(i.timestamp-1/this._track.timeResolution,r):i)}async getNextKeyPacket(e,r={}){if(!(e instanceof L))throw new TypeError("packet must be an EncodedPacket.");if(gr(r),this._track.input._disposed)throw new re;if(!r.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,r);let i=await this._track._backing.getNextKeyPacket(e,r);return i&&(h(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getNextKeyPacket(i,r):i)}packets(e,r,i={}){if(e!==void 0&&!(e instanceof L))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(r!==void 0&&!(r instanceof L))throw new TypeError("endPacket must be an EncodedPacket.");if(gr(i),this._track.input._disposed)throw new re;let n=[],{promise:s,resolve:o}=ce(),{promise:a,resolve:c}=ce(),u=!1,l=!1,d=null,f=[],m=()=>Math.max(2,f.length);(async()=>{let g=e??await this.getFirstPacket(i);for(;g&&!l&&!this._track.input._disposed&&!(r&&g.sequenceNumber>=r?.sequenceNumber);){if(n.length>m()){({promise:a,resolve:c}=ce()),await a;continue}n.push(g),o(),{promise:s,resolve:o}=ce(),g=await this.getNextPacket(g,i)}u=!0,o()})().catch(g=>{d||(d=g,o())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new re;if(l)return{value:void 0,done:!0};if(d)throw d;if(n.length>0){let g=n.shift(),b=performance.now();for(f.push(b);f.length>0&&b-f[0]>=1e3;)f.shift();return c(),{value:g,done:!1}}else{if(u)return{value:void 0,done:!0};await s}}},async return(){return l=!0,c(),o(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},pi=class{constructor(e,r){this.onSample=e,this.onError=r}},gi=class{mediaSamplesInRange(e=0,r=1/0){qt(e),qt(r);let i=[],n=!1,s=null,{promise:o,resolve:a}=ce(),{promise:c,resolve:u}=ce(),l=!1,d=!1,f=!1,m=null;(async()=>{let b=await this._createDecoder(S=>{if(u(),S.timestamp>=r&&(d=!0),d){S.close();return}s&&(S.timestamp>e?(i.push(s),n=!0):s.close()),S.timestamp>=e&&(i.push(S),n=!0),s=n?null:S,i.length>0&&(a(),{promise:o,resolve:a}=ce())},S=>{m||(m=S,a())}),w=this._createPacketSink(),x=await w.getKeyPacket(e,{verifyKeyPackets:!0})??await w.getFirstPacket(),y=x,T;if(r<1/0){let S=await w.getPacket(r),P=S?S.type==="key"&&S.timestamp===r?S:await w.getNextKeyPacket(S,{verifyKeyPackets:!0}):null;P&&(T=P)}let E=w.packets(x??void 0,T);for(await E.next();y&&!d&&!this._track.input._disposed;){let S=eu(i.length);if(i.length+b.getDecodeQueueSize()>S){({promise:c,resolve:u}=ce()),await c;continue}b.decode(y);let P=await E.next();if(P.done)break;y=P.value}await E.return(),!f&&!this._track.input._disposed&&await b.flush(),b.close(),!n&&s&&i.push(s),l=!0,a()})().catch(b=>{m||(m=b,a())});let p=this._track,g=()=>{s?.close();for(let b of i)b.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new re;if(f)return{value:void 0,done:!0};if(m)throw g(),m;if(i.length>0){let b=i.shift();return u(),{value:b,done:!1}}else if(!l)await o;else return{value:void 0,done:!0}}},async return(){return f=!0,d=!0,u(),a(),g(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){ac(e);let r=oc(e),i=[],n=[],{promise:s,resolve:o}=ce(),{promise:a,resolve:c}=ce(),u=!1,l=!1,d=null,f=g=>{n.push(g),o(),{promise:s,resolve:o}=ce()};(async()=>{let g=await this._createDecoder(S=>{if(c(),l){S.close();return}let P=0;for(;i.length>0&&S.timestamp-i[0]>-1e-10;)P++,i.shift();if(P>0)for(let v=0;v<P;v++)f(v<P-1?S.clone():S);else S.close()},S=>{d||(d=S,o())}),b=this._createPacketSink(),w=null,x=null,y=-1,T=async()=>{h(x);let S=x;for(g.decode(S);S.sequenceNumber<y;){let P=eu(n.length);for(;n.length+g.getDecodeQueueSize()>P&&!l;)({promise:a,resolve:c}=ce()),await a;if(l)break;let v=await b.getNextPacket(S);h(v),g.decode(v),S=v}y=-1},E=async()=>{await g.flush();for(let S=0;S<i.length;S++)f(null);i.length=0};for await(let S of r){if(qt(S),l||this._track.input._disposed)break;let P=await b.getPacket(S),v=P&&await b.getKeyPacket(S,{verifyKeyPackets:!0});if(!v){y!==-1&&(await T(),await E()),f(null),w=null;continue}w&&(v.sequenceNumber!==x.sequenceNumber||P.timestamp<w.timestamp)&&(await T(),await E()),i.push(P.timestamp),y=Math.max(P.sequenceNumber,y),w=P,x=v}!l&&!this._track.input._disposed&&(y!==-1&&await T(),await E()),g.close(),u=!0,o()})().catch(g=>{d||(d=g,o())});let m=this._track,p=()=>{for(let g of n)g?.close()};return{async next(){for(;;){if(m.input._disposed)throw p(),new re;if(l)return{value:void 0,done:!0};if(d)throw p(),d;if(n.length>0){let g=n.shift();return h(g!==void 0),c(),{value:g,done:!1}}else if(!u)await s;else return{value:void 0,done:!0}}},async return(){return l=!0,c(),o(),p(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},eu=t=>t===0?40:8,ro=class extends pi{constructor(e,r,i,n,s,o){super(e,r),this.codec=i,this.decoderConfig=n,this.rotation=s,this.timeResolution=o,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new ht,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 a=In.find(c=>c.supports(i,n));if(a)this.customDecoder=new a,this.customDecoder.codec=i,this.customDecoder.config=n,this.customDecoder.onSample=c=>{if(!(c instanceof Ee))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=l=>{if(this.alphaQueue.length>0){let d=this.alphaQueue.shift();h(d!==void 0),this.mergeAlpha(l,d)}else this.colorQueue.push(l)};if(i==="avc"&&this.decoderConfig.description&&ai()){let l=Nc(J(this.decoderConfig.description));if(l&&l.sequenceParameterSets.length>0){let d=Ys(l.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let u=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:l=>{try{c(l)}catch(d){this.onError(d)}},error:l=>{l.stack=u,this.onError(l)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(h(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&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(h(this.decoder),pt()||qs(this.inputTimestamps,e.timestamp,r=>r),ai()&&this.currentPacketIndex===0&&this.codec==="avc"){let i=Ks(e.data,this.decoderConfig).filter(s=>{let o=zt(s);return!(o>=20&&o<=31)}),n=Rc(i,this.decoderConfig);e=new L(n,e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new io}catch(i){console.error("Due to an error, only color data will be decoded.",i),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let i=s=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let o=this.colorQueue.shift();h(o!==void 0),this.mergeAlpha(o,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let o=this.colorQueue.shift();h(o!==void 0),this.mergeAlpha(o,null)}else this.alphaQueue.push(null)},n=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{i(s)}catch(o){this.onError(o)}},error:s=>{s.stack=n,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}let r=Dn(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=r==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){return Zs(e,this.decoderConfig).some(i=>{let n=tt(i);return n===me.RASL_N||n===me.RASL_R})}sampleHandler(e){if(pt()){if(this.sampleQueue.length>0&&e.timestamp>=G(this.sampleQueue).timestamp){for(let r of this.sampleQueue)this.finalizeAndEmitSample(r);this.sampleQueue.length=0}qs(this.sampleQueue,e,r=>r.timestamp)}else{let r=this.inputTimestamps.shift();h(r!==void 0),e.setTimestamp(r),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,r){if(!r){let s=new Ee(e);this.sampleHandler(s);return}h(this.merger),this.merger.update(e,r),e.close(),r.close();let i=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),n=new Ee(i);this.sampleHandler(n)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(h(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),pt()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(h(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},io=class{constructor(){typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
7
|
+
`)}});var si=()=>({stdout:async t=>console.log(t),stderr:async t=>console.error(t)});var In=()=>ps()?ri():gs()?ii():si();var vn=()=>({stdout:async()=>{},stderr:async()=>{}});function An(){return()=>({stdout:t=>t,stderr:t=>t})}var Rt=class t{static writers={auto:In,void:vn,deno:ri,node:ii,console:si};static colors={auto:ws,colorful:()=>pr,colorless:()=>mr};static themes={auto:Cn,basic:Zr};static shapers={auto:En,none:An,errors:ei,timestamp:ti};writer=t.writers.auto();colors=t.colors.auto();theme=t.themes.auto();shaper=t.shapers.auto();async log(...e){await this.writer.stdout(this.shaper(this).stdout(e).join(" "))}async error(...e){await this.writer.stderr(this.shaper(this).stderr(e).join(" "))}setWriter(e){return this.writer=e,this}setColors(e){return this.colors=e,this}setTheme(e){return this.theme=e,this}setShaper(...e){return this.shaper=gr(...e),this}};var wr=class extends Rt{static dummy(){return new this().setWriter(Rt.writers.void())}rpcRequest=async({request:e,...r})=>{let i=this.colors.none;this.log(...this.#e(r),i(`${e.method}()`))};rpcError=async({request:e,error:r,...i})=>{this.error(...this.#e(i),`${e.method}()`,r)};#e({meta:e,label:r,remote:i}){let s=this.colors.mix(this.colors.blue,this.colors.dim),n=this.colors.mix(this.colors.cyan,this.colors.dim);return[e?this.#t(e):void 0,r||void 0,i===void 0?void 0:i?s("<-"):n("->")].filter(Boolean)}#t(e){let{headers:r}=e.request;return[this.colors.yellow(`[${e.ip}]`),this.colors.green(r.origin?r.origin:"(no-origin)")].join(" ")}};var Pe=class extends wr{rpcRequest=async()=>{}};function Ee(){let t,e,r=new Promise((s,n)=>{t=s,e=n});function i(s){return s.then(t).catch(e),r}return{promise:r,resolve:t,reject:e,entangle:i}}var Fn=Object.freeze({happy:t=>t!=null,sad:t=>t==null,boolean:t=>typeof t=="boolean",number:t=>typeof t=="number",string:t=>typeof t=="string",bigint:t=>typeof t=="bigint",object:t=>typeof t=="object"&&t!==null,array:t=>Array.isArray(t),fn:t=>typeof t=="function",symbol:t=>typeof t=="symbol"});var br=class extends Error{milliseconds;name=this.constructor.name;constructor(e){super(`deadline exceeded (${(e/1e3).toFixed(1)} seconds)`),this.milliseconds=e}};function Rn(t,e){return t<=0||t===1/0?e():new Promise((r,i)=>{let s=setTimeout(()=>i(new br(t)),t);e().then(r).catch(i).finally(()=>clearTimeout(s))})}function ni(){let t=[];function e(){for(let r of t)r();t=[]}return e.schedule=(...r)=>(t.push(...r),e),e}function Bn(t,e){let r=t;for(let i of e)if(r=r[i],Fn.sad(r))break;return r}function sc(){let t=new Set;async function e(...c){await Promise.all([...t].map(l=>l(...c)))}function r(c){return t.add(c),()=>{t.delete(c)}}async function i(...c){return e(...c)}function s(c){return r(c)}async function n(c){let{promise:l,resolve:d}=Ee(),u=s(async(...h)=>{c&&await c(...h),d(h),u()});return l}function a(){t.clear()}let o={pub:i,sub:s,publish:e,subscribe:r,on:r,next:n,clear:a};return Object.assign(s,o),Object.assign(i,o),o}function ai(t){let e=sc();return t&&e.sub(t),e.pub}var De;(function(t){t.version="2.0";function e(r){return"id"in r?r.id:null}t.getId=e,t.errorCodes={serverError:-32e3,unexposedError:-32001}})(De||(De={}));var oi=class extends Error{name=this.constructor.name},at=class extends Error{name=this.constructor.name};async function Dn({tap:t,request:e,action:r}){let i=De.getId(e);try{let s=await r();return i===null?null:{id:i,result:s,jsonrpc:De.version}}catch(s){return t.rpcError({request:e,error:s}),i===null?null:{id:i,jsonrpc:De.version,error:s instanceof oi?{code:De.errorCodes.serverError,message:s.message}:{code:De.errorCodes.unexposedError,message:"unexposed error"}}}}function ci(t){let e=t.tap??new Pe;return async r=>{let i=r.method.split("."),s=Bn(t.fns,i),n=async()=>await s(...r.params);return e.rpcRequest({request:r}),await Dn({tap:e,request:r,action:n})}}var On=Symbol("tune"),nc=Symbol("query"),ac=Symbol("notify"),oc=Symbol("settings");function zn(t){function e(r){let i={notify:void 0};return new Proxy((()=>{}),{apply:(s,n,a)=>t(r,a,i),get:(s,n)=>{if(n!=="then")return n===On?a=>(...o)=>t(r,o,{...i,...a}):n===ac?(...a)=>t(r,a,{...i,notify:!0}):n===nc?(...a)=>t(r,a,{...i,notify:!1}):n===oc?i:(s[n]||(s[n]=e([...r,n])),s[n])},set:(s,n,a)=>(s[n]=a,!0)})}return e([])}function ot(t){let{endpoint:e,tap:r=new Pe}=t,i=1;return zn(async(s,n,a)=>{let o=a.notify??t.notify??!1,c=a.transfer,l={jsonrpc:"2.0",method:s.join("."),params:n},d=o?l:{...l,id:i++};r.rpcRequest({request:d});let u=await e(d,{transfer:c});if(o&&!u)return null;if(!u)throw new at("response was null, but shouldn't be, because the request was not a notification");if("error"in u)throw new at(t.label?`${t.label}: ${u.error.message}`:u.error.message);return u.result})}function kr(t){return ot({endpoint:ci(t),tap:t.tap})}var ct=class{recv=ai();sendRequest=ai();sendResponse=ai();static makeEntangledPair({origin:e="example.e280.org"}={}){let r=new this,i=new this,s=[r.sendRequest.sub(a=>i.recv(a,{origin:e})),r.sendResponse.sub(a=>i.recv(a,{origin:e})),i.sendRequest.sub(a=>r.recv(a,{origin:e})),i.sendResponse.sub(a=>r.recv(a,{origin:e}))];return[r,i,()=>s.forEach(a=>a())]}};function li(t,e){return t.addEventListener("message",e),()=>t.removeEventListener("message",e)}function Mn(t,e){return async(r,{transfer:i}={})=>{if("id"in r){let s=Ee();return e(r,i,s.promise),t.wait(r.id,r.method).then(n=>(s.resolve(n),n))}else{let s=Promise.resolve(null);return e(r,i,s),s}}}function Un(t){let e=[],r=[];for(let i of Array.isArray(t)?t:[t])"method"in i?e.push(i):r.push(i);return{requests:e,responses:r}}async function Nn(t,e){let r=(await Promise.all(e.map(async i=>t(i)))).filter(i=>i!==null);return r.length===0?null:r.length===1?r[0]:r}var Bt=class extends ct{dispose=ni();constructor(e){super(),this.dispose.schedule(this.sendRequest.sub((r,i)=>e.postMessage(r,i)),this.sendResponse.sub((r,i)=>e.postMessage(r,i)),li(e,r=>this.recv(r.data,r)))}};var ui=class{remote;transfer;constructor(e){this.remote=e}};var bs=Object.freeze({timeout:6e4,maxRequestBytes:1e7});var di=class{timeout;pending=new Map;constructor(e){this.timeout=e}async wait(e,r){let i=Ee();return this.pending.set(e,{method:r,deferred:i}),await Rn(this.timeout,()=>i.promise).catch(s=>{throw s instanceof br&&(s.message=`request #${e} ${r}(), ${s.message}`),s})}deliverResponse(e){let r=this.pending.get(e.id);r&&("error"in e?r.deferred.reject(new at(e.error.message)):r.deferred.resolve(e))}};var lt=class{options;remote;remoteEndpoint;dispose=ni();#e;constructor(e){this.options=e;let{conduit:r,tap:i}=e;this.#e=new di(e.timeout??bs.timeout),this.remoteEndpoint=Mn(this.#e,r.sendRequest.pub.bind(r.sendRequest)),this.remote=ot({endpoint:this.remoteEndpoint,tap:i&&ms(i,{remote:!0})}),this.dispose.schedule(r.recv.sub(s=>this.recv(s)))}async recv(e){let r=new ui(this.remote),{conduit:i,rpc:s,tap:n}=this.options,{requests:a,responses:o}=Un(e);for(let u of o)this.#e.deliverResponse(u);if(!s)return;let c=await s(r),l=ci({fns:c,tap:n&&ms(n,{remote:!1})}),d=await Nn(l,a);d&&await i.sendResponse(d,r.transfer)}};var Oe={derive:{host:t=>({host:t.remote.host,get transfer(){return t.transfer},set transfer(e){t.transfer=e}}),work:t=>({work:t.remote,get transfer(){return t.transfer},set transfer(e){t.transfer=e}})},mock:{host:()=>({host:void 0,transfer:void 0}),work:()=>({work:void 0,transfer:void 0})}};var ze=new Pe;async function Vn(t,e,r={}){let i=r.tap??ze,s=new lt({tap:i,timeout:r.timeout??1/0,conduit:new Bt(t.getSelf()),rpc:async n=>e(Oe.derive.host(n))});return await s.remote.infra.ready(),s.remote.host}var Dt=class{worker;messenger;constructor(e,r){this.worker=e,this.messenger=r}static async make(e,r){let i=r.tap??ze,s=r.label??"comrade",n=e.loadWorker(r.workerUrl,s),a=Ee(),o={async ready(){a.resolve()}},c=new lt({tap:i,timeout:r.timeout??1/0,conduit:new Bt(n),rpc:async l=>({infra:o,host:r.setupHost(Oe.derive.work(l))})});return await a.promise,new this(n,c)}get work(){return this.messenger.remote}terminate(){this.worker.terminate()}};var hi=class{threads;static async make(e,r){let i=r.workerCount??e.guessOptimalThreadCount(),s=await Promise.all([...Array(i)].map(async(n,a)=>Dt.make(e,{...r,label:r.label??`${r.label??"comrade"}_${a+1}`})));return new this(s,{tap:r.tap})}work;#e=new Set;#t=[];constructor(e,r={}){this.threads=e;let i=r.tap??ze,s=async(n,a)=>this.#i({request:n,prom:Ee(),transfer:a?.transfer});this.work=ot({tap:i,endpoint:s}),e.forEach(n=>this.#e.add(n))}get threadCount(){return this.threads.length}terminate(){for(let e of this.threads)e.terminate()}#i(e){return this.#t.push(e),this.#r(),e.prom.promise}#r(){for(;this.#e.size>0&&this.#t.length>0;){let e=[...this.#e].pop();this.#e.delete(e);let r=this.#t.shift();this.#e.delete(e);let i=e.messenger.remoteEndpoint(r.request,{transfer:r.transfer});r.prom.entangle(i).finally(()=>{this.#e.add(e),this.#r()})}}};var Ln=t=>({thread:e=>Dt.make(t,e),cluster:e=>hi.make(t,e),worker:(e,r={})=>Vn(t,e,r),work:e=>e,host:e=>e,mocks(e){let{setupWork:r,setupHost:i,tap:s=ze}=e,n=Oe.mock.host(),a=Oe.mock.work();return a.work=kr({tap:s,fns:r(n)}),n.host=kr({tap:s,fns:i(a)}),{workShell:a,hostShell:n,work:a.work,host:n.host}},mockWork(e,r=ze){let i=Oe.mock.host(),s=Oe.mock.work();return s.work=kr({tap:r,fns:e(i)}),{workShell:s,hostShell:i,work:s.work,mockHost:n=>(i.host=kr({tap:r,fns:n(s)}),{workShell:s,hostShell:i,work:s.work,host:i.host})}}});var Wn=()=>({getSelf(){return self},guessOptimalThreadCount(){let t=navigator.hardwareConcurrency??1;return Math.max(1,t-1)},loadWorker(t,e){return new window.Worker(t,{name:e,type:"module"})},async loadWasm(t){return WebAssembly.instantiateStreaming(fetch(t))}});var uc=Wn(),fi=Ln(uc);function m(t){if(!t)throw new Error("Assertion failed.")}var mi=t=>{let e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},q=t=>t&&t[t.length-1],ut=t=>t>=0&&t<2**32,H=class t{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),r=this.bytes[e]??0,i=7-(this.pos&7),s=(r&1<<i)>>i;return this.pos++,s}readBits(e){if(e===1)return this.readBit();let r=0;for(let i=0;i<e;i++)r<<=1,r|=this.readBit();return r}writeBits(e,r){let i=this.pos+e;for(let s=this.pos;s<i;s++){let n=Math.floor(s/8),a=this.bytes[n],o=7-(s&7);a&=~(1<<o),a|=(r&1<<i-s-1)>>i-s-1<<o,this.bytes[n]=a}this.pos=i}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,r=this.bytes[e]??0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new t(this.bytes);return e.pos=this.pos,e}},I=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},Ie=t=>{let e=I(t);return(e&1)===0?-(e>>1):e+1>>1};var K=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),V=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),ie=new TextDecoder,ue=new TextEncoder;var Ss=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),dt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},pi=Ss(dt),ht={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},gi=Ss(ht),ft={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},wi=Ss(ft),qn=t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,Ot=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),le=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,r=new Promise(s=>{e=s}),i=this.currentPromise;return this.currentPromise=r,await i,e}},Cs=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),_s=t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0),mt=(t,e,r)=>{let i=0,s=t.length-1,n=-1;for(;i<=s;){let a=i+s>>1,o=r(t[a]);o===e?(n=a,s=a-1):o<e?i=a+1:s=a-1}return n},M=(t,e,r)=>{let i=0,s=t.length-1,n=-1;for(;i<=s;){let a=i+(s-i+1)/2|0;r(t[a])<=e?(n=a,i=a+1):s=a-1}return n},Ps=(t,e,r)=>{let i=M(t,r(e),r);t.splice(i+1,0,e)},se=()=>{let t,e;return{promise:new Promise((i,s)=>{t=i,e=s}),resolve:t,reject:e}};var Es=(t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return t[r]},bi=(t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1},jn=async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},$n=t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},ne=t=>{throw new Error(`Unexpected value: ${t}`)},pt=(t,e,r)=>{let i=t.getUint8(e),s=t.getUint8(e+1),n=t.getUint8(e+2);return r?i|s<<8|n<<16:i<<16|s<<8|n},Qn=(t,e,r)=>pt(t,e,r)<<8>>8,yr=(t,e,r,i)=>{r=r>>>0,r=r&16777215,i?(t.setUint8(e,r&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r>>>16&255)):(t.setUint8(e,r>>>16&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r&255))},Gn=(t,e,r,i)=>{r=X(r,-8388608,8388607),r<0&&(r=r+16777216&16777215),yr(t,e,r,i)};var X=(t,e,r)=>Math.max(e,Math.min(r,t)),G="und",gt=t=>{let e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},Kn=(t,e)=>Math.round(t/e)*e,Xn=t=>{let e=0;for(;t;)e++,t>>=1;return e},dc=/^[a-z]{3}$/,zt=t=>dc.test(t),ve=1e6*(1+Number.EPSILON),Is=(t,e)=>{let r={...t,...e};if(t.headers||e.headers){let i=t.headers?Hn(t.headers):{},s=e.headers?Hn(e.headers):{},n={...i};Object.entries(s).forEach(([a,o])=>{let c=Object.keys(n).find(l=>l.toLowerCase()===a.toLowerCase());c&&delete n[c],n[a]=o}),r.headers=n}return r},Hn=t=>{if(t instanceof Headers){let e={};return t.forEach((r,i)=>{e[i]=r}),e}if(Array.isArray(t)){let e={};return t.forEach(([r,i])=>{e[r]=i}),e}return t},vs=async(t,e,r,i,s)=>{let n=0;for(;;)try{return await t(e,r)}catch(a){if(s())throw a;n++;let o=i(n,a,e);if(o===null)throw a;if(console.error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await new Promise(c=>setTimeout(c,1e3*o)),s())throw a}},Yn=(t,e)=>{let r=t<0?-1:1;t=Math.abs(t);let i=0,s=1,n=1,a=0,o=t;for(;;){let c=Math.floor(o),l=c*n+i,d=c*a+s;if(d>e)return{numerator:r*n,denominator:a};if(i=n,s=a,n=l,a=d,o=1/(o-c),!isFinite(o))break}return{numerator:r*n,denominator:a}},Xe=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},ks=null,Ye=()=>ks!==null?ks:ks=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),ys=null,Mt=()=>ys!==null?ys:ys=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),Ts=null,Tr=()=>Ts!==null?Ts:Ts=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),xs=null,Zn=()=>{if(xs!==null)return xs;if(typeof navigator>"u")return null;let t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?xs=Number(t[1]):null},wt=(t,e)=>t!==-1?t:e,ki=(t,e,r,i)=>t<=i&&r<=e,xr=function*(t){for(let e in t){let r=t[e];r!==void 0&&(yield{key:e,value:r})}};var Jn=t=>{let e=atob(t),r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i);return r};var yi=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Sr=t=>typeof t=="number"&&!Number.isNaN(t);var ke=class{constructor(e,r){if(this.data=e,this.mimeType=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof r!="string")throw new TypeError("mimeType must be a string.")}},Cr=class{constructor(e,r,i,s){if(this.data=e,this.mimeType=r,this.name=i,this.description=s,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!==void 0&&typeof r!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(s!==void 0&&typeof s!="string")throw new TypeError("description, when provided, must be a string.")}},ea=t=>{if(!t||typeof t!="object")throw new TypeError("tags must be an object.");if(t.title!==void 0&&typeof t.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(t.artist!==void 0&&typeof t.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(t.album!==void 0&&typeof t.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(t.albumArtist!==void 0&&typeof t.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(t.trackNumber!==void 0&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(t.tracksTotal!==void 0&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(t.discNumber!==void 0&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(t.discsTotal!==void 0&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(t.genre!==void 0&&typeof t.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(t.date!==void 0&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(t.lyrics!==void 0&&typeof t.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(t.images!==void 0){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(let e of t.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(t.comment!==void 0&&typeof t.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(t.raw!==void 0){if(!t.raw||typeof t.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(let e of Object.values(t.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof ke)&&!(e instanceof Cr))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}};var de={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},ta=t=>{if(!t||typeof t!="object")throw new TypeError("disposition must be an object.");if(t.default!==void 0&&typeof t.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(t.forced!==void 0&&typeof t.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(t.original!==void 0&&typeof t.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(t.commentary!==void 0&&typeof t.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(t.hearingImpaired!==void 0&&typeof t.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(t.visuallyImpaired!==void 0&&typeof t.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};var Ae=["avc","hevc","vp9","av1","vp8"],Q=["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"],As=["aac","opus","mp3","vorbis","flac"],Ue=[...As,...Q],bt=["webvtt"],ra=[{maxMacroblocks:99,maxBitrate:64e3,level:10},{maxMacroblocks:396,maxBitrate:192e3,level:11},{maxMacroblocks:396,maxBitrate:384e3,level:12},{maxMacroblocks:396,maxBitrate:768e3,level:13},{maxMacroblocks:396,maxBitrate:2e6,level:20},{maxMacroblocks:792,maxBitrate:4e6,level:21},{maxMacroblocks:1620,maxBitrate:4e6,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14e6,level:31},{maxMacroblocks:5120,maxBitrate:2e7,level:32},{maxMacroblocks:8192,maxBitrate:2e7,level:40},{maxMacroblocks:8192,maxBitrate:5e7,level:41},{maxMacroblocks:8704,maxBitrate:5e7,level:42},{maxMacroblocks:22080,maxBitrate:135e6,level:50},{maxMacroblocks:36864,maxBitrate:24e7,level:51},{maxMacroblocks:36864,maxBitrate:24e7,level:52},{maxMacroblocks:139264,maxBitrate:24e7,level:60},{maxMacroblocks:139264,maxBitrate:48e7,level:61},{maxMacroblocks:139264,maxBitrate:8e8,level:62}],ia=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],Me=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],sa=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],na=".01.01.01.01.00",aa=".0.110.01.01.01.0",oa=(t,e,r,i)=>{if(t==="avc"){let n=Math.ceil(e/16)*Math.ceil(r/16),a=ra.find(u=>n<=u.maxMacroblocks&&i<=u.maxBitrate)??q(ra),o=a?a.level:0,c="64".padStart(2,"0"),l="00",d=o.toString(16).padStart(2,"0");return`avc1.${c}${l}${d}`}else if(t==="hevc"){let o=e*r,c=ia.find(d=>o<=d.maxPictureSize&&i<=d.maxBitrate)??q(ia);return`hev1.1.6.${c.tier}${c.level}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){let n=e*r;return`vp09.00.${(Me.find(c=>n<=c.maxPictureSize&&i<=c.maxBitrate)??q(Me)).level.toString().padStart(2,"0")}.08`}else if(t==="av1"){let n=e*r,a=sa.find(l=>n<=l.maxPictureSize&&i<=l.maxBitrate)??q(sa);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${t}'.`)};var ca=t=>{let e=t.split("."),s=(1<<7)+1,n=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(n<<5)+o,l=a.slice(-1)==="H"?1:0,u=Number(e[3])===8?0:1,h=0,f=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,g=e[5]?Number(e[5][1]):1,w=e[5]?Number(e[5][2]):0,b=(l<<7)+(u<<6)+(h<<5)+(f<<4)+(p<<3)+(g<<2)+w;return[s,c,b,0]},Ti=t=>{let{codec:e,codecDescription:r,colorSpace:i,avcCodecInfo:s,hevcCodecInfo:n,vp9CodecInfo:a,av1CodecInfo:o}=t;if(e==="avc"){if(m(t.avcType!==null),s){let c=new Uint8Array([s.avcProfileIndication,s.profileCompatibility,s.avcLevelIndication]);return`avc${t.avcType}.${Cs(c)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${Cs(r.subarray(1,4))}`}else if(e==="hevc"){let c,l,d,u,h,f;if(n)c=n.generalProfileSpace,l=n.generalProfileIdc,d=_s(n.generalProfileCompatibilityFlags),u=n.generalTierFlag,h=n.generalLevelIdc,f=[...n.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let g=V(r),w=g.getUint8(1);c=w>>6&3,l=w&31,d=_s(g.getUint32(2)),u=w>>5&1,h=g.getUint8(12),f=[];for(let b=0;b<6;b++)f.push(g.getUint8(6+b))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=d.toString(16).toUpperCase(),p+=".",p+=u===0?"L":"H",p+=h;f.length>0&&f[f.length-1]===0;)f.pop();return f.length>0&&(p+=".",p+=f.map(g=>g.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){let b=t.width*t.height,k=q(Me).level;for(let y of Me)if(b<=y.maxPictureSize){k=y.level;break}return`vp09.00.${k.toString().padStart(2,"0")}.08`}let c=a.profile.toString().padStart(2,"0"),l=a.level.toString().padStart(2,"0"),d=a.bitDepth.toString().padStart(2,"0"),u=a.chromaSubsampling.toString().padStart(2,"0"),h=a.colourPrimaries.toString().padStart(2,"0"),f=a.transferCharacteristics.toString().padStart(2,"0"),p=a.matrixCoefficients.toString().padStart(2,"0"),g=a.videoFullRangeFlag.toString().padStart(2,"0"),w=`vp09.${c}.${l}.${d}.${u}`;return w+=`.${h}.${f}.${p}.${g}`,w.endsWith(na)&&(w=w.slice(0,-na.length)),w}else if(e==="av1"){if(!o){let y=t.width*t.height,x=q(Me).level;for(let P of Me)if(y<=P.maxPictureSize){x=P.level;break}return`av01.0.${x.toString().padStart(2,"0")}M.08`}let c=o.profile,l=o.level.toString().padStart(2,"0"),d=o.tier?"H":"M",u=o.bitDepth.toString().padStart(2,"0"),h=o.monochrome?"1":"0",f=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),p=i?.primaries?dt[i.primaries]:1,g=i?.transfer?ht[i.transfer]:1,w=i?.matrix?ft[i.matrix]:1,b=i?.fullRange?1:0,k=`av01.${c}.${l}${d}.${u}`;return k+=`.${h}.${f.toString().padStart(3,"0")}`,k+=`.${p.toString().padStart(2,"0")}`,k+=`.${g.toString().padStart(2,"0")}`,k+=`.${w.toString().padStart(2,"0")}`,k+=`.${b}`,k.endsWith(aa)&&(k=k.slice(0,-aa.length)),k}}throw new TypeError(`Unhandled codec '${e}'.`)},la=(t,e,r)=>{if(t==="aac")return e>=2&&r<=24e3?"mp4a.40.29":r<=24e3?"mp4a.40.5":"mp4a.40.2";if(t==="mp3")return"mp3";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";if(t==="flac")return"flac";if(Q.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},xi=t=>{let{codec:e,codecDescription:r,aacCodecInfo:i}=t;if(e==="aac"){if(!i)throw new TypeError("AAC codec info must be provided.");return i.isMpeg2?"mp4a.67":`mp4a.40.${_r(r).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&Q.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},Ut=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Si=[-1,1,2,3,4,5,6,8],_r=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new H(t),r=e.readBits(5);r===31&&(r=32+e.readBits(6));let i=e.readBits(4),s=null;i===15?s=e.readBits(24):i<Ut.length&&(s=Ut[i]);let n=e.readBits(4),a=null;return n>=1&&n<=7&&(a=Si[n]),{objectType:r,frequencyIndex:i,sampleRate:s,channelConfiguration:n,numberOfChannels:a}},ua=t=>{let e=Ut.indexOf(t.sampleRate),r=null;e===-1&&(e=15,r=t.sampleRate);let i=Si.indexOf(t.numberOfChannels);if(i===-1)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let s=13;t.objectType>=32&&(s+=6),e===15&&(s+=24);let n=Math.ceil(s/8),a=new Uint8Array(n),o=new H(a);return t.objectType<32?o.writeBits(5,t.objectType):(o.writeBits(5,31),o.writeBits(6,t.objectType-32)),o.writeBits(4,e),e===15&&o.writeBits(24,r),o.writeBits(4,i),a},kt=48e3,da=/^pcm-([usf])(\d+)+(be)?$/,fe=t=>{if(m(Q.includes(t)),t==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(t==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=da.exec(t);m(e);let r;e[1]==="u"?r="unsigned":e[1]==="s"?r="signed":r="float";let i=Number(e[2])/8,s=e[3]!=="be",n=t==="pcm-u8"?2**7:0;return{dataType:r,sampleSize:i,littleEndian:s,silentValue:n}},Fs=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":t==="vp8"?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":t.startsWith("mp4a.40")||t==="mp4a.67"?"aac":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"?"mp3":t==="opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ulaw"?"ulaw":t==="alaw"?"alaw":da.test(t)?t:t==="webvtt"?"webvtt":null,ha=t=>t==="avc"?{avc:{format:"avc"}}:t==="hevc"?{hevc:{format:"hevc"}}:{},fa=t=>t==="aac"?{aac:{format:"aac"}}:t==="opus"?{opus:{format:"opus"}}:{},hc=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],fc=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,mc=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,pc=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,gc=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,ma=t=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Video chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!hc.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(t.decoderConfig.description!==void 0&&!Ot(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=t.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let r=Object.keys(dt);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);let i=Object.keys(ht);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);let s=Object.keys(ft);if(e.matrix!=null&&!s.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${s.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!fc.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(t.decoderConfig.codec.startsWith("hev1")||t.decoderConfig.codec.startsWith("hvc1")){if(!mc.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(t.decoderConfig.codec.startsWith("vp8")){if(t.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(t.decoderConfig.codec.startsWith("vp09")){if(!pc.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(t.decoderConfig.codec.startsWith("av01")&&!gc.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},wc=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],pa=t=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!wc.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(t.decoderConfig.description!==void 0&&!Ot(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if(t.decoderConfig.codec!=="mp3"&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if(t.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if(t.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if(t.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!Q.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Q.join(", ")}).`)},ga=t=>{if(!t)throw new TypeError("Subtitle metadata must be provided.");if(typeof t!="object")throw new TypeError("Subtitle metadata must be an object.");if(!t.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof t.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof t.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};var Ci=class{constructor(e){this.mutex=new le,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,r,i){r+=e.source._timestampOffset;let s=this.trackTimestampInfo.get(e);if(!s){if(!i)throw new Error("First packet must be a key packet.");s={maxTimestamp:r,maxTimestampBeforeLastKeyPacket:r},this.trackTimestampInfo.set(e,s)}if(r<0)throw new Error(`Timestamps must be non-negative (got ${r}s).`);if(i&&(s.maxTimestampBeforeLastKeyPacket=s.maxTimestamp),r<s.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${r}s, but largest timestamp is ${s.maxTimestampBeforeLastKeyPacket}s.`);return s.maxTimestamp=Math.max(s.maxTimestamp,r),r}};var yt;(function(t){t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.SPS_EXT=13]="SPS_EXT"})(yt||(yt={}));var ce;(function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(ce||(ce={}));var Nt=t=>{let e=[],r=0;for(;r<t.length;){let i=-1,s=0;for(let n=r;n<t.length-3;n++){if(t[n]===0&&t[n+1]===0&&t[n+2]===1){i=n,s=3;break}if(n<t.length-4&&t[n]===0&&t[n+1]===0&&t[n+2]===0&&t[n+3]===1){i=n,s=4;break}}if(i===-1)break;if(r>0&&i>r){let n=t.subarray(r,i);n.length>0&&e.push(n)}r=i+s}if(r<t.length){let i=t.subarray(r);i.length>0&&e.push(i)}return e},ba=(t,e)=>{let r=[],i=0,s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;i+e<=t.length;){let n;e===1?n=s.getUint8(i):e===2?n=s.getUint16(i,!1):e===3?n=pt(s,i,!1):e===4?n=s.getUint32(i,!1):(ne(e),m(!1)),i+=e;let a=t.subarray(i,i+n);r.push(a),i+=n}return r},_i=t=>{let e=[],r=t.length;for(let i=0;i<r;i++)i+2<r&&t[i]===0&&t[i+1]===0&&t[i+2]===3?(e.push(0,0),i+=2):e.push(t[i]);return new Uint8Array(e)},Rs=new Uint8Array([0,0,0,1]),bc=t=>{let e=t.reduce((s,n)=>s+Rs.byteLength+n.byteLength,0),r=new Uint8Array(e),i=0;for(let s of t)r.set(Rs,i),i+=Rs.byteLength,r.set(s,i),i+=s.byteLength;return r},Bs=(t,e)=>{let r=t.reduce((n,a)=>n+e+a.byteLength,0),i=new Uint8Array(r),s=0;for(let n of t){let a=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(e){case 1:a.setUint8(s,n.byteLength);break;case 2:a.setUint16(s,n.byteLength,!1);break;case 3:yr(a,s,n.byteLength,!1);break;case 4:a.setUint32(s,n.byteLength,!1);break}s+=e,i.set(n,s),s+=n.byteLength}return i},Ds=(t,e)=>{if(e.description){let s=(K(e.description)[4]&3)+1;return ba(t,s)}else return Nt(t)},ka=(t,e)=>{if(e.description){let s=(K(e.description)[4]&3)+1;return Bs(t,s)}else return bc(t)},Tt=t=>t[0]&31,Pi=t=>{try{let e=Nt(t),r=e.filter(c=>Tt(c)===yt.SPS),i=e.filter(c=>Tt(c)===yt.PPS),s=e.filter(c=>Tt(c)===yt.SPS_EXT);if(r.length===0||i.length===0)return null;let n=r[0],a=Os(n);m(a!==null);let o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:r,pictureParameterSets:i,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?s:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},ya=t=>{let e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|t.lengthSizeMinusOne&3),e.push(224|t.sequenceParameterSets.length&31);for(let r of t.sequenceParameterSets){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let s=0;s<i;s++)e.push(r[s])}e.push(t.pictureParameterSets.length);for(let r of t.pictureParameterSets){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let s=0;s<i;s++)e.push(r[s])}if(t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144){m(t.chromaFormat!==null),m(t.bitDepthLumaMinus8!==null),m(t.bitDepthChromaMinus8!==null),m(t.sequenceParameterSetExt!==null),e.push(252|t.chromaFormat&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.sequenceParameterSetExt.length);for(let r of t.sequenceParameterSetExt){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let s=0;s<i;s++)e.push(r[s])}}return new Uint8Array(e)},Ta=t=>{try{let e=V(t),r=0,i=e.getUint8(r++),s=e.getUint8(r++),n=e.getUint8(r++),a=e.getUint8(r++),o=e.getUint8(r++)&3,c=e.getUint8(r++)&31,l=[];for(let f=0;f<c;f++){let p=e.getUint16(r,!1);r+=2,l.push(t.subarray(r,r+p)),r+=p}let d=e.getUint8(r++),u=[];for(let f=0;f<d;f++){let p=e.getUint16(r,!1);r+=2,u.push(t.subarray(r,r+p)),r+=p}let h={configurationVersion:i,avcProfileIndication:s,profileCompatibility:n,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((s===100||s===110||s===122||s===144)&&r+4<=t.length){let f=e.getUint8(r++)&3,p=e.getUint8(r++)&7,g=e.getUint8(r++)&7,w=e.getUint8(r++);h.chromaFormat=f,h.bitDepthLumaMinus8=p,h.bitDepthChromaMinus8=g;let b=[];for(let k=0;k<w;k++){let y=e.getUint16(r,!1);r+=2,b.push(t.subarray(r,r+y)),r+=y}h.sequenceParameterSetExt=b}return h}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},Os=t=>{try{let e=new H(_i(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let i=e.readAlignedByte(),s=e.readAlignedByte(),n=e.readAlignedByte();I(e);let a=null,o=null,c=null;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(a=I(e),a===3&&e.skipBits(1),o=I(e),c=I(e),e.skipBits(1),e.readBits(1))){for(let h=0;h<(a!==3?8:12);h++)if(e.readBits(1)){let p=h<6?16:64,g=8,w=8;for(let b=0;b<p;b++){if(w!==0){let k=Ie(e);w=(g+k+256)%256}g=w===0?g:w}}}I(e);let l=I(e);if(l===0)I(e);else if(l===1){e.skipBits(1),Ie(e),Ie(e);let u=I(e);for(let h=0;h<u;h++)Ie(e)}I(e),e.skipBits(1),I(e),I(e);let d=e.readBits(1);return{profileIdc:i,constraintFlags:s,levelIdc:n,frameMbsOnlyFlag:d,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},zs=(t,e)=>{if(e.description){let s=(K(e.description)[21]&3)+1;return ba(t,s)}else return Nt(t)},Ne=t=>t[0]>>1&63,Ei=t=>{try{let e=Nt(t),r=e.filter(N=>Ne(N)===ce.VPS_NUT),i=e.filter(N=>Ne(N)===ce.SPS_NUT),s=e.filter(N=>Ne(N)===ce.PPS_NUT),n=e.filter(N=>Ne(N)===ce.PREFIX_SEI_NUT||Ne(N)===ce.SUFFIX_SEI_NUT);if(i.length===0||s.length===0)return null;let a=i[0],o=new H(_i(a));o.skipBits(16),o.readBits(4);let c=o.readBits(3),l=o.readBits(1),{general_profile_space:d,general_tier_flag:u,general_profile_idc:h,general_profile_compatibility_flags:f,general_constraint_indicator_flags:p,general_level_idc:g}=kc(o,c);I(o);let w=I(o);w===3&&o.skipBits(1),I(o),I(o),o.readBits(1)&&(I(o),I(o),I(o),I(o));let b=I(o),k=I(o);I(o);let x=o.readBits(1)?0:c;for(let N=x;N<=c;N++)I(o),I(o),I(o);I(o),I(o),I(o),I(o),I(o),I(o),o.readBits(1)&&o.readBits(1)&&yc(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),I(o),I(o),o.skipBits(1));let P=I(o);if(Tc(o,P),o.readBits(1)){let N=I(o);for(let z=0;z<N;z++)I(o),o.skipBits(1)}o.skipBits(1),o.skipBits(1);let S=0;o.readBits(1)&&(S=Sc(o,c));let A=0;if(s.length>0){let N=s[0],z=new H(_i(N));z.skipBits(16),I(z),I(z),z.skipBits(1),z.skipBits(1),z.skipBits(3),z.skipBits(1),z.skipBits(1),I(z),I(z),Ie(z),z.skipBits(1),z.skipBits(1),z.readBits(1)&&I(z),Ie(z),Ie(z),z.skipBits(1),z.skipBits(1),z.skipBits(1),z.skipBits(1);let re=z.readBits(1),nt=z.readBits(1);!re&&!nt?A=0:re&&!nt?A=2:!re&&nt?A=3:A=0}let E=[...r.length?[{arrayCompleteness:1,nalUnitType:ce.VPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:ce.SPS_NUT,nalUnits:i}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:ce.PPS_NUT,nalUnits:s}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Ne(n[0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:d,generalTierFlag:u,generalProfileIdc:h,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:p,generalLevelIdc:g,minSpatialSegmentationIdc:S,parallelismType:A,chromaFormatIdc:w,bitDepthLumaMinus8:b,bitDepthChromaMinus8:k,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:l,lengthSizeMinusOne:3,arrays:E}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},kc=(t,e)=>{let r=t.readBits(2),i=t.readBits(1),s=t.readBits(5),n=0;for(let d=0;d<32;d++)n=n<<1|t.readBits(1);let a=new Uint8Array(6);for(let d=0;d<6;d++)a[d]=t.readBits(8);let o=t.readBits(8),c=[],l=[];for(let d=0;d<e;d++)c.push(t.readBits(1)),l.push(t.readBits(1));if(e>0)for(let d=e;d<8;d++)t.skipBits(2);for(let d=0;d<e;d++)c[d]&&t.skipBits(88),l[d]&&t.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:s,general_profile_compatibility_flags:n,general_constraint_indicator_flags:a,general_level_idc:o}},yc=t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))I(t);else{let s=Math.min(64,1<<4+(e<<1));e>1&&Ie(t);for(let n=0;n<s;n++)Ie(t)}},Tc=(t,e)=>{let r=[];for(let i=0;i<e;i++)r[i]=xc(t,i,e,r)},xc=(t,e,r,i)=>{let s=0,n=0,a=0;if(e!==0&&(n=t.readBits(1)),n){if(e===r){let c=I(t);a=e-(c+1)}else a=e-1;t.readBits(1),I(t);let o=i[a]??0;for(let c=0;c<=o;c++)t.readBits(1)||t.readBits(1);s=i[a]}else{let o=I(t),c=I(t);for(let l=0;l<o;l++)I(t),t.readBits(1);for(let l=0;l<c;l++)I(t),t.readBits(1);s=o+c}return s},Sc=(t,e)=>{if(t.readBits(1)&&t.readBits(8)===255&&(t.readBits(16),t.readBits(16)),t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),t.readBits(1),t.readBits(1)&&(t.readBits(8),t.readBits(8),t.readBits(8))),t.readBits(1)&&(I(t),I(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(I(t),I(t),I(t),I(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&I(t),t.readBits(1)&&Cc(t,!0,e)),t.readBits(1)){t.readBits(1),t.readBits(1),t.readBits(1);let r=I(t);return I(t),I(t),I(t),I(t),r}return 0},Cc=(t,e,r)=>{let i=!1,s=!1,n=!1;e&&(i=t.readBits(1)===1,s=t.readBits(1)===1,(i||s)&&(n=t.readBits(1)===1,n&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),n&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let a=0;a<=r;a++){let o=t.readBits(1)===1,c=!0;o||(c=t.readBits(1)===1);let l=!1;c?I(t):l=t.readBits(1)===1;let d=1;l||(d=I(t)+1),i&&wa(t,d,n),s&&wa(t,d,n)}},wa=(t,e,r)=>{for(let i=0;i<e;i++)I(t),I(t),r&&(I(t),I(t)),t.readBits(1)},xa=t=>{let e=[];e.push(t.configurationVersion),e.push((t.generalProfileSpace&3)<<6|(t.generalTierFlag&1)<<5|t.generalProfileIdc&31),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(t.generalProfileCompatibilityFlags&255),e.push(...t.generalConstraintIndicatorFlags),e.push(t.generalLevelIdc&255),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(t.minSpatialSegmentationIdc&255),e.push(252|t.parallelismType&3),e.push(252|t.chromaFormatIdc&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.avgFrameRate>>8&255),e.push(t.avgFrameRate&255),e.push((t.constantFrameRate&3)<<6|(t.numTemporalLayers&7)<<3|(t.temporalIdNested&1)<<2|t.lengthSizeMinusOne&3),e.push(t.arrays.length&255);for(let r of t.arrays){e.push((r.arrayCompleteness&1)<<7|0|r.nalUnitType&63),e.push(r.nalUnits.length>>8&255),e.push(r.nalUnits.length&255);for(let i of r.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let s=0;s<i.length;s++)e.push(i[s])}}return new Uint8Array(e)},Ii=t=>{let e=new H(t);if(e.readBits(2)!==2)return null;let i=e.readBits(1),n=(e.readBits(1)<<1)+i;if(n===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;n>=2&&(l=e.readBits(1)?12:10);let d=e.readBits(3),u=0,h=0;if(d!==7)if(h=e.readBits(1),n===1||n===3){let A=e.readBits(1),E=e.readBits(1);u=!A&&!E?3:A&&!E?2:1,e.skipBits(1)}else u=1;else u=3,h=1;let f=e.readBits(16),p=e.readBits(16),g=f+1,w=p+1,b=g*w,k=q(Me).level;for(let S of Me)if(b<=S.maxPictureSize){k=S.level;break}return{profile:n,level:k,bitDepth:l,chromaSubsampling:u,videoFullRangeFlag:h,colourPrimaries:d===2?1:d===1?6:2,transferCharacteristics:d===2?1:d===1?6:2,matrixCoefficients:d===7?0:d===2?1:d===1?6:2}},Sa=function*(t){let e=new H(t),r=()=>{let i=0;for(let s=0;s<8;s++){let n=e.readAlignedByte();if(i|=(n&127)<<s*7,!(n&128))break;if(s===7&&n&128)return null}return i>=2**32-1?null:i};for(;e.getBitsLeft()>=8;){e.skipBits(1);let i=e.readBits(4),s=e.readBits(1),n=e.readBits(1);e.skipBits(1),s&&e.skipBits(8);let a;if(n){let o=r();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);m(e.pos%8===0),yield{type:i,data:t.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},vi=t=>{for(let{type:e,data:r}of Sa(t)){if(e!==1)continue;let i=new H(r),s=i.readBits(3),n=i.readBits(1),a=i.readBits(1),o=0,c=0,l=0;if(a)o=i.readBits(5);else{if(i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.readBits(1)))return null;let S=i.readBits(1);S&&(l=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5));let A=i.readBits(5);for(let E=0;E<=A;E++){i.skipBits(12);let D=i.readBits(5);if(E===0&&(o=D),D>7){let z=i.readBits(1);E===0&&(c=z)}if(S&&i.readBits(1)){let re=l+1;i.skipBits(re),i.skipBits(re),i.skipBits(1)}i.readBits(1)&&i.skipBits(4)}}let d=i.readBits(4),u=i.readBits(4),h=d+1;i.skipBits(h);let f=u+1;i.skipBits(f);let p=0;if(a?p=0:p=i.readBits(1),p&&(i.skipBits(4),i.skipBits(3)),i.skipBits(1),i.skipBits(1),i.skipBits(1),!a){i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);let P=i.readBits(1);P&&(i.skipBits(1),i.skipBits(1));let S=i.readBits(1),A=0;S?A=2:A=i.readBits(1),A>0&&(i.readBits(1)||i.skipBits(1)),P&&i.skipBits(3)}i.skipBits(1),i.skipBits(1),i.skipBits(1);let g=i.readBits(1),w=8;s===2&&g?w=i.readBits(1)?12:10:s<=2&&(w=g?10:8);let b=0;s!==1&&(b=i.readBits(1));let k=1,y=1,x=0;return b||(s===0?(k=1,y=1):s===1?(k=0,y=0):w===12&&(k=i.readBits(1),k&&(y=i.readBits(1))),k&&y&&(x=i.readBits(2))),{profile:s,level:o,tier:c,bitDepth:w,monochrome:b,chromaSubsamplingX:k,chromaSubsamplingY:y,chromaSamplePosition:x}}return null},Ai=t=>{let e=V(t),r=e.getUint8(9),i=e.getUint16(10,!0),s=e.getUint32(12,!0),n=e.getInt16(16,!0),a=e.getUint8(18),o=null;return a&&(o=t.subarray(19,21+r)),{outputChannelCount:r,preSkip:i,inputSampleRate:s,outputGain:n,channelMappingFamily:a,channelMappingTable:o}},_c=[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],Ca=t=>{let e=t[0]>>3;return{durationInSamples:_c[e]}},_a=t=>{if(t.length<7)throw new Error("Setup header is too short.");if(t[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...t.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let r=t.length,i=new Uint8Array(r);for(let u=0;u<r;u++)i[u]=t[r-1-u];let s=new H(i),n=0;for(;s.getBitsLeft()>97;)if(s.readBits(1)===1){n=s.pos;break}if(n===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;s.getBitsLeft()>=97;){let u=s.pos,h=s.readBits(8),f=s.readBits(16),p=s.readBits(16);if(h>63||f!==0||p!==0){s.pos=u;break}if(s.skipBits(1),a++,a>64)break;s.clone().readBits(6)+1===a&&(o=!0,c=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let l=c;s.pos=0,s.skipBits(n);let d=Array(l).fill(0);for(let u=l-1;u>=0;u--)s.skipBits(40),d[u]=s.readBits(1);return{modeBlockflags:d}},Fi=(t,e,r)=>{switch(t){case"avc":{let i=Ds(r,e),s=i.some(n=>Tt(n)===yt.IDR);if(!s&&(!Tr()||Zn()>=144))for(let n of i){if(Tt(n)!==yt.SEI)continue;let o=_i(n),c=1;do{let l=0;for(;;){let h=o[c++];if(h===void 0||(l+=h,h<255))break}let d=0;for(;;){let h=o[c++];if(h===void 0||(d+=h,h<255))break}if(l===6){let h=new H(o);h.pos=8*c;let f=I(h),p=h.readBits(1);if(f===0&&p===1){s=!0;break}}c+=d}while(c<o.length-1)}return s?"key":"delta"}case"hevc":return zs(r,e).some(n=>{let a=Ne(n);return ce.BLA_W_LP<=a&&a<=ce.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return(r[0]&1)===0?"key":"delta";case"vp9":{let i=new H(r);if(i.readBits(2)!==2)return null;let s=i.readBits(1);return(i.readBits(1)<<1)+s===3&&i.skipBits(1),i.readBits(1)?null:i.readBits(1)===0?"key":"delta"}case"av1":{let i=!1;for(let{type:s,data:n}of Sa(r))if(s===1){let a=new H(n);a.skipBits(4),i=!!a.readBits(1)}else if(s===3||s===6||s===7){if(i)return"key";let a=new H(n);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}default:ne(t),m(!1)}},Ze;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(Ze||(Ze={}));var Pr=(t,e)=>{let r=V(t),i=0,s=r.getUint32(i,!0);i+=4;let n=ie.decode(t.subarray(i,i+s));i+=s,s>0&&(e.raw??={},e.raw.vendor??=n);let a=r.getUint32(i,!0);i+=4;for(let o=0;o<a;o++){let c=r.getUint32(i,!0);i+=4;let l=ie.decode(t.subarray(i,i+c));i+=c;let d=l.indexOf("=");if(d===-1)continue;let u=l.slice(0,d).toUpperCase(),h=l.slice(d+1);switch(e.raw??={},e.raw[u]??=h,u){case"TITLE":e.title??=h;break;case"DESCRIPTION":e.description??=h;break;case"ARTIST":e.artist??=h;break;case"ALBUM":e.album??=h;break;case"ALBUMARTIST":e.albumArtist??=h;break;case"COMMENT":e.comment??=h;break;case"LYRICS":e.lyrics??=h;break;case"TRACKNUMBER":{let f=h.split("/"),p=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.tracksTotal??=g)}break;case"TRACKTOTAL":{let f=Number.parseInt(h,10);Number.isInteger(f)&&f>0&&(e.tracksTotal??=f)}break;case"DISCNUMBER":{let f=h.split("/"),p=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),g&&Number.isInteger(g)&&g>0&&(e.discsTotal??=g)}break;case"DISCTOTAL":{let f=Number.parseInt(h,10);Number.isInteger(f)&&f>0&&(e.discsTotal??=f)}break;case"DATE":{let f=new Date(h);Number.isNaN(f.getTime())||(e.date??=f)}break;case"GENRE":e.genre??=h;break;case"METADATA_BLOCK_PICTURE":{let f=Jn(h),p=V(f),g=p.getUint32(0,!1),w=p.getUint32(4,!1),b=String.fromCharCode(...f.subarray(8,8+w)),k=p.getUint32(8+w,!1),y=ie.decode(f.subarray(12+w,12+w+k)),x=p.getUint32(w+k+28),P=f.subarray(w+k+32,w+k+32+x);e.images??=[],e.images.push({data:P,mimeType:b,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:y||void 0})}break}}};var ae=class{constructor(e){this.input=e}};var Ri=[],Bi=[],Pa=[],Ea=[];var Y=new Uint8Array(0),L=class t{constructor(e,r,i,s,n=-1,a,o){if(this.data=e,this.type=r,this.timestamp=i,this.duration=s,this.sequenceNumber=n,e===Y&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!=="key"&&r!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(s)||s<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Y}get microsecondTimestamp(){return Math.trunc(ve*this.timestamp)}get microsecondDuration(){return Math.trunc(ve*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,r){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let i=new Uint8Array(e.byteLength);return e.copyTo(i),new t(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,r)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new t(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var Ia=t=>{let i=t,s=4096,n=0,a=12,o=0;for(i<0&&(i=-i,n=128),i+=33,i>8191&&(i=8191);(i&s)!==s&&a>=5;)s>>=1,a--;return o=i>>a-4&15,~(n|a-5<<4|o)&255},va=t=>{let r=0,i=0,s=~t;s&128&&(s&=-129,r=-1),i=((s&240)>>4)+5;let n=(1<<i|(s&15)<<i-4|1<<i-5)-33;return r===0?n:-n},Aa=t=>{let r=2048,i=0,s=11,n=0,a=t;for(a<0&&(a=-a,i=128),a>4095&&(a=4095);(a&r)!==r&&s>=5;)r>>=1,s--;return n=a>>(s===4?1:s-4)&15,(i|s-4<<4|n)^85},Fa=t=>{let e=0,r=0,i=t^85;i&128&&(i&=-129,e=-1),r=((i&240)>>4)+4;let s=0;return r!==4?s=1<<r|(i&15)<<r-4|1<<r-5:s=i<<1|1,e===0?s:-s};yi();var Ra=-1/0,Ba=-1/0,Ir=null;typeof FinalizationRegistry<"u"&&(Ir=new FinalizationRegistry(t=>{let e=Date.now();t.type==="video"?(e-Ra>=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."),Ra=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-Ba>=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."),Ba=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));var Us=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Pc=new Set(Us),ge=class t{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(ve*this.timestamp)}get microsecondDuration(){return Math.trunc(ve*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,r){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.format===void 0||!Pc.has(r.format))throw new TypeError("init.format must be one of: "+Us.join(", "));if(!Number.isInteger(r.codedWidth)||r.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(r.codedHeight)||r.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=K(e).slice(),this._layout=r.layout??Ec(r.format,r.codedWidth,r.codedHeight),this.format=r.format,this.codedWidth=r.codedWidth,this.codedHeight=r.codedHeight,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Lt(r.colorSpace)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(r?.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(r?.timestamp!==void 0&&!Number.isFinite(r?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(r?.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=r?.rotation??0,this.timestamp=r?.timestamp??e.timestamp/1e6,this.duration=r?.duration??(e.duration??0)/1e6,this.colorSpace=new Lt(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new t(new VideoFrame(e,{timestamp:Math.trunc(r.timestamp*ve),duration:Math.trunc((r.duration??0)*ve)||void 0}),r);let i=0,s=0;if("naturalWidth"in e?(i=e.naturalWidth,s=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,s=e.videoHeight):"width"in e&&(i=Number(e.width),s=Number(e.height)),!i||!s)throw new TypeError("Could not determine dimensions.");let n=new OffscreenCanvas(i,s),a=n.getContext("2d",{alpha:Mt(),willReadFrequently:!0});m(a),a.drawImage(e,0,0),this._data=n,this._layout=null,this.format="RGBX",this.codedWidth=i,this.codedHeight=s,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Lt({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");Ir?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),xt(this._data)?new t(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(m(this._layout),new t(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 t(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||(Ir?.unregister(this),xt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Da(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)===null)throw new Error("Cannot get allocation size when format is null. Please manually provide an RGB pixel format in the options instead.");if(m(this._data!==null),!xt(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let r=this.toVideoFrame(),i=r.allocationSize(e);return r.close(),i}return xt(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,r={}){if(!Ot(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Da(r),this._closed)throw new Error("VideoSample is closed.");if((r.format??this.format)===null)throw new Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(m(this._data!==null),!xt(this._data)&&(r.colorSpace||r.format&&r.format!==this.format||r.layout||r.rect)){let i=this.toVideoFrame(),s=await i.copyTo(e,r);return i.close(),s}if(xt(this._data))return this._data.copyTo(e,r);if(this._data instanceof Uint8Array)return m(this._layout),K(e).set(this._data),this._layout;{let s=this._data.getContext("2d");m(s);let n=s.getImageData(0,0,this.codedWidth,this.codedHeight);return K(e).set(n.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),xt(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,r,i,s,n,a,o,c,l){let d=0,u=0,h=this.displayWidth,f=this.displayHeight,p=0,g=0,w=this.displayWidth,b=this.displayHeight;if(a!==void 0?(d=r,u=i,h=s,f=n,p=a,g=o,c!==void 0?(w=c,b=l):(w=h,b=f)):(p=r,g=i,s!==void 0&&(w=s,b=n)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(g))throw new TypeError("dy must be a number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(b)||b<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:d,sy:u,sWidth:h,sHeight:f}=this._rotateSourceRegion(d,u,h,f,this.rotation));let k=this.toCanvasImageSource();e.save();let y=p+w/2,x=g+b/2;e.translate(y,x),e.rotate(this.rotation*Math.PI/180);let P=this.rotation%180===0?1:w/b;e.scale(1/P,P),e.drawImage(k,d,u,h,f,-w/2,-b/2,w,b),e.restore()}drawWithFit(e,r){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");r.crop!==void 0&&za(r.crop,"options.");let i=e.canvas.width,s=e.canvas.height,n=r.rotation??this.rotation,[a,o]=n%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];r.crop&&Oa(r.crop,a,o);let c,l,d,u,{sx:h,sy:f,sWidth:p,sHeight:g}=this._rotateSourceRegion(r.crop?.left??0,r.crop?.top??0,r.crop?.width??a,r.crop?.height??o,n);if(r.fit==="fill")c=0,l=0,d=i,u=s;else{let[b,k]=r.crop?[r.crop.width,r.crop.height]:[a,o],y=r.fit==="contain"?Math.min(i/b,s/k):Math.max(i/b,s/k);d=b*y,u=k*y,c=(i-d)/2,l=(s-u)/2}e.save();let w=n%180===0?1:d/u;e.translate(i/2,s/2),e.rotate(n*Math.PI/180),e.scale(1/w,w),e.translate(-i/2,-s/2),e.drawImage(this.toCanvasImageSource(),h,f,p,g,c,l,d,u),e.restore()}_rotateSourceRegion(e,r,i,s,n){return n===90?[e,r,i,s]=[r,this.codedHeight-e-i,s,i]:n===180?[e,r]=[this.codedWidth-e-i,this.codedHeight-r-s]:n===270&&([e,r,i,s]=[this.codedWidth-r-s,e,s,i]),{sx:e,sy:r,sWidth:i,sHeight:s}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(m(this._data!==null),this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}},Lt=class{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}}},xt=t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,Oa=(t,e,r)=>{t.left=Math.min(t.left,e),t.top=Math.min(t.top,r),t.width=Math.min(t.width,e-t.left),t.height=Math.min(t.height,r-t.top),m(t.width>=0),m(t.height>=0)},za=(t,e)=>{if(!t||typeof t!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Da=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.colorSpace!==void 0&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(t.format!==void 0&&typeof t.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of t.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.rect!==void 0){if(!t.rect||typeof t.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(t.rect.x!==void 0&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(t.rect.y!==void 0&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(t.rect.width!==void 0&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(t.rect.height!==void 0&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Ec=(t,e,r)=>{let i=Ic(t),s=[],n=0;for(let a of i){let o=Math.ceil(e/a.widthDivisor),c=Math.ceil(r/a.heightDivisor),l=o*a.sampleBytes,d=l*c;s.push({offset:n,stride:l}),n+=d}return s},Ic=t=>{let e=(r,i,s,n,a)=>{let o=[{sampleBytes:r,widthDivisor:1,heightDivisor:1},{sampleBytes:i,widthDivisor:s,heightDivisor:n},{sampleBytes:i,widthDivisor:s,heightDivisor:n}];return a&&o.push({sampleBytes:r,widthDivisor:1,heightDivisor:1}),o};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(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:ne(t),m(!1)}},Ms=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),we=class t{get microsecondTimestamp(){return Math.trunc(ve*this.timestamp)}get microsecondDuration(){return Math.trunc(ve*this.duration)}constructor(e){if(this._closed=!1,Er(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Ms.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");let r=e.data.byteLength/(St(e.format)*e.numberOfChannels);if(!Number.isInteger(r))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=r,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=r/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let s=this.numberOfFrames*this.numberOfChannels*St(this.format);if(i.byteLength<s)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}Ir?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Ms.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let r=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let s=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(s>this.numberOfFrames-i)throw new RangeError("frameCount out of range");let n=St(r),a=Vt(r);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?s:s*this.numberOfChannels)*n}copyTo(e,r){if(!Ot(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(r.planeIndex)||r.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(r.format!==void 0&&!Ms.has(r.format))throw new TypeError("Invalid format.");if(r.frameOffset!==void 0&&(!Number.isInteger(r.frameOffset)||r.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(r.frameCount!==void 0&&(!Number.isInteger(r.frameCount)||r.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:i,format:s,frameCount:n,frameOffset:a}=r,o=this.format,c=s??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,d=this.numberOfChannels,u=a??0;if(u>=l)throw new RangeError("frameOffset out of range");let h=n!==void 0?n:l-u;if(h>l-u)throw new RangeError("frameCount out of range");let f=St(c),p=Vt(c);if(p&&i>=d)throw new RangeError("planeIndex out of range");if(!p&&i!==0)throw new RangeError("planeIndex out of range");let w=(p?h:h*d)*f;if(e.byteLength<w)throw new RangeError("Destination buffer is too small");let b=V(e),k=Ua(c);if(Er(this._data))Ye()&&d>2&&c!==o?vc(this._data,b,o,c,d,i,u,h):this._data.copyTo(e,{planeIndex:i,frameOffset:u,frameCount:h,format:c});else{let y=this._data,x=V(y),P=Ma(o),S=St(o),A=Vt(o);for(let E=0;E<h;E++)if(p){let D=E*f,N;A?N=(i*l+(E+u))*S:N=((E+u)*d+i)*S;let z=P(x,N);k(b,D,z)}else for(let D=0;D<d;D++){let z=(E*d+D)*f,re;A?re=(D*l+(E+u))*S:re=((E+u)*d+D)*S;let nt=P(x,re);k(b,z,nt)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(Er(this._data)){let e=new t(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new t({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(Ir?.unregister(this),Er(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(Er(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(Vt(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),r=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(r,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:r})}else{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})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),r=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(r,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(r,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let i=48e3*5,s=e.numberOfChannels,n=e.sampleRate,a=e.length,o=Math.floor(i/s),c=0,l=a;for(;l>0;){let d=Math.min(o,l),u=new Float32Array(s*d);for(let h=0;h<s;h++)e.copyFromChannel(u.subarray(h*d,(h+1)*d),h,c);yield new t({format:"f32-planar",sampleRate:n,numberOfFrames:d,numberOfChannels:s,timestamp:r+c/n,data:u}),c+=d,l-=d}}static fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let i=48e3*5,s=e.numberOfChannels,n=e.sampleRate,a=e.length,o=Math.floor(i/s),c=0,l=a,d=[];for(;l>0;){let u=Math.min(o,l),h=new Float32Array(s*u);for(let p=0;p<s;p++)e.copyFromChannel(h.subarray(p*u,(p+1)*u),p,c);let f=new t({format:"f32-planar",sampleRate:n,numberOfFrames:u,numberOfChannels:s,timestamp:r+c/n,data:h});d.push(f),c+=u,l-=u}return d}},St=t=>{switch(t){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},Vt=t=>{switch(t){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Ma=t=>{switch(t){case"u8":case"u8-planar":return(e,r)=>(e.getUint8(r)-128)/128;case"s16":case"s16-planar":return(e,r)=>e.getInt16(r,!0)/32768;case"s32":case"s32-planar":return(e,r)=>e.getInt32(r,!0)/2147483648;case"f32":case"f32-planar":return(e,r)=>e.getFloat32(r,!0)}},Ua=t=>{switch(t){case"u8":case"u8-planar":return(e,r,i)=>e.setUint8(r,X((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,r,i)=>e.setInt16(r,X(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,r,i)=>e.setInt32(r,X(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,r,i)=>e.setFloat32(r,i,!0)}},Er=t=>typeof AudioData<"u"&&t instanceof AudioData,vc=(t,e,r,i,s,n,a,o)=>{let c=Ma(r),l=Ua(i),d=St(r),u=St(i),h=Vt(r);if(Vt(i))if(h){let p=new ArrayBuffer(o*d),g=V(p);t.copyTo(p,{planeIndex:n,frameOffset:a,frameCount:o,format:r});for(let w=0;w<o;w++){let b=w*d,k=w*u,y=c(g,b);l(e,k,y)}}else{let p=new ArrayBuffer(o*s*d),g=V(p);t.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:r});for(let w=0;w<o;w++){let b=(w*s+n)*d,k=w*u,y=c(g,b);l(e,k,y)}}else if(h){let p=o*d,g=new ArrayBuffer(p),w=V(g);for(let b=0;b<s;b++){t.copyTo(g,{planeIndex:b,frameOffset:a,frameCount:o,format:r});for(let k=0;k<o;k++){let y=k*d,x=(k*s+b)*u,P=c(w,y);l(e,x,P)}}}else{let p=new ArrayBuffer(o*s*d),g=V(p);t.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:r});for(let w=0;w<o;w++)for(let b=0;b<s;b++){let k=w*s+b,y=k*d,x=k*u,P=c(g,y);l(e,x,P)}}};var Wt=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.metadataOnly!==void 0&&typeof t.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(t.verifyKeyPackets!==void 0&&typeof t.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(t.verifyKeyPackets&&t.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},Ct=t=>{if(!Sr(t))throw new TypeError("timestamp must be a number.")},Ns=(t,e,r)=>r.verifyKeyPackets?e.then(async i=>{if(!i||i.type==="delta")return i;let s=await t.determinePacketType(i);return s&&(i.type=s),i}):e,_t=class{constructor(e){if(!(e instanceof Ht))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(Wt(e),this._track.input._disposed)throw new Z;return Ns(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,r={}){if(Ct(e),Wt(r),this._track.input._disposed)throw new Z;return Ns(this._track,this._track._backing.getPacket(e,r),r)}getNextPacket(e,r={}){if(!(e instanceof L))throw new TypeError("packet must be an EncodedPacket.");if(Wt(r),this._track.input._disposed)throw new Z;return Ns(this._track,this._track._backing.getNextPacket(e,r),r)}async getKeyPacket(e,r={}){if(Ct(e),Wt(r),this._track.input._disposed)throw new Z;if(!r.verifyKeyPackets)return this._track._backing.getKeyPacket(e,r);let i=await this._track._backing.getKeyPacket(e,r);return i&&(m(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getKeyPacket(i.timestamp-1/this._track.timeResolution,r):i)}async getNextKeyPacket(e,r={}){if(!(e instanceof L))throw new TypeError("packet must be an EncodedPacket.");if(Wt(r),this._track.input._disposed)throw new Z;if(!r.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,r);let i=await this._track._backing.getNextKeyPacket(e,r);return i&&(m(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getNextKeyPacket(i,r):i)}packets(e,r,i={}){if(e!==void 0&&!(e instanceof L))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(r!==void 0&&!(r instanceof L))throw new TypeError("endPacket must be an EncodedPacket.");if(Wt(i),this._track.input._disposed)throw new Z;let s=[],{promise:n,resolve:a}=se(),{promise:o,resolve:c}=se(),l=!1,d=!1,u=null,h=[],f=()=>Math.max(2,h.length);(async()=>{let g=e??await this.getFirstPacket(i);for(;g&&!d&&!this._track.input._disposed&&!(r&&g.sequenceNumber>=r?.sequenceNumber);){if(s.length>f()){({promise:o,resolve:c}=se()),await o;continue}s.push(g),a(),{promise:n,resolve:a}=se(),g=await this.getNextPacket(g,i)}l=!0,a()})().catch(g=>{u||(u=g,a())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new Z;if(d)return{value:void 0,done:!0};if(u)throw u;if(s.length>0){let g=s.shift(),w=performance.now();for(h.push(w);h.length>0&&w-h[0]>=1e3;)h.shift();return c(),{value:g,done:!1}}else{if(l)return{value:void 0,done:!0};await n}}},async return(){return d=!0,c(),a(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},vr=class{constructor(e,r){this.onSample=e,this.onError=r}},Ar=class{mediaSamplesInRange(e=0,r=1/0){Ct(e),Ct(r);let i=[],s=!1,n=null,{promise:a,resolve:o}=se(),{promise:c,resolve:l}=se(),d=!1,u=!1,h=!1,f=null;(async()=>{let w=await this._createDecoder(S=>{if(l(),S.timestamp>=r&&(u=!0),u){S.close();return}n&&(S.timestamp>e?(i.push(n),s=!0):n.close()),S.timestamp>=e&&(i.push(S),s=!0),n=s?null:S,i.length>0&&(o(),{promise:a,resolve:o}=se())},S=>{f||(f=S,o())}),b=this._createPacketSink(),k=await b.getKeyPacket(e,{verifyKeyPackets:!0})??await b.getFirstPacket(),y=k,x;if(r<1/0){let S=await b.getPacket(r),A=S?S.type==="key"&&S.timestamp===r?S:await b.getNextKeyPacket(S,{verifyKeyPackets:!0}):null;A&&(x=A)}let P=b.packets(k??void 0,x);for(await P.next();y&&!u&&!this._track.input._disposed;){let S=Na(i.length);if(i.length+w.getDecodeQueueSize()>S){({promise:c,resolve:l}=se()),await c;continue}w.decode(y);let A=await P.next();if(A.done)break;y=A.value}await P.return(),!h&&!this._track.input._disposed&&await w.flush(),w.close(),!s&&n&&i.push(n),d=!0,o()})().catch(w=>{f||(f=w,o())});let p=this._track,g=()=>{n?.close();for(let w of i)w.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new Z;if(h)return{value:void 0,done:!0};if(f)throw g(),f;if(i.length>0){let w=i.shift();return l(),{value:w,done:!1}}else if(!d)await a;else return{value:void 0,done:!0}}},async return(){return h=!0,u=!0,l(),o(),g(),{value:void 0,done:!0}},async throw(w){throw w},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){$n(e);let r=jn(e),i=[],s=[],{promise:n,resolve:a}=se(),{promise:o,resolve:c}=se(),l=!1,d=!1,u=null,h=g=>{s.push(g),a(),{promise:n,resolve:a}=se()};(async()=>{let g=await this._createDecoder(S=>{if(c(),d){S.close();return}let A=0;for(;i.length>0&&S.timestamp-i[0]>-1e-10;)A++,i.shift();if(A>0)for(let E=0;E<A;E++)h(E<A-1?S.clone():S);else S.close()},S=>{u||(u=S,a())}),w=this._createPacketSink(),b=null,k=null,y=-1,x=async()=>{m(k);let S=k;for(g.decode(S);S.sequenceNumber<y;){let A=Na(s.length);for(;s.length+g.getDecodeQueueSize()>A&&!d;)({promise:o,resolve:c}=se()),await o;if(d)break;let E=await w.getNextPacket(S);m(E),g.decode(E),S=E}y=-1},P=async()=>{await g.flush();for(let S=0;S<i.length;S++)h(null);i.length=0};for await(let S of r){if(Ct(S),d||this._track.input._disposed)break;let A=await w.getPacket(S),E=A&&await w.getKeyPacket(S,{verifyKeyPackets:!0});if(!E){y!==-1&&(await x(),await P()),h(null),b=null;continue}b&&(E.sequenceNumber!==k.sequenceNumber||A.timestamp<b.timestamp)&&(await x(),await P()),i.push(A.timestamp),y=Math.max(A.sequenceNumber,y),b=A,k=E}!d&&!this._track.input._disposed&&(y!==-1&&await x(),await P()),g.close(),l=!0,a()})().catch(g=>{u||(u=g,a())});let f=this._track,p=()=>{for(let g of s)g?.close()};return{async next(){for(;;){if(f.input._disposed)throw p(),new Z;if(d)return{value:void 0,done:!0};if(u)throw p(),u;if(s.length>0){let g=s.shift();return m(g!==void 0),c(),{value:g,done:!1}}else if(!l)await n;else return{value:void 0,done:!0}}},async return(){return d=!0,c(),a(),p(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},Na=t=>t===0?40:8,Vs=class extends vr{constructor(e,r,i,s,n,a){super(e,r),this.codec=i,this.decoderConfig=s,this.rotation=n,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Xe,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=Ri.find(c=>c.supports(i,s));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=s,this.customDecoder.onSample=c=>{if(!(c instanceof ge))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=d=>{if(this.alphaQueue.length>0){let u=this.alphaQueue.shift();m(u!==void 0),this.mergeAlpha(d,u)}else this.colorQueue.push(d)};if(i==="avc"&&this.decoderConfig.description&&Tr()){let d=Ta(K(this.decoderConfig.description));if(d&&d.sequenceParameterSets.length>0){let u=Os(d.sequenceParameterSets[0]);u&&u.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:d=>{try{c(d)}catch(u){this.onError(u)}},error:d=>{d.stack=l,this.onError(d)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&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(m(this.decoder),Ye()||Ps(this.inputTimestamps,e.timestamp,r=>r),Tr()&&this.currentPacketIndex===0&&this.codec==="avc"){let i=Ds(e.data,this.decoderConfig).filter(n=>{let a=Tt(n);return!(a>=20&&a<=31)}),s=ka(i,this.decoderConfig);e=new L(s,e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new Ls}catch(i){console.error("Due to an error, only color data will be decoded.",i),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let i=n=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let a=this.colorQueue.shift();m(a!==void 0),this.mergeAlpha(a,n)}else this.alphaQueue.push(n);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let a=this.colorQueue.shift();m(a!==void 0),this.mergeAlpha(a,null)}else this.alphaQueue.push(null)},s=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:n=>{try{i(n)}catch(a){this.onError(a)}},error:n=>{n.stack=s,this.onError(n)}}),this.alphaDecoder.configure(this.decoderConfig)}let r=Fi(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=r==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){return zs(e,this.decoderConfig).some(i=>{let s=Ne(i);return s===ce.RASL_N||s===ce.RASL_R})}sampleHandler(e){if(Ye()){if(this.sampleQueue.length>0&&e.timestamp>=q(this.sampleQueue).timestamp){for(let r of this.sampleQueue)this.finalizeAndEmitSample(r);this.sampleQueue.length=0}Ps(this.sampleQueue,e,r=>r.timestamp)}else{let r=this.inputTimestamps.shift();m(r!==void 0),e.setTimestamp(r),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,r){if(!r){let n=new ge(e);this.sampleHandler(n);return}m(this.merger),this.merger.update(e,r),e.close(),r.close();let i=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),s=new ge(i);this.sampleHandler(s)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(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),Ye()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(m(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},Ls=class{constructor(){typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
12
8
|
in vec2 a_position;
|
|
13
9
|
in vec2 a_texCoord;
|
|
14
10
|
out vec2 v_texCoord;
|
|
@@ -30,7 +26,7 @@ import"./chunk-WCZ2O3UN.js";import"./chunk-3L3MB5NY.js";import"./chunk-BFBY7VYB.
|
|
|
30
26
|
float alpha = texture(u_alphaTexture, v_texCoord).r;
|
|
31
27
|
fragColor = vec4(color, alpha);
|
|
32
28
|
}
|
|
33
|
-
`),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,r),this.gl.linkProgram(i),i}createShader(e,r){let i=this.gl.createShader(e);return this.gl.shaderSource(i,r),this.gl.compileShader(i),i}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let r=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.STATIC_DRAW);let n=this.gl.getAttribLocation(this.program,"a_position"),s=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,r){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},bi=class extends gi{constructor(e){if(!(e instanceof rt))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let i=this._track.codec,n=this._track.rotation,s=await this._track.getDecoderConfig(),o=this._track.timeResolution;return h(i&&s),new ro(e,r,i,s,n,o)}_createPacketSink(){return new Ht(this._track)}async getSample(e){qt(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}};var no=class extends pi{constructor(e,r,i,n){super(e,r),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new ht,this.customDecoderQueueSize=0,this.currentTimestamp=null;let s=a=>{(this.currentTimestamp===null||Math.abs(a.timestamp-this.currentTimestamp)>=a.duration)&&(this.currentTimestamp=a.timestamp);let c=this.currentTimestamp;if(this.currentTimestamp+=a.duration,a.numberOfFrames===0){a.close();return}let u=n.sampleRate;a.setTimestamp(Math.round(c*u)/u),e(a)},o=Fn.find(a=>a.supports(i,n));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=n,this.customDecoder.onSample=a=>{if(!(a instanceof Ae))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(a)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let a=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:c=>{try{s(new Ae(c))}catch(u){this.onError(u)}},error:c=>{c.stack=a,this.onError(c)}}),this.decoder.configure(n)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(h(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(h(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(h(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(h(this.decoder),this.decoder.close())}},so=class extends pi{constructor(e,r,i){super(e,r),this.decoderConfig=i,this.currentTimestamp=null,h(Y.includes(i.codec)),this.codec=i.codec;let{dataType:n,sampleSize:s,littleEndian:o}=Te(this.codec);switch(this.inputSampleSize=s,s){case 1:n==="unsigned"?this.readInputValue=(a,c)=>a.getUint8(c)-2**7:n==="signed"?this.readInputValue=(a,c)=>a.getInt8(c):n==="ulaw"?this.readInputValue=(a,c)=>Wc(a.getUint8(c)):n==="alaw"?this.readInputValue=(a,c)=>jc(a.getUint8(c)):h(!1);break;case 2:n==="unsigned"?this.readInputValue=(a,c)=>a.getUint16(c,o)-2**15:n==="signed"?this.readInputValue=(a,c)=>a.getInt16(c,o):h(!1);break;case 3:n==="unsigned"?this.readInputValue=(a,c)=>Bt(a,c,o)-2**23:n==="signed"?this.readInputValue=(a,c)=>cc(a,c,o):h(!1);break;case 4:n==="unsigned"?this.readInputValue=(a,c)=>a.getUint32(c,o)-2**31:n==="signed"?this.readInputValue=(a,c)=>a.getInt32(c,o):n==="float"?this.readInputValue=(a,c)=>a.getFloat32(c,o):h(!1);break;case 8:n==="float"?this.readInputValue=(a,c)=>a.getFloat64(c,o):h(!1);break;default:ue(s),h(!1)}switch(s){case 1:n==="ulaw"||n==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(a,c,u)=>a.setInt16(c,u,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(a,c,u)=>a.setUint8(c,u+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(a,c,u)=>a.setInt16(c,u,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(a,c,u)=>a.setInt32(c,u<<8,!0);break;case 4:this.outputSampleSize=4,n==="float"?(this.outputFormat="f32",this.writeOutputValue=(a,c,u)=>a.setFloat32(c,u,!0)):(this.outputFormat="s32",this.writeOutputValue=(a,c,u)=>a.setInt32(c,u,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(a,c,u)=>a.setFloat32(c,u,!0);break;default:ue(s),h(!1)}}getDecodeQueueSize(){return 0}decode(e){let r=V(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,n=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(n),o=new DataView(s);for(let l=0;l<i*this.decoderConfig.numberOfChannels;l++){let d=l*this.inputSampleSize,f=l*this.outputSampleSize,m=this.readInputValue(r,d);this.writeOutputValue(o,f,m)}let a=i/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=a)&&(this.currentTimestamp=e.timestamp);let c=this.currentTimestamp;this.currentTimestamp+=a;let u=new Ae({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:c});this.onSample(u)}async flush(){}close(){}},wi=class extends gi{constructor(e){if(!(e instanceof ie))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let i=this._track.codec,n=await this._track.getDecoderConfig();return h(i&&n),Y.includes(n.codec)?new so(e,r,n):new no(e,r,i,n)}_createPacketSink(){return new Ht(this._track)}async getSample(e){qt(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}};var br=class{constructor(e,r){this.input=e,this._backing=r}isVideoTrack(){return this instanceof rt}isAudioTrack(){return this instanceof ie}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let r=new Ht(this),i=1/0,n=-1/0,s=0,o=0;for await(let a of r.packets(void 0,void 0,{metadataOnly:!0})){if(s>=e&&a.timestamp>=n)break;i=Math.min(i,a.timestamp),n=Math.max(n,a.timestamp+a.duration),s++,o+=a.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(n-i)).toPrecision(16)):0,averageBitrate:s?Number((8*o/(n-i)).toPrecision(16)):0}}},rt=class extends br{constructor(e,r){super(e,r),this._backing=r}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180===0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180===0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=this._backing.getCodec();return h(r!==null),In.some(n=>n.supports(r,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof L))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(this.codec===null)return null;let r=await this.getDecoderConfig();return h(r),Dn(this.codec,r,e.data)}},ie=class extends br{constructor(e,r){super(e,r),this._backing=r}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=this._backing.getCodec();return h(r!==null),Fn.some(i=>i.supports(r,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof L))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var Bn=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){let i=[...new Set(t.codecStrings)];r+=`; codecs="${i.join(", ")}"`}return r};var De=8,it=16,nt=t=>{let e=A(t),r=j(t,4),i=8;e===1&&(e=ke(t),i=16);let s=e-i;return s<0?null:{name:r,totalSize:e,headerSize:i,contentSize:s}},bt=t=>st(t)/65536,Rn=t=>st(t)/1073741824,On=t=>{let e=0;for(let r=0;r<4;r++){e<<=7;let i=D(t);if(e|=i&127,(i&128)===0)break}return e},Ie=t=>{let e=ne(t);return t.skip(2),e=Math.min(e,t.remainingLength),ae.decode(I(t,e))},tu=t=>{let e=nt(t);if(!e||e.name!=="data"||t.remainingLength<8)return null;let r=A(t);t.skip(4);let i=I(t,e.contentSize-8);switch(r){case 1:return ae.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new Pe(i,"image/jpeg");case 14:return new Pe(i,"image/png");case 27:return new Pe(i,"image/bmp");default:return i}};var Nn=class extends de{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(i=>i.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(r=>r.inputTrack.getCodecParameterString()));return Bn({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.info?.type==="audio"),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,De,it);if(r instanceof Promise&&(r=await r),!r)break;let i=e,n=nt(r);if(!n)break;if(n.name==="ftyp"){let s=j(r,4);this.isQuickTime=s==="qt "}else if(n.name==="moov"){let s=this.reader.requestSlice(r.filePos,n.contentSize);if(s instanceof Promise&&(s=await s),!s)break;this.moovSlice=s,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((o,a)=>Number(a.disposition.default)-Number(o.disposition.default));for(let o of this.tracks){let a=o.editListPreviousSegmentDurations/this.movieTimescale;o.editListOffset-=Math.round(a*o.timescale)}break}e=i+n.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let r=this.reader.requestSlice(this.reader.fileSize-4,4);r instanceof Promise&&(r=await r),h(r);let i=A(r),n=this.reader.fileSize-i;if(n>=0&&n<=this.reader.fileSize-it){let s=this.reader.requestSliceRange(n,De,it);if(s instanceof Promise&&(s=await s),s){let o=nt(s);if(o&&o.name==="mfra"){let a=this.reader.requestSlice(s.filePos,o.contentSize);a instanceof Promise&&(a=await a),a&&this.readContiguousBoxes(a)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=r,h(this.moovSlice);let i=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(i),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&Y.includes(e.info.codec)&&r.sampleCompositionTimeOffsets.length===0){h(e.info?.type==="audio");let s=Te(e.info.codec),o=[],a=[];for(let c=0;c<r.sampleToChunk.length;c++){let u=r.sampleToChunk[c],l=r.sampleToChunk[c+1],d=(l?l.startChunkIndex:r.chunkOffsets.length)-u.startChunkIndex;for(let f=0;f<d;f++){let m=u.startSampleIndex+f*u.samplesPerChunk,p=m+u.samplesPerChunk,g=U(r.sampleTimingEntries,m,v=>v.startIndex),b=r.sampleTimingEntries[g],w=U(r.sampleTimingEntries,p,v=>v.startIndex),x=r.sampleTimingEntries[w],y=b.startDecodeTimestamp+(m-b.startIndex)*b.delta,E=x.startDecodeTimestamp+(p-x.startIndex)*x.delta-y,S=G(o);S&&S.delta===E?S.count++:o.push({startIndex:u.startChunkIndex+f,startDecodeTimestamp:y,count:1,delta:E});let P=u.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;a.push(P)}u.startSampleIndex=u.startChunkIndex,u.samplesPerChunk=1}r.sampleTimingEntries=o,r.sampleSizes=a}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(let s of r.sampleTimingEntries)for(let o=0;o<s.count;o++)r.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+o*s.delta,sampleIndex:s.startIndex+o});for(let s of r.sampleCompositionTimeOffsets)for(let o=0;o<s.count;o++){let a=s.startIndex+o,c=r.presentationTimestamps[a];c&&(c.presentationTimestamp+=s.offset)}r.presentationTimestamps.sort((s,o)=>s.presentationTimestamp-o.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let s=0;s<r.presentationTimestamps.length;s++)r.presentationTimestampIndexMap[r.presentationTimestamps[s].sampleIndex]=s}return r}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let r=this.reader.requestSliceRange(e,De,it);r instanceof Promise&&(r=await r),h(r);let i=nt(r);h(i?.name==="moof");let n=this.reader.requestSlice(e,i.totalSize);n instanceof Promise&&(n=await n),h(n),this.traverseBox(n);let s=this.lastReadFragment;h(s&&s.moofOffset===e);for(let[,o]of s.trackData){let a=o.track,{fragmentPositionCache:c}=a;if(!o.startTimestampIsFinal){let l=a.fragmentLookupTable.find(d=>d.moofOffset===s.moofOffset);if(l)oo(o,l.timestamp);else{let d=U(c,s.moofOffset-1,f=>f.moofOffset);if(d!==-1){let f=c[d];oo(o,f.endTimestamp)}}o.startTimestampIsFinal=!0}let u=U(c,o.startTimestamp,l=>l.startTimestamp);(u===-1||c[u].moofOffset!==s.moofOffset)&&c.splice(u+1,0,{moofOffset:s.moofOffset,startTimestamp:o.startTimestamp,endTimestamp:o.endTimestamp})}return s}readContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-De&&this.traverseBox(e););}*iterateContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-De;){let i=e.filePos,n=nt(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=i+n.totalSize}}traverseBox(e){let r=e.filePos,i=nt(e);if(!i)return!1;let n=e.filePos,s=r+i.totalSize;switch(i.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"mvhd":{let o=D(e);e.skip(3),o===1?(e.skip(16),this.movieTimescale=A(e),this.movieDurationInTimescale=ke(e)):(e.skip(8),this.movieTimescale=A(e),this.movieDurationInTimescale=A(e))}break;case"trak":{let o={id:-1,demuxer:this,inputTrack:null,disposition:{...xe},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Z,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=o,this.readContiguousBoxes(e.slice(n,i.contentSize)),o.id!==-1&&o.timescale!==-1&&o.info!==null){if(o.info.type==="video"&&o.info.width!==-1){let a=o;o.inputTrack=new rt(this.input,new ao(a)),this.tracks.push(o)}else if(o.info.type==="audio"&&o.info.numberOfChannels!==-1){let a=o;o.inputTrack=new ie(this.input,new co(a)),this.tracks.push(o)}}this.currentTrack=null}break;case"tkhd":{let o=this.currentTrack;if(!o)break;let a=D(e),u=!!(wt(e)&1);if(o.disposition.default=u,a===0)e.skip(8),o.id=A(e),e.skip(4),o.durationInMovieTimescale=A(e);else if(a===1)e.skip(16),o.id=A(e),e.skip(4),o.durationInMovieTimescale=ke(e);else throw new Error(`Incorrect track header version ${a}.`);e.skip(16);let l=[bt(e),bt(e),Rn(e),bt(e),bt(e),Rn(e),bt(e),bt(e),Rn(e)],d=mn(lc(Sd(l),90));h(d===0||d===90||d===180||d===270),o.rotation=d}break;case"elst":{let o=this.currentTrack;if(!o)break;let a=D(e);e.skip(3);let c=!1,u=0,l=A(e);for(let d=0;d<l;d++){let f=a===1?ke(e):A(e),m=a===1?iu(e):st(e),p=bt(e);if(f!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(m===-1){u+=f;continue}if(p!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}o.editListPreviousSegmentDurations=u,o.editListOffset=m,c=!0}}}break;case"mdhd":{let o=this.currentTrack;if(!o)break;let a=D(e);e.skip(3),a===0?(e.skip(8),o.timescale=A(e),o.durationInMediaTimescale=A(e)):a===1&&(e.skip(16),o.timescale=A(e),o.durationInMediaTimescale=ke(e));let c=ne(e);if(c>0){o.languageCode="";for(let u=0;u<3;u++)o.languageCode=String.fromCharCode(96+(c&31))+o.languageCode,c>>=5;lr(o.languageCode)||(o.languageCode=Z)}}break;case"hdlr":{let o=this.currentTrack;if(!o)break;e.skip(8);let a=j(e,4);a==="vide"?o.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:a==="soun"&&(o.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let o=this.currentTrack;if(!o)break;o.sampleTableByteOffset=r,this.readContiguousBoxes(e.slice(n,i.contentSize))}break;case"stsd":{let o=this.currentTrack;if(!o||o.info===null||o.sampleTable)break;let a=D(e);e.skip(3);let c=A(e);for(let u=0;u<c;u++){let l=e.filePos,d=nt(e);if(!d)break;o.internalCodecId=d.name;let f=d.name.toLowerCase();if(o.info.type==="video")f==="avc1"||f==="avc3"?(o.info.codec="avc",o.info.avcType=f==="avc1"?1:3):f==="hvc1"||f==="hev1"?o.info.codec="hevc":f==="vp08"?o.info.codec="vp8":f==="vp09"?o.info.codec="vp9":f==="av01"?o.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${d.name}').`),e.skip(24),o.info.width=ne(e),o.info.height=ne(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,l+d.totalSize-e.filePos));else{f==="mp4a"||(f==="opus"?o.info.codec="opus":f==="flac"?o.info.codec="flac":f==="twos"||f==="sowt"||f==="raw "||f==="in24"||f==="in32"||f==="fl32"||f==="fl64"||f==="lpcm"||f==="ipcm"||f==="fpcm"||(f==="ulaw"?o.info.codec="ulaw":f==="alaw"?o.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${d.name}').`))),e.skip(8);let m=ne(e);e.skip(6);let p=ne(e),g=ne(e);e.skip(4);let b=A(e)/65536;if(a===0&&m>0){if(m===1)e.skip(4),g=8*A(e),e.skip(8);else if(m===2){e.skip(4),b=Un(e),p=A(e),e.skip(4),g=A(e);let w=A(e);if(e.skip(8),f==="lpcm"){let x=g+7>>3,y=!!(w&1),T=!!(w&2),E=w&4?-1:0;g>0&&g<=64&&(y?g===32&&(o.info.codec=T?"pcm-f32be":"pcm-f32"):E&1<<x-1?x===1?o.info.codec="pcm-s8":x===2?o.info.codec=T?"pcm-s16be":"pcm-s16":x===3?o.info.codec=T?"pcm-s24be":"pcm-s24":x===4&&(o.info.codec=T?"pcm-s32be":"pcm-s32"):x===1&&(o.info.codec="pcm-u8")),o.info.codec===null&&console.warn("Unsupported PCM format.")}}}o.info.codec==="opus"&&(b=Mt),o.info.numberOfChannels=p,o.info.sampleRate=b,f==="twos"?g===8?o.info.codec="pcm-s8":g===16?o.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${g} for codec 'twos'.`),o.info.codec=null):f==="sowt"?g===8?o.info.codec="pcm-s8":g===16?o.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${g} for codec 'sowt'.`),o.info.codec=null):f==="raw "?o.info.codec="pcm-u8":f==="in24"?o.info.codec="pcm-s24be":f==="in32"?o.info.codec="pcm-s32be":f==="fl32"?o.info.codec="pcm-f32be":f==="fl64"?o.info.codec="pcm-f64be":f==="ipcm"?o.info.codec="pcm-s16be":f==="fpcm"&&(o.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,l+d.totalSize-e.filePos))}}}break;case"avcC":{let o=this.currentTrack;if(!o)break;h(o.info),o.info.codecDescription=I(e,i.contentSize)}break;case"hvcC":{let o=this.currentTrack;if(!o)break;h(o.info),o.info.codecDescription=I(e,i.contentSize)}break;case"vpcC":{let o=this.currentTrack;if(!o)break;h(o.info?.type==="video"),e.skip(4);let a=D(e),c=D(e),u=D(e),l=u>>4,d=u>>1&7,f=u&1,m=D(e),p=D(e),g=D(e);o.info.vp9CodecInfo={profile:a,level:c,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:m,transferCharacteristics:p,matrixCoefficients:g}}break;case"av1C":{let o=this.currentTrack;if(!o)break;h(o.info?.type==="video"),e.skip(1);let a=D(e),c=a>>5,u=a&31,l=D(e),d=l>>7,f=l>>6&1,m=l>>5&1,p=l>>4&1,g=l>>3&1,b=l>>2&1,w=l&3,x=c===2&&f?m?12:10:f?10:8;o.info.av1CodecInfo={profile:c,level:u,tier:d,bitDepth:x,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:b,chromaSamplePosition:w}}break;case"colr":{let o=this.currentTrack;if(!o||(h(o.info?.type==="video"),j(e,4)!=="nclx"))break;let c=ne(e),u=ne(e),l=ne(e),d=!!(D(e)&128);o.info.colorSpace={primaries:hn[c],transfer:pn[u],matrix:gn[l],fullRange:d}}break;case"wave":this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"esds":{let o=this.currentTrack;if(!o)break;h(o.info?.type==="audio"),e.skip(4);let a=D(e);h(a===3),On(e),e.skip(2);let c=D(e),u=(c&128)!==0,l=(c&64)!==0,d=(c&32)!==0;if(u&&e.skip(2),l){let b=D(e);e.skip(b)}d&&e.skip(2);let f=D(e);h(f===4);let m=On(e),p=e.filePos,g=D(e);if(g===64||g===103?(o.info.codec="aac",o.info.aacCodecInfo={isMpeg2:g===103}):g===105||g===107?o.info.codec="mp3":g===221?o.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${g}) - discarding track.`),e.skip(12),m>e.filePos-p){let b=D(e);h(b===5);let w=On(e);if(o.info.codecDescription=I(e,w),o.info.codec==="aac"){let x=di(o.info.codecDescription);x.numberOfChannels!==null&&(o.info.numberOfChannels=x.numberOfChannels),x.sampleRate!==null&&(o.info.sampleRate=x.sampleRate)}}}break;case"enda":{let o=this.currentTrack;if(!o)break;h(o.info?.type==="audio"),ne(e)&255&&(o.info.codec==="pcm-s16be"?o.info.codec="pcm-s16":o.info.codec==="pcm-s24be"?o.info.codec="pcm-s24":o.info.codec==="pcm-s32be"?o.info.codec="pcm-s32":o.info.codec==="pcm-f32be"?o.info.codec="pcm-f32":o.info.codec==="pcm-f64be"&&(o.info.codec="pcm-f64"))}break;case"pcmC":{let o=this.currentTrack;if(!o)break;h(o.info?.type==="audio"),e.skip(4);let c=!!(D(e)&1),u=D(e);o.info.codec==="pcm-s16be"?c?u===16?o.info.codec="pcm-s16":u===24?o.info.codec="pcm-s24":u===32?o.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${u}.`),o.info.codec=null):u===16?o.info.codec="pcm-s16be":u===24?o.info.codec="pcm-s24be":u===32?o.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${u}.`),o.info.codec=null):o.info.codec==="pcm-f32be"&&(c?u===32?o.info.codec="pcm-f32":u===64?o.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${u}.`),o.info.codec=null):u===32?o.info.codec="pcm-f32be":u===64?o.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${u}.`),o.info.codec=null));break}case"dOps":{let o=this.currentTrack;if(!o)break;h(o.info?.type==="audio"),e.skip(1);let a=D(e),c=ne(e),u=A(e),l=xi(e),d=D(e),f;d!==0?f=I(e,2+a):f=new Uint8Array(0);let m=new Uint8Array(19+f.byteLength),p=new DataView(m.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,a),p.setUint16(10,c,!0),p.setUint32(12,u,!0),p.setInt16(16,l,!0),p.setUint8(18,d),m.set(f,19),o.info.codecDescription=m,o.info.numberOfChannels=a}break;case"dfLa":{let o=this.currentTrack;if(!o)break;h(o.info?.type==="audio"),e.skip(4);let a=127,c=128,u=e.filePos;for(;e.filePos<s;){let p=D(e),g=wt(e);if((p&a)===gt.STREAMINFO){e.skip(10);let w=A(e),x=w>>>12,y=(w>>9&7)+1;o.info.sampleRate=x,o.info.numberOfChannels=y,e.skip(20)}else e.skip(g);if(p&c)break}let l=e.filePos;e.filePos=u;let d=I(e,l-u),f=new Uint8Array(4+d.byteLength);new DataView(f.buffer).setUint32(0,1716281667,!1),f.set(d,4),o.info.codecDescription=f}break;case"stts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=A(e),c=0,u=0;for(let l=0;l<a;l++){let d=A(e),f=A(e);o.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:u,count:d,delta:f}),c+=d,u+=d*f}}break;case"ctts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=A(e),c=0;for(let u=0;u<a;u++){let l=A(e),d=st(e);o.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:l,offset:d}),c+=l}}break;case"stsz":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=A(e),c=A(e);if(a===0)for(let u=0;u<c;u++){let l=A(e);o.sampleTable.sampleSizes.push(l)}else o.sampleTable.sampleSizes.push(a)}break;case"stz2":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),e.skip(3);let a=D(e),c=A(e),u=I(e,Math.ceil(c*a/8)),l=new W(u);for(let d=0;d<c;d++){let f=l.readBits(a);o.sampleTable.sampleSizes.push(f)}}break;case"stss":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),o.sampleTable.keySampleIndices=[];let a=A(e);for(let c=0;c<a;c++){let u=A(e)-1;o.sampleTable.keySampleIndices.push(u)}o.sampleTable.keySampleIndices[0]!==0&&o.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=A(e);for(let u=0;u<a;u++){let l=A(e)-1,d=A(e),f=A(e);o.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:l,samplesPerChunk:d,sampleDescriptionIndex:f})}let c=0;for(let u=0;u<o.sampleTable.sampleToChunk.length;u++)if(o.sampleTable.sampleToChunk[u].startSampleIndex=c,u<o.sampleTable.sampleToChunk.length-1){let d=o.sampleTable.sampleToChunk[u+1].startChunkIndex-o.sampleTable.sampleToChunk[u].startChunkIndex;c+=d*o.sampleTable.sampleToChunk[u].samplesPerChunk}}break;case"stco":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=A(e);for(let c=0;c<a;c++){let u=A(e);o.sampleTable.chunkOffsets.push(u)}}break;case"co64":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let a=A(e);for(let c=0;c<a;c++){let u=ke(e);o.sampleTable.chunkOffsets.push(u)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"mehd":{let o=D(e);e.skip(3);let a=o===1?ke(e):A(e);this.movieDurationInTimescale=a}break;case"trex":{e.skip(4);let o=A(e),a=A(e),c=A(e),u=A(e),l=A(e);this.fragmentTrackDefaults.push({trackId:o,defaultSampleDescriptionIndex:a,defaultSampleDuration:c,defaultSampleSize:u,defaultSampleFlags:l})}break;case"tfra":{let o=D(e);e.skip(3);let a=A(e),c=this.tracks.find(x=>x.id===a);if(!c)break;let u=A(e),l=(u&48)>>4,d=(u&12)>>2,f=u&3,m=[D,ne,wt,A],p=m[l],g=m[d],b=m[f],w=A(e);for(let x=0;x<w;x++){let y=o===1?ke(e):A(e),T=o===1?ke(e):A(e);p(e),g(e),b(e),c.fragmentLookupTable.push({timestamp:y,moofOffset:T})}c.fragmentLookupTable.sort((x,y)=>x.timestamp-y.timestamp);for(let x=0;x<c.fragmentLookupTable.length-1;x++){let y=c.fragmentLookupTable[x],T=c.fragmentLookupTable[x+1];y.timestamp===T.timestamp&&(c.fragmentLookupTable.splice(x+1,1),x--)}}break;case"moof":this.currentFragment={moofOffset:r,moofSize:i.totalSize,implicitBaseDataOffset:r,trackData:new Map},this.readContiguousBoxes(e.slice(n,i.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(h(this.currentFragment),this.readContiguousBoxes(e.slice(n,i.contentSize)),this.currentTrack){let o=this.currentFragment.trackData.get(this.currentTrack.id);if(o){let{currentFragmentState:a}=this.currentTrack;h(a),a.startTimestamp!==null&&(oo(o,a.startTimestamp),o.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{h(this.currentFragment),e.skip(1);let o=wt(e),a=!!(o&1),c=!!(o&2),u=!!(o&8),l=!!(o&16),d=!!(o&32),f=!!(o&65536),m=!!(o&131072),p=A(e),g=this.tracks.find(w=>w.id===p);if(!g)break;let b=this.fragmentTrackDefaults.find(w=>w.trackId===p);this.currentTrack=g,g.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:b?.defaultSampleDescriptionIndex??null,defaultSampleDuration:b?.defaultSampleDuration??null,defaultSampleSize:b?.defaultSampleSize??null,defaultSampleFlags:b?.defaultSampleFlags??null,startTimestamp:null},a?g.currentFragmentState.baseDataOffset=ke(e):m&&(g.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(g.currentFragmentState.sampleDescriptionIndex=A(e)),u&&(g.currentFragmentState.defaultSampleDuration=A(e)),l&&(g.currentFragmentState.defaultSampleSize=A(e)),d&&(g.currentFragmentState.defaultSampleFlags=A(e)),f&&(g.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let o=this.currentTrack;if(!o)break;h(o.currentFragmentState);let a=D(e);e.skip(3);let c=a===0?A(e):ke(e);o.currentFragmentState.startTimestamp=c}break;case"trun":{let o=this.currentTrack;if(!o)break;if(h(this.currentFragment),h(o.currentFragmentState),this.currentFragment.trackData.has(o.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let a=D(e),c=wt(e),u=!!(c&1),l=!!(c&4),d=!!(c&256),f=!!(c&512),m=!!(c&1024),p=!!(c&2048),g=A(e),b=o.currentFragmentState.baseDataOffset;u&&(b+=st(e));let w=null;l&&(w=A(e));let x=b;if(g===0){this.currentFragment.implicitBaseDataOffset=x;break}let y=0,T={track:o,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(o.id,T);for(let P=0;P<g;P++){let v;d?v=A(e):(h(o.currentFragmentState.defaultSampleDuration!==null),v=o.currentFragmentState.defaultSampleDuration);let F;f?F=A(e):(h(o.currentFragmentState.defaultSampleSize!==null),F=o.currentFragmentState.defaultSampleSize);let M;m?M=A(e):(h(o.currentFragmentState.defaultSampleFlags!==null),M=o.currentFragmentState.defaultSampleFlags),P===0&&w!==null&&(M=w);let B=0;p&&(a===0?B=A(e):B=st(e));let Q=!(M&65536);T.samples.push({presentationTimestamp:y+B,duration:v,byteOffset:x,byteSize:F,isKeyFrame:Q}),x+=F,y+=v}T.presentationTimestamps=T.samples.map((P,v)=>({presentationTimestamp:P.presentationTimestamp,sampleIndex:v})).sort((P,v)=>P.presentationTimestamp-v.presentationTimestamp);for(let P=0;P<T.presentationTimestamps.length;P++){let v=T.presentationTimestamps[P],F=T.samples[v.sampleIndex];if(T.firstKeyFrameTimestamp===null&&F.isKeyFrame&&(T.firstKeyFrameTimestamp=F.presentationTimestamp),P<T.presentationTimestamps.length-1){let M=T.presentationTimestamps[P+1];F.duration=M.presentationTimestamp-v.presentationTimestamp}}let E=T.samples[T.presentationTimestamps[0].sampleIndex],S=T.samples[G(T.presentationTimestamps).sampleIndex];T.startTimestamp=E.presentationTimestamp,T.endTimestamp=S.presentationTimestamp+S.duration,this.currentFragment.implicitBaseDataOffset=x}break;case"udta":{let o=this.iterateContiguousBoxes(e.slice(n,i.contentSize));for(let{boxInfo:a,slice:c}of o){if(a.name!=="meta"&&!this.currentTrack){let u=c.filePos;this.metadataTags.raw??={},a.name[0]==="\xA9"?this.metadataTags.raw[a.name]??=Ie(c):this.metadataTags.raw[a.name]??=I(c,a.contentSize),c.filePos=u}switch(a.name){case"meta":c.skip(-a.headerSize),this.traverseBox(c);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=ae.decode(I(c,a.contentSize)):this.metadataTags.title??=Ie(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=Ie(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=Ie(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=Ie(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Ie(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=Ie(c));break;case"\xA9day":if(!this.currentTrack){let u=new Date(Ie(c));Number.isNaN(u.getTime())||(this.metadataTags.date??=u)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=Ie(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=Ie(c));break}}}break;case"meta":{if(this.currentTrack)break;let a=A(e)!==0;this.currentMetadataKeys=new Map,a?this.readContiguousBoxes(e.slice(n,i.contentSize)):this.readContiguousBoxes(e.slice(n+4,i.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let o=A(e);for(let a=0;a<o;a++){let c=A(e);e.skip(4);let u=ae.decode(I(e,c-8));this.currentMetadataKeys.set(a+1,u)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let o=this.iterateContiguousBoxes(e.slice(n,i.contentSize));for(let{boxInfo:a,slice:c}of o){let u=a.name,l=(u.charCodeAt(0)<<24)+(u.charCodeAt(1)<<16)+(u.charCodeAt(2)<<8)+u.charCodeAt(3);this.currentMetadataKeys.has(l)&&(u=this.currentMetadataKeys.get(l));let d=tu(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[u]??=d,u){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof d=="string"&&(this.metadataTags.album??=d);break;case"aART":case"album_artist":typeof d=="string"&&(this.metadataTags.albumArtist??=d);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"\xA9lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){let f=new Date(d);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof Pe?(this.metadataTags.images??=[],this.metadataTags.images.push({data:d.data,kind:"coverFront",mimeType:d.mimeType})):d instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:d,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof d=="string"){let f=d.split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){let f=V(d),m=f.getUint16(2,!1),p=f.getUint16(4,!1);m>0&&(this.metadataTags.trackNumber??=m),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){let f=V(d),m=f.getUint16(2,!1),p=f.getUint16(4,!1);m>0&&(this.metadataTags.discNumber??=m),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=s,!0}},Mn=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let r=await this.fetchPacketForSampleIndex(0,e);return r||!this.internalTrack.demuxer.isFragmented?r:this.performFragmentedLookup(null,i=>i.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Rt(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,r){let i=this.mapTimestampIntoTimescale(e),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=uo(n,i),o=await this.fetchPacketForSampleIndex(s,r);return!ru(n)||!this.internalTrack.demuxer.isFragmented?o:this.performFragmentedLookup(null,a=>{let c=a.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let u=U(c.presentationTimestamps,i,f=>f.presentationTimestamp),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&i<c.endTimestamp;return{sampleIndex:l,correctSampleFound:d}},i,i,r)}async getNextPacket(e,r){let i=this.packetToSampleIndex.get(e);if(i!==void 0)return this.fetchPacketForSampleIndex(i+1,r);let n=this.packetToFragmentLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){let o=s.trackData.get(this.internalTrack.id);if(n.sampleIndex+1<o.samples.length)return{sampleIndex:n.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let i=this.mapTimestampIntoTimescale(e),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=yd(n,i),o=await this.fetchPacketForSampleIndex(s,r);return!ru(n)||!this.internalTrack.demuxer.isFragmented?o:this.performFragmentedLookup(null,a=>{let c=a.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let u=bn(c.presentationTimestamps,f=>c.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=i),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&i<c.endTimestamp;return{sampleIndex:l,correctSampleFound:d}},i,i,r)}async getNextKeyPacket(e,r){let i=this.packetToSampleIndex.get(e);if(i!==void 0){let s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=kd(s,i);return this.fetchPacketForSampleIndex(o,r)}let n=this.packetToFragmentLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){let a=s.trackData.get(this.internalTrack.id).samples.findIndex((c,u)=>c.isKeyFrame&&u>n.sampleIndex);if(a!==-1)return{sampleIndex:a,correctSampleFound:!0}}else{let o=s.trackData.get(this.internalTrack.id);if(o&&o.firstKeyFrameTimestamp!==null){let a=o.samples.findIndex(c=>c.isKeyFrame);return h(a!==-1),{sampleIndex:a,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async fetchPacketForSampleIndex(e,r){if(e===-1)return null;let i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Td(i,e);if(!n)return null;let s;if(r.metadataOnly)s=te;else{let u=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);u instanceof Promise&&(u=await u),h(u),s=I(u,n.sampleSize)}let o=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=n.duration/this.internalTrack.timescale,c=new L(s,n.isKeyFrame?"key":"delta",o,a,e,n.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,r,i){if(r===-1)return null;let s=e.trackData.get(this.internalTrack.id).samples[r];h(s);let o;if(i.metadataOnly)o=te;else{let l=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);l instanceof Promise&&(l=await l),h(l),o=I(l,s.byteSize)}let a=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,u=new L(o,s.isKeyFrame?"key":"delta",a,c,e.moofOffset+r,s.byteSize);return this.packetToFragmentLocation.set(u,{fragment:e,sampleIndex:r}),u}async performFragmentedLookup(e,r,i,n,s){let o=this.internalTrack.demuxer,a=null,c=null,u=-1;if(e){let{sampleIndex:b,correctSampleFound:w}=r(e);if(w)return this.fetchPacketInFragment(e,b,s);b!==-1&&(c=e,u=b)}let l=U(this.internalTrack.fragmentLookupTable,i,b=>b.timestamp),d=l!==-1?this.internalTrack.fragmentLookupTable[l]:null,f=U(this.internalTrack.fragmentPositionCache,i,b=>b.startTimestamp),m=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,p=Math.max(d?.moofOffset??0,m?.moofOffset??0)||null,g;for(e?p===null||e.moofOffset>=p?(g=e.moofOffset+e.moofSize,a=e):g=p:g=p??0;;){if(a){let y=a.trackData.get(this.internalTrack.id);if(y&&y.startTimestamp>n)break}let b=o.reader.requestSliceRange(g,De,it);if(b instanceof Promise&&(b=await b),!b)break;let w=g,x=nt(b);if(!x)break;if(x.name==="moof"){a=await o.readFragment(w);let{sampleIndex:y,correctSampleFound:T}=r(a);if(T)return this.fetchPacketInFragment(a,y,s);y!==-1&&(c=a,u=y)}g=w+x.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){let b=this.internalTrack.fragmentLookupTable[l-1];h(!b||b.timestamp<d.timestamp);let w=b?.timestamp??-1/0;return this.performFragmentedLookup(null,r,w,n,s)}return c?this.fetchPacketInFragment(c,u,s):null}},ao=class extends Mn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&vn(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&_n(e.data)}return{codec:yn(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},co=class extends Mn{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Tn(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},uo=(t,e)=>{if(t.presentationTimestamps){let r=U(t.presentationTimestamps,e,i=>i.presentationTimestamp);return r===-1?-1:t.presentationTimestamps[r].sampleIndex}else{let r=U(t.sampleTimingEntries,e,n=>n.startDecodeTimestamp);if(r===-1)return-1;let i=t.sampleTimingEntries[r];return i.startIndex+Math.min(Math.floor((e-i.startDecodeTimestamp)/i.delta),i.count-1)}},yd=(t,e)=>{if(!t.keySampleIndices)return uo(t,e);if(t.presentationTimestamps){let r=U(t.presentationTimestamps,e,i=>i.presentationTimestamp);if(r===-1)return-1;for(let i=r;i>=0;i--){let n=t.presentationTimestamps[i].sampleIndex;if(Ft(t.keySampleIndices,n,o=>o)!==-1)return n}return-1}else{let r=uo(t,e),i=U(t.keySampleIndices,r,n=>n);return t.keySampleIndices[i]??-1}},Td=(t,e)=>{let r=U(t.sampleTimingEntries,e,w=>w.startIndex),i=t.sampleTimingEntries[r];if(!i||i.startIndex+i.count<=e)return null;let s=i.startDecodeTimestamp+(e-i.startIndex)*i.delta,o=U(t.sampleCompositionTimeOffsets,e,w=>w.startIndex),a=t.sampleCompositionTimeOffsets[o];a&&e-a.startIndex<a.count&&(s+=a.offset);let c=t.sampleSizes[Math.min(e,t.sampleSizes.length-1)],u=U(t.sampleToChunk,e,w=>w.startSampleIndex),l=t.sampleToChunk[u];h(l);let d=l.startChunkIndex+Math.floor((e-l.startSampleIndex)/l.samplesPerChunk),f=t.chunkOffsets[d],m=l.startSampleIndex+(d-l.startChunkIndex)*l.samplesPerChunk,p=0,g=f;if(t.sampleSizes.length===1)g+=c*(e-m),p+=c*l.samplesPerChunk;else for(let w=m;w<m+l.samplesPerChunk;w++){let x=t.sampleSizes[w];w<e&&(g+=x),p+=x}let b=i.delta;if(t.presentationTimestamps){let w=t.presentationTimestampIndexMap[e];h(w!==void 0),w<t.presentationTimestamps.length-1&&(b=t.presentationTimestamps[w+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:b,sampleOffset:g,sampleSize:c,chunkOffset:f,chunkSize:p,isKeyFrame:t.keySampleIndices?Ft(t.keySampleIndices,e,w=>w)!==-1:!0}},kd=(t,e)=>{if(!t.keySampleIndices)return e+1;let r=U(t.keySampleIndices,e,i=>i);return t.keySampleIndices[r+1]??-1},oo=(t,e)=>{t.startTimestamp+=e,t.endTimestamp+=e;for(let r of t.samples)r.presentationTimestamp+=e;for(let r of t.presentationTimestamps)r.presentationTimestamp+=e},Sd=t=>{let[e,,,r]=t,i=Math.hypot(e,r),n=e/i,s=r/i,o=-Math.atan2(s,n)*(180/Math.PI);return Number.isFinite(o)?o:0},ru=t=>t.sampleSizes.length===0;var k;(function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"})(k||(k={}));var Cd=[k.EBML,k.Segment],wr=[k.SeekHead,k.Info,k.Cluster,k.Tracks,k.Cues,k.Attachments,k.Chapters,k.Tags],yi=[...Cd,...wr];var lo=8,Se=2,Fe=2*lo,fo=t=>{let e=D(t);if(t.skip(-1),e===0)return null;let r=1,i=128;for(;(e&i)===0;)r++,i>>=1;return r},xr=t=>{let e=D(t);if(e===0)return null;let r=1,i=128;for(;(e&i)===0;)r++,i>>=1;let n=e&i-1;for(let s=1;s<r;s++)n*=256,n+=D(t);return n},N=(t,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let r=0;for(let i=0;i<e;i++)r*=256,r+=D(t);return r},nu=(t,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let r=0n;for(let i=0;i<e;i++)r<<=8n,r+=BigInt(D(t));return r};var zn=t=>{let e=fo(t);return e===null?null:N(t,e)},mo=t=>{let e=D(t);return e===255?e=null:(t.skip(-1),e=xr(t),e===72057594037927940&&(e=null)),e},Be=t=>{let e=zn(t);if(e===null)return null;let r=mo(t);return{id:e,size:r}},xt=(t,e)=>{let r=I(t,e),i=0;for(;i<e&&r[i]!==0;)i+=1;return String.fromCharCode(...r.subarray(0,i))},yr=(t,e)=>{let r=I(t,e),i=0;for(;i<e&&r[i]!==0;)i+=1;return ae.decode(r.subarray(0,i))},Vn=(t,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?su(t):Un(t)},Ln=async(t,e,r,i)=>{let n=new Set(r),s=e;for(;i===null||s<i;){let o=t.requestSliceRange(s,Se,Fe);if(o instanceof Promise&&(o=await o),!o)break;let a=Be(o);if(!a)break;if(n.has(a.id))return{pos:s,found:!0};ot(a.size),s=o.filePos+a.size}return{pos:i!==null&&i>s?i:s,found:!1}},ho=async(t,e,r,i)=>{let s=new Set(r),o=e;for(;o<i;){let a=t.requestSliceRange(o,0,Math.min(65536,i-o));if(a instanceof Promise&&(a=await a),!a||a.length<lo)break;for(let c=0;c<a.length-lo;c++){a.filePos=o;let u=zn(a);if(u!==null&&s.has(u))return o;o++}}return null},Re={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function ot(t){if(t===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var ou=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");if(t.codecStrings.length>0){let i=[...new Set(t.codecStrings.filter(Boolean))];r+=`; codecs="${i.join(", ")}"`}return r};var at;(function(t){t[t.None=0]="None",t[t.Xiph=1]="Xiph",t[t.FixedSize=2]="FixedSize",t[t.Ebml=3]="Ebml"})(at||(at={}));var qn;(function(t){t[t.Block=1]="Block",t[t.Private=2]="Private",t[t.Next=4]="Next"})(qn||(qn={}));var Ti;(function(t){t[t.Zlib=0]="Zlib",t[t.Bzlib=1]="Bzlib",t[t.lzo1x=2]="lzo1x",t[t.HeaderStripping=3]="HeaderStripping"})(Ti||(Ti={}));var po=[{id:k.SeekHead,flag:"seekHeadSeen"},{id:k.Info,flag:"infoSeen"},{id:k.Tracks,flag:"tracksSeen"},{id:k.Cues,flag:"cuesSeen"}],au=10*2**20,Hn=class extends de{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(i=>i.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(r=>r.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),r=await Promise.all(e.map(i=>i.getCodecParameterString()));return ou({isWebM:this.isWebM,hasVideo:this.segments.some(i=>i.tracks.some(n=>n.info?.type==="video")),hasAudio:this.segments.some(i=>i.tracks.some(n=>n.info?.type==="audio")),codecStrings:r.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let r of this.segments)r.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(r),r.metadataTagsCollected=!0);let e={};for(let r of this.segments)e={...e,...r.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,Se,Fe);if(r instanceof Promise&&(r=await r),!r)break;let i=Be(r);if(!i)break;let n=i.id,s=i.size,o=r.filePos;if(n===k.EBML){ot(s);let a=this.reader.requestSlice(o,s);if(a instanceof Promise&&(a=await a),!a)break;this.readContiguousElements(a)}else if(n===k.Segment){if(await this.readSegment(o,s),s===null||this.reader.fileSize===null)break}else if(n===k.Cluster){if(this.reader.fileSize===null)break;s===null&&(s=(await Ln(this.reader,o,yi,this.reader.fileSize)).pos-o);let a=G(this.segments);a&&(a.elementEndPos=o+s)}ot(s),e=o+s}})()}async readSegment(e,r){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:r===null?null:e+r,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;this.currentSegment.elementEndPos===null||i<this.currentSegment.elementEndPos;){let a=this.reader.requestSliceRange(i,Se,Fe);if(a instanceof Promise&&(a=await a),!a)break;let c=i,u=Be(a);if(!u||!wr.includes(u.id)&&u.id!==k.Void){let p=await ho(this.reader,c,wr,Math.min(this.currentSegment.elementEndPos??1/0,c+au));if(p){i=p;continue}else break}let{id:l,size:d}=u,f=a.filePos,m=po.findIndex(p=>p.id===l);if(m!==-1){let p=po[m].flag;this.currentSegment[p]=!0,ot(d);let g=this.reader.requestSlice(f,d);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(l===k.Tags||l===k.Attachments){l===k.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ot(d);let p=this.reader.requestSlice(f,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(l===k.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===null)break;i=f+d}if(this.currentSegment.seekEntries.sort((a,c)=>a.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let a of this.currentSegment.seekEntries){let c=po.find(p=>p.id===a.id);if(!c||this.currentSegment[c.flag])continue;let u=this.reader.requestSliceRange(e+a.segmentPosition,Se,Fe);if(u instanceof Promise&&(u=await u),!u)continue;let l=Be(u);if(!l)continue;let{id:d,size:f}=l;if(d!==c.id)continue;ot(f),this.currentSegment[c.flag]=!0;let m=this.reader.requestSlice(u.filePos,f);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6),this.currentSegment.tracks.sort((a,c)=>Number(c.disposition.default)-Number(a.disposition.default));let n=new Map(this.currentSegment.tracks.map(a=>[a.id,a]));for(let a of this.currentSegment.cuePoints){let c=n.get(a.trackId);c&&c.cuePoints.push(a)}for(let a of this.currentSegment.tracks){a.cuePoints.sort((c,u)=>c.time-u.time);for(let c=0;c<a.cuePoints.length-1;c++){let u=a.cuePoints[c],l=a.cuePoints[c+1];u.time===l.time&&(a.cuePoints.splice(c+1,1),c--)}}let s=null,o=-1/0;for(let a of this.currentSegment.tracks)a.cuePoints.length>o&&(o=a.cuePoints.length,s=a);for(let a of this.currentSegment.tracks)a.cuePoints.length===0&&(a.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,r){if(r.lastReadCluster?.elementStartPos===e)return r.lastReadCluster;let i=this.reader.requestSliceRange(e,Se,Fe);i instanceof Promise&&(i=await i),h(i);let n=e,s=Be(i);h(s);let o=s.id;h(o===k.Cluster);let a=s.size,c=i.filePos;a===null&&(a=(await Ln(this.reader,c,yi,r.elementEndPos)).pos-c);let u=this.reader.requestSlice(c,a);u instanceof Promise&&(u=await u);let l={segment:r,elementStartPos:n,elementEndPos:c+a,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=l,u){let d=this.readContiguousElements(u,yi);l.elementEndPos=d}for(let[,d]of l.trackData){let f=d.track;h(d.blocks.length>0);let m=!1;for(let w=0;w<d.blocks.length;w++){let x=d.blocks[w];x.timestamp+=l.timestamp,m||=x.lacing!==at.None}d.presentationTimestamps=d.blocks.map((w,x)=>({timestamp:w.timestamp,blockIndex:x})).sort((w,x)=>w.timestamp-x.timestamp);for(let w=0;w<d.presentationTimestamps.length;w++){let x=d.presentationTimestamps[w],y=d.blocks[x.blockIndex];if(d.firstKeyFrameTimestamp===null&&y.isKeyFrame&&(d.firstKeyFrameTimestamp=y.timestamp),w<d.presentationTimestamps.length-1){let T=d.presentationTimestamps[w+1];y.duration=T.timestamp-y.timestamp}else y.duration===0&&f.defaultDuration!=null&&y.lacing===at.None&&(y.duration=f.defaultDuration)}m&&(this.expandLacedBlocks(d.blocks,f),d.presentationTimestamps=d.blocks.map((w,x)=>({timestamp:w.timestamp,blockIndex:x})).sort((w,x)=>w.timestamp-x.timestamp));let p=d.blocks[d.presentationTimestamps[0].blockIndex],g=d.blocks[G(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=g.timestamp+g.duration;let b=U(f.clusterPositionCache,d.startTimestamp,w=>w.startTimestamp);(b===-1||f.clusterPositionCache[b].elementStartPos!==n)&&f.clusterPositionCache.splice(b+1,0,{elementStartPos:l.elementStartPos,startTimestamp:d.startTimestamp})}return r.lastReadCluster=l,l}getTrackDataInCluster(e,r){let i=e.trackData.get(r);if(!i){let n=e.segment.tracks.find(s=>s.id===r);if(!n)return null;i={track:n,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(r,i)}return i}expandLacedBlocks(e,r){for(let i=0;i<e.length;i++){let n=e[i];if(n.lacing===at.None)continue;n.decoded||(n.data=this.decodeBlockData(r,n.data),n.decoded=!0);let s=Tr.tempFromBytes(n.data),o=[],a=D(s)+1;switch(n.lacing){case at.Xiph:{let u=0;for(let l=0;l<a-1;l++){let d=0;for(;s.bufferPos<s.length;){let f=D(s);if(d+=f,f<255){o.push(d),u+=d;break}}}o.push(s.length-(s.bufferPos+u))}break;case at.FixedSize:{let u=s.length-1,l=Math.floor(u/a);for(let d=0;d<a;d++)o.push(l)}break;case at.Ebml:{let u=xr(s);h(u!==null);let l=u;o.push(l);let d=l;for(let f=1;f<a-1;f++){let m=s.bufferPos,p=xr(s);h(p!==null);let g=p,w=(1<<(s.bufferPos-m)*7-1)-1,x=g-w;l+=x,o.push(l),d+=l}o.push(s.length-(s.bufferPos+d))}break;default:h(!1)}h(o.length===a),e.splice(i,1);let c=n.duration||a*(r.defaultDuration??0);for(let u=0;u<a;u++){let l=o[u],d=I(s,l),f=n.timestamp+c*u/a,m=c/a;e.splice(i+u,0,{timestamp:f,duration:m,isKeyFrame:n.isKeyFrame,data:d,lacing:at.None,decoded:!0,mainAdditional:n.mainAdditional})}i+=a,i--}}async loadSegmentMetadata(e){for(let r of e.seekEntries){if(!(r.id===k.Tags&&!e.tagsSeen)){if(!(r.id===k.Attachments&&!e.attachmentsSeen))continue}let i=this.reader.requestSliceRange(e.dataStartPos+r.segmentPosition,Se,Fe);if(i instanceof Promise&&(i=await i),!i)continue;let n=Be(i);if(!n||n.id!==r.id)continue;let{size:s}=n;ot(s),h(!this.currentSegment),this.currentSegment=e;let o=this.reader.requestSlice(i.filePos,s);o instanceof Promise&&(o=await o),o&&this.readContiguousElements(o),this.currentSegment=null,r.id===k.Tags?e.tagsSeen=!0:r.id===k.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,r){let i=e.filePos;for(;e.filePos-i<=e.length-Se;){let n=e.filePos;if(!this.traverseElement(e,r))return n}return e.filePos}traverseElement(e,r){let i=Be(e);if(!i||r&&r.includes(i.id))return!1;let{id:n,size:s}=i,o=e.filePos;switch(ot(s),n){case k.DocType:this.isWebM=xt(e,s)==="webm";break;case k.Seek:{if(!this.currentSegment)break;let a={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(a),this.readContiguousElements(e.slice(o,s)),(a.id===-1||a.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case k.SeekID:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.id=N(e,s)}break;case k.SeekPosition:{let a=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!a)break;a.segmentPosition=N(e,s)}break;case k.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=N(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case k.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Vn(e,s)}break;case k.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...xe},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:Z,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(o,s)),this.currentTrack.decodingInstructions.some(a=>a.data?.type!=="decompress"||a.scope!==qn.Block||a.data.algorithm!==Ti.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let a=this.currentTrack.codecId.indexOf("/"),c=a===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,a);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.codecId===Re.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Re.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Re.vp8?this.currentTrack.info.codec="vp8":c===Re.vp9?this.currentTrack.info.codec="vp9":c===Re.av1&&(this.currentTrack.info.codec="av1");let u=this.currentTrack,l=new rt(this.input,new go(u));this.currentTrack.inputTrack=l,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===Re.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Re.mp3?this.currentTrack.info.codec="mp3":c===Re.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Mt):c===Re.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Re.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let u=this.currentTrack,l=new ie(this.input,new bo(u));this.currentTrack.inputTrack=l,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case k.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=N(e,s)}break;case k.TrackType:{if(!this.currentTrack)break;let a=N(e,s);a===1?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:a===2&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case k.FlagEnabled:{if(!this.currentTrack)break;N(e,s)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case k.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!N(e,s)}break;case k.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!N(e,s)}break;case k.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!N(e,s)}break;case k.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!N(e,s)}break;case k.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!N(e,s)}break;case k.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!N(e,s)}break;case k.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=xt(e,s)}break;case k.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=I(e,s)}break;case k.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*N(e,s)/1e9}break;case k.Name:{if(!this.currentTrack)break;this.currentTrack.name=yr(e,s)}break;case k.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==Z)break;this.currentTrack.languageCode=xt(e,s),lr(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Z)}break;case k.LanguageBCP47:{if(!this.currentTrack)break;let c=xt(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=Z}break;case k.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,s))}break;case k.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=N(e,s)}break;case k.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=N(e,s)}break;case k.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=N(e,s)===1}break;case k.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(o,s))}break;case k.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=N(e,s),c=gn[a]??null;this.currentTrack.info.colorSpace.matrix=c}break;case k.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=N(e,s)===2}break;case k.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=N(e,s),c=pn[a]??null;this.currentTrack.info.colorSpace.transfer=c}break;case k.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let a=N(e,s),c=hn[a]??null;this.currentTrack.info.colorSpace.primaries=c}break;case k.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,s))}break;case k.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let c=-Vn(e,s);try{this.currentTrack.info.rotation=mn(c)}catch{}}break;case k.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(o,s))}break;case k.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Vn(e,s)}break;case k.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=N(e,s)}break;case k.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=N(e,s)}break;case k.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,s)),this.currentCueTime=null}break;case k.CueTime:this.currentCueTime=N(e,s);break;case k.CueTrackPositions:{if(this.currentCueTime===null)break;h(this.currentSegment);let a={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(a),this.readContiguousElements(e.slice(o,s)),(a.trackId===-1||a.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case k.CueTrack:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;a.trackId=N(e,s)}break;case k.CueClusterPosition:{let a=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!a)break;h(this.currentSegment),a.clusterPosition=this.currentSegment.dataStartPos+N(e,s)}break;case k.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=N(e,s)}break;case k.SimpleBlock:{if(!this.currentCluster)break;let a=xr(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let u=xi(e),l=D(e),d=l>>1&3,f=!!(l&128);c.track.info?.type==="audio"&&c.track.info.codec&&(f=!0);let m=I(e,s-(e.filePos-o)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:u,duration:0,isKeyFrame:f,data:m,lacing:d,decoded:!p,mainAdditional:null})}break;case k.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,s)),this.currentBlock=null}break;case k.Block:{if(!this.currentCluster)break;let a=xr(e);if(a===null)break;let c=this.getTrackDataInCluster(this.currentCluster,a);if(!c)break;let u=xi(e),d=D(e)>>1&3,f=I(e,s-(e.filePos-o)),m=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:u,duration:0,isKeyFrame:!0,data:f,lacing:d,decoded:!m,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case k.BlockAdditions:this.readContiguousElements(e.slice(o,s));break;case k.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(o,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case k.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=I(e,s)}break;case k.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=N(e,s)}break;case k.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=N(e,s)}break;case k.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case k.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,s));break;case k.Targets:this.readContiguousElements(e.slice(o,s));break;case k.TargetTypeValue:N(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case k.TagTrackUID:case k.TagEditionUID:case k.TagChapterUID:case k.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case k.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,s))}break;case k.TagName:this.currentSimpleTagName=yr(e,s);break;case k.TagString:{if(!this.currentSimpleTagName)break;let a=yr(e,s);this.processTagValue(this.currentSimpleTagName,a)}break;case k.TagBinary:{if(!this.currentSimpleTagName)break;let a=I(e,s);this.processTagValue(this.currentSimpleTagName,a)}break;case k.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(o,s));let a=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(a.raw??={},a.raw[this.currentAttachedFile.fileUid.toString()]=new li(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let c=this.currentAttachedFile.fileName,u="unknown";if(c){let l=c.toLowerCase();l.startsWith("cover.")?u="coverFront":l.startsWith("back.")&&(u="coverBack")}a.images??=[],a.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:u,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case k.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=nu(e,s)}break;case k.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=yr(e,s)}break;case k.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=xt(e,s)}break;case k.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=I(e,s)}break;case k.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=yr(e,s)}break;case k.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(o,s)),this.currentTrack.decodingInstructions.sort((a,c)=>c.order-a.order)}break;case k.ContentEncoding:this.currentDecodingInstruction={order:0,scope:qn.Block,data:null},this.readContiguousElements(e.slice(o,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case k.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=N(e,s)}break;case k.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=N(e,s)}break;case k.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Ti.Zlib,settings:null},this.readContiguousElements(e.slice(o,s))}break;case k.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=N(e,s)}break;case k.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=I(e,s)}break;case k.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=o+s,!0}decodeBlockData(e,r){h(e.decodingInstructions.length>0);let i=r;for(let n of e.decodingInstructions)switch(h(n.data),n.data.type){case"decompress":switch(n.data.algorithm){case Ti.HeaderStripping:if(n.data.settings&&n.data.settings.length>0){let s=n.data.settings,o=new Uint8Array(s.length+i.length);o.set(s,0),o.set(i,s.length),i=o}break;default:}break;default:}return i}processTagValue(e,r){if(!this.currentSegment?.metadataTags)return;let i=this.currentSegment.metadataTags;if(i.raw??={},i.raw[e]??=r,typeof r=="string")switch(e.toLowerCase()){case"title":i.title??=r;break;case"description":i.description??=r;break;case"artist":i.artist??=r;break;case"album":i.album??=r;break;case"album_artist":i.albumArtist??=r;break;case"genre":i.genre??=r;break;case"comment":i.comment??=r;break;case"lyrics":i.lyrics??=r;break;case"date":{let n=new Date(r);Number.isNaN(n.getTime())||(i.date??=n)}break;case"track_number":case"part_number":{let n=r.split("/"),s=Number.parseInt(n[0],10),o=n[1]&&Number.parseInt(n[1],10);Number.isInteger(s)&&s>0&&(i.trackNumber??=s),o&&Number.isInteger(o)&&o>0&&(i.tracksTotal??=o)}break;case"disc_number":case"disc":{let n=r.split("/"),s=Number.parseInt(n[0],10),o=n[1]&&Number.parseInt(n[1],10);Number.isInteger(s)&&s>0&&(i.discNumber??=s),o&&Number.isInteger(o)&&o>0&&(i.discsTotal??=o)}break}}},Wn=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,r=>r.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Rt(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,r){let i=this.intoTimescale(e);return this.performClusterLookup(null,n=>{let s=n.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let o=U(s.presentationTimestamps,i,u=>u.timestamp),a=o!==-1?s.presentationTimestamps[o].blockIndex:-1,c=o!==-1&&i<s.endTimestamp;return{blockIndex:a,correctBlockFound:c}},i,i,r)}async getNextPacket(e,r){let i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,n=>{if(n===i.cluster){let s=n.trackData.get(this.internalTrack.id);if(i.blockIndex+1<s.blocks.length)return{blockIndex:i.blockIndex+1,correctBlockFound:!0}}else if(n.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let i=this.intoTimescale(e);return this.performClusterLookup(null,n=>{let s=n.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};let o=bn(s.presentationTimestamps,u=>s.blocks[u.blockIndex].isKeyFrame&&u.timestamp<=i),a=o!==-1?s.presentationTimestamps[o].blockIndex:-1,c=o!==-1&&i<s.endTimestamp;return{blockIndex:a,correctBlockFound:c}},i,i,r)}async getNextKeyPacket(e,r){let i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,n=>{if(n===i.cluster){let o=n.trackData.get(this.internalTrack.id).blocks.findIndex((a,c)=>a.isKeyFrame&&c>i.blockIndex);if(o!==-1)return{blockIndex:o,correctBlockFound:!0}}else{let s=n.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let o=s.blocks.findIndex(a=>a.isKeyFrame);return h(o!==-1),{blockIndex:o,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async fetchPacketInCluster(e,r,i){if(r===-1)return null;let s=e.trackData.get(this.internalTrack.id).blocks[r];h(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0);let o=i.metadataOnly?te:s.data,a=s.timestamp/this.internalTrack.segment.timestampFactor,c=s.duration/this.internalTrack.segment.timestampFactor,u={};s.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(u.alpha=i.metadataOnly?te:s.mainAdditional,u.alphaByteLength=s.mainAdditional.byteLength);let l=new L(o,s.isKeyFrame?"key":"delta",a,c,e.dataStartPos+r,s.data.byteLength,u);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:r}),l}async performClusterLookup(e,r,i,n,s){let{demuxer:o,segment:a}=this.internalTrack,c=null,u=null,l=-1;if(e){let{blockIndex:w,correctBlockFound:x}=r(e);if(x)return this.fetchPacketInCluster(e,w,s);w!==-1&&(u=e,l=w)}let d=U(this.internalTrack.cuePoints,i,w=>w.time),f=d!==-1?this.internalTrack.cuePoints[d]:null,m=U(this.internalTrack.clusterPositionCache,i,w=>w.startTimestamp),p=m!==-1?this.internalTrack.clusterPositionCache[m]:null,g=Math.max(f?.clusterPosition??0,p?.elementStartPos??0)||null,b;for(e?g===null||e.elementStartPos>=g?(b=e.elementEndPos,c=e):b=g:b=g??a.clusterSeekStartPos;a.elementEndPos===null||b<=a.elementEndPos-Se;){if(c){let v=c.trackData.get(this.internalTrack.id);if(v&&v.startTimestamp>n)break}let w=o.reader.requestSliceRange(b,Se,Fe);if(w instanceof Promise&&(w=await w),!w)break;let x=b,y=Be(w);if(!y||!wr.includes(y.id)&&y.id!==k.Void){let v=await ho(o.reader,x,wr,Math.min(a.elementEndPos??1/0,x+au));if(v){b=v;continue}else break}let T=y.id,E=y.size,S=w.filePos;if(T===k.Cluster){c=await o.readCluster(x,a),E=c.elementEndPos-S;let{blockIndex:v,correctBlockFound:F}=r(c);if(F)return this.fetchPacketInCluster(c,v,s);v!==-1&&(u=c,l=v)}E===null&&(h(T!==k.Cluster),E=(await Ln(o.reader,S,yi,a.elementEndPos)).pos-S);let P=S+E;if(a.elementEndPos===null){let v=o.reader.requestSliceRange(P,Se,Fe);if(v instanceof Promise&&(v=await v),!v)break;if(zn(v)===k.Segment){a.elementEndPos=P;break}}b=P}if(f&&(!u||u.elementStartPos<f.clusterPosition)){let w=this.internalTrack.cuePoints[d-1];h(!w||w.time<f.time);let x=w?.time??-1/0;return this.performClusterLookup(null,r,x,n,s)}return u?this.fetchPacketInCluster(u,l,s):null}},go=class extends Wn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;return(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:yn({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?En(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?An(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?vn(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?_n(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},bo=class extends Wn{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Tn({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}};var Ed=[44100,48e3,32e3],Ad=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],cu=1483304551,uu=1231971951,vd=(t,e,r,i,n)=>e===0?0:e===1?Math.floor(144*r/(i<<t))+n:e===2?Math.floor(144*r/i)+n:(Math.floor(12*r/i)+n)*4,lu=(t,e)=>t===3?e===3?21:36:e===3?13:21,du=(t,e)=>{let r=t>>>24,i=t>>>16&255,n=t>>>8&255,s=t&255;if(r!==255&&i!==255&&n!==255&&s!==255)return{header:null,bytesAdvanced:4};if(r!==255)return{header:null,bytesAdvanced:1};if((i&224)!==224)return{header:null,bytesAdvanced:1};let o=0,a=0;i&16?o=i&8?0:1:(o=1,a=1);let c=i>>3&3,u=i>>1&3,l=n>>4&15,d=(n>>2&3)%3,f=n>>1&1,m=s>>6&3,p=s>>4&3,g=s>>3&1,b=s>>2&1,w=s&3,x=Ad[o*16*4+u*16+l];if(x===-1)return{header:null,bytesAdvanced:1};let y=x*1e3,T=Ed[d]>>o+a,E=vd(o,u,y,T,f);if(e!==null&&e<E)return{header:null,bytesAdvanced:1};let S;return c===3?S=u===3?384:1152:u===3?S=384:u===2?S=1152:S=576,{header:{totalSize:E,mpegVersionId:c,layer:u,bitrate:y,frequencyIndex:d,sampleRate:T,channel:m,modeExtension:p,copyright:g,original:b,emphasis:w,audioSamplesInFrame:S},bytesAdvanced:1}};var Gn=t=>{let e=2130706432,r=0;for(;e!==0;)r>>=1,r|=t&e,e>>=8;return r};var Sr;(function(t){t[t.Unsynchronisation=128]="Unsynchronisation",t[t.ExtendedHeader=64]="ExtendedHeader",t[t.ExperimentalIndicator=32]="ExperimentalIndicator",t[t.Footer=16]="Footer"})(Sr||(Sr={}));var Cr;(function(t){t[t.ISO_8859_1=0]="ISO_8859_1",t[t.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",t[t.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",t[t.UTF_8=3]="UTF_8"})(Cr||(Cr={}));var ki=128,Ar=10,Er=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],fu=(t,e)=>{let r=t.filePos;e.raw??={},e.raw.TAG??=I(t,ki-3),t.filePos=r;let i=kr(t,30);i&&(e.title??=i);let n=kr(t,30);n&&(e.artist??=n);let s=kr(t,30);s&&(e.album??=s);let o=kr(t,4),a=Number.parseInt(o,10);Number.isInteger(a)&&a>0&&(e.date??=new Date(a,0,1));let c=I(t,30),u;if(c[28]===0&&c[29]!==0){let d=c[29];d>0&&(e.trackNumber??=d),t.skip(-30),u=kr(t,28),t.skip(2)}else t.skip(-30),u=kr(t,30);u&&(e.comment??=u);let l=D(t);l<Er.length&&(e.genre??=Er[l])},kr=(t,e)=>{let r=I(t,e),i=Ot(r.indexOf(0),r.length),n=r.subarray(0,i),s="";for(let o=0;o<n.length;o++)s+=String.fromCharCode(n[o]);return s.trimEnd()},Wt=t=>{let e=t.filePos,r=j(t,3),i=D(t),n=D(t),s=D(t),o=A(t);if(r!=="ID3"||i===255||n===255||(o&2155905152)!==0)return t.filePos=e,null;let a=Gn(o);return{majorVersion:i,revision:n,flags:s,size:a}},jn=(t,e,r)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let i=I(t,e.size),n=new wo(e,i);if(e.flags&Sr.Footer&&n.removeFooter(),e.flags&Sr.Unsynchronisation&&e.majorVersion===3&&n.ununsynchronizeAll(),e.flags&Sr.ExtendedHeader){let s=n.readU32();e.majorVersion===3?n.pos+=s:n.pos+=s-4}for(;n.pos<=n.bytes.length-n.frameHeaderSize();){let s=n.readId3V2Frame();if(!s)break;let o=n.pos,a=n.pos+s.size,c=!1,u=!1,l=!1;if(e.majorVersion===3?(c=!!(s.flags&64),u=!!(s.flags&128)):e.majorVersion===4&&(c=!!(s.flags&4),u=!!(s.flags&8),l=!!(s.flags&2)||!!(e.flags&Sr.Unsynchronisation)),c){console.warn(`Skipping encrypted ID3v2 frame ${s.id}`),n.pos=a;continue}if(u){console.warn(`Skipping compressed ID3v2 frame ${s.id}`),n.pos=a;continue}switch(l&&n.ununsynchronizeRegion(n.pos,a),r.raw??={},s.id[0]==="T"?r.raw[s.id]??=n.readId3V2EncodingAndText(a):r.raw[s.id]??=n.readBytes(s.size),n.pos=o,s.id){case"TIT2":case"TT2":r.title??=n.readId3V2EncodingAndText(a);break;case"TIT3":case"TT3":r.description??=n.readId3V2EncodingAndText(a);break;case"TPE1":case"TP1":r.artist??=n.readId3V2EncodingAndText(a);break;case"TALB":case"TAL":r.album??=n.readId3V2EncodingAndText(a);break;case"TPE2":case"TP2":r.albumArtist??=n.readId3V2EncodingAndText(a);break;case"TRCK":case"TRK":{let f=n.readId3V2EncodingAndText(a).split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(r.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(r.tracksTotal??=p)}break;case"TPOS":case"TPA":{let f=n.readId3V2EncodingAndText(a).split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(r.discNumber??=m),p&&Number.isInteger(p)&&p>0&&(r.discsTotal??=p)}break;case"TCON":case"TCO":{let d=n.readId3V2EncodingAndText(a),f=/^\((\d+)\)/.exec(d);if(f){let m=Number.parseInt(f[1]);if(Er[m]!==void 0){r.genre??=Er[m];break}}if(f=/^\d+$/.exec(d),f){let m=Number.parseInt(f[0]);if(Er[m]!==void 0){r.genre??=Er[m];break}}r.genre??=d}break;case"TDRC":case"TDAT":{let d=n.readId3V2EncodingAndText(a),f=new Date(d);Number.isNaN(f.getTime())||(r.date??=f)}break;case"TYER":case"TYE":{let d=n.readId3V2EncodingAndText(a),f=Number.parseInt(d,10);Number.isInteger(f)&&(r.date??=new Date(f,0,1))}break;case"USLT":case"ULT":{let d=n.readU8();n.pos+=3,n.readId3V2Text(d,a),r.lyrics??=n.readId3V2Text(d,a)}break;case"COMM":case"COM":{let d=n.readU8();n.pos+=3,n.readId3V2Text(d,a),r.comment??=n.readId3V2Text(d,a)}break;case"APIC":case"PIC":{let d=n.readId3V2TextEncoding(),f;if(e.majorVersion===2){let b=n.readAscii(3);f=b==="PNG"?"image/png":b==="JPG"?"image/jpeg":"image/*"}else f=n.readId3V2Text(d,a);let m=n.readU8(),p=n.readId3V2Text(d,a).trimEnd(),g=a-n.pos;if(g>=0){let b=n.readBytes(g);r.images||(r.images=[]),r.images.push({data:b,mimeType:f,kind:m===3?"coverFront":m===4?"coverBack":"unknown",description:p})}}break;default:n.pos+=s.size;break}n.pos=a}},wo=class{constructor(e,r){this.header=e,this.bytes=r,this.pos=0,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let r=0;r<this.bytes.length;r++){let i=this.bytes[r];e.push(i),i===255&&r!==this.bytes.length-1&&this.bytes[r]===0&&r++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,r){let i=[];for(let o=e;o<r;o++){let a=this.bytes[o];i.push(a),a===255&&o!==r-1&&this.bytes[o+1]===0&&o++}let n=this.bytes.subarray(0,e),s=this.bytes.subarray(r);this.bytes=new Uint8Array(n.length+i.length+s.length),this.bytes.set(n,0),this.bytes.set(i,n.length),this.bytes.set(s,n.length+i.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-Ar),this.view=new DataView(this.bytes.buffer)}readBytes(e){let r=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,r}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),r=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+r}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let r="";for(let i=0;i<e;i++)r+=String.fromCharCode(this.view.getUint8(this.pos+i));return this.pos+=e,r}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let r=this.readU24();return{id:e,size:r,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let r=this.readU32(),i=this.header.majorVersion===4?Gn(r):r,n=this.readU16(),s=this.pos,o=a=>{let c=this.pos+a;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=a;let u=this.readAscii(4);if(u!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(u))return!1}return!0};if(!o(i)){let a=this.header.majorVersion===4?r:Gn(r);o(a)&&(i=a)}return this.pos=s,{id:e,size:i,flags:n}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,r){let i=this.pos,n=this.readBytes(r-this.pos);switch(e){case Cr.ISO_8859_1:{let s="";for(let o=0;o<n.length;o++){let a=n[o];if(a===0){this.pos=i+o+1;break}s+=String.fromCharCode(a)}return s}case Cr.UTF_16_WITH_BOM:if(n[0]===255&&n[1]===254){let s=new TextDecoder("utf-16le"),o=Ot(n.findIndex((a,c)=>a===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=i+Math.min(o+2,n.length),s.decode(n.subarray(2,o))}else if(n[0]===254&&n[1]===255){let s=new TextDecoder("utf-16be"),o=Ot(n.findIndex((a,c)=>a===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=i+Math.min(o+2,n.length),s.decode(n.subarray(2,o))}else{let s=Ot(n.findIndex(o=>o===0),n.length);return this.pos=i+Math.min(s+1,n.length),ae.decode(n.subarray(0,s))}case Cr.UTF_16_BE_NO_BOM:{let s=new TextDecoder("utf-16be"),o=Ot(n.findIndex((a,c)=>a===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=i+Math.min(o+2,n.length),s.decode(n.subarray(0,o))}case Cr.UTF_8:{let s=Ot(n.findIndex(o=>o===0),n.length);return this.pos=i+Math.min(s+1,n.length),ae.decode(n.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let r=this.readId3V2TextEncoding();return this.readId3V2Text(r,e)}};var Si=async(t,e,r)=>{let i=e;for(;r===null||i<r;){let n=t.requestSlice(i,4);if(n instanceof Promise&&(n=await n),!n)break;let s=A(n),o=du(s,t.fileSize!==null?t.fileSize-i:null);if(o.header)return{header:o.header,startPos:i};i+=o.bytesAdvanced}return null};var $n=class extends de{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new be,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.tracks=[new ie(this.input,new xo(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,Ar);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let c=Wt(a);if(!c)break;this.lastLoadedPos=a.filePos+c.size}let e=await Si(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let r=e.header;this.lastLoadedPos=e.startPos+r.totalSize-1;let i=lu(r.mpegVersionId,r.channel),n=this.reader.requestSlice(e.startPos+i,4);if(n instanceof Promise&&(n=await n),n){let a=A(n);if(a===cu||a===uu)return}this.firstFrameHeader||(this.firstFrameHeader=r),r.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${r.sampleRate} Hz. Might be a bug, so please report this file.`);let s=r.audioSamplesInFrame/this.firstFrameHeader.sampleRate,o={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:r.totalSize};this.loadedSamples.push(o),this.nextTimestampInSamples+=r.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0,i=!1;for(;;){let n=this.reader.requestSlice(r,Ar);if(n instanceof Promise&&(n=await n),!n)break;let s=Wt(n);if(!s)break;i=!0;let o=this.reader.requestSlice(n.filePos,s.size);if(o instanceof Promise&&(o=await o),!o)break;jn(o,s,this.metadataTags),r=n.filePos+s.size}if(!i&&this.reader.fileSize!==null&&this.reader.fileSize>=ki){let n=this.reader.requestSlice(this.reader.fileSize-ki,ki);n instanceof Promise&&(n=await n),h(n),j(n,3)==="TAG"&&fu(n,this.metadataTags)}return this.metadataTags}finally{e()}}},xo=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Z}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...xe}}async getDecoderConfig(){return h(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,r){if(e===-1)return null;let i=this.demuxer.loadedSamples[e];if(!i)return null;let n;if(r.metadataOnly)n=te;else{let s=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;n=I(s,i.dataSize)}return new L(n,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,r){let i=await this.demuxer.readingMutex.acquire();try{let n=Ft(this.demuxer.loadedSamples,e.timestamp,o=>o.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");let s=n+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,r)}finally{i()}}async getPacket(e,r){let i=await this.demuxer.readingMutex.acquire();try{for(;;){let n=U(this.demuxer.loadedSamples,e,s=>s.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,r);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,r);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}};var yo=1399285583,_d=79764919,hu=new Uint32Array(256);for(let t=0;t<256;t++){let e=t<<24;for(let r=0;r<8;r++)e=e&2147483648?e<<1^_d:e<<1;hu[t]=e>>>0&4294967295}var pu=t=>{let e=V(t),r=e.getUint32(22,!0);e.setUint32(22,0,!0);let i=0;for(let n=0;n<t.length;n++){let s=t[n];i=(i<<8^hu[i>>>24^s])>>>0}return e.setUint32(22,r,!0),i},gu=(t,e,r)=>{let i=0,n=null;if(t.length>0)if(e.codec==="vorbis"){h(e.vorbisInfo);let s=e.vorbisInfo.modeBlockflags.length,a=(1<<dc(s-1))-1<<1,c=(t[0]&a)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let u=r,l=e.vorbisInfo.modeBlockflags[c];if(n=e.vorbisInfo.blocksizes[l],l===1){let d=(a|1)+1,f=t[0]&d?1:0;u=e.vorbisInfo.blocksizes[f]}i=u!==null?u+n>>2:0}else e.codec==="opus"&&(i=zc(t).durationInSamples);return{durationInSamples:i,vorbisBlockSize:n}},bu=t=>{let e="audio/ogg";if(t.codecStrings){let r=[...new Set(t.codecStrings)];e+=`; codecs="${r.join(", ")}"`}return e};var yt=27,jt=282,wu=jt+65025,vr=t=>{let e=t.filePos;if(Gt(t)!==yo)return null;t.skip(1);let i=D(t),n=yu(t),s=Gt(t),o=Gt(t),a=Gt(t),c=D(t),u=new Uint8Array(c);for(let m=0;m<c;m++)u[m]=D(t);let l=27+c,d=u.reduce((m,p)=>m+p,0),f=l+d;return{headerStartPos:e,totalSize:f,dataStartPos:e+l,dataSize:d,headerType:i,granulePosition:n,serialNumber:s,sequenceNumber:o,checksum:a,lacingValues:u}},xu=(t,e)=>{for(;t.filePos<e-3;){let r=Gt(t),i=r&255,n=r>>>8&255,s=r>>>16&255,o=r>>>24&255,a=79;if(!(i!==a&&n!==a&&s!==a&&o!==a)){if(t.skip(-4),r===yo)return!0;t.skip(1)}}return!1};var Qn=class extends de{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,yt,jt);if(r instanceof Promise&&(r=await r),!r)break;let i=vr(r);if(!i||!!!(i.headerType&2))break;this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(let r of this.bitstreams){let i=await this.readPacket(r.bosPage,0);i&&(i.data.byteLength>=7&&i.data[0]===1&&i.data[1]===118&&i.data[2]===111&&i.data[3]===114&&i.data[4]===98&&i.data[5]===105&&i.data[6]===115?await this.readVorbisMetadata(i,r):i.data.byteLength>=8&&i.data[0]===79&&i.data[1]===112&&i.data[2]===117&&i.data[3]===115&&i.data[4]===72&&i.data[5]===101&&i.data[6]===97&&i.data[7]===100&&await this.readOpusMetadata(i,r),r.codecInfo.codec!==null&&this.tracks.push(new ie(this.input,new To(r,this))))}})()}async readVorbisMetadata(e,r){let i=await this.findNextPacketStart(e);if(!i)return;let n=await this.readPacket(i.startPage,i.startSegmentIndex);if(!n||(i=await this.findNextPacketStart(n),!i))return;let s=await this.readPacket(i.startPage,i.startSegmentIndex);if(!s||n.data[0]!==3||s.data[0]!==5)return;let o=[],a=d=>{for(;o.push(Math.min(255,d)),!(d<255);)d-=255};a(e.data.length),a(n.data.length);let c=new Uint8Array(1+o.length+e.data.length+n.data.length+s.data.length);c[0]=2,c.set(o,1),c.set(e.data,1+o.length),c.set(n.data,1+o.length+e.data.length),c.set(s.data,1+o.length+e.data.length+n.data.length),r.codecInfo.codec="vorbis",r.description=c,r.lastMetadataPacket=s;let u=V(e.data);r.numberOfChannels=u.getUint8(11),r.sampleRate=u.getUint32(12,!0);let l=u.getUint8(28);r.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:Vc(s.data).modeBlockflags},fi(n.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,r){let i=await this.findNextPacketStart(e);if(!i)return;let n=await this.readPacket(i.startPage,i.startSegmentIndex);if(!n)return;r.codecInfo.codec="opus",r.description=e.data,r.lastMetadataPacket=n;let s=Pn(e.data);r.numberOfChannels=s.outputChannelCount,r.sampleRate=Mt,r.codecInfo.opusInfo={preSkip:s.preSkip},fi(n.data.subarray(8),this.metadataTags)}async readPacket(e,r){h(r<e.lacingValues.length);let i=0;for(let d=0;d<r;d++)i+=e.lacingValues[d];let n=e,s=i,o=r,a=[];e:for(;;){let d=this.reader.requestSlice(n.dataStartPos,n.dataSize);d instanceof Promise&&(d=await d),h(d);let f=I(d,n.dataSize);for(;;){if(o===n.lacingValues.length){a.push(f.subarray(i,s));break}let p=n.lacingValues[o];if(s+=p,p<255){a.push(f.subarray(i,s));break e}o++}let m=n.headerStartPos+n.totalSize;for(;;){let p=this.reader.requestSliceRange(m,yt,jt);if(p instanceof Promise&&(p=await p),!p)return null;let g=vr(p);if(!g)return null;if(n=g,n.serialNumber===e.serialNumber)break;m=n.headerStartPos+n.totalSize}i=0,s=0,o=0}let c=a.reduce((d,f)=>d+f.length,0),u=new Uint8Array(c),l=0;for(let d=0;d<a.length;d++){let f=a[d];u.set(f,l),l+=f.length}return{data:u,endPage:n,endSegmentIndex:o}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let i=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let n=this.reader.requestSliceRange(i,yt,jt);if(n instanceof Promise&&(n=await n),!n)return null;let s=vr(n);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};i=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(r=>r.getCodecParameterString()));return bu({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(i=>i.computeDuration()));return Math.max(0,...r)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},To=class{constructor(e,r){this.bitstream=e,this.demuxer=r,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new be,this.internalSampleRate=e.codecInfo.codec==="opus"?Mt:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return h(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return Z}getDisposition(){return{...xe}}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(h(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,r,i){if(!e)return null;let{durationInSamples:n,vorbisBlockSize:s}=gu(e.data,this.bitstream.codecInfo,r.vorbisLastBlocksize),o=new L(i.metadataOnly?te:e.data,"key",Math.max(0,r.timestampInSamples)/this.internalSampleRate,n/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(o,{packet:e,timestampInSamples:r.timestampInSamples,durationInSamples:n,vorbisLastBlockSize:r.vorbisLastBlocksize,vorbisBlockSize:s}),o}async getFirstPacket(e){h(this.bitstream.lastMetadataPacket);let r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let i=0;this.bitstream.codecInfo.codec==="opus"&&(h(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);let n=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(n,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,r){let i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");let n=await this.demuxer.findNextPacketStart(i.packet);if(!n)return null;let s=i.timestampInSamples+i.durationInSamples,o=await this.demuxer.readPacket(n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:s,vorbisLastBlocksize:i.vorbisBlockSize},r)}async getPacket(e,r){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,r);let i=Rt(e*this.internalSampleRate);if(i===0)return this.getFirstPacket(r);if(i<0)return null;h(this.bitstream.lastMetadataPacket);let n=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!n)return null;let s=n.startPage,o=this.demuxer.reader.fileSize,a=[s];e:for(;s.headerStartPos+s.totalSize<o;){let x=s.headerStartPos,y=Math.floor((x+o)/2),T=y;for(;;){let E=Math.min(T+wu,o-yt),S=this.demuxer.reader.requestSlice(T,E-T);if(S instanceof Promise&&(S=await S),h(S),!xu(S,E)){o=y+yt;continue e}let v=this.demuxer.reader.requestSliceRange(S.filePos,yt,jt);v instanceof Promise&&(v=await v),h(v);let F=vr(v);h(F);let M=!1;if(F.serialNumber===this.bitstream.serialNumber)M=!0;else{let Q=this.demuxer.reader.requestSlice(F.headerStartPos,F.totalSize);Q instanceof Promise&&(Q=await Q),h(Q);let je=I(Q,F.totalSize);M=pu(je)===F.checksum}if(!M){T=F.headerStartPos+4;continue}if(M&&F.serialNumber!==this.bitstream.serialNumber){T=F.headerStartPos+F.totalSize;continue}if(F.granulePosition===-1){T=F.headerStartPos+F.totalSize;continue}this.granulePositionToTimestampInSamples(F.granulePosition)>i?o=F.headerStartPos:(s=F,a.push(F));continue e}}let c=n.startPage;for(let x of a){if(x.granulePosition===s.granulePosition)break;(!c||x.headerStartPos>c.headerStartPos)&&(c=x)}let u=c,l=[u];for(;!(u.serialNumber===this.bitstream.serialNumber&&u.granulePosition===s.granulePosition);){let x=u.headerStartPos+u.totalSize,y=this.demuxer.reader.requestSliceRange(x,yt,jt);y instanceof Promise&&(y=await y),h(y);let T=vr(y);h(T),u=T,u.serialNumber===this.bitstream.serialNumber&&l.push(u)}h(u.granulePosition!==-1);let d=null,f,m,p=u,g=0;if(u.headerStartPos===n.startPage.headerStartPos)f=this.granulePositionToTimestampInSamples(0),m=!0,d=0;else{f=0,m=!1;for(let T=u.lacingValues.length-1;T>=0;T--)if(u.lacingValues[T]<255){d=T+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");g=d-1;let x={data:te,endPage:p,endSegmentIndex:g};if(await this.demuxer.findNextPacketStart(x)){let T=ku(l,u,d);h(T);let E=Tu(l,T.page,T.segmentIndex);E&&(u=E.page,d=E.segmentIndex)}else for(;;){let T=ku(l,u,d);if(!T)break;let E=Tu(l,T.page,T.segmentIndex);if(!E)break;if(u=E.page,d=E.segmentIndex,T.page.headerStartPos!==p.headerStartPos){p=T.page,g=T.segmentIndex;break}}}let b=null,w=null;for(;u!==null;){h(d!==null);let x=await this.demuxer.readPacket(u,d);if(!x)break;if(!(u.headerStartPos===n.startPage.headerStartPos&&d<n.startSegmentIndex)){let E=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:f,vorbisLastBlocksize:w?.vorbisBlockSize??null},r);h(E);let S=this.encodedPacketToMetadata.get(E);if(h(S),!m&&x.endPage.headerStartPos===p.headerStartPos&&x.endSegmentIndex===g?(f=this.granulePositionToTimestampInSamples(u.granulePosition),m=!0,E=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:f-S.durationInSamples,vorbisLastBlocksize:w?.vorbisBlockSize??null},r),h(E),S=this.encodedPacketToMetadata.get(E),h(S)):f+=S.durationInSamples,b=E,w=S,m&&(Math.max(f,0)>i||Math.max(S.timestampInSamples,0)===i))break}let T=await this.demuxer.findNextPacketStart(x);if(!T)break;u=T.startPage,d=T.startSegmentIndex}return b}async getPacketSequential(e,r){let i=await this.sequentialScanMutex.acquire();try{let n=Rt(e*this.internalSampleRate);e=n/this.internalSampleRate;let s=U(this.sequentialScanCache,n,c=>c.timestampInSamples),o;if(s!==-1){let c=this.sequentialScanCache[s];o=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},r)}else o=await this.getFirstPacket(r);let a=0;for(;o&&o.timestamp<e;){let c=await this.getNextPacket(o,r);if(!c||c.timestamp>e)break;if(o=c,a++,a===100){a=0;let u=this.encodedPacketToMetadata.get(o);h(u),this.sequentialScanCache.length>0&&h(G(this.sequentialScanCache).timestampInSamples<=u.timestampInSamples),this.sequentialScanCache.push(u)}}return o}finally{i()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}},Tu=(t,e,r)=>{let i=e,n=r;e:for(;;){for(n--,n;n>=0;n--)if(i.lacingValues[n]<255){n++;break e}if(h(n===-1),!(i.headerType&1)){n=0;break}let o=Hs(t,a=>a.headerStartPos<i.headerStartPos);if(!o)return null;i=o,n=i.lacingValues.length}if(h(n!==-1),n===i.lacingValues.length){let s=t[t.indexOf(i)+1];h(s),i=s,n=0}return{page:i,segmentIndex:n}},ku=(t,e,r)=>{if(r>0)return{page:e,segmentIndex:r-1};let i=Hs(t,n=>n.headerStartPos<e.headerStartPos);return i?{page:i,segmentIndex:i.lacingValues.length-1}:null};var ct;(function(t){t[t.PCM=1]="PCM",t[t.IEEE_FLOAT=3]="IEEE_FLOAT",t[t.ALAW=6]="ALAW",t[t.MULAW=7]="MULAW",t[t.EXTENSIBLE=65534]="EXTENSIBLE"})(ct||(ct={}));var Xn=class extends de{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),h(e);let r=j(e,4),i=r!=="RIFX",n=r==="RF64",s=ut(e,i),o=n?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(j(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,u=null,l=e.filePos;for(;o===null||l<o;){let f=this.reader.requestSlice(l,8);if(f instanceof Promise&&(f=await f),!f)break;let m=j(f,4),p=ut(f,i),g=f.filePos;if(n&&c===0&&m!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(m==="fmt ")await this.parseFmtChunk(g,p,i);else if(m==="data"){if(u??=p,this.dataStart=f.filePos,this.dataSize=Math.min(u,(o??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(m==="ds64"){let b=this.reader.requestSlice(g,p);if(b instanceof Promise&&(b=await b),!b)break;let w=So(b,i);u=So(b,i),o=Math.min(w+8,this.reader.fileSize??1/0)}else m==="LIST"?await this.parseListChunk(g,p,i):(m==="ID3 "||m==="id3 ")&&await this.parseId3Chunk(g,p);l=g+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.tracks.push(new ie(this.input,new ko(this)))})()}async parseFmtChunk(e,r,i){let n=this.reader.requestSlice(e,r);if(n instanceof Promise&&(n=await n),!n)return;let s=Pr(n,i),o=Pr(n,i),a=ut(n,i);n.skip(4);let c=Pr(n,i),u;if(r===14?u=8:u=Pr(n,i),r>=18&&s!==357){let l=Pr(n,i),d=r-18;if(Math.min(d,l)>=22&&s===ct.EXTENSIBLE){n.skip(6);let m=I(n,16);s=m[0]|m[1]<<8}}(s===ct.MULAW||s===ct.ALAW)&&(u=8),this.audioInfo={format:s,numberOfChannels:o,sampleRate:a,sampleSizeInBytes:Math.ceil(u/8),blockSizeInBytes:c}}async parseListChunk(e,r,i){let n=this.reader.requestSlice(e,r);if(n instanceof Promise&&(n=await n),!n)return;let s=j(n,4);if(s!=="INFO"&&s!=="INF0")return;let o=n.filePos;for(;o<=e+r-8;){n.filePos=o;let a=j(n,4),c=ut(n,i),u=I(n,c),l=0;for(let f=0;f<u.length&&u[f]!==0;f++)l++;let d=String.fromCharCode(...u.subarray(0,l));switch(this.metadataTags.raw??={},this.metadataTags.raw[a]=d,a){case"INAM":case"TITL":this.metadataTags.title??=d;break;case"TIT3":this.metadataTags.description??=d;break;case"IART":this.metadataTags.artist??=d;break;case"IPRD":this.metadataTags.album??=d;break;case"IPRT":case"ITRK":case"TRCK":{let f=d.split("/"),m=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(m)&&m>0&&(this.metadataTags.trackNumber??=m),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let f=new Date(d);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"YEAR":{let f=Number.parseInt(d,10);Number.isInteger(f)&&f>0&&(this.metadataTags.date??=new Date(f,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}o+=8+c+(c&1)}}async parseId3Chunk(e,r){let i=this.reader.requestSlice(e,r);if(i instanceof Promise&&(i=await i),!i)return;let n=Wt(i);if(n){let s=i.slice(e+10,n.size);jn(s,n,this.metadataTags)}}getCodec(){if(h(this.audioInfo),this.audioInfo.format===ct.MULAW)return"ulaw";if(this.audioInfo.format===ct.ALAW)return"alaw";if(this.audioInfo.format===ct.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===ct.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},_r=2048,ko=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(h(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Z}getDisposition(){return{...xe}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,r){h(this.demuxer.audioInfo);let i=e*_r*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;let n=Math.min(_r*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-i);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,n);if(c instanceof Promise&&(c=await c),!c)return null}let s;if(r.metadataOnly)s=te;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,n);c instanceof Promise&&(c=await c),h(c),s=I(c,n)}let o=e*_r/this.demuxer.audioInfo.sampleRate,a=n/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,o),new L(s,"key",o,a,e,n)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,r){h(this.demuxer.audioInfo);let i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/_r,(this.demuxer.dataSize-1)/(_r*this.demuxer.audioInfo.blockSizeInBytes))),n=await this.getPacketAtIndex(i,r);if(n)return n;if(i===0)return null;h(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,r);for(;s;){let o=await this.getNextPacket(s,r);if(!o)break;s=o}return s}getNextPacket(e,r){h(this.demuxer.audioInfo);let i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/_r);return this.getPacketAtIndex(i+1,r)}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}};var Dr=7,Ir=9,Ci=t=>{let e=t.filePos,r=I(t,9),i=new W(r);if(i.readBits(12)!==4095||(i.skipBits(1),i.readBits(2)!==0))return null;let o=i.readBits(1),a=i.readBits(2)+1,c=i.readBits(4);if(c===15)return null;i.skipBits(1);let u=i.readBits(3);if(u===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);let l=i.readBits(13);i.skipBits(11);let d=i.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let f=null;return o===1?t.filePos-=2:f=i.readBits(16),{objectType:a,samplingFrequencyIndex:c,channelConfiguration:u,frameLength:l,numberOfAacFrames:d,crcCheck:f,startPos:e}};var Co=1024,Kn=class extends de{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new be,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();h(this.firstFrameHeader),this.tracks=[new ie(this.input,new Eo(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,Dr,Ir);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let r=Ci(e);if(!r){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&r.startPos+r.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=r);let i=fr[r.samplingFrequencyIndex];h(i!==void 0);let n=Co/i,s=r.crcCheck?Ir:Dr,o={timestamp:this.nextTimestampInSamples/i,duration:n,dataStart:r.startPos+s,dataSize:r.frameLength-s};this.loadedSamples.push(o),this.nextTimestampInSamples+=Co,this.lastLoadedPos=r.startPos+r.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return h(e),e.computeDuration()}async getMetadataTags(){return{}}},Eo=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/Co}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return Z}getCodec(){return"aac"}getInternalCodecId(){return h(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){h(this.demuxer.firstFrameHeader);let e=kn[this.demuxer.firstFrameHeader.channelConfiguration];return h(e!==void 0),e}getSampleRate(){h(this.demuxer.firstFrameHeader);let e=fr[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return h(e!==void 0),e}getDisposition(){return{...xe}}async getDecoderConfig(){h(this.demuxer.firstFrameHeader);let e=new Uint8Array(3),r=new W(e),{objectType:i,samplingFrequencyIndex:n,channelConfiguration:s}=this.demuxer.firstFrameHeader;return i>31?(r.writeBits(5,31),r.writeBits(6,i-32)):r.writeBits(5,i),r.writeBits(4,n),r.writeBits(4,s),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((r.pos-1)/8))}}async getPacketAtIndex(e,r){if(e===-1)return null;let i=this.demuxer.loadedSamples[e];if(!i)return null;let n;if(r.metadataOnly)n=te;else{let s=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;n=I(s,i.dataSize)}return new L(n,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,r){let i=await this.demuxer.readingMutex.acquire();try{let n=Ft(this.demuxer.loadedSamples,e.timestamp,o=>o.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");let s=n+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,r)}finally{i()}}async getPacket(e,r){let i=await this.demuxer.readingMutex.acquire();try{for(;;){let n=U(this.demuxer.loadedSamples,e,s=>s.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,r);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,r);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}};var Su=t=>t===0?null:t===1?192:t>=2&&t<=5?144*2**t:t===6?"uncommon-u8":t===7?"uncommon-u16":t>=8&&t<=15?2**t:null,Cu=(t,e)=>{switch(t){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},Eu=t=>{let e=0,r=new W(I(t,1));for(;r.readBits(1)===1;)e++;if(e===0)return r.readBits(7);let i=[],n=e-1,s=new W(I(t,n)),o=8-e-1;for(let c=0;c<o;c++)i.unshift(r.readBits(1));for(let c=0;c<n;c++)for(let u=0;u<8;u++){let l=s.readBits(1);u<2||i.unshift(l)}return i.reduce((c,u,l)=>c|u<<l,0)},Au=(t,e)=>{if(e==="uncommon-u16")return ne(t)+1;if(e==="uncommon-u8")return D(t)+1;if(typeof e=="number")return e;ue(e),h(!1)},vu=(t,e)=>e==="uncommon-u16"?ne(t):e==="uncommon-u16-10"?ne(t)*10:e==="uncommon-u8"?D(t):typeof e=="number"?e:null,_u=t=>{let r=0;for(let i of t){r^=i;for(let n=0;n<8;n++)(r&128)!==0?r=r<<1^7:r<<=1,r&=255}return r};var Yn=class extends de{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new be,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),h(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),h(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||e<this.reader.fileSize;){let r=this.reader.requestSlice(e,4);if(r instanceof Promise&&(r=await r),e+=4,r===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);h(r);let i=D(r),n=wt(r),s=(i&128)!==0;switch(i&127){case gt.STREAMINFO:{let a=this.reader.requestSlice(e,n);if(a instanceof Promise&&(a=await a),h(a),a===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=I(a,34),u=new W(c),l=u.readBits(16),d=u.readBits(16),f=u.readBits(24),m=u.readBits(24),p=u.readBits(20),g=u.readBits(3)+1;u.readBits(5);let b=u.readBits(36);u.skipBits(128);let w=new Uint8Array(42);w.set(new Uint8Array([102,76,97,67]),0),w.set(new Uint8Array([128,0,0,34]),4),w.set(c,8),this.audioInfo={numberOfChannels:g,sampleRate:p,totalSamples:b,minimumBlockSize:l,maximumBlockSize:d,minimumFrameSize:f,maximumFrameSize:m,description:w},this.track=new ie(this.input,new Ao(this));break}case gt.VORBIS_COMMENT:{let a=this.reader.requestSlice(e,n);a instanceof Promise&&(a=await a),h(a),fi(I(a,n),this.metadataTags);break}case gt.PICTURE:{let a=this.reader.requestSlice(e,n);a instanceof Promise&&(a=await a),h(a);let c=A(a),u=A(a),l=ae.decode(I(a,u)),d=A(a),f=ae.decode(I(a,d));a.skip(16);let m=A(a),p=I(a,m);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:l,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:f});break}default:break}if(e+=n,s){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:r}){h(this.audioInfo);let i=6,s=this.audioInfo.maximumFrameSize+16,o=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,s);if(!o)return null;let a=this.readFlacFrameHeader({slice:o,isFirstPacket:r});if(!a)return null;for(o.filePos=e+this.audioInfo.minimumFrameSize;;){if(o.filePos>o.end-i)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:o.end-e,isLastFrame:!0};if(D(o)===255){let u=o.filePos,l=D(o),d=this.blockingBit===1?249:248;if(l!==d){o.filePos=u;continue}o.skip(-2);let f=o.filePos-e,m=this.readFlacFrameHeader({slice:o,isFirstPacket:!1});if(!m){o.filePos=u;continue}if(this.blockingBit===0){if(m.num-a.num!==1){o.filePos=u;continue}}else if(m.num-a.num!==a.blockSize){o.filePos=u;continue}return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:f,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:r}){let i=e.filePos,n=I(e,4),s=new W(n);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){h(r);let b=s.readBits(1);this.blockingBit=b}else if(this.blockingBit===1){if(h(!r),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(h(!r),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let a=Su(s.readBits(4));if(!a)return null;h(this.audioInfo);let c=Cu(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;let l=Eu(e),d=Au(e,a),f=vu(e,c);if(f===null||f!==this.audioInfo.sampleRate)return null;let m=e.filePos-i,p=D(e);e.skip(-m),e.skip(-1);let g=_u(I(e,m));return p!==g?null:{num:l,blockSize:d,sampleRate:f}}async advanceReader(){await this.readMetadata(),h(this.lastLoadedPos!==null),h(this.audioInfo);let e=this.lastLoadedPos,r=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!r){this.lastSampleLoaded=!0;return}let i=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:r.blockSize,byteOffset:e,byteSize:r.size};if(this.lastLoadedPos=this.lastLoadedPos+r.size,this.loadedSamples.push(s),r.isLastFrame){this.lastSampleLoaded=!0;return}}},Ao=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Z}getTimeResolution(){return h(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...xe}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return h(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,r){if(h(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");let i=await this.demuxer.readingMutex.acquire();try{for(;;){let n=U(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){await this.demuxer.advanceReader();continue}let s=this.demuxer.loadedSamples[n],o=s.blockOffset/this.demuxer.audioInfo.sampleRate,a=s.blockSize/this.demuxer.audioInfo.sampleRate;if(o+a<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,r);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,r)}}finally{i()}}async getNextPacket(e,r){let i=await this.demuxer.readingMutex.acquire();try{let n=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,r)}finally{i()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}async getPacketAtIndex(e,r){let i=this.demuxer.loadedSamples[e];if(!i)return null;let n;if(r.metadataOnly)n=te;else{let a=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(a instanceof Promise&&(a=await a),!a)return null;n=I(a,i.byteSize)}h(this.demuxer.audioInfo);let s=i.blockOffset/this.demuxer.audioInfo.sampleRate,o=i.blockSize/this.demuxer.audioInfo.sampleRate;return new L(n,"key",s,o,e,i.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}};var ve=class{},Ei=class extends ve{async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);return r instanceof Promise&&(r=await r),!r||(r.skip(4),j(r,4)!=="ftyp")?null:j(r,4)}_createDemuxer(e){return new Nn(e)}},Zn=class extends Ei{async _canReadInput(e){let r=await this._getMajorBrand(e);return!!r&&r!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Jn=class extends Ei{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},Ai=class extends ve{async isSupportedEBMLOfDocType(e,r){let i=e._reader.requestSlice(0,Fe);if(i instanceof Promise&&(i=await i),!i)return!1;let n=fo(i);if(n===null||n<1||n>8||N(i,n)!==k.EBML)return!1;let o=mo(i);if(o===null)return!1;let a=e._reader.requestSlice(i.filePos,o);if(a instanceof Promise&&(a=await a),!a)return!1;let c=i.filePos;for(;a.filePos<=c+o-Se;){let u=Be(a);if(!u)break;let{id:l,size:d}=u,f=a.filePos;if(d===null)return!1;switch(l){case k.EBMLVersion:if(N(a,d)!==1)return!1;break;case k.EBMLReadVersion:if(N(a,d)!==1)return!1;break;case k.DocType:if(xt(a,d)!==r)return!1;break;case k.DocTypeVersion:if(N(a,d)>4)return!1;break}a.filePos=f+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Hn(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},es=class extends Ai{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},ts=class extends ve{async _canReadInput(e){let r=e._reader.requestSlice(0,10);if(r instanceof Promise&&(r=await r),!r)return!1;let i=0,n=!1;for(;;){let u=e._reader.requestSlice(i,Ar);if(u instanceof Promise&&(u=await u),!u)break;let l=Wt(u);if(!l)break;n=!0,i=u.filePos+l.size}let s=await Si(e._reader,i,i+4096);if(!s)return!1;if(n)return!0;i=s.startPos+s.header.totalSize;let o=await Si(e._reader,i,i+4);if(!o)return!1;let a=s.header,c=o.header;return!(a.channel!==c.channel||a.sampleRate!==c.sampleRate)}_createDemuxer(e){return new $n(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},rs=class extends ve{async _canReadInput(e){let r=e._reader.requestSlice(0,12);if(r instanceof Promise&&(r=await r),!r)return!1;let i=j(r,4);return i!=="RIFF"&&i!=="RIFX"&&i!=="RF64"?!1:(r.skip(4),j(r,4)==="WAVE")}_createDemuxer(e){return new Xn(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},is=class extends ve{async _canReadInput(e){let r=e._reader.requestSlice(0,4);return r instanceof Promise&&(r=await r),r?j(r,4)==="OggS":!1}_createDemuxer(e){return new Qn(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},ns=class extends ve{async _canReadInput(e){let r=e._reader.requestSlice(0,4);return r instanceof Promise&&(r=await r),r?j(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Yn(e)}},ss=class extends ve{async _canReadInput(e){let r=e._reader.requestSliceRange(0,Dr,Ir);if(r instanceof Promise&&(r=await r),!r)return!1;let i=Ci(r);if(!i||(r=e._reader.requestSliceRange(i.frameLength,Dr,Ir),r instanceof Promise&&(r=await r),!r))return!1;let n=Ci(r);return n?i.objectType===n.objectType&&i.samplingFrequencyIndex===n.samplingFrequencyIndex&&i.channelConfiguration===n.channelConfiguration:!1}_createDemuxer(e){return new Kn(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},Pu=new Zn,Du=new Jn,Iu=new Ai,Fu=new es,Bu=new ts,Ru=new rs,Ou=new is,Nu=new ss,Mu=new ns,os=[Pu,Du,Iu,Fu,Ru,Ou,Mu,Bu,Nu];var $t=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new re;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new re;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}};var vi=class extends $t{constructor(e,r={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!ui(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new as({maxCacheSize:r.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:zu.fileSystem})}_retrieveSize(){let e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){let r=this._readers.get(e);for(r===void 0&&("stream"in this._blob&&!pt()?r=this._blob.slice(e.currentPos).stream().getReader():r=null,this._readers.set(e,r));e.currentPos<e.targetPos&&!e.aborted;)if(r){let{done:i,value:n}=await r.read();if(i)throw this._orchestrator.forgetWorker(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}else{let i=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+i.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(i))}e.running=!1,e.aborted&&await r?.cancel()}_dispose(){this._orchestrator.dispose()}},Uu=.5*2**20,Pd=((t,e,r)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))){let n=null;try{typeof window<"u"&&typeof window.location<"u"&&(n=new URL(r instanceof Request?r.url:r,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&n!==null&&n!==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**(t-2),16)}),_i=class extends $t{constructor(e,r={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.requestInit!==void 0&&(!r.requestInit||typeof r.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(r.getRetryDelay!==void 0&&typeof r.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(r.maxCacheSize!==void 0&&(!ui(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(r.fetchFn!==void 0&&typeof r.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=r,this._getRetryDelay=r.getRetryDelay??Pd,this._orchestrator=new as({maxCacheSize:r.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:zu.network})}async _retrieveSize(){let e=new AbortController,r=await Gs(this._options.fetchFn??fetch,this._url,Ws(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);let i,n;if(r.status===206)n=this._getTotalLengthFromRangeResponse(r),i=this._orchestrator.createWorker(0,Math.min(n,Uu));else{let s=r.headers.get("Content-Length");if(s)n=Number(s),i=this._orchestrator.createWorker(0,n),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 new Error(`HTTP response (status ${r.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=n,this._existingResponses.set(i,{response:r,abortController:e}),this._orchestrator.runWorker(i),n}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){for(;;){let r=this._existingResponses.get(e);this._existingResponses.delete(e);let i=r?.abortController,n=r?.response;if(i||(i=new AbortController,n=await Gs(this._options.fetchFn??fetch,this._url,Ws(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:i.signal}),this._getRetryDelay,()=>this._disposed)),h(n),!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);if(e.currentPos>0&&n.status!==206)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let s=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){i.abort(),e.running=!1;return}let o;try{o=await s.read()}catch(u){if(this._disposed)throw u;let l=this._getRetryDelay(1,u,this._url);if(l!==null){console.error("Error while reading response stream. Attempting to resume.",u),await new Promise(d=>setTimeout(d,1e3*l));break}else throw u}if(e.aborted)continue;let{done:a,value:c}=o;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}}_getTotalLengthFromRangeResponse(e){let r=e.headers.get("Content-Range");if(r){let n=/\/(\d+)/.exec(r);if(n)return Number(n[1])}let i=e.headers.get("Content-Length");if(i)return Number(i);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}};var zu={none:(t,e)=>({start:t,end:e}),fileSystem:(t,e)=>(t=Math.floor((t-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:t,end:e}),network:(t,e,r)=>{t=Math.max(0,Math.floor((t-65536)/65536)*65536);for(let n of r){let o=Math.max((n.startPos+n.targetPos)/2,n.targetPos-8388608);if(wn(t,e,o,n.targetPos)){let a=n.targetPos-n.startPos,c=Math.ceil((a+1)/8388608)*8388608,u=2**Math.ceil(Math.log2(a+1)),l=Math.min(u,c);e=Math.max(e,n.startPos+l)}}return e=Math.max(e,t+Uu),{start:t,end:e}}},as=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,r){h(this.fileSize!==null);let i=this.options.prefetchProfile(e,r,this.workers),n=Math.max(i.start,0),s=Math.min(i.end,this.fileSize);h(n<=e&&r<=s);let o=null,a=U(this.cache,e,x=>x.start),c=a!==-1?this.cache[a]:null;c&&c.start<=e&&r<=c.end&&(c.age=this.nextAge++,o={bytes:c.bytes,view:c.view,offset:c.start});let u=U(this.cache,n,x=>x.start),l=o?null:new Uint8Array(r-e),d=0,f=n,m=[];if(u!==-1){for(let x=u;x<this.cache.length;x++){let y=this.cache[x];if(y.start>=s)break;if(y.end<=n)continue;let T=Math.max(n,y.start),E=Math.min(s,y.end);if(h(T<=E),f<T&&m.push({start:f,end:T}),f=E,l){let S=Math.max(e,y.start),P=Math.min(r,y.end);if(S<P){let v=S-e;l.set(y.bytes.subarray(S-y.start,P-y.start),v),v===d&&(d=P-e)}}y.age=this.nextAge++}f<s&&m.push({start:f,end:s})}else m.push({start:n,end:s});if(l&&d>=l.length&&(o={bytes:l,view:V(l),offset:e}),m.length===0)return h(o),o;let{promise:p,resolve:g,reject:b}=ce(),w=[];for(let x of m){let y=Math.max(e,x.start),T=Math.min(r,x.end);y===x.start&&T===x.end?w.push(x):y<T&&w.push({start:y,end:T})}for(let x of m){let y=l&&{start:e,bytes:l,holes:w,resolve:g,reject:b},T=!1;for(let E of this.workers)if(wn(x.start-131072,x.start,E.currentPos,E.targetPos)){E.targetPos=Math.max(E.targetPos,x.end),T=!0,y&&!E.pendingSlices.includes(y)&&E.pendingSlices.push(y),E.running||this.runWorker(E);break}if(!T){let E=this.createWorker(x.start,x.end);y&&(E.pendingSlices=[y]),this.runWorker(E)}}return o||(h(l),o=p.then(x=>({bytes:x,view:V(x),offset:e}))),o}createWorker(e,r){let i={startPos:e,currentPos:e,targetPos:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(i);this.workers.length>this.options.maxWorkerCount;){let n=0,s=this.workers[0];for(let o=1;o<this.workers.length;o++){let a=this.workers[o];a.age<s.age&&(n=o,s=a)}if(s.running&&s.pendingSlices.length>0)break;s.aborted=!0,this.workers.splice(n,1)}return i}runWorker(e){h(!e.running),h(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(r=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(i=>i.reject(r)),e.pendingSlices.length=0;else throw r})}supplyWorkerData(e,r){h(!e.aborted);let i=e.currentPos,n=i+r.length;this.insertIntoCache({start:i,end:n,bytes:r,view:V(r),age:this.nextAge++}),e.currentPos+=r.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let s=0;s<e.pendingSlices.length;s++){let o=e.pendingSlices[s],a=Math.max(i,o.start),c=Math.min(n,o.start+o.bytes.length);a<c&&o.bytes.set(r.subarray(a-i,c-i),a-o.start);for(let u=0;u<o.holes.length;u++){let l=o.holes[u];i<=l.start&&n>l.start&&(l.start=n),l.end<=l.start&&(o.holes.splice(u,1),u--)}o.holes.length===0&&(o.resolve(o.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){let o=this.workers[s];e===o||o.running||wn(i,n,o.currentPos,o.targetPos)&&(this.workers.splice(s,1),s--)}}forgetWorker(e){let r=this.workers.indexOf(e);h(r!==-1),this.workers.splice(r,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let r=U(this.cache,e.start,i=>i.start)+1;if(r>0){let i=this.cache[r-1];if(i.end>=e.end)return;if(i.end>e.start){let n=new Uint8Array(e.end-i.start);n.set(i.bytes,0),n.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=n,i.view=V(n),i.end=e.end,r--,e=i}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length;for(let i=r+1;i<this.cache.length;i++){let n=this.cache[i];if(e.end<=n.start)break;if(e.end>=n.end){this.cache.splice(i,1),this.currentCacheSize-=n.bytes.length,i--;continue}let s=new Uint8Array(n.end-e.start);s.set(e.bytes,0),s.set(n.bytes,n.start-e.start),this.currentCacheSize-=e.end-n.start,e.bytes=s,e.view=V(s),e.end=n.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let i=0,n=this.cache[0];for(let s=1;s<this.cache.length;s++){let o=this.cache[s];o.age<n.age&&(i=s,n=o)}if(this.currentCacheSize-n.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(i,1),this.currentCacheSize-=n.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};xn();var Fr=class{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(r=>!(r instanceof ve)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof $t))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new cs(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),h(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(r=>r.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(r=>r.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(r=>r.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(r=>r.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()}},re=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var cs=class{constructor(e){this.source=e}requestSlice(e,r){if(this.source._disposed)throw new re;if(this.fileSize!==null&&e+r>this.fileSize)return null;let i=e+r,n=this.source._read(e,i);return n instanceof Promise?n.then(s=>s?new Tr(s.bytes,s.view,s.offset,e,i):null):n?new Tr(n.bytes,n.view,n.offset,e,i):null}requestSliceRange(e,r,i){if(this.source._disposed)throw new re;if(this.fileSize!==null)return this.requestSlice(e,ee(this.fileSize-e,r,i));{let n=this.requestSlice(e,i),s=o=>{if(o)return o;let a=u=>(h(u!==null),this.requestSlice(e,ee(u-e,r,i))),c=this.source._retrieveSize();return c instanceof Promise?c.then(a):a(c)};return n instanceof Promise?n.then(s):s(n)}}},Tr=class t{constructor(e,r,i,n,s){this.bytes=e,this.view=r,this.offset=i,this.start=n,this.end=s,this.bufferPos=n-i}static tempFromBytes(e){return new t(e,V(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,r=this.end-e){if(e<this.start||e+r>this.end)throw new RangeError("Slicing outside of original slice.");return new t(this.bytes,this.view,this.offset,e,e+r)}},ye=(t,e)=>{if(t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)},I=(t,e)=>{ye(t,e);let r=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,r},D=t=>(ye(t,1),t.view.getUint8(t.bufferPos++)),Pr=(t,e)=>{ye(t,2);let r=t.view.getUint16(t.bufferPos,e);return t.bufferPos+=2,r},ne=t=>{ye(t,2);let e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},wt=t=>{ye(t,3);let e=Bt(t.view,t.bufferPos,!1);return t.bufferPos+=3,e},xi=t=>{ye(t,2);let e=t.view.getInt16(t.bufferPos,!1);return t.bufferPos+=2,e},ut=(t,e)=>{ye(t,4);let r=t.view.getUint32(t.bufferPos,e);return t.bufferPos+=4,r},A=t=>{ye(t,4);let e=t.view.getUint32(t.bufferPos,!1);return t.bufferPos+=4,e},Gt=t=>{ye(t,4);let e=t.view.getUint32(t.bufferPos,!0);return t.bufferPos+=4,e},st=t=>{ye(t,4);let e=t.view.getInt32(t.bufferPos,!1);return t.bufferPos+=4,e},Dd=t=>{ye(t,4);let e=t.view.getInt32(t.bufferPos,!0);return t.bufferPos+=4,e},So=(t,e)=>{let r,i;return e?(r=ut(t,!0),i=ut(t,!0)):(i=ut(t,!1),r=ut(t,!1)),i*4294967296+r},ke=t=>{let e=A(t),r=A(t);return e*4294967296+r},iu=t=>{let e=st(t),r=A(t);return e*4294967296+r},yu=t=>{let e=Gt(t);return Dd(t)*4294967296+e},su=t=>{ye(t,4);let e=t.view.getFloat32(t.bufferPos,!1);return t.bufferPos+=4,e},Un=t=>{ye(t,8);let e=t.view.getFloat64(t.bufferPos,!1);return t.bufferPos+=8,e},j=(t,e)=>{ye(t,e);let r="";for(let i=0;i<e;i++)r+=String.fromCharCode(t.bytes[t.bufferPos++]);return r};var vo=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;var Vu=t=>{let e=Math.floor(t/36e5),r=Math.floor(t%(3600*1e3)/(60*1e3)),i=Math.floor(t%(60*1e3)/1e3),n=t%1e3;return e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};var Pi=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let r=0;r<e.length;r++)this.helperView.setUint8(r%8,e.charCodeAt(r)),r%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let r=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let s of e.children)s&&this.writeBox(s);let i=this.writer.getPos(),n=e.size??i-r;this.writer.seek(r),this.writeBoxHeader(e,n),this.writer.seek(i)}}writeBoxHeader(e,r){this.writeU32(e.largeSize?1:r),this.writeAscii(e.type),e.largeSize&&this.writeU64(r)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let r=this.offsets.get(e);h(r!==void 0);let i=this.writer.getPos();this.writer.seek(r),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let r=this.measureBoxHeader(e);if(e.contents&&(r+=e.contents.byteLength),e.children)for(let i of e.children)i&&(r+=this.measureBox(i));return r}}},z=new Uint8Array(8),Ge=new DataView(z.buffer),$=t=>[(t%256+256)%256],R=t=>(Ge.setUint16(0,t,!1),[z[0],z[1]]),Hu=t=>(Ge.setInt16(0,t,!1),[z[0],z[1]]),Wu=t=>(Ge.setUint32(0,t,!1),[z[1],z[2],z[3]]),C=t=>(Ge.setUint32(0,t,!1),[z[0],z[1],z[2],z[3]]),kt=t=>(Ge.setInt32(0,t,!1),[z[0],z[1],z[2],z[3]]),Qt=t=>(Ge.setUint32(0,Math.floor(t/2**32),!1),Ge.setUint32(4,t,!1),[z[0],z[1],z[2],z[3],z[4],z[5],z[6],z[7]]),Gu=t=>(Ge.setInt16(0,2**8*t,!1),[z[0],z[1]]),lt=t=>(Ge.setInt32(0,2**16*t,!1),[z[0],z[1],z[2],z[3]]),_o=t=>(Ge.setInt32(0,2**30*t,!1),[z[0],z[1],z[2],z[3]]),Po=(t,e)=>{let r=[],i=t;do{let n=i&127;i>>=7,r.length>0&&(n|=128),r.push(n),e!==void 0&&e--}while(i>0||e);return r.reverse()},fe=(t,e=!1)=>{let r=Array(t.length).fill(null).map((i,n)=>t.charCodeAt(n));return e&&r.push(0),r},Io=t=>{let e=null;for(let r of t)(!e||r.timestamp>e.timestamp)&&(e=r);return e},ju=t=>{let e=t*(Math.PI/180),r=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[r,i,0,-i,r,0,0,0,1]},$u=ju(0),Qu=t=>[lt(t[0]),lt(t[1]),_o(t[2]),lt(t[3]),lt(t[4]),_o(t[5]),lt(t[6]),lt(t[7]),_o(t[8])],O=(t,e,r)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:r}),q=(t,e,r,i,n)=>O(t,[$(e),Wu(r),i??[]],n),Xu=t=>t.isQuickTime?O("ftyp",[fe("qt "),C(512),fe("qt ")]):t.fragmented?O("ftyp",[fe("iso5"),C(512),fe("iso5"),fe("iso6"),fe("mp41")]):O("ftyp",[fe("isom"),C(512),fe("isom"),t.holdsAvc?fe("avc1"):[],fe("mp41")]),Di=t=>({type:"mdat",largeSize:t}),Ku=t=>({type:"free",size:t}),Br=t=>O("moov",void 0,[Id(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>Fd(e,t.creationTime)),t.isFragmented?hf(t.trackDatas):null,Sf(t)]),Id=(t,e)=>{let r=se(Math.max(0,...e.filter(o=>o.samples.length>0).map(o=>{let a=Io(o.samples);return a.timestamp+a.duration})),us),i=Math.max(0,...e.map(o=>o.track.id))+1,n=!_t(t)||!_t(r),s=n?Qt:C;return q("mvhd",+n,0,[s(t),s(t),C(us),s(r),lt(1),Gu(1),Array(10).fill(0),Qu($u),Array(24).fill(0),C(i)])},Fd=(t,e)=>{let r=sl(t);return O("trak",void 0,[Bd(t,e),Rd(t,e),r.name!==void 0?O("udta",void 0,[O("name",[...we.encode(r.name)])]):null])},Bd=(t,e)=>{let r=Io(t.samples),i=se(r?r.timestamp+r.duration:0,us),n=!_t(e)||!_t(i),s=n?Qt:C,o;if(t.type==="video"){let c=t.track.metadata.rotation;o=ju(c??0)}else o=$u;let a=2;return t.track.metadata.disposition?.default!==!1&&(a|=1),q("tkhd",+n,a,[s(e),s(e),C(t.track.id),C(0),s(i),Array(8).fill(0),R(0),R(t.track.id),Gu(t.type==="audio"?1:0),R(0),Qu(o),lt(t.type==="video"?t.info.width:0),lt(t.type==="video"?t.info.height:0)])},Rd=(t,e)=>O("mdia",void 0,[Od(t,e),Fo(!0,Nd[t.type],Md[t.type]),Ud(t)]),Od=(t,e)=>{let r=Io(t.samples),i=se(r?r.timestamp+r.duration:0,t.timescale),n=!_t(e)||!_t(i),s=n?Qt:C;return q("mdhd",+n,0,[s(e),s(e),C(t.timescale),s(i),R(nl(t.track.metadata.languageCode??Z)),R(0)])},Nd={video:"vide",audio:"soun",subtitle:"text"},Md={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Fo=(t,e,r,i="\0\0\0\0")=>q("hdlr",0,0,[t?fe("mhlr"):C(0),fe(e),fe(i),C(0),C(0),fe(r,!0)]),Ud=t=>O("minf",void 0,[qd[t.type](),Hd(),jd(t)]),zd=()=>q("vmhd",0,1,[R(0),R(0),R(0),R(0)]),Vd=()=>q("smhd",0,0,[R(0),R(0)]),Ld=()=>q("nmhd",0,0),qd={video:zd,audio:Vd,subtitle:Ld},Hd=()=>O("dinf",void 0,[Wd()]),Wd=()=>q("dref",0,0,[C(1)],[Gd()]),Gd=()=>q("url ",0,1),jd=t=>{let e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(r=>r.sampleCompositionTimeOffset!==0);return O("stbl",void 0,[$d(t),af(t),e?ff(t):null,e?mf(t):null,uf(t),lf(t),df(t),cf(t)])},$d=t=>{let e;if(t.type==="video")e=Qd(vf(t.track.source._codec,t.info.decoderConfig.codec),t);else if(t.type==="audio"){let r=il(t.track.source._codec,t.muxer.isQuickTime);h(r),e=Jd(r,t)}else t.type==="subtitle"&&(e=sf(Df[t.track.source._codec],t));return h(e),q("stsd",0,0,[C(1)],[e])},Qd=(t,e)=>O(t,[Array(6).fill(0),R(1),R(0),R(0),Array(12).fill(0),R(e.info.width),R(e.info.height),C(4718592),C(4718592),C(0),R(1),Array(32).fill(0),R(24),Hu(65535)],[_f[e.track.source._codec](e),sc(e.info.decoderConfig.colorSpace)?Xd(e):null]),Xd=t=>O("colr",[fe("nclx"),R(Pt[t.info.decoderConfig.colorSpace.primaries]),R(Dt[t.info.decoderConfig.colorSpace.transfer]),R(It[t.info.decoderConfig.colorSpace.matrix]),$((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Kd=t=>t.info.decoderConfig&&O("avcC",[...J(t.info.decoderConfig.description)]),Yd=t=>t.info.decoderConfig&&O("hvcC",[...J(t.info.decoderConfig.description)]),Lu=t=>{if(!t.info.decoderConfig)return null;let e=t.info.decoderConfig,r=e.codec.split("."),i=Number(r[1]),n=Number(r[2]),s=Number(r[3]),o=r[4]?Number(r[4]):1,a=r[8]?Number(r[8]):Number(e.colorSpace?.fullRange??0),c=(s<<4)+(o<<1)+a,u=r[5]?Number(r[5]):e.colorSpace?.primaries?Pt[e.colorSpace.primaries]:2,l=r[6]?Number(r[6]):e.colorSpace?.transfer?Dt[e.colorSpace.transfer]:2,d=r[7]?Number(r[7]):e.colorSpace?.matrix?It[e.colorSpace.matrix]:2;return q("vpcC",1,0,[$(i),$(n),$(c),$(u),$(l),$(d),R(0)])},Zd=t=>O("av1C",Sc(t.info.decoderConfig.codec)),Jd=(t,e)=>{let r=0,i,n=16;if(Y.includes(e.track.source._codec)){let s=e.track.source._codec,{sampleSize:o}=Te(s);n=8*o,n>16&&(r=1)}return r===0?i=[Array(6).fill(0),R(1),R(r),R(0),C(0),R(e.info.numberOfChannels),R(n),R(0),R(0),R(e.info.sampleRate<2**16?e.info.sampleRate:0),R(0)]:i=[Array(6).fill(0),R(1),R(r),R(0),C(0),R(e.info.numberOfChannels),R(Math.min(n,16)),R(0),R(0),R(e.info.sampleRate<2**16?e.info.sampleRate:0),R(0),C(1),C(n/8),C(e.info.numberOfChannels*n/8),C(2)],O(t,i,[Pf(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Do=t=>{let e;switch(t.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source._codec}`)}let r=[...$(e),...$(21),...Wu(0),...C(0),...C(0)];if(t.info.decoderConfig.description){let i=J(t.info.decoderConfig.description);r=[...r,...$(5),...Po(i.byteLength),...i]}return r=[...R(1),...$(0),...$(4),...Po(r.length),...r,...$(6),...$(1),...$(2)],r=[...$(3),...Po(r.length),...r],q("esds",0,0,r)},Tt=t=>O("wave",void 0,[ef(t),tf(t),O("\0\0\0\0")]),ef=t=>O("frma",[fe(il(t.track.source._codec,t.muxer.isQuickTime))]),tf=t=>{let{littleEndian:e}=Te(t.track.source._codec);return O("enda",[R(+e)])},rf=t=>{let e=t.info.numberOfChannels,r=3840,i=t.info.sampleRate,n=0,s=0,o=new Uint8Array(0),a=t.info.decoderConfig?.description;if(a){h(a.byteLength>=18);let c=J(a),u=Pn(c);e=u.outputChannelCount,r=u.preSkip,i=u.inputSampleRate,n=u.outputGain,s=u.channelMappingFamily,u.channelMappingTable&&(o=u.channelMappingTable)}return O("dOps",[$(0),$(e),R(r),C(i),Hu(n),$(s),...o])},nf=t=>{let e=t.info.decoderConfig?.description;h(e);let r=J(e);return q("dfLa",0,0,[...r.subarray(4)])},He=t=>{let{littleEndian:e,sampleSize:r}=Te(t.track.source._codec),i=+e;return q("pcmC",0,0,[$(i),$(8*r)])},sf=(t,e)=>O(t,[Array(6).fill(0),R(1)],[If[e.track.source._codec](e)]),of=t=>O("vttC",[...we.encode(t.info.config.description)]);var af=t=>q("stts",0,0,[C(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[C(e.sampleCount),C(e.sampleDelta)])]),cf=t=>{if(t.samples.every(r=>r.type==="key"))return null;let e=[...t.samples.entries()].filter(([,r])=>r.type==="key");return q("stss",0,0,[C(e.length),e.map(([r])=>C(r+1))])},uf=t=>q("stsc",0,0,[C(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[C(e.firstChunk),C(e.samplesPerChunk),C(1)])]),lf=t=>{if(t.type==="audio"&&t.info.requiresPcmTransformation){let{sampleSize:e}=Te(t.track.source._codec);return q("stsz",0,0,[C(e*t.info.numberOfChannels),C(t.samples.reduce((r,i)=>r+se(i.duration,t.timescale),0))])}return q("stsz",0,0,[C(0),C(t.samples.length),t.samples.map(e=>C(e.size))])},df=t=>t.finalizedChunks.length>0&&G(t.finalizedChunks).offset>=2**32?q("co64",0,0,[C(t.finalizedChunks.length),t.finalizedChunks.map(e=>Qt(e.offset))]):q("stco",0,0,[C(t.finalizedChunks.length),t.finalizedChunks.map(e=>C(e.offset))]),ff=t=>q("ctts",1,0,[C(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[C(e.sampleCount),kt(e.sampleCompositionTimeOffset)])]),mf=t=>{let e=1/0,r=-1/0,i=1/0,n=-1/0;h(t.compositionTimeOffsetTable.length>0),h(t.samples.length>0);for(let o=0;o<t.compositionTimeOffsetTable.length;o++){let a=t.compositionTimeOffsetTable[o];e=Math.min(e,a.sampleCompositionTimeOffset),r=Math.max(r,a.sampleCompositionTimeOffset)}for(let o=0;o<t.samples.length;o++){let a=t.samples[o];i=Math.min(i,se(a.timestamp,t.timescale)),n=Math.max(n,se(a.timestamp+a.duration,t.timescale))}let s=Math.max(-e,0);return n>=2**31?null:q("cslg",0,0,[kt(s),kt(e),kt(r),kt(i),kt(n)])},hf=t=>O("mvex",void 0,t.map(pf)),pf=t=>q("trex",0,0,[C(t.track.id),C(1),C(0),C(0),C(0)]),Bo=(t,e)=>O("moof",void 0,[gf(t),...e.map(bf)]),gf=t=>q("mfhd",0,0,[C(t)]),Yu=t=>{let e=0,r=0,i=0,n=0,s=t.type==="delta";return r|=+s,s?e|=1:e|=2,e<<24|r<<16|i<<8|n},bf=t=>O("traf",void 0,[wf(t),xf(t),yf(t)]),wf=t=>{h(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;let r=t.currentChunk.samples[1]??t.currentChunk.samples[0],i={duration:r.timescaleUnitsToNextSample,size:r.size,flags:Yu(r)};return q("tfhd",0,e,[C(t.track.id),C(i.duration),C(i.size),C(i.flags)])},xf=t=>(h(t.currentChunk),q("tfdt",1,0,[Qt(se(t.currentChunk.startTimestamp,t.timescale))])),yf=t=>{h(t.currentChunk);let e=t.currentChunk.samples.map(g=>g.timescaleUnitsToNextSample),r=t.currentChunk.samples.map(g=>g.size),i=t.currentChunk.samples.map(Yu),n=t.currentChunk.samples.map(g=>se(g.timestamp-g.decodeTimestamp,t.timescale)),s=new Set(e),o=new Set(r),a=new Set(i),c=new Set(n),u=a.size===2&&i[0]!==i[1],l=s.size>1,d=o.size>1,f=!u&&a.size>1,m=c.size>1||[...c].some(g=>g!==0),p=0;return p|=1,p|=4*+u,p|=256*+l,p|=512*+d,p|=1024*+f,p|=2048*+m,q("trun",1,p,[C(t.currentChunk.samples.length),C(t.currentChunk.offset-t.currentChunk.moofOffset||0),u?C(i[0]):[],t.currentChunk.samples.map((g,b)=>[l?C(e[b]):[],d?C(r[b]):[],f?C(i[b]):[],m?kt(n[b]):[]])])},Zu=t=>O("mfra",void 0,[...t.map(Tf),kf()]),Tf=(t,e)=>q("tfra",1,0,[C(t.track.id),C(63),C(t.finalizedChunks.length),t.finalizedChunks.map(i=>[Qt(se(i.samples[0].timestamp,t.timescale)),Qt(i.moofOffset),C(e+1),C(1),C(1)])]),kf=()=>q("mfro",0,0,[C(0)]),Ju=()=>O("vtte"),el=(t,e,r,i,n)=>O("vttc",void 0,[n!==null?O("vsid",[kt(n)]):null,r!==null?O("iden",[...we.encode(r)]):null,e!==null?O("ctim",[...we.encode(Vu(e))]):null,i!==null?O("sttg",[...we.encode(i)]):null,O("payl",[...we.encode(t)])]),tl=t=>O("vtta",[...we.encode(t)]),Sf=t=>{let e=[],r=t.format._options.metadataFormat??"auto",i=t.output._metadataTags;if(r==="mdir"||r==="auto"&&!t.isQuickTime){let n=Ef(i);n&&e.push(n)}else if(r==="mdta"){let n=Af(i);n&&e.push(n)}else(r==="udta"||r==="auto"&&t.isQuickTime)&&Cf(e,t.output._metadataTags);return e.length===0?null:O("udta",void 0,e)},Cf=(t,e)=>{for(let{key:r,value:i}of ci(e))switch(r){case"title":t.push(We("\xA9nam",i));break;case"description":t.push(We("\xA9des",i));break;case"artist":t.push(We("\xA9ART",i));break;case"album":t.push(We("\xA9alb",i));break;case"albumArtist":t.push(We("albr",i));break;case"genre":t.push(We("\xA9gen",i));break;case"date":t.push(We("\xA9day",i.toISOString().slice(0,10)));break;case"comment":t.push(We("\xA9cmt",i));break;case"lyrics":t.push(We("\xA9lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:ue(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||r.length!==4||t.some(n=>n.type===r)||(typeof i=="string"?t.push(We(r,i)):i instanceof Uint8Array&&t.push(O(r,Array.from(i))))}},We=(t,e)=>{let r=we.encode(e);return O(t,[R(r.length),R(nl("und")),Array.from(r)])},qu={"image/jpeg":13,"image/png":14,"image/bmp":27},rl=(t,e)=>{let r=[];for(let{key:i,value:n}of ci(t))switch(i){case"title":r.push({key:e?"title":"\xA9nam",value:Oe(n)});break;case"description":r.push({key:e?"description":"\xA9des",value:Oe(n)});break;case"artist":r.push({key:e?"artist":"\xA9ART",value:Oe(n)});break;case"album":r.push({key:e?"album":"\xA9alb",value:Oe(n)});break;case"albumArtist":r.push({key:e?"album_artist":"aART",value:Oe(n)});break;case"comment":r.push({key:e?"comment":"\xA9cmt",value:Oe(n)});break;case"genre":r.push({key:e?"genre":"\xA9gen",value:Oe(n)});break;case"lyrics":r.push({key:e?"lyrics":"\xA9lyr",value:Oe(n)});break;case"date":r.push({key:e?"date":"\xA9day",value:Oe(n.toISOString().slice(0,10))});break;case"images":for(let s of n)s.kind==="coverFront"&&r.push({key:"covr",value:O("data",[C(qu[s.mimeType]??0),C(0),Array.from(s.data)])});break;case"trackNumber":if(e){let s=t.tracksTotal!==void 0?`${n}/${t.tracksTotal}`:n.toString();r.push({key:"track",value:Oe(s)})}else r.push({key:"trkn",value:O("data",[C(0),C(0),R(0),R(n),R(t.tracksTotal??0),R(0)])});break;case"discNumber":e||r.push({key:"disc",value:O("data",[C(0),C(0),R(0),R(n),R(t.discsTotal??0),R(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ue(i)}if(t.raw)for(let i in t.raw){let n=t.raw[i];n==null||!e&&i.length!==4||r.some(s=>s.key===i)||(typeof n=="string"?r.push({key:i,value:Oe(n)}):n instanceof Uint8Array?r.push({key:i,value:O("data",[C(0),C(0),Array.from(n)])}):n instanceof Pe&&r.push({key:i,value:O("data",[C(qu[n.mimeType]??0),C(0),Array.from(n.data)])}))}return r},Ef=t=>{let e=rl(t,!1);return e.length===0?null:q("meta",0,0,void 0,[Fo(!1,"mdir","","appl"),O("ilst",void 0,e.map(r=>O(r.key,void 0,[r.value])))])},Af=t=>{let e=rl(t,!0);return e.length===0?null:O("meta",void 0,[Fo(!1,"mdta",""),q("keys",0,0,[C(e.length)],e.map(r=>O("mdta",[...we.encode(r.key)]))),O("ilst",void 0,e.map((r,i)=>{let n=String.fromCharCode(...C(i+1));return O(n,void 0,[r.value])}))])},Oe=t=>O("data",[C(1),C(0),...we.encode(t)]),vf=(t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},_f={avc:Kd,hevc:Yd,vp8:Lu,vp9:Lu,av1:Zd},il=(t,e)=>{switch(t){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt"}if(e)switch(t){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(t){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},Pf=(t,e)=>{switch(t){case"aac":return Do;case"mp3":return Do;case"opus":return rf;case"vorbis":return Do;case"flac":return nf}if(e)switch(t){case"pcm-s24":return Tt;case"pcm-s24be":return Tt;case"pcm-s32":return Tt;case"pcm-s32be":return Tt;case"pcm-f32":return Tt;case"pcm-f32be":return Tt;case"pcm-f64":return Tt;case"pcm-f64be":return Tt}else switch(t){case"pcm-s16":return He;case"pcm-s16be":return He;case"pcm-s24":return He;case"pcm-s24be":return He;case"pcm-s32":return He;case"pcm-s32be":return He;case"pcm-f32":return He;case"pcm-f32be":return He;case"pcm-f64":return He;case"pcm-f64be":return He}return null},Df={webvtt:"wvtt"},If={webvtt:of},nl=t=>{h(t.length===3);let e=0;for(let r=0;r<3;r++)e<<=5,e+=t.charCodeAt(r)-96;return e};var ls=class{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let r=this.getPos();if(r<this.trackedStart){if(r+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-r),r=0}let i=r+e.byteLength-this.trackedStart,n=this.trackedWrites.byteLength;for(;n<i;)n*=2;if(n!==this.trackedWrites.byteLength){let s=new Uint8Array(n);s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,r-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,r+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");let r={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,r}},Ro=2**16,Oo=2**32,Rr=class extends ls{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(Ro,{maxByteLength:Oo})}catch{this.buffer=new ArrayBuffer(Ro),this.supportsResize=!1}else this.buffer=new ArrayBuffer(Ro);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let r=this.buffer.byteLength;for(;r<e;)r*=2;if(r!==this.buffer.byteLength){if(r>Oo)throw new Error(`ArrayBuffer exceeded maximum size of ${Oo} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(r);else{let i=new ArrayBuffer(r),n=new Uint8Array(i);n.set(this.bytes,0),this.buffer=i,this.bytes=n}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,r){return this.bytes.slice(e,r)}},Ff=2**24,Bf=2,ds=class extends ls{constructor(e){super(),this.pos=0,this.sections=[],this.lastWriteEnd=0,this.lastFlushEnd=0,this.writer=null,this.chunks=[],this.target=e,this.chunked=e._options.chunked??!1,this.chunkSize=e._options.chunkSize??Ff}start(){this.writer=this.target._writable.getWriter()}write(e){if(this.pos>this.lastWriteEnd){let r=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(r))}this.maybeTrackWrites(e),this.sections.push({data:e.slice(),start:this.pos}),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){if(this.pos>this.lastWriteEnd){let i=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(i))}if(h(this.writer),this.sections.length===0)return;let e=[],r=[...this.sections].sort((i,n)=>i.start-n.start);e.push({start:r[0].start,size:r[0].data.byteLength});for(let i=1;i<r.length;i++){let n=e[e.length-1],s=r[i];s.start<=n.start+n.size?n.size=Math.max(n.size,s.start+s.data.byteLength-n.start):e.push({start:s.start,size:s.data.byteLength})}for(let i of e){i.data=new Uint8Array(i.size);for(let n of this.sections)i.start<=n.start&&n.start<i.start+i.size&&i.data.set(n.data,n.start-i.start);if(this.writer.desiredSize!==null&&this.writer.desiredSize<=0&&await this.writer.ready,this.chunked)this.writeDataIntoChunks(i.data,i.start),this.tryToFlushChunks();else{if(this.ensureMonotonicity&&i.start!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:i.data,position:i.start}),this.lastFlushEnd=i.start+i.data.byteLength}}this.sections.length=0}writeDataIntoChunks(e,r){let i=this.chunks.findIndex(c=>c.start<=r&&r<c.start+this.chunkSize);i===-1&&(i=this.createChunk(r));let n=this.chunks[i],s=r-n.start,o=e.subarray(0,Math.min(this.chunkSize-s,e.byteLength));n.data.set(o,s);let a={start:s,end:s+o.byteLength};if(this.insertSectionIntoChunk(n,a),n.written[0].start===0&&n.written[0].end===this.chunkSize&&(n.shouldFlush=!0),this.chunks.length>Bf){for(let c=0;c<this.chunks.length-1;c++)this.chunks[c].shouldFlush=!0;this.tryToFlushChunks()}o.byteLength<e.byteLength&&this.writeDataIntoChunks(e.subarray(o.byteLength),r+o.byteLength)}insertSectionIntoChunk(e,r){let i=0,n=e.written.length-1,s=-1;for(;i<=n;){let o=Math.floor(i+(n-i+1)/2);e.written[o].start<=r.start?(i=o+1,s=o):n=o-1}for(e.written.splice(s+1,0,r),(s===-1||e.written[s].end<r.start)&&s++;s<e.written.length-1&&e.written[s].end>=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}createChunk(e){let i={start:Math.floor(e/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(i),this.chunks.sort((n,s)=>n.start-s.start),this.chunks.indexOf(i)}tryToFlushChunks(e=!1){h(this.writer);for(let r=0;r<this.chunks.length;r++){let i=this.chunks[r];if(!(!i.shouldFlush&&!e)){for(let n of i.written){let s=i.start+n.start;if(this.ensureMonotonicity&&s!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:i.data.subarray(n.start,n.end),position:s}),this.lastFlushEnd=i.start+n.end}this.chunks.splice(r--,1)}}}finalize(){return this.chunked&&this.tryToFlushChunks(!0),h(this.writer),this.writer.close()}async close(){return this.writer?.close()}};var Xt=class{constructor(){this._output=null,this.onwrite=null}},Ii=class extends Xt{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new Rr(this)}},Fi=class extends Xt{constructor(e,r={}){if(super(),!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(r!=null&&typeof r!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(r.chunked!==void 0&&typeof r.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(r.chunkSize!==void 0&&(!Number.isInteger(r.chunkSize)||r.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=r}_createWriter(){return new ds(this)}};var us=1e3,Rf=2082844800,sl=t=>{let e={},r=t.track;return r.metadata.name!==void 0&&(e.name=r.metadata.name),e},se=(t,e,r=!0)=>{let i=t*e;return r?Math.round(i):i},fs=class extends Sn{constructor(e,r){super(e),this.auxTarget=new Ii,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new Pi(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=ce(),this.creationTime=Math.floor(Date.now()/1e3)+Rf,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=r,this.writer=e._writer,this.boxWriter=new Pi(this.writer),this.isQuickTime=r instanceof Or;let i=this.writer instanceof Rr?"in-memory":!1;this.fastStart=r._options.fastStart??i,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=r._options.minimumFragmentDuration??1}async start(){let e=await this.mutex.acquire(),r=this.output._tracks.some(i=>i.type==="video"&&i.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(Xu({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:i,start:n}=this.writer.stopTrackingWrites();this.format._options.onFtyp(i,n)}if(this.ftypSize=this.writer.getPos(),this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let i of this.output._tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Di(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Bn({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,i){let n=this.trackDatas.find(u=>u.track===e);if(n)return n;Pc(i),h(i),h(i.decoderConfig);let s={...i.decoderConfig};h(s.codedWidth!==void 0),h(s.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!s.description){let u=En(r.data);if(!u)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=Oc(u),o=!0}else if(e.source._codec==="hevc"&&!s.description){let u=An(r.data);if(!u)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=Mc(u),o=!0}let a=fc(1/(e.metadata.frameRate??57600),1e6).denominator,c={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,decoderConfig:s,requiresAnnexBTransformation:o},timescale:a,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(c),this.trackDatas.sort((u,l)=>u.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,r){let i=this.trackDatas.find(s=>s.track===e);if(i)return i;Dc(r),h(r),h(r.decoderConfig);let n={muxer:this,track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig,requiresPcmTransformation:!this.isFragmented&&Y.includes(e.source._codec)},timescale:r.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(e,r){let i=this.trackDatas.find(s=>s.track===e);if(i)return i;Ic(r),h(r),h(r.config);let n={muxer:this,track:e,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(e,r,i){let n=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,i),o=r.data;if(s.info.requiresAnnexBTransformation){let u=mr(o);if(u.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=Xs(u,4)}let a=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),c=this.createSampleForTrack(s,o,a,r.duration,r.type);await this.registerSample(s,c)}finally{n()}}async addEncodedAudioPacket(e,r,i){let n=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,i),o=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),a=this.createSampleForTrack(s,r.data,o,r.duration,r.type);s.info.requiresPcmTransformation&&await this.maybePadWithSilence(s,o),await this.registerSample(s,a)}finally{n()}}async maybePadWithSilence(e,r){let i=G(e.samples),n=i?i.timestamp+i.duration:0,s=r-n,o=se(s,e.timescale);if(o>0){let{sampleSize:a,silentValue:c}=Te(e.info.decoderConfig.codec),u=o*e.info.numberOfChannels,l=new Uint8Array(a*u).fill(c),d=this.createSampleForTrack(e,new Uint8Array(l.buffer),n,s,"key");await this.registerSample(e,d)}}async addSubtitleCue(e,r,i){let n=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,i);this.validateAndNormalizeTimestamp(s.track,r.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{n()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){let i=new Set([]);for(let u of e.cueQueue)h(u.timestamp<=r),h(e.lastCueEndTimestamp<=u.timestamp+u.duration),i.add(Math.max(u.timestamp,e.lastCueEndTimestamp)),i.add(u.timestamp+u.duration);let n=[...i].sort((u,l)=>u-l),s=n[0],o=n[1]??s;if(r<o)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let u=Ju();this.auxBoxWriter.writeBox(u);let l=this.auxWriter.getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,l,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let u=0;u<e.cueQueue.length;u++){let l=e.cueQueue[u];if(l.timestamp>=o)break;vo.lastIndex=0;let d=vo.test(l.text),f=l.timestamp+l.duration,m=e.cueToSourceId.get(l);if(m===void 0&&o<f&&(m=e.nextSourceId++,e.cueToSourceId.set(l,m)),l.notes){let g=tl(l.notes);this.auxBoxWriter.writeBox(g)}let p=el(l.text,d?s:null,l.identifier??null,l.settings??null,m??null);this.auxBoxWriter.writeBox(p),f===o&&e.cueQueue.splice(u--,1)}let a=this.auxWriter.getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,a,s,o-s,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=o}}createSampleForTrack(e,r,i,n,s){return{timestamp:i,decodeTimestamp:i,duration:n,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:se(n,e.timescale)}}processTimestamps(e,r){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){let n=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){let o=e.timestampProcessingQueue[s],a=se(o.duration,e.timescale);n+=a}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{let s=G(e.timeToSampleTable);s.sampleCount+=n}e.timestampProcessingQueue.length=0;return}let i=e.timestampProcessingQueue.map(n=>n.timestamp).sort((n,s)=>n-s);for(let n=0;n<e.timestampProcessingQueue.length;n++){let s=e.timestampProcessingQueue[n];s.decodeTimestamp=i[n],!this.isFragmented&&e.lastTimescaleUnits===null&&(s.decodeTimestamp=0);let o=se(s.timestamp-s.decodeTimestamp,e.timescale),a=se(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){h(e.lastSample);let c=se(s.decodeTimestamp,e.timescale,!1),u=Math.round(c-e.lastTimescaleUnits);if(h(u>=0),e.lastTimescaleUnits+=u,e.lastSample.timescaleUnitsToNextSample=u,!this.isFragmented){let l=G(e.timeToSampleTable);if(h(l),l.sampleCount===1){l.sampleDelta=u;let f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===u&&(f.sampleCount++,e.timeToSampleTable.pop(),l=f)}else l.sampleDelta!==u&&(l.sampleCount--,e.timeToSampleTable.push(l={sampleCount:1,sampleDelta:u}));l.sampleDelta===a?l.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let d=G(e.compositionTimeOffsetTable);h(d),d.sampleCompositionTimeOffset===o?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=se(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,h(e.lastSample),h(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){h(r.type==="key");let n=se(r.timestamp,e.timescale,!1),s=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,r){r.type==="key"&&this.processTimestamps(e,r),e.timestampProcessingQueue.push(r),this.isFragmented?(e.sampleQueue.push(r),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,r):await this.addSampleToTrack(e,r)}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),this.fastStart==="reserve")){let n=e.track.metadata.maximumPacketCount;if(h(n!==void 0),e.samples.length>n)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${n}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,r.timestamp);let n=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(o=>{if(e===o)return r.type==="key";let a=o.sampleQueue[0];return a?a.type==="key":o.track.source._closed});n>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=n>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),h(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){if(h(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce((i,n)=>i+se(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||G(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let i of e.currentChunk.samples)h(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(h(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,i=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.track.source._closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<i&&(r=s,i=s.sampleQueue[0].timestamp)}if(!r)break;let n=r.sampleQueue.shift();await this.addSampleToTrack(r,n)}}async finalizeFragment(e=!0){h(this.isFragmented);let r=this.nextFragmentNumber++;if(r===1){this.format._options.onMoov&&this.writer.startTrackingWrites();let m=Br(this);if(this.boxWriter.writeBox(m),this.format._options.onMoov){let{data:p,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoov(p,g)}}let i=this.trackDatas.filter(m=>m.currentChunk),n=Bo(r,i),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(n),a=o+De,c=1/0;for(let m of i){m.currentChunk.offset=a,m.currentChunk.moofOffset=s;for(let p of m.currentChunk.samples)a+=p.size;c=Math.min(c,m.currentChunk.startTimestamp)}let u=a-o,l=u>=2**32;if(l)for(let m of i)m.currentChunk.offset+=it-De;this.format._options.onMoof&&this.writer.startTrackingWrites();let d=Bo(r,i);if(this.boxWriter.writeBox(d),this.format._options.onMoof){let{data:m,start:p}=this.writer.stopTrackingWrites();this.format._options.onMoof(m,p,c)}h(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();let f=Di(l);f.size=u,this.boxWriter.writeBox(f),this.writer.seek(o+(l?it:De));for(let m of i)for(let p of m.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.format._options.onMdat){let{data:m,start:p}=this.writer.stopTrackingWrites();this.format._options.onMdat(m,p)}for(let m of i)m.finalizedChunks.push(m.currentChunk),this.finalizedChunks.push(m.currentChunk),m.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){if(this.allTracksAreKnown()){if(!this.mdat){let i=Br(this),s=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;h(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Di(!0),this.boxWriter.writeBox(this.mdat);for(let o of this.trackDatas){for(let a of o.sampleQueue)await this.addSampleToTrack(o,a);o.sampleQueue.length=0}}await this.addSampleToTrack(e,r)}else e.sampleQueue.push(r)}computeSampleTableSizeUpperBound(){h(this.fastStart==="reserve");let e=0;for(let r of this.trackDatas){let i=r.track.metadata.maximumPacketCount;h(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){let r=await this.mutex.acquire();if(e.type==="subtitle"&&e.source._codec==="webvtt"){let i=this.trackDatas.find(n=>n.track===e);i&&await this.processWebVTTCues(i,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(let r of this.trackDatas)this.processTimestamps(r);await this.finalizeFragment(!1)}else for(let r of this.trackDatas)this.processTimestamps(r),await this.finalizeCurrentChunk(r);if(this.fastStart==="in-memory"){this.mdat=Di(!1);let r;for(let n=0;n<2;n++){let s=Br(this),o=this.boxWriter.measureBox(s);r=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+o+r;for(let c of this.finalizedChunks){c.offset=a;for(let{data:u}of c.samples)h(u),a+=u.byteLength,r+=u.byteLength}if(a<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let i=Br(this);if(this.boxWriter.writeBox(i),this.format._options.onMoov){let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let n of this.finalizedChunks)for(let s of n.samples)h(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,s)}}else if(this.isFragmented){let r=this.writer.getPos(),i=Zu(this.trackDatas);this.boxWriter.writeBox(i);let n=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{h(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);h(r!==void 0);let i=this.writer.getPos()-r;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,o)}let n=Br(this);if(this.fastStart==="reserve"){h(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Ku(s))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.format._options.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,o)}}e()}};var Nr=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>qe.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>et.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Nt.includes(e))}_codecUnsupportedHint(e){return""}},Bi=class extends Nr{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new fs(e,this)}},Mr=class extends Bi{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...qe,...js,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Nt]}_codecUnsupportedHint(e){return new Or().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},Or=class extends Bi{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...qe,...et]}_codecUnsupportedHint(e){return new Mr().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}};var ol=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!qe.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${qe.join(", ")}.`);if(!(t.bitrate instanceof Ur)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(t.keyFrameInterval!==void 0&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(t.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");Of(t.codec,t)},Of=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&$s(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},al=t=>{let e=t.bitrate instanceof Ur?t.bitrate._toVideoBitrate(t.codec,t.width,t.height):t.bitrate;return{codec:t.fullCodecString??kc(t.codec,t.width,t.height,e),width:t.width,height:t.height,bitrate:e,bitrateMode:t.bitrateMode,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...vc(t.codec)}},cl=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!et.includes(t.codec))throw new TypeError(`Invalid audio codec '${t.codec}'. Must be one of: ${et.join(", ")}.`);if(t.bitrate===void 0&&(!Y.includes(t.codec)||t.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(t.bitrate!==void 0&&!(t.bitrate instanceof Ur)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");Nf(t.codec,t)},Nf=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&$s(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`)},ul=t=>{let e=t.bitrate instanceof Ur?t.bitrate._toAudioBitrate(t.codec):t.bitrate;return{codec:t.fullCodecString??Cc(t.codec,t.numberOfChannels,t.sampleRate),numberOfChannels:t.numberOfChannels,sampleRate:t.sampleRate,bitrate:e,bitrateMode:t.bitrateMode,..._c(t.codec)}},Ur=class{constructor(e){this._factor=e}_toVideoBitrate(e,r,i){let n=r*i,s={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},o=1920*1080,a=3e6,c=Math.pow(n/o,.95),d=a*c*s[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(Y.includes(e)||e==="flac")return;let i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!i)throw new Error(`Unhandled codec: ${e}`);let n=i*this._factor;return e==="aac"?n=[96e3,128e3,16e4,192e3].reduce((o,a)=>Math.abs(a-n)<Math.abs(o-n)?a:o):e==="opus"||e==="vorbis"?n=Math.max(6e3,n):e==="mp3"&&(n=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((o,a)=>Math.abs(a-n)<Math.abs(o-n)?a:o)),Math.round(n/1e3)*1e3}};var zr=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise?this._closingPromise:this._flushAndClose(e)}},Vr=class extends zr{constructor(e){if(super(),this._connectedTrack=null,!qe.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${qe.join(", ")}.`);this._codec=e}};var No=class{constructor(e,r){this.source=e,this.encodingConfig=r,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new ht,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorNeedsNewStack=!0}async add(e,r,i){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){let a=this.encodingConfig.sizeChangeBehavior??"deny";if(a!=="passThrough"){if(a==="deny")throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'strict' in the encoding options.`);{let c=!1;this.resizeCanvas||(typeof document<"u"?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),c=!0);let u=this.resizeCanvas.getContext("2d",{alpha:dr()});h(u),c||(dr()?(u.fillStyle="black",u.fillRect(0,0,this.codedWidth,this.codedHeight)):u.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(u,{fit:a}),r&&e.close(),e=new Ee(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),r=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),h(this.encoderInitialized);let n=this.encodingConfig.keyFrameInterval??5,s=Math.floor(e.timestamp/n),o={...i,keyFrame:i?.keyFrame||n===0||s!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=s,this.customEncoder){this.customEncoderQueueSize++;let a=e.clone(),c=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(a,o)).then(()=>this.customEncoderQueueSize--).catch(u=>this.error??=u).finally(()=>{a.close()});this.customEncoderQueueSize>=4&&await c}else{h(this.encoder);let a=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(a,o),a.close();else if(!!a.format&&!a.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(a,o),a.close();else{let u=a.displayWidth,l=a.displayHeight;if(!this.splitter)try{this.splitter=new Mo(u,l)}catch(d){console.error("Due to an error, only color data will be encoded.",d),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(a,o),a.close()}if(this.splitter){let d=this.splitter.extractColor(a),f=this.splitter.extractAlpha(a);this.alphaFrameQueue.push(f),this.encoder.encode(d,o),d.close(),a.close()}}r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(c=>this.encoder.addEventListener("dequeue",c,{once:!0}))}await this.muxer.mutex.currentPromise}finally{r&&e.close()}}ensureEncoder(e){let r=new Error;this.ensureEncoderPromise=(async()=>{let i=al({width:e.codedWidth,height:e.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(i);let n=Lc.find(s=>s.supports(this.encodingConfig.codec,i));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(s,o)=>{if(!(s instanceof L))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(o!==void 0&&(!o||typeof o!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(s,o),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,s,o).catch(a=>{this.error??=a,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(i.alpha="discard",this.encodingConfig.alpha==="keep"&&(i.latencyMode="quality"),(i.width%2===1||i.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${i.width}x${i.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.width}x${i.height}, hardware acceleration: ${i.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let a=[],c=[],u=0,l=0,d=(f,m,p)=>{let g={};if(m){let w=new Uint8Array(m.byteLength);m.copyTo(w),g.alpha=w}let b=L.fromEncodedChunk(f,g);this.encodingConfig.onEncodedPacket?.(b,p),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,b,p).catch(w=>{this.error??=w,this.errorNeedsNewStack=!1})};this.encoder=new VideoEncoder({output:(f,m)=>{if(!this.alphaEncoder){d(f,null,m);return}let p=this.alphaFrameQueue.shift();h(p!==void 0),p?(this.alphaEncoder.encode(p,{keyFrame:f.type==="key"}),l++,p.close(),a.push({chunk:f,meta:m})):l===0?d(f,null,m):(c.push(u+l),a.push({chunk:f,meta:m}))},error:f=>{f.stack=r.stack,this.error??=f}}),this.encoder.configure(i),this.encodingConfig.alpha==="keep"&&(this.alphaEncoder=new VideoEncoder({output:(f,m)=>{l--;let p=a.shift();for(h(p!==void 0),d(p.chunk,f,p.meta),u++;c.length>0&&c[0]===u;){c.shift();let g=a.shift();h(g!==void 0),d(g.chunk,null,g.meta)}},error:f=>{f.stack=r.stack,this.error??=f}}),this.alphaEncoder.configure(i))}h(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(r=>r?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}},Mo=class{constructor(e,r){this.lastFrame=null,typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,r):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=r);let i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
29
|
+
`),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,r),this.gl.linkProgram(i),i}createShader(e,r){let i=this.gl.createShader(e);return this.gl.shaderSource(i,r),this.gl.compileShader(i),i}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let r=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.STATIC_DRAW);let s=this.gl.getAttribLocation(this.program,"a_position"),n=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,r){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},Fr=class extends Ar{constructor(e){if(!(e instanceof Ve))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let i=this._track.codec,s=this._track.rotation,n=await this._track.getDecoderConfig(),a=this._track.timeResolution;return m(i&&n),new Vs(e,r,i,n,s,a)}_createPacketSink(){return new _t(this._track)}async getSample(e){Ct(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}};var Ws=class extends vr{constructor(e,r,i,s){super(e,r),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Xe,this.customDecoderQueueSize=0,this.currentTimestamp=null;let n=o=>{(this.currentTimestamp===null||Math.abs(o.timestamp-this.currentTimestamp)>=o.duration)&&(this.currentTimestamp=o.timestamp);let c=this.currentTimestamp;if(this.currentTimestamp+=o.duration,o.numberOfFrames===0){o.close();return}let l=s.sampleRate;o.setTimestamp(Math.round(c*l)/l),e(o)},a=Bi.find(o=>o.supports(i,s));if(a)this.customDecoder=new a,this.customDecoder.codec=i,this.customDecoder.config=s,this.customDecoder.onSample=o=>{if(!(o instanceof we))throw new TypeError("The argument passed to onSample must be an AudioSample.");n(o)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let o=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:c=>{try{n(new we(c))}catch(l){this.onError(l)}},error:c=>{c.stack=o,this.onError(c)}}),this.decoder.configure(s)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(m(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(m(this.decoder),this.decoder.close())}},Hs=class extends vr{constructor(e,r,i){super(e,r),this.decoderConfig=i,this.currentTimestamp=null,m(Q.includes(i.codec)),this.codec=i.codec;let{dataType:s,sampleSize:n,littleEndian:a}=fe(this.codec);switch(this.inputSampleSize=n,n){case 1:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint8(c)-2**7:s==="signed"?this.readInputValue=(o,c)=>o.getInt8(c):s==="ulaw"?this.readInputValue=(o,c)=>va(o.getUint8(c)):s==="alaw"?this.readInputValue=(o,c)=>Fa(o.getUint8(c)):m(!1);break;case 2:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint16(c,a)-2**15:s==="signed"?this.readInputValue=(o,c)=>o.getInt16(c,a):m(!1);break;case 3:s==="unsigned"?this.readInputValue=(o,c)=>pt(o,c,a)-2**23:s==="signed"?this.readInputValue=(o,c)=>Qn(o,c,a):m(!1);break;case 4:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint32(c,a)-2**31:s==="signed"?this.readInputValue=(o,c)=>o.getInt32(c,a):s==="float"?this.readInputValue=(o,c)=>o.getFloat32(c,a):m(!1);break;case 8:s==="float"?this.readInputValue=(o,c)=>o.getFloat64(c,a):m(!1);break;default:ne(n),m(!1)}switch(n){case 1:s==="ulaw"||s==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,l)=>o.setInt16(c,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(o,c,l)=>o.setUint8(c,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,l)=>o.setInt16(c,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(o,c,l)=>o.setInt32(c,l<<8,!0);break;case 4:this.outputSampleSize=4,s==="float"?(this.outputFormat="f32",this.writeOutputValue=(o,c,l)=>o.setFloat32(c,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(o,c,l)=>o.setInt32(c,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(o,c,l)=>o.setFloat32(c,l,!0);break;default:ne(n),m(!1)}}getDecodeQueueSize(){return 0}decode(e){let r=V(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,s=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,n=new ArrayBuffer(s),a=new DataView(n);for(let d=0;d<i*this.decoderConfig.numberOfChannels;d++){let u=d*this.inputSampleSize,h=d*this.outputSampleSize,f=this.readInputValue(r,u);this.writeOutputValue(a,h,f)}let o=i/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);let c=this.currentTimestamp;this.currentTimestamp+=o;let l=new we({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:c});this.onSample(l)}async flush(){}close(){}},Rr=class extends Ar{constructor(e){if(!(e instanceof J))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,r){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let i=this._track.codec,s=await this._track.getDecoderConfig();return m(i&&s),Q.includes(s.codec)?new Hs(e,r,s):new Ws(e,r,i,s)}_createPacketSink(){return new _t(this._track)}async getSample(e){Ct(e);for await(let r of this.mediaSamplesAtTimestamps([e]))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,r=1/0){return this.mediaSamplesInRange(e,r)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}};var Ht=class{constructor(e,r){this.input=e,this._backing=r}isVideoTrack(){return this instanceof Ve}isAudioTrack(){return this instanceof J}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let r=new _t(this),i=1/0,s=-1/0,n=0,a=0;for await(let o of r.packets(void 0,void 0,{metadataOnly:!0})){if(n>=e&&o.timestamp>=s)break;i=Math.min(i,o.timestamp),s=Math.max(s,o.timestamp+o.duration),n++,a+=o.byteLength}return{packetCount:n,averagePacketRate:n?Number((n/(s-i)).toPrecision(16)):0,averageBitrate:n?Number((8*a/(s-i)).toPrecision(16)):0}}},Ve=class extends Ht{constructor(e,r){super(e,r),this._backing=r}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180===0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180===0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=this._backing.getCodec();return m(r!==null),Ri.some(s=>s.supports(r,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof L))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(this.codec===null)return null;let r=await this.getDecoderConfig();return m(r),Fi(this.codec,r,e.data)}},J=class extends Ht{constructor(e,r){super(e,r),this._backing=r}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=this._backing.getCodec();return m(r!==null),Bi.some(i=>i.supports(r,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof L))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var Di=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){let i=[...new Set(t.codecStrings)];r+=`; codecs="${i.join(", ")}"`}return r};var ye=8,Le=16,We=t=>{let e=_(t),r=j(t,4),i=8;e===1&&(e=me(t),i=16);let n=e-i;return n<0?null:{name:r,totalSize:e,headerSize:i,contentSize:n}},Je=t=>He(t)/65536,Oi=t=>He(t)/1073741824,zi=t=>{let e=0;for(let r=0;r<4;r++){e<<=7;let i=v(t);if(e|=i&127,(i&128)===0)break}return e},Te=t=>{let e=ee(t);return t.skip(2),e=Math.min(e,t.remainingLength),ie.decode(F(t,e))},Va=t=>{let e=We(t);if(!e||e.name!=="data"||t.remainingLength<8)return null;let r=_(t);t.skip(4);let i=F(t,e.contentSize-8);switch(r){case 1:return ie.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new ke(i,"image/jpeg");case 14:return new ke(i,"image/png");case 27:return new ke(i,"image/bmp");default:return i}};var Mi=class extends ae{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(i=>i.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(r=>r.inputTrack.getCodecParameterString()));return Di({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.info?.type==="audio"),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,ye,Le);if(r instanceof Promise&&(r=await r),!r)break;let i=e,s=We(r);if(!s)break;if(s.name==="ftyp"){let n=j(r,4);this.isQuickTime=n==="qt "}else if(s.name==="moov"){let n=this.reader.requestSlice(r.filePos,s.contentSize);if(n instanceof Promise&&(n=await n),!n)break;this.moovSlice=n,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((a,o)=>Number(o.disposition.default)-Number(a.disposition.default));for(let a of this.tracks){let o=a.editListPreviousSegmentDurations/this.movieTimescale;a.editListOffset-=Math.round(o*a.timescale)}break}e=i+s.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let r=this.reader.requestSlice(this.reader.fileSize-4,4);r instanceof Promise&&(r=await r),m(r);let i=_(r),s=this.reader.fileSize-i;if(s>=0&&s<=this.reader.fileSize-Le){let n=this.reader.requestSliceRange(s,ye,Le);if(n instanceof Promise&&(n=await n),n){let a=We(n);if(a&&a.name==="mfra"){let o=this.reader.requestSlice(n.filePos,a.contentSize);o instanceof Promise&&(o=await o),o&&this.readContiguousBoxes(o)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=r,m(this.moovSlice);let i=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(i),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&Q.includes(e.info.codec)&&r.sampleCompositionTimeOffsets.length===0){m(e.info?.type==="audio");let n=fe(e.info.codec),a=[],o=[];for(let c=0;c<r.sampleToChunk.length;c++){let l=r.sampleToChunk[c],d=r.sampleToChunk[c+1],u=(d?d.startChunkIndex:r.chunkOffsets.length)-l.startChunkIndex;for(let h=0;h<u;h++){let f=l.startSampleIndex+h*l.samplesPerChunk,p=f+l.samplesPerChunk,g=M(r.sampleTimingEntries,f,E=>E.startIndex),w=r.sampleTimingEntries[g],b=M(r.sampleTimingEntries,p,E=>E.startIndex),k=r.sampleTimingEntries[b],y=w.startDecodeTimestamp+(f-w.startIndex)*w.delta,P=k.startDecodeTimestamp+(p-k.startIndex)*k.delta-y,S=q(a);S&&S.delta===P?S.count++:a.push({startIndex:l.startChunkIndex+h,startDecodeTimestamp:y,count:1,delta:P});let A=l.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;o.push(A)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}r.sampleTimingEntries=a,r.sampleSizes=o}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(let n of r.sampleTimingEntries)for(let a=0;a<n.count;a++)r.presentationTimestamps.push({presentationTimestamp:n.startDecodeTimestamp+a*n.delta,sampleIndex:n.startIndex+a});for(let n of r.sampleCompositionTimeOffsets)for(let a=0;a<n.count;a++){let o=n.startIndex+a,c=r.presentationTimestamps[o];c&&(c.presentationTimestamp+=n.offset)}r.presentationTimestamps.sort((n,a)=>n.presentationTimestamp-a.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let n=0;n<r.presentationTimestamps.length;n++)r.presentationTimestampIndexMap[r.presentationTimestamps[n].sampleIndex]=n}return r}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let r=this.reader.requestSliceRange(e,ye,Le);r instanceof Promise&&(r=await r),m(r);let i=We(r);m(i?.name==="moof");let s=this.reader.requestSlice(e,i.totalSize);s instanceof Promise&&(s=await s),m(s),this.traverseBox(s);let n=this.lastReadFragment;m(n&&n.moofOffset===e);for(let[,a]of n.trackData){let o=a.track,{fragmentPositionCache:c}=o;if(!a.startTimestampIsFinal){let d=o.fragmentLookupTable.find(u=>u.moofOffset===n.moofOffset);if(d)qs(a,d.timestamp);else{let u=M(c,n.moofOffset-1,h=>h.moofOffset);if(u!==-1){let h=c[u];qs(a,h.endTimestamp)}}a.startTimestampIsFinal=!0}let l=M(c,a.startTimestamp,d=>d.startTimestamp);(l===-1||c[l].moofOffset!==n.moofOffset)&&c.splice(l+1,0,{moofOffset:n.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp})}return n}readContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-ye&&this.traverseBox(e););}*iterateContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-ye;){let i=e.filePos,s=We(e);if(!s)break;yield{boxInfo:s,slice:e},e.filePos=i+s.totalSize}}traverseBox(e){let r=e.filePos,i=We(e);if(!i)return!1;let s=e.filePos,n=r+i.totalSize;switch(i.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(e.slice(s,i.contentSize));break;case"mvhd":{let a=v(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=_(e),this.movieDurationInTimescale=me(e)):(e.skip(8),this.movieTimescale=_(e),this.movieDurationInTimescale=_(e))}break;case"trak":{let a={id:-1,demuxer:this,inputTrack:null,disposition:{...de},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:G,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=a,this.readContiguousBoxes(e.slice(s,i.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){let o=a;a.inputTrack=new Ve(this.input,new js(o)),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){let o=a;a.inputTrack=new J(this.input,new $s(o)),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{let a=this.currentTrack;if(!a)break;let o=v(e),l=!!(et(e)&1);if(a.disposition.default=l,o===0)e.skip(8),a.id=_(e),e.skip(4),a.durationInMovieTimescale=_(e);else if(o===1)e.skip(16),a.id=_(e),e.skip(4),a.durationInMovieTimescale=me(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);let d=[Je(e),Je(e),Oi(e),Je(e),Je(e),Oi(e),Je(e),Je(e),Oi(e)],u=mi(Kn(Bc(d),90));m(u===0||u===90||u===180||u===270),a.rotation=u}break;case"elst":{let a=this.currentTrack;if(!a)break;let o=v(e);e.skip(3);let c=!1,l=0,d=_(e);for(let u=0;u<d;u++){let h=o===1?me(e):_(e),f=o===1?Wa(e):He(e),p=Je(e);if(h!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(f===-1){l+=h;continue}if(p!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=l,a.editListOffset=f,c=!0}}}break;case"mdhd":{let a=this.currentTrack;if(!a)break;let o=v(e);e.skip(3),o===0?(e.skip(8),a.timescale=_(e),a.durationInMediaTimescale=_(e)):o===1&&(e.skip(16),a.timescale=_(e),a.durationInMediaTimescale=me(e));let c=ee(e);if(c>0){a.languageCode="";for(let l=0;l<3;l++)a.languageCode=String.fromCharCode(96+(c&31))+a.languageCode,c>>=5;zt(a.languageCode)||(a.languageCode=G)}}break;case"hdlr":{let a=this.currentTrack;if(!a)break;e.skip(8);let o=j(e,4);o==="vide"?a.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:o==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=r,this.readContiguousBoxes(e.slice(s,i.contentSize))}break;case"stsd":{let a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;let o=v(e);e.skip(3);let c=_(e);for(let l=0;l<c;l++){let d=e.filePos,u=We(e);if(!u)break;a.internalCodecId=u.name;let h=u.name.toLowerCase();if(a.info.type==="video")h==="avc1"||h==="avc3"?(a.info.codec="avc",a.info.avcType=h==="avc1"?1:3):h==="hvc1"||h==="hev1"?a.info.codec="hevc":h==="vp08"?a.info.codec="vp8":h==="vp09"?a.info.codec="vp9":h==="av01"?a.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${u.name}').`),e.skip(24),a.info.width=ee(e),a.info.height=ee(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,d+u.totalSize-e.filePos));else{h==="mp4a"||(h==="opus"?a.info.codec="opus":h==="flac"?a.info.codec="flac":h==="twos"||h==="sowt"||h==="raw "||h==="in24"||h==="in32"||h==="fl32"||h==="fl64"||h==="lpcm"||h==="ipcm"||h==="fpcm"||(h==="ulaw"?a.info.codec="ulaw":h==="alaw"?a.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${u.name}').`))),e.skip(8);let f=ee(e);e.skip(6);let p=ee(e),g=ee(e);e.skip(4);let w=_(e)/65536;if(o===0&&f>0){if(f===1)e.skip(4),g=8*_(e),e.skip(8);else if(f===2){e.skip(4),w=Ni(e),p=_(e),e.skip(4),g=_(e);let b=_(e);if(e.skip(8),h==="lpcm"){let k=g+7>>3,y=!!(b&1),x=!!(b&2),P=b&4?-1:0;g>0&&g<=64&&(y?g===32&&(a.info.codec=x?"pcm-f32be":"pcm-f32"):P&1<<k-1?k===1?a.info.codec="pcm-s8":k===2?a.info.codec=x?"pcm-s16be":"pcm-s16":k===3?a.info.codec=x?"pcm-s24be":"pcm-s24":k===4&&(a.info.codec=x?"pcm-s32be":"pcm-s32"):k===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&console.warn("Unsupported PCM format.")}}}a.info.codec==="opus"&&(w=kt),a.info.numberOfChannels=p,a.info.sampleRate=w,h==="twos"?g===8?a.info.codec="pcm-s8":g===16?a.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${g} for codec 'twos'.`),a.info.codec=null):h==="sowt"?g===8?a.info.codec="pcm-s8":g===16?a.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${g} for codec 'sowt'.`),a.info.codec=null):h==="raw "?a.info.codec="pcm-u8":h==="in24"?a.info.codec="pcm-s24be":h==="in32"?a.info.codec="pcm-s32be":h==="fl32"?a.info.codec="pcm-f32be":h==="fl64"?a.info.codec="pcm-f64be":h==="ipcm"?a.info.codec="pcm-s16be":h==="fpcm"&&(a.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,d+u.totalSize-e.filePos))}}}break;case"avcC":{let a=this.currentTrack;if(!a)break;m(a.info),a.info.codecDescription=F(e,i.contentSize)}break;case"hvcC":{let a=this.currentTrack;if(!a)break;m(a.info),a.info.codecDescription=F(e,i.contentSize)}break;case"vpcC":{let a=this.currentTrack;if(!a)break;m(a.info?.type==="video"),e.skip(4);let o=v(e),c=v(e),l=v(e),d=l>>4,u=l>>1&7,h=l&1,f=v(e),p=v(e),g=v(e);a.info.vp9CodecInfo={profile:o,level:c,bitDepth:d,chromaSubsampling:u,videoFullRangeFlag:h,colourPrimaries:f,transferCharacteristics:p,matrixCoefficients:g}}break;case"av1C":{let a=this.currentTrack;if(!a)break;m(a.info?.type==="video"),e.skip(1);let o=v(e),c=o>>5,l=o&31,d=v(e),u=d>>7,h=d>>6&1,f=d>>5&1,p=d>>4&1,g=d>>3&1,w=d>>2&1,b=d&3,k=c===2&&h?f?12:10:h?10:8;a.info.av1CodecInfo={profile:c,level:l,tier:u,bitDepth:k,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:w,chromaSamplePosition:b}}break;case"colr":{let a=this.currentTrack;if(!a||(m(a.info?.type==="video"),j(e,4)!=="nclx"))break;let c=ee(e),l=ee(e),d=ee(e),u=!!(v(e)&128);a.info.colorSpace={primaries:pi[c],transfer:gi[l],matrix:wi[d],fullRange:u}}break;case"wave":this.readContiguousBoxes(e.slice(s,i.contentSize));break;case"esds":{let a=this.currentTrack;if(!a)break;m(a.info?.type==="audio"),e.skip(4);let o=v(e);m(o===3),zi(e),e.skip(2);let c=v(e),l=(c&128)!==0,d=(c&64)!==0,u=(c&32)!==0;if(l&&e.skip(2),d){let w=v(e);e.skip(w)}u&&e.skip(2);let h=v(e);m(h===4);let f=zi(e),p=e.filePos,g=v(e);if(g===64||g===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:g===103}):g===105||g===107?a.info.codec="mp3":g===221?a.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${g}) - discarding track.`),e.skip(12),f>e.filePos-p){let w=v(e);m(w===5);let b=zi(e);if(a.info.codecDescription=F(e,b),a.info.codec==="aac"){let k=_r(a.info.codecDescription);k.numberOfChannels!==null&&(a.info.numberOfChannels=k.numberOfChannels),k.sampleRate!==null&&(a.info.sampleRate=k.sampleRate)}}}break;case"enda":{let a=this.currentTrack;if(!a)break;m(a.info?.type==="audio"),ee(e)&255&&(a.info.codec==="pcm-s16be"?a.info.codec="pcm-s16":a.info.codec==="pcm-s24be"?a.info.codec="pcm-s24":a.info.codec==="pcm-s32be"?a.info.codec="pcm-s32":a.info.codec==="pcm-f32be"?a.info.codec="pcm-f32":a.info.codec==="pcm-f64be"&&(a.info.codec="pcm-f64"))}break;case"pcmC":{let a=this.currentTrack;if(!a)break;m(a.info?.type==="audio"),e.skip(4);let c=!!(v(e)&1),l=v(e);a.info.codec==="pcm-s16be"?c?l===16?a.info.codec="pcm-s16":l===24?a.info.codec="pcm-s24":l===32?a.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${l}.`),a.info.codec=null):l===16?a.info.codec="pcm-s16be":l===24?a.info.codec="pcm-s24be":l===32?a.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${l}.`),a.info.codec=null):a.info.codec==="pcm-f32be"&&(c?l===32?a.info.codec="pcm-f32":l===64?a.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${l}.`),a.info.codec=null):l===32?a.info.codec="pcm-f32be":l===64?a.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${l}.`),a.info.codec=null));break}case"dOps":{let a=this.currentTrack;if(!a)break;m(a.info?.type==="audio"),e.skip(1);let o=v(e),c=ee(e),l=_(e),d=Br(e),u=v(e),h;u!==0?h=F(e,2+o):h=new Uint8Array(0);let f=new Uint8Array(19+h.byteLength),p=new DataView(f.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,o),p.setUint16(10,c,!0),p.setUint32(12,l,!0),p.setInt16(16,d,!0),p.setUint8(18,u),f.set(h,19),a.info.codecDescription=f,a.info.numberOfChannels=o}break;case"dfLa":{let a=this.currentTrack;if(!a)break;m(a.info?.type==="audio"),e.skip(4);let o=127,c=128,l=e.filePos;for(;e.filePos<n;){let p=v(e),g=et(e);if((p&o)===Ze.STREAMINFO){e.skip(10);let b=_(e),k=b>>>12,y=(b>>9&7)+1;a.info.sampleRate=k,a.info.numberOfChannels=y,e.skip(20)}else e.skip(g);if(p&c)break}let d=e.filePos;e.filePos=l;let u=F(e,d-l),h=new Uint8Array(4+u.byteLength);new DataView(h.buffer).setUint32(0,1716281667,!1),h.set(u,4),a.info.codecDescription=h}break;case"stts":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=_(e),c=0,l=0;for(let d=0;d<o;d++){let u=_(e),h=_(e);a.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:u,delta:h}),c+=u,l+=u*h}}break;case"ctts":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=_(e),c=0;for(let l=0;l<o;l++){let d=_(e),u=He(e);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:d,offset:u}),c+=d}}break;case"stsz":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=_(e),c=_(e);if(o===0)for(let l=0;l<c;l++){let d=_(e);a.sampleTable.sampleSizes.push(d)}else a.sampleTable.sampleSizes.push(o)}break;case"stz2":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),e.skip(3);let o=v(e),c=_(e),l=F(e,Math.ceil(c*o/8)),d=new H(l);for(let u=0;u<c;u++){let h=d.readBits(o);a.sampleTable.sampleSizes.push(h)}}break;case"stss":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),a.sampleTable.keySampleIndices=[];let o=_(e);for(let c=0;c<o;c++){let l=_(e)-1;a.sampleTable.keySampleIndices.push(l)}a.sampleTable.keySampleIndices[0]!==0&&a.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=_(e);for(let l=0;l<o;l++){let d=_(e)-1,u=_(e),h=_(e);a.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:d,samplesPerChunk:u,sampleDescriptionIndex:h})}let c=0;for(let l=0;l<a.sampleTable.sampleToChunk.length;l++)if(a.sampleTable.sampleToChunk[l].startSampleIndex=c,l<a.sampleTable.sampleToChunk.length-1){let u=a.sampleTable.sampleToChunk[l+1].startChunkIndex-a.sampleTable.sampleToChunk[l].startChunkIndex;c+=u*a.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=_(e);for(let c=0;c<o;c++){let l=_(e);a.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=_(e);for(let c=0;c<o;c++){let l=me(e);a.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(s,i.contentSize));break;case"mehd":{let a=v(e);e.skip(3);let o=a===1?me(e):_(e);this.movieDurationInTimescale=o}break;case"trex":{e.skip(4);let a=_(e),o=_(e),c=_(e),l=_(e),d=_(e);this.fragmentTrackDefaults.push({trackId:a,defaultSampleDescriptionIndex:o,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:d})}break;case"tfra":{let a=v(e);e.skip(3);let o=_(e),c=this.tracks.find(k=>k.id===o);if(!c)break;let l=_(e),d=(l&48)>>4,u=(l&12)>>2,h=l&3,f=[v,ee,et,_],p=f[d],g=f[u],w=f[h],b=_(e);for(let k=0;k<b;k++){let y=a===1?me(e):_(e),x=a===1?me(e):_(e);p(e),g(e),w(e),c.fragmentLookupTable.push({timestamp:y,moofOffset:x})}c.fragmentLookupTable.sort((k,y)=>k.timestamp-y.timestamp);for(let k=0;k<c.fragmentLookupTable.length-1;k++){let y=c.fragmentLookupTable[k],x=c.fragmentLookupTable[k+1];y.timestamp===x.timestamp&&(c.fragmentLookupTable.splice(k+1,1),k--)}}break;case"moof":this.currentFragment={moofOffset:r,moofSize:i.totalSize,implicitBaseDataOffset:r,trackData:new Map},this.readContiguousBoxes(e.slice(s,i.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(m(this.currentFragment),this.readContiguousBoxes(e.slice(s,i.contentSize)),this.currentTrack){let a=this.currentFragment.trackData.get(this.currentTrack.id);if(a){let{currentFragmentState:o}=this.currentTrack;m(o),o.startTimestamp!==null&&(qs(a,o.startTimestamp),a.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{m(this.currentFragment),e.skip(1);let a=et(e),o=!!(a&1),c=!!(a&2),l=!!(a&8),d=!!(a&16),u=!!(a&32),h=!!(a&65536),f=!!(a&131072),p=_(e),g=this.tracks.find(b=>b.id===p);if(!g)break;let w=this.fragmentTrackDefaults.find(b=>b.trackId===p);this.currentTrack=g,g.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:w?.defaultSampleDescriptionIndex??null,defaultSampleDuration:w?.defaultSampleDuration??null,defaultSampleSize:w?.defaultSampleSize??null,defaultSampleFlags:w?.defaultSampleFlags??null,startTimestamp:null},o?g.currentFragmentState.baseDataOffset=me(e):f&&(g.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(g.currentFragmentState.sampleDescriptionIndex=_(e)),l&&(g.currentFragmentState.defaultSampleDuration=_(e)),d&&(g.currentFragmentState.defaultSampleSize=_(e)),u&&(g.currentFragmentState.defaultSampleFlags=_(e)),h&&(g.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let a=this.currentTrack;if(!a)break;m(a.currentFragmentState);let o=v(e);e.skip(3);let c=o===0?_(e):me(e);a.currentFragmentState.startTimestamp=c}break;case"trun":{let a=this.currentTrack;if(!a)break;if(m(this.currentFragment),m(a.currentFragmentState),this.currentFragment.trackData.has(a.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let o=v(e),c=et(e),l=!!(c&1),d=!!(c&4),u=!!(c&256),h=!!(c&512),f=!!(c&1024),p=!!(c&2048),g=_(e),w=a.currentFragmentState.baseDataOffset;l&&(w+=He(e));let b=null;d&&(b=_(e));let k=w;if(g===0){this.currentFragment.implicitBaseDataOffset=k;break}let y=0,x={track:a,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(a.id,x);for(let A=0;A<g;A++){let E;u?E=_(e):(m(a.currentFragmentState.defaultSampleDuration!==null),E=a.currentFragmentState.defaultSampleDuration);let D;h?D=_(e):(m(a.currentFragmentState.defaultSampleSize!==null),D=a.currentFragmentState.defaultSampleSize);let N;f?N=_(e):(m(a.currentFragmentState.defaultSampleFlags!==null),N=a.currentFragmentState.defaultSampleFlags),A===0&&b!==null&&(N=b);let z=0;p&&(o===0?z=_(e):z=He(e));let re=!(N&65536);x.samples.push({presentationTimestamp:y+z,duration:E,byteOffset:k,byteSize:D,isKeyFrame:re}),k+=D,y+=E}x.presentationTimestamps=x.samples.map((A,E)=>({presentationTimestamp:A.presentationTimestamp,sampleIndex:E})).sort((A,E)=>A.presentationTimestamp-E.presentationTimestamp);for(let A=0;A<x.presentationTimestamps.length;A++){let E=x.presentationTimestamps[A],D=x.samples[E.sampleIndex];if(x.firstKeyFrameTimestamp===null&&D.isKeyFrame&&(x.firstKeyFrameTimestamp=D.presentationTimestamp),A<x.presentationTimestamps.length-1){let N=x.presentationTimestamps[A+1];D.duration=N.presentationTimestamp-E.presentationTimestamp}}let P=x.samples[x.presentationTimestamps[0].sampleIndex],S=x.samples[q(x.presentationTimestamps).sampleIndex];x.startTimestamp=P.presentationTimestamp,x.endTimestamp=S.presentationTimestamp+S.duration,this.currentFragment.implicitBaseDataOffset=k}break;case"udta":{let a=this.iterateContiguousBoxes(e.slice(s,i.contentSize));for(let{boxInfo:o,slice:c}of a){if(o.name!=="meta"&&!this.currentTrack){let l=c.filePos;this.metadataTags.raw??={},o.name[0]==="\xA9"?this.metadataTags.raw[o.name]??=Te(c):this.metadataTags.raw[o.name]??=F(c,o.contentSize),c.filePos=l}switch(o.name){case"meta":c.skip(-o.headerSize),this.traverseBox(c);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=ie.decode(F(c,o.contentSize)):this.metadataTags.title??=Te(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=Te(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=Te(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=Te(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Te(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=Te(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(Te(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=Te(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=Te(c));break}}}break;case"meta":{if(this.currentTrack)break;let o=_(e)!==0;this.currentMetadataKeys=new Map,o?this.readContiguousBoxes(e.slice(s,i.contentSize)):this.readContiguousBoxes(e.slice(s+4,i.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let a=_(e);for(let o=0;o<a;o++){let c=_(e);e.skip(4);let l=ie.decode(F(e,c-8));this.currentMetadataKeys.set(o+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let a=this.iterateContiguousBoxes(e.slice(s,i.contentSize));for(let{boxInfo:o,slice:c}of a){let l=o.name,d=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(d)&&(l=this.currentMetadataKeys.get(d));let u=Va(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=u,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof u=="string"&&(this.metadataTags.title??=u);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof u=="string"&&(this.metadataTags.description??=u);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof u=="string"&&(this.metadataTags.artist??=u);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof u=="string"&&(this.metadataTags.album??=u);break;case"aART":case"album_artist":typeof u=="string"&&(this.metadataTags.albumArtist??=u);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof u=="string"&&(this.metadataTags.comment??=u);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof u=="string"&&(this.metadataTags.genre??=u);break;case"\xA9lyr":case"lyrics":typeof u=="string"&&(this.metadataTags.lyrics??=u);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof u=="string"){let h=new Date(u);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"covr":case"com.apple.quicktime.artwork":u instanceof ke?(this.metadataTags.images??=[],this.metadataTags.images.push({data:u.data,kind:"coverFront",mimeType:u.mimeType})):u instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:u,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof u=="string"){let h=u.split("/"),f=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(u instanceof Uint8Array&&u.length>=6){let h=V(u),f=h.getUint16(2,!1),p=h.getUint16(4,!1);f>0&&(this.metadataTags.trackNumber??=f),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(u instanceof Uint8Array&&u.length>=6){let h=V(u),f=h.getUint16(2,!1),p=h.getUint16(4,!1);f>0&&(this.metadataTags.discNumber??=f),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return e.filePos=n,!0}},Ui=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let r=await this.fetchPacketForSampleIndex(0,e);return r||!this.internalTrack.demuxer.isFragmented?r:this.performFragmentedLookup(null,i=>i.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return gt(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,r){let i=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Qs(s,i),a=await this.fetchPacketForSampleIndex(n,r);return!La(s)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=M(c.presentationTimestamps,i,h=>h.presentationTimestamp),d=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&i<c.endTimestamp;return{sampleIndex:d,correctSampleFound:u}},i,i,r)}async getNextPacket(e,r){let i=this.packetToSampleIndex.get(e);if(i!==void 0)return this.fetchPacketForSampleIndex(i+1,r);let s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(s.fragment,n=>{if(n===s.fragment){let a=n.trackData.get(this.internalTrack.id);if(s.sampleIndex+1<a.samples.length)return{sampleIndex:s.sampleIndex+1,correctSampleFound:!0}}else if(n.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let i=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Ac(s,i),a=await this.fetchPacketForSampleIndex(n,r);return!La(s)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=bi(c.presentationTimestamps,h=>c.samples[h.sampleIndex].isKeyFrame&&h.presentationTimestamp<=i),d=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&i<c.endTimestamp;return{sampleIndex:d,correctSampleFound:u}},i,i,r)}async getNextKeyPacket(e,r){let i=this.packetToSampleIndex.get(e);if(i!==void 0){let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Rc(n,i);return this.fetchPacketForSampleIndex(a,r)}let s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(s.fragment,n=>{if(n===s.fragment){let o=n.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>s.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{let a=n.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){let o=a.samples.findIndex(c=>c.isKeyFrame);return m(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async fetchPacketForSampleIndex(e,r){if(e===-1)return null;let i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Fc(i,e);if(!s)return null;let n;if(r.metadataOnly)n=Y;else{let l=this.internalTrack.demuxer.reader.requestSlice(s.sampleOffset,s.sampleSize);l instanceof Promise&&(l=await l),m(l),n=F(l,s.sampleSize)}let a=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=s.duration/this.internalTrack.timescale,c=new L(n,s.isKeyFrame?"key":"delta",a,o,e,s.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,r,i){if(r===-1)return null;let n=e.trackData.get(this.internalTrack.id).samples[r];m(n);let a;if(i.metadataOnly)a=Y;else{let d=this.internalTrack.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);d instanceof Promise&&(d=await d),m(d),a=F(d,n.byteSize)}let o=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=n.duration/this.internalTrack.timescale,l=new L(a,n.isKeyFrame?"key":"delta",o,c,e.moofOffset+r,n.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:r}),l}async performFragmentedLookup(e,r,i,s,n){let a=this.internalTrack.demuxer,o=null,c=null,l=-1;if(e){let{sampleIndex:w,correctSampleFound:b}=r(e);if(b)return this.fetchPacketInFragment(e,w,n);w!==-1&&(c=e,l=w)}let d=M(this.internalTrack.fragmentLookupTable,i,w=>w.timestamp),u=d!==-1?this.internalTrack.fragmentLookupTable[d]:null,h=M(this.internalTrack.fragmentPositionCache,i,w=>w.startTimestamp),f=h!==-1?this.internalTrack.fragmentPositionCache[h]:null,p=Math.max(u?.moofOffset??0,f?.moofOffset??0)||null,g;for(e?p===null||e.moofOffset>=p?(g=e.moofOffset+e.moofSize,o=e):g=p:g=p??0;;){if(o){let y=o.trackData.get(this.internalTrack.id);if(y&&y.startTimestamp>s)break}let w=a.reader.requestSliceRange(g,ye,Le);if(w instanceof Promise&&(w=await w),!w)break;let b=g,k=We(w);if(!k)break;if(k.name==="moof"){o=await a.readFragment(b);let{sampleIndex:y,correctSampleFound:x}=r(o);if(x)return this.fetchPacketInFragment(o,y,n);y!==-1&&(c=o,l=y)}g=b+k.totalSize}if(u&&(!c||c.moofOffset<u.moofOffset)){let w=this.internalTrack.fragmentLookupTable[d-1];m(!w||w.timestamp<u.timestamp);let b=w?.timestamp??-1/0;return this.performFragmentedLookup(null,r,b,s,n)}return c?this.fetchPacketInFragment(c,l,n):null}},js=class extends Ui{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&Ii(e.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&vi(e.data)}return{codec:Ti(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},$s=class extends Ui{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:xi(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},Qs=(t,e)=>{if(t.presentationTimestamps){let r=M(t.presentationTimestamps,e,i=>i.presentationTimestamp);return r===-1?-1:t.presentationTimestamps[r].sampleIndex}else{let r=M(t.sampleTimingEntries,e,s=>s.startDecodeTimestamp);if(r===-1)return-1;let i=t.sampleTimingEntries[r];return i.startIndex+Math.min(Math.floor((e-i.startDecodeTimestamp)/i.delta),i.count-1)}},Ac=(t,e)=>{if(!t.keySampleIndices)return Qs(t,e);if(t.presentationTimestamps){let r=M(t.presentationTimestamps,e,i=>i.presentationTimestamp);if(r===-1)return-1;for(let i=r;i>=0;i--){let s=t.presentationTimestamps[i].sampleIndex;if(mt(t.keySampleIndices,s,a=>a)!==-1)return s}return-1}else{let r=Qs(t,e),i=M(t.keySampleIndices,r,s=>s);return t.keySampleIndices[i]??-1}},Fc=(t,e)=>{let r=M(t.sampleTimingEntries,e,b=>b.startIndex),i=t.sampleTimingEntries[r];if(!i||i.startIndex+i.count<=e)return null;let n=i.startDecodeTimestamp+(e-i.startIndex)*i.delta,a=M(t.sampleCompositionTimeOffsets,e,b=>b.startIndex),o=t.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(n+=o.offset);let c=t.sampleSizes[Math.min(e,t.sampleSizes.length-1)],l=M(t.sampleToChunk,e,b=>b.startSampleIndex),d=t.sampleToChunk[l];m(d);let u=d.startChunkIndex+Math.floor((e-d.startSampleIndex)/d.samplesPerChunk),h=t.chunkOffsets[u],f=d.startSampleIndex+(u-d.startChunkIndex)*d.samplesPerChunk,p=0,g=h;if(t.sampleSizes.length===1)g+=c*(e-f),p+=c*d.samplesPerChunk;else for(let b=f;b<f+d.samplesPerChunk;b++){let k=t.sampleSizes[b];b<e&&(g+=k),p+=k}let w=i.delta;if(t.presentationTimestamps){let b=t.presentationTimestampIndexMap[e];m(b!==void 0),b<t.presentationTimestamps.length-1&&(w=t.presentationTimestamps[b+1].presentationTimestamp-n)}return{presentationTimestamp:n,duration:w,sampleOffset:g,sampleSize:c,chunkOffset:h,chunkSize:p,isKeyFrame:t.keySampleIndices?mt(t.keySampleIndices,e,b=>b)!==-1:!0}},Rc=(t,e)=>{if(!t.keySampleIndices)return e+1;let r=M(t.keySampleIndices,e,i=>i);return t.keySampleIndices[r+1]??-1},qs=(t,e)=>{t.startTimestamp+=e,t.endTimestamp+=e;for(let r of t.samples)r.presentationTimestamp+=e;for(let r of t.presentationTimestamps)r.presentationTimestamp+=e},Bc=t=>{let[e,,,r]=t,i=Math.hypot(e,r),s=e/i,n=r/i,a=-Math.atan2(n,s)*(180/Math.PI);return Number.isFinite(a)?a:0},La=t=>t.sampleSizes.length===0;var T;(function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"})(T||(T={}));var Dc=[T.EBML,T.Segment],qt=[T.SeekHead,T.Info,T.Cluster,T.Tracks,T.Cues,T.Attachments,T.Chapters,T.Tags],Dr=[...Dc,...qt];var Gs=8,pe=2,xe=2*Gs,Ks=t=>{let e=v(t);if(t.skip(-1),e===0)return null;let r=1,i=128;for(;(e&i)===0;)r++,i>>=1;return r},jt=t=>{let e=v(t);if(e===0)return null;let r=1,i=128;for(;(e&i)===0;)r++,i>>=1;let s=e&i-1;for(let n=1;n<r;n++)s*=256,s+=v(t);return s},O=(t,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let r=0;for(let i=0;i<e;i++)r*=256,r+=v(t);return r},Ha=(t,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let r=0n;for(let i=0;i<e;i++)r<<=8n,r+=BigInt(v(t));return r};var Vi=t=>{let e=Ks(t);return e===null?null:O(t,e)},Xs=t=>{let e=v(t);return e===255?e=null:(t.skip(-1),e=jt(t),e===72057594037927940&&(e=null)),e},Se=t=>{let e=Vi(t);if(e===null)return null;let r=Xs(t);return{id:e,size:r}},tt=(t,e)=>{let r=F(t,e),i=0;for(;i<e&&r[i]!==0;)i+=1;return String.fromCharCode(...r.subarray(0,i))},$t=(t,e)=>{let r=F(t,e),i=0;for(;i<e&&r[i]!==0;)i+=1;return ie.decode(r.subarray(0,i))},Li=(t,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?qa(t):Ni(t)},Wi=async(t,e,r,i)=>{let s=new Set(r),n=e;for(;i===null||n<i;){let a=t.requestSliceRange(n,pe,xe);if(a instanceof Promise&&(a=await a),!a)break;let o=Se(a);if(!o)break;if(s.has(o.id))return{pos:n,found:!0};qe(o.size),n=a.filePos+o.size}return{pos:i!==null&&i>n?i:n,found:!1}},Ys=async(t,e,r,i)=>{let n=new Set(r),a=e;for(;a<i;){let o=t.requestSliceRange(a,0,Math.min(65536,i-a));if(o instanceof Promise&&(o=await o),!o||o.length<Gs)break;for(let c=0;c<o.length-Gs;c++){o.filePos=a;let l=Vi(o);if(l!==null&&n.has(l))return a;a++}}return null},Ce={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function qe(t){if(t===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var ja=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");if(t.codecStrings.length>0){let i=[...new Set(t.codecStrings.filter(Boolean))];r+=`; codecs="${i.join(", ")}"`}return r};var je;(function(t){t[t.None=0]="None",t[t.Xiph=1]="Xiph",t[t.FixedSize=2]="FixedSize",t[t.Ebml=3]="Ebml"})(je||(je={}));var Hi;(function(t){t[t.Block=1]="Block",t[t.Private=2]="Private",t[t.Next=4]="Next"})(Hi||(Hi={}));var Or;(function(t){t[t.Zlib=0]="Zlib",t[t.Bzlib=1]="Bzlib",t[t.lzo1x=2]="lzo1x",t[t.HeaderStripping=3]="HeaderStripping"})(Or||(Or={}));var Zs=[{id:T.SeekHead,flag:"seekHeadSeen"},{id:T.Info,flag:"infoSeen"},{id:T.Tracks,flag:"tracksSeen"},{id:T.Cues,flag:"cuesSeen"}],$a=10*2**20,qi=class extends ae{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(i=>i.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(r=>r.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),r=await Promise.all(e.map(i=>i.getCodecParameterString()));return ja({isWebM:this.isWebM,hasVideo:this.segments.some(i=>i.tracks.some(s=>s.info?.type==="video")),hasAudio:this.segments.some(i=>i.tracks.some(s=>s.info?.type==="audio")),codecStrings:r.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let r of this.segments)r.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(r),r.metadataTagsCollected=!0);let e={};for(let r of this.segments)e={...e,...r.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,pe,xe);if(r instanceof Promise&&(r=await r),!r)break;let i=Se(r);if(!i)break;let s=i.id,n=i.size,a=r.filePos;if(s===T.EBML){qe(n);let o=this.reader.requestSlice(a,n);if(o instanceof Promise&&(o=await o),!o)break;this.readContiguousElements(o)}else if(s===T.Segment){if(await this.readSegment(a,n),n===null||this.reader.fileSize===null)break}else if(s===T.Cluster){if(this.reader.fileSize===null)break;n===null&&(n=(await Wi(this.reader,a,Dr,this.reader.fileSize)).pos-a);let o=q(this.segments);o&&(o.elementEndPos=a+n)}qe(n),e=a+n}})()}async readSegment(e,r){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:r===null?null:e+r,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;this.currentSegment.elementEndPos===null||i<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(i,pe,xe);if(o instanceof Promise&&(o=await o),!o)break;let c=i,l=Se(o);if(!l||!qt.includes(l.id)&&l.id!==T.Void){let p=await Ys(this.reader,c,qt,Math.min(this.currentSegment.elementEndPos??1/0,c+$a));if(p){i=p;continue}else break}let{id:d,size:u}=l,h=o.filePos,f=Zs.findIndex(p=>p.id===d);if(f!==-1){let p=Zs[f].flag;this.currentSegment[p]=!0,qe(u);let g=this.reader.requestSlice(h,u);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(d===T.Tags||d===T.Attachments){d===T.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,qe(u);let p=this.reader.requestSlice(h,u);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(d===T.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(u===null)break;i=h+u}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let o of this.currentSegment.seekEntries){let c=Zs.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+o.segmentPosition,pe,xe);if(l instanceof Promise&&(l=await l),!l)continue;let d=Se(l);if(!d)continue;let{id:u,size:h}=d;if(u!==c.id)continue;qe(h),this.currentSegment[c.flag]=!0;let f=this.reader.requestSlice(l.filePos,h);f instanceof Promise&&(f=await f),f&&this.readContiguousElements(f)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6),this.currentSegment.tracks.sort((o,c)=>Number(c.disposition.default)-Number(o.disposition.default));let s=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(let o of this.currentSegment.cuePoints){let c=s.get(o.trackId);c&&c.cuePoints.push(o)}for(let o of this.currentSegment.tracks){o.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<o.cuePoints.length-1;c++){let l=o.cuePoints[c],d=o.cuePoints[c+1];l.time===d.time&&(o.cuePoints.splice(c+1,1),c--)}}let n=null,a=-1/0;for(let o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,n=o);for(let o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=n.cuePoints);this.currentSegment=null}async readCluster(e,r){if(r.lastReadCluster?.elementStartPos===e)return r.lastReadCluster;let i=this.reader.requestSliceRange(e,pe,xe);i instanceof Promise&&(i=await i),m(i);let s=e,n=Se(i);m(n);let a=n.id;m(a===T.Cluster);let o=n.size,c=i.filePos;o===null&&(o=(await Wi(this.reader,c,Dr,r.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);let d={segment:r,elementStartPos:s,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=d,l){let u=this.readContiguousElements(l,Dr);d.elementEndPos=u}for(let[,u]of d.trackData){let h=u.track;m(u.blocks.length>0);let f=!1;for(let b=0;b<u.blocks.length;b++){let k=u.blocks[b];k.timestamp+=d.timestamp,f||=k.lacing!==je.None}u.presentationTimestamps=u.blocks.map((b,k)=>({timestamp:b.timestamp,blockIndex:k})).sort((b,k)=>b.timestamp-k.timestamp);for(let b=0;b<u.presentationTimestamps.length;b++){let k=u.presentationTimestamps[b],y=u.blocks[k.blockIndex];if(u.firstKeyFrameTimestamp===null&&y.isKeyFrame&&(u.firstKeyFrameTimestamp=y.timestamp),b<u.presentationTimestamps.length-1){let x=u.presentationTimestamps[b+1];y.duration=x.timestamp-y.timestamp}else y.duration===0&&h.defaultDuration!=null&&y.lacing===je.None&&(y.duration=h.defaultDuration)}f&&(this.expandLacedBlocks(u.blocks,h),u.presentationTimestamps=u.blocks.map((b,k)=>({timestamp:b.timestamp,blockIndex:k})).sort((b,k)=>b.timestamp-k.timestamp));let p=u.blocks[u.presentationTimestamps[0].blockIndex],g=u.blocks[q(u.presentationTimestamps).blockIndex];u.startTimestamp=p.timestamp,u.endTimestamp=g.timestamp+g.duration;let w=M(h.clusterPositionCache,u.startTimestamp,b=>b.startTimestamp);(w===-1||h.clusterPositionCache[w].elementStartPos!==s)&&h.clusterPositionCache.splice(w+1,0,{elementStartPos:d.elementStartPos,startTimestamp:u.startTimestamp})}return r.lastReadCluster=d,d}getTrackDataInCluster(e,r){let i=e.trackData.get(r);if(!i){let s=e.segment.tracks.find(n=>n.id===r);if(!s)return null;i={track:s,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(r,i)}return i}expandLacedBlocks(e,r){for(let i=0;i<e.length;i++){let s=e[i];if(s.lacing===je.None)continue;s.decoded||(s.data=this.decodeBlockData(r,s.data),s.decoded=!0);let n=Qt.tempFromBytes(s.data),a=[],o=v(n)+1;switch(s.lacing){case je.Xiph:{let l=0;for(let d=0;d<o-1;d++){let u=0;for(;n.bufferPos<n.length;){let h=v(n);if(u+=h,h<255){a.push(u),l+=u;break}}}a.push(n.length-(n.bufferPos+l))}break;case je.FixedSize:{let l=n.length-1,d=Math.floor(l/o);for(let u=0;u<o;u++)a.push(d)}break;case je.Ebml:{let l=jt(n);m(l!==null);let d=l;a.push(d);let u=d;for(let h=1;h<o-1;h++){let f=n.bufferPos,p=jt(n);m(p!==null);let g=p,b=(1<<(n.bufferPos-f)*7-1)-1,k=g-b;d+=k,a.push(d),u+=d}a.push(n.length-(n.bufferPos+u))}break;default:m(!1)}m(a.length===o),e.splice(i,1);let c=s.duration||o*(r.defaultDuration??0);for(let l=0;l<o;l++){let d=a[l],u=F(n,d),h=s.timestamp+c*l/o,f=c/o;e.splice(i+l,0,{timestamp:h,duration:f,isKeyFrame:s.isKeyFrame,data:u,lacing:je.None,decoded:!0,mainAdditional:s.mainAdditional})}i+=o,i--}}async loadSegmentMetadata(e){for(let r of e.seekEntries){if(!(r.id===T.Tags&&!e.tagsSeen)){if(!(r.id===T.Attachments&&!e.attachmentsSeen))continue}let i=this.reader.requestSliceRange(e.dataStartPos+r.segmentPosition,pe,xe);if(i instanceof Promise&&(i=await i),!i)continue;let s=Se(i);if(!s||s.id!==r.id)continue;let{size:n}=s;qe(n),m(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(i.filePos,n);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,r.id===T.Tags?e.tagsSeen=!0:r.id===T.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,r){let i=e.filePos;for(;e.filePos-i<=e.length-pe;){let s=e.filePos;if(!this.traverseElement(e,r))return s}return e.filePos}traverseElement(e,r){let i=Se(e);if(!i||r&&r.includes(i.id))return!1;let{id:s,size:n}=i,a=e.filePos;switch(qe(n),s){case T.DocType:this.isWebM=tt(e,n)==="webm";break;case T.Seek:{if(!this.currentSegment)break;let o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(e.slice(a,n)),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case T.SeekID:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=O(e,n)}break;case T.SeekPosition:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=O(e,n)}break;case T.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=O(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case T.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Li(e,n)}break;case T.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...de},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:G,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,n)),this.currentTrack.decodingInstructions.some(o=>o.data?.type!=="decompress"||o.scope!==Hi.Block||o.data.algorithm!==Or.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let o=this.currentTrack.codecId.indexOf("/"),c=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.codecId===Ce.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Ce.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Ce.vp8?this.currentTrack.info.codec="vp8":c===Ce.vp9?this.currentTrack.info.codec="vp9":c===Ce.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack,d=new Ve(this.input,new Js(l));this.currentTrack.inputTrack=d,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===Ce.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Ce.mp3?this.currentTrack.info.codec="mp3":c===Ce.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=kt):c===Ce.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Ce.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let l=this.currentTrack,d=new J(this.input,new en(l));this.currentTrack.inputTrack=d,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case T.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=O(e,n)}break;case T.TrackType:{if(!this.currentTrack)break;let o=O(e,n);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case T.FlagEnabled:{if(!this.currentTrack)break;O(e,n)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case T.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!O(e,n)}break;case T.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!O(e,n)}break;case T.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!O(e,n)}break;case T.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!O(e,n)}break;case T.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!O(e,n)}break;case T.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!O(e,n)}break;case T.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=tt(e,n)}break;case T.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=F(e,n)}break;case T.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*O(e,n)/1e9}break;case T.Name:{if(!this.currentTrack)break;this.currentTrack.name=$t(e,n)}break;case T.Language:{if(!this.currentTrack||this.currentTrack.languageCode!==G)break;this.currentTrack.languageCode=tt(e,n),zt(this.currentTrack.languageCode)||(this.currentTrack.languageCode=G)}break;case T.LanguageBCP47:{if(!this.currentTrack)break;let c=tt(e,n).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=G}break;case T.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case T.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=O(e,n)}break;case T.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=O(e,n)}break;case T.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=O(e,n)===1}break;case T.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,n))}break;case T.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=O(e,n),c=wi[o]??null;this.currentTrack.info.colorSpace.matrix=c}break;case T.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=O(e,n)===2}break;case T.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=O(e,n),c=gi[o]??null;this.currentTrack.info.colorSpace.transfer=c}break;case T.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=O(e,n),c=pi[o]??null;this.currentTrack.info.colorSpace.primaries=c}break;case T.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case T.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let c=-Li(e,n);try{this.currentTrack.info.rotation=mi(c)}catch{}}break;case T.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,n))}break;case T.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Li(e,n)}break;case T.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=O(e,n)}break;case T.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=O(e,n)}break;case T.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,n)),this.currentCueTime=null}break;case T.CueTime:this.currentCueTime=O(e,n);break;case T.CueTrackPositions:{if(this.currentCueTime===null)break;m(this.currentSegment);let o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(a,n)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case T.CueTrack:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=O(e,n)}break;case T.CueClusterPosition:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;m(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+O(e,n)}break;case T.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=O(e,n)}break;case T.SimpleBlock:{if(!this.currentCluster)break;let o=jt(e);if(o===null)break;let c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;let l=Br(e),d=v(e),u=d>>1&3,h=!!(d&128);c.track.info?.type==="audio"&&c.track.info.codec&&(h=!0);let f=F(e,n-(e.filePos-a)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:h,data:f,lacing:u,decoded:!p,mainAdditional:null})}break;case T.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,n)),this.currentBlock=null}break;case T.Block:{if(!this.currentCluster)break;let o=jt(e);if(o===null)break;let c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;let l=Br(e),u=v(e)>>1&3,h=F(e,n-(e.filePos-a)),f=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:h,lacing:u,decoded:!f,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case T.BlockAdditions:this.readContiguousElements(e.slice(a,n));break;case T.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,n)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case T.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=F(e,n)}break;case T.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=O(e,n)}break;case T.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=O(e,n)}break;case T.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case T.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,n));break;case T.Targets:this.readContiguousElements(e.slice(a,n));break;case T.TargetTypeValue:O(e,n)!==50&&(this.currentTagTargetIsMovie=!1);break;case T.TagTrackUID:case T.TagEditionUID:case T.TagChapterUID:case T.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case T.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,n))}break;case T.TagName:this.currentSimpleTagName=$t(e,n);break;case T.TagString:{if(!this.currentSimpleTagName)break;let o=$t(e,n);this.processTagValue(this.currentSimpleTagName,o)}break;case T.TagBinary:{if(!this.currentSimpleTagName)break;let o=F(e,n);this.processTagValue(this.currentSimpleTagName,o)}break;case T.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,n));let o=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(o.raw??={},o.raw[this.currentAttachedFile.fileUid.toString()]=new Cr(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let c=this.currentAttachedFile.fileName,l="unknown";if(c){let d=c.toLowerCase();d.startsWith("cover.")?l="coverFront":d.startsWith("back.")&&(l="coverBack")}o.images??=[],o.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case T.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Ha(e,n)}break;case T.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=$t(e,n)}break;case T.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=tt(e,n)}break;case T.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=F(e,n)}break;case T.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=$t(e,n)}break;case T.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,n)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case T.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Hi.Block,data:null},this.readContiguousElements(e.slice(a,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case T.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=O(e,n)}break;case T.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=O(e,n)}break;case T.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Or.Zlib,settings:null},this.readContiguousElements(e.slice(a,n))}break;case T.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=O(e,n)}break;case T.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=F(e,n)}break;case T.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+n,!0}decodeBlockData(e,r){m(e.decodingInstructions.length>0);let i=r;for(let s of e.decodingInstructions)switch(m(s.data),s.data.type){case"decompress":switch(s.data.algorithm){case Or.HeaderStripping:if(s.data.settings&&s.data.settings.length>0){let n=s.data.settings,a=new Uint8Array(n.length+i.length);a.set(n,0),a.set(i,n.length),i=a}break;default:}break;default:}return i}processTagValue(e,r){if(!this.currentSegment?.metadataTags)return;let i=this.currentSegment.metadataTags;if(i.raw??={},i.raw[e]??=r,typeof r=="string")switch(e.toLowerCase()){case"title":i.title??=r;break;case"description":i.description??=r;break;case"artist":i.artist??=r;break;case"album":i.album??=r;break;case"album_artist":i.albumArtist??=r;break;case"genre":i.genre??=r;break;case"comment":i.comment??=r;break;case"lyrics":i.lyrics??=r;break;case"date":{let s=new Date(r);Number.isNaN(s.getTime())||(i.date??=s)}break;case"track_number":case"part_number":{let s=r.split("/"),n=Number.parseInt(s[0],10),a=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(i.trackNumber??=n),a&&Number.isInteger(a)&&a>0&&(i.tracksTotal??=a)}break;case"disc_number":case"disc":{let s=r.split("/"),n=Number.parseInt(s[0],10),a=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(i.discNumber??=n),a&&Number.isInteger(a)&&a>0&&(i.discsTotal??=a)}break}}},ji=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,r=>r.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return gt(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,r){let i=this.intoTimescale(e);return this.performClusterLookup(null,s=>{let n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};let a=M(n.presentationTimestamps,i,l=>l.timestamp),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<n.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,r)}async getNextPacket(e,r){let i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,s=>{if(s===i.cluster){let n=s.trackData.get(this.internalTrack.id);if(i.blockIndex+1<n.blocks.length)return{blockIndex:i.blockIndex+1,correctBlockFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async getKeyPacket(e,r){let i=this.intoTimescale(e);return this.performClusterLookup(null,s=>{let n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};let a=bi(n.presentationTimestamps,l=>n.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=i),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<n.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,r)}async getNextKeyPacket(e,r){let i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,s=>{if(s===i.cluster){let a=s.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>i.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{let n=s.trackData.get(this.internalTrack.id);if(n&&n.firstKeyFrameTimestamp!==null){let a=n.blocks.findIndex(o=>o.isKeyFrame);return m(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async fetchPacketInCluster(e,r,i){if(r===-1)return null;let n=e.trackData.get(this.internalTrack.id).blocks[r];m(n),n.decoded||(n.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,n.data),n.decoded=!0);let a=i.metadataOnly?Y:n.data,o=n.timestamp/this.internalTrack.segment.timestampFactor,c=n.duration/this.internalTrack.segment.timestampFactor,l={};n.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=i.metadataOnly?Y:n.mainAdditional,l.alphaByteLength=n.mainAdditional.byteLength);let d=new L(a,n.isKeyFrame?"key":"delta",o,c,e.dataStartPos+r,n.data.byteLength,l);return this.packetToClusterLocation.set(d,{cluster:e,blockIndex:r}),d}async performClusterLookup(e,r,i,s,n){let{demuxer:a,segment:o}=this.internalTrack,c=null,l=null,d=-1;if(e){let{blockIndex:b,correctBlockFound:k}=r(e);if(k)return this.fetchPacketInCluster(e,b,n);b!==-1&&(l=e,d=b)}let u=M(this.internalTrack.cuePoints,i,b=>b.time),h=u!==-1?this.internalTrack.cuePoints[u]:null,f=M(this.internalTrack.clusterPositionCache,i,b=>b.startTimestamp),p=f!==-1?this.internalTrack.clusterPositionCache[f]:null,g=Math.max(h?.clusterPosition??0,p?.elementStartPos??0)||null,w;for(e?g===null||e.elementStartPos>=g?(w=e.elementEndPos,c=e):w=g:w=g??o.clusterSeekStartPos;o.elementEndPos===null||w<=o.elementEndPos-pe;){if(c){let E=c.trackData.get(this.internalTrack.id);if(E&&E.startTimestamp>s)break}let b=a.reader.requestSliceRange(w,pe,xe);if(b instanceof Promise&&(b=await b),!b)break;let k=w,y=Se(b);if(!y||!qt.includes(y.id)&&y.id!==T.Void){let E=await Ys(a.reader,k,qt,Math.min(o.elementEndPos??1/0,k+$a));if(E){w=E;continue}else break}let x=y.id,P=y.size,S=b.filePos;if(x===T.Cluster){c=await a.readCluster(k,o),P=c.elementEndPos-S;let{blockIndex:E,correctBlockFound:D}=r(c);if(D)return this.fetchPacketInCluster(c,E,n);E!==-1&&(l=c,d=E)}P===null&&(m(x!==T.Cluster),P=(await Wi(a.reader,S,Dr,o.elementEndPos)).pos-S);let A=S+P;if(o.elementEndPos===null){let E=a.reader.requestSliceRange(A,pe,xe);if(E instanceof Promise&&(E=await E),!E)break;if(Vi(E)===T.Segment){o.elementEndPos=A;break}}w=A}if(h&&(!l||l.elementStartPos<h.clusterPosition)){let b=this.internalTrack.cuePoints[u-1];m(!b||b.time<h.time);let k=b?.time??-1/0;return this.performClusterLookup(null,r,k,s,n)}return l?this.fetchPacketInCluster(l,d,n):null}},Js=class extends ji{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;return(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:Ti({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?Pi(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Ei(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Ii(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?vi(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},en=class extends ji{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:xi({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}};var Oc=[44100,48e3,32e3],zc=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Qa=1483304551,Ga=1231971951,Mc=(t,e,r,i,s)=>e===0?0:e===1?Math.floor(144*r/(i<<t))+s:e===2?Math.floor(144*r/i)+s:(Math.floor(12*r/i)+s)*4,Ka=(t,e)=>t===3?e===3?21:36:e===3?13:21,Xa=(t,e)=>{let r=t>>>24,i=t>>>16&255,s=t>>>8&255,n=t&255;if(r!==255&&i!==255&&s!==255&&n!==255)return{header:null,bytesAdvanced:4};if(r!==255)return{header:null,bytesAdvanced:1};if((i&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;i&16?a=i&8?0:1:(a=1,o=1);let c=i>>3&3,l=i>>1&3,d=s>>4&15,u=(s>>2&3)%3,h=s>>1&1,f=n>>6&3,p=n>>4&3,g=n>>3&1,w=n>>2&1,b=n&3,k=zc[a*16*4+l*16+d];if(k===-1)return{header:null,bytesAdvanced:1};let y=k*1e3,x=Oc[u]>>a+o,P=Mc(a,l,y,x,h);if(e!==null&&e<P)return{header:null,bytesAdvanced:1};let S;return c===3?S=l===3?384:1152:l===3?S=384:l===2?S=1152:S=576,{header:{totalSize:P,mpegVersionId:c,layer:l,bitrate:y,frequencyIndex:u,sampleRate:x,channel:f,modeExtension:p,copyright:g,original:w,emphasis:b,audioSamplesInFrame:S},bytesAdvanced:1}};var $i=t=>{let e=2130706432,r=0;for(;e!==0;)r>>=1,r|=t&e,e>>=8;return r};var Kt;(function(t){t[t.Unsynchronisation=128]="Unsynchronisation",t[t.ExtendedHeader=64]="ExtendedHeader",t[t.ExperimentalIndicator=32]="ExperimentalIndicator",t[t.Footer=16]="Footer"})(Kt||(Kt={}));var Xt;(function(t){t[t.ISO_8859_1=0]="ISO_8859_1",t[t.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",t[t.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",t[t.UTF_8=3]="UTF_8"})(Xt||(Xt={}));var zr=128,Zt=10,Yt=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],Ya=(t,e)=>{let r=t.filePos;e.raw??={},e.raw.TAG??=F(t,zr-3),t.filePos=r;let i=Gt(t,30);i&&(e.title??=i);let s=Gt(t,30);s&&(e.artist??=s);let n=Gt(t,30);n&&(e.album??=n);let a=Gt(t,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??=new Date(o,0,1));let c=F(t,30),l;if(c[28]===0&&c[29]!==0){let u=c[29];u>0&&(e.trackNumber??=u),t.skip(-30),l=Gt(t,28),t.skip(2)}else t.skip(-30),l=Gt(t,30);l&&(e.comment??=l);let d=v(t);d<Yt.length&&(e.genre??=Yt[d])},Gt=(t,e)=>{let r=F(t,e),i=wt(r.indexOf(0),r.length),s=r.subarray(0,i),n="";for(let a=0;a<s.length;a++)n+=String.fromCharCode(s[a]);return n.trimEnd()},Pt=t=>{let e=t.filePos,r=j(t,3),i=v(t),s=v(t),n=v(t),a=_(t);if(r!=="ID3"||i===255||s===255||(a&2155905152)!==0)return t.filePos=e,null;let o=$i(a);return{majorVersion:i,revision:s,flags:n,size:o}},Qi=(t,e,r)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let i=F(t,e.size),s=new tn(e,i);if(e.flags&Kt.Footer&&s.removeFooter(),e.flags&Kt.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&Kt.ExtendedHeader){let n=s.readU32();e.majorVersion===3?s.pos+=n:s.pos+=n-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){let n=s.readId3V2Frame();if(!n)break;let a=s.pos,o=s.pos+n.size,c=!1,l=!1,d=!1;if(e.majorVersion===3?(c=!!(n.flags&64),l=!!(n.flags&128)):e.majorVersion===4&&(c=!!(n.flags&4),l=!!(n.flags&8),d=!!(n.flags&2)||!!(e.flags&Kt.Unsynchronisation)),c){console.warn(`Skipping encrypted ID3v2 frame ${n.id}`),s.pos=o;continue}if(l){console.warn(`Skipping compressed ID3v2 frame ${n.id}`),s.pos=o;continue}switch(d&&s.ununsynchronizeRegion(s.pos,o),r.raw??={},n.id[0]==="T"?r.raw[n.id]??=s.readId3V2EncodingAndText(o):r.raw[n.id]??=s.readBytes(n.size),s.pos=a,n.id){case"TIT2":case"TT2":r.title??=s.readId3V2EncodingAndText(o);break;case"TIT3":case"TT3":r.description??=s.readId3V2EncodingAndText(o);break;case"TPE1":case"TP1":r.artist??=s.readId3V2EncodingAndText(o);break;case"TALB":case"TAL":r.album??=s.readId3V2EncodingAndText(o);break;case"TPE2":case"TP2":r.albumArtist??=s.readId3V2EncodingAndText(o);break;case"TRCK":case"TRK":{let h=s.readId3V2EncodingAndText(o).split("/"),f=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(r.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(r.tracksTotal??=p)}break;case"TPOS":case"TPA":{let h=s.readId3V2EncodingAndText(o).split("/"),f=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(r.discNumber??=f),p&&Number.isInteger(p)&&p>0&&(r.discsTotal??=p)}break;case"TCON":case"TCO":{let u=s.readId3V2EncodingAndText(o),h=/^\((\d+)\)/.exec(u);if(h){let f=Number.parseInt(h[1]);if(Yt[f]!==void 0){r.genre??=Yt[f];break}}if(h=/^\d+$/.exec(u),h){let f=Number.parseInt(h[0]);if(Yt[f]!==void 0){r.genre??=Yt[f];break}}r.genre??=u}break;case"TDRC":case"TDAT":{let u=s.readId3V2EncodingAndText(o),h=new Date(u);Number.isNaN(h.getTime())||(r.date??=h)}break;case"TYER":case"TYE":{let u=s.readId3V2EncodingAndText(o),h=Number.parseInt(u,10);Number.isInteger(h)&&(r.date??=new Date(h,0,1))}break;case"USLT":case"ULT":{let u=s.readU8();s.pos+=3,s.readId3V2Text(u,o),r.lyrics??=s.readId3V2Text(u,o)}break;case"COMM":case"COM":{let u=s.readU8();s.pos+=3,s.readId3V2Text(u,o),r.comment??=s.readId3V2Text(u,o)}break;case"APIC":case"PIC":{let u=s.readId3V2TextEncoding(),h;if(e.majorVersion===2){let w=s.readAscii(3);h=w==="PNG"?"image/png":w==="JPG"?"image/jpeg":"image/*"}else h=s.readId3V2Text(u,o);let f=s.readU8(),p=s.readId3V2Text(u,o).trimEnd(),g=o-s.pos;if(g>=0){let w=s.readBytes(g);r.images||(r.images=[]),r.images.push({data:w,mimeType:h,kind:f===3?"coverFront":f===4?"coverBack":"unknown",description:p})}}break;default:s.pos+=n.size;break}s.pos=o}},tn=class{constructor(e,r){this.header=e,this.bytes=r,this.pos=0,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let r=0;r<this.bytes.length;r++){let i=this.bytes[r];e.push(i),i===255&&r!==this.bytes.length-1&&this.bytes[r]===0&&r++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,r){let i=[];for(let a=e;a<r;a++){let o=this.bytes[a];i.push(o),o===255&&a!==r-1&&this.bytes[a+1]===0&&a++}let s=this.bytes.subarray(0,e),n=this.bytes.subarray(r);this.bytes=new Uint8Array(s.length+i.length+n.length),this.bytes.set(s,0),this.bytes.set(i,s.length),this.bytes.set(n,s.length+i.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-Zt),this.view=new DataView(this.bytes.buffer)}readBytes(e){let r=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,r}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),r=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+r}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let r="";for(let i=0;i<e;i++)r+=String.fromCharCode(this.view.getUint8(this.pos+i));return this.pos+=e,r}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let r=this.readU24();return{id:e,size:r,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let r=this.readU32(),i=this.header.majorVersion===4?$i(r):r,s=this.readU16(),n=this.pos,a=o=>{let c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;let l=this.readAscii(4);if(l!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(l))return!1}return!0};if(!a(i)){let o=this.header.majorVersion===4?r:$i(r);a(o)&&(i=o)}return this.pos=n,{id:e,size:i,flags:s}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,r){let i=this.pos,s=this.readBytes(r-this.pos);switch(e){case Xt.ISO_8859_1:{let n="";for(let a=0;a<s.length;a++){let o=s[a];if(o===0){this.pos=i+a+1;break}n+=String.fromCharCode(o)}return n}case Xt.UTF_16_WITH_BOM:if(s[0]===255&&s[1]===254){let n=new TextDecoder("utf-16le"),a=wt(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=i+Math.min(a+2,s.length),n.decode(s.subarray(2,a))}else if(s[0]===254&&s[1]===255){let n=new TextDecoder("utf-16be"),a=wt(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=i+Math.min(a+2,s.length),n.decode(s.subarray(2,a))}else{let n=wt(s.findIndex(a=>a===0),s.length);return this.pos=i+Math.min(n+1,s.length),ie.decode(s.subarray(0,n))}case Xt.UTF_16_BE_NO_BOM:{let n=new TextDecoder("utf-16be"),a=wt(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=i+Math.min(a+2,s.length),n.decode(s.subarray(0,a))}case Xt.UTF_8:{let n=wt(s.findIndex(a=>a===0),s.length);return this.pos=i+Math.min(n+1,s.length),ie.decode(s.subarray(0,n))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let r=this.readId3V2TextEncoding();return this.readId3V2Text(r,e)}};var Mr=async(t,e,r)=>{let i=e;for(;r===null||i<r;){let s=t.requestSlice(i,4);if(s instanceof Promise&&(s=await s),!s)break;let n=_(s),a=Xa(n,t.fileSize!==null?t.fileSize-i:null);if(a.header)return{header:a.header,startPos:i};i+=a.bytesAdvanced}return null};var Gi=class extends ae{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new le,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.tracks=[new J(this.input,new rn(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,Zt);if(o instanceof Promise&&(o=await o),!o){this.lastSampleLoaded=!0;return}let c=Pt(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}let e=await Mr(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let r=e.header;this.lastLoadedPos=e.startPos+r.totalSize-1;let i=Ka(r.mpegVersionId,r.channel),s=this.reader.requestSlice(e.startPos+i,4);if(s instanceof Promise&&(s=await s),s){let o=_(s);if(o===Qa||o===Ga)return}this.firstFrameHeader||(this.firstFrameHeader=r),r.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${r.sampleRate} Hz. Might be a bug, so please report this file.`);let n=r.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:n,dataStart:e.startPos,dataSize:r.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=r.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return m(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0,i=!1;for(;;){let s=this.reader.requestSlice(r,Zt);if(s instanceof Promise&&(s=await s),!s)break;let n=Pt(s);if(!n)break;i=!0;let a=this.reader.requestSlice(s.filePos,n.size);if(a instanceof Promise&&(a=await a),!a)break;Qi(a,n,this.metadataTags),r=s.filePos+n.size}if(!i&&this.reader.fileSize!==null&&this.reader.fileSize>=zr){let s=this.reader.requestSlice(this.reader.fileSize-zr,zr);s instanceof Promise&&(s=await s),m(s),j(s,3)==="TAG"&&Ya(s,this.metadataTags)}return this.metadataTags}finally{e()}}},rn=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return G}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...de}}async getDecoderConfig(){return m(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,r){if(e===-1)return null;let i=this.demuxer.loadedSamples[e];if(!i)return null;let s;if(r.metadataOnly)s=Y;else{let n=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=F(n,i.dataSize)}return new L(s,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,r){let i=await this.demuxer.readingMutex.acquire();try{let s=mt(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");let n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,r)}finally{i()}}async getPacket(e,r){let i=await this.demuxer.readingMutex.acquire();try{for(;;){let s=M(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,r);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,r);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}};var sn=1399285583,Uc=79764919,Ja=new Uint32Array(256);for(let t=0;t<256;t++){let e=t<<24;for(let r=0;r<8;r++)e=e&2147483648?e<<1^Uc:e<<1;Ja[t]=e>>>0&4294967295}var eo=t=>{let e=V(t),r=e.getUint32(22,!0);e.setUint32(22,0,!0);let i=0;for(let s=0;s<t.length;s++){let n=t[s];i=(i<<8^Ja[i>>>24^n])>>>0}return e.setUint32(22,r,!0),i},to=(t,e,r)=>{let i=0,s=null;if(t.length>0)if(e.codec==="vorbis"){m(e.vorbisInfo);let n=e.vorbisInfo.modeBlockflags.length,o=(1<<Xn(n-1))-1<<1,c=(t[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=r,d=e.vorbisInfo.modeBlockflags[c];if(s=e.vorbisInfo.blocksizes[d],d===1){let u=(o|1)+1,h=t[0]&u?1:0;l=e.vorbisInfo.blocksizes[h]}i=l!==null?l+s>>2:0}else e.codec==="opus"&&(i=Ca(t).durationInSamples);return{durationInSamples:i,vorbisBlockSize:s}},ro=t=>{let e="audio/ogg";if(t.codecStrings){let r=[...new Set(t.codecStrings)];e+=`; codecs="${r.join(", ")}"`}return e};var rt=27,It=282,io=It+65025,Jt=t=>{let e=t.filePos;if(Et(t)!==sn)return null;t.skip(1);let i=v(t),s=no(t),n=Et(t),a=Et(t),o=Et(t),c=v(t),l=new Uint8Array(c);for(let f=0;f<c;f++)l[f]=v(t);let d=27+c,u=l.reduce((f,p)=>f+p,0),h=d+u;return{headerStartPos:e,totalSize:h,dataStartPos:e+d,dataSize:u,headerType:i,granulePosition:s,serialNumber:n,sequenceNumber:a,checksum:o,lacingValues:l}},so=(t,e)=>{for(;t.filePos<e-3;){let r=Et(t),i=r&255,s=r>>>8&255,n=r>>>16&255,a=r>>>24&255,o=79;if(!(i!==o&&s!==o&&n!==o&&a!==o)){if(t.skip(-4),r===sn)return!0;t.skip(1)}}return!1};var Ki=class extends ae{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,rt,It);if(r instanceof Promise&&(r=await r),!r)break;let i=Jt(r);if(!i||!!!(i.headerType&2))break;this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(let r of this.bitstreams){let i=await this.readPacket(r.bosPage,0);i&&(i.data.byteLength>=7&&i.data[0]===1&&i.data[1]===118&&i.data[2]===111&&i.data[3]===114&&i.data[4]===98&&i.data[5]===105&&i.data[6]===115?await this.readVorbisMetadata(i,r):i.data.byteLength>=8&&i.data[0]===79&&i.data[1]===112&&i.data[2]===117&&i.data[3]===115&&i.data[4]===72&&i.data[5]===101&&i.data[6]===97&&i.data[7]===100&&await this.readOpusMetadata(i,r),r.codecInfo.codec!==null&&this.tracks.push(new J(this.input,new nn(r,this))))}})()}async readVorbisMetadata(e,r){let i=await this.findNextPacketStart(e);if(!i)return;let s=await this.readPacket(i.startPage,i.startSegmentIndex);if(!s||(i=await this.findNextPacketStart(s),!i))return;let n=await this.readPacket(i.startPage,i.startSegmentIndex);if(!n||s.data[0]!==3||n.data[0]!==5)return;let a=[],o=u=>{for(;a.push(Math.min(255,u)),!(u<255);)u-=255};o(e.data.length),o(s.data.length);let c=new Uint8Array(1+a.length+e.data.length+s.data.length+n.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(s.data,1+a.length+e.data.length),c.set(n.data,1+a.length+e.data.length+s.data.length),r.codecInfo.codec="vorbis",r.description=c,r.lastMetadataPacket=n;let l=V(e.data);r.numberOfChannels=l.getUint8(11),r.sampleRate=l.getUint32(12,!0);let d=l.getUint8(28);r.codecInfo.vorbisInfo={blocksizes:[1<<(d&15),1<<(d>>4)],modeBlockflags:_a(n.data).modeBlockflags},Pr(s.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,r){let i=await this.findNextPacketStart(e);if(!i)return;let s=await this.readPacket(i.startPage,i.startSegmentIndex);if(!s)return;r.codecInfo.codec="opus",r.description=e.data,r.lastMetadataPacket=s;let n=Ai(e.data);r.numberOfChannels=n.outputChannelCount,r.sampleRate=kt,r.codecInfo.opusInfo={preSkip:n.preSkip},Pr(s.data.subarray(8),this.metadataTags)}async readPacket(e,r){m(r<e.lacingValues.length);let i=0;for(let u=0;u<r;u++)i+=e.lacingValues[u];let s=e,n=i,a=r,o=[];e:for(;;){let u=this.reader.requestSlice(s.dataStartPos,s.dataSize);u instanceof Promise&&(u=await u),m(u);let h=F(u,s.dataSize);for(;;){if(a===s.lacingValues.length){o.push(h.subarray(i,n));break}let p=s.lacingValues[a];if(n+=p,p<255){o.push(h.subarray(i,n));break e}a++}let f=s.headerStartPos+s.totalSize;for(;;){let p=this.reader.requestSliceRange(f,rt,It);if(p instanceof Promise&&(p=await p),!p)return null;let g=Jt(p);if(!g)return null;if(s=g,s.serialNumber===e.serialNumber)break;f=s.headerStartPos+s.totalSize}i=0,n=0,a=0}let c=o.reduce((u,h)=>u+h.length,0),l=new Uint8Array(c),d=0;for(let u=0;u<o.length;u++){let h=o[u];l.set(h,d),d+=h.length}return{data:l,endPage:s,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let i=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let s=this.reader.requestSliceRange(i,rt,It);if(s instanceof Promise&&(s=await s),!s)return null;let n=Jt(s);if(!n)return null;if(n.serialNumber===e.endPage.serialNumber)return{startPage:n,startSegmentIndex:0};i=n.headerStartPos+n.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(r=>r.getCodecParameterString()));return ro({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),r=await Promise.all(e.map(i=>i.computeDuration()));return Math.max(0,...r)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},nn=class{constructor(e,r){this.bitstream=e,this.demuxer=r,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new le,this.internalSampleRate=e.codecInfo.codec==="opus"?kt:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return m(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return G}getDisposition(){return{...de}}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(m(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,r,i){if(!e)return null;let{durationInSamples:s,vorbisBlockSize:n}=to(e.data,this.bitstream.codecInfo,r.vorbisLastBlocksize),a=new L(i.metadataOnly?Y:e.data,"key",Math.max(0,r.timestampInSamples)/this.internalSampleRate,s/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:r.timestampInSamples,durationInSamples:s,vorbisLastBlockSize:r.vorbisLastBlocksize,vorbisBlockSize:n}),a}async getFirstPacket(e){m(this.bitstream.lastMetadataPacket);let r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let i=0;this.bitstream.codecInfo.codec==="opus"&&(m(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);let s=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,r){let i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");let s=await this.demuxer.findNextPacketStart(i.packet);if(!s)return null;let n=i.timestampInSamples+i.durationInSamples,a=await this.demuxer.readPacket(s.startPage,s.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:n,vorbisLastBlocksize:i.vorbisBlockSize},r)}async getPacket(e,r){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,r);let i=gt(e*this.internalSampleRate);if(i===0)return this.getFirstPacket(r);if(i<0)return null;m(this.bitstream.lastMetadataPacket);let s=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let n=s.startPage,a=this.demuxer.reader.fileSize,o=[n];e:for(;n.headerStartPos+n.totalSize<a;){let k=n.headerStartPos,y=Math.floor((k+a)/2),x=y;for(;;){let P=Math.min(x+io,a-rt),S=this.demuxer.reader.requestSlice(x,P-x);if(S instanceof Promise&&(S=await S),m(S),!so(S,P)){a=y+rt;continue e}let E=this.demuxer.reader.requestSliceRange(S.filePos,rt,It);E instanceof Promise&&(E=await E),m(E);let D=Jt(E);m(D);let N=!1;if(D.serialNumber===this.bitstream.serialNumber)N=!0;else{let re=this.demuxer.reader.requestSlice(D.headerStartPos,D.totalSize);re instanceof Promise&&(re=await re),m(re);let nt=F(re,D.totalSize);N=eo(nt)===D.checksum}if(!N){x=D.headerStartPos+4;continue}if(N&&D.serialNumber!==this.bitstream.serialNumber){x=D.headerStartPos+D.totalSize;continue}if(D.granulePosition===-1){x=D.headerStartPos+D.totalSize;continue}this.granulePositionToTimestampInSamples(D.granulePosition)>i?a=D.headerStartPos:(n=D,o.push(D));continue e}}let c=s.startPage;for(let k of o){if(k.granulePosition===n.granulePosition)break;(!c||k.headerStartPos>c.headerStartPos)&&(c=k)}let l=c,d=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===n.granulePosition);){let k=l.headerStartPos+l.totalSize,y=this.demuxer.reader.requestSliceRange(k,rt,It);y instanceof Promise&&(y=await y),m(y);let x=Jt(y);m(x),l=x,l.serialNumber===this.bitstream.serialNumber&&d.push(l)}m(l.granulePosition!==-1);let u=null,h,f,p=l,g=0;if(l.headerStartPos===s.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),f=!0,u=0;else{h=0,f=!1;for(let x=l.lacingValues.length-1;x>=0;x--)if(l.lacingValues[x]<255){u=x+1;break}if(u===null)throw new Error("Invalid page with granule position: no packets end on this page.");g=u-1;let k={data:Y,endPage:p,endSegmentIndex:g};if(await this.demuxer.findNextPacketStart(k)){let x=oo(d,l,u);m(x);let P=ao(d,x.page,x.segmentIndex);P&&(l=P.page,u=P.segmentIndex)}else for(;;){let x=oo(d,l,u);if(!x)break;let P=ao(d,x.page,x.segmentIndex);if(!P)break;if(l=P.page,u=P.segmentIndex,x.page.headerStartPos!==p.headerStartPos){p=x.page,g=x.segmentIndex;break}}}let w=null,b=null;for(;l!==null;){m(u!==null);let k=await this.demuxer.readPacket(l,u);if(!k)break;if(!(l.headerStartPos===s.startPage.headerStartPos&&u<s.startSegmentIndex)){let P=this.createEncodedPacketFromOggPacket(k,{timestampInSamples:h,vorbisLastBlocksize:b?.vorbisBlockSize??null},r);m(P);let S=this.encodedPacketToMetadata.get(P);if(m(S),!f&&k.endPage.headerStartPos===p.headerStartPos&&k.endSegmentIndex===g?(h=this.granulePositionToTimestampInSamples(l.granulePosition),f=!0,P=this.createEncodedPacketFromOggPacket(k,{timestampInSamples:h-S.durationInSamples,vorbisLastBlocksize:b?.vorbisBlockSize??null},r),m(P),S=this.encodedPacketToMetadata.get(P),m(S)):h+=S.durationInSamples,w=P,b=S,f&&(Math.max(h,0)>i||Math.max(S.timestampInSamples,0)===i))break}let x=await this.demuxer.findNextPacketStart(k);if(!x)break;l=x.startPage,u=x.startSegmentIndex}return w}async getPacketSequential(e,r){let i=await this.sequentialScanMutex.acquire();try{let s=gt(e*this.internalSampleRate);e=s/this.internalSampleRate;let n=M(this.sequentialScanCache,s,c=>c.timestampInSamples),a;if(n!==-1){let c=this.sequentialScanCache[n];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},r)}else a=await this.getFirstPacket(r);let o=0;for(;a&&a.timestamp<e;){let c=await this.getNextPacket(a,r);if(!c||c.timestamp>e)break;if(a=c,o++,o===100){o=0;let l=this.encodedPacketToMetadata.get(a);m(l),this.sequentialScanCache.length>0&&m(q(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return a}finally{i()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}},ao=(t,e,r)=>{let i=e,s=r;e:for(;;){for(s--,s;s>=0;s--)if(i.lacingValues[s]<255){s++;break e}if(m(s===-1),!(i.headerType&1)){s=0;break}let a=Es(t,o=>o.headerStartPos<i.headerStartPos);if(!a)return null;i=a,s=i.lacingValues.length}if(m(s!==-1),s===i.lacingValues.length){let n=t[t.indexOf(i)+1];m(n),i=n,s=0}return{page:i,segmentIndex:s}},oo=(t,e,r)=>{if(r>0)return{page:e,segmentIndex:r-1};let i=Es(t,s=>s.headerStartPos<e.headerStartPos);return i?{page:i,segmentIndex:i.lacingValues.length-1}:null};var $e;(function(t){t[t.PCM=1]="PCM",t[t.IEEE_FLOAT=3]="IEEE_FLOAT",t[t.ALAW=6]="ALAW",t[t.MULAW=7]="MULAW",t[t.EXTENSIBLE=65534]="EXTENSIBLE"})($e||($e={}));var Xi=class extends ae{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),m(e);let r=j(e,4),i=r!=="RIFX",s=r==="RF64",n=Qe(e,i),a=s?this.reader.fileSize:Math.min(n+8,this.reader.fileSize??1/0);if(j(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,d=e.filePos;for(;a===null||d<a;){let h=this.reader.requestSlice(d,8);if(h instanceof Promise&&(h=await h),!h)break;let f=j(h,4),p=Qe(h,i),g=h.filePos;if(s&&c===0&&f!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(f==="fmt ")await this.parseFmtChunk(g,p,i);else if(f==="data"){if(l??=p,this.dataStart=h.filePos,this.dataSize=Math.min(l,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(f==="ds64"){let w=this.reader.requestSlice(g,p);if(w instanceof Promise&&(w=await w),!w)break;let b=on(w,i);l=on(w,i),a=Math.min(b+8,this.reader.fileSize??1/0)}else f==="LIST"?await this.parseListChunk(g,p,i):(f==="ID3 "||f==="id3 ")&&await this.parseId3Chunk(g,p);d=g+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let u=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/u)*u,this.tracks.push(new J(this.input,new an(this)))})()}async parseFmtChunk(e,r,i){let s=this.reader.requestSlice(e,r);if(s instanceof Promise&&(s=await s),!s)return;let n=tr(s,i),a=tr(s,i),o=Qe(s,i);s.skip(4);let c=tr(s,i),l;if(r===14?l=8:l=tr(s,i),r>=18&&n!==357){let d=tr(s,i),u=r-18;if(Math.min(u,d)>=22&&n===$e.EXTENSIBLE){s.skip(6);let f=F(s,16);n=f[0]|f[1]<<8}}(n===$e.MULAW||n===$e.ALAW)&&(l=8),this.audioInfo={format:n,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,r,i){let s=this.reader.requestSlice(e,r);if(s instanceof Promise&&(s=await s),!s)return;let n=j(s,4);if(n!=="INFO"&&n!=="INF0")return;let a=s.filePos;for(;a<=e+r-8;){s.filePos=a;let o=j(s,4),c=Qe(s,i),l=F(s,c),d=0;for(let h=0;h<l.length&&l[h]!==0;h++)d++;let u=String.fromCharCode(...l.subarray(0,d));switch(this.metadataTags.raw??={},this.metadataTags.raw[o]=u,o){case"INAM":case"TITL":this.metadataTags.title??=u;break;case"TIT3":this.metadataTags.description??=u;break;case"IART":this.metadataTags.artist??=u;break;case"IPRD":this.metadataTags.album??=u;break;case"IPRT":case"ITRK":case"TRCK":{let h=u.split("/"),f=Number.parseInt(h[0],10),p=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let h=new Date(u);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"YEAR":{let h=Number.parseInt(u,10);Number.isInteger(h)&&h>0&&(this.metadataTags.date??=new Date(h,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=u;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=u;break}a+=8+c+(c&1)}}async parseId3Chunk(e,r){let i=this.reader.requestSlice(e,r);if(i instanceof Promise&&(i=await i),!i)return;let s=Pt(i);if(s){let n=i.slice(e+10,s.size);Qi(n,s,this.metadataTags)}}getCodec(){if(m(this.audioInfo),this.audioInfo.format===$e.MULAW)return"ulaw";if(this.audioInfo.format===$e.ALAW)return"alaw";if(this.audioInfo.format===$e.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===$e.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return m(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},er=2048,an=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(m(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return G}getDisposition(){return{...de}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,r){m(this.demuxer.audioInfo);let i=e*er*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;let s=Math.min(er*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-i);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,s);if(c instanceof Promise&&(c=await c),!c)return null}let n;if(r.metadataOnly)n=Y;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,s);c instanceof Promise&&(c=await c),m(c),n=F(c,s)}let a=e*er/this.demuxer.audioInfo.sampleRate,o=s/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,a),new L(n,"key",a,o,e,s)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,r){m(this.demuxer.audioInfo);let i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/er,(this.demuxer.dataSize-1)/(er*this.demuxer.audioInfo.blockSizeInBytes))),s=await this.getPacketAtIndex(i,r);if(s)return s;if(i===0)return null;m(this.demuxer.reader.fileSize===null);let n=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,r);for(;n;){let a=await this.getNextPacket(n,r);if(!a)break;n=a}return n}getNextPacket(e,r){m(this.demuxer.audioInfo);let i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/er);return this.getPacketAtIndex(i+1,r)}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}};var rr=7,ir=9,Ur=t=>{let e=t.filePos,r=F(t,9),i=new H(r);if(i.readBits(12)!==4095||(i.skipBits(1),i.readBits(2)!==0))return null;let a=i.readBits(1),o=i.readBits(2)+1,c=i.readBits(4);if(c===15)return null;i.skipBits(1);let l=i.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);let d=i.readBits(13);i.skipBits(11);let u=i.readBits(2)+1;if(u!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let h=null;return a===1?t.filePos-=2:h=i.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:d,numberOfAacFrames:u,crcCheck:h,startPos:e}};var cn=1024,Yi=class extends ae{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new le,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();m(this.firstFrameHeader),this.tracks=[new J(this.input,new ln(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,rr,ir);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let r=Ur(e);if(!r){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&r.startPos+r.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=r);let i=Ut[r.samplingFrequencyIndex];m(i!==void 0);let s=cn/i,n=r.crcCheck?ir:rr,a={timestamp:this.nextTimestampInSamples/i,duration:s,dataStart:r.startPos+n,dataSize:r.frameLength-n};this.loadedSamples.push(a),this.nextTimestampInSamples+=cn,this.lastLoadedPos=r.startPos+r.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return m(e),e.computeDuration()}async getMetadataTags(){return{}}},ln=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/cn}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return G}getCodec(){return"aac"}getInternalCodecId(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){m(this.demuxer.firstFrameHeader);let e=Si[this.demuxer.firstFrameHeader.channelConfiguration];return m(e!==void 0),e}getSampleRate(){m(this.demuxer.firstFrameHeader);let e=Ut[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return m(e!==void 0),e}getDisposition(){return{...de}}async getDecoderConfig(){m(this.demuxer.firstFrameHeader);let e=new Uint8Array(3),r=new H(e),{objectType:i,samplingFrequencyIndex:s,channelConfiguration:n}=this.demuxer.firstFrameHeader;return i>31?(r.writeBits(5,31),r.writeBits(6,i-32)):r.writeBits(5,i),r.writeBits(4,s),r.writeBits(4,n),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((r.pos-1)/8))}}async getPacketAtIndex(e,r){if(e===-1)return null;let i=this.demuxer.loadedSamples[e];if(!i)return null;let s;if(r.metadataOnly)s=Y;else{let n=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=F(n,i.dataSize)}return new L(s,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,r){let i=await this.demuxer.readingMutex.acquire();try{let s=mt(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");let n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,r)}finally{i()}}async getPacket(e,r){let i=await this.demuxer.readingMutex.acquire();try{for(;;){let s=M(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,r);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,r);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}};var co=t=>t===0?null:t===1?192:t>=2&&t<=5?144*2**t:t===6?"uncommon-u8":t===7?"uncommon-u16":t>=8&&t<=15?2**t:null,lo=(t,e)=>{switch(t){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},uo=t=>{let e=0,r=new H(F(t,1));for(;r.readBits(1)===1;)e++;if(e===0)return r.readBits(7);let i=[],s=e-1,n=new H(F(t,s)),a=8-e-1;for(let c=0;c<a;c++)i.unshift(r.readBits(1));for(let c=0;c<s;c++)for(let l=0;l<8;l++){let d=n.readBits(1);l<2||i.unshift(d)}return i.reduce((c,l,d)=>c|l<<d,0)},ho=(t,e)=>{if(e==="uncommon-u16")return ee(t)+1;if(e==="uncommon-u8")return v(t)+1;if(typeof e=="number")return e;ne(e),m(!1)},fo=(t,e)=>e==="uncommon-u16"?ee(t):e==="uncommon-u16-10"?ee(t)*10:e==="uncommon-u8"?v(t):typeof e=="number"?e:null,mo=t=>{let r=0;for(let i of t){r^=i;for(let s=0;s<8;s++)(r&128)!==0?r=r<<1^7:r<<=1,r&=255}return r};var Zi=class extends ae{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new le,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),m(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),m(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||e<this.reader.fileSize;){let r=this.reader.requestSlice(e,4);if(r instanceof Promise&&(r=await r),e+=4,r===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);m(r);let i=v(r),s=et(r),n=(i&128)!==0;switch(i&127){case Ze.STREAMINFO:{let o=this.reader.requestSlice(e,s);if(o instanceof Promise&&(o=await o),m(o),o===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=F(o,34),l=new H(c),d=l.readBits(16),u=l.readBits(16),h=l.readBits(24),f=l.readBits(24),p=l.readBits(20),g=l.readBits(3)+1;l.readBits(5);let w=l.readBits(36);l.skipBits(128);let b=new Uint8Array(42);b.set(new Uint8Array([102,76,97,67]),0),b.set(new Uint8Array([128,0,0,34]),4),b.set(c,8),this.audioInfo={numberOfChannels:g,sampleRate:p,totalSamples:w,minimumBlockSize:d,maximumBlockSize:u,minimumFrameSize:h,maximumFrameSize:f,description:b},this.track=new J(this.input,new un(this));break}case Ze.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,s);o instanceof Promise&&(o=await o),m(o),Pr(F(o,s),this.metadataTags);break}case Ze.PICTURE:{let o=this.reader.requestSlice(e,s);o instanceof Promise&&(o=await o),m(o);let c=_(o),l=_(o),d=ie.decode(F(o,l)),u=_(o),h=ie.decode(F(o,u));o.skip(16);let f=_(o),p=F(o,f);this.metadataTags.images??=[],this.metadataTags.images.push({data:p,mimeType:d,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:h});break}default:break}if(e+=s,n){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:r}){m(this.audioInfo);let i=6,n=this.audioInfo.maximumFrameSize+16,a=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,n);if(!a)return null;let o=this.readFlacFrameHeader({slice:a,isFirstPacket:r});if(!o)return null;for(a.filePos=e+this.audioInfo.minimumFrameSize;;){if(a.filePos>a.end-i)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:a.end-e,isLastFrame:!0};if(v(a)===255){let l=a.filePos,d=v(a),u=this.blockingBit===1?249:248;if(d!==u){a.filePos=l;continue}a.skip(-2);let h=a.filePos-e,f=this.readFlacFrameHeader({slice:a,isFirstPacket:!1});if(!f){a.filePos=l;continue}if(this.blockingBit===0){if(f.num-o.num!==1){a.filePos=l;continue}}else if(f.num-o.num!==o.blockSize){a.filePos=l;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:h,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:r}){let i=e.filePos,s=F(e,4),n=new H(s);if(n.readBits(15)!==32764)return null;if(this.blockingBit===null){m(r);let w=n.readBits(1);this.blockingBit=w}else if(this.blockingBit===1){if(m(!r),n.readBits(1)!==1)return null}else if(this.blockingBit===0){if(m(!r),n.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let o=co(n.readBits(4));if(!o)return null;m(this.audioInfo);let c=lo(n.readBits(4),this.audioInfo.sampleRate);if(!c||(n.readBits(4),n.readBits(3),n.readBits(1)!==0))return null;let d=uo(e),u=ho(e,o),h=fo(e,c);if(h===null||h!==this.audioInfo.sampleRate)return null;let f=e.filePos-i,p=v(e);e.skip(-f),e.skip(-1);let g=mo(F(e,f));return p!==g?null:{num:d,blockSize:u,sampleRate:h}}async advanceReader(){await this.readMetadata(),m(this.lastLoadedPos!==null),m(this.audioInfo);let e=this.lastLoadedPos,r=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!r){this.lastSampleLoaded=!0;return}let i=this.loadedSamples[this.loadedSamples.length-1],n={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:r.blockSize,byteOffset:e,byteSize:r.size};if(this.lastLoadedPos=this.lastLoadedPos+r.size,this.loadedSamples.push(n),r.isLastFrame){this.lastSampleLoaded=!0;return}}},un=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return G}getTimeResolution(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...de}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return m(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,r){if(m(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");let i=await this.demuxer.readingMutex.acquire();try{for(;;){let s=M(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(s===-1){await this.demuxer.advanceReader();continue}let n=this.demuxer.loadedSamples[s],a=n.blockOffset/this.demuxer.audioInfo.sampleRate,o=n.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,r);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(s,r)}}finally{i()}}async getNextPacket(e,r){let i=await this.demuxer.readingMutex.acquire();try{let s=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&s>=this.demuxer.loadedSamples.length)return null;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,r)}finally{i()}}getKeyPacket(e,r){return this.getPacket(e,r)}getNextKeyPacket(e,r){return this.getNextPacket(e,r)}async getPacketAtIndex(e,r){let i=this.demuxer.loadedSamples[e];if(!i)return null;let s;if(r.metadataOnly)s=Y;else{let o=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(o instanceof Promise&&(o=await o),!o)return null;s=F(o,i.byteSize)}m(this.demuxer.audioInfo);let n=i.blockOffset/this.demuxer.audioInfo.sampleRate,a=i.blockSize/this.demuxer.audioInfo.sampleRate;return new L(s,"key",n,a,e,i.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}};var be=class{},Nr=class extends be{async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);return r instanceof Promise&&(r=await r),!r||(r.skip(4),j(r,4)!=="ftyp")?null:j(r,4)}_createDemuxer(e){return new Mi(e)}},Ji=class extends Nr{async _canReadInput(e){let r=await this._getMajorBrand(e);return!!r&&r!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},es=class extends Nr{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},Vr=class extends be{async isSupportedEBMLOfDocType(e,r){let i=e._reader.requestSlice(0,xe);if(i instanceof Promise&&(i=await i),!i)return!1;let s=Ks(i);if(s===null||s<1||s>8||O(i,s)!==T.EBML)return!1;let a=Xs(i);if(a===null)return!1;let o=e._reader.requestSlice(i.filePos,a);if(o instanceof Promise&&(o=await o),!o)return!1;let c=i.filePos;for(;o.filePos<=c+a-pe;){let l=Se(o);if(!l)break;let{id:d,size:u}=l,h=o.filePos;if(u===null)return!1;switch(d){case T.EBMLVersion:if(O(o,u)!==1)return!1;break;case T.EBMLReadVersion:if(O(o,u)!==1)return!1;break;case T.DocType:if(tt(o,u)!==r)return!1;break;case T.DocTypeVersion:if(O(o,u)>4)return!1;break}o.filePos=h+u}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new qi(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},ts=class extends Vr{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},rs=class extends be{async _canReadInput(e){let r=e._reader.requestSlice(0,10);if(r instanceof Promise&&(r=await r),!r)return!1;let i=0,s=!1;for(;;){let l=e._reader.requestSlice(i,Zt);if(l instanceof Promise&&(l=await l),!l)break;let d=Pt(l);if(!d)break;s=!0,i=l.filePos+d.size}let n=await Mr(e._reader,i,i+4096);if(!n)return!1;if(s)return!0;i=n.startPos+n.header.totalSize;let a=await Mr(e._reader,i,i+4);if(!a)return!1;let o=n.header,c=a.header;return!(o.channel!==c.channel||o.sampleRate!==c.sampleRate)}_createDemuxer(e){return new Gi(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},is=class extends be{async _canReadInput(e){let r=e._reader.requestSlice(0,12);if(r instanceof Promise&&(r=await r),!r)return!1;let i=j(r,4);return i!=="RIFF"&&i!=="RIFX"&&i!=="RF64"?!1:(r.skip(4),j(r,4)==="WAVE")}_createDemuxer(e){return new Xi(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},ss=class extends be{async _canReadInput(e){let r=e._reader.requestSlice(0,4);return r instanceof Promise&&(r=await r),r?j(r,4)==="OggS":!1}_createDemuxer(e){return new Ki(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},ns=class extends be{async _canReadInput(e){let r=e._reader.requestSlice(0,4);return r instanceof Promise&&(r=await r),r?j(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Zi(e)}},as=class extends be{async _canReadInput(e){let r=e._reader.requestSliceRange(0,rr,ir);if(r instanceof Promise&&(r=await r),!r)return!1;let i=Ur(r);if(!i||(r=e._reader.requestSliceRange(i.frameLength,rr,ir),r instanceof Promise&&(r=await r),!r))return!1;let s=Ur(r);return s?i.objectType===s.objectType&&i.samplingFrequencyIndex===s.samplingFrequencyIndex&&i.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new Yi(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},po=new Ji,go=new es,wo=new Vr,bo=new ts,ko=new rs,yo=new is,To=new ss,xo=new as,So=new ns,os=[po,go,wo,bo,yo,To,So,ko,xo];var vt=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new Z;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new Z;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}};var Lr=class extends vt{constructor(e,r={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!Sr(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new cs({maxCacheSize:r.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:_o.fileSystem})}_retrieveSize(){let e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){let r=this._readers.get(e);for(r===void 0&&("stream"in this._blob&&!Ye()?r=this._blob.slice(e.currentPos).stream().getReader():r=null,this._readers.set(e,r));e.currentPos<e.targetPos&&!e.aborted;)if(r){let{done:i,value:s}=await r.read();if(i)throw this._orchestrator.forgetWorker(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+s.length),this._orchestrator.supplyWorkerData(e,s)}else{let i=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+i.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(i))}e.running=!1,e.aborted&&await r?.cancel()}_dispose(){this._orchestrator.dispose()}},Co=.5*2**20,Nc=((t,e,r)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))){let s=null;try{typeof window<"u"&&typeof window.location<"u"&&(s=new URL(r instanceof Request?r.url:r,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&s!==null&&s!==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**(t-2),16)}),Wr=class extends vt{constructor(e,r={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.requestInit!==void 0&&(!r.requestInit||typeof r.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(r.getRetryDelay!==void 0&&typeof r.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(r.maxCacheSize!==void 0&&(!Sr(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(r.fetchFn!==void 0&&typeof r.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=r,this._getRetryDelay=r.getRetryDelay??Nc,this._orchestrator=new cs({maxCacheSize:r.maxCacheSize??64*2**20,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:_o.network})}async _retrieveSize(){let e=new AbortController,r=await vs(this._options.fetchFn??fetch,this._url,Is(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);let i,s;if(r.status===206)s=this._getTotalLengthFromRangeResponse(r),i=this._orchestrator.createWorker(0,Math.min(s,Co));else{let n=r.headers.get("Content-Length");if(n)s=Number(n),i=this._orchestrator.createWorker(0,s),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 new Error(`HTTP response (status ${r.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=s,this._existingResponses.set(i,{response:r,abortController:e}),this._orchestrator.runWorker(i),s}_read(e,r){return this._orchestrator.read(e,r)}async _runWorker(e){for(;;){let r=this._existingResponses.get(e);this._existingResponses.delete(e);let i=r?.abortController,s=r?.response;if(i||(i=new AbortController,s=await vs(this._options.fetchFn??fetch,this._url,Is(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:i.signal}),this._getRetryDelay,()=>this._disposed)),m(s),!s.ok)throw new Error(`Error fetching ${String(this._url)}: ${s.status} ${s.statusText}`);if(e.currentPos>0&&s.status!==206)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!s.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let n=s.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){i.abort(),e.running=!1;return}let a;try{a=await n.read()}catch(l){if(this._disposed)throw l;let d=this._getRetryDelay(1,l,this._url);if(d!==null){console.error("Error while reading response stream. Attempting to resume.",l),await new Promise(u=>setTimeout(u,1e3*d));break}else throw l}if(e.aborted)continue;let{done:o,value:c}=a;if(o){if(e.currentPos>=e.targetPos){this._orchestrator.forgetWorker(e),e.running=!1;return}break}this.onread?.(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}}_getTotalLengthFromRangeResponse(e){let r=e.headers.get("Content-Range");if(r){let s=/\/(\d+)/.exec(r);if(s)return Number(s[1])}let i=e.headers.get("Content-Length");if(i)return Number(i);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}};var _o={none:(t,e)=>({start:t,end:e}),fileSystem:(t,e)=>(t=Math.floor((t-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:t,end:e}),network:(t,e,r)=>{t=Math.max(0,Math.floor((t-65536)/65536)*65536);for(let s of r){let a=Math.max((s.startPos+s.targetPos)/2,s.targetPos-8388608);if(ki(t,e,a,s.targetPos)){let o=s.targetPos-s.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),d=Math.min(l,c);e=Math.max(e,s.startPos+d)}}return e=Math.max(e,t+Co),{start:t,end:e}}},cs=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,r){m(this.fileSize!==null);let i=this.options.prefetchProfile(e,r,this.workers),s=Math.max(i.start,0),n=Math.min(i.end,this.fileSize);m(s<=e&&r<=n);let a=null,o=M(this.cache,e,k=>k.start),c=o!==-1?this.cache[o]:null;c&&c.start<=e&&r<=c.end&&(c.age=this.nextAge++,a={bytes:c.bytes,view:c.view,offset:c.start});let l=M(this.cache,s,k=>k.start),d=a?null:new Uint8Array(r-e),u=0,h=s,f=[];if(l!==-1){for(let k=l;k<this.cache.length;k++){let y=this.cache[k];if(y.start>=n)break;if(y.end<=s)continue;let x=Math.max(s,y.start),P=Math.min(n,y.end);if(m(x<=P),h<x&&f.push({start:h,end:x}),h=P,d){let S=Math.max(e,y.start),A=Math.min(r,y.end);if(S<A){let E=S-e;d.set(y.bytes.subarray(S-y.start,A-y.start),E),E===u&&(u=A-e)}}y.age=this.nextAge++}h<n&&f.push({start:h,end:n})}else f.push({start:s,end:n});if(d&&u>=d.length&&(a={bytes:d,view:V(d),offset:e}),f.length===0)return m(a),a;let{promise:p,resolve:g,reject:w}=se(),b=[];for(let k of f){let y=Math.max(e,k.start),x=Math.min(r,k.end);y===k.start&&x===k.end?b.push(k):y<x&&b.push({start:y,end:x})}for(let k of f){let y=d&&{start:e,bytes:d,holes:b,resolve:g,reject:w},x=!1;for(let P of this.workers)if(ki(k.start-131072,k.start,P.currentPos,P.targetPos)){P.targetPos=Math.max(P.targetPos,k.end),x=!0,y&&!P.pendingSlices.includes(y)&&P.pendingSlices.push(y),P.running||this.runWorker(P);break}if(!x){let P=this.createWorker(k.start,k.end);y&&(P.pendingSlices=[y]),this.runWorker(P)}}return a||(m(d),a=p.then(k=>({bytes:k,view:V(k),offset:e}))),a}createWorker(e,r){let i={startPos:e,currentPos:e,targetPos:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(i);this.workers.length>this.options.maxWorkerCount;){let s=0,n=this.workers[0];for(let a=1;a<this.workers.length;a++){let o=this.workers[a];o.age<n.age&&(s=a,n=o)}if(n.running&&n.pendingSlices.length>0)break;n.aborted=!0,this.workers.splice(s,1)}return i}runWorker(e){m(!e.running),m(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(r=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(i=>i.reject(r)),e.pendingSlices.length=0;else throw r})}supplyWorkerData(e,r){m(!e.aborted);let i=e.currentPos,s=i+r.length;this.insertIntoCache({start:i,end:s,bytes:r,view:V(r),age:this.nextAge++}),e.currentPos+=r.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let n=0;n<e.pendingSlices.length;n++){let a=e.pendingSlices[n],o=Math.max(i,a.start),c=Math.min(s,a.start+a.bytes.length);o<c&&a.bytes.set(r.subarray(o-i,c-i),o-a.start);for(let l=0;l<a.holes.length;l++){let d=a.holes[l];i<=d.start&&s>d.start&&(d.start=s),d.end<=d.start&&(a.holes.splice(l,1),l--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(n,1),n--)}for(let n=0;n<this.workers.length;n++){let a=this.workers[n];e===a||a.running||ki(i,s,a.currentPos,a.targetPos)&&(this.workers.splice(n,1),n--)}}forgetWorker(e){let r=this.workers.indexOf(e);m(r!==-1),this.workers.splice(r,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let r=M(this.cache,e.start,i=>i.start)+1;if(r>0){let i=this.cache[r-1];if(i.end>=e.end)return;if(i.end>e.start){let s=new Uint8Array(e.end-i.start);s.set(i.bytes,0),s.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=s,i.view=V(s),i.end=e.end,r--,e=i}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(r,0,e),this.currentCacheSize+=e.bytes.length;for(let i=r+1;i<this.cache.length;i++){let s=this.cache[i];if(e.end<=s.start)break;if(e.end>=s.end){this.cache.splice(i,1),this.currentCacheSize-=s.bytes.length,i--;continue}let n=new Uint8Array(s.end-e.start);n.set(e.bytes,0),n.set(s.bytes,s.start-e.start),this.currentCacheSize-=e.end-s.start,e.bytes=n,e.view=V(n),e.end=s.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let i=0,s=this.cache[0];for(let n=1;n<this.cache.length;n++){let a=this.cache[n];a.age<s.age&&(i=n,s=a)}if(this.currentCacheSize-s.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(i,1),this.currentCacheSize-=s.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};yi();var sr=class{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(r=>!(r instanceof be)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof vt))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new ls(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),m(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(r=>r.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(r=>r.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(r=>r.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(r=>r.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()}},Z=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var ls=class{constructor(e){this.source=e}requestSlice(e,r){if(this.source._disposed)throw new Z;if(this.fileSize!==null&&e+r>this.fileSize)return null;let i=e+r,s=this.source._read(e,i);return s instanceof Promise?s.then(n=>n?new Qt(n.bytes,n.view,n.offset,e,i):null):s?new Qt(s.bytes,s.view,s.offset,e,i):null}requestSliceRange(e,r,i){if(this.source._disposed)throw new Z;if(this.fileSize!==null)return this.requestSlice(e,X(this.fileSize-e,r,i));{let s=this.requestSlice(e,i),n=a=>{if(a)return a;let o=l=>(m(l!==null),this.requestSlice(e,X(l-e,r,i))),c=this.source._retrieveSize();return c instanceof Promise?c.then(o):o(c)};return s instanceof Promise?s.then(n):n(s)}}},Qt=class t{constructor(e,r,i,s,n){this.bytes=e,this.view=r,this.offset=i,this.start=s,this.end=n,this.bufferPos=s-i}static tempFromBytes(e){return new t(e,V(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,r=this.end-e){if(e<this.start||e+r>this.end)throw new RangeError("Slicing outside of original slice.");return new t(this.bytes,this.view,this.offset,e,e+r)}},he=(t,e)=>{if(t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)},F=(t,e)=>{he(t,e);let r=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,r},v=t=>(he(t,1),t.view.getUint8(t.bufferPos++)),tr=(t,e)=>{he(t,2);let r=t.view.getUint16(t.bufferPos,e);return t.bufferPos+=2,r},ee=t=>{he(t,2);let e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},et=t=>{he(t,3);let e=pt(t.view,t.bufferPos,!1);return t.bufferPos+=3,e},Br=t=>{he(t,2);let e=t.view.getInt16(t.bufferPos,!1);return t.bufferPos+=2,e},Qe=(t,e)=>{he(t,4);let r=t.view.getUint32(t.bufferPos,e);return t.bufferPos+=4,r},_=t=>{he(t,4);let e=t.view.getUint32(t.bufferPos,!1);return t.bufferPos+=4,e},Et=t=>{he(t,4);let e=t.view.getUint32(t.bufferPos,!0);return t.bufferPos+=4,e},He=t=>{he(t,4);let e=t.view.getInt32(t.bufferPos,!1);return t.bufferPos+=4,e},Vc=t=>{he(t,4);let e=t.view.getInt32(t.bufferPos,!0);return t.bufferPos+=4,e},on=(t,e)=>{let r,i;return e?(r=Qe(t,!0),i=Qe(t,!0)):(i=Qe(t,!1),r=Qe(t,!1)),i*4294967296+r},me=t=>{let e=_(t),r=_(t);return e*4294967296+r},Wa=t=>{let e=He(t),r=_(t);return e*4294967296+r},no=t=>{let e=Et(t);return Vc(t)*4294967296+e},qa=t=>{he(t,4);let e=t.view.getFloat32(t.bufferPos,!1);return t.bufferPos+=4,e},Ni=t=>{he(t,8);let e=t.view.getFloat64(t.bufferPos,!1);return t.bufferPos+=8,e},j=(t,e)=>{he(t,e);let r="";for(let i=0;i<e;i++)r+=String.fromCharCode(t.bytes[t.bufferPos++]);return r};var dn=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;var Po=t=>{let e=Math.floor(t/36e5),r=Math.floor(t%(3600*1e3)/(60*1e3)),i=Math.floor(t%(60*1e3)/1e3),s=t%1e3;return e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+s.toString().padStart(3,"0")};var Hr=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let r=0;r<e.length;r++)this.helperView.setUint8(r%8,e.charCodeAt(r)),r%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let r=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let n of e.children)n&&this.writeBox(n);let i=this.writer.getPos(),s=e.size??i-r;this.writer.seek(r),this.writeBoxHeader(e,s),this.writer.seek(i)}}writeBoxHeader(e,r){this.writeU32(e.largeSize?1:r),this.writeAscii(e.type),e.largeSize&&this.writeU64(r)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let r=this.offsets.get(e);m(r!==void 0);let i=this.writer.getPos();this.writer.seek(r),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let r=this.measureBoxHeader(e);if(e.contents&&(r+=e.contents.byteLength),e.children)for(let i of e.children)i&&(r+=this.measureBox(i));return r}}},U=new Uint8Array(8),Be=new DataView(U.buffer),$=t=>[(t%256+256)%256],R=t=>(Be.setUint16(0,t,!1),[U[0],U[1]]),vo=t=>(Be.setInt16(0,t,!1),[U[0],U[1]]),Ao=t=>(Be.setUint32(0,t,!1),[U[1],U[2],U[3]]),C=t=>(Be.setUint32(0,t,!1),[U[0],U[1],U[2],U[3]]),st=t=>(Be.setInt32(0,t,!1),[U[0],U[1],U[2],U[3]]),At=t=>(Be.setUint32(0,Math.floor(t/2**32),!1),Be.setUint32(4,t,!1),[U[0],U[1],U[2],U[3],U[4],U[5],U[6],U[7]]),Fo=t=>(Be.setInt16(0,2**8*t,!1),[U[0],U[1]]),Ge=t=>(Be.setInt32(0,2**16*t,!1),[U[0],U[1],U[2],U[3]]),hn=t=>(Be.setInt32(0,2**30*t,!1),[U[0],U[1],U[2],U[3]]),fn=(t,e)=>{let r=[],i=t;do{let s=i&127;i>>=7,r.length>0&&(s|=128),r.push(s),e!==void 0&&e--}while(i>0||e);return r.reverse()},oe=(t,e=!1)=>{let r=Array(t.length).fill(null).map((i,s)=>t.charCodeAt(s));return e&&r.push(0),r},pn=t=>{let e=null;for(let r of t)(!e||r.timestamp>e.timestamp)&&(e=r);return e},Ro=t=>{let e=t*(Math.PI/180),r=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[r,i,0,-i,r,0,0,0,1]},Bo=Ro(0),Do=t=>[Ge(t[0]),Ge(t[1]),hn(t[2]),Ge(t[3]),Ge(t[4]),hn(t[5]),Ge(t[6]),Ge(t[7]),hn(t[8])],B=(t,e,r)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:r}),W=(t,e,r,i,s)=>B(t,[$(e),Ao(r),i??[]],s),Oo=t=>t.isQuickTime?B("ftyp",[oe("qt "),C(512),oe("qt ")]):t.fragmented?B("ftyp",[oe("iso5"),C(512),oe("iso5"),oe("iso6"),oe("mp41")]):B("ftyp",[oe("isom"),C(512),oe("isom"),t.holdsAvc?oe("avc1"):[],oe("mp41")]),qr=t=>({type:"mdat",largeSize:t}),zo=t=>({type:"free",size:t}),nr=t=>B("moov",void 0,[Lc(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>Wc(e,t.creationTime)),t.isFragmented?Sl(t.trackDatas):null,Rl(t)]),Lc=(t,e)=>{let r=te(Math.max(0,...e.filter(a=>a.samples.length>0).map(a=>{let o=pn(a.samples);return o.timestamp+o.duration})),us),i=Math.max(0,...e.map(a=>a.track.id))+1,s=!ut(t)||!ut(r),n=s?At:C;return W("mvhd",+s,0,[n(t),n(t),C(us),n(r),Ge(1),Fo(1),Array(10).fill(0),Do(Bo),Array(24).fill(0),C(i)])},Wc=(t,e)=>{let r=jo(t);return B("trak",void 0,[Hc(t,e),qc(t,e),r.name!==void 0?B("udta",void 0,[B("name",[...ue.encode(r.name)])]):null])},Hc=(t,e)=>{let r=pn(t.samples),i=te(r?r.timestamp+r.duration:0,us),s=!ut(e)||!ut(i),n=s?At:C,a;if(t.type==="video"){let c=t.track.metadata.rotation;a=Ro(c??0)}else a=Bo;let o=2;return t.track.metadata.disposition?.default!==!1&&(o|=1),W("tkhd",+s,o,[n(e),n(e),C(t.track.id),C(0),n(i),Array(8).fill(0),R(0),R(t.track.id),Fo(t.type==="audio"?1:0),R(0),Do(a),Ge(t.type==="video"?t.info.width:0),Ge(t.type==="video"?t.info.height:0)])},qc=(t,e)=>B("mdia",void 0,[jc(t,e),gn(!0,$c[t.type],Qc[t.type]),Gc(t)]),jc=(t,e)=>{let r=pn(t.samples),i=te(r?r.timestamp+r.duration:0,t.timescale),s=!ut(e)||!ut(i),n=s?At:C;return W("mdhd",+s,0,[n(e),n(e),C(t.timescale),n(i),R(qo(t.track.metadata.languageCode??G)),R(0)])},$c={video:"vide",audio:"soun",subtitle:"text"},Qc={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},gn=(t,e,r,i="\0\0\0\0")=>W("hdlr",0,0,[t?oe("mhlr"):C(0),oe(e),oe(i),C(0),C(0),oe(r,!0)]),Gc=t=>B("minf",void 0,[Zc[t.type](),Jc(),rl(t)]),Kc=()=>W("vmhd",0,1,[R(0),R(0),R(0),R(0)]),Xc=()=>W("smhd",0,0,[R(0),R(0)]),Yc=()=>W("nmhd",0,0),Zc={video:Kc,audio:Xc,subtitle:Yc},Jc=()=>B("dinf",void 0,[el()]),el=()=>W("dref",0,0,[C(1)],[tl()]),tl=()=>W("url ",0,1),rl=t=>{let e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(r=>r.sampleCompositionTimeOffset!==0);return B("stbl",void 0,[il(t),gl(t),e?Tl(t):null,e?xl(t):null,bl(t),kl(t),yl(t),wl(t)])},il=t=>{let e;if(t.type==="video")e=sl(zl(t.track.source._codec,t.info.decoderConfig.codec),t);else if(t.type==="audio"){let r=Ho(t.track.source._codec,t.muxer.isQuickTime);m(r),e=ll(r,t)}else t.type==="subtitle"&&(e=ml(Nl[t.track.source._codec],t));return m(e),W("stsd",0,0,[C(1)],[e])},sl=(t,e)=>B(t,[Array(6).fill(0),R(1),R(0),R(0),Array(12).fill(0),R(e.info.width),R(e.info.height),C(4718592),C(4718592),C(0),R(1),Array(32).fill(0),R(24),vo(65535)],[Ml[e.track.source._codec](e),qn(e.info.decoderConfig.colorSpace)?nl(e):null]),nl=t=>B("colr",[oe("nclx"),R(dt[t.info.decoderConfig.colorSpace.primaries]),R(ht[t.info.decoderConfig.colorSpace.transfer]),R(ft[t.info.decoderConfig.colorSpace.matrix]),$((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),al=t=>t.info.decoderConfig&&B("avcC",[...K(t.info.decoderConfig.description)]),ol=t=>t.info.decoderConfig&&B("hvcC",[...K(t.info.decoderConfig.description)]),Eo=t=>{if(!t.info.decoderConfig)return null;let e=t.info.decoderConfig,r=e.codec.split("."),i=Number(r[1]),s=Number(r[2]),n=Number(r[3]),a=r[4]?Number(r[4]):1,o=r[8]?Number(r[8]):Number(e.colorSpace?.fullRange??0),c=(n<<4)+(a<<1)+o,l=r[5]?Number(r[5]):e.colorSpace?.primaries?dt[e.colorSpace.primaries]:2,d=r[6]?Number(r[6]):e.colorSpace?.transfer?ht[e.colorSpace.transfer]:2,u=r[7]?Number(r[7]):e.colorSpace?.matrix?ft[e.colorSpace.matrix]:2;return W("vpcC",1,0,[$(i),$(s),$(c),$(l),$(d),$(u),R(0)])},cl=t=>B("av1C",ca(t.info.decoderConfig.codec)),ll=(t,e)=>{let r=0,i,s=16;if(Q.includes(e.track.source._codec)){let n=e.track.source._codec,{sampleSize:a}=fe(n);s=8*a,s>16&&(r=1)}return r===0?i=[Array(6).fill(0),R(1),R(r),R(0),C(0),R(e.info.numberOfChannels),R(s),R(0),R(0),R(e.info.sampleRate<2**16?e.info.sampleRate:0),R(0)]:i=[Array(6).fill(0),R(1),R(r),R(0),C(0),R(e.info.numberOfChannels),R(Math.min(s,16)),R(0),R(0),R(e.info.sampleRate<2**16?e.info.sampleRate:0),R(0),C(1),C(s/8),C(e.info.numberOfChannels*s/8),C(2)],B(t,i,[Ul(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},mn=t=>{let e;switch(t.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source._codec}`)}let r=[...$(e),...$(21),...Ao(0),...C(0),...C(0)];if(t.info.decoderConfig.description){let i=K(t.info.decoderConfig.description);r=[...r,...$(5),...fn(i.byteLength),...i]}return r=[...R(1),...$(0),...$(4),...fn(r.length),...r,...$(6),...$(1),...$(2)],r=[...$(3),...fn(r.length),...r],W("esds",0,0,r)},it=t=>B("wave",void 0,[ul(t),dl(t),B("\0\0\0\0")]),ul=t=>B("frma",[oe(Ho(t.track.source._codec,t.muxer.isQuickTime))]),dl=t=>{let{littleEndian:e}=fe(t.track.source._codec);return B("enda",[R(+e)])},hl=t=>{let e=t.info.numberOfChannels,r=3840,i=t.info.sampleRate,s=0,n=0,a=new Uint8Array(0),o=t.info.decoderConfig?.description;if(o){m(o.byteLength>=18);let c=K(o),l=Ai(c);e=l.outputChannelCount,r=l.preSkip,i=l.inputSampleRate,s=l.outputGain,n=l.channelMappingFamily,l.channelMappingTable&&(a=l.channelMappingTable)}return B("dOps",[$(0),$(e),R(r),C(i),vo(s),$(n),...a])},fl=t=>{let e=t.info.decoderConfig?.description;m(e);let r=K(e);return W("dfLa",0,0,[...r.subarray(4)])},Fe=t=>{let{littleEndian:e,sampleSize:r}=fe(t.track.source._codec),i=+e;return W("pcmC",0,0,[$(i),$(8*r)])},ml=(t,e)=>B(t,[Array(6).fill(0),R(1)],[Vl[e.track.source._codec](e)]),pl=t=>B("vttC",[...ue.encode(t.info.config.description)]);var gl=t=>W("stts",0,0,[C(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[C(e.sampleCount),C(e.sampleDelta)])]),wl=t=>{if(t.samples.every(r=>r.type==="key"))return null;let e=[...t.samples.entries()].filter(([,r])=>r.type==="key");return W("stss",0,0,[C(e.length),e.map(([r])=>C(r+1))])},bl=t=>W("stsc",0,0,[C(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[C(e.firstChunk),C(e.samplesPerChunk),C(1)])]),kl=t=>{if(t.type==="audio"&&t.info.requiresPcmTransformation){let{sampleSize:e}=fe(t.track.source._codec);return W("stsz",0,0,[C(e*t.info.numberOfChannels),C(t.samples.reduce((r,i)=>r+te(i.duration,t.timescale),0))])}return W("stsz",0,0,[C(0),C(t.samples.length),t.samples.map(e=>C(e.size))])},yl=t=>t.finalizedChunks.length>0&&q(t.finalizedChunks).offset>=2**32?W("co64",0,0,[C(t.finalizedChunks.length),t.finalizedChunks.map(e=>At(e.offset))]):W("stco",0,0,[C(t.finalizedChunks.length),t.finalizedChunks.map(e=>C(e.offset))]),Tl=t=>W("ctts",1,0,[C(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[C(e.sampleCount),st(e.sampleCompositionTimeOffset)])]),xl=t=>{let e=1/0,r=-1/0,i=1/0,s=-1/0;m(t.compositionTimeOffsetTable.length>0),m(t.samples.length>0);for(let a=0;a<t.compositionTimeOffsetTable.length;a++){let o=t.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),r=Math.max(r,o.sampleCompositionTimeOffset)}for(let a=0;a<t.samples.length;a++){let o=t.samples[a];i=Math.min(i,te(o.timestamp,t.timescale)),s=Math.max(s,te(o.timestamp+o.duration,t.timescale))}let n=Math.max(-e,0);return s>=2**31?null:W("cslg",0,0,[st(n),st(e),st(r),st(i),st(s)])},Sl=t=>B("mvex",void 0,t.map(Cl)),Cl=t=>W("trex",0,0,[C(t.track.id),C(1),C(0),C(0),C(0)]),wn=(t,e)=>B("moof",void 0,[_l(t),...e.map(Pl)]),_l=t=>W("mfhd",0,0,[C(t)]),Mo=t=>{let e=0,r=0,i=0,s=0,n=t.type==="delta";return r|=+n,n?e|=1:e|=2,e<<24|r<<16|i<<8|s},Pl=t=>B("traf",void 0,[El(t),Il(t),vl(t)]),El=t=>{m(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;let r=t.currentChunk.samples[1]??t.currentChunk.samples[0],i={duration:r.timescaleUnitsToNextSample,size:r.size,flags:Mo(r)};return W("tfhd",0,e,[C(t.track.id),C(i.duration),C(i.size),C(i.flags)])},Il=t=>(m(t.currentChunk),W("tfdt",1,0,[At(te(t.currentChunk.startTimestamp,t.timescale))])),vl=t=>{m(t.currentChunk);let e=t.currentChunk.samples.map(g=>g.timescaleUnitsToNextSample),r=t.currentChunk.samples.map(g=>g.size),i=t.currentChunk.samples.map(Mo),s=t.currentChunk.samples.map(g=>te(g.timestamp-g.decodeTimestamp,t.timescale)),n=new Set(e),a=new Set(r),o=new Set(i),c=new Set(s),l=o.size===2&&i[0]!==i[1],d=n.size>1,u=a.size>1,h=!l&&o.size>1,f=c.size>1||[...c].some(g=>g!==0),p=0;return p|=1,p|=4*+l,p|=256*+d,p|=512*+u,p|=1024*+h,p|=2048*+f,W("trun",1,p,[C(t.currentChunk.samples.length),C(t.currentChunk.offset-t.currentChunk.moofOffset||0),l?C(i[0]):[],t.currentChunk.samples.map((g,w)=>[d?C(e[w]):[],u?C(r[w]):[],h?C(i[w]):[],f?st(s[w]):[]])])},Uo=t=>B("mfra",void 0,[...t.map(Al),Fl()]),Al=(t,e)=>W("tfra",1,0,[C(t.track.id),C(63),C(t.finalizedChunks.length),t.finalizedChunks.map(i=>[At(te(i.samples[0].timestamp,t.timescale)),At(i.moofOffset),C(e+1),C(1),C(1)])]),Fl=()=>W("mfro",0,0,[C(0)]),No=()=>B("vtte"),Vo=(t,e,r,i,s)=>B("vttc",void 0,[s!==null?B("vsid",[st(s)]):null,r!==null?B("iden",[...ue.encode(r)]):null,e!==null?B("ctim",[...ue.encode(Po(e))]):null,i!==null?B("sttg",[...ue.encode(i)]):null,B("payl",[...ue.encode(t)])]),Lo=t=>B("vtta",[...ue.encode(t)]),Rl=t=>{let e=[],r=t.format._options.metadataFormat??"auto",i=t.output._metadataTags;if(r==="mdir"||r==="auto"&&!t.isQuickTime){let s=Dl(i);s&&e.push(s)}else if(r==="mdta"){let s=Ol(i);s&&e.push(s)}else(r==="udta"||r==="auto"&&t.isQuickTime)&&Bl(e,t.output._metadataTags);return e.length===0?null:B("udta",void 0,e)},Bl=(t,e)=>{for(let{key:r,value:i}of xr(e))switch(r){case"title":t.push(Re("\xA9nam",i));break;case"description":t.push(Re("\xA9des",i));break;case"artist":t.push(Re("\xA9ART",i));break;case"album":t.push(Re("\xA9alb",i));break;case"albumArtist":t.push(Re("albr",i));break;case"genre":t.push(Re("\xA9gen",i));break;case"date":t.push(Re("\xA9day",i.toISOString().slice(0,10)));break;case"comment":t.push(Re("\xA9cmt",i));break;case"lyrics":t.push(Re("\xA9lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:ne(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||r.length!==4||t.some(s=>s.type===r)||(typeof i=="string"?t.push(Re(r,i)):i instanceof Uint8Array&&t.push(B(r,Array.from(i))))}},Re=(t,e)=>{let r=ue.encode(e);return B(t,[R(r.length),R(qo("und")),Array.from(r)])},Io={"image/jpeg":13,"image/png":14,"image/bmp":27},Wo=(t,e)=>{let r=[];for(let{key:i,value:s}of xr(t))switch(i){case"title":r.push({key:e?"title":"\xA9nam",value:_e(s)});break;case"description":r.push({key:e?"description":"\xA9des",value:_e(s)});break;case"artist":r.push({key:e?"artist":"\xA9ART",value:_e(s)});break;case"album":r.push({key:e?"album":"\xA9alb",value:_e(s)});break;case"albumArtist":r.push({key:e?"album_artist":"aART",value:_e(s)});break;case"comment":r.push({key:e?"comment":"\xA9cmt",value:_e(s)});break;case"genre":r.push({key:e?"genre":"\xA9gen",value:_e(s)});break;case"lyrics":r.push({key:e?"lyrics":"\xA9lyr",value:_e(s)});break;case"date":r.push({key:e?"date":"\xA9day",value:_e(s.toISOString().slice(0,10))});break;case"images":for(let n of s)n.kind==="coverFront"&&r.push({key:"covr",value:B("data",[C(Io[n.mimeType]??0),C(0),Array.from(n.data)])});break;case"trackNumber":if(e){let n=t.tracksTotal!==void 0?`${s}/${t.tracksTotal}`:s.toString();r.push({key:"track",value:_e(n)})}else r.push({key:"trkn",value:B("data",[C(0),C(0),R(0),R(s),R(t.tracksTotal??0),R(0)])});break;case"discNumber":e||r.push({key:"disc",value:B("data",[C(0),C(0),R(0),R(s),R(t.discsTotal??0),R(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ne(i)}if(t.raw)for(let i in t.raw){let s=t.raw[i];s==null||!e&&i.length!==4||r.some(n=>n.key===i)||(typeof s=="string"?r.push({key:i,value:_e(s)}):s instanceof Uint8Array?r.push({key:i,value:B("data",[C(0),C(0),Array.from(s)])}):s instanceof ke&&r.push({key:i,value:B("data",[C(Io[s.mimeType]??0),C(0),Array.from(s.data)])}))}return r},Dl=t=>{let e=Wo(t,!1);return e.length===0?null:W("meta",0,0,void 0,[gn(!1,"mdir","","appl"),B("ilst",void 0,e.map(r=>B(r.key,void 0,[r.value])))])},Ol=t=>{let e=Wo(t,!0);return e.length===0?null:B("meta",void 0,[gn(!1,"mdta",""),W("keys",0,0,[C(e.length)],e.map(r=>B("mdta",[...ue.encode(r.key)]))),B("ilst",void 0,e.map((r,i)=>{let s=String.fromCharCode(...C(i+1));return B(s,void 0,[r.value])}))])},_e=t=>B("data",[C(1),C(0),...ue.encode(t)]),zl=(t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},Ml={avc:al,hevc:ol,vp8:Eo,vp9:Eo,av1:cl},Ho=(t,e)=>{switch(t){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt"}if(e)switch(t){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(t){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},Ul=(t,e)=>{switch(t){case"aac":return mn;case"mp3":return mn;case"opus":return hl;case"vorbis":return mn;case"flac":return fl}if(e)switch(t){case"pcm-s24":return it;case"pcm-s24be":return it;case"pcm-s32":return it;case"pcm-s32be":return it;case"pcm-f32":return it;case"pcm-f32be":return it;case"pcm-f64":return it;case"pcm-f64be":return it}else switch(t){case"pcm-s16":return Fe;case"pcm-s16be":return Fe;case"pcm-s24":return Fe;case"pcm-s24be":return Fe;case"pcm-s32":return Fe;case"pcm-s32be":return Fe;case"pcm-f32":return Fe;case"pcm-f32be":return Fe;case"pcm-f64":return Fe;case"pcm-f64be":return Fe}return null},Nl={webvtt:"wvtt"},Vl={webvtt:pl},qo=t=>{m(t.length===3);let e=0;for(let r=0;r<3;r++)e<<=5,e+=t.charCodeAt(r)-96;return e};var ds=class{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let r=this.getPos();if(r<this.trackedStart){if(r+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-r),r=0}let i=r+e.byteLength-this.trackedStart,s=this.trackedWrites.byteLength;for(;s<i;)s*=2;if(s!==this.trackedWrites.byteLength){let n=new Uint8Array(s);n.set(this.trackedWrites,0),this.trackedWrites=n}this.trackedWrites.set(e,r-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,r+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");let r={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,r}},bn=2**16,kn=2**32,ar=class extends ds{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(bn,{maxByteLength:kn})}catch{this.buffer=new ArrayBuffer(bn),this.supportsResize=!1}else this.buffer=new ArrayBuffer(bn);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let r=this.buffer.byteLength;for(;r<e;)r*=2;if(r!==this.buffer.byteLength){if(r>kn)throw new Error(`ArrayBuffer exceeded maximum size of ${kn} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(r);else{let i=new ArrayBuffer(r),s=new Uint8Array(i);s.set(this.bytes,0),this.buffer=i,this.bytes=s}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,r){return this.bytes.slice(e,r)}},Ll=2**24,Wl=2,hs=class extends ds{constructor(e){super(),this.pos=0,this.sections=[],this.lastWriteEnd=0,this.lastFlushEnd=0,this.writer=null,this.chunks=[],this.target=e,this.chunked=e._options.chunked??!1,this.chunkSize=e._options.chunkSize??Ll}start(){this.writer=this.target._writable.getWriter()}write(e){if(this.pos>this.lastWriteEnd){let r=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(r))}this.maybeTrackWrites(e),this.sections.push({data:e.slice(),start:this.pos}),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){if(this.pos>this.lastWriteEnd){let i=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(i))}if(m(this.writer),this.sections.length===0)return;let e=[],r=[...this.sections].sort((i,s)=>i.start-s.start);e.push({start:r[0].start,size:r[0].data.byteLength});for(let i=1;i<r.length;i++){let s=e[e.length-1],n=r[i];n.start<=s.start+s.size?s.size=Math.max(s.size,n.start+n.data.byteLength-s.start):e.push({start:n.start,size:n.data.byteLength})}for(let i of e){i.data=new Uint8Array(i.size);for(let s of this.sections)i.start<=s.start&&s.start<i.start+i.size&&i.data.set(s.data,s.start-i.start);if(this.writer.desiredSize!==null&&this.writer.desiredSize<=0&&await this.writer.ready,this.chunked)this.writeDataIntoChunks(i.data,i.start),this.tryToFlushChunks();else{if(this.ensureMonotonicity&&i.start!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:i.data,position:i.start}),this.lastFlushEnd=i.start+i.data.byteLength}}this.sections.length=0}writeDataIntoChunks(e,r){let i=this.chunks.findIndex(c=>c.start<=r&&r<c.start+this.chunkSize);i===-1&&(i=this.createChunk(r));let s=this.chunks[i],n=r-s.start,a=e.subarray(0,Math.min(this.chunkSize-n,e.byteLength));s.data.set(a,n);let o={start:n,end:n+a.byteLength};if(this.insertSectionIntoChunk(s,o),s.written[0].start===0&&s.written[0].end===this.chunkSize&&(s.shouldFlush=!0),this.chunks.length>Wl){for(let c=0;c<this.chunks.length-1;c++)this.chunks[c].shouldFlush=!0;this.tryToFlushChunks()}a.byteLength<e.byteLength&&this.writeDataIntoChunks(e.subarray(a.byteLength),r+a.byteLength)}insertSectionIntoChunk(e,r){let i=0,s=e.written.length-1,n=-1;for(;i<=s;){let a=Math.floor(i+(s-i+1)/2);e.written[a].start<=r.start?(i=a+1,n=a):s=a-1}for(e.written.splice(n+1,0,r),(n===-1||e.written[n].end<r.start)&&n++;n<e.written.length-1&&e.written[n].end>=e.written[n+1].start;)e.written[n].end=Math.max(e.written[n].end,e.written[n+1].end),e.written.splice(n+1,1)}createChunk(e){let i={start:Math.floor(e/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(i),this.chunks.sort((s,n)=>s.start-n.start),this.chunks.indexOf(i)}tryToFlushChunks(e=!1){m(this.writer);for(let r=0;r<this.chunks.length;r++){let i=this.chunks[r];if(!(!i.shouldFlush&&!e)){for(let s of i.written){let n=i.start+s.start;if(this.ensureMonotonicity&&n!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:i.data.subarray(s.start,s.end),position:n}),this.lastFlushEnd=i.start+s.end}this.chunks.splice(r--,1)}}}finalize(){return this.chunked&&this.tryToFlushChunks(!0),m(this.writer),this.writer.close()}async close(){return this.writer?.close()}};var Ft=class{constructor(){this._output=null,this.onwrite=null}},jr=class extends Ft{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new ar(this)}},$r=class extends Ft{constructor(e,r={}){if(super(),!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(r!=null&&typeof r!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(r.chunked!==void 0&&typeof r.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(r.chunkSize!==void 0&&(!Number.isInteger(r.chunkSize)||r.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=r}_createWriter(){return new hs(this)}};var us=1e3,Hl=2082844800,jo=t=>{let e={},r=t.track;return r.metadata.name!==void 0&&(e.name=r.metadata.name),e},te=(t,e,r=!0)=>{let i=t*e;return r?Math.round(i):i},fs=class extends Ci{constructor(e,r){super(e),this.auxTarget=new jr,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new Hr(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=se(),this.creationTime=Math.floor(Date.now()/1e3)+Hl,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=r,this.writer=e._writer,this.boxWriter=new Hr(this.writer),this.isQuickTime=r instanceof or;let i=this.writer instanceof ar?"in-memory":!1;this.fastStart=r._options.fastStart??i,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=r._options.minimumFragmentDuration??1}async start(){let e=await this.mutex.acquire(),r=this.output._tracks.some(i=>i.type==="video"&&i.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(Oo({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onFtyp(i,s)}if(this.ftypSize=this.writer.getPos(),this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let i of this.output._tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=qr(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Di({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,i){let s=this.trackDatas.find(l=>l.track===e);if(s)return s;ma(i),m(i),m(i.decoderConfig);let n={...i.decoderConfig};m(n.codedWidth!==void 0),m(n.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!n.description){let l=Pi(r.data);if(!l)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=ya(l),a=!0}else if(e.source._codec==="hevc"&&!n.description){let l=Ei(r.data);if(!l)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=xa(l),a=!0}let o=Yn(1/(e.metadata.frameRate??57600),1e6).denominator,c={muxer:this,track:e,type:"video",info:{width:n.codedWidth,height:n.codedHeight,decoderConfig:n,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(c),this.trackDatas.sort((l,d)=>l.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,r){let i=this.trackDatas.find(n=>n.track===e);if(i)return i;pa(r),m(r),m(r.decoderConfig);let s={muxer:this,track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig,requiresPcmTransformation:!this.isFragmented&&Q.includes(e.source._codec)},timescale:r.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(e,r){let i=this.trackDatas.find(n=>n.track===e);if(i)return i;ga(r),m(r),m(r.config);let s={muxer:this,track:e,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,r,i){let s=await this.mutex.acquire();try{let n=this.getVideoTrackData(e,r,i),a=r.data;if(n.info.requiresAnnexBTransformation){let l=Nt(a);if(l.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=Bs(l,4)}let o=this.validateAndNormalizeTimestamp(n.track,r.timestamp,r.type==="key"),c=this.createSampleForTrack(n,a,o,r.duration,r.type);await this.registerSample(n,c)}finally{s()}}async addEncodedAudioPacket(e,r,i){let s=await this.mutex.acquire();try{let n=this.getAudioTrackData(e,i),a=this.validateAndNormalizeTimestamp(n.track,r.timestamp,r.type==="key"),o=this.createSampleForTrack(n,r.data,a,r.duration,r.type);n.info.requiresPcmTransformation&&await this.maybePadWithSilence(n,a),await this.registerSample(n,o)}finally{s()}}async maybePadWithSilence(e,r){let i=q(e.samples),s=i?i.timestamp+i.duration:0,n=r-s,a=te(n,e.timescale);if(a>0){let{sampleSize:o,silentValue:c}=fe(e.info.decoderConfig.codec),l=a*e.info.numberOfChannels,d=new Uint8Array(o*l).fill(c),u=this.createSampleForTrack(e,new Uint8Array(d.buffer),s,n,"key");await this.registerSample(e,u)}}async addSubtitleCue(e,r,i){let s=await this.mutex.acquire();try{let n=this.getSubtitleTrackData(e,i);this.validateAndNormalizeTimestamp(n.track,r.timestamp,!0),e.source._codec==="webvtt"&&(n.cueQueue.push(r),await this.processWebVTTCues(n,r.timestamp))}finally{s()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){let i=new Set([]);for(let l of e.cueQueue)m(l.timestamp<=r),m(e.lastCueEndTimestamp<=l.timestamp+l.duration),i.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),i.add(l.timestamp+l.duration);let s=[...i].sort((l,d)=>l-d),n=s[0],a=s[1]??n;if(r<a)break;if(e.lastCueEndTimestamp<n){this.auxWriter.seek(0);let l=No();this.auxBoxWriter.writeBox(l);let d=this.auxWriter.getSlice(0,this.auxWriter.getPos()),u=this.createSampleForTrack(e,d,e.lastCueEndTimestamp,n-e.lastCueEndTimestamp,"key");await this.registerSample(e,u),e.lastCueEndTimestamp=n}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){let d=e.cueQueue[l];if(d.timestamp>=a)break;dn.lastIndex=0;let u=dn.test(d.text),h=d.timestamp+d.duration,f=e.cueToSourceId.get(d);if(f===void 0&&a<h&&(f=e.nextSourceId++,e.cueToSourceId.set(d,f)),d.notes){let g=Lo(d.notes);this.auxBoxWriter.writeBox(g)}let p=Vo(d.text,u?n:null,d.identifier??null,d.settings??null,f??null);this.auxBoxWriter.writeBox(p),h===a&&e.cueQueue.splice(l--,1)}let o=this.auxWriter.getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,n,a-n,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=a}}createSampleForTrack(e,r,i,s,n){return{timestamp:i,decodeTimestamp:i,duration:s,data:r,size:r.byteLength,type:n,timescaleUnitsToNextSample:te(s,e.timescale)}}processTimestamps(e,r){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){let s=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let a=e.timestampProcessingQueue[n],o=te(a.duration,e.timescale);s+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:s,sampleDelta:1});else{let n=q(e.timeToSampleTable);n.sampleCount+=s}e.timestampProcessingQueue.length=0;return}let i=e.timestampProcessingQueue.map(s=>s.timestamp).sort((s,n)=>s-n);for(let s=0;s<e.timestampProcessingQueue.length;s++){let n=e.timestampProcessingQueue[s];n.decodeTimestamp=i[s],!this.isFragmented&&e.lastTimescaleUnits===null&&(n.decodeTimestamp=0);let a=te(n.timestamp-n.decodeTimestamp,e.timescale),o=te(n.duration,e.timescale);if(e.lastTimescaleUnits!==null){m(e.lastSample);let c=te(n.decodeTimestamp,e.timescale,!1),l=Math.round(c-e.lastTimescaleUnits);if(m(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let d=q(e.timeToSampleTable);if(m(d),d.sampleCount===1){d.sampleDelta=l;let h=e.timeToSampleTable[e.timeToSampleTable.length-2];h&&h.sampleDelta===l&&(h.sampleCount++,e.timeToSampleTable.pop(),d=h)}else d.sampleDelta!==l&&(d.sampleCount--,e.timeToSampleTable.push(d={sampleCount:1,sampleDelta:l}));d.sampleDelta===o?d.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});let u=q(e.compositionTimeOffsetTable);m(u),u.sampleCompositionTimeOffset===a?u.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=te(n.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=n}if(e.timestampProcessingQueue.length=0,m(e.lastSample),m(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){m(r.type==="key");let s=te(r.timestamp,e.timescale,!1),n=Math.round(s-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=n}}async registerSample(e,r){r.type==="key"&&this.processTimestamps(e,r),e.timestampProcessingQueue.push(r),this.isFragmented?(e.sampleQueue.push(r),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,r):await this.addSampleToTrack(e,r)}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),this.fastStart==="reserve")){let s=e.track.metadata.maximumPacketCount;if(m(s!==void 0),e.samples.length>s)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${s}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,r.timestamp);let s=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let n=this.trackDatas.every(a=>{if(e===a)return r.type==="key";let o=a.sampleQueue[0];return o?o.type==="key":a.track.source._closed});s>=this.minimumFragmentDuration&&n&&r.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=s>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),m(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){if(m(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce((i,s)=>i+te(s.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||q(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let i of e.currentChunk.samples)m(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(m(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,i=1/0;for(let n of this.trackDatas){if(!e&&n.sampleQueue.length===0&&!n.track.source._closed)break e;n.sampleQueue.length>0&&n.sampleQueue[0].timestamp<i&&(r=n,i=n.sampleQueue[0].timestamp)}if(!r)break;let s=r.sampleQueue.shift();await this.addSampleToTrack(r,s)}}async finalizeFragment(e=!0){m(this.isFragmented);let r=this.nextFragmentNumber++;if(r===1){this.format._options.onMoov&&this.writer.startTrackingWrites();let f=nr(this);if(this.boxWriter.writeBox(f),this.format._options.onMoov){let{data:p,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoov(p,g)}}let i=this.trackDatas.filter(f=>f.currentChunk),s=wn(r,i),n=this.writer.getPos(),a=n+this.boxWriter.measureBox(s),o=a+ye,c=1/0;for(let f of i){f.currentChunk.offset=o,f.currentChunk.moofOffset=n;for(let p of f.currentChunk.samples)o+=p.size;c=Math.min(c,f.currentChunk.startTimestamp)}let l=o-a,d=l>=2**32;if(d)for(let f of i)f.currentChunk.offset+=Le-ye;this.format._options.onMoof&&this.writer.startTrackingWrites();let u=wn(r,i);if(this.boxWriter.writeBox(u),this.format._options.onMoof){let{data:f,start:p}=this.writer.stopTrackingWrites();this.format._options.onMoof(f,p,c)}m(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();let h=qr(d);h.size=l,this.boxWriter.writeBox(h),this.writer.seek(a+(d?Le:ye));for(let f of i)for(let p of f.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.format._options.onMdat){let{data:f,start:p}=this.writer.stopTrackingWrites();this.format._options.onMdat(f,p)}for(let f of i)f.finalizedChunks.push(f.currentChunk),this.finalizedChunks.push(f.currentChunk),f.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){if(this.allTracksAreKnown()){if(!this.mdat){let i=nr(this),n=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;m(this.ftypSize!==null),this.writer.seek(this.ftypSize+n),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=qr(!0),this.boxWriter.writeBox(this.mdat);for(let a of this.trackDatas){for(let o of a.sampleQueue)await this.addSampleToTrack(a,o);a.sampleQueue.length=0}}await this.addSampleToTrack(e,r)}else e.sampleQueue.push(r)}computeSampleTableSizeUpperBound(){m(this.fastStart==="reserve");let e=0;for(let r of this.trackDatas){let i=r.track.metadata.maximumPacketCount;m(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){let r=await this.mutex.acquire();if(e.type==="subtitle"&&e.source._codec==="webvtt"){let i=this.trackDatas.find(s=>s.track===e);i&&await this.processWebVTTCues(i,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(let r of this.trackDatas)this.processTimestamps(r);await this.finalizeFragment(!1)}else for(let r of this.trackDatas)this.processTimestamps(r),await this.finalizeCurrentChunk(r);if(this.fastStart==="in-memory"){this.mdat=qr(!1);let r;for(let s=0;s<2;s++){let n=nr(this),a=this.boxWriter.measureBox(n);r=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+r;for(let c of this.finalizedChunks){c.offset=o;for(let{data:l}of c.samples)m(l),o+=l.byteLength,r+=l.byteLength}if(o<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let i=nr(this);if(this.boxWriter.writeBox(i),this.format._options.onMoov){let{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,n)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let s of this.finalizedChunks)for(let n of s.samples)m(n.data),this.writer.write(n.data),n.data=null;if(this.format._options.onMdat){let{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,n)}}else if(this.isFragmented){let r=this.writer.getPos(),i=Uo(this.trackDatas);this.boxWriter.writeBox(i);let s=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(s)}else{m(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);m(r!==void 0);let i=this.writer.getPos()-r;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,a)}let s=nr(this);if(this.fastStart==="reserve"){m(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);let n=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(zo(n))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);if(this.format._options.onMoov){let{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,a)}}e()}};var cr=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Ae.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Ue.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>bt.includes(e))}_codecUnsupportedHint(e){return""}},Qr=class extends cr{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new fs(e,this)}},lr=class extends Qr{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Ae,...As,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...bt]}_codecUnsupportedHint(e){return new or().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},or=class extends Qr{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Ae,...Ue]}_codecUnsupportedHint(e){return new lr().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}};var $o=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!Ae.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${Ae.join(", ")}.`);if(!(t.bitrate instanceof ur)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(t.keyFrameInterval!==void 0&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(t.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");ql(t.codec,t)},ql=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Fs(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},Qo=t=>{let e=t.bitrate instanceof ur?t.bitrate._toVideoBitrate(t.codec,t.width,t.height):t.bitrate;return{codec:t.fullCodecString??oa(t.codec,t.width,t.height,e),width:t.width,height:t.height,bitrate:e,bitrateMode:t.bitrateMode,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...ha(t.codec)}},Go=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!Ue.includes(t.codec))throw new TypeError(`Invalid audio codec '${t.codec}'. Must be one of: ${Ue.join(", ")}.`);if(t.bitrate===void 0&&(!Q.includes(t.codec)||t.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(t.bitrate!==void 0&&!(t.bitrate instanceof ur)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");jl(t.codec,t)},jl=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Fs(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`)},Ko=t=>{let e=t.bitrate instanceof ur?t.bitrate._toAudioBitrate(t.codec):t.bitrate;return{codec:t.fullCodecString??la(t.codec,t.numberOfChannels,t.sampleRate),numberOfChannels:t.numberOfChannels,sampleRate:t.sampleRate,bitrate:e,bitrateMode:t.bitrateMode,...fa(t.codec)}},ur=class{constructor(e){this._factor=e}_toVideoBitrate(e,r,i){let s=r*i,n={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},a=1920*1080,o=3e6,c=Math.pow(s/a,.95),u=o*c*n[e]*this._factor;return Math.ceil(u/1e3)*1e3}_toAudioBitrate(e){if(Q.includes(e)||e==="flac")return;let i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!i)throw new Error(`Unhandled codec: ${e}`);let s=i*this._factor;return e==="aac"?s=[96e3,128e3,16e4,192e3].reduce((a,o)=>Math.abs(o-s)<Math.abs(a-s)?o:a):e==="opus"||e==="vorbis"?s=Math.max(6e3,s):e==="mp3"&&(s=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,o)=>Math.abs(o-s)<Math.abs(a-s)?o:a)),Math.round(s/1e3)*1e3}};var dr=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise?this._closingPromise:this._flushAndClose(e)}},hr=class extends dr{constructor(e){if(super(),this._connectedTrack=null,!Ae.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${Ae.join(", ")}.`);this._codec=e}};var yn=class{constructor(e,r){this.source=e,this.encodingConfig=r,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new Xe,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorNeedsNewStack=!0}async add(e,r,i){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){let o=this.encodingConfig.sizeChangeBehavior??"deny";if(o!=="passThrough"){if(o==="deny")throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'strict' in the encoding options.`);{let c=!1;this.resizeCanvas||(typeof document<"u"?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),c=!0);let l=this.resizeCanvas.getContext("2d",{alpha:Mt()});m(l),c||(Mt()?(l.fillStyle="black",l.fillRect(0,0,this.codedWidth,this.codedHeight)):l.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(l,{fit:o}),r&&e.close(),e=new ge(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),r=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),m(this.encoderInitialized);let s=this.encodingConfig.keyFrameInterval??5,n=Math.floor(e.timestamp/s),a={...i,keyFrame:i?.keyFrame||s===0||n!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=n,this.customEncoder){this.customEncoderQueueSize++;let o=e.clone(),c=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(o,a)).then(()=>this.customEncoderQueueSize--).catch(l=>this.error??=l).finally(()=>{o.close()});this.customEncoderQueueSize>=4&&await c}else{m(this.encoder);let o=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(o,a),o.close();else if(!!o.format&&!o.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(o,a),o.close();else{let l=o.displayWidth,d=o.displayHeight;if(!this.splitter)try{this.splitter=new Tn(l,d)}catch(u){console.error("Due to an error, only color data will be encoded.",u),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(o,a),o.close()}if(this.splitter){let u=this.splitter.extractColor(o),h=this.splitter.extractAlpha(o);this.alphaFrameQueue.push(h),this.encoder.encode(u,a),u.close(),o.close()}}r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(c=>this.encoder.addEventListener("dequeue",c,{once:!0}))}await this.muxer.mutex.currentPromise}finally{r&&e.close()}}ensureEncoder(e){let r=new Error;this.ensureEncoderPromise=(async()=>{let i=Qo({width:e.codedWidth,height:e.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(i);let s=Pa.find(n=>n.supports(this.encodingConfig.codec,i));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(n,a)=>{if(!(n instanceof L))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(a!==void 0&&(!a||typeof a!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(n,a),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,n,a).catch(o=>{this.error??=o,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(i.alpha="discard",this.encodingConfig.alpha==="keep"&&(i.latencyMode="quality"),(i.width%2===1||i.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${i.width}x${i.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.width}x${i.height}, hardware acceleration: ${i.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let o=[],c=[],l=0,d=0,u=(h,f,p)=>{let g={};if(f){let b=new Uint8Array(f.byteLength);f.copyTo(b),g.alpha=b}let w=L.fromEncodedChunk(h,g);this.encodingConfig.onEncodedPacket?.(w,p),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,w,p).catch(b=>{this.error??=b,this.errorNeedsNewStack=!1})};this.encoder=new VideoEncoder({output:(h,f)=>{if(!this.alphaEncoder){u(h,null,f);return}let p=this.alphaFrameQueue.shift();m(p!==void 0),p?(this.alphaEncoder.encode(p,{keyFrame:h.type==="key"}),d++,p.close(),o.push({chunk:h,meta:f})):d===0?u(h,null,f):(c.push(l+d),o.push({chunk:h,meta:f}))},error:h=>{h.stack=r.stack,this.error??=h}}),this.encoder.configure(i),this.encodingConfig.alpha==="keep"&&(this.alphaEncoder=new VideoEncoder({output:(h,f)=>{d--;let p=o.shift();for(m(p!==void 0),u(p.chunk,h,p.meta),l++;c.length>0&&c[0]===l;){c.shift();let g=o.shift();m(g!==void 0),u(g.chunk,null,g.meta)}},error:h=>{h.stack=r.stack,this.error??=h}}),this.alphaEncoder.configure(i))}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(r=>r?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}},Tn=class{constructor(e,r){this.lastFrame=null,typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,r):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=r);let i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
34
30
|
in vec2 a_position;
|
|
35
31
|
in vec2 a_texCoord;
|
|
36
32
|
out vec2 v_texCoord;
|
|
@@ -94,7 +90,7 @@ import"./chunk-WCZ2O3UN.js";import"./chunk-3L3MB5NY.js";import"./chunk-BFBY7VYB.
|
|
|
94
90
|
|
|
95
91
|
fragColor = result;
|
|
96
92
|
}
|
|
97
|
-
`),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,r),this.gl.linkProgram(i),i}createShader(e,r){let i=this.gl.createShader(e);return this.gl.shaderSource(i,r),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)||console.error("Shader compile error:",this.gl.getShaderInfoLog(i)),i}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let r=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.STATIC_DRAW);let n=this.gl.getAttribLocation(this.colorProgram,"a_position"),s=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}updateTexture(e){this.lastFrame!==e&&((e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.lastFrame=e)}extractColor(e){return this.updateTexture(e),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}extractAlpha(e){this.updateTexture(e),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let{width:r,height:i}=this.canvas,n=Math.ceil(r/2)*Math.ceil(i/2),s=r*i+n*2,o=Math.ceil(s/(r*4)),a=new Uint8Array(4*r*o);this.gl.readPixels(0,0,r,o,this.gl.RGBA,this.gl.UNSIGNED_BYTE,a),a=a.subarray(0,s),h(a[r*i]===128),h(a[a.length-1]===128);let c={format:"I420",codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[a.buffer]};return new VideoFrame(a,c)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},Ri=class extends Vr{constructor(e){ol(e),super(e.codec),this._encoder=new No(this,e)}add(e,r){if(!(e instanceof Ee))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,r)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var Lr=class extends zr{constructor(e){if(super(),this._connectedTrack=null,!et.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${et.join(", ")}.`);this._codec=e}};var Uo=class{constructor(e,r){this.source=e,this.encodingConfig=r,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new ht,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.error=null,this.errorNeedsNewStack=!0}async add(e,r){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),h(this.encoderInitialized);{let i=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let s=i-this.lastEndSampleIndex;if(s>=64){let o=new Ae({data:new Float32Array(s*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:s,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.add(o,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.customEncoder){this.customEncoderQueueSize++;let i=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(i)).then(()=>this.customEncoderQueueSize--).catch(s=>this.error??=s).finally(()=>{i.close()});this.customEncoderQueueSize>=4&&await n,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,r);else{h(this.encoder);let i=e.toAudioData();this.encoder.encode(i),i.close(),r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(n=>this.encoder.addEventListener("dequeue",n,{once:!0})),await this.muxer.mutex.currentPromise}}finally{r&&e.close()}}async doPcmEncoding(e,r){h(this.outputSampleSize),h(this.writeOutputValue);let{numberOfChannels:i,numberOfFrames:n,sampleRate:s,timestamp:o}=e,a=2048,c=[];for(let f=0;f<n;f+=a){let m=Math.min(a,e.numberOfFrames-f),p=m*i*this.outputSampleSize,g=new ArrayBuffer(p),b=new DataView(g);c.push({frameCount:m,view:b})}let u=e.allocationSize({planeIndex:0,format:"f32-planar"}),l=new Float32Array(u/Float32Array.BYTES_PER_ELEMENT);for(let f=0;f<i;f++){e.copyTo(l,{planeIndex:f,format:"f32-planar"});for(let m=0;m<c.length;m++){let{frameCount:p,view:g}=c[m];for(let b=0;b<p;b++)this.writeOutputValue(g,(b*i+f)*this.outputSampleSize,l[m*a+b])}}r&&e.close();let d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:s}};for(let f=0;f<c.length;f++){let{frameCount:m,view:p}=c[f],g=p.buffer,b=f*a,w=new L(new Uint8Array(g),"key",o+b/s,m/s);this.encodingConfig.onEncodedPacket?.(w,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,w,d)}}ensureEncoder(e){let r=new Error;this.ensureEncoderPromise=(async()=>{let{numberOfChannels:i,sampleRate:n}=e,s=ul({numberOfChannels:i,sampleRate:n,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(s);let o=qc.find(a=>a.supports(this.encodingConfig.codec,s));if(o)this.customEncoder=new o,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(a,c)=>{if(!(a instanceof L))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(a,c),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,a,c).catch(u=>{this.error??=u,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else if(Y.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(s)).supported)throw new Error(`This specific encoder configuration (${s.codec}, ${s.bitrate} bps, ${s.numberOfChannels} channels, ${s.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(c,u)=>{if(this.encodingConfig.codec==="aac"&&u?.decoderConfig){let d=!1;if(!u.decoderConfig.description||u.decoderConfig.description.byteLength<2?d=!0:d=di(J(u.decoderConfig.description)).objectType===0,d){let f=Number(G(s.codec.split(".")));u.decoderConfig.description=Ec({objectType:f,numberOfChannels:u.decoderConfig.numberOfChannels,sampleRate:u.decoderConfig.sampleRate})}}let l=L.fromEncodedChunk(c);this.encodingConfig.onEncodedPacket?.(l,u),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,u).catch(d=>{this.error??=d,this.errorNeedsNewStack=!1})},error:c=>{c.stack=r.stack,this.error??=c}}),this.encoder.configure(s)}h(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:r,sampleSize:i,littleEndian:n}=Te(e);switch(this.outputSampleSize=i,i){case 1:r==="unsigned"?this.writeOutputValue=(s,o,a)=>s.setUint8(o,ee((a+1)*127.5,0,255)):r==="signed"?this.writeOutputValue=(s,o,a)=>{s.setInt8(o,ee(Math.round(a*128),-128,127))}:r==="ulaw"?this.writeOutputValue=(s,o,a)=>{let c=ee(Math.floor(a*32767),-32768,32767);s.setUint8(o,Hc(c))}:r==="alaw"?this.writeOutputValue=(s,o,a)=>{let c=ee(Math.floor(a*32767),-32768,32767);s.setUint8(o,Gc(c))}:h(!1);break;case 2:r==="unsigned"?this.writeOutputValue=(s,o,a)=>s.setUint16(o,ee((a+1)*32767.5,0,65535),n):r==="signed"?this.writeOutputValue=(s,o,a)=>s.setInt16(o,ee(Math.round(a*32767),-32768,32767),n):h(!1);break;case 3:r==="unsigned"?this.writeOutputValue=(s,o,a)=>oi(s,o,ee((a+1)*83886075e-1,0,16777215),n):r==="signed"?this.writeOutputValue=(s,o,a)=>uc(s,o,ee(Math.round(a*8388607),-8388608,8388607),n):h(!1);break;case 4:r==="unsigned"?this.writeOutputValue=(s,o,a)=>s.setUint32(o,ee((a+1)*21474836475e-1,0,4294967295),n):r==="signed"?this.writeOutputValue=(s,o,a)=>s.setInt32(o,ee(Math.round(a*2147483647),-2147483648,2147483647),n):r==="float"?this.writeOutputValue=(s,o,a)=>s.setFloat32(o,a,n):h(!1);break;case 8:r==="float"?this.writeOutputValue=(s,o,a)=>s.setFloat64(o,a,n):h(!1);break;default:ue(i),h(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}},Oi=class extends Lr{constructor(e){cl(e),super(e.codec),this._encoder=new Uo(this,e)}add(e){if(!(e instanceof Ae))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var Ni=class extends zr{constructor(e){if(super(),this._connectedTrack=null,!Nt.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Nt.join(", ")}.`);this._codec=e}};var Mf=["video","audio","subtitle"],zo=t=>{if(!t||typeof t!="object")throw new TypeError("metadata must be an object.");if(t.languageCode!==void 0&&!lr(t.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(t.name!==void 0&&typeof t.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(t.disposition!==void 0&&gc(t.disposition),t.maximumPacketCount!==void 0&&(!Number.isInteger(t.maximumPacketCount)||t.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")},Mi=class{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new be,this._metadataTags={},!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Nr))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Xt))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,r={}){if(!(e instanceof Vr))throw new TypeError("source must be a VideoSource.");if(zo(r),r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError(`Invalid video rotation: ${r.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&r.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(r.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${r.frameRate}. Must be a positive number.`);this._addTrack("video",e,r)}addAudioTrack(e,r={}){if(!(e instanceof Lr))throw new TypeError("source must be an AudioSource.");zo(r),this._addTrack("audio",e,r)}addSubtitleTrack(e,r={}){if(!(e instanceof Ni))throw new TypeError("source must be a SubtitleSource.");zo(r),this._addTrack("subtitle",e,r)}setMetadataTags(e){if(pc(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e,r,i){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(r._connectedTrack)throw new Error("Source is already used for a track.");let n=this.format.getSupportedTrackCounts(),s=this._tracks.reduce((u,l)=>u+(l.type===e?1:0),0),o=n[e].max;if(s===o)throw new Error(o===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${o} ${e} track${o===1?"":"s"}.`);let a=n.total.max;if(this._tracks.length===a)throw new Error(`${this.format._name} does not support more than ${a} tracks${a===1?"":"s"} in total.`);let c={id:this._tracks.length+1,output:this,type:e,source:r,metadata:i};if(c.type==="video"){let u=this.format.getSupportedVideoCodecs();if(u.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!u.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${u.map(l=>`'${l}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="audio"){let u=this.format.getSupportedAudioCodecs();if(u.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!u.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${u.map(l=>`'${l}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="subtitle"){let u=this.format.getSupportedSubtitleCodecs();if(u.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!u.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${u.map(l=>`'${l}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}this._tracks.push(c),r._connectedTrack=c}async start(){let e=this.format.getSupportedTrackCounts();for(let i of Mf){let n=this._tracks.reduce((o,a)=>o+(a.type===i?1:0),0),s=e[i].min;if(n<s)throw new Error(s===e[i].max?`${this.format._name} requires exactly ${s} ${i} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${i} track${s===1?"":"s"}.`)}let r=e.total.min;if(this._tracks.length<r)throw new Error(r===e.total.max?`${this.format._name} requires exactly ${r} track${r===1?"":"s"}.`:`${this.format._name} requires at least ${r} track${r===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();let i=await this._mutex.acquire();await this._muxer.start();let n=this._tracks.map(s=>s.source._start());await Promise.all(n),i()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire(),r=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(r),await this._writer.close(),e()})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire(),r=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));await Promise.all(r),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}};ms.set(Rs);var ll=async t=>t instanceof Blob?new vi(t):new _i(t),dl=tn.work(t=>({async hello(){await t.host.world()},async decodeAudio({source:e,audio:r,start:i,end:n,cancel:s}){let o=new Fr({source:await ll(e),formats:os}),a=await o.getPrimaryAudioTrack(),c=await a?.canDecode(),u=r.getWriter();if(!c||!a)return;let d=new wi(a).samples(i,n);s.onmessage=async()=>{d.return(),o.dispose(),s.close()};for await(let f of d){let m=f.toAudioData();f.close(),await u.write(m),m.close()}await u.close()},async decodeVideo({source:e,video:r,start:i,end:n,cancel:s}){let o=new Fr({source:await ll(e),formats:os}),a=await o.getPrimaryVideoTrack(),c=await a?.canDecode(),u=r.getWriter();if(!c||!a)return;let d=new bi(a).samples(i,n);s.onmessage=async()=>{d.return(),o.dispose(),s.close()};for await(let f of d){let m=f.toVideoFrame();f.close(),await u.write(m),m.close()}await u.close()},async encode({video:e,audio:r,config:i,writable:n}){let s=new Mi({format:new Mr,target:new Fi(n,{chunked:!0})});async function o(){if(!e)return;let l=new Ri(i.video);s.addVideoTrack(l);for await(let d of e){let f=new Ee(d);await l.add(f),f.close(),d.close()}}async function a(){if(!r)return;let l=new Oi(i.audio);s.addAudioTrack(l);for await(let d of r){let f=new Ae(d);await l.add(f),f.close(),d.close()}}let c=a(),u=o();await s.start(),await Promise.all([c,u]),await s.finalize()}}));await tn.worker(dl);
|
|
93
|
+
`),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,r),this.gl.linkProgram(i),i}createShader(e,r){let i=this.gl.createShader(e);return this.gl.shaderSource(i,r),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)||console.error("Shader compile error:",this.gl.getShaderInfoLog(i)),i}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let r=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.STATIC_DRAW);let s=this.gl.getAttribLocation(this.colorProgram,"a_position"),n=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}updateTexture(e){this.lastFrame!==e&&((e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.lastFrame=e)}extractColor(e){return this.updateTexture(e),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}extractAlpha(e){this.updateTexture(e),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let{width:r,height:i}=this.canvas,s=Math.ceil(r/2)*Math.ceil(i/2),n=r*i+s*2,a=Math.ceil(n/(r*4)),o=new Uint8Array(4*r*a);this.gl.readPixels(0,0,r,a,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,n),m(o[r*i]===128),m(o[o.length-1]===128);let c={format:"I420",codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,c)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}},Gr=class extends hr{constructor(e){$o(e),super(e.codec),this._encoder=new yn(this,e)}add(e,r){if(!(e instanceof ge))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,r)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var fr=class extends dr{constructor(e){if(super(),this._connectedTrack=null,!Ue.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Ue.join(", ")}.`);this._codec=e}};var xn=class{constructor(e,r){this.source=e,this.encodingConfig=r,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new Xe,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.error=null,this.errorNeedsNewStack=!0}async add(e,r){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),m(this.encoderInitialized);{let i=Math.round(e.timestamp*e.sampleRate),s=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=s;else{let n=i-this.lastEndSampleIndex;if(n>=64){let a=new we({data:new Float32Array(n*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.add(a,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.customEncoder){this.customEncoderQueueSize++;let i=e.clone(),s=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(i)).then(()=>this.customEncoderQueueSize--).catch(n=>this.error??=n).finally(()=>{i.close()});this.customEncoderQueueSize>=4&&await s,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,r);else{m(this.encoder);let i=e.toAudioData();this.encoder.encode(i),i.close(),r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(s=>this.encoder.addEventListener("dequeue",s,{once:!0})),await this.muxer.mutex.currentPromise}}finally{r&&e.close()}}async doPcmEncoding(e,r){m(this.outputSampleSize),m(this.writeOutputValue);let{numberOfChannels:i,numberOfFrames:s,sampleRate:n,timestamp:a}=e,o=2048,c=[];for(let h=0;h<s;h+=o){let f=Math.min(o,e.numberOfFrames-h),p=f*i*this.outputSampleSize,g=new ArrayBuffer(p),w=new DataView(g);c.push({frameCount:f,view:w})}let l=e.allocationSize({planeIndex:0,format:"f32-planar"}),d=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let h=0;h<i;h++){e.copyTo(d,{planeIndex:h,format:"f32-planar"});for(let f=0;f<c.length;f++){let{frameCount:p,view:g}=c[f];for(let w=0;w<p;w++)this.writeOutputValue(g,(w*i+h)*this.outputSampleSize,d[f*o+w])}}r&&e.close();let u={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:n}};for(let h=0;h<c.length;h++){let{frameCount:f,view:p}=c[h],g=p.buffer,w=h*o,b=new L(new Uint8Array(g),"key",a+w/n,f/n);this.encodingConfig.onEncodedPacket?.(b,u),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,b,u)}}ensureEncoder(e){let r=new Error;this.ensureEncoderPromise=(async()=>{let{numberOfChannels:i,sampleRate:s}=e,n=Ko({numberOfChannels:i,sampleRate:s,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(n);let a=Ea.find(o=>o.supports(this.encodingConfig.codec,n));if(a)this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof L))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(o,c),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,o,c).catch(l=>{this.error??=l,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else if(Q.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.numberOfChannels} channels, ${n.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(c,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){let u=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?u=!0:u=_r(K(l.decoderConfig.description)).objectType===0,u){let h=Number(q(n.codec.split(".")));l.decoderConfig.description=ua({objectType:h,numberOfChannels:l.decoderConfig.numberOfChannels,sampleRate:l.decoderConfig.sampleRate})}}let d=L.fromEncodedChunk(c);this.encodingConfig.onEncodedPacket?.(d,l),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,l).catch(u=>{this.error??=u,this.errorNeedsNewStack=!1})},error:c=>{c.stack=r.stack,this.error??=c}}),this.encoder.configure(n)}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:r,sampleSize:i,littleEndian:s}=fe(e);switch(this.outputSampleSize=i,i){case 1:r==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint8(a,X((o+1)*127.5,0,255)):r==="signed"?this.writeOutputValue=(n,a,o)=>{n.setInt8(a,X(Math.round(o*128),-128,127))}:r==="ulaw"?this.writeOutputValue=(n,a,o)=>{let c=X(Math.floor(o*32767),-32768,32767);n.setUint8(a,Ia(c))}:r==="alaw"?this.writeOutputValue=(n,a,o)=>{let c=X(Math.floor(o*32767),-32768,32767);n.setUint8(a,Aa(c))}:m(!1);break;case 2:r==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint16(a,X((o+1)*32767.5,0,65535),s):r==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt16(a,X(Math.round(o*32767),-32768,32767),s):m(!1);break;case 3:r==="unsigned"?this.writeOutputValue=(n,a,o)=>yr(n,a,X((o+1)*83886075e-1,0,16777215),s):r==="signed"?this.writeOutputValue=(n,a,o)=>Gn(n,a,X(Math.round(o*8388607),-8388608,8388607),s):m(!1);break;case 4:r==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint32(a,X((o+1)*21474836475e-1,0,4294967295),s):r==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt32(a,X(Math.round(o*2147483647),-2147483648,2147483647),s):r==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat32(a,o,s):m(!1);break;case 8:r==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat64(a,o,s):m(!1);break;default:ne(i),m(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}},Kr=class extends fr{constructor(e){Go(e),super(e.codec),this._encoder=new xn(this,e)}add(e){if(!(e instanceof we))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var Xr=class extends dr{constructor(e){if(super(),this._connectedTrack=null,!bt.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${bt.join(", ")}.`);this._codec=e}};var $l=["video","audio","subtitle"],Sn=t=>{if(!t||typeof t!="object")throw new TypeError("metadata must be an object.");if(t.languageCode!==void 0&&!zt(t.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(t.name!==void 0&&typeof t.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(t.disposition!==void 0&&ta(t.disposition),t.maximumPacketCount!==void 0&&(!Number.isInteger(t.maximumPacketCount)||t.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")},Yr=class{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new le,this._metadataTags={},!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof cr))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Ft))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,r={}){if(!(e instanceof hr))throw new TypeError("source must be a VideoSource.");if(Sn(r),r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError(`Invalid video rotation: ${r.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&r.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(r.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${r.frameRate}. Must be a positive number.`);this._addTrack("video",e,r)}addAudioTrack(e,r={}){if(!(e instanceof fr))throw new TypeError("source must be an AudioSource.");Sn(r),this._addTrack("audio",e,r)}addSubtitleTrack(e,r={}){if(!(e instanceof Xr))throw new TypeError("source must be a SubtitleSource.");Sn(r),this._addTrack("subtitle",e,r)}setMetadataTags(e){if(ea(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e,r,i){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(r._connectedTrack)throw new Error("Source is already used for a track.");let s=this.format.getSupportedTrackCounts(),n=this._tracks.reduce((l,d)=>l+(d.type===e?1:0),0),a=s[e].max;if(n===a)throw new Error(a===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${a} ${e} track${a===1?"":"s"}.`);let o=s.total.max;if(this._tracks.length===o)throw new Error(`${this.format._name} does not support more than ${o} tracks${o===1?"":"s"} in total.`);let c={id:this._tracks.length+1,output:this,type:e,source:r,metadata:i};if(c.type==="video"){let l=this.format.getSupportedVideoCodecs();if(l.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!l.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${l.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="audio"){let l=this.format.getSupportedAudioCodecs();if(l.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!l.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${l.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="subtitle"){let l=this.format.getSupportedSubtitleCodecs();if(l.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!l.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${l.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}this._tracks.push(c),r._connectedTrack=c}async start(){let e=this.format.getSupportedTrackCounts();for(let i of $l){let s=this._tracks.reduce((a,o)=>a+(o.type===i?1:0),0),n=e[i].min;if(s<n)throw new Error(n===e[i].max?`${this.format._name} requires exactly ${n} ${i} track${n===1?"":"s"}.`:`${this.format._name} requires at least ${n} ${i} track${n===1?"":"s"}.`)}let r=e.total.min;if(this._tracks.length<r)throw new Error(r===e.total.max?`${this.format._name} requires exactly ${r} track${r===1?"":"s"}.`:`${this.format._name} requires at least ${r} track${r===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();let i=await this._mutex.acquire();await this._muxer.start();let s=this._tracks.map(n=>n.source._start());await Promise.all(s),i()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire(),r=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(r),await this._writer.close(),e()})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire(),r=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));await Promise.all(r),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}};var Xo=async t=>t instanceof Blob?new Lr(t):new Wr(t),Yo=fi.work(t=>({async hello(){await t.host.world()},async decodeAudio({source:e,audio:r,start:i,end:s,cancel:n}){let a=new sr({source:await Xo(e),formats:os}),o=await a.getPrimaryAudioTrack(),c=await o?.canDecode(),l=r.getWriter();if(!c||!o)return;let u=new Rr(o).samples(i,s);n.onmessage=async()=>{u.return(),a.dispose(),n.close()};for await(let h of u){let f=h.toAudioData();h.close(),await l.write(f),f.close()}await l.close()},async decodeVideo({source:e,video:r,start:i,end:s,cancel:n}){let a=new sr({source:await Xo(e),formats:os}),o=await a.getPrimaryVideoTrack(),c=await o?.canDecode(),l=r.getWriter();if(!c||!o)return;let u=new Fr(o).samples(i,s);n.onmessage=async()=>{u.return(),a.dispose(),n.close()};for await(let h of u){let f=h.toVideoFrame();h.close(),await l.write(f),f.close()}await l.close()},async encode({video:e,audio:r,config:i,writable:s}){let n=new Yr({format:new lr,target:new $r(s,{chunked:!0})});async function a(){if(!e)return;let d=new Gr(i.video);n.addVideoTrack(d);for await(let u of e){let h=new ge(u);await d.add(h),h.close(),u.close()}}async function o(){if(!r)return;let d=new Kr(i.audio);n.addAudioTrack(d);for await(let u of r){let h=new we(u);await d.add(h),h.close(),u.close()}}let c=o(),l=a();await n.start(),await Promise.all([c,l]),await n.finalize()}}));await fi.worker(Yo);
|
|
98
94
|
/*! Bundled license information:
|
|
99
95
|
|
|
100
96
|
mediabunny/dist/modules/src/misc.js:
|