@stinkycomputing/web-live-player 0.1.12 → 0.1.13
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.
|
@@ -11,6 +11,8 @@ export interface PlayerConfig {
|
|
|
11
11
|
/** Buffer delay in milliseconds (default: 100ms) */
|
|
12
12
|
bufferDelayMs?: number;
|
|
13
13
|
enableAudio?: boolean;
|
|
14
|
+
/** External AudioContext to use for audio playback. If provided, the player will not create or close it. */
|
|
15
|
+
audioContext?: AudioContext;
|
|
14
16
|
/** Video track name for MoQ streams (default: 'video'). Set to null to accept video from any track. */
|
|
15
17
|
videoTrackName?: string | null;
|
|
16
18
|
/** Audio track name for MoQ streams (default: 'audio'). Set to null to accept audio from any track. */
|
package/dist/web-live-player.cjs
CHANGED
|
@@ -148,7 +148,7 @@ class LiveAudioProcessor extends AudioWorkletProcessor {
|
|
|
148
148
|
}
|
|
149
149
|
|
|
150
150
|
registerProcessor('live-audio-processor', LiveAudioProcessor);
|
|
151
|
-
`;class LiveAudioPlayer{constructor(o,l={}){U(this,"ctx");U(this,"decoder",null);U(this,"workletNode",null);U(this,"gainNode");U(this,"initialized",!1);U(this,"targetSampleRate");U(this,"startTime",0);U(this,"bufferDelayMs");this.ctx=o,this.targetSampleRate=o.sampleRate,this.bufferDelayMs=l.bufferDelayMs??100,this.gainNode=this.ctx.createGain(),this.startTime=performance.now()*1e3}async init(o){if(this.ctx.audioWorklet===void 0)throw new Error("AudioWorklet not supported - need localhost or HTTPS");const l=this.buildDecoderConfig(o);if(!(await AudioDecoder.isConfigSupported(l)).supported)throw new Error(`Audio codec not supported: ${l.codec}`);this.decoder=new AudioDecoder({output:e=>this.handleDecodedFrame(e),error:e=>{console.error("LiveAudioPlayer decoder error:",e)}}),this.decoder.configure(l);const r=new Blob([LIVE_WORKLET_CODE],{type:"application/javascript"}),t=URL.createObjectURL(r);try{await this.ctx.audioWorklet.addModule(t)}finally{URL.revokeObjectURL(t)}this.workletNode=new AudioWorkletNode(this.ctx,"live-audio-processor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2],processorOptions:{sampleRate:this.ctx.sampleRate}}),this.workletNode.connect(this.gainNode).connect(this.ctx.destination),this.workletNode.port.postMessage({type:"setBufferTarget",targetMs:this.bufferDelayMs}),this.workletNode.port.postMessage({type:"setSampleRate",sampleRate:this.ctx.sampleRate}),this.initialized=!0}buildDecoderConfig(o){const l=(o==null?void 0:o.codecType)??CodecType.CODEC_TYPE_AUDIO_OPUS,n=(o==null?void 0:o.sampleRate)||48e3,r=(o==null?void 0:o.channels)||2;switch(l){case CodecType.CODEC_TYPE_AUDIO_OPUS:return{codec:"opus",sampleRate:48e3,numberOfChannels:r};case CodecType.CODEC_TYPE_AUDIO_AAC:return{codec:"mp4a.40.2",sampleRate:n,numberOfChannels:r};case CodecType.CODEC_TYPE_AUDIO_PCM:throw new Error("PCM audio not yet supported");default:return{codec:"opus",sampleRate:48e3,numberOfChannels:2}}}handleDecodedFrame(o){if(!this.workletNode){o.close();return}try{const l=o.numberOfFrames;let n=1;try{o.numberOfChannels>1&&(o.allocationSize({planeIndex:1,frameOffset:0,frameCount:1}),n=o.numberOfChannels)}catch{n=1}const r=new Float32Array(l),t=new Float32Array(l);if(n===1){const s=o.allocationSize({planeIndex:0,frameOffset:0,frameCount:o.numberOfFrames}),d=new ArrayBuffer(s);o.copyTo(d,{planeIndex:0,frameOffset:0,frameCount:o.numberOfFrames});const c=new Float32Array(d);if(o.numberOfChannels===1)r.set(c),t.set(c);else for(let F=0;F<l;F++)r[F]=c[F*2],t[F]=c[F*2+1]}else{const s=new ArrayBuffer(o.allocationSize({planeIndex:0,frameOffset:0,frameCount:o.numberOfFrames}));if(o.copyTo(s,{planeIndex:0,frameOffset:0,frameCount:o.numberOfFrames}),r.set(new Float32Array(s)),o.numberOfChannels>1){const d=new ArrayBuffer(o.allocationSize({planeIndex:1,frameOffset:0,frameCount:o.numberOfFrames}));o.copyTo(d,{planeIndex:1,frameOffset:0,frameCount:o.numberOfFrames}),t.set(new Float32Array(d))}else t.set(r)}const e=this.resampleAudio(r,o.sampleRate,this.targetSampleRate),i=this.resampleAudio(t,o.sampleRate,this.targetSampleRate),a=o.timestamp??performance.now()*1e3-this.startTime;this.workletNode.port.postMessage({type:"audioData",data:{left:e.buffer,right:i.buffer},timestamp:a},[e.buffer,i.buffer]),o.close()}catch(l){console.error("Error processing live audio frame:",l),o.close()}}resampleAudio(o,l,n){if(l===n)return o;const r=l/n,t=Math.floor(o.length/r),e=new Float32Array(t);for(let i=0;i<t;i++){const a=i*r,s=Math.floor(a),d=Math.min(s+1,o.length-1),c=a-s;e[i]=o[s]*(1-c)+o[d]*c}return e}decode(o,l){if(!(!this.initialized||!this.decoder||this.decoder.state!=="configured")&&!(o.length<1))try{let n;l!=null?isLong(l)?n=l.toNumber():n=Number(l):n=performance.now()*1e3-this.startTime;const r=new EncodedAudioChunk({type:"key",timestamp:Math.max(0,n),data:o});this.decoder.decode(r)}catch(n){console.error("Error decoding live audio:",n)}}setBufferDelay(o){var l;this.bufferDelayMs=o,(l=this.workletNode)==null||l.port.postMessage({type:"setBufferTarget",targetMs:o})}start(){var o;(o=this.workletNode)==null||o.port.postMessage({type:"start"}),this.ctx.resume()}stop(){var o;(o=this.workletNode)==null||o.port.postMessage({type:"stop"})}clear(){var o;(o=this.workletNode)==null||o.port.postMessage({type:"clear"}),this.resetTiming()}resetTiming(){this.startTime=performance.now()*1e3}setVolume(o){this.gainNode.gain.value=Math.max(0,Math.min(1,o))}dispose(){if(this.initialized=!1,this.decoder){try{this.decoder.state==="configured"&&this.decoder.reset(),this.decoder.state!=="closed"&&this.decoder.close()}catch{}this.decoder=null}if(this.workletNode){try{this.workletNode.disconnect()}catch{}this.workletNode=null}if(this.gainNode)try{this.gainNode.disconnect()}catch{}}}function createPlayer(u={}){return new LiveVideoPlayer(u)}const Ko=class Ko extends BasePlayer{constructor(l={}){super("idle",l.debugLogging??!1);U(this,"config");U(this,"streamSource",null);U(this,"trackFilter",null);U(this,"boundDataHandler",null);U(this,"decoder",null);U(this,"currentCodecData");U(this,"useWasmDecoder",!1);U(this,"waitingForKeyframe",!0);U(this,"lastWaitingForKeyframeLog",0);U(this,"lastKeyframeRequest",0);U(this,"statusLogCounter",0);U(this,"isConfiguring",!1);U(this,"pendingDuringConfig",[]);U(this,"frameScheduler");U(this,"lastVideoFrame",null);U(this,"consecutiveDrops",0);U(this,"totalDrops",0);U(this,"lastDropLogTime",0);U(this,"streamWidth",0);U(this,"streamHeight",0);U(this,"estimatedFrameRate",30);U(this,"lastVideoTimestampUs",-1);U(this,"fpsEstimateSamples",[]);U(this,"audioContext",null);U(this,"audioPlayer",null);U(this,"ownsAudioContext",!1);U(this,"audioCodecData",null);U(this,"arrivalTimes",new Map);U(this,"keyframeStatus",new Map);U(this,"videoBytesReceived",0);U(this,"audioBytesReceived",0);U(this,"lastBandwidthUpdateTime",0);U(this,"lastVideoBytesReceived",0);U(this,"lastAudioBytesReceived",0);U(this,"currentBandwidth",{videoBytesPerSecond:0,audioBytesPerSecond:0,totalBytesPerSecond:0});this.config={preferredDecoder:l.preferredDecoder??"webcodecs-sw",bufferDelayMs:l.bufferDelayMs??100,enableAudio:l.enableAudio??!0,videoTrackName:l.videoTrackName===void 0?"video":l.videoTrackName,audioTrackName:l.audioTrackName===void 0?"audio":l.audioTrackName,debugLogging:l.debugLogging??!1},this.config.enableAudio&&(this.audioContext=new AudioContext,this.ownsAudioContext=!0),this.frameScheduler=new FrameScheduler({bufferDelayMs:this.config.bufferDelayMs,logger:n=>{this.config.debugLogging&&this.logger.info(n)},onFrameDropped:(n,r)=>{if(this.totalDrops++,this.consecutiveDrops++,this.config.debugLogging){const t=Date.now();(t-this.lastDropLogTime>500||this.consecutiveDrops===1)&&(this.consecutiveDrops>1?this.logger.warn(`Dropped ${this.consecutiveDrops} frames (${r}), total=${this.totalDrops}`):this.logger.warn(`Frame dropped (${r}), total=${this.totalDrops}`),this.lastDropLogTime=t,this.consecutiveDrops=0)}n.close()}})}setDebugLogging(l){this.config.debugLogging=l,super.setDebugLogging(l)}setVolume(l){this.audioPlayer&&this.audioPlayer.setVolume(l)}getVolume(){return 1}setStreamSource(l){this.streamSource&&this.boundDataHandler&&this.streamSource.off("data",this.boundDataHandler),this.streamSource=l,this.boundDataHandler=this.handleStreamData.bind(this),this.streamSource.on("data",this.boundDataHandler),this.logger.info("Stream source connected")}setTrackFilter(l){this.trackFilter=l,this.logger.info(`Track filter set: ${l}`)}connectToMoQSession(l,n){this.setStreamSource(l),n&&this.setTrackFilter(n)}async connectToMoQRelay(l,n,r){const{createMoQSource:t}=await Promise.resolve().then(()=>moqSource),e=(r==null?void 0:r.videoTrack)??this.config.videoTrackName??"video",i=(r==null?void 0:r.audioTrack)===!1?null:(r==null?void 0:r.audioTrack)??this.config.audioTrackName??"audio",a=[{trackName:e,streamType:"video",priority:0}];i&&this.config.enableAudio&&a.push({trackName:i,streamType:"audio",priority:0}),this.logger.info(`MoQ subscriptions: ${JSON.stringify(a)}`);const s=t({relayUrl:l,namespace:n,subscriptions:a});this.setStreamSource(s),await s.connect()}play(){this._state!=="error"&&(this.setState("playing"),this.logger.info("Playback started"))}pause(){this._state==="playing"&&(this.setState("paused"),this.logger.info("Playback paused"))}getVideoFrame(l){if(this._state!=="playing")return this.config.debugLogging&&this.logger.debug(`getVideoFrame: state=${this._state}, returning lastFrame=${!!this.lastVideoFrame}`),this.lastVideoFrame;this.config.debugLogging&&(this.statusLogCounter++,this.statusLogCounter>=300&&(this.frameScheduler.logStatus(),this.statusLogCounter=0));const n=this.frameScheduler.dequeue(l);return n&&(this.consecutiveDrops=0,this.lastVideoFrame&&this.lastVideoFrame!==n&&this.lastVideoFrame.close(),this.lastVideoFrame=n),this.lastVideoFrame}setBufferDelay(l){var n;this.config.bufferDelayMs=l,this.frameScheduler.setBufferDelay(l),(n=this.audioPlayer)==null||n.setBufferDelay(l)}getBufferDelay(){return this.frameScheduler.getBufferDelay()}setPreferredDecoder(l){var e,i,a,s;const n=this.config.preferredDecoder;this.config.preferredDecoder=l,n==="wasm"!==(l==="wasm")&&this.decoder?(this.logger.info(`Decoder type changed from ${n} to ${l}, switching decoder...`),this.decoder.dispose(),this.decoder=null,this.frameScheduler.clear(),this.lastVideoFrame&&(this.lastVideoFrame.close(),this.lastVideoFrame=null),this.waitingForKeyframe=!0,this.currentCodecData=void 0,(i=(e=this.streamSource)==null?void 0:e.requestKeyframe)==null||i.call(e),this.logger.info("Keyframe requested for decoder switch")):n!==l&&this.decoder&&(this.logger.info(`Decoder preference changed from ${n} to ${l}`),this.waitingForKeyframe=!0,this.currentCodecData=void 0,this.decoder.dispose(),this.decoder=null,this.frameScheduler.clear(),(s=(a=this.streamSource)==null?void 0:a.requestKeyframe)==null||s.call(a))}flush(){var l,n,r;this.logger.info("Flushing player pipeline"),this.waitingForKeyframe=!0,(l=this.decoder)==null||l.flushSync(),this.frameScheduler.clear(),this.lastVideoFrame&&(this.lastVideoFrame.close(),this.lastVideoFrame=null),(r=(n=this.streamSource)==null?void 0:n.requestKeyframe)==null||r.call(n)}getStats(){var n;const l=this.frameScheduler.getStatus();return this.updateBandwidthStats(),{bufferSize:l.currentBufferSize,bufferMs:l.currentBufferMs,avgBufferMs:l.avgBufferMs,targetBufferMs:l.targetBufferMs,droppedFrames:l.droppedFrames,totalFrames:l.totalEnqueuedFrames,decoderState:((n=this.decoder)==null?void 0:n.state)??"none",streamWidth:this.streamWidth,streamHeight:this.streamHeight,frameRate:this.estimatedFrameRate,latency:l.latency,bandwidth:this.currentBandwidth}}updateBandwidthStats(){const l=performance.now(),n=l-this.lastBandwidthUpdateTime;if(n<500)return;const r=n/1e3,t=this.videoBytesReceived-this.lastVideoBytesReceived,e=this.audioBytesReceived-this.lastAudioBytesReceived;this.currentBandwidth={videoBytesPerSecond:t/r,audioBytesPerSecond:e/r,totalBytesPerSecond:(t+e)/r},this.lastBandwidthUpdateTime=l,this.lastVideoBytesReceived=this.videoBytesReceived,this.lastAudioBytesReceived=this.audioBytesReceived}getPacketTimingHistory(){return this.frameScheduler.getPacketTimingHistory()}on(l,n){super.on(l,n)}off(l,n){super.off(l,n)}async handleStreamData(l){var a,s,d,c,F,B,S,y,E,v,N,T,C,m,Q,p,f;const n=l.data;if(!n.valid||!n.header)return;const r=((a=n.payload)==null?void 0:a.byteLength)||0;if(n.header.type===FrameType.FRAME_TYPE_AUDIO||l.streamType==="audio"){this.audioBytesReceived+=r;const h=this.config.audioTrackName;if(h!=null&&l.trackName!==h&&l.streamType!=="audio")return;await this.handleAudioData(n);return}this.videoBytesReceived+=r;const e=this.trackFilter??this.config.videoTrackName;if(e!=null&&l.trackName!==e||l.streamType!=="video"||!((s=n.header.media)!=null&&s.codecData))return;const i=!!((d=n.header.media)!=null&&d.keyframe);if(codecDataChanged(this.currentCodecData,(c=n.header.media)==null?void 0:c.codecData)){if(!i){this.logger.debug("Waiting for keyframe (codec change)");return}this.currentCodecData=(F=n.header.media)==null?void 0:F.codecData,this.isConfiguring=!0,this.pendingDuringConfig=[n],await this.configureDecoder((B=n.header.media)==null?void 0:B.codecData),this.isConfiguring=!1,this.waitingForKeyframe=!0;const h=this.pendingDuringConfig;this.pendingDuringConfig=[],this.logger.info(`Processing ${h.length} frames queued during configuration`);for(const R of h)await this.handleStreamData({trackName:l.trackName,streamType:l.streamType,data:R});return}if(this.isConfiguring){this.logger.debug(`Queueing frame pts=${(S=n.header.media)==null?void 0:S.pts} during configuration`),this.pendingDuringConfig.push(n);return}if(!this.decoder||this.decoder.state!=="configured"){this.logger.warn(`Dropping frame pts=${(y=n.header.media)==null?void 0:y.pts}: decoder not ready (state=${((E=this.decoder)==null?void 0:E.state)??"null"})`);return}if(this.waitingForKeyframe){if(!i){this.logger.debug(`Dropping frame pts=${(v=n.header.media)==null?void 0:v.pts}: waiting for keyframe`);const h=Date.now();(!this.lastWaitingForKeyframeLog||h-this.lastWaitingForKeyframeLog>1e3)&&(this.logger.info("Waiting for keyframe to resume playback..."),this.lastWaitingForKeyframeLog=h,(!this.lastKeyframeRequest||h-this.lastKeyframeRequest>1e3)&&(this.logger.info("Requesting keyframe..."),(T=(N=this.streamSource)==null?void 0:N.requestKeyframe)==null||T.call(N),this.lastKeyframeRequest=h));return}this.logger.debug("Keyframe received, resuming decode"),this.waitingForKeyframe=!1,this.lastWaitingForKeyframeLog=0}try{const h=performance.now(),R=(m=(C=n.header.media)==null?void 0:C.codecData)!=null&&m.timebaseDen&&((p=(Q=n.header.media)==null?void 0:Q.codecData)!=null&&p.timebaseNum)?{num:n.header.media.codecData.timebaseNum,den:n.header.media.codecData.timebaseDen}:{num:1,den:1e6},J={num:1,den:1e6},V=rescaleTime(((f=n.header.media)==null?void 0:f.pts)??0,R,J);if(this.arrivalTimes.set(V,h),this.keyframeStatus.set(V,i),this.lastVideoTimestampUs>=0&&V>this.lastVideoTimestampUs){const W=V-this.lastVideoTimestampUs;if(W>5e3&&W<1e6&&(this.fpsEstimateSamples.push(W),this.fpsEstimateSamples.length>Ko.FPS_SAMPLE_COUNT&&this.fpsEstimateSamples.shift(),this.fpsEstimateSamples.length>=3)){const b=this.fpsEstimateSamples.reduce((g,Z)=>g+Z,0)/this.fpsEstimateSamples.length;this.estimatedFrameRate=Math.round(1e6/b)}}if(this.lastVideoTimestampUs=V,this.arrivalTimes.size>100){const W=[...this.arrivalTimes.entries()];for(let b=0;b<W.length-100;b++)this.arrivalTimes.delete(W[b][0]),this.keyframeStatus.delete(W[b][0])}this.decoder.decodeBinary(n)}catch(h){this.logger.error(`Decode error: ${h}`)}}async handleAudioData(l){var r,t,e,i,a,s,d,c,F,B;if(!this.config.enableAudio)return;const n=this.audioCodecData??void 0;(t=(r=l.header)==null?void 0:r.media)!=null&&t.codecData&&codecDataChanged(n,l.header.media.codecData)&&(this.audioCodecData=l.header.media.codecData,this.audioPlayer&&(this.audioPlayer.dispose(),this.audioPlayer=null),this.audioContext||(this.audioContext=new AudioContext,this.ownsAudioContext=!0),this.audioPlayer=new LiveAudioPlayer(this.audioContext,{bufferDelayMs:this.config.bufferDelayMs??100}),await this.audioPlayer.init((e=l.header.media)==null?void 0:e.codecData),this.audioPlayer.start(),this.logger.info(`Audio player started: ${(a=(i=l.header.media)==null?void 0:i.codecData)==null?void 0:a.codecType}, ${(d=(s=l.header.media)==null?void 0:s.codecData)==null?void 0:d.sampleRate}Hz, ${(F=(c=l.header.media)==null?void 0:c.codecData)==null?void 0:F.channels}ch`)),this.audioPlayer&&l.payload&&l.header&&this.audioPlayer.decode(l.payload,(B=l.header.media)==null?void 0:B.pts)}async configureDecoder(l){this.useWasmDecoder=this.config.preferredDecoder==="wasm",(!this.decoder||this.useWasmDecoder&&this.decoder instanceof WebCodecsDecoder||!this.useWasmDecoder&&this.decoder instanceof WasmDecoder)&&(this.decoder&&this.decoder.dispose(),this.useWasmDecoder?(this.logger.info("Using WASM decoder"),this.decoder=new WasmDecoder({onFrameDecoded:r=>this.handleDecodedYUVFrame(r),onError:r=>this.handleDecoderError(r),onQueueOverflow:r=>this.handleQueueOverflow(r),maxQueueSize:10})):(this.logger.info(`Using WebCodecs decoder (${this.config.preferredDecoder})`),this.decoder=new WebCodecsDecoder({logger:this.logger,onFrameDecoded:r=>this.handleDecodedFrame(r),onError:r=>this.handleDecoderError(r),onQueueOverflow:r=>this.handleQueueOverflow(r),maxQueueSize:10})));const n=this.config.preferredDecoder==="webcodecs-hw";try{this.useWasmDecoder?await this.decoder.configure(l):await this.decoder.configure(l,n),this.streamWidth=l.width||0,this.streamHeight=l.height||0,this.lastVideoTimestampUs=-1,this.fpsEstimateSamples=[],this.estimatedFrameRate=30,this.emit("metadata",{width:l.width,height:l.height,codec:this.getCodecName(l.codecType||sesame.v1.common.CodecType.CODEC_TYPE_VIDEO_AVC)})}catch(r){this.logger.error(`Failed to configure decoder: ${r}`),this.setState("error"),this.emit("error",r instanceof Error?r:new Error(String(r)))}}getCodecName(l){switch(l){case sesame.v1.common.CodecType.CODEC_TYPE_VIDEO_AVC:return"H.264";case sesame.v1.common.CodecType.CODEC_TYPE_VIDEO_HEVC:return"HEVC";case sesame.v1.common.CodecType.CODEC_TYPE_VIDEO_AV1:return"AV1";default:return"Unknown"}}handleDecodedFrame(l){const n=performance.now(),r=this.arrivalTimes.get(l.timestamp)??n,t=this.keyframeStatus.get(l.timestamp)??!1,e={arrivalTime:r,decodeTime:n};this.frameScheduler.enqueue(l,l.timestamp,e,t),this.emit("frame",l)}handleDecodedYUVFrame(l){const n=performance.now(),r=this.arrivalTimes.get(l.timestamp)??n,t=this.keyframeStatus.get(l.timestamp)??!1,e=this.convertYUVToVideoFrame(l,this.streamWidth,this.streamHeight);if(e){const i={arrivalTime:r,decodeTime:n};this.frameScheduler.enqueue(e,l.timestamp,i,t),this.emit("frame",e)}}convertYUVToVideoFrame(l,n,r){try{const{y:t,u:e,v:i,width:a,height:s,chromaStride:d,chromaHeight:c}=l,F=n>0?n:a,B=r>0?r:s,y=a*s,E=d*c,v=y+E*2,N=new Uint8Array(v);N.set(t.subarray(0,y),0);const T=a/2,C=y;if(d===T)N.set(e.subarray(0,E),C);else for(let Q=0;Q<c;Q++)N.set(e.subarray(Q*d,Q*d+T),C+Q*T);const m=C+T*c;if(d===T)N.set(i.subarray(0,E),m);else for(let Q=0;Q<c;Q++)N.set(i.subarray(Q*d,Q*d+T),m+Q*T);return new VideoFrame(N,{format:"I420",codedWidth:a,codedHeight:s,visibleRect:{x:0,y:0,width:F,height:B},timestamp:l.timestamp,duration:this.estimatedFrameRate>0?1e6/this.estimatedFrameRate:33333})}catch(t){return this.logger.error(`YUV conversion error: ${t}`),null}}handleDecoderError(l){this.logger.error(`Decoder error: ${l.message}`),this.emit("error",l)}handleQueueOverflow(l){this.logger.warn(`Decoder queue overflow: ${l} frames, flushing...`),this.flush()}dispose(){this.streamSource&&this.boundDataHandler&&this.streamSource.off("data",this.boundDataHandler),this.streamSource=null,this.boundDataHandler=null,this.decoder&&(this.decoder.dispose(),this.decoder=null),this.audioPlayer&&(this.audioPlayer.dispose(),this.audioPlayer=null),this.ownsAudioContext&&this.audioContext&&this.audioContext.close(),this.audioContext=null,this.audioCodecData=null,this.frameScheduler.clear(),this.lastVideoFrame&&(this.lastVideoFrame.close(),this.lastVideoFrame=null),this.arrivalTimes.clear(),this.currentCodecData=void 0,this.waitingForKeyframe=!0,this.totalDrops=0,this.consecutiveDrops=0,this.clearEventHandlers(),this.setState("idle"),this.logger.info("Player disposed")}};U(Ko,"FPS_SAMPLE_COUNT",10);let LiveVideoPlayer=Ko;var __defProp=Object.defineProperty,__export=(u,o)=>{for(var l in o)__defProp(u,l,{get:o[l],enumerable:!0})},MAX_SIZE=Math.pow(2,32),MAX_UINT32=Math.pow(2,32)-1,TKHD_FLAG_ENABLED=1,TKHD_FLAG_IN_MOVIE=2,TKHD_FLAG_IN_PREVIEW=4,TFHD_FLAG_BASE_DATA_OFFSET=1,TFHD_FLAG_SAMPLE_DESC=2,TFHD_FLAG_SAMPLE_DUR=8,TFHD_FLAG_SAMPLE_SIZE=16,TFHD_FLAG_SAMPLE_FLAGS=32,TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,TRUN_FLAGS_DATA_OFFSET=1,TRUN_FLAGS_FIRST_FLAG=4,TRUN_FLAGS_DURATION=256,TRUN_FLAGS_SIZE=512,TRUN_FLAGS_FLAGS=1024,TRUN_FLAGS_CTS_OFFSET=2048,ERR_INVALID_DATA=-1,ERR_NOT_ENOUGH_DATA=0,OK=1,MP4BoxBuffer=class cr extends ArrayBuffer{constructor(o){super(o),this.fileStart=0,this.usedBytes=0}static fromArrayBuffer(o,l){const n=new cr(o.byteLength);return new Uint8Array(n).set(new Uint8Array(o)),n.fileStart=l,n}},P,ar,k,DataStream=(k=class{constructor(o,l,n){rr(this,P);this._byteLength=0,this.failurePosition=0,this._dynamicSize=1,this._byteOffset=l||0,o instanceof ArrayBuffer?this.buffer=MP4BoxBuffer.fromArrayBuffer(o,0):o instanceof DataView?(this.dataView=o,l&&(this._byteOffset+=l)):this.buffer=new MP4BoxBuffer(o||0),this.position=0,this.endianness=n||1}getPosition(){return this.position}_realloc(o){if(!this._dynamicSize)return;const l=this._byteOffset+this.position+o;let n=this._buffer.byteLength;if(l<=n){l>this._byteLength&&(this._byteLength=l);return}for(n<1&&(n=1);l>n;)n*=2;const r=new MP4BoxBuffer(n),t=new Uint8Array(this._buffer);new Uint8Array(r,0,t.length).set(t),this.buffer=r,this._byteLength=l}_trimAlloc(){if(this._byteLength===this._buffer.byteLength)return;const o=new MP4BoxBuffer(this._byteLength),l=new Uint8Array(o),n=new Uint8Array(this._buffer,0,l.length);l.set(n),this.buffer=o}get byteLength(){return this._byteLength-this._byteOffset}get buffer(){return this._trimAlloc(),this._buffer}set buffer(o){this._buffer=o,this._dataView=new DataView(o,this._byteOffset),this._byteLength=o.byteLength}get byteOffset(){return this._byteOffset}set byteOffset(o){this._byteOffset=o,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}get dataView(){return this._dataView}set dataView(o){this._byteOffset=o.byteOffset,this._buffer=MP4BoxBuffer.fromArrayBuffer(o.buffer,0),this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+o.byteLength}seek(o){const l=Math.max(0,Math.min(this.byteLength,o));this.position=isNaN(l)||!isFinite(l)?0:l}isEof(){return this.position>=this._byteLength}mapUint8Array(o){this._realloc(o*1);const l=new Uint8Array(this._buffer,this.byteOffset+this.position,o);return this.position+=o*1,l}readInt32Array(o,l){o=o===void 0?this.byteLength-this.position/4:o;const n=new Int32Array(o);return k.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,o*n.BYTES_PER_ELEMENT),k.arrayToNative(n,l??this.endianness),this.position+=n.byteLength,n}readInt16Array(o,l){o=o===void 0?this.byteLength-this.position/2:o;const n=new Int16Array(o);return k.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,o*n.BYTES_PER_ELEMENT),k.arrayToNative(n,l??this.endianness),this.position+=n.byteLength,n}readInt8Array(o){o=o===void 0?this.byteLength-this.position:o;const l=new Int8Array(o);return k.memcpy(l.buffer,0,this.buffer,this.byteOffset+this.position,o*l.BYTES_PER_ELEMENT),this.position+=l.byteLength,l}readUint32Array(o,l){o=o===void 0?this.byteLength-this.position/4:o;const n=new Uint32Array(o);return k.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,o*n.BYTES_PER_ELEMENT),k.arrayToNative(n,l??this.endianness),this.position+=n.byteLength,n}readUint16Array(o,l){o=o===void 0?this.byteLength-this.position/2:o;const n=new Uint16Array(o);return k.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,o*n.BYTES_PER_ELEMENT),k.arrayToNative(n,l??this.endianness),this.position+=n.byteLength,n}readUint8Array(o){o=o===void 0?this.byteLength-this.position:o;const l=new Uint8Array(o);return k.memcpy(l.buffer,0,this.buffer,this.byteOffset+this.position,o*l.BYTES_PER_ELEMENT),this.position+=l.byteLength,l}readFloat64Array(o,l){o=o===void 0?this.byteLength-this.position/8:o;const n=new Float64Array(o);return k.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,o*n.BYTES_PER_ELEMENT),k.arrayToNative(n,l??this.endianness),this.position+=n.byteLength,n}readFloat32Array(o,l){o=o===void 0?this.byteLength-this.position/4:o;const n=new Float32Array(o);return k.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,o*n.BYTES_PER_ELEMENT),k.arrayToNative(n,l??this.endianness),this.position+=n.byteLength,n}readInt32(o){const l=this._dataView.getInt32(this.position,(o??this.endianness)===2);return this.position+=4,l}readInt16(o){const l=this._dataView.getInt16(this.position,(o??this.endianness)===2);return this.position+=2,l}readInt8(){const o=this._dataView.getInt8(this.position);return this.position+=1,o}readUint32(o){const l=this._dataView.getUint32(this.position,(o??this.endianness)===2);return this.position+=4,l}readUint16(o){const l=this._dataView.getUint16(this.position,(o??this.endianness)===2);return this.position+=2,l}readUint8(){const o=this._dataView.getUint8(this.position);return this.position+=1,o}readFloat32(o){const l=this._dataView.getFloat32(this.position,(o??this.endianness)===2);return this.position+=4,l}readFloat64(o){const l=this._dataView.getFloat64(this.position,(o??this.endianness)===2);return this.position+=8,l}static memcpy(o,l,n,r,t){const e=new Uint8Array(o,l,t),i=new Uint8Array(n,r,t);e.set(i)}static arrayToNative(o,l){return l===k.ENDIANNESS?o:this.flipArrayEndianness(o)}static nativeToEndian(o,l){return l&&k.ENDIANNESS===2?o:this.flipArrayEndianness(o)}static flipArrayEndianness(o){const l=new Uint8Array(o.buffer,o.byteOffset,o.byteLength);for(let n=0;n<o.byteLength;n+=o.BYTES_PER_ELEMENT)for(let r=n+o.BYTES_PER_ELEMENT-1,t=n;r>t;r--,t++){const e=l[t];l[t]=l[r],l[r]=e}return o}readString(o,l){return l===void 0||l==="ASCII"?fromCharCodeUint8(this.mapUint8Array(o===void 0?this.byteLength-this.position:o)):new TextDecoder(l).decode(this.mapUint8Array(o))}readCString(o){let l=0;const n=this.byteLength-this.position,r=new Uint8Array(this._buffer,this._byteOffset+this.position),t=o!==void 0?Math.min(o,n):n;for(;l<t&&r[l]!==0;l++);const e=fromCharCodeUint8(this.mapUint8Array(l));return o!==void 0?this.position+=t-l:l!==n&&(this.position+=1),e}readInt64(){return this.readInt32()*MAX_SIZE+this.readUint32()}readUint64(){return this.readUint32()*MAX_SIZE+this.readUint32()}readUint24(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()}save(o){const l=new Blob([this.buffer]);if(typeof window<"u"&&typeof document<"u")if(window.URL&&URL.createObjectURL){const n=window.URL.createObjectURL(l),r=document.createElement("a");document.body.appendChild(r),r.setAttribute("href",n),r.setAttribute("download",o),r.setAttribute("target","_self"),r.click(),window.URL.revokeObjectURL(n),document.body.removeChild(r)}else throw new Error("DataStream.save: Can't create object URL.");return l}get dynamicSize(){return this._dynamicSize}set dynamicSize(o){o||this._trimAlloc(),this._dynamicSize=o}shift(o){const l=new MP4BoxBuffer(this._byteLength-o),n=new Uint8Array(l),r=new Uint8Array(this._buffer,o,n.length);n.set(r),this.buffer=l,this.position-=o}writeInt32Array(o,l){if(this._realloc(o.length*4),o instanceof Int32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt32Array(o.length,l);else for(let n=0;n<o.length;n++)this.writeInt32(o[n],l)}writeInt16Array(o,l){if(this._realloc(o.length*2),o instanceof Int16Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt16Array(o.length,l);else for(let n=0;n<o.length;n++)this.writeInt16(o[n],l)}writeInt8Array(o){if(this._realloc(o.length*1),o instanceof Int8Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt8Array(o.length);else for(let l=0;l<o.length;l++)this.writeInt8(o[l])}writeUint32Array(o,l){if(this._realloc(o.length*4),o instanceof Uint32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint32Array(o.length,l);else for(let n=0;n<o.length;n++)this.writeUint32(o[n],l)}writeUint16Array(o,l){if(this._realloc(o.length*2),o instanceof Uint16Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint16Array(o.length,l);else for(let n=0;n<o.length;n++)this.writeUint16(o[n],l)}writeUint8Array(o){if(this._realloc(o.length*1),o instanceof Uint8Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint8Array(o.length);else for(let l=0;l<o.length;l++)this.writeUint8(o[l])}writeFloat64Array(o,l){if(this._realloc(o.length*8),o instanceof Float64Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapFloat64Array(o.length,l);else for(let n=0;n<o.length;n++)this.writeFloat64(o[n],l)}writeFloat32Array(o,l){if(this._realloc(o.length*4),o instanceof Float32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapFloat32Array(o.length,l);else for(let n=0;n<o.length;n++)this.writeFloat32(o[n],l)}writeInt64(o,l){this._realloc(8),this._dataView.setBigInt64(this.position,BigInt(o),(l??this.endianness)===2),this.position+=8}writeInt32(o,l){this._realloc(4),this._dataView.setInt32(this.position,o,(l??this.endianness)===2),this.position+=4}writeInt16(o,l){this._realloc(2),this._dataView.setInt16(this.position,o,(l??this.endianness)===2),this.position+=2}writeInt8(o){this._realloc(1),this._dataView.setInt8(this.position,o),this.position+=1}writeUint32(o,l){this._realloc(4),this._dataView.setUint32(this.position,o,(l??this.endianness)===2),this.position+=4}writeUint16(o,l){this._realloc(2),this._dataView.setUint16(this.position,o,(l??this.endianness)===2),this.position+=2}writeUint8(o){this._realloc(1),this._dataView.setUint8(this.position,o),this.position+=1}writeFloat32(o,l){this._realloc(4),this._dataView.setFloat32(this.position,o,(l??this.endianness)===2),this.position+=4}writeFloat64(o,l){this._realloc(8),this._dataView.setFloat64(this.position,o,(l??this.endianness)===2),this.position+=8}writeUCS2String(o,l,n){n===void 0&&(n=o.length);let r;for(r=0;r<o.length&&r<n;r++)this.writeUint16(o.charCodeAt(r),l);for(;r<n;r++)this.writeUint16(0)}writeString(o,l,n){let r=0;if(l===void 0||l==="ASCII")if(n!==void 0){const t=Math.min(o.length,n);for(r=0;r<t;r++)this.writeUint8(o.charCodeAt(r));for(;r<n;r++)this.writeUint8(0)}else for(r=0;r<o.length;r++)this.writeUint8(o.charCodeAt(r));else this.writeUint8Array(new TextEncoder(l).encode(o.substring(0,n)))}writeCString(o,l){let n=0;if(l!==void 0){const r=Math.min(o.length,l);for(n=0;n<r;n++)this.writeUint8(o.charCodeAt(n));for(;n<l;n++)this.writeUint8(0)}else{for(n=0;n<o.length;n++)this.writeUint8(o.charCodeAt(n));this.writeUint8(0)}}writeStruct(o,l){for(let n=0;n<o.length;n++){const[r,t]=o[n],e=l[r];this.writeType(t,e,l)}}writeType(o,l,n){if(typeof o=="function")return o(this,l);if(typeof o=="object"&&!(o instanceof Array))return o.set(this,l,n);let r,t="ASCII";const e=this.position;let i=o;if(typeof o=="string"&&/:/.test(o)){const a=o.split(":");i=a[0],r=parseInt(a[1])}if(typeof i=="string"&&/,/.test(i)){const a=i.split(",");i=a[0],t=a[1]}switch(i){case"uint8":this.writeUint8(l);break;case"int8":this.writeInt8(l);break;case"uint16":this.writeUint16(l,this.endianness);break;case"int16":this.writeInt16(l,this.endianness);break;case"uint32":this.writeUint32(l,this.endianness);break;case"int32":this.writeInt32(l,this.endianness);break;case"float32":this.writeFloat32(l,this.endianness);break;case"float64":this.writeFloat64(l,this.endianness);break;case"uint16be":this.writeUint16(l,1);break;case"int16be":this.writeInt16(l,1);break;case"uint32be":this.writeUint32(l,1);break;case"int32be":this.writeInt32(l,1);break;case"float32be":this.writeFloat32(l,1);break;case"float64be":this.writeFloat64(l,1);break;case"uint16le":this.writeUint16(l,2);break;case"int16le":this.writeInt16(l,2);break;case"uint32le":this.writeUint32(l,2);break;case"int32le":this.writeInt32(l,2);break;case"float32le":this.writeFloat32(l,2);break;case"float64le":this.writeFloat64(l,2);break;case"cstring":this.writeCString(l,r);break;case"string":this.writeString(l,t,r);break;case"u16string":this.writeUCS2String(l,this.endianness,r);break;case"u16stringle":this.writeUCS2String(l,2,r);break;case"u16stringbe":this.writeUCS2String(l,1,r);break;default:if(lr(this,P,ar).call(this,i)){const[,a]=i;for(let s=0;s<l.length;s++)this.writeType(a,l[s]);break}else{this.writeStruct(i,l);break}}r&&(this.position=e,this._realloc(r),this.position=e+r)}writeUint64(o){const l=Math.floor(o/MAX_SIZE);this.writeUint32(l),this.writeUint32(o&4294967295)}writeUint24(o){this.writeUint8((o&16711680)>>16),this.writeUint8((o&65280)>>8),this.writeUint8(o&255)}adjustUint32(o,l){const n=this.position;this.seek(o),this.writeUint32(l),this.seek(n)}readStruct(o){const l={},n=this.position;for(let r=0;r<o.length;r+=1){const t=o[r][1],e=this.readType(t,l);if(!e){this.failurePosition===0&&(this.failurePosition=this.position),this.position=n;return}l[o[r][0]]=e}return l}readUCS2String(o,l){return String.fromCharCode.apply(void 0,this.readUint16Array(o,l))}readType(o,l){if(typeof o=="function")return o(this,l);if(typeof o=="object"&&!(o instanceof Array))return o.get(this,l);if(o instanceof Array&&o.length!==3)return this.readStruct(o);let n,r,t="ASCII";const e=this.position;let i=o;if(typeof i=="string"&&/:/.test(i)){const a=i.split(":");i=a[0],r=parseInt(a[1])}if(typeof i=="string"&&/,/.test(i)){const a=i.split(",");i=a[0],t=a[1]}switch(i){case"uint8":n=this.readUint8();break;case"int8":n=this.readInt8();break;case"uint16":n=this.readUint16(this.endianness);break;case"int16":n=this.readInt16(this.endianness);break;case"uint32":n=this.readUint32(this.endianness);break;case"int32":n=this.readInt32(this.endianness);break;case"float32":n=this.readFloat32(this.endianness);break;case"float64":n=this.readFloat64(this.endianness);break;case"uint16be":n=this.readUint16(1);break;case"int16be":n=this.readInt16(1);break;case"uint32be":n=this.readUint32(1);break;case"int32be":n=this.readInt32(1);break;case"float32be":n=this.readFloat32(1);break;case"float64be":n=this.readFloat64(1);break;case"uint16le":n=this.readUint16(2);break;case"int16le":n=this.readInt16(2);break;case"uint32le":n=this.readUint32(2);break;case"int32le":n=this.readInt32(2);break;case"float32le":n=this.readFloat32(2);break;case"float64le":n=this.readFloat64(2);break;case"cstring":n=this.readCString(r);break;case"string":n=this.readString(r,t);break;case"u16string":n=this.readUCS2String(r,this.endianness);break;case"u16stringle":n=this.readUCS2String(r,2);break;case"u16stringbe":n=this.readUCS2String(r,1);break;default:if(lr(this,P,ar).call(this,i)){const[,a,s]=i,d=typeof s=="function"?s(l,this,i):typeof s=="string"&&l[s]!==void 0?parseInt(l[s]):typeof s=="number"?s:s==="*"?void 0:parseInt(s);if(typeof a=="string"){const c=a.replace(/(le|be)$/,"");let F;switch(/le$/.test(a)?F=2:/be$/.test(a)&&(F=1),c){case"uint8":n=this.readUint8Array(d);break;case"uint16":n=this.readUint16Array(d,F);break;case"uint32":n=this.readUint32Array(d,F);break;case"int8":n=this.readInt8Array(d);break;case"int16":n=this.readInt16Array(d,F);break;case"int32":n=this.readInt32Array(d,F);break;case"float32":n=this.readFloat32Array(d,F);break;case"float64":n=this.readFloat64Array(d,F);break;case"cstring":case"utf16string":case"string":if(d){n=new Array(d);for(let B=0;B<d;B++)n[B]=this.readType(a,l)}else for(n=[];!this.isEof();){const B=this.readType(a,l);if(!B)break;n.push(B)}break}}else if(d){n=new Array(d);for(let c=0;c<d;c++){const F=this.readType(a,l);if(!F)return;n[c]=F}}else for(n=[];;){const c=this.position;try{const F=this.readType(a,l);if(!F){this.position=c;break}n.push(F)}catch{this.position=c;break}}break}}return r&&(this.position=e+r),n}mapInt32Array(o,l){this._realloc(o*4);const n=new Int32Array(this._buffer,this.byteOffset+this.position,o);return k.arrayToNative(n,l??this.endianness),this.position+=o*4,n}mapInt16Array(o,l){this._realloc(o*2);const n=new Int16Array(this._buffer,this.byteOffset+this.position,o);return k.arrayToNative(n,l??this.endianness),this.position+=o*2,n}mapInt8Array(o,l){this._realloc(o*1);const n=new Int8Array(this._buffer,this.byteOffset+this.position,o);return this.position+=o*1,n}mapUint32Array(o,l){this._realloc(o*4);const n=new Uint32Array(this._buffer,this.byteOffset+this.position,o);return k.arrayToNative(n,l??this.endianness),this.position+=o*4,n}mapUint16Array(o,l){this._realloc(o*2);const n=new Uint16Array(this._buffer,this.byteOffset+this.position,o);return k.arrayToNative(n,l??this.endianness),this.position+=o*2,n}mapFloat64Array(o,l){this._realloc(o*8);const n=new Float64Array(this._buffer,this.byteOffset+this.position,o);return k.arrayToNative(n,l??this.endianness),this.position+=o*8,n}mapFloat32Array(o,l){this._realloc(o*4);const n=new Float32Array(this._buffer,this.byteOffset+this.position,o);return k.arrayToNative(n,l??this.endianness),this.position+=o*4,n}},P=new WeakSet,ar=function(o){return Array.isArray(o)&&o.length===3&&o[0]==="[]"},k.ENDIANNESS=new Int8Array(new Int16Array([1]).buffer)[0]>0?2:1,k);function fromCharCodeUint8(u){const o=[];for(let l=0;l<u.length;l++)o[l]=u[l];return String.fromCharCode.apply(void 0,o)}var start=new Date,LOG_LEVEL_ERROR=4,LOG_LEVEL_WARNING=3,LOG_LEVEL_INFO=2,LOG_LEVEL_DEBUG=1,log_level=LOG_LEVEL_ERROR,Log={setLogLevel(u){u===this.debug?log_level=LOG_LEVEL_DEBUG:u===this.info?log_level=LOG_LEVEL_INFO:u===this.warn?log_level=LOG_LEVEL_WARNING:(this.error,log_level=LOG_LEVEL_ERROR)},debug(u,o){console.debug===void 0&&(console.debug=console.log),LOG_LEVEL_DEBUG>=log_level&&console.debug("["+Log.getDurationString(new Date().getTime()-start.getTime(),1e3)+"]","["+u+"]",o)},log(u,o){this.debug(u.msg)},info(u,o){LOG_LEVEL_INFO>=log_level&&console.info("["+Log.getDurationString(new Date().getTime()-start.getTime(),1e3)+"]","["+u+"]",o)},warn(u,o){LOG_LEVEL_WARNING>=log_level&&console.warn("["+Log.getDurationString(new Date().getTime()-start.getTime(),1e3)+"]","["+u+"]",o)},error(u,o,l){l!=null&&l.onError?l.onError(u,o):LOG_LEVEL_ERROR>=log_level&&console.error("["+Log.getDurationString(new Date().getTime()-start.getTime(),1e3)+"]","["+u+"]",o)},getDurationString(u,o){let l;function n(s,d){const F=(""+s).split(".");for(;F[0].length<d;)F[0]="0"+F[0];return F.join(".")}u<0?(l=!0,u=-u):l=!1;let t=u/(o||1);const e=Math.floor(t/3600);t-=e*3600;const i=Math.floor(t/60);t-=i*60;let a=t*1e3;return t=Math.floor(t),a-=t*1e3,a=Math.floor(a),(l?"-":"")+e+":"+n(i,2)+":"+n(t,2)+"."+n(a,3)},printRanges(u){const o=u.length;if(o>0){let l="";for(let n=0;n<o;n++)n>0&&(l+=","),l+="["+Log.getDurationString(u.start(n))+","+Log.getDurationString(u.end(n))+"]";return l}else return"(empty)"}};function concatBuffers(u,o){Log.debug("ArrayBuffer","Trying to create a new buffer of size: "+(u.byteLength+o.byteLength));const l=new Uint8Array(u.byteLength+o.byteLength);return l.set(new Uint8Array(u),0),l.set(new Uint8Array(o),u.byteLength),l.buffer}var MultiBufferStream=class extends DataStream{constructor(u){super(new ArrayBuffer,0),this.buffers=[],this.bufferIndex=-1,u&&(this.insertBuffer(u),this.bufferIndex=0)}initialized(){if(this.bufferIndex>-1)return!0;if(this.buffers.length>0){const u=this.buffers[0];return u.fileStart===0?(this.buffer=u,this.bufferIndex=0,Log.debug("MultiBufferStream","Stream ready for parsing"),!0):(Log.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)}else return Log.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1}reduceBuffer(u,o,l){const n=new Uint8Array(l);return n.set(new Uint8Array(u,o,l)),n.buffer.fileStart=u.fileStart+o,n.buffer.usedBytes=0,n.buffer}insertBuffer(u){let o=!0,l=0;for(;l<this.buffers.length;l++){const n=this.buffers[l];if(u.fileStart<=n.fileStart){if(u.fileStart===n.fileStart)if(u.byteLength>n.byteLength){this.buffers.splice(l,1),l--;continue}else Log.warn("MultiBufferStream","Buffer (fileStart: "+u.fileStart+" - Length: "+u.byteLength+") already appended, ignoring");else u.fileStart+u.byteLength<=n.fileStart||(u=this.reduceBuffer(u,0,n.fileStart-u.fileStart)),Log.debug("MultiBufferStream","Appending new buffer (fileStart: "+u.fileStart+" - Length: "+u.byteLength+")"),this.buffers.splice(l,0,u),l===0&&(this.buffer=u);o=!1;break}else if(u.fileStart<n.fileStart+n.byteLength){const r=n.fileStart+n.byteLength-u.fileStart,t=u.byteLength-r;if(t>0)u=this.reduceBuffer(u,r,t);else{o=!1;break}}}o&&(Log.debug("MultiBufferStream","Appending new buffer (fileStart: "+u.fileStart+" - Length: "+u.byteLength+")"),this.buffers.push(u),l===0&&(this.buffer=u))}logBufferLevel(u){const o=[];let l="",n,r=0,t=0;for(let i=0;i<this.buffers.length;i++){const a=this.buffers[i];i===0?(n={start:a.fileStart,end:a.fileStart+a.byteLength},o.push(n),l+="["+n.start+"-"):n.end===a.fileStart?n.end=a.fileStart+a.byteLength:(n={start:a.fileStart,end:a.fileStart+a.byteLength},l+=o[o.length-1].end-1+"], ["+n.start+"-",o.push(n)),r+=a.usedBytes,t+=a.byteLength}o.length>0&&(l+=n.end-1+"]");const e=u?Log.info:Log.debug;this.buffers.length===0?e("MultiBufferStream","No more buffer in memory"):e("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+r+"/"+t+" bytes), continuous ranges: "+l)}cleanBuffers(){for(let u=0;u<this.buffers.length;u++){const o=this.buffers[u];o.usedBytes===o.byteLength&&(Log.debug("MultiBufferStream","Removing buffer #"+u),this.buffers.splice(u,1),u--)}}mergeNextBuffer(){if(this.bufferIndex+1<this.buffers.length){const u=this.buffers[this.bufferIndex+1];if(u.fileStart===this.buffer.fileStart+this.buffer.byteLength){const o=this.buffer.byteLength,l=this.buffer.usedBytes,n=this.buffer.fileStart;return this.buffers[this.bufferIndex]=concatBuffers(this.buffer,u),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=l,this.buffer.fileStart=n,Log.debug("ISOFile","Concatenating buffer for box parsing (length: "+o+"->"+this.buffer.byteLength+")"),!0}else return!1}else return!1}findPosition(u,o,l){let n=-1,r=u===!0?0:this.bufferIndex;for(;r<this.buffers.length;){const e=this.buffers[r];if(e&&e.fileStart<=o)n=r,l&&(e.fileStart+e.byteLength<=o?e.usedBytes=e.byteLength:e.usedBytes=o-e.fileStart,this.logBufferLevel());else break;r++}if(n===-1)return-1;const t=this.buffers[n];return t.fileStart+t.byteLength>=o?(Log.debug("MultiBufferStream","Found position in existing buffer #"+n),n):-1}findEndContiguousBuf(u){const o=u!==void 0?u:this.bufferIndex;let l=this.buffers[o];if(this.buffers.length>o+1)for(let n=o+1;n<this.buffers.length;n++){const r=this.buffers[n];if(r.fileStart===l.fileStart+l.byteLength)l=r;else break}return l.fileStart+l.byteLength}getEndFilePositionAfter(u){const o=this.findPosition(!0,u,!1);return o!==-1?this.findEndContiguousBuf(o):u}addUsedBytes(u){this.buffer.usedBytes+=u,this.logBufferLevel()}setAllUsedBytes(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()}seek(u,o,l){const n=this.findPosition(o,u,l);return n!==-1?(this.buffer=this.buffers[n],this.bufferIndex=n,this.position=u-this.buffer.fileStart,Log.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(Log.debug("MultiBufferStream","Position "+u+" not found in buffered data"),!1)}getPosition(){return this.bufferIndex===-1||this.buffers[this.bufferIndex]===void 0?0:this.buffers[this.bufferIndex].fileStart+this.position}getLength(){return this.byteLength}getEndPosition(){return this.bufferIndex===-1||this.buffers[this.bufferIndex]===void 0?0:this.buffers[this.bufferIndex].fileStart+this.byteLength}getAbsoluteEndPosition(){if(this.buffers.length===0)return 0;const u=this.buffers[this.buffers.length-1];return u.fileStart+u.byteLength}},$,L,Box=(L=class{constructor(o=0){rr(this,$,void 0);this.size=o}get type(){return this.constructor.fourcc??dr(this,$)}set type(o){ur(this,$,o)}addBox(o){return this.boxes||(this.boxes=[]),this.boxes.push(o),this[o.type+"s"]?this[o.type+"s"].push(o):this[o.type]=o,o}set(o,l){return this[o]=l,this}addEntry(o,l){const n=l||"entries";return this[n]||(this[n]=[]),this[n].push(o),this}writeHeader(o,l){if(this.size+=8,(this.size>MAX_UINT32||this.original_size===1)&&(this.size+=8),this.type==="uuid"&&(this.size+=16),Log.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+o.getPosition()+(l||"")),this.original_size===0?o.writeUint32(0):this.size>MAX_UINT32||this.original_size===1?o.writeUint32(1):(this.sizePosition=o.getPosition(),o.writeUint32(this.size)),o.writeString(this.type,void 0,4),this.type==="uuid"){const n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(this.uuid.substring(r*2,r*2+2),16);o.writeUint8Array(n)}(this.size>MAX_UINT32||this.original_size===1)&&(this.sizePosition=o.getPosition(),o.writeUint64(this.size))}write(o){if(this.type==="mdat"){const l=this;if(l.stream){this.size=l.stream.getAbsoluteEndPosition(),this.writeHeader(o);for(const n of l.stream.buffers){const r=new Uint8Array(n);o.writeUint8Array(r)}}else l.data&&(this.size=l.data.length,this.writeHeader(o),o.writeUint8Array(l.data))}else this.size=this.data?this.data.length:0,this.writeHeader(o),this.data&&o.writeUint8Array(this.data)}printHeader(o){this.size+=8,this.size>MAX_UINT32&&(this.size+=8),this.type==="uuid"&&(this.size+=16),o.log(o.indent+"size:"+this.size),o.log(o.indent+"type:"+this.type)}print(o){this.printHeader(o)}parse(o){this.type!=="mdat"?this.data=o.readUint8Array(this.size-this.hdr_size):this.size===0?o.seek(o.getEndPosition()):o.seek(this.start+this.size)}parseDataAndRewind(o){this.data=o.readUint8Array(this.size-this.hdr_size),o.seek(this.start+this.hdr_size)}parseLanguage(o){this.language=o.readUint16();const l=[];l[0]=this.language>>10&31,l[1]=this.language>>5&31,l[2]=this.language&31,this.languageString=String.fromCharCode(l[0]+96,l[1]+96,l[2]+96)}computeSize(o){const l=o||new MultiBufferStream;this.write(l)}isEndOfBox(o){const l=o.getPosition(),n=this.start+this.size;return l===n}},$=new WeakMap,L.registryId=Symbol.for("BoxIdentifier"),L),FullBox=class extends Box{constructor(){super(...arguments),this.flags=0,this.version=0}writeHeader(u){this.size+=4,super.writeHeader(u," v="+this.version+" f="+this.flags),u.writeUint8(this.version),u.writeUint24(this.flags)}printHeader(u){this.size+=4,super.printHeader(u),u.log(u.indent+"version:"+this.version),u.log(u.indent+"flags:"+this.flags)}parseDataAndRewind(u){this.parseFullHeader(u),this.data=u.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,u.seek(this.start+this.hdr_size)}parseFullHeader(u){this.version=u.readUint8(),this.flags=u.readUint24(),this.hdr_size+=4}parse(u){this.parseFullHeader(u),this.data=u.readUint8Array(this.size-this.hdr_size)}},A,SampleGroupEntry=(A=class{constructor(o){this.grouping_type=o}write(o){o.writeUint8Array(this.data)}parse(o){Log.warn("BoxParser",`Unknown sample group type: '${this.grouping_type}'`),this.data=o.readUint8Array(this.description_length)}},A.registryId=Symbol.for("SampleGroupEntryIdentifier"),A),TrackGroupTypeBox=class extends FullBox{parse(u){this.parseFullHeader(u),this.track_group_id=u.readUint32()}},SingleItemTypeReferenceBox=class extends Box{constructor(u,o,l,n,r){super(o),this.box_name=l,this.hdr_size=n,this.start=r,this.type=u}parse(u){this.from_item_ID=u.readUint16();const o=u.readUint16();this.references=[];for(let l=0;l<o;l++)this.references[l]={to_item_ID:u.readUint16()}}},SingleItemTypeReferenceBoxLarge=class extends Box{constructor(u,o,l,n,r){super(o),this.box_name=l,this.hdr_size=n,this.start=r,this.type=u}parse(u){this.from_item_ID=u.readUint32();const o=u.readUint16();this.references=[];for(let l=0;l<o;l++)this.references[l]={to_item_ID:u.readUint32()}}},TrackReferenceTypeBox=class extends Box{constructor(u,o,l,n){super(o),this.hdr_size=l,this.start=n,this.type=u}parse(u){this.track_ids=u.readUint32Array((this.size-this.hdr_size)/4)}write(u){this.size=this.track_ids.length*4,this.writeHeader(u),u.writeUint32Array(this.track_ids)}},DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"];function boxEqualFields(u,o){if(u&&!o)return!1;let l;for(l in u)if(!DIFF_BOXES_PROP_NAMES.find(n=>n===l)){if(u[l]instanceof Box||o[l]instanceof Box)continue;if(typeof u[l]>"u"||typeof o[l]>"u")continue;if(typeof u[l]=="function"||typeof o[l]=="function")continue;if("subBoxNames"in u&&u.subBoxNames.indexOf(l.slice(0,4))>-1||"subBoxNames"in o&&o.subBoxNames.indexOf(l.slice(0,4))>-1)continue;if(l==="data"||l==="start"||l==="size"||l==="creation_time"||l==="modification_time")continue;if(DIFF_PRIMITIVE_ARRAY_PROP_NAMES.find(n=>n===l))continue;if(u[l]!==o[l])return!1}return!0}function boxEqual(u,o){if(!boxEqualFields(u,o))return!1;for(let l=0;l<DIFF_BOXES_PROP_NAMES.length;l++){const n=DIFF_BOXES_PROP_NAMES[l];if(u[n]&&o[n]&&!boxEqual(u[n],o[n]))return!1}return!0}function getRegistryId(u){let o=u;for(;o;){if("registryId"in o)return o.registryId;o=Object.getPrototypeOf(o)}}var isSampleGroupEntry=u=>{const o=Symbol.for("SampleGroupEntryIdentifier");return getRegistryId(u)===o},isSampleEntry=u=>{const o=Symbol.for("SampleEntryIdentifier");return getRegistryId(u)===o},isBox=u=>{const o=Symbol.for("BoxIdentifier");return getRegistryId(u)===o},BoxRegistry={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};function registerBoxes(u){const o={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};for(const[l,n]of Object.entries(u)){if(isSampleGroupEntry(n)){const r="grouping_type"in n?n.grouping_type:void 0;if(!r)throw new Error(`SampleGroupEntry class ${l} does not have a valid static grouping_type. Please ensure it is defined correctly.`);if(r in o.sampleGroupEntry)throw new Error(`SampleGroupEntry class ${l} has a grouping_type that is already registered. Please ensure it is unique.`);o.sampleGroupEntry[r]=n;continue}if(isSampleEntry(n)){const r="fourcc"in n?n.fourcc:void 0;if(!r)throw new Error(`SampleEntry class ${l} does not have a valid static fourcc. Please ensure it is defined correctly.`);if(r in o.sampleEntry)throw new Error(`SampleEntry class ${l} has a fourcc that is already registered. Please ensure it is unique.`);o.sampleEntry[r]=n;continue}if(isBox(n)){const r="fourcc"in n?n.fourcc:void 0,t="uuid"in n?n.uuid:void 0;if(r==="uuid"){if(!t)throw new Error(`Box class ${l} has a fourcc of 'uuid' but does not have a valid uuid. Please ensure it is defined correctly.`);if(t in o.uuid)throw new Error(`Box class ${l} has a uuid that is already registered. Please ensure it is unique.`);o.uuid[t]=n;continue}o.box[r]=n;continue}throw new Error(`Box class ${l} does not have a valid static fourcc, uuid, or grouping_type. Please ensure it is defined correctly.`)}return BoxRegistry.uuid={...o.uuid},BoxRegistry.sampleEntry={...o.sampleEntry},BoxRegistry.sampleGroupEntry={...o.sampleGroupEntry},BoxRegistry.box={...o.box},BoxRegistry}var DescriptorRegistry={};function registerDescriptors(u){return Object.entries(u).forEach(([o,l])=>DescriptorRegistry[o]=l),DescriptorRegistry}function parseUUID(u){return parseHex16(u)}function parseHex16(u){let o="";for(let l=0;l<16;l++){const n=u.readUint8().toString(16);o+=n.length===1?"0"+n:n}return o}function parseOneBox(u,o,l){let n,r;const t=u.getPosition();let e=0,i;if(u.getEndPosition()-t<8)return Log.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:ERR_NOT_ENOUGH_DATA};if(l&&l<8)return Log.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:ERR_NOT_ENOUGH_DATA};let a=u.readUint32();const s=u.readString(4);if(s.length!==4||!/^[\x20-\x7E]{4}$/.test(s))return Log.error("BoxParser",`Invalid box type: '${s}'`),{code:ERR_INVALID_DATA,start:t,type:s};let d=s;if(Log.debug("BoxParser","Found box of type '"+s+"' and size "+a+" at position "+t),e=8,s==="uuid"){if(u.getEndPosition()-u.getPosition()<16||l-e<16)return u.seek(t),Log.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:ERR_NOT_ENOUGH_DATA};i=parseUUID(u),e+=16,d=i}if(a===1){if(u.getEndPosition()-u.getPosition()<8||l&&l-e<8)return u.seek(t),Log.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+s+'" box'),{code:ERR_NOT_ENOUGH_DATA};r=a,a=u.readUint64(),e+=8}else if(a===0){if(l)a=l;else if(s!=="mdat")return Log.error("BoxParser","Unlimited box size not supported for type: '"+s+"'"),n=new Box(a),n.type=s,{code:OK,box:n,size:n.size}}if(a!==0&&a<e)return Log.error("BoxParser","Box of type "+s+" has an invalid size "+a+" (too small to be a box)"),{code:ERR_NOT_ENOUGH_DATA,type:s,size:a,hdr_size:e,start:t};if(a!==0&&l&&a>l)return Log.error("BoxParser","Box of type '"+s+"' has a size "+a+" greater than its container size "+l),{code:ERR_NOT_ENOUGH_DATA,type:s,size:a,hdr_size:e,start:t};if(a!==0&&t+a>u.getEndPosition())return u.seek(t),Log.info("BoxParser","Not enough data in stream to parse the entire '"+s+"' box"),{code:ERR_NOT_ENOUGH_DATA,type:s,size:a,hdr_size:e,start:t,original_size:r};if(o)return{code:OK,type:s,size:a,hdr_size:e,start:t};s in BoxRegistry.box?n=new BoxRegistry.box[s](a):s!=="uuid"?(Log.warn("BoxParser",`Unknown box type: '${s}'`),n=new Box(a),n.type=s,n.has_unparsed_data=!0):i in BoxRegistry.uuid?n=new BoxRegistry.uuid[i](a):(Log.warn("BoxParser",`Unknown UUID box type: '${i}'`),n=new Box(a),n.type=s,n.uuid=i,n.has_unparsed_data=!0),n.original_size=r,n.hdr_size=e,n.start=t,n.write===Box.prototype.write&&n.type!=="mdat"&&(Log.info("BoxParser","'"+d+"' box writing not yet implemented, keeping unparsed data in memory for later write"),n.parseDataAndRewind(u)),n.parse(u);const c=u.getPosition()-(n.start+n.size);return c<0?(Log.warn("BoxParser","Parsing of box '"+d+"' did not read the entire indicated box data size (missing "+-c+" bytes), seeking forward"),u.seek(n.start+n.size)):c>0&&n.size!==0&&(Log.error("BoxParser","Parsing of box '"+d+"' read "+c+" more bytes than the indicated box data size, seeking backwards"),u.seek(n.start+n.size)),{code:OK,box:n,size:n.size}}var ContainerBox=class extends Box{write(u){if(this.size=0,this.writeHeader(u),this.boxes)for(let o=0;o<this.boxes.length;o++)this.boxes[o]&&(this.boxes[o].write(u),this.size+=this.boxes[o].size);Log.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),u.adjustUint32(this.sizePosition,this.size)}print(u){this.printHeader(u);for(let o=0;o<this.boxes.length;o++)if(this.boxes[o]){const l=u.indent;u.indent+=" ",this.boxes[o].print(u),u.indent=l}}parse(u){let o;for(;u.getPosition()<this.start+this.size;)if(o=parseOneBox(u,!1,this.size-(u.getPosition()-this.start)),o.code===OK){const l=o.box;if(this.boxes||(this.boxes=[]),this.boxes.push(l),this.subBoxNames&&this.subBoxNames.indexOf(l.type)!==-1){const n=this.subBoxNames[this.subBoxNames.indexOf(l.type)]+"s";this[n]||(this[n]=[]),this[n].push(l)}else{const n=l.type!=="uuid"?l.type:l.uuid;this[n]?Log.warn("ContainerBox",`Box of type ${n} already exists in container box ${this.type}.`):this[n]=l}}else return}},G,SampleEntry=(G=class extends ContainerBox{constructor(o,l,n){super(o),this.hdr_size=l,this.start=n}isVideo(){return!1}isAudio(){return!1}isSubtitle(){return!1}isMetadata(){return!1}isHint(){return!1}getCodec(){return this.type.replace(".","")}getWidth(){return""}getHeight(){return""}getChannelCount(){return""}getSampleRate(){return""}getSampleSize(){return""}parseHeader(o){o.readUint8Array(6),this.data_reference_index=o.readUint16(),this.hdr_size+=8}parse(o){this.parseHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size)}parseDataAndRewind(o){this.parseHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,o.seek(this.start+this.hdr_size)}parseFooter(o){super.parse(o)}writeHeader(o){this.size=8,super.writeHeader(o),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint16(this.data_reference_index)}writeFooter(o){if(this.boxes)for(let l=0;l<this.boxes.length;l++)this.boxes[l].write(o),this.size+=this.boxes[l].size;Log.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)}write(o){this.writeHeader(o),o.writeUint8Array(this.data),this.size+=this.data.length,Log.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)}},G.registryId=Symbol.for("SampleEntryIdentifier"),G),HintSampleEntry=class extends SampleEntry{},MetadataSampleEntry=class extends SampleEntry{isMetadata(){return!0}},SubtitleSampleEntry=class extends SampleEntry{isSubtitle(){return!0}},TextSampleEntry=class extends SampleEntry{},VisualSampleEntry=class extends SampleEntry{parse(u){this.parseHeader(u),u.readUint16(),u.readUint16(),u.readUint32Array(3),this.width=u.readUint16(),this.height=u.readUint16(),this.horizresolution=u.readUint32(),this.vertresolution=u.readUint32(),u.readUint32(),this.frame_count=u.readUint16();const o=Math.min(31,u.readUint8());this.compressorname=u.readString(o),o<31&&u.readString(31-o),this.depth=u.readUint16(),u.readUint16(),this.parseFooter(u)}isVideo(){return!0}getWidth(){return this.width}getHeight(){return this.height}write(u){this.writeHeader(u),this.size+=2*7+6*4+32,u.writeUint16(0),u.writeUint16(0),u.writeUint32(0),u.writeUint32(0),u.writeUint32(0),u.writeUint16(this.width),u.writeUint16(this.height),u.writeUint32(this.horizresolution),u.writeUint32(this.vertresolution),u.writeUint32(0),u.writeUint16(this.frame_count),u.writeUint8(Math.min(31,this.compressorname.length)),u.writeString(this.compressorname,void 0,31),u.writeUint16(this.depth),u.writeInt16(-1),this.writeFooter(u)}},AudioSampleEntry=class extends SampleEntry{parse(u){var l,n;this.parseHeader(u),this.version=u.readUint16(),u.readUint16(),u.readUint32(),this.channel_count=u.readUint16(),this.samplesize=u.readUint16(),u.readUint16(),u.readUint16(),this.samplerate=u.readUint32()/65536,((n=(l=u.isofile)==null?void 0:l.ftyp)==null?void 0:n.major_brand.includes("qt"))&&(this.version===1?this.extensions=u.readUint8Array(16):this.version===2&&(this.extensions=u.readUint8Array(36))),this.parseFooter(u)}isAudio(){return!0}getChannelCount(){return this.channel_count}getSampleRate(){return this.samplerate}getSampleSize(){return this.samplesize}write(u){this.writeHeader(u),this.size+=2*4+3*4,u.writeUint32(0),u.writeUint32(0),u.writeUint16(this.channel_count),u.writeUint16(this.samplesize),u.writeUint16(0),u.writeUint16(0),u.writeUint32(this.samplerate<<16),this.writeFooter(u)}},SystemSampleEntry=class extends SampleEntry{parse(u){this.parseHeader(u),this.parseFooter(u)}write(u){this.writeHeader(u),this.writeFooter(u)}},ParameterSetArray=class extends Array{toString(){let u="<table class='inner-table'>";u+="<thead><tr><th>length</th><th>nalu_data</th></tr></thead>",u+="<tbody>";for(let o=0;o<this.length;o++){const l=this[o];u+="<tr>",u+="<td>"+l.length+"</td>",u+="<td>",u+=l.data.reduce(function(n,r){return n+r.toString(16).padStart(2,"0")},"0x"),u+="</td></tr>"}return u+="</tbody></table>",u}},H,avcCBox=(H=class extends Box{constructor(){super(...arguments),this.box_name="AVCConfigurationBox"}parse(o){this.configurationVersion=o.readUint8(),this.AVCProfileIndication=o.readUint8(),this.profile_compatibility=o.readUint8(),this.AVCLevelIndication=o.readUint8(),this.lengthSizeMinusOne=o.readUint8()&3,this.nb_SPS_nalus=o.readUint8()&31;let l=this.size-this.hdr_size-6;this.SPS=new ParameterSetArray;for(let n=0;n<this.nb_SPS_nalus;n++){const r=o.readUint16();this.SPS.push({length:r,data:o.readUint8Array(r)}),l-=2+r}this.nb_PPS_nalus=o.readUint8(),l--,this.PPS=new ParameterSetArray;for(let n=0;n<this.nb_PPS_nalus;n++){const r=o.readUint16();this.PPS.push({length:r,data:o.readUint8Array(r)}),l-=2+r}l>0&&(this.ext=o.readUint8Array(l))}write(o){this.size=7;for(let l=0;l<this.SPS.length;l++)this.size+=2+this.SPS[l].length;for(let l=0;l<this.PPS.length;l++)this.size+=2+this.PPS[l].length;this.ext&&(this.size+=this.ext.length),this.writeHeader(o),o.writeUint8(this.configurationVersion),o.writeUint8(this.AVCProfileIndication),o.writeUint8(this.profile_compatibility),o.writeUint8(this.AVCLevelIndication),o.writeUint8(this.lengthSizeMinusOne+252),o.writeUint8(this.SPS.length+224);for(let l=0;l<this.SPS.length;l++)o.writeUint16(this.SPS[l].length),o.writeUint8Array(this.SPS[l].data);o.writeUint8(this.PPS.length);for(let l=0;l<this.PPS.length;l++)o.writeUint16(this.PPS[l].length),o.writeUint8Array(this.PPS[l].data);this.ext&&o.writeUint8Array(this.ext)}},H.fourcc="avcC",H),z,mdatBox=(z=class extends Box{constructor(){super(...arguments),this.box_name="MediaDataBox"}},z.fourcc="mdat",z),Y,idatBox=(Y=class extends Box{constructor(){super(...arguments),this.box_name="ItemDataBox"}},Y.fourcc="idat",Y),j,freeBox=(j=class extends Box{constructor(){super(...arguments),this.box_name="FreeSpaceBox"}},j.fourcc="free",j),X,skipBox=(X=class extends Box{constructor(){super(...arguments),this.box_name="FreeSpaceBox"}},X.fourcc="skip",X),q,hmhdBox=(q=class extends FullBox{constructor(){super(...arguments),this.box_name="HintMediaHeaderBox"}},q.fourcc="hmhd",q),K,nmhdBox=(K=class extends FullBox{constructor(){super(...arguments),this.box_name="NullMediaHeaderBox"}},K.fourcc="nmhd",K),tt,iodsBox=(tt=class extends FullBox{constructor(){super(...arguments),this.box_name="ObjectDescriptorBox"}},tt.fourcc="iods",tt),et,xmlBox=(et=class extends FullBox{constructor(){super(...arguments),this.box_name="XMLBox"}},et.fourcc="xml ",et),nt,bxmlBox=(nt=class extends FullBox{constructor(){super(...arguments),this.box_name="BinaryXMLBox"}},nt.fourcc="bxml",nt),it,iproBox=(it=class extends FullBox{constructor(){super(...arguments),this.box_name="ItemProtectionBox",this.sinfs=[]}get protections(){return this.sinfs}},it.fourcc="ipro",it),ot,moovBox=(ot=class extends ContainerBox{constructor(){super(...arguments),this.box_name="MovieBox",this.traks=[],this.psshs=[],this.subBoxNames=["trak","pssh"]}},ot.fourcc="moov",ot),rt,trakBox=(rt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="TrackBox",this.samples=[]}},rt.fourcc="trak",rt),lt,edtsBox=(lt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="EditBox"}},lt.fourcc="edts",lt),at,mdiaBox=(at=class extends ContainerBox{constructor(){super(...arguments),this.box_name="MediaBox"}},at.fourcc="mdia",at),st,minfBox=(st=class extends ContainerBox{constructor(){super(...arguments),this.box_name="MediaInformationBox"}},st.fourcc="minf",st),dt,dinfBox=(dt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="DataInformationBox"}},dt.fourcc="dinf",dt),ut,stblBox=(ut=class extends ContainerBox{constructor(){super(...arguments),this.box_name="SampleTableBox",this.sgpds=[],this.sbgps=[],this.subBoxNames=["sgpd","sbgp"]}},ut.fourcc="stbl",ut),ct,mvexBox=(ct=class extends ContainerBox{constructor(){super(...arguments),this.box_name="MovieExtendsBox",this.trexs=[],this.subBoxNames=["trex"]}},ct.fourcc="mvex",ct),Ut,moofBox=(Ut=class extends ContainerBox{constructor(){super(...arguments),this.box_name="MovieFragmentBox",this.trafs=[],this.subBoxNames=["traf"]}},Ut.fourcc="moof",Ut),Ft,trafBox=(Ft=class extends ContainerBox{constructor(){super(...arguments),this.box_name="TrackFragmentBox",this.truns=[],this.sgpds=[],this.sbgps=[],this.subBoxNames=["trun","sgpd","sbgp"]}},Ft.fourcc="traf",Ft),Qt,vttcBox=(Qt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="VTTCueBox"}},Qt.fourcc="vttc",Qt),pt,mfraBox=(pt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="MovieFragmentRandomAccessBox",this.tfras=[],this.subBoxNames=["tfra"]}},pt.fourcc="mfra",pt),ft,mecoBox=(ft=class extends ContainerBox{constructor(){super(...arguments),this.box_name="AdditionalMetadataContainerBox"}},ft.fourcc="meco",ft),ht,hntiBox=(ht=class extends ContainerBox{constructor(){super(...arguments),this.box_name="trackhintinformation",this.subBoxNames=["sdp ","rtp "]}},ht.fourcc="hnti",ht),Rt,hinfBox=(Rt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="hintstatisticsbox",this.maxrs=[],this.subBoxNames=["maxr"]}},Rt.fourcc="hinf",Rt),Bt,strkBox=(Bt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="SubTrackBox"}},Bt.fourcc="strk",Bt),St,strdBox=(St=class extends ContainerBox{constructor(){super(...arguments),this.box_name="SubTrackDefinitionBox"}},St.fourcc="strd",St),yt,sinfBox=(yt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="ProtectionSchemeInfoBox"}},yt.fourcc="sinf",yt),Vt,rinfBox=(Vt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="RestrictedSchemeInfoBox"}},Vt.fourcc="rinf",Vt),Jt,schiBox=(Jt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="SchemeInformationBox"}},Jt.fourcc="schi",Jt),Et,trgrBox=(Et=class extends ContainerBox{constructor(){super(...arguments),this.box_name="TrackGroupBox"}},Et.fourcc="trgr",Et),mt,udtaBox=(mt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="UserDataBox",this.kinds=[],this.strks=[],this.subBoxNames=["kind","strk"]}},mt.fourcc="udta",mt),kt,iprpBox=(kt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="ItemPropertiesBox",this.ipmas=[],this.subBoxNames=["ipma"]}},kt.fourcc="iprp",kt),Nt,ipcoBox=(Nt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="ItemPropertyContainerBox",this.hvcCs=[],this.ispes=[],this.claps=[],this.irots=[],this.subBoxNames=["hvcC","ispe","clap","irot"]}},Nt.fourcc="ipco",Nt),Tt,grplBox=(Tt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="GroupsListBox"}},Tt.fourcc="grpl",Tt),vt,j2kHBox=(vt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="J2KHeaderInfoBox"}},vt.fourcc="j2kH",vt),Ct,etypBox=(Ct=class extends ContainerBox{constructor(){super(...arguments),this.box_name="ExtendedTypeBox",this.tycos=[],this.subBoxNames=["tyco"]}},Ct.fourcc="etyp",Ct),Wt,povdBox=(Wt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="ProjectedOmniVideoBox",this.subBoxNames=["prfr"]}},Wt.fourcc="povd",Wt),bt,drefBox=(bt=class extends FullBox{constructor(){super(...arguments),this.box_name="DataReferenceBox"}parse(o){this.parseFullHeader(o),this.entries=[];const l=o.readUint32();for(let n=0;n<l;n++){const r=parseOneBox(o,!1,this.size-(o.getPosition()-this.start));if(r.code===OK){const t=r.box;this.entries.push(t)}else return}}write(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.entries.length);for(let l=0;l<this.entries.length;l++)this.entries[l].write(o),this.size+=this.entries[l].size;Log.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)}},bt.fourcc="dref",bt),Ot,elngBox=(Ot=class extends FullBox{constructor(){super(...arguments),this.box_name="ExtendedLanguageBox"}parse(o){this.parseFullHeader(o),this.extended_language=o.readString(this.size-this.hdr_size)}write(o){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(o),o.writeString(this.extended_language)}},Ot.fourcc="elng",Ot),Zt,ftypBox=(Zt=class extends Box{constructor(){super(...arguments),this.box_name="FileTypeBox"}parse(o){let l=this.size-this.hdr_size;this.major_brand=o.readString(4),this.minor_version=o.readUint32(),l-=8,this.compatible_brands=[];let n=0;for(;l>=4;)this.compatible_brands[n]=o.readString(4),l-=4,n++}write(o){this.size=8+4*this.compatible_brands.length,this.writeHeader(o),o.writeString(this.major_brand,void 0,4),o.writeUint32(this.minor_version);for(let l=0;l<this.compatible_brands.length;l++)o.writeString(this.compatible_brands[l],void 0,4)}},Zt.fourcc="ftyp",Zt),Dt,hdlrBox=(Dt=class extends FullBox{constructor(){super(...arguments),this.box_name="HandlerBox"}parse(o){if(this.parseFullHeader(o),this.version===0&&(o.readUint32(),this.handler=o.readString(4),o.readUint32Array(3),!this.isEndOfBox(o))){const l=this.start+this.size-o.getPosition();this.name=o.readCString();const n=this.start+this.size-1;o.seek(n),o.readUint8()!==0&&l>1&&(Log.info("BoxParser","Warning: hdlr name is not null-terminated, possibly length-prefixed string. Trimming first byte."),this.name=this.name.slice(1))}}write(o){this.size=5*4+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(o),o.writeUint32(0),o.writeString(this.handler,void 0,4),o.writeUint32Array([0,0,0]),o.writeCString(this.name)}},Dt.fourcc="hdlr",Dt),wt,hvcCBox=(wt=class extends Box{constructor(){super(...arguments),this.box_name="HEVCConfigurationBox"}parse(o){this.configurationVersion=o.readUint8();let l=o.readUint8();this.general_profile_space=l>>6,this.general_tier_flag=(l&32)>>5,this.general_profile_idc=l&31,this.general_profile_compatibility=o.readUint32(),this.general_constraint_indicator=o.readUint8Array(6),this.general_level_idc=o.readUint8(),this.min_spatial_segmentation_idc=o.readUint16()&4095,this.parallelismType=o.readUint8()&3,this.chroma_format_idc=o.readUint8()&3,this.bit_depth_luma_minus8=o.readUint8()&7,this.bit_depth_chroma_minus8=o.readUint8()&7,this.avgFrameRate=o.readUint16(),l=o.readUint8(),this.constantFrameRate=l>>6,this.numTemporalLayers=(l&13)>>3,this.temporalIdNested=(l&4)>>2,this.lengthSizeMinusOne=l&3,this.nalu_arrays=[];const n=o.readUint8();for(let r=0;r<n;r++){const t=[];this.nalu_arrays.push(t),l=o.readUint8(),t.completeness=(l&128)>>7,t.nalu_type=l&63;const e=o.readUint16();for(let i=0;i<e;i++){const a=o.readUint16();t.push({data:o.readUint8Array(a)})}}}write(o){this.size=23;for(let l=0;l<this.nalu_arrays.length;l++){this.size+=3;for(let n=0;n<this.nalu_arrays[l].length;n++)this.size+=2+this.nalu_arrays[l][n].data.length}this.writeHeader(o),o.writeUint8(this.configurationVersion),o.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),o.writeUint32(this.general_profile_compatibility),o.writeUint8Array(this.general_constraint_indicator),o.writeUint8(this.general_level_idc),o.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),o.writeUint8(this.parallelismType+252),o.writeUint8(this.chroma_format_idc+252),o.writeUint8(this.bit_depth_luma_minus8+248),o.writeUint8(this.bit_depth_chroma_minus8+248),o.writeUint16(this.avgFrameRate),o.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),o.writeUint8(this.nalu_arrays.length);for(let l=0;l<this.nalu_arrays.length;l++){o.writeUint8((this.nalu_arrays[l].completeness<<7)+this.nalu_arrays[l].nalu_type),o.writeUint16(this.nalu_arrays[l].length);for(let n=0;n<this.nalu_arrays[l].length;n++)o.writeUint16(this.nalu_arrays[l][n].data.length),o.writeUint8Array(this.nalu_arrays[l][n].data)}}},wt.fourcc="hvcC",wt),gt,mdhdBox=(gt=class extends FullBox{constructor(){super(...arguments),this.box_name="MediaHeaderBox"}parse(o){this.parseFullHeader(o),this.version===1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.timescale=o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.timescale=o.readUint32(),this.duration=o.readUint32()),this.parseLanguage(o),o.readUint16()}write(o){const l=this.modification_time>MAX_UINT32||this.creation_time>MAX_UINT32||this.duration>MAX_UINT32||this.version===1;this.version=l?1:0,this.size=4*4+2*2,this.size+=l?3*4:0,this.flags=0,this.writeHeader(o),l?(o.writeUint64(this.creation_time),o.writeUint64(this.modification_time),o.writeUint32(this.timescale),o.writeUint64(this.duration)):(o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.timescale),o.writeUint32(this.duration)),o.writeUint16(this.language),o.writeUint16(0)}},gt.fourcc="mdhd",gt),xt,mehdBox=(xt=class extends FullBox{constructor(){super(...arguments),this.box_name="MovieExtendsHeaderBox"}parse(o){this.parseFullHeader(o),this.flags&1&&(Log.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version===1?this.fragment_duration=o.readUint64():this.fragment_duration=o.readUint32()}write(o){const l=this.fragment_duration>MAX_UINT32||this.version===1;this.version=l?1:0,this.size=4,this.size+=l?4:0,this.flags=0,this.writeHeader(o),l?o.writeUint64(this.fragment_duration):o.writeUint32(this.fragment_duration)}},xt.fourcc="mehd",xt),It,infeBox=(It=class extends FullBox{constructor(){super(...arguments),this.box_name="ItemInfoEntry"}parse(o){if(this.parseFullHeader(o),(this.version===0||this.version===1)&&(this.item_ID=o.readUint16(),this.item_protection_index=o.readUint16(),this.item_name=o.readCString(),this.content_type=o.readCString(),this.isEndOfBox(o)||(this.content_encoding=o.readCString())),this.version===1){this.extension_type=o.readString(4),Log.warn("BoxParser","Cannot parse extension type"),o.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=o.readUint16():this.version===3&&(this.item_ID=o.readUint32()),this.item_protection_index=o.readUint16(),this.item_type=o.readString(4),this.item_name=o.readCString(),this.item_type==="mime"?(this.content_type=o.readCString(),this.content_encoding=o.readCString()):this.item_type==="uri "&&(this.item_uri_type=o.readCString()))}},It.fourcc="infe",It),Mt,iinfBox=(Mt=class extends FullBox{constructor(){super(...arguments),this.box_name="ItemInfoBox"}parse(o){this.parseFullHeader(o),this.version===0?this.entry_count=o.readUint16():this.entry_count=o.readUint32(),this.item_infos=[];for(let l=0;l<this.entry_count;l++){const n=parseOneBox(o,!1,this.size-(o.getPosition()-this.start));if(n.code===OK){const r=n.box;r.type==="infe"?this.item_infos[l]=r:Log.error("BoxParser","Expected 'infe' box, got "+n.box.type,o.isofile)}else return}}},Mt.fourcc="iinf",Mt),_t,ilocBox=(_t=class extends FullBox{constructor(){super(...arguments),this.box_name="ItemLocationBox"}parse(o){this.parseFullHeader(o);let l;l=o.readUint8(),this.offset_size=l>>4&15,this.length_size=l&15,l=o.readUint8(),this.base_offset_size=l>>4&15,this.version===1||this.version===2?this.index_size=l&15:this.index_size=0,this.items=[];let n=0;if(this.version<2)n=o.readUint16();else if(this.version===2)n=o.readUint32();else throw new Error("version of iloc box not supported");for(let r=0;r<n;r++){let t=0,e=0,i=0;if(this.version<2)t=o.readUint16();else if(this.version===2)t=o.readUint32();else throw new Error("version of iloc box not supported");this.version===1||this.version===2?e=o.readUint16()&15:e=0;const a=o.readUint16();switch(this.base_offset_size){case 0:i=0;break;case 4:i=o.readUint32();break;case 8:i=o.readUint64();break;default:throw new Error("Error reading base offset size")}const s=[],d=o.readUint16();for(let c=0;c<d;c++){let F=0,B=0,S=0;if(this.version===1||this.version===2)switch(this.index_size){case 0:F=0;break;case 4:F=o.readUint32();break;case 8:F=o.readUint64();break;default:throw new Error("Error reading extent index")}switch(this.offset_size){case 0:B=0;break;case 4:B=o.readUint32();break;case 8:B=o.readUint64();break;default:throw new Error("Error reading extent index")}switch(this.length_size){case 0:S=0;break;case 4:S=o.readUint32();break;case 8:S=o.readUint64();break;default:throw new Error("Error reading extent index")}s.push({extent_index:F,extent_length:S,extent_offset:B})}this.items.push({base_offset:i,construction_method:e,item_ID:t,data_reference_index:a,extents:s})}}},_t.fourcc="iloc",_t),REFERENCE_TYPE_NAMES={auxl:"Auxiliary image item",base:"Pre-derived image item base",cdsc:"Item describes referenced item",dimg:"Derived image item",dpnd:"Item coding dependency",eroi:"Region",evir:"EVC slice",exbl:"Scalable image item","fdl ":"File delivery",font:"Font item",iloc:"Item data location",mask:"Region mask",mint:"Data integrity",pred:"Predictively coded item",prem:"Pre-multiplied item",tbas:"HEVC tile track base item",text:"Text item",thmb:"Thumbnail image item"},x,irefBox=(x=class extends FullBox{constructor(){super(...arguments),this.box_name="ItemReferenceBox",this.references=[]}parse(o){for(this.parseFullHeader(o),this.references=[];o.getPosition()<this.start+this.size;){const l=parseOneBox(o,!0,this.size-(o.getPosition()-this.start));if(l.code===OK){let n="Unknown item reference";x.allowed_types.includes(l.type)?n=REFERENCE_TYPE_NAMES[l.type]:Log.warn("BoxParser",`Unknown item reference type: '${l.type}'`);const r=this.version===0?new SingleItemTypeReferenceBox(l.type,l.size,n,l.hdr_size,l.start):new SingleItemTypeReferenceBoxLarge(l.type,l.size,n,l.hdr_size,l.start);r.write===Box.prototype.write&&r.type!=="mdat"&&(Log.warn("BoxParser",r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(o)),r.parse(o),this.references.push(r)}else return}}},x.fourcc="iref",x.allowed_types=["auxl","base","cdsc","dimg","dpnd","eroi","evir","exbl","fdl ","font","iloc","mask","mint","pred","prem","tbas","text","thmb"],x),Pt,pitmBox=(Pt=class extends FullBox{constructor(){super(...arguments),this.box_name="PrimaryItemBox"}parse(o){this.parseFullHeader(o),this.version===0?this.item_id=o.readUint16():this.item_id=o.readUint32()}},Pt.fourcc="pitm",Pt),$t,metaBox=($t=class extends FullBox{constructor(){super(...arguments),this.box_name="MetaBox",this.isQT=!1}parse(o){const l=o.getPosition();if(this.size>8){switch(o.readUint32(),o.readString(4)){case"hdlr":case"mhdr":case"keys":case"ilst":case"ctry":case"lang":this.isQT=!0;break}o.seek(l)}this.isQT||this.parseFullHeader(o),ContainerBox.prototype.parse.call(this,o)}},$t.fourcc="meta",$t),Lt,mfhdBox=(Lt=class extends FullBox{constructor(){super(...arguments),this.box_name="MovieFragmentHeaderBox"}parse(o){this.parseFullHeader(o),this.sequence_number=o.readUint32()}write(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.sequence_number)}},Lt.fourcc="mfhd",Lt),At,mvhdBox=(At=class extends FullBox{constructor(){super(...arguments),this.box_name="MovieHeaderBox"}parse(o){this.parseFullHeader(o),this.version===1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.timescale=o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.timescale=o.readUint32(),this.duration=o.readUint32()),this.rate=o.readUint32(),this.volume=o.readUint16()>>8,o.readUint16(),o.readUint32Array(2),this.matrix=o.readInt32Array(9),o.readUint32Array(6),this.next_track_id=o.readUint32()}write(o){const l=this.modification_time>MAX_UINT32||this.creation_time>MAX_UINT32||this.duration>MAX_UINT32||this.version===1;this.version=l?1:0,this.size=4*4+20*4,this.size+=l?3*4:0,this.flags=0,this.writeHeader(o),l?(o.writeUint64(this.creation_time),o.writeUint64(this.modification_time),o.writeUint32(this.timescale),o.writeUint64(this.duration)):(o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.timescale),o.writeUint32(this.duration)),o.writeUint32(this.rate),o.writeUint16(this.volume<<8),o.writeUint16(0),o.writeUint32(0),o.writeUint32(0),o.writeInt32Array(this.matrix),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(this.next_track_id)}print(o){super.printHeader(o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"timescale: "+this.timescale),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"rate: "+this.rate),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"next_track_id: "+this.next_track_id)}},At.fourcc="mvhd",At),Gt,mettSampleEntry=(Gt=class extends MetadataSampleEntry{parse(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}},Gt.fourcc="mett",Gt),Ht,metxSampleEntry=(Ht=class extends MetadataSampleEntry{parse(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.namespace=o.readCString(),this.schema_location=o.readCString(),this.parseFooter(o)}},Ht.fourcc="metx",Ht),zt,av1CBox=(zt=class extends Box{constructor(){super(...arguments),this.box_name="AV1CodecConfigurationBox"}parse(o){let l=o.readUint8();if((l>>7&1)!==1){Log.error("BoxParser","av1C marker problem",o.isofile);return}if(this.version=l&127,this.version!==1){Log.error("BoxParser","av1C version "+this.version+" not supported",o.isofile);return}if(l=o.readUint8(),this.seq_profile=l>>5&7,this.seq_level_idx_0=l&31,l=o.readUint8(),this.seq_tier_0=l>>7&1,this.high_bitdepth=l>>6&1,this.twelve_bit=l>>5&1,this.monochrome=l>>4&1,this.chroma_subsampling_x=l>>3&1,this.chroma_subsampling_y=l>>2&1,this.chroma_sample_position=l&3,l=o.readUint8(),this.reserved_1=l>>5&7,this.reserved_1!==0){Log.error("BoxParser","av1C reserved_1 parsing problem",o.isofile);return}if(this.initial_presentation_delay_present=l>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=l&15;else if(this.reserved_2=l&15,this.reserved_2!==0){Log.error("BoxParser","av1C reserved_2 parsing problem",o.isofile);return}const n=this.size-this.hdr_size-4;this.configOBUs=o.readUint8Array(n)}},zt.fourcc="av1C",zt),Yt,esdsBox=(Yt=class extends FullBox{constructor(){super(...arguments),this.box_name="ElementaryStreamDescriptorBox"}parse(o){this.parseFullHeader(o);const l=o.readUint8Array(this.size-this.hdr_size);if("MPEG4DescriptorParser"in DescriptorRegistry){const n=new DescriptorRegistry.MPEG4DescriptorParser;this.esd=n.parseOneDescriptor(new DataStream(l.buffer,0))}}},Yt.fourcc="esds",Yt),jt,vpcCBox=(jt=class extends FullBox{constructor(){super(...arguments),this.box_name="VPCodecConfigurationRecord"}parse(o){if(this.parseFullHeader(o),this.version===1){this.profile=o.readUint8(),this.level=o.readUint8();const l=o.readUint8();this.bitDepth=l>>4,this.chromaSubsampling=l>>1&7,this.videoFullRangeFlag=l&1,this.colourPrimaries=o.readUint8(),this.transferCharacteristics=o.readUint8(),this.matrixCoefficients=o.readUint8(),this.codecIntializationDataSize=o.readUint16(),this.codecIntializationData=o.readUint8Array(this.codecIntializationDataSize)}else{this.profile=o.readUint8(),this.level=o.readUint8();let l=o.readUint8();this.bitDepth=l>>4&15,this.colorSpace=l&15,l=o.readUint8(),this.chromaSubsampling=l>>4&15,this.transferFunction=l>>1&7,this.videoFullRangeFlag=l&1,this.codecIntializationDataSize=o.readUint16(),this.codecIntializationData=o.readUint8Array(this.codecIntializationDataSize)}}},jt.fourcc="vpcC",jt),Xt,vvcCBox=(Xt=class extends FullBox{constructor(){super(...arguments),this.box_name="VvcConfigurationBox"}parse(o){this.parseFullHeader(o);const l={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(e){this.held_bits=e.readUint8(),this.num_held_bits=1*8},stream_read_2_bytes:function(e){this.held_bits=e.readUint16(),this.num_held_bits=2*8},extract_bits:function(e){const i=this.held_bits>>this.num_held_bits-e&(1<<e)-1;return this.num_held_bits-=e,i}};if(l.stream_read_1_bytes(o),l.extract_bits(5),this.lengthSizeMinusOne=l.extract_bits(2),this.ptl_present_flag=l.extract_bits(1),this.ptl_present_flag){l.stream_read_2_bytes(o),this.ols_idx=l.extract_bits(9),this.num_sublayers=l.extract_bits(3),this.constant_frame_rate=l.extract_bits(2),this.chroma_format_idc=l.extract_bits(2),l.stream_read_1_bytes(o),this.bit_depth_minus8=l.extract_bits(3),l.extract_bits(5);{if(l.stream_read_2_bytes(o),l.extract_bits(2),this.num_bytes_constraint_info=l.extract_bits(6),this.general_profile_idc=l.extract_bits(7),this.general_tier_flag=l.extract_bits(1),this.general_level_idc=o.readUint8(),l.stream_read_1_bytes(o),this.ptl_frame_only_constraint_flag=l.extract_bits(1),this.ptl_multilayer_enabled_flag=l.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(let e=0;e<this.num_bytes_constraint_info-1;e++){const i=l.extract_bits(6);l.stream_read_1_bytes(o);const a=l.extract_bits(2);this.general_constraint_info[e]=i<<2|a}this.general_constraint_info[this.num_bytes_constraint_info-1]=l.extract_bits(6)}else l.extract_bits(6);if(this.num_sublayers>1){l.stream_read_1_bytes(o),this.ptl_sublayer_present_mask=0;for(let e=this.num_sublayers-2;e>=0;--e){const i=l.extract_bits(1);this.ptl_sublayer_present_mask|=i<<e}for(let e=this.num_sublayers;e<=8&&this.num_sublayers>1;++e)l.extract_bits(1);this.sublayer_level_idc=[];for(let e=this.num_sublayers-2;e>=0;--e)this.ptl_sublayer_present_mask&1<<e&&(this.sublayer_level_idc[e]=o.readUint8())}if(this.ptl_num_sub_profiles=o.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(let e=0;e<this.ptl_num_sub_profiles;e++)this.general_sub_profile_idc.push(o.readUint32())}this.max_picture_width=o.readUint16(),this.max_picture_height=o.readUint16(),this.avg_frame_rate=o.readUint16()}const n=12,r=13;this.nalu_arrays=[];const t=o.readUint8();for(let e=0;e<t;e++){const i=[];this.nalu_arrays.push(i),l.stream_read_1_bytes(o),i.completeness=l.extract_bits(1),l.extract_bits(2),i.nalu_type=l.extract_bits(5);let a=1;i.nalu_type!==r&&i.nalu_type!==n&&(a=o.readUint16());for(let s=0;s<a;s++){const d=o.readUint16();i.push({data:o.readUint8Array(d),length:d})}}}},Xt.fourcc="vvcC",Xt),qt,colrBox=(qt=class extends Box{constructor(){super(...arguments),this.box_name="ColourInformationBox"}parse(o){if(this.colour_type=o.readString(4),this.colour_type==="nclx"){this.colour_primaries=o.readUint16(),this.transfer_characteristics=o.readUint16(),this.matrix_coefficients=o.readUint16();const l=o.readUint8();this.full_range_flag=l>>7}else this.colour_type==="rICC"?this.ICC_profile=o.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=o.readUint8Array(this.size-4))}},qt.fourcc="colr",qt);function decimalToHex(u,o){let l=Number(u).toString(16);for(o=typeof o>"u"?2:o;l.length<o;)l="0"+l;return l}var avcCSampleEntryBase=class extends VisualSampleEntry{getCodec(){const u=super.getCodec();return this.avcC?`${u}.${decimalToHex(this.avcC.AVCProfileIndication)}${decimalToHex(this.avcC.profile_compatibility)}${decimalToHex(this.avcC.AVCLevelIndication)}`:u}},Kt,avc1SampleEntry=(Kt=class extends avcCSampleEntryBase{constructor(){super(...arguments),this.box_name="AVCSampleEntry"}},Kt.fourcc="avc1",Kt),te,avc2SampleEntry=(te=class extends avcCSampleEntryBase{constructor(){super(...arguments),this.box_name="AVC2SampleEntry"}},te.fourcc="avc2",te),ee,avc3SampleEntry=(ee=class extends avcCSampleEntryBase{constructor(){super(...arguments),this.box_name="AVCSampleEntry"}},ee.fourcc="avc3",ee),ne,avc4SampleEntry=(ne=class extends avcCSampleEntryBase{constructor(){super(...arguments),this.box_name="AVC2SampleEntry"}},ne.fourcc="avc4",ne),ie,av01SampleEntry=(ie=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="AV1SampleEntry"}getCodec(){const o=super.getCodec(),l=this.av1C.seq_level_idx_0,n=l<10?"0"+l:l;let r;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?r=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(r=this.av1C.high_bitdepth===1?"10":"08"),o+"."+this.av1C.seq_profile+"."+n+(this.av1C.seq_tier_0?"H":"M")+"."+r}},ie.fourcc="av01",ie),oe,dav1SampleEntry=(oe=class extends VisualSampleEntry{},oe.fourcc="dav1",oe),hvcCSampleEntryBase=class extends VisualSampleEntry{getCodec(){let u=super.getCodec();if(this.hvcC){switch(u+=".",this.hvcC.general_profile_space){case 0:u+="";break;case 1:u+="A";break;case 2:u+="B";break;case 3:u+="C";break}u+=this.hvcC.general_profile_idc,u+=".";let o=this.hvcC.general_profile_compatibility,l=0;for(let t=0;t<32&&(l|=o&1,t!==31);t++)l<<=1,o>>=1;u+=decimalToHex(l,0),u+=".",this.hvcC.general_tier_flag===0?u+="L":u+="H",u+=this.hvcC.general_level_idc;let n=!1,r="";for(let t=5;t>=0;t--)(this.hvcC.general_constraint_indicator[t]||n)&&(r="."+decimalToHex(this.hvcC.general_constraint_indicator[t],0)+r,n=!0);u+=r}return u}},re,hvc1SampleEntry=(re=class extends hvcCSampleEntryBase{constructor(){super(...arguments),this.box_name="HEVCSampleEntry"}},re.fourcc="hvc1",re),le,hvc2SampleEntry=(le=class extends hvcCSampleEntryBase{},le.fourcc="hvc2",le),ae,hev1SampleEntry=(ae=class extends hvcCSampleEntryBase{constructor(){super(...arguments),this.box_name="HEVCSampleEntry",this.colrs=[],this.subBoxNames=["colr"]}},ae.fourcc="hev1",ae),se,hev2SampleEntry=(se=class extends hvcCSampleEntryBase{},se.fourcc="hev2",se),de,hvt1SampleEntry=(de=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="HEVCTileSampleSampleEntry"}},de.fourcc="hvt1",de),ue,lhe1SampleEntry=(ue=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="LHEVCSampleEntry"}},ue.fourcc="lhe1",ue),ce,lhv1SampleEntry=(ce=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="LHEVCSampleEntry"}},ce.fourcc="lhv1",ce),Ue,dvh1SampleEntry=(Ue=class extends VisualSampleEntry{},Ue.fourcc="dvh1",Ue),Fe,dvheSampleEntry=(Fe=class extends VisualSampleEntry{},Fe.fourcc="dvhe",Fe),vvcCSampleEntryBase=class extends VisualSampleEntry{getCodec(){let u=super.getCodec();if(this.vvcC){u+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?u+=".H":u+=".L",u+=this.vvcC.general_level_idc;let o="";if(this.vvcC.general_constraint_info){const l=[];let n=0;n|=this.vvcC.ptl_frame_only_constraint_flag<<7,n|=this.vvcC.ptl_multilayer_enabled_flag<<6;let r;for(let t=0;t<this.vvcC.general_constraint_info.length;++t)n|=this.vvcC.general_constraint_info[t]>>2&63,l.push(n),n&&(r=t),n=this.vvcC.general_constraint_info[t]>>2&3;if(r===void 0)o=".CA";else{o=".C";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";let e=0,i=0;for(let a=0;a<=r;++a)for(e=e<<8|l[a],i+=8;i>=5;){const s=e>>i-5&31;o+=t[s],i-=5,e&=(1<<i)-1}i&&(e<<=5-i,o+=t[e&31])}}u+=o}return u}},Qe,vvc1SampleEntry=(Qe=class extends vvcCSampleEntryBase{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}},Qe.fourcc="vvc1",Qe),pe,vvi1SampleEntry=(pe=class extends vvcCSampleEntryBase{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}},pe.fourcc="vvi1",pe),fe,vvs1SampleEntry=(fe=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}},fe.fourcc="vvs1",fe),he,vvcNSampleEntry=(he=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="VvcNonVCLSampleEntry"}},he.fourcc="vvcN",he),vpcCSampleEntryBase=class extends VisualSampleEntry{getCodec(){const u=super.getCodec();let o=this.vpcC.level;o===0&&(o="00");let l=this.vpcC.bitDepth;return l===8&&(l="08"),`${u}.0${this.vpcC.profile}.${o}.${l}`}},Re,vp08SampleEntry=(Re=class extends vpcCSampleEntryBase{},Re.fourcc="vp08",Re),Be,vp09SampleEntry=(Be=class extends vpcCSampleEntryBase{},Be.fourcc="vp09",Be),Se,avs3SampleEntry=(Se=class extends VisualSampleEntry{},Se.fourcc="avs3",Se),ye,j2kiSampleEntry=(ye=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="J2KSampleEntry"}},ye.fourcc="j2ki",ye),Ve,mjp2SampleEntry=(Ve=class extends VisualSampleEntry{},Ve.fourcc="mjp2",Ve),Je,mjpgSampleEntry=(Je=class extends VisualSampleEntry{},Je.fourcc="mjpg",Je),Ee,uncvSampleEntry=(Ee=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="UncompressedVideoSampleEntry"}},Ee.fourcc="uncv",Ee),me,mp4vSampleEntry=(me=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="MP4VisualSampleEntry"}},me.fourcc="mp4v",me),ke,mp4aSampleEntry=(ke=class extends AudioSampleEntry{constructor(){super(...arguments),this.box_name="MP4AudioSampleEntry"}getCodec(){const o=super.getCodec();if(this.esds&&this.esds.esd){const l=this.esds.esd.getOTI(),n=this.esds.esd.getAudioConfig();return o+"."+decimalToHex(l)+(n?"."+n:"")}else return o}},ke.fourcc="mp4a",ke),Ne,m4aeSampleEntry=(Ne=class extends AudioSampleEntry{},Ne.fourcc="m4ae",Ne),Te,ac_3SampleEntry=(Te=class extends AudioSampleEntry{},Te.fourcc="ac-3",Te),ve,ac_4SampleEntry=(ve=class extends AudioSampleEntry{},ve.fourcc="ac-4",ve),Ce,ec_3SampleEntry=(Ce=class extends AudioSampleEntry{},Ce.fourcc="ec-3",Ce),We,OpusSampleEntry=(We=class extends AudioSampleEntry{},We.fourcc="Opus",We),be,mha1SampleEntry=(be=class extends AudioSampleEntry{},be.fourcc="mha1",be),Oe,mha2SampleEntry=(Oe=class extends AudioSampleEntry{},Oe.fourcc="mha2",Oe),Ze,mhm1SampleEntry=(Ze=class extends AudioSampleEntry{},Ze.fourcc="mhm1",Ze),De,mhm2SampleEntry=(De=class extends AudioSampleEntry{},De.fourcc="mhm2",De),we,fLaCSampleEntry=(we=class extends AudioSampleEntry{},we.fourcc="fLaC",we),ge,encvSampleEntry=(ge=class extends VisualSampleEntry{},ge.fourcc="encv",ge),xe,encaSampleEntry=(xe=class extends AudioSampleEntry{},xe.fourcc="enca",xe),Ie,encuSampleEntry=(Ie=class extends SubtitleSampleEntry{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Ie.fourcc="encu",Ie),Me,encsSampleEntry=(Me=class extends SystemSampleEntry{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Me.fourcc="encs",Me),_e,mp4sSampleEntry=(_e=class extends SystemSampleEntry{},_e.fourcc="mp4s",_e),Pe,enctSampleEntry=(Pe=class extends TextSampleEntry{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Pe.fourcc="enct",Pe),$e,encmSampleEntry=($e=class extends MetadataSampleEntry{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},$e.fourcc="encm",$e),Le,resvSampleEntry=(Le=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="RestrictedVideoSampleEntry"}},Le.fourcc="resv",Le),Ae,sbttSampleEntry=(Ae=class extends SubtitleSampleEntry{parse(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}},Ae.fourcc="sbtt",Ae),Ge,stppSampleEntry=(Ge=class extends SubtitleSampleEntry{parse(o){this.parseHeader(o),this.namespace=o.readCString(),this.schema_location=o.readCString(),this.auxiliary_mime_types=o.readCString(),this.parseFooter(o)}write(o){this.writeHeader(o),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,o.writeCString(this.namespace),o.writeCString(this.schema_location),o.writeCString(this.auxiliary_mime_types),this.writeFooter(o)}},Ge.fourcc="stpp",Ge),He,stxtSampleEntry=(He=class extends SubtitleSampleEntry{parse(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}getCodec(){const o=super.getCodec();return this.mime_format?o+"."+this.mime_format:o}},He.fourcc="stxt",He),ze,tx3gSampleEntry=(ze=class extends SubtitleSampleEntry{parse(o){this.parseHeader(o),this.displayFlags=o.readUint32(),this.horizontal_justification=o.readInt8(),this.vertical_justification=o.readInt8(),this.bg_color_rgba=o.readUint8Array(4),this.box_record=o.readInt16Array(4),this.style_record=o.readUint8Array(12),this.parseFooter(o)}},ze.fourcc="tx3g",ze),Ye,wvttSampleEntry=(Ye=class extends MetadataSampleEntry{parse(o){this.parseHeader(o),this.parseFooter(o)}},Ye.fourcc="wvtt",Ye),je,sbgpBox=(je=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleToGroupBox"}parse(o){this.parseFullHeader(o),this.grouping_type=o.readString(4),this.version===1?this.grouping_type_parameter=o.readUint32():this.grouping_type_parameter=0,this.entries=[];const l=o.readUint32();for(let n=0;n<l;n++)this.entries.push({sample_count:o.readInt32(),group_description_index:o.readInt32()})}write(o){this.grouping_type_parameter?this.version=1:this.version=0,this.flags=0,this.size=8+8*this.entries.length+(this.version===1?4:0),this.writeHeader(o),o.writeString(this.grouping_type,void 0,4),this.version===1&&o.writeUint32(this.grouping_type_parameter),o.writeUint32(this.entries.length);for(let l=0;l<this.entries.length;l++){const n=this.entries[l];o.writeInt32(n.sample_count),o.writeInt32(n.group_description_index)}}},je.fourcc="sbgp",je),Xe,sdtpBox=(Xe=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleDependencyTypeBox"}parse(o){this.parseFullHeader(o);const l=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(let n=0;n<l;n++){const r=o.readUint8();this.is_leading[n]=r>>6,this.sample_depends_on[n]=r>>4&3,this.sample_is_depended_on[n]=r>>2&3,this.sample_has_redundancy[n]=r&3}}},Xe.fourcc="sdtp",Xe),qe,sgpdBox=(qe=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleGroupDescriptionBox"}parse(o){this.parseFullHeader(o),this.grouping_type=o.readString(4),Log.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=o.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=o.readUint32()),this.entries=[];const l=o.readUint32();for(let n=0;n<l;n++){let r;this.grouping_type in BoxRegistry.sampleGroupEntry?r=new BoxRegistry.sampleGroupEntry[this.grouping_type](this.grouping_type):r=new SampleGroupEntry(this.grouping_type),this.entries.push(r),this.version===1?this.default_length===0?r.description_length=o.readUint32():r.description_length=this.default_length:r.description_length=this.default_length,r.write===SampleGroupEntry.prototype.write&&(Log.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),r.data=o.readUint8Array(r.description_length),o.seek(o.getPosition()-r.description_length)),r.parse(o)}}write(o){this.flags=0,this.size=12;for(let l=0;l<this.entries.length;l++){const n=this.entries[l];this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=n.data.length)}this.writeHeader(o),o.writeString(this.grouping_type,void 0,4),this.version===1&&o.writeUint32(this.default_length),this.version>=2&&o.writeUint32(this.default_sample_description_index),o.writeUint32(this.entries.length);for(let l=0;l<this.entries.length;l++){const n=this.entries[l];this.version===1&&this.default_length===0&&o.writeUint32(n.description_length),n.write(o)}}},qe.fourcc="sgpd",qe),Ke,sidxBox=(Ke=class extends FullBox{constructor(){super(...arguments),this.box_name="CompressedSegmentIndexBox"}parse(o){this.parseFullHeader(o),this.reference_ID=o.readUint32(),this.timescale=o.readUint32(),this.version===0?(this.earliest_presentation_time=o.readUint32(),this.first_offset=o.readUint32()):(this.earliest_presentation_time=o.readUint64(),this.first_offset=o.readUint64()),o.readUint16(),this.references=[];const l=o.readUint16();for(let n=0;n<l;n++){const r=o.readUint32(),t=o.readUint32(),e=o.readUint32();this.references.push({reference_type:r>>31&1,referenced_size:r&2147483647,subsegment_duration:t,starts_with_SAP:e>>31&1,SAP_type:e>>28&7,SAP_delta_time:e&268435455})}}write(o){const l=this.earliest_presentation_time>MAX_UINT32||this.first_offset>MAX_UINT32||this.version===1;this.version=l?1:0,this.size=4*2+2+2+12*this.references.length,this.size+=l?16:8,this.flags=0,this.writeHeader(o),o.writeUint32(this.reference_ID),o.writeUint32(this.timescale),l?(o.writeUint64(this.earliest_presentation_time),o.writeUint64(this.first_offset)):(o.writeUint32(this.earliest_presentation_time),o.writeUint32(this.first_offset)),o.writeUint16(0),o.writeUint16(this.references.length);for(let n=0;n<this.references.length;n++){const r=this.references[n];o.writeUint32(r.reference_type<<31|r.referenced_size),o.writeUint32(r.subsegment_duration),o.writeUint32(r.starts_with_SAP<<31|r.SAP_type<<28|r.SAP_delta_time)}}},Ke.fourcc="sidx",Ke),tn,smhdBox=(tn=class extends FullBox{constructor(){super(...arguments),this.box_name="SoundMediaHeaderBox"}parse(o){this.parseFullHeader(o),this.balance=o.readUint16(),o.readUint16()}write(o){this.version=0,this.size=4,this.writeHeader(o),o.writeUint16(this.balance),o.writeUint16(0)}},tn.fourcc="smhd",tn),en,stcoBox=(en=class extends FullBox{constructor(){super(...arguments),this.box_name="ChunkOffsetBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.chunk_offsets=[],this.version===0)for(let n=0;n<l;n++)this.chunk_offsets.push(o.readUint32())}write(o){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(o),o.writeUint32(this.chunk_offsets.length),o.writeUint32Array(this.chunk_offsets)}unpack(o){for(let l=0;l<this.chunk_offsets.length;l++)o[l].offset=this.chunk_offsets[l]}},en.fourcc="stco",en),nn,sthdBox=(nn=class extends FullBox{constructor(){super(...arguments),this.box_name="SubtitleMediaHeaderBox"}},nn.fourcc="sthd",nn),on,stscBox=(on=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleToChunkBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(let n=0;n<l;n++)this.first_chunk.push(o.readUint32()),this.samples_per_chunk.push(o.readUint32()),this.sample_description_index.push(o.readUint32())}write(o){this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(o),o.writeUint32(this.first_chunk.length);for(let l=0;l<this.first_chunk.length;l++)o.writeUint32(this.first_chunk[l]),o.writeUint32(this.samples_per_chunk[l]),o.writeUint32(this.sample_description_index[l])}unpack(o){let l=0,n=0;for(let r=0;r<this.first_chunk.length;r++)for(let t=0;t<(r+1<this.first_chunk.length?this.first_chunk[r+1]:1/0);t++){n++;for(let e=0;e<this.samples_per_chunk[r];e++){if(o[l])o[l].description_index=this.sample_description_index[r],o[l].chunk_index=n;else return;l++}}}},on.fourcc="stsc",on),rn,stsdBox=(rn=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleDescriptionBox"}parse(o){this.parseFullHeader(o),this.entries=[];const l=o.readUint32();for(let n=1;n<=l;n++){const r=parseOneBox(o,!0,this.size-(o.getPosition()-this.start));if(r.code===OK){let t;r.type in BoxRegistry.sampleEntry?(t=new BoxRegistry.sampleEntry[r.type](r.size),t.hdr_size=r.hdr_size,t.start=r.start):(Log.warn("BoxParser",`Unknown sample entry type: '${r.type}'`),t=new SampleEntry(r.size,r.hdr_size,r.start),t.type=r.type),t.write===SampleEntry.prototype.write&&(Log.info("BoxParser","SampleEntry "+t.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),t.parseDataAndRewind(o)),t.parse(o),this.entries.push(t)}else return}}write(o){this.version=0,this.flags=0,this.size=0,this.writeHeader(o),o.writeUint32(this.entries.length),this.size+=4;for(let l=0;l<this.entries.length;l++)this.entries[l].write(o),this.size+=this.entries[l].size;Log.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)}},rn.fourcc="stsd",rn),ln,stszBox=(ln=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleSizeBox"}parse(o){if(this.parseFullHeader(o),this.sample_sizes=[],this.version===0){this.sample_size=o.readUint32(),this.sample_count=o.readUint32();for(let l=0;l<this.sample_count;l++)this.sample_size===0?this.sample_sizes.push(o.readUint32()):this.sample_sizes[l]=this.sample_size}}write(o){let l=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0){let n=0;for(;n+1<this.sample_sizes.length;)if(this.sample_sizes[n+1]!==this.sample_sizes[0]){l=!1;break}else n++}else l=!1;this.size=8,l||(this.size+=4*this.sample_sizes.length),this.writeHeader(o),l?o.writeUint32(this.sample_sizes[0]):o.writeUint32(0),o.writeUint32(this.sample_sizes.length),l||o.writeUint32Array(this.sample_sizes)}unpack(o){for(let l=0;l<this.sample_sizes.length;l++)o[l].size=this.sample_sizes[l]}},ln.fourcc="stsz",ln),an,sttsBox=(an=class extends FullBox{constructor(){super(...arguments),this.box_name="TimeToSampleBox",this.sample_counts=[],this.sample_deltas=[]}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.sample_counts.length=0,this.sample_deltas.length=0,this.version===0)for(let n=0;n<l;n++){this.sample_counts.push(o.readUint32());let r=o.readInt32();r<0&&(Log.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),r=1),this.sample_deltas.push(r)}}write(o){this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(o),o.writeUint32(this.sample_counts.length);for(let l=0;l<this.sample_counts.length;l++)o.writeUint32(this.sample_counts[l]),o.writeUint32(this.sample_deltas[l])}unpack(o){let l=0;for(let n=0;n<this.sample_counts.length;n++)for(let r=0;r<this.sample_counts[n];r++)l===0?o[l].dts=0:o[l].dts=o[l-1].dts+this.sample_deltas[n],l++}},an.fourcc="stts",an),sn,tfdtBox=(sn=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackFragmentBaseMediaDecodeTimeBox"}parse(o){this.parseFullHeader(o),this.version===1?this.baseMediaDecodeTime=o.readUint64():this.baseMediaDecodeTime=o.readUint32()}write(o){const l=this.baseMediaDecodeTime>MAX_UINT32||this.version===1;this.version=l?1:0,this.size=4,this.size+=l?4:0,this.flags=0,this.writeHeader(o),l?o.writeUint64(this.baseMediaDecodeTime):o.writeUint32(this.baseMediaDecodeTime)}},sn.fourcc="tfdt",sn),dn,tfhdBox=(dn=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackFragmentHeaderBox"}parse(o){this.parseFullHeader(o);let l=0;this.track_id=o.readUint32(),this.size-this.hdr_size>l&&this.flags&TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=o.readUint64(),l+=8):this.base_data_offset=0,this.size-this.hdr_size>l&&this.flags&TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=o.readUint32(),l+=4):this.default_sample_description_index=0,this.size-this.hdr_size>l&&this.flags&TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=o.readUint32(),l+=4):this.default_sample_duration=0,this.size-this.hdr_size>l&&this.flags&TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=o.readUint32(),l+=4):this.default_sample_size=0,this.size-this.hdr_size>l&&this.flags&TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=o.readUint32(),l+=4):this.default_sample_flags=0}write(o){this.version=0,this.size=4,this.flags&TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(o),o.writeUint32(this.track_id),this.flags&TFHD_FLAG_BASE_DATA_OFFSET&&o.writeUint64(this.base_data_offset),this.flags&TFHD_FLAG_SAMPLE_DESC&&o.writeUint32(this.default_sample_description_index),this.flags&TFHD_FLAG_SAMPLE_DUR&&o.writeUint32(this.default_sample_duration),this.flags&TFHD_FLAG_SAMPLE_SIZE&&o.writeUint32(this.default_sample_size),this.flags&TFHD_FLAG_SAMPLE_FLAGS&&o.writeUint32(this.default_sample_flags)}},dn.fourcc="tfhd",dn),un,tkhdBox=(un=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackHeaderBox",this.layer=0,this.alternate_group=0}parse(o){this.parseFullHeader(o),this.version===1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.track_id=o.readUint32(),o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.track_id=o.readUint32(),o.readUint32(),this.duration=o.readUint32()),o.readUint32Array(2),this.layer=o.readInt16(),this.alternate_group=o.readInt16(),this.volume=o.readInt16()>>8,o.readUint16(),this.matrix=o.readInt32Array(9),this.width=o.readUint32(),this.height=o.readUint32()}write(o){const l=this.modification_time>MAX_UINT32||this.creation_time>MAX_UINT32||this.duration>MAX_UINT32||this.version===1;this.version=l?1:0,this.size=5*4+15*4,this.size+=l?3*4:0,this.flags=this.flags??3,this.writeHeader(o),l?(o.writeUint64(this.creation_time),o.writeUint64(this.modification_time),o.writeUint32(this.track_id),o.writeUint32(0),o.writeUint64(this.duration)):(o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.track_id),o.writeUint32(0),o.writeUint32(this.duration)),o.writeUint32Array([0,0]),o.writeInt16(this.layer),o.writeInt16(this.alternate_group),o.writeInt16(this.volume<<8),o.writeInt16(0),o.writeInt32Array(this.matrix),o.writeUint32(this.width),o.writeUint32(this.height)}print(o){super.printHeader(o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"track_id: "+this.track_id),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"layer: "+this.layer),o.log(o.indent+"alternate_group: "+this.alternate_group),o.log(o.indent+"width: "+this.width),o.log(o.indent+"height: "+this.height)}},un.fourcc="tkhd",un),cn,trexBox=(cn=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackExtendsBox"}parse(o){this.parseFullHeader(o),this.track_id=o.readUint32(),this.default_sample_description_index=o.readUint32(),this.default_sample_duration=o.readUint32(),this.default_sample_size=o.readUint32(),this.default_sample_flags=o.readUint32()}write(o){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(o),o.writeUint32(this.track_id),o.writeUint32(this.default_sample_description_index),o.writeUint32(this.default_sample_duration),o.writeUint32(this.default_sample_size),o.writeUint32(this.default_sample_flags)}},cn.fourcc="trex",cn),Un,trunBox=(Un=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackRunBox",this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[]}parse(o){this.parseFullHeader(o);let l=0;if(this.sample_count=o.readUint32(),l+=4,this.size-this.hdr_size>l&&this.flags&TRUN_FLAGS_DATA_OFFSET?(this.data_offset=o.readInt32(),l+=4):this.data_offset=0,this.size-this.hdr_size>l&&this.flags&TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=o.readUint32(),l+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>l)for(let n=0;n<this.sample_count;n++)this.flags&TRUN_FLAGS_DURATION&&(this.sample_duration[n]=o.readUint32()),this.flags&TRUN_FLAGS_SIZE&&(this.sample_size[n]=o.readUint32()),this.flags&TRUN_FLAGS_FLAGS&&(this.sample_flags[n]=o.readUint32()),this.flags&TRUN_FLAGS_CTS_OFFSET&&(this.version===0?this.sample_composition_time_offset[n]=o.readUint32():this.sample_composition_time_offset[n]=o.readInt32())}write(o){this.size=4,this.flags&TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(o),o.writeUint32(this.sample_count),this.flags&TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=o.getPosition(),o.writeInt32(this.data_offset)),this.flags&TRUN_FLAGS_FIRST_FLAG&&o.writeUint32(this.first_sample_flags);for(let l=0;l<this.sample_count;l++)this.flags&TRUN_FLAGS_DURATION&&o.writeUint32(this.sample_duration[l]),this.flags&TRUN_FLAGS_SIZE&&o.writeUint32(this.sample_size[l]),this.flags&TRUN_FLAGS_FLAGS&&o.writeUint32(this.sample_flags[l]),this.flags&TRUN_FLAGS_CTS_OFFSET&&(this.version===0?o.writeUint32(this.sample_composition_time_offset[l]):o.writeInt32(this.sample_composition_time_offset[l]))}},Un.fourcc="trun",Un),Fn,urlBox=(Fn=class extends FullBox{constructor(){super(...arguments),this.box_name="DataEntryUrlBox"}parse(o){this.parseFullHeader(o),this.flags!==1&&(this.location=o.readCString())}write(o){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(o),this.location&&o.writeCString(this.location)}},Fn.fourcc="url ",Fn),Qn,vmhdBox=(Qn=class extends FullBox{constructor(){super(...arguments),this.box_name="VideoMediaHeaderBox"}parse(o){this.parseFullHeader(o),this.graphicsmode=o.readUint16(),this.opcolor=o.readUint16Array(3)}write(o){this.version=0,this.size=8,this.writeHeader(o),o.writeUint16(this.graphicsmode),o.writeUint16Array(this.opcolor)}},Qn.fourcc="vmhd",Qn),SampleGroupInfo=class{constructor(u,o,l){this.grouping_type=u,this.grouping_type_parameter=o,this.sbgp=l,this.last_sample_in_run=-1,this.entry_index=-1}},ISOFile=class w{constructor(o,l=!0){this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.moovStartSent=!1,this.readySent=!1,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.sidxSent=!1,this.items=[],this.entity_groups=[],this.itemsDataSize=0,this.lastMoofIndex=0,this.samplesDataSize=0,this.lastBoxStartPosition=0,this.nextParsePosition=0,this.discardMdatData=!0,this.discardMdatData=l,o?(this.stream=o,this.parse()):this.stream=new MultiBufferStream,this.stream.isofile=this}setSegmentOptions(o,l,n){const{sizePerSegment:r=Number.MAX_SAFE_INTEGER,rapAlignement:t=!0}=n;let e=n.nbSamples??n.nbSamplesPerFragment??1e3;const i=n.nbSamplesPerFragment??e;if(e<=0||i<=0||r<=0){Log.error("ISOFile",`Invalid segment options: nbSamples=${e}, nbSamplesPerFragment=${i}, sizePerSegment=${r}`);return}if(e<i&&(Log.warn("ISOFile",`nbSamples (${e}) is less than nbSamplesPerFragment (${i}), setting nbSamples to nbSamplesPerFragment`),e=i),this.fragmentedTracks.some(s=>s.nb_samples!==e)){Log.error("ISOFile",`Cannot set segment options for track ${o}: nbSamples (${e}) does not match existing tracks`);return}const a=this.getTrackById(o);if(a){const s={id:o,user:l,trak:a,segmentStream:void 0,nb_samples:e,nb_samples_per_fragment:i,size_per_segment:r,rapAlignement:t,state:{lastFragmentSampleNumber:0,lastSegmentSampleNumber:0,accumulatedSize:0}};this.fragmentedTracks.push(s),a.nextSample=0}this.discardMdatData&&Log.warn("ISOFile","Segmentation options set but discardMdatData is true, samples will not be segmented")}unsetSegmentOptions(o){let l=-1;for(let n=0;n<this.fragmentedTracks.length;n++)this.fragmentedTracks[n].id===o&&(l=n);l>-1&&this.fragmentedTracks.splice(l,1)}setExtractionOptions(o,l,{nbSamples:n=1e3}={}){const r=this.getTrackById(o);r&&(this.extractedTracks.push({id:o,user:l,trak:r,nb_samples:n,samples:[]}),r.nextSample=0),this.discardMdatData&&Log.warn("ISOFile","Extraction options set but discardMdatData is true, samples will not be extracted")}unsetExtractionOptions(o){let l=-1;for(let n=0;n<this.extractedTracks.length;n++)this.extractedTracks[n].id===o&&(l=n);l>-1&&this.extractedTracks.splice(l,1)}parse(){if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else{this.saveParsePosition&&this.saveParsePosition();const l=parseOneBox(this.stream,!1);if(l.code===ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(l))continue;return}else return;else if(l.code===OK){const n=l.box;if(this.boxes.push(n),n.type==="uuid")this[n.uuid]!==void 0&&Log.warn("ISOFile","Duplicate Box of uuid: "+n.uuid+", overriding previous occurrence"),this[n.uuid]=n;else switch(n.type){case"mdat":this.mdats.push(n),this.transferMdatData(n);break;case"moof":this.moofs.push(n);break;case"free":case"skip":break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[n.type]!==void 0?Array.isArray(this[n.type+"s"])?(Log.info("ISOFile",`Found multiple boxes of type ${n.type} in ISOFile, adding to array`),this[n.type+"s"].push(n)):(Log.warn("ISOFile",`Found multiple boxes of type ${n.type} but no array exists. Creating array dynamically.`),this[n.type+"s"]=[this[n.type],n]):(this[n.type]=n,Array.isArray(this[n.type+"s"])&&this[n.type+"s"].push(n));break}this.updateUsedBytes&&this.updateUsedBytes(n,l)}else if(l.code===ERR_INVALID_DATA){Log.error("ISOFile",`Invalid data found while parsing box of type '${l.type}' at position ${l.start}. Aborting parsing.`,this);break}}}checkBuffer(o){if(!o)throw new Error("Buffer must be defined and non empty");return o.byteLength===0?(Log.warn("ISOFile","Ignoring empty buffer (fileStart: "+o.fileStart+")"),this.stream.logBufferLevel(),!1):(Log.info("ISOFile","Processing buffer (fileStart: "+o.fileStart+")"),o.usedBytes=0,this.stream.insertBuffer(o),this.stream.logBufferLevel(),this.stream.initialized()?!0:(Log.warn("ISOFile","Not ready to start parsing"),!1))}appendBuffer(o,l){let n;if(this.checkBuffer(o))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(l),this.nextSeekPosition?(n=this.nextSeekPosition,this.nextSeekPosition=void 0):n=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(n=this.stream.getEndFilePositionAfter(n))):this.nextParsePosition?n=this.nextParsePosition:n=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(Log.info("ISOFile","Done processing buffer (fileStart: "+o.fileStart+") - next buffer to fetch should have a fileStart position of "+n),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),Log.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),n}getFragmentDuration(){const o=this.getBox("mvex");if(!o)return;if(o.mehd)return{num:o.mehd.fragment_duration,den:this.moov.mvhd.timescale};const l=this.getBoxes("trak",!1);let n={num:0,den:1};for(const r of l){const t=r.samples_duration,e=r.mdia.mdhd.timescale;t&&e&&t/e>n.num/n.den&&(n={num:t,den:e})}return n}getInfo(){if(!this.moov)return{hasMoov:!1,mime:""};const o=new Date("1904-01-01T00:00:00Z").getTime(),l=this.getBox("mvex")!==void 0,n={hasMoov:!0,duration:this.moov.mvhd.duration,timescale:this.moov.mvhd.timescale,isFragmented:l,fragment_duration:this.getFragmentDuration(),isProgressive:this.isProgressive,hasIOD:this.moov.iods!==void 0,brands:[this.ftyp.major_brand].concat(this.ftyp.compatible_brands),created:new Date(o+this.moov.mvhd.creation_time*1e3),modified:new Date(o+this.moov.mvhd.modification_time*1e3),tracks:[],audioTracks:[],videoTracks:[],subtitleTracks:[],metadataTracks:[],hintTracks:[],otherTracks:[],mime:""};for(let r=0;r<this.moov.traks.length;r++){const t=this.moov.traks[r],e=t.mdia.minf.stbl.stsd.entries[0],i=t.samples_size,a=t.mdia.mdhd.timescale,s=t.samples_duration,d=i*8*a/s,c={samples_duration:s,bitrate:d,size:i,timescale:a,alternate_group:t.tkhd.alternate_group,codec:e.getCodec(),created:new Date(o+t.tkhd.creation_time*1e3),cts_shift:t.mdia.minf.stbl.cslg,duration:t.mdia.mdhd.duration,id:t.tkhd.track_id,kind:t.udta&&t.udta.kinds.length?t.udta.kinds[0]:{schemeURI:"",value:""},language:t.mdia.elng?t.mdia.elng.extended_language:t.mdia.mdhd.languageString,layer:t.tkhd.layer,matrix:t.tkhd.matrix,modified:new Date(o+t.tkhd.modification_time*1e3),movie_duration:t.tkhd.duration,movie_timescale:n.timescale,name:t.mdia.hdlr.name,nb_samples:t.samples.length,references:[],track_height:t.tkhd.height/65536,track_width:t.tkhd.width/65536,volume:t.tkhd.volume};if(n.tracks.push(c),t.tref)for(let F=0;F<t.tref.references.length;F++)c.references.push({type:t.tref.references[F].type,track_ids:t.tref.references[F].track_ids});t.edts!==void 0&&t.edts.elst!==void 0&&(c.edits=t.edts.elst.entries),e instanceof AudioSampleEntry?(c.type="audio",n.audioTracks.push(c),c.audio={sample_rate:e.getSampleRate(),channel_count:e.getChannelCount(),sample_size:e.getSampleSize()}):e instanceof VisualSampleEntry?(c.type="video",n.videoTracks.push(c),c.video={width:e.getWidth(),height:e.getHeight()}):e instanceof SubtitleSampleEntry?(c.type="subtitles",n.subtitleTracks.push(c)):e instanceof HintSampleEntry?(c.type="metadata",n.hintTracks.push(c)):e instanceof MetadataSampleEntry?(c.type="metadata",n.metadataTracks.push(c)):(c.type="metadata",n.otherTracks.push(c))}n.videoTracks&&n.videoTracks.length>0?n.mime+='video/mp4; codecs="':n.audioTracks&&n.audioTracks.length>0?n.mime+='audio/mp4; codecs="':n.mime+='application/mp4; codecs="';for(let r=0;r<n.tracks.length;r++)r!==0&&(n.mime+=","),n.mime+=n.tracks[r].codec;return n.mime+='"; profiles="',n.mime+=this.ftyp.compatible_brands.join(),n.mime+='"',n}setNextSeekPositionFromSample(o){o&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(o.offset+o.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=o.offset+o.alreadyRead)}processSamples(o){if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==void 0){const l=new Set;for(;l.size<this.fragmentedTracks.length&&this.fragmentedTracks.some(n=>n.trak.nextSample<n.trak.samples.length)&&this.sampleProcessingStarted;)for(const n of this.fragmentedTracks){const r=n.trak;if(!l.has(n.id)){const t=r.nextSample<r.samples.length?this.getSample(r,r.nextSample):void 0;if(!t){this.setNextSeekPositionFromSample(r.samples[r.nextSample]),l.add(n.id);continue}n.state.accumulatedSize+=t.size;const e=r.nextSample+1,i=e-n.state.lastFragmentSampleNumber>n.nb_samples_per_fragment,a=e-n.state.lastSegmentSampleNumber>n.nb_samples;let s=i||e%n.nb_samples_per_fragment===0,d=a||e%n.nb_samples===0,c=n.state.accumulatedSize>=n.size_per_segment;const F=!n.rapAlignement||t.is_sync,B=o||r.nextSample+1>=r.samples.length;if(B&&!F&&Log.warn("ISOFile","Flushing track #"+n.id+" at sample #"+r.nextSample+" which is not a RAP, this may lead to playback issues"),s=s&&F,d=d&&F,c=c&&F,s||c||B){i?Log.warn("ISOFile","Fragment on track #"+n.id+" is overdue, creating it with samples ["+n.state.lastFragmentSampleNumber+", "+r.nextSample+"]"):Log.debug("ISOFile","Creating media fragment on track #"+n.id+" for samples ["+n.state.lastFragmentSampleNumber+", "+r.nextSample+"]");const S=this.createFragment(n.id,n.state.lastFragmentSampleNumber,r.nextSample,n.segmentStream);if(S)n.segmentStream=S,n.state.lastFragmentSampleNumber=r.nextSample+1;else{l.add(n.id);continue}}(d||c||B)&&(a?Log.warn("ISOFile","Segment on track #"+n.id+" is overdue, sending it with samples ["+Math.max(0,r.nextSample-n.nb_samples)+", "+(r.nextSample-1)+"]"):Log.info("ISOFile","Sending fragmented data on track #"+n.id+" for samples ["+Math.max(0,r.nextSample-n.nb_samples)+", "+(r.nextSample-1)+"]"),Log.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(n.id,n.user,n.segmentStream.buffer,r.nextSample+1,o||r.nextSample+1>=r.samples.length),n.segmentStream=void 0,n.state.accumulatedSize=0,n.state.lastSegmentSampleNumber=r.nextSample+1),r.nextSample++}}}if(this.onSamples!==void 0)for(let l=0;l<this.extractedTracks.length;l++){const n=this.extractedTracks[l],r=n.trak;for(;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){Log.debug("ISOFile","Exporting on track #"+n.id+" sample #"+r.nextSample);const t=this.getSample(r,r.nextSample);if(t)r.nextSample++,n.samples.push(t);else{this.setNextSeekPositionFromSample(r.samples[r.nextSample]);break}if((r.nextSample%n.nb_samples===0||r.nextSample>=r.samples.length)&&(Log.debug("ISOFile","Sending samples on track #"+n.id+" for sample "+r.nextSample),this.onSamples&&this.onSamples(n.id,n.user,n.samples),n.samples=[],n!==this.extractedTracks[l]))break}}}}getBox(o){const l=this.getBoxes(o,!0);return l.length?l[0]:void 0}getBoxes(o,l){const n=[],r=t=>{t instanceof Box&&t.type&&t.type===o&&n.push(t);const e=[];t.boxes&&e.push(...t.boxes),t.entries&&e.push(...t.entries),t.item_infos&&e.push(...t.item_infos),t.references&&e.push(...t.references);for(const i of e){if(n.length&&l)return;r(i)}};return r(this),n}getTrackSamplesInfo(o){const l=this.getTrackById(o);if(l)return l.samples}getTrackSample(o,l){const n=this.getTrackById(o);return this.getSample(n,l)}releaseUsedSamples(o,l){let n=0;const r=this.getTrackById(o);r.lastValidSample||(r.lastValidSample=0);for(let t=r.lastValidSample;t<l;t++)n+=this.releaseSample(r,t);Log.info("ISOFile","Track #"+o+" released samples up to "+l+" (released size: "+n+", remaining: "+this.samplesDataSize+")"),r.lastValidSample=l}start(){this.sampleProcessingStarted=!0,this.processSamples(!1)}stop(){this.sampleProcessingStarted=!1}flush(){Log.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)}seekTrack(o,l,n){let r=0,t=0,e;if(n.samples.length===0)return Log.info("ISOFile","No sample in track, cannot seek! Using time "+Log.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(let a=0;a<n.samples.length;a++){const s=n.samples[a];if(a===0)t=0,e=s.timescale;else if(s.cts>o*s.timescale){t=a-1;break}l&&s.is_sync&&(r=a)}for(l&&(t=r),o=n.samples[t].cts,n.nextSample=t;n.samples[t].alreadyRead===n.samples[t].size&&n.samples[t+1];)t++;const i=n.samples[t].offset+n.samples[t].alreadyRead;return Log.info("ISOFile","Seeking to "+(l?"RAP":"")+" sample #"+n.nextSample+" on track "+n.tkhd.track_id+", time "+Log.getDurationString(o,e)+" and offset: "+i),{offset:i,time:o/e}}getTrackDuration(o){if(!o.samples)return 1/0;const l=o.samples[o.samples.length-1];return(l.cts+l.duration)/l.timescale}seek(o,l){const n=this.moov;let r={offset:1/0,time:1/0};if(this.moov){for(let t=0;t<n.traks.length;t++){const e=n.traks[t];if(o>this.getTrackDuration(e))continue;const i=this.seekTrack(o,l,e);i.offset<r.offset&&(r.offset=i.offset),i.time<r.time&&(r.time=i.time)}return Log.info("ISOFile","Seeking at time "+Log.getDurationString(r.time,1)+" needs a buffer with a fileStart position of "+r.offset),r.offset===1/0?r={offset:this.nextParsePosition,time:0}:r.offset=this.stream.getEndFilePositionAfter(r.offset),Log.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+r.offset),r}else throw new Error("Cannot seek: moov not received!")}equal(o){let l=0;for(;l<this.boxes.length&&l<o.boxes.length;){const n=this.boxes[l],r=o.boxes[l];if(!boxEqual(n,r))return!1;l++}return!0}write(o){for(let l=0;l<this.boxes.length;l++)this.boxes[l].write(o)}createFragment(o,l,n,r){const t=[];for(let d=l;d<=n;d++){const c=this.getTrackById(o),F=this.getSample(c,d);if(!F){this.setNextSeekPositionFromSample(c.samples[d]);return}t.push(F)}const e=r||new DataStream,i=this.createMoof(t);i.write(e),i.trafs[0].truns[0].data_offset=i.size+8,Log.debug("MP4Box","Adjusting data_offset with new value "+i.trafs[0].truns[0].data_offset),e.adjustUint32(i.trafs[0].truns[0].data_offset_position,i.trafs[0].truns[0].data_offset);const a=new mdatBox;a.stream=new MultiBufferStream;let s=0;for(const d of t)if(d.data){const c=MP4BoxBuffer.fromArrayBuffer(d.data.buffer,s);a.stream.insertBuffer(c),s+=d.data.byteLength}return a.write(e),e}static writeInitializationSegment(o,l,n){var e;Log.debug("ISOFile","Generating initialization segment");const r=new DataStream;o.write(r);const t=l.addBox(new mvexBox);if(n){const i=t.addBox(new mehdBox);i.fragment_duration=n}for(let i=0;i<l.traks.length;i++){const a=t.addBox(new trexBox);a.track_id=l.traks[i].tkhd.track_id,a.default_sample_description_index=1,a.default_sample_duration=((e=l.traks[i].samples[0])==null?void 0:e.duration)??0,a.default_sample_size=0,a.default_sample_flags=65536}return l.write(r),r.buffer}save(o){const l=new DataStream;return l.isofile=this,this.write(l),l.save(o)}getBuffer(){const o=new DataStream;return o.isofile=this,this.write(o),o}initializeSegmentation(){var l,n;this.onSegment||Log.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.resetTables());const o=new moovBox;o.addBox(this.moov.mvhd);for(let r=0;r<this.fragmentedTracks.length;r++){const t=this.getTrackById(this.fragmentedTracks[r].id);if(!t){Log.warn("ISOFile",`Track with id ${this.fragmentedTracks[r].id} not found, skipping fragmentation initialization`);continue}o.addBox(t)}return{tracks:o.traks.map((r,t)=>({id:r.tkhd.track_id,user:this.fragmentedTracks[t].user})),buffer:w.writeInitializationSegment(this.ftyp,o,(n=(l=this.moov)==null?void 0:l.mvex)==null?void 0:n.mehd.fragment_duration)}}resetTables(){this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0;for(let o=0;o<this.moov.traks.length;o++){const l=this.moov.traks[o];l.tkhd.duration=0,l.mdia.mdhd.duration=0;const n=l.mdia.minf.stbl.stco||l.mdia.minf.stbl.co64;n.chunk_offsets=[];const r=l.mdia.minf.stbl.stsc;r.first_chunk=[],r.samples_per_chunk=[],r.sample_description_index=[];const t=l.mdia.minf.stbl.stsz||l.mdia.minf.stbl.stz2;t.sample_sizes=[];const e=l.mdia.minf.stbl.stts;e.sample_counts=[],e.sample_deltas=[];const i=l.mdia.minf.stbl.ctts;i&&(i.sample_counts=[],i.sample_offsets=[]);const a=l.mdia.minf.stbl.stss,s=l.mdia.minf.stbl.boxes.indexOf(a);s!==-1&&(l.mdia.minf.stbl.boxes[s]=void 0)}}static initSampleGroups(o,l,n,r,t){l&&(l.sample_groups_info=[]),o.sample_groups_info||(o.sample_groups_info=[]);for(let e=0;e<n.length;e++){const i=n[e].grouping_type+"/"+n[e].grouping_type_parameter,a=new SampleGroupInfo(n[e].grouping_type,n[e].grouping_type_parameter,n[e]);l&&(l.sample_groups_info[i]=a),o.sample_groups_info[i]||(o.sample_groups_info[i]=a);for(let s=0;s<r.length;s++)r[s].grouping_type===n[e].grouping_type&&(a.description=r[s],a.description.used=!0);if(t)for(let s=0;s<t.length;s++)t[s].grouping_type===n[e].grouping_type&&(a.fragment_description=t[s],a.fragment_description.used=!0,a.is_fragment=!0)}if(l){if(t){for(let e=0;e<t.length;e++)if(!t[e].used&&t[e].version>=2){const i=t[e].grouping_type+"/0",a=new SampleGroupInfo(t[e].grouping_type,0);a.is_fragment=!0,l.sample_groups_info[i]||(l.sample_groups_info[i]=a)}}}else for(let e=0;e<r.length;e++)if(!r[e].used&&r[e].version>=2){const i=r[e].grouping_type+"/0",a=new SampleGroupInfo(r[e].grouping_type,0);o.sample_groups_info[i]||(o.sample_groups_info[i]=a)}}static setSampleGroupProperties(o,l,n,r){l.sample_groups=[];for(const t in r)if(l.sample_groups[t]={grouping_type:r[t].grouping_type,grouping_type_parameter:r[t].grouping_type_parameter},n>=r[t].last_sample_in_run&&(r[t].last_sample_in_run<0&&(r[t].last_sample_in_run=0),r[t].entry_index++,r[t].entry_index<=r[t].sbgp.entries.length-1&&(r[t].last_sample_in_run+=r[t].sbgp.entries[r[t].entry_index].sample_count)),r[t].entry_index<=r[t].sbgp.entries.length-1?l.sample_groups[t].group_description_index=r[t].sbgp.entries[r[t].entry_index].group_description_index:l.sample_groups[t].group_description_index=-1,l.sample_groups[t].group_description_index!==0){let e;if(r[t].fragment_description?e=r[t].fragment_description:e=r[t].description,l.sample_groups[t].group_description_index>0){let i;l.sample_groups[t].group_description_index>65535?i=(l.sample_groups[t].group_description_index>>16)-1:i=l.sample_groups[t].group_description_index-1,e&&i>=0&&(l.sample_groups[t].description=e.entries[i])}else e&&e.version>=2&&e.default_group_description_index>0&&(l.sample_groups[t].description=e.entries[e.default_group_description_index-1])}}static process_sdtp(o,l,n){l&&(o?(l.is_leading=o.is_leading[n],l.depends_on=o.sample_depends_on[n],l.is_depended_on=o.sample_is_depended_on[n],l.has_redundancy=o.sample_has_redundancy[n]):(l.is_leading=0,l.depends_on=0,l.is_depended_on=0,l.has_redundancy=0))}buildSampleLists(){for(let o=0;o<this.moov.traks.length;o++)this.buildTrakSampleLists(this.moov.traks[o])}buildTrakSampleLists(o){let l,n,r,t,e,i;o.samples=[],o.samples_duration=0,o.samples_size=0;const a=o.mdia.minf.stbl.stco||o.mdia.minf.stbl.co64,s=o.mdia.minf.stbl.stsc,d=o.mdia.minf.stbl.stsz||o.mdia.minf.stbl.stz2,c=o.mdia.minf.stbl.stts,F=o.mdia.minf.stbl.ctts,B=o.mdia.minf.stbl.stss,S=o.mdia.minf.stbl.stsd,y=o.mdia.minf.stbl.subs,E=o.mdia.minf.stbl.stdp,v=o.mdia.minf.stbl.sbgps,N=o.mdia.minf.stbl.sgpds;let T=-1,C=-1,m=-1,Q=-1,p=0,f=0,h=0;if(w.initSampleGroups(o,void 0,v,N),!(typeof d>"u")){for(l=0;l<d.sample_sizes.length;l++){const R={number:l,track_id:o.tkhd.track_id,timescale:o.mdia.mdhd.timescale,alreadyRead:0,size:d.sample_sizes[l]};o.samples[l]=R,o.samples_size+=R.size,l===0?(r=1,n=0,R.chunk_index=r,R.chunk_run_index=n,i=s.samples_per_chunk[n],e=0,n+1<s.first_chunk.length?t=s.first_chunk[n+1]-1:t=1/0):l<i?(R.chunk_index=r,R.chunk_run_index=n):(r++,R.chunk_index=r,e=0,r<=t||(n++,n+1<s.first_chunk.length?t=s.first_chunk[n+1]-1:t=1/0),R.chunk_run_index=n,i+=s.samples_per_chunk[n]),R.description_index=s.sample_description_index[R.chunk_run_index]-1,R.description=S.entries[R.description_index],R.offset=a.chunk_offsets[R.chunk_index-1]+e,e+=R.size,l>T&&(C++,T<0&&(T=0),T+=c.sample_counts[C]),l>0?(o.samples[l-1].duration=c.sample_deltas[C],o.samples_duration+=o.samples[l-1].duration,R.dts=o.samples[l-1].dts+o.samples[l-1].duration):R.dts=0,F?(l>=m&&(Q++,m<0&&(m=0),m+=F.sample_counts[Q]),R.cts=o.samples[l].dts+F.sample_offsets[Q]):R.cts=R.dts,B?(l===B.sample_numbers[p]-1?(R.is_sync=!0,p++):(R.is_sync=!1,R.degradation_priority=0),y&&y.entries[f].sample_delta+h===l+1&&(R.subsamples=y.entries[f].subsamples,h+=y.entries[f].sample_delta,f++)):R.is_sync=!0,w.process_sdtp(o.mdia.minf.stbl.sdtp,R,R.number),E?R.degradation_priority=E.priority[l]:R.degradation_priority=0,y&&y.entries[f].sample_delta+h===l&&(R.subsamples=y.entries[f].subsamples,h+=y.entries[f].sample_delta),(v.length>0||N.length>0)&&w.setSampleGroupProperties(o,R,l,o.sample_groups_info)}l>0&&(o.samples[l-1].duration=Math.max(o.mdia.mdhd.duration-o.samples[l-1].dts,0),o.samples_duration+=o.samples[l-1].duration)}}updateSampleLists(){let o,l,n,r,t;if(this.moov!==void 0)for(;this.lastMoofIndex<this.moofs.length;){const e=this.moofs[this.lastMoofIndex];if(this.lastMoofIndex++,e.type==="moof"){const i=e;for(let a=0;a<i.trafs.length;a++){const s=i.trafs[a],d=this.getTrackById(s.tfhd.track_id),c=this.getTrexById(s.tfhd.track_id);s.tfhd.flags&TFHD_FLAG_SAMPLE_DESC?o=s.tfhd.default_sample_description_index:o=c?c.default_sample_description_index:1,s.tfhd.flags&TFHD_FLAG_SAMPLE_DUR?l=s.tfhd.default_sample_duration:l=c?c.default_sample_duration:0,s.tfhd.flags&TFHD_FLAG_SAMPLE_SIZE?n=s.tfhd.default_sample_size:n=c?c.default_sample_size:0,s.tfhd.flags&TFHD_FLAG_SAMPLE_FLAGS?r=s.tfhd.default_sample_flags:r=c?c.default_sample_flags:0,s.sample_number=0,s.sbgps.length>0&&w.initSampleGroups(d,s,s.sbgps,d.mdia.minf.stbl.sgpds,s.sgpds);for(let F=0;F<s.truns.length;F++){const B=s.truns[F];for(let S=0;S<B.sample_count;S++){const y=o-1;let E=r;B.flags&TRUN_FLAGS_FLAGS?E=B.sample_flags[S]:S===0&&B.flags&TRUN_FLAGS_FIRST_FLAG&&(E=B.first_sample_flags);let v=n;B.flags&TRUN_FLAGS_SIZE&&(v=B.sample_size[S]),d.samples_size+=v;let N=l;B.flags&TRUN_FLAGS_DURATION&&(N=B.sample_duration[S]),d.samples_duration+=N;let T;d.first_traf_merged||S>0?T=d.samples[d.samples.length-1].dts+d.samples[d.samples.length-1].duration:(s.tfdt?T=s.tfdt.baseMediaDecodeTime:T=0,d.first_traf_merged=!0);let C=T;B.flags&TRUN_FLAGS_CTS_OFFSET&&(C=T+B.sample_composition_time_offset[S]);const m=!!(s.tfhd.flags&TFHD_FLAG_BASE_DATA_OFFSET),Q=!!(s.tfhd.flags&TFHD_FLAG_DEFAULT_BASE_IS_MOOF),p=!!(B.flags&TRUN_FLAGS_DATA_OFFSET);let f=0;m?f=s.tfhd.base_data_offset:Q||F===0?f=i.start:f=t;let h;F===0&&S===0?p?h=f+B.data_offset:h=f:h=t,t=h+v;const R=s.sample_number;s.sample_number++;const J={cts:C,description_index:y,description:d.mdia.minf.stbl.stsd.entries[y],dts:T,duration:N,moof_number:this.lastMoofIndex,number_in_traf:R,number:d.samples.length,offset:h,size:v,timescale:d.mdia.mdhd.timescale,track_id:d.tkhd.track_id,is_sync:!(E>>16&1),is_leading:E>>26&3,depends_on:E>>24&3,is_depended_on:E>>22&3,has_redundancy:E>>20&3,degradation_priority:E&65535};s.first_sample_index=d.samples.length,d.samples.push(J),(s.sbgps.length>0||s.sgpds.length>0||d.mdia.minf.stbl.sbgps.length>0||d.mdia.minf.stbl.sgpds.length>0)&&w.setSampleGroupProperties(d,J,J.number_in_traf,s.sample_groups_info)}}if(s.subs){d.has_fragment_subsamples=!0;let F=s.first_sample_index;for(let B=0;B<s.subs.entries.length;B++){F+=s.subs.entries[B].sample_delta;const S=d.samples[F-1];S.subsamples=s.subs.entries[B].subsamples}}}}}}getSample(o,l){const n=o.samples[l];if(this.moov){if(!n.data)n.data=new Uint8Array(n.size),n.alreadyRead=0,this.samplesDataSize+=n.size,Log.debug("ISOFile","Allocating sample #"+l+" on track #"+o.tkhd.track_id+" of size "+n.size+" (total: "+this.samplesDataSize+")");else if(n.alreadyRead===n.size)return n;for(;;){let r=this.stream,t=r.findPosition(!0,n.offset+n.alreadyRead,!1),e,i;if(t>-1)e=r.buffers[t],i=e.fileStart;else for(const a of this.mdats){if(!a.stream){Log.debug("ISOFile","mdat stream not yet fully read for #"+this.mdats.indexOf(a)+" mdat");continue}if(t=a.stream.findPosition(!0,n.offset+n.alreadyRead-a.start-a.hdr_size,!1),t>-1){r=a.stream,e=a.stream.buffers[t],i=a.start+a.hdr_size+e.fileStart;break}}if(e){const a=e.byteLength-(n.offset+n.alreadyRead-i);if(n.size-n.alreadyRead<=a)return Log.debug("ISOFile","Getting sample #"+l+" data (alreadyRead: "+n.alreadyRead+" offset: "+(n.offset+n.alreadyRead-i)+" read size: "+(n.size-n.alreadyRead)+" full size: "+n.size+")"),DataStream.memcpy(n.data.buffer,n.alreadyRead,e,n.offset+n.alreadyRead-i,n.size-n.alreadyRead),e.usedBytes+=n.size-n.alreadyRead,r.logBufferLevel(),n.alreadyRead=n.size,n;if(a===0)return;Log.debug("ISOFile","Getting sample #"+l+" partial data (alreadyRead: "+n.alreadyRead+" offset: "+(n.offset+n.alreadyRead-i)+" read size: "+a+" full size: "+n.size+")"),DataStream.memcpy(n.data.buffer,n.alreadyRead,e,n.offset+n.alreadyRead-i,a),n.alreadyRead+=a,e.usedBytes+=a,r.logBufferLevel()}else return}}}releaseSample(o,l){const n=o.samples[l];return n.data?(this.samplesDataSize-=n.size,n.data=void 0,n.alreadyRead=0,n.size):0}getAllocatedSampleDataSize(){return this.samplesDataSize}getCodecs(){let o="";for(let l=0;l<this.moov.traks.length;l++){const n=this.moov.traks[l];l>0&&(o+=","),o+=n.mdia.minf.stbl.stsd.entries[0].getCodec()}return o}getTrexById(o){if(!(!this.moov||!this.moov.mvex))for(let l=0;l<this.moov.mvex.trexs.length;l++){const n=this.moov.mvex.trexs[l];if(n.track_id===o)return n}}getTrackById(o){if(this.moov)for(let l=0;l<this.moov.traks.length;l++){const n=this.moov.traks[l];if(n.tkhd.track_id===o)return n}}flattenItemInfo(){const o=this.items,l=this.entity_groups,n=this.meta;if(!(!n||!n.hdlr||!n.iinf)){for(let r=0;r<n.iinf.item_infos.length;r++){const t=n.iinf.item_infos[r].item_ID;o[t]={id:t,name:n.iinf.item_infos[r].item_name,ref_to:[],content_type:n.iinf.item_infos[r].content_type,content_encoding:n.iinf.item_infos[r].content_encoding,item_uri_type:n.iinf.item_infos[r].item_uri_type,type:n.iinf.item_infos[r].item_type?n.iinf.item_infos[r].item_type:"mime",protection:n.iinf.item_infos[r].item_protection_index>0?n.ipro.protections[n.iinf.item_infos[r].item_protection_index-1]:void 0}}if(n.grpl)for(let r=0;r<n.grpl.boxes.length;r++){const t=n.grpl.boxes[r];l[t.group_id]={id:t.group_id,entity_ids:t.entity_ids,type:t.type}}if(n.iloc)for(let r=0;r<n.iloc.items.length;r++){const t=n.iloc.items[r],e=o[t.item_ID];t.data_reference_index!==0&&(Log.warn("Item storage with reference to other files: not supported"),e.source=n.dinf.boxes[t.data_reference_index-1]),e.extents=[],e.size=0;for(let i=0;i<t.extents.length;i++)e.extents[i]={offset:t.extents[i].extent_offset+t.base_offset,length:t.extents[i].extent_length,alreadyRead:0},t.construction_method===1&&(e.extents[i].offset+=n.idat.start+n.idat.hdr_size),e.size+=e.extents[i].length}if(n.pitm&&(o[n.pitm.item_id].primary=!0),n.iref)for(let r=0;r<n.iref.references.length;r++){const t=n.iref.references[r];for(let e=0;e<t.references.length;e++)o[t.from_item_ID].ref_to.push({type:t.type,id:t.references[e]})}if(n.iprp)for(let r=0;r<n.iprp.ipmas.length;r++){const t=n.iprp.ipmas[r];for(let e=0;e<t.associations.length;e++){const i=t.associations[e],a=o[i.id]??l[i.id];if(a){a.properties===void 0&&(a.properties={boxes:[]});for(let s=0;s<i.props.length;s++){const d=i.props[s];if(d.property_index>0&&d.property_index-1<n.iprp.ipco.boxes.length){const c=n.iprp.ipco.boxes[d.property_index-1];a.properties[c.type]=c,a.properties.boxes.push(c)}}}}}}}getItem(o){if(!this.meta)return;const l=this.items[o];if(!l.data&&l.size)l.data=new Uint8Array(l.size),l.alreadyRead=0,this.itemsDataSize+=l.size,Log.debug("ISOFile","Allocating item #"+o+" of size "+l.size+" (total: "+this.itemsDataSize+")");else if(l.alreadyRead===l.size)return l;for(let n=0;n<l.extents.length;n++){const r=l.extents[n];if(r.alreadyRead!==r.length){const t=this.stream.findPosition(!0,r.offset+r.alreadyRead,!1);if(t>-1){const e=this.stream.buffers[t],i=e.byteLength-(r.offset+r.alreadyRead-e.fileStart);if(r.length-r.alreadyRead<=i)Log.debug("ISOFile","Getting item #"+o+" extent #"+n+" data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-e.fileStart)+" read size: "+(r.length-r.alreadyRead)+" full extent size: "+r.length+" full item size: "+l.size+")"),DataStream.memcpy(l.data.buffer,l.alreadyRead,e,r.offset+r.alreadyRead-e.fileStart,r.length-r.alreadyRead),(!this.parsingMdat||this.discardMdatData)&&(e.usedBytes+=r.length-r.alreadyRead),this.stream.logBufferLevel(),l.alreadyRead+=r.length-r.alreadyRead,r.alreadyRead=r.length;else{Log.debug("ISOFile","Getting item #"+o+" extent #"+n+" partial data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-e.fileStart)+" read size: "+i+" full extent size: "+r.length+" full item size: "+l.size+")"),DataStream.memcpy(l.data.buffer,l.alreadyRead,e,r.offset+r.alreadyRead-e.fileStart,i),r.alreadyRead+=i,l.alreadyRead+=i,(!this.parsingMdat||this.discardMdatData)&&(e.usedBytes+=i),this.stream.logBufferLevel();return}}else return}}if(l.alreadyRead===l.size)return l}releaseItem(o){const l=this.items[o];if(l.data){this.itemsDataSize-=l.size,l.data=void 0,l.alreadyRead=0;for(let n=0;n<l.extents.length;n++){const r=l.extents[n];r.alreadyRead=0}return l.size}else return 0}processItems(o){for(const l in this.items){const n=this.items[l];this.getItem(n.id),o&&!n.sent&&(o(n),n.sent=!0,n.data=void 0)}}hasItem(o){for(const l in this.items){const n=this.items[l];if(n.name===o)return n.id}return-1}getMetaHandler(){if(this.meta)return this.meta.hdlr.handler}getPrimaryItem(){if(this.meta&&this.meta.pitm)return this.getItem(this.meta.pitm.item_id)}itemToFragmentedTrackFile({itemId:o}={}){let l;if(o?l=this.getItem(o):l=this.getPrimaryItem(),!l)return;const n=new w;n.discardMdatData=!1;const r={type:l.type,description_boxes:l.properties.boxes};l.properties.ispe&&(r.width=l.properties.ispe.image_width,r.height=l.properties.ispe.image_height);const t=n.addTrack(r);if(t)return n.addSample(t,l.data),n}processIncompleteBox(o){if(o.type==="mdat"){const l=new mdatBox(o.size);return this.parsingMdat=l,this.boxes.push(l),this.mdats.push(l),l.start=o.start,l.hdr_size=o.hdr_size,l.original_size=o.original_size,this.stream.addUsedBytes(l.hdr_size),this.lastBoxStartPosition=l.start+l.size,this.stream.seek(l.start+l.size,!1,this.discardMdatData)?(this.transferMdatData(),this.parsingMdat=void 0,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=l.start+l.size,!1)}else return o.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),(this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1)?(this.nextParsePosition=this.stream.getEndPosition(),!0):(o.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+o.size:this.nextParsePosition=this.stream.getEndPosition(),!1)}hasIncompleteMdat(){return this.parsingMdat!==void 0}transferMdatData(o){const l=o??this.parsingMdat;if(this.discardMdatData){Log.debug("ISOFile","Discarding 'mdat' data, not transferring it to the mdat box stream");return}if(!l){Log.warn("ISOFile","Cannot transfer 'mdat' data, no mdat box is being parsed");return}const n=this.stream.findPosition(!0,l.start+l.hdr_size,!1),r=this.stream.findPosition(!0,l.start+l.size,!1);if(n===-1||r===-1){Log.warn("ISOFile","Cannot transfer 'mdat' data, start or end buffer not found");return}l.stream=new MultiBufferStream;for(let t=n;t<=r;t++){const e=this.stream.buffers[t],i=t===n?l.start+l.hdr_size-e.fileStart:0,a=t===r?l.start+l.size-e.fileStart:e.byteLength;if(a>i){Log.debug("ISOFile","Transferring 'mdat' data from buffer #"+t+" ("+i+" to "+a+")");const s=a-i,d=new MP4BoxBuffer(s),c=l.stream.getAbsoluteEndPosition();DataStream.memcpy(d,0,e,i,s),d.fileStart=c,l.stream.insertBuffer(d),e.usedBytes+=s}}}processIncompleteMdat(){const o=this.parsingMdat;return this.stream.seek(o.start+o.size,!1,this.discardMdatData)?(Log.debug("ISOFile","Found 'mdat' end in buffered data"),this.transferMdatData(),this.parsingMdat=void 0,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)}restoreParsePosition(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)}saveParsePosition(){this.lastBoxStartPosition=this.stream.getPosition()}updateUsedBytes(o,l){this.stream.addUsedBytes&&(o.type==="mdat"?(this.stream.addUsedBytes(o.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(o.size-o.hdr_size)):this.stream.addUsedBytes(o.size))}addBox(o){return Box.prototype.addBox.call(this,o)}init(o={}){const l=this.addBox(new ftypBox);l.major_brand=o.brands&&o.brands[0]||"iso4",l.minor_version=0,l.compatible_brands=o.brands||["iso4"];const n=this.addBox(new moovBox);n.addBox(new mvexBox);const r=n.addBox(new mvhdBox);return r.timescale=o.timescale||600,r.rate=o.rate||65536,r.creation_time=0,r.modification_time=0,r.duration=o.duration||0,r.volume=o.width?0:256,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.next_track_id=1,this}addTrack(o={}){this.moov||this.init(o);const l=o||{};l.width=l.width||320,l.height=l.height||320,l.id=l.id||this.moov.mvhd.next_track_id,l.type=l.type||"avc1";const n=this.moov.addBox(new trakBox);this.moov.mvhd.next_track_id=l.id+1;const r=n.addBox(new tkhdBox);r.flags=TKHD_FLAG_ENABLED|TKHD_FLAG_IN_MOVIE|TKHD_FLAG_IN_PREVIEW,r.creation_time=0,r.modification_time=0,r.track_id=l.id,r.duration=l.duration||0,r.layer=l.layer||0,r.alternate_group=0,r.volume=1,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.width=l.width<<16,r.height=l.height<<16;const t=n.addBox(new mdiaBox),e=t.addBox(new mdhdBox);e.creation_time=0,e.modification_time=0,e.timescale=l.timescale||1,e.duration=l.media_duration||0,e.language=l.language||"und";const i=t.addBox(new hdlrBox);i.handler=l.hdlr||"vide",i.name=l.name||"Track created with MP4Box.js";const a=t.addBox(new elngBox);a.extended_language=l.language||"fr-FR";const s=t.addBox(new minfBox),d=BoxRegistry.sampleEntry[l.type];if(!d)return;const c=new d;if(c.data_reference_index=1,c instanceof VisualSampleEntry){const Q=c,p=s.addBox(new vmhdBox);p.graphicsmode=0,p.opcolor=[0,0,0],Q.width=l.width,Q.height=l.height,Q.horizresolution=72<<16,Q.vertresolution=72<<16,Q.frame_count=1,Q.compressorname=l.type+" Compressor",Q.depth=24,l.avcDecoderConfigRecord?Q.addBox(new avcCBox(l.avcDecoderConfigRecord.byteLength)).parse(new DataStream(l.avcDecoderConfigRecord)):l.hevcDecoderConfigRecord&&Q.addBox(new hvcCBox(l.hevcDecoderConfigRecord.byteLength)).parse(new DataStream(l.hevcDecoderConfigRecord))}else if(c instanceof AudioSampleEntry){const Q=c,p=s.addBox(new smhdBox);p.balance=l.balance||0,Q.channel_count=l.channel_count||2,Q.samplesize=l.samplesize||16,Q.samplerate=l.samplerate||65536}else c instanceof HintSampleEntry?s.addBox(new hmhdBox):c instanceof SubtitleSampleEntry?(s.addBox(new sthdBox),c instanceof stppSampleEntry&&(c.namespace=l.namespace||"nonamespace",c.schema_location=l.schema_location||"",c.auxiliary_mime_types=l.auxiliary_mime_types||"")):c instanceof MetadataSampleEntry?s.addBox(new nmhdBox):c instanceof SystemSampleEntry?s.addBox(new nmhdBox):s.addBox(new nmhdBox);l.description&&c.addBox.call(c,l.description),l.description_boxes&&l.description_boxes.forEach(function(Q){c.addBox.call(c,Q)});const B=s.addBox(new dinfBox).addBox(new drefBox),S=new urlBox;S.flags=1,B.addEntry(S);const y=s.addBox(new stblBox);y.addBox(new stsdBox).addEntry(c);const v=y.addBox(new sttsBox);v.sample_counts=[],v.sample_deltas=[];const N=y.addBox(new stscBox);N.first_chunk=[],N.samples_per_chunk=[],N.sample_description_index=[];const T=y.addBox(new stcoBox);T.chunk_offsets=[];const C=y.addBox(new stszBox);C.sample_sizes=[];const m=this.moov.mvex.addBox(new trexBox);return m.track_id=l.id,m.default_sample_description_index=l.default_sample_description_index||1,m.default_sample_duration=l.default_sample_duration||0,m.default_sample_size=l.default_sample_size||0,m.default_sample_flags=l.default_sample_flags||0,this.buildTrakSampleLists(n),l.id}addSample(o,l,{sample_description_index:n,duration:r=1,cts:t=0,dts:e=0,is_sync:i=!1,is_leading:a=0,depends_on:s=0,is_depended_on:d=0,has_redundancy:c=0,degradation_priority:F=0,subsamples:B,offset:S=0}={}){const y=this.getTrackById(o);if(y===void 0)return;const E=n?n-1:0,v={number:y.samples.length,track_id:y.tkhd.track_id,timescale:y.mdia.mdhd.timescale,description_index:E,description:y.mdia.minf.stbl.stsd.entries[E],data:l,size:l.byteLength,alreadyRead:l.byteLength,duration:r,cts:t,dts:e,is_sync:i,is_leading:a,depends_on:s,is_depended_on:d,has_redundancy:c,degradation_priority:F,offset:S,subsamples:B};y.samples.push(v),y.samples_size+=v.size,y.samples_duration+=v.duration,y.first_dts===void 0&&(y.first_dts=e),this.processSamples();const N=this.addBox(this.createMoof([v]));N.computeSize(),N.trafs[0].truns[0].data_offset=N.size+8;const T=this.addBox(new mdatBox);return T.data=new Uint8Array(l),v}createMoof(o){if(o.length===0)return;if(o.some(d=>d.track_id!==o[0].track_id))throw new Error("Cannot create moof for samples from different tracks: "+o.map(d=>d.track_id).join(", "));const l=o[0].track_id,n=this.getTrackById(l);if(!n)throw new Error("Cannot create moof for non-existing track: "+l);const r=new moofBox,t=r.addBox(new mfhdBox);t.sequence_number=++this.nextMoofNumber;const e=r.addBox(new trafBox),i=e.addBox(new tfhdBox);i.track_id=l,i.flags=TFHD_FLAG_DEFAULT_BASE_IS_MOOF;const a=e.addBox(new tfdtBox);a.baseMediaDecodeTime=o[0].dts-(n.first_dts||0);const s=e.addBox(new trunBox);s.flags=TRUN_FLAGS_DATA_OFFSET|TRUN_FLAGS_DURATION|TRUN_FLAGS_SIZE|TRUN_FLAGS_FLAGS|TRUN_FLAGS_CTS_OFFSET,s.data_offset=0,s.first_sample_flags=0,s.sample_count=o.length;for(const d of o){let c=0;d.is_sync?c=1<<25:c=65536,s.sample_duration.push(d.duration),s.sample_size.push(d.size),s.sample_flags.push(c),s.sample_composition_time_offset.push(d.cts-d.dts)}return r}print(o){o.indent="";for(let l=0;l<this.boxes.length;l++)this.boxes[l]&&this.boxes[l].print(o)}};function createFile(u=!1,o){return new ISOFile(o,!u)}var descriptor_exports={};__export(descriptor_exports,{Descriptor:()=>Descriptor,ES_Descriptor:()=>ES_Descriptor,MPEG4DescriptorParser:()=>MPEG4DescriptorParser});var ES_DescrTag=3,DecoderConfigDescrTag=4,DecSpecificInfoTag=5,SLConfigDescrTag=6,Descriptor=class Ur{constructor(o,l){this.tag=o,this.size=l,this.descs=[]}parse(o){this.data=o.readUint8Array(this.size)}findDescriptor(o){for(let l=0;l<this.descs.length;l++)if(this.descs[l].tag===o)return this.descs[l]}parseOneDescriptor(o){let l=0;const n=o.readUint8();let r=o.readUint8();for(;r&128;)l=(l<<7)+(r&127),r=o.readUint8();l=(l<<7)+(r&127),Log.debug("Descriptor","Found "+(descTagToName[n]||"Descriptor "+n)+", size "+l+" at position "+o.getPosition());const t=descTagToName[n]?new DESCRIPTOR_CLASSES[descTagToName[n]](l):new Ur(l);return t.parse(o),t}parseRemainingDescriptors(o){var n;const l=o.getPosition();for(;o.getPosition()<l+this.size;){const r=(n=this.parseOneDescriptor)==null?void 0:n.call(this,o);this.descs.push(r)}}},ES_Descriptor=class extends Descriptor{constructor(u){super(ES_DescrTag,u)}parse(u){if(this.ES_ID=u.readUint16(),this.flags=u.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=u.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){const o=u.readUint8();this.URL=u.readString(o),this.size-=o+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=u.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(u)}getOTI(){const u=this.findDescriptor(DecoderConfigDescrTag);return u?u.oti:0}getAudioConfig(){const u=this.findDescriptor(DecoderConfigDescrTag);if(!u)return;const o=u.findDescriptor(DecSpecificInfoTag);if(o&&o.data){let l=(o.data[0]&248)>>3;return l===31&&o.data.length>=2&&(l=32+((o.data[0]&7)<<3)+((o.data[1]&224)>>5)),l}}},DecoderConfigDescriptor=class extends Descriptor{constructor(u){super(DecoderConfigDescrTag,u)}parse(u){this.oti=u.readUint8(),this.streamType=u.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=u.readUint24(),this.maxBitrate=u.readUint32(),this.avgBitrate=u.readUint32(),this.size-=13,this.parseRemainingDescriptors(u)}},DecoderSpecificInfo=class extends Descriptor{constructor(u){super(DecSpecificInfoTag,u)}},SLConfigDescriptor=class extends Descriptor{constructor(u){super(SLConfigDescrTag,u)}},DESCRIPTOR_CLASSES={Descriptor,ES_Descriptor,DecoderConfigDescriptor,DecoderSpecificInfo,SLConfigDescriptor},descTagToName={[ES_DescrTag]:"ES_Descriptor",[DecoderConfigDescrTag]:"DecoderConfigDescriptor",[DecSpecificInfoTag]:"DecoderSpecificInfo",[SLConfigDescrTag]:"SLConfigDescriptor"},MPEG4DescriptorParser=class{constructor(){this.parseOneDescriptor=Descriptor.prototype.parseOneDescriptor}getDescriptorName(u){return descTagToName[u]}},all_boxes_exports={};__export(all_boxes_exports,{CoLLBox:()=>CoLLBox,ItemContentIDPropertyBox:()=>ItemContentIDPropertyBox,OpusSampleEntry:()=>OpusSampleEntry,SmDmBox:()=>SmDmBox,a1lxBox:()=>a1lxBox,a1opBox:()=>a1opBox,ac_3SampleEntry:()=>ac_3SampleEntry,ac_4SampleEntry:()=>ac_4SampleEntry,aebrBox:()=>aebrBox,afbrBox:()=>afbrBox,albcBox:()=>albcBox,alstSampleGroupEntry:()=>alstSampleGroupEntry,altrBox:()=>altrBox,auxCBox:()=>auxCBox,av01SampleEntry:()=>av01SampleEntry,av1CBox:()=>av1CBox,avc1SampleEntry:()=>avc1SampleEntry,avc2SampleEntry:()=>avc2SampleEntry,avc3SampleEntry:()=>avc3SampleEntry,avc4SampleEntry:()=>avc4SampleEntry,avcCBox:()=>avcCBox,avllSampleGroupEntry:()=>avllSampleGroupEntry,avs3SampleEntry:()=>avs3SampleEntry,avssSampleGroupEntry:()=>avssSampleGroupEntry,brstBox:()=>brstBox,btrtBox:()=>btrtBox,bxmlBox:()=>bxmlBox,ccstBox:()=>ccstBox,cdefBox:()=>cdefBox,clapBox:()=>clapBox,clefBox:()=>clefBox,clliBox:()=>clliBox,cmexBox:()=>cmexBox,cminBox:()=>cminBox,cmpdBox:()=>cmpdBox,co64Box:()=>co64Box,colrBox:()=>colrBox,coviBox:()=>coviBox,cprtBox:()=>cprtBox,cschBox:()=>cschBox,cslgBox:()=>cslgBox,cttsBox:()=>cttsBox,dOpsBox:()=>dOpsBox,dac3Box:()=>dac3Box,dataBox:()=>dataBox,dav1SampleEntry:()=>dav1SampleEntry,dec3Box:()=>dec3Box,dfLaBox:()=>dfLaBox,dimmBox:()=>dimmBox,dinfBox:()=>dinfBox,dmax:()=>dmax,dmedBox:()=>dmedBox,dobrBox:()=>dobrBox,drefBox:()=>drefBox,drepBox:()=>drepBox,dtrtSampleGroupEntry:()=>dtrtSampleGroupEntry,dvh1SampleEntry:()=>dvh1SampleEntry,dvheSampleEntry:()=>dvheSampleEntry,ec_3SampleEntry:()=>ec_3SampleEntry,edtsBox:()=>edtsBox,elngBox:()=>elngBox,elstBox:()=>elstBox,emsgBox:()=>emsgBox,encaSampleEntry:()=>encaSampleEntry,encmSampleEntry:()=>encmSampleEntry,encsSampleEntry:()=>encsSampleEntry,enctSampleEntry:()=>enctSampleEntry,encuSampleEntry:()=>encuSampleEntry,encvSampleEntry:()=>encvSampleEntry,enofBox:()=>enofBox,eqivBox:()=>eqivBox,esdsBox:()=>esdsBox,etypBox:()=>etypBox,fLaCSampleEntry:()=>fLaCSampleEntry,favcBox:()=>favcBox,fielBox:()=>fielBox,fobrBox:()=>fobrBox,freeBox:()=>freeBox,frmaBox:()=>frmaBox,ftypBox:()=>ftypBox,grplBox:()=>grplBox,hdlrBox:()=>hdlrBox,hev1SampleEntry:()=>hev1SampleEntry,hev2SampleEntry:()=>hev2SampleEntry,hinfBox:()=>hinfBox,hmhdBox:()=>hmhdBox,hntiBox:()=>hntiBox,hvc1SampleEntry:()=>hvc1SampleEntry,hvc2SampleEntry:()=>hvc2SampleEntry,hvcCBox:()=>hvcCBox,hvt1SampleEntry:()=>hvt1SampleEntry,iaugBox:()=>iaugBox,idatBox:()=>idatBox,iinfBox:()=>iinfBox,ilocBox:()=>ilocBox,ilstBox:()=>ilstBox,imirBox:()=>imirBox,infeBox:()=>infeBox,iodsBox:()=>iodsBox,ipcoBox:()=>ipcoBox,ipmaBox:()=>ipmaBox,iproBox:()=>iproBox,iprpBox:()=>iprpBox,irefBox:()=>irefBox,irotBox:()=>irotBox,ispeBox:()=>ispeBox,itaiBox:()=>itaiBox,j2kHBox:()=>j2kHBox,j2kiSampleEntry:()=>j2kiSampleEntry,keysBox:()=>keysBox,kindBox:()=>kindBox,levaBox:()=>levaBox,lhe1SampleEntry:()=>lhe1SampleEntry,lhv1SampleEntry:()=>lhv1SampleEntry,lhvCBox:()=>lhvCBox,lselBox:()=>lselBox,m4aeSampleEntry:()=>m4aeSampleEntry,maxrBox:()=>maxrBox,mdatBox:()=>mdatBox,mdcvBox:()=>mdcvBox,mdhdBox:()=>mdhdBox,mdiaBox:()=>mdiaBox,mecoBox:()=>mecoBox,mehdBox:()=>mehdBox,metaBox:()=>metaBox,mettSampleEntry:()=>mettSampleEntry,metxSampleEntry:()=>metxSampleEntry,mfhdBox:()=>mfhdBox,mfraBox:()=>mfraBox,mfroBox:()=>mfroBox,mha1SampleEntry:()=>mha1SampleEntry,mha2SampleEntry:()=>mha2SampleEntry,mhm1SampleEntry:()=>mhm1SampleEntry,mhm2SampleEntry:()=>mhm2SampleEntry,minfBox:()=>minfBox,mjp2SampleEntry:()=>mjp2SampleEntry,mjpgSampleEntry:()=>mjpgSampleEntry,moofBox:()=>moofBox,moovBox:()=>moovBox,mp4aSampleEntry:()=>mp4aSampleEntry,mp4sSampleEntry:()=>mp4sSampleEntry,mp4vSampleEntry:()=>mp4vSampleEntry,mskCBox:()=>mskCBox,msrcTrackGroupTypeBox:()=>msrcTrackGroupTypeBox,mvexBox:()=>mvexBox,mvhdBox:()=>mvhdBox,mvifSampleGroupEntry:()=>mvifSampleGroupEntry,nmhdBox:()=>nmhdBox,npckBox:()=>npckBox,numpBox:()=>numpBox,padbBox:()=>padbBox,panoBox:()=>panoBox,paspBox:()=>paspBox,paylBox:()=>paylBox,paytBox:()=>paytBox,pdinBox:()=>pdinBox,piffLsmBox:()=>piffLsmBox,piffPsshBox:()=>piffPsshBox,piffSencBox:()=>piffSencBox,piffTencBox:()=>piffTencBox,piffTfrfBox:()=>piffTfrfBox,piffTfxdBox:()=>piffTfxdBox,pitmBox:()=>pitmBox,pixiBox:()=>pixiBox,pmaxBox:()=>pmaxBox,povdBox:()=>povdBox,prdiBox:()=>prdiBox,prfrBox:()=>prfrBox,prftBox:()=>prftBox,prgrBox:()=>prgrBox,profBox:()=>profBox,prolSampleGroupEntry:()=>prolSampleGroupEntry,psshBox:()=>psshBox,pymdBox:()=>pymdBox,rapSampleGroupEntry:()=>rapSampleGroupEntry,rashSampleGroupEntry:()=>rashSampleGroupEntry,resvSampleEntry:()=>resvSampleEntry,rinfBox:()=>rinfBox,rollSampleGroupEntry:()=>rollSampleGroupEntry,rtp_Box:()=>rtp_Box,saioBox:()=>saioBox,saizBox:()=>saizBox,sbgpBox:()=>sbgpBox,sbpmBox:()=>sbpmBox,sbttSampleEntry:()=>sbttSampleEntry,schiBox:()=>schiBox,schmBox:()=>schmBox,scifSampleGroupEntry:()=>scifSampleGroupEntry,scnmSampleGroupEntry:()=>scnmSampleGroupEntry,sdp_Box:()=>sdp_Box,sdtpBox:()=>sdtpBox,seigSampleGroupEntry:()=>seigSampleGroupEntry,sencBox:()=>sencBox,sgpdBox:()=>sgpdBox,sidxBox:()=>sidxBox,sinfBox:()=>sinfBox,skipBox:()=>skipBox,slidBox:()=>slidBox,smhdBox:()=>smhdBox,sratBox:()=>sratBox,ssixBox:()=>ssixBox,stblBox:()=>stblBox,stcoBox:()=>stcoBox,stdpBox:()=>stdpBox,sterBox:()=>sterBox,sthdBox:()=>sthdBox,stppSampleEntry:()=>stppSampleEntry,strdBox:()=>strdBox,striBox:()=>striBox,strkBox:()=>strkBox,stsaSampleGroupEntry:()=>stsaSampleGroupEntry,stscBox:()=>stscBox,stsdBox:()=>stsdBox,stsgBox:()=>stsgBox,stshBox:()=>stshBox,stssBox:()=>stssBox,stszBox:()=>stszBox,sttsBox:()=>sttsBox,stviBox:()=>stviBox,stxtSampleEntry:()=>stxtSampleEntry,stypBox:()=>stypBox,stz2Box:()=>stz2Box,subsBox:()=>subsBox,syncSampleGroupEntry:()=>syncSampleGroupEntry,taicBox:()=>taicBox,taptBox:()=>taptBox,teleSampleGroupEntry:()=>teleSampleGroupEntry,tencBox:()=>tencBox,tfdtBox:()=>tfdtBox,tfhdBox:()=>tfhdBox,tfraBox:()=>tfraBox,tkhdBox:()=>tkhdBox,tmaxBox:()=>tmaxBox,tminBox:()=>tminBox,totlBox:()=>totlBox,tpayBox:()=>tpayBox,tpylBox:()=>tpylBox,trafBox:()=>trafBox,trakBox:()=>trakBox,trefBox:()=>trefBox,trepBox:()=>trepBox,trexBox:()=>trexBox,trgrBox:()=>trgrBox,trpyBox:()=>trpyBox,trunBox:()=>trunBox,tsasSampleGroupEntry:()=>tsasSampleGroupEntry,tsclSampleGroupEntry:()=>tsclSampleGroupEntry,tselBox:()=>tselBox,tsynBox:()=>tsynBox,tx3gSampleEntry:()=>tx3gSampleEntry,txtcBox:()=>txtcBox,tycoBox:()=>tycoBox,udesBox:()=>udesBox,udtaBox:()=>udtaBox,uncCBox:()=>uncCBox,uncvSampleEntry:()=>uncvSampleEntry,urlBox:()=>urlBox,urnBox:()=>urnBox,viprSampleGroupEntry:()=>viprSampleGroupEntry,vmhdBox:()=>vmhdBox,vp08SampleEntry:()=>vp08SampleEntry,vp09SampleEntry:()=>vp09SampleEntry,vpcCBox:()=>vpcCBox,vttCBox:()=>vttCBox,vttcBox:()=>vttcBox,vvc1SampleEntry:()=>vvc1SampleEntry,vvcCBox:()=>vvcCBox,vvcNSampleEntry:()=>vvcNSampleEntry,vvi1SampleEntry:()=>vvi1SampleEntry,vvnCBox:()=>vvnCBox,vvs1SampleEntry:()=>vvs1SampleEntry,waveBox:()=>waveBox,wbbrBox:()=>wbbrBox,wvttSampleEntry:()=>wvttSampleEntry,xmlBox:()=>xmlBox});var pn,a1lxBox=(pn=class extends Box{constructor(){super(...arguments),this.box_name="AV1LayeredImageIndexingProperty"}parse(o){const n=((o.readUint8()&1&1)+1)*16;this.layer_size=[];for(let r=0;r<3;r++)n===16?this.layer_size[r]=o.readUint16():this.layer_size[r]=o.readUint32()}},pn.fourcc="a1lx",pn),fn,a1opBox=(fn=class extends Box{constructor(){super(...arguments),this.box_name="OperatingPointSelectorProperty"}parse(o){this.op_index=o.readUint8()}},fn.fourcc="a1op",fn),hn,auxCBox=(hn=class extends FullBox{constructor(){super(...arguments),this.box_name="AuxiliaryTypeProperty"}parse(o){this.parseFullHeader(o),this.aux_type=o.readCString();const l=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=o.readUint8Array(l)}},hn.fourcc="auxC",hn),Rn,btrtBox=(Rn=class extends Box{constructor(){super(...arguments),this.box_name="BitRateBox"}parse(o){this.bufferSizeDB=o.readUint32(),this.maxBitrate=o.readUint32(),this.avgBitrate=o.readUint32()}},Rn.fourcc="btrt",Rn),Bn,ccstBox=(Bn=class extends FullBox{constructor(){super(...arguments),this.box_name="CodingConstraintsBox"}parse(o){this.parseFullHeader(o);const l=o.readUint8();this.all_ref_pics_intra=(l&128)===128,this.intra_pred_used=(l&64)===64,this.max_ref_per_pic=(l&63)>>2,o.readUint24()}},Bn.fourcc="ccst",Bn),Sn,cdefBox=(Sn=class extends Box{constructor(){super(...arguments),this.box_name="ComponentDefinitionBox"}parse(o){this.channel_count=o.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[];for(let l=0;l<this.channel_count;l++)this.channel_indexes.push(o.readUint16()),this.channel_types.push(o.readUint16()),this.channel_associations.push(o.readUint16())}},Sn.fourcc="cdef",Sn),yn,clapBox=(yn=class extends Box{constructor(){super(...arguments),this.box_name="CleanApertureBox"}parse(o){this.cleanApertureWidthN=o.readUint32(),this.cleanApertureWidthD=o.readUint32(),this.cleanApertureHeightN=o.readUint32(),this.cleanApertureHeightD=o.readUint32(),this.horizOffN=o.readUint32(),this.horizOffD=o.readUint32(),this.vertOffN=o.readUint32(),this.vertOffD=o.readUint32()}},yn.fourcc="clap",yn),Vn,clliBox=(Vn=class extends Box{constructor(){super(...arguments),this.box_name="ContentLightLevelBox"}parse(o){this.max_content_light_level=o.readUint16(),this.max_pic_average_light_level=o.readUint16()}},Vn.fourcc="clli",Vn),Jn,cmexBox=(Jn=class extends Box{constructor(){super(...arguments),this.box_name="CameraExtrinsicMatrixProperty"}parse(o){this.flags&1&&(this.pos_x=o.readInt32()),this.flags&2&&(this.pos_y=o.readInt32()),this.flags&4&&(this.pos_z=o.readInt32()),this.flags&8&&(this.version===0?this.flags&16?(this.quat_x=o.readInt32(),this.quat_y=o.readInt32(),this.quat_z=o.readInt32()):(this.quat_x=o.readInt16(),this.quat_y=o.readInt16(),this.quat_z=o.readInt16()):this.version),this.flags&32&&(this.id=o.readUint32())}},Jn.fourcc="cmex",Jn),En,cminBox=(En=class extends Box{constructor(){super(...arguments),this.box_name="CameraIntrinsicMatrixProperty"}parse(o){this.focal_length_x=o.readInt32(),this.principal_point_x=o.readInt32(),this.principal_point_y=o.readInt32(),this.flags&1&&(this.focal_length_y=o.readInt32(),this.skew_factor=o.readInt32())}},En.fourcc="cmin",En),mn,cmpdBox=(mn=class extends Box{constructor(){super(...arguments),this.box_name="ComponentDefinitionBox"}parse(o){this.component_count=o.readUint32(),this.component_types=[],this.component_type_urls=[];for(let l=0;l<this.component_count;l++){const n=o.readUint16();this.component_types.push(n),n>=32768&&this.component_type_urls.push(o.readCString())}}},mn.fourcc="cmpd",mn),kn,co64Box=(kn=class extends FullBox{constructor(){super(...arguments),this.box_name="ChunkLargeOffsetBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.chunk_offsets=[],this.version===0)for(let n=0;n<l;n++)this.chunk_offsets.push(o.readUint64())}write(o){this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(o),o.writeUint32(this.chunk_offsets.length);for(let l=0;l<this.chunk_offsets.length;l++)o.writeUint64(this.chunk_offsets[l])}},kn.fourcc="co64",kn),Nn,CoLLBox=(Nn=class extends FullBox{constructor(){super(...arguments),this.box_name="ContentLightLevelBox"}parse(o){this.parseFullHeader(o),this.maxCLL=o.readUint16(),this.maxFALL=o.readUint16()}},Nn.fourcc="CoLL",Nn),SphereRegion=class{toString(){let u="centre_azimuth: ";return u+=this.centre_azimuth,u+=" (",u+=this.centre_azimuth*2**-16,u+="°), centre_elevation: ",u+=this.centre_elevation,u+=" (",u+=this.centre_elevation*2**-16,u+="°), centre_tilt: ",u+=this.centre_tilt,u+=" (",u+=this.centre_tilt*2**-16,u+="°)",this.range_included_flag&&(u+=", azimuth_range: ",u+=this.azimuth_range,u+=" (",u+=this.azimuth_range*2**-16,u+="°), elevation_range: ",u+=this.elevation_range,u+=" (",u+=this.elevation_range*2**-16,u+="°)"),this.interpolate_included_flag&&(u+=", interpolate: ",u+=this.interpolate),u}},CoverageSphereRegion=class{toString(){let u="";return this.view_idc&&(u+="view_idc: ",u+=this.view_idc,u+=", "),u+="sphere_region: {",u+=this.sphere_region,u+="}",u}},Tn,coviBox=(Tn=class extends FullBox{constructor(){super(...arguments),this.box_name="CoverageInformationBox"}parse(o){this.parseFullHeader(o),this.coverage_shape_type=o.readUint8();const l=o.readUint8(),n=o.readInt8(),r=n&128;r&&(this.default_view_idc=(n&96)>>5),this.coverage_regions=new Array;for(let t=0;t<l;t++){const e=new CoverageSphereRegion;r&&(e.view_idc=o.readUint8()>>6),e.sphere_region=this.parseSphereRegion(o,!0,!0),this.coverage_regions.push(e)}}parseSphereRegion(o,l,n){const r=new SphereRegion;return r.centre_azimuth=o.readInt32(),r.centre_elevation=o.readInt32(),r.centre_tilt=o.readInt32(),r.range_included_flag=l,l&&(r.azimuth_range=o.readUint32(),r.elevation_range=o.readUint32()),r.interpolate_included_flag=n,n&&(r.interpolate=(o.readUint8()&128)===128),r}},Tn.fourcc="covi",Tn),vn,cprtBox=(vn=class extends FullBox{constructor(){super(...arguments),this.box_name="CopyrightBox"}parse(o){this.parseFullHeader(o),this.parseLanguage(o),this.notice=o.readCString()}},vn.fourcc="cprt",vn),Cn,cschBox=(Cn=class extends FullBox{constructor(){super(...arguments),this.box_name="CompatibleSchemeTypeBox"}parse(o){this.parseFullHeader(o),this.scheme_type=o.readString(4),this.scheme_version=o.readUint32(),this.flags&1&&(this.scheme_uri=o.readCString())}},Cn.fourcc="csch",Cn),INT32_MAX=2147483647,Wn,cslgBox=(Wn=class extends FullBox{constructor(){super(...arguments),this.box_name="CompositionToDecodeBox"}parse(o){this.parseFullHeader(o),this.version===0?(this.compositionToDTSShift=o.readInt32(),this.leastDecodeToDisplayDelta=o.readInt32(),this.greatestDecodeToDisplayDelta=o.readInt32(),this.compositionStartTime=o.readInt32(),this.compositionEndTime=o.readInt32()):this.version===1&&(this.compositionToDTSShift=o.readInt64(),this.leastDecodeToDisplayDelta=o.readInt64(),this.greatestDecodeToDisplayDelta=o.readInt64(),this.compositionStartTime=o.readInt64(),this.compositionEndTime=o.readInt64())}write(o){this.version=0,(this.compositionToDTSShift>INT32_MAX||this.leastDecodeToDisplayDelta>INT32_MAX||this.greatestDecodeToDisplayDelta>INT32_MAX||this.compositionStartTime>INT32_MAX||this.compositionEndTime>INT32_MAX)&&(this.version=1),this.flags=0,this.version===0?(this.size=4*5,this.writeHeader(o),o.writeInt32(this.compositionToDTSShift),o.writeInt32(this.leastDecodeToDisplayDelta),o.writeInt32(this.greatestDecodeToDisplayDelta),o.writeInt32(this.compositionStartTime),o.writeInt32(this.compositionEndTime)):this.version===1&&(this.size=8*5,this.writeHeader(o),o.writeInt64(this.compositionToDTSShift),o.writeInt64(this.leastDecodeToDisplayDelta),o.writeInt64(this.greatestDecodeToDisplayDelta),o.writeInt64(this.compositionStartTime),o.writeInt64(this.compositionEndTime))}},Wn.fourcc="cslg",Wn),bn,cttsBox=(bn=class extends FullBox{constructor(){super(...arguments),this.box_name="CompositionOffsetBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.sample_counts=[],this.sample_offsets=[],this.version===0)for(let n=0;n<l;n++){this.sample_counts.push(o.readUint32());const r=o.readInt32();r<0&&Log.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(r)}else if(this.version===1)for(let n=0;n<l;n++)this.sample_counts.push(o.readUint32()),this.sample_offsets.push(o.readInt32())}write(o){this.version=this.sample_offsets.some(l=>l<0)?1:0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(o),o.writeUint32(this.sample_counts.length);for(let l=0;l<this.sample_counts.length;l++)o.writeUint32(this.sample_counts[l]),this.version===1?o.writeInt32(this.sample_offsets[l]):o.writeUint32(this.sample_offsets[l])}unpack(o){let l=0;for(let n=0;n<this.sample_counts.length;n++)for(let r=0;r<this.sample_counts[n];r++)o[l].pts=o[l].dts+this.sample_offsets[n],l++}},bn.fourcc="ctts",bn),On,dac3Box=(On=class extends Box{constructor(){super(...arguments),this.box_name="AC3SpecificBox"}parse(o){const l=o.readUint8(),n=o.readUint8(),r=o.readUint8();this.fscod=l>>6,this.bsid=l>>1&31,this.bsmod=(l&1)<<2|n>>6&3,this.acmod=n>>3&7,this.lfeon=n>>2&1,this.bit_rate_code=n&3|r>>5&7}},On.fourcc="dac3",On),Zn,dec3Box=(Zn=class extends Box{constructor(){super(...arguments),this.box_name="EC3SpecificBox"}parse(o){const l=o.readUint16();this.data_rate=l>>3,this.num_ind_sub=l&7,this.ind_subs=[];for(let n=0;n<this.num_ind_sub+1;n++){const r=o.readUint8(),t=o.readUint8(),e=o.readUint8(),i={fscod:r>>6,bsid:r>>1&31,bsmod:(r&1)<<4|t>>4&15,acmod:t>>1&7,lfeon:t&1,num_dep_sub:e>>1&15};this.ind_subs.push(i),i.num_dep_sub>0&&(i.chan_loc=(e&1)<<8|o.readUint8())}}},Zn.fourcc="dec3",Zn),Dn,dfLaBox=(Dn=class extends FullBox{constructor(){super(...arguments),this.box_name="FLACSpecificBox"}parse(o){this.parseFullHeader(o);const l=127,n=128,r=[],t=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];let e;do{e=o.readUint8();const i=Math.min(e&l,t.length-1);i?o.readUint8Array(o.readUint24()):(o.readUint8Array(13),this.samplerate=o.readUint32()>>12,o.readUint8Array(20)),r.push(t[i])}while(e&n);this.numMetadataBlocks=r.length+" ("+r.join(", ")+")"}},Dn.fourcc="dfLa",Dn),wn,dimmBox=(wn=class extends Box{constructor(){super(...arguments),this.box_name="hintimmediateBytesSent"}parse(o){this.bytessent=o.readUint64()}},wn.fourcc="dimm",wn),gn,dmax=(gn=class extends Box{constructor(){super(...arguments),this.box_name="hintlongestpacket"}parse(o){this.time=o.readUint32()}},gn.fourcc="dmax",gn),xn,dmedBox=(xn=class extends Box{constructor(){super(...arguments),this.box_name="hintmediaBytesSent"}parse(o){this.bytessent=o.readUint64()}},xn.fourcc="dmed",xn),In,dOpsBox=(In=class extends Box{constructor(){super(...arguments),this.box_name="OpusSpecificBox"}parse(o){if(this.Version=o.readUint8(),this.OutputChannelCount=o.readUint8(),this.PreSkip=o.readUint16(),this.InputSampleRate=o.readUint32(),this.OutputGain=o.readInt16(),this.ChannelMappingFamily=o.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=o.readUint8(),this.CoupledCount=o.readUint8(),this.ChannelMapping=[];for(let l=0;l<this.OutputChannelCount;l++)this.ChannelMapping[l]=o.readUint8()}}write(o){if(this.size=11,this.ChannelMappingFamily!==0&&(this.size+=2+this.OutputChannelCount),this.writeHeader(o),o.writeUint8(this.Version),o.writeUint8(this.OutputChannelCount),o.writeUint16(this.PreSkip),o.writeUint32(this.InputSampleRate),o.writeInt16(this.OutputGain),o.writeUint8(this.ChannelMappingFamily),this.ChannelMappingFamily!==0){o.writeUint8(this.StreamCount),o.writeUint8(this.CoupledCount);for(let l=0;l<this.OutputChannelCount;l++)o.writeUint8(this.ChannelMapping[l])}}},In.fourcc="dOps",In),Mn,drepBox=(Mn=class extends Box{constructor(){super(...arguments),this.box_name="hintrepeatedBytesSent"}parse(o){this.bytessent=o.readUint64()}},Mn.fourcc="drep",Mn),_n,elstBox=(_n=class extends FullBox{constructor(){super(...arguments),this.box_name="EditListBox"}parse(o){this.parseFullHeader(o),this.entries=[];const l=o.readUint32();for(let n=0;n<l;n++){const r={segment_duration:this.version===1?o.readUint64():o.readUint32(),media_time:this.version===1?o.readInt64():o.readInt32(),media_rate_integer:o.readInt16(),media_rate_fraction:o.readInt16()};this.entries.push(r)}}write(o){const l=this.entries.some(n=>n.segment_duration>MAX_UINT32||n.media_time>MAX_UINT32)||this.version===1;this.version=l?1:0,this.size=4+12*this.entries.length,this.size+=l?2*4*this.entries.length:0,this.writeHeader(o),o.writeUint32(this.entries.length);for(let n=0;n<this.entries.length;n++){const r=this.entries[n];l?(o.writeUint64(r.segment_duration),o.writeInt64(r.media_time)):(o.writeUint32(r.segment_duration),o.writeInt32(r.media_time)),o.writeInt16(r.media_rate_integer),o.writeInt16(r.media_rate_fraction)}}},_n.fourcc="elst",_n),Pn,emsgBox=(Pn=class extends FullBox{constructor(){super(...arguments),this.box_name="EventMessageBox"}parse(o){this.parseFullHeader(o),this.version===1?(this.timescale=o.readUint32(),this.presentation_time=o.readUint64(),this.event_duration=o.readUint32(),this.id=o.readUint32(),this.scheme_id_uri=o.readCString(),this.value=o.readCString()):(this.scheme_id_uri=o.readCString(),this.value=o.readCString(),this.timescale=o.readUint32(),this.presentation_time_delta=o.readUint32(),this.event_duration=o.readUint32(),this.id=o.readUint32());let l=this.size-this.hdr_size-(4*4+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version===1&&(l-=4),this.message_data=o.readUint8Array(l)}write(o){this.version=0,this.flags=0,this.size=4*4+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(o),o.writeCString(this.scheme_id_uri),o.writeCString(this.value),o.writeUint32(this.timescale),o.writeUint32(this.presentation_time_delta),o.writeUint32(this.event_duration),o.writeUint32(this.id),o.writeUint8Array(this.message_data)}},Pn.fourcc="emsg",Pn),EntityToGroup=class extends FullBox{parse(u){this.parseFullHeader(u),this.group_id=u.readUint32(),this.num_entities_in_group=u.readUint32(),this.entity_ids=[];for(let o=0;o<this.num_entities_in_group;o++){const l=u.readUint32();this.entity_ids.push(l)}}},$n,aebrBox=($n=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Auto exposure bracketing"}},$n.fourcc="aebr",$n),Ln,afbrBox=(Ln=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Flash exposure information"}},Ln.fourcc="afbr",Ln),An,albcBox=(An=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Album collection"}},An.fourcc="albc",An),Gn,altrBox=(Gn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Alternative entity"}},Gn.fourcc="altr",Gn),Hn,brstBox=(Hn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Burst image"}},Hn.fourcc="brst",Hn),zn,dobrBox=(zn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Depth of field bracketing"}},zn.fourcc="dobr",zn),Yn,eqivBox=(Yn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Equivalent entity"}},Yn.fourcc="eqiv",Yn),jn,favcBox=(jn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Favorites collection"}},jn.fourcc="favc",jn),Xn,fobrBox=(Xn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Focus bracketing"}},Xn.fourcc="fobr",Xn),qn,iaugBox=(qn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Image item with an audio track"}},qn.fourcc="iaug",qn),Kn,panoBox=(Kn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Panorama"}},Kn.fourcc="pano",Kn),ti,slidBox=(ti=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Slideshow"}},ti.fourcc="slid",ti),ei,sterBox=(ei=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Stereo"}},ei.fourcc="ster",ei),ni,tsynBox=(ni=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Time-synchronized capture"}},ni.fourcc="tsyn",ni),ii,wbbrBox=(ii=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="White balance bracketing"}},ii.fourcc="wbbr",ii),oi,prgrBox=(oi=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Progressive rendering"}},oi.fourcc="prgr",oi),ri,pymdBox=(ri=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Image pyramid"}parse(o){this.parseFullHeader(o),this.group_id=o.readUint32(),this.num_entities_in_group=o.readUint32(),this.entity_ids=[];for(let l=0;l<this.num_entities_in_group;l++){const n=o.readUint32();this.entity_ids.push(n)}this.tile_size_x=o.readUint16(),this.tile_size_y=o.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[];for(let l=0;l<this.num_entities_in_group;l++)this.layer_binning[l]=o.readUint16(),this.tiles_in_layer_row_minus1[l]=o.readUint16(),this.tiles_in_layer_column_minus1[l]=o.readUint16()}},ri.fourcc="pymd",ri),li,fielBox=(li=class extends Box{constructor(){super(...arguments),this.box_name="FieldHandlingBox"}parse(o){this.fieldCount=o.readUint8(),this.fieldOrdering=o.readUint8()}},li.fourcc="fiel",li),ai,frmaBox=(ai=class extends Box{constructor(){super(...arguments),this.box_name="OriginalFormatBox"}parse(o){this.data_format=o.readString(4)}},ai.fourcc="frma",ai),si,imirBox=(si=class extends Box{constructor(){super(...arguments),this.box_name="ImageMirror"}parse(o){const l=o.readUint8();this.reserved=l>>7,this.axis=l&1}},si.fourcc="imir",si),di,ipmaBox=(di=class extends FullBox{constructor(){super(...arguments),this.box_name="ItemPropertyAssociationBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();this.associations=[];for(let n=0;n<l;n++){const r=this.version<1?o.readUint16():o.readUint32(),t=[],e=o.readUint8();for(let i=0;i<e;i++){const a=o.readUint8();t.push({essential:(a&128)>>7===1,property_index:this.flags&1?(a&127)<<8|o.readUint8():a&127})}this.associations.push({id:r,props:t})}}},di.fourcc="ipma",di),ui,irotBox=(ui=class extends Box{constructor(){super(...arguments),this.box_name="ImageRotation"}parse(o){this.angle=o.readUint8()&3}},ui.fourcc="irot",ui),ci,ispeBox=(ci=class extends FullBox{constructor(){super(...arguments),this.box_name="ImageSpatialExtentsProperty"}parse(o){this.parseFullHeader(o),this.image_width=o.readUint32(),this.image_height=o.readUint32()}},ci.fourcc="ispe",ci),Ui,itaiBox=(Ui=class extends FullBox{constructor(){super(...arguments),this.box_name="TAITimestampBox"}parse(o){this.TAI_timestamp=o.readUint64();const l=o.readUint8();this.sychronization_state=l>>7&1,this.timestamp_generation_failure=l>>6&1,this.timestamp_is_modified=l>>5&1}},Ui.fourcc="itai",Ui),Fi,kindBox=(Fi=class extends FullBox{constructor(){super(...arguments),this.box_name="KindBox"}parse(o){this.parseFullHeader(o),this.schemeURI=o.readCString(),this.isEndOfBox(o)||(this.value=o.readCString())}write(o){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value?this.value.length+1:0),this.writeHeader(o),o.writeCString(this.schemeURI),this.value&&o.writeCString(this.value)}},Fi.fourcc="kind",Fi),Qi,levaBox=(Qi=class extends FullBox{constructor(){super(...arguments),this.box_name="LevelAssignmentBox"}parse(o){this.parseFullHeader(o);const l=o.readUint8();this.levels=[];for(let n=0;n<l;n++){const r={};this.levels[n]=r,r.track_ID=o.readUint32();const t=o.readUint8();switch(r.padding_flag=t>>7,r.assignment_type=t&127,r.assignment_type){case 0:r.grouping_type=o.readString(4);break;case 1:r.grouping_type=o.readString(4),r.grouping_type_parameter=o.readUint32();break;case 2:break;case 3:break;case 4:r.sub_track_id=o.readUint32();break;default:Log.warn("BoxParser",`Unknown level assignment type: ${r.assignment_type}`)}}}},Qi.fourcc="leva",Qi),pi,lhvCBox=(pi=class extends Box{constructor(){super(...arguments),this.box_name="LHEVCConfigurationBox"}parse(o){this.configurationVersion=o.readUint8(),this.min_spatial_segmentation_idc=o.readUint16()&4095,this.parallelismType=o.readUint8()&3;let l=o.readUint8();this.numTemporalLayers=(l&13)>>3,this.temporalIdNested=(l&4)>>2,this.lengthSizeMinusOne=l&3,this.nalu_arrays=[];const n=o.readUint8();for(let r=0;r<n;r++){const t=[];this.nalu_arrays.push(t),l=o.readUint8(),t.completeness=(l&128)>>7,t.nalu_type=l&63;const e=o.readUint16();for(let i=0;i<e;i++){const a=o.readUint16();t.push({data:o.readUint8Array(a)})}}}},pi.fourcc="lhvC",pi),fi,lselBox=(fi=class extends Box{constructor(){super(...arguments),this.box_name="LayerSelectorProperty"}parse(o){this.layer_id=o.readUint16()}},fi.fourcc="lsel",fi),hi,maxrBox=(hi=class extends Box{constructor(){super(...arguments),this.box_name="hintmaxrate"}parse(o){this.period=o.readUint32(),this.bytes=o.readUint32()}},hi.fourcc="maxr",hi),ColorPoint=class{constructor(u,o){this.x=u,this.y=o}toString(){return"("+this.x+","+this.y+")"}},Ri,mdcvBox=(Ri=class extends Box{constructor(){super(...arguments),this.box_name="MasteringDisplayColourVolumeBox"}parse(o){this.display_primaries=[],this.display_primaries[0]=new ColorPoint(o.readUint16(),o.readUint16()),this.display_primaries[1]=new ColorPoint(o.readUint16(),o.readUint16()),this.display_primaries[2]=new ColorPoint(o.readUint16(),o.readUint16()),this.white_point=new ColorPoint(o.readUint16(),o.readUint16()),this.max_display_mastering_luminance=o.readUint32(),this.min_display_mastering_luminance=o.readUint32()}},Ri.fourcc="mdcv",Ri),Bi,mfroBox=(Bi=class extends FullBox{constructor(){super(...arguments),this.box_name="MovieFragmentRandomAccessOffsetBox"}parse(o){this.parseFullHeader(o),this._size=o.readUint32()}},Bi.fourcc="mfro",Bi),Si,mskCBox=(Si=class extends FullBox{constructor(){super(...arguments),this.box_name="MaskConfigurationProperty"}parse(o){this.parseFullHeader(o),this.bits_per_pixel=o.readUint8()}},Si.fourcc="mskC",Si),yi,npckBox=(yi=class extends Box{constructor(){super(...arguments),this.box_name="hintPacketsSent"}parse(o){this.packetssent=o.readUint32()}},yi.fourcc="npck",yi),Vi,numpBox=(Vi=class extends Box{constructor(){super(...arguments),this.box_name="hintPacketsSent"}parse(o){this.packetssent=o.readUint64()}},Vi.fourcc="nump",Vi),PaddingBit=class{constructor(u,o){this.pad1=u,this.pad2=o}},Ji,padbBox=(Ji=class extends FullBox{constructor(){super(...arguments),this.box_name="PaddingBitsBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();this.padbits=[];for(let n=0;n<Math.floor((l+1)/2);n++){const r=o.readUint8(),t=(r&112)>>4,e=r&7;this.padbits.push(new PaddingBit(t,e))}}},Ji.fourcc="padb",Ji),Ei,paspBox=(Ei=class extends Box{constructor(){super(...arguments),this.box_name="PixelAspectRatioBox"}parse(o){this.hSpacing=o.readUint32(),this.vSpacing=o.readUint32()}},Ei.fourcc="pasp",Ei),mi,paylBox=(mi=class extends Box{constructor(){super(...arguments),this.box_name="CuePayloadBox"}parse(o){this.text=o.readString(this.size-this.hdr_size)}},mi.fourcc="payl",mi),ki,paytBox=(ki=class extends Box{constructor(){super(...arguments),this.box_name="hintpayloadID"}parse(o){this.payloadID=o.readUint32();const l=o.readUint8();this.rtpmap_string=o.readString(l)}},ki.fourcc="payt",ki),Ni,pdinBox=(Ni=class extends FullBox{constructor(){super(...arguments),this.box_name="ProgressiveDownloadInfoBox",this.rate=[],this.initial_delay=[]}parse(o){this.parseFullHeader(o);const l=(this.size-this.hdr_size)/8;for(let n=0;n<l;n++)this.rate[n]=o.readUint32(),this.initial_delay[n]=o.readUint32()}},Ni.fourcc="pdin",Ni),Ti,pixiBox=(Ti=class extends FullBox{constructor(){super(...arguments),this.box_name="PixelInformationProperty"}parse(o){this.parseFullHeader(o),this.num_channels=o.readUint8(),this.bits_per_channels=[];for(let l=0;l<this.num_channels;l++)this.bits_per_channels[l]=o.readUint8()}},Ti.fourcc="pixi",Ti),vi,pmaxBox=(vi=class extends Box{constructor(){super(...arguments),this.box_name="hintlargestpacket"}parse(o){this.bytes=o.readUint32()}},vi.fourcc="pmax",vi),Ci,prdiBox=(Ci=class extends FullBox{constructor(){super(...arguments),this.box_name="ProgressiveDerivedImageItemInformationProperty"}parse(o){if(this.parseFullHeader(o),this.step_count=o.readUint16(),this.item_count=[],this.flags&2)for(let l=0;l<this.step_count;l++)this.item_count[l]=o.readUint16()}},Ci.fourcc="prdi",Ci),Wi,prfrBox=(Wi=class extends FullBox{constructor(){super(...arguments),this.box_name="ProjectionFormatBox"}parse(o){this.parseFullHeader(o),this.projection_type=o.readUint8()&31}},Wi.fourcc="prfr",Wi),bi,prftBox=(bi=class extends FullBox{constructor(){super(...arguments),this.box_name="ProducerReferenceTimeBox"}parse(o){this.parseFullHeader(o),this.ref_track_id=o.readUint32(),this.ntp_timestamp=o.readUint64(),this.version===0?this.media_time=o.readUint32():this.media_time=o.readUint64()}},bi.fourcc="prft",bi),Oi,psshBox=(Oi=class extends FullBox{constructor(){super(...arguments),this.box_name="ProtectionSystemSpecificHeaderBox"}parse(o){if(this.parseFullHeader(o),this.system_id=parseHex16(o),this.kid=[],this.version>0){const n=o.readUint32();for(let r=0;r<n;r++)this.kid[r]=parseHex16(o)}const l=o.readUint32();l>0&&(this.protection_data=o.readUint8Array(l))}},Oi.fourcc="pssh",Oi),Zi,clefBox=(Zi=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackCleanApertureDimensionsBox"}parse(o){this.parseFullHeader(o),this.width=o.readUint32(),this.height=o.readUint32()}},Zi.fourcc="clef",Zi);function parseItifData(u,o){if(u===dataBox.Types.UTF8)return new TextDecoder("utf-8").decode(o);const l=new DataView(o.buffer);if(u===dataBox.Types.BE_UNSIGNED_INT){if(o.length===1)return l.getUint8(0);if(o.length===2)return l.getUint16(0,!1);if(o.length===4)return l.getUint32(0,!1);if(o.length===8)return l.getBigUint64(0,!1);throw new Error("Unsupported ITIF_TYPE_BE_UNSIGNED_INT length "+o.length)}else if(u===dataBox.Types.BE_SIGNED_INT){if(o.length===1)return l.getInt8(0);if(o.length===2)return l.getInt16(0,!1);if(o.length===4)return l.getInt32(0,!1);if(o.length===8)return l.getBigInt64(0,!1);throw new Error("Unsupported ITIF_TYPE_BE_SIGNED_INT length "+o.length)}else if(u===dataBox.Types.BE_FLOAT32)return l.getFloat32(0,!1);Log.warn("DataBox","Unsupported or unimplemented itif data type: "+u)}var _,dataBox=(_=class extends Box{constructor(){super(...arguments),this.box_name="DataBox"}parse(o){this.valueType=o.readUint32(),this.country=o.readUint16(),this.country>255&&(o.seek(o.getPosition()-2),this.countryString=o.readString(2)),this.language=o.readUint16(),this.language>255&&(o.seek(o.getPosition()-2),this.parseLanguage(o)),this.raw=o.readUint8Array(this.size-this.hdr_size-8),this.value=parseItifData(this.valueType,this.raw)}},_.fourcc="data",_.Types={RESERVED:0,UTF8:1,UTF16:2,SJIS:3,UTF8_SORT:4,UTF16_SORT:5,JPEG:13,PNG:14,BE_SIGNED_INT:21,BE_UNSIGNED_INT:22,BE_FLOAT32:23,BE_FLOAT64:24,BMP:27,QT_ATOM:28,BE_SIGNED_INT8:65,BE_SIGNED_INT16:66,BE_SIGNED_INT32:67,BE_FLOAT32_POINT:70,BE_FLOAT32_DIMENSIONS:71,BE_FLOAT32_RECT:72,BE_SIGNED_INT64:74,BE_UNSIGNED_INT8:75,BE_UNSIGNED_INT16:76,BE_UNSIGNED_INT32:77,BE_UNSIGNED_INT64:78,BE_FLOAT64_AFFINE_TRANSFORM:79},_),Di,enofBox=(Di=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackEncodedPixelsDimensionsBox"}parse(o){this.parseFullHeader(o),this.width=o.readUint32(),this.height=o.readUint32()}},Di.fourcc="enof",Di),wi,ilstBox=(wi=class extends Box{constructor(){super(...arguments),this.box_name="IlstBox"}parse(o){this.list={};let l=this.size-this.hdr_size;for(;l>0;){const n=o.readUint32(),r=o.readUint32(),t=parseOneBox(o,!1,n-8);t.code===OK&&(this.list[r]=t.box),l-=n}}},wi.fourcc="ilst",wi),gi,keysBox=(gi=class extends FullBox{constructor(){super(...arguments),this.box_name="KeysBox"}parse(o){this.parseFullHeader(o),this.count=o.readUint32(),this.keys={};for(let l=0;l<this.count;l++){const n=o.readUint32();this.keys[l+1]=o.readString(n-4)}}},gi.fourcc="keys",gi),xi,profBox=(xi=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackProductionApertureDimensionsBox"}parse(o){this.parseFullHeader(o),this.width=o.readUint32(),this.height=o.readUint32()}},xi.fourcc="prof",xi),Ii,taptBox=(Ii=class extends ContainerBox{constructor(){super(...arguments),this.box_name="TrackApertureModeDimensionsBox",this.clefs=[],this.profs=[],this.enofs=[],this.subBoxNames=["clef","prof","enof"]}},Ii.fourcc="tapt",Ii),Mi,waveBox=(Mi=class extends ContainerBox{constructor(){super(...arguments),this.box_name="siDecompressionParamBox"}},Mi.fourcc="wave",Mi),_i,rtp_Box=(_i=class extends Box{constructor(){super(...arguments),this.box_name="rtpmoviehintinformation"}parse(o){this.descriptionformat=o.readString(4),this.sdptext=o.readString(this.size-this.hdr_size-4)}},_i.fourcc="rtp ",_i),Pi,saioBox=(Pi=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleAuxiliaryInformationOffsetsBox"}parse(o){this.parseFullHeader(o),this.flags&1&&(this.aux_info_type=o.readString(4),this.aux_info_type_parameter=o.readUint32());const l=o.readUint32();this.offset=[];for(let n=0;n<l;n++)this.version===0?this.offset[n]=o.readUint32():this.offset[n]=o.readUint64()}},Pi.fourcc="saio",Pi),$i,saizBox=($i=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleAuxiliaryInformationSizesBox"}parse(o){if(this.parseFullHeader(o),this.flags&1&&(this.aux_info_type=o.readString(4),this.aux_info_type_parameter=o.readUint32()),this.default_sample_info_size=o.readUint8(),this.sample_count=o.readUint32(),this.sample_info_size=[],this.default_sample_info_size===0)for(let l=0;l<this.sample_count;l++)this.sample_info_size[l]=o.readUint8()}},$i.fourcc="saiz",$i),Pixel=class{constructor(u,o){this.bad_pixel_row=u,this.bad_pixel_column=o}toString(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"}},Li,sbpmBox=(Li=class extends FullBox{constructor(){super(...arguments),this.box_name="SensorBadPixelsMapBox"}parse(o){this.parseFullHeader(o),this.component_count=o.readUint16(),this.component_index=[];for(let n=0;n<this.component_count;n++)this.component_index.push(o.readUint16());const l=o.readUint8();this.correction_applied=(l&128)===128,this.num_bad_rows=o.readUint32(),this.num_bad_cols=o.readUint32(),this.num_bad_pixels=o.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[];for(let n=0;n<this.num_bad_rows;n++)this.bad_rows.push(o.readUint32());for(let n=0;n<this.num_bad_cols;n++)this.bad_columns.push(o.readUint32());for(let n=0;n<this.num_bad_pixels;n++){const r=o.readUint32(),t=o.readUint32();this.bad_pixels.push(new Pixel(r,t))}}},Li.fourcc="sbpm",Li),Ai,schmBox=(Ai=class extends FullBox{constructor(){super(...arguments),this.box_name="SchemeTypeBox"}parse(o){this.parseFullHeader(o),this.scheme_type=o.readString(4),this.scheme_version=o.readUint32(),this.flags&1&&(this.scheme_uri=o.readString(this.size-this.hdr_size-8))}},Ai.fourcc="schm",Ai),Gi,sdp_Box=(Gi=class extends Box{constructor(){super(...arguments),this.box_name="rtptracksdphintinformation"}parse(o){this.sdptext=o.readString(this.size-this.hdr_size)}},Gi.fourcc="sdp ",Gi),Hi,sencBox=(Hi=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleEncryptionBox"}},Hi.fourcc="senc",Hi),zi,SmDmBox=(zi=class extends FullBox{constructor(){super(...arguments),this.box_name="SMPTE2086MasteringDisplayMetadataBox"}parse(o){this.parseFullHeader(o),this.primaryRChromaticity_x=o.readUint16(),this.primaryRChromaticity_y=o.readUint16(),this.primaryGChromaticity_x=o.readUint16(),this.primaryGChromaticity_y=o.readUint16(),this.primaryBChromaticity_x=o.readUint16(),this.primaryBChromaticity_y=o.readUint16(),this.whitePointChromaticity_x=o.readUint16(),this.whitePointChromaticity_y=o.readUint16(),this.luminanceMax=o.readUint32(),this.luminanceMin=o.readUint32()}},zi.fourcc="SmDm",zi),Yi,sratBox=(Yi=class extends FullBox{constructor(){super(...arguments),this.box_name="SamplingRateBox"}parse(o){this.parseFullHeader(o),this.sampling_rate=o.readUint32()}},Yi.fourcc="srat",Yi),ji,ssixBox=(ji=class extends FullBox{constructor(){super(...arguments),this.box_name="CompressedSubsegmentIndexBox"}parse(o){this.parseFullHeader(o),this.subsegments=[];const l=o.readUint32();for(let n=0;n<l;n++){const r={};this.subsegments.push(r),r.ranges=[];const t=o.readUint32();for(let e=0;e<t;e++){const i={};r.ranges.push(i),i.level=o.readUint8(),i.range_size=o.readUint24()}}}},ji.fourcc="ssix",ji),Xi,stdpBox=(Xi=class extends FullBox{constructor(){super(...arguments),this.box_name="DegradationPriorityBox"}parse(o){this.parseFullHeader(o);const l=(this.size-this.hdr_size)/2;this.priority=[];for(let n=0;n<l;n++)this.priority[n]=o.readUint16()}},Xi.fourcc="stpd",Xi),qi,striBox=(qi=class extends FullBox{constructor(){super(...arguments),this.box_name="SubTrackInformationBox"}parse(o){this.parseFullHeader(o),this.switch_group=o.readUint16(),this.alternate_group=o.readUint16(),this.sub_track_id=o.readUint32();const l=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(let n=0;n<l;n++)this.attribute_list[n]=o.readUint32()}},qi.fourcc="stri",qi),Ki,stsgBox=(Ki=class extends FullBox{constructor(){super(...arguments),this.box_name="SubTrackSampleGroupBox"}parse(o){this.parseFullHeader(o),this.grouping_type=o.readUint32();const l=o.readUint16();this.group_description_index=[];for(let n=0;n<l;n++)this.group_description_index[n]=o.readUint32()}},Ki.fourcc="stsg",Ki),to,stshBox=(to=class extends FullBox{constructor(){super(...arguments),this.box_name="ShadowSyncSampleBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(let n=0;n<l;n++)this.shadowed_sample_numbers.push(o.readUint32()),this.sync_sample_numbers.push(o.readUint32())}write(o){this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(o),o.writeUint32(this.shadowed_sample_numbers.length);for(let l=0;l<this.shadowed_sample_numbers.length;l++)o.writeUint32(this.shadowed_sample_numbers[l]),o.writeUint32(this.sync_sample_numbers[l])}},to.fourcc="stsh",to),eo,stssBox=(eo=class extends FullBox{constructor(){super(...arguments),this.box_name="SyncSampleBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.version===0){this.sample_numbers=[];for(let n=0;n<l;n++)this.sample_numbers.push(o.readUint32())}}write(o){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(o),o.writeUint32(this.sample_numbers.length),o.writeUint32Array(this.sample_numbers)}},eo.fourcc="stss",eo),no,stviBox=(no=class extends FullBox{constructor(){super(...arguments),this.box_name="StereoVideoBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();this.single_view_allowed=l&3,this.stereo_scheme=o.readUint32();const n=o.readUint32();for(this.stereo_indication_type=o.readString(n),this.boxes=[];o.getPosition()<this.start+this.size;){const r=parseOneBox(o,!1,this.size-(o.getPosition()-this.start));if(r.code===OK){const t=r.box;this.boxes.push(t),this[t.type]=t}else return}}},no.fourcc="stvi",no),io,stypBox=(io=class extends Box{constructor(){super(...arguments),this.box_name="SegmentTypeBox"}parse(o){let l=this.size-this.hdr_size;this.major_brand=o.readString(4),this.minor_version=o.readUint32(),l-=8,this.compatible_brands=[];let n=0;for(;l>=4;)this.compatible_brands[n]=o.readString(4),l-=4,n++}write(o){this.size=8+4*this.compatible_brands.length,this.writeHeader(o),o.writeString(this.major_brand,void 0,4),o.writeUint32(this.minor_version);for(let l=0;l<this.compatible_brands.length;l++)o.writeString(this.compatible_brands[l],void 0,4)}},io.fourcc="styp",io),oo,stz2Box=(oo=class extends FullBox{constructor(){super(...arguments),this.box_name="CompactSampleSizeBox"}parse(o){if(this.parseFullHeader(o),this.sample_sizes=[],this.version===0){this.reserved=o.readUint24(),this.field_size=o.readUint8();const l=o.readUint32();if(this.field_size===4)for(let n=0;n<l;n+=2){const r=o.readUint8();this.sample_sizes[n]=r>>4&15,this.sample_sizes[n+1]=r&15}else if(this.field_size===8)for(let n=0;n<l;n++)this.sample_sizes[n]=o.readUint8();else if(this.field_size===16)for(let n=0;n<l;n++)this.sample_sizes[n]=o.readUint16();else Log.error("BoxParser","Error in length field in stz2 box",o.isofile)}}},oo.fourcc="stz2",oo),ro,subsBox=(ro=class extends FullBox{constructor(){super(...arguments),this.box_name="SubSampleInformationBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();this.entries=[];let n;for(let r=0;r<l;r++){const t={};if(this.entries[r]=t,t.sample_delta=o.readUint32(),t.subsamples=[],n=o.readUint16(),n>0)for(let e=0;e<n;e++){const i={};t.subsamples.push(i),this.version===1?i.size=o.readUint32():i.size=o.readUint16(),i.priority=o.readUint8(),i.discardable=o.readUint8(),i.codec_specific_parameters=o.readUint32()}}}},ro.fourcc="subs",ro),lo,taicBox=(lo=class extends FullBox{constructor(){super(...arguments),this.box_name="TAIClockInfoBox"}parse(o){this.time_uncertainty=o.readUint64(),this.clock_resolution=o.readUint32(),this.clock_drift_rate=o.readInt32();const l=o.readUint8();this.clock_type=(l&192)>>6}},lo.fourcc="taic",lo),ao,tencBox=(ao=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackEncryptionBox"}parse(o){if(this.parseFullHeader(o),o.readUint8(),this.version===0)o.readUint8();else{const l=o.readUint8();this.default_crypt_byte_block=l>>4&15,this.default_skip_byte_block=l&15}this.default_isProtected=o.readUint8(),this.default_Per_Sample_IV_Size=o.readUint8(),this.default_KID=parseHex16(o),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=o.readUint8(),this.default_constant_IV=o.readUint8Array(this.default_constant_IV_size))}},ao.fourcc="tenc",ao),so,tfraBox=(so=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackFragmentRandomAccessBox"}parse(o){this.parseFullHeader(o),this.track_ID=o.readUint32(),o.readUint24();const l=o.readUint8();this.length_size_of_traf_num=l>>4&3,this.length_size_of_trun_num=l>>2&3,this.length_size_of_sample_num=l&3,this.entries=[];const n=o.readUint32();for(let r=0;r<n;r++)this.version===1?(this.time=o.readUint64(),this.moof_offset=o.readUint64()):(this.time=o.readUint32(),this.moof_offset=o.readUint32()),this.traf_number=o["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=o["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=o["readUint"+8*(this.length_size_of_sample_num+1)]()}},so.fourcc="tfra",so),uo,tmaxBox=(uo=class extends Box{constructor(){super(...arguments),this.box_name="hintmaxrelativetime"}parse(o){this.time=o.readUint32()}},uo.fourcc="tmax",uo),co,tminBox=(co=class extends Box{constructor(){super(...arguments),this.box_name="hintminrelativetime"}parse(o){this.time=o.readUint32()}},co.fourcc="tmin",co),Uo,totlBox=(Uo=class extends Box{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(o){this.bytessent=o.readUint32()}},Uo.fourcc="totl",Uo),Fo,tpayBox=(Fo=class extends Box{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(o){this.bytessent=o.readUint32()}},Fo.fourcc="tpay",Fo),Qo,tpylBox=(Qo=class extends Box{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(o){this.bytessent=o.readUint64()}},Qo.fourcc="tpyl",Qo),po,msrcTrackGroupTypeBox=(po=class extends TrackGroupTypeBox{},po.fourcc="msrc",po),I,trefBox=(I=class extends Box{constructor(){super(...arguments),this.box_name="TrackReferenceBox",this.references=[]}parse(o){for(;o.getPosition()<this.start+this.size;){const l=parseOneBox(o,!0,this.size-(o.getPosition()-this.start));if(l.code===OK){I.allowed_types.includes(l.type)||Log.warn("BoxParser",`Unknown track reference type: '${l.type}'`);const n=new TrackReferenceTypeBox(l.type,l.size,l.hdr_size,l.start);n.write===Box.prototype.write&&n.type!=="mdat"&&(Log.info("BoxParser","TrackReference "+n.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),n.parseDataAndRewind(o)),n.parse(o),this.references.push(n)}else return}}},I.fourcc="tref",I.allowed_types=["hint","cdsc","font","hind","vdep","vplx","subt","thmb","auxl","cdtg","shsc","aest"],I),fo,trepBox=(fo=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackExtensionPropertiesBox"}parse(o){for(this.parseFullHeader(o),this.track_ID=o.readUint32(),this.boxes=[];o.getPosition()<this.start+this.size;){const l=parseOneBox(o,!1,this.size-(o.getPosition()-this.start));if(l.code===OK){const n=l.box;this.boxes.push(n)}else return}}},fo.fourcc="trep",fo),ho,trpyBox=(ho=class extends Box{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(o){this.bytessent=o.readUint64()}},ho.fourcc="trpy",ho),Ro,tselBox=(Ro=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackSelectionBox"}parse(o){this.parseFullHeader(o),this.switch_group=o.readUint32();const l=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(let n=0;n<l;n++)this.attribute_list[n]=o.readUint32()}},Ro.fourcc="tsel",Ro),Bo,txtcBox=(Bo=class extends FullBox{constructor(){super(...arguments),this.box_name="TextConfigBox"}parse(o){this.parseFullHeader(o),this.config=o.readCString()}},Bo.fourcc="txtc",Bo),So,tycoBox=(So=class extends Box{constructor(){super(...arguments),this.box_name="TypeCombinationBox"}parse(o){const l=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(let n=0;n<l;n++)this.compatible_brands[n]=o.readString(4)}},So.fourcc="tyco",So),yo,udesBox=(yo=class extends FullBox{constructor(){super(...arguments),this.box_name="UserDescriptionProperty"}parse(o){this.parseFullHeader(o),this.lang=o.readCString(),this.name=o.readCString(),this.description=o.readCString(),this.tags=o.readCString()}},yo.fourcc="udes",yo),Vo,uncCBox=(Vo=class extends FullBox{constructor(){super(...arguments),this.box_name="UncompressedFrameConfigBox"}parse(o){if(this.parseFullHeader(o),this.profile=o.readString(4),this.version!==1){if(this.version===0){this.component_count=o.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[];for(let n=0;n<this.component_count;n++)this.component_index.push(o.readUint16()),this.component_bit_depth_minus_one.push(o.readUint8()),this.component_format.push(o.readUint8()),this.component_align_size.push(o.readUint8());this.sampling_type=o.readUint8(),this.interleave_type=o.readUint8(),this.block_size=o.readUint8();const l=o.readUint8();this.component_little_endian=l>>7&1,this.block_pad_lsb=l>>6&1,this.block_little_endian=l>>5&1,this.block_reversed=l>>4&1,this.pad_unknown=l>>3&1,this.pixel_size=o.readUint32(),this.row_align_size=o.readUint32(),this.tile_align_size=o.readUint32(),this.num_tile_cols_minus_one=o.readUint32(),this.num_tile_rows_minus_one=o.readUint32()}}}},Vo.fourcc="uncC",Vo),Jo,urnBox=(Jo=class extends FullBox{constructor(){super(...arguments),this.box_name="DataEntryUrnBox"}parse(o){this.parseFullHeader(o),this.name=o.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=o.readCString())}write(o){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(o),o.writeCString(this.name),this.location&&o.writeCString(this.location)}},Jo.fourcc="urn ",Jo),Eo,vttCBox=(Eo=class extends Box{constructor(){super(...arguments),this.box_name="WebVTTConfigurationBox"}parse(o){this.text=o.readString(this.size-this.hdr_size)}},Eo.fourcc="vttC",Eo),mo,vvnCBox=(mo=class extends FullBox{constructor(){super(...arguments),this.box_name="VvcNALUConfigBox"}parse(o){this.parseFullHeader(o);const l=o.readUint8();this.lengthSizeMinusOne=l&3}},mo.fourcc="vvnC",mo),ko,alstSampleGroupEntry=(ko=class extends SampleGroupEntry{parse(o){const l=o.readUint16();this.first_output_sample=o.readUint16(),this.sample_offset=[];for(let r=0;r<l;r++)this.sample_offset[r]=o.readUint32();const n=this.description_length-4-4*l;this.num_output_samples=[],this.num_total_samples=[];for(let r=0;r<n/4;r++)this.num_output_samples[r]=o.readUint16(),this.num_total_samples[r]=o.readUint16()}},ko.grouping_type="alst",ko),No,avllSampleGroupEntry=(No=class extends SampleGroupEntry{parse(o){this.layerNumber=o.readUint8(),this.accurateStatisticsFlag=o.readUint8(),this.avgBitRate=o.readUint16(),this.avgFrameRate=o.readUint16()}},No.grouping_type="avll",No),To,avssSampleGroupEntry=(To=class extends SampleGroupEntry{parse(o){this.subSequenceIdentifier=o.readUint16(),this.layerNumber=o.readUint8();const l=o.readUint8();this.durationFlag=l>>7,this.avgRateFlag=l>>6&1,this.durationFlag&&(this.duration=o.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=o.readUint8(),this.avgBitRate=o.readUint16(),this.avgFrameRate=o.readUint16()),this.dependency=[];const n=o.readUint8();for(let r=0;r<n;r++)this.dependency.push({subSeqDirectionFlag:o.readUint8(),layerNumber:o.readUint8(),subSequenceIdentifier:o.readUint16()})}},To.grouping_type="avss",To),vo,dtrtSampleGroupEntry=(vo=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},vo.grouping_type="dtrt",vo),Co,mvifSampleGroupEntry=(Co=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Co.grouping_type="mvif",Co),Wo,prolSampleGroupEntry=(Wo=class extends SampleGroupEntry{parse(o){this.roll_distance=o.readInt16()}},Wo.grouping_type="prol",Wo),bo,rapSampleGroupEntry=(bo=class extends SampleGroupEntry{parse(o){const l=o.readUint8();this.num_leading_samples_known=l>>7,this.num_leading_samples=l&127}},bo.grouping_type="rap ",bo),Oo,rashSampleGroupEntry=(Oo=class extends SampleGroupEntry{parse(o){if(this.operation_point_count=o.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)Log.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=o.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=o.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(let l=0;l<this.operation_point_count;l++)this.available_bitrate[l]=o.readUint32(),this.target_rate_share[l]=o.readUint16()}this.maximum_bitrate=o.readUint32(),this.minimum_bitrate=o.readUint32(),this.discard_priority=o.readUint8()}}},Oo.grouping_type="rash",Oo),Zo,rollSampleGroupEntry=(Zo=class extends SampleGroupEntry{parse(o){this.roll_distance=o.readInt16()}},Zo.grouping_type="roll",Zo),Do,scifSampleGroupEntry=(Do=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Do.grouping_type="scif",Do),wo,scnmSampleGroupEntry=(wo=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},wo.grouping_type="scnm",wo),go,seigSampleGroupEntry=(go=class extends SampleGroupEntry{parse(o){this.reserved=o.readUint8();const l=o.readUint8();this.crypt_byte_block=l>>4,this.skip_byte_block=l&15,this.isProtected=o.readUint8(),this.Per_Sample_IV_Size=o.readUint8(),this.KID=parseHex16(o),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=o.readUint8(),this.constant_IV=o.readUint8Array(this.constant_IV_size))}},go.grouping_type="seig",go),xo,stsaSampleGroupEntry=(xo=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},xo.grouping_type="stsa",xo),Io,syncSampleGroupEntry=(Io=class extends SampleGroupEntry{parse(o){const l=o.readUint8();this.NAL_unit_type=l&63}},Io.grouping_type="sync",Io),Mo,teleSampleGroupEntry=(Mo=class extends SampleGroupEntry{parse(o){const l=o.readUint8();this.level_independently_decodable=l>>7}},Mo.grouping_type="tele",Mo),_o,tsasSampleGroupEntry=(_o=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},_o.grouping_type="tsas",_o),Po,tsclSampleGroupEntry=(Po=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Po.grouping_type="tscl",Po),$o,viprSampleGroupEntry=($o=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},$o.grouping_type="vipr",$o),Lo,UUIDBox=(Lo=class extends Box{},Lo.fourcc="uuid",Lo),Ao,UUIDFullBox=(Ao=class extends FullBox{},Ao.fourcc="uuid",Ao),Go,piffLsmBox=(Go=class extends UUIDFullBox{constructor(){super(...arguments),this.box_name="LiveServerManifestBox"}parse(o){this.parseFullHeader(o),this.LiveServerManifest=o.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}},Go.uuid="a5d40b30e81411ddba2f0800200c9a66",Go),Ho,piffPsshBox=(Ho=class extends UUIDFullBox{constructor(){super(...arguments),this.box_name="PiffProtectionSystemSpecificHeaderBox"}parse(o){this.parseFullHeader(o),this.system_id=parseHex16(o);const l=o.readUint32();l>0&&(this.data=o.readUint8Array(l))}},Ho.uuid="d08a4f1810f34a82b6c832d8aba183d3",Ho),zo,piffSencBox=(zo=class extends UUIDFullBox{constructor(){super(...arguments),this.box_name="PiffSampleEncryptionBox"}},zo.uuid="a2394f525a9b4f14a2446c427c648df4",zo),Yo,piffTencBox=(Yo=class extends UUIDFullBox{constructor(){super(...arguments),this.box_name="PiffTrackEncryptionBox"}parse(o){this.parseFullHeader(o),this.default_AlgorithmID=o.readUint24(),this.default_IV_size=o.readUint8(),this.default_KID=parseHex16(o)}},Yo.uuid="8974dbce7be74c5184f97148f9882554",Yo),jo,piffTfrfBox=(jo=class extends UUIDFullBox{constructor(){super(...arguments),this.box_name="TfrfBox"}parse(o){this.parseFullHeader(o),this.fragment_count=o.readUint8(),this.entries=[];for(let l=0;l<this.fragment_count;l++){let n=0,r=0;this.version===1?(n=o.readUint64(),r=o.readUint64()):(n=o.readUint32(),r=o.readUint32()),this.entries.push({absolute_time:n,absolute_duration:r})}}},jo.uuid="d4807ef2ca3946958e5426cb9e46a79f",jo),Xo,piffTfxdBox=(Xo=class extends UUIDFullBox{constructor(){super(...arguments),this.box_name="TfxdBox"}parse(o){this.parseFullHeader(o),this.version===1?(this.absolute_time=o.readUint64(),this.duration=o.readUint64()):(this.absolute_time=o.readUint32(),this.duration=o.readUint32())}},Xo.uuid="6d1d9b0542d544e680e2141daff757b2",Xo),qo,ItemContentIDPropertyBox=(qo=class extends UUIDBox{constructor(){super(...arguments),this.box_name="ItemContentIDProperty"}parse(o){this.content_id=o.readCString()}},qo.uuid="261ef3741d975bbaacbd9d2c8ea73522",qo);registerBoxes(all_boxes_exports);registerDescriptors(descriptor_exports);class MP4FileSource{constructor(o={}){U(this,"mp4File",null);U(this,"fileInfo",null);U(this,"videoTrackId",null);U(this,"audioTrackId",null);U(this,"videoTrack",null);U(this,"audioTrack",null);U(this,"nextVideoSampleIndex",0);U(this,"nextAudioSampleIndex",0);U(this,"totalVideoSamples",0);U(this,"totalAudioSamples",0);U(this,"samplesRequested",!1);U(this,"isProgressiveLoading",!1);U(this,"fileSize",0);U(this,"loadedBytes",0);U(this,"videoDescription",null);U(this,"audioDescription",null);U(this,"events",{});this.events=o}getFileInfo(){return this.fileInfo}getVideoDescription(){return this.videoDescription}getAudioDescription(){return this.audioDescription}async loadFromUrl(o){this.initMP4File();const l=4*1024*1024;let n=0,r=!1;try{const t=await fetch(o,{method:"HEAD"});if(t.ok){const e=t.headers.get("Content-Length");e&&(this.fileSize=parseInt(e,10))}}catch{}return new Promise((t,e)=>{let i=!1;const a=this.mp4File.onSamples;this.mp4File.onSamples=(c,F,B)=>{!i&&c===this.videoTrackId&&B.length>0&&(i=!0),a==null||a.call(this.mp4File,c,F,B)};const s=this.mp4File.onReady;this.mp4File.onReady=c=>{s==null||s.call(this.mp4File,c),this.fileInfo&&!r&&(r=!0)},(async()=>{var c,F,B,S,y,E,v,N,T,C;try{const m=await fetch(o,{headers:{Range:`bytes=0-${l-1}`}});if(!m.ok&&m.status!==206)throw new Error(`Failed to fetch: ${m.status} ${m.statusText}`);if(m.status===200){this.isProgressiveLoading=!1;const f=await m.arrayBuffer();this.fileSize=f.byteLength,this.loadedBytes=f.byteLength;const h=f;h.fileStart=0,(c=this.mp4File)==null||c.appendBuffer(h),(F=this.mp4File)==null||F.flush(),this.fileInfo?t(this.fileInfo):e(new Error("File loaded but no video track found"));return}if(this.isProgressiveLoading=!0,!this.fileSize){const f=m.headers.get("Content-Range");if(f){const h=f.match(/bytes \d+-\d+\/(\d+)/);h&&(this.fileSize=parseInt(h[1],10))}}const Q=await m.arrayBuffer(),p=Q;if(p.fileStart=0,n=Q.byteLength,this.loadedBytes=n,(S=(B=this.events).onProgress)==null||S.call(B,this.loadedBytes,this.fileSize),(y=this.mp4File)==null||y.appendBuffer(p),r&&i){n<this.fileSize?this.continueLoadingInBackground(o,n,l):(E=this.mp4File)==null||E.flush(),t(this.fileInfo);return}for(;n<this.fileSize&&(!r||!i);){const f=Math.min(n+l-1,this.fileSize-1),h=await fetch(o,{headers:{Range:`bytes=${n}-${f}`}});if(!h.ok&&h.status!==206)throw new Error(`Failed to fetch chunk: ${h.status} ${h.statusText}`);const R=await h.arrayBuffer(),J=R;if(J.fileStart=n,n+=R.byteLength,this.loadedBytes=n,(N=(v=this.events).onProgress)==null||N.call(v,this.loadedBytes,this.fileSize),(T=this.mp4File)==null||T.appendBuffer(J),r&&i){this.continueLoadingInBackground(o,n,l),t(this.fileInfo);return}}n>=this.fileSize&&((C=this.mp4File)==null||C.flush(),this.fileInfo?t(this.fileInfo):e(new Error("File loaded but no video track found")))}catch(m){e(m)}})()})}continueLoadingInBackground(o,l,n){(async()=>{var t,e,i,a,s,d,c,F;let r=l;try{for(;r<this.fileSize;){const B=Math.min(r+n-1,this.fileSize-1),S=await fetch(o,{headers:{Range:`bytes=${r}-${B}`}});if(!S.ok&&S.status!==206){(e=(t=this.events).onError)==null||e.call(t,new Error(`Failed to fetch chunk: ${S.status}`));break}const y=await S.arrayBuffer(),E=y;E.fileStart=r,r+=y.byteLength,this.loadedBytes=r,(a=(i=this.events).onProgress)==null||a.call(i,this.loadedBytes,this.fileSize),(s=this.mp4File)==null||s.appendBuffer(E)}(d=this.mp4File)==null||d.flush()}catch(B){(F=(c=this.events).onError)==null||F.call(c,B)}})()}async loadFromFile(o){this.fileSize=o.size;const l=await o.arrayBuffer();return this.isProgressiveLoading=!1,this.loadFromArrayBuffer(l)}async loadFromStream(o){this.initMP4File(),this.isProgressiveLoading=!0;let l=0;return new Promise((n,r)=>{const t=i=>{var s,d,c;const a=new ArrayBuffer(i.byteLength);new Uint8Array(a).set(i),a.fileStart=l,l+=a.byteLength,this.loadedBytes=l,(d=(s=this.events).onProgress)==null||d.call(s,this.loadedBytes,this.fileSize),(c=this.mp4File)==null||c.appendBuffer(a)},e=async()=>{var i;try{const{done:a,value:s}=await o.read();if(a){(i=this.mp4File)==null||i.flush(),this.fileInfo?n(this.fileInfo):r(new Error("File loaded but no video track found"));return}s&&t(s),e()}catch(a){r(a)}};e()})}async loadFromArrayBuffer(o){return this.initMP4File(),new Promise((l,n)=>{var e,i;const r=this.mp4File.onReady;this.mp4File.onReady=a=>{r==null||r.call(this.mp4File,a),this.fileInfo?(this.requestSamples(),l(this.fileInfo)):n(new Error("No video track found in file"))};const t=o;t.fileStart=0,this.loadedBytes=o.byteLength,(e=this.mp4File)==null||e.appendBuffer(t),(i=this.mp4File)==null||i.flush()})}initMP4File(){this.mp4File=createFile(),this.mp4File.onReady=o=>{this.handleFileReady(o)},this.mp4File.onSamples=(o,l,n)=>{this.handleSamples(o,n)},this.mp4File.onError=(o,l)=>{var r,t;if(l.includes("Invalid box type")||l.includes("Unknown box")){console.warn(`[MP4FileSource] Ignoring unknown box: ${l}`);return}const n=new Error(`MP4Box error in ${o}: ${l}`);(t=(r=this.events).onError)==null||t.call(r,n)}}handleFileReady(o){var l,n,r,t,e,i,a,s,d,c,F,B,S,y,E,v,N,T,C,m,Q,p,f,h,R,J,V,W,b,g;if(o.videoTracks.length>0){this.videoTrack=o.videoTracks[0],this.videoTrackId=this.videoTrack.id,this.totalVideoSamples=this.videoTrack.nb_samples;const Z=(l=this.mp4File)==null?void 0:l.getTrackById(this.videoTrackId);if(Z){const M=(i=(e=(t=(r=(n=Z.mdia)==null?void 0:n.minf)==null?void 0:r.stbl)==null?void 0:t.stsd)==null?void 0:e.entries)==null?void 0:i[0];if(M){const O=M.avcC,D=M.hvcC;O?this.videoDescription=this.serializeAvcC(O):D&&(this.videoDescription=this.serializeHvcC(D))}}}if(o.audioTracks.length>0){this.audioTrack=o.audioTracks[0],this.audioTrackId=this.audioTrack.id,this.totalAudioSamples=this.audioTrack.nb_samples;const Z=(a=this.mp4File)==null?void 0:a.getTrackById(this.audioTrackId);if(Z){const M=(B=(F=(c=(d=(s=Z.mdia)==null?void 0:s.minf)==null?void 0:d.stbl)==null?void 0:c.stsd)==null?void 0:F.entries)==null?void 0:B[0];if(M){const O=M.esds;if(O){let D=null;if((N=(v=(E=(y=(S=O.esd)==null?void 0:S.descs)==null?void 0:y[0])==null?void 0:E.descs)==null?void 0:v[0])!=null&&N.data)D=O.esd.descs[0].descs[0].data;else if((m=(C=(T=O.esd)==null?void 0:T.descs)==null?void 0:C[0])!=null&&m.data)D=O.esd.descs[0].data;else if((Q=O.esd)!=null&&Q.descs)for(const er of O.esd.descs){if(er.tag===4&&er.descs){for(const nr of er.descs)if(nr.tag===5&&nr.data){D=nr.data;break}}if(D)break}D&&(this.audioDescription=D)}}}}if(!this.videoTrack){(f=(p=this.events).onError)==null||f.call(p,new Error("No video track found in file"));return}this.fileInfo={duration:this.videoTrack.duration/this.videoTrack.timescale,timescale:this.videoTrack.timescale,width:((h=this.videoTrack.video)==null?void 0:h.width)??0,height:((R=this.videoTrack.video)==null?void 0:R.height)??0,videoCodec:this.videoTrack.codec,frameRate:this.videoTrack.nb_samples/(this.videoTrack.duration/this.videoTrack.timescale),bitrate:this.videoTrack.bitrate,isMoovAtStart:((J=this.mp4File)==null?void 0:J.isProgressive)??void 0},this.audioTrack&&(this.fileInfo.audioCodec=this.audioTrack.codec,this.fileInfo.audioChannels=(V=this.audioTrack.audio)==null?void 0:V.channel_count,this.fileInfo.audioSampleRate=(W=this.audioTrack.audio)==null?void 0:W.sample_rate),this.requestSamples(),(g=(b=this.events).onReady)==null||g.call(b,this.fileInfo)}requestSamples(){var o,l,n,r,t;this.samplesRequested||(this.samplesRequested=!0,this.videoTrackId!==null&&(this.isProgressiveLoading?(o=this.mp4File)==null||o.setExtractionOptions(this.videoTrackId,null,{nbSamples:100}):(l=this.mp4File)==null||l.setExtractionOptions(this.videoTrackId,null,{nbSamples:this.totalVideoSamples})),this.audioTrackId!==null&&(this.isProgressiveLoading?(n=this.mp4File)==null||n.setExtractionOptions(this.audioTrackId,null,{nbSamples:100}):(r=this.mp4File)==null||r.setExtractionOptions(this.audioTrackId,null,{nbSamples:this.totalAudioSamples})),(t=this.mp4File)==null||t.start())}handleSamples(o,l){var e,i,a,s;const n=o===this.videoTrackId;if(!(n?this.videoTrack:this.audioTrack))return;const t=l.filter(d=>d.data!=null).map(d=>{const c=d.cts/d.timescale*1e6,F=d.duration/d.timescale*1e6;return{data:d.data,timestamp:c,duration:F,isKeyframe:d.is_sync,type:n?"video":"audio"}});if(n?(this.nextVideoSampleIndex+=l.length,this.nextVideoSampleIndex>=this.totalVideoSamples&&((i=(e=this.events).onEnded)==null||i.call(e))):this.nextAudioSampleIndex+=l.length,this.mp4File){const d=l[l.length-1];this.mp4File.releaseUsedSamples(o,d.number)}(s=(a=this.events).onSamples)==null||s.call(a,t)}seek(o){if(!this.mp4File||!this.videoTrackId)return 0;const l=this.mp4File.seek(o,!0);return this.nextVideoSampleIndex=0,this.nextAudioSampleIndex=0,this.samplesRequested=!1,this.mp4File.stop(),this.requestSamples(),l.time}getPosition(){return{currentSample:this.nextVideoSampleIndex,totalSamples:this.totalVideoSamples,progress:this.totalVideoSamples>0?this.nextVideoSampleIndex/this.totalVideoSamples:0}}stop(){var o;(o=this.mp4File)==null||o.stop()}start(){var o;(o=this.mp4File)==null||o.start()}dispose(){var o;(o=this.mp4File)==null||o.stop(),this.mp4File=null,this.fileInfo=null,this.videoTrack=null,this.audioTrack=null,this.videoDescription=null,this.audioDescription=null,this.isProgressiveLoading=!1}serializeAvcC(o){let l=6;const n=o.SPS||[];for(const i of n)l+=2+i.data.length;l+=1;const r=o.PPS||[];for(const i of r)l+=2+i.data.length;const t=new Uint8Array(l);let e=0;t[e++]=o.configurationVersion||1,t[e++]=o.AVCProfileIndication,t[e++]=o.profile_compatibility,t[e++]=o.AVCLevelIndication,t[e++]=255,t[e++]=224|n.length;for(const i of n){const a=i.data.length;t[e++]=a>>8&255,t[e++]=a&255,t.set(new Uint8Array(i.data),e),e+=a}t[e++]=r.length;for(const i of r){const a=i.data.length;t[e++]=a>>8&255,t[e++]=a&255,t.set(new Uint8Array(i.data),e),e+=a}return t}serializeHvcC(o){return o.data&&o.data instanceof Uint8Array?o.data:(console.warn("HEVC serialization not fully implemented"),new Uint8Array(0))}}const WORKLET_CODE=`
|
|
151
|
+
`;class LiveAudioPlayer{constructor(o,l={}){U(this,"ctx");U(this,"decoder",null);U(this,"workletNode",null);U(this,"gainNode");U(this,"initialized",!1);U(this,"targetSampleRate");U(this,"startTime",0);U(this,"bufferDelayMs");this.ctx=o,this.targetSampleRate=o.sampleRate,this.bufferDelayMs=l.bufferDelayMs??100,this.gainNode=this.ctx.createGain(),this.startTime=performance.now()*1e3}async init(o){if(this.ctx.audioWorklet===void 0)throw new Error("AudioWorklet not supported - need localhost or HTTPS");const l=this.buildDecoderConfig(o);if(!(await AudioDecoder.isConfigSupported(l)).supported)throw new Error(`Audio codec not supported: ${l.codec}`);this.decoder=new AudioDecoder({output:e=>this.handleDecodedFrame(e),error:e=>{console.error("LiveAudioPlayer decoder error:",e)}}),this.decoder.configure(l);const r=new Blob([LIVE_WORKLET_CODE],{type:"application/javascript"}),t=URL.createObjectURL(r);try{await this.ctx.audioWorklet.addModule(t)}finally{URL.revokeObjectURL(t)}this.workletNode=new AudioWorkletNode(this.ctx,"live-audio-processor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2],processorOptions:{sampleRate:this.ctx.sampleRate}}),this.workletNode.connect(this.gainNode).connect(this.ctx.destination),this.workletNode.port.postMessage({type:"setBufferTarget",targetMs:this.bufferDelayMs}),this.workletNode.port.postMessage({type:"setSampleRate",sampleRate:this.ctx.sampleRate}),this.initialized=!0}buildDecoderConfig(o){const l=(o==null?void 0:o.codecType)??CodecType.CODEC_TYPE_AUDIO_OPUS,n=(o==null?void 0:o.sampleRate)||48e3,r=(o==null?void 0:o.channels)||2;switch(l){case CodecType.CODEC_TYPE_AUDIO_OPUS:return{codec:"opus",sampleRate:48e3,numberOfChannels:r};case CodecType.CODEC_TYPE_AUDIO_AAC:return{codec:"mp4a.40.2",sampleRate:n,numberOfChannels:r};case CodecType.CODEC_TYPE_AUDIO_PCM:throw new Error("PCM audio not yet supported");default:return{codec:"opus",sampleRate:48e3,numberOfChannels:2}}}handleDecodedFrame(o){if(!this.workletNode){o.close();return}try{const l=o.numberOfFrames;let n=1;try{o.numberOfChannels>1&&(o.allocationSize({planeIndex:1,frameOffset:0,frameCount:1}),n=o.numberOfChannels)}catch{n=1}const r=new Float32Array(l),t=new Float32Array(l);if(n===1){const s=o.allocationSize({planeIndex:0,frameOffset:0,frameCount:o.numberOfFrames}),d=new ArrayBuffer(s);o.copyTo(d,{planeIndex:0,frameOffset:0,frameCount:o.numberOfFrames});const c=new Float32Array(d);if(o.numberOfChannels===1)r.set(c),t.set(c);else for(let F=0;F<l;F++)r[F]=c[F*2],t[F]=c[F*2+1]}else{const s=new ArrayBuffer(o.allocationSize({planeIndex:0,frameOffset:0,frameCount:o.numberOfFrames}));if(o.copyTo(s,{planeIndex:0,frameOffset:0,frameCount:o.numberOfFrames}),r.set(new Float32Array(s)),o.numberOfChannels>1){const d=new ArrayBuffer(o.allocationSize({planeIndex:1,frameOffset:0,frameCount:o.numberOfFrames}));o.copyTo(d,{planeIndex:1,frameOffset:0,frameCount:o.numberOfFrames}),t.set(new Float32Array(d))}else t.set(r)}const e=this.resampleAudio(r,o.sampleRate,this.targetSampleRate),i=this.resampleAudio(t,o.sampleRate,this.targetSampleRate),a=o.timestamp??performance.now()*1e3-this.startTime;this.workletNode.port.postMessage({type:"audioData",data:{left:e.buffer,right:i.buffer},timestamp:a},[e.buffer,i.buffer]),o.close()}catch(l){console.error("Error processing live audio frame:",l),o.close()}}resampleAudio(o,l,n){if(l===n)return o;const r=l/n,t=Math.floor(o.length/r),e=new Float32Array(t);for(let i=0;i<t;i++){const a=i*r,s=Math.floor(a),d=Math.min(s+1,o.length-1),c=a-s;e[i]=o[s]*(1-c)+o[d]*c}return e}decode(o,l){if(!(!this.initialized||!this.decoder||this.decoder.state!=="configured")&&!(o.length<1))try{let n;l!=null?isLong(l)?n=l.toNumber():n=Number(l):n=performance.now()*1e3-this.startTime;const r=new EncodedAudioChunk({type:"key",timestamp:Math.max(0,n),data:o});this.decoder.decode(r)}catch(n){console.error("Error decoding live audio:",n)}}setBufferDelay(o){var l;this.bufferDelayMs=o,(l=this.workletNode)==null||l.port.postMessage({type:"setBufferTarget",targetMs:o})}start(){var o;(o=this.workletNode)==null||o.port.postMessage({type:"start"}),this.ctx.resume()}stop(){var o;(o=this.workletNode)==null||o.port.postMessage({type:"stop"})}clear(){var o;(o=this.workletNode)==null||o.port.postMessage({type:"clear"}),this.resetTiming()}resetTiming(){this.startTime=performance.now()*1e3}setVolume(o){this.gainNode.gain.value=Math.max(0,Math.min(1,o))}dispose(){if(this.initialized=!1,this.decoder){try{this.decoder.state==="configured"&&this.decoder.reset(),this.decoder.state!=="closed"&&this.decoder.close()}catch{}this.decoder=null}if(this.workletNode){try{this.workletNode.disconnect()}catch{}this.workletNode=null}if(this.gainNode)try{this.gainNode.disconnect()}catch{}}}function createPlayer(u={}){return new LiveVideoPlayer(u)}const Ko=class Ko extends BasePlayer{constructor(l={}){super("idle",l.debugLogging??!1);U(this,"config");U(this,"streamSource",null);U(this,"trackFilter",null);U(this,"boundDataHandler",null);U(this,"decoder",null);U(this,"currentCodecData");U(this,"useWasmDecoder",!1);U(this,"waitingForKeyframe",!0);U(this,"lastWaitingForKeyframeLog",0);U(this,"lastKeyframeRequest",0);U(this,"statusLogCounter",0);U(this,"isConfiguring",!1);U(this,"pendingDuringConfig",[]);U(this,"frameScheduler");U(this,"lastVideoFrame",null);U(this,"consecutiveDrops",0);U(this,"totalDrops",0);U(this,"lastDropLogTime",0);U(this,"streamWidth",0);U(this,"streamHeight",0);U(this,"estimatedFrameRate",30);U(this,"lastVideoTimestampUs",-1);U(this,"fpsEstimateSamples",[]);U(this,"audioContext",null);U(this,"audioPlayer",null);U(this,"ownsAudioContext",!1);U(this,"audioCodecData",null);U(this,"arrivalTimes",new Map);U(this,"keyframeStatus",new Map);U(this,"videoBytesReceived",0);U(this,"audioBytesReceived",0);U(this,"lastBandwidthUpdateTime",0);U(this,"lastVideoBytesReceived",0);U(this,"lastAudioBytesReceived",0);U(this,"currentBandwidth",{videoBytesPerSecond:0,audioBytesPerSecond:0,totalBytesPerSecond:0});this.config={preferredDecoder:l.preferredDecoder??"webcodecs-sw",bufferDelayMs:l.bufferDelayMs??100,enableAudio:l.enableAudio??!0,videoTrackName:l.videoTrackName===void 0?"video":l.videoTrackName,audioTrackName:l.audioTrackName===void 0?"audio":l.audioTrackName,debugLogging:l.debugLogging??!1},this.config.enableAudio&&(l.audioContext?(this.audioContext=l.audioContext,this.ownsAudioContext=!1):(this.audioContext=new AudioContext,this.ownsAudioContext=!0)),this.frameScheduler=new FrameScheduler({bufferDelayMs:this.config.bufferDelayMs,logger:n=>{this.config.debugLogging&&this.logger.info(n)},onFrameDropped:(n,r)=>{if(this.totalDrops++,this.consecutiveDrops++,this.config.debugLogging){const t=Date.now();(t-this.lastDropLogTime>500||this.consecutiveDrops===1)&&(this.consecutiveDrops>1?this.logger.warn(`Dropped ${this.consecutiveDrops} frames (${r}), total=${this.totalDrops}`):this.logger.warn(`Frame dropped (${r}), total=${this.totalDrops}`),this.lastDropLogTime=t,this.consecutiveDrops=0)}n.close()}})}setDebugLogging(l){this.config.debugLogging=l,super.setDebugLogging(l)}setVolume(l){this.audioPlayer&&this.audioPlayer.setVolume(l)}getVolume(){return 1}setStreamSource(l){this.streamSource&&this.boundDataHandler&&this.streamSource.off("data",this.boundDataHandler),this.streamSource=l,this.boundDataHandler=this.handleStreamData.bind(this),this.streamSource.on("data",this.boundDataHandler),this.logger.info("Stream source connected")}setTrackFilter(l){this.trackFilter=l,this.logger.info(`Track filter set: ${l}`)}connectToMoQSession(l,n){this.setStreamSource(l),n&&this.setTrackFilter(n)}async connectToMoQRelay(l,n,r){const{createMoQSource:t}=await Promise.resolve().then(()=>moqSource),e=(r==null?void 0:r.videoTrack)??this.config.videoTrackName??"video",i=(r==null?void 0:r.audioTrack)===!1?null:(r==null?void 0:r.audioTrack)??this.config.audioTrackName??"audio",a=[{trackName:e,streamType:"video",priority:0}];i&&this.config.enableAudio&&a.push({trackName:i,streamType:"audio",priority:0}),this.logger.info(`MoQ subscriptions: ${JSON.stringify(a)}`);const s=t({relayUrl:l,namespace:n,subscriptions:a});this.setStreamSource(s),await s.connect()}play(){this._state!=="error"&&(this.setState("playing"),this.logger.info("Playback started"))}pause(){this._state==="playing"&&(this.setState("paused"),this.logger.info("Playback paused"))}getVideoFrame(l){if(this._state!=="playing")return this.config.debugLogging&&this.logger.debug(`getVideoFrame: state=${this._state}, returning lastFrame=${!!this.lastVideoFrame}`),this.lastVideoFrame;this.config.debugLogging&&(this.statusLogCounter++,this.statusLogCounter>=300&&(this.frameScheduler.logStatus(),this.statusLogCounter=0));const n=this.frameScheduler.dequeue(l);return n&&(this.consecutiveDrops=0,this.lastVideoFrame&&this.lastVideoFrame!==n&&this.lastVideoFrame.close(),this.lastVideoFrame=n),this.lastVideoFrame}setBufferDelay(l){var n;this.config.bufferDelayMs=l,this.frameScheduler.setBufferDelay(l),(n=this.audioPlayer)==null||n.setBufferDelay(l)}getBufferDelay(){return this.frameScheduler.getBufferDelay()}setPreferredDecoder(l){var e,i,a,s;const n=this.config.preferredDecoder;this.config.preferredDecoder=l,n==="wasm"!==(l==="wasm")&&this.decoder?(this.logger.info(`Decoder type changed from ${n} to ${l}, switching decoder...`),this.decoder.dispose(),this.decoder=null,this.frameScheduler.clear(),this.lastVideoFrame&&(this.lastVideoFrame.close(),this.lastVideoFrame=null),this.waitingForKeyframe=!0,this.currentCodecData=void 0,(i=(e=this.streamSource)==null?void 0:e.requestKeyframe)==null||i.call(e),this.logger.info("Keyframe requested for decoder switch")):n!==l&&this.decoder&&(this.logger.info(`Decoder preference changed from ${n} to ${l}`),this.waitingForKeyframe=!0,this.currentCodecData=void 0,this.decoder.dispose(),this.decoder=null,this.frameScheduler.clear(),(s=(a=this.streamSource)==null?void 0:a.requestKeyframe)==null||s.call(a))}flush(){var l,n,r;this.logger.info("Flushing player pipeline"),this.waitingForKeyframe=!0,(l=this.decoder)==null||l.flushSync(),this.frameScheduler.clear(),this.lastVideoFrame&&(this.lastVideoFrame.close(),this.lastVideoFrame=null),(r=(n=this.streamSource)==null?void 0:n.requestKeyframe)==null||r.call(n)}getStats(){var n;const l=this.frameScheduler.getStatus();return this.updateBandwidthStats(),{bufferSize:l.currentBufferSize,bufferMs:l.currentBufferMs,avgBufferMs:l.avgBufferMs,targetBufferMs:l.targetBufferMs,droppedFrames:l.droppedFrames,totalFrames:l.totalEnqueuedFrames,decoderState:((n=this.decoder)==null?void 0:n.state)??"none",streamWidth:this.streamWidth,streamHeight:this.streamHeight,frameRate:this.estimatedFrameRate,latency:l.latency,bandwidth:this.currentBandwidth}}updateBandwidthStats(){const l=performance.now(),n=l-this.lastBandwidthUpdateTime;if(n<500)return;const r=n/1e3,t=this.videoBytesReceived-this.lastVideoBytesReceived,e=this.audioBytesReceived-this.lastAudioBytesReceived;this.currentBandwidth={videoBytesPerSecond:t/r,audioBytesPerSecond:e/r,totalBytesPerSecond:(t+e)/r},this.lastBandwidthUpdateTime=l,this.lastVideoBytesReceived=this.videoBytesReceived,this.lastAudioBytesReceived=this.audioBytesReceived}getPacketTimingHistory(){return this.frameScheduler.getPacketTimingHistory()}on(l,n){super.on(l,n)}off(l,n){super.off(l,n)}async handleStreamData(l){var a,s,d,c,F,B,S,y,E,v,N,T,C,m,Q,p,f;const n=l.data;if(!n.valid||!n.header)return;const r=((a=n.payload)==null?void 0:a.byteLength)||0;if(n.header.type===FrameType.FRAME_TYPE_AUDIO||l.streamType==="audio"){this.audioBytesReceived+=r;const h=this.config.audioTrackName;if(h!=null&&l.trackName!==h&&l.streamType!=="audio")return;await this.handleAudioData(n);return}this.videoBytesReceived+=r;const e=this.trackFilter??this.config.videoTrackName;if(e!=null&&l.trackName!==e||l.streamType!=="video"||!((s=n.header.media)!=null&&s.codecData))return;const i=!!((d=n.header.media)!=null&&d.keyframe);if(codecDataChanged(this.currentCodecData,(c=n.header.media)==null?void 0:c.codecData)){if(!i){this.logger.debug("Waiting for keyframe (codec change)");return}this.currentCodecData=(F=n.header.media)==null?void 0:F.codecData,this.isConfiguring=!0,this.pendingDuringConfig=[n],await this.configureDecoder((B=n.header.media)==null?void 0:B.codecData),this.isConfiguring=!1,this.waitingForKeyframe=!0;const h=this.pendingDuringConfig;this.pendingDuringConfig=[],this.logger.info(`Processing ${h.length} frames queued during configuration`);for(const R of h)await this.handleStreamData({trackName:l.trackName,streamType:l.streamType,data:R});return}if(this.isConfiguring){this.logger.debug(`Queueing frame pts=${(S=n.header.media)==null?void 0:S.pts} during configuration`),this.pendingDuringConfig.push(n);return}if(!this.decoder||this.decoder.state!=="configured"){this.logger.warn(`Dropping frame pts=${(y=n.header.media)==null?void 0:y.pts}: decoder not ready (state=${((E=this.decoder)==null?void 0:E.state)??"null"})`);return}if(this.waitingForKeyframe){if(!i){this.logger.debug(`Dropping frame pts=${(v=n.header.media)==null?void 0:v.pts}: waiting for keyframe`);const h=Date.now();(!this.lastWaitingForKeyframeLog||h-this.lastWaitingForKeyframeLog>1e3)&&(this.logger.info("Waiting for keyframe to resume playback..."),this.lastWaitingForKeyframeLog=h,(!this.lastKeyframeRequest||h-this.lastKeyframeRequest>1e3)&&(this.logger.info("Requesting keyframe..."),(T=(N=this.streamSource)==null?void 0:N.requestKeyframe)==null||T.call(N),this.lastKeyframeRequest=h));return}this.logger.debug("Keyframe received, resuming decode"),this.waitingForKeyframe=!1,this.lastWaitingForKeyframeLog=0}try{const h=performance.now(),R=(m=(C=n.header.media)==null?void 0:C.codecData)!=null&&m.timebaseDen&&((p=(Q=n.header.media)==null?void 0:Q.codecData)!=null&&p.timebaseNum)?{num:n.header.media.codecData.timebaseNum,den:n.header.media.codecData.timebaseDen}:{num:1,den:1e6},J={num:1,den:1e6},V=rescaleTime(((f=n.header.media)==null?void 0:f.pts)??0,R,J);if(this.arrivalTimes.set(V,h),this.keyframeStatus.set(V,i),this.lastVideoTimestampUs>=0&&V>this.lastVideoTimestampUs){const W=V-this.lastVideoTimestampUs;if(W>5e3&&W<1e6&&(this.fpsEstimateSamples.push(W),this.fpsEstimateSamples.length>Ko.FPS_SAMPLE_COUNT&&this.fpsEstimateSamples.shift(),this.fpsEstimateSamples.length>=3)){const b=this.fpsEstimateSamples.reduce((g,Z)=>g+Z,0)/this.fpsEstimateSamples.length;this.estimatedFrameRate=Math.round(1e6/b)}}if(this.lastVideoTimestampUs=V,this.arrivalTimes.size>100){const W=[...this.arrivalTimes.entries()];for(let b=0;b<W.length-100;b++)this.arrivalTimes.delete(W[b][0]),this.keyframeStatus.delete(W[b][0])}this.decoder.decodeBinary(n)}catch(h){this.logger.error(`Decode error: ${h}`)}}async handleAudioData(l){var r,t,e,i,a,s,d,c,F,B;if(!this.config.enableAudio)return;const n=this.audioCodecData??void 0;(t=(r=l.header)==null?void 0:r.media)!=null&&t.codecData&&codecDataChanged(n,l.header.media.codecData)&&(this.audioCodecData=l.header.media.codecData,this.audioPlayer&&(this.audioPlayer.dispose(),this.audioPlayer=null),this.audioContext||(this.config.audioContext?(this.audioContext=this.config.audioContext,this.ownsAudioContext=!1):(this.audioContext=new AudioContext,this.ownsAudioContext=!0)),this.audioPlayer=new LiveAudioPlayer(this.audioContext,{bufferDelayMs:this.config.bufferDelayMs??100}),await this.audioPlayer.init((e=l.header.media)==null?void 0:e.codecData),this.audioPlayer.start(),this.logger.info(`Audio player started: ${(a=(i=l.header.media)==null?void 0:i.codecData)==null?void 0:a.codecType}, ${(d=(s=l.header.media)==null?void 0:s.codecData)==null?void 0:d.sampleRate}Hz, ${(F=(c=l.header.media)==null?void 0:c.codecData)==null?void 0:F.channels}ch`)),this.audioPlayer&&l.payload&&l.header&&this.audioPlayer.decode(l.payload,(B=l.header.media)==null?void 0:B.pts)}async configureDecoder(l){this.useWasmDecoder=this.config.preferredDecoder==="wasm",(!this.decoder||this.useWasmDecoder&&this.decoder instanceof WebCodecsDecoder||!this.useWasmDecoder&&this.decoder instanceof WasmDecoder)&&(this.decoder&&this.decoder.dispose(),this.useWasmDecoder?(this.logger.info("Using WASM decoder"),this.decoder=new WasmDecoder({onFrameDecoded:r=>this.handleDecodedYUVFrame(r),onError:r=>this.handleDecoderError(r),onQueueOverflow:r=>this.handleQueueOverflow(r),maxQueueSize:10})):(this.logger.info(`Using WebCodecs decoder (${this.config.preferredDecoder})`),this.decoder=new WebCodecsDecoder({logger:this.logger,onFrameDecoded:r=>this.handleDecodedFrame(r),onError:r=>this.handleDecoderError(r),onQueueOverflow:r=>this.handleQueueOverflow(r),maxQueueSize:10})));const n=this.config.preferredDecoder==="webcodecs-hw";try{this.useWasmDecoder?await this.decoder.configure(l):await this.decoder.configure(l,n),this.streamWidth=l.width||0,this.streamHeight=l.height||0,this.lastVideoTimestampUs=-1,this.fpsEstimateSamples=[],this.estimatedFrameRate=30,this.emit("metadata",{width:l.width,height:l.height,codec:this.getCodecName(l.codecType||sesame.v1.common.CodecType.CODEC_TYPE_VIDEO_AVC)})}catch(r){this.logger.error(`Failed to configure decoder: ${r}`),this.setState("error"),this.emit("error",r instanceof Error?r:new Error(String(r)))}}getCodecName(l){switch(l){case sesame.v1.common.CodecType.CODEC_TYPE_VIDEO_AVC:return"H.264";case sesame.v1.common.CodecType.CODEC_TYPE_VIDEO_HEVC:return"HEVC";case sesame.v1.common.CodecType.CODEC_TYPE_VIDEO_AV1:return"AV1";default:return"Unknown"}}handleDecodedFrame(l){const n=performance.now(),r=this.arrivalTimes.get(l.timestamp)??n,t=this.keyframeStatus.get(l.timestamp)??!1,e={arrivalTime:r,decodeTime:n};this.frameScheduler.enqueue(l,l.timestamp,e,t),this.emit("frame",l)}handleDecodedYUVFrame(l){const n=performance.now(),r=this.arrivalTimes.get(l.timestamp)??n,t=this.keyframeStatus.get(l.timestamp)??!1,e=this.convertYUVToVideoFrame(l,this.streamWidth,this.streamHeight);if(e){const i={arrivalTime:r,decodeTime:n};this.frameScheduler.enqueue(e,l.timestamp,i,t),this.emit("frame",e)}}convertYUVToVideoFrame(l,n,r){try{const{y:t,u:e,v:i,width:a,height:s,chromaStride:d,chromaHeight:c}=l,F=n>0?n:a,B=r>0?r:s,y=a*s,E=d*c,v=y+E*2,N=new Uint8Array(v);N.set(t.subarray(0,y),0);const T=a/2,C=y;if(d===T)N.set(e.subarray(0,E),C);else for(let Q=0;Q<c;Q++)N.set(e.subarray(Q*d,Q*d+T),C+Q*T);const m=C+T*c;if(d===T)N.set(i.subarray(0,E),m);else for(let Q=0;Q<c;Q++)N.set(i.subarray(Q*d,Q*d+T),m+Q*T);return new VideoFrame(N,{format:"I420",codedWidth:a,codedHeight:s,visibleRect:{x:0,y:0,width:F,height:B},timestamp:l.timestamp,duration:this.estimatedFrameRate>0?1e6/this.estimatedFrameRate:33333})}catch(t){return this.logger.error(`YUV conversion error: ${t}`),null}}handleDecoderError(l){this.logger.error(`Decoder error: ${l.message}`),this.emit("error",l)}handleQueueOverflow(l){this.logger.warn(`Decoder queue overflow: ${l} frames, flushing...`),this.flush()}dispose(){this.streamSource&&this.boundDataHandler&&this.streamSource.off("data",this.boundDataHandler),this.streamSource=null,this.boundDataHandler=null,this.decoder&&(this.decoder.dispose(),this.decoder=null),this.audioPlayer&&(this.audioPlayer.dispose(),this.audioPlayer=null),this.ownsAudioContext&&this.audioContext&&this.audioContext.close(),this.audioContext=null,this.audioCodecData=null,this.frameScheduler.clear(),this.lastVideoFrame&&(this.lastVideoFrame.close(),this.lastVideoFrame=null),this.arrivalTimes.clear(),this.currentCodecData=void 0,this.waitingForKeyframe=!0,this.totalDrops=0,this.consecutiveDrops=0,this.clearEventHandlers(),this.setState("idle"),this.logger.info("Player disposed")}};U(Ko,"FPS_SAMPLE_COUNT",10);let LiveVideoPlayer=Ko;var __defProp=Object.defineProperty,__export=(u,o)=>{for(var l in o)__defProp(u,l,{get:o[l],enumerable:!0})},MAX_SIZE=Math.pow(2,32),MAX_UINT32=Math.pow(2,32)-1,TKHD_FLAG_ENABLED=1,TKHD_FLAG_IN_MOVIE=2,TKHD_FLAG_IN_PREVIEW=4,TFHD_FLAG_BASE_DATA_OFFSET=1,TFHD_FLAG_SAMPLE_DESC=2,TFHD_FLAG_SAMPLE_DUR=8,TFHD_FLAG_SAMPLE_SIZE=16,TFHD_FLAG_SAMPLE_FLAGS=32,TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,TRUN_FLAGS_DATA_OFFSET=1,TRUN_FLAGS_FIRST_FLAG=4,TRUN_FLAGS_DURATION=256,TRUN_FLAGS_SIZE=512,TRUN_FLAGS_FLAGS=1024,TRUN_FLAGS_CTS_OFFSET=2048,ERR_INVALID_DATA=-1,ERR_NOT_ENOUGH_DATA=0,OK=1,MP4BoxBuffer=class cr extends ArrayBuffer{constructor(o){super(o),this.fileStart=0,this.usedBytes=0}static fromArrayBuffer(o,l){const n=new cr(o.byteLength);return new Uint8Array(n).set(new Uint8Array(o)),n.fileStart=l,n}},P,ar,k,DataStream=(k=class{constructor(o,l,n){rr(this,P);this._byteLength=0,this.failurePosition=0,this._dynamicSize=1,this._byteOffset=l||0,o instanceof ArrayBuffer?this.buffer=MP4BoxBuffer.fromArrayBuffer(o,0):o instanceof DataView?(this.dataView=o,l&&(this._byteOffset+=l)):this.buffer=new MP4BoxBuffer(o||0),this.position=0,this.endianness=n||1}getPosition(){return this.position}_realloc(o){if(!this._dynamicSize)return;const l=this._byteOffset+this.position+o;let n=this._buffer.byteLength;if(l<=n){l>this._byteLength&&(this._byteLength=l);return}for(n<1&&(n=1);l>n;)n*=2;const r=new MP4BoxBuffer(n),t=new Uint8Array(this._buffer);new Uint8Array(r,0,t.length).set(t),this.buffer=r,this._byteLength=l}_trimAlloc(){if(this._byteLength===this._buffer.byteLength)return;const o=new MP4BoxBuffer(this._byteLength),l=new Uint8Array(o),n=new Uint8Array(this._buffer,0,l.length);l.set(n),this.buffer=o}get byteLength(){return this._byteLength-this._byteOffset}get buffer(){return this._trimAlloc(),this._buffer}set buffer(o){this._buffer=o,this._dataView=new DataView(o,this._byteOffset),this._byteLength=o.byteLength}get byteOffset(){return this._byteOffset}set byteOffset(o){this._byteOffset=o,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}get dataView(){return this._dataView}set dataView(o){this._byteOffset=o.byteOffset,this._buffer=MP4BoxBuffer.fromArrayBuffer(o.buffer,0),this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+o.byteLength}seek(o){const l=Math.max(0,Math.min(this.byteLength,o));this.position=isNaN(l)||!isFinite(l)?0:l}isEof(){return this.position>=this._byteLength}mapUint8Array(o){this._realloc(o*1);const l=new Uint8Array(this._buffer,this.byteOffset+this.position,o);return this.position+=o*1,l}readInt32Array(o,l){o=o===void 0?this.byteLength-this.position/4:o;const n=new Int32Array(o);return k.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,o*n.BYTES_PER_ELEMENT),k.arrayToNative(n,l??this.endianness),this.position+=n.byteLength,n}readInt16Array(o,l){o=o===void 0?this.byteLength-this.position/2:o;const n=new Int16Array(o);return k.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,o*n.BYTES_PER_ELEMENT),k.arrayToNative(n,l??this.endianness),this.position+=n.byteLength,n}readInt8Array(o){o=o===void 0?this.byteLength-this.position:o;const l=new Int8Array(o);return k.memcpy(l.buffer,0,this.buffer,this.byteOffset+this.position,o*l.BYTES_PER_ELEMENT),this.position+=l.byteLength,l}readUint32Array(o,l){o=o===void 0?this.byteLength-this.position/4:o;const n=new Uint32Array(o);return k.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,o*n.BYTES_PER_ELEMENT),k.arrayToNative(n,l??this.endianness),this.position+=n.byteLength,n}readUint16Array(o,l){o=o===void 0?this.byteLength-this.position/2:o;const n=new Uint16Array(o);return k.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,o*n.BYTES_PER_ELEMENT),k.arrayToNative(n,l??this.endianness),this.position+=n.byteLength,n}readUint8Array(o){o=o===void 0?this.byteLength-this.position:o;const l=new Uint8Array(o);return k.memcpy(l.buffer,0,this.buffer,this.byteOffset+this.position,o*l.BYTES_PER_ELEMENT),this.position+=l.byteLength,l}readFloat64Array(o,l){o=o===void 0?this.byteLength-this.position/8:o;const n=new Float64Array(o);return k.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,o*n.BYTES_PER_ELEMENT),k.arrayToNative(n,l??this.endianness),this.position+=n.byteLength,n}readFloat32Array(o,l){o=o===void 0?this.byteLength-this.position/4:o;const n=new Float32Array(o);return k.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,o*n.BYTES_PER_ELEMENT),k.arrayToNative(n,l??this.endianness),this.position+=n.byteLength,n}readInt32(o){const l=this._dataView.getInt32(this.position,(o??this.endianness)===2);return this.position+=4,l}readInt16(o){const l=this._dataView.getInt16(this.position,(o??this.endianness)===2);return this.position+=2,l}readInt8(){const o=this._dataView.getInt8(this.position);return this.position+=1,o}readUint32(o){const l=this._dataView.getUint32(this.position,(o??this.endianness)===2);return this.position+=4,l}readUint16(o){const l=this._dataView.getUint16(this.position,(o??this.endianness)===2);return this.position+=2,l}readUint8(){const o=this._dataView.getUint8(this.position);return this.position+=1,o}readFloat32(o){const l=this._dataView.getFloat32(this.position,(o??this.endianness)===2);return this.position+=4,l}readFloat64(o){const l=this._dataView.getFloat64(this.position,(o??this.endianness)===2);return this.position+=8,l}static memcpy(o,l,n,r,t){const e=new Uint8Array(o,l,t),i=new Uint8Array(n,r,t);e.set(i)}static arrayToNative(o,l){return l===k.ENDIANNESS?o:this.flipArrayEndianness(o)}static nativeToEndian(o,l){return l&&k.ENDIANNESS===2?o:this.flipArrayEndianness(o)}static flipArrayEndianness(o){const l=new Uint8Array(o.buffer,o.byteOffset,o.byteLength);for(let n=0;n<o.byteLength;n+=o.BYTES_PER_ELEMENT)for(let r=n+o.BYTES_PER_ELEMENT-1,t=n;r>t;r--,t++){const e=l[t];l[t]=l[r],l[r]=e}return o}readString(o,l){return l===void 0||l==="ASCII"?fromCharCodeUint8(this.mapUint8Array(o===void 0?this.byteLength-this.position:o)):new TextDecoder(l).decode(this.mapUint8Array(o))}readCString(o){let l=0;const n=this.byteLength-this.position,r=new Uint8Array(this._buffer,this._byteOffset+this.position),t=o!==void 0?Math.min(o,n):n;for(;l<t&&r[l]!==0;l++);const e=fromCharCodeUint8(this.mapUint8Array(l));return o!==void 0?this.position+=t-l:l!==n&&(this.position+=1),e}readInt64(){return this.readInt32()*MAX_SIZE+this.readUint32()}readUint64(){return this.readUint32()*MAX_SIZE+this.readUint32()}readUint24(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()}save(o){const l=new Blob([this.buffer]);if(typeof window<"u"&&typeof document<"u")if(window.URL&&URL.createObjectURL){const n=window.URL.createObjectURL(l),r=document.createElement("a");document.body.appendChild(r),r.setAttribute("href",n),r.setAttribute("download",o),r.setAttribute("target","_self"),r.click(),window.URL.revokeObjectURL(n),document.body.removeChild(r)}else throw new Error("DataStream.save: Can't create object URL.");return l}get dynamicSize(){return this._dynamicSize}set dynamicSize(o){o||this._trimAlloc(),this._dynamicSize=o}shift(o){const l=new MP4BoxBuffer(this._byteLength-o),n=new Uint8Array(l),r=new Uint8Array(this._buffer,o,n.length);n.set(r),this.buffer=l,this.position-=o}writeInt32Array(o,l){if(this._realloc(o.length*4),o instanceof Int32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt32Array(o.length,l);else for(let n=0;n<o.length;n++)this.writeInt32(o[n],l)}writeInt16Array(o,l){if(this._realloc(o.length*2),o instanceof Int16Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt16Array(o.length,l);else for(let n=0;n<o.length;n++)this.writeInt16(o[n],l)}writeInt8Array(o){if(this._realloc(o.length*1),o instanceof Int8Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt8Array(o.length);else for(let l=0;l<o.length;l++)this.writeInt8(o[l])}writeUint32Array(o,l){if(this._realloc(o.length*4),o instanceof Uint32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint32Array(o.length,l);else for(let n=0;n<o.length;n++)this.writeUint32(o[n],l)}writeUint16Array(o,l){if(this._realloc(o.length*2),o instanceof Uint16Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint16Array(o.length,l);else for(let n=0;n<o.length;n++)this.writeUint16(o[n],l)}writeUint8Array(o){if(this._realloc(o.length*1),o instanceof Uint8Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint8Array(o.length);else for(let l=0;l<o.length;l++)this.writeUint8(o[l])}writeFloat64Array(o,l){if(this._realloc(o.length*8),o instanceof Float64Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapFloat64Array(o.length,l);else for(let n=0;n<o.length;n++)this.writeFloat64(o[n],l)}writeFloat32Array(o,l){if(this._realloc(o.length*4),o instanceof Float32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)k.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapFloat32Array(o.length,l);else for(let n=0;n<o.length;n++)this.writeFloat32(o[n],l)}writeInt64(o,l){this._realloc(8),this._dataView.setBigInt64(this.position,BigInt(o),(l??this.endianness)===2),this.position+=8}writeInt32(o,l){this._realloc(4),this._dataView.setInt32(this.position,o,(l??this.endianness)===2),this.position+=4}writeInt16(o,l){this._realloc(2),this._dataView.setInt16(this.position,o,(l??this.endianness)===2),this.position+=2}writeInt8(o){this._realloc(1),this._dataView.setInt8(this.position,o),this.position+=1}writeUint32(o,l){this._realloc(4),this._dataView.setUint32(this.position,o,(l??this.endianness)===2),this.position+=4}writeUint16(o,l){this._realloc(2),this._dataView.setUint16(this.position,o,(l??this.endianness)===2),this.position+=2}writeUint8(o){this._realloc(1),this._dataView.setUint8(this.position,o),this.position+=1}writeFloat32(o,l){this._realloc(4),this._dataView.setFloat32(this.position,o,(l??this.endianness)===2),this.position+=4}writeFloat64(o,l){this._realloc(8),this._dataView.setFloat64(this.position,o,(l??this.endianness)===2),this.position+=8}writeUCS2String(o,l,n){n===void 0&&(n=o.length);let r;for(r=0;r<o.length&&r<n;r++)this.writeUint16(o.charCodeAt(r),l);for(;r<n;r++)this.writeUint16(0)}writeString(o,l,n){let r=0;if(l===void 0||l==="ASCII")if(n!==void 0){const t=Math.min(o.length,n);for(r=0;r<t;r++)this.writeUint8(o.charCodeAt(r));for(;r<n;r++)this.writeUint8(0)}else for(r=0;r<o.length;r++)this.writeUint8(o.charCodeAt(r));else this.writeUint8Array(new TextEncoder(l).encode(o.substring(0,n)))}writeCString(o,l){let n=0;if(l!==void 0){const r=Math.min(o.length,l);for(n=0;n<r;n++)this.writeUint8(o.charCodeAt(n));for(;n<l;n++)this.writeUint8(0)}else{for(n=0;n<o.length;n++)this.writeUint8(o.charCodeAt(n));this.writeUint8(0)}}writeStruct(o,l){for(let n=0;n<o.length;n++){const[r,t]=o[n],e=l[r];this.writeType(t,e,l)}}writeType(o,l,n){if(typeof o=="function")return o(this,l);if(typeof o=="object"&&!(o instanceof Array))return o.set(this,l,n);let r,t="ASCII";const e=this.position;let i=o;if(typeof o=="string"&&/:/.test(o)){const a=o.split(":");i=a[0],r=parseInt(a[1])}if(typeof i=="string"&&/,/.test(i)){const a=i.split(",");i=a[0],t=a[1]}switch(i){case"uint8":this.writeUint8(l);break;case"int8":this.writeInt8(l);break;case"uint16":this.writeUint16(l,this.endianness);break;case"int16":this.writeInt16(l,this.endianness);break;case"uint32":this.writeUint32(l,this.endianness);break;case"int32":this.writeInt32(l,this.endianness);break;case"float32":this.writeFloat32(l,this.endianness);break;case"float64":this.writeFloat64(l,this.endianness);break;case"uint16be":this.writeUint16(l,1);break;case"int16be":this.writeInt16(l,1);break;case"uint32be":this.writeUint32(l,1);break;case"int32be":this.writeInt32(l,1);break;case"float32be":this.writeFloat32(l,1);break;case"float64be":this.writeFloat64(l,1);break;case"uint16le":this.writeUint16(l,2);break;case"int16le":this.writeInt16(l,2);break;case"uint32le":this.writeUint32(l,2);break;case"int32le":this.writeInt32(l,2);break;case"float32le":this.writeFloat32(l,2);break;case"float64le":this.writeFloat64(l,2);break;case"cstring":this.writeCString(l,r);break;case"string":this.writeString(l,t,r);break;case"u16string":this.writeUCS2String(l,this.endianness,r);break;case"u16stringle":this.writeUCS2String(l,2,r);break;case"u16stringbe":this.writeUCS2String(l,1,r);break;default:if(lr(this,P,ar).call(this,i)){const[,a]=i;for(let s=0;s<l.length;s++)this.writeType(a,l[s]);break}else{this.writeStruct(i,l);break}}r&&(this.position=e,this._realloc(r),this.position=e+r)}writeUint64(o){const l=Math.floor(o/MAX_SIZE);this.writeUint32(l),this.writeUint32(o&4294967295)}writeUint24(o){this.writeUint8((o&16711680)>>16),this.writeUint8((o&65280)>>8),this.writeUint8(o&255)}adjustUint32(o,l){const n=this.position;this.seek(o),this.writeUint32(l),this.seek(n)}readStruct(o){const l={},n=this.position;for(let r=0;r<o.length;r+=1){const t=o[r][1],e=this.readType(t,l);if(!e){this.failurePosition===0&&(this.failurePosition=this.position),this.position=n;return}l[o[r][0]]=e}return l}readUCS2String(o,l){return String.fromCharCode.apply(void 0,this.readUint16Array(o,l))}readType(o,l){if(typeof o=="function")return o(this,l);if(typeof o=="object"&&!(o instanceof Array))return o.get(this,l);if(o instanceof Array&&o.length!==3)return this.readStruct(o);let n,r,t="ASCII";const e=this.position;let i=o;if(typeof i=="string"&&/:/.test(i)){const a=i.split(":");i=a[0],r=parseInt(a[1])}if(typeof i=="string"&&/,/.test(i)){const a=i.split(",");i=a[0],t=a[1]}switch(i){case"uint8":n=this.readUint8();break;case"int8":n=this.readInt8();break;case"uint16":n=this.readUint16(this.endianness);break;case"int16":n=this.readInt16(this.endianness);break;case"uint32":n=this.readUint32(this.endianness);break;case"int32":n=this.readInt32(this.endianness);break;case"float32":n=this.readFloat32(this.endianness);break;case"float64":n=this.readFloat64(this.endianness);break;case"uint16be":n=this.readUint16(1);break;case"int16be":n=this.readInt16(1);break;case"uint32be":n=this.readUint32(1);break;case"int32be":n=this.readInt32(1);break;case"float32be":n=this.readFloat32(1);break;case"float64be":n=this.readFloat64(1);break;case"uint16le":n=this.readUint16(2);break;case"int16le":n=this.readInt16(2);break;case"uint32le":n=this.readUint32(2);break;case"int32le":n=this.readInt32(2);break;case"float32le":n=this.readFloat32(2);break;case"float64le":n=this.readFloat64(2);break;case"cstring":n=this.readCString(r);break;case"string":n=this.readString(r,t);break;case"u16string":n=this.readUCS2String(r,this.endianness);break;case"u16stringle":n=this.readUCS2String(r,2);break;case"u16stringbe":n=this.readUCS2String(r,1);break;default:if(lr(this,P,ar).call(this,i)){const[,a,s]=i,d=typeof s=="function"?s(l,this,i):typeof s=="string"&&l[s]!==void 0?parseInt(l[s]):typeof s=="number"?s:s==="*"?void 0:parseInt(s);if(typeof a=="string"){const c=a.replace(/(le|be)$/,"");let F;switch(/le$/.test(a)?F=2:/be$/.test(a)&&(F=1),c){case"uint8":n=this.readUint8Array(d);break;case"uint16":n=this.readUint16Array(d,F);break;case"uint32":n=this.readUint32Array(d,F);break;case"int8":n=this.readInt8Array(d);break;case"int16":n=this.readInt16Array(d,F);break;case"int32":n=this.readInt32Array(d,F);break;case"float32":n=this.readFloat32Array(d,F);break;case"float64":n=this.readFloat64Array(d,F);break;case"cstring":case"utf16string":case"string":if(d){n=new Array(d);for(let B=0;B<d;B++)n[B]=this.readType(a,l)}else for(n=[];!this.isEof();){const B=this.readType(a,l);if(!B)break;n.push(B)}break}}else if(d){n=new Array(d);for(let c=0;c<d;c++){const F=this.readType(a,l);if(!F)return;n[c]=F}}else for(n=[];;){const c=this.position;try{const F=this.readType(a,l);if(!F){this.position=c;break}n.push(F)}catch{this.position=c;break}}break}}return r&&(this.position=e+r),n}mapInt32Array(o,l){this._realloc(o*4);const n=new Int32Array(this._buffer,this.byteOffset+this.position,o);return k.arrayToNative(n,l??this.endianness),this.position+=o*4,n}mapInt16Array(o,l){this._realloc(o*2);const n=new Int16Array(this._buffer,this.byteOffset+this.position,o);return k.arrayToNative(n,l??this.endianness),this.position+=o*2,n}mapInt8Array(o,l){this._realloc(o*1);const n=new Int8Array(this._buffer,this.byteOffset+this.position,o);return this.position+=o*1,n}mapUint32Array(o,l){this._realloc(o*4);const n=new Uint32Array(this._buffer,this.byteOffset+this.position,o);return k.arrayToNative(n,l??this.endianness),this.position+=o*4,n}mapUint16Array(o,l){this._realloc(o*2);const n=new Uint16Array(this._buffer,this.byteOffset+this.position,o);return k.arrayToNative(n,l??this.endianness),this.position+=o*2,n}mapFloat64Array(o,l){this._realloc(o*8);const n=new Float64Array(this._buffer,this.byteOffset+this.position,o);return k.arrayToNative(n,l??this.endianness),this.position+=o*8,n}mapFloat32Array(o,l){this._realloc(o*4);const n=new Float32Array(this._buffer,this.byteOffset+this.position,o);return k.arrayToNative(n,l??this.endianness),this.position+=o*4,n}},P=new WeakSet,ar=function(o){return Array.isArray(o)&&o.length===3&&o[0]==="[]"},k.ENDIANNESS=new Int8Array(new Int16Array([1]).buffer)[0]>0?2:1,k);function fromCharCodeUint8(u){const o=[];for(let l=0;l<u.length;l++)o[l]=u[l];return String.fromCharCode.apply(void 0,o)}var start=new Date,LOG_LEVEL_ERROR=4,LOG_LEVEL_WARNING=3,LOG_LEVEL_INFO=2,LOG_LEVEL_DEBUG=1,log_level=LOG_LEVEL_ERROR,Log={setLogLevel(u){u===this.debug?log_level=LOG_LEVEL_DEBUG:u===this.info?log_level=LOG_LEVEL_INFO:u===this.warn?log_level=LOG_LEVEL_WARNING:(this.error,log_level=LOG_LEVEL_ERROR)},debug(u,o){console.debug===void 0&&(console.debug=console.log),LOG_LEVEL_DEBUG>=log_level&&console.debug("["+Log.getDurationString(new Date().getTime()-start.getTime(),1e3)+"]","["+u+"]",o)},log(u,o){this.debug(u.msg)},info(u,o){LOG_LEVEL_INFO>=log_level&&console.info("["+Log.getDurationString(new Date().getTime()-start.getTime(),1e3)+"]","["+u+"]",o)},warn(u,o){LOG_LEVEL_WARNING>=log_level&&console.warn("["+Log.getDurationString(new Date().getTime()-start.getTime(),1e3)+"]","["+u+"]",o)},error(u,o,l){l!=null&&l.onError?l.onError(u,o):LOG_LEVEL_ERROR>=log_level&&console.error("["+Log.getDurationString(new Date().getTime()-start.getTime(),1e3)+"]","["+u+"]",o)},getDurationString(u,o){let l;function n(s,d){const F=(""+s).split(".");for(;F[0].length<d;)F[0]="0"+F[0];return F.join(".")}u<0?(l=!0,u=-u):l=!1;let t=u/(o||1);const e=Math.floor(t/3600);t-=e*3600;const i=Math.floor(t/60);t-=i*60;let a=t*1e3;return t=Math.floor(t),a-=t*1e3,a=Math.floor(a),(l?"-":"")+e+":"+n(i,2)+":"+n(t,2)+"."+n(a,3)},printRanges(u){const o=u.length;if(o>0){let l="";for(let n=0;n<o;n++)n>0&&(l+=","),l+="["+Log.getDurationString(u.start(n))+","+Log.getDurationString(u.end(n))+"]";return l}else return"(empty)"}};function concatBuffers(u,o){Log.debug("ArrayBuffer","Trying to create a new buffer of size: "+(u.byteLength+o.byteLength));const l=new Uint8Array(u.byteLength+o.byteLength);return l.set(new Uint8Array(u),0),l.set(new Uint8Array(o),u.byteLength),l.buffer}var MultiBufferStream=class extends DataStream{constructor(u){super(new ArrayBuffer,0),this.buffers=[],this.bufferIndex=-1,u&&(this.insertBuffer(u),this.bufferIndex=0)}initialized(){if(this.bufferIndex>-1)return!0;if(this.buffers.length>0){const u=this.buffers[0];return u.fileStart===0?(this.buffer=u,this.bufferIndex=0,Log.debug("MultiBufferStream","Stream ready for parsing"),!0):(Log.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)}else return Log.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1}reduceBuffer(u,o,l){const n=new Uint8Array(l);return n.set(new Uint8Array(u,o,l)),n.buffer.fileStart=u.fileStart+o,n.buffer.usedBytes=0,n.buffer}insertBuffer(u){let o=!0,l=0;for(;l<this.buffers.length;l++){const n=this.buffers[l];if(u.fileStart<=n.fileStart){if(u.fileStart===n.fileStart)if(u.byteLength>n.byteLength){this.buffers.splice(l,1),l--;continue}else Log.warn("MultiBufferStream","Buffer (fileStart: "+u.fileStart+" - Length: "+u.byteLength+") already appended, ignoring");else u.fileStart+u.byteLength<=n.fileStart||(u=this.reduceBuffer(u,0,n.fileStart-u.fileStart)),Log.debug("MultiBufferStream","Appending new buffer (fileStart: "+u.fileStart+" - Length: "+u.byteLength+")"),this.buffers.splice(l,0,u),l===0&&(this.buffer=u);o=!1;break}else if(u.fileStart<n.fileStart+n.byteLength){const r=n.fileStart+n.byteLength-u.fileStart,t=u.byteLength-r;if(t>0)u=this.reduceBuffer(u,r,t);else{o=!1;break}}}o&&(Log.debug("MultiBufferStream","Appending new buffer (fileStart: "+u.fileStart+" - Length: "+u.byteLength+")"),this.buffers.push(u),l===0&&(this.buffer=u))}logBufferLevel(u){const o=[];let l="",n,r=0,t=0;for(let i=0;i<this.buffers.length;i++){const a=this.buffers[i];i===0?(n={start:a.fileStart,end:a.fileStart+a.byteLength},o.push(n),l+="["+n.start+"-"):n.end===a.fileStart?n.end=a.fileStart+a.byteLength:(n={start:a.fileStart,end:a.fileStart+a.byteLength},l+=o[o.length-1].end-1+"], ["+n.start+"-",o.push(n)),r+=a.usedBytes,t+=a.byteLength}o.length>0&&(l+=n.end-1+"]");const e=u?Log.info:Log.debug;this.buffers.length===0?e("MultiBufferStream","No more buffer in memory"):e("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+r+"/"+t+" bytes), continuous ranges: "+l)}cleanBuffers(){for(let u=0;u<this.buffers.length;u++){const o=this.buffers[u];o.usedBytes===o.byteLength&&(Log.debug("MultiBufferStream","Removing buffer #"+u),this.buffers.splice(u,1),u--)}}mergeNextBuffer(){if(this.bufferIndex+1<this.buffers.length){const u=this.buffers[this.bufferIndex+1];if(u.fileStart===this.buffer.fileStart+this.buffer.byteLength){const o=this.buffer.byteLength,l=this.buffer.usedBytes,n=this.buffer.fileStart;return this.buffers[this.bufferIndex]=concatBuffers(this.buffer,u),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=l,this.buffer.fileStart=n,Log.debug("ISOFile","Concatenating buffer for box parsing (length: "+o+"->"+this.buffer.byteLength+")"),!0}else return!1}else return!1}findPosition(u,o,l){let n=-1,r=u===!0?0:this.bufferIndex;for(;r<this.buffers.length;){const e=this.buffers[r];if(e&&e.fileStart<=o)n=r,l&&(e.fileStart+e.byteLength<=o?e.usedBytes=e.byteLength:e.usedBytes=o-e.fileStart,this.logBufferLevel());else break;r++}if(n===-1)return-1;const t=this.buffers[n];return t.fileStart+t.byteLength>=o?(Log.debug("MultiBufferStream","Found position in existing buffer #"+n),n):-1}findEndContiguousBuf(u){const o=u!==void 0?u:this.bufferIndex;let l=this.buffers[o];if(this.buffers.length>o+1)for(let n=o+1;n<this.buffers.length;n++){const r=this.buffers[n];if(r.fileStart===l.fileStart+l.byteLength)l=r;else break}return l.fileStart+l.byteLength}getEndFilePositionAfter(u){const o=this.findPosition(!0,u,!1);return o!==-1?this.findEndContiguousBuf(o):u}addUsedBytes(u){this.buffer.usedBytes+=u,this.logBufferLevel()}setAllUsedBytes(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()}seek(u,o,l){const n=this.findPosition(o,u,l);return n!==-1?(this.buffer=this.buffers[n],this.bufferIndex=n,this.position=u-this.buffer.fileStart,Log.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(Log.debug("MultiBufferStream","Position "+u+" not found in buffered data"),!1)}getPosition(){return this.bufferIndex===-1||this.buffers[this.bufferIndex]===void 0?0:this.buffers[this.bufferIndex].fileStart+this.position}getLength(){return this.byteLength}getEndPosition(){return this.bufferIndex===-1||this.buffers[this.bufferIndex]===void 0?0:this.buffers[this.bufferIndex].fileStart+this.byteLength}getAbsoluteEndPosition(){if(this.buffers.length===0)return 0;const u=this.buffers[this.buffers.length-1];return u.fileStart+u.byteLength}},$,L,Box=(L=class{constructor(o=0){rr(this,$,void 0);this.size=o}get type(){return this.constructor.fourcc??dr(this,$)}set type(o){ur(this,$,o)}addBox(o){return this.boxes||(this.boxes=[]),this.boxes.push(o),this[o.type+"s"]?this[o.type+"s"].push(o):this[o.type]=o,o}set(o,l){return this[o]=l,this}addEntry(o,l){const n=l||"entries";return this[n]||(this[n]=[]),this[n].push(o),this}writeHeader(o,l){if(this.size+=8,(this.size>MAX_UINT32||this.original_size===1)&&(this.size+=8),this.type==="uuid"&&(this.size+=16),Log.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+o.getPosition()+(l||"")),this.original_size===0?o.writeUint32(0):this.size>MAX_UINT32||this.original_size===1?o.writeUint32(1):(this.sizePosition=o.getPosition(),o.writeUint32(this.size)),o.writeString(this.type,void 0,4),this.type==="uuid"){const n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(this.uuid.substring(r*2,r*2+2),16);o.writeUint8Array(n)}(this.size>MAX_UINT32||this.original_size===1)&&(this.sizePosition=o.getPosition(),o.writeUint64(this.size))}write(o){if(this.type==="mdat"){const l=this;if(l.stream){this.size=l.stream.getAbsoluteEndPosition(),this.writeHeader(o);for(const n of l.stream.buffers){const r=new Uint8Array(n);o.writeUint8Array(r)}}else l.data&&(this.size=l.data.length,this.writeHeader(o),o.writeUint8Array(l.data))}else this.size=this.data?this.data.length:0,this.writeHeader(o),this.data&&o.writeUint8Array(this.data)}printHeader(o){this.size+=8,this.size>MAX_UINT32&&(this.size+=8),this.type==="uuid"&&(this.size+=16),o.log(o.indent+"size:"+this.size),o.log(o.indent+"type:"+this.type)}print(o){this.printHeader(o)}parse(o){this.type!=="mdat"?this.data=o.readUint8Array(this.size-this.hdr_size):this.size===0?o.seek(o.getEndPosition()):o.seek(this.start+this.size)}parseDataAndRewind(o){this.data=o.readUint8Array(this.size-this.hdr_size),o.seek(this.start+this.hdr_size)}parseLanguage(o){this.language=o.readUint16();const l=[];l[0]=this.language>>10&31,l[1]=this.language>>5&31,l[2]=this.language&31,this.languageString=String.fromCharCode(l[0]+96,l[1]+96,l[2]+96)}computeSize(o){const l=o||new MultiBufferStream;this.write(l)}isEndOfBox(o){const l=o.getPosition(),n=this.start+this.size;return l===n}},$=new WeakMap,L.registryId=Symbol.for("BoxIdentifier"),L),FullBox=class extends Box{constructor(){super(...arguments),this.flags=0,this.version=0}writeHeader(u){this.size+=4,super.writeHeader(u," v="+this.version+" f="+this.flags),u.writeUint8(this.version),u.writeUint24(this.flags)}printHeader(u){this.size+=4,super.printHeader(u),u.log(u.indent+"version:"+this.version),u.log(u.indent+"flags:"+this.flags)}parseDataAndRewind(u){this.parseFullHeader(u),this.data=u.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,u.seek(this.start+this.hdr_size)}parseFullHeader(u){this.version=u.readUint8(),this.flags=u.readUint24(),this.hdr_size+=4}parse(u){this.parseFullHeader(u),this.data=u.readUint8Array(this.size-this.hdr_size)}},A,SampleGroupEntry=(A=class{constructor(o){this.grouping_type=o}write(o){o.writeUint8Array(this.data)}parse(o){Log.warn("BoxParser",`Unknown sample group type: '${this.grouping_type}'`),this.data=o.readUint8Array(this.description_length)}},A.registryId=Symbol.for("SampleGroupEntryIdentifier"),A),TrackGroupTypeBox=class extends FullBox{parse(u){this.parseFullHeader(u),this.track_group_id=u.readUint32()}},SingleItemTypeReferenceBox=class extends Box{constructor(u,o,l,n,r){super(o),this.box_name=l,this.hdr_size=n,this.start=r,this.type=u}parse(u){this.from_item_ID=u.readUint16();const o=u.readUint16();this.references=[];for(let l=0;l<o;l++)this.references[l]={to_item_ID:u.readUint16()}}},SingleItemTypeReferenceBoxLarge=class extends Box{constructor(u,o,l,n,r){super(o),this.box_name=l,this.hdr_size=n,this.start=r,this.type=u}parse(u){this.from_item_ID=u.readUint32();const o=u.readUint16();this.references=[];for(let l=0;l<o;l++)this.references[l]={to_item_ID:u.readUint32()}}},TrackReferenceTypeBox=class extends Box{constructor(u,o,l,n){super(o),this.hdr_size=l,this.start=n,this.type=u}parse(u){this.track_ids=u.readUint32Array((this.size-this.hdr_size)/4)}write(u){this.size=this.track_ids.length*4,this.writeHeader(u),u.writeUint32Array(this.track_ids)}},DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"];function boxEqualFields(u,o){if(u&&!o)return!1;let l;for(l in u)if(!DIFF_BOXES_PROP_NAMES.find(n=>n===l)){if(u[l]instanceof Box||o[l]instanceof Box)continue;if(typeof u[l]>"u"||typeof o[l]>"u")continue;if(typeof u[l]=="function"||typeof o[l]=="function")continue;if("subBoxNames"in u&&u.subBoxNames.indexOf(l.slice(0,4))>-1||"subBoxNames"in o&&o.subBoxNames.indexOf(l.slice(0,4))>-1)continue;if(l==="data"||l==="start"||l==="size"||l==="creation_time"||l==="modification_time")continue;if(DIFF_PRIMITIVE_ARRAY_PROP_NAMES.find(n=>n===l))continue;if(u[l]!==o[l])return!1}return!0}function boxEqual(u,o){if(!boxEqualFields(u,o))return!1;for(let l=0;l<DIFF_BOXES_PROP_NAMES.length;l++){const n=DIFF_BOXES_PROP_NAMES[l];if(u[n]&&o[n]&&!boxEqual(u[n],o[n]))return!1}return!0}function getRegistryId(u){let o=u;for(;o;){if("registryId"in o)return o.registryId;o=Object.getPrototypeOf(o)}}var isSampleGroupEntry=u=>{const o=Symbol.for("SampleGroupEntryIdentifier");return getRegistryId(u)===o},isSampleEntry=u=>{const o=Symbol.for("SampleEntryIdentifier");return getRegistryId(u)===o},isBox=u=>{const o=Symbol.for("BoxIdentifier");return getRegistryId(u)===o},BoxRegistry={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};function registerBoxes(u){const o={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};for(const[l,n]of Object.entries(u)){if(isSampleGroupEntry(n)){const r="grouping_type"in n?n.grouping_type:void 0;if(!r)throw new Error(`SampleGroupEntry class ${l} does not have a valid static grouping_type. Please ensure it is defined correctly.`);if(r in o.sampleGroupEntry)throw new Error(`SampleGroupEntry class ${l} has a grouping_type that is already registered. Please ensure it is unique.`);o.sampleGroupEntry[r]=n;continue}if(isSampleEntry(n)){const r="fourcc"in n?n.fourcc:void 0;if(!r)throw new Error(`SampleEntry class ${l} does not have a valid static fourcc. Please ensure it is defined correctly.`);if(r in o.sampleEntry)throw new Error(`SampleEntry class ${l} has a fourcc that is already registered. Please ensure it is unique.`);o.sampleEntry[r]=n;continue}if(isBox(n)){const r="fourcc"in n?n.fourcc:void 0,t="uuid"in n?n.uuid:void 0;if(r==="uuid"){if(!t)throw new Error(`Box class ${l} has a fourcc of 'uuid' but does not have a valid uuid. Please ensure it is defined correctly.`);if(t in o.uuid)throw new Error(`Box class ${l} has a uuid that is already registered. Please ensure it is unique.`);o.uuid[t]=n;continue}o.box[r]=n;continue}throw new Error(`Box class ${l} does not have a valid static fourcc, uuid, or grouping_type. Please ensure it is defined correctly.`)}return BoxRegistry.uuid={...o.uuid},BoxRegistry.sampleEntry={...o.sampleEntry},BoxRegistry.sampleGroupEntry={...o.sampleGroupEntry},BoxRegistry.box={...o.box},BoxRegistry}var DescriptorRegistry={};function registerDescriptors(u){return Object.entries(u).forEach(([o,l])=>DescriptorRegistry[o]=l),DescriptorRegistry}function parseUUID(u){return parseHex16(u)}function parseHex16(u){let o="";for(let l=0;l<16;l++){const n=u.readUint8().toString(16);o+=n.length===1?"0"+n:n}return o}function parseOneBox(u,o,l){let n,r;const t=u.getPosition();let e=0,i;if(u.getEndPosition()-t<8)return Log.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:ERR_NOT_ENOUGH_DATA};if(l&&l<8)return Log.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:ERR_NOT_ENOUGH_DATA};let a=u.readUint32();const s=u.readString(4);if(s.length!==4||!/^[\x20-\x7E]{4}$/.test(s))return Log.error("BoxParser",`Invalid box type: '${s}'`),{code:ERR_INVALID_DATA,start:t,type:s};let d=s;if(Log.debug("BoxParser","Found box of type '"+s+"' and size "+a+" at position "+t),e=8,s==="uuid"){if(u.getEndPosition()-u.getPosition()<16||l-e<16)return u.seek(t),Log.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:ERR_NOT_ENOUGH_DATA};i=parseUUID(u),e+=16,d=i}if(a===1){if(u.getEndPosition()-u.getPosition()<8||l&&l-e<8)return u.seek(t),Log.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+s+'" box'),{code:ERR_NOT_ENOUGH_DATA};r=a,a=u.readUint64(),e+=8}else if(a===0){if(l)a=l;else if(s!=="mdat")return Log.error("BoxParser","Unlimited box size not supported for type: '"+s+"'"),n=new Box(a),n.type=s,{code:OK,box:n,size:n.size}}if(a!==0&&a<e)return Log.error("BoxParser","Box of type "+s+" has an invalid size "+a+" (too small to be a box)"),{code:ERR_NOT_ENOUGH_DATA,type:s,size:a,hdr_size:e,start:t};if(a!==0&&l&&a>l)return Log.error("BoxParser","Box of type '"+s+"' has a size "+a+" greater than its container size "+l),{code:ERR_NOT_ENOUGH_DATA,type:s,size:a,hdr_size:e,start:t};if(a!==0&&t+a>u.getEndPosition())return u.seek(t),Log.info("BoxParser","Not enough data in stream to parse the entire '"+s+"' box"),{code:ERR_NOT_ENOUGH_DATA,type:s,size:a,hdr_size:e,start:t,original_size:r};if(o)return{code:OK,type:s,size:a,hdr_size:e,start:t};s in BoxRegistry.box?n=new BoxRegistry.box[s](a):s!=="uuid"?(Log.warn("BoxParser",`Unknown box type: '${s}'`),n=new Box(a),n.type=s,n.has_unparsed_data=!0):i in BoxRegistry.uuid?n=new BoxRegistry.uuid[i](a):(Log.warn("BoxParser",`Unknown UUID box type: '${i}'`),n=new Box(a),n.type=s,n.uuid=i,n.has_unparsed_data=!0),n.original_size=r,n.hdr_size=e,n.start=t,n.write===Box.prototype.write&&n.type!=="mdat"&&(Log.info("BoxParser","'"+d+"' box writing not yet implemented, keeping unparsed data in memory for later write"),n.parseDataAndRewind(u)),n.parse(u);const c=u.getPosition()-(n.start+n.size);return c<0?(Log.warn("BoxParser","Parsing of box '"+d+"' did not read the entire indicated box data size (missing "+-c+" bytes), seeking forward"),u.seek(n.start+n.size)):c>0&&n.size!==0&&(Log.error("BoxParser","Parsing of box '"+d+"' read "+c+" more bytes than the indicated box data size, seeking backwards"),u.seek(n.start+n.size)),{code:OK,box:n,size:n.size}}var ContainerBox=class extends Box{write(u){if(this.size=0,this.writeHeader(u),this.boxes)for(let o=0;o<this.boxes.length;o++)this.boxes[o]&&(this.boxes[o].write(u),this.size+=this.boxes[o].size);Log.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),u.adjustUint32(this.sizePosition,this.size)}print(u){this.printHeader(u);for(let o=0;o<this.boxes.length;o++)if(this.boxes[o]){const l=u.indent;u.indent+=" ",this.boxes[o].print(u),u.indent=l}}parse(u){let o;for(;u.getPosition()<this.start+this.size;)if(o=parseOneBox(u,!1,this.size-(u.getPosition()-this.start)),o.code===OK){const l=o.box;if(this.boxes||(this.boxes=[]),this.boxes.push(l),this.subBoxNames&&this.subBoxNames.indexOf(l.type)!==-1){const n=this.subBoxNames[this.subBoxNames.indexOf(l.type)]+"s";this[n]||(this[n]=[]),this[n].push(l)}else{const n=l.type!=="uuid"?l.type:l.uuid;this[n]?Log.warn("ContainerBox",`Box of type ${n} already exists in container box ${this.type}.`):this[n]=l}}else return}},G,SampleEntry=(G=class extends ContainerBox{constructor(o,l,n){super(o),this.hdr_size=l,this.start=n}isVideo(){return!1}isAudio(){return!1}isSubtitle(){return!1}isMetadata(){return!1}isHint(){return!1}getCodec(){return this.type.replace(".","")}getWidth(){return""}getHeight(){return""}getChannelCount(){return""}getSampleRate(){return""}getSampleSize(){return""}parseHeader(o){o.readUint8Array(6),this.data_reference_index=o.readUint16(),this.hdr_size+=8}parse(o){this.parseHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size)}parseDataAndRewind(o){this.parseHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,o.seek(this.start+this.hdr_size)}parseFooter(o){super.parse(o)}writeHeader(o){this.size=8,super.writeHeader(o),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint16(this.data_reference_index)}writeFooter(o){if(this.boxes)for(let l=0;l<this.boxes.length;l++)this.boxes[l].write(o),this.size+=this.boxes[l].size;Log.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)}write(o){this.writeHeader(o),o.writeUint8Array(this.data),this.size+=this.data.length,Log.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)}},G.registryId=Symbol.for("SampleEntryIdentifier"),G),HintSampleEntry=class extends SampleEntry{},MetadataSampleEntry=class extends SampleEntry{isMetadata(){return!0}},SubtitleSampleEntry=class extends SampleEntry{isSubtitle(){return!0}},TextSampleEntry=class extends SampleEntry{},VisualSampleEntry=class extends SampleEntry{parse(u){this.parseHeader(u),u.readUint16(),u.readUint16(),u.readUint32Array(3),this.width=u.readUint16(),this.height=u.readUint16(),this.horizresolution=u.readUint32(),this.vertresolution=u.readUint32(),u.readUint32(),this.frame_count=u.readUint16();const o=Math.min(31,u.readUint8());this.compressorname=u.readString(o),o<31&&u.readString(31-o),this.depth=u.readUint16(),u.readUint16(),this.parseFooter(u)}isVideo(){return!0}getWidth(){return this.width}getHeight(){return this.height}write(u){this.writeHeader(u),this.size+=2*7+6*4+32,u.writeUint16(0),u.writeUint16(0),u.writeUint32(0),u.writeUint32(0),u.writeUint32(0),u.writeUint16(this.width),u.writeUint16(this.height),u.writeUint32(this.horizresolution),u.writeUint32(this.vertresolution),u.writeUint32(0),u.writeUint16(this.frame_count),u.writeUint8(Math.min(31,this.compressorname.length)),u.writeString(this.compressorname,void 0,31),u.writeUint16(this.depth),u.writeInt16(-1),this.writeFooter(u)}},AudioSampleEntry=class extends SampleEntry{parse(u){var l,n;this.parseHeader(u),this.version=u.readUint16(),u.readUint16(),u.readUint32(),this.channel_count=u.readUint16(),this.samplesize=u.readUint16(),u.readUint16(),u.readUint16(),this.samplerate=u.readUint32()/65536,((n=(l=u.isofile)==null?void 0:l.ftyp)==null?void 0:n.major_brand.includes("qt"))&&(this.version===1?this.extensions=u.readUint8Array(16):this.version===2&&(this.extensions=u.readUint8Array(36))),this.parseFooter(u)}isAudio(){return!0}getChannelCount(){return this.channel_count}getSampleRate(){return this.samplerate}getSampleSize(){return this.samplesize}write(u){this.writeHeader(u),this.size+=2*4+3*4,u.writeUint32(0),u.writeUint32(0),u.writeUint16(this.channel_count),u.writeUint16(this.samplesize),u.writeUint16(0),u.writeUint16(0),u.writeUint32(this.samplerate<<16),this.writeFooter(u)}},SystemSampleEntry=class extends SampleEntry{parse(u){this.parseHeader(u),this.parseFooter(u)}write(u){this.writeHeader(u),this.writeFooter(u)}},ParameterSetArray=class extends Array{toString(){let u="<table class='inner-table'>";u+="<thead><tr><th>length</th><th>nalu_data</th></tr></thead>",u+="<tbody>";for(let o=0;o<this.length;o++){const l=this[o];u+="<tr>",u+="<td>"+l.length+"</td>",u+="<td>",u+=l.data.reduce(function(n,r){return n+r.toString(16).padStart(2,"0")},"0x"),u+="</td></tr>"}return u+="</tbody></table>",u}},H,avcCBox=(H=class extends Box{constructor(){super(...arguments),this.box_name="AVCConfigurationBox"}parse(o){this.configurationVersion=o.readUint8(),this.AVCProfileIndication=o.readUint8(),this.profile_compatibility=o.readUint8(),this.AVCLevelIndication=o.readUint8(),this.lengthSizeMinusOne=o.readUint8()&3,this.nb_SPS_nalus=o.readUint8()&31;let l=this.size-this.hdr_size-6;this.SPS=new ParameterSetArray;for(let n=0;n<this.nb_SPS_nalus;n++){const r=o.readUint16();this.SPS.push({length:r,data:o.readUint8Array(r)}),l-=2+r}this.nb_PPS_nalus=o.readUint8(),l--,this.PPS=new ParameterSetArray;for(let n=0;n<this.nb_PPS_nalus;n++){const r=o.readUint16();this.PPS.push({length:r,data:o.readUint8Array(r)}),l-=2+r}l>0&&(this.ext=o.readUint8Array(l))}write(o){this.size=7;for(let l=0;l<this.SPS.length;l++)this.size+=2+this.SPS[l].length;for(let l=0;l<this.PPS.length;l++)this.size+=2+this.PPS[l].length;this.ext&&(this.size+=this.ext.length),this.writeHeader(o),o.writeUint8(this.configurationVersion),o.writeUint8(this.AVCProfileIndication),o.writeUint8(this.profile_compatibility),o.writeUint8(this.AVCLevelIndication),o.writeUint8(this.lengthSizeMinusOne+252),o.writeUint8(this.SPS.length+224);for(let l=0;l<this.SPS.length;l++)o.writeUint16(this.SPS[l].length),o.writeUint8Array(this.SPS[l].data);o.writeUint8(this.PPS.length);for(let l=0;l<this.PPS.length;l++)o.writeUint16(this.PPS[l].length),o.writeUint8Array(this.PPS[l].data);this.ext&&o.writeUint8Array(this.ext)}},H.fourcc="avcC",H),z,mdatBox=(z=class extends Box{constructor(){super(...arguments),this.box_name="MediaDataBox"}},z.fourcc="mdat",z),Y,idatBox=(Y=class extends Box{constructor(){super(...arguments),this.box_name="ItemDataBox"}},Y.fourcc="idat",Y),j,freeBox=(j=class extends Box{constructor(){super(...arguments),this.box_name="FreeSpaceBox"}},j.fourcc="free",j),X,skipBox=(X=class extends Box{constructor(){super(...arguments),this.box_name="FreeSpaceBox"}},X.fourcc="skip",X),q,hmhdBox=(q=class extends FullBox{constructor(){super(...arguments),this.box_name="HintMediaHeaderBox"}},q.fourcc="hmhd",q),K,nmhdBox=(K=class extends FullBox{constructor(){super(...arguments),this.box_name="NullMediaHeaderBox"}},K.fourcc="nmhd",K),tt,iodsBox=(tt=class extends FullBox{constructor(){super(...arguments),this.box_name="ObjectDescriptorBox"}},tt.fourcc="iods",tt),et,xmlBox=(et=class extends FullBox{constructor(){super(...arguments),this.box_name="XMLBox"}},et.fourcc="xml ",et),nt,bxmlBox=(nt=class extends FullBox{constructor(){super(...arguments),this.box_name="BinaryXMLBox"}},nt.fourcc="bxml",nt),it,iproBox=(it=class extends FullBox{constructor(){super(...arguments),this.box_name="ItemProtectionBox",this.sinfs=[]}get protections(){return this.sinfs}},it.fourcc="ipro",it),ot,moovBox=(ot=class extends ContainerBox{constructor(){super(...arguments),this.box_name="MovieBox",this.traks=[],this.psshs=[],this.subBoxNames=["trak","pssh"]}},ot.fourcc="moov",ot),rt,trakBox=(rt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="TrackBox",this.samples=[]}},rt.fourcc="trak",rt),lt,edtsBox=(lt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="EditBox"}},lt.fourcc="edts",lt),at,mdiaBox=(at=class extends ContainerBox{constructor(){super(...arguments),this.box_name="MediaBox"}},at.fourcc="mdia",at),st,minfBox=(st=class extends ContainerBox{constructor(){super(...arguments),this.box_name="MediaInformationBox"}},st.fourcc="minf",st),dt,dinfBox=(dt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="DataInformationBox"}},dt.fourcc="dinf",dt),ut,stblBox=(ut=class extends ContainerBox{constructor(){super(...arguments),this.box_name="SampleTableBox",this.sgpds=[],this.sbgps=[],this.subBoxNames=["sgpd","sbgp"]}},ut.fourcc="stbl",ut),ct,mvexBox=(ct=class extends ContainerBox{constructor(){super(...arguments),this.box_name="MovieExtendsBox",this.trexs=[],this.subBoxNames=["trex"]}},ct.fourcc="mvex",ct),Ut,moofBox=(Ut=class extends ContainerBox{constructor(){super(...arguments),this.box_name="MovieFragmentBox",this.trafs=[],this.subBoxNames=["traf"]}},Ut.fourcc="moof",Ut),Ft,trafBox=(Ft=class extends ContainerBox{constructor(){super(...arguments),this.box_name="TrackFragmentBox",this.truns=[],this.sgpds=[],this.sbgps=[],this.subBoxNames=["trun","sgpd","sbgp"]}},Ft.fourcc="traf",Ft),Qt,vttcBox=(Qt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="VTTCueBox"}},Qt.fourcc="vttc",Qt),pt,mfraBox=(pt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="MovieFragmentRandomAccessBox",this.tfras=[],this.subBoxNames=["tfra"]}},pt.fourcc="mfra",pt),ft,mecoBox=(ft=class extends ContainerBox{constructor(){super(...arguments),this.box_name="AdditionalMetadataContainerBox"}},ft.fourcc="meco",ft),ht,hntiBox=(ht=class extends ContainerBox{constructor(){super(...arguments),this.box_name="trackhintinformation",this.subBoxNames=["sdp ","rtp "]}},ht.fourcc="hnti",ht),Rt,hinfBox=(Rt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="hintstatisticsbox",this.maxrs=[],this.subBoxNames=["maxr"]}},Rt.fourcc="hinf",Rt),Bt,strkBox=(Bt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="SubTrackBox"}},Bt.fourcc="strk",Bt),St,strdBox=(St=class extends ContainerBox{constructor(){super(...arguments),this.box_name="SubTrackDefinitionBox"}},St.fourcc="strd",St),yt,sinfBox=(yt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="ProtectionSchemeInfoBox"}},yt.fourcc="sinf",yt),Vt,rinfBox=(Vt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="RestrictedSchemeInfoBox"}},Vt.fourcc="rinf",Vt),Jt,schiBox=(Jt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="SchemeInformationBox"}},Jt.fourcc="schi",Jt),Et,trgrBox=(Et=class extends ContainerBox{constructor(){super(...arguments),this.box_name="TrackGroupBox"}},Et.fourcc="trgr",Et),mt,udtaBox=(mt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="UserDataBox",this.kinds=[],this.strks=[],this.subBoxNames=["kind","strk"]}},mt.fourcc="udta",mt),kt,iprpBox=(kt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="ItemPropertiesBox",this.ipmas=[],this.subBoxNames=["ipma"]}},kt.fourcc="iprp",kt),Nt,ipcoBox=(Nt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="ItemPropertyContainerBox",this.hvcCs=[],this.ispes=[],this.claps=[],this.irots=[],this.subBoxNames=["hvcC","ispe","clap","irot"]}},Nt.fourcc="ipco",Nt),Tt,grplBox=(Tt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="GroupsListBox"}},Tt.fourcc="grpl",Tt),vt,j2kHBox=(vt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="J2KHeaderInfoBox"}},vt.fourcc="j2kH",vt),Ct,etypBox=(Ct=class extends ContainerBox{constructor(){super(...arguments),this.box_name="ExtendedTypeBox",this.tycos=[],this.subBoxNames=["tyco"]}},Ct.fourcc="etyp",Ct),Wt,povdBox=(Wt=class extends ContainerBox{constructor(){super(...arguments),this.box_name="ProjectedOmniVideoBox",this.subBoxNames=["prfr"]}},Wt.fourcc="povd",Wt),bt,drefBox=(bt=class extends FullBox{constructor(){super(...arguments),this.box_name="DataReferenceBox"}parse(o){this.parseFullHeader(o),this.entries=[];const l=o.readUint32();for(let n=0;n<l;n++){const r=parseOneBox(o,!1,this.size-(o.getPosition()-this.start));if(r.code===OK){const t=r.box;this.entries.push(t)}else return}}write(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.entries.length);for(let l=0;l<this.entries.length;l++)this.entries[l].write(o),this.size+=this.entries[l].size;Log.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)}},bt.fourcc="dref",bt),Ot,elngBox=(Ot=class extends FullBox{constructor(){super(...arguments),this.box_name="ExtendedLanguageBox"}parse(o){this.parseFullHeader(o),this.extended_language=o.readString(this.size-this.hdr_size)}write(o){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(o),o.writeString(this.extended_language)}},Ot.fourcc="elng",Ot),Zt,ftypBox=(Zt=class extends Box{constructor(){super(...arguments),this.box_name="FileTypeBox"}parse(o){let l=this.size-this.hdr_size;this.major_brand=o.readString(4),this.minor_version=o.readUint32(),l-=8,this.compatible_brands=[];let n=0;for(;l>=4;)this.compatible_brands[n]=o.readString(4),l-=4,n++}write(o){this.size=8+4*this.compatible_brands.length,this.writeHeader(o),o.writeString(this.major_brand,void 0,4),o.writeUint32(this.minor_version);for(let l=0;l<this.compatible_brands.length;l++)o.writeString(this.compatible_brands[l],void 0,4)}},Zt.fourcc="ftyp",Zt),Dt,hdlrBox=(Dt=class extends FullBox{constructor(){super(...arguments),this.box_name="HandlerBox"}parse(o){if(this.parseFullHeader(o),this.version===0&&(o.readUint32(),this.handler=o.readString(4),o.readUint32Array(3),!this.isEndOfBox(o))){const l=this.start+this.size-o.getPosition();this.name=o.readCString();const n=this.start+this.size-1;o.seek(n),o.readUint8()!==0&&l>1&&(Log.info("BoxParser","Warning: hdlr name is not null-terminated, possibly length-prefixed string. Trimming first byte."),this.name=this.name.slice(1))}}write(o){this.size=5*4+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(o),o.writeUint32(0),o.writeString(this.handler,void 0,4),o.writeUint32Array([0,0,0]),o.writeCString(this.name)}},Dt.fourcc="hdlr",Dt),wt,hvcCBox=(wt=class extends Box{constructor(){super(...arguments),this.box_name="HEVCConfigurationBox"}parse(o){this.configurationVersion=o.readUint8();let l=o.readUint8();this.general_profile_space=l>>6,this.general_tier_flag=(l&32)>>5,this.general_profile_idc=l&31,this.general_profile_compatibility=o.readUint32(),this.general_constraint_indicator=o.readUint8Array(6),this.general_level_idc=o.readUint8(),this.min_spatial_segmentation_idc=o.readUint16()&4095,this.parallelismType=o.readUint8()&3,this.chroma_format_idc=o.readUint8()&3,this.bit_depth_luma_minus8=o.readUint8()&7,this.bit_depth_chroma_minus8=o.readUint8()&7,this.avgFrameRate=o.readUint16(),l=o.readUint8(),this.constantFrameRate=l>>6,this.numTemporalLayers=(l&13)>>3,this.temporalIdNested=(l&4)>>2,this.lengthSizeMinusOne=l&3,this.nalu_arrays=[];const n=o.readUint8();for(let r=0;r<n;r++){const t=[];this.nalu_arrays.push(t),l=o.readUint8(),t.completeness=(l&128)>>7,t.nalu_type=l&63;const e=o.readUint16();for(let i=0;i<e;i++){const a=o.readUint16();t.push({data:o.readUint8Array(a)})}}}write(o){this.size=23;for(let l=0;l<this.nalu_arrays.length;l++){this.size+=3;for(let n=0;n<this.nalu_arrays[l].length;n++)this.size+=2+this.nalu_arrays[l][n].data.length}this.writeHeader(o),o.writeUint8(this.configurationVersion),o.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),o.writeUint32(this.general_profile_compatibility),o.writeUint8Array(this.general_constraint_indicator),o.writeUint8(this.general_level_idc),o.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),o.writeUint8(this.parallelismType+252),o.writeUint8(this.chroma_format_idc+252),o.writeUint8(this.bit_depth_luma_minus8+248),o.writeUint8(this.bit_depth_chroma_minus8+248),o.writeUint16(this.avgFrameRate),o.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),o.writeUint8(this.nalu_arrays.length);for(let l=0;l<this.nalu_arrays.length;l++){o.writeUint8((this.nalu_arrays[l].completeness<<7)+this.nalu_arrays[l].nalu_type),o.writeUint16(this.nalu_arrays[l].length);for(let n=0;n<this.nalu_arrays[l].length;n++)o.writeUint16(this.nalu_arrays[l][n].data.length),o.writeUint8Array(this.nalu_arrays[l][n].data)}}},wt.fourcc="hvcC",wt),gt,mdhdBox=(gt=class extends FullBox{constructor(){super(...arguments),this.box_name="MediaHeaderBox"}parse(o){this.parseFullHeader(o),this.version===1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.timescale=o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.timescale=o.readUint32(),this.duration=o.readUint32()),this.parseLanguage(o),o.readUint16()}write(o){const l=this.modification_time>MAX_UINT32||this.creation_time>MAX_UINT32||this.duration>MAX_UINT32||this.version===1;this.version=l?1:0,this.size=4*4+2*2,this.size+=l?3*4:0,this.flags=0,this.writeHeader(o),l?(o.writeUint64(this.creation_time),o.writeUint64(this.modification_time),o.writeUint32(this.timescale),o.writeUint64(this.duration)):(o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.timescale),o.writeUint32(this.duration)),o.writeUint16(this.language),o.writeUint16(0)}},gt.fourcc="mdhd",gt),xt,mehdBox=(xt=class extends FullBox{constructor(){super(...arguments),this.box_name="MovieExtendsHeaderBox"}parse(o){this.parseFullHeader(o),this.flags&1&&(Log.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version===1?this.fragment_duration=o.readUint64():this.fragment_duration=o.readUint32()}write(o){const l=this.fragment_duration>MAX_UINT32||this.version===1;this.version=l?1:0,this.size=4,this.size+=l?4:0,this.flags=0,this.writeHeader(o),l?o.writeUint64(this.fragment_duration):o.writeUint32(this.fragment_duration)}},xt.fourcc="mehd",xt),It,infeBox=(It=class extends FullBox{constructor(){super(...arguments),this.box_name="ItemInfoEntry"}parse(o){if(this.parseFullHeader(o),(this.version===0||this.version===1)&&(this.item_ID=o.readUint16(),this.item_protection_index=o.readUint16(),this.item_name=o.readCString(),this.content_type=o.readCString(),this.isEndOfBox(o)||(this.content_encoding=o.readCString())),this.version===1){this.extension_type=o.readString(4),Log.warn("BoxParser","Cannot parse extension type"),o.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=o.readUint16():this.version===3&&(this.item_ID=o.readUint32()),this.item_protection_index=o.readUint16(),this.item_type=o.readString(4),this.item_name=o.readCString(),this.item_type==="mime"?(this.content_type=o.readCString(),this.content_encoding=o.readCString()):this.item_type==="uri "&&(this.item_uri_type=o.readCString()))}},It.fourcc="infe",It),Mt,iinfBox=(Mt=class extends FullBox{constructor(){super(...arguments),this.box_name="ItemInfoBox"}parse(o){this.parseFullHeader(o),this.version===0?this.entry_count=o.readUint16():this.entry_count=o.readUint32(),this.item_infos=[];for(let l=0;l<this.entry_count;l++){const n=parseOneBox(o,!1,this.size-(o.getPosition()-this.start));if(n.code===OK){const r=n.box;r.type==="infe"?this.item_infos[l]=r:Log.error("BoxParser","Expected 'infe' box, got "+n.box.type,o.isofile)}else return}}},Mt.fourcc="iinf",Mt),_t,ilocBox=(_t=class extends FullBox{constructor(){super(...arguments),this.box_name="ItemLocationBox"}parse(o){this.parseFullHeader(o);let l;l=o.readUint8(),this.offset_size=l>>4&15,this.length_size=l&15,l=o.readUint8(),this.base_offset_size=l>>4&15,this.version===1||this.version===2?this.index_size=l&15:this.index_size=0,this.items=[];let n=0;if(this.version<2)n=o.readUint16();else if(this.version===2)n=o.readUint32();else throw new Error("version of iloc box not supported");for(let r=0;r<n;r++){let t=0,e=0,i=0;if(this.version<2)t=o.readUint16();else if(this.version===2)t=o.readUint32();else throw new Error("version of iloc box not supported");this.version===1||this.version===2?e=o.readUint16()&15:e=0;const a=o.readUint16();switch(this.base_offset_size){case 0:i=0;break;case 4:i=o.readUint32();break;case 8:i=o.readUint64();break;default:throw new Error("Error reading base offset size")}const s=[],d=o.readUint16();for(let c=0;c<d;c++){let F=0,B=0,S=0;if(this.version===1||this.version===2)switch(this.index_size){case 0:F=0;break;case 4:F=o.readUint32();break;case 8:F=o.readUint64();break;default:throw new Error("Error reading extent index")}switch(this.offset_size){case 0:B=0;break;case 4:B=o.readUint32();break;case 8:B=o.readUint64();break;default:throw new Error("Error reading extent index")}switch(this.length_size){case 0:S=0;break;case 4:S=o.readUint32();break;case 8:S=o.readUint64();break;default:throw new Error("Error reading extent index")}s.push({extent_index:F,extent_length:S,extent_offset:B})}this.items.push({base_offset:i,construction_method:e,item_ID:t,data_reference_index:a,extents:s})}}},_t.fourcc="iloc",_t),REFERENCE_TYPE_NAMES={auxl:"Auxiliary image item",base:"Pre-derived image item base",cdsc:"Item describes referenced item",dimg:"Derived image item",dpnd:"Item coding dependency",eroi:"Region",evir:"EVC slice",exbl:"Scalable image item","fdl ":"File delivery",font:"Font item",iloc:"Item data location",mask:"Region mask",mint:"Data integrity",pred:"Predictively coded item",prem:"Pre-multiplied item",tbas:"HEVC tile track base item",text:"Text item",thmb:"Thumbnail image item"},x,irefBox=(x=class extends FullBox{constructor(){super(...arguments),this.box_name="ItemReferenceBox",this.references=[]}parse(o){for(this.parseFullHeader(o),this.references=[];o.getPosition()<this.start+this.size;){const l=parseOneBox(o,!0,this.size-(o.getPosition()-this.start));if(l.code===OK){let n="Unknown item reference";x.allowed_types.includes(l.type)?n=REFERENCE_TYPE_NAMES[l.type]:Log.warn("BoxParser",`Unknown item reference type: '${l.type}'`);const r=this.version===0?new SingleItemTypeReferenceBox(l.type,l.size,n,l.hdr_size,l.start):new SingleItemTypeReferenceBoxLarge(l.type,l.size,n,l.hdr_size,l.start);r.write===Box.prototype.write&&r.type!=="mdat"&&(Log.warn("BoxParser",r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(o)),r.parse(o),this.references.push(r)}else return}}},x.fourcc="iref",x.allowed_types=["auxl","base","cdsc","dimg","dpnd","eroi","evir","exbl","fdl ","font","iloc","mask","mint","pred","prem","tbas","text","thmb"],x),Pt,pitmBox=(Pt=class extends FullBox{constructor(){super(...arguments),this.box_name="PrimaryItemBox"}parse(o){this.parseFullHeader(o),this.version===0?this.item_id=o.readUint16():this.item_id=o.readUint32()}},Pt.fourcc="pitm",Pt),$t,metaBox=($t=class extends FullBox{constructor(){super(...arguments),this.box_name="MetaBox",this.isQT=!1}parse(o){const l=o.getPosition();if(this.size>8){switch(o.readUint32(),o.readString(4)){case"hdlr":case"mhdr":case"keys":case"ilst":case"ctry":case"lang":this.isQT=!0;break}o.seek(l)}this.isQT||this.parseFullHeader(o),ContainerBox.prototype.parse.call(this,o)}},$t.fourcc="meta",$t),Lt,mfhdBox=(Lt=class extends FullBox{constructor(){super(...arguments),this.box_name="MovieFragmentHeaderBox"}parse(o){this.parseFullHeader(o),this.sequence_number=o.readUint32()}write(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.sequence_number)}},Lt.fourcc="mfhd",Lt),At,mvhdBox=(At=class extends FullBox{constructor(){super(...arguments),this.box_name="MovieHeaderBox"}parse(o){this.parseFullHeader(o),this.version===1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.timescale=o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.timescale=o.readUint32(),this.duration=o.readUint32()),this.rate=o.readUint32(),this.volume=o.readUint16()>>8,o.readUint16(),o.readUint32Array(2),this.matrix=o.readInt32Array(9),o.readUint32Array(6),this.next_track_id=o.readUint32()}write(o){const l=this.modification_time>MAX_UINT32||this.creation_time>MAX_UINT32||this.duration>MAX_UINT32||this.version===1;this.version=l?1:0,this.size=4*4+20*4,this.size+=l?3*4:0,this.flags=0,this.writeHeader(o),l?(o.writeUint64(this.creation_time),o.writeUint64(this.modification_time),o.writeUint32(this.timescale),o.writeUint64(this.duration)):(o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.timescale),o.writeUint32(this.duration)),o.writeUint32(this.rate),o.writeUint16(this.volume<<8),o.writeUint16(0),o.writeUint32(0),o.writeUint32(0),o.writeInt32Array(this.matrix),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(this.next_track_id)}print(o){super.printHeader(o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"timescale: "+this.timescale),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"rate: "+this.rate),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"next_track_id: "+this.next_track_id)}},At.fourcc="mvhd",At),Gt,mettSampleEntry=(Gt=class extends MetadataSampleEntry{parse(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}},Gt.fourcc="mett",Gt),Ht,metxSampleEntry=(Ht=class extends MetadataSampleEntry{parse(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.namespace=o.readCString(),this.schema_location=o.readCString(),this.parseFooter(o)}},Ht.fourcc="metx",Ht),zt,av1CBox=(zt=class extends Box{constructor(){super(...arguments),this.box_name="AV1CodecConfigurationBox"}parse(o){let l=o.readUint8();if((l>>7&1)!==1){Log.error("BoxParser","av1C marker problem",o.isofile);return}if(this.version=l&127,this.version!==1){Log.error("BoxParser","av1C version "+this.version+" not supported",o.isofile);return}if(l=o.readUint8(),this.seq_profile=l>>5&7,this.seq_level_idx_0=l&31,l=o.readUint8(),this.seq_tier_0=l>>7&1,this.high_bitdepth=l>>6&1,this.twelve_bit=l>>5&1,this.monochrome=l>>4&1,this.chroma_subsampling_x=l>>3&1,this.chroma_subsampling_y=l>>2&1,this.chroma_sample_position=l&3,l=o.readUint8(),this.reserved_1=l>>5&7,this.reserved_1!==0){Log.error("BoxParser","av1C reserved_1 parsing problem",o.isofile);return}if(this.initial_presentation_delay_present=l>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=l&15;else if(this.reserved_2=l&15,this.reserved_2!==0){Log.error("BoxParser","av1C reserved_2 parsing problem",o.isofile);return}const n=this.size-this.hdr_size-4;this.configOBUs=o.readUint8Array(n)}},zt.fourcc="av1C",zt),Yt,esdsBox=(Yt=class extends FullBox{constructor(){super(...arguments),this.box_name="ElementaryStreamDescriptorBox"}parse(o){this.parseFullHeader(o);const l=o.readUint8Array(this.size-this.hdr_size);if("MPEG4DescriptorParser"in DescriptorRegistry){const n=new DescriptorRegistry.MPEG4DescriptorParser;this.esd=n.parseOneDescriptor(new DataStream(l.buffer,0))}}},Yt.fourcc="esds",Yt),jt,vpcCBox=(jt=class extends FullBox{constructor(){super(...arguments),this.box_name="VPCodecConfigurationRecord"}parse(o){if(this.parseFullHeader(o),this.version===1){this.profile=o.readUint8(),this.level=o.readUint8();const l=o.readUint8();this.bitDepth=l>>4,this.chromaSubsampling=l>>1&7,this.videoFullRangeFlag=l&1,this.colourPrimaries=o.readUint8(),this.transferCharacteristics=o.readUint8(),this.matrixCoefficients=o.readUint8(),this.codecIntializationDataSize=o.readUint16(),this.codecIntializationData=o.readUint8Array(this.codecIntializationDataSize)}else{this.profile=o.readUint8(),this.level=o.readUint8();let l=o.readUint8();this.bitDepth=l>>4&15,this.colorSpace=l&15,l=o.readUint8(),this.chromaSubsampling=l>>4&15,this.transferFunction=l>>1&7,this.videoFullRangeFlag=l&1,this.codecIntializationDataSize=o.readUint16(),this.codecIntializationData=o.readUint8Array(this.codecIntializationDataSize)}}},jt.fourcc="vpcC",jt),Xt,vvcCBox=(Xt=class extends FullBox{constructor(){super(...arguments),this.box_name="VvcConfigurationBox"}parse(o){this.parseFullHeader(o);const l={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(e){this.held_bits=e.readUint8(),this.num_held_bits=1*8},stream_read_2_bytes:function(e){this.held_bits=e.readUint16(),this.num_held_bits=2*8},extract_bits:function(e){const i=this.held_bits>>this.num_held_bits-e&(1<<e)-1;return this.num_held_bits-=e,i}};if(l.stream_read_1_bytes(o),l.extract_bits(5),this.lengthSizeMinusOne=l.extract_bits(2),this.ptl_present_flag=l.extract_bits(1),this.ptl_present_flag){l.stream_read_2_bytes(o),this.ols_idx=l.extract_bits(9),this.num_sublayers=l.extract_bits(3),this.constant_frame_rate=l.extract_bits(2),this.chroma_format_idc=l.extract_bits(2),l.stream_read_1_bytes(o),this.bit_depth_minus8=l.extract_bits(3),l.extract_bits(5);{if(l.stream_read_2_bytes(o),l.extract_bits(2),this.num_bytes_constraint_info=l.extract_bits(6),this.general_profile_idc=l.extract_bits(7),this.general_tier_flag=l.extract_bits(1),this.general_level_idc=o.readUint8(),l.stream_read_1_bytes(o),this.ptl_frame_only_constraint_flag=l.extract_bits(1),this.ptl_multilayer_enabled_flag=l.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(let e=0;e<this.num_bytes_constraint_info-1;e++){const i=l.extract_bits(6);l.stream_read_1_bytes(o);const a=l.extract_bits(2);this.general_constraint_info[e]=i<<2|a}this.general_constraint_info[this.num_bytes_constraint_info-1]=l.extract_bits(6)}else l.extract_bits(6);if(this.num_sublayers>1){l.stream_read_1_bytes(o),this.ptl_sublayer_present_mask=0;for(let e=this.num_sublayers-2;e>=0;--e){const i=l.extract_bits(1);this.ptl_sublayer_present_mask|=i<<e}for(let e=this.num_sublayers;e<=8&&this.num_sublayers>1;++e)l.extract_bits(1);this.sublayer_level_idc=[];for(let e=this.num_sublayers-2;e>=0;--e)this.ptl_sublayer_present_mask&1<<e&&(this.sublayer_level_idc[e]=o.readUint8())}if(this.ptl_num_sub_profiles=o.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(let e=0;e<this.ptl_num_sub_profiles;e++)this.general_sub_profile_idc.push(o.readUint32())}this.max_picture_width=o.readUint16(),this.max_picture_height=o.readUint16(),this.avg_frame_rate=o.readUint16()}const n=12,r=13;this.nalu_arrays=[];const t=o.readUint8();for(let e=0;e<t;e++){const i=[];this.nalu_arrays.push(i),l.stream_read_1_bytes(o),i.completeness=l.extract_bits(1),l.extract_bits(2),i.nalu_type=l.extract_bits(5);let a=1;i.nalu_type!==r&&i.nalu_type!==n&&(a=o.readUint16());for(let s=0;s<a;s++){const d=o.readUint16();i.push({data:o.readUint8Array(d),length:d})}}}},Xt.fourcc="vvcC",Xt),qt,colrBox=(qt=class extends Box{constructor(){super(...arguments),this.box_name="ColourInformationBox"}parse(o){if(this.colour_type=o.readString(4),this.colour_type==="nclx"){this.colour_primaries=o.readUint16(),this.transfer_characteristics=o.readUint16(),this.matrix_coefficients=o.readUint16();const l=o.readUint8();this.full_range_flag=l>>7}else this.colour_type==="rICC"?this.ICC_profile=o.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=o.readUint8Array(this.size-4))}},qt.fourcc="colr",qt);function decimalToHex(u,o){let l=Number(u).toString(16);for(o=typeof o>"u"?2:o;l.length<o;)l="0"+l;return l}var avcCSampleEntryBase=class extends VisualSampleEntry{getCodec(){const u=super.getCodec();return this.avcC?`${u}.${decimalToHex(this.avcC.AVCProfileIndication)}${decimalToHex(this.avcC.profile_compatibility)}${decimalToHex(this.avcC.AVCLevelIndication)}`:u}},Kt,avc1SampleEntry=(Kt=class extends avcCSampleEntryBase{constructor(){super(...arguments),this.box_name="AVCSampleEntry"}},Kt.fourcc="avc1",Kt),te,avc2SampleEntry=(te=class extends avcCSampleEntryBase{constructor(){super(...arguments),this.box_name="AVC2SampleEntry"}},te.fourcc="avc2",te),ee,avc3SampleEntry=(ee=class extends avcCSampleEntryBase{constructor(){super(...arguments),this.box_name="AVCSampleEntry"}},ee.fourcc="avc3",ee),ne,avc4SampleEntry=(ne=class extends avcCSampleEntryBase{constructor(){super(...arguments),this.box_name="AVC2SampleEntry"}},ne.fourcc="avc4",ne),ie,av01SampleEntry=(ie=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="AV1SampleEntry"}getCodec(){const o=super.getCodec(),l=this.av1C.seq_level_idx_0,n=l<10?"0"+l:l;let r;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?r=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(r=this.av1C.high_bitdepth===1?"10":"08"),o+"."+this.av1C.seq_profile+"."+n+(this.av1C.seq_tier_0?"H":"M")+"."+r}},ie.fourcc="av01",ie),oe,dav1SampleEntry=(oe=class extends VisualSampleEntry{},oe.fourcc="dav1",oe),hvcCSampleEntryBase=class extends VisualSampleEntry{getCodec(){let u=super.getCodec();if(this.hvcC){switch(u+=".",this.hvcC.general_profile_space){case 0:u+="";break;case 1:u+="A";break;case 2:u+="B";break;case 3:u+="C";break}u+=this.hvcC.general_profile_idc,u+=".";let o=this.hvcC.general_profile_compatibility,l=0;for(let t=0;t<32&&(l|=o&1,t!==31);t++)l<<=1,o>>=1;u+=decimalToHex(l,0),u+=".",this.hvcC.general_tier_flag===0?u+="L":u+="H",u+=this.hvcC.general_level_idc;let n=!1,r="";for(let t=5;t>=0;t--)(this.hvcC.general_constraint_indicator[t]||n)&&(r="."+decimalToHex(this.hvcC.general_constraint_indicator[t],0)+r,n=!0);u+=r}return u}},re,hvc1SampleEntry=(re=class extends hvcCSampleEntryBase{constructor(){super(...arguments),this.box_name="HEVCSampleEntry"}},re.fourcc="hvc1",re),le,hvc2SampleEntry=(le=class extends hvcCSampleEntryBase{},le.fourcc="hvc2",le),ae,hev1SampleEntry=(ae=class extends hvcCSampleEntryBase{constructor(){super(...arguments),this.box_name="HEVCSampleEntry",this.colrs=[],this.subBoxNames=["colr"]}},ae.fourcc="hev1",ae),se,hev2SampleEntry=(se=class extends hvcCSampleEntryBase{},se.fourcc="hev2",se),de,hvt1SampleEntry=(de=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="HEVCTileSampleSampleEntry"}},de.fourcc="hvt1",de),ue,lhe1SampleEntry=(ue=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="LHEVCSampleEntry"}},ue.fourcc="lhe1",ue),ce,lhv1SampleEntry=(ce=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="LHEVCSampleEntry"}},ce.fourcc="lhv1",ce),Ue,dvh1SampleEntry=(Ue=class extends VisualSampleEntry{},Ue.fourcc="dvh1",Ue),Fe,dvheSampleEntry=(Fe=class extends VisualSampleEntry{},Fe.fourcc="dvhe",Fe),vvcCSampleEntryBase=class extends VisualSampleEntry{getCodec(){let u=super.getCodec();if(this.vvcC){u+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?u+=".H":u+=".L",u+=this.vvcC.general_level_idc;let o="";if(this.vvcC.general_constraint_info){const l=[];let n=0;n|=this.vvcC.ptl_frame_only_constraint_flag<<7,n|=this.vvcC.ptl_multilayer_enabled_flag<<6;let r;for(let t=0;t<this.vvcC.general_constraint_info.length;++t)n|=this.vvcC.general_constraint_info[t]>>2&63,l.push(n),n&&(r=t),n=this.vvcC.general_constraint_info[t]>>2&3;if(r===void 0)o=".CA";else{o=".C";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";let e=0,i=0;for(let a=0;a<=r;++a)for(e=e<<8|l[a],i+=8;i>=5;){const s=e>>i-5&31;o+=t[s],i-=5,e&=(1<<i)-1}i&&(e<<=5-i,o+=t[e&31])}}u+=o}return u}},Qe,vvc1SampleEntry=(Qe=class extends vvcCSampleEntryBase{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}},Qe.fourcc="vvc1",Qe),pe,vvi1SampleEntry=(pe=class extends vvcCSampleEntryBase{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}},pe.fourcc="vvi1",pe),fe,vvs1SampleEntry=(fe=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}},fe.fourcc="vvs1",fe),he,vvcNSampleEntry=(he=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="VvcNonVCLSampleEntry"}},he.fourcc="vvcN",he),vpcCSampleEntryBase=class extends VisualSampleEntry{getCodec(){const u=super.getCodec();let o=this.vpcC.level;o===0&&(o="00");let l=this.vpcC.bitDepth;return l===8&&(l="08"),`${u}.0${this.vpcC.profile}.${o}.${l}`}},Re,vp08SampleEntry=(Re=class extends vpcCSampleEntryBase{},Re.fourcc="vp08",Re),Be,vp09SampleEntry=(Be=class extends vpcCSampleEntryBase{},Be.fourcc="vp09",Be),Se,avs3SampleEntry=(Se=class extends VisualSampleEntry{},Se.fourcc="avs3",Se),ye,j2kiSampleEntry=(ye=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="J2KSampleEntry"}},ye.fourcc="j2ki",ye),Ve,mjp2SampleEntry=(Ve=class extends VisualSampleEntry{},Ve.fourcc="mjp2",Ve),Je,mjpgSampleEntry=(Je=class extends VisualSampleEntry{},Je.fourcc="mjpg",Je),Ee,uncvSampleEntry=(Ee=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="UncompressedVideoSampleEntry"}},Ee.fourcc="uncv",Ee),me,mp4vSampleEntry=(me=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="MP4VisualSampleEntry"}},me.fourcc="mp4v",me),ke,mp4aSampleEntry=(ke=class extends AudioSampleEntry{constructor(){super(...arguments),this.box_name="MP4AudioSampleEntry"}getCodec(){const o=super.getCodec();if(this.esds&&this.esds.esd){const l=this.esds.esd.getOTI(),n=this.esds.esd.getAudioConfig();return o+"."+decimalToHex(l)+(n?"."+n:"")}else return o}},ke.fourcc="mp4a",ke),Ne,m4aeSampleEntry=(Ne=class extends AudioSampleEntry{},Ne.fourcc="m4ae",Ne),Te,ac_3SampleEntry=(Te=class extends AudioSampleEntry{},Te.fourcc="ac-3",Te),ve,ac_4SampleEntry=(ve=class extends AudioSampleEntry{},ve.fourcc="ac-4",ve),Ce,ec_3SampleEntry=(Ce=class extends AudioSampleEntry{},Ce.fourcc="ec-3",Ce),We,OpusSampleEntry=(We=class extends AudioSampleEntry{},We.fourcc="Opus",We),be,mha1SampleEntry=(be=class extends AudioSampleEntry{},be.fourcc="mha1",be),Oe,mha2SampleEntry=(Oe=class extends AudioSampleEntry{},Oe.fourcc="mha2",Oe),Ze,mhm1SampleEntry=(Ze=class extends AudioSampleEntry{},Ze.fourcc="mhm1",Ze),De,mhm2SampleEntry=(De=class extends AudioSampleEntry{},De.fourcc="mhm2",De),we,fLaCSampleEntry=(we=class extends AudioSampleEntry{},we.fourcc="fLaC",we),ge,encvSampleEntry=(ge=class extends VisualSampleEntry{},ge.fourcc="encv",ge),xe,encaSampleEntry=(xe=class extends AudioSampleEntry{},xe.fourcc="enca",xe),Ie,encuSampleEntry=(Ie=class extends SubtitleSampleEntry{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Ie.fourcc="encu",Ie),Me,encsSampleEntry=(Me=class extends SystemSampleEntry{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Me.fourcc="encs",Me),_e,mp4sSampleEntry=(_e=class extends SystemSampleEntry{},_e.fourcc="mp4s",_e),Pe,enctSampleEntry=(Pe=class extends TextSampleEntry{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Pe.fourcc="enct",Pe),$e,encmSampleEntry=($e=class extends MetadataSampleEntry{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},$e.fourcc="encm",$e),Le,resvSampleEntry=(Le=class extends VisualSampleEntry{constructor(){super(...arguments),this.box_name="RestrictedVideoSampleEntry"}},Le.fourcc="resv",Le),Ae,sbttSampleEntry=(Ae=class extends SubtitleSampleEntry{parse(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}},Ae.fourcc="sbtt",Ae),Ge,stppSampleEntry=(Ge=class extends SubtitleSampleEntry{parse(o){this.parseHeader(o),this.namespace=o.readCString(),this.schema_location=o.readCString(),this.auxiliary_mime_types=o.readCString(),this.parseFooter(o)}write(o){this.writeHeader(o),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,o.writeCString(this.namespace),o.writeCString(this.schema_location),o.writeCString(this.auxiliary_mime_types),this.writeFooter(o)}},Ge.fourcc="stpp",Ge),He,stxtSampleEntry=(He=class extends SubtitleSampleEntry{parse(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}getCodec(){const o=super.getCodec();return this.mime_format?o+"."+this.mime_format:o}},He.fourcc="stxt",He),ze,tx3gSampleEntry=(ze=class extends SubtitleSampleEntry{parse(o){this.parseHeader(o),this.displayFlags=o.readUint32(),this.horizontal_justification=o.readInt8(),this.vertical_justification=o.readInt8(),this.bg_color_rgba=o.readUint8Array(4),this.box_record=o.readInt16Array(4),this.style_record=o.readUint8Array(12),this.parseFooter(o)}},ze.fourcc="tx3g",ze),Ye,wvttSampleEntry=(Ye=class extends MetadataSampleEntry{parse(o){this.parseHeader(o),this.parseFooter(o)}},Ye.fourcc="wvtt",Ye),je,sbgpBox=(je=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleToGroupBox"}parse(o){this.parseFullHeader(o),this.grouping_type=o.readString(4),this.version===1?this.grouping_type_parameter=o.readUint32():this.grouping_type_parameter=0,this.entries=[];const l=o.readUint32();for(let n=0;n<l;n++)this.entries.push({sample_count:o.readInt32(),group_description_index:o.readInt32()})}write(o){this.grouping_type_parameter?this.version=1:this.version=0,this.flags=0,this.size=8+8*this.entries.length+(this.version===1?4:0),this.writeHeader(o),o.writeString(this.grouping_type,void 0,4),this.version===1&&o.writeUint32(this.grouping_type_parameter),o.writeUint32(this.entries.length);for(let l=0;l<this.entries.length;l++){const n=this.entries[l];o.writeInt32(n.sample_count),o.writeInt32(n.group_description_index)}}},je.fourcc="sbgp",je),Xe,sdtpBox=(Xe=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleDependencyTypeBox"}parse(o){this.parseFullHeader(o);const l=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(let n=0;n<l;n++){const r=o.readUint8();this.is_leading[n]=r>>6,this.sample_depends_on[n]=r>>4&3,this.sample_is_depended_on[n]=r>>2&3,this.sample_has_redundancy[n]=r&3}}},Xe.fourcc="sdtp",Xe),qe,sgpdBox=(qe=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleGroupDescriptionBox"}parse(o){this.parseFullHeader(o),this.grouping_type=o.readString(4),Log.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=o.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=o.readUint32()),this.entries=[];const l=o.readUint32();for(let n=0;n<l;n++){let r;this.grouping_type in BoxRegistry.sampleGroupEntry?r=new BoxRegistry.sampleGroupEntry[this.grouping_type](this.grouping_type):r=new SampleGroupEntry(this.grouping_type),this.entries.push(r),this.version===1?this.default_length===0?r.description_length=o.readUint32():r.description_length=this.default_length:r.description_length=this.default_length,r.write===SampleGroupEntry.prototype.write&&(Log.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),r.data=o.readUint8Array(r.description_length),o.seek(o.getPosition()-r.description_length)),r.parse(o)}}write(o){this.flags=0,this.size=12;for(let l=0;l<this.entries.length;l++){const n=this.entries[l];this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=n.data.length)}this.writeHeader(o),o.writeString(this.grouping_type,void 0,4),this.version===1&&o.writeUint32(this.default_length),this.version>=2&&o.writeUint32(this.default_sample_description_index),o.writeUint32(this.entries.length);for(let l=0;l<this.entries.length;l++){const n=this.entries[l];this.version===1&&this.default_length===0&&o.writeUint32(n.description_length),n.write(o)}}},qe.fourcc="sgpd",qe),Ke,sidxBox=(Ke=class extends FullBox{constructor(){super(...arguments),this.box_name="CompressedSegmentIndexBox"}parse(o){this.parseFullHeader(o),this.reference_ID=o.readUint32(),this.timescale=o.readUint32(),this.version===0?(this.earliest_presentation_time=o.readUint32(),this.first_offset=o.readUint32()):(this.earliest_presentation_time=o.readUint64(),this.first_offset=o.readUint64()),o.readUint16(),this.references=[];const l=o.readUint16();for(let n=0;n<l;n++){const r=o.readUint32(),t=o.readUint32(),e=o.readUint32();this.references.push({reference_type:r>>31&1,referenced_size:r&2147483647,subsegment_duration:t,starts_with_SAP:e>>31&1,SAP_type:e>>28&7,SAP_delta_time:e&268435455})}}write(o){const l=this.earliest_presentation_time>MAX_UINT32||this.first_offset>MAX_UINT32||this.version===1;this.version=l?1:0,this.size=4*2+2+2+12*this.references.length,this.size+=l?16:8,this.flags=0,this.writeHeader(o),o.writeUint32(this.reference_ID),o.writeUint32(this.timescale),l?(o.writeUint64(this.earliest_presentation_time),o.writeUint64(this.first_offset)):(o.writeUint32(this.earliest_presentation_time),o.writeUint32(this.first_offset)),o.writeUint16(0),o.writeUint16(this.references.length);for(let n=0;n<this.references.length;n++){const r=this.references[n];o.writeUint32(r.reference_type<<31|r.referenced_size),o.writeUint32(r.subsegment_duration),o.writeUint32(r.starts_with_SAP<<31|r.SAP_type<<28|r.SAP_delta_time)}}},Ke.fourcc="sidx",Ke),tn,smhdBox=(tn=class extends FullBox{constructor(){super(...arguments),this.box_name="SoundMediaHeaderBox"}parse(o){this.parseFullHeader(o),this.balance=o.readUint16(),o.readUint16()}write(o){this.version=0,this.size=4,this.writeHeader(o),o.writeUint16(this.balance),o.writeUint16(0)}},tn.fourcc="smhd",tn),en,stcoBox=(en=class extends FullBox{constructor(){super(...arguments),this.box_name="ChunkOffsetBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.chunk_offsets=[],this.version===0)for(let n=0;n<l;n++)this.chunk_offsets.push(o.readUint32())}write(o){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(o),o.writeUint32(this.chunk_offsets.length),o.writeUint32Array(this.chunk_offsets)}unpack(o){for(let l=0;l<this.chunk_offsets.length;l++)o[l].offset=this.chunk_offsets[l]}},en.fourcc="stco",en),nn,sthdBox=(nn=class extends FullBox{constructor(){super(...arguments),this.box_name="SubtitleMediaHeaderBox"}},nn.fourcc="sthd",nn),on,stscBox=(on=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleToChunkBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(let n=0;n<l;n++)this.first_chunk.push(o.readUint32()),this.samples_per_chunk.push(o.readUint32()),this.sample_description_index.push(o.readUint32())}write(o){this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(o),o.writeUint32(this.first_chunk.length);for(let l=0;l<this.first_chunk.length;l++)o.writeUint32(this.first_chunk[l]),o.writeUint32(this.samples_per_chunk[l]),o.writeUint32(this.sample_description_index[l])}unpack(o){let l=0,n=0;for(let r=0;r<this.first_chunk.length;r++)for(let t=0;t<(r+1<this.first_chunk.length?this.first_chunk[r+1]:1/0);t++){n++;for(let e=0;e<this.samples_per_chunk[r];e++){if(o[l])o[l].description_index=this.sample_description_index[r],o[l].chunk_index=n;else return;l++}}}},on.fourcc="stsc",on),rn,stsdBox=(rn=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleDescriptionBox"}parse(o){this.parseFullHeader(o),this.entries=[];const l=o.readUint32();for(let n=1;n<=l;n++){const r=parseOneBox(o,!0,this.size-(o.getPosition()-this.start));if(r.code===OK){let t;r.type in BoxRegistry.sampleEntry?(t=new BoxRegistry.sampleEntry[r.type](r.size),t.hdr_size=r.hdr_size,t.start=r.start):(Log.warn("BoxParser",`Unknown sample entry type: '${r.type}'`),t=new SampleEntry(r.size,r.hdr_size,r.start),t.type=r.type),t.write===SampleEntry.prototype.write&&(Log.info("BoxParser","SampleEntry "+t.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),t.parseDataAndRewind(o)),t.parse(o),this.entries.push(t)}else return}}write(o){this.version=0,this.flags=0,this.size=0,this.writeHeader(o),o.writeUint32(this.entries.length),this.size+=4;for(let l=0;l<this.entries.length;l++)this.entries[l].write(o),this.size+=this.entries[l].size;Log.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)}},rn.fourcc="stsd",rn),ln,stszBox=(ln=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleSizeBox"}parse(o){if(this.parseFullHeader(o),this.sample_sizes=[],this.version===0){this.sample_size=o.readUint32(),this.sample_count=o.readUint32();for(let l=0;l<this.sample_count;l++)this.sample_size===0?this.sample_sizes.push(o.readUint32()):this.sample_sizes[l]=this.sample_size}}write(o){let l=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0){let n=0;for(;n+1<this.sample_sizes.length;)if(this.sample_sizes[n+1]!==this.sample_sizes[0]){l=!1;break}else n++}else l=!1;this.size=8,l||(this.size+=4*this.sample_sizes.length),this.writeHeader(o),l?o.writeUint32(this.sample_sizes[0]):o.writeUint32(0),o.writeUint32(this.sample_sizes.length),l||o.writeUint32Array(this.sample_sizes)}unpack(o){for(let l=0;l<this.sample_sizes.length;l++)o[l].size=this.sample_sizes[l]}},ln.fourcc="stsz",ln),an,sttsBox=(an=class extends FullBox{constructor(){super(...arguments),this.box_name="TimeToSampleBox",this.sample_counts=[],this.sample_deltas=[]}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.sample_counts.length=0,this.sample_deltas.length=0,this.version===0)for(let n=0;n<l;n++){this.sample_counts.push(o.readUint32());let r=o.readInt32();r<0&&(Log.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),r=1),this.sample_deltas.push(r)}}write(o){this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(o),o.writeUint32(this.sample_counts.length);for(let l=0;l<this.sample_counts.length;l++)o.writeUint32(this.sample_counts[l]),o.writeUint32(this.sample_deltas[l])}unpack(o){let l=0;for(let n=0;n<this.sample_counts.length;n++)for(let r=0;r<this.sample_counts[n];r++)l===0?o[l].dts=0:o[l].dts=o[l-1].dts+this.sample_deltas[n],l++}},an.fourcc="stts",an),sn,tfdtBox=(sn=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackFragmentBaseMediaDecodeTimeBox"}parse(o){this.parseFullHeader(o),this.version===1?this.baseMediaDecodeTime=o.readUint64():this.baseMediaDecodeTime=o.readUint32()}write(o){const l=this.baseMediaDecodeTime>MAX_UINT32||this.version===1;this.version=l?1:0,this.size=4,this.size+=l?4:0,this.flags=0,this.writeHeader(o),l?o.writeUint64(this.baseMediaDecodeTime):o.writeUint32(this.baseMediaDecodeTime)}},sn.fourcc="tfdt",sn),dn,tfhdBox=(dn=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackFragmentHeaderBox"}parse(o){this.parseFullHeader(o);let l=0;this.track_id=o.readUint32(),this.size-this.hdr_size>l&&this.flags&TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=o.readUint64(),l+=8):this.base_data_offset=0,this.size-this.hdr_size>l&&this.flags&TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=o.readUint32(),l+=4):this.default_sample_description_index=0,this.size-this.hdr_size>l&&this.flags&TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=o.readUint32(),l+=4):this.default_sample_duration=0,this.size-this.hdr_size>l&&this.flags&TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=o.readUint32(),l+=4):this.default_sample_size=0,this.size-this.hdr_size>l&&this.flags&TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=o.readUint32(),l+=4):this.default_sample_flags=0}write(o){this.version=0,this.size=4,this.flags&TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(o),o.writeUint32(this.track_id),this.flags&TFHD_FLAG_BASE_DATA_OFFSET&&o.writeUint64(this.base_data_offset),this.flags&TFHD_FLAG_SAMPLE_DESC&&o.writeUint32(this.default_sample_description_index),this.flags&TFHD_FLAG_SAMPLE_DUR&&o.writeUint32(this.default_sample_duration),this.flags&TFHD_FLAG_SAMPLE_SIZE&&o.writeUint32(this.default_sample_size),this.flags&TFHD_FLAG_SAMPLE_FLAGS&&o.writeUint32(this.default_sample_flags)}},dn.fourcc="tfhd",dn),un,tkhdBox=(un=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackHeaderBox",this.layer=0,this.alternate_group=0}parse(o){this.parseFullHeader(o),this.version===1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.track_id=o.readUint32(),o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.track_id=o.readUint32(),o.readUint32(),this.duration=o.readUint32()),o.readUint32Array(2),this.layer=o.readInt16(),this.alternate_group=o.readInt16(),this.volume=o.readInt16()>>8,o.readUint16(),this.matrix=o.readInt32Array(9),this.width=o.readUint32(),this.height=o.readUint32()}write(o){const l=this.modification_time>MAX_UINT32||this.creation_time>MAX_UINT32||this.duration>MAX_UINT32||this.version===1;this.version=l?1:0,this.size=5*4+15*4,this.size+=l?3*4:0,this.flags=this.flags??3,this.writeHeader(o),l?(o.writeUint64(this.creation_time),o.writeUint64(this.modification_time),o.writeUint32(this.track_id),o.writeUint32(0),o.writeUint64(this.duration)):(o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.track_id),o.writeUint32(0),o.writeUint32(this.duration)),o.writeUint32Array([0,0]),o.writeInt16(this.layer),o.writeInt16(this.alternate_group),o.writeInt16(this.volume<<8),o.writeInt16(0),o.writeInt32Array(this.matrix),o.writeUint32(this.width),o.writeUint32(this.height)}print(o){super.printHeader(o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"track_id: "+this.track_id),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"layer: "+this.layer),o.log(o.indent+"alternate_group: "+this.alternate_group),o.log(o.indent+"width: "+this.width),o.log(o.indent+"height: "+this.height)}},un.fourcc="tkhd",un),cn,trexBox=(cn=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackExtendsBox"}parse(o){this.parseFullHeader(o),this.track_id=o.readUint32(),this.default_sample_description_index=o.readUint32(),this.default_sample_duration=o.readUint32(),this.default_sample_size=o.readUint32(),this.default_sample_flags=o.readUint32()}write(o){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(o),o.writeUint32(this.track_id),o.writeUint32(this.default_sample_description_index),o.writeUint32(this.default_sample_duration),o.writeUint32(this.default_sample_size),o.writeUint32(this.default_sample_flags)}},cn.fourcc="trex",cn),Un,trunBox=(Un=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackRunBox",this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[]}parse(o){this.parseFullHeader(o);let l=0;if(this.sample_count=o.readUint32(),l+=4,this.size-this.hdr_size>l&&this.flags&TRUN_FLAGS_DATA_OFFSET?(this.data_offset=o.readInt32(),l+=4):this.data_offset=0,this.size-this.hdr_size>l&&this.flags&TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=o.readUint32(),l+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>l)for(let n=0;n<this.sample_count;n++)this.flags&TRUN_FLAGS_DURATION&&(this.sample_duration[n]=o.readUint32()),this.flags&TRUN_FLAGS_SIZE&&(this.sample_size[n]=o.readUint32()),this.flags&TRUN_FLAGS_FLAGS&&(this.sample_flags[n]=o.readUint32()),this.flags&TRUN_FLAGS_CTS_OFFSET&&(this.version===0?this.sample_composition_time_offset[n]=o.readUint32():this.sample_composition_time_offset[n]=o.readInt32())}write(o){this.size=4,this.flags&TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(o),o.writeUint32(this.sample_count),this.flags&TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=o.getPosition(),o.writeInt32(this.data_offset)),this.flags&TRUN_FLAGS_FIRST_FLAG&&o.writeUint32(this.first_sample_flags);for(let l=0;l<this.sample_count;l++)this.flags&TRUN_FLAGS_DURATION&&o.writeUint32(this.sample_duration[l]),this.flags&TRUN_FLAGS_SIZE&&o.writeUint32(this.sample_size[l]),this.flags&TRUN_FLAGS_FLAGS&&o.writeUint32(this.sample_flags[l]),this.flags&TRUN_FLAGS_CTS_OFFSET&&(this.version===0?o.writeUint32(this.sample_composition_time_offset[l]):o.writeInt32(this.sample_composition_time_offset[l]))}},Un.fourcc="trun",Un),Fn,urlBox=(Fn=class extends FullBox{constructor(){super(...arguments),this.box_name="DataEntryUrlBox"}parse(o){this.parseFullHeader(o),this.flags!==1&&(this.location=o.readCString())}write(o){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(o),this.location&&o.writeCString(this.location)}},Fn.fourcc="url ",Fn),Qn,vmhdBox=(Qn=class extends FullBox{constructor(){super(...arguments),this.box_name="VideoMediaHeaderBox"}parse(o){this.parseFullHeader(o),this.graphicsmode=o.readUint16(),this.opcolor=o.readUint16Array(3)}write(o){this.version=0,this.size=8,this.writeHeader(o),o.writeUint16(this.graphicsmode),o.writeUint16Array(this.opcolor)}},Qn.fourcc="vmhd",Qn),SampleGroupInfo=class{constructor(u,o,l){this.grouping_type=u,this.grouping_type_parameter=o,this.sbgp=l,this.last_sample_in_run=-1,this.entry_index=-1}},ISOFile=class w{constructor(o,l=!0){this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.moovStartSent=!1,this.readySent=!1,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.sidxSent=!1,this.items=[],this.entity_groups=[],this.itemsDataSize=0,this.lastMoofIndex=0,this.samplesDataSize=0,this.lastBoxStartPosition=0,this.nextParsePosition=0,this.discardMdatData=!0,this.discardMdatData=l,o?(this.stream=o,this.parse()):this.stream=new MultiBufferStream,this.stream.isofile=this}setSegmentOptions(o,l,n){const{sizePerSegment:r=Number.MAX_SAFE_INTEGER,rapAlignement:t=!0}=n;let e=n.nbSamples??n.nbSamplesPerFragment??1e3;const i=n.nbSamplesPerFragment??e;if(e<=0||i<=0||r<=0){Log.error("ISOFile",`Invalid segment options: nbSamples=${e}, nbSamplesPerFragment=${i}, sizePerSegment=${r}`);return}if(e<i&&(Log.warn("ISOFile",`nbSamples (${e}) is less than nbSamplesPerFragment (${i}), setting nbSamples to nbSamplesPerFragment`),e=i),this.fragmentedTracks.some(s=>s.nb_samples!==e)){Log.error("ISOFile",`Cannot set segment options for track ${o}: nbSamples (${e}) does not match existing tracks`);return}const a=this.getTrackById(o);if(a){const s={id:o,user:l,trak:a,segmentStream:void 0,nb_samples:e,nb_samples_per_fragment:i,size_per_segment:r,rapAlignement:t,state:{lastFragmentSampleNumber:0,lastSegmentSampleNumber:0,accumulatedSize:0}};this.fragmentedTracks.push(s),a.nextSample=0}this.discardMdatData&&Log.warn("ISOFile","Segmentation options set but discardMdatData is true, samples will not be segmented")}unsetSegmentOptions(o){let l=-1;for(let n=0;n<this.fragmentedTracks.length;n++)this.fragmentedTracks[n].id===o&&(l=n);l>-1&&this.fragmentedTracks.splice(l,1)}setExtractionOptions(o,l,{nbSamples:n=1e3}={}){const r=this.getTrackById(o);r&&(this.extractedTracks.push({id:o,user:l,trak:r,nb_samples:n,samples:[]}),r.nextSample=0),this.discardMdatData&&Log.warn("ISOFile","Extraction options set but discardMdatData is true, samples will not be extracted")}unsetExtractionOptions(o){let l=-1;for(let n=0;n<this.extractedTracks.length;n++)this.extractedTracks[n].id===o&&(l=n);l>-1&&this.extractedTracks.splice(l,1)}parse(){if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else{this.saveParsePosition&&this.saveParsePosition();const l=parseOneBox(this.stream,!1);if(l.code===ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(l))continue;return}else return;else if(l.code===OK){const n=l.box;if(this.boxes.push(n),n.type==="uuid")this[n.uuid]!==void 0&&Log.warn("ISOFile","Duplicate Box of uuid: "+n.uuid+", overriding previous occurrence"),this[n.uuid]=n;else switch(n.type){case"mdat":this.mdats.push(n),this.transferMdatData(n);break;case"moof":this.moofs.push(n);break;case"free":case"skip":break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[n.type]!==void 0?Array.isArray(this[n.type+"s"])?(Log.info("ISOFile",`Found multiple boxes of type ${n.type} in ISOFile, adding to array`),this[n.type+"s"].push(n)):(Log.warn("ISOFile",`Found multiple boxes of type ${n.type} but no array exists. Creating array dynamically.`),this[n.type+"s"]=[this[n.type],n]):(this[n.type]=n,Array.isArray(this[n.type+"s"])&&this[n.type+"s"].push(n));break}this.updateUsedBytes&&this.updateUsedBytes(n,l)}else if(l.code===ERR_INVALID_DATA){Log.error("ISOFile",`Invalid data found while parsing box of type '${l.type}' at position ${l.start}. Aborting parsing.`,this);break}}}checkBuffer(o){if(!o)throw new Error("Buffer must be defined and non empty");return o.byteLength===0?(Log.warn("ISOFile","Ignoring empty buffer (fileStart: "+o.fileStart+")"),this.stream.logBufferLevel(),!1):(Log.info("ISOFile","Processing buffer (fileStart: "+o.fileStart+")"),o.usedBytes=0,this.stream.insertBuffer(o),this.stream.logBufferLevel(),this.stream.initialized()?!0:(Log.warn("ISOFile","Not ready to start parsing"),!1))}appendBuffer(o,l){let n;if(this.checkBuffer(o))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(l),this.nextSeekPosition?(n=this.nextSeekPosition,this.nextSeekPosition=void 0):n=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(n=this.stream.getEndFilePositionAfter(n))):this.nextParsePosition?n=this.nextParsePosition:n=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(Log.info("ISOFile","Done processing buffer (fileStart: "+o.fileStart+") - next buffer to fetch should have a fileStart position of "+n),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),Log.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),n}getFragmentDuration(){const o=this.getBox("mvex");if(!o)return;if(o.mehd)return{num:o.mehd.fragment_duration,den:this.moov.mvhd.timescale};const l=this.getBoxes("trak",!1);let n={num:0,den:1};for(const r of l){const t=r.samples_duration,e=r.mdia.mdhd.timescale;t&&e&&t/e>n.num/n.den&&(n={num:t,den:e})}return n}getInfo(){if(!this.moov)return{hasMoov:!1,mime:""};const o=new Date("1904-01-01T00:00:00Z").getTime(),l=this.getBox("mvex")!==void 0,n={hasMoov:!0,duration:this.moov.mvhd.duration,timescale:this.moov.mvhd.timescale,isFragmented:l,fragment_duration:this.getFragmentDuration(),isProgressive:this.isProgressive,hasIOD:this.moov.iods!==void 0,brands:[this.ftyp.major_brand].concat(this.ftyp.compatible_brands),created:new Date(o+this.moov.mvhd.creation_time*1e3),modified:new Date(o+this.moov.mvhd.modification_time*1e3),tracks:[],audioTracks:[],videoTracks:[],subtitleTracks:[],metadataTracks:[],hintTracks:[],otherTracks:[],mime:""};for(let r=0;r<this.moov.traks.length;r++){const t=this.moov.traks[r],e=t.mdia.minf.stbl.stsd.entries[0],i=t.samples_size,a=t.mdia.mdhd.timescale,s=t.samples_duration,d=i*8*a/s,c={samples_duration:s,bitrate:d,size:i,timescale:a,alternate_group:t.tkhd.alternate_group,codec:e.getCodec(),created:new Date(o+t.tkhd.creation_time*1e3),cts_shift:t.mdia.minf.stbl.cslg,duration:t.mdia.mdhd.duration,id:t.tkhd.track_id,kind:t.udta&&t.udta.kinds.length?t.udta.kinds[0]:{schemeURI:"",value:""},language:t.mdia.elng?t.mdia.elng.extended_language:t.mdia.mdhd.languageString,layer:t.tkhd.layer,matrix:t.tkhd.matrix,modified:new Date(o+t.tkhd.modification_time*1e3),movie_duration:t.tkhd.duration,movie_timescale:n.timescale,name:t.mdia.hdlr.name,nb_samples:t.samples.length,references:[],track_height:t.tkhd.height/65536,track_width:t.tkhd.width/65536,volume:t.tkhd.volume};if(n.tracks.push(c),t.tref)for(let F=0;F<t.tref.references.length;F++)c.references.push({type:t.tref.references[F].type,track_ids:t.tref.references[F].track_ids});t.edts!==void 0&&t.edts.elst!==void 0&&(c.edits=t.edts.elst.entries),e instanceof AudioSampleEntry?(c.type="audio",n.audioTracks.push(c),c.audio={sample_rate:e.getSampleRate(),channel_count:e.getChannelCount(),sample_size:e.getSampleSize()}):e instanceof VisualSampleEntry?(c.type="video",n.videoTracks.push(c),c.video={width:e.getWidth(),height:e.getHeight()}):e instanceof SubtitleSampleEntry?(c.type="subtitles",n.subtitleTracks.push(c)):e instanceof HintSampleEntry?(c.type="metadata",n.hintTracks.push(c)):e instanceof MetadataSampleEntry?(c.type="metadata",n.metadataTracks.push(c)):(c.type="metadata",n.otherTracks.push(c))}n.videoTracks&&n.videoTracks.length>0?n.mime+='video/mp4; codecs="':n.audioTracks&&n.audioTracks.length>0?n.mime+='audio/mp4; codecs="':n.mime+='application/mp4; codecs="';for(let r=0;r<n.tracks.length;r++)r!==0&&(n.mime+=","),n.mime+=n.tracks[r].codec;return n.mime+='"; profiles="',n.mime+=this.ftyp.compatible_brands.join(),n.mime+='"',n}setNextSeekPositionFromSample(o){o&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(o.offset+o.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=o.offset+o.alreadyRead)}processSamples(o){if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==void 0){const l=new Set;for(;l.size<this.fragmentedTracks.length&&this.fragmentedTracks.some(n=>n.trak.nextSample<n.trak.samples.length)&&this.sampleProcessingStarted;)for(const n of this.fragmentedTracks){const r=n.trak;if(!l.has(n.id)){const t=r.nextSample<r.samples.length?this.getSample(r,r.nextSample):void 0;if(!t){this.setNextSeekPositionFromSample(r.samples[r.nextSample]),l.add(n.id);continue}n.state.accumulatedSize+=t.size;const e=r.nextSample+1,i=e-n.state.lastFragmentSampleNumber>n.nb_samples_per_fragment,a=e-n.state.lastSegmentSampleNumber>n.nb_samples;let s=i||e%n.nb_samples_per_fragment===0,d=a||e%n.nb_samples===0,c=n.state.accumulatedSize>=n.size_per_segment;const F=!n.rapAlignement||t.is_sync,B=o||r.nextSample+1>=r.samples.length;if(B&&!F&&Log.warn("ISOFile","Flushing track #"+n.id+" at sample #"+r.nextSample+" which is not a RAP, this may lead to playback issues"),s=s&&F,d=d&&F,c=c&&F,s||c||B){i?Log.warn("ISOFile","Fragment on track #"+n.id+" is overdue, creating it with samples ["+n.state.lastFragmentSampleNumber+", "+r.nextSample+"]"):Log.debug("ISOFile","Creating media fragment on track #"+n.id+" for samples ["+n.state.lastFragmentSampleNumber+", "+r.nextSample+"]");const S=this.createFragment(n.id,n.state.lastFragmentSampleNumber,r.nextSample,n.segmentStream);if(S)n.segmentStream=S,n.state.lastFragmentSampleNumber=r.nextSample+1;else{l.add(n.id);continue}}(d||c||B)&&(a?Log.warn("ISOFile","Segment on track #"+n.id+" is overdue, sending it with samples ["+Math.max(0,r.nextSample-n.nb_samples)+", "+(r.nextSample-1)+"]"):Log.info("ISOFile","Sending fragmented data on track #"+n.id+" for samples ["+Math.max(0,r.nextSample-n.nb_samples)+", "+(r.nextSample-1)+"]"),Log.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(n.id,n.user,n.segmentStream.buffer,r.nextSample+1,o||r.nextSample+1>=r.samples.length),n.segmentStream=void 0,n.state.accumulatedSize=0,n.state.lastSegmentSampleNumber=r.nextSample+1),r.nextSample++}}}if(this.onSamples!==void 0)for(let l=0;l<this.extractedTracks.length;l++){const n=this.extractedTracks[l],r=n.trak;for(;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){Log.debug("ISOFile","Exporting on track #"+n.id+" sample #"+r.nextSample);const t=this.getSample(r,r.nextSample);if(t)r.nextSample++,n.samples.push(t);else{this.setNextSeekPositionFromSample(r.samples[r.nextSample]);break}if((r.nextSample%n.nb_samples===0||r.nextSample>=r.samples.length)&&(Log.debug("ISOFile","Sending samples on track #"+n.id+" for sample "+r.nextSample),this.onSamples&&this.onSamples(n.id,n.user,n.samples),n.samples=[],n!==this.extractedTracks[l]))break}}}}getBox(o){const l=this.getBoxes(o,!0);return l.length?l[0]:void 0}getBoxes(o,l){const n=[],r=t=>{t instanceof Box&&t.type&&t.type===o&&n.push(t);const e=[];t.boxes&&e.push(...t.boxes),t.entries&&e.push(...t.entries),t.item_infos&&e.push(...t.item_infos),t.references&&e.push(...t.references);for(const i of e){if(n.length&&l)return;r(i)}};return r(this),n}getTrackSamplesInfo(o){const l=this.getTrackById(o);if(l)return l.samples}getTrackSample(o,l){const n=this.getTrackById(o);return this.getSample(n,l)}releaseUsedSamples(o,l){let n=0;const r=this.getTrackById(o);r.lastValidSample||(r.lastValidSample=0);for(let t=r.lastValidSample;t<l;t++)n+=this.releaseSample(r,t);Log.info("ISOFile","Track #"+o+" released samples up to "+l+" (released size: "+n+", remaining: "+this.samplesDataSize+")"),r.lastValidSample=l}start(){this.sampleProcessingStarted=!0,this.processSamples(!1)}stop(){this.sampleProcessingStarted=!1}flush(){Log.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)}seekTrack(o,l,n){let r=0,t=0,e;if(n.samples.length===0)return Log.info("ISOFile","No sample in track, cannot seek! Using time "+Log.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(let a=0;a<n.samples.length;a++){const s=n.samples[a];if(a===0)t=0,e=s.timescale;else if(s.cts>o*s.timescale){t=a-1;break}l&&s.is_sync&&(r=a)}for(l&&(t=r),o=n.samples[t].cts,n.nextSample=t;n.samples[t].alreadyRead===n.samples[t].size&&n.samples[t+1];)t++;const i=n.samples[t].offset+n.samples[t].alreadyRead;return Log.info("ISOFile","Seeking to "+(l?"RAP":"")+" sample #"+n.nextSample+" on track "+n.tkhd.track_id+", time "+Log.getDurationString(o,e)+" and offset: "+i),{offset:i,time:o/e}}getTrackDuration(o){if(!o.samples)return 1/0;const l=o.samples[o.samples.length-1];return(l.cts+l.duration)/l.timescale}seek(o,l){const n=this.moov;let r={offset:1/0,time:1/0};if(this.moov){for(let t=0;t<n.traks.length;t++){const e=n.traks[t];if(o>this.getTrackDuration(e))continue;const i=this.seekTrack(o,l,e);i.offset<r.offset&&(r.offset=i.offset),i.time<r.time&&(r.time=i.time)}return Log.info("ISOFile","Seeking at time "+Log.getDurationString(r.time,1)+" needs a buffer with a fileStart position of "+r.offset),r.offset===1/0?r={offset:this.nextParsePosition,time:0}:r.offset=this.stream.getEndFilePositionAfter(r.offset),Log.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+r.offset),r}else throw new Error("Cannot seek: moov not received!")}equal(o){let l=0;for(;l<this.boxes.length&&l<o.boxes.length;){const n=this.boxes[l],r=o.boxes[l];if(!boxEqual(n,r))return!1;l++}return!0}write(o){for(let l=0;l<this.boxes.length;l++)this.boxes[l].write(o)}createFragment(o,l,n,r){const t=[];for(let d=l;d<=n;d++){const c=this.getTrackById(o),F=this.getSample(c,d);if(!F){this.setNextSeekPositionFromSample(c.samples[d]);return}t.push(F)}const e=r||new DataStream,i=this.createMoof(t);i.write(e),i.trafs[0].truns[0].data_offset=i.size+8,Log.debug("MP4Box","Adjusting data_offset with new value "+i.trafs[0].truns[0].data_offset),e.adjustUint32(i.trafs[0].truns[0].data_offset_position,i.trafs[0].truns[0].data_offset);const a=new mdatBox;a.stream=new MultiBufferStream;let s=0;for(const d of t)if(d.data){const c=MP4BoxBuffer.fromArrayBuffer(d.data.buffer,s);a.stream.insertBuffer(c),s+=d.data.byteLength}return a.write(e),e}static writeInitializationSegment(o,l,n){var e;Log.debug("ISOFile","Generating initialization segment");const r=new DataStream;o.write(r);const t=l.addBox(new mvexBox);if(n){const i=t.addBox(new mehdBox);i.fragment_duration=n}for(let i=0;i<l.traks.length;i++){const a=t.addBox(new trexBox);a.track_id=l.traks[i].tkhd.track_id,a.default_sample_description_index=1,a.default_sample_duration=((e=l.traks[i].samples[0])==null?void 0:e.duration)??0,a.default_sample_size=0,a.default_sample_flags=65536}return l.write(r),r.buffer}save(o){const l=new DataStream;return l.isofile=this,this.write(l),l.save(o)}getBuffer(){const o=new DataStream;return o.isofile=this,this.write(o),o}initializeSegmentation(){var l,n;this.onSegment||Log.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.resetTables());const o=new moovBox;o.addBox(this.moov.mvhd);for(let r=0;r<this.fragmentedTracks.length;r++){const t=this.getTrackById(this.fragmentedTracks[r].id);if(!t){Log.warn("ISOFile",`Track with id ${this.fragmentedTracks[r].id} not found, skipping fragmentation initialization`);continue}o.addBox(t)}return{tracks:o.traks.map((r,t)=>({id:r.tkhd.track_id,user:this.fragmentedTracks[t].user})),buffer:w.writeInitializationSegment(this.ftyp,o,(n=(l=this.moov)==null?void 0:l.mvex)==null?void 0:n.mehd.fragment_duration)}}resetTables(){this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0;for(let o=0;o<this.moov.traks.length;o++){const l=this.moov.traks[o];l.tkhd.duration=0,l.mdia.mdhd.duration=0;const n=l.mdia.minf.stbl.stco||l.mdia.minf.stbl.co64;n.chunk_offsets=[];const r=l.mdia.minf.stbl.stsc;r.first_chunk=[],r.samples_per_chunk=[],r.sample_description_index=[];const t=l.mdia.minf.stbl.stsz||l.mdia.minf.stbl.stz2;t.sample_sizes=[];const e=l.mdia.minf.stbl.stts;e.sample_counts=[],e.sample_deltas=[];const i=l.mdia.minf.stbl.ctts;i&&(i.sample_counts=[],i.sample_offsets=[]);const a=l.mdia.minf.stbl.stss,s=l.mdia.minf.stbl.boxes.indexOf(a);s!==-1&&(l.mdia.minf.stbl.boxes[s]=void 0)}}static initSampleGroups(o,l,n,r,t){l&&(l.sample_groups_info=[]),o.sample_groups_info||(o.sample_groups_info=[]);for(let e=0;e<n.length;e++){const i=n[e].grouping_type+"/"+n[e].grouping_type_parameter,a=new SampleGroupInfo(n[e].grouping_type,n[e].grouping_type_parameter,n[e]);l&&(l.sample_groups_info[i]=a),o.sample_groups_info[i]||(o.sample_groups_info[i]=a);for(let s=0;s<r.length;s++)r[s].grouping_type===n[e].grouping_type&&(a.description=r[s],a.description.used=!0);if(t)for(let s=0;s<t.length;s++)t[s].grouping_type===n[e].grouping_type&&(a.fragment_description=t[s],a.fragment_description.used=!0,a.is_fragment=!0)}if(l){if(t){for(let e=0;e<t.length;e++)if(!t[e].used&&t[e].version>=2){const i=t[e].grouping_type+"/0",a=new SampleGroupInfo(t[e].grouping_type,0);a.is_fragment=!0,l.sample_groups_info[i]||(l.sample_groups_info[i]=a)}}}else for(let e=0;e<r.length;e++)if(!r[e].used&&r[e].version>=2){const i=r[e].grouping_type+"/0",a=new SampleGroupInfo(r[e].grouping_type,0);o.sample_groups_info[i]||(o.sample_groups_info[i]=a)}}static setSampleGroupProperties(o,l,n,r){l.sample_groups=[];for(const t in r)if(l.sample_groups[t]={grouping_type:r[t].grouping_type,grouping_type_parameter:r[t].grouping_type_parameter},n>=r[t].last_sample_in_run&&(r[t].last_sample_in_run<0&&(r[t].last_sample_in_run=0),r[t].entry_index++,r[t].entry_index<=r[t].sbgp.entries.length-1&&(r[t].last_sample_in_run+=r[t].sbgp.entries[r[t].entry_index].sample_count)),r[t].entry_index<=r[t].sbgp.entries.length-1?l.sample_groups[t].group_description_index=r[t].sbgp.entries[r[t].entry_index].group_description_index:l.sample_groups[t].group_description_index=-1,l.sample_groups[t].group_description_index!==0){let e;if(r[t].fragment_description?e=r[t].fragment_description:e=r[t].description,l.sample_groups[t].group_description_index>0){let i;l.sample_groups[t].group_description_index>65535?i=(l.sample_groups[t].group_description_index>>16)-1:i=l.sample_groups[t].group_description_index-1,e&&i>=0&&(l.sample_groups[t].description=e.entries[i])}else e&&e.version>=2&&e.default_group_description_index>0&&(l.sample_groups[t].description=e.entries[e.default_group_description_index-1])}}static process_sdtp(o,l,n){l&&(o?(l.is_leading=o.is_leading[n],l.depends_on=o.sample_depends_on[n],l.is_depended_on=o.sample_is_depended_on[n],l.has_redundancy=o.sample_has_redundancy[n]):(l.is_leading=0,l.depends_on=0,l.is_depended_on=0,l.has_redundancy=0))}buildSampleLists(){for(let o=0;o<this.moov.traks.length;o++)this.buildTrakSampleLists(this.moov.traks[o])}buildTrakSampleLists(o){let l,n,r,t,e,i;o.samples=[],o.samples_duration=0,o.samples_size=0;const a=o.mdia.minf.stbl.stco||o.mdia.minf.stbl.co64,s=o.mdia.minf.stbl.stsc,d=o.mdia.minf.stbl.stsz||o.mdia.minf.stbl.stz2,c=o.mdia.minf.stbl.stts,F=o.mdia.minf.stbl.ctts,B=o.mdia.minf.stbl.stss,S=o.mdia.minf.stbl.stsd,y=o.mdia.minf.stbl.subs,E=o.mdia.minf.stbl.stdp,v=o.mdia.minf.stbl.sbgps,N=o.mdia.minf.stbl.sgpds;let T=-1,C=-1,m=-1,Q=-1,p=0,f=0,h=0;if(w.initSampleGroups(o,void 0,v,N),!(typeof d>"u")){for(l=0;l<d.sample_sizes.length;l++){const R={number:l,track_id:o.tkhd.track_id,timescale:o.mdia.mdhd.timescale,alreadyRead:0,size:d.sample_sizes[l]};o.samples[l]=R,o.samples_size+=R.size,l===0?(r=1,n=0,R.chunk_index=r,R.chunk_run_index=n,i=s.samples_per_chunk[n],e=0,n+1<s.first_chunk.length?t=s.first_chunk[n+1]-1:t=1/0):l<i?(R.chunk_index=r,R.chunk_run_index=n):(r++,R.chunk_index=r,e=0,r<=t||(n++,n+1<s.first_chunk.length?t=s.first_chunk[n+1]-1:t=1/0),R.chunk_run_index=n,i+=s.samples_per_chunk[n]),R.description_index=s.sample_description_index[R.chunk_run_index]-1,R.description=S.entries[R.description_index],R.offset=a.chunk_offsets[R.chunk_index-1]+e,e+=R.size,l>T&&(C++,T<0&&(T=0),T+=c.sample_counts[C]),l>0?(o.samples[l-1].duration=c.sample_deltas[C],o.samples_duration+=o.samples[l-1].duration,R.dts=o.samples[l-1].dts+o.samples[l-1].duration):R.dts=0,F?(l>=m&&(Q++,m<0&&(m=0),m+=F.sample_counts[Q]),R.cts=o.samples[l].dts+F.sample_offsets[Q]):R.cts=R.dts,B?(l===B.sample_numbers[p]-1?(R.is_sync=!0,p++):(R.is_sync=!1,R.degradation_priority=0),y&&y.entries[f].sample_delta+h===l+1&&(R.subsamples=y.entries[f].subsamples,h+=y.entries[f].sample_delta,f++)):R.is_sync=!0,w.process_sdtp(o.mdia.minf.stbl.sdtp,R,R.number),E?R.degradation_priority=E.priority[l]:R.degradation_priority=0,y&&y.entries[f].sample_delta+h===l&&(R.subsamples=y.entries[f].subsamples,h+=y.entries[f].sample_delta),(v.length>0||N.length>0)&&w.setSampleGroupProperties(o,R,l,o.sample_groups_info)}l>0&&(o.samples[l-1].duration=Math.max(o.mdia.mdhd.duration-o.samples[l-1].dts,0),o.samples_duration+=o.samples[l-1].duration)}}updateSampleLists(){let o,l,n,r,t;if(this.moov!==void 0)for(;this.lastMoofIndex<this.moofs.length;){const e=this.moofs[this.lastMoofIndex];if(this.lastMoofIndex++,e.type==="moof"){const i=e;for(let a=0;a<i.trafs.length;a++){const s=i.trafs[a],d=this.getTrackById(s.tfhd.track_id),c=this.getTrexById(s.tfhd.track_id);s.tfhd.flags&TFHD_FLAG_SAMPLE_DESC?o=s.tfhd.default_sample_description_index:o=c?c.default_sample_description_index:1,s.tfhd.flags&TFHD_FLAG_SAMPLE_DUR?l=s.tfhd.default_sample_duration:l=c?c.default_sample_duration:0,s.tfhd.flags&TFHD_FLAG_SAMPLE_SIZE?n=s.tfhd.default_sample_size:n=c?c.default_sample_size:0,s.tfhd.flags&TFHD_FLAG_SAMPLE_FLAGS?r=s.tfhd.default_sample_flags:r=c?c.default_sample_flags:0,s.sample_number=0,s.sbgps.length>0&&w.initSampleGroups(d,s,s.sbgps,d.mdia.minf.stbl.sgpds,s.sgpds);for(let F=0;F<s.truns.length;F++){const B=s.truns[F];for(let S=0;S<B.sample_count;S++){const y=o-1;let E=r;B.flags&TRUN_FLAGS_FLAGS?E=B.sample_flags[S]:S===0&&B.flags&TRUN_FLAGS_FIRST_FLAG&&(E=B.first_sample_flags);let v=n;B.flags&TRUN_FLAGS_SIZE&&(v=B.sample_size[S]),d.samples_size+=v;let N=l;B.flags&TRUN_FLAGS_DURATION&&(N=B.sample_duration[S]),d.samples_duration+=N;let T;d.first_traf_merged||S>0?T=d.samples[d.samples.length-1].dts+d.samples[d.samples.length-1].duration:(s.tfdt?T=s.tfdt.baseMediaDecodeTime:T=0,d.first_traf_merged=!0);let C=T;B.flags&TRUN_FLAGS_CTS_OFFSET&&(C=T+B.sample_composition_time_offset[S]);const m=!!(s.tfhd.flags&TFHD_FLAG_BASE_DATA_OFFSET),Q=!!(s.tfhd.flags&TFHD_FLAG_DEFAULT_BASE_IS_MOOF),p=!!(B.flags&TRUN_FLAGS_DATA_OFFSET);let f=0;m?f=s.tfhd.base_data_offset:Q||F===0?f=i.start:f=t;let h;F===0&&S===0?p?h=f+B.data_offset:h=f:h=t,t=h+v;const R=s.sample_number;s.sample_number++;const J={cts:C,description_index:y,description:d.mdia.minf.stbl.stsd.entries[y],dts:T,duration:N,moof_number:this.lastMoofIndex,number_in_traf:R,number:d.samples.length,offset:h,size:v,timescale:d.mdia.mdhd.timescale,track_id:d.tkhd.track_id,is_sync:!(E>>16&1),is_leading:E>>26&3,depends_on:E>>24&3,is_depended_on:E>>22&3,has_redundancy:E>>20&3,degradation_priority:E&65535};s.first_sample_index=d.samples.length,d.samples.push(J),(s.sbgps.length>0||s.sgpds.length>0||d.mdia.minf.stbl.sbgps.length>0||d.mdia.minf.stbl.sgpds.length>0)&&w.setSampleGroupProperties(d,J,J.number_in_traf,s.sample_groups_info)}}if(s.subs){d.has_fragment_subsamples=!0;let F=s.first_sample_index;for(let B=0;B<s.subs.entries.length;B++){F+=s.subs.entries[B].sample_delta;const S=d.samples[F-1];S.subsamples=s.subs.entries[B].subsamples}}}}}}getSample(o,l){const n=o.samples[l];if(this.moov){if(!n.data)n.data=new Uint8Array(n.size),n.alreadyRead=0,this.samplesDataSize+=n.size,Log.debug("ISOFile","Allocating sample #"+l+" on track #"+o.tkhd.track_id+" of size "+n.size+" (total: "+this.samplesDataSize+")");else if(n.alreadyRead===n.size)return n;for(;;){let r=this.stream,t=r.findPosition(!0,n.offset+n.alreadyRead,!1),e,i;if(t>-1)e=r.buffers[t],i=e.fileStart;else for(const a of this.mdats){if(!a.stream){Log.debug("ISOFile","mdat stream not yet fully read for #"+this.mdats.indexOf(a)+" mdat");continue}if(t=a.stream.findPosition(!0,n.offset+n.alreadyRead-a.start-a.hdr_size,!1),t>-1){r=a.stream,e=a.stream.buffers[t],i=a.start+a.hdr_size+e.fileStart;break}}if(e){const a=e.byteLength-(n.offset+n.alreadyRead-i);if(n.size-n.alreadyRead<=a)return Log.debug("ISOFile","Getting sample #"+l+" data (alreadyRead: "+n.alreadyRead+" offset: "+(n.offset+n.alreadyRead-i)+" read size: "+(n.size-n.alreadyRead)+" full size: "+n.size+")"),DataStream.memcpy(n.data.buffer,n.alreadyRead,e,n.offset+n.alreadyRead-i,n.size-n.alreadyRead),e.usedBytes+=n.size-n.alreadyRead,r.logBufferLevel(),n.alreadyRead=n.size,n;if(a===0)return;Log.debug("ISOFile","Getting sample #"+l+" partial data (alreadyRead: "+n.alreadyRead+" offset: "+(n.offset+n.alreadyRead-i)+" read size: "+a+" full size: "+n.size+")"),DataStream.memcpy(n.data.buffer,n.alreadyRead,e,n.offset+n.alreadyRead-i,a),n.alreadyRead+=a,e.usedBytes+=a,r.logBufferLevel()}else return}}}releaseSample(o,l){const n=o.samples[l];return n.data?(this.samplesDataSize-=n.size,n.data=void 0,n.alreadyRead=0,n.size):0}getAllocatedSampleDataSize(){return this.samplesDataSize}getCodecs(){let o="";for(let l=0;l<this.moov.traks.length;l++){const n=this.moov.traks[l];l>0&&(o+=","),o+=n.mdia.minf.stbl.stsd.entries[0].getCodec()}return o}getTrexById(o){if(!(!this.moov||!this.moov.mvex))for(let l=0;l<this.moov.mvex.trexs.length;l++){const n=this.moov.mvex.trexs[l];if(n.track_id===o)return n}}getTrackById(o){if(this.moov)for(let l=0;l<this.moov.traks.length;l++){const n=this.moov.traks[l];if(n.tkhd.track_id===o)return n}}flattenItemInfo(){const o=this.items,l=this.entity_groups,n=this.meta;if(!(!n||!n.hdlr||!n.iinf)){for(let r=0;r<n.iinf.item_infos.length;r++){const t=n.iinf.item_infos[r].item_ID;o[t]={id:t,name:n.iinf.item_infos[r].item_name,ref_to:[],content_type:n.iinf.item_infos[r].content_type,content_encoding:n.iinf.item_infos[r].content_encoding,item_uri_type:n.iinf.item_infos[r].item_uri_type,type:n.iinf.item_infos[r].item_type?n.iinf.item_infos[r].item_type:"mime",protection:n.iinf.item_infos[r].item_protection_index>0?n.ipro.protections[n.iinf.item_infos[r].item_protection_index-1]:void 0}}if(n.grpl)for(let r=0;r<n.grpl.boxes.length;r++){const t=n.grpl.boxes[r];l[t.group_id]={id:t.group_id,entity_ids:t.entity_ids,type:t.type}}if(n.iloc)for(let r=0;r<n.iloc.items.length;r++){const t=n.iloc.items[r],e=o[t.item_ID];t.data_reference_index!==0&&(Log.warn("Item storage with reference to other files: not supported"),e.source=n.dinf.boxes[t.data_reference_index-1]),e.extents=[],e.size=0;for(let i=0;i<t.extents.length;i++)e.extents[i]={offset:t.extents[i].extent_offset+t.base_offset,length:t.extents[i].extent_length,alreadyRead:0},t.construction_method===1&&(e.extents[i].offset+=n.idat.start+n.idat.hdr_size),e.size+=e.extents[i].length}if(n.pitm&&(o[n.pitm.item_id].primary=!0),n.iref)for(let r=0;r<n.iref.references.length;r++){const t=n.iref.references[r];for(let e=0;e<t.references.length;e++)o[t.from_item_ID].ref_to.push({type:t.type,id:t.references[e]})}if(n.iprp)for(let r=0;r<n.iprp.ipmas.length;r++){const t=n.iprp.ipmas[r];for(let e=0;e<t.associations.length;e++){const i=t.associations[e],a=o[i.id]??l[i.id];if(a){a.properties===void 0&&(a.properties={boxes:[]});for(let s=0;s<i.props.length;s++){const d=i.props[s];if(d.property_index>0&&d.property_index-1<n.iprp.ipco.boxes.length){const c=n.iprp.ipco.boxes[d.property_index-1];a.properties[c.type]=c,a.properties.boxes.push(c)}}}}}}}getItem(o){if(!this.meta)return;const l=this.items[o];if(!l.data&&l.size)l.data=new Uint8Array(l.size),l.alreadyRead=0,this.itemsDataSize+=l.size,Log.debug("ISOFile","Allocating item #"+o+" of size "+l.size+" (total: "+this.itemsDataSize+")");else if(l.alreadyRead===l.size)return l;for(let n=0;n<l.extents.length;n++){const r=l.extents[n];if(r.alreadyRead!==r.length){const t=this.stream.findPosition(!0,r.offset+r.alreadyRead,!1);if(t>-1){const e=this.stream.buffers[t],i=e.byteLength-(r.offset+r.alreadyRead-e.fileStart);if(r.length-r.alreadyRead<=i)Log.debug("ISOFile","Getting item #"+o+" extent #"+n+" data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-e.fileStart)+" read size: "+(r.length-r.alreadyRead)+" full extent size: "+r.length+" full item size: "+l.size+")"),DataStream.memcpy(l.data.buffer,l.alreadyRead,e,r.offset+r.alreadyRead-e.fileStart,r.length-r.alreadyRead),(!this.parsingMdat||this.discardMdatData)&&(e.usedBytes+=r.length-r.alreadyRead),this.stream.logBufferLevel(),l.alreadyRead+=r.length-r.alreadyRead,r.alreadyRead=r.length;else{Log.debug("ISOFile","Getting item #"+o+" extent #"+n+" partial data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-e.fileStart)+" read size: "+i+" full extent size: "+r.length+" full item size: "+l.size+")"),DataStream.memcpy(l.data.buffer,l.alreadyRead,e,r.offset+r.alreadyRead-e.fileStart,i),r.alreadyRead+=i,l.alreadyRead+=i,(!this.parsingMdat||this.discardMdatData)&&(e.usedBytes+=i),this.stream.logBufferLevel();return}}else return}}if(l.alreadyRead===l.size)return l}releaseItem(o){const l=this.items[o];if(l.data){this.itemsDataSize-=l.size,l.data=void 0,l.alreadyRead=0;for(let n=0;n<l.extents.length;n++){const r=l.extents[n];r.alreadyRead=0}return l.size}else return 0}processItems(o){for(const l in this.items){const n=this.items[l];this.getItem(n.id),o&&!n.sent&&(o(n),n.sent=!0,n.data=void 0)}}hasItem(o){for(const l in this.items){const n=this.items[l];if(n.name===o)return n.id}return-1}getMetaHandler(){if(this.meta)return this.meta.hdlr.handler}getPrimaryItem(){if(this.meta&&this.meta.pitm)return this.getItem(this.meta.pitm.item_id)}itemToFragmentedTrackFile({itemId:o}={}){let l;if(o?l=this.getItem(o):l=this.getPrimaryItem(),!l)return;const n=new w;n.discardMdatData=!1;const r={type:l.type,description_boxes:l.properties.boxes};l.properties.ispe&&(r.width=l.properties.ispe.image_width,r.height=l.properties.ispe.image_height);const t=n.addTrack(r);if(t)return n.addSample(t,l.data),n}processIncompleteBox(o){if(o.type==="mdat"){const l=new mdatBox(o.size);return this.parsingMdat=l,this.boxes.push(l),this.mdats.push(l),l.start=o.start,l.hdr_size=o.hdr_size,l.original_size=o.original_size,this.stream.addUsedBytes(l.hdr_size),this.lastBoxStartPosition=l.start+l.size,this.stream.seek(l.start+l.size,!1,this.discardMdatData)?(this.transferMdatData(),this.parsingMdat=void 0,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=l.start+l.size,!1)}else return o.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),(this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1)?(this.nextParsePosition=this.stream.getEndPosition(),!0):(o.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+o.size:this.nextParsePosition=this.stream.getEndPosition(),!1)}hasIncompleteMdat(){return this.parsingMdat!==void 0}transferMdatData(o){const l=o??this.parsingMdat;if(this.discardMdatData){Log.debug("ISOFile","Discarding 'mdat' data, not transferring it to the mdat box stream");return}if(!l){Log.warn("ISOFile","Cannot transfer 'mdat' data, no mdat box is being parsed");return}const n=this.stream.findPosition(!0,l.start+l.hdr_size,!1),r=this.stream.findPosition(!0,l.start+l.size,!1);if(n===-1||r===-1){Log.warn("ISOFile","Cannot transfer 'mdat' data, start or end buffer not found");return}l.stream=new MultiBufferStream;for(let t=n;t<=r;t++){const e=this.stream.buffers[t],i=t===n?l.start+l.hdr_size-e.fileStart:0,a=t===r?l.start+l.size-e.fileStart:e.byteLength;if(a>i){Log.debug("ISOFile","Transferring 'mdat' data from buffer #"+t+" ("+i+" to "+a+")");const s=a-i,d=new MP4BoxBuffer(s),c=l.stream.getAbsoluteEndPosition();DataStream.memcpy(d,0,e,i,s),d.fileStart=c,l.stream.insertBuffer(d),e.usedBytes+=s}}}processIncompleteMdat(){const o=this.parsingMdat;return this.stream.seek(o.start+o.size,!1,this.discardMdatData)?(Log.debug("ISOFile","Found 'mdat' end in buffered data"),this.transferMdatData(),this.parsingMdat=void 0,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)}restoreParsePosition(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)}saveParsePosition(){this.lastBoxStartPosition=this.stream.getPosition()}updateUsedBytes(o,l){this.stream.addUsedBytes&&(o.type==="mdat"?(this.stream.addUsedBytes(o.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(o.size-o.hdr_size)):this.stream.addUsedBytes(o.size))}addBox(o){return Box.prototype.addBox.call(this,o)}init(o={}){const l=this.addBox(new ftypBox);l.major_brand=o.brands&&o.brands[0]||"iso4",l.minor_version=0,l.compatible_brands=o.brands||["iso4"];const n=this.addBox(new moovBox);n.addBox(new mvexBox);const r=n.addBox(new mvhdBox);return r.timescale=o.timescale||600,r.rate=o.rate||65536,r.creation_time=0,r.modification_time=0,r.duration=o.duration||0,r.volume=o.width?0:256,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.next_track_id=1,this}addTrack(o={}){this.moov||this.init(o);const l=o||{};l.width=l.width||320,l.height=l.height||320,l.id=l.id||this.moov.mvhd.next_track_id,l.type=l.type||"avc1";const n=this.moov.addBox(new trakBox);this.moov.mvhd.next_track_id=l.id+1;const r=n.addBox(new tkhdBox);r.flags=TKHD_FLAG_ENABLED|TKHD_FLAG_IN_MOVIE|TKHD_FLAG_IN_PREVIEW,r.creation_time=0,r.modification_time=0,r.track_id=l.id,r.duration=l.duration||0,r.layer=l.layer||0,r.alternate_group=0,r.volume=1,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.width=l.width<<16,r.height=l.height<<16;const t=n.addBox(new mdiaBox),e=t.addBox(new mdhdBox);e.creation_time=0,e.modification_time=0,e.timescale=l.timescale||1,e.duration=l.media_duration||0,e.language=l.language||"und";const i=t.addBox(new hdlrBox);i.handler=l.hdlr||"vide",i.name=l.name||"Track created with MP4Box.js";const a=t.addBox(new elngBox);a.extended_language=l.language||"fr-FR";const s=t.addBox(new minfBox),d=BoxRegistry.sampleEntry[l.type];if(!d)return;const c=new d;if(c.data_reference_index=1,c instanceof VisualSampleEntry){const Q=c,p=s.addBox(new vmhdBox);p.graphicsmode=0,p.opcolor=[0,0,0],Q.width=l.width,Q.height=l.height,Q.horizresolution=72<<16,Q.vertresolution=72<<16,Q.frame_count=1,Q.compressorname=l.type+" Compressor",Q.depth=24,l.avcDecoderConfigRecord?Q.addBox(new avcCBox(l.avcDecoderConfigRecord.byteLength)).parse(new DataStream(l.avcDecoderConfigRecord)):l.hevcDecoderConfigRecord&&Q.addBox(new hvcCBox(l.hevcDecoderConfigRecord.byteLength)).parse(new DataStream(l.hevcDecoderConfigRecord))}else if(c instanceof AudioSampleEntry){const Q=c,p=s.addBox(new smhdBox);p.balance=l.balance||0,Q.channel_count=l.channel_count||2,Q.samplesize=l.samplesize||16,Q.samplerate=l.samplerate||65536}else c instanceof HintSampleEntry?s.addBox(new hmhdBox):c instanceof SubtitleSampleEntry?(s.addBox(new sthdBox),c instanceof stppSampleEntry&&(c.namespace=l.namespace||"nonamespace",c.schema_location=l.schema_location||"",c.auxiliary_mime_types=l.auxiliary_mime_types||"")):c instanceof MetadataSampleEntry?s.addBox(new nmhdBox):c instanceof SystemSampleEntry?s.addBox(new nmhdBox):s.addBox(new nmhdBox);l.description&&c.addBox.call(c,l.description),l.description_boxes&&l.description_boxes.forEach(function(Q){c.addBox.call(c,Q)});const B=s.addBox(new dinfBox).addBox(new drefBox),S=new urlBox;S.flags=1,B.addEntry(S);const y=s.addBox(new stblBox);y.addBox(new stsdBox).addEntry(c);const v=y.addBox(new sttsBox);v.sample_counts=[],v.sample_deltas=[];const N=y.addBox(new stscBox);N.first_chunk=[],N.samples_per_chunk=[],N.sample_description_index=[];const T=y.addBox(new stcoBox);T.chunk_offsets=[];const C=y.addBox(new stszBox);C.sample_sizes=[];const m=this.moov.mvex.addBox(new trexBox);return m.track_id=l.id,m.default_sample_description_index=l.default_sample_description_index||1,m.default_sample_duration=l.default_sample_duration||0,m.default_sample_size=l.default_sample_size||0,m.default_sample_flags=l.default_sample_flags||0,this.buildTrakSampleLists(n),l.id}addSample(o,l,{sample_description_index:n,duration:r=1,cts:t=0,dts:e=0,is_sync:i=!1,is_leading:a=0,depends_on:s=0,is_depended_on:d=0,has_redundancy:c=0,degradation_priority:F=0,subsamples:B,offset:S=0}={}){const y=this.getTrackById(o);if(y===void 0)return;const E=n?n-1:0,v={number:y.samples.length,track_id:y.tkhd.track_id,timescale:y.mdia.mdhd.timescale,description_index:E,description:y.mdia.minf.stbl.stsd.entries[E],data:l,size:l.byteLength,alreadyRead:l.byteLength,duration:r,cts:t,dts:e,is_sync:i,is_leading:a,depends_on:s,is_depended_on:d,has_redundancy:c,degradation_priority:F,offset:S,subsamples:B};y.samples.push(v),y.samples_size+=v.size,y.samples_duration+=v.duration,y.first_dts===void 0&&(y.first_dts=e),this.processSamples();const N=this.addBox(this.createMoof([v]));N.computeSize(),N.trafs[0].truns[0].data_offset=N.size+8;const T=this.addBox(new mdatBox);return T.data=new Uint8Array(l),v}createMoof(o){if(o.length===0)return;if(o.some(d=>d.track_id!==o[0].track_id))throw new Error("Cannot create moof for samples from different tracks: "+o.map(d=>d.track_id).join(", "));const l=o[0].track_id,n=this.getTrackById(l);if(!n)throw new Error("Cannot create moof for non-existing track: "+l);const r=new moofBox,t=r.addBox(new mfhdBox);t.sequence_number=++this.nextMoofNumber;const e=r.addBox(new trafBox),i=e.addBox(new tfhdBox);i.track_id=l,i.flags=TFHD_FLAG_DEFAULT_BASE_IS_MOOF;const a=e.addBox(new tfdtBox);a.baseMediaDecodeTime=o[0].dts-(n.first_dts||0);const s=e.addBox(new trunBox);s.flags=TRUN_FLAGS_DATA_OFFSET|TRUN_FLAGS_DURATION|TRUN_FLAGS_SIZE|TRUN_FLAGS_FLAGS|TRUN_FLAGS_CTS_OFFSET,s.data_offset=0,s.first_sample_flags=0,s.sample_count=o.length;for(const d of o){let c=0;d.is_sync?c=1<<25:c=65536,s.sample_duration.push(d.duration),s.sample_size.push(d.size),s.sample_flags.push(c),s.sample_composition_time_offset.push(d.cts-d.dts)}return r}print(o){o.indent="";for(let l=0;l<this.boxes.length;l++)this.boxes[l]&&this.boxes[l].print(o)}};function createFile(u=!1,o){return new ISOFile(o,!u)}var descriptor_exports={};__export(descriptor_exports,{Descriptor:()=>Descriptor,ES_Descriptor:()=>ES_Descriptor,MPEG4DescriptorParser:()=>MPEG4DescriptorParser});var ES_DescrTag=3,DecoderConfigDescrTag=4,DecSpecificInfoTag=5,SLConfigDescrTag=6,Descriptor=class Ur{constructor(o,l){this.tag=o,this.size=l,this.descs=[]}parse(o){this.data=o.readUint8Array(this.size)}findDescriptor(o){for(let l=0;l<this.descs.length;l++)if(this.descs[l].tag===o)return this.descs[l]}parseOneDescriptor(o){let l=0;const n=o.readUint8();let r=o.readUint8();for(;r&128;)l=(l<<7)+(r&127),r=o.readUint8();l=(l<<7)+(r&127),Log.debug("Descriptor","Found "+(descTagToName[n]||"Descriptor "+n)+", size "+l+" at position "+o.getPosition());const t=descTagToName[n]?new DESCRIPTOR_CLASSES[descTagToName[n]](l):new Ur(l);return t.parse(o),t}parseRemainingDescriptors(o){var n;const l=o.getPosition();for(;o.getPosition()<l+this.size;){const r=(n=this.parseOneDescriptor)==null?void 0:n.call(this,o);this.descs.push(r)}}},ES_Descriptor=class extends Descriptor{constructor(u){super(ES_DescrTag,u)}parse(u){if(this.ES_ID=u.readUint16(),this.flags=u.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=u.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){const o=u.readUint8();this.URL=u.readString(o),this.size-=o+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=u.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(u)}getOTI(){const u=this.findDescriptor(DecoderConfigDescrTag);return u?u.oti:0}getAudioConfig(){const u=this.findDescriptor(DecoderConfigDescrTag);if(!u)return;const o=u.findDescriptor(DecSpecificInfoTag);if(o&&o.data){let l=(o.data[0]&248)>>3;return l===31&&o.data.length>=2&&(l=32+((o.data[0]&7)<<3)+((o.data[1]&224)>>5)),l}}},DecoderConfigDescriptor=class extends Descriptor{constructor(u){super(DecoderConfigDescrTag,u)}parse(u){this.oti=u.readUint8(),this.streamType=u.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=u.readUint24(),this.maxBitrate=u.readUint32(),this.avgBitrate=u.readUint32(),this.size-=13,this.parseRemainingDescriptors(u)}},DecoderSpecificInfo=class extends Descriptor{constructor(u){super(DecSpecificInfoTag,u)}},SLConfigDescriptor=class extends Descriptor{constructor(u){super(SLConfigDescrTag,u)}},DESCRIPTOR_CLASSES={Descriptor,ES_Descriptor,DecoderConfigDescriptor,DecoderSpecificInfo,SLConfigDescriptor},descTagToName={[ES_DescrTag]:"ES_Descriptor",[DecoderConfigDescrTag]:"DecoderConfigDescriptor",[DecSpecificInfoTag]:"DecoderSpecificInfo",[SLConfigDescrTag]:"SLConfigDescriptor"},MPEG4DescriptorParser=class{constructor(){this.parseOneDescriptor=Descriptor.prototype.parseOneDescriptor}getDescriptorName(u){return descTagToName[u]}},all_boxes_exports={};__export(all_boxes_exports,{CoLLBox:()=>CoLLBox,ItemContentIDPropertyBox:()=>ItemContentIDPropertyBox,OpusSampleEntry:()=>OpusSampleEntry,SmDmBox:()=>SmDmBox,a1lxBox:()=>a1lxBox,a1opBox:()=>a1opBox,ac_3SampleEntry:()=>ac_3SampleEntry,ac_4SampleEntry:()=>ac_4SampleEntry,aebrBox:()=>aebrBox,afbrBox:()=>afbrBox,albcBox:()=>albcBox,alstSampleGroupEntry:()=>alstSampleGroupEntry,altrBox:()=>altrBox,auxCBox:()=>auxCBox,av01SampleEntry:()=>av01SampleEntry,av1CBox:()=>av1CBox,avc1SampleEntry:()=>avc1SampleEntry,avc2SampleEntry:()=>avc2SampleEntry,avc3SampleEntry:()=>avc3SampleEntry,avc4SampleEntry:()=>avc4SampleEntry,avcCBox:()=>avcCBox,avllSampleGroupEntry:()=>avllSampleGroupEntry,avs3SampleEntry:()=>avs3SampleEntry,avssSampleGroupEntry:()=>avssSampleGroupEntry,brstBox:()=>brstBox,btrtBox:()=>btrtBox,bxmlBox:()=>bxmlBox,ccstBox:()=>ccstBox,cdefBox:()=>cdefBox,clapBox:()=>clapBox,clefBox:()=>clefBox,clliBox:()=>clliBox,cmexBox:()=>cmexBox,cminBox:()=>cminBox,cmpdBox:()=>cmpdBox,co64Box:()=>co64Box,colrBox:()=>colrBox,coviBox:()=>coviBox,cprtBox:()=>cprtBox,cschBox:()=>cschBox,cslgBox:()=>cslgBox,cttsBox:()=>cttsBox,dOpsBox:()=>dOpsBox,dac3Box:()=>dac3Box,dataBox:()=>dataBox,dav1SampleEntry:()=>dav1SampleEntry,dec3Box:()=>dec3Box,dfLaBox:()=>dfLaBox,dimmBox:()=>dimmBox,dinfBox:()=>dinfBox,dmax:()=>dmax,dmedBox:()=>dmedBox,dobrBox:()=>dobrBox,drefBox:()=>drefBox,drepBox:()=>drepBox,dtrtSampleGroupEntry:()=>dtrtSampleGroupEntry,dvh1SampleEntry:()=>dvh1SampleEntry,dvheSampleEntry:()=>dvheSampleEntry,ec_3SampleEntry:()=>ec_3SampleEntry,edtsBox:()=>edtsBox,elngBox:()=>elngBox,elstBox:()=>elstBox,emsgBox:()=>emsgBox,encaSampleEntry:()=>encaSampleEntry,encmSampleEntry:()=>encmSampleEntry,encsSampleEntry:()=>encsSampleEntry,enctSampleEntry:()=>enctSampleEntry,encuSampleEntry:()=>encuSampleEntry,encvSampleEntry:()=>encvSampleEntry,enofBox:()=>enofBox,eqivBox:()=>eqivBox,esdsBox:()=>esdsBox,etypBox:()=>etypBox,fLaCSampleEntry:()=>fLaCSampleEntry,favcBox:()=>favcBox,fielBox:()=>fielBox,fobrBox:()=>fobrBox,freeBox:()=>freeBox,frmaBox:()=>frmaBox,ftypBox:()=>ftypBox,grplBox:()=>grplBox,hdlrBox:()=>hdlrBox,hev1SampleEntry:()=>hev1SampleEntry,hev2SampleEntry:()=>hev2SampleEntry,hinfBox:()=>hinfBox,hmhdBox:()=>hmhdBox,hntiBox:()=>hntiBox,hvc1SampleEntry:()=>hvc1SampleEntry,hvc2SampleEntry:()=>hvc2SampleEntry,hvcCBox:()=>hvcCBox,hvt1SampleEntry:()=>hvt1SampleEntry,iaugBox:()=>iaugBox,idatBox:()=>idatBox,iinfBox:()=>iinfBox,ilocBox:()=>ilocBox,ilstBox:()=>ilstBox,imirBox:()=>imirBox,infeBox:()=>infeBox,iodsBox:()=>iodsBox,ipcoBox:()=>ipcoBox,ipmaBox:()=>ipmaBox,iproBox:()=>iproBox,iprpBox:()=>iprpBox,irefBox:()=>irefBox,irotBox:()=>irotBox,ispeBox:()=>ispeBox,itaiBox:()=>itaiBox,j2kHBox:()=>j2kHBox,j2kiSampleEntry:()=>j2kiSampleEntry,keysBox:()=>keysBox,kindBox:()=>kindBox,levaBox:()=>levaBox,lhe1SampleEntry:()=>lhe1SampleEntry,lhv1SampleEntry:()=>lhv1SampleEntry,lhvCBox:()=>lhvCBox,lselBox:()=>lselBox,m4aeSampleEntry:()=>m4aeSampleEntry,maxrBox:()=>maxrBox,mdatBox:()=>mdatBox,mdcvBox:()=>mdcvBox,mdhdBox:()=>mdhdBox,mdiaBox:()=>mdiaBox,mecoBox:()=>mecoBox,mehdBox:()=>mehdBox,metaBox:()=>metaBox,mettSampleEntry:()=>mettSampleEntry,metxSampleEntry:()=>metxSampleEntry,mfhdBox:()=>mfhdBox,mfraBox:()=>mfraBox,mfroBox:()=>mfroBox,mha1SampleEntry:()=>mha1SampleEntry,mha2SampleEntry:()=>mha2SampleEntry,mhm1SampleEntry:()=>mhm1SampleEntry,mhm2SampleEntry:()=>mhm2SampleEntry,minfBox:()=>minfBox,mjp2SampleEntry:()=>mjp2SampleEntry,mjpgSampleEntry:()=>mjpgSampleEntry,moofBox:()=>moofBox,moovBox:()=>moovBox,mp4aSampleEntry:()=>mp4aSampleEntry,mp4sSampleEntry:()=>mp4sSampleEntry,mp4vSampleEntry:()=>mp4vSampleEntry,mskCBox:()=>mskCBox,msrcTrackGroupTypeBox:()=>msrcTrackGroupTypeBox,mvexBox:()=>mvexBox,mvhdBox:()=>mvhdBox,mvifSampleGroupEntry:()=>mvifSampleGroupEntry,nmhdBox:()=>nmhdBox,npckBox:()=>npckBox,numpBox:()=>numpBox,padbBox:()=>padbBox,panoBox:()=>panoBox,paspBox:()=>paspBox,paylBox:()=>paylBox,paytBox:()=>paytBox,pdinBox:()=>pdinBox,piffLsmBox:()=>piffLsmBox,piffPsshBox:()=>piffPsshBox,piffSencBox:()=>piffSencBox,piffTencBox:()=>piffTencBox,piffTfrfBox:()=>piffTfrfBox,piffTfxdBox:()=>piffTfxdBox,pitmBox:()=>pitmBox,pixiBox:()=>pixiBox,pmaxBox:()=>pmaxBox,povdBox:()=>povdBox,prdiBox:()=>prdiBox,prfrBox:()=>prfrBox,prftBox:()=>prftBox,prgrBox:()=>prgrBox,profBox:()=>profBox,prolSampleGroupEntry:()=>prolSampleGroupEntry,psshBox:()=>psshBox,pymdBox:()=>pymdBox,rapSampleGroupEntry:()=>rapSampleGroupEntry,rashSampleGroupEntry:()=>rashSampleGroupEntry,resvSampleEntry:()=>resvSampleEntry,rinfBox:()=>rinfBox,rollSampleGroupEntry:()=>rollSampleGroupEntry,rtp_Box:()=>rtp_Box,saioBox:()=>saioBox,saizBox:()=>saizBox,sbgpBox:()=>sbgpBox,sbpmBox:()=>sbpmBox,sbttSampleEntry:()=>sbttSampleEntry,schiBox:()=>schiBox,schmBox:()=>schmBox,scifSampleGroupEntry:()=>scifSampleGroupEntry,scnmSampleGroupEntry:()=>scnmSampleGroupEntry,sdp_Box:()=>sdp_Box,sdtpBox:()=>sdtpBox,seigSampleGroupEntry:()=>seigSampleGroupEntry,sencBox:()=>sencBox,sgpdBox:()=>sgpdBox,sidxBox:()=>sidxBox,sinfBox:()=>sinfBox,skipBox:()=>skipBox,slidBox:()=>slidBox,smhdBox:()=>smhdBox,sratBox:()=>sratBox,ssixBox:()=>ssixBox,stblBox:()=>stblBox,stcoBox:()=>stcoBox,stdpBox:()=>stdpBox,sterBox:()=>sterBox,sthdBox:()=>sthdBox,stppSampleEntry:()=>stppSampleEntry,strdBox:()=>strdBox,striBox:()=>striBox,strkBox:()=>strkBox,stsaSampleGroupEntry:()=>stsaSampleGroupEntry,stscBox:()=>stscBox,stsdBox:()=>stsdBox,stsgBox:()=>stsgBox,stshBox:()=>stshBox,stssBox:()=>stssBox,stszBox:()=>stszBox,sttsBox:()=>sttsBox,stviBox:()=>stviBox,stxtSampleEntry:()=>stxtSampleEntry,stypBox:()=>stypBox,stz2Box:()=>stz2Box,subsBox:()=>subsBox,syncSampleGroupEntry:()=>syncSampleGroupEntry,taicBox:()=>taicBox,taptBox:()=>taptBox,teleSampleGroupEntry:()=>teleSampleGroupEntry,tencBox:()=>tencBox,tfdtBox:()=>tfdtBox,tfhdBox:()=>tfhdBox,tfraBox:()=>tfraBox,tkhdBox:()=>tkhdBox,tmaxBox:()=>tmaxBox,tminBox:()=>tminBox,totlBox:()=>totlBox,tpayBox:()=>tpayBox,tpylBox:()=>tpylBox,trafBox:()=>trafBox,trakBox:()=>trakBox,trefBox:()=>trefBox,trepBox:()=>trepBox,trexBox:()=>trexBox,trgrBox:()=>trgrBox,trpyBox:()=>trpyBox,trunBox:()=>trunBox,tsasSampleGroupEntry:()=>tsasSampleGroupEntry,tsclSampleGroupEntry:()=>tsclSampleGroupEntry,tselBox:()=>tselBox,tsynBox:()=>tsynBox,tx3gSampleEntry:()=>tx3gSampleEntry,txtcBox:()=>txtcBox,tycoBox:()=>tycoBox,udesBox:()=>udesBox,udtaBox:()=>udtaBox,uncCBox:()=>uncCBox,uncvSampleEntry:()=>uncvSampleEntry,urlBox:()=>urlBox,urnBox:()=>urnBox,viprSampleGroupEntry:()=>viprSampleGroupEntry,vmhdBox:()=>vmhdBox,vp08SampleEntry:()=>vp08SampleEntry,vp09SampleEntry:()=>vp09SampleEntry,vpcCBox:()=>vpcCBox,vttCBox:()=>vttCBox,vttcBox:()=>vttcBox,vvc1SampleEntry:()=>vvc1SampleEntry,vvcCBox:()=>vvcCBox,vvcNSampleEntry:()=>vvcNSampleEntry,vvi1SampleEntry:()=>vvi1SampleEntry,vvnCBox:()=>vvnCBox,vvs1SampleEntry:()=>vvs1SampleEntry,waveBox:()=>waveBox,wbbrBox:()=>wbbrBox,wvttSampleEntry:()=>wvttSampleEntry,xmlBox:()=>xmlBox});var pn,a1lxBox=(pn=class extends Box{constructor(){super(...arguments),this.box_name="AV1LayeredImageIndexingProperty"}parse(o){const n=((o.readUint8()&1&1)+1)*16;this.layer_size=[];for(let r=0;r<3;r++)n===16?this.layer_size[r]=o.readUint16():this.layer_size[r]=o.readUint32()}},pn.fourcc="a1lx",pn),fn,a1opBox=(fn=class extends Box{constructor(){super(...arguments),this.box_name="OperatingPointSelectorProperty"}parse(o){this.op_index=o.readUint8()}},fn.fourcc="a1op",fn),hn,auxCBox=(hn=class extends FullBox{constructor(){super(...arguments),this.box_name="AuxiliaryTypeProperty"}parse(o){this.parseFullHeader(o),this.aux_type=o.readCString();const l=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=o.readUint8Array(l)}},hn.fourcc="auxC",hn),Rn,btrtBox=(Rn=class extends Box{constructor(){super(...arguments),this.box_name="BitRateBox"}parse(o){this.bufferSizeDB=o.readUint32(),this.maxBitrate=o.readUint32(),this.avgBitrate=o.readUint32()}},Rn.fourcc="btrt",Rn),Bn,ccstBox=(Bn=class extends FullBox{constructor(){super(...arguments),this.box_name="CodingConstraintsBox"}parse(o){this.parseFullHeader(o);const l=o.readUint8();this.all_ref_pics_intra=(l&128)===128,this.intra_pred_used=(l&64)===64,this.max_ref_per_pic=(l&63)>>2,o.readUint24()}},Bn.fourcc="ccst",Bn),Sn,cdefBox=(Sn=class extends Box{constructor(){super(...arguments),this.box_name="ComponentDefinitionBox"}parse(o){this.channel_count=o.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[];for(let l=0;l<this.channel_count;l++)this.channel_indexes.push(o.readUint16()),this.channel_types.push(o.readUint16()),this.channel_associations.push(o.readUint16())}},Sn.fourcc="cdef",Sn),yn,clapBox=(yn=class extends Box{constructor(){super(...arguments),this.box_name="CleanApertureBox"}parse(o){this.cleanApertureWidthN=o.readUint32(),this.cleanApertureWidthD=o.readUint32(),this.cleanApertureHeightN=o.readUint32(),this.cleanApertureHeightD=o.readUint32(),this.horizOffN=o.readUint32(),this.horizOffD=o.readUint32(),this.vertOffN=o.readUint32(),this.vertOffD=o.readUint32()}},yn.fourcc="clap",yn),Vn,clliBox=(Vn=class extends Box{constructor(){super(...arguments),this.box_name="ContentLightLevelBox"}parse(o){this.max_content_light_level=o.readUint16(),this.max_pic_average_light_level=o.readUint16()}},Vn.fourcc="clli",Vn),Jn,cmexBox=(Jn=class extends Box{constructor(){super(...arguments),this.box_name="CameraExtrinsicMatrixProperty"}parse(o){this.flags&1&&(this.pos_x=o.readInt32()),this.flags&2&&(this.pos_y=o.readInt32()),this.flags&4&&(this.pos_z=o.readInt32()),this.flags&8&&(this.version===0?this.flags&16?(this.quat_x=o.readInt32(),this.quat_y=o.readInt32(),this.quat_z=o.readInt32()):(this.quat_x=o.readInt16(),this.quat_y=o.readInt16(),this.quat_z=o.readInt16()):this.version),this.flags&32&&(this.id=o.readUint32())}},Jn.fourcc="cmex",Jn),En,cminBox=(En=class extends Box{constructor(){super(...arguments),this.box_name="CameraIntrinsicMatrixProperty"}parse(o){this.focal_length_x=o.readInt32(),this.principal_point_x=o.readInt32(),this.principal_point_y=o.readInt32(),this.flags&1&&(this.focal_length_y=o.readInt32(),this.skew_factor=o.readInt32())}},En.fourcc="cmin",En),mn,cmpdBox=(mn=class extends Box{constructor(){super(...arguments),this.box_name="ComponentDefinitionBox"}parse(o){this.component_count=o.readUint32(),this.component_types=[],this.component_type_urls=[];for(let l=0;l<this.component_count;l++){const n=o.readUint16();this.component_types.push(n),n>=32768&&this.component_type_urls.push(o.readCString())}}},mn.fourcc="cmpd",mn),kn,co64Box=(kn=class extends FullBox{constructor(){super(...arguments),this.box_name="ChunkLargeOffsetBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.chunk_offsets=[],this.version===0)for(let n=0;n<l;n++)this.chunk_offsets.push(o.readUint64())}write(o){this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(o),o.writeUint32(this.chunk_offsets.length);for(let l=0;l<this.chunk_offsets.length;l++)o.writeUint64(this.chunk_offsets[l])}},kn.fourcc="co64",kn),Nn,CoLLBox=(Nn=class extends FullBox{constructor(){super(...arguments),this.box_name="ContentLightLevelBox"}parse(o){this.parseFullHeader(o),this.maxCLL=o.readUint16(),this.maxFALL=o.readUint16()}},Nn.fourcc="CoLL",Nn),SphereRegion=class{toString(){let u="centre_azimuth: ";return u+=this.centre_azimuth,u+=" (",u+=this.centre_azimuth*2**-16,u+="°), centre_elevation: ",u+=this.centre_elevation,u+=" (",u+=this.centre_elevation*2**-16,u+="°), centre_tilt: ",u+=this.centre_tilt,u+=" (",u+=this.centre_tilt*2**-16,u+="°)",this.range_included_flag&&(u+=", azimuth_range: ",u+=this.azimuth_range,u+=" (",u+=this.azimuth_range*2**-16,u+="°), elevation_range: ",u+=this.elevation_range,u+=" (",u+=this.elevation_range*2**-16,u+="°)"),this.interpolate_included_flag&&(u+=", interpolate: ",u+=this.interpolate),u}},CoverageSphereRegion=class{toString(){let u="";return this.view_idc&&(u+="view_idc: ",u+=this.view_idc,u+=", "),u+="sphere_region: {",u+=this.sphere_region,u+="}",u}},Tn,coviBox=(Tn=class extends FullBox{constructor(){super(...arguments),this.box_name="CoverageInformationBox"}parse(o){this.parseFullHeader(o),this.coverage_shape_type=o.readUint8();const l=o.readUint8(),n=o.readInt8(),r=n&128;r&&(this.default_view_idc=(n&96)>>5),this.coverage_regions=new Array;for(let t=0;t<l;t++){const e=new CoverageSphereRegion;r&&(e.view_idc=o.readUint8()>>6),e.sphere_region=this.parseSphereRegion(o,!0,!0),this.coverage_regions.push(e)}}parseSphereRegion(o,l,n){const r=new SphereRegion;return r.centre_azimuth=o.readInt32(),r.centre_elevation=o.readInt32(),r.centre_tilt=o.readInt32(),r.range_included_flag=l,l&&(r.azimuth_range=o.readUint32(),r.elevation_range=o.readUint32()),r.interpolate_included_flag=n,n&&(r.interpolate=(o.readUint8()&128)===128),r}},Tn.fourcc="covi",Tn),vn,cprtBox=(vn=class extends FullBox{constructor(){super(...arguments),this.box_name="CopyrightBox"}parse(o){this.parseFullHeader(o),this.parseLanguage(o),this.notice=o.readCString()}},vn.fourcc="cprt",vn),Cn,cschBox=(Cn=class extends FullBox{constructor(){super(...arguments),this.box_name="CompatibleSchemeTypeBox"}parse(o){this.parseFullHeader(o),this.scheme_type=o.readString(4),this.scheme_version=o.readUint32(),this.flags&1&&(this.scheme_uri=o.readCString())}},Cn.fourcc="csch",Cn),INT32_MAX=2147483647,Wn,cslgBox=(Wn=class extends FullBox{constructor(){super(...arguments),this.box_name="CompositionToDecodeBox"}parse(o){this.parseFullHeader(o),this.version===0?(this.compositionToDTSShift=o.readInt32(),this.leastDecodeToDisplayDelta=o.readInt32(),this.greatestDecodeToDisplayDelta=o.readInt32(),this.compositionStartTime=o.readInt32(),this.compositionEndTime=o.readInt32()):this.version===1&&(this.compositionToDTSShift=o.readInt64(),this.leastDecodeToDisplayDelta=o.readInt64(),this.greatestDecodeToDisplayDelta=o.readInt64(),this.compositionStartTime=o.readInt64(),this.compositionEndTime=o.readInt64())}write(o){this.version=0,(this.compositionToDTSShift>INT32_MAX||this.leastDecodeToDisplayDelta>INT32_MAX||this.greatestDecodeToDisplayDelta>INT32_MAX||this.compositionStartTime>INT32_MAX||this.compositionEndTime>INT32_MAX)&&(this.version=1),this.flags=0,this.version===0?(this.size=4*5,this.writeHeader(o),o.writeInt32(this.compositionToDTSShift),o.writeInt32(this.leastDecodeToDisplayDelta),o.writeInt32(this.greatestDecodeToDisplayDelta),o.writeInt32(this.compositionStartTime),o.writeInt32(this.compositionEndTime)):this.version===1&&(this.size=8*5,this.writeHeader(o),o.writeInt64(this.compositionToDTSShift),o.writeInt64(this.leastDecodeToDisplayDelta),o.writeInt64(this.greatestDecodeToDisplayDelta),o.writeInt64(this.compositionStartTime),o.writeInt64(this.compositionEndTime))}},Wn.fourcc="cslg",Wn),bn,cttsBox=(bn=class extends FullBox{constructor(){super(...arguments),this.box_name="CompositionOffsetBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.sample_counts=[],this.sample_offsets=[],this.version===0)for(let n=0;n<l;n++){this.sample_counts.push(o.readUint32());const r=o.readInt32();r<0&&Log.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(r)}else if(this.version===1)for(let n=0;n<l;n++)this.sample_counts.push(o.readUint32()),this.sample_offsets.push(o.readInt32())}write(o){this.version=this.sample_offsets.some(l=>l<0)?1:0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(o),o.writeUint32(this.sample_counts.length);for(let l=0;l<this.sample_counts.length;l++)o.writeUint32(this.sample_counts[l]),this.version===1?o.writeInt32(this.sample_offsets[l]):o.writeUint32(this.sample_offsets[l])}unpack(o){let l=0;for(let n=0;n<this.sample_counts.length;n++)for(let r=0;r<this.sample_counts[n];r++)o[l].pts=o[l].dts+this.sample_offsets[n],l++}},bn.fourcc="ctts",bn),On,dac3Box=(On=class extends Box{constructor(){super(...arguments),this.box_name="AC3SpecificBox"}parse(o){const l=o.readUint8(),n=o.readUint8(),r=o.readUint8();this.fscod=l>>6,this.bsid=l>>1&31,this.bsmod=(l&1)<<2|n>>6&3,this.acmod=n>>3&7,this.lfeon=n>>2&1,this.bit_rate_code=n&3|r>>5&7}},On.fourcc="dac3",On),Zn,dec3Box=(Zn=class extends Box{constructor(){super(...arguments),this.box_name="EC3SpecificBox"}parse(o){const l=o.readUint16();this.data_rate=l>>3,this.num_ind_sub=l&7,this.ind_subs=[];for(let n=0;n<this.num_ind_sub+1;n++){const r=o.readUint8(),t=o.readUint8(),e=o.readUint8(),i={fscod:r>>6,bsid:r>>1&31,bsmod:(r&1)<<4|t>>4&15,acmod:t>>1&7,lfeon:t&1,num_dep_sub:e>>1&15};this.ind_subs.push(i),i.num_dep_sub>0&&(i.chan_loc=(e&1)<<8|o.readUint8())}}},Zn.fourcc="dec3",Zn),Dn,dfLaBox=(Dn=class extends FullBox{constructor(){super(...arguments),this.box_name="FLACSpecificBox"}parse(o){this.parseFullHeader(o);const l=127,n=128,r=[],t=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];let e;do{e=o.readUint8();const i=Math.min(e&l,t.length-1);i?o.readUint8Array(o.readUint24()):(o.readUint8Array(13),this.samplerate=o.readUint32()>>12,o.readUint8Array(20)),r.push(t[i])}while(e&n);this.numMetadataBlocks=r.length+" ("+r.join(", ")+")"}},Dn.fourcc="dfLa",Dn),wn,dimmBox=(wn=class extends Box{constructor(){super(...arguments),this.box_name="hintimmediateBytesSent"}parse(o){this.bytessent=o.readUint64()}},wn.fourcc="dimm",wn),gn,dmax=(gn=class extends Box{constructor(){super(...arguments),this.box_name="hintlongestpacket"}parse(o){this.time=o.readUint32()}},gn.fourcc="dmax",gn),xn,dmedBox=(xn=class extends Box{constructor(){super(...arguments),this.box_name="hintmediaBytesSent"}parse(o){this.bytessent=o.readUint64()}},xn.fourcc="dmed",xn),In,dOpsBox=(In=class extends Box{constructor(){super(...arguments),this.box_name="OpusSpecificBox"}parse(o){if(this.Version=o.readUint8(),this.OutputChannelCount=o.readUint8(),this.PreSkip=o.readUint16(),this.InputSampleRate=o.readUint32(),this.OutputGain=o.readInt16(),this.ChannelMappingFamily=o.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=o.readUint8(),this.CoupledCount=o.readUint8(),this.ChannelMapping=[];for(let l=0;l<this.OutputChannelCount;l++)this.ChannelMapping[l]=o.readUint8()}}write(o){if(this.size=11,this.ChannelMappingFamily!==0&&(this.size+=2+this.OutputChannelCount),this.writeHeader(o),o.writeUint8(this.Version),o.writeUint8(this.OutputChannelCount),o.writeUint16(this.PreSkip),o.writeUint32(this.InputSampleRate),o.writeInt16(this.OutputGain),o.writeUint8(this.ChannelMappingFamily),this.ChannelMappingFamily!==0){o.writeUint8(this.StreamCount),o.writeUint8(this.CoupledCount);for(let l=0;l<this.OutputChannelCount;l++)o.writeUint8(this.ChannelMapping[l])}}},In.fourcc="dOps",In),Mn,drepBox=(Mn=class extends Box{constructor(){super(...arguments),this.box_name="hintrepeatedBytesSent"}parse(o){this.bytessent=o.readUint64()}},Mn.fourcc="drep",Mn),_n,elstBox=(_n=class extends FullBox{constructor(){super(...arguments),this.box_name="EditListBox"}parse(o){this.parseFullHeader(o),this.entries=[];const l=o.readUint32();for(let n=0;n<l;n++){const r={segment_duration:this.version===1?o.readUint64():o.readUint32(),media_time:this.version===1?o.readInt64():o.readInt32(),media_rate_integer:o.readInt16(),media_rate_fraction:o.readInt16()};this.entries.push(r)}}write(o){const l=this.entries.some(n=>n.segment_duration>MAX_UINT32||n.media_time>MAX_UINT32)||this.version===1;this.version=l?1:0,this.size=4+12*this.entries.length,this.size+=l?2*4*this.entries.length:0,this.writeHeader(o),o.writeUint32(this.entries.length);for(let n=0;n<this.entries.length;n++){const r=this.entries[n];l?(o.writeUint64(r.segment_duration),o.writeInt64(r.media_time)):(o.writeUint32(r.segment_duration),o.writeInt32(r.media_time)),o.writeInt16(r.media_rate_integer),o.writeInt16(r.media_rate_fraction)}}},_n.fourcc="elst",_n),Pn,emsgBox=(Pn=class extends FullBox{constructor(){super(...arguments),this.box_name="EventMessageBox"}parse(o){this.parseFullHeader(o),this.version===1?(this.timescale=o.readUint32(),this.presentation_time=o.readUint64(),this.event_duration=o.readUint32(),this.id=o.readUint32(),this.scheme_id_uri=o.readCString(),this.value=o.readCString()):(this.scheme_id_uri=o.readCString(),this.value=o.readCString(),this.timescale=o.readUint32(),this.presentation_time_delta=o.readUint32(),this.event_duration=o.readUint32(),this.id=o.readUint32());let l=this.size-this.hdr_size-(4*4+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version===1&&(l-=4),this.message_data=o.readUint8Array(l)}write(o){this.version=0,this.flags=0,this.size=4*4+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(o),o.writeCString(this.scheme_id_uri),o.writeCString(this.value),o.writeUint32(this.timescale),o.writeUint32(this.presentation_time_delta),o.writeUint32(this.event_duration),o.writeUint32(this.id),o.writeUint8Array(this.message_data)}},Pn.fourcc="emsg",Pn),EntityToGroup=class extends FullBox{parse(u){this.parseFullHeader(u),this.group_id=u.readUint32(),this.num_entities_in_group=u.readUint32(),this.entity_ids=[];for(let o=0;o<this.num_entities_in_group;o++){const l=u.readUint32();this.entity_ids.push(l)}}},$n,aebrBox=($n=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Auto exposure bracketing"}},$n.fourcc="aebr",$n),Ln,afbrBox=(Ln=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Flash exposure information"}},Ln.fourcc="afbr",Ln),An,albcBox=(An=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Album collection"}},An.fourcc="albc",An),Gn,altrBox=(Gn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Alternative entity"}},Gn.fourcc="altr",Gn),Hn,brstBox=(Hn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Burst image"}},Hn.fourcc="brst",Hn),zn,dobrBox=(zn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Depth of field bracketing"}},zn.fourcc="dobr",zn),Yn,eqivBox=(Yn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Equivalent entity"}},Yn.fourcc="eqiv",Yn),jn,favcBox=(jn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Favorites collection"}},jn.fourcc="favc",jn),Xn,fobrBox=(Xn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Focus bracketing"}},Xn.fourcc="fobr",Xn),qn,iaugBox=(qn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Image item with an audio track"}},qn.fourcc="iaug",qn),Kn,panoBox=(Kn=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Panorama"}},Kn.fourcc="pano",Kn),ti,slidBox=(ti=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Slideshow"}},ti.fourcc="slid",ti),ei,sterBox=(ei=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Stereo"}},ei.fourcc="ster",ei),ni,tsynBox=(ni=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Time-synchronized capture"}},ni.fourcc="tsyn",ni),ii,wbbrBox=(ii=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="White balance bracketing"}},ii.fourcc="wbbr",ii),oi,prgrBox=(oi=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Progressive rendering"}},oi.fourcc="prgr",oi),ri,pymdBox=(ri=class extends EntityToGroup{constructor(){super(...arguments),this.box_name="Image pyramid"}parse(o){this.parseFullHeader(o),this.group_id=o.readUint32(),this.num_entities_in_group=o.readUint32(),this.entity_ids=[];for(let l=0;l<this.num_entities_in_group;l++){const n=o.readUint32();this.entity_ids.push(n)}this.tile_size_x=o.readUint16(),this.tile_size_y=o.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[];for(let l=0;l<this.num_entities_in_group;l++)this.layer_binning[l]=o.readUint16(),this.tiles_in_layer_row_minus1[l]=o.readUint16(),this.tiles_in_layer_column_minus1[l]=o.readUint16()}},ri.fourcc="pymd",ri),li,fielBox=(li=class extends Box{constructor(){super(...arguments),this.box_name="FieldHandlingBox"}parse(o){this.fieldCount=o.readUint8(),this.fieldOrdering=o.readUint8()}},li.fourcc="fiel",li),ai,frmaBox=(ai=class extends Box{constructor(){super(...arguments),this.box_name="OriginalFormatBox"}parse(o){this.data_format=o.readString(4)}},ai.fourcc="frma",ai),si,imirBox=(si=class extends Box{constructor(){super(...arguments),this.box_name="ImageMirror"}parse(o){const l=o.readUint8();this.reserved=l>>7,this.axis=l&1}},si.fourcc="imir",si),di,ipmaBox=(di=class extends FullBox{constructor(){super(...arguments),this.box_name="ItemPropertyAssociationBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();this.associations=[];for(let n=0;n<l;n++){const r=this.version<1?o.readUint16():o.readUint32(),t=[],e=o.readUint8();for(let i=0;i<e;i++){const a=o.readUint8();t.push({essential:(a&128)>>7===1,property_index:this.flags&1?(a&127)<<8|o.readUint8():a&127})}this.associations.push({id:r,props:t})}}},di.fourcc="ipma",di),ui,irotBox=(ui=class extends Box{constructor(){super(...arguments),this.box_name="ImageRotation"}parse(o){this.angle=o.readUint8()&3}},ui.fourcc="irot",ui),ci,ispeBox=(ci=class extends FullBox{constructor(){super(...arguments),this.box_name="ImageSpatialExtentsProperty"}parse(o){this.parseFullHeader(o),this.image_width=o.readUint32(),this.image_height=o.readUint32()}},ci.fourcc="ispe",ci),Ui,itaiBox=(Ui=class extends FullBox{constructor(){super(...arguments),this.box_name="TAITimestampBox"}parse(o){this.TAI_timestamp=o.readUint64();const l=o.readUint8();this.sychronization_state=l>>7&1,this.timestamp_generation_failure=l>>6&1,this.timestamp_is_modified=l>>5&1}},Ui.fourcc="itai",Ui),Fi,kindBox=(Fi=class extends FullBox{constructor(){super(...arguments),this.box_name="KindBox"}parse(o){this.parseFullHeader(o),this.schemeURI=o.readCString(),this.isEndOfBox(o)||(this.value=o.readCString())}write(o){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value?this.value.length+1:0),this.writeHeader(o),o.writeCString(this.schemeURI),this.value&&o.writeCString(this.value)}},Fi.fourcc="kind",Fi),Qi,levaBox=(Qi=class extends FullBox{constructor(){super(...arguments),this.box_name="LevelAssignmentBox"}parse(o){this.parseFullHeader(o);const l=o.readUint8();this.levels=[];for(let n=0;n<l;n++){const r={};this.levels[n]=r,r.track_ID=o.readUint32();const t=o.readUint8();switch(r.padding_flag=t>>7,r.assignment_type=t&127,r.assignment_type){case 0:r.grouping_type=o.readString(4);break;case 1:r.grouping_type=o.readString(4),r.grouping_type_parameter=o.readUint32();break;case 2:break;case 3:break;case 4:r.sub_track_id=o.readUint32();break;default:Log.warn("BoxParser",`Unknown level assignment type: ${r.assignment_type}`)}}}},Qi.fourcc="leva",Qi),pi,lhvCBox=(pi=class extends Box{constructor(){super(...arguments),this.box_name="LHEVCConfigurationBox"}parse(o){this.configurationVersion=o.readUint8(),this.min_spatial_segmentation_idc=o.readUint16()&4095,this.parallelismType=o.readUint8()&3;let l=o.readUint8();this.numTemporalLayers=(l&13)>>3,this.temporalIdNested=(l&4)>>2,this.lengthSizeMinusOne=l&3,this.nalu_arrays=[];const n=o.readUint8();for(let r=0;r<n;r++){const t=[];this.nalu_arrays.push(t),l=o.readUint8(),t.completeness=(l&128)>>7,t.nalu_type=l&63;const e=o.readUint16();for(let i=0;i<e;i++){const a=o.readUint16();t.push({data:o.readUint8Array(a)})}}}},pi.fourcc="lhvC",pi),fi,lselBox=(fi=class extends Box{constructor(){super(...arguments),this.box_name="LayerSelectorProperty"}parse(o){this.layer_id=o.readUint16()}},fi.fourcc="lsel",fi),hi,maxrBox=(hi=class extends Box{constructor(){super(...arguments),this.box_name="hintmaxrate"}parse(o){this.period=o.readUint32(),this.bytes=o.readUint32()}},hi.fourcc="maxr",hi),ColorPoint=class{constructor(u,o){this.x=u,this.y=o}toString(){return"("+this.x+","+this.y+")"}},Ri,mdcvBox=(Ri=class extends Box{constructor(){super(...arguments),this.box_name="MasteringDisplayColourVolumeBox"}parse(o){this.display_primaries=[],this.display_primaries[0]=new ColorPoint(o.readUint16(),o.readUint16()),this.display_primaries[1]=new ColorPoint(o.readUint16(),o.readUint16()),this.display_primaries[2]=new ColorPoint(o.readUint16(),o.readUint16()),this.white_point=new ColorPoint(o.readUint16(),o.readUint16()),this.max_display_mastering_luminance=o.readUint32(),this.min_display_mastering_luminance=o.readUint32()}},Ri.fourcc="mdcv",Ri),Bi,mfroBox=(Bi=class extends FullBox{constructor(){super(...arguments),this.box_name="MovieFragmentRandomAccessOffsetBox"}parse(o){this.parseFullHeader(o),this._size=o.readUint32()}},Bi.fourcc="mfro",Bi),Si,mskCBox=(Si=class extends FullBox{constructor(){super(...arguments),this.box_name="MaskConfigurationProperty"}parse(o){this.parseFullHeader(o),this.bits_per_pixel=o.readUint8()}},Si.fourcc="mskC",Si),yi,npckBox=(yi=class extends Box{constructor(){super(...arguments),this.box_name="hintPacketsSent"}parse(o){this.packetssent=o.readUint32()}},yi.fourcc="npck",yi),Vi,numpBox=(Vi=class extends Box{constructor(){super(...arguments),this.box_name="hintPacketsSent"}parse(o){this.packetssent=o.readUint64()}},Vi.fourcc="nump",Vi),PaddingBit=class{constructor(u,o){this.pad1=u,this.pad2=o}},Ji,padbBox=(Ji=class extends FullBox{constructor(){super(...arguments),this.box_name="PaddingBitsBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();this.padbits=[];for(let n=0;n<Math.floor((l+1)/2);n++){const r=o.readUint8(),t=(r&112)>>4,e=r&7;this.padbits.push(new PaddingBit(t,e))}}},Ji.fourcc="padb",Ji),Ei,paspBox=(Ei=class extends Box{constructor(){super(...arguments),this.box_name="PixelAspectRatioBox"}parse(o){this.hSpacing=o.readUint32(),this.vSpacing=o.readUint32()}},Ei.fourcc="pasp",Ei),mi,paylBox=(mi=class extends Box{constructor(){super(...arguments),this.box_name="CuePayloadBox"}parse(o){this.text=o.readString(this.size-this.hdr_size)}},mi.fourcc="payl",mi),ki,paytBox=(ki=class extends Box{constructor(){super(...arguments),this.box_name="hintpayloadID"}parse(o){this.payloadID=o.readUint32();const l=o.readUint8();this.rtpmap_string=o.readString(l)}},ki.fourcc="payt",ki),Ni,pdinBox=(Ni=class extends FullBox{constructor(){super(...arguments),this.box_name="ProgressiveDownloadInfoBox",this.rate=[],this.initial_delay=[]}parse(o){this.parseFullHeader(o);const l=(this.size-this.hdr_size)/8;for(let n=0;n<l;n++)this.rate[n]=o.readUint32(),this.initial_delay[n]=o.readUint32()}},Ni.fourcc="pdin",Ni),Ti,pixiBox=(Ti=class extends FullBox{constructor(){super(...arguments),this.box_name="PixelInformationProperty"}parse(o){this.parseFullHeader(o),this.num_channels=o.readUint8(),this.bits_per_channels=[];for(let l=0;l<this.num_channels;l++)this.bits_per_channels[l]=o.readUint8()}},Ti.fourcc="pixi",Ti),vi,pmaxBox=(vi=class extends Box{constructor(){super(...arguments),this.box_name="hintlargestpacket"}parse(o){this.bytes=o.readUint32()}},vi.fourcc="pmax",vi),Ci,prdiBox=(Ci=class extends FullBox{constructor(){super(...arguments),this.box_name="ProgressiveDerivedImageItemInformationProperty"}parse(o){if(this.parseFullHeader(o),this.step_count=o.readUint16(),this.item_count=[],this.flags&2)for(let l=0;l<this.step_count;l++)this.item_count[l]=o.readUint16()}},Ci.fourcc="prdi",Ci),Wi,prfrBox=(Wi=class extends FullBox{constructor(){super(...arguments),this.box_name="ProjectionFormatBox"}parse(o){this.parseFullHeader(o),this.projection_type=o.readUint8()&31}},Wi.fourcc="prfr",Wi),bi,prftBox=(bi=class extends FullBox{constructor(){super(...arguments),this.box_name="ProducerReferenceTimeBox"}parse(o){this.parseFullHeader(o),this.ref_track_id=o.readUint32(),this.ntp_timestamp=o.readUint64(),this.version===0?this.media_time=o.readUint32():this.media_time=o.readUint64()}},bi.fourcc="prft",bi),Oi,psshBox=(Oi=class extends FullBox{constructor(){super(...arguments),this.box_name="ProtectionSystemSpecificHeaderBox"}parse(o){if(this.parseFullHeader(o),this.system_id=parseHex16(o),this.kid=[],this.version>0){const n=o.readUint32();for(let r=0;r<n;r++)this.kid[r]=parseHex16(o)}const l=o.readUint32();l>0&&(this.protection_data=o.readUint8Array(l))}},Oi.fourcc="pssh",Oi),Zi,clefBox=(Zi=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackCleanApertureDimensionsBox"}parse(o){this.parseFullHeader(o),this.width=o.readUint32(),this.height=o.readUint32()}},Zi.fourcc="clef",Zi);function parseItifData(u,o){if(u===dataBox.Types.UTF8)return new TextDecoder("utf-8").decode(o);const l=new DataView(o.buffer);if(u===dataBox.Types.BE_UNSIGNED_INT){if(o.length===1)return l.getUint8(0);if(o.length===2)return l.getUint16(0,!1);if(o.length===4)return l.getUint32(0,!1);if(o.length===8)return l.getBigUint64(0,!1);throw new Error("Unsupported ITIF_TYPE_BE_UNSIGNED_INT length "+o.length)}else if(u===dataBox.Types.BE_SIGNED_INT){if(o.length===1)return l.getInt8(0);if(o.length===2)return l.getInt16(0,!1);if(o.length===4)return l.getInt32(0,!1);if(o.length===8)return l.getBigInt64(0,!1);throw new Error("Unsupported ITIF_TYPE_BE_SIGNED_INT length "+o.length)}else if(u===dataBox.Types.BE_FLOAT32)return l.getFloat32(0,!1);Log.warn("DataBox","Unsupported or unimplemented itif data type: "+u)}var _,dataBox=(_=class extends Box{constructor(){super(...arguments),this.box_name="DataBox"}parse(o){this.valueType=o.readUint32(),this.country=o.readUint16(),this.country>255&&(o.seek(o.getPosition()-2),this.countryString=o.readString(2)),this.language=o.readUint16(),this.language>255&&(o.seek(o.getPosition()-2),this.parseLanguage(o)),this.raw=o.readUint8Array(this.size-this.hdr_size-8),this.value=parseItifData(this.valueType,this.raw)}},_.fourcc="data",_.Types={RESERVED:0,UTF8:1,UTF16:2,SJIS:3,UTF8_SORT:4,UTF16_SORT:5,JPEG:13,PNG:14,BE_SIGNED_INT:21,BE_UNSIGNED_INT:22,BE_FLOAT32:23,BE_FLOAT64:24,BMP:27,QT_ATOM:28,BE_SIGNED_INT8:65,BE_SIGNED_INT16:66,BE_SIGNED_INT32:67,BE_FLOAT32_POINT:70,BE_FLOAT32_DIMENSIONS:71,BE_FLOAT32_RECT:72,BE_SIGNED_INT64:74,BE_UNSIGNED_INT8:75,BE_UNSIGNED_INT16:76,BE_UNSIGNED_INT32:77,BE_UNSIGNED_INT64:78,BE_FLOAT64_AFFINE_TRANSFORM:79},_),Di,enofBox=(Di=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackEncodedPixelsDimensionsBox"}parse(o){this.parseFullHeader(o),this.width=o.readUint32(),this.height=o.readUint32()}},Di.fourcc="enof",Di),wi,ilstBox=(wi=class extends Box{constructor(){super(...arguments),this.box_name="IlstBox"}parse(o){this.list={};let l=this.size-this.hdr_size;for(;l>0;){const n=o.readUint32(),r=o.readUint32(),t=parseOneBox(o,!1,n-8);t.code===OK&&(this.list[r]=t.box),l-=n}}},wi.fourcc="ilst",wi),gi,keysBox=(gi=class extends FullBox{constructor(){super(...arguments),this.box_name="KeysBox"}parse(o){this.parseFullHeader(o),this.count=o.readUint32(),this.keys={};for(let l=0;l<this.count;l++){const n=o.readUint32();this.keys[l+1]=o.readString(n-4)}}},gi.fourcc="keys",gi),xi,profBox=(xi=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackProductionApertureDimensionsBox"}parse(o){this.parseFullHeader(o),this.width=o.readUint32(),this.height=o.readUint32()}},xi.fourcc="prof",xi),Ii,taptBox=(Ii=class extends ContainerBox{constructor(){super(...arguments),this.box_name="TrackApertureModeDimensionsBox",this.clefs=[],this.profs=[],this.enofs=[],this.subBoxNames=["clef","prof","enof"]}},Ii.fourcc="tapt",Ii),Mi,waveBox=(Mi=class extends ContainerBox{constructor(){super(...arguments),this.box_name="siDecompressionParamBox"}},Mi.fourcc="wave",Mi),_i,rtp_Box=(_i=class extends Box{constructor(){super(...arguments),this.box_name="rtpmoviehintinformation"}parse(o){this.descriptionformat=o.readString(4),this.sdptext=o.readString(this.size-this.hdr_size-4)}},_i.fourcc="rtp ",_i),Pi,saioBox=(Pi=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleAuxiliaryInformationOffsetsBox"}parse(o){this.parseFullHeader(o),this.flags&1&&(this.aux_info_type=o.readString(4),this.aux_info_type_parameter=o.readUint32());const l=o.readUint32();this.offset=[];for(let n=0;n<l;n++)this.version===0?this.offset[n]=o.readUint32():this.offset[n]=o.readUint64()}},Pi.fourcc="saio",Pi),$i,saizBox=($i=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleAuxiliaryInformationSizesBox"}parse(o){if(this.parseFullHeader(o),this.flags&1&&(this.aux_info_type=o.readString(4),this.aux_info_type_parameter=o.readUint32()),this.default_sample_info_size=o.readUint8(),this.sample_count=o.readUint32(),this.sample_info_size=[],this.default_sample_info_size===0)for(let l=0;l<this.sample_count;l++)this.sample_info_size[l]=o.readUint8()}},$i.fourcc="saiz",$i),Pixel=class{constructor(u,o){this.bad_pixel_row=u,this.bad_pixel_column=o}toString(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"}},Li,sbpmBox=(Li=class extends FullBox{constructor(){super(...arguments),this.box_name="SensorBadPixelsMapBox"}parse(o){this.parseFullHeader(o),this.component_count=o.readUint16(),this.component_index=[];for(let n=0;n<this.component_count;n++)this.component_index.push(o.readUint16());const l=o.readUint8();this.correction_applied=(l&128)===128,this.num_bad_rows=o.readUint32(),this.num_bad_cols=o.readUint32(),this.num_bad_pixels=o.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[];for(let n=0;n<this.num_bad_rows;n++)this.bad_rows.push(o.readUint32());for(let n=0;n<this.num_bad_cols;n++)this.bad_columns.push(o.readUint32());for(let n=0;n<this.num_bad_pixels;n++){const r=o.readUint32(),t=o.readUint32();this.bad_pixels.push(new Pixel(r,t))}}},Li.fourcc="sbpm",Li),Ai,schmBox=(Ai=class extends FullBox{constructor(){super(...arguments),this.box_name="SchemeTypeBox"}parse(o){this.parseFullHeader(o),this.scheme_type=o.readString(4),this.scheme_version=o.readUint32(),this.flags&1&&(this.scheme_uri=o.readString(this.size-this.hdr_size-8))}},Ai.fourcc="schm",Ai),Gi,sdp_Box=(Gi=class extends Box{constructor(){super(...arguments),this.box_name="rtptracksdphintinformation"}parse(o){this.sdptext=o.readString(this.size-this.hdr_size)}},Gi.fourcc="sdp ",Gi),Hi,sencBox=(Hi=class extends FullBox{constructor(){super(...arguments),this.box_name="SampleEncryptionBox"}},Hi.fourcc="senc",Hi),zi,SmDmBox=(zi=class extends FullBox{constructor(){super(...arguments),this.box_name="SMPTE2086MasteringDisplayMetadataBox"}parse(o){this.parseFullHeader(o),this.primaryRChromaticity_x=o.readUint16(),this.primaryRChromaticity_y=o.readUint16(),this.primaryGChromaticity_x=o.readUint16(),this.primaryGChromaticity_y=o.readUint16(),this.primaryBChromaticity_x=o.readUint16(),this.primaryBChromaticity_y=o.readUint16(),this.whitePointChromaticity_x=o.readUint16(),this.whitePointChromaticity_y=o.readUint16(),this.luminanceMax=o.readUint32(),this.luminanceMin=o.readUint32()}},zi.fourcc="SmDm",zi),Yi,sratBox=(Yi=class extends FullBox{constructor(){super(...arguments),this.box_name="SamplingRateBox"}parse(o){this.parseFullHeader(o),this.sampling_rate=o.readUint32()}},Yi.fourcc="srat",Yi),ji,ssixBox=(ji=class extends FullBox{constructor(){super(...arguments),this.box_name="CompressedSubsegmentIndexBox"}parse(o){this.parseFullHeader(o),this.subsegments=[];const l=o.readUint32();for(let n=0;n<l;n++){const r={};this.subsegments.push(r),r.ranges=[];const t=o.readUint32();for(let e=0;e<t;e++){const i={};r.ranges.push(i),i.level=o.readUint8(),i.range_size=o.readUint24()}}}},ji.fourcc="ssix",ji),Xi,stdpBox=(Xi=class extends FullBox{constructor(){super(...arguments),this.box_name="DegradationPriorityBox"}parse(o){this.parseFullHeader(o);const l=(this.size-this.hdr_size)/2;this.priority=[];for(let n=0;n<l;n++)this.priority[n]=o.readUint16()}},Xi.fourcc="stpd",Xi),qi,striBox=(qi=class extends FullBox{constructor(){super(...arguments),this.box_name="SubTrackInformationBox"}parse(o){this.parseFullHeader(o),this.switch_group=o.readUint16(),this.alternate_group=o.readUint16(),this.sub_track_id=o.readUint32();const l=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(let n=0;n<l;n++)this.attribute_list[n]=o.readUint32()}},qi.fourcc="stri",qi),Ki,stsgBox=(Ki=class extends FullBox{constructor(){super(...arguments),this.box_name="SubTrackSampleGroupBox"}parse(o){this.parseFullHeader(o),this.grouping_type=o.readUint32();const l=o.readUint16();this.group_description_index=[];for(let n=0;n<l;n++)this.group_description_index[n]=o.readUint32()}},Ki.fourcc="stsg",Ki),to,stshBox=(to=class extends FullBox{constructor(){super(...arguments),this.box_name="ShadowSyncSampleBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(let n=0;n<l;n++)this.shadowed_sample_numbers.push(o.readUint32()),this.sync_sample_numbers.push(o.readUint32())}write(o){this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(o),o.writeUint32(this.shadowed_sample_numbers.length);for(let l=0;l<this.shadowed_sample_numbers.length;l++)o.writeUint32(this.shadowed_sample_numbers[l]),o.writeUint32(this.sync_sample_numbers[l])}},to.fourcc="stsh",to),eo,stssBox=(eo=class extends FullBox{constructor(){super(...arguments),this.box_name="SyncSampleBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();if(this.version===0){this.sample_numbers=[];for(let n=0;n<l;n++)this.sample_numbers.push(o.readUint32())}}write(o){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(o),o.writeUint32(this.sample_numbers.length),o.writeUint32Array(this.sample_numbers)}},eo.fourcc="stss",eo),no,stviBox=(no=class extends FullBox{constructor(){super(...arguments),this.box_name="StereoVideoBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();this.single_view_allowed=l&3,this.stereo_scheme=o.readUint32();const n=o.readUint32();for(this.stereo_indication_type=o.readString(n),this.boxes=[];o.getPosition()<this.start+this.size;){const r=parseOneBox(o,!1,this.size-(o.getPosition()-this.start));if(r.code===OK){const t=r.box;this.boxes.push(t),this[t.type]=t}else return}}},no.fourcc="stvi",no),io,stypBox=(io=class extends Box{constructor(){super(...arguments),this.box_name="SegmentTypeBox"}parse(o){let l=this.size-this.hdr_size;this.major_brand=o.readString(4),this.minor_version=o.readUint32(),l-=8,this.compatible_brands=[];let n=0;for(;l>=4;)this.compatible_brands[n]=o.readString(4),l-=4,n++}write(o){this.size=8+4*this.compatible_brands.length,this.writeHeader(o),o.writeString(this.major_brand,void 0,4),o.writeUint32(this.minor_version);for(let l=0;l<this.compatible_brands.length;l++)o.writeString(this.compatible_brands[l],void 0,4)}},io.fourcc="styp",io),oo,stz2Box=(oo=class extends FullBox{constructor(){super(...arguments),this.box_name="CompactSampleSizeBox"}parse(o){if(this.parseFullHeader(o),this.sample_sizes=[],this.version===0){this.reserved=o.readUint24(),this.field_size=o.readUint8();const l=o.readUint32();if(this.field_size===4)for(let n=0;n<l;n+=2){const r=o.readUint8();this.sample_sizes[n]=r>>4&15,this.sample_sizes[n+1]=r&15}else if(this.field_size===8)for(let n=0;n<l;n++)this.sample_sizes[n]=o.readUint8();else if(this.field_size===16)for(let n=0;n<l;n++)this.sample_sizes[n]=o.readUint16();else Log.error("BoxParser","Error in length field in stz2 box",o.isofile)}}},oo.fourcc="stz2",oo),ro,subsBox=(ro=class extends FullBox{constructor(){super(...arguments),this.box_name="SubSampleInformationBox"}parse(o){this.parseFullHeader(o);const l=o.readUint32();this.entries=[];let n;for(let r=0;r<l;r++){const t={};if(this.entries[r]=t,t.sample_delta=o.readUint32(),t.subsamples=[],n=o.readUint16(),n>0)for(let e=0;e<n;e++){const i={};t.subsamples.push(i),this.version===1?i.size=o.readUint32():i.size=o.readUint16(),i.priority=o.readUint8(),i.discardable=o.readUint8(),i.codec_specific_parameters=o.readUint32()}}}},ro.fourcc="subs",ro),lo,taicBox=(lo=class extends FullBox{constructor(){super(...arguments),this.box_name="TAIClockInfoBox"}parse(o){this.time_uncertainty=o.readUint64(),this.clock_resolution=o.readUint32(),this.clock_drift_rate=o.readInt32();const l=o.readUint8();this.clock_type=(l&192)>>6}},lo.fourcc="taic",lo),ao,tencBox=(ao=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackEncryptionBox"}parse(o){if(this.parseFullHeader(o),o.readUint8(),this.version===0)o.readUint8();else{const l=o.readUint8();this.default_crypt_byte_block=l>>4&15,this.default_skip_byte_block=l&15}this.default_isProtected=o.readUint8(),this.default_Per_Sample_IV_Size=o.readUint8(),this.default_KID=parseHex16(o),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=o.readUint8(),this.default_constant_IV=o.readUint8Array(this.default_constant_IV_size))}},ao.fourcc="tenc",ao),so,tfraBox=(so=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackFragmentRandomAccessBox"}parse(o){this.parseFullHeader(o),this.track_ID=o.readUint32(),o.readUint24();const l=o.readUint8();this.length_size_of_traf_num=l>>4&3,this.length_size_of_trun_num=l>>2&3,this.length_size_of_sample_num=l&3,this.entries=[];const n=o.readUint32();for(let r=0;r<n;r++)this.version===1?(this.time=o.readUint64(),this.moof_offset=o.readUint64()):(this.time=o.readUint32(),this.moof_offset=o.readUint32()),this.traf_number=o["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=o["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=o["readUint"+8*(this.length_size_of_sample_num+1)]()}},so.fourcc="tfra",so),uo,tmaxBox=(uo=class extends Box{constructor(){super(...arguments),this.box_name="hintmaxrelativetime"}parse(o){this.time=o.readUint32()}},uo.fourcc="tmax",uo),co,tminBox=(co=class extends Box{constructor(){super(...arguments),this.box_name="hintminrelativetime"}parse(o){this.time=o.readUint32()}},co.fourcc="tmin",co),Uo,totlBox=(Uo=class extends Box{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(o){this.bytessent=o.readUint32()}},Uo.fourcc="totl",Uo),Fo,tpayBox=(Fo=class extends Box{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(o){this.bytessent=o.readUint32()}},Fo.fourcc="tpay",Fo),Qo,tpylBox=(Qo=class extends Box{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(o){this.bytessent=o.readUint64()}},Qo.fourcc="tpyl",Qo),po,msrcTrackGroupTypeBox=(po=class extends TrackGroupTypeBox{},po.fourcc="msrc",po),I,trefBox=(I=class extends Box{constructor(){super(...arguments),this.box_name="TrackReferenceBox",this.references=[]}parse(o){for(;o.getPosition()<this.start+this.size;){const l=parseOneBox(o,!0,this.size-(o.getPosition()-this.start));if(l.code===OK){I.allowed_types.includes(l.type)||Log.warn("BoxParser",`Unknown track reference type: '${l.type}'`);const n=new TrackReferenceTypeBox(l.type,l.size,l.hdr_size,l.start);n.write===Box.prototype.write&&n.type!=="mdat"&&(Log.info("BoxParser","TrackReference "+n.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),n.parseDataAndRewind(o)),n.parse(o),this.references.push(n)}else return}}},I.fourcc="tref",I.allowed_types=["hint","cdsc","font","hind","vdep","vplx","subt","thmb","auxl","cdtg","shsc","aest"],I),fo,trepBox=(fo=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackExtensionPropertiesBox"}parse(o){for(this.parseFullHeader(o),this.track_ID=o.readUint32(),this.boxes=[];o.getPosition()<this.start+this.size;){const l=parseOneBox(o,!1,this.size-(o.getPosition()-this.start));if(l.code===OK){const n=l.box;this.boxes.push(n)}else return}}},fo.fourcc="trep",fo),ho,trpyBox=(ho=class extends Box{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(o){this.bytessent=o.readUint64()}},ho.fourcc="trpy",ho),Ro,tselBox=(Ro=class extends FullBox{constructor(){super(...arguments),this.box_name="TrackSelectionBox"}parse(o){this.parseFullHeader(o),this.switch_group=o.readUint32();const l=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(let n=0;n<l;n++)this.attribute_list[n]=o.readUint32()}},Ro.fourcc="tsel",Ro),Bo,txtcBox=(Bo=class extends FullBox{constructor(){super(...arguments),this.box_name="TextConfigBox"}parse(o){this.parseFullHeader(o),this.config=o.readCString()}},Bo.fourcc="txtc",Bo),So,tycoBox=(So=class extends Box{constructor(){super(...arguments),this.box_name="TypeCombinationBox"}parse(o){const l=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(let n=0;n<l;n++)this.compatible_brands[n]=o.readString(4)}},So.fourcc="tyco",So),yo,udesBox=(yo=class extends FullBox{constructor(){super(...arguments),this.box_name="UserDescriptionProperty"}parse(o){this.parseFullHeader(o),this.lang=o.readCString(),this.name=o.readCString(),this.description=o.readCString(),this.tags=o.readCString()}},yo.fourcc="udes",yo),Vo,uncCBox=(Vo=class extends FullBox{constructor(){super(...arguments),this.box_name="UncompressedFrameConfigBox"}parse(o){if(this.parseFullHeader(o),this.profile=o.readString(4),this.version!==1){if(this.version===0){this.component_count=o.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[];for(let n=0;n<this.component_count;n++)this.component_index.push(o.readUint16()),this.component_bit_depth_minus_one.push(o.readUint8()),this.component_format.push(o.readUint8()),this.component_align_size.push(o.readUint8());this.sampling_type=o.readUint8(),this.interleave_type=o.readUint8(),this.block_size=o.readUint8();const l=o.readUint8();this.component_little_endian=l>>7&1,this.block_pad_lsb=l>>6&1,this.block_little_endian=l>>5&1,this.block_reversed=l>>4&1,this.pad_unknown=l>>3&1,this.pixel_size=o.readUint32(),this.row_align_size=o.readUint32(),this.tile_align_size=o.readUint32(),this.num_tile_cols_minus_one=o.readUint32(),this.num_tile_rows_minus_one=o.readUint32()}}}},Vo.fourcc="uncC",Vo),Jo,urnBox=(Jo=class extends FullBox{constructor(){super(...arguments),this.box_name="DataEntryUrnBox"}parse(o){this.parseFullHeader(o),this.name=o.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=o.readCString())}write(o){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(o),o.writeCString(this.name),this.location&&o.writeCString(this.location)}},Jo.fourcc="urn ",Jo),Eo,vttCBox=(Eo=class extends Box{constructor(){super(...arguments),this.box_name="WebVTTConfigurationBox"}parse(o){this.text=o.readString(this.size-this.hdr_size)}},Eo.fourcc="vttC",Eo),mo,vvnCBox=(mo=class extends FullBox{constructor(){super(...arguments),this.box_name="VvcNALUConfigBox"}parse(o){this.parseFullHeader(o);const l=o.readUint8();this.lengthSizeMinusOne=l&3}},mo.fourcc="vvnC",mo),ko,alstSampleGroupEntry=(ko=class extends SampleGroupEntry{parse(o){const l=o.readUint16();this.first_output_sample=o.readUint16(),this.sample_offset=[];for(let r=0;r<l;r++)this.sample_offset[r]=o.readUint32();const n=this.description_length-4-4*l;this.num_output_samples=[],this.num_total_samples=[];for(let r=0;r<n/4;r++)this.num_output_samples[r]=o.readUint16(),this.num_total_samples[r]=o.readUint16()}},ko.grouping_type="alst",ko),No,avllSampleGroupEntry=(No=class extends SampleGroupEntry{parse(o){this.layerNumber=o.readUint8(),this.accurateStatisticsFlag=o.readUint8(),this.avgBitRate=o.readUint16(),this.avgFrameRate=o.readUint16()}},No.grouping_type="avll",No),To,avssSampleGroupEntry=(To=class extends SampleGroupEntry{parse(o){this.subSequenceIdentifier=o.readUint16(),this.layerNumber=o.readUint8();const l=o.readUint8();this.durationFlag=l>>7,this.avgRateFlag=l>>6&1,this.durationFlag&&(this.duration=o.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=o.readUint8(),this.avgBitRate=o.readUint16(),this.avgFrameRate=o.readUint16()),this.dependency=[];const n=o.readUint8();for(let r=0;r<n;r++)this.dependency.push({subSeqDirectionFlag:o.readUint8(),layerNumber:o.readUint8(),subSequenceIdentifier:o.readUint16()})}},To.grouping_type="avss",To),vo,dtrtSampleGroupEntry=(vo=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},vo.grouping_type="dtrt",vo),Co,mvifSampleGroupEntry=(Co=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Co.grouping_type="mvif",Co),Wo,prolSampleGroupEntry=(Wo=class extends SampleGroupEntry{parse(o){this.roll_distance=o.readInt16()}},Wo.grouping_type="prol",Wo),bo,rapSampleGroupEntry=(bo=class extends SampleGroupEntry{parse(o){const l=o.readUint8();this.num_leading_samples_known=l>>7,this.num_leading_samples=l&127}},bo.grouping_type="rap ",bo),Oo,rashSampleGroupEntry=(Oo=class extends SampleGroupEntry{parse(o){if(this.operation_point_count=o.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)Log.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=o.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=o.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(let l=0;l<this.operation_point_count;l++)this.available_bitrate[l]=o.readUint32(),this.target_rate_share[l]=o.readUint16()}this.maximum_bitrate=o.readUint32(),this.minimum_bitrate=o.readUint32(),this.discard_priority=o.readUint8()}}},Oo.grouping_type="rash",Oo),Zo,rollSampleGroupEntry=(Zo=class extends SampleGroupEntry{parse(o){this.roll_distance=o.readInt16()}},Zo.grouping_type="roll",Zo),Do,scifSampleGroupEntry=(Do=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Do.grouping_type="scif",Do),wo,scnmSampleGroupEntry=(wo=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},wo.grouping_type="scnm",wo),go,seigSampleGroupEntry=(go=class extends SampleGroupEntry{parse(o){this.reserved=o.readUint8();const l=o.readUint8();this.crypt_byte_block=l>>4,this.skip_byte_block=l&15,this.isProtected=o.readUint8(),this.Per_Sample_IV_Size=o.readUint8(),this.KID=parseHex16(o),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=o.readUint8(),this.constant_IV=o.readUint8Array(this.constant_IV_size))}},go.grouping_type="seig",go),xo,stsaSampleGroupEntry=(xo=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},xo.grouping_type="stsa",xo),Io,syncSampleGroupEntry=(Io=class extends SampleGroupEntry{parse(o){const l=o.readUint8();this.NAL_unit_type=l&63}},Io.grouping_type="sync",Io),Mo,teleSampleGroupEntry=(Mo=class extends SampleGroupEntry{parse(o){const l=o.readUint8();this.level_independently_decodable=l>>7}},Mo.grouping_type="tele",Mo),_o,tsasSampleGroupEntry=(_o=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},_o.grouping_type="tsas",_o),Po,tsclSampleGroupEntry=(Po=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Po.grouping_type="tscl",Po),$o,viprSampleGroupEntry=($o=class extends SampleGroupEntry{parse(o){Log.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},$o.grouping_type="vipr",$o),Lo,UUIDBox=(Lo=class extends Box{},Lo.fourcc="uuid",Lo),Ao,UUIDFullBox=(Ao=class extends FullBox{},Ao.fourcc="uuid",Ao),Go,piffLsmBox=(Go=class extends UUIDFullBox{constructor(){super(...arguments),this.box_name="LiveServerManifestBox"}parse(o){this.parseFullHeader(o),this.LiveServerManifest=o.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}},Go.uuid="a5d40b30e81411ddba2f0800200c9a66",Go),Ho,piffPsshBox=(Ho=class extends UUIDFullBox{constructor(){super(...arguments),this.box_name="PiffProtectionSystemSpecificHeaderBox"}parse(o){this.parseFullHeader(o),this.system_id=parseHex16(o);const l=o.readUint32();l>0&&(this.data=o.readUint8Array(l))}},Ho.uuid="d08a4f1810f34a82b6c832d8aba183d3",Ho),zo,piffSencBox=(zo=class extends UUIDFullBox{constructor(){super(...arguments),this.box_name="PiffSampleEncryptionBox"}},zo.uuid="a2394f525a9b4f14a2446c427c648df4",zo),Yo,piffTencBox=(Yo=class extends UUIDFullBox{constructor(){super(...arguments),this.box_name="PiffTrackEncryptionBox"}parse(o){this.parseFullHeader(o),this.default_AlgorithmID=o.readUint24(),this.default_IV_size=o.readUint8(),this.default_KID=parseHex16(o)}},Yo.uuid="8974dbce7be74c5184f97148f9882554",Yo),jo,piffTfrfBox=(jo=class extends UUIDFullBox{constructor(){super(...arguments),this.box_name="TfrfBox"}parse(o){this.parseFullHeader(o),this.fragment_count=o.readUint8(),this.entries=[];for(let l=0;l<this.fragment_count;l++){let n=0,r=0;this.version===1?(n=o.readUint64(),r=o.readUint64()):(n=o.readUint32(),r=o.readUint32()),this.entries.push({absolute_time:n,absolute_duration:r})}}},jo.uuid="d4807ef2ca3946958e5426cb9e46a79f",jo),Xo,piffTfxdBox=(Xo=class extends UUIDFullBox{constructor(){super(...arguments),this.box_name="TfxdBox"}parse(o){this.parseFullHeader(o),this.version===1?(this.absolute_time=o.readUint64(),this.duration=o.readUint64()):(this.absolute_time=o.readUint32(),this.duration=o.readUint32())}},Xo.uuid="6d1d9b0542d544e680e2141daff757b2",Xo),qo,ItemContentIDPropertyBox=(qo=class extends UUIDBox{constructor(){super(...arguments),this.box_name="ItemContentIDProperty"}parse(o){this.content_id=o.readCString()}},qo.uuid="261ef3741d975bbaacbd9d2c8ea73522",qo);registerBoxes(all_boxes_exports);registerDescriptors(descriptor_exports);class MP4FileSource{constructor(o={}){U(this,"mp4File",null);U(this,"fileInfo",null);U(this,"videoTrackId",null);U(this,"audioTrackId",null);U(this,"videoTrack",null);U(this,"audioTrack",null);U(this,"nextVideoSampleIndex",0);U(this,"nextAudioSampleIndex",0);U(this,"totalVideoSamples",0);U(this,"totalAudioSamples",0);U(this,"samplesRequested",!1);U(this,"isProgressiveLoading",!1);U(this,"fileSize",0);U(this,"loadedBytes",0);U(this,"videoDescription",null);U(this,"audioDescription",null);U(this,"events",{});this.events=o}getFileInfo(){return this.fileInfo}getVideoDescription(){return this.videoDescription}getAudioDescription(){return this.audioDescription}async loadFromUrl(o){this.initMP4File();const l=4*1024*1024;let n=0,r=!1;try{const t=await fetch(o,{method:"HEAD"});if(t.ok){const e=t.headers.get("Content-Length");e&&(this.fileSize=parseInt(e,10))}}catch{}return new Promise((t,e)=>{let i=!1;const a=this.mp4File.onSamples;this.mp4File.onSamples=(c,F,B)=>{!i&&c===this.videoTrackId&&B.length>0&&(i=!0),a==null||a.call(this.mp4File,c,F,B)};const s=this.mp4File.onReady;this.mp4File.onReady=c=>{s==null||s.call(this.mp4File,c),this.fileInfo&&!r&&(r=!0)},(async()=>{var c,F,B,S,y,E,v,N,T,C;try{const m=await fetch(o,{headers:{Range:`bytes=0-${l-1}`}});if(!m.ok&&m.status!==206)throw new Error(`Failed to fetch: ${m.status} ${m.statusText}`);if(m.status===200){this.isProgressiveLoading=!1;const f=await m.arrayBuffer();this.fileSize=f.byteLength,this.loadedBytes=f.byteLength;const h=f;h.fileStart=0,(c=this.mp4File)==null||c.appendBuffer(h),(F=this.mp4File)==null||F.flush(),this.fileInfo?t(this.fileInfo):e(new Error("File loaded but no video track found"));return}if(this.isProgressiveLoading=!0,!this.fileSize){const f=m.headers.get("Content-Range");if(f){const h=f.match(/bytes \d+-\d+\/(\d+)/);h&&(this.fileSize=parseInt(h[1],10))}}const Q=await m.arrayBuffer(),p=Q;if(p.fileStart=0,n=Q.byteLength,this.loadedBytes=n,(S=(B=this.events).onProgress)==null||S.call(B,this.loadedBytes,this.fileSize),(y=this.mp4File)==null||y.appendBuffer(p),r&&i){n<this.fileSize?this.continueLoadingInBackground(o,n,l):(E=this.mp4File)==null||E.flush(),t(this.fileInfo);return}for(;n<this.fileSize&&(!r||!i);){const f=Math.min(n+l-1,this.fileSize-1),h=await fetch(o,{headers:{Range:`bytes=${n}-${f}`}});if(!h.ok&&h.status!==206)throw new Error(`Failed to fetch chunk: ${h.status} ${h.statusText}`);const R=await h.arrayBuffer(),J=R;if(J.fileStart=n,n+=R.byteLength,this.loadedBytes=n,(N=(v=this.events).onProgress)==null||N.call(v,this.loadedBytes,this.fileSize),(T=this.mp4File)==null||T.appendBuffer(J),r&&i){this.continueLoadingInBackground(o,n,l),t(this.fileInfo);return}}n>=this.fileSize&&((C=this.mp4File)==null||C.flush(),this.fileInfo?t(this.fileInfo):e(new Error("File loaded but no video track found")))}catch(m){e(m)}})()})}continueLoadingInBackground(o,l,n){(async()=>{var t,e,i,a,s,d,c,F;let r=l;try{for(;r<this.fileSize;){const B=Math.min(r+n-1,this.fileSize-1),S=await fetch(o,{headers:{Range:`bytes=${r}-${B}`}});if(!S.ok&&S.status!==206){(e=(t=this.events).onError)==null||e.call(t,new Error(`Failed to fetch chunk: ${S.status}`));break}const y=await S.arrayBuffer(),E=y;E.fileStart=r,r+=y.byteLength,this.loadedBytes=r,(a=(i=this.events).onProgress)==null||a.call(i,this.loadedBytes,this.fileSize),(s=this.mp4File)==null||s.appendBuffer(E)}(d=this.mp4File)==null||d.flush()}catch(B){(F=(c=this.events).onError)==null||F.call(c,B)}})()}async loadFromFile(o){this.fileSize=o.size;const l=await o.arrayBuffer();return this.isProgressiveLoading=!1,this.loadFromArrayBuffer(l)}async loadFromStream(o){this.initMP4File(),this.isProgressiveLoading=!0;let l=0;return new Promise((n,r)=>{const t=i=>{var s,d,c;const a=new ArrayBuffer(i.byteLength);new Uint8Array(a).set(i),a.fileStart=l,l+=a.byteLength,this.loadedBytes=l,(d=(s=this.events).onProgress)==null||d.call(s,this.loadedBytes,this.fileSize),(c=this.mp4File)==null||c.appendBuffer(a)},e=async()=>{var i;try{const{done:a,value:s}=await o.read();if(a){(i=this.mp4File)==null||i.flush(),this.fileInfo?n(this.fileInfo):r(new Error("File loaded but no video track found"));return}s&&t(s),e()}catch(a){r(a)}};e()})}async loadFromArrayBuffer(o){return this.initMP4File(),new Promise((l,n)=>{var e,i;const r=this.mp4File.onReady;this.mp4File.onReady=a=>{r==null||r.call(this.mp4File,a),this.fileInfo?(this.requestSamples(),l(this.fileInfo)):n(new Error("No video track found in file"))};const t=o;t.fileStart=0,this.loadedBytes=o.byteLength,(e=this.mp4File)==null||e.appendBuffer(t),(i=this.mp4File)==null||i.flush()})}initMP4File(){this.mp4File=createFile(),this.mp4File.onReady=o=>{this.handleFileReady(o)},this.mp4File.onSamples=(o,l,n)=>{this.handleSamples(o,n)},this.mp4File.onError=(o,l)=>{var r,t;if(l.includes("Invalid box type")||l.includes("Unknown box")){console.warn(`[MP4FileSource] Ignoring unknown box: ${l}`);return}const n=new Error(`MP4Box error in ${o}: ${l}`);(t=(r=this.events).onError)==null||t.call(r,n)}}handleFileReady(o){var l,n,r,t,e,i,a,s,d,c,F,B,S,y,E,v,N,T,C,m,Q,p,f,h,R,J,V,W,b,g;if(o.videoTracks.length>0){this.videoTrack=o.videoTracks[0],this.videoTrackId=this.videoTrack.id,this.totalVideoSamples=this.videoTrack.nb_samples;const Z=(l=this.mp4File)==null?void 0:l.getTrackById(this.videoTrackId);if(Z){const M=(i=(e=(t=(r=(n=Z.mdia)==null?void 0:n.minf)==null?void 0:r.stbl)==null?void 0:t.stsd)==null?void 0:e.entries)==null?void 0:i[0];if(M){const O=M.avcC,D=M.hvcC;O?this.videoDescription=this.serializeAvcC(O):D&&(this.videoDescription=this.serializeHvcC(D))}}}if(o.audioTracks.length>0){this.audioTrack=o.audioTracks[0],this.audioTrackId=this.audioTrack.id,this.totalAudioSamples=this.audioTrack.nb_samples;const Z=(a=this.mp4File)==null?void 0:a.getTrackById(this.audioTrackId);if(Z){const M=(B=(F=(c=(d=(s=Z.mdia)==null?void 0:s.minf)==null?void 0:d.stbl)==null?void 0:c.stsd)==null?void 0:F.entries)==null?void 0:B[0];if(M){const O=M.esds;if(O){let D=null;if((N=(v=(E=(y=(S=O.esd)==null?void 0:S.descs)==null?void 0:y[0])==null?void 0:E.descs)==null?void 0:v[0])!=null&&N.data)D=O.esd.descs[0].descs[0].data;else if((m=(C=(T=O.esd)==null?void 0:T.descs)==null?void 0:C[0])!=null&&m.data)D=O.esd.descs[0].data;else if((Q=O.esd)!=null&&Q.descs)for(const er of O.esd.descs){if(er.tag===4&&er.descs){for(const nr of er.descs)if(nr.tag===5&&nr.data){D=nr.data;break}}if(D)break}D&&(this.audioDescription=D)}}}}if(!this.videoTrack){(f=(p=this.events).onError)==null||f.call(p,new Error("No video track found in file"));return}this.fileInfo={duration:this.videoTrack.duration/this.videoTrack.timescale,timescale:this.videoTrack.timescale,width:((h=this.videoTrack.video)==null?void 0:h.width)??0,height:((R=this.videoTrack.video)==null?void 0:R.height)??0,videoCodec:this.videoTrack.codec,frameRate:this.videoTrack.nb_samples/(this.videoTrack.duration/this.videoTrack.timescale),bitrate:this.videoTrack.bitrate,isMoovAtStart:((J=this.mp4File)==null?void 0:J.isProgressive)??void 0},this.audioTrack&&(this.fileInfo.audioCodec=this.audioTrack.codec,this.fileInfo.audioChannels=(V=this.audioTrack.audio)==null?void 0:V.channel_count,this.fileInfo.audioSampleRate=(W=this.audioTrack.audio)==null?void 0:W.sample_rate),this.requestSamples(),(g=(b=this.events).onReady)==null||g.call(b,this.fileInfo)}requestSamples(){var o,l,n,r,t;this.samplesRequested||(this.samplesRequested=!0,this.videoTrackId!==null&&(this.isProgressiveLoading?(o=this.mp4File)==null||o.setExtractionOptions(this.videoTrackId,null,{nbSamples:100}):(l=this.mp4File)==null||l.setExtractionOptions(this.videoTrackId,null,{nbSamples:this.totalVideoSamples})),this.audioTrackId!==null&&(this.isProgressiveLoading?(n=this.mp4File)==null||n.setExtractionOptions(this.audioTrackId,null,{nbSamples:100}):(r=this.mp4File)==null||r.setExtractionOptions(this.audioTrackId,null,{nbSamples:this.totalAudioSamples})),(t=this.mp4File)==null||t.start())}handleSamples(o,l){var e,i,a,s;const n=o===this.videoTrackId;if(!(n?this.videoTrack:this.audioTrack))return;const t=l.filter(d=>d.data!=null).map(d=>{const c=d.cts/d.timescale*1e6,F=d.duration/d.timescale*1e6;return{data:d.data,timestamp:c,duration:F,isKeyframe:d.is_sync,type:n?"video":"audio"}});if(n?(this.nextVideoSampleIndex+=l.length,this.nextVideoSampleIndex>=this.totalVideoSamples&&((i=(e=this.events).onEnded)==null||i.call(e))):this.nextAudioSampleIndex+=l.length,this.mp4File){const d=l[l.length-1];this.mp4File.releaseUsedSamples(o,d.number)}(s=(a=this.events).onSamples)==null||s.call(a,t)}seek(o){if(!this.mp4File||!this.videoTrackId)return 0;const l=this.mp4File.seek(o,!0);return this.nextVideoSampleIndex=0,this.nextAudioSampleIndex=0,this.samplesRequested=!1,this.mp4File.stop(),this.requestSamples(),l.time}getPosition(){return{currentSample:this.nextVideoSampleIndex,totalSamples:this.totalVideoSamples,progress:this.totalVideoSamples>0?this.nextVideoSampleIndex/this.totalVideoSamples:0}}stop(){var o;(o=this.mp4File)==null||o.stop()}start(){var o;(o=this.mp4File)==null||o.start()}dispose(){var o;(o=this.mp4File)==null||o.stop(),this.mp4File=null,this.fileInfo=null,this.videoTrack=null,this.audioTrack=null,this.videoDescription=null,this.audioDescription=null,this.isProgressiveLoading=!1}serializeAvcC(o){let l=6;const n=o.SPS||[];for(const i of n)l+=2+i.data.length;l+=1;const r=o.PPS||[];for(const i of r)l+=2+i.data.length;const t=new Uint8Array(l);let e=0;t[e++]=o.configurationVersion||1,t[e++]=o.AVCProfileIndication,t[e++]=o.profile_compatibility,t[e++]=o.AVCLevelIndication,t[e++]=255,t[e++]=224|n.length;for(const i of n){const a=i.data.length;t[e++]=a>>8&255,t[e++]=a&255,t.set(new Uint8Array(i.data),e),e+=a}t[e++]=r.length;for(const i of r){const a=i.data.length;t[e++]=a>>8&255,t[e++]=a&255,t.set(new Uint8Array(i.data),e),e+=a}return t}serializeHvcC(o){return o.data&&o.data instanceof Uint8Array?o.data:(console.warn("HEVC serialization not fully implemented"),new Uint8Array(0))}}const WORKLET_CODE=`
|
|
152
152
|
class AudioPlayProcessor extends AudioWorkletProcessor {
|
|
153
153
|
constructor(options) {
|
|
154
154
|
super();
|
package/dist/web-live-player.mjs
CHANGED
|
@@ -17476,7 +17476,7 @@ const Ko = class Ko extends BasePlayer {
|
|
|
17476
17476
|
videoTrackName: l.videoTrackName === void 0 ? "video" : l.videoTrackName,
|
|
17477
17477
|
audioTrackName: l.audioTrackName === void 0 ? "audio" : l.audioTrackName,
|
|
17478
17478
|
debugLogging: l.debugLogging ?? !1
|
|
17479
|
-
}, this.config.enableAudio && (this.audioContext = new AudioContext(), this.ownsAudioContext = !0), this.frameScheduler = new FrameScheduler({
|
|
17479
|
+
}, this.config.enableAudio && (l.audioContext ? (this.audioContext = l.audioContext, this.ownsAudioContext = !1) : (this.audioContext = new AudioContext(), this.ownsAudioContext = !0)), this.frameScheduler = new FrameScheduler({
|
|
17480
17480
|
bufferDelayMs: this.config.bufferDelayMs,
|
|
17481
17481
|
logger: (n) => {
|
|
17482
17482
|
this.config.debugLogging && this.logger.info(n);
|
|
@@ -17742,7 +17742,7 @@ const Ko = class Ko extends BasePlayer {
|
|
|
17742
17742
|
if (!this.config.enableAudio)
|
|
17743
17743
|
return;
|
|
17744
17744
|
const n = this.audioCodecData ?? void 0;
|
|
17745
|
-
(t = (r = l.header) == null ? void 0 : r.media) != null && t.codecData && codecDataChanged(n, l.header.media.codecData) && (this.audioCodecData = l.header.media.codecData, this.audioPlayer && (this.audioPlayer.dispose(), this.audioPlayer = null), this.audioContext || (this.audioContext = new AudioContext(), this.ownsAudioContext = !0), this.audioPlayer = new LiveAudioPlayer(this.audioContext, {
|
|
17745
|
+
(t = (r = l.header) == null ? void 0 : r.media) != null && t.codecData && codecDataChanged(n, l.header.media.codecData) && (this.audioCodecData = l.header.media.codecData, this.audioPlayer && (this.audioPlayer.dispose(), this.audioPlayer = null), this.audioContext || (this.config.audioContext ? (this.audioContext = this.config.audioContext, this.ownsAudioContext = !1) : (this.audioContext = new AudioContext(), this.ownsAudioContext = !0)), this.audioPlayer = new LiveAudioPlayer(this.audioContext, {
|
|
17746
17746
|
bufferDelayMs: this.config.bufferDelayMs ?? 100
|
|
17747
17747
|
}), await this.audioPlayer.init((e = l.header.media) == null ? void 0 : e.codecData), this.audioPlayer.start(), this.logger.info(`Audio player started: ${(a = (i = l.header.media) == null ? void 0 : i.codecData) == null ? void 0 : a.codecType}, ${(d = (s = l.header.media) == null ? void 0 : s.codecData) == null ? void 0 : d.sampleRate}Hz, ${(F = (U = l.header.media) == null ? void 0 : U.codecData) == null ? void 0 : F.channels}ch`)), this.audioPlayer && l.payload && l.header && this.audioPlayer.decode(l.payload, (B = l.header.media) == null ? void 0 : B.pts);
|
|
17748
17748
|
}
|
package/package.json
CHANGED