VideoPlayer-6cce6818.js 52 KB

1234567891011121314151617181920212223242526272829303132
  1. import{d as Re,k as T,e as ge,w as Le,o as Ie,b as Fe,X as U,a6 as k,a9 as S,_ as W,aa as F,a7 as j,a8 as Z,B as Me,F as Oe,a2 as Ve}from"./vue-fae2b924.js";import{V as $e,A as We,a as ze,b as J,c as Ne}from"./canvas-14fb4930.js";import{V as He}from"./radical-3ee02118.js";var H={},Ge={get exports(){return H},set exports(d){H=d}};(function(d){var t=Object.prototype.hasOwnProperty,e="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(e=!1));function i(o,r,u){this.fn=o,this.context=r,this.once=u||!1}function a(o,r,u,c,f){if(typeof u!="function")throw new TypeError("The listener must be a function");var h=new i(u,c||o,f),g=e?e+r:r;return o._events[g]?o._events[g].fn?o._events[g]=[o._events[g],h]:o._events[g].push(h):(o._events[g]=h,o._eventsCount++),o}function n(o,r){--o._eventsCount===0?o._events=new s:delete o._events[r]}function l(){this._events=new s,this._eventsCount=0}l.prototype.eventNames=function(){var r=[],u,c;if(this._eventsCount===0)return r;for(c in u=this._events)t.call(u,c)&&r.push(e?c.slice(1):c);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(u)):r},l.prototype.listeners=function(r){var u=e?e+r:r,c=this._events[u];if(!c)return[];if(c.fn)return[c.fn];for(var f=0,h=c.length,g=new Array(h);f<h;f++)g[f]=c[f].fn;return g},l.prototype.listenerCount=function(r){var u=e?e+r:r,c=this._events[u];return c?c.fn?1:c.length:0},l.prototype.emit=function(r,u,c,f,h,g){var x=e?e+r:r;if(!this._events[x])return!1;var p=this._events[x],E=arguments.length,C,y;if(p.fn){switch(p.once&&this.removeListener(r,p.fn,void 0,!0),E){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,u),!0;case 3:return p.fn.call(p.context,u,c),!0;case 4:return p.fn.call(p.context,u,c,f),!0;case 5:return p.fn.call(p.context,u,c,f,h),!0;case 6:return p.fn.call(p.context,u,c,f,h,g),!0}for(y=1,C=new Array(E-1);y<E;y++)C[y-1]=arguments[y];p.fn.apply(p.context,C)}else{var I=p.length,D;for(y=0;y<I;y++)switch(p[y].once&&this.removeListener(r,p[y].fn,void 0,!0),E){case 1:p[y].fn.call(p[y].context);break;case 2:p[y].fn.call(p[y].context,u);break;case 3:p[y].fn.call(p[y].context,u,c);break;case 4:p[y].fn.call(p[y].context,u,c,f);break;default:if(!C)for(D=1,C=new Array(E-1);D<E;D++)C[D-1]=arguments[D];p[y].fn.apply(p[y].context,C)}}return!0},l.prototype.on=function(r,u,c){return a(this,r,u,c,!1)},l.prototype.once=function(r,u,c){return a(this,r,u,c,!0)},l.prototype.removeListener=function(r,u,c,f){var h=e?e+r:r;if(!this._events[h])return this;if(!u)return n(this,h),this;var g=this._events[h];if(g.fn)g.fn===u&&(!f||g.once)&&(!c||g.context===c)&&n(this,h);else{for(var x=0,p=[],E=g.length;x<E;x++)(g[x].fn!==u||f&&!g[x].once||c&&g[x].context!==c)&&p.push(g[x]);p.length?this._events[h]=p.length===1?p[0]:p:n(this,h)}return this},l.prototype.removeAllListeners=function(r){var u;return r?(u=e?e+r:r,this._events[u]&&n(this,u)):(this._events=new s,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=e,l.EventEmitter=l,d.exports=l})(Ge);function B(...d){}const Xe=d=>d();function je(){this.dispose()}const Qe=()=>typeof __FASTRX_DEVTOOLS__<"u";let qe=1;class $ extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){const e=new Ke(t,this,this.streamId++);return b.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}}class ie{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=B,this.error=B,this.next=B,this.dispose=B,this.subscribe=B,this.doDefer()}subscribe(t){return t instanceof $?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(Xe),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}}class M extends ie{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}}class Ye extends ie{constructor(t,e=B,s=B,i=B){if(super(),this._next=e,this._error=s,this._complete=i,this.then=B,t instanceof $){const a={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{b.defer(a,0)}),b.create(a),b.pipe(a),this.sourceId=a.id,this.subscribe(t),b.subscribe({id:a.id,end:!0}),e==B?this._next=n=>b.next(a,0,n):this.next=n=>{b.next(a,0,n),e(n)},i==B?this._complete=()=>b.complete(a,0):this.complete=()=>{this.dispose(),b.complete(a,0),i()},s==B?this._error=n=>b.complete(a,0,n):this.error=n=>{this.dispose(),b.complete(a,0,n),s()}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}}function O(d,...t){return t.reduce((e,s)=>s(e),d)}function R(d,t,e){if(Qe()){const s=Object.defineProperties(Object.setPrototypeOf(d,$.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});b.create(s);for(let i=0;i<e.length;i++){const a=e[i];typeof a=="function"&&a instanceof $&&b.addSource(s,a)}return s}return d}function se(d,t){return function(...e){return s=>{if(s instanceof $){const i=R(a=>{const n=new d(a,...e);n.sourceId=i.id,n.subscribe(s)},t,arguments);return i.source=s,b.pipe(i),i}else return i=>s(new d(i,...e))}}}function L(d,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:d,payload:t}})}class Ke extends M{constructor(t,e,s){super(t),this.source=e,this.id=s,this.sourceId=t.sourceId,this.defer(()=>{b.defer(this.source,this.id)})}next(t){b.next(this.source,this.id,t),this.sink.next(t)}complete(){b.complete(this.source,this.id),this.sink.complete()}error(t){b.complete(this.source,this.id,t),this.sink.error(t)}}const b={addSource(d,t){L("addSource",{id:d.id,name:d.toString(),source:{id:t.id,name:t.toString()}})},next(d,t,e){L("next",{id:d.id,streamId:t,data:e&&e.toString()})},subscribe({id:d,end:t},e){L("subscribe",{id:d,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(d,t,e){L("complete",{id:d.id,streamId:t,err:e?e.toString():null})},defer(d,t){L("defer",{id:d.id,streamId:t})},pipe(d){L("pipe",{name:d.toString(),id:d.id,source:{id:d.source.id,name:d.source.toString()}})},update(d){L("update",{id:d.id,name:d.toString()})},create(d){d.id||(d.id=qe++),L("create",{name:d.toString(),id:d.id})}};class Ze extends ie{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}}function Je(){return d=>{const t=new Ze(d);if(d instanceof $){const e=R(s=>{t.add(s)},"share",arguments);return t.sourceId=e.id,e.source=d,b.pipe(e),e}return R(t.add.bind(t),"share",arguments)}}function et(...d){return R(t=>{const e=new M(t);let s=d.length;e.complete=()=>{--s===0&&t.complete()},d.forEach(e.bindSubscribe)},"merge",arguments)}globalThis&&globalThis.__awaiter;function ee(d){const t=arguments,e=Je()(R(s=>{e.next=i=>s.next(i),e.complete=()=>s.complete(),e.error=i=>s.error(i),d&&s.subscribe(d)},"subject",t));return e.next=B,e.complete=B,e.error=B,e}function te(d,t){return e=>{const s=i=>e.next(i);e.defer(()=>t(s)),d(s)}}function z(d,t){if("on"in d&&"off"in d)return R(te(e=>d.on(t,e),e=>d.off(t,e)),"fromEvent",arguments);if("addListener"in d&&"removeListener"in d)return R(te(e=>d.addListener(t,e),e=>d.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in d)return R(te(e=>d.addEventListener(t,e),e=>d.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function tt(){return R(()=>{},"never",arguments)}class it extends M{constructor(t,e){super(t);const s=new M(t);s.next=()=>t.complete(),s.complete=je,s.subscribe(e)}}const N=se(it,"takeUntil");class st extends M{constructor(t,e,s){super(t),this.data=e,this.context=s}next(t){const e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}}class rt extends M{constructor(t,e,s){super(t),this.makeSource=e,this.combineResults=s,this.index=0}subInner(t,e){const s=this.currentSink=new e(this.sink,t,this);this.complete=this.tryComplete,s.complete=s.tryComplete,s.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}}class fe extends st{}class nt extends rt{next(t){this.subInner(t,fe),this.next=e=>{this.currentSink.dispose(),this.subInner(e,fe)}}}const at=se(nt,"switchMap");class ot extends M{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}}const lt=se(ot,"catchError"),V=(d=B,t=B,e=B)=>s=>new Ye(s,d,t,e);class ut{constructor(t){this.id=t,this.type="",this.codec="",this.timescale=0,this.duration=0,this.language="und",this.samples=[]}addSample(t){this.samples.push(t)}addSamples(t){this.samples.push(...t)}getSampleCount(){return this.samples.length}getTotalDuration(){return this.samples.reduce((t,e)=>t+(e.duration||0),0)}}class ct{constructor(t=!1){this.HEADER_SIZE=8,this.sourceUint8Array=null,this.tracks=new Map,this.debug=t}setDebug(t){this.debug=t}parse(t){this.sourceUint8Array=new Uint8Array(t),this.tracks.clear();const e=[];let s=0;for(;s<t.byteLength;){const i=this.parseBox(t,s);if(!i)break;e.push(i),s=i.end,this.debug&&this.logBox(i)}return this.processTrackInfo(e),this.processSampleData(e),this.processCodecInfo(e),Array.from(this.tracks.values())}processTrackInfo(t){var i,a;const e=t.find(n=>n.type==="moov");if(!(e!=null&&e.children))return;const s=e.children.filter(n=>n.type==="trak");for(const n of s){if(!n.children)continue;const l=this.findBox(n,"tkhd");if(!(l!=null&&l.data))continue;const o=l.data.trackID,r=new ut(o),u=this.findBox(n,"mdia");if(!(u!=null&&u.children))continue;const c=this.findBox(u,"hdlr");c!=null&&c.data&&(r.type=c.data.handlerType==="vide"?"video":c.data.handlerType==="soun"?"audio":"unknown");const f=this.findBox(u,"mdhd");f!=null&&f.data&&(r.timescale=f.data.timescale,r.duration=Number(f.data.duration),r.language=f.data.language);const h=this.findBox(n,"stsd");if((a=(i=h==null?void 0:h.data)==null?void 0:i.entries)!=null&&a[0]){const g=h.data.entries[0];g.data&&(r.type==="video"?(r.width=g.data.width,r.height=g.data.height):r.type==="audio"&&(r.channelCount=g.data.channelCount,r.sampleRate=g.data.sampleRate))}this.tracks.set(o,r)}}processCodecInfo(t){const e=this.generateCodecStrings(t);for(const s of this.tracks.values()){const i=e.find(a=>s.type==="video"&&a.mimeType==="video/mp4"||s.type==="audio"&&a.mimeType==="audio/mp4");i&&(s.codecInfo=i,s.codec=i.codecString)}}findBox(t,e){if(t.children)return t.children.find(s=>s.type===e)}processSampleData(t){for(let e=0;e<t.length;e++)if(t[e].type==="moof"&&e+1<t.length&&t[e+1].type==="mdat"){const s=t[e],i=t[e+1];if(s.children)for(const a of s.children)a.type==="traf"&&this.processTrafBox(a,s.start,i)}}processTrafBox(t,e,s){if(!t.children)return;let i=null,a=null;for(const c of t.children)c.type==="tfhd"?i=c:c.type==="trun"&&(a=c);if(!(i!=null&&i.data)||!(a!=null&&a.data))return;const n=i.data.trackID,l=this.tracks.get(n);if(!l)return;const o=a.data;if(!o.samples||o.dataOffset===void 0)return;const r=e+o.dataOffset;if(r<s.start+this.HEADER_SIZE||r>=s.end){this.debug&&console.warn(`Data offset ${r} is outside mdat box range`);return}let u=r;for(const c of o.samples){const f=c.size||i.data.defaultSampleSize||0;if(f<=0)continue;const h=u,g=h+f;g<=s.end&&this.sourceUint8Array&&(c.dataStart=h,c.dataEnd=g,c.data=this.sourceUint8Array.subarray(h,g),l.addSample(c)),u+=f}}parseBox(t,e){if(e+this.HEADER_SIZE>t.byteLength)return null;const i=new DataView(t).getUint32(e,!1),a=new Uint8Array(t,e+4,4),n=String.fromCharCode(...a),l=e,o=e+i,r={type:n,size:i,start:l,end:o};return this.isContainerBox(n)?r.children=this.parseChildren(t,e+this.HEADER_SIZE,o):r.data=this.parseBoxData(t,n,e+this.HEADER_SIZE,o),r}parseChildren(t,e,s){const i=[];let a=e;for(;a<s;){const n=this.parseBox(t,a);if(!n)break;i.push(n),a=n.end}return i}parseBoxData(t,e,s,i){if(i-s<=0)return null;switch(e){case"ftyp":return this.parseFtypBox(t,s,i);case"mvhd":return this.parseMvhdBox(t,s,i);case"mdhd":return this.parseMdhdBox(t,s,i);case"hdlr":return this.parseHdlrBox(t,s,i);case"tkhd":return this.parseTkhdBox(t,s,i);case"elst":return this.parseElstBox(t,s,i);case"moof":case"mfhd":return this.parseMfhdBox(t,s,i);case"tfhd":return this.parseTfhdBox(t,s,i);case"tfdt":return this.parseTfdtBox(t,s,i);case"trun":return this.parseTrunBox(t,s,i);case"mdat":return this.parseMdatBox(t,s,i);case"stsd":return this.parseStsdBox(t,s,i);case"avc1":case"avc3":return this.parseAvcBox(t,s,i);case"hev1":case"hvc1":return this.parseHevcBox(t,s,i);case"mp4a":return this.parseMp4aBox(t,s,i);case"avcC":return this.parseAvcCBox(t,s,i);case"hvcC":return this.parseHvcCBox(t,s,i);case"esds":return this.parseEsdsBox(t,s,i);default:return new Uint8Array(t.slice(s,i))}}parseMdatBox(t,e,s){return{dataSize:s-e,dataOffset:e}}isContainerBox(t){return["moov","trak","edts","mdia","minf","dinf","stbl","mvex","moof","traf","mfra","skip","meta","ipro","sinf"].includes(t)}parseFtypBox(t,e,s){const i=new DataView(t),a=this.readFourCC(t,e),n=i.getUint32(e+4,!1),l=[];for(let o=e+8;o<s;o+=4)l.push(this.readFourCC(t,o));return{majorBrand:a,minorVersion:n,compatibleBrands:l}}parseMvhdBox(t,e,s){const i=new DataView(t),a=i.getUint8(e),n=i.getUint8(e+1)<<16|i.getUint8(e+2)<<8|i.getUint8(e+3);let l,o,r,u;return a===1?(l=i.getBigUint64(e+4,!1),o=i.getBigUint64(e+12,!1),r=i.getUint32(e+20,!1),u=i.getBigUint64(e+24,!1)):(l=i.getUint32(e+4,!1),o=i.getUint32(e+8,!1),r=i.getUint32(e+12,!1),u=i.getUint32(e+16,!1)),{version:a,flags:n,creationTime:l,modificationTime:o,timescale:r,duration:u}}parseMdhdBox(t,e,s){const i=new DataView(t),a=i.getUint8(e),n=i.getUint8(e+1)<<16|i.getUint8(e+2)<<8|i.getUint8(e+3);let l,o,r,u,c;return a===1?(l=i.getBigUint64(e+4,!1),o=i.getBigUint64(e+12,!1),r=i.getUint32(e+20,!1),u=i.getBigUint64(e+24,!1),c=this.parseLanguage(i.getUint16(e+32,!1))):(l=i.getUint32(e+4,!1),o=i.getUint32(e+8,!1),r=i.getUint32(e+12,!1),u=i.getUint32(e+16,!1),c=this.parseLanguage(i.getUint16(e+20,!1))),{version:a,flags:n,creationTime:l,modificationTime:o,timescale:r,duration:u,language:c}}parseHdlrBox(t,e,s){const i=new DataView(t),a=i.getUint8(e),n=i.getUint8(e+1)<<16|i.getUint8(e+2)<<8|i.getUint8(e+3),l=this.readFourCC(t,e+8);let o="",r=e+24;for(;r<s;){const u=i.getUint8(r);if(u===0)break;o+=String.fromCharCode(u),r++}return{version:a,flags:n,handlerType:l,name:o}}parseTkhdBox(t,e,s){const i=new DataView(t),a=i.getUint8(e),n=i.getUint8(e+1)<<16|i.getUint8(e+2)<<8|i.getUint8(e+3);let l,o,r,u;return a===1?(l=i.getBigUint64(e+4,!1),o=i.getBigUint64(e+12,!1),r=i.getUint32(e+20,!1),u=i.getBigUint64(e+28,!1)):(l=i.getUint32(e+4,!1),o=i.getUint32(e+8,!1),r=i.getUint32(e+12,!1),u=i.getUint32(e+20,!1)),{version:a,flags:n,creationTime:l,modificationTime:o,trackID:r,duration:u,enabled:(n&1)!==0,inMovie:(n&2)!==0,inPreview:(n&4)!==0}}parseElstBox(t,e,s){const i=new DataView(t),a=i.getUint8(e),n=i.getUint8(e+1)<<16|i.getUint8(e+2)<<8|i.getUint8(e+3),l=i.getUint32(e+4,!1),o=[];let r=e+8;for(let u=0;u<l;u++)if(a===1){const c=i.getBigUint64(r,!1),f=i.getBigInt64(r+8,!1),h=i.getInt16(r+16,!1),g=i.getInt16(r+18,!1);o.push({segmentDuration:c,mediaTime:f,mediaRateInteger:h,mediaRateFraction:g}),r+=20}else{const c=i.getUint32(r,!1),f=i.getInt32(r+4,!1),h=i.getInt16(r+8,!1),g=i.getInt16(r+10,!1);o.push({segmentDuration:c,mediaTime:f,mediaRateInteger:h,mediaRateFraction:g}),r+=12}return{version:a,flags:n,entries:o}}parseMfhdBox(t,e,s){const i=new DataView(t),a=i.getUint8(e),n=i.getUint8(e+1)<<16|i.getUint8(e+2)<<8|i.getUint8(e+3),l=i.getUint32(e+4,!1);return{version:a,flags:n,sequenceNumber:l}}parseTfhdBox(t,e,s){const i=new DataView(t),a=i.getUint8(e),n=i.getUint8(e+1)<<16|i.getUint8(e+2)<<8|i.getUint8(e+3),l=i.getUint32(e+4,!1);let o=e+8;const r={version:a,flags:n,trackID:l};return n&1&&(r.baseDataOffset=i.getBigUint64(o,!1),o+=8),n&2&&(r.sampleDescriptionIndex=i.getUint32(o,!1),o+=4),n&8&&(r.defaultSampleDuration=i.getUint32(o,!1),o+=4),n&16&&(r.defaultSampleSize=i.getUint32(o,!1),o+=4),n&32&&(r.defaultSampleFlags=i.getUint32(o,!1)),r}parseTfdtBox(t,e,s){const i=new DataView(t),a=i.getUint8(e),n=i.getUint8(e+1)<<16|i.getUint8(e+2)<<8|i.getUint8(e+3);let l;return a===1?l=i.getBigUint64(e+4,!1):l=i.getUint32(e+4,!1),{version:a,flags:n,baseMediaDecodeTime:l}}parseTrunBox(t,e,s){const i=new DataView(t),a=i.getUint8(e),n=i.getUint8(e+1)<<16|i.getUint8(e+2)<<8|i.getUint8(e+3),l=i.getUint32(e+4,!1);let o=e+8;const r={version:a,flags:n,sampleCount:l,samples:[]};n&1&&(r.dataOffset=i.getInt32(o,!1),o+=4),n&4&&(r.firstSampleFlags=i.getUint32(o,!1),o+=4);const u=[];for(let c=0;c<l;c++){const f={dataStart:0,dataEnd:0,data:new Uint8Array(0),keyFrame:!0};if(n&256&&(f.duration=i.getUint32(o,!1),o+=4),n&512&&(f.size=i.getUint32(o,!1),o+=4),n&1024){f.flags=i.getUint32(o,!1);const h=f.flags>>24&3;f.keyFrame=h===2,o+=4}else if(c===0&&r.firstSampleFlags!==void 0){const h=r.firstSampleFlags>>24&3;f.keyFrame=h===2}n&2048&&(a===0?f.compositionTimeOffset=i.getUint32(o,!1):f.compositionTimeOffset=i.getInt32(o,!1),o+=4),u.push(f)}return r.samples=u,r}parseLanguage(t){const e=String.fromCharCode((t>>10&31)+96),s=String.fromCharCode((t>>5&31)+96),i=String.fromCharCode((t&31)+96);return e+s+i}readFourCC(t,e){const s=new Uint8Array(t,e,4);return String.fromCharCode(...s)}logBox(t,e=0){if(!this.debug)return;const s=" ".repeat(e);if(`${s}${t.type}${t.size}${t.start}${t.end}`,t.data&&(`${s}`,t.data),t.children&&t.children.length>0){`${s}${t.children.length}`;for(const i of t.children)this.logBox(i,e+2)}}printBoxes(t){let e=`FMP4 Structure:
  2. `;const s=(i,a=0)=>{const n=" ".repeat(a);if(e+=`${n}${i.type} (${i.size} bytes)
  3. `,i.data){const l=JSON.stringify(i.data,(o,r)=>typeof r=="bigint"?r.toString():o==="data"&&r instanceof Uint8Array?`Uint8Array(${r.byteLength} bytes)`:r,2);e+=`${n} Data: ${l}
  4. `}if(i.children&&i.children.length>0)for(const l of i.children)s(l,a+1)};for(const i of t)s(i);return e}getSamples(t,e){const s=[];return this.findBoxes(t,"moof").forEach(i=>{i.children&&i.children.filter(a=>a.type==="traf").forEach(a=>{if(!a.children)return;const n=a.children.find(o=>o.type==="tfhd");if(!n||!n.data||e!==void 0&&n.data.trackID!==e)return;a.children.filter(o=>o.type==="trun").forEach(o=>{!o.data||!o.data.samples||o.data.samples.forEach(r=>{r.data&&r.data.byteLength>0&&s.push(r)})})})}),s}findBoxes(t,e){const s=[],i=a=>{for(const n of a)n.type===e&&s.push(n),n.children&&n.children.length>0&&i(n.children)};return i(t),s}parseStsdBox(t,e,s){const i=new DataView(t),a=i.getUint8(e),n=i.getUint8(e+1)<<16|i.getUint8(e+2)<<8|i.getUint8(e+3),l=i.getUint32(e+4,!1);let o=e+8;const r=[];for(let u=0;u<l&&o<s;u++){const c=i.getUint32(o,!1),f=this.readFourCC(t,o+4);let h;switch(f){case"avc1":case"avc3":if(h=this.parseAvcBox(t,o+8,o+c),o+c>o+8+78){const g=this.parseBox(t,o+8+78);g&&g.type==="avcC"&&(h.avcC=g.data)}break;case"hev1":case"hvc1":if(h=this.parseHevcBox(t,o+8,o+c),o+c>o+8+78){const g=this.parseBox(t,o+8+78);g&&g.type==="hvcC"&&(h.hvcC=g.data)}break;case"mp4a":if(h=this.parseMp4aBox(t,o+8,o+c),o+c>o+8+28){const g=this.parseBox(t,o+8+28);g&&g.type==="esds"&&(h.esds=g.data)}break;default:h=new Uint8Array(t.slice(o+8,o+c))}r.push({size:c,type:f,data:h}),o+=c}return{version:a,flags:n,entryCount:l,entries:r}}parseAvcBox(t,e,s){const i=new DataView(t);e+=6;const a=i.getUint16(e,!1);e+=2,e+=16;const n=i.getUint16(e,!1),l=i.getUint16(e+2,!1),o=i.getUint32(e+4,!1),r=i.getUint32(e+8,!1);e+=12,e+=4;const u=i.getUint16(e,!1);e+=2;const c=i.getUint8(e),f=this.readString(t,e+1,c);e+=32;const h=i.getUint16(e,!1),g=i.getInt16(e+2,!1);return{dataReferenceIndex:a,width:n,height:l,horizresolution:o,vertresolution:r,frameCount:u,compressorName:f,depth:h,preDefined:g}}parseHevcBox(t,e,s){return this.parseAvcBox(t,e,s)}parseMp4aBox(t,e,s){const i=new DataView(t);e+=6;const a=i.getUint16(e,!1);e+=2,e+=8;const n=i.getUint16(e,!1),l=i.getUint16(e+2,!1);e+=4,e+=4;const o=i.getUint32(e,!1)>>16;return{dataReferenceIndex:a,channelCount:n,sampleSize:l,sampleRate:o}}readString(t,e,s){const i=new Uint8Array(t,e,s);return String.fromCharCode(...i).replace(/\0+$/,"")}parseAvcCBox(t,e,s){const i=new DataView(t);return{data:new Uint8Array(t,e,s-e),configurationVersion:i.getUint8(e),profileIndication:i.getUint8(e+1),profileCompatibility:i.getUint8(e+2),levelIndication:i.getUint8(e+3)}}parseHvcCBox(t,e,s){const i=new DataView(t);return{data:new Uint8Array(t,e,s-e),configurationVersion:i.getUint8(e),generalProfileSpace:i.getUint8(e+1)>>6&3,generalTierFlag:i.getUint8(e+1)>>5&1,generalProfileIdc:i.getUint8(e+1)&31,generalProfileCompatibilityFlags:i.getUint32(e+2),generalConstraintIndicatorFlags:new Uint8Array(t,e+6,6),generalLevelIdc:i.getUint8(e+12),minSpatialSegmentationIdc:i.getUint16(e+13,!1)&4095,parallelismType:i.getUint8(e+15)&3}}parseEsdsBox(t,e,s){const i=new DataView(t);if(e+=4,i.getUint8(e)===3){const a=this.parseExpandableLength(t,e+1);if(e+=1+a.bytesRead,e+=3,i.getUint8(e)===4){const n=this.parseExpandableLength(t,e+1);e+=1+n.bytesRead;const l={objectTypeIndication:(i.getUint8(e)>>6)+1,streamType:i.getUint8(e+1)>>2&63,bufferSizeDB:(i.getUint8(e+1)&3)<<16|i.getUint8(e+2)<<8|i.getUint8(e+3),maxBitrate:i.getUint32(e+4,!1),avgBitrate:i.getUint32(e+8,!1)};if(e+=13,e<s&&i.getUint8(e)===5){const o=this.parseExpandableLength(t,e+1);e+=1+o.bytesRead;const r=new Uint8Array(t,e,o.length);return e+=o.length,{decoderConfig:l,specificInfo:r,data:r}}return{decoderConfig:l,data:new Uint8Array(0)}}}return null}parseExpandableLength(t,e){const s=new DataView(t);let i=0,a=0,n;do n=s.getUint8(e+a),i=i<<7|n&127,a++;while(n&128);return{length:i,bytesRead:a}}reverseBits(t){let e=0;for(let s=0;s<32&&(e|=t&1,s!==31);s++)e<<=1,t>>=1;return e}generateCodecStrings(t){var i,a;const e=[],s=this.findBoxes(t,"stsd");for(const n of s)if((i=n.data)!=null&&i.entries)for(const l of n.data.entries){const{type:o,data:r}=l;switch(o){case"avc1":case"avc3":{if(r!=null&&r.avcC){const{profileIndication:u,profileCompatibility:c,levelIndication:f}=r.avcC,h=`${o}.`+u.toString(16).padStart(2,"0")+c.toString(16).padStart(2,"0")+f.toString(16).padStart(2,"0");e.push({codecString:h,mimeType:"video/mp4",extraData:r.avcC.data})}break}case"hev1":case"hvc1":{if(r!=null&&r.hvcC){const{generalProfileSpace:u,generalProfileIdc:c,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:h,generalLevelIdc:g}=r.hvcC,x=c,p=this.reverseBits(f).toString(16),E=`L${g}`,C=h[0].toString(16).padStart(2,"0"),y=`${o}.${x}.${p}.${E}.${C}`;e.push({codecString:y,mimeType:"video/mp4",extraData:r.hvcC.data})}break}case"mp4a":{if((a=r==null?void 0:r.esds)!=null&&a.decoderConfig){const{objectTypeIndication:u}=r.esds.decoderConfig,c=`mp4a.40.${u}`;e.push({codecString:c,mimeType:"audio/mp4",extraData:r.esds.data})}break}}}return e}}class dt extends H{constructor(t,e){super(),this.index=t,this.state="init",this.fmp4Parser=new ct(!1),this.tracks=[],this.loadingProgress={loaded:0,total:0},this.url=e.url,this.duration=e.duration,this.virtualStartTime=0,this.virtualEndTime=0,this.physicalTime=e.physicalTime}async fetchWithProgress(t){const e=await fetch(t),s=e.body.getReader(),i=+e.headers.get("Content-Length");let a=0;const n=[];for(;;){const{done:r,value:u}=await s.read();if(r)break;n.push(u),a+=u.length,this.loadingProgress={loaded:a,total:i},this.emit("progress",this.loadingProgress)}const l=new Uint8Array(a);let o=0;for(const r of n)l.set(r,o),o+=r.length;return l.buffer}async load(t){this.state="loading",this.data||(this.data=this.fetchWithProgress(this.url));const e=await this.data;if(this.tracks.length===0&&(this.tracks=this.fmp4Parser.parse(e)),!t.initialized){const s=`video/mp4; codecs="${this.tracks.map(i=>i.codec).join(", ")}"`;if(MediaSource.isTypeSupported(s))t.init(s);else throw new Error(`Unsupported codec: ${s}`)}this.state==="loading"&&(this.state="buffering",await t.appendBuffer({data:e,tracks:this.tracks}),this.state="buffered")}unBuffer(){this.state!=="init"&&(delete this.ready,this.state="loaded")}downgrade(t){this.load=async function(e){var a,n;if(this.state==="init"){this.state="loading",this.data||(this.data=this.fetchWithProgress(this.url));const l=await this.data;this.tracks=this.fmp4Parser.parse(l),this.state="buffering"}const s=this.tracks.filter(l=>l.type==="video"),i=this.tracks.filter(l=>l.type==="audio");for(const l of s){t.videoDecoder.state!=="configured"&&(await t.videoDecoder.initialize(),await t.videoDecoder.configure({codec:l.codec.startsWith("avc1")?"avc":"hevc",description:(a=l.codecInfo)==null?void 0:a.extraData}),t.canvas.width=l.width??1920,t.canvas.height=l.height??1080);let o=this.virtualStartTime*1e3;l.samples.forEach(r=>{t.decodeVideo({data:r.data,timestamp:o,type:r.keyFrame?"key":"delta"}),o+=r.duration??0})}for(const l of i){t.audioDecoder.state!=="configured"&&(await t.audioDecoder.initialize(),await t.audioDecoder.configure({codec:"aac",description:(n=l.codecInfo)==null?void 0:n.extraData,numberOfChannels:l.channelCount??2,sampleRate:l.sampleRate??44100}));let o=this.virtualStartTime*1e3;l.samples.forEach(r=>{t.decodeAudio({data:r.data,timestamp:o,type:"key"}),o+=r.duration??0})}this.state="buffered"},this.unBuffer=function(){this.state!=="init"&&(delete this.ready,this.state="loaded",t.videoBuffer=t.videoBuffer.filter(e=>e.timestamp<this.virtualStartTime*1e3||e.timestamp>=this.virtualEndTime*1e3),t.audioBuffer=t.audioBuffer.filter(e=>e.timestamp<this.virtualStartTime*1e3||e.timestamp>=this.virtualEndTime*1e3))}}}const ht=/#EXTINF:(\d+\.\d+),(.*?)\s*$/;function gt(d,t){const e=d.split(`
  5. `),s=[];let i=0,a=0,n=0,l=null;for(let o=0;o<e.length;o++){const r=e[o].trim();if(r.startsWith("#EXTINF:")){const u=r.match(ht);if(u){n=parseFloat(u[1]);const c=u[2]?u[2].trim():"";try{c?l=new Date(c):l=null}catch{l=null}}}else if(!r.startsWith("#")&&r!==""){const u=new URL(r,t),c=i,f=i+n,h=new dt(a,{url:u.toString(),duration:n,physicalTime:l});h.virtualStartTime=c,h.virtualEndTime=f,s.push(h),i+=n,a++,l=null}}return{segments:s,totalDuration:i}}class pe{constructor(t){this.mediaSource=t,this.queue=[],this.removeQueue=[],this.currentError=console.log}get initialized(){return!!this.sourceBuffer}init(t){this.sourceBuffer=this.mediaSource.addSourceBuffer(t),this.sourceBuffer.mode="sequence",this.sourceBuffer.addEventListener("updateend",()=>{var e;if((e=this.currentWaiting)==null||e.call(this),this.removeQueue.length>0){const{start:s,end:i,resolve:a,reject:n}=this.removeQueue.shift();this.sourceBuffer.remove(s,i),this.currentWaiting=a,this.currentError=n}else if(this.queue.length>0){const{data:s,resolve:i,reject:a}=this.queue.shift();this.sourceBuffer.appendBuffer(s),this.currentWaiting=i,this.currentError=a}else delete this.currentWaiting}),this.sourceBuffer.addEventListener("error",e=>{this.currentError(e)})}appendBuffer(t){return this.currentWaiting?new Promise((e,s)=>{this.queue.push({data:t.data,resolve:e,reject:s})}):(this.sourceBuffer.appendBuffer(t.data),new Promise((e,s)=>{this.currentWaiting=e,this.currentError=s}))}remove(t,e){return this.currentWaiting?new Promise((s,i)=>{this.removeQueue.push({start:t,end:e,resolve:s,reject:i})}):(this.sourceBuffer.remove(t,e),new Promise((s,i)=>{this.currentWaiting=s,this.currentError=i}))}destroy(){if(this.sourceBuffer){try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch{}this.sourceBuffer=void 0}this.queue=[],this.removeQueue=[],delete this.currentWaiting,this.currentError=()=>{}}}class ft extends H{constructor(t,e={debug:!1}){super(),this.video=t,this.mediaSource=new MediaSource,this.sourceBufferProxy=new pe(this.mediaSource),this.urlSource=URL.createObjectURL(this.mediaSource),this.debug=!1,this.ready=this.init(),this.debug=e.debug,t.src=this.urlSource}async appendSegment(t){if(this.mediaSource.readyState!=="open")return!1;if(!this.sourceBufferProxy)throw new Error("SourceBufferProxy not initialized");return t.ready?(await t.ready,!1):(t.ready=t.load(this.sourceBufferProxy),await t.ready,!0)}async removeBuffer(t,e){if(!this.sourceBufferProxy)throw new Error("SourceBufferProxy not initialized");return this.sourceBufferProxy.remove(t,e)}destroy(){this.video.src="",this.mediaSource.readyState==="open"&&this.mediaSource.endOfStream(),this.urlSource&&URL.revokeObjectURL(this.urlSource),this.sourceBufferProxy.destroy(),this.emit("destroyed")}get readyState(){return this.mediaSource.readyState}endOfStream(){this.mediaSource.readyState==="open"&&this.mediaSource.endOfStream()}reset(){this.destroy(),this.mediaSource=new MediaSource,this.sourceBufferProxy=new pe(this.mediaSource),this.urlSource=URL.createObjectURL(this.mediaSource),this.video.src=this.urlSource,this.ready=this.init()}init(){return this.mediaSource.addEventListener("sourceended",()=>{this.emit("ended")}),this.mediaSource.addEventListener("sourceclose",()=>{this.emit("closed")}),new Promise((t,e)=>{this.mediaSource.addEventListener("sourceopen",()=>{this.emit("sourceopen"),t()})})}}class pt{constructor(t){this.gl=null,this.program=null,this.yTexture=null,this.uTexture=null,this.vTexture=null,this.positionBuffer=null,this.texCoordBuffer=null,this.width=0,this.height=0,this.setupWebGL(t)}setupWebGL(t){try{if(this.gl=t.getContext("webgl",{preserveDrawingBuffer:!0}),!this.gl)throw new Error("WebGL not supported");const e=this.createShader(this.gl.VERTEX_SHADER,`
  6. attribute vec4 a_position;
  7. attribute vec2 a_texCoord;
  8. varying vec2 v_texCoord;
  9. void main() {
  10. gl_Position = a_position;
  11. v_texCoord = a_texCoord;
  12. }
  13. `),s=this.createShader(this.gl.FRAGMENT_SHADER,`
  14. precision mediump float;
  15. uniform sampler2D y_texture;
  16. uniform sampler2D u_texture;
  17. uniform sampler2D v_texture;
  18. varying vec2 v_texCoord;
  19. void main() {
  20. float y = texture2D(y_texture, v_texCoord).r;
  21. float u = texture2D(u_texture, v_texCoord).r - 0.5;
  22. float v = texture2D(v_texture, v_texCoord).r - 0.5;
  23. // YUV to RGB conversion
  24. float r = y + 1.402 * v;
  25. float g = y - 0.344 * u - 0.714 * v;
  26. float b = y + 1.772 * u;
  27. gl_FragColor = vec4(r, g, b, 1.0);
  28. }
  29. `);if(!e||!s)throw new Error("Failed to create shaders");if(this.program=this.createProgram(e,s),!this.program)throw new Error("Failed to create shader program");this.createBuffers(),this.yTexture=this.createTexture(),this.uTexture=this.createTexture(),this.vTexture=this.createTexture()}catch(e){console.error("Error initializing WebGL:",e),this.gl=null}}createShader(t,e){if(!this.gl)return null;const s=this.gl.createShader(t);return s?(this.gl.shaderSource(s,e),this.gl.compileShader(s),this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS)?s:(console.error("Shader compile error:",this.gl.getShaderInfoLog(s)),this.gl.deleteShader(s),null)):null}createProgram(t,e){if(!this.gl)return null;const s=this.gl.createProgram();return s?(this.gl.attachShader(s,t),this.gl.attachShader(s,e),this.gl.linkProgram(s),this.gl.getProgramParameter(s,this.gl.LINK_STATUS)?s:(console.error("Program link error:",this.gl.getProgramInfoLog(s)),this.gl.deleteProgram(s),null)):null}createTexture(){if(!this.gl)return null;const t=this.gl.createTexture();return t?(this.gl.bindTexture(this.gl.TEXTURE_2D,t),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),t):null}createBuffers(){if(!this.gl||!this.program)return;this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer);const t=[-1,-1,1,-1,-1,1,1,1];this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(t),this.gl.STATIC_DRAW),this.texCoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer);const e=[0,1,1,1,0,0,1,0];this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(e),this.gl.STATIC_DRAW)}setDimensions(t,e){this.width=t,this.height=e,this.gl&&this.gl.viewport(0,0,t,e)}render(t,e,s,i,a){if(!this.gl||!this.program||!this.yTexture||!this.uTexture||!this.vTexture){console.error("WebGL not initialized properly");return}this.gl.useProgram(this.program),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer);const n=this.gl.getAttribLocation(this.program,"a_position");this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer);const l=this.gl.getAttribLocation(this.program,"a_texCoord");this.gl.enableVertexAttribArray(l),this.gl.vertexAttribPointer(l,2,this.gl.FLOAT,!1,0,0),this.updateTexture(this.yTexture,0,t,this.width,this.height,i),this.updateTexture(this.uTexture,1,e,this.width/2,this.height/2,a),this.updateTexture(this.vTexture,2,s,this.width/2,this.height/2,a);const o=this.gl.getUniformLocation(this.program,"y_texture"),r=this.gl.getUniformLocation(this.program,"u_texture"),u=this.gl.getUniformLocation(this.program,"v_texture");this.gl.uniform1i(o,0),this.gl.uniform1i(r,1),this.gl.uniform1i(u,2),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}updateTexture(t,e,s,i,a,n){if(this.gl)if(this.gl.activeTexture(this.gl.TEXTURE0+e),this.gl.bindTexture(this.gl.TEXTURE_2D,t),n===i)this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.LUMINANCE,i,a,0,this.gl.LUMINANCE,this.gl.UNSIGNED_BYTE,s);else{const l=new Uint8Array(i*a);for(let o=0;o<a;o++)for(let r=0;r<i;r++)l[o*i+r]=s[o*n+r];this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.LUMINANCE,i,a,0,this.gl.LUMINANCE,this.gl.UNSIGNED_BYTE,l)}}renderVideoFrame(t){this.setDimensions(t.codedWidth,t.codedHeight);const e=t.codedWidth*t.codedHeight,s=t.codedWidth/2*(t.codedHeight/2),i=new Uint8Array(e),a=new Uint8Array(s),n=new Uint8Array(s);t.copyTo(i,{rect:{x:0,y:0,width:t.codedWidth,height:t.codedHeight},layout:[{offset:0,stride:t.codedWidth}]}),t.format==="I420"?(t.copyTo(a,{rect:{x:0,y:0,width:t.codedWidth/2,height:t.codedHeight/2},layout:[{offset:e,stride:t.codedWidth/2}]}),t.copyTo(n,{rect:{x:0,y:0,width:t.codedWidth/2,height:t.codedHeight/2},layout:[{offset:e+s,stride:t.codedWidth/2}]})):(t.copyTo(n,{rect:{x:0,y:0,width:t.codedWidth/2,height:t.codedHeight/2},layout:[{offset:e,stride:t.codedWidth/2}]}),t.copyTo(a,{rect:{x:0,y:0,width:t.codedWidth/2,height:t.codedHeight/2},layout:[{offset:e+s,stride:t.codedWidth/2}]})),this.render(i,a,n,t.codedWidth,t.codedWidth/2)}dispose(){this.gl&&(this.gl.deleteTexture(this.yTexture),this.gl.deleteTexture(this.uTexture),this.gl.deleteTexture(this.vTexture),this.gl.deleteBuffer(this.positionBuffer),this.gl.deleteBuffer(this.texCoordBuffer),this.program&&this.gl.deleteProgram(this.program),this.gl=null)}}class mt{constructor(t,e){this.audioContext=null,this.videoBuffer=[],this.audioBuffer=[],this.startTime=0,this.isPlaying=!1,this.animationFrameId=null,this.maxBufferSize=1/0,this.playbackSpeed=1,this.keyFrameList=[],this.seekTime=null,this.timeOffset=0,this.gl=null,this.yuvRenderer=null,this.audioQueue=[],this.audioQueueTimestamps=[],this.nextAudioStartTime=0,this.audioScheduleAheadTime=.2,this.lastAudioScheduleTime=0,this.audioGain=null,this.pausedAt=null,this.processNextFrame=()=>{if(!this.isPlaying)return;const s=this.getCurrentTime();if(this.videoBuffer.length&&(this.videoBuffer.length,this.videoBuffer[this.videoBuffer.length-1].timestamp),this.seekTime!==null){for(;this.videoBuffer.length>0&&this.videoBuffer[0].timestamp<this.seekTime;)this.videoBuffer.shift();for(;this.audioBuffer.length>0&&this.audioBuffer[0].timestamp<this.seekTime;)this.audioBuffer.shift();this.seekTime=null}if(this.videoBuffer.length>0&&this.videoBuffer[0].timestamp<=s){const i=this.videoBuffer.shift();i&&this.videoDecoder.decode(i)}if(this.videoBuffer.length>0){const i=this.videoBuffer.findIndex((a,n)=>n>0&&a.type==="key");i!==-1&&this.videoBuffer.slice(0,i).every(l=>l.timestamp<=s)&&this.videoBuffer.splice(0,i)}if(this.audioBuffer.length>0&&this.audioBuffer[0].timestamp<=s){const i=this.audioBuffer.shift();i&&this.audioDecoder.decode(i)}this.audioContext&&this.audioContext.currentTime-this.lastAudioScheduleTime>this.audioScheduleAheadTime/2&&this.scheduleAudioPlayback(),this.animationFrameId=requestAnimationFrame(this.processNextFrame)},this.canvas=document.createElement("canvas"),this.canvas.style.width="160px",this.canvas.style.height="120px",e!=null&&e.yuvMode?this.yuvRenderer=new pt(this.canvas):this.gl=this.canvas.getContext("2d"),this.videoDecoder=new $e({workerMode:!1,yuvMode:!!this.yuvRenderer,canvas:this.canvas,wasmPath:t}),this.audioDecoder=typeof AudioDecoder>"u"?new We:new ze,this.videoDecoder.on(J.VideoFrame,s=>{if(this.yuvRenderer){const i=s;this.yuvRenderer.render(i[0],i[1],i[2],this.canvas.width,this.canvas.width/2)}else this.gl&&(this.gl.drawImage(s,0,0),s.close())}),this.videoDecoder.on(J.VideoCodecInfo,s=>{this.canvas.width=s.width,this.canvas.height=s.height,this.yuvRenderer&&this.yuvRenderer.setDimensions(s.width,s.height)}),this.videoDecoder.on(J.Error,s=>{console.error(s)}),this.audioDecoder.on(Ne.AudioFrame,s=>{this.audioContext||this.initAudioContext();const i=this.audioContext.createBuffer(s.numberOfChannels,s.numberOfFrames,s.sampleRate);for(let a=0;a<s.numberOfChannels;a++){const n=new Float32Array(s.numberOfFrames);s.copyTo(n,{planeIndex:a}),i.copyToChannel(n,a)}this.audioQueue.push(i),this.audioQueueTimestamps.push(s.timestamp),this.scheduleAudioPlayback()})}initAudioContext(){this.audioContext=new AudioContext,this.audioGain=this.audioContext.createGain(),this.audioGain.connect(this.audioContext.destination),this.nextAudioStartTime=this.audioContext.currentTime}scheduleAudioPlayback(){if(!(!this.isPlaying||!this.audioContext||this.audioQueue.length===0)&&!(this.nextAudioStartTime>this.audioContext.currentTime+this.audioScheduleAheadTime)){for(;this.audioQueue.length>0;){const t=this.audioQueue[0],e=this.audioQueueTimestamps[0],s=this.audioContext.createBufferSource();s.buffer=t,s.connect(this.audioGain),s.playbackRate.value=this.playbackSpeed;const i=performance.now(),a=e*this.playbackSpeed,n=this.audioContext.currentTime+Math.max(0,(a-(i-this.startTime))/1e3),l=Math.max(this.audioContext.currentTime,Math.max(n,this.nextAudioStartTime));if(s.start(l),this.nextAudioStartTime=l+t.duration/this.playbackSpeed,this.audioQueue.shift(),this.audioQueueTimestamps.shift(),this.nextAudioStartTime>this.audioContext.currentTime+this.audioScheduleAheadTime)break}this.lastAudioScheduleTime=this.audioContext.currentTime}}setPlaybackSpeed(t){if(t<=0)throw new Error("Playback speed must be greater than 0");const e=this.getCurrentTime();this.startTime=performance.now()-e/t,this.playbackSpeed=t,this.playbackSpeed}seek(t){if(!this.isPlaying)return;const e=this.findNearestKeyFrame(t*1e3);this.videoBuffer=this.videoBuffer.filter(s=>s.timestamp>=e),this.audioBuffer=this.audioBuffer.filter(s=>s.timestamp>=e),this.audioQueue=[],this.audioQueueTimestamps=[],this.audioContext&&(this.nextAudioStartTime=this.audioContext.currentTime),this.timeOffset=t*1e3,this.startTime=performance.now()-t*1e3,this.seekTime=e}findNearestKeyFrame(t){for(let e=this.keyFrameList.length-1;e>=0;e--)if(this.keyFrameList[e]<=t)return this.keyFrameList[e];return this.keyFrameList[0]||0}start(){this.isPlaying||(this.isPlaying=!0,this.pausedAt!==null?(this.startTime=performance.now()-this.pausedAt,this.pausedAt=null):this.startTime=performance.now()-this.timeOffset,this.processNextFrame(),this.audioContext?this.audioContext.state==="suspended"&&this.audioContext.resume():this.initAudioContext(),this.scheduleAudioPlayback())}stop(){this.isPlaying&&(this.isPlaying=!1,this.pausedAt=this.getCurrentTime(),this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.audioContext&&this.audioContext.state==="running"&&this.audioContext.suspend())}getCurrentTime(){return this.pausedAt!==null?this.pausedAt:(performance.now()-this.startTime+this.timeOffset)*this.playbackSpeed}processInitialFrame(){if(this.videoBuffer.length>0){const t=this.videoBuffer.shift();t&&this.videoDecoder.decode(t)}}decodeVideo(t){if(this.videoBuffer.length>=this.maxBufferSize){console.warn("Video buffer full, dropping frame");return}t.type==="key"&&this.keyFrameList.push(t.timestamp),this.videoBuffer.push(t)}decodeAudio(t){if(this.audioBuffer.length>=this.maxBufferSize){console.warn("Audio buffer full, dropping frame");return}this.audioBuffer.push(t)}dispose(){this.stop(),this.videoBuffer=[],this.audioBuffer=[],this.audioQueue=[],this.audioQueueTimestamps=[],this.yuvRenderer&&(this.yuvRenderer.dispose(),this.yuvRenderer=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.gl=null,this.audioGain=null}}class vt extends H{constructor(t,e={debug:!1,autoPlay:!1}){super(),this.video=t,this.segments=[],this.totalDuration=0,this.position=0,this.debug=!1,this.autoPlay=!1,this.isPlaying=!1,this.pauseOB=ee(),this.seekOB=ee(),this.destroyOB=ee(),this.debug=e.debug,this.autoPlay=e.autoPlay,this.log("Engine initialized with options:",e);const s=new ft(t,{debug:this.debug});let i=Promise.resolve(!0),a=0;O(this.seekOB,at(n=>{this.log("Seek requested to time:",n),this.position=n;const l=this.currentSegment,o=n-l.virtualStartTime;return this.log("Offset in segment:",o),t.pause(),async r=>{try{if(await i,r.disposed||(await s.ready,r.disposed))return;const u=this.bufferStart,c=this.bufferEnd;this.log("Appending segment:",l);const f=await s.appendSegment(l);if(r.disposed)return;if(f){if(this.log("Segment appended successfully"),this.segments.filter(x=>x.ready&&x!=l).forEach(x=>{this.log("Unbuffering segment:",x),x.unBuffer()}),c>u&&(this.log("Removing buffer range:",u,"to",c),await s.removeBuffer(u,c),r.disposed))return;const g=o+c;a=n-g,this.log("New offset calculated:",a,"target:",g,"position:",n)}const h=n-a;this.log("Buffer:",`[${this.bufferStart},${this.bufferEnd}]`,"Target:",h),t.currentTime=h,this.log("Set video currentTime to:",t.currentTime),r.next(!0)}catch(u){r.error(u)}}}),lt(n=>(this.log(n,"downgrade"),this.softDecoder=new mt("",{yuvMode:!0}),this.video.srcObject=this.softDecoder.canvas.captureStream(),this.segments.forEach(l=>l.downgrade(this.softDecoder)),s.appendSegment(this.currentSegment).then(()=>{var l;(l=this.softDecoder)==null||l.processInitialFrame()}),O(z(t,"pause"),V(()=>{var l;(l=this.softDecoder)==null||l.stop()})),tt())),N(this.destroyOB),V(()=>{var n;this.isPlaying&&(this.log("Resuming playback"),t.play(),(n=this.softDecoder)==null||n.start())})),O(z(t,"timeupdate"),N(this.destroyOB),V(()=>{if(this.position=t.currentTime+a,!this.currentSegment)return;const n=this.segments[this.currentSegment.index+1];n&&!n.ready&&(this.log("Loading next segment:",n),i=s.appendSegment(n))})),O(z(t,"error"),N(this.destroyOB),V(()=>{const n=this.position;s.reset(),this.segments.forEach(l=>l.unBuffer()),a=0,this.seek(n+1)})),O(z(t,"waiting"),N(this.destroyOB),V(()=>{this.totalDuration-this.position<1&&(s.reset(),this.segments.forEach(n=>n.unBuffer()),a=0,this.pause(),this.seek(0))}))}log(...t){this.debug&&[...t]}get loadingProgress(){const t=this.segments.filter(e=>e.state==="loading").map(e=>e.loadingProgress).reduce((e,s)=>({loaded:e.loaded+s.loaded,total:e.total+s.total}),{loaded:0,total:0});return{...t,percent:t.total?t.loaded*100/t.total:0}}get currentSegment(){return this.segments.find(t=>t.virtualEndTime>this.position)}get bufferStart(){return this.video.buffered.length>0?this.video.buffered.start(0):0}get bufferEnd(){return this.video.buffered.length>0?this.video.buffered.end(this.video.buffered.length-1):0}set playbackRate(t){this.softDecoder?this.softDecoder.setPlaybackSpeed(t):this.video.playbackRate=t}get bufferedLength(){const t=this.currentSegment;if(!t)return 0;let e=0;for(let s=t.index;s<this.segments.length&&this.segments[s].state==="buffered";s++)e+=this.segments[s].duration;return e-(this.position-t.virtualStartTime)}async load(t){this.log("Loading URL:",t);let e;try{e=new URL(t)}catch{e=new URL(t,window.location.href)}switch(e.pathname.split(".").pop()){case"m3u8":this.log("Processing M3U8 playlist");const s=await fetch(e.toString()).then(a=>a.text()),i=gt(s,e.origin+e.pathname.split("/").slice(0,-1).join("/"));this.log("Playlist created:",i),this.segments=i.segments,this.totalDuration=i.totalDuration,O(et(...this.segments.map(a=>z(a,"progress"))),N(this.destroyOB),V(()=>{this.emit("progress",this.loadingProgress)})),this.autoPlay?(this.log("Auto-play enabled, starting playback"),this.play()):(this.log("Seeking to start position"),this.seek(0));break}}play(){this.log("Play requested"),this.isPlaying=!0,this.seekOB.next(this.position)}pause(){this.log("Pause requested"),this.isPlaying=!1,this.pauseOB.next(!0),this.video.pause()}seek(t){this.log("Seek requested to:",t),this.seekOB.next(t)}destroy(){this.log("Destroying engine"),this.video.src="",this.destroyOB.next(!0)}}const yt=["controls"],xt={key:0,class:"loading-overlay"},St={class:"loading-spinner"},wt={key:0,class:"loading-text"},Tt={class:"controls-container"},bt={class:"controls-left"},Bt={key:0,class:"icon-pause"},Ut={key:1,class:"icon-play"},kt={class:"time-display"},Et={class:"controls-right"},Ct={class:"playback-rate-control"},_t={key:0,class:"playback-rate-menu"},Dt=["onClick"],At={key:0,class:"icon-volume-mute"},Pt={key:1,class:"icon-volume-low"},Rt={key:2,class:"icon-volume-high"},Lt={key:0,class:"volume-slider-container"},It={key:0,class:"icon-fullscreen-exit"},Ft={key:1,class:"icon-fullscreen"},Mt=Re({__name:"VideoPlayer",props:{src:{},debug:{type:Boolean},autoPlay:{type:Boolean}},emits:["timeupdate","segments"],setup(d,{expose:t,emit:e}){const s=d,i=T(),a=T(),n=T(),l=T(),o=T(),r=T(0),u=T(!1),c=T(!1),f=T(1),h=T(),g=T(!1),x=T(0),p=T(0),E=T(!1),C=T(null),y=T(1),I=T(!1),D=T(!1),G=T(!1),Q=T(!1),X=T(!1),re=T(!1),q=T(!0),A=T(!1);t({value:i,seek:m=>{var v;(v=h.value)==null||v.seek(m),x.value=m}});const ne=e,me=ge(()=>ae(x.value)),ve=ge(()=>ae(p.value)),ye=[.5,1,1.5,2,3,4];function ae(m){const v=Math.floor(m/3600),w=Math.floor(m%3600/60),_=Math.floor(m%60);return v>0?`${v.toString().padStart(2,"0")}:${w.toString().padStart(2,"0")}:${_.toString().padStart(2,"0")}`:`${w.toString().padStart(2,"0")}:${_.toString().padStart(2,"0")}`}function oe(){a.value&&(q.value=a.value.offsetWidth>=400)}function le(){var w;if(!n.value||!l.value||!o.value||!h.value)return;x.value=h.value.position,p.value!==h.value.totalDuration&&(p.value=h.value.totalDuration);const m=h.value.position/p.value*100;l.value.style.width=`${m}%`;const v=(h.value.position+h.value.bufferedLength)/p.value*100;o.value.style.width=`${v}%`,ne("timeupdate",h.value.position),g.value=!((w=i.value)!=null&&w.paused)}function ue(m){if(!n.value||!h.value)return;const v=n.value.getBoundingClientRect(),_=(m.clientX-v.left)/v.width*p.value;h.value.seek(_),x.value=_}function xe(m){u.value=!0,Y(m),document.addEventListener("mousemove",Y),document.addEventListener("mouseup",ce)}function Y(m){if(!u.value||!n.value||!h.value)return;const v=n.value.getBoundingClientRect(),w=(m.clientX-v.left)/v.width,_=Math.max(0,Math.min(w*p.value,p.value));x.value=_;const P=_/p.value*100;l.value&&(l.value.style.width=`${P}%`)}function ce(m){u.value&&(ue(m),document.removeEventListener("mousemove",Y),document.removeEventListener("mouseup",ce),u.value=!1)}function Se(){c.value=!0}function we(){c.value=!1}function Te(m){i.value&&(f.value=m,h.value&&(h.value.playbackRate=m),D.value=!1)}function be(){D.value=!D.value}function de(){!i.value||!h.value||(h.value.isPlaying?h.value.pause():h.value.play())}function Be(){i.value&&(I.value=!I.value,i.value.muted=I.value)}function Ue(m){if(!i.value)return;const w=m.currentTarget.getBoundingClientRect();K(m.clientY,w)}function K(m,v){const w=v.height,_=1-Math.max(0,Math.min(1,(m-v.top)/w)),P=Math.max(0,Math.min(1,_));y.value=P,i.value&&(i.value.volume=P,I.value=P===0,i.value.muted=P===0)}function ke(m){m.preventDefault(),X.value=!0;const w=m.currentTarget.getBoundingClientRect();K(m.clientY,w);const _=Pe=>{X.value&&K(Pe.clientY,w)};document.addEventListener("mousemove",_);const P=()=>{X.value=!1,document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",P),setTimeout(()=>{document.querySelector(".volume-control:hover")||(G.value=!1)},500)};document.addEventListener("mouseup",P)}function Ee(){if(!h.value)return;const m=Math.min(h.value.position+10,p.value);h.value.seek(m),x.value=m}function Ce(){if(!h.value)return;const m=Math.max(h.value.position-10,0);h.value.seek(m),x.value=m}function he(){E.value=!0,C.value!==null&&(window.clearTimeout(C.value),C.value=null)}function _e(){u.value||(C.value=window.setTimeout(()=>{E.value=!1},2e3))}function De(){he()}function Ae(){a.value&&(document.fullscreenElement?document.exitFullscreen().then(()=>{Q.value=!1}).catch(m=>{console.error(`Error attempting to exit fullscreen: ${m.message}`)}):a.value.requestFullscreen().then(()=>{Q.value=!0}).catch(m=>{console.error(`Error attempting to enable fullscreen: ${m.message}`)}))}return Le(()=>i.value?s.src:null,m=>{if(h.value&&h.value.destroy(),!!m&&i.value){A.value=!0;const v=new vt(i.value,{debug:s.debug,autoPlay:s.debug});v.on("progress",w=>{r.value=w.percent}),h.value=v,x.value=0,p.value=0,v.load(m).then(()=>{p.value=v.totalDuration,ne("segments",v.segments),A.value=!1}).catch(w=>{console.error("Failed to load video:",w),A.value=!1})}}),Ie(()=>{i.value&&(i.value.addEventListener("timeupdate",le),i.value.addEventListener("play",()=>{g.value=!0,A.value=!1}),i.value.addEventListener("pause",()=>{var m;g.value=!1,(m=h.value)!=null&&m.isPlaying&&(A.value=!0)}),i.value.addEventListener("canplay",()=>{A.value=!1}),i.value.addEventListener("playing",()=>{A.value=!1}),i.value.addEventListener("error",m=>{console.error("Video error occurred:",m),A.value=!1}),i.value.volume=y.value,a.value&&(new ResizeObserver(()=>{oe()}).observe(a.value),oe()))}),Fe(()=>{h.value&&h.value.destroy(),i.value&&i.value.removeEventListener("timeupdate",le)}),(m,v)=>(U(),k("div",{class:"video-player",ref_key:"playerRef",ref:a,onMouseenter:he,onMouseleave:_e,onMousemove:De},[S("video",{ref_key:"video",ref:i,onClick:de,controls:re.value},null,8,yt),A.value?(U(),k("div",xt,[S("div",St,[v[2]||(v[2]=S("div",{class:"spinner"},null,-1)),v[3]||(v[3]=S("span",{class:"loading-text"},"加载中...",-1)),h.value?(U(),k("div",wt,W(r.value.toFixed(2))+"%",1)):F("",!0)])])):F("",!0),h.value&&!re.value?(U(),k("div",{key:1,class:j(["controls-overlay",{"show-controls":E.value||u.value}])},[S("div",{class:j(["timeline",{"timeline-hover":c.value}]),ref_key:"timelineRef",ref:n,onClick:ue,onMouseenter:Se,onMouseleave:we},[S("div",{class:"timeline-buffer",ref_key:"bufferRef",ref:o},null,512),S("div",{class:"timeline-progress",ref_key:"progressRef",ref:l},null,512),S("div",{class:j(["timeline-handle",{"timeline-handle-hover":c.value||u.value}]),style:Z({left:`${x.value/(p.value||1)*100}%`}),onMousedown:Me(xe,["stop"])},null,38)],34),S("div",Tt,[S("div",bt,[S("button",{class:"control-button",onClick:de},[g.value?(U(),k("i",Bt,"▮▮")):(U(),k("i",Ut,"▶"))]),q.value?(U(),k("button",{key:0,class:"control-button",onClick:Ce},v[4]||(v[4]=[S("i",{class:"icon-backward"},"◀◀",-1)]))):F("",!0),q.value?(U(),k("button",{key:1,class:"control-button",onClick:Ee},v[5]||(v[5]=[S("i",{class:"icon-forward"},"▶▶",-1)]))):F("",!0),S("div",kt,W(me.value)+" / "+W(ve.value),1)]),S("div",Et,[S("div",Ct,[S("button",{class:"control-button playback-rate-button",onClick:be},[S("span",null,W(f.value)+"x",1)]),D.value?(U(),k("div",_t,[(U(),k(Oe,null,Ve(ye,w=>S("button",{key:w,onClick:_=>Te(w),class:j([{active:f.value===w},"playback-rate-option"])},W(w)+"x ",11,Dt)),64))])):F("",!0)]),S("div",{class:"volume-control",onMouseenter:v[0]||(v[0]=w=>G.value=!0),onMouseleave:v[1]||(v[1]=()=>{X.value||(G.value=!1)})},[S("button",{class:"control-button",onClick:Be},[I.value||y.value===0?(U(),k("i",At)):y.value<.5?(U(),k("i",Pt)):(U(),k("i",Rt))]),G.value?(U(),k("div",Lt,[S("div",{class:"volume-slider",onClick:Ue,onMousedown:ke},[v[6]||(v[6]=S("div",{class:"volume-slider-track"},null,-1)),S("div",{class:"volume-slider-fill",style:Z({height:`${y.value*100}%`})},null,4),S("div",{class:"volume-slider-thumb",style:Z({bottom:`${y.value*100}%`})},null,4)],32)])):F("",!0)],32),S("button",{class:"control-button",onClick:Ae},[Q.value?(U(),k("i",It,"⤓")):(U(),k("i",Ft,"⤢"))])])])],2)):F("",!0)],544))}});const Wt=He(Mt,[["__scopeId","data-v-1f1506b1"]]);export{Wt as V};